@opentf/afw 0.0.0-stage → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +123 -2
  3. package/components/Link.d.ts +12 -0
  4. package/components/Link.jsx +54 -0
  5. package/core/context.d.ts +7 -0
  6. package/core/context.js +60 -0
  7. package/core/dev.js +27 -0
  8. package/core/errors.d.ts +14 -0
  9. package/core/errors.js +48 -0
  10. package/core/html.js +10 -0
  11. package/core/metadata.js +186 -0
  12. package/core/reactive.d.ts +5 -0
  13. package/core/reactive.js +190 -0
  14. package/core/render-context.js +11 -0
  15. package/core/signals.d.ts +8 -0
  16. package/core/signals.js +264 -0
  17. package/index.d.ts +5 -0
  18. package/index.js +13 -0
  19. package/jsx-runtime.d.ts +37 -0
  20. package/package.json +66 -4
  21. package/runtime/clipboard.d.ts +7 -0
  22. package/runtime/clipboard.js +47 -0
  23. package/runtime/code-block.d.ts +14 -0
  24. package/runtime/code-block.js +76 -0
  25. package/runtime/context.browser.js +163 -0
  26. package/runtime/context.d.ts +13 -0
  27. package/runtime/context.js +44 -0
  28. package/runtime/dom.browser.js +423 -0
  29. package/runtime/dom.d.ts +142 -0
  30. package/runtime/dom.js +670 -0
  31. package/runtime/error-boundary.browser.js +140 -0
  32. package/runtime/error-boundary.d.ts +19 -0
  33. package/runtime/error-boundary.js +123 -0
  34. package/runtime/events.browser.js +29 -0
  35. package/runtime/events.d.ts +1 -0
  36. package/runtime/events.js +17 -0
  37. package/runtime/head.js +29 -0
  38. package/runtime/hmr.js +199 -0
  39. package/runtime/hydrate.browser.js +144 -0
  40. package/runtime/hydrate.d.ts +179 -0
  41. package/runtime/hydrate.js +584 -0
  42. package/runtime/index.d.ts +14 -0
  43. package/runtime/index.js +24 -0
  44. package/runtime/lifecycle.d.ts +6 -0
  45. package/runtime/lifecycle.js +14 -0
  46. package/runtime/mount.d.ts +20 -0
  47. package/runtime/mount.js +88 -0
  48. package/runtime/portal.browser.js +85 -0
  49. package/runtime/portal.d.ts +12 -0
  50. package/runtime/portal.js +74 -0
  51. package/runtime/raw-html.d.ts +11 -0
  52. package/runtime/raw-html.js +55 -0
  53. package/runtime/resource.d.ts +9 -0
  54. package/runtime/resource.js +139 -0
  55. package/runtime/route-data.d.ts +15 -0
  56. package/runtime/route-data.js +64 -0
  57. package/runtime/router.d.ts +149 -0
  58. package/runtime/router.js +807 -0
  59. package/server/adapters/node.d.ts +28 -0
  60. package/server/adapters/node.js +74 -0
  61. package/server/api.d.ts +175 -0
  62. package/server/api.js +233 -0
  63. package/server/builtins.js +42 -0
  64. package/server/cookies.d.ts +44 -0
  65. package/server/cookies.js +122 -0
  66. package/server/head.js +9 -0
  67. package/server/index.d.ts +155 -0
  68. package/server/index.js +31 -0
  69. package/server/loader.js +201 -0
  70. package/server/middleware.js +119 -0
  71. package/server/render-context.js +30 -0
  72. package/server/render.js +175 -0
  73. package/server/ssg-runtime.js +297 -0
@@ -0,0 +1,28 @@
1
+ // Type definitions for the Node.js adapter (SPEC §11.4).
2
+ import type { IncomingMessage, ServerResponse } from "node:http";
3
+
4
+ import type { RequestHandler } from "../api.js";
5
+
6
+ export interface NodeAdapterOptions {
7
+ /** Response for requests that match no API route (default: a 404). */
8
+ fallback?: (request: Request) => Response | Promise<Response>;
9
+ }
10
+
11
+ /** Build a WHATWG `Request` from a Node `IncomingMessage`. */
12
+ export function toWebRequest(req: IncomingMessage, options?: { protocol?: string }): Promise<Request>;
13
+
14
+ /** Write a WHATWG `Response` to a Node `ServerResponse`. */
15
+ export function sendWebResponse(res: ServerResponse, webRes: Response): Promise<void>;
16
+
17
+ /**
18
+ * Turn a Fetch handler into a Node `(req, res)` listener:
19
+ *
20
+ * import { createServer } from "node:http";
21
+ * import { apiHandler } from "./dist/server/api.js";
22
+ * import { toNodeListener } from "@opentf/afw/server/adapters/node";
23
+ * createServer(toNodeListener(apiHandler)).listen(3000);
24
+ */
25
+ export function toNodeListener(
26
+ handler: RequestHandler,
27
+ options?: NodeAdapterOptions,
28
+ ): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
@@ -0,0 +1,74 @@
1
+ // Node.js adapter for AFW API routes (SPEC §11.4). The API handler speaks the
2
+ // standard Fetch `Request`/`Response`; Bun, Cloudflare Workers, and Deno provide
3
+ // those natively, but `node:http` speaks its own `IncomingMessage`/`ServerResponse`.
4
+ // This adapter translates between the two so `dist/server/api.js` runs on Node.
5
+ //
6
+ // import { createServer } from "node:http";
7
+ // import { apiHandler } from "./dist/server/api.js";
8
+ // import { toNodeListener } from "@opentf/afw/server/adapters/node";
9
+ // createServer(toNodeListener(apiHandler)).listen(3000);
10
+
11
+ /** Build a WHATWG `Request` from a Node `IncomingMessage`. */
12
+ export async function toWebRequest(req, { protocol = "http" } = {}) {
13
+ const host = req.headers.host ?? "localhost";
14
+ const url = `${protocol}://${host}${req.url}`;
15
+ const method = req.method ?? "GET";
16
+ const headers = new Headers();
17
+ for (const [k, v] of Object.entries(req.headers)) {
18
+ if (Array.isArray(v)) for (const one of v) headers.append(k, one);
19
+ else if (v != null) headers.set(k, v);
20
+ }
21
+ // GET/HEAD must not carry a body; everything else streams the request in.
22
+ const hasBody = method !== "GET" && method !== "HEAD";
23
+ const body = hasBody ? await readBody(req) : undefined;
24
+ return new Request(url, { method, headers, body });
25
+ }
26
+
27
+ function readBody(req) {
28
+ return new Promise((resolve, reject) => {
29
+ const chunks = [];
30
+ req.on("data", (c) => chunks.push(c));
31
+ req.on("end", () => resolve(Buffer.concat(chunks)));
32
+ req.on("error", reject);
33
+ });
34
+ }
35
+
36
+ /** Write a WHATWG `Response` to a Node `ServerResponse`. */
37
+ export async function sendWebResponse(res, webRes) {
38
+ const headers = {};
39
+ webRes.headers.forEach((value, key) => {
40
+ if (key !== "set-cookie") headers[key] = value;
41
+ });
42
+ // `Headers` iteration collapses repeated Set-Cookie values into one string, which
43
+ // breaks multi-cookie responses (session + CSRF). Recover the individual cookies;
44
+ // Node accepts an array header value and writes one Set-Cookie line per entry.
45
+ const cookies = webRes.headers.getSetCookie?.() ?? [];
46
+ if (cookies.length > 0) headers["set-cookie"] = cookies;
47
+ res.writeHead(webRes.status, headers);
48
+ if (webRes.body) {
49
+ const buf = Buffer.from(await webRes.arrayBuffer());
50
+ res.end(buf);
51
+ } else {
52
+ res.end();
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Turn a Fetch handler `(request) => Response | null` into a Node
58
+ * `(req, res)` listener. A `null` result (no API route matched) becomes the
59
+ * optional `fallback(request)` response, or a 404.
60
+ */
61
+ export function toNodeListener(handler, { fallback } = {}) {
62
+ return async (req, res) => {
63
+ try {
64
+ const request = await toWebRequest(req);
65
+ let webRes = await handler(request);
66
+ if (!webRes) webRes = fallback ? await fallback(request) : new Response("Not Found", { status: 404 });
67
+ await sendWebResponse(res, webRes);
68
+ } catch (e) {
69
+ if (!res.headersSent) res.writeHead(500, { "content-type": "application/json" });
70
+ res.end(JSON.stringify({ error: "Internal Server Error" }));
71
+ console.error("✗ API (node adapter):", e?.stack ?? e);
72
+ }
73
+ };
74
+ }
@@ -0,0 +1,175 @@
1
+ // Type definitions for file-based API routes (SPEC §11). Authoring handlers in
2
+ // TypeScript: annotate the method exports with `ApiHandler` and the `_middleware`
3
+ // default export with `Middleware`.
4
+ //
5
+ // import type { ApiHandler, Middleware } from "@opentf/afw/server";
6
+ // export const GET: ApiHandler = (request, { params }) => Response.json({ id: params.id });
7
+
8
+ type MaybePromise<T> = T | Promise<T>;
9
+
10
+ /**
11
+ * Route params resolved from `[param]` / `[...rest]` segments. A `[param]` segment
12
+ * resolves to a `string`; a `[...rest]` catch-all resolves to a `string[]`. Values
13
+ * arrive percent-decoded (`/users/John%20Doe` → `"John Doe"`).
14
+ */
15
+ export type RouteParams = Record<string, string | string[]>;
16
+
17
+ /** Per-request context, passed as the second argument to handlers and middleware.
18
+ * Pipeline middleware (run before routing — see {@link createMiddleware}) receives
19
+ * it without `params`/`query`: no route has matched yet. */
20
+ export interface ApiContext {
21
+ /** Dynamic route params resolved from the matched path. */
22
+ params: RouteParams;
23
+ /** Parsed query-string parameters. */
24
+ query: Record<string, string>;
25
+ /** The parsed request URL. */
26
+ url: URL;
27
+ /**
28
+ * Mutable per-request bag. Middleware writes to it (e.g. an authenticated user
29
+ * or a validated body) and downstream middleware / the handler reads from it.
30
+ */
31
+ locals: Record<string, unknown>;
32
+ /**
33
+ * The platform environment / bindings — the second argument the runtime's
34
+ * `fetch` receives. On Cloudflare Workers this holds your bindings (`env.DB` for
35
+ * D1, KV namespaces, secrets); on Bun/Node it is `undefined` and environment
36
+ * variables are read from `process.env` instead. Type it per project with a
37
+ * generic, e.g. `context.env as Env`.
38
+ */
39
+ env?: unknown;
40
+ /**
41
+ * The execution context — the third `fetch` argument on Cloudflare Workers,
42
+ * exposing `waitUntil(promise)` for background work after the response is sent.
43
+ * `undefined` on runtimes that don't provide one.
44
+ */
45
+ ctx?: { waitUntil(promise: Promise<unknown>): void; passThroughOnException?(): void };
46
+ }
47
+
48
+ /**
49
+ * An HTTP method handler (`GET`, `POST`, …). Receives the standard Fetch `Request`
50
+ * plus the {@link ApiContext}. Should return (or throw) a `Response`; a plain value
51
+ * is a convenience that gets JSON-encoded.
52
+ */
53
+ export type ApiHandler = (request: Request, context: ApiContext) => MaybePromise<Response>;
54
+
55
+ /** Continue to the next middleware, or ultimately the route handler / terminal.
56
+ * Pass a replacement `Request` to rewrite what downstream routes on. */
57
+ export type NextFn = (rewrittenRequest?: Request) => Promise<Response>;
58
+
59
+ /** The context pipeline middleware receives: pre-routing, so no `params`/`query`. */
60
+ export type MiddlewareContext = Omit<ApiContext, "params" | "query">;
61
+
62
+ /**
63
+ * Folder middleware — the default export of a `_middleware.{js,ts}` file. Applies
64
+ * to its folder and everything nested under it — pages, API endpoints, loader-data
65
+ * requests, and 404s alike; multiple middleware compose outermost-first. Call
66
+ * `next()` to continue (or `next(new Request(...))` to rewrite), or return a
67
+ * `Response` to short-circuit (e.g. an auth guard).
68
+ */
69
+ export type Middleware = (
70
+ request: Request,
71
+ context: MiddlewareContext & Partial<Pick<ApiContext, "params" | "query">>,
72
+ next: NextFn,
73
+ ) => MaybePromise<Response>;
74
+
75
+ /**
76
+ * The composed request handler produced by {@link createApiHandler}: resolves to a
77
+ * `Response`, or `null` when no API route matched (so the caller can fall through
78
+ * to SSR or a 404). `init.locals` shares a pipeline-middleware `locals` bag with
79
+ * the handlers (same object, by reference).
80
+ */
81
+ export type RequestHandler = (
82
+ request: Request,
83
+ env?: unknown,
84
+ ctx?: unknown,
85
+ init?: { locals?: Record<string, unknown> },
86
+ ) => Promise<Response | null>;
87
+
88
+ /**
89
+ * The runner produced by {@link createMiddleware}: `run` composes the applicable
90
+ * middleware chain (by folder scope) around a terminal for one request.
91
+ */
92
+ export interface MiddlewareRunner {
93
+ /** Number of discovered middleware functions (0 → nothing will ever run). */
94
+ size: number;
95
+ /** The governed folder scopes, outermost first (e.g. `["/", "/api"]`). */
96
+ scopes: string[];
97
+ run(
98
+ request: Request,
99
+ terminal: (request: Request, context: MiddlewareContext) => MaybePromise<Response>,
100
+ extras?: { env?: unknown; ctx?: unknown },
101
+ ): Promise<Response>;
102
+ }
103
+
104
+ /** A discovered route module: its method-named handler exports, keyed by method. */
105
+ export type RouteModule = Partial<Record<string, ApiHandler>>;
106
+
107
+ /** A discovered `_middleware` module: the middleware is the default export. */
108
+ export interface MiddlewareModule {
109
+ default?: Middleware;
110
+ middleware?: Middleware;
111
+ }
112
+
113
+ export interface FetchHandlerOptions {
114
+ /**
115
+ * Response for requests that match no API route (default: a 404). Receives the
116
+ * same `env`/`ctx` the runtime passed to `fetch`, so on Cloudflare Workers a
117
+ * static-asset fallback can call `env.ASSETS.fetch(request)`.
118
+ */
119
+ fallback?: (request: Request, env?: unknown, ctx?: unknown) => MaybePromise<Response>;
120
+ /**
121
+ * Request middleware (a {@link createMiddleware} runner) wrapped around the
122
+ * whole request — handler *and* fallback. Pair it with the routes-only
123
+ * `apiRoutes` bundle export, not the composed `apiHandler` (which would run the
124
+ * API-scoped middleware a second time).
125
+ */
126
+ middleware?: MiddlewareRunner;
127
+ }
128
+
129
+ export interface ApiHandlerOptions {
130
+ /**
131
+ * Absolute path of the app directory the module keys live under. When given, the
132
+ * route is derived by stripping this exact prefix (the CLI always passes it);
133
+ * without it a `/app` path-segment heuristic is used.
134
+ */
135
+ appDir?: string;
136
+ }
137
+
138
+ /** Derive the route path from an `app/.../route.{js,ts}` file path (folder = URL). */
139
+ export function apiRouteFromPath(filePath: string, appDir?: string): string;
140
+
141
+ /** Derive the folder route a `_middleware` file governs from its file path. */
142
+ export function middlewareScopeFromPath(filePath: string, appDir?: string): string;
143
+
144
+ /**
145
+ * Build the API request handler from discovered route + middleware modules (both
146
+ * keyed by absolute file path so routes are derived from the path).
147
+ */
148
+ export function createApiHandler(
149
+ routeModules?: Record<string, RouteModule>,
150
+ middlewareModules?: Record<string, MiddlewareModule>,
151
+ options?: ApiHandlerOptions,
152
+ ): RequestHandler;
153
+
154
+ /**
155
+ * Build the request-middleware runner from discovered `_middleware` modules (keyed
156
+ * by absolute file path so each scope is derived from the path). The optional
157
+ * `i18n` config lets scope matching strip a non-default locale prefix, and a
158
+ * `<path>/__data.json` request is always governed by its page's scope.
159
+ */
160
+ export function createMiddleware(
161
+ middlewareModules?: Record<string, MiddlewareModule>,
162
+ options?: ApiHandlerOptions & { i18n?: { locales?: string[]; defaultLocale?: string } },
163
+ ): MiddlewareRunner;
164
+
165
+ /**
166
+ * Wrap a {@link RequestHandler} into a total Fetch handler that always returns a
167
+ * `Response` — a `null` (no route matched) becomes the `fallback` or a 404. Use it
168
+ * to mount the handler on Fetch-native runtimes (Bun, Cloudflare Workers, Deno):
169
+ *
170
+ * export default { fetch: createFetchHandler(apiHandler) };
171
+ */
172
+ export function createFetchHandler(
173
+ handler: RequestHandler,
174
+ options?: FetchHandlerOptions,
175
+ ): (request: Request, env?: unknown, ctx?: unknown) => Promise<Response>;
package/server/api.js ADDED
@@ -0,0 +1,233 @@
1
+ // File-based API routes for the AFW runtime — the API backend (ARCHITECTURE
2
+ // §6, SPEC §11). An endpoint is a `route.{js,ts}` file — the API analogue of a
3
+ // page's `page.{jsx,tsx}` — so the folder is the URL (`app/api/users/[id]/route.ts`
4
+ // → `/api/users/:id`), exactly like pages. Handlers are *plain server modules*
5
+ // (not JSX/DOM-compiled): each exports named functions per HTTP method that take a
6
+ // standard `Request` and return a standard `Response`, portable across Bun / Node /
7
+ // Cloudflare Workers (SPEC §11.1). A folder may hold a `page.*` or a `route.*`, not
8
+ // both — the toolchain errors on the conflict (like Next.js's App Router).
9
+ //
10
+ // This module is runtime-agnostic: `createApiHandler` turns a discovered route
11
+ // map into a single `(request) => Response | null` function. `null` means "no
12
+ // API route matched" so the caller (dev/serve/adapter) can fall through to SSR
13
+ // or a 404. Matching reuses the `[param]` / `[...rest]` convention and regex
14
+ // approach of the page router (runtime/router.js `matchRoute`) so behavior is
15
+ // identical across pages and API and across every deployment target.
16
+
17
+ import { middlewareScopeFromPath } from "./middleware.js";
18
+
19
+ // Scope derivation lives in middleware.js now that middleware governs the whole
20
+ // pipeline, not just API routes; re-exported here for backward compatibility.
21
+ export { middlewareScopeFromPath };
22
+
23
+ const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
24
+
25
+ /**
26
+ * Strip the app-directory prefix from a route/middleware file path. When the
27
+ * caller knows the app dir (the CLI always does), the exact prefix is removed —
28
+ * unambiguous even for an `app/app/...` folder. Without it, fall back to the last
29
+ * complete `/app` path segment; the lookahead keeps folders that merely *start*
30
+ * with "app" (`/appointments`, `/apps`) intact.
31
+ */
32
+ function stripAppDir(filePath, appDir) {
33
+ if (appDir) {
34
+ const base = appDir.replace(/\/+$/, "");
35
+ if (filePath.startsWith(base + "/")) return filePath.slice(base.length);
36
+ }
37
+ return filePath.replace(/^.*\/app(?=\/)/, "");
38
+ }
39
+
40
+ /**
41
+ * Derive the API route path from a `.../app/<...>/route.{js,ts}` file path — the
42
+ * folder is the URL, mirroring `routeFromPath` in the page router.
43
+ * `app/api/status/route.js` → `/api/status`, `app/api/users/[id]/route.ts` →
44
+ * `/api/users/[id]`, `app/route.js` → `/`. Pass `appDir` (the absolute app
45
+ * directory) when known so the prefix is stripped exactly.
46
+ */
47
+ export function apiRouteFromPath(filePath, appDir) {
48
+ const r = stripAppDir(filePath, appDir).replace(/\/route\.(jsx?|tsx?)$/, "");
49
+ return r === "" ? "/" : r;
50
+ }
51
+
52
+ /** Compile a route path with `[param]` / `[...rest]` segments to a matcher regex.
53
+ * Named groups become route params; literal parts are regex-escaped (a `v1.0`
54
+ * folder must not match `v1X0`); the optional trailing slash is tolerated. */
55
+ function compilePattern(route) {
56
+ const src = route
57
+ .split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\])/)
58
+ .map((part) => {
59
+ if (part.startsWith("[...")) return `(?<${part.slice(4, -1)}>.+)`;
60
+ if (part.startsWith("[")) return `(?<${part.slice(1, -1)}>[^/]+)`;
61
+ return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
62
+ })
63
+ .join("");
64
+ return new RegExp(`^${src}/?$`);
65
+ }
66
+
67
+ // Percent-decode a matched param segment; malformed input stays raw rather than throwing.
68
+ const decodeParam = (s) => {
69
+ try {
70
+ return decodeURIComponent(s);
71
+ } catch {
72
+ return s;
73
+ }
74
+ };
75
+
76
+ const normalize = (p) => (p || "/").replace(/(.)\/+$/, "$1");
77
+
78
+ /** The `Allow` header value for a handler module: the methods it exports, plus the
79
+ * auto-provided HEAD (when GET exists) and OPTIONS. */
80
+ function allowedMethods(mod) {
81
+ const set = new Set(METHODS.filter((m) => typeof mod[m] === "function"));
82
+ if (set.has("GET")) set.add("HEAD");
83
+ set.add("OPTIONS");
84
+ return [...set].join(", ");
85
+ }
86
+
87
+ /**
88
+ * Build the API request handler from a discovered route + middleware map.
89
+ *
90
+ * @param {Record<string, object>} routeModules `{ [absFilePath]: moduleNamespace }`
91
+ * — each module exports method handlers (`GET`, `POST`, …).
92
+ * @param {Record<string, object>} middlewareModules `{ [absFilePath]: moduleNamespace }`
93
+ * for `_middleware.{js,ts}` files; the middleware is the default export.
94
+ * @param {{ appDir?: string }} [options] `appDir` — the absolute app directory the
95
+ * module keys live under, for exact route derivation (the CLI passes it).
96
+ * @returns {(request: Request, env?: unknown, ctx?: unknown, init?: { locals?: object }) => Promise<Response | null>}
97
+ * `init.locals` — a pre-existing `locals` bag from pipeline middleware
98
+ * (middleware.js), shared by reference so its writes reach the handlers.
99
+ */
100
+ export function createApiHandler(routeModules = {}, middlewareModules = {}, { appDir } = {}) {
101
+ const routes = [];
102
+ for (const file in routeModules) {
103
+ const route = apiRouteFromPath(file, appDir);
104
+ routes.push({ route, pattern: compilePattern(route), module: routeModules[file], dynamic: route.includes("[") });
105
+ }
106
+ // Static routes before dynamic, longer (more specific) before shorter, so the
107
+ // most specific match wins deterministically regardless of discovery order.
108
+ routes.sort((a, b) => a.dynamic - b.dynamic || b.route.length - a.route.length);
109
+
110
+ const middleware = [];
111
+ for (const file in middlewareModules) {
112
+ const mod = middlewareModules[file];
113
+ const fn = mod.default ?? mod.middleware;
114
+ if (typeof fn === "function") middleware.push({ scope: middlewareScopeFromPath(file, appDir), fn });
115
+ }
116
+ // Outermost (shortest scope) runs first, so `/api/_middleware` wraps `/api/users/_middleware`.
117
+ middleware.sort((a, b) => a.scope.length - b.scope.length);
118
+
119
+ return async function handle(request, env, ctx, init) {
120
+ const url = new URL(request.url);
121
+ const pathname = normalize(url.pathname);
122
+
123
+ let matched = null;
124
+ let params = {};
125
+ for (const r of routes) {
126
+ const m = pathname.match(r.pattern);
127
+ if (!m) continue;
128
+ matched = r;
129
+ params = { ...(m.groups || {}) };
130
+ // Params reach handlers percent-decoded (`/users/John%20Doe` → "John Doe");
131
+ // catch-all segments are split first so an encoded `%2F` never adds a segment.
132
+ for (const k in params) {
133
+ params[k] = r.route.includes(`[...${k}]`)
134
+ ? params[k].split("/").map(decodeParam)
135
+ : decodeParam(params[k]);
136
+ }
137
+ break;
138
+ }
139
+ if (!matched) return null; // no API route — fall through to SSR / 404
140
+
141
+ // Shared per-request context. `locals` is the channel middleware uses to pass
142
+ // data (auth user, validated body) down to the handler. `env`/`ctx` are the
143
+ // platform's fetch arguments — on Cloudflare Workers `env` holds the bindings
144
+ // (D1, KV, secrets) and `ctx` the execution context (`waitUntil`); on Bun/Node
145
+ // they're absent and env vars are read from `process.env` instead.
146
+ const context = {
147
+ params,
148
+ query: Object.fromEntries(url.searchParams),
149
+ url,
150
+ locals: init?.locals ?? {},
151
+ env,
152
+ ctx,
153
+ };
154
+
155
+ const dispatch = async (req) => {
156
+ const mod = matched.module;
157
+ const method = req.method.toUpperCase();
158
+ const fn = mod[method];
159
+ if (typeof fn === "function") return fn(req, context);
160
+ // Auto HEAD from GET (drop the body); auto OPTIONS; else 405.
161
+ if (method === "HEAD" && typeof mod.GET === "function") {
162
+ const got = await mod.GET(req, context);
163
+ // GET may lean on the plain-value → JSON convenience; HEAD must then carry
164
+ // the same status/headers that GET response would have had.
165
+ const res = got instanceof Response ? got : Response.json(got);
166
+ return new Response(null, { status: res.status, headers: res.headers });
167
+ }
168
+ if (method === "OPTIONS") return new Response(null, { status: 204, headers: { Allow: allowedMethods(mod) } });
169
+ return new Response(null, { status: 405, headers: { Allow: allowedMethods(mod) } });
170
+ };
171
+
172
+ // Compose the applicable middleware chain around dispatch (outermost first).
173
+ // The root scope ("/", from an `app/_middleware.*`) governs every route.
174
+ const chain = middleware.filter(
175
+ (mw) => mw.scope === "/" || pathname === mw.scope || pathname.startsWith(mw.scope + "/"),
176
+ );
177
+ let next = dispatch;
178
+ for (let i = chain.length - 1; i >= 0; i--) {
179
+ const { fn } = chain[i];
180
+ const downstream = next;
181
+ // `next()` continues with the current request; `next(rewrittenRequest)`
182
+ // hands downstream a replacement (same contract as pipeline middleware).
183
+ next = (req) => fn(req, context, (nextReq) => downstream(nextReq instanceof Request ? nextReq : req));
184
+ }
185
+
186
+ try {
187
+ const res = await next(request);
188
+ if (res instanceof Response) return res;
189
+ if (res === undefined) {
190
+ throw new Error(`API handler for ${request.method} ${pathname} returned no Response`);
191
+ }
192
+ return Response.json(res); // lenient: a plain value becomes a JSON response
193
+ } catch (e) {
194
+ if (e instanceof Response) return e; // handlers/middleware may throw a Response
195
+ console.error(`✗ API ${request.method} ${pathname}:`, e?.stack ?? e);
196
+ return Response.json({ error: "Internal Server Error" }, { status: 500 });
197
+ }
198
+ };
199
+ }
200
+
201
+ /**
202
+ * Wrap an API handler (`(request) => Response | null`) into a total Fetch handler
203
+ * that always returns a `Response` — a `null` (no route matched) becomes the
204
+ * optional `fallback(request, env, ctx)` or a 404. Fetch-native runtimes (Bun,
205
+ * Cloudflare Workers, Deno) can export it directly; the runtime's `fetch`
206
+ * arguments (`env`, `ctx`) are threaded through to handlers and the fallback, so
207
+ * on Workers your handlers reach the bindings via `context.env` and a static-asset
208
+ * fallback reaches `env.ASSETS`:
209
+ *
210
+ * import { apiRoutes, middleware } from "./dist/server/api.js";
211
+ * export default {
212
+ * fetch: createFetchHandler(apiRoutes, {
213
+ * middleware, // request middleware wraps API dispatch *and* the fallback
214
+ * fallback: (req, env) => env.ASSETS.fetch(req), // SPA / static assets
215
+ * }),
216
+ * };
217
+ *
218
+ * With `middleware` (a `createMiddleware` runner), the chain wraps the whole
219
+ * request — pass the *routes-only* `apiRoutes` handler then, not the composed
220
+ * `apiHandler`, or API middleware would run twice.
221
+ */
222
+ export function createFetchHandler(handler, { fallback, middleware } = {}) {
223
+ const terminal = async (request, env, ctx, context) => {
224
+ const res = await handler(request, env, ctx, context ? { locals: context.locals } : undefined);
225
+ if (res) return res;
226
+ return fallback ? fallback(request, env, ctx) : new Response("Not Found", { status: 404 });
227
+ };
228
+ if (middleware && middleware.size > 0) {
229
+ return (request, env, ctx) =>
230
+ middleware.run(request, (req, context) => terminal(req, env, ctx, context), { env, ctx });
231
+ }
232
+ return (request, env, ctx) => terminal(request, env, ctx);
233
+ }
@@ -0,0 +1,42 @@
1
+ //! SSG renderers for the built-in runtime components (the ones that are
2
+ //! hand-written Custom Elements, not compiled). Registered on import so the SSG
3
+ //! bundle can render `<Link>`, `<ContextProvider>`, `<Portal>`, `<ErrorBoundary>`.
4
+
5
+ import { attr, defineSSG } from "./ssg-runtime.js";
6
+ import { localizePath } from "../runtime/router.js";
7
+
8
+ // Passthrough: their effect is structural/client-side; SSG renders children inline.
9
+ //
10
+ // The children are a `{children}` slot the compiler adopts on hydration via `hydrateSlot`,
11
+ // which locates the slotted content by the `<!--c[-->…<!--c]-->` markers (hydrate.js
12
+ // SLOT_START/SLOT_END) — the same markers the compiler emits around `{children}` in a normal
13
+ // component's SSG view. These hand-written renderers must emit them too, or the slotted
14
+ // content never gets its reactivity wired on first paint (dead bindings until a CSR rebuild).
15
+ // The markers carry the host's own tag, exactly as the compiled components' do — slot
16
+ // regions nest, and the label is what lets each side find its own pair (see ssg.rs).
17
+ const slot = (tag, children) => `<!--c[${tag}-->${children ?? ""}<!--c]${tag}-->`;
18
+ const register = (tag, render) => {
19
+ render.tag = tag;
20
+ return defineSSG(tag, render);
21
+ };
22
+ const passthrough = (tag) => register(tag, (_props, children) => slot(tag, children));
23
+ // Match Link.jsx's static view without importing its browser registration barrel.
24
+ export const Link = register("afw-link", (props, children) =>
25
+ `<a${attr("href", localizePath(props.href))}${attr("class", props.class)}${attr("aria-label", props["aria-label"] || props.ariaLabel)}${attr("aria-current", props["aria-current"] || props.ariaCurrent)}>${slot("afw-link", children)}</a>`);
26
+ Link.hostClass = "afw-link";
27
+ // The provider has to carry its context token in the *served HTML*. Consumers are
28
+ // Custom Elements that upgrade the moment their definition is registered — which
29
+ // happens before the enclosing component's hydrate code runs and assigns the
30
+ // `context` prop. `readContext` resolves the provider with `closest()`, so if the
31
+ // attribute is not already in the markup at upgrade time, every consumer on the page
32
+ // silently binds to the context *default* and never sees a provided value again.
33
+ export const ContextProvider = passthrough("afw-internal-context-provider");
34
+ ContextProvider.hostAttrs = (props) =>
35
+ props && props.context && props.context.id ? ` data-afw-ctx="${props.context.id}"` : "";
36
+ export const Portal = passthrough("afw-internal-portal");
37
+ export const ErrorBoundary = passthrough("afw-internal-error-boundary");
38
+ // RawHtml: emit the trusted HTML string inline (MDX highlighted code blocks).
39
+ export const RawHtml = register("afw-internal-raw-html", (props) => (props && props.html != null ? String(props.html) : ""));
40
+ // CodeFence: same inline HTML as RawHtml; the copy button wires up on the client
41
+ // when the element upgrades (SSG output is static, the behavior is CSR-only).
42
+ export const CodeFence = register("afw-internal-code-block", (props) => (props && props.html != null ? String(props.html) : ""));
@@ -0,0 +1,44 @@
1
+ // Types for the cookie helpers (cookies.js) — standards-based wrappers over the
2
+ // `Cookie` / `Set-Cookie` headers, exported from `@opentf/afw/server`.
3
+
4
+ /** Anything cookies can be read from: a Request (or any `.headers` carrier), a
5
+ * Headers, or the raw `Cookie` header string. */
6
+ export type CookieSource = Request | Headers | { headers: Headers } | string;
7
+
8
+ /** Anything a `Set-Cookie` header can be appended to: a Response (or any
9
+ * `.headers` carrier) or a Headers. */
10
+ export type CookieTarget = Response | Headers | { headers: Headers };
11
+
12
+ export interface CookieOptions {
13
+ /** Defaults to `"/"`; pass `null` to omit (the spec then scopes to the request's path). */
14
+ path?: string | null;
15
+ domain?: string;
16
+ /** Lifetime in seconds. */
17
+ maxAge?: number;
18
+ /** A `Date`, or anything `new Date(...)` accepts (ISO string, epoch ms). */
19
+ expires?: Date | string | number;
20
+ httpOnly?: boolean;
21
+ secure?: boolean;
22
+ /** `"None"` requires `secure: true` (enforced at write time). */
23
+ sameSite?: "Strict" | "Lax" | "None" | "strict" | "lax" | "none";
24
+ partitioned?: boolean;
25
+ }
26
+
27
+ /** Parse cookies into `{ name: value }` (percent-decoded; first duplicate wins). */
28
+ export function getCookies(source: CookieSource): Record<string, string>;
29
+
30
+ /** One cookie's (percent-decoded) value, or `undefined` when absent. */
31
+ export function getCookie(source: CookieSource, name: string): string | undefined;
32
+
33
+ /** Serialize one `Set-Cookie` header value (value percent-encoded). */
34
+ export function serializeCookie(name: string, value: string, options?: CookieOptions): string;
35
+
36
+ /** Append a `Set-Cookie` header to a Response/Headers; returns the serialized value. */
37
+ export function setCookie(target: CookieTarget, name: string, value: string, options?: CookieOptions): string;
38
+
39
+ /** Expire a cookie on the client (`Max-Age=0`); `path`/`domain` must match how it was set. */
40
+ export function deleteCookie(
41
+ target: CookieTarget,
42
+ name: string,
43
+ options?: Pick<CookieOptions, "path" | "domain">,
44
+ ): string;