@dokebi/template-inertia 0.4.11 → 0.4.13

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 CHANGED
@@ -175,7 +175,7 @@ A page whose entry script cannot be fetched (a `dokebi dev` restart, a deploy in
175
175
  - The built-in look follows the browser: a dark colour scheme (`prefers-color-scheme: dark`) gets a dark box over the whole window (the page behind it is white without the app's CSS), a light one leaves the page's background; reduced motion (`prefers-reduced-motion: reduce`) stops the spinner. `logo` (a local URL such as `/assets/logo.svg`) shows an image above the spinner and the "could not load" text, decorative (`alt=""`, `[data-dokebi-boot-logo]`, at most 160 × 64 px by default).
176
176
  - Selectors for your stylesheet: `[data-dokebi-boot]` (the box, `role="status"`, `data-dokebi-boot="failed"` once it failed early), `[data-dokebi-boot-loading]`, `[data-dokebi-boot-failed]`. Never set `visibility`, `position` or `animation` on the two lines (their switch is those); animate a pseudo-element instead.
177
177
  - **Your own look: `bootFallback.stylesheet`** (a local URL such as `/assets/boot.css`, a plain CSS file of the app's `public/` that @dokebi/app serves) is linked right after the built-in style, so it applies before any script of the app runs. Do not style the box from the Vite bundle (`main.css`): under `dokebi dev` that CSS comes with the scripts, so the box shows unstyled while they load and stays unstyled when they fail. Keep the file small and self-contained (no Tailwind, no tokens of the bundle: they are not loaded yet).
178
- - CSP: web's default policy allows both inline blocks (`'unsafe-inline'`). A policy without it needs their hashes in `style-src` and `script-src` — the debug records `Inertia error answers` and `Inertia scope created` carry `bootFallback.cspHashes` (fixed per root id and timeout) — or `bootFallback: { enabled: false }`.
178
+ - CSP: web's default policy allows both inline blocks (`'unsafe-inline'`). Under web's nonce policy (`securityHeaders.contentSecurityPolicy.nonce` / `styleNonce`, 0.4.12, D-0247) both carry the page's nonce and nothing else is needed. A policy of your own without `'unsafe-inline'` and without a nonce needs their hashes in `style-src` and `script-src` — the debug records `Inertia error answers` and `Inertia scope created` carry `bootFallback.cspHashes` (fixed per root id and timeout) — or `bootFallback: { enabled: false }`.
179
179
  - A scope (`scope({ bootFallback })`, an app's inertia options) has its own; `false` there turns it off for that scope.
180
180
 
181
181
  ### 3.5 Public pages and head tags (0.4.6, D-0195)
@@ -272,7 +272,8 @@ A module keeps its Vue pages in its own views folder (@dokebi/module AI.md §4a)
272
272
  - Cluster apps run one worker under `dokebi dev` (@dokebi/cluster); `DOKEBI_DEV_WORKERS` asks for more, which also works on a cold cache.
273
273
  - When a build marks absolute-path imports as `external`, the dev server prefixes those paths with `<base>`. In the dev server use a Vite plugin that resolves them to real files (see the playground's `vite.config.ts`).
274
274
  - Production (no `DOKEBI_VITE_DEV`) is unaffected. Never set this variable on a production server.
275
- - **Content-Security-Policy** (dokebi-web security headers, [D-0149](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0149-security-headers.md)): in development this plugin adds `ws://*:* wss://*:*` to `connect-src` for Vite's HMR socket, which connects to the page's own origin and `<base>` (`ws://localhost:<app port>/build/`, or `wss://<public host>/build/` through a tunnel; §5.1), and `worker-src 'self' blob:` for the `blob:` SharedWorker Vite's client pings a restarted dev host from (without it the page never reconnects); production adds nothing. Pages load their scripts from `'self'` (the page data is JSON, not a script); keep `'unsafe-inline'` in a policy of your own when a Vite framework plugin adds inline scripts in development.
275
+ - **Content-Security-Policy** (dokebi-web security headers, [D-0149](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0149-security-headers.md)): Vite's HMR socket connects to the page's own origin and `<base>` (`ws://localhost:<app port>/build/`, or `wss://<public host>/build/` through a tunnel; §5.1), which `connect-src 'self'` allows (CSP3), so nothing is added for it (0.4.13, [D-0249](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0249-dev-hmr-csp-self.md); before, `ws://*:* wss://*:*`). Only a project whose Vite config sends the socket elsewhere — `server.ws` (or the older `server.hmr`) with `host`, `protocol`, `port` or `clientPort` — gets that origin added in development, exactly: the scheme (both `ws:` and `wss:` when the page decides), the host (`*` when it is the page's) and the port (`clientPort`, else `port`; `*` when it is the page's), e.g. `clientPort: 5174` → `ws://*:5174 wss://*:5174`. The dev host reports it when an app process connects (debug `Vite HMR socket origin added to connect-src`). In development this plugin also adds `worker-src 'self' blob:` for the `blob:` SharedWorker Vite's client pings a restarted dev host from (without it the page never reconnects); production adds nothing. Pages load their scripts from `'self'` (the page data is JSON, not a script); keep `'unsafe-inline'` in a policy of your own when a Vite framework plugin adds inline scripts in development.
276
+ - **Nonce policy** (0.4.12, [D-0247](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0247-csp-nonce.md); web 0.4.19 `contentSecurityPolicy: { nonce: true, styleNonce?: true }`): the first HTML — plain, sealed or server rendered, built or in development — writes the request's nonce (`web.cspNonce(request)`) on every module script and on the boot fallback's `<style>` and `<script>`, and adds `<meta property="csp-nonce" nonce="…">`, which Vite's client (development `<style>` of imported CSS) and its preload helper read. The page data block (`type="application/json"`) is never run and needs none. What the entry imports or creates is trusted by `'strict-dynamic'`. Inertia's own progress bar and error dialog styles take the nonce from `createInertiaApp({ nonce: document.querySelector('meta[property="csp-nonce"]')?.nonce || undefined })` (the generated `views/app.js` does; add it to an older entry before `styleNonce`). Checked in Chromium: a built Vue app with SSR and navigation (example 24), a seal host with server-rendered public pages and a framed page (example 80), and the Vite dev page with imported CSS, a dynamic import and the HMR client (`tests/dev-files.test.ts`).
276
277
  - The host answers a Vite middleware error with 500 (error log `INERTIA_VITE_HOST_FAILED`); 404 only when Vite has nothing for the URL. A host that does not answer is a 502 with error `INERTIA_VITE_DEV_FAILED` (once per 10 seconds, `repeated`); a host that cannot be reached at start is `VITE_DEV_UNAVAILABLE`.
277
278
  - Debug logs (D-0047): `Inertia settings resolved`, `Vite dev server ready` (ms, `shared`), `Vite dev route registered`, `Vite manifest read`, `Inertia SSR bundle loaded`, `Inertia SSR render deadline` (`timeoutMs`), `Inertia SSR render finished after its deadline` (a cut render that ended later), `Inertia SSR renders the source through Vite` (the source used), `Inertia scope created`, `Vite dev uses the host of dokebi dev`, `Vite dev starts a host in this process`, `Vite dev host connected` / `disconnected`; in the host `Vite dev host listening` (`port`, `hosts`), `Vite dev host started` (ms), `Vite dev host closed` (`connections`), `Vite dev host listens on IPv4 loopback only`, `Vite dev host port is taken on ::1, trying another`, `Vite dev host filters watcher events of unchanged files`, `Vite dev host ignored an event for a file that did not change` (the first and every 100th, `dropped`); `Vite dev host settings read` (`depsRepairIntervalMs`), `Vite dev host recorded itself in the cache folder` (`shared`), `Vite dev host re-optimized its dependencies` (`trigger`, `ms`, `repairs`), and per check only when debug is on `Vite dev host dependency cache matches` (`trigger`, `files`); per real file event, only when debug is on, `Vite dev host passes a file change`. A file whose state cannot be read is warn `INERTIA_VITE_WATCH_STAT_FAILED` (the event goes on). Per request, only when debug is on: `Vite dev route refused a host`, `Vite dev host closed an upgrade that is not Vite`, `Vite dev host refused a request without its key`, `Vite dev request ended by the browser`. Host listener and request failures are error `INERTIA_VITE_HOST_FAILED`.
278
279
 
@@ -34,12 +34,14 @@ export declare function normalizeBootFallback(input: InertiaBootFallback | false
34
34
  * the root's content. The head part depends on the root id and the timeout only, so its hashes are
35
35
  * fixed for a scope (logged at debug for a CSP that lists hashes).
36
36
  */
37
- export declare function bootMarkup(settings: NormalizedBootFallback, rootId: string, language: string | undefined): {
37
+ export declare function bootMarkup(settings: NormalizedBootFallback, rootId: string, language: string | undefined,
38
+ /** D-0247: the page's CSP nonce, written on the style and the script. */
39
+ nonce?: string): {
38
40
  readonly head: string;
39
41
  readonly root: string;
40
42
  };
41
- /** The style and the script of the head (fixed per root id and timeout). */
42
- export declare function bootHead(rootId: string, timeoutMs: number): string;
43
+ /** The style and the script of the head (fixed per root id and timeout; D-0247: with the page's nonce). */
44
+ export declare function bootHead(rootId: string, timeoutMs: number, nonce?: string): string;
43
45
  /**
44
46
  * "Loading" turns to "could not load" after the delay, or at once once the script marks it. The
45
47
  * look: the box fills the window and centers its line; "loading" is a spinner (its text, at size 0,
@@ -95,19 +95,22 @@ function textsFor(settings, language) {
95
95
  * the root's content. The head part depends on the root id and the timeout only, so its hashes are
96
96
  * fixed for a scope (logged at debug for a CSP that lists hashes).
97
97
  */
98
- export function bootMarkup(settings, rootId, language) {
98
+ export function bootMarkup(settings, rootId, language,
99
+ /** D-0247: the page's CSP nonce, written on the style and the script. */
100
+ nonce) {
99
101
  const texts = textsFor(settings, language);
100
102
  return {
101
- head: bootHead(rootId, settings.timeoutMs) +
103
+ head: bootHead(rootId, settings.timeoutMs, nonce) +
102
104
  (settings.stylesheet
103
105
  ? `<link rel="stylesheet" href="${escapeHtml(settings.stylesheet)}">`
104
106
  : ''),
105
107
  root: `<div data-dokebi-boot role="status" aria-live="polite">${settings.logo ? `<img data-dokebi-boot-logo src="${escapeHtml(settings.logo)}" alt="">` : ''}<p data-dokebi-boot-loading>${escapeHtml(texts.loading)}</p><p data-dokebi-boot-failed>${escapeHtml(texts.failed)} <a href="">${escapeHtml(texts.reload)}</a></p></div>`,
106
108
  };
107
109
  }
108
- /** The style and the script of the head (fixed per root id and timeout). */
109
- export function bootHead(rootId, timeoutMs) {
110
- return `<style>${bootStyle(timeoutMs)}</style><script>${bootScript(rootId)}</script>`;
110
+ /** The style and the script of the head (fixed per root id and timeout; D-0247: with the page's nonce). */
111
+ export function bootHead(rootId, timeoutMs, nonce) {
112
+ const attribute = nonce === undefined ? '' : ` nonce="${escapeHtml(nonce)}"`;
113
+ return `<style${attribute}>${bootStyle(timeoutMs)}</style><script${attribute}>${bootScript(rootId)}</script>`;
111
114
  }
112
115
  /**
113
116
  * "Loading" turns to "could not load" after the delay, or at once once the script marks it. The
package/dist/index.js CHANGED
@@ -292,7 +292,7 @@ function hasCookie(header, name) {
292
292
  */
293
293
  const web = providerDependency({
294
294
  name: 'dokebi-web',
295
- version: '^0.4.3',
295
+ version: '^0.4.19',
296
296
  packageName: '@dokebi/web',
297
297
  load: () => import('@dokebi/web'),
298
298
  });
@@ -439,6 +439,7 @@ class InertiaRuntime {
439
439
  const resets = new WeakMap();
440
440
  const hooks = Object.freeze({
441
441
  sealOf: (request) => server.sealOf(request),
442
+ cspNonce: (request) => server.cspNonce(request),
442
443
  ...(sessions
443
444
  ? {
444
445
  historyReset: async (request) => {
@@ -519,17 +520,15 @@ class InertiaRuntime {
519
520
  // Development (D-0045): one Vite for every scope, reached by the first `vite` (the host of
520
521
  // `dokebi dev`, shared by every worker, or one started in this process).
521
522
  const develop = viteDevRequested();
522
- // D-0149: the HMR socket of the Vite dev host is on its own port of the page's host name;
523
- // the default CSP (connect-src 'self') would block it. When the dev host restarts, Vite's
524
- // client pings it from a `blob:` SharedWorker, which script-src would block without
525
- // worker-src (community request A4). Development only.
523
+ // When the dev host restarts, Vite's client pings it from a `blob:` SharedWorker, which
524
+ // script-src would block without worker-src (community request A4). The HMR socket itself
525
+ // goes to the page's own origin, which connect-src 'self' allows; a Vite config that sends it
526
+ // elsewhere gets that origin added below (D-0249; it was ws://*:* wss://*:* before).
527
+ // Development only.
526
528
  if (develop)
527
529
  server.contentSecurityPolicy({
528
530
  plugin: 'dokebi-template-inertia',
529
- directives: {
530
- 'connect-src': ['ws://*:*', 'wss://*:*'],
531
- 'worker-src': ["'self'", 'blob:'],
532
- },
531
+ directives: { 'worker-src': ["'self'", 'blob:'] },
533
532
  });
534
533
  logger.log('debug', 'Inertia settings resolved', {
535
534
  develop,
@@ -651,7 +650,7 @@ class InertiaRuntime {
651
650
  nodeServer?.removeListener('upgrade', onUpgrade);
652
651
  });
653
652
  }
654
- const viteDev = (base) => {
653
+ const openDev = () => {
655
654
  if (!devServer) {
656
655
  const begin = performance.now();
657
656
  // A start failure reaches setup or the request that awaits the server.
@@ -668,7 +667,10 @@ class InertiaRuntime {
668
667
  code: 'INERTIA_VITE_DEV',
669
668
  });
670
669
  }
671
- const current = devServer;
670
+ return devServer;
671
+ };
672
+ const viteDev = (base) => {
673
+ const current = openDev();
672
674
  if (!devBases.has(base)) {
673
675
  devBases.add(base);
674
676
  // Modules, pre-bundled dependencies and @vite/client, under the Vite base.
@@ -731,6 +733,21 @@ class InertiaRuntime {
731
733
  }
732
734
  return current;
733
735
  };
736
+ // D-0249: the HMR socket's origin is the page's own unless the project's Vite config names
737
+ // another (server.ws / server.hmr host, protocol, port or clientPort): only the dev host
738
+ // knows, so it is asked now, while CSP sources may still be added (web freezes them at start).
739
+ if (develop && context.runtime.describing !== true) {
740
+ const opened = await openDev();
741
+ if (opened.hmrSources.length) {
742
+ server.contentSecurityPolicy({
743
+ plugin: 'dokebi-template-inertia',
744
+ directives: { 'connect-src': [...opened.hmrSources] },
745
+ });
746
+ logger.log('debug', 'Vite HMR socket origin added to connect-src', {
747
+ sources: opened.hmrSources,
748
+ });
749
+ }
750
+ }
734
751
  // Built files are served at their exact URL (no wildcard), once even if apps share chunks.
735
752
  const served = new Set();
736
753
  const loaded = new Set();
@@ -1036,7 +1053,7 @@ class InertiaRuntime {
1036
1053
  }
1037
1054
  export const createPlugin = definePlugin({
1038
1055
  name: 'dokebi-template-inertia',
1039
- version: '0.4.11',
1056
+ version: '0.4.13',
1040
1057
  core: '^0.4.2',
1041
1058
  options,
1042
1059
  entry: parseEntry,
@@ -91,6 +91,8 @@ export interface InertiaHooks {
91
91
  readonly sealOf?: (request: FastifyRequest) => {
92
92
  encode(text: string): string;
93
93
  } | undefined;
94
+ /** D-0247: the request's CSP nonce (dokebi-web `cspNonce`), undefined when no policy asks for one. */
95
+ readonly cspNonce?: (request: FastifyRequest) => string | undefined;
94
96
  readonly historyReset?: (request: FastifyRequest) => Promise<boolean>;
95
97
  /**
96
98
  * The validation redirect of an Inertia request (D-0074 §3): flashes `errors` (and `old`) in
package/dist/responder.js CHANGED
@@ -479,9 +479,17 @@ export class InertiaResponder {
479
479
  const htmlLanguage = typeof language === 'string' && /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(language)
480
480
  ? ` lang="${escapeHtml(language)}"`
481
481
  : '';
482
+ // D-0247: under a nonce policy every script of the page carries the nonce, and the meta tag
483
+ // hands it to Vite's client and preload helper for the styles and preloads they add.
484
+ const cspNonce = this.hooks.cspNonce?.(request);
485
+ const nonce = cspNonce === undefined ? '' : ` nonce="${escapeHtml(cspNonce)}"`;
486
+ const nonceMeta = cspNonce === undefined ? '' : `<meta property="csp-nonce"${nonce}>`;
487
+ const moduleScripts = scripts
488
+ .map((url) => `<script type="module"${nonce} src="${escapeHtml(url)}"></script>`)
489
+ .join('');
482
490
  // Studio v2: "loading", then "could not load — reload", while the app has not mounted.
483
491
  const boot = this.options.bootFallback.enabled
484
- ? bootMarkup(this.options.bootFallback, rootId, typeof language === 'string' ? language : undefined)
492
+ ? bootMarkup(this.options.bootFallback, rootId, typeof language === 'string' ? language : undefined, cspNonce)
485
493
  : undefined;
486
494
  if (sealer && !publicHtml) {
487
495
  // `E:<ts>:<base64>` holds no HTML specials; the client opens it before Inertia starts
@@ -490,7 +498,7 @@ export class InertiaResponder {
490
498
  const frame = sealer.encode(json);
491
499
  return reply
492
500
  .type('text/html; charset=utf-8')
493
- .send(`<!doctype html><html${htmlLanguage}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)}</title>${head?.tags ?? ''}${styles.map((url) => `<link rel="stylesheet" href="${escapeHtml(url)}">`).join('')}${boot?.head ?? ''}${scripts.map((url) => `<script type="module" src="${escapeHtml(url)}"></script>`).join('')}</head><body><script data-page="${rootId}" type="application/json" data-sealed="true">${escapeHtml(frame)}</script><div id="${rootId}">${boot?.root ?? ''}</div></body></html>`);
501
+ .send(`<!doctype html><html${htmlLanguage}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)}</title>${nonceMeta}${head?.tags ?? ''}${styles.map((url) => `<link rel="stylesheet" href="${escapeHtml(url)}">`).join('')}${boot?.head ?? ''}${moduleScripts}</head><body><script data-page="${rootId}" type="application/json" data-sealed="true">${escapeHtml(frame)}</script><div id="${rootId}">${boot?.root ?? ''}</div></body></html>`);
494
502
  }
495
503
  // Only the first HTML is server rendered; Inertia visits above stay JSON.
496
504
  const rendered = this.ssr ? await this.#serverRender(JSON.parse(json), rootId) : undefined;
@@ -523,7 +531,7 @@ export class InertiaResponder {
523
531
  const sealHost = sealer ? SEAL_HOST_META : '';
524
532
  return reply
525
533
  .type('text/html; charset=utf-8')
526
- .send(`<!doctype html><html${htmlLanguage}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${sealHost}${titled ? '' : `<title>${escapeHtml(title)}</title>`}${head?.tags ?? ''}${styles.map((url) => `<link rel="stylesheet" href="${escapeHtml(url)}">`).join('')}${rendered ? '' : (boot?.head ?? '')}${scripts.map((url) => `<script type="module" src="${escapeHtml(url)}"></script>`).join('')}${ssrHead.join('')}</head><body>${rendered?.body ?? `<script data-page="${rootId}" type="application/json">${safeJson}</script><div id="${rootId}">${boot?.root ?? ''}</div>`}</body></html>`);
534
+ .send(`<!doctype html><html${htmlLanguage}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${sealHost}${titled ? '' : `<title>${escapeHtml(title)}</title>`}${nonceMeta}${head?.tags ?? ''}${styles.map((url) => `<link rel="stylesheet" href="${escapeHtml(url)}">`).join('')}${rendered ? '' : (boot?.head ?? '')}${moduleScripts}${ssrHead.join('')}</head><body>${rendered?.body ?? `<script data-page="${rootId}" type="application/json">${safeJson}</script><div id="${rootId}">${boot?.root ?? ''}</div>`}</body></html>`);
527
535
  }
528
536
  /**
529
537
  * The value of one selected prop. A function runs here; a rescued deferred prop that throws is
@@ -39,6 +39,12 @@ export interface ViteHost {
39
39
  }
40
40
  /** What an app process uses: the host's files for `<base>*` and server rendering. */
41
41
  export interface ViteDev {
42
+ /**
43
+ * D-0249: the CSP sources of the HMR socket when the project's Vite config sends it somewhere
44
+ * other than the page's own origin (`server.ws` / `server.hmr` with `host`, `protocol`, `port`
45
+ * or `clientPort`); empty when it connects to the page's origin, which `'self'` allows.
46
+ */
47
+ readonly hmrSources: readonly string[];
42
48
  /** Answers a dev route request from the host (status, headers and body as Vite sent them). */
43
49
  forward(request: IncomingMessage, response: ServerResponse, report: (error: unknown) => void): void;
44
50
  /**
@@ -91,6 +97,14 @@ export declare function destroyRequest(outgoing: ClientRequest, error?: Error):
91
97
  * Connects this process to a Vite host and checks that it answers with the key. Requests share
92
98
  * keep-alive connections; `close` ends them (the host keeps running).
93
99
  */
100
+ /**
101
+ * D-0249: the CSP sources of an HMR socket Vite's client sends elsewhere than the page's origin,
102
+ * from the resolved `server.ws` (Vite 8; `server.hmr` is folded into it): the scheme (both when
103
+ * the config leaves it to the page), the host (`*` when the page's host is used) and the port
104
+ * (`clientPort`, else `port`; `*` when the page's port is used). None when the config names none
105
+ * of them: the client then connects to the page's own origin and `<base>`.
106
+ */
107
+ export declare function hmrSources(ws: unknown): string[];
94
108
  export declare function connectViteDev(logger: Logger, url: string, key: string): Promise<ViteDev>;
95
109
  /**
96
110
  * The Vite of this process: the host of `dokebi dev` when `DOKEBI_VITE_DEV_URL` and
package/dist/vite-dev.js CHANGED
@@ -285,7 +285,12 @@ export async function startViteHost(logger, root = process.cwd(), settings = {})
285
285
  if (path === HOST_PATH && !browser) {
286
286
  // An app process connects (it started or restarted): it is answered once the pre-bundled
287
287
  // dependencies match what Vite serves, so its pages get hashes that load (D-0128).
288
- void (cache ? cache.ensure('client').catch(report('deps')) : Promise.resolve()).then(() => sendJson(response, 200, { root, pid: process.pid }));
288
+ void (cache ? cache.ensure('client').catch(report('deps')) : Promise.resolve()).then(() => sendJson(response, 200, {
289
+ root,
290
+ pid: process.pid,
291
+ // D-0249: where Vite's client sends the HMR socket, when not to the page's origin.
292
+ hmr: hmrSources(server.config.server.ws),
293
+ }));
289
294
  }
290
295
  else if (path === SSR_PATH && request.method === 'POST' && !browser)
291
296
  void ssr(request, response, server);
@@ -422,6 +427,27 @@ export function destroyRequest(outgoing, error) {
422
427
  * Connects this process to a Vite host and checks that it answers with the key. Requests share
423
428
  * keep-alive connections; `close` ends them (the host keeps running).
424
429
  */
430
+ /**
431
+ * D-0249: the CSP sources of an HMR socket Vite's client sends elsewhere than the page's origin,
432
+ * from the resolved `server.ws` (Vite 8; `server.hmr` is folded into it): the scheme (both when
433
+ * the config leaves it to the page), the host (`*` when the page's host is used) and the port
434
+ * (`clientPort`, else `port`; `*` when the page's port is used). None when the config names none
435
+ * of them: the client then connects to the page's own origin and `<base>`.
436
+ */
437
+ export function hmrSources(ws) {
438
+ if (ws === null || typeof ws !== 'object')
439
+ return [];
440
+ const { host, protocol, port, clientPort } = ws;
441
+ const reach = clientPort ?? port;
442
+ const named = (value) => value !== undefined && value !== null && value !== '';
443
+ if (!named(host) && !named(protocol) && !named(reach))
444
+ return [];
445
+ const name = named(host) ? String(host) : '*';
446
+ const hostPart = name.includes(':') && !name.startsWith('[') ? `[${name}]` : name;
447
+ const portPart = named(reach) ? `:${Number(reach)}` : ':*';
448
+ const schemes = named(protocol) ? [String(protocol)] : ['ws', 'wss'];
449
+ return schemes.map((scheme) => `${scheme}://${hostPart}${portPart}`);
450
+ }
425
451
  export async function connectViteDev(logger, url, key) {
426
452
  const target = hostUrl(url);
427
453
  const host = target.hostname.replace(/^\[(.*)\]$/, '$1');
@@ -467,10 +493,15 @@ export async function connectViteDev(logger, url, key) {
467
493
  }
468
494
  outgoing.end(body);
469
495
  });
496
+ let sources = [];
470
497
  try {
471
- const { status } = await call('GET', HOST_PATH);
498
+ const { status, text } = await call('GET', HOST_PATH);
472
499
  if (status !== 200)
473
500
  throw new InertiaError('VITE_DEV_UNAVAILABLE', `The Vite dev host at ${target.origin} answered ${status} (wrong DOKEBI_VITE_DEV_KEY?)`);
501
+ // D-0249: a host before it sends no `hmr`: its socket is the page's origin, as before.
502
+ const answer = JSON.parse(text);
503
+ if (Array.isArray(answer.hmr))
504
+ sources = answer.hmr.filter((source) => typeof source === 'string');
474
505
  }
475
506
  catch (cause) {
476
507
  agent.destroy();
@@ -479,10 +510,11 @@ export async function connectViteDev(logger, url, key) {
479
510
  throw cause;
480
511
  throw new InertiaError('VITE_DEV_UNAVAILABLE', `The Vite dev host at ${target.origin} cannot be reached`, { cause });
481
512
  }
482
- logger.log('debug', 'Vite dev host connected', { url: target.origin });
513
+ logger.log('debug', 'Vite dev host connected', { url: target.origin, hmr: sources });
483
514
  /** HMR sockets joined to the host, ended by close(). */
484
515
  const joined = new Set();
485
516
  return {
517
+ hmrSources: Object.freeze(sources),
486
518
  upgrade(request, socket, head, report) {
487
519
  const upstream = connectNet({ host, port });
488
520
  joined.add(socket);
@@ -621,6 +653,7 @@ export async function openViteDev(logger, environment = process.env, root = proc
621
653
  throw error;
622
654
  }
623
655
  return {
656
+ hmrSources: client.hmrSources,
624
657
  forward: client.forward,
625
658
  render: client.render,
626
659
  upgrade: client.upgrade,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/template-inertia",
3
- "version": "0.4.11",
3
+ "version": "0.4.13",
4
4
  "description": "Inertia v3 server adapter for Dokebi: page JSON, Vite manifest assets and optional server-side rendering.",
5
5
  "keywords": [
6
6
  "dokebi",
@@ -61,7 +61,7 @@
61
61
  },
62
62
  "peerDependencies": {
63
63
  "@dokebi/core": "^0.4.2",
64
- "@dokebi/web": "^0.4.3",
64
+ "@dokebi/web": "^0.4.19",
65
65
  "fastify": "^5.12.7",
66
66
  "vue": "^3.5.0"
67
67
  },
@@ -77,7 +77,7 @@
77
77
  "dependencies": [
78
78
  {
79
79
  "name": "dokebi-web",
80
- "version": "^0.4.3"
80
+ "version": "^0.4.19"
81
81
  },
82
82
  {
83
83
  "name": "dokebi-session",
@@ -143,11 +143,11 @@
143
143
  ]
144
144
  },
145
145
  "devDependencies": {
146
- "@dokebi/i18n": "0.2.5",
147
- "@dokebi/session": "0.4.8",
148
- "@dokebi/web": "0.4.12",
149
- "@dokebi/websocket": "0.4.8",
150
- "@dokebi/websocket-hub": "0.4.3",
146
+ "@dokebi/i18n": "0.2.8",
147
+ "@dokebi/session": "0.4.9",
148
+ "@dokebi/web": "0.4.20",
149
+ "@dokebi/websocket": "0.4.9",
150
+ "@dokebi/websocket-hub": "0.4.5",
151
151
  "@inertiajs/vue3": "3.9.1",
152
152
  "vue": "3.5.44"
153
153
  },