@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 +21 -0
- package/README.md +34 -2
- package/compile.js +89 -0
- package/compiler-client.js +187 -0
- package/document.js +246 -0
- package/host.js +51 -0
- package/index.js +27 -0
- package/package.json +41 -4
- package/prerender.js +124 -0
- package/resolve-compiler.js +75 -0
- package/routes.js +176 -0
- package/server-functions.js +107 -0
- package/server.js +205 -0
package/server.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// The server half of file-based routing, shared by every toolchain: discover API
|
|
2
|
+
// routes (`route.*`), middleware (`_middleware.*`) and loaders (`loader.*`) under
|
|
3
|
+
// `app/`, check how they sit beside pages, and generate the `@afw/server` module that
|
|
4
|
+
// composes them into one Fetch handler:
|
|
5
|
+
//
|
|
6
|
+
// import { createHandler, createPageRenderer } from "@afw/server";
|
|
7
|
+
// const handle = createHandler({
|
|
8
|
+
// files: serveBuiltFile, // optional: built assets
|
|
9
|
+
// renderPage: createPageRenderer({ shell }), // optional: server-rendered pages
|
|
10
|
+
// fallback: () => new Response("Not Found", { status: 404 }),
|
|
11
|
+
// });
|
|
12
|
+
// const response = await handle(request);
|
|
13
|
+
// // middleware → API routes → loader data → files → page render → fallback
|
|
14
|
+
|
|
15
|
+
import { discoverPages, routeKey } from "./routes.js";
|
|
16
|
+
import { serverFunctionTable } from "./server-functions.js";
|
|
17
|
+
|
|
18
|
+
/** The specifier a server entry imports. */
|
|
19
|
+
export const SERVER_ID = "@afw/server";
|
|
20
|
+
|
|
21
|
+
const ROUTE_FILE = /^route\.(jsx?|tsx?)$/;
|
|
22
|
+
const MIDDLEWARE_FILE = /^_middleware\.(jsx?|tsx?)$/;
|
|
23
|
+
const LOADER_FILE = /^loader\.(js|ts)$/;
|
|
24
|
+
const PAGE_FILE = /^page\.(mdx|md|jsx|tsx)$/;
|
|
25
|
+
|
|
26
|
+
async function walk(host, dir, exclude, visitFile) {
|
|
27
|
+
async function visit(abs, rel) {
|
|
28
|
+
let entries;
|
|
29
|
+
try {
|
|
30
|
+
entries = await host.readDir(abs);
|
|
31
|
+
} catch {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
for (const entry of entries) {
|
|
35
|
+
const childRel = rel ? `${rel}/${entry.name}` : entry.name;
|
|
36
|
+
if ([...exclude].some((name) => childRel === name || childRel.startsWith(`${name}/`))) continue;
|
|
37
|
+
const childAbs = host.path.join(abs, entry.name);
|
|
38
|
+
let isDir = entry.isDir;
|
|
39
|
+
let isFile = entry.isFile;
|
|
40
|
+
if (entry.isSymlink) {
|
|
41
|
+
const kind = await host.kind(childAbs);
|
|
42
|
+
isDir = kind === "dir";
|
|
43
|
+
isFile = kind === "file";
|
|
44
|
+
}
|
|
45
|
+
if (isDir) {
|
|
46
|
+
if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
|
|
47
|
+
await visit(childAbs, childRel);
|
|
48
|
+
} else if (isFile) {
|
|
49
|
+
visitFile(entry.name, childAbs, rel);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
await visit(dir, "");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Server files under `dir`, as sorted absolute paths, plus each folder's page (for
|
|
58
|
+
* the conflict checks).
|
|
59
|
+
*
|
|
60
|
+
* @returns {Promise<{ routes: string[], middleware: string[], loaders: string[], pages: Map<string, string> }>}
|
|
61
|
+
*/
|
|
62
|
+
export async function discoverServerFiles(host, dir, { exclude = [] } = {}) {
|
|
63
|
+
const routes = [], middleware = [], loaders = [];
|
|
64
|
+
const pages = new Map(); // folder (relative, "" for the root) → page file
|
|
65
|
+
await walk(host, dir, new Set(exclude), (name, abs, folder) => {
|
|
66
|
+
if (ROUTE_FILE.test(name)) routes.push(abs);
|
|
67
|
+
else if (MIDDLEWARE_FILE.test(name)) middleware.push(abs);
|
|
68
|
+
else if (LOADER_FILE.test(name)) loaders.push(abs);
|
|
69
|
+
else if (PAGE_FILE.test(name)) pages.set(folder, abs);
|
|
70
|
+
});
|
|
71
|
+
return { routes: routes.sort(), middleware: middleware.sort(), loaders: loaders.sort(), pages };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Whether the app has anything for a server to run. */
|
|
75
|
+
export function hasServerFiles({ routes, middleware, loaders }) {
|
|
76
|
+
return routes.length + middleware.length + loaders.length > 0;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const folderOf = (host, dir, file) => {
|
|
80
|
+
const parent = host.path.dirname(file);
|
|
81
|
+
return parent === dir ? "" : parent.slice(dir.length + 1);
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Layout mistakes the server cannot route around: a page and an API route in the
|
|
86
|
+
* same folder (both answer one URL), and a loader with no page beside it.
|
|
87
|
+
*
|
|
88
|
+
* @returns {string[]} one message per problem; empty when the layout is sound.
|
|
89
|
+
*/
|
|
90
|
+
export function serverConflicts(host, dir, files) {
|
|
91
|
+
const problems = [];
|
|
92
|
+
for (const route of files.routes) {
|
|
93
|
+
const folder = folderOf(host, dir, route);
|
|
94
|
+
if (files.pages.has(folder)) {
|
|
95
|
+
problems.push(`a page and an API route answer /${folder}: ${files.pages.get(folder)} and ${route}. Move one to another folder.`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
for (const loader of files.loaders) {
|
|
99
|
+
const folder = folderOf(host, dir, loader);
|
|
100
|
+
if (files.pages.has(folder)) continue;
|
|
101
|
+
const beside = files.routes.some((r) => folderOf(host, dir, r) === folder);
|
|
102
|
+
problems.push(
|
|
103
|
+
`${loader} ${beside ? "sits next to a route.* API endpoint (endpoints take a Request; loaders feed pages)" : "has no sibling page.* to feed"}.`,
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
return problems;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Generate the `@afw/server` module for the app at `root`. It exports the composed
|
|
111
|
+
* pieces (`apiHandler`, `apiRoutes`, `middleware`, `loaders`) and `createHandler`,
|
|
112
|
+
* whose Fetch handler runs middleware around API routes and loader data, then the
|
|
113
|
+
* optional `files` and `renderPage` steps, then `fallback`. Throws on a layout conflict.
|
|
114
|
+
*
|
|
115
|
+
* With `pages`, the module also registers every page (compiled for the server) and
|
|
116
|
+
* exports `render` (the render API static generation needs) and
|
|
117
|
+
* `createPageRenderer({ shell, baseUrl })`, a `renderPage` step built on
|
|
118
|
+
* `renderDocument`. `drafts: false` leaves unpublished Markdown pages out.
|
|
119
|
+
*
|
|
120
|
+
* @param {{ exclude?: string[], i18n?: { locales: string[], defaultLocale?: string } | null,
|
|
121
|
+
* pages?: boolean, drafts?: boolean }} [options]
|
|
122
|
+
* @returns {Promise<{ code: string, files: string[] }>}
|
|
123
|
+
*/
|
|
124
|
+
export async function serverModule(host, root, { exclude = [], i18n = null, pages = false, drafts = true, listExports } = {}) {
|
|
125
|
+
const files = await discoverServerFiles(host, root, { exclude });
|
|
126
|
+
const problems = serverConflicts(host, root, files);
|
|
127
|
+
if (problems.length) throw new Error(`AFW server routes:\n ${problems.join("\n ")}`);
|
|
128
|
+
const group = (list, prefix) => ({
|
|
129
|
+
imports: list.map((p, i) => `import * as ${prefix}${i} from ${JSON.stringify(p)};`).join("\n"),
|
|
130
|
+
map: list.map((p, i) => ` [${JSON.stringify(p)}]: ${prefix}${i},`).join("\n"),
|
|
131
|
+
});
|
|
132
|
+
const r = group(files.routes, "r"), m = group(files.middleware, "m"), l = group(files.loaders, "l");
|
|
133
|
+
const options = { appDir: root };
|
|
134
|
+
if (i18n && Array.isArray(i18n.locales) && i18n.locales.length) {
|
|
135
|
+
options.i18n = { locales: i18n.locales, defaultLocale: i18n.defaultLocale ?? i18n.locales[0] };
|
|
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: [] };
|
|
141
|
+
const p = group(pageFiles, "p");
|
|
142
|
+
const renderPart = pages
|
|
143
|
+
? `import { collectRoutePaths, configureI18n, registerRoutes, renderHead, renderRoute, resolveMetadata } from "@opentf/afw/server";\n` +
|
|
144
|
+
`import { renderDocument, stampHydrateSentinel } from "@opentf/afw-build/document";\n` +
|
|
145
|
+
(p.imports ? `${p.imports}\n` : "") +
|
|
146
|
+
(options.i18n ? `configureI18n(options.i18n);\n` : "") +
|
|
147
|
+
`registerRoutes({\n${pageFiles.map((f, i) => ` [${JSON.stringify(routeKey(f, root))}]: p${i},`).join("\n")}\n});\n` +
|
|
148
|
+
`export const render = { renderRoute, renderHead, collectRoutePaths, resolveMetadata };\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` +
|
|
152
|
+
` return async (request, { locals = {} } = {}) => {\n` +
|
|
153
|
+
` const method = request.method.toUpperCase();\n` +
|
|
154
|
+
` if (method !== "GET" && method !== "HEAD") return null;\n` +
|
|
155
|
+
` const url = new URL(request.url);\n` +
|
|
156
|
+
` const doc = await renderDocument(render, {\n` +
|
|
157
|
+
` shell, url: url.pathname, search: url.search, loaders, baseUrl, i18n: options.i18n ?? null,\n` +
|
|
158
|
+
` loaderContext: { request, query: Object.fromEntries(url.searchParams), locals },\n` +
|
|
159
|
+
` });\n` +
|
|
160
|
+
` if (!doc) return null;\n` +
|
|
161
|
+
` return new Response(method === "HEAD" ? null : doc.html, {\n` +
|
|
162
|
+
` status: doc.status, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache" },\n` +
|
|
163
|
+
` });\n` +
|
|
164
|
+
` };\n` +
|
|
165
|
+
`}\n`
|
|
166
|
+
: "";
|
|
167
|
+
const code =
|
|
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" +
|
|
170
|
+
`const options = ${JSON.stringify(options)};\n` +
|
|
171
|
+
`const routeModules = {\n${r.map}\n};\n` +
|
|
172
|
+
`const middlewareModules = {\n${m.map}\n};\n` +
|
|
173
|
+
`const loaderModules = {\n${l.map}\n};\n` +
|
|
174
|
+
`export const apiHandler = createApiHandler(routeModules, middlewareModules, options);\n` +
|
|
175
|
+
`export const apiRoutes = createApiHandler(routeModules, {}, options);\n` +
|
|
176
|
+
`export const middleware = createMiddleware(middlewareModules, options);\n` +
|
|
177
|
+
`export const loaders = createLoaderRegistry(loaderModules, options);\n` +
|
|
178
|
+
`export const serverFunctions = createServerFunctions({\n${fns.table}\n});\n` +
|
|
179
|
+
`export const loaderRoutes = ${JSON.stringify(loaderRoutePatterns(host, root, files.loaders))};\n` +
|
|
180
|
+
renderPart +
|
|
181
|
+
`/**\n` +
|
|
182
|
+
` * A Fetch handler. Inside the middleware: API routes, loader data (\`<path>/__data.json\`),\n` +
|
|
183
|
+
` * then \`files(request)\` and \`renderPage(request, { locals })\` when given (each may\n` +
|
|
184
|
+
` * return null to pass). Then \`fallback\`.\n` +
|
|
185
|
+
` */\n` +
|
|
186
|
+
`export function createHandler({ files, renderPage, fallback } = {}) {\n` +
|
|
187
|
+
` const terminal = async (request, env, ctx, init) => {\n` +
|
|
188
|
+
` const locals = init?.locals ?? {};\n` +
|
|
189
|
+
` return (await apiRoutes(request, env, ctx, init)) ??\n` +
|
|
190
|
+
` (await serverFunctions.handle(request, { locals, env, ctx })) ??\n` +
|
|
191
|
+
` (await loaders.handle(request, { locals })) ??\n` +
|
|
192
|
+
` (files ? await files(request) : null) ??\n` +
|
|
193
|
+
` (renderPage ? await renderPage(request, { locals }) : null);\n` +
|
|
194
|
+
` };\n` +
|
|
195
|
+
` return createFetchHandler(terminal, { middleware, fallback });\n` +
|
|
196
|
+
`}\n`;
|
|
197
|
+
return { code, files: [...files.routes, ...files.middleware, ...files.loaders, ...pageFiles, ...fns.files] };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function loaderRoutePatterns(host, root, loaders) {
|
|
201
|
+
return loaders.map((file) => {
|
|
202
|
+
const folder = folderOf(host, root, file);
|
|
203
|
+
return folder ? `/${folder}` : "/";
|
|
204
|
+
}).sort();
|
|
205
|
+
}
|