@dokebi/template-inertia 0.4.25 → 0.4.27

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.
@@ -11,11 +11,15 @@ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'nod
11
11
  import { pathToFileURL } from 'node:url';
12
12
  import { ConsoleLogger } from '@dokebi/core';
13
13
  import { InertiaError, InertiaUsageError } from './errors.js';
14
- import { checkTemplateBundle, jsonValue, PAGE_META_MAX_BYTES, SHARED_DEFAULTS, SHARED_SPECIFIER, sha256, TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_MAX_BYTES, TEMPLATE_NAME, TEMPLATE_PAGE, TEMPLATE_VERSION, } from './template-bundle.js';
14
+ import { checkTemplateBundle, cspDeclarationProblem, jsonValue, PAGE_META_MAX_BYTES, SHARED_DEFAULTS, SHARED_SPECIFIER, sha256, TEMPLATE_FILE, TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_MAX_BYTES, TEMPLATE_NAME, TEMPLATE_PAGE, TEMPLATE_STYLES_MAX, TEMPLATE_VERSION, } from './template-bundle.js';
15
15
  import { packageVersion } from './template-shared.js';
16
16
  import { registerVueTypeScript } from './vue-typescript.js';
17
17
  /** The builder written into `builtWith` (scripts/testing/check-metadata.mjs keeps it the package version). */
18
- const BUILDER = { name: 'dokebi-template-inertia', version: '0.4.25' };
18
+ const BUILDER = { name: 'dokebi-template-inertia', version: '0.4.27' };
19
+ /** D-0296: carried files go under this folder of the bundle (served like the pages' files). */
20
+ export const TEMPLATE_CARRY_FOLDER = 'browser';
21
+ /** The folders Vite writes under browser/: a carried file never takes them (any case). */
22
+ const BUILT_FOLDERS = ['pages', 'chunks', 'assets'];
19
23
  function defaultLogger() {
20
24
  return new ConsoleLogger({ level: 'info' }, { plugin: 'dokebi-template-inertia', process: 'template-build' });
21
25
  }
@@ -97,6 +101,71 @@ async function listFiles(dir, root = dir, found = []) {
97
101
  }
98
102
  return found;
99
103
  }
104
+ /**
105
+ * D-0296: the carried files, checked before the build: bundle path → the file in the template
106
+ * folder. A path is relative to the folder, a plain file inside it (no link on the way), not one of
107
+ * Vite's folders, and a bundle file name.
108
+ */
109
+ export async function carriedFiles(folder, paths) {
110
+ const carried = new Map();
111
+ const real = realpathSync(folder);
112
+ for (const path of paths) {
113
+ if (typeof path !== 'string' || path === '' || isAbsolute(path))
114
+ throw usage(`--carry ${String(path)} must be a file path relative to the template folder`);
115
+ const parts = path.split(/[\\/]/);
116
+ const target = `${TEMPLATE_CARRY_FOLDER}/${parts.join('/')}`;
117
+ if (parts.some((part) => part === '' || part === '.' || part === '..') ||
118
+ !TEMPLATE_FILE.test(target))
119
+ throw usage(`--carry ${path} is not a plain path inside the template folder (letters, digits, _ . @ + -, no .., no hidden file)`);
120
+ if (BUILT_FOLDERS.includes(parts[0].toLowerCase()))
121
+ throw usage(`--carry ${path} would land in browser/${parts[0]}/, where the build writes its files: put it in another folder`);
122
+ const file = join(folder, ...parts);
123
+ const info = await lstat(file).catch((error) => {
124
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR')
125
+ return undefined;
126
+ throw error;
127
+ });
128
+ if (info === undefined)
129
+ throw usage(`--carry ${path} is not in ${folder}`);
130
+ if (!info.isFile() || !within(realpathSync(file), real))
131
+ throw usage(`--carry ${path} must be a plain file of the template folder, not a folder or a link`);
132
+ carried.set(target, file);
133
+ }
134
+ return carried;
135
+ }
136
+ /** D-0297: the file of a template folder that declares the sources of other origins it uses. */
137
+ export const TEMPLATE_CSP_FILE = 'csp.json';
138
+ /**
139
+ * D-0297: the template folder's `csp.json`, checked (INVALID_TEMPLATE_BUILD), each list sorted and
140
+ * without repeats, empty lists left out; undefined without the file or with nothing in it.
141
+ */
142
+ export async function templateCsp(folder) {
143
+ const file = join(folder, TEMPLATE_CSP_FILE);
144
+ let text;
145
+ try {
146
+ text = await readFile(file, 'utf8');
147
+ }
148
+ catch (error) {
149
+ if (error.code === 'ENOENT')
150
+ return undefined;
151
+ throw error;
152
+ }
153
+ let parsed;
154
+ try {
155
+ parsed = JSON.parse(text);
156
+ }
157
+ catch (cause) {
158
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `${TEMPLATE_CSP_FILE} is not JSON: ${cause.message}`, { cause });
159
+ }
160
+ const problem = cspDeclarationProblem(parsed);
161
+ if (problem)
162
+ throw usage(`${TEMPLATE_CSP_FILE}: ${problem}`);
163
+ const declared = {};
164
+ for (const [name, sources] of Object.entries(parsed).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
165
+ if (sources.length)
166
+ declared[name] = [...new Set(sources)].sort();
167
+ return Object.keys(declared).length ? declared : undefined;
168
+ }
100
169
  const outputs = (result) => (Array.isArray(result) ? result : [result]).flatMap((item) => item.output ?? []);
101
170
  /**
102
171
  * Builds the template folder `options.dir` of `options.root` into a bundle at `options.out`
@@ -139,6 +208,19 @@ export async function buildTemplateBundle(options) {
139
208
  if (typeof module !== 'string' || !SHARED_SPECIFIER.test(module))
140
209
  throw new InertiaUsageError('INVALID_TEMPLATE_SHARED', `--shared ${String(module)} is not a package name with an optional subpath`);
141
210
  const shared = [...new Set([...SHARED_DEFAULTS, ...own])];
211
+ // Before anything is emptied or built.
212
+ const carry = await carriedFiles(folder, options.carry ?? []);
213
+ // D-0298: the stylesheets are carried files too, in their order.
214
+ const styleFiles = await carriedFiles(folder, options.styles ?? []);
215
+ for (const [target, file] of styleFiles) {
216
+ if (!target.endsWith('.css'))
217
+ throw usage(`--style ${target.slice(TEMPLATE_CARRY_FOLDER.length + 1)} is not a .css file`);
218
+ carry.set(target, file);
219
+ }
220
+ const styles = [...styleFiles.keys()];
221
+ if (styles.length > TEMPLATE_STYLES_MAX)
222
+ throw usage(`--style names ${styles.length} stylesheets; at most ${TEMPLATE_STYLES_MAX}`);
223
+ const csp = await templateCsp(folder);
142
224
  const out = resolve(root, options.out ?? join('dist', 'template', name));
143
225
  if (!within(out, root) || within(root, out) || within(folder, out) || within(out, folder))
144
226
  throw usage(`--out ${relative(root, out) || '.'} must be a folder inside the project, apart from the template folder (the build imports the server pages from there)`);
@@ -152,170 +234,176 @@ export async function buildTemplateBundle(options) {
152
234
  await rm(out, { recursive: true, force: true });
153
235
  }
154
236
  const pages = await templatePages(folder);
155
- if (pages.size === 0)
156
- throw usage(`${options.dir} has no Layout.vue and no Pages/**/*.vue`);
157
- const input = Object.fromEntries(pages);
158
- const vite = await importPackage(root, 'vite', 'Install Vite in the template repository: npm install --save-dev vite');
159
- // The project's vite config (--config) may bring its own Vue plugin; otherwise one is added.
160
- const configFile = options.config ? resolve(root, options.config) : undefined;
161
- let ownVue = false;
162
- if (configFile) {
163
- const loaded = (await vite.loadConfigFromFile({ command: 'build', mode: 'production' }, configFile, root)) ?? {
164
- config: {},
165
- };
166
- const names = (loaded.config.plugins ?? [])
167
- .flat(Infinity)
168
- .map((plugin) => plugin?.name);
169
- ownVue = names.includes('vite:vue');
170
- }
171
- const vue = ownVue
172
- ? undefined
173
- : await importPackage(root, '@vitejs/plugin-vue', 'Install the Vue plugin in the template repository: npm install --save-dev @vitejs/plugin-vue');
174
- registerVueTypeScript(root, logger);
175
- const isShared = (id) => shared.includes(id);
176
- logger.log('info', 'Template bundle build started', {
177
- code: 'INERTIA_TEMPLATE_BUILD_STARTED',
178
- name,
179
- version,
180
- dir: relative(root, folder),
181
- out: relative(root, out),
182
- pages: pages.size,
183
- shared,
184
- });
185
- const common = {
186
- root,
187
- configFile: configFile ?? false,
188
- logLevel: 'warn',
189
- publicDir: false,
190
- // The compiler reads the props types a page imports from files (as the app's vite config does).
191
- plugins: vue ? [vue.default({ script: { fs: VUE_TYPE_FILES } })] : [],
192
- };
237
+ // D-0298: a template of styles alone (carried files, screen words) is a bundle too.
238
+ if (pages.size === 0 && carry.size === 0 && !existsSync(join(folder, 'locales')))
239
+ throw usage(`${options.dir} has no Layout.vue, no Pages/**/*.vue and nothing carried (--style, --carry) or locales/`);
193
240
  const imported = new Set();
194
- const collect = (items) => {
195
- for (const item of items)
196
- for (const id of [...(item.imports ?? []), ...(item.dynamicImports ?? [])])
197
- if (isShared(id))
198
- imported.add(id);
199
- };
200
- let browserItems;
201
- let serverItems;
202
- // `vite build` sets process.env.NODE_ENV to production: a caller in the same process (a
203
- // test, a script that builds and then serves) gets it back as it was.
204
- const environment = process.env.NODE_ENV;
205
- try {
206
- browserItems = outputs(await vite.build({
207
- ...common,
208
- base: './',
209
- build: {
210
- outDir: join(out, 'browser'),
211
- emptyOutDir: true,
212
- manifest: true,
213
- cssCodeSplit: true,
214
- modulePreload: false,
215
- copyPublicDir: false,
216
- rollupOptions: {
217
- input,
218
- external: isShared,
219
- preserveEntrySignatures: 'strict',
220
- output: {
221
- entryFileNames: 'pages/[name]-[hash].js',
222
- chunkFileNames: 'chunks/[name]-[hash].js',
223
- assetFileNames: 'assets/[name]-[hash][extname]',
241
+ const pageEntries = {};
242
+ // D-0298: a bundle without pages (styles and other carried files only) runs no Vite build.
243
+ if (pages.size > 0) {
244
+ const input = Object.fromEntries(pages);
245
+ const vite = await importPackage(root, 'vite', 'Install Vite in the template repository: npm install --save-dev vite');
246
+ // The project's vite config (--config) may bring its own Vue plugin; otherwise one is added.
247
+ const configFile = options.config ? resolve(root, options.config) : undefined;
248
+ let ownVue = false;
249
+ if (configFile) {
250
+ const loaded = (await vite.loadConfigFromFile({ command: 'build', mode: 'production' }, configFile, root)) ?? {
251
+ config: {},
252
+ };
253
+ const names = (loaded.config.plugins ?? [])
254
+ .flat(Infinity)
255
+ .map((plugin) => plugin?.name);
256
+ ownVue = names.includes('vite:vue');
257
+ }
258
+ const vue = ownVue
259
+ ? undefined
260
+ : await importPackage(root, '@vitejs/plugin-vue', 'Install the Vue plugin in the template repository: npm install --save-dev @vitejs/plugin-vue');
261
+ registerVueTypeScript(root, logger);
262
+ const isShared = (id) => shared.includes(id);
263
+ logger.log('info', 'Template bundle build started', {
264
+ code: 'INERTIA_TEMPLATE_BUILD_STARTED',
265
+ name,
266
+ version,
267
+ dir: relative(root, folder),
268
+ out: relative(root, out),
269
+ pages: pages.size,
270
+ shared,
271
+ });
272
+ const common = {
273
+ root,
274
+ configFile: configFile ?? false,
275
+ logLevel: 'warn',
276
+ publicDir: false,
277
+ // The compiler reads the props types a page imports from files (as the app's vite config does).
278
+ plugins: vue ? [vue.default({ script: { fs: VUE_TYPE_FILES } })] : [],
279
+ };
280
+ const collect = (items) => {
281
+ for (const item of items)
282
+ for (const id of [...(item.imports ?? []), ...(item.dynamicImports ?? [])])
283
+ if (isShared(id))
284
+ imported.add(id);
285
+ };
286
+ let browserItems;
287
+ let serverItems;
288
+ // `vite build` sets process.env.NODE_ENV to production: a caller in the same process (a
289
+ // test, a script that builds and then serves) gets it back as it was.
290
+ const environment = process.env.NODE_ENV;
291
+ try {
292
+ browserItems = outputs(await vite.build({
293
+ ...common,
294
+ base: './',
295
+ build: {
296
+ outDir: join(out, 'browser'),
297
+ emptyOutDir: true,
298
+ manifest: true,
299
+ cssCodeSplit: true,
300
+ modulePreload: false,
301
+ copyPublicDir: false,
302
+ rollupOptions: {
303
+ input,
304
+ external: isShared,
305
+ preserveEntrySignatures: 'strict',
306
+ output: {
307
+ entryFileNames: 'pages/[name]-[hash].js',
308
+ chunkFileNames: 'chunks/[name]-[hash].js',
309
+ assetFileNames: 'assets/[name]-[hash][extname]',
310
+ },
224
311
  },
225
312
  },
226
- },
227
- }));
228
- serverItems = outputs(await vite.build({
229
- ...common,
230
- ssr: { noExternal: true },
231
- build: {
232
- ssr: true,
233
- outDir: join(out, 'ssr'),
234
- emptyOutDir: true,
235
- copyPublicDir: false,
236
- rollupOptions: {
237
- input,
238
- external: isShared,
239
- preserveEntrySignatures: 'strict',
240
- output: {
241
- format: 'es',
242
- entryFileNames: 'pages/[name].js',
243
- chunkFileNames: 'chunks/[name]-[hash].js',
313
+ }));
314
+ serverItems = outputs(await vite.build({
315
+ ...common,
316
+ ssr: { noExternal: true },
317
+ build: {
318
+ ssr: true,
319
+ outDir: join(out, 'ssr'),
320
+ emptyOutDir: true,
321
+ copyPublicDir: false,
322
+ rollupOptions: {
323
+ input,
324
+ external: isShared,
325
+ preserveEntrySignatures: 'strict',
326
+ output: {
327
+ format: 'es',
328
+ entryFileNames: 'pages/[name].js',
329
+ chunkFileNames: 'chunks/[name]-[hash].js',
330
+ },
244
331
  },
245
332
  },
246
- },
247
- }));
248
- }
249
- catch (cause) {
250
- throw new InertiaError('TEMPLATE_BUILD_FAILED', `The Vite build of ${name} failed`, { cause });
251
- }
252
- finally {
253
- if (environment === undefined)
254
- delete process.env.NODE_ENV;
255
- else
256
- process.env.NODE_ENV = environment;
257
- }
258
- collect(browserItems);
259
- collect(serverItems);
260
- // The browser manifest gives each page its stylesheets and the chunks it imports.
261
- const manifestPath = join(out, 'browser', '.vite', 'manifest.json');
262
- const vm = JSON.parse(await readFile(manifestPath, 'utf8'));
263
- await rm(join(out, 'browser', '.vite'), { recursive: true, force: true });
264
- const byName = new Map();
265
- for (const entry of Object.values(vm))
266
- if (entry.isEntry && entry.name)
267
- byName.set(entry.name, entry);
268
- const server = new Map();
269
- for (const item of serverItems)
270
- if (item.type === 'chunk' && item.isEntry && item.name)
271
- server.set(item.name, item.fileName);
272
- const pageEntries = {};
273
- for (const page of pages.keys()) {
274
- const entry = byName.get(page);
275
- const ssrFile = server.get(page);
276
- if (entry === undefined || ssrFile === undefined)
277
- throw new InertiaError('TEMPLATE_BUILD_FAILED', `The build has no entry for ${page} (browser ${entry ? 'yes' : 'no'}, server ${ssrFile ? 'yes' : 'no'})`);
278
- const css = [];
279
- const preload = [];
280
- const seen = new Set();
281
- const visit = (key) => {
282
- if (seen.has(key))
283
- return;
284
- seen.add(key);
285
- const chunk = vm[key];
286
- if (!chunk)
287
- return;
288
- for (const next of chunk.imports ?? [])
289
- visit(next);
290
- if (chunk !== entry)
291
- preload.push(`browser/${chunk.file}`);
292
- for (const file of chunk.css ?? [])
293
- if (!css.includes(`browser/${file}`))
294
- css.push(`browser/${file}`);
295
- };
296
- const key = Object.keys(vm).find((candidate) => vm[candidate] === entry);
297
- visit(key);
298
- let meta;
299
- try {
300
- const module = (await import(`${pathToFileURL(join(out, 'ssr', ssrFile)).href}?build=${Date.now()}`));
301
- meta = module.meta;
333
+ }));
302
334
  }
303
335
  catch (cause) {
304
- throw new InertiaError('TEMPLATE_BUILD_FAILED', `The server module of ${page} could not be imported to read its meta: ${cause.message}`, { cause });
336
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `The Vite build of ${name} failed`, {
337
+ cause,
338
+ });
305
339
  }
306
- if (meta !== undefined) {
307
- if (!jsonValue(meta))
308
- throw new InertiaError('TEMPLATE_BUILD_FAILED', `${page} exports a meta that is not JSON data`);
309
- if (Buffer.byteLength(JSON.stringify(meta)) > PAGE_META_MAX_BYTES)
310
- throw new InertiaError('TEMPLATE_BUILD_FAILED', `${page} exports a meta larger than ${PAGE_META_MAX_BYTES} bytes`);
340
+ finally {
341
+ if (environment === undefined)
342
+ delete process.env.NODE_ENV;
343
+ else
344
+ process.env.NODE_ENV = environment;
345
+ }
346
+ collect(browserItems);
347
+ collect(serverItems);
348
+ // The browser manifest gives each page its stylesheets and the chunks it imports.
349
+ const manifestPath = join(out, 'browser', '.vite', 'manifest.json');
350
+ const vm = JSON.parse(await readFile(manifestPath, 'utf8'));
351
+ await rm(join(out, 'browser', '.vite'), { recursive: true, force: true });
352
+ const byName = new Map();
353
+ for (const entry of Object.values(vm))
354
+ if (entry.isEntry && entry.name)
355
+ byName.set(entry.name, entry);
356
+ const server = new Map();
357
+ for (const item of serverItems)
358
+ if (item.type === 'chunk' && item.isEntry && item.name)
359
+ server.set(item.name, item.fileName);
360
+ for (const page of pages.keys()) {
361
+ const entry = byName.get(page);
362
+ const ssrFile = server.get(page);
363
+ if (entry === undefined || ssrFile === undefined)
364
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `The build has no entry for ${page} (browser ${entry ? 'yes' : 'no'}, server ${ssrFile ? 'yes' : 'no'})`);
365
+ const css = [];
366
+ const preload = [];
367
+ const seen = new Set();
368
+ const visit = (key) => {
369
+ if (seen.has(key))
370
+ return;
371
+ seen.add(key);
372
+ const chunk = vm[key];
373
+ if (!chunk)
374
+ return;
375
+ for (const next of chunk.imports ?? [])
376
+ visit(next);
377
+ if (chunk !== entry)
378
+ preload.push(`browser/${chunk.file}`);
379
+ for (const file of chunk.css ?? [])
380
+ if (!css.includes(`browser/${file}`))
381
+ css.push(`browser/${file}`);
382
+ };
383
+ const key = Object.keys(vm).find((candidate) => vm[candidate] === entry);
384
+ visit(key);
385
+ let meta;
386
+ try {
387
+ const module = (await import(`${pathToFileURL(join(out, 'ssr', ssrFile)).href}?build=${Date.now()}`));
388
+ meta = module.meta;
389
+ }
390
+ catch (cause) {
391
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `The server module of ${page} could not be imported to read its meta: ${cause.message}`, { cause });
392
+ }
393
+ if (meta !== undefined) {
394
+ if (!jsonValue(meta))
395
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `${page} exports a meta that is not JSON data`);
396
+ if (Buffer.byteLength(JSON.stringify(meta)) > PAGE_META_MAX_BYTES)
397
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `${page} exports a meta larger than ${PAGE_META_MAX_BYTES} bytes`);
398
+ }
399
+ pageEntries[page] = {
400
+ browser: `browser/${entry.file}`,
401
+ css,
402
+ preload,
403
+ ssr: `ssr/${ssrFile}`,
404
+ ...(meta === undefined ? {} : { meta }),
405
+ };
311
406
  }
312
- pageEntries[page] = {
313
- browser: `browser/${entry.file}`,
314
- css,
315
- preload,
316
- ssr: `ssr/${ssrFile}`,
317
- ...(meta === undefined ? {} : { meta }),
318
- };
319
407
  }
320
408
  // D-0291 stage 3b: the template's screen words, locales/<locale>/<namespace>.json, as they are
321
409
  // (the app's @dokebi/i18n reads them with its own loader and rules).
@@ -340,9 +428,15 @@ export async function buildTemplateBundle(options) {
340
428
  await writeFile(join(out, 'locales', file), text);
341
429
  wordFiles++;
342
430
  }
431
+ // D-0296: the carried files, as they are, after Vite emptied browser/.
432
+ for (const [target, file] of carry) {
433
+ const to = join(out, ...target.split('/'));
434
+ await mkdir(dirname(to), { recursive: true });
435
+ await writeFile(to, await readFile(file));
436
+ }
343
437
  const files = {};
344
438
  for (const top of wordFiles ? ['browser', 'ssr', 'locales'] : ['browser', 'ssr'])
345
- for (const file of await listFiles(join(out, top))) {
439
+ for (const file of existsSync(join(out, top)) ? await listFiles(join(out, top)) : []) {
346
440
  const content = await readFile(join(out, top, file));
347
441
  files[`${top}/${file}`] = { bytes: content.length, sha256: sha256(content) };
348
442
  }
@@ -354,6 +448,8 @@ export async function buildTemplateBundle(options) {
354
448
  shared: Object.fromEntries([...imported].sort().map((module) => [module, packageVersion(root, module)])),
355
449
  pages: pageEntries,
356
450
  files,
451
+ ...(styles.length ? { styles } : {}),
452
+ ...(csp === undefined ? {} : { csp }),
357
453
  };
358
454
  await writeFile(join(out, TEMPLATE_MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
359
455
  const check = await checkTemplateBundle(out, {
@@ -368,6 +464,9 @@ export async function buildTemplateBundle(options) {
368
464
  buildId: check.buildId,
369
465
  pages: Object.keys(pageEntries),
370
466
  shared: manifest.shared,
467
+ carried: [...carry.keys()],
468
+ styles,
469
+ ...(csp === undefined ? {} : { csp }),
371
470
  files: Object.keys(files).length,
372
471
  bytes: check.bytes,
373
472
  ms: Math.round(performance.now() - begin),
@@ -380,6 +479,9 @@ export async function buildTemplateBundle(options) {
380
479
  out: relative(root, out),
381
480
  pages: result.pages.length,
382
481
  words: wordFiles,
482
+ carried: result.carried,
483
+ styles,
484
+ csp,
383
485
  files: result.files,
384
486
  bytes: result.bytes,
385
487
  shared: manifest.shared,
@@ -10,8 +10,24 @@ export declare const TEMPLATE_NAME: RegExp;
10
10
  export declare const TEMPLATE_VERSION: RegExp;
11
11
  /** A page of a bundle: `Layout`, or `Pages/<path>` without the `.vue`. */
12
12
  export declare const TEMPLATE_PAGE: RegExp;
13
+ /**
14
+ * A file of a bundle: under browser/ or ssr/, or a screen-word file `locales/<locale>/<ns>.json`
15
+ * (D-0291 stage 3b), plain path segments only.
16
+ */
17
+ export declare const TEMPLATE_FILE: RegExp;
13
18
  /** A shared module specifier: a package name with an optional subpath. */
14
19
  export declare const SHARED_SPECIFIER: RegExp;
20
+ /**
21
+ * D-0297: the CSP directives a template may add sources to (its `csp.json`, the manifest's `csp`):
22
+ * the widgets, APIs, styles, fonts, images and frames of other origins its pages use.
23
+ */
24
+ export declare const TEMPLATE_CSP_DIRECTIVES: readonly string[];
25
+ /** D-0298: at most this many template stylesheets. */
26
+ export declare const TEMPLATE_STYLES_MAX = 32;
27
+ /** At most this many sources per directive. */
28
+ export declare const TEMPLATE_CSP_MAX_SOURCES = 32;
29
+ /** D-0297: the problem of a template's CSP declaration, or undefined. */
30
+ export declare function cspDeclarationProblem(value: unknown): string | undefined;
15
31
  /** A page's `meta` (JSON) may take this many bytes. */
16
32
  export declare const PAGE_META_MAX_BYTES = 4096;
17
33
  /** Default limits of one bundle. */
@@ -52,6 +68,16 @@ export interface TemplateManifest {
52
68
  readonly bytes: number;
53
69
  readonly sha256: string;
54
70
  }>>;
71
+ /**
72
+ * D-0297: the sources of other origins the pages use (the template folder's `csp.json`), added
73
+ * to the CSP of the answers drawn with this template. Apps before 0.4.27 ignore it.
74
+ */
75
+ readonly csp?: Readonly<Record<string, readonly string[]>>;
76
+ /**
77
+ * D-0298: the template's own stylesheets (`browser/…css` files of `files`), in order: the app
78
+ * puts them into the first HTML of every page of the template. Apps before 0.4.27 ignore it.
79
+ */
80
+ readonly styles?: readonly string[];
55
81
  }
56
82
  /** What is wrong with a bundle (one entry per problem; the code is stable). */
57
83
  export interface TemplateProblem {
@@ -30,11 +30,51 @@ export const TEMPLATE_PAGE = /^(?:Layout|Pages(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,
30
30
  * A file of a bundle: under browser/ or ssr/, or a screen-word file `locales/<locale>/<ns>.json`
31
31
  * (D-0291 stage 3b), plain path segments only.
32
32
  */
33
- const FILE = /^(?:(?:browser|ssr)(?:\/[A-Za-z0-9_@+][A-Za-z0-9_.@+-]{0,199}){1,32}|locales\/[A-Za-z][A-Za-z0-9_-]{0,34}(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,99}){1,8}\.json)$/;
33
+ export const TEMPLATE_FILE = /^(?:(?:browser|ssr)(?:\/[A-Za-z0-9_@+][A-Za-z0-9_.@+-]{0,199}){1,32}|locales\/[A-Za-z][A-Za-z0-9_-]{0,34}(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,99}){1,8}\.json)$/;
34
34
  /** The folders of a bundle. */
35
35
  const FOLDERS = ['browser', 'ssr', 'locales'];
36
36
  /** A shared module specifier: a package name with an optional subpath. */
37
37
  export const SHARED_SPECIFIER = /^(?:@[a-z0-9][a-z0-9._-]{0,213}\/)?[a-z0-9][a-z0-9._-]{0,213}(?:\/[A-Za-z0-9_.@+-]{1,200}){0,16}$/;
38
+ /**
39
+ * D-0297: the CSP directives a template may add sources to (its `csp.json`, the manifest's `csp`):
40
+ * the widgets, APIs, styles, fonts, images and frames of other origins its pages use.
41
+ */
42
+ export const TEMPLATE_CSP_DIRECTIVES = Object.freeze([
43
+ 'script-src',
44
+ 'style-src',
45
+ 'connect-src',
46
+ 'font-src',
47
+ 'img-src',
48
+ 'frame-src',
49
+ ]);
50
+ /** D-0298: at most this many template stylesheets. */
51
+ export const TEMPLATE_STYLES_MAX = 32;
52
+ /** At most this many sources per directive. */
53
+ export const TEMPLATE_CSP_MAX_SOURCES = 32;
54
+ /**
55
+ * D-0297: one source a template may declare: an https origin (a wss one in connect-src), its host
56
+ * with an optional `*.` in front, an optional port and path. No keyword ('unsafe-inline', a
57
+ * nonce), no bare scheme (`https:`, `data:`), no `*`, no plain http.
58
+ */
59
+ const CSP_SOURCE = /^(?:https|wss):\/\/(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+(?::\d{1,5})?(?:\/[A-Za-z0-9._~%!$&'()*+=:@/-]{0,200})?$/;
60
+ /** D-0297: the problem of a template's CSP declaration, or undefined. */
61
+ export function cspDeclarationProblem(value) {
62
+ if (!plain(value))
63
+ return 'csp must be an object of directive → sources';
64
+ for (const [name, sources] of Object.entries(value)) {
65
+ if (!TEMPLATE_CSP_DIRECTIVES.includes(name))
66
+ return `csp ${name} is not one of ${TEMPLATE_CSP_DIRECTIVES.join(', ')}`;
67
+ if (!Array.isArray(sources) || sources.length > TEMPLATE_CSP_MAX_SOURCES)
68
+ return `csp ${name} must be a list of at most ${TEMPLATE_CSP_MAX_SOURCES} sources`;
69
+ for (const source of sources) {
70
+ if (typeof source !== 'string' || !CSP_SOURCE.test(source))
71
+ return `csp ${name}: ${String(source)} is not an https origin (https://host[:port][/path], *.host allowed; wss:// in connect-src): no keyword, bare scheme, * or http`;
72
+ if (source.startsWith('wss:') && name !== 'connect-src')
73
+ return `csp ${name}: ${source} — wss:// belongs in connect-src`;
74
+ }
75
+ }
76
+ return undefined;
77
+ }
38
78
  /** A page's `meta` (JSON) may take this many bytes. */
39
79
  export const PAGE_META_MAX_BYTES = 4096;
40
80
  /** Default limits of one bundle. */
@@ -90,7 +130,7 @@ export function manifestProblem(value) {
90
130
  if (!plain(value.files))
91
131
  return 'files must be an object of path → { bytes, sha256 }';
92
132
  for (const [file, entry] of Object.entries(value.files)) {
93
- if (!FILE.test(file) || file.split('/').some((part) => part === '..' || part === '.'))
133
+ if (!TEMPLATE_FILE.test(file) || file.split('/').some((part) => part === '..' || part === '.'))
94
134
  return `file ${file} is not a path under browser/ or ssr/, or a locales/<locale>/<namespace>.json`;
95
135
  if (!plain(entry) ||
96
136
  !Number.isSafeInteger(entry.bytes) ||
@@ -99,9 +139,26 @@ export function manifestProblem(value) {
99
139
  !/^[0-9a-f]{64}$/.test(entry.sha256))
100
140
  return `file ${file} needs bytes (a whole number) and sha256 (64 hex)`;
101
141
  }
102
- if (!plain(value.pages) || Object.keys(value.pages).length === 0)
103
- return 'pages must name at least one page';
142
+ if (value.csp !== undefined) {
143
+ const problem = cspDeclarationProblem(value.csp);
144
+ if (problem)
145
+ return problem;
146
+ }
147
+ // D-0298: a bundle may have no page (a template of styles alone).
148
+ if (!plain(value.pages))
149
+ return 'pages must be an object of page → files';
104
150
  const files = value.files;
151
+ if (value.styles !== undefined) {
152
+ const list = value.styles;
153
+ if (!Array.isArray(list) ||
154
+ list.length > TEMPLATE_STYLES_MAX ||
155
+ list.some((file) => typeof file !== 'string' ||
156
+ !file.startsWith('browser/') ||
157
+ !file.endsWith('.css') ||
158
+ !Object.hasOwn(files, file)) ||
159
+ new Set(list).size !== list.length)
160
+ return `styles must be a list of at most ${TEMPLATE_STYLES_MAX} different browser/….css files of files`;
161
+ }
105
162
  for (const [page, entry] of Object.entries(value.pages)) {
106
163
  if (!TEMPLATE_PAGE.test(page))
107
164
  return `page ${page} is not Layout or Pages/<path>`;
@@ -12,6 +12,17 @@ export interface TemplatePreviewOptions {
12
12
  readonly host?: string;
13
13
  /** A vite config of the project to merge; @vitejs/plugin-vue is added unless it has its own. */
14
14
  readonly config?: string;
15
+ /**
16
+ * D-0297: a JSON file of the app's `securityHeaders.contentSecurityPolicy` (`{ directives?,
17
+ * nonce?, styleNonce? }`), relative to root: the policy the pages are drawn under. Default: web's
18
+ * default policy.
19
+ */
20
+ readonly csp?: string;
21
+ /**
22
+ * D-0298: the template's own stylesheets (`.css` files of the template folder, in order), linked
23
+ * in every page as the app does with a bundle's `styles` (and updated by HMR).
24
+ */
25
+ readonly styles?: readonly string[];
15
26
  readonly logger?: Logger;
16
27
  }
17
28
  export interface TemplatePreviewPage {
@@ -31,6 +42,11 @@ export declare function previewCases(file: string): Promise<Record<string, Recor
31
42
  * (`locales/<locale>/<namespace>.json`), so pages that call t() draw; undefined without words.
32
43
  */
33
44
  export declare function previewWords(folder: string, wanted?: string): Promise<Record<string, unknown> | undefined>;
45
+ /**
46
+ * D-0297: the policy of a preview page: the app's setting (or web's default), the template's
47
+ * declared sources, the HMR socket, and the nonce where the setting asks for one.
48
+ */
49
+ export declare function previewPolicy(folder: string, setting: string | undefined, socket: string, nonce: string): Promise<string>;
34
50
  /**
35
51
  * Starts the preview of the template folder `options.dir` (D-0291 stage 3). Resolves once the
36
52
  * server listens; `close()` stops it.