Skip to content

Commit

Permalink
feat: forward runtime context
Browse files Browse the repository at this point in the history
  • Loading branch information
magne4000 committed Aug 29, 2024
1 parent a2171ea commit ea4bbfd
Show file tree
Hide file tree
Showing 21 changed files with 126 additions and 92 deletions.
6 changes: 5 additions & 1 deletion examples/hattip-app/.testRun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@ import { expect, fetchHtml, getServerUrl, page, run, test } from "@brillout/test

export { testRun };

let isProd: boolean;

function testRun(cmd: `pnpm run ${"dev" | "preview"}${string}`, options?: Parameters<typeof run>[1]) {
run(cmd, options);

isProd = !cmd.startsWith("pnpm run dev");

testUrl({
url: "/",
title: "My Vike App",
text: "Rendered to HTML",
text: isProd ? "SSR running on Cloudflare" : "Rendered to HTML",
textHydration: "Rendered to HTML",
});

Expand Down
21 changes: 5 additions & 16 deletions examples/hattip-app/hattip-entry.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,18 @@
import type { HattipHandler } from "@hattip/core";
import { createRouter } from "@hattip/router";
import { createHandler } from "@universal-middleware/hattip";
import { createTodoHandler } from "./server/create-todo-handler";
import { vikeHandler } from "./server/vike-handler";
import type { HattipHandler } from "@hattip/core";
import { createRouter, type RouteHandler } from "@hattip/router";

type Middleware<Context extends Record<string | number | symbol, unknown>> = (request: Request, context: Context) => Response | void | Promise<Response> | Promise<void>

function handlerAdapter<Context extends Record<string | number | symbol, unknown>>(
handler: Middleware<Context>,
): RouteHandler<unknown, unknown> {
return (context) => {
const rawContext = context as unknown as Record<string, unknown>;
rawContext.context ??= {};
return handler(context.request, rawContext.context as Context);
};
}

const router = createRouter();

router.post("/api/todo/create", handlerAdapter(createTodoHandler));
router.post("/api/todo/create", createHandler(() => createTodoHandler)());

/**
* Vike route
*
* @link {@see https://vike.dev}
**/
router.use(handlerAdapter(vikeHandler));
router.use(createHandler(() => vikeHandler)());

export default router.buildHandler() as HattipHandler;
2 changes: 2 additions & 0 deletions examples/hattip-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"@hattip/adapter-cloudflare-workers": "^0.0.47",
"@hattip/adapter-node": "^0.0.47",
"@hattip/vite": "^0.0.47",
"@universal-middleware/core": "^0.2.6",
"cross-env": "^7.0.3",
"typescript": "^5.5.4",
"vike-cloudflare": "^0.1.0",
Expand All @@ -25,6 +26,7 @@
"dependencies": {
"@hattip/core": "^0.0.47",
"@hattip/router": "^0.0.47",
"@universal-middleware/hattip": "^0.2.3",
"cross-fetch": "^4.0.0",
"hattip": "^0.0.33",
"lowdb": "^7.0.1",
Expand Down
4 changes: 4 additions & 0 deletions examples/hattip-app/pages/index/+Page.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { usePageContext } from "vike-solid/usePageContext";
import { Counter } from "./Counter.js";

export default function Page() {
const ctx = usePageContext();

return (
<>
<h1>My Vike app</h1>
This page is:
<ul>
<li>Rendered to HTML.</li>
{typeof ctx?.ctx?.waitUntil === "function" ? <li>SSR running on Cloudflare</li> : null}
<li>
Interactive. <Counter />
</li>
Expand Down
9 changes: 4 additions & 5 deletions examples/hattip-app/server/create-todo-handler.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
export async function createTodoHandler<Context extends Record<string | number | symbol, unknown>>(
request: Request,
_context?: Context,
): Promise<Response> {
import type { UniversalHandler } from "@universal-middleware/core";

export const createTodoHandler = (async (request: Request): Promise<Response> => {
await request.json();

return new Response(JSON.stringify({ status: "OK" }), {
Expand All @@ -10,4 +9,4 @@ export async function createTodoHandler<Context extends Record<string | number |
"content-type": "application/json",
},
});
}
}) satisfies UniversalHandler;
10 changes: 4 additions & 6 deletions examples/hattip-app/server/vike-handler.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { renderPage } from "vike/server";
import type { UniversalHandler } from "@universal-middleware/core";

export async function vikeHandler<Context extends Record<string | number | symbol, unknown>>(
request: Request,
context?: Context,
): Promise<Response> {
const pageContextInit = { ...context, urlOriginal: request.url };
export const vikeHandler = (async (request, context, runtime): Promise<Response> => {
const pageContextInit = { ...context, urlOriginal: request.url, ...runtime };
const pageContext = await renderPage(pageContextInit);
const response = pageContext.httpResponse;

Expand All @@ -16,4 +14,4 @@ export async function vikeHandler<Context extends Record<string | number | symbo
status: response?.statusCode,
headers: response?.headers,
});
}
}) satisfies UniversalHandler;
2 changes: 1 addition & 1 deletion examples/hattip-app/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"moduleResolution": "Bundler",
"target": "ES2022",
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"types": ["vite/client", "vike-solid/client"],
"types": ["vite/client", "vike-solid/client", "vike-cloudflare/types"],
"jsx": "preserve",
"jsxImportSource": "solid-js"
},
Expand Down
4 changes: 2 additions & 2 deletions examples/hono-app/.testRun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ let isProd: boolean;
function testRun(cmd: `pnpm run ${"dev" | "preview"}${string}`, options?: Parameters<typeof run>[1]) {
run(cmd, options);

isProd = cmd !== "pnpm run dev";
isProd = !cmd.startsWith("pnpm run dev");

testUrl({
url: "/",
title: "My Vike App",
text: "Rendered to HTML",
text: isProd ? "SSR running on Cloudflare" : "Rendered to HTML",
textHydration: "Rendered to HTML",
});

Expand Down
29 changes: 3 additions & 26 deletions examples/hono-app/hono-entry.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,17 @@
import { createHandler } from "@universal-middleware/hono";
import { Hono } from "hono";
import { createMiddleware } from "hono/factory";
import { createTodoHandler } from "./server/create-todo-handler.js";
import { vikeHandler } from "./server/vike-handler";

type Middleware<Context extends Record<string | number | symbol, unknown>> = (request: Request, context: Context) => Response | void | Promise<Response> | Promise<void>

export function handlerAdapter<Context extends Record<string | number | symbol, unknown>>(
handler: Middleware<Context>,
) {
return createMiddleware(async (context, next) => {
let ctx = context.get("context");
if (!ctx) {
ctx = {};
context.set("context", ctx);
}

const res = await handler(context.req.raw, ctx as Context);
context.set("context", ctx);

if (!res) {
await next();
}

return res;
});
}

const app = new Hono();

app.post("/api/todo/create", handlerAdapter(createTodoHandler));
app.post("/api/todo/create", createHandler(() => createTodoHandler)());

/**
* Vike route
*
* @link {@see https://vike.dev}
**/
app.all("*", handlerAdapter(vikeHandler));
app.all("*", createHandler(() => vikeHandler)());

export default app;
2 changes: 2 additions & 0 deletions examples/hono-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@
"@hono/vite-cloudflare-pages": "^0.4.2",
"@hono/vite-dev-server": "^0.14.0",
"@types/node": "^18.19.14",
"@universal-middleware/core": "^0.2.6",
"typescript": "^5.5.4",
"vike-cloudflare": "^0.1.0",
"wrangler": "^3.72.2"
},
"dependencies": {
"@universal-middleware/hono": "^0.2.4",
"cross-fetch": "^4.0.0",
"hono": "^4.5.8",
"solid-js": "^1.8.21",
Expand Down
4 changes: 4 additions & 0 deletions examples/hono-app/pages/index/+Page.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { usePageContext } from "vike-solid/usePageContext";
import { Counter } from "./Counter.js";

export default function Page() {
const ctx = usePageContext();

return (
<>
<h1>My Vike app</h1>
This page is:
<ul>
<li>Rendered to HTML.</li>
{typeof ctx?.ctx?.waitUntil === "function" ? <li>SSR running on Cloudflare</li> : null}
<li>
Interactive. <Counter />
</li>
Expand Down
9 changes: 4 additions & 5 deletions examples/hono-app/server/create-todo-handler.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
export async function createTodoHandler<Context extends Record<string | number | symbol, unknown>>(
request: Request,
_context?: Context,
): Promise<Response> {
import type { UniversalHandler } from "@universal-middleware/core";

export const createTodoHandler = (async (request: Request): Promise<Response> => {
await request.json();

return new Response(JSON.stringify({ status: "OK" }), {
Expand All @@ -10,4 +9,4 @@ export async function createTodoHandler<Context extends Record<string | number |
"content-type": "application/json",
},
});
}
}) satisfies UniversalHandler;
10 changes: 4 additions & 6 deletions examples/hono-app/server/vike-handler.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { renderPage } from "vike/server";
import type { UniversalHandler } from "@universal-middleware/core";

export async function vikeHandler<Context extends Record<string | number | symbol, unknown>>(
request: Request,
context?: Context,
): Promise<Response> {
const pageContextInit = { ...context, urlOriginal: request.url };
export const vikeHandler = (async (request, context, runtime): Promise<Response> => {
const pageContextInit = { ...context, urlOriginal: request.url, ...runtime };
const pageContext = await renderPage(pageContextInit);
const response = pageContext.httpResponse;

Expand All @@ -16,4 +14,4 @@ export async function vikeHandler<Context extends Record<string | number | symbo
status: response?.statusCode,
headers: response?.headers,
});
}
}) satisfies UniversalHandler;
2 changes: 1 addition & 1 deletion examples/hono-app/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"moduleResolution": "Bundler",
"target": "ES2022",
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"types": ["vite/client", "vike-solid/client"],
"types": ["vite/client", "vike-solid/client", "vike-cloudflare/types"],
"jsx": "preserve",
"jsxImportSource": "solid-js"
},
Expand Down
4 changes: 2 additions & 2 deletions examples/vike-app/.testRun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ let isProd: boolean;
function testRun(cmd: `pnpm run ${"dev" | "preview"}${string}`, options?: Parameters<typeof run>[1]) {
run(cmd, options);

isProd = cmd !== "pnpm run dev";
isProd = !cmd.startsWith("pnpm run dev");

testUrl({
url: "/",
title: "My Vike App",
text: "Rendered to HTML",
text: isProd ? "SSR running on Cloudflare" : "Rendered to HTML",
textHydration: "Rendered to HTML",
});

Expand Down
4 changes: 4 additions & 0 deletions examples/vike-app/pages/index/+Page.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { usePageContext } from "vike-solid/usePageContext";
import { Counter } from "./Counter.js";

export default function Page() {
const ctx = usePageContext();

return (
<>
<h1>My Vike app</h1>
This page is:
<ul>
<li>Rendered to HTML.</li>
{typeof ctx?.ctx?.waitUntil === "function" ? <li>SSR running on Cloudflare</li> : null}
<li>
Interactive. <Counter />
</li>
Expand Down
2 changes: 1 addition & 1 deletion examples/vike-app/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"moduleResolution": "Bundler",
"target": "ES2022",
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"types": ["vite/client", "vike-solid/client"],
"types": ["vite/client", "vike-solid/client", "vike-cloudflare/types"],
"jsx": "preserve",
"jsxImportSource": "solid-js"
},
Expand Down
25 changes: 14 additions & 11 deletions packages/vike-cloudflare/assets/vike.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,40 @@ import { renderPage } from "vike/server";

/**
* @param url {string}
* @param ctx {{ env: any, ctx: any }}
* @returns {Promise<Response>}
*/
async function handleSsr(url) {
async function handleSsr(url, ctx) {
const pageContextInit = {
urlOriginal: url,
fetch,
...ctx,
};
const pageContext = await renderPage(pageContextInit);
const { httpResponse } = pageContext;
if (!httpResponse) {
return new Response("Something went wrong", { status: 500 });
}
const { statusCode: status, headers } = httpResponse;
const { statusCode: status, headers } = httpResponse;

const { readable, writable } = new TransformStream();
const { readable, writable } = new TransformStream();

httpResponse.pipe(writable);
httpResponse.pipe(writable);

return new Response(readable, {
status,
headers,
});
return new Response(readable, {
status,
headers,
});
}

export default {
/**
* @param request {Request}
* @param env {{}}
* @param env {any}
* @param ctx {any}
* @returns {Promise<Response>}
*/
async fetch(request, env) {
return handleSsr(request.url);
async fetch(request, env, ctx) {
return handleSsr(request.url, { env, ctx });
},
};
7 changes: 6 additions & 1 deletion packages/vike-cloudflare/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,19 @@
"@hattip/adapter-cloudflare-workers": "^0.0.47"
},
"files": [
"dist"
"dist",
"vike.d.ts"
],
"types": "./vike.d.ts",
"exports": {
".": {
"import": "./dist/index.js",
"node": "./dist/index.js",
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./types": {
"types": "./vike.d.ts"
}
},
"repository": "github:vikejs/vike-cloudflare"
Expand Down
14 changes: 14 additions & 0 deletions packages/vike-cloudflare/vike.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
declare global {
namespace Vike {
interface PageContext {
ctx?: {
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
waitUntil(promise: Promise<any>): void;
passThroughOnException(): void;
};
env?: Record<string | symbol | number, unknown>;
}
}
}

export type {};
Loading

0 comments on commit ea4bbfd

Please sign in to comment.