@opentf/afw-build 0.0.0-stage → 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Open Tech Foundation and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,35 @@
1
- # Temporary Holding Version
1
+ # @opentf/afw-build
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The toolchain-neutral core of the AFW build. AFW ships two official workflows, each a
4
+ thin integration over this package:
5
+
6
+ | Workflow | Toolchain package | Runs on |
7
+ | --- | --- | --- |
8
+ | esdev + ES-Runtime | `@opentf/esdev-plugin-afw` | ES-Runtime |
9
+ | Vite + Node | `@opentf/vite-plugin-afw` | Node |
10
+
11
+ You normally install one of those, not this package directly.
12
+
13
+ ## What lives here
14
+
15
+ | Module | Purpose |
16
+ | --- | --- |
17
+ | `compiler-client.js` | The `afwc serve` protocol: one long-lived compiler child for every module |
18
+ | `compile.js` | Compiler target rules (`chooseTarget`), the compile-error stub, route-module detection |
19
+ | `resolve-compiler.js` | Finds `afwc`: `AFWC_BIN`, the prebuilt `@opentf/afw-compiler` binary, or a cargo build in a source checkout |
20
+ | `routes.js` | File-based routing: page, layout, 404 and loader discovery, and the `@afw/routes` module |
21
+ | `document.js` | The HTML document: shell helpers and `renderDocument`, shared by SSR and static generation |
22
+ | `prerender.js` | Static generation: pages, loader data, `404.html`, sitemap and robots |
23
+ | `server.js` | Server routing: API routes, middleware and loaders composed into the `@afw/server` handler |
24
+ | `host.js` | The host interface the above run against |
25
+
26
+ ## The host interface
27
+
28
+ Nothing here imports `runtime:*` or `node:*`. A toolchain supplies a host object with
29
+ file access (`readText`, `readDir`, `kind`), processes (`spawn`, `run`), `cwd`, `env`
30
+ and `path` helpers; see `host.js` for the full contract. A test enforces that the
31
+ package stays platform-free.
32
+
33
+ ## License
34
+
35
+ MIT
package/compile.js ADDED
@@ -0,0 +1,89 @@
1
+ // What every toolchain does with an AFW source module: pick the compiler target for
2
+ // the build at hand, compile through `afwc`, and turn a failure into either a thrown
3
+ // diagnostic or a visible stub module.
4
+
5
+ /** Rendering modes a project chooses from. */
6
+ export const MODES = new Set(["spa", "ssg", "ssr"]);
7
+ /** Compiler backends: live DOM, HTML-string renderers, or the hydrating dual module. */
8
+ export const TARGETS = new Set(["csr", "ssg", "hydrate"]);
9
+
10
+ /** Source modules the compiler owns. */
11
+ export const SOURCE_FILTER = /\.(mdx|md|[jt]sx)$/;
12
+
13
+ /** Throw on an unknown mode or target, before any compiler starts. */
14
+ export function validateOptions({ mode = "spa", target } = {}) {
15
+ if (!MODES.has(mode)) throw new Error(`Unknown AFW rendering mode: ${mode} (expected spa, ssg, or ssr)`);
16
+ if (target !== undefined && !TARGETS.has(target)) {
17
+ throw new Error(`Unknown AFW compiler target: ${target} (expected csr, ssg, or hydrate)`);
18
+ }
19
+ }
20
+
21
+ /**
22
+ * The compiler target for one module. `server` — the module is bundled for the
23
+ * server (string renderers). `dev` — a dev server or test run, which always renders
24
+ * on the client. Otherwise a release browser build: CSR for an SPA, the hydrating
25
+ * dual module when the server renders first.
26
+ */
27
+ export function chooseTarget({ mode = "spa", target, server = false, dev = false } = {}) {
28
+ if (target) return target;
29
+ if (server) return "ssg";
30
+ if (dev) return "csr";
31
+ return mode === "spa" ? "csr" : "hydrate";
32
+ }
33
+
34
+ /** Whether framework imports in this build resolve to the DOM-free server entry. */
35
+ export function usesServerEntry({ target, server = false } = {}) {
36
+ return (target ?? (server ? "ssg" : undefined)) === "ssg";
37
+ }
38
+
39
+ /** The framework specifiers that resolve to `@opentf/afw/server` in a server build. */
40
+ export const FRAMEWORK_IMPORT = /^@opentf\/afw(?:\/runtime)?$/;
41
+
42
+ /** Page, layout and 404 modules compile to route factories; the rest to components. */
43
+ export function isRouteModule(id) {
44
+ const base = id.split(/[\\/]/).pop().replace(SOURCE_FILTER, "");
45
+ return base === "page" || base === "layout" || base === "404";
46
+ }
47
+
48
+ /** A module that shows the compile error in place of the page or component. */
49
+ export function errorStub(text) {
50
+ return (
51
+ `export default function () { const pre = document.createElement("pre");` +
52
+ ` pre.style.cssText = "color:#f87171;padding:1rem;white-space:pre-wrap";` +
53
+ ` pre.textContent = ${JSON.stringify(`Compile error\n\n${text}`)};` +
54
+ ` return pre; }`
55
+ );
56
+ }
57
+
58
+ /**
59
+ * Compile one module. `server` is a compiler client (compiler-client.js). `hot`
60
+ * requests the refresh-instrumented CSR build. On failure, `failOnError` throws the
61
+ * diagnostic (after `error(message)` when the toolchain reports through its own
62
+ * channel); otherwise it logs and returns the stub, so one broken file does not
63
+ * stop a dev server.
64
+ *
65
+ * @returns {Promise<{ code: string, map: object | null }>}
66
+ */
67
+ export async function compileModule(server, code, id, {
68
+ target, hot = false, failOnError = false, onResult, quiet = () => {}, error,
69
+ } = {}) {
70
+ try {
71
+ const out = await server.compile(id, code, !isRouteModule(id), hot && target === "csr" ? "csr-hot" : target);
72
+ onResult?.(id, null);
73
+ return typeof out === "string" ? { code: out, map: null } : { code: out.code, map: out.map ?? null };
74
+ } catch (e) {
75
+ // `text` is the diagnostic as a terminal or overlay shows it — the position line
76
+ // plus a code frame; `diag` is the same as fields, for the overlay.
77
+ const text = e?.text ?? e?.message ?? String(e);
78
+ const diag = e?.diag ?? { file: id, message: e?.message ?? String(e) };
79
+ onResult?.(id, diag);
80
+ // A build phase may be drawing on the terminal's last line; take it back first.
81
+ quiet();
82
+ if (failOnError) {
83
+ error?.(`afwc failed:\n${text}`);
84
+ throw e;
85
+ }
86
+ console.error(`✗ afwc failed:\n${text}`);
87
+ return { code: errorStub(text), map: { version: 3, sources: [], names: [], mappings: "" } };
88
+ }
89
+ }
@@ -0,0 +1,187 @@
1
+ // The `afwc serve` protocol client, shared by every toolchain integration.
2
+ //
3
+ // One long-lived compiler child serves every module of every build in the process;
4
+ // requests and replies are framed over its stdin/stdout. Starting the child is the
5
+ // only platform-specific step, so it comes from the host's `spawn` (see host.js).
6
+
7
+ /**
8
+ * Turn an `ERR` reply payload into an `Error` carrying the compiler's diagnostic.
9
+ * The payload is the JSON object `Diag::json` writes — `{ file, message, line,
10
+ * column, frame, note }` — so the position survives as data all the way to the browser
11
+ * overlay instead of being flattened into prose. An older compiler (or a protocol
12
+ * error) sends a bare string; that still works, it just has no position.
13
+ *
14
+ * `error.message` is the one-line human form (`path:line:col message`), `error.diag`
15
+ * the structured fields, and `error.text` the full terminal rendering with the frame.
16
+ */
17
+ export function compileError(payload) {
18
+ let d = null;
19
+ if (payload.startsWith("{")) {
20
+ try {
21
+ d = JSON.parse(payload);
22
+ } catch {}
23
+ }
24
+ if (!d?.message) {
25
+ const err = new Error(payload);
26
+ err.diag = { message: payload };
27
+ err.text = payload;
28
+ return err;
29
+ }
30
+ const where = d.line ? `${d.file}:${d.line}:${d.column}` : d.file;
31
+ const err = new Error(`${where}: ${d.message}`);
32
+ err.diag = d;
33
+ err.text =
34
+ `${where}: ${d.message}\n` + (d.note ? `note: ${d.note}\n` : "") + (d.frame ? `\n${d.frame}` : "");
35
+ return err;
36
+ }
37
+
38
+ /**
39
+ * Start a long-lived `afwc serve` process and talk to it over a framed
40
+ * stdin/stdout protocol (see crates/afw_cli/src/main.rs `serve`). One process
41
+ * compiles every module, so the toolchain pays the binary-startup cost once
42
+ * instead of spawning a subprocess per file — the dominant dev-server cost.
43
+ *
44
+ * `compile(id, source, component, target)` resolves to the emitted JS or rejects
45
+ * with the compiler diagnostic (`target` is `"csr"` | `"ssg"` | `"hydrate"`).
46
+ * With `{ sourceMap: true }`, success resolves to `{ code, map }`. Older
47
+ * binaries still compile, returning `map: null`. The request framing is unchanged.
48
+ * Requests are serialized through a FIFO queue: the server
49
+ * is single-threaded, replies arrive in request order, so the head of the queue
50
+ * always pairs with the next frame. The child is killed when this process exits.
51
+ */
52
+ // Every compiler child started in this process, so a one-shot command can shut them
53
+ // all down. It has to: an open reader on a child's stdout keeps the runtime alive, so
54
+ // a prerender step that simply returned would hang after its output is written.
55
+ const compilers = new Set();
56
+
57
+ /** Stop every `afwc serve` child. Called at the end of the one-shot commands. */
58
+ export async function closeCompilers() {
59
+ await Promise.all([...compilers].map((close) => close()));
60
+ compilers.clear();
61
+ }
62
+
63
+ export function startCompilerServer(afwc, { sourceMap = false, spawn } = {}) {
64
+ if (typeof spawn !== "function") throw new TypeError("startCompilerServer: a host `spawn` function is required");
65
+ const enc = new TextEncoder();
66
+ const dec = new TextDecoder();
67
+ const queue = []; // { resolve, reject } in request order
68
+ let buf = new Uint8Array(0);
69
+ let pumping = false;
70
+ let dead = false;
71
+ let started = null;
72
+
73
+ const append = (a, b) => {
74
+ const out = new Uint8Array(a.length + b.length);
75
+ out.set(a);
76
+ out.set(b, a.length);
77
+ return out;
78
+ };
79
+ const die = (err) => {
80
+ dead = true;
81
+ while (queue.length) queue.shift().reject(err);
82
+ idle();
83
+ };
84
+
85
+ // Spawning is async here, so the child is started on the first compile rather than
86
+ // when the plugin is constructed — a build that never touches a `.jsx` never pays
87
+ // for it. Nothing awaits the child's exit, so it holds nothing open; when this
88
+ // process goes, the child sees EOF on its stdin and stops.
89
+ let reading = null; // the stdout reader, so `close` can release it
90
+ // The child holds its parent process open only while a compile is in flight
91
+ // (hosts that can — Node — expose `ref`/`unref`). An idle compiler must not keep a
92
+ // build or test process alive when the toolchain never calls `close`.
93
+ let child = null;
94
+ const idle = () => child?.unref?.();
95
+
96
+ function start() {
97
+ started ??= Promise.resolve(spawn(afwc, sourceMap ? ["serve", "--sourcemap"] : ["serve"])).then((proc) => {
98
+ reading = proc.stdout.getReader();
99
+ child = proc;
100
+ return { proc, writer: proc.stdin.getWriter(), reader: reading };
101
+ });
102
+ return started;
103
+ }
104
+
105
+ // Drain reply frames as they arrive, resolving queued requests in order. A frame
106
+ // is `<status> <byteLen>\n` followed by exactly `byteLen` bytes of payload.
107
+ async function pump(reader) {
108
+ if (pumping) return;
109
+ pumping = true;
110
+ try {
111
+ while (queue.length) {
112
+ let nl = buf.indexOf(10);
113
+ while (nl === -1) {
114
+ const { value, done } = await reader.read();
115
+ if (done) return die(new Error("afwc serve exited"));
116
+ buf = append(buf, value);
117
+ nl = buf.indexOf(10);
118
+ }
119
+ const [status, lenStr] = dec.decode(buf.subarray(0, nl)).split(" ");
120
+ const len = Number(lenStr);
121
+ while (buf.length < nl + 1 + len) {
122
+ const { value, done } = await reader.read();
123
+ if (done) return die(new Error("afwc serve exited"));
124
+ buf = append(buf, value);
125
+ }
126
+ const payload = dec.decode(buf.subarray(nl + 1, nl + 1 + len));
127
+ buf = buf.slice(nl + 1 + len);
128
+ const job = queue.shift();
129
+ if (status === "MAP") job.resolve(JSON.parse(payload));
130
+ // Older packaged binaries ignore --sourcemap and return plain OK frames.
131
+ // Keep them usable; they cannot provide mappings until upgraded.
132
+ else if (status === "OK") job.resolve(sourceMap ? { code: payload, map: null } : payload);
133
+ else job.reject(compileError(payload));
134
+ if (!queue.length) idle();
135
+ }
136
+ } finally {
137
+ pumping = false;
138
+ }
139
+ }
140
+
141
+ // Replies are paired with requests by position, so the frames must reach the child
142
+ // in the order their promises were queued. Writing to a `WritableStream` is async,
143
+ // so the writes are chained rather than merely awaited per call — two concurrent
144
+ // `compile()`s would otherwise interleave their header and payload bytes.
145
+ let writes = Promise.resolve();
146
+
147
+ function compile(id, source, component, target = "csr") {
148
+ if (dead) return Promise.reject(new Error("afwc serve is not running"));
149
+ return new Promise((resolve, reject) => {
150
+ queue.push({ resolve, reject });
151
+ writes = writes
152
+ .then(async () => {
153
+ const { proc, writer, reader } = await start();
154
+ proc.ref?.();
155
+ const idB = enc.encode(id);
156
+ const srcB = enc.encode(source);
157
+ await writer.write(enc.encode(`${idB.length} ${srcB.length} ${component ? 1 : 0} ${target}\n`));
158
+ await writer.write(idB);
159
+ await writer.write(srcB);
160
+ pump(reader);
161
+ })
162
+ .catch(die);
163
+ });
164
+ }
165
+
166
+ async function close() {
167
+ compilers.delete(close);
168
+ if (dead) return;
169
+ dead = true;
170
+ if (!started) return;
171
+ try {
172
+ const { proc, writer } = await started;
173
+ try {
174
+ await writer.close();
175
+ } catch {}
176
+ // Releasing the reader matters as much as killing the child: an outstanding
177
+ // reader on a child's stdout is itself a reason for the runtime to stay up.
178
+ try {
179
+ await reading?.cancel();
180
+ } catch {}
181
+ proc.kill();
182
+ } catch {}
183
+ }
184
+
185
+ compilers.add(close);
186
+ return { compile, close };
187
+ }
package/document.js ADDED
@@ -0,0 +1,246 @@
1
+ // The HTML document, shared by every toolchain's server rendering: the shell helpers
2
+ // that place rendered markup, head tags and data payloads into the app's
3
+ // `index.html`, and `renderDocument`, which renders one URL into a complete document.
4
+ // Static generation (prerender.js) and per-request SSR both go through it, so a
5
+ // prerendered page and a server-rendered one are byte-for-byte the same document.
6
+ //
7
+ // Pure string work: nothing here touches a file system or the AFW runtime directly.
8
+ // `render` is the server render API (`renderRoute`, `renderHead` from
9
+ // `@opentf/afw/server`), passed in by the caller.
10
+
11
+ /** Inject `snippet` just before `</body>` (or append when there is none). */
12
+ export function injectBeforeBody(html, snippet) {
13
+ // Function replacer so `$` in `snippet` is literal (String.replace treats `$1`,
14
+ // `$&`, … in a string replacement as back-references — e.g. a "$189.00" price).
15
+ return html.includes("</body>") ? html.replace("</body>", () => `${snippet}</body>`) : html + snippet;
16
+ }
17
+
18
+ /** Inject pre-rendered markup into the shell's empty `#app` container. */
19
+ export function injectMarkup(shellHtml, markup) {
20
+ // Function replacer: `markup` may contain `$` (currency, etc.) — keep it literal.
21
+ return shellHtml.replace(/(<div id="app"[^>]*>)\s*(<\/div>)/, (_m, open, close) => `${open}${markup}${close}`);
22
+ }
23
+
24
+ /**
25
+ * Embed the island hydration payload (`renderRoute().hydration`) as a
26
+ * `<script type="application/json" id="__afw_h">` the client reads at upgrade so
27
+ * components resume from rich JS props (compiler-driven data hydration). Placed before
28
+ * `</body>`; a deferred module bundle runs after parse, so the payload is always in the
29
+ * DOM first. `json` is already `<`-escaped by the server collector, so it can't break out
30
+ * of the script. No-op for an empty payload. Uses a function replacer so `$` in the JSON
31
+ * stays literal.
32
+ */
33
+ export function injectHydrationData(shellHtml, json) {
34
+ if (!json) return shellHtml;
35
+ return injectBeforeBody(shellHtml, `<script type="application/json" id="__afw_h">${json}</script>`);
36
+ }
37
+
38
+ /** The reserved per-route data filename/URL suffix (mirrors the runtime's
39
+ * `DATA_FILE` in `@opentf/afw` runtime/route-data.js). */
40
+ export const DATA_FILE = "__data.json";
41
+
42
+ /**
43
+ * Embed a route loader's data (docs/DATA.md) as a `<script type="application/json"
44
+ * id="__afw_data">` the client router reads on first paint (instead of fetching
45
+ * `<path>/__data.json`). A separate script from the island payload above — the two
46
+ * channels have independent shapes and readers. `json` comes `<`-escaped from
47
+ * `serializeRouteData`; no-op for an empty payload (route without a loader, or an
48
+ * undefined loader result).
49
+ */
50
+ export function injectRouteData(shellHtml, json) {
51
+ if (!json) return shellHtml;
52
+ return injectBeforeBody(shellHtml, `<script type="application/json" id="__afw_data">${json}</script>`);
53
+ }
54
+
55
+ /**
56
+ * Stamp the `data-afw-hydrate` sentinel onto the shell's `#app` container, telling
57
+ * the client to *adopt* the server-rendered DOM on first paint instead of rebuilding
58
+ * it (`runtime/router.js` `mountApp`). Used when the client bundle was built for the
59
+ * hydrate target and there is server markup to adopt (SSR, and SSG pre-render).
60
+ * Idempotent — a no-op if the sentinel is already present.
61
+ */
62
+ export function stampHydrateSentinel(shellHtml) {
63
+ return shellHtml.replace(/<div id="app"([^>]*)>/, (m, attrs) =>
64
+ /\bdata-afw-hydrate\b/.test(attrs) ? m : `<div id="app"${attrs} data-afw-hydrate>`,
65
+ );
66
+ }
67
+
68
+ /**
69
+ * Record the route a prerendered page was rendered for on its hydrate sentinel
70
+ * (`data-afw-hydrate="/docs/x"`), so the client adopts the markup only at that URL
71
+ * and builds the requested route when a host serves this file for another path.
72
+ * A no-op when the shell carries no sentinel (a CSR-only shell).
73
+ */
74
+ export function stampRenderedPath(shellHtml, path) {
75
+ const value = String(path).replace(/&/g, "&amp;").replace(/"/g, "&quot;");
76
+ return shellHtml.replace(/(<div id="app"[^>]*?\sdata-afw-hydrate)(?:="[^"]*")?/, (_m, attr) => `${attr}="${value}"`);
77
+ }
78
+
79
+ /**
80
+ * Inject per-route `<head>` tags before `</head>`, dropping the shell's default
81
+ * `<title>` when the route supplies its own (so each page gets a unique,
82
+ * non-duplicated title). Shared by SSG pre-render and the SSR server.
83
+ */
84
+ export function injectHead(shellHtml, headHtml) {
85
+ if (!headHtml) return shellHtml;
86
+ let out = stripRouteHead(shellHtml);
87
+ if (/<title[\s>]/i.test(headHtml)) out = out.replace(/<title>[\s\S]*?<\/title>\s*/i, "");
88
+ // Function replacer so `$` in `headHtml` (e.g. a price in a meta description) is literal.
89
+ return out.replace(/<\/head>/i, () => `${headHtml}\n</head>`);
90
+ }
91
+
92
+ const ROUTE_HEAD_TAG = /<(meta|link)\b[^>]*>\s*|<script\b([^>]*)>[\s\S]*?<\/script>\s*/gi;
93
+
94
+ /** The attribute `name`'s value in an opening tag, lower-cased; "" if absent. */
95
+ function attrOf(tag, name) {
96
+ const m = tag.match(new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i"));
97
+ return (m ? (m[1] ?? m[2] ?? m[3]) : "").toLowerCase();
98
+ }
99
+
100
+ /**
101
+ * Remove the shell's route-owned SEO tags (description, robots, `og:`/`twitter:`/`article:`,
102
+ * canonical, JSON-LD, anything marked `data-afw-head`) so the page's own head replaces them.
103
+ * This is the set the client's `updateRouteHead` (runtime/head.js) removes on navigation,
104
+ * so a prerendered page and a client-navigated one end up with the same head.
105
+ */
106
+ function stripRouteHead(shellHtml) {
107
+ const head = shellHtml.match(/<head\b[^>]*>([\s\S]*?)<\/head>/i);
108
+ if (!head) return shellHtml;
109
+ const inner = head[1].replace(ROUTE_HEAD_TAG, (tag, el) => {
110
+ if (/\sdata-afw-head\b/i.test(tag)) return "";
111
+ if (el?.toLowerCase() === "meta") {
112
+ const name = attrOf(tag, "name");
113
+ const property = attrOf(tag, "property");
114
+ if (name === "description" || name === "robots" || name.startsWith("twitter:")) return "";
115
+ if (property.startsWith("og:") || property.startsWith("article:")) return "";
116
+ } else if (el?.toLowerCase() === "link") {
117
+ if (attrOf(tag, "rel") === "canonical") return "";
118
+ } else if (attrOf(tag, "type") === "application/ld+json") return "";
119
+ return tag;
120
+ });
121
+ const start = head.index + head[0].indexOf(">") + 1;
122
+ return shellHtml.slice(0, start) + inner + shellHtml.slice(start + head[1].length);
123
+ }
124
+
125
+ /** Set/replace the shell's `<html lang>` for a localized page (i18n; docs/I18N.md §6). */
126
+ export function withHtmlLang(shellHtml, locale) {
127
+ if (!locale) return shellHtml;
128
+ if (/<html[^>]*\slang=/i.test(shellHtml)) {
129
+ return shellHtml.replace(/(<html[^>]*\slang=)(["'])[^"']*\2/i, `$1$2${locale}$2`);
130
+ }
131
+ return shellHtml.replace(/<html\b/i, `<html lang="${locale}"`);
132
+ }
133
+
134
+ /** `<link rel="modulepreload">` tags for a route's chunk hrefs (`""` when there are none). */
135
+ export function modulepreloadTags(hrefs) {
136
+ if (!hrefs || hrefs.length === 0) return "";
137
+ return hrefs.map((h) => `<link rel="modulepreload" href="${h}">`).join("\n");
138
+ }
139
+
140
+ /** Escape text for an XML/HTML attribute or text node. */
141
+ export function escapeXml(s) {
142
+ return String(s).replace(/[&<>'"]/g, (c) =>
143
+ c === "&" ? "&amp;" : c === "<" ? "&lt;" : c === ">" ? "&gt;" : c === "'" ? "&apos;" : "&quot;",
144
+ );
145
+ }
146
+
147
+ /** The locale settings, or `null` when i18n is off. */
148
+ export function i18nSettings(i18n) {
149
+ if (!i18n || !Array.isArray(i18n.locales) || !i18n.locales.length) return null;
150
+ return { locales: i18n.locales, defaultLocale: i18n.defaultLocale ?? i18n.locales[0] };
151
+ }
152
+
153
+ /** Prefix a locale-agnostic path with `locale` (bare for the default locale). */
154
+ export function localizePath(path, locale, defaultLocale) {
155
+ if (!locale || locale === defaultLocale) return path;
156
+ return path === "/" ? `/${locale}` : `/${locale}${path}`;
157
+ }
158
+
159
+ /** Split a URL path into its locale and locale-agnostic path. */
160
+ export function splitLocale(pathname, i18n) {
161
+ const settings = i18nSettings(i18n);
162
+ if (!settings) return { locale: null, path: pathname };
163
+ const m = pathname.match(/^\/([^/]+)(\/.*|)$/);
164
+ if (m && m[1] !== settings.defaultLocale && settings.locales.includes(m[1])) return { locale: m[1], path: m[2] || "/" };
165
+ return { locale: settings.defaultLocale, path: pathname };
166
+ }
167
+
168
+ /** `rel="alternate" hreflang` links for a path across every locale, plus x-default. */
169
+ export function alternateLinks(path, i18n) {
170
+ const settings = i18nSettings(i18n);
171
+ if (!settings) return [];
172
+ const links = settings.locales.map((l) => ({ rel: "alternate", hreflang: l, href: localizePath(path, l, settings.defaultLocale) }));
173
+ links.push({ rel: "alternate", hreflang: "x-default", href: localizePath(path, settings.defaultLocale, settings.defaultLocale) });
174
+ return links;
175
+ }
176
+
177
+ /**
178
+ * Render one URL into a complete HTML document.
179
+ *
180
+ * `render` is `{ renderRoute, renderHead }` from the server bundle. `url` is the
181
+ * request path (locale prefix included); `params` overrides the matched route's
182
+ * params (static generation from `getStaticPaths`). With `loaders` (a
183
+ * `createLoaderRegistry`), the route's loader runs with `loaderContext`
184
+ * (`{ request, query, locals }`); a loader calling `notFound()` renders the 404 page.
185
+ * `shell` is the client's `index.html`; a hydrating build marks it with
186
+ * `stampHydrateSentinel` first. `preload` is extra head markup (modulepreload tags).
187
+ * `modifiedTime` adds `article:modified_time` on article pages. `notFound`: what a
188
+ * loader's `notFound()` does — `"render"` the 404 page (a request server), or
189
+ * `"throw"` it to the caller (static generation, which reports the path as failed).
190
+ *
191
+ * @returns {Promise<{ status: number, html: string, dataJson: string, loaded: boolean, metadata: object } | null>}
192
+ * `null` when no page and no 404 page match.
193
+ */
194
+ export async function renderDocument(render, {
195
+ shell, url, params = null, search = "", loaders = null, loaderContext = {}, baseUrl = "", i18n = null,
196
+ preload = "", modifiedTime = null, notFound = "render",
197
+ } = {}) {
198
+ const { locale, path } = splitLocale(url, i18n);
199
+ const match = loaders?.match(url);
200
+ let data;
201
+ let dataJson = "";
202
+ if (match) {
203
+ try {
204
+ ({ data, json: dataJson } = await loaders.loadSerialized(match, { query: {}, ...loaderContext }));
205
+ } catch (e) {
206
+ if (e?.afwNotFound !== true || notFound === "throw") throw e;
207
+ return renderNotFound(render, { shell, baseUrl, preload });
208
+ }
209
+ }
210
+ const result = await render.renderRoute(url, params, search, { data });
211
+ if (!result) return null;
212
+ const { html, metadata = {}, hydration = "", status = 200 } = result;
213
+ const alternates = alternateLinks(path, i18n);
214
+ const meta = alternates.length ? { ...metadata, links: [...(metadata.links || []), ...alternates] } : metadata;
215
+ let head = render.renderHead(status === 404 ? { robots: "noindex", ...meta } : meta, { path: url, baseUrl, managed: true });
216
+ if (preload) head += `\n${preload}`;
217
+ // Article tags only on an article: `og:type` "article", or a page with a publish
218
+ // `date`. An index or a landing page is a website; a modified time there describes nothing.
219
+ const published = typeof metadata?.date === "string" ? metadata.date.trim() : "";
220
+ const article = metadata?.openGraph?.type === "article" || Boolean(published);
221
+ if (article && modifiedTime) head += `\n<meta data-afw-head="" property="article:modified_time" content="${escapeXml(modifiedTime)}">`;
222
+ if (published) head += `\n<meta data-afw-head="" property="article:published_time" content="${escapeXml(published)}">`;
223
+ const document = injectRouteData(
224
+ injectHydrationData(
225
+ injectMarkup(injectHead(withHtmlLang(stampRenderedPath(shell, url), locale), head), html),
226
+ hydration,
227
+ ),
228
+ dataJson,
229
+ );
230
+ return { status, html: document, dataJson, loaded: !!match, metadata };
231
+ }
232
+
233
+ /** The 404 page as a document (`noindex`), or `null` when the app has none. */
234
+ export async function renderNotFound(render, { shell, baseUrl = "", preload = "" } = {}) {
235
+ const result = await render.renderRoute("/__afw_404__");
236
+ if (!result) return null;
237
+ let head = render.renderHead({ robots: "noindex", ...result.metadata }, { baseUrl, managed: true });
238
+ if (preload) head += `\n${preload}`;
239
+ return {
240
+ status: 404,
241
+ html: injectHydrationData(injectMarkup(injectHead(shell, head), result.html), result.hydration),
242
+ dataJson: "",
243
+ loaded: false,
244
+ metadata: result.metadata ?? {},
245
+ };
246
+ }
package/host.js ADDED
@@ -0,0 +1,51 @@
1
+ // The host interface: everything `@opentf/afw-build` needs from the platform it runs
2
+ // on. This package never imports `runtime:*` or `node:*`; each toolchain integration
3
+ // (`@opentf/esdev-plugin-afw` on ES-Runtime, `@opentf/vite-plugin-afw` on Node)
4
+ // supplies one of these objects, so the build logic is written once.
5
+ //
6
+ // Paths are absolute and `/`-separated in everything the host returns.
7
+
8
+ /**
9
+ * @typedef {object} DirEntry
10
+ * @property {string} name
11
+ * @property {boolean} isFile
12
+ * @property {boolean} isDir
13
+ * @property {boolean} [isSymlink]
14
+ */
15
+
16
+ /**
17
+ * @typedef {object} ChildProcess
18
+ * @property {WritableStream<Uint8Array>} stdin
19
+ * @property {ReadableStream<Uint8Array>} stdout
20
+ * @property {() => void} kill
21
+ * @property {() => void} [ref] Keep the parent process alive (a compile is in flight).
22
+ * @property {() => void} [unref] Let the parent exit while the child idles.
23
+ */
24
+
25
+ /**
26
+ * @typedef {object} BuildHost
27
+ * @property {(path: string) => Promise<string>} readText Read a UTF-8 file.
28
+ * @property {(path: string) => Promise<DirEntry[]>} readDir List a directory.
29
+ * @property {(path: string, text: string) => Promise<void>} writeText
30
+ * Write a UTF-8 file, creating missing parent directories.
31
+ * @property {(path: string) => Promise<"file" | "dir" | null>} kind
32
+ * What is at `path` (symlinks followed), or `null` when nothing is, or it is unreadable.
33
+ * @property {(program: string, args: string[]) => Promise<ChildProcess>} spawn
34
+ * Start a long-lived child with piped stdin/stdout and inherited stderr.
35
+ * @property {(program: string, args: string[], options?: { cwd?: string, inherit?: boolean }) => Promise<{ ok: boolean, code: number | null }>} run
36
+ * Run a command to completion. A missing program resolves `{ ok: false }`.
37
+ * @property {() => string} cwd
38
+ * @property {Record<string, string | undefined>} env
39
+ * @property {{ join: (...parts: string[]) => string, dirname: (path: string) => string, resolve: (...parts: string[]) => string }} path
40
+ */
41
+
42
+ /** The host methods every caller of a module here may need, checked up front so a
43
+ * missing method fails with its name instead of "undefined is not a function". */
44
+ export function assertHost(host, methods) {
45
+ if (!host || typeof host !== "object") throw new TypeError("afw-build: a host object is required");
46
+ for (const name of methods) {
47
+ const value = name === "path" ? host.path : host[name];
48
+ if (value == null) throw new TypeError(`afw-build: the host is missing \`${name}\``);
49
+ }
50
+ return host;
51
+ }
package/index.js ADDED
@@ -0,0 +1,27 @@
1
+ // `@opentf/afw-build` — the toolchain-neutral half of AFW's build: the compiler
2
+ // client, compile-target rules, compiler resolution and file-convention routing.
3
+ // Toolchain integrations (`@opentf/esdev-plugin-afw`, `@opentf/vite-plugin-afw`)
4
+ // pass a host object (host.js) and wire these into their own plugin APIs.
5
+
6
+ export { assertHost } from "./host.js";
7
+ export { compileError, closeCompilers, startCompilerServer } from "./compiler-client.js";
8
+ export {
9
+ FRAMEWORK_IMPORT, MODES, SOURCE_FILTER, TARGETS,
10
+ chooseTarget, compileModule, errorStub, isRouteModule, usesServerEntry, validateOptions,
11
+ } from "./compile.js";
12
+ export { ensureCompiler, findUp, resolveCompiler } from "./resolve-compiler.js";
13
+ export {
14
+ ROUTES_ID,
15
+ discoverLoaders, discoverPages, findGuard, isUnpublishedPage, isUnpublishedSource,
16
+ resolveAppRoot, routeKey, routesModule,
17
+ } from "./routes.js";
18
+ export { SERVER_ID, discoverServerFiles, hasServerFiles, serverConflicts, serverModule } from "./server.js";
19
+ export {
20
+ DATA_FILE, alternateLinks, escapeXml, i18nSettings, injectBeforeBody, injectHead, injectHydrationData,
21
+ injectMarkup, injectRouteData, localizePath, modulepreloadTags, renderDocument, renderNotFound, splitLocale,
22
+ stampHydrateSentinel, stampRenderedPath, withHtmlLang,
23
+ } from "./document.js";
24
+ export { prerender, robotsTxt, sitemapXml } from "./prerender.js";
25
+ export {
26
+ SERVER_MODULE_FILE, discoverServerModules, serverExports, serverFunctionEndpoint, serverFunctionStub, serverFunctionTable,
27
+ } from "./server-functions.js";