@dokebi/template-inertia 0.4.26 → 0.4.28

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.
@@ -9,13 +9,20 @@
9
9
  // template folder's `preview.json` (`{ "shared": { …props every page gets } }`). The shared
10
10
  // modules (vue, @inertiajs/vue3, the SDK) are the template repository's installed packages.
11
11
  // Inertia visits (a <Link> to another preview URL) are answered too.
12
+ //
13
+ // D-0297: each page carries a Content-Security-Policy as an app would send it: web's default policy
14
+ // (or the app's own setting, `csp`: a JSON file `{ directives?, nonce?, styleNonce? }` shaped like
15
+ // `securityHeaders.contentSecurityPolicy`), the template's `csp.json` sources and the HMR socket.
16
+ // What the policy blocks is listed on the page, so a designer sees an origin to declare. A changed
17
+ // csp.json or setting file reloads the page.
18
+ import { randomBytes } from 'node:crypto';
12
19
  import { existsSync, readFileSync, realpathSync } from 'node:fs';
13
20
  import { readdir, readFile } from 'node:fs/promises';
14
21
  import { basename, join, relative, resolve, sep } from 'node:path';
15
22
  import { pathToFileURL } from 'node:url';
16
23
  import { ConsoleLogger } from '@dokebi/core';
17
24
  import { InertiaError, InertiaUsageError } from './errors.js';
18
- import { packageEntry, templatePages } from './template-build.js';
25
+ import { carriedFiles, packageEntry, TEMPLATE_CSP_FILE, templateCsp, templatePages, } from './template-build.js';
19
26
  import { jsonValue, TEMPLATE_PAGE } from './template-bundle.js';
20
27
  import { vueTypeBarrels } from './vite-type-barrels.js';
21
28
  import { registerVueTypeScript } from './vue-typescript.js';
@@ -70,53 +77,135 @@ function flatten(input, prefix, out) {
70
77
  out[name] = value;
71
78
  }
72
79
  }
73
- /**
74
- * D-0291 stage 3b: the `i18n` page prop of the preview from the template's own words
75
- * (`locales/<locale>/<namespace>.json`), so pages that call t() draw; undefined without words.
76
- */
77
- export async function previewWords(folder, wanted) {
78
- const root = join(folder, 'locales');
79
- if (!existsSync(root))
80
- return undefined;
81
- const locales = (await readdir(root, { withFileTypes: true }))
82
- .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
80
+ /** D-0300: the cookie the preview's language switch writes (the app's switchLocale). */
81
+ export const PREVIEW_LOCALE_COOKIE = 'dokebi_preview_locale';
82
+ /** A locale folder name: a language tag. */
83
+ const LOCALE = /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8}){0,4}$/;
84
+ /** The locale folders of `root`, sorted (none when it is missing). */
85
+ async function localeFolders(root) {
86
+ if (root === undefined || !existsSync(root))
87
+ return [];
88
+ return (await readdir(root, { withFileTypes: true }))
89
+ .filter((entry) => entry.isDirectory() && LOCALE.test(entry.name))
83
90
  .map((entry) => entry.name)
84
91
  .sort();
85
- const locale = wanted !== undefined && locales.includes(wanted) ? wanted : locales[0];
86
- if (locale === undefined)
87
- return undefined;
88
- const messages = {};
89
- const namespaces = [];
90
- for (const entry of await readdir(join(root, locale), { withFileTypes: true })) {
92
+ }
93
+ /** The flat messages and namespaces of one locale folder (`<namespace>.json` files). */
94
+ async function localeWords(root, locale, messages, namespaces) {
95
+ if (root === undefined)
96
+ return;
97
+ const folder = join(root, locale);
98
+ if (!existsSync(folder))
99
+ return;
100
+ for (const entry of await readdir(folder, { withFileTypes: true })) {
91
101
  if (!entry.isFile() || !entry.name.endsWith('.json') || entry.name.startsWith('.'))
92
102
  continue;
93
103
  const namespace = entry.name.slice(0, -'.json'.length);
94
- namespaces.push(namespace);
95
- flatten(JSON.parse(await readFile(join(root, locale, entry.name), 'utf8')), namespace, messages);
104
+ const file = join(folder, entry.name);
105
+ let parsed;
106
+ try {
107
+ parsed = JSON.parse(await readFile(file, 'utf8'));
108
+ }
109
+ catch (error) {
110
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${file} is not JSON: ${error.message}`);
111
+ }
112
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
113
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${file} is not an object of words`);
114
+ namespaces.add(namespace);
115
+ flatten(parsed, namespace, messages);
116
+ }
117
+ }
118
+ /**
119
+ * D-0291 stage 3b, D-0300: the `i18n` page prop of the preview: the words of `wanted` (or the
120
+ * default language) from the template's `locales/<locale>/<namespace>.json` over the app's
121
+ * catalogs (`options.words`), with the default language's as the fallback, and the settings of a
122
+ * language switch (every language offered, the default, the preview's cookie), so pages that call
123
+ * t() draw and the app's language buttons show and work. Undefined without any words.
124
+ */
125
+ export async function previewWords(folder, wanted, options = {}) {
126
+ const own = join(folder, 'locales');
127
+ const app = options.words;
128
+ const found = [...new Set([...(await localeFolders(own)), ...(await localeFolders(app))])].sort();
129
+ const locales = options.locales?.length ? [...options.locales] : found;
130
+ for (const locale of locales)
131
+ if (!LOCALE.test(locale))
132
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${locale} is not a language tag`);
133
+ const defaultLocale = options.defaultLocale !== undefined && locales.includes(options.defaultLocale)
134
+ ? options.defaultLocale
135
+ : locales[0];
136
+ if (defaultLocale === undefined)
137
+ return undefined;
138
+ const locale = wanted !== undefined && locales.includes(wanted) ? wanted : defaultLocale;
139
+ const fallback = locale === defaultLocale ? [locale] : [locale, defaultLocale];
140
+ const messages = {};
141
+ const namespaces = new Set();
142
+ // Each key once, from the first language of the chain that has it (as the server sends a page's
143
+ // messages: the browser takes the last source of a key it is given twice).
144
+ const seen = new Set();
145
+ for (const source of fallback) {
146
+ const words = {};
147
+ // The app's catalogs first, the template's own over them (D-0282).
148
+ await localeWords(app, source, words, namespaces);
149
+ await localeWords(own, source, words, namespaces);
150
+ const fresh = Object.fromEntries(Object.entries(words).filter(([key]) => !seen.has(key)));
151
+ for (const key of Object.keys(fresh))
152
+ seen.add(key);
153
+ if (Object.keys(fresh).length || source === locale)
154
+ messages[source] = fresh;
96
155
  }
97
156
  return {
98
157
  locale,
99
158
  version: 'preview',
100
- fallback: [locale],
101
- namespaces: namespaces.sort(),
102
- messages: { [locale]: messages },
159
+ fallback,
160
+ namespaces: [...namespaces].sort(),
161
+ messages,
162
+ settings: {
163
+ locales,
164
+ defaultLocale,
165
+ missing: 'key',
166
+ timeZone: 'UTC',
167
+ maxOutputLength: 65536,
168
+ cookie: PREVIEW_LOCALE_COOKIE,
169
+ numberFormats: {},
170
+ dateFormats: {},
171
+ },
103
172
  };
104
173
  }
105
- /** `preview.json` of the template folder: `{ shared, locale? }`. */
174
+ /** `preview.json` of the template folder: `{ shared, locale?, locales? }` (the languages). */
106
175
  async function previewLocale(folder) {
107
176
  const file = join(folder, 'preview.json');
108
177
  if (!existsSync(file))
109
- return undefined;
178
+ return {};
110
179
  try {
111
- const locale = JSON.parse(await readFile(file, 'utf8'))
112
- ?.locale;
113
- return typeof locale === 'string' ? locale : undefined;
180
+ const parsed = JSON.parse(await readFile(file, 'utf8'));
181
+ return {
182
+ ...(typeof parsed?.locale === 'string' ? { locale: parsed.locale } : {}),
183
+ ...(Array.isArray(parsed?.locales) && parsed.locales.every((item) => typeof item === 'string')
184
+ ? { locales: parsed.locales }
185
+ : {}),
186
+ };
114
187
  }
115
188
  catch {
116
189
  // Its shape is reported by previewShared.
117
- return undefined;
190
+ return {};
118
191
  }
119
192
  }
193
+ /** D-0300: the preview's language cookie of a request, when it names one. */
194
+ function cookieLocale(header) {
195
+ for (const part of (header ?? '').split(';')) {
196
+ const [name, ...value] = part.trim().split('=');
197
+ if (name === PREVIEW_LOCALE_COOKIE) {
198
+ try {
199
+ return decodeURIComponent(value.join('='));
200
+ }
201
+ catch {
202
+ // A cookie that is not URI-encoded names no language.
203
+ return undefined;
204
+ }
205
+ }
206
+ }
207
+ return undefined;
208
+ }
120
209
  /** `preview.json` of the template folder: `{ shared }`. */
121
210
  async function previewShared(folder) {
122
211
  const file = join(folder, 'preview.json');
@@ -136,6 +225,65 @@ async function previewShared(folder) {
136
225
  }
137
226
  const escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]);
138
227
  const scriptJson = (value) => JSON.stringify(value).replace(/</g, '\\u003c');
228
+ /** D-0297: web's default policy (`DEFAULT_DIRECTIVES` of @dokebi/web 0.4.28), which apps start from. */
229
+ const DEFAULT_CSP = {
230
+ 'default-src': ["'self'"],
231
+ 'base-uri': ["'self'"],
232
+ 'object-src': ["'none'"],
233
+ 'frame-ancestors': ["'self'"],
234
+ 'script-src': ["'self'", "'unsafe-inline'"],
235
+ 'style-src': ["'self'", "'unsafe-inline'", 'https:'],
236
+ 'img-src': ["'self'", 'data:', 'blob:', 'https:'],
237
+ 'font-src': ["'self'", 'data:', 'https:'],
238
+ 'connect-src': ["'self'"],
239
+ };
240
+ /** Appends sources as web does: an unset fetch directive starts from default-src; 'none' gives way. */
241
+ function appendSources(merged, name, sources) {
242
+ const base = merged[name] ?? (name.endsWith('-src') ? (merged['default-src'] ?? []) : []);
243
+ const kept = sources.length ? base.filter((source) => source !== "'none'") : base;
244
+ merged[name] = [...new Set([...kept, ...sources])];
245
+ }
246
+ /**
247
+ * D-0297: the policy of a preview page: the app's setting (or web's default), the template's
248
+ * declared sources, the HMR socket, and the nonce where the setting asks for one.
249
+ */
250
+ export async function previewPolicy(folder, setting, socket, nonce) {
251
+ let own = {};
252
+ if (setting !== undefined) {
253
+ let parsed;
254
+ try {
255
+ parsed = JSON.parse(await readFile(setting, 'utf8'));
256
+ }
257
+ catch (cause) {
258
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `--csp ${setting} is not a JSON file: ${cause.message}`, { cause });
259
+ }
260
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
261
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `--csp ${setting} must hold the app's contentSecurityPolicy setting: { directives?, nonce?, styleNonce? }`);
262
+ own = parsed;
263
+ }
264
+ const merged = { ...DEFAULT_CSP };
265
+ for (const [name, sources] of Object.entries(own.directives ?? {}))
266
+ if (sources === false)
267
+ delete merged[name];
268
+ else if (Array.isArray(sources))
269
+ merged[name] = sources.map(String);
270
+ for (const [name, sources] of Object.entries((await templateCsp(folder)) ?? {}))
271
+ appendSources(merged, name, sources);
272
+ appendSources(merged, 'connect-src', [socket]);
273
+ const withNonce = (name, more) => {
274
+ const base = merged[name] ?? merged['default-src'] ?? [];
275
+ merged[name] = [
276
+ ...new Set([...base.filter((source) => source !== "'unsafe-inline'"), ...more]),
277
+ ];
278
+ };
279
+ if (own.nonce === true)
280
+ withNonce('script-src', [`'nonce-${nonce}'`, "'strict-dynamic'"]);
281
+ if (own.styleNonce === true)
282
+ withNonce('style-src', [`'nonce-${nonce}'`]);
283
+ return Object.entries(merged)
284
+ .map(([name, sources]) => (sources.length ? `${name} ${sources.join(' ')}` : name))
285
+ .join('; ');
286
+ }
139
287
  /**
140
288
  * Starts the preview of the template folder `options.dir` (D-0291 stage 3). Resolves once the
141
289
  * server listens; `close()` stops it.
@@ -148,9 +296,25 @@ export async function startTemplatePreview(options) {
148
296
  const inside = relative(root, folder);
149
297
  if (!inside || inside.startsWith('..') || !existsSync(folder))
150
298
  throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${options.dir} must be a template folder inside ${root}`);
151
- const pages = await templatePages(folder);
152
- if (![...pages.keys()].some((key) => key.startsWith('Pages/')))
153
- throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${options.dir} has no Pages/**/*.vue`);
299
+ // D-0299: the pages are read again for every request (a page added or removed while the preview
300
+ // runs is listed and drawn at once); a template without pages yet starts too.
301
+ await templatePages(folder);
302
+ // D-0298: the template's stylesheets, checked as the build checks them.
303
+ let styles;
304
+ try {
305
+ styles = [...(await carriedFiles(folder, options.styles ?? [])).keys()].map((target) => target.slice('browser/'.length));
306
+ }
307
+ catch (error) {
308
+ // A path the build would refuse is this command's usage error; anything else goes up as it is.
309
+ if (!(error instanceof InertiaUsageError))
310
+ throw error;
311
+ const refused = new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', error.message.replace('--carry', '--style'));
312
+ refused.cause = error;
313
+ throw refused;
314
+ }
315
+ const notCss = styles.find((file) => !file.endsWith('.css'));
316
+ if (notCss !== undefined)
317
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `--style ${notCss} is not a .css file`);
154
318
  const viteEntry = packageEntry(root, 'vite');
155
319
  if (!viteEntry)
156
320
  throw new InertiaError('TEMPLATE_BUILD_FAILED', `vite is not installed in ${root}`, {
@@ -177,12 +341,24 @@ export async function startTemplatePreview(options) {
177
341
  .default
178
342
  : undefined;
179
343
  registerVueTypeScript(root, logger);
344
+ // D-0297: the app's CSP setting the pages are drawn under, and the nonce of this preview (Vite
345
+ // writes it on the tags it adds; one per server is enough for a local preview).
346
+ const cspSetting = options.csp === undefined ? undefined : resolve(root, options.csp);
347
+ if (cspSetting !== undefined && !existsSync(cspSetting))
348
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `--csp ${options.csp} is not a file`);
349
+ const nonce = randomBytes(16).toString('base64');
350
+ // D-0300: the app's catalogs the template's words lie over.
351
+ const appWords = options.words === undefined ? undefined : resolve(root, options.words);
352
+ if (appWords !== undefined && !existsSync(appWords))
353
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `--words ${options.words} is not a folder`);
354
+ let socketOrigin = () => 'ws://127.0.0.1';
180
355
  const folderUrl = `/${inside.split(sep).join('/')}`;
181
- const names = [...pages.keys()]
356
+ /** D-0299: the pages of the folder now (a few readdir calls). */
357
+ const currentNames = async () => [...(await templatePages(folder)).keys()]
182
358
  .filter((key) => key.startsWith('Pages/'))
183
359
  .map((key) => key.slice(6));
184
360
  /** The page object of one preview URL. */
185
- const pageObject = async (name, wanted) => {
361
+ const pageObject = async (name, wanted, language) => {
186
362
  const cases = await previewCases(join(folder, 'Pages', `${name}.preview.json`));
187
363
  const chosen = wanted !== null && Object.hasOwn(cases, wanted) ? wanted : Object.keys(cases)[0];
188
364
  const props = {
@@ -192,7 +368,16 @@ export async function startTemplatePreview(options) {
192
368
  };
193
369
  // D-0291 stage 3b: the template's own words, unless the case gives its own i18n.
194
370
  if (props.i18n === undefined) {
195
- const words = await previewWords(folder, await previewLocale(folder));
371
+ // D-0300: every language (options, else preview.json, else the locale folders), the one the
372
+ // language switch chose (its cookie), the app's catalogs under the template's words.
373
+ const chosenLanguages = await previewLocale(folder);
374
+ const defaultLocale = options.defaultLocale ?? chosenLanguages.locale;
375
+ const locales = options.locales ?? chosenLanguages.locales;
376
+ const words = await previewWords(folder, language ?? defaultLocale, {
377
+ ...(appWords === undefined ? {} : { words: appWords }),
378
+ ...(locales === undefined ? {} : { locales }),
379
+ ...(defaultLocale === undefined ? {} : { defaultLocale }),
380
+ });
196
381
  if (words) {
197
382
  props.i18n = words;
198
383
  props.locale ??= words.locale;
@@ -218,7 +403,29 @@ export async function startTemplatePreview(options) {
218
403
  load(id) {
219
404
  if (id !== ENTRY_ID)
220
405
  return null;
221
- return `import { createInertiaApp, router } from '@inertiajs/vue3';
406
+ return `// D-0297: what the page's Content-Security-Policy blocks, listed on the page.
407
+ const blocked = new Set();
408
+ document.addEventListener('securitypolicyviolation', (event) => {
409
+ const line = event.effectiveDirective + ' blocked ' + (event.blockedURI || 'an inline ' + (event.effectiveDirective.startsWith('style') ? 'style' : 'script'));
410
+ if (blocked.has(line)) return;
411
+ blocked.add(line);
412
+ console.warn('[dokebi preview] ' + line + ': declare the origin in ${TEMPLATE_CSP_FILE} (D-0297)');
413
+ let box = document.getElementById('dokebi-preview-csp');
414
+ if (!box) {
415
+ box = document.createElement('div');
416
+ box.id = 'dokebi-preview-csp';
417
+ box.setAttribute('role', 'alert');
418
+ box.style.cssText = 'position:fixed;left:8px;right:8px;bottom:8px;z-index:2147483647;max-height:40vh;overflow:auto;background:#fff4f4;color:#7a0000;border:2px solid #c00;border-radius:6px;padding:8px 12px;font:13px/1.5 system-ui,sans-serif;';
419
+ const title = document.createElement('strong');
420
+ title.textContent = 'Blocked by the Content-Security-Policy: declare these origins in ${TEMPLATE_CSP_FILE}';
421
+ box.append(title, document.createElement('ul'));
422
+ document.body.append(box);
423
+ }
424
+ const item = document.createElement('li');
425
+ item.textContent = line;
426
+ box.querySelector('ul').append(item);
427
+ });
428
+ import { createInertiaApp, router } from '@inertiajs/vue3';
222
429
  import { pageI18n } from '@dokebi/template-inertia/i18n';
223
430
  import { createApp, h } from 'vue';
224
431
  const files = import.meta.glob(${JSON.stringify(`${folderUrl}/{Layout,Pages/**/*}.vue`)});
@@ -237,6 +444,16 @@ await createInertiaApp({
237
444
  });
238
445
  `;
239
446
  },
447
+ // D-0297: the policy is the document's: a changed csp.json (or setting file) reloads the page.
448
+ handleHotUpdate(context) {
449
+ const file = resolve(context.file);
450
+ if (file === join(folder, TEMPLATE_CSP_FILE) ||
451
+ (cspSetting !== undefined && file === cspSetting)) {
452
+ context.server.ws.send({ type: 'full-reload' });
453
+ return [];
454
+ }
455
+ return undefined;
456
+ },
240
457
  configureServer(server) {
241
458
  server.middlewares.use((request, response, next) => {
242
459
  const url = new URL(request.url ?? '/', 'http://preview');
@@ -259,31 +476,55 @@ await createInertiaApp({
259
476
  send(500, 'text/html; charset=utf-8', `<!doctype html><pre>${escapeHtml(error.message)}</pre>`);
260
477
  };
261
478
  if (url.pathname === '/') {
262
- Promise.all(names.map(async (name) => ({
479
+ currentNames()
480
+ .then((names) => Promise.all(names.map(async (name) => ({
263
481
  name,
264
482
  cases: Object.keys(await previewCases(join(folder, 'Pages', `${name}.preview.json`))),
265
- }))).then((listed) => send(200, 'text/html; charset=utf-8', `<!doctype html><html><head><meta charset="utf-8"><title>${escapeHtml(basename(folder))} preview</title></head><body><h1>${escapeHtml(basename(folder))}</h1><ul>${listed
483
+ }))))
484
+ .then(async (listed) => send(200, 'text/html; charset=utf-8',
485
+ // D-0299: Vite's client on the list too, so an added or removed page reloads it.
486
+ await server.transformIndexHtml('/', `<!doctype html><html><head><meta charset="utf-8"><title>${escapeHtml(basename(folder))} preview</title></head><body><h1>${escapeHtml(basename(folder))}</h1>${listed.length ? '' : `<p data-empty>No page yet: add Pages/&lt;Name&gt;.vue to ${escapeHtml(options.dir)}.</p>`}<ul>${listed
266
487
  .map((item) => `<li data-page="${escapeHtml(item.name)}">${escapeHtml(item.name)}: ${item.cases
267
488
  .map((name) => `<a href="${PREVIEW_PREFIX}${escapeHtml(item.name)}?case=${encodeURIComponent(name)}">${escapeHtml(name)}</a>`)
268
489
  .join(' · ')}</li>`)
269
- .join('')}</ul></body></html>`), fail);
490
+ .join('')}</ul></body></html>`)))
491
+ .catch(fail);
270
492
  return;
271
493
  }
272
494
  if (!url.pathname.startsWith(PREVIEW_PREFIX))
273
495
  return next();
274
496
  const name = decodeURIComponent(url.pathname.slice(PREVIEW_PREFIX.length));
275
- if (!TEMPLATE_PAGE.test(`Pages/${name}`) || !names.includes(name))
497
+ if (!TEMPLATE_PAGE.test(`Pages/${name}`))
276
498
  return send(404, 'text/plain; charset=utf-8', `No page ${name} in ${options.dir}`);
277
- pageObject(name, url.searchParams.get('case')).then(async ({ page }) => {
499
+ currentNames().then(async (names) => {
500
+ if (!names.includes(name))
501
+ return send(404, 'text/plain; charset=utf-8', `No page ${name} in ${options.dir}`);
502
+ const { page } = await pageObject(name, url.searchParams.get('case'), cookieLocale(request.headers.cookie));
278
503
  if (request.headers['x-inertia'] === 'true')
279
504
  return send(200, 'application/json; charset=utf-8', JSON.stringify(page), {
280
505
  'x-inertia': 'true',
281
506
  vary: 'X-Inertia',
282
507
  });
283
- const html = await server.transformIndexHtml(url.pathname, `<!doctype html><html><head><meta charset="utf-8"><title>${escapeHtml(name)} · preview</title><script type="module" src="${ENTRY_URL}"></script></head><body><script data-page="app" type="application/json">${scriptJson(page)}</script><div id="app"></div></body></html>`);
284
- send(200, 'text/html; charset=utf-8', html);
508
+ const policy = await previewPolicy(folder, cspSetting, socketOrigin(), nonce);
509
+ const html = await server.transformIndexHtml(url.pathname, `<!doctype html><html><head><meta charset="utf-8"><title>${escapeHtml(name)} · preview</title>${styles.map((file) => `<link rel="stylesheet" nonce="${nonce}" href="${escapeHtml(`${folderUrl}/${file}`)}">`).join('')}<script type="module" src="${ENTRY_URL}" nonce="${nonce}"></script></head><body><script data-page="app" type="application/json">${scriptJson(page)}</script><div id="app"></div></body></html>`);
510
+ send(200, 'text/html; charset=utf-8', html, { 'content-security-policy': policy });
285
511
  }, fail);
286
512
  });
513
+ // D-0299: a page added or removed (or the Layout) reloads the open pages and the list.
514
+ const pagesFolder = join(folder, 'Pages') + sep;
515
+ const layout = join(folder, 'Layout.vue');
516
+ const changed = (event) => (file) => {
517
+ const path = resolve(file);
518
+ if (path !== layout && !(path.startsWith(pagesFolder) && path.endsWith('.vue')))
519
+ return;
520
+ logger.log('debug', 'Template preview page added or removed; the pages reload', {
521
+ event,
522
+ file: relative(root, path),
523
+ });
524
+ server.ws.send({ type: 'full-reload' });
525
+ };
526
+ server.watcher.on('add', changed('add'));
527
+ server.watcher.on('unlink', changed('unlink'));
287
528
  },
288
529
  };
289
530
  let server;
@@ -294,6 +535,7 @@ await createInertiaApp({
294
535
  logLevel: 'warn',
295
536
  publicDir: false,
296
537
  appType: 'custom',
538
+ html: { cspNonce: nonce },
297
539
  plugins: [
298
540
  ...(vue
299
541
  ? [
@@ -325,7 +567,8 @@ await createInertiaApp({
325
567
  const port = typeof address === 'object' && address ? address.port : (options.port ?? 5180);
326
568
  const host = options.host ?? '127.0.0.1';
327
569
  const url = `http://${host.includes(':') ? `[${host}]` : host}:${port}/`;
328
- const listed = await Promise.all(names.map(async (name) => ({
570
+ socketOrigin = () => `ws://${host.includes(':') ? `[${host}]` : host}:${port}`;
571
+ const listed = await Promise.all((await currentNames()).map(async (name) => ({
329
572
  page: name,
330
573
  cases: Object.keys(await previewCases(join(folder, 'Pages', `${name}.preview.json`))),
331
574
  })));
@@ -38,6 +38,11 @@ export type TemplateVerifyResult = {
38
38
  readonly page: string;
39
39
  readonly reason: string;
40
40
  }[];
41
+ /**
42
+ * D-0297: the sources of the manifest's `csp` the app lets the bundle's answers add (the
43
+ * rest are left out, warn INERTIA_TEMPLATE_CSP_REFUSED). Left out: every declared source.
44
+ */
45
+ readonly csp?: Readonly<Record<string, readonly string[]>>;
41
46
  } | {
42
47
  readonly accept: false;
43
48
  readonly reason: string;
@@ -97,6 +102,10 @@ export interface TemplateState {
97
102
  readonly reason?: string;
98
103
  /** The last look at the mount that found a change (a load, a refusal), Date.now(). */
99
104
  readonly checkedAt?: number;
105
+ /** D-0297: the CSP sources the answers of the bundle in use add (after verifyTemplate). */
106
+ readonly csp?: Readonly<Record<string, readonly string[]>>;
107
+ /** D-0297: declared sources verifyTemplate left out. */
108
+ readonly cspRefused?: Readonly<Record<string, readonly string[]>>;
100
109
  }
101
110
  /** D-0294: what changed a template's state. */
102
111
  export type TemplateChange = 'loaded' | 'failed' | 'page-failed' | 'removed';
@@ -124,6 +133,10 @@ export declare class TemplateGeneration {
124
133
  readonly rejected: readonly string[];
125
134
  /** D-0294: the refusals of `rejected`, with verifyTemplate's reasons. */
126
135
  readonly rejectedWhy: readonly TemplatePageRefusal[];
136
+ /** D-0297: the CSP sources its answers add, and what web made of them (`cspAddition`). */
137
+ readonly csp: TemplateCsp | undefined;
138
+ /** D-0298: the URLs of the template's own stylesheets (the manifest's `styles`), in order. */
139
+ readonly styles: readonly string[];
127
140
  readonly setAside: Set<string>;
128
141
  /** D-0294: why each page set aside at render was (and when). */
129
142
  readonly setAsideWhy: Map<string, TemplatePageRefusal>;
@@ -139,7 +152,11 @@ export declare class TemplateGeneration {
139
152
  /** Pages the app's check refused. */
140
153
  rejected: readonly string[],
141
154
  /** D-0294: the refusals of `rejected`, with verifyTemplate's reasons. */
142
- rejectedWhy?: readonly TemplatePageRefusal[]);
155
+ rejectedWhy?: readonly TemplatePageRefusal[],
156
+ /** D-0297: the CSP sources its answers add, and what web made of them (`cspAddition`). */
157
+ csp?: TemplateCsp | undefined,
158
+ /** D-0298: the URLs of the template's own stylesheets (the manifest's `styles`), in order. */
159
+ styles?: readonly string[]);
143
160
  /** The page table of the first HTML (JSON, without the pages set aside). */
144
161
  table(): string;
145
162
  /** Leaves `page` to the app's own page for the rest of this generation. */
@@ -147,6 +164,14 @@ export declare class TemplateGeneration {
147
164
  /** The server module of `page`, unless it is set aside. */
148
165
  serverPage(page: string): Readonly<Record<string, unknown>> | undefined;
149
166
  }
167
+ /** D-0297: the CSP sources of a generation. */
168
+ export interface TemplateCsp {
169
+ readonly sources: Readonly<Record<string, readonly string[]>>;
170
+ /** Declared sources verifyTemplate left out. */
171
+ readonly refused: Readonly<Record<string, readonly string[]>>;
172
+ /** What `web.cspAddition` made of `sources` (undefined: nothing to add, or an older web). */
173
+ readonly addition: unknown;
174
+ }
150
175
  /** The part of a template the responder uses for one request. */
151
176
  export interface TemplateUse {
152
177
  /** The asset version of this request's pages. */
@@ -179,6 +204,11 @@ export interface TemplateBundlesOptions {
179
204
  ok: false;
180
205
  reason: string;
181
206
  }>;
207
+ /**
208
+ * D-0297: web's `cspAddition` (the sources a bundle's answers add); absent with a web before
209
+ * 0.4.28, then a bundle's `csp` is not used (warn INERTIA_TEMPLATE_CSP_UNSUPPORTED).
210
+ */
211
+ readonly cspAddition?: (directives: Readonly<Record<string, readonly string[]>>) => unknown;
182
212
  }
183
213
  /** Every app's template bundles. */
184
214
  export declare class TemplateBundles {