@dokebi/template-inertia 0.4.20 → 0.4.22
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/AI.md +53 -4
- package/README.md +1 -1
- package/dist/errors.d.ts +2 -2
- package/dist/errors.js +3 -1
- package/dist/index.d.ts +19 -0
- package/dist/index.js +116 -12
- package/dist/options.d.ts +9 -0
- package/dist/options.js +53 -0
- package/dist/pages.d.ts +33 -0
- package/dist/pages.js +82 -0
- package/dist/responder.d.ts +6 -0
- package/dist/responder.js +18 -8
- package/dist/template-build.js +61 -7
- package/dist/template-bundle.js +11 -7
- package/dist/template-preview.d.ts +38 -0
- package/dist/template-preview.js +336 -0
- package/dist/template-runtime.d.ts +157 -0
- package/dist/template-runtime.js +771 -0
- package/dist/template-shared.d.ts +6 -0
- package/dist/template-shared.js +36 -2
- package/dist/template.d.ts +2 -1
- package/dist/template.js +2 -1
- package/dist/vite-plugin.js +3 -0
- package/dist/vue-typescript.d.ts +9 -0
- package/dist/vue-typescript.js +68 -0
- package/options.schema.json +79 -1
- package/package.json +7 -2
- package/templates/shared.ts +4 -0
|
@@ -0,0 +1,771 @@
|
|
|
1
|
+
// D-0291 stage 2: template bundles used while the app runs. For each app and template named in
|
|
2
|
+
// `templates.<app>.<template>.path`, the bundle folder (a mount outside the image) is read once
|
|
3
|
+
// into the process's cache folder — every file hashed against the manifest on the way, so what
|
|
4
|
+
// was checked is what runs — checked against what the app build provides, judged by the app's
|
|
5
|
+
// `verifyTemplate`, and its server modules imported. Only then does it become the template's
|
|
6
|
+
// current generation: the next request uses it, a request under way keeps the one it started
|
|
7
|
+
// with. The mount is looked at again every `templateCheckMs`.
|
|
8
|
+
//
|
|
9
|
+
// A page of a host whose template has a generation gets, in its first HTML, an import map (the
|
|
10
|
+
// shared modules → the app build's files of them, so the bundle's `import 'vue'` is the app's vue)
|
|
11
|
+
// and the table of the bundle's pages; the asset version carries `+<template>@<buildId>`. Server
|
|
12
|
+
// rendering reads the generation through a global registry (`templatePages()` of
|
|
13
|
+
// `@dokebi/template-inertia/pages` has no imports) under an AsyncLocalStorage store, and the
|
|
14
|
+
// bundle's server modules import the shared modules through a resolve hook that answers only
|
|
15
|
+
// importers inside the cache folder. Nothing here stops the start: a missing, broken or refused
|
|
16
|
+
// bundle leaves its template to the app's own pages, said once per window.
|
|
17
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
18
|
+
import { randomBytes } from 'node:crypto';
|
|
19
|
+
import { createReadStream, existsSync } from 'node:fs';
|
|
20
|
+
import { lstat, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
21
|
+
import { registerHooks } from 'node:module';
|
|
22
|
+
import { dirname, extname, isAbsolute, join, resolve, sep } from 'node:path';
|
|
23
|
+
import { pathToFileURL } from 'node:url';
|
|
24
|
+
import { diagnostics } from '@dokebi/core/libraries';
|
|
25
|
+
import { checkTemplateBundle, manifestProblem, SERVER_ONLY_SHARED, sha256, sharedProblems, TEMPLATE_MANIFEST, TEMPLATE_SIGNATURE, } from './template-bundle.js';
|
|
26
|
+
import { SHARED_FILE } from './template-shared.js';
|
|
27
|
+
const { describeError } = diagnostics;
|
|
28
|
+
/** The URL prefix of bundle files (one route for every app, template and generation). */
|
|
29
|
+
export const TEMPLATE_FILES_PREFIX = '/_dokebi/templates/';
|
|
30
|
+
/** The registry `templatePages()` reads during server rendering (no imports there). */
|
|
31
|
+
export const TEMPLATE_REGISTRY = Symbol.for('dokebi.inertia.template-bundles.v1');
|
|
32
|
+
/** One loaded bundle of one app's template. */
|
|
33
|
+
export class TemplateGeneration {
|
|
34
|
+
app;
|
|
35
|
+
template;
|
|
36
|
+
buildId;
|
|
37
|
+
manifest;
|
|
38
|
+
dir;
|
|
39
|
+
pages;
|
|
40
|
+
server;
|
|
41
|
+
importMap;
|
|
42
|
+
rejected;
|
|
43
|
+
setAside = new Set();
|
|
44
|
+
#table;
|
|
45
|
+
constructor(app, template, buildId, manifest,
|
|
46
|
+
/** The checked copy in the cache. */
|
|
47
|
+
dir,
|
|
48
|
+
/** Accepted pages → their URLs. */
|
|
49
|
+
pages,
|
|
50
|
+
/** Accepted pages → their server modules (empty without server rendering). */
|
|
51
|
+
server, importMap,
|
|
52
|
+
/** Pages the app's check refused. */
|
|
53
|
+
rejected) {
|
|
54
|
+
this.app = app;
|
|
55
|
+
this.template = template;
|
|
56
|
+
this.buildId = buildId;
|
|
57
|
+
this.manifest = manifest;
|
|
58
|
+
this.dir = dir;
|
|
59
|
+
this.pages = pages;
|
|
60
|
+
this.server = server;
|
|
61
|
+
this.importMap = importMap;
|
|
62
|
+
this.rejected = rejected;
|
|
63
|
+
}
|
|
64
|
+
/** The page table of the first HTML (JSON, without the pages set aside). */
|
|
65
|
+
table() {
|
|
66
|
+
if (this.#table !== undefined)
|
|
67
|
+
return this.#table;
|
|
68
|
+
const pages = {};
|
|
69
|
+
for (const [page, urls] of this.pages)
|
|
70
|
+
if (!this.setAside.has(page))
|
|
71
|
+
pages[page] = { js: urls.js, css: urls.css };
|
|
72
|
+
this.#table = JSON.stringify({
|
|
73
|
+
template: this.template,
|
|
74
|
+
name: this.manifest.name,
|
|
75
|
+
version: this.manifest.version,
|
|
76
|
+
buildId: this.buildId,
|
|
77
|
+
pages,
|
|
78
|
+
});
|
|
79
|
+
return this.#table;
|
|
80
|
+
}
|
|
81
|
+
/** Leaves `page` to the app's own page for the rest of this generation. */
|
|
82
|
+
putAside(page) {
|
|
83
|
+
this.setAside.add(page);
|
|
84
|
+
this.#table = undefined;
|
|
85
|
+
}
|
|
86
|
+
/** The server module of `page`, unless it is set aside. */
|
|
87
|
+
serverPage(page) {
|
|
88
|
+
return this.setAside.has(page) ? undefined : this.server.get(page);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const ESCAPE = {
|
|
92
|
+
'&': '&',
|
|
93
|
+
'<': '<',
|
|
94
|
+
'>': '>',
|
|
95
|
+
'"': '"',
|
|
96
|
+
"'": ''',
|
|
97
|
+
};
|
|
98
|
+
const escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => ESCAPE[char]);
|
|
99
|
+
/** JSON inside a <script>: no `</script>`, no line separators. */
|
|
100
|
+
const scriptJson = (value) => value
|
|
101
|
+
.replace(/</g, '\\u003c')
|
|
102
|
+
.replace(/\u2028/g, '\\u2028')
|
|
103
|
+
.replace(/\u2029/g, '\\u2029');
|
|
104
|
+
const CONTENT_TYPES = {
|
|
105
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
106
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
107
|
+
'.css': 'text/css; charset=utf-8',
|
|
108
|
+
'.json': 'application/json; charset=utf-8',
|
|
109
|
+
'.svg': 'image/svg+xml',
|
|
110
|
+
'.png': 'image/png',
|
|
111
|
+
'.jpg': 'image/jpeg',
|
|
112
|
+
'.jpeg': 'image/jpeg',
|
|
113
|
+
'.gif': 'image/gif',
|
|
114
|
+
'.webp': 'image/webp',
|
|
115
|
+
'.avif': 'image/avif',
|
|
116
|
+
'.ico': 'image/x-icon',
|
|
117
|
+
'.woff': 'font/woff',
|
|
118
|
+
'.woff2': 'font/woff2',
|
|
119
|
+
'.ttf': 'font/ttf',
|
|
120
|
+
'.otf': 'font/otf',
|
|
121
|
+
'.wasm': 'application/wasm',
|
|
122
|
+
};
|
|
123
|
+
/** module → file URL, per cache folder of an app (the resolve hook's table). */
|
|
124
|
+
const serverShared = new Map();
|
|
125
|
+
let hookRegistered = false;
|
|
126
|
+
function registerSharedHook(logger) {
|
|
127
|
+
if (hookRegistered)
|
|
128
|
+
return;
|
|
129
|
+
hookRegistered = true;
|
|
130
|
+
registerHooks({
|
|
131
|
+
resolve(specifier, context, next) {
|
|
132
|
+
const parent = context.parentURL;
|
|
133
|
+
if (parent !== undefined)
|
|
134
|
+
for (const [prefix, table] of serverShared)
|
|
135
|
+
if (parent.startsWith(prefix)) {
|
|
136
|
+
const url = table[specifier];
|
|
137
|
+
if (url !== undefined)
|
|
138
|
+
return { url, shortCircuit: true };
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
return next(specifier, context);
|
|
142
|
+
},
|
|
143
|
+
});
|
|
144
|
+
logger.log('debug', 'Template bundle server imports resolve to the app build', {
|
|
145
|
+
code: 'INERTIA_TEMPLATE_RESOLVE_HOOK',
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
/** The nearest `.vite/dokebi-shared.json` at or above `dir` (at most 4 levels). */
|
|
149
|
+
function sharedFileFrom(dir) {
|
|
150
|
+
let current = resolve(dir);
|
|
151
|
+
for (let level = 0; level < 5; level++) {
|
|
152
|
+
const file = join(current, SHARED_FILE);
|
|
153
|
+
if (existsSync(file))
|
|
154
|
+
return file;
|
|
155
|
+
const up = dirname(current);
|
|
156
|
+
if (up === current)
|
|
157
|
+
return undefined;
|
|
158
|
+
current = up;
|
|
159
|
+
}
|
|
160
|
+
return undefined;
|
|
161
|
+
}
|
|
162
|
+
async function readShared(file) {
|
|
163
|
+
const parsed = JSON.parse(await readFile(file, 'utf8'));
|
|
164
|
+
if (parsed?.format !== 1 || parsed.modules === null || typeof parsed.modules !== 'object')
|
|
165
|
+
throw new Error(`${file} is not a dokebi-shared.json of format 1`);
|
|
166
|
+
return parsed;
|
|
167
|
+
}
|
|
168
|
+
/** Thrown inside a load: the reason the generation is not used. */
|
|
169
|
+
class Refused extends Error {
|
|
170
|
+
code;
|
|
171
|
+
data;
|
|
172
|
+
constructor(code, message, data = {}) {
|
|
173
|
+
super(message);
|
|
174
|
+
this.code = code;
|
|
175
|
+
this.data = data;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/** Every app's template bundles. */
|
|
179
|
+
export class TemplateBundles {
|
|
180
|
+
#logger;
|
|
181
|
+
#verify;
|
|
182
|
+
#repeat;
|
|
183
|
+
#production;
|
|
184
|
+
#words;
|
|
185
|
+
#settings;
|
|
186
|
+
#apps = new Map();
|
|
187
|
+
#slots = new Map();
|
|
188
|
+
#store = new AsyncLocalStorage();
|
|
189
|
+
#timer;
|
|
190
|
+
#closed = false;
|
|
191
|
+
#cacheRoot;
|
|
192
|
+
constructor(options) {
|
|
193
|
+
this.#logger = options.logger;
|
|
194
|
+
this.#settings = options.settings;
|
|
195
|
+
this.#verify = options.verify;
|
|
196
|
+
this.#repeat = options.repeat;
|
|
197
|
+
this.#production = options.production ?? process.env.NODE_ENV === 'production';
|
|
198
|
+
this.#words = options.words;
|
|
199
|
+
this.#cacheRoot = resolve(options.settings.cacheDir);
|
|
200
|
+
const store = this.#store;
|
|
201
|
+
globalThis[TEMPLATE_REGISTRY] = Object.freeze({
|
|
202
|
+
/** The bundle of the render under way: its template, pages and layout. */
|
|
203
|
+
current() {
|
|
204
|
+
const active = store.getStore();
|
|
205
|
+
if (!active)
|
|
206
|
+
return undefined;
|
|
207
|
+
return {
|
|
208
|
+
template: active.generation.template,
|
|
209
|
+
page(key) {
|
|
210
|
+
const module = active.generation.serverPage(key);
|
|
211
|
+
if (module !== undefined)
|
|
212
|
+
active.used.add(key);
|
|
213
|
+
return module;
|
|
214
|
+
},
|
|
215
|
+
};
|
|
216
|
+
},
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
/** The configured template names of an app. */
|
|
220
|
+
templatesOf(app) {
|
|
221
|
+
return Object.keys(this.#settings.templates[app] ?? {});
|
|
222
|
+
}
|
|
223
|
+
/** An app's build, from its Inertia scope (the first scope of an app wins). */
|
|
224
|
+
registerApp(app, build) {
|
|
225
|
+
if (this.#apps.has(app))
|
|
226
|
+
return;
|
|
227
|
+
this.#apps.set(app, build);
|
|
228
|
+
}
|
|
229
|
+
/** The apps of `templates` that are not apps (`names`, undefined: no app routing). */
|
|
230
|
+
static unknownApps(settings, names) {
|
|
231
|
+
return Object.keys(settings.templates).filter((app) => !names?.includes(app));
|
|
232
|
+
}
|
|
233
|
+
/** At start: every configured bundle, and the timer. Never throws. */
|
|
234
|
+
async start() {
|
|
235
|
+
await this.#reconcile();
|
|
236
|
+
this.#schedule();
|
|
237
|
+
}
|
|
238
|
+
/** A reload: the new settings for the next look; the bundles are compared now. */
|
|
239
|
+
update(settings) {
|
|
240
|
+
this.#settings = settings;
|
|
241
|
+
this.#schedule();
|
|
242
|
+
void this.#reconcile();
|
|
243
|
+
}
|
|
244
|
+
stop() {
|
|
245
|
+
this.#closed = true;
|
|
246
|
+
if (this.#timer)
|
|
247
|
+
clearInterval(this.#timer);
|
|
248
|
+
this.#timer = undefined;
|
|
249
|
+
}
|
|
250
|
+
#schedule() {
|
|
251
|
+
if (this.#timer)
|
|
252
|
+
clearInterval(this.#timer);
|
|
253
|
+
this.#timer = undefined;
|
|
254
|
+
if (this.#closed || this.#settings.checkMs === 0)
|
|
255
|
+
return;
|
|
256
|
+
this.#timer = setInterval(() => void this.#reconcile(), this.#settings.checkMs);
|
|
257
|
+
this.#timer.unref();
|
|
258
|
+
}
|
|
259
|
+
/** Brings every slot in line with the settings and its mount. */
|
|
260
|
+
async #reconcile() {
|
|
261
|
+
const wanted = new Set();
|
|
262
|
+
const work = [];
|
|
263
|
+
for (const [app, templates] of Object.entries(this.#settings.templates))
|
|
264
|
+
for (const [template, source] of Object.entries(templates)) {
|
|
265
|
+
const key = `${app}/${template}`;
|
|
266
|
+
wanted.add(key);
|
|
267
|
+
let slot = this.#slots.get(key);
|
|
268
|
+
if (!slot) {
|
|
269
|
+
slot = {
|
|
270
|
+
app,
|
|
271
|
+
template,
|
|
272
|
+
path: source.path,
|
|
273
|
+
current: undefined,
|
|
274
|
+
kept: [],
|
|
275
|
+
seen: undefined,
|
|
276
|
+
loading: undefined,
|
|
277
|
+
words: false,
|
|
278
|
+
};
|
|
279
|
+
this.#slots.set(key, slot);
|
|
280
|
+
}
|
|
281
|
+
else if (slot.path !== source.path) {
|
|
282
|
+
slot.path = source.path;
|
|
283
|
+
slot.seen = undefined;
|
|
284
|
+
}
|
|
285
|
+
work.push(this.#look(slot));
|
|
286
|
+
}
|
|
287
|
+
for (const [key, slot] of this.#slots)
|
|
288
|
+
if (!wanted.has(key)) {
|
|
289
|
+
this.#slots.delete(key);
|
|
290
|
+
if (slot.words)
|
|
291
|
+
work.push(this.#setWords(slot, undefined, undefined));
|
|
292
|
+
this.#logger.log('info', 'Template bundle no longer configured; the app pages answer', {
|
|
293
|
+
code: 'INERTIA_TEMPLATE_REMOVED',
|
|
294
|
+
app: slot.app,
|
|
295
|
+
template: slot.template,
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
await Promise.all(work);
|
|
299
|
+
}
|
|
300
|
+
/** Loads the slot's mount when its manifest changed since the last look. */
|
|
301
|
+
async #look(slot) {
|
|
302
|
+
if (slot.loading)
|
|
303
|
+
return slot.loading;
|
|
304
|
+
const manifest = join(resolve(slot.path), TEMPLATE_MANIFEST);
|
|
305
|
+
let mark;
|
|
306
|
+
try {
|
|
307
|
+
const info = await stat(manifest);
|
|
308
|
+
mark = `${info.ino}:${info.size}:${info.mtimeMs}`;
|
|
309
|
+
}
|
|
310
|
+
catch (error) {
|
|
311
|
+
mark = `missing:${error.code ?? 'error'}`;
|
|
312
|
+
}
|
|
313
|
+
if (mark === slot.seen)
|
|
314
|
+
return;
|
|
315
|
+
slot.seen = mark;
|
|
316
|
+
slot.loading = this.#load(slot).finally(() => {
|
|
317
|
+
slot.loading = undefined;
|
|
318
|
+
});
|
|
319
|
+
return slot.loading;
|
|
320
|
+
}
|
|
321
|
+
#fail(slot, failure) {
|
|
322
|
+
const code = failure instanceof Refused ? failure.code : 'INERTIA_TEMPLATE_UNAVAILABLE';
|
|
323
|
+
const repeated = this.#repeat(`${code} ${slot.app} ${slot.template} ${failure.message}`);
|
|
324
|
+
if (repeated === undefined)
|
|
325
|
+
return;
|
|
326
|
+
this.#logger.log('error', 'Template bundle not used; the app pages answer for this template', {
|
|
327
|
+
code,
|
|
328
|
+
app: slot.app,
|
|
329
|
+
template: slot.template,
|
|
330
|
+
path: slot.path,
|
|
331
|
+
reason: failure.message,
|
|
332
|
+
...(failure instanceof Refused ? failure.data : { error: describeError(failure) }),
|
|
333
|
+
kept: slot.current?.buildId ?? null,
|
|
334
|
+
...(repeated ? { repeated } : {}),
|
|
335
|
+
fix: code === 'INERTIA_TEMPLATE_UNVERIFIED'
|
|
336
|
+
? 'Export verifyTemplate from src/infra/inertia/shared.ts (it judges the signature and the page contracts); in production a bundle is not used without it.'
|
|
337
|
+
: 'Mount a bundle that npx dokebi template check accepts, built against this app build (npx dokebi template check <dir> --against dist/.vite/dokebi-shared.json).',
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
async #provided(app, build) {
|
|
341
|
+
const browserFile = join(dirname(resolve(build.manifest)), 'dokebi-shared.json');
|
|
342
|
+
let browser;
|
|
343
|
+
try {
|
|
344
|
+
browser = await readShared(browserFile);
|
|
345
|
+
}
|
|
346
|
+
catch (error) {
|
|
347
|
+
throw new Refused('INERTIA_TEMPLATE_REJECTED', `the app build provides no shared modules (${browserFile}): build the app with dokebiInertia({ templates })`, { error: describeError(error) });
|
|
348
|
+
}
|
|
349
|
+
const base = build.base.endsWith('/') ? build.base : `${build.base}/`;
|
|
350
|
+
const versions = {};
|
|
351
|
+
const browserUrls = {};
|
|
352
|
+
for (const [module, entry] of Object.entries(browser.modules)) {
|
|
353
|
+
browserUrls[module] = `${base}${entry.file}`;
|
|
354
|
+
versions[module] = entry;
|
|
355
|
+
}
|
|
356
|
+
let server;
|
|
357
|
+
if (build.ssrBundle !== undefined) {
|
|
358
|
+
const file = sharedFileFrom(dirname(resolve(build.ssrBundle)));
|
|
359
|
+
if (!file)
|
|
360
|
+
throw new Refused('INERTIA_TEMPLATE_REJECTED', `the app's server build provides no shared modules (no ${SHARED_FILE} above ${build.ssrBundle}): add dokebiInertia({ templates }) to vite.ssr.config.ts too`);
|
|
361
|
+
const parsed = await readShared(file);
|
|
362
|
+
const outDir = dirname(dirname(file));
|
|
363
|
+
server = {};
|
|
364
|
+
for (const [module, entry] of Object.entries(parsed.modules)) {
|
|
365
|
+
server[module] = pathToFileURL(join(outDir, entry.file)).href;
|
|
366
|
+
versions[module] ??= entry;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
if (this.#logger.isEnabled('debug'))
|
|
370
|
+
this.#logger.log('debug', 'Template bundle: the app build provides shared modules', {
|
|
371
|
+
app,
|
|
372
|
+
browser: Object.keys(browserUrls),
|
|
373
|
+
server: server ? Object.keys(server) : false,
|
|
374
|
+
});
|
|
375
|
+
return { browser: browserUrls, server, versions };
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Copies the mount into a fresh cache folder, hashing every file on the way, and checks the
|
|
379
|
+
* copy. Returns the folder (reused when an earlier process made the same generation).
|
|
380
|
+
*/
|
|
381
|
+
async #copy(slot) {
|
|
382
|
+
const source = resolve(slot.path);
|
|
383
|
+
let text;
|
|
384
|
+
try {
|
|
385
|
+
const info = await lstat(join(source, TEMPLATE_MANIFEST));
|
|
386
|
+
if (!info.isFile())
|
|
387
|
+
throw new Error(`${TEMPLATE_MANIFEST} is not a plain file`);
|
|
388
|
+
if (info.size > 4 * 1024 * 1024)
|
|
389
|
+
throw new Error(`${TEMPLATE_MANIFEST} is larger than 4 MiB`);
|
|
390
|
+
text = await readFile(join(source, TEMPLATE_MANIFEST));
|
|
391
|
+
}
|
|
392
|
+
catch (error) {
|
|
393
|
+
throw new Refused('INERTIA_TEMPLATE_UNAVAILABLE', `${join(slot.path, TEMPLATE_MANIFEST)} could not be read: ${error.message}`);
|
|
394
|
+
}
|
|
395
|
+
let parsed;
|
|
396
|
+
try {
|
|
397
|
+
parsed = JSON.parse(text.toString('utf8'));
|
|
398
|
+
}
|
|
399
|
+
catch (error) {
|
|
400
|
+
throw new Refused('INERTIA_TEMPLATE_REJECTED', `the manifest is not JSON: ${error.message}`);
|
|
401
|
+
}
|
|
402
|
+
const shape = manifestProblem(parsed);
|
|
403
|
+
if (shape !== undefined)
|
|
404
|
+
throw new Refused('INERTIA_TEMPLATE_REJECTED', `the manifest: ${shape}`);
|
|
405
|
+
const manifest = parsed;
|
|
406
|
+
const buildId = sha256(text).slice(0, 12);
|
|
407
|
+
const total = Object.values(manifest.files).reduce((sum, file) => sum + file.bytes, 0);
|
|
408
|
+
if (total > this.#settings.maxBytes)
|
|
409
|
+
throw new Refused('INERTIA_TEMPLATE_REJECTED', `the bundle takes ${total} bytes, more than templateMaxBytes ${this.#settings.maxBytes}`);
|
|
410
|
+
let signature;
|
|
411
|
+
try {
|
|
412
|
+
signature = await readFile(join(source, TEMPLATE_SIGNATURE));
|
|
413
|
+
}
|
|
414
|
+
catch (error) {
|
|
415
|
+
if (error.code !== 'ENOENT')
|
|
416
|
+
throw new Refused('INERTIA_TEMPLATE_UNAVAILABLE', `${TEMPLATE_SIGNATURE} could not be read: ${error.message}`);
|
|
417
|
+
}
|
|
418
|
+
const final = join(this.#cacheRoot, slot.app, slot.template, buildId);
|
|
419
|
+
if (existsSync(final)) {
|
|
420
|
+
const check = await checkTemplateBundle(final, { maxBytes: this.#settings.maxBytes });
|
|
421
|
+
if (check.problems.length === 0 && check.buildId === buildId)
|
|
422
|
+
return { dir: final, manifest, buildId, signature };
|
|
423
|
+
await rm(final, { recursive: true, force: true });
|
|
424
|
+
}
|
|
425
|
+
const temporary = `${final}.tmp-${randomBytes(6).toString('hex')}`;
|
|
426
|
+
try {
|
|
427
|
+
for (const [file, entry] of Object.entries(manifest.files)) {
|
|
428
|
+
const from = join(source, ...file.split('/'));
|
|
429
|
+
const info = await lstat(from).catch((error) => {
|
|
430
|
+
throw new Refused('INERTIA_TEMPLATE_REJECTED', `${file} is missing: ${error.message}`);
|
|
431
|
+
});
|
|
432
|
+
if (!info.isFile())
|
|
433
|
+
throw new Refused('INERTIA_TEMPLATE_REJECTED', `${file} is a link or not a plain file`);
|
|
434
|
+
const content = await readFile(from);
|
|
435
|
+
if (content.length !== entry.bytes || sha256(content) !== entry.sha256)
|
|
436
|
+
throw new Refused('INERTIA_TEMPLATE_REJECTED', `${file} is not the file the manifest names (size or sha256 differs)`);
|
|
437
|
+
const to = join(temporary, ...file.split('/'));
|
|
438
|
+
await mkdir(dirname(to), { recursive: true });
|
|
439
|
+
await writeFile(to, content);
|
|
440
|
+
}
|
|
441
|
+
await writeFile(join(temporary, TEMPLATE_MANIFEST), text);
|
|
442
|
+
if (signature)
|
|
443
|
+
await writeFile(join(temporary, TEMPLATE_SIGNATURE), signature);
|
|
444
|
+
const check = await checkTemplateBundle(temporary, { maxBytes: this.#settings.maxBytes });
|
|
445
|
+
if (check.problems.length)
|
|
446
|
+
throw new Refused('INERTIA_TEMPLATE_REJECTED', check.problems.map((problem) => problem.message).join('; '));
|
|
447
|
+
await mkdir(dirname(final), { recursive: true });
|
|
448
|
+
try {
|
|
449
|
+
await rename(temporary, final);
|
|
450
|
+
}
|
|
451
|
+
catch (error) {
|
|
452
|
+
// Another worker made the same generation first: its copy is the same bundle.
|
|
453
|
+
if (!existsSync(final))
|
|
454
|
+
throw error;
|
|
455
|
+
await rm(temporary, { recursive: true, force: true });
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
catch (error) {
|
|
459
|
+
await rm(temporary, { recursive: true, force: true });
|
|
460
|
+
throw error;
|
|
461
|
+
}
|
|
462
|
+
return { dir: final, manifest, buildId, signature };
|
|
463
|
+
}
|
|
464
|
+
async #load(slot) {
|
|
465
|
+
const begin = performance.now();
|
|
466
|
+
const build = this.#apps.get(slot.app);
|
|
467
|
+
try {
|
|
468
|
+
if (!build)
|
|
469
|
+
throw new Refused('INERTIA_TEMPLATE_REJECTED', `app ${slot.app} has no Inertia pages built with Vite (its inertia.vite) in this process`);
|
|
470
|
+
const { dir, manifest, buildId, signature } = await this.#copy(slot);
|
|
471
|
+
if (slot.current?.buildId === buildId)
|
|
472
|
+
return;
|
|
473
|
+
const provided = await this.#provided(slot.app, build);
|
|
474
|
+
const needed = Object.fromEntries(Object.entries(manifest.shared).filter(([module]) => provided.server !== undefined || !SERVER_ONLY_SHARED.includes(module)));
|
|
475
|
+
const problems = sharedProblems(needed, provided.versions);
|
|
476
|
+
if (problems.length)
|
|
477
|
+
throw new Refused('INERTIA_TEMPLATE_REJECTED', problems.map((problem) => problem.message).join('; '), { shared: needed });
|
|
478
|
+
// The app's own judgement: signature and page contracts.
|
|
479
|
+
let rejectPages = [];
|
|
480
|
+
if (this.#verify) {
|
|
481
|
+
const verify = this.#verify;
|
|
482
|
+
let timer;
|
|
483
|
+
const input = Object.freeze({
|
|
484
|
+
app: slot.app,
|
|
485
|
+
template: slot.template,
|
|
486
|
+
path: slot.path,
|
|
487
|
+
buildId,
|
|
488
|
+
manifest,
|
|
489
|
+
signature,
|
|
490
|
+
read: async (file) => {
|
|
491
|
+
if (typeof file !== 'string' ||
|
|
492
|
+
(file !== TEMPLATE_MANIFEST && !Object.hasOwn(manifest.files, file)))
|
|
493
|
+
throw new Error(`${String(file)} is not a file of the bundle`);
|
|
494
|
+
return readFile(join(dir, ...file.split('/')));
|
|
495
|
+
},
|
|
496
|
+
});
|
|
497
|
+
let answer;
|
|
498
|
+
try {
|
|
499
|
+
answer = await Promise.race([
|
|
500
|
+
Promise.resolve().then(() => verify(input)),
|
|
501
|
+
new Promise((_, reject) => {
|
|
502
|
+
timer = setTimeout(() => reject(new Error(`verifyTemplate took longer than ${this.#settings.verifyTimeoutMs} ms`)), this.#settings.verifyTimeoutMs);
|
|
503
|
+
}),
|
|
504
|
+
]);
|
|
505
|
+
}
|
|
506
|
+
catch (error) {
|
|
507
|
+
throw new Refused('INERTIA_TEMPLATE_REJECTED', `verifyTemplate failed: ${error.message}`, {
|
|
508
|
+
error: describeError(error),
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
finally {
|
|
512
|
+
clearTimeout(timer);
|
|
513
|
+
}
|
|
514
|
+
if (answer === null || typeof answer !== 'object' || typeof answer.accept !== 'boolean')
|
|
515
|
+
throw new Refused('INERTIA_TEMPLATE_REJECTED', 'verifyTemplate must answer { accept: true, rejectPages? } or { accept: false, reason }');
|
|
516
|
+
if (!answer.accept)
|
|
517
|
+
throw new Refused('INERTIA_TEMPLATE_REJECTED', `verifyTemplate refused it: ${String(answer.reason)}`);
|
|
518
|
+
rejectPages = answer.rejectPages ?? [];
|
|
519
|
+
}
|
|
520
|
+
else if (this.#production)
|
|
521
|
+
throw new Refused('INERTIA_TEMPLATE_UNVERIFIED', 'no verifyTemplate: in production a bundle runs only after the app judged it');
|
|
522
|
+
else {
|
|
523
|
+
const repeated = this.#repeat(`unverified ${slot.app} ${slot.template}`);
|
|
524
|
+
if (repeated !== undefined)
|
|
525
|
+
this.#logger.log('warn', 'Template bundle used without verifyTemplate (development)', {
|
|
526
|
+
code: 'INERTIA_TEMPLATE_UNVERIFIED',
|
|
527
|
+
app: slot.app,
|
|
528
|
+
template: slot.template,
|
|
529
|
+
fix: 'Export verifyTemplate from src/infra/inertia/shared.ts before production: there a bundle is not used without it.',
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
const refused = new Set();
|
|
533
|
+
for (const item of rejectPages) {
|
|
534
|
+
if (typeof item?.page !== 'string' || !Object.hasOwn(manifest.pages, item.page))
|
|
535
|
+
continue;
|
|
536
|
+
refused.add(item.page);
|
|
537
|
+
this.#logger.log('warn', 'Template bundle page refused; the app page answers for it', {
|
|
538
|
+
code: 'INERTIA_TEMPLATE_PAGE_REJECTED',
|
|
539
|
+
app: slot.app,
|
|
540
|
+
template: slot.template,
|
|
541
|
+
buildId,
|
|
542
|
+
page: item.page,
|
|
543
|
+
reason: String(item.reason ?? ''),
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
const prefix = `${TEMPLATE_FILES_PREFIX}${slot.app}/${slot.template}/${buildId}/`;
|
|
547
|
+
const url = (file) => `${prefix}${file}`;
|
|
548
|
+
const pages = new Map();
|
|
549
|
+
const server = new Map();
|
|
550
|
+
if (provided.server) {
|
|
551
|
+
registerSharedHook(this.#logger);
|
|
552
|
+
serverShared.set(pathToFileURL(join(this.#cacheRoot, slot.app) + sep).href, provided.server);
|
|
553
|
+
await this.#ensureModuleScope();
|
|
554
|
+
}
|
|
555
|
+
for (const [page, entry] of Object.entries(manifest.pages)) {
|
|
556
|
+
if (refused.has(page))
|
|
557
|
+
continue;
|
|
558
|
+
if (provided.server) {
|
|
559
|
+
try {
|
|
560
|
+
server.set(page, (await import(pathToFileURL(join(dir, ...entry.ssr.split('/'))).href)));
|
|
561
|
+
}
|
|
562
|
+
catch (error) {
|
|
563
|
+
throw new Refused('INERTIA_TEMPLATE_REJECTED', `the server module of ${page} could not be imported: ${error.message}`, { page, error: describeError(error) });
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
pages.set(page, {
|
|
567
|
+
js: url(entry.browser),
|
|
568
|
+
css: entry.css.map(url),
|
|
569
|
+
preload: entry.preload.map(url),
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
const importMap = {};
|
|
573
|
+
for (const module of Object.keys(manifest.shared)) {
|
|
574
|
+
const target = provided.browser[module];
|
|
575
|
+
if (target !== undefined)
|
|
576
|
+
importMap[module] = target;
|
|
577
|
+
}
|
|
578
|
+
// D-0291 stage 3b: the bundle's screen words, just before it serves (a refused set leaves the
|
|
579
|
+
// bundle in use with the words of before; a bundle without words takes them out).
|
|
580
|
+
const hasWords = Object.keys(manifest.files).some((file) => file.startsWith('locales/'));
|
|
581
|
+
if (hasWords || slot.words)
|
|
582
|
+
await this.#setWords(slot, hasWords ? join(dir, 'locales') : undefined, buildId);
|
|
583
|
+
const generation = new TemplateGeneration(slot.app, slot.template, buildId, manifest, dir, pages, server, importMap, [...refused]);
|
|
584
|
+
const previous = slot.current;
|
|
585
|
+
slot.current = generation;
|
|
586
|
+
slot.kept.unshift(generation);
|
|
587
|
+
const dropped = slot.kept.splice(Math.max(1, this.#settings.keep));
|
|
588
|
+
this.#logger.log('info', 'Template bundle loaded; the next pages of its template use it', {
|
|
589
|
+
code: 'INERTIA_TEMPLATE_LOADED',
|
|
590
|
+
app: slot.app,
|
|
591
|
+
template: slot.template,
|
|
592
|
+
name: manifest.name,
|
|
593
|
+
version: manifest.version,
|
|
594
|
+
buildId,
|
|
595
|
+
previous: previous?.buildId ?? null,
|
|
596
|
+
pages: pages.size,
|
|
597
|
+
rejectedPages: [...refused],
|
|
598
|
+
serverRendering: provided.server !== undefined,
|
|
599
|
+
kept: slot.kept.map((kept) => kept.buildId),
|
|
600
|
+
ms: Math.round(performance.now() - begin),
|
|
601
|
+
});
|
|
602
|
+
for (const old of dropped)
|
|
603
|
+
await this.#prune(old);
|
|
604
|
+
}
|
|
605
|
+
catch (error) {
|
|
606
|
+
this.#fail(slot, error);
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
/** D-0291 stage 3b: hands a generation's words (or none) to @dokebi/i18n. Never throws. */
|
|
610
|
+
async #setWords(slot, directory, buildId) {
|
|
611
|
+
const words = this.#words;
|
|
612
|
+
if (!words) {
|
|
613
|
+
if (directory !== undefined) {
|
|
614
|
+
const repeated = this.#repeat(`words unused ${slot.app} ${slot.template}`);
|
|
615
|
+
if (repeated !== undefined)
|
|
616
|
+
this.#logger.log('info', 'Template bundle words are not used: @dokebi/i18n is not registered', {
|
|
617
|
+
code: 'INERTIA_TEMPLATE_LOCALES_UNUSED',
|
|
618
|
+
app: slot.app,
|
|
619
|
+
template: slot.template,
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
let answer;
|
|
625
|
+
try {
|
|
626
|
+
answer = await words(slot.app, slot.template, directory);
|
|
627
|
+
}
|
|
628
|
+
catch (error) {
|
|
629
|
+
answer = { ok: false, reason: error.message };
|
|
630
|
+
}
|
|
631
|
+
if (answer.ok) {
|
|
632
|
+
slot.words = directory !== undefined;
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
const repeated = this.#repeat(`words ${slot.app} ${slot.template} ${answer.reason}`);
|
|
636
|
+
if (repeated !== undefined)
|
|
637
|
+
this.#logger.log('warn', 'Template bundle words refused; its pages keep the words of before', {
|
|
638
|
+
code: 'INERTIA_TEMPLATE_LOCALES_REJECTED',
|
|
639
|
+
app: slot.app,
|
|
640
|
+
template: slot.template,
|
|
641
|
+
buildId: buildId ?? null,
|
|
642
|
+
reason: answer.reason,
|
|
643
|
+
...(repeated ? { repeated } : {}),
|
|
644
|
+
fix: 'Replace only keys the app’s catalogs have, with the same placeholders and in the app’s locales (D-0282 rules), then build the bundle again.',
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
/** A package.json at the cache root: the bundle's .js modules are ES modules. */
|
|
648
|
+
async #ensureModuleScope() {
|
|
649
|
+
const file = join(this.#cacheRoot, 'package.json');
|
|
650
|
+
if (existsSync(file))
|
|
651
|
+
return;
|
|
652
|
+
await mkdir(this.#cacheRoot, { recursive: true });
|
|
653
|
+
await writeFile(file, '{"type":"module","private":true}\n');
|
|
654
|
+
}
|
|
655
|
+
async #prune(generation) {
|
|
656
|
+
try {
|
|
657
|
+
await rm(generation.dir, { recursive: true, force: true });
|
|
658
|
+
this.#logger.log('debug', 'Template bundle generation removed from the cache', {
|
|
659
|
+
app: generation.app,
|
|
660
|
+
template: generation.template,
|
|
661
|
+
buildId: generation.buildId,
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
catch (error) {
|
|
665
|
+
this.#logger.log('error', 'Template bundle generation could not be removed from the cache', {
|
|
666
|
+
code: 'INERTIA_TEMPLATE_PRUNE_FAILED',
|
|
667
|
+
dir: generation.dir,
|
|
668
|
+
error: describeError(error),
|
|
669
|
+
});
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
/** The current generation of an app's template, or undefined. */
|
|
673
|
+
current(app, template) {
|
|
674
|
+
if (template === undefined)
|
|
675
|
+
return undefined;
|
|
676
|
+
return this.#slots.get(`${app}/${template}`)?.current;
|
|
677
|
+
}
|
|
678
|
+
/** The use of one request: undefined when its template has no bundle. */
|
|
679
|
+
use(app, template, baseVersion) {
|
|
680
|
+
const generation = this.current(app, template);
|
|
681
|
+
if (!generation)
|
|
682
|
+
return undefined;
|
|
683
|
+
const store = this.#store;
|
|
684
|
+
const logger = this.#logger;
|
|
685
|
+
const repeat = this.#repeat;
|
|
686
|
+
return {
|
|
687
|
+
version: `${baseVersion}+${generation.template}@${generation.buildId}`,
|
|
688
|
+
generation,
|
|
689
|
+
head(component, nonce) {
|
|
690
|
+
const attribute = nonce === '' ? '' : ` nonce="${escapeHtml(nonce)}"`;
|
|
691
|
+
const map = Object.keys(generation.importMap).length
|
|
692
|
+
? `<script type="importmap"${attribute}>${scriptJson(JSON.stringify({ imports: generation.importMap }))}</script>`
|
|
693
|
+
: '';
|
|
694
|
+
const table = `<script type="application/json" id="dokebi-template">${scriptJson(generation.table())}</script>`;
|
|
695
|
+
const first = ['Layout', `Pages/${component}`]
|
|
696
|
+
.filter((page) => !generation.setAside.has(page))
|
|
697
|
+
.map((page) => generation.pages.get(page))
|
|
698
|
+
.filter((urls) => urls !== undefined);
|
|
699
|
+
const css = [...new Set(first.flatMap((urls) => urls.css))]
|
|
700
|
+
.map((href) => `<link rel="stylesheet" href="${escapeHtml(href)}">`)
|
|
701
|
+
.join('');
|
|
702
|
+
const preload = [...new Set(first.flatMap((urls) => [urls.js, ...urls.preload]))]
|
|
703
|
+
.map((href) => `<link rel="modulepreload"${attribute} href="${escapeHtml(href)}">`)
|
|
704
|
+
.join('');
|
|
705
|
+
return `${map}${table}${css}${preload}`;
|
|
706
|
+
},
|
|
707
|
+
async render(run, component) {
|
|
708
|
+
// The page first: a failure that took the component's own bundle page sets that page
|
|
709
|
+
// aside and renders again; one that fails again (or took only other pages, the Layout)
|
|
710
|
+
// sets those aside too. At most two more renders.
|
|
711
|
+
const page = `Pages/${component}`;
|
|
712
|
+
let used = new Set();
|
|
713
|
+
for (let attempt = 0;; attempt++) {
|
|
714
|
+
try {
|
|
715
|
+
return await store.run({ generation, used }, run);
|
|
716
|
+
}
|
|
717
|
+
catch (error) {
|
|
718
|
+
const blame = used.has(page) && attempt === 0 ? [page] : [...used];
|
|
719
|
+
if (blame.length === 0 || attempt === 2)
|
|
720
|
+
throw error;
|
|
721
|
+
for (const key of blame)
|
|
722
|
+
generation.putAside(key);
|
|
723
|
+
const repeated = repeat(`page ${generation.app} ${generation.template} ${generation.buildId} ${blame.join(',')}`);
|
|
724
|
+
if (repeated !== undefined)
|
|
725
|
+
logger.log('error', 'Template bundle page failed to render; the app page answers for it', {
|
|
726
|
+
code: 'INERTIA_TEMPLATE_PAGE_FAILED',
|
|
727
|
+
app: generation.app,
|
|
728
|
+
template: generation.template,
|
|
729
|
+
buildId: generation.buildId,
|
|
730
|
+
component,
|
|
731
|
+
pages: blame,
|
|
732
|
+
error: describeError(error),
|
|
733
|
+
...(repeated ? { repeated } : {}),
|
|
734
|
+
});
|
|
735
|
+
used = new Set();
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
},
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
/** `GET /_dokebi/templates/<app>/<template>/<buildId>/browser/…` of a kept generation. */
|
|
742
|
+
async serve(path, reply) {
|
|
743
|
+
const parts = path.split('/');
|
|
744
|
+
const [app, template, buildId, ...rest] = parts;
|
|
745
|
+
const file = rest.join('/');
|
|
746
|
+
const slot = app && template ? this.#slots.get(`${app}/${template}`) : undefined;
|
|
747
|
+
const generation = slot?.kept.find((kept) => kept.buildId === buildId);
|
|
748
|
+
if (!generation ||
|
|
749
|
+
!file.startsWith('browser/') ||
|
|
750
|
+
!Object.hasOwn(generation.manifest.files, file))
|
|
751
|
+
return reply.code(404).send({ error: 'NOT_FOUND' });
|
|
752
|
+
const absolute = join(generation.dir, ...file.split('/'));
|
|
753
|
+
if (!absolute.startsWith(generation.dir + sep) || isAbsolute(file))
|
|
754
|
+
return reply.code(404).send({ error: 'NOT_FOUND' });
|
|
755
|
+
return reply
|
|
756
|
+
.type(CONTENT_TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream')
|
|
757
|
+
.header('cache-control', 'public, max-age=31536000, immutable')
|
|
758
|
+
.send(createReadStream(absolute));
|
|
759
|
+
}
|
|
760
|
+
/** For tests and describe: the loaded generations. */
|
|
761
|
+
generations() {
|
|
762
|
+
return [...this.#slots.values()]
|
|
763
|
+
.filter((slot) => slot.current)
|
|
764
|
+
.map((slot) => ({
|
|
765
|
+
app: slot.app,
|
|
766
|
+
template: slot.template,
|
|
767
|
+
buildId: slot.current.buildId,
|
|
768
|
+
kept: slot.kept.map((kept) => kept.buildId),
|
|
769
|
+
}));
|
|
770
|
+
}
|
|
771
|
+
}
|