@opentf/afw-build 0.1.0 → 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/index.js CHANGED
@@ -22,3 +22,6 @@ export {
22
22
  stampHydrateSentinel, stampRenderedPath, withHtmlLang,
23
23
  } from "./document.js";
24
24
  export { prerender, robotsTxt, sitemapXml } from "./prerender.js";
25
+ export {
26
+ SERVER_MODULE_FILE, discoverServerModules, serverExports, serverFunctionEndpoint, serverFunctionStub, serverFunctionTable,
27
+ } from "./server-functions.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opentf/afw-build",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "The toolchain-neutral core of AFW's build: compiler client, compile targets and file-based routing.",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -19,7 +19,8 @@
19
19
  "routes.js",
20
20
  "server.js",
21
21
  "document.js",
22
- "prerender.js"
22
+ "prerender.js",
23
+ "server-functions.js"
23
24
  ],
24
25
  "keywords": [
25
26
  "afw",
@@ -0,0 +1,107 @@
1
+ // Server functions at build time (docs/SERVER_FUNCTIONS.md), shared by every toolchain:
2
+ // find the app's `*.server.{js,ts}` modules, give each `query()` / `action()` export a
3
+ // stable endpoint under its folder, and generate the browser stub that calls it.
4
+ //
5
+ // Endpoints are computed here and nowhere else: the browser stub and the server's
6
+ // endpoint table both come from `serverFunctionEndpoint`, so they cannot disagree.
7
+
8
+ /** A server module's file name. */
9
+ export const SERVER_MODULE_FILE = /\.server\.(?:[cm]?js|[cm]?ts)$/;
10
+
11
+ // FNV-1a, 64-bit: a stable, short id that does not reveal the file path.
12
+ function fnv1a64(text) {
13
+ let hash = 0xcbf29ce484222325n;
14
+ for (const byte of new TextEncoder().encode(text)) {
15
+ hash ^= BigInt(byte);
16
+ hash = (hash * 0x100000001b3n) & 0xffffffffffffffffn;
17
+ }
18
+ return hash.toString(16).padStart(16, "0");
19
+ }
20
+
21
+ const relativeTo = (root, file) => (file.startsWith(`${root}/`) ? file.slice(root.length + 1) : null);
22
+
23
+ /**
24
+ * The endpoint of export `name` of the server module `file` under the app at `root`:
25
+ * `<folder>/__fn/<id>`, so the folder's `_middleware` governs it.
26
+ */
27
+ export function serverFunctionEndpoint(root, file, name) {
28
+ const rel = relativeTo(root, file);
29
+ if (rel === null) throw new Error(`${file}: server modules must be inside the app directory (${root})`);
30
+ const folder = rel.includes("/") ? `/${rel.slice(0, rel.lastIndexOf("/"))}` : "";
31
+ return `${folder}/__fn/${fnv1a64(`${rel}#${name}`)}`;
32
+ }
33
+
34
+ /** Every `*.server` module under `dir`, sorted, skipping dot folders, node_modules and `exclude`. */
35
+ export async function discoverServerModules(host, dir, { exclude = [] } = {}) {
36
+ const skip = new Set(exclude);
37
+ const found = [];
38
+ async function visit(abs, rel) {
39
+ let entries;
40
+ try {
41
+ entries = await host.readDir(abs);
42
+ } catch {
43
+ return;
44
+ }
45
+ for (const entry of entries) {
46
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
47
+ if ([...skip].some((name) => childRel === name || childRel.startsWith(`${name}/`))) continue;
48
+ const childAbs = host.path.join(abs, entry.name);
49
+ if (entry.isDir) {
50
+ if (!entry.name.startsWith(".") && entry.name !== "node_modules") await visit(childAbs, childRel);
51
+ } else if (entry.isFile && SERVER_MODULE_FILE.test(entry.name)) {
52
+ found.push(childAbs);
53
+ }
54
+ }
55
+ }
56
+ await visit(dir, "");
57
+ return found.sort();
58
+ }
59
+
60
+ /**
61
+ * The exports of a server module, from the compiler (`afwc serve`'s `server-exports`):
62
+ * `[{ name, kind: "query" | "action" | null }]`. Rejects with the compiler's diagnostic
63
+ * for shapes it cannot read statically.
64
+ */
65
+ export async function serverExports(compiler, file, source) {
66
+ const out = await compiler.compile(file, source, false, "server-exports");
67
+ return JSON.parse(typeof out === "string" ? out : out.code).exports;
68
+ }
69
+
70
+ /**
71
+ * The browser module that replaces a server module: one fetch stub per server function.
72
+ * Plain exports are left out, so importing a server-only helper from browser code fails
73
+ * the build instead of shipping it.
74
+ */
75
+ export function serverFunctionStub(root, file, exports) {
76
+ const lines = [`import { serverFunction } from "@opentf/afw";`];
77
+ for (const { name, kind } of exports) {
78
+ if (!kind) continue;
79
+ const endpoint = JSON.stringify(serverFunctionEndpoint(root, file, name));
80
+ lines.push(name === "default"
81
+ ? `export default serverFunction(${endpoint}, ${JSON.stringify(kind)});`
82
+ : `export const ${name} = serverFunction(${endpoint}, ${JSON.stringify(kind)});`);
83
+ }
84
+ return `${lines.join("\n")}\n`;
85
+ }
86
+
87
+ /**
88
+ * The server side: for each server module, its import and the endpoint table entries.
89
+ * `listExports(file)` returns the module's exports (see `serverExports`).
90
+ *
91
+ * @returns {Promise<{ imports: string, table: string, files: string[] }>}
92
+ */
93
+ export async function serverFunctionTable(host, root, { exclude = [], listExports }) {
94
+ const files = await discoverServerModules(host, root, { exclude });
95
+ const imports = [];
96
+ const entries = [];
97
+ for (const [i, file] of files.entries()) {
98
+ const exports = await listExports(file);
99
+ const fns = exports.filter((e) => e.kind);
100
+ if (!fns.length) continue;
101
+ imports.push(`import * as sf${i} from ${JSON.stringify(file)};`);
102
+ for (const { name } of fns) {
103
+ entries.push(` [${JSON.stringify(serverFunctionEndpoint(root, file, name))}]: sf${i}[${JSON.stringify(name)}],`);
104
+ }
105
+ }
106
+ return { imports: imports.join("\n"), table: entries.join("\n"), files };
107
+ }
package/server.js CHANGED
@@ -13,6 +13,7 @@
13
13
  // // middleware → API routes → loader data → files → page render → fallback
14
14
 
15
15
  import { discoverPages, routeKey } from "./routes.js";
16
+ import { serverFunctionTable } from "./server-functions.js";
16
17
 
17
18
  /** The specifier a server entry imports. */
18
19
  export const SERVER_ID = "@afw/server";
@@ -120,7 +121,7 @@ export function serverConflicts(host, dir, files) {
120
121
  * pages?: boolean, drafts?: boolean }} [options]
121
122
  * @returns {Promise<{ code: string, files: string[] }>}
122
123
  */
123
- export async function serverModule(host, root, { exclude = [], i18n = null, pages = false, drafts = true } = {}) {
124
+ export async function serverModule(host, root, { exclude = [], i18n = null, pages = false, drafts = true, listExports } = {}) {
124
125
  const files = await discoverServerFiles(host, root, { exclude });
125
126
  const problems = serverConflicts(host, root, files);
126
127
  if (problems.length) throw new Error(`AFW server routes:\n ${problems.join("\n ")}`);
@@ -134,16 +135,20 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
134
135
  options.i18n = { locales: i18n.locales, defaultLocale: i18n.defaultLocale ?? i18n.locales[0] };
135
136
  }
136
137
  const pageFiles = pages ? await discoverPages(host, root, { exclude, drafts }) : [];
138
+ // Server functions (docs/SERVER_FUNCTIONS.md): `listExports(file)` asks the compiler
139
+ // which exports of a `.server` module are query()/action().
140
+ const fns = listExports ? await serverFunctionTable(host, root, { exclude, listExports }) : { imports: "", table: "", files: [] };
137
141
  const p = group(pageFiles, "p");
138
142
  const renderPart = pages
139
143
  ? `import { collectRoutePaths, configureI18n, registerRoutes, renderHead, renderRoute, resolveMetadata } from "@opentf/afw/server";\n` +
140
- `import { renderDocument } from "@opentf/afw-build/document";\n` +
144
+ `import { renderDocument, stampHydrateSentinel } from "@opentf/afw-build/document";\n` +
141
145
  (p.imports ? `${p.imports}\n` : "") +
142
146
  (options.i18n ? `configureI18n(options.i18n);\n` : "") +
143
147
  `registerRoutes({\n${pageFiles.map((f, i) => ` [${JSON.stringify(routeKey(f, root))}]: p${i},`).join("\n")}\n});\n` +
144
148
  `export const render = { renderRoute, renderHead, collectRoutePaths, resolveMetadata };\n` +
145
- `/** A \`renderPage\` step: server-render page requests (\`GET\`/\`HEAD\`) into \`shell\`. */\n` +
146
- `export function createPageRenderer({ shell, baseUrl = "" }) {\n` +
149
+ `/** A \`renderPage\` step: server-render page requests (\`GET\`/\`HEAD\`) into \`shell\`, the client's index.html. */\n` +
150
+ `export function createPageRenderer({ shell: html, baseUrl = "" }) {\n` +
151
+ ` const shell = stampHydrateSentinel(html);\n` +
147
152
  ` return async (request, { locals = {} } = {}) => {\n` +
148
153
  ` const method = request.method.toUpperCase();\n` +
149
154
  ` if (method !== "GET" && method !== "HEAD") return null;\n` +
@@ -160,8 +165,8 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
160
165
  `}\n`
161
166
  : "";
162
167
  const code =
163
- `import { createApiHandler, createFetchHandler, createLoaderRegistry, createMiddleware } from "@opentf/afw/server";\n` +
164
- [r.imports, m.imports, l.imports].filter(Boolean).join("\n") + "\n" +
168
+ `import { createApiHandler, createFetchHandler, createLoaderRegistry, createMiddleware, createServerFunctions } from "@opentf/afw/server";\n` +
169
+ [r.imports, m.imports, l.imports, fns.imports].filter(Boolean).join("\n") + "\n" +
165
170
  `const options = ${JSON.stringify(options)};\n` +
166
171
  `const routeModules = {\n${r.map}\n};\n` +
167
172
  `const middlewareModules = {\n${m.map}\n};\n` +
@@ -170,6 +175,7 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
170
175
  `export const apiRoutes = createApiHandler(routeModules, {}, options);\n` +
171
176
  `export const middleware = createMiddleware(middlewareModules, options);\n` +
172
177
  `export const loaders = createLoaderRegistry(loaderModules, options);\n` +
178
+ `export const serverFunctions = createServerFunctions({\n${fns.table}\n});\n` +
173
179
  `export const loaderRoutes = ${JSON.stringify(loaderRoutePatterns(host, root, files.loaders))};\n` +
174
180
  renderPart +
175
181
  `/**\n` +
@@ -181,13 +187,14 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
181
187
  ` const terminal = async (request, env, ctx, init) => {\n` +
182
188
  ` const locals = init?.locals ?? {};\n` +
183
189
  ` return (await apiRoutes(request, env, ctx, init)) ??\n` +
190
+ ` (await serverFunctions.handle(request, { locals, env, ctx })) ??\n` +
184
191
  ` (await loaders.handle(request, { locals })) ??\n` +
185
192
  ` (files ? await files(request) : null) ??\n` +
186
193
  ` (renderPage ? await renderPage(request, { locals }) : null);\n` +
187
194
  ` };\n` +
188
195
  ` return createFetchHandler(terminal, { middleware, fallback });\n` +
189
196
  `}\n`;
190
- return { code, files: [...files.routes, ...files.middleware, ...files.loaders, ...pageFiles] };
197
+ return { code, files: [...files.routes, ...files.middleware, ...files.loaders, ...pageFiles, ...fns.files] };
191
198
  }
192
199
 
193
200
  function loaderRoutePatterns(host, root, loaders) {