@dokebi/template-inertia 0.4.23 → 0.4.25

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
@@ -298,8 +298,15 @@ A template can live apart from the app: a `views/<template>/` folder (Layout.vue
298
298
  - a missing, unreadable, changed, too large or incompatible bundle, one `verifyTemplate` refused, or one that fails to import: the template keeps its previous generation, or the app's pages when there is none (error `INERTIA_TEMPLATE_UNAVAILABLE` / `INERTIA_TEMPLATE_REJECTED`, once per `logRepeatWindowMs` per cause).
299
299
  - A bundle page whose server render throws or times out is set aside for this generation and the request renders again with the app's page (then the layout, if it still fails): error `INERTIA_TEMPLATE_PAGE_FAILED`. The next first HTMLs leave it out of the table, so the browser uses the app's page too; a new generation tries it again.
300
300
  - In the browser, a bundle page that cannot load (network, syntax) falls back to the app's page with a console warning.
301
- - **Logs:** info `INERTIA_TEMPLATE_LOADED` (app, template, name, version, buildId, previous, pages, rejectedPages, serverRendering, kept, ms), warn `INERTIA_TEMPLATE_PAGE_REJECTED`, info `INERTIA_TEMPLATE_REMOVED`, info `INERTIA_TEMPLATE_DEV_SKIPPED`.
301
+ - **Logs:** info `INERTIA_TEMPLATE_LOADED` (app, template, name, version, buildId, previous, pages, rejectedPages, serverRendering, kept, ms), warn `INERTIA_TEMPLATE_PAGE_REJECTED`, info `INERTIA_TEMPLATE_REMOVED`, info `INERTIA_TEMPLATE_DEV_SKIPPED`, error `INERTIA_TEMPLATE_LISTENER_FAILED` (D-0294). A refused or missing bundle's error says `the bundle in use stays` when an older generation still serves the template (0.4.24; before, it always said the app pages answer).
302
302
  - **Not under `dokebi dev`:** there the pages come from Vite, and bundles are not used (info `INERTIA_TEMPLATE_DEV_SKIPPED`); work on a template in the template repository.
303
+ - **The app reads what happened (0.4.24, [D-0294](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0294-template-bundle-state.md)).** The plugin's API (the value of `context.get(templateInertia)` in a plugin or module setup) has:
304
+ - `templateState(app?)`: every configured template (`templates.<app>.<template>`), or those of `app`, as this process serves it now, frozen: `{ app, template, path, state, name?, version?, buildId?, loadedAt?, rejectedPages, failure?, reason?, checkedAt? }`.
305
+ - `state` is `loaded` (a bundle serves it: its manifest's `name` and `version`, its `buildId`, `loadedAt`), `rejected` or `unavailable` (no bundle serves it and the app's pages answer; the last load was refused — `INERTIA_TEMPLATE_REJECTED`, or `INERTIA_TEMPLATE_UNVERIFIED` in production — or found no bundle, `INERTIA_TEMPLATE_UNAVAILABLE`; `reason` says why), or `default` (none serves it and none failed: not looked at yet, or this process uses no bundles — under `dokebi dev`, `dokebi describe`, or one that serves no pages; `reason` says which).
306
+ - `rejectedPages`: the pages of the bundle in use that the app's own pages answer for, each `{ page, reason, code, at }`: `INERTIA_TEMPLATE_PAGE_REJECTED` (your `verifyTemplate` refused it, with its reason) or `INERTIA_TEMPLATE_PAGE_FAILED` (its server render failed: `its server render failed: <message>`).
307
+ - `failure`: the last load that failed, `{ code, reason, at, buildId? }`, also while an older bundle still serves the template (then `state` stays `loaded` and the log says `the bundle in use stays`); a load that succeeds clears it.
308
+ - `onTemplateState((state, change) => { … })`: runs synchronously with the template's new state whenever it changes in this process: `change` is `loaded` (at start, at a settings reload, at a look of `templateCheckMs`), `failed`, `page-failed` (a page set aside at render) or `removed` (no longer configured; `state: 'default'`). Register it in setup to hear the loads of the start. A listener that throws is logged (error `INERTIA_TEMPLATE_LISTENER_FAILED`) and the others still run; a non-function is `INVALID_TEMPLATE_LISTENER`. It returns the removal.
309
+ - A page that fails to load in the browser (network, syntax) is not seen by the server, so it is in neither.
303
310
 
304
311
  **Screen words of a bundle (0.4.22, with @dokebi/i18n 0.2.10).** A template folder may hold `locales/<locale>/<namespace>.json` (the shape of `views/<template>/locales`, D-0282): `template build` copies them into the bundle (`locales/…`, hashed like the rest), and when the app loads the bundle they become the words of that template's pages, over the app's own template words, checked by the app's i18n (keys its catalogs have, the same placeholders, its locales). Words the app refuses leave the bundle in use with the words of before (warn `INERTIA_TEMPLATE_LOCALES_REJECTED`, with the reason); a new generation without words, or a template taken out of `templates`, takes them out. Without @dokebi/i18n they are not used (info `INERTIA_TEMPLATE_LOCALES_UNUSED`). An app on template-inertia before 0.4.22 refuses a bundle that holds `locales/`.
305
312
 
@@ -334,7 +341,8 @@ A template can live apart from the app: a `views/<template>/` folder (Layout.vue
334
341
  - **The host compares with the disk on a timer too (0.4.19, [D-0289](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0289-vite-host-rescans-and-env-records.md))**: FSEvents delivers edits seconds late (measured: 2.8 s median, 6 s at worst on an idle Mac; far more under load), so the comparison below also runs every `DOKEBI_DEV_RESCAN_MS` (the variable `dokebi dev` uses for src/, default 2000, `0` off, 250–600000; `.env` works, dev passes it on): an open page gets its HMR update within that time without a page load (info `INERTIA_VITE_WATCH_MISSED` with `trigger: 'timer'` when it found something; an empty pass says nothing). The module page tables follow the disk the same way: the files the worker read for a table (the app file, the module list, the definitions) and the `.vue` listing of its folders are compared and a difference reloads the browser (info `INERTIA_MODULE_PAGES_MISSED`). The filter of unchanged files also records the env files Vite restarts for (`.env`, `.env.local`, `.env.<mode>`, `.env.<mode>.local`, and the config's dependencies): a late event for one written before the start no longer restarts Vite (a request then under way got 504).
335
342
  - **Edits the watcher missed are read anyway (D-0283, 0.4.17)**: FSEvents can report an edit a minute late, or not before the next page load (a `git pull` that restarted the app while the host kept serving the old `.vue`, and the page broke on its new locales). The same records serve a comparison: when an app process connects (`trigger` `client`), before a server render (`ssr`) and when a page loads `<base>@vite/client` (`page`), the host compares every file Vite read with its state on disk. A file that changed is invalidated in every module graph at once and handed to Vite as the watcher's `change` (`unlink` when it is gone), so plugins, HMR updates and reloads run as for the watcher's own event, and the request that follows gets the file as it is; the watcher's late event then changes nothing and is dropped. Each find is info `INERTIA_VITE_WATCH_MISSED` (`trigger`, `files`, `sample` of at most 5, `compared`, `ms`). Open pages still get their immediate HMR from the watcher; the comparison guarantees that a reloaded page or a restarted app gets the files on disk.
336
343
  - **A module that does not compile answers 500, not 404 (0.4.23, [D-0292](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0292-vite-host-explains-module-404.md))**: in middleware mode Vite's error middleware logs a transform error, sends it to the open pages' overlay and calls `next()` without it, so the host answered an empty 404 (a `[@vue/compiler-sfc] Unresolvable type reference` looked like a missing page). The host keeps the error of each request (an error middleware in a `configureServer` post hook, before Vite's own) and answers it 500: error `INERTIA_VITE_MODULE_FAILED` with `url` and the whole `error`, and a `text/plain` body with the URL and Vite's message on this machine (`500 Internal Server Error\n` alone for a remote host, a `devHosts` tunnel). Vite still logs it and sends the overlay.
337
- - **A type added to a file a barrel re-exports reaches the pages (0.4.23, D-0292)**: `defineProps<X>()` resolves X through @vue/compiler-sfc's type scopes, cached per file; for `export * from './event'` the compiler copies the source file's types into the barrel's scope, and @vitejs/plugin-vue clears only the changed file. A new type in an existing file that a barrel re-exports was `Unresolvable type reference` in dev until the barrel changed or dev restarted (vue-tsc and the build passed). The Vite host (and `dokebi template preview`) now clears, on every change or removal of a `.ts`/`.tsx`/`.mts`/`.cts` file, the type cache of the files that `export *` or `export type *` from it — in its folder and each folder above it up to its package root (the nearest package.json), and their own re-exporters — through the vue/compiler-sfc plugin-vue resolves from the project root (debug `Vue type caches of re-exporting files cleared` with `barrels`). The host also registers a TypeScript with a JS API on that compiler, as `dokebiInertia()` does, so a vite.config without it resolves imported props types too.
344
+ - **A type added to a file a barrel re-exports reaches the pages (0.4.23, D-0292)**: `defineProps<X>()` resolves X through @vue/compiler-sfc's type scopes, cached per file; for `export * from './event'` the compiler copies the source file's types into the barrel's scope, and @vitejs/plugin-vue clears only the changed file. A new type in an existing file that a barrel re-exports was `Unresolvable type reference` in dev until the barrel changed or dev restarted (vue-tsc and the build passed). The Vite host (and `dokebi template preview`) now clears, on every change or removal of a `.ts`/`.tsx`/`.mts`/`.cts` file, the type cache of the files that `export *` or `export type *` from it — in its folder and each folder above it up to its package root (the nearest package.json), and their own re-exporters — through the vue/compiler-sfc plugin-vue resolves from the project root (debug `Vue type caches of re-exporting files cleared` with `barrels`). The host also registers a TypeScript with a JS API on that compiler, as `dokebiInertia()` does, so a vite.config without it resolves imported props types too. The type files that compiler reads (outside node_modules) join the host's comparison with the disk (D-0283, D-0289: the page load, app connect, server render and `DOKEBI_DEV_RESCAN_MS` timer), which before saw only the modules Vite loads: an edit of a type file the watcher reports late or never reaches the pages within that time too (info `INERTIA_VITE_WATCH_MISSED` names it). The host learns them by wrapping the compiler's file access (`script.fs`, through @vitejs/plugin-vue's public `api.options`): its own `fs` when the config gives one, else node:fs with the answers of TypeScript's `ts.sys`.
345
+ - **A props type changed by a checkout reaches the pages at once, and stays (0.4.25, [D-0295](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0295-vite-host-type-changes-after-checkout.md))**: after a `git merge --ff` of many files, a page kept the old props of a type a barrel re-exports until the type file and the page were touched (the dev compiler had rebuilt the barrel from the old cache of the changed file while it cleared the barrels, and kept it). The changed type file's own cache is now cleared first, before the barrels, so a page that compiles meanwhile (a server render, another page of the same checkout) reads the new types. And a request that finds changed type files in the comparison with the disk (app connect, server render, a page loading Vite's client) goes on only once Vite has cleared their caches and invalidated the pages compiled with them (at most 2 s; none with `server.hmr: false`): the first server render after a checkout has the new props, where it used to have the old ones until the next request (debug `Vite handled the changed type files before the request`).
338
346
  - **A module URL the host answers 404 says why (0.4.23, [D-0292](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0292-vite-host-explains-module-404.md))**: Vite turns `ERR_LOAD_URL` ("Failed to load url … (resolved id: …) in <importer>") into `next()` without the error, so a module it could not load answered an empty 404 and nothing was logged. Now, when a module request (`GET`/`HEAD` under the base with a module or style extension, `?import`, or `Sec-Fetch-Dest: script`) ends that way, the host asks Vite again in the same process and logs warn `INERTIA_VITE_NOT_LOADED` with `url`, `module` (the module URL without `t` and `import`), `root`, `file`, `exists` (with `missing`: `ENOENT`, `directory`, …), `readable`, `real` (when it is a link), `allowed` (Vite's `isFileLoadingAllowed`), `graph` (the module graph's entry for the URL: `id`, `file`, `stale` when its id names another file, `transformed`, `invalidatedAt`), `cause` (the error of one more `transformRequest`: the message Vite dropped, with its `code`) and `loadsNow`. Once per URL until it is served again; repeats are debug with `repeats`. Vite's static middleware serves a file that is there and allowed even when its transform fails, so an empty 404 means that this process saw the file missing or not allowed; when the diagnosis finds it there, readable and allowed after all (`retry: true`), the host invalidates the module, drops a URL entry whose id names another file and runs the request through Vite once more: the warning then says it was served after invalidating it, and `retried` is the status of that second answer. A page, a folder and a virtual `/@id/` URL keep the plain 404.
339
347
  - **Pre-bundled dependencies that load (D-0128, 0.4.4)**: Vite keeps what its dependency optimizer wrote (each dependency's file under `node_modules/.vite/deps` and the `?v=` hash pages get) in memory, and at start trusts `_metadata.json` whenever the lockfile and config hashes match; it never looks at the files again, and it answers a file that is gone with 504 "Outdated Optimize Dep". A folder changed under it (two Vite optimizers on one folder — two `dokebi dev` sessions, a host still closing while the next starts — or a reinstall) therefore left every page blank through app restarts and dev restarts, until `rm -rf node_modules/.vite`. The host now compares its optimizer's files and metadata hashes with the folder when it starts, whenever an app process connects (every app or worker start) and after it answered a 504; when they differ it removes the deps folder and restarts its Vite (warn `INERTIA_VITE_DEPS_STALE` with `trigger` `start`, `client` or `outdated`, `drift` `missing` or `rewritten`, and a sample of the missing files), and the app process is answered after the repair. Open pages reconnect HMR and reload; a new page load gets the new hashes. At most one repair per `devDepsRepairIntervalMs`; faster changes are reported with warn `INERTIA_VITE_DEPS_CHANGING`. The host records its pid in `<cacheDir>/.dokebi/vite-host.json` and warns `INERTIA_VITE_HOST_SHARED` when another live host recorded itself there (stop one of the two `dokebi dev`). App processes pass Vite's status text on (`504 Outdated Optimize Dep`).
340
348
  - SSR: the host runs `ssrLoadModule(<source entry>)` and `render(page)` per request. The app process asks on connections of its own (a render that waits never holds the connections module requests are forwarded on) and cuts the request at `ssr.timeoutMs`, so renders that never finish do not pile up on the host. The source entry is `ssr.entry` (for example `src/apps/admin/views/ssr.js`), otherwise `ssr.js` in the folder of `vite.entry`. When neither exists the start fails (`SSR_ENTRY_MISSING`).
@@ -399,6 +407,7 @@ A template can live apart from the app: a `views/<template>/` folder (Layout.vue
399
407
  | `TEMPLATE_BUILD_FAILED` | `InertiaError` | (`dokebi template build`, D-0291) the Vite build of a template failed, a page's server module could not be imported to read its `meta`, a `meta` is not JSON data or larger than 4 KiB, or the built bundle fails its own check; the original error is the `cause` (§4.3) |
400
408
  | `INVALID_TEMPLATE_SHARED` | `InertiaUsageError` | (D-0291) `templates.shared` of `dokebiInertia()` or `--shared` names something that is not a package name with an optional subpath, more than 64, two names that make one entry, or a module that cannot be resolved or imported from the project (§4.3) |
401
409
  | `INVALID_TEMPLATE_PREVIEW` | `InertiaUsageError` | (D-0291) `dokebi template preview`: the folder is outside the project or has no `Pages/**/*.vue`, or a `<Page>.preview.json` / `preview.json` is not the documented shape (§4.3) |
410
+ | `INVALID_TEMPLATE_LISTENER` | `InertiaUsageError` | (D-0294) `onTemplateState` was given something other than a function |
402
411
  | `INVALID_TEMPLATE_BUILD` | `InertiaUsageError` | (D-0291) `dokebi template build`: the folder is missing, outside the project or has no page, a page path is not a page name, the name or version is wrong, or `--out` is the project, the template folder, or a folder that holds files and no earlier bundle (§4.3) |
403
412
  | `INVALID_PRUNE` | `InertiaUsageError` | `pruneBuildFiles` without a manifest path, or an `olderThanMs`, `maxManifestBytes` or `now` that is not a whole number from 0 |
404
413
 
package/dist/errors.d.ts CHANGED
@@ -2,7 +2,7 @@ import { DokebiError, type DokebiErrorOptions } from '@dokebi/core';
2
2
  /** Codes of `InertiaError` (failures of setup, files and the page flow). */
3
3
  export type InertiaErrorCode = 'SSR_BUNDLE_MISSING' | 'SSR_BUNDLE_INVALID' | 'SSR_ENTRY_MISSING' | 'SSR_TIMEOUT' | 'VITE_MANIFEST_MISSING' | 'VITE_MANIFEST_INVALID' | 'VITE_DEV_MISSING' | 'VITE_DEV_UNAVAILABLE' | 'METHOD_NOT_ALLOWED' | 'CLOSED' | 'MODULE_PAGES_APP_MISSING' | 'MODULE_PAGES_FAILED' | 'TEMPLATE_BUILD_FAILED' | 'TEMPLATE_APP_UNKNOWN';
4
4
  /** Codes of `InertiaUsageError` (a wrong argument: a TypeError, as before 0.4.0). */
5
- export type InertiaUsageErrorCode = 'INVALID_ENTRY' | 'INVALID_SCOPE' | 'INVALID_RENDER' | 'INVALID_PROPS' | 'INVALID_URL' | 'INVALID_PROP_HELPER' | 'SSR_INVALID_RESULT' | 'INVALID_PRUNE' | 'INVALID_TEMPLATE_SHARED' | 'INVALID_TEMPLATE_BUILD' | 'INVALID_TEMPLATE_PREVIEW';
5
+ export type InertiaUsageErrorCode = 'INVALID_ENTRY' | 'INVALID_SCOPE' | 'INVALID_RENDER' | 'INVALID_PROPS' | 'INVALID_URL' | 'INVALID_PROP_HELPER' | 'SSR_INVALID_RESULT' | 'INVALID_PRUNE' | 'INVALID_TEMPLATE_SHARED' | 'INVALID_TEMPLATE_BUILD' | 'INVALID_TEMPLATE_PREVIEW' | 'INVALID_TEMPLATE_LISTENER';
6
6
  /** Failures of @dokebi/template-inertia; compare `code`, not the class. */
7
7
  export declare class InertiaError extends DokebiError<InertiaErrorCode> {
8
8
  constructor(code: InertiaErrorCode, message: string, options?: DokebiErrorOptions);
package/dist/errors.js CHANGED
@@ -25,6 +25,7 @@ const FIX = {
25
25
  INVALID_PRUNE: "pruneBuildFiles({ manifest: 'dist/.vite/manifest.json', olderThanMs?, dryRun?, maxManifestBytes?, now? }): a manifest path, and whole non-negative numbers.",
26
26
  INVALID_TEMPLATE_SHARED: "Give dokebiInertia({ templates: { shared } }) (and dokebi template build --shared) installed package names with an optional subpath, at most 64, such as ['@shop/sdk', '@shop/sdk/components'] (D-0291).",
27
27
  INVALID_TEMPLATE_PREVIEW: 'dokebi template preview <dir>: a template folder inside the project with Pages/**/*.vue; each <Page>.preview.json is an object of case name → props ({ "default": { … } }), and preview.json of the folder is { "shared": { … } }, both JSON data up to 1 MiB (D-0291).',
28
+ INVALID_TEMPLATE_LISTENER: 'onTemplateState((state, change) => { … }): a function, which runs synchronously whenever a template bundle loads, fails, has a page set aside or is no longer configured (D-0294).',
28
29
  INVALID_TEMPLATE_BUILD: 'dokebi template build <dir>: a folder with Layout.vue and/or Pages/**/*.vue inside the project, a template name (^[a-z][a-z0-9-]{0,31}$), a version (letters, digits, . + -) and an --out folder that is neither the project nor the template folder (D-0291).',
29
30
  };
30
31
  /** Failures of @dokebi/template-inertia; compare `code`, not the class. */
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { type Awaitable } from '@dokebi/core';
2
2
  import type { FastifyRequest } from 'fastify';
3
3
  import { type InertiaApi, type Props } from './responder.js';
4
- import { type VerifyTemplate } from './template-runtime.js';
4
+ import { type TemplateState, type TemplateStateListener, type VerifyTemplate } from './template-runtime.js';
5
5
  export type { InertiaBootFallback, InertiaBootMessages } from './boot-fallback.js';
6
6
  export { InertiaError, type InertiaErrorCode, InertiaUsageError, type InertiaUsageErrorCode, } from './errors.js';
7
7
  export type { InertiaHead, InertiaHeadAlternate, InertiaHeadMeta, } from './head.js';
@@ -111,6 +111,21 @@ export interface InertiaPluginApi extends InertiaApi {
111
111
  scope(options: InertiaScopeOptions): Promise<InertiaApi>;
112
112
  /** Server renders and render failures of every scope since start (zero without `ssr`). */
113
113
  ssrStats(): InertiaSsrStats;
114
+ /**
115
+ * D-0294: every configured template bundle (`templates.<app>.<template>`), or those of `app`, as
116
+ * this process serves it now: `state` (loaded, rejected, unavailable, default), the bundle in
117
+ * use (name, version, buildId, loadedAt), the pages the app's own pages answer for and why, and
118
+ * the last load that failed.
119
+ */
120
+ templateState(app?: string): readonly TemplateState[];
121
+ /**
122
+ * D-0294: `listener(state, change)` runs whenever a template's state changes in this process:
123
+ * a bundle loaded (at start, at a reload, at a look of `templateCheckMs`), a load that failed,
124
+ * a page set aside because its server render failed, a template no longer configured. It runs
125
+ * synchronously (a listener that throws is logged, INERTIA_TEMPLATE_LISTENER_FAILED). Register it
126
+ * in setup to get the loads of the start. Returns the removal.
127
+ */
128
+ onTemplateState(listener: TemplateStateListener): () => void;
114
129
  }
115
130
  /**
116
131
  * Assets read from a Vite build manifest at setup: the entry script, the CSS of the entry and
@@ -130,5 +145,5 @@ export interface InertiaViteOptions {
130
145
  * path that reads as another host (ISSUE-0006 A02); 0.4.3 has the view data point (D-0076 §5). A local descriptor instead of
131
146
  * '@dokebi/web/dependency' (whose range stays ^0.4.0 for the plugins that need nothing newer).
132
147
  */
133
- export type { TemplateVerifyInput, TemplateVerifyResult, VerifyTemplate, } from './template-runtime.js';
148
+ export type { TemplateChange, TemplateFailure, TemplatePageRefusal, TemplateState, TemplateStateListener, TemplateVerifyInput, TemplateVerifyResult, VerifyTemplate, } from './template-runtime.js';
134
149
  export declare const createPlugin: import("@dokebi/core").PluginFactory<InertiaPluginApi>;
package/dist/index.js CHANGED
@@ -1137,6 +1137,32 @@ class InertiaRuntime {
1137
1137
  ...root,
1138
1138
  render: rootRender,
1139
1139
  ssrStats: () => Object.freeze({ ...stats }),
1140
+ templateState: (app) => {
1141
+ if (templateRuntime)
1142
+ return templateRuntime.state(app);
1143
+ // No bundles in this process: every configured template answers with the app's pages.
1144
+ const reason = describing
1145
+ ? 'dokebi describe uses no bundle'
1146
+ : develop
1147
+ ? 'template bundles are not used under dokebi dev'
1148
+ : 'this process serves no pages';
1149
+ const configured = (this.#templateSettings ?? this.settings.templates).templates;
1150
+ return Object.entries(configured)
1151
+ .filter(([name]) => app === undefined || name === app)
1152
+ .flatMap(([name, templates]) => Object.entries(templates).map(([template, source]) => Object.freeze({
1153
+ app: name,
1154
+ template,
1155
+ path: source.path,
1156
+ state: 'default',
1157
+ rejectedPages: Object.freeze([]),
1158
+ reason,
1159
+ })));
1160
+ },
1161
+ onTemplateState: (listener) => {
1162
+ if (typeof listener !== 'function')
1163
+ throw new InertiaUsageError('INVALID_TEMPLATE_LISTENER', 'onTemplateState needs a function (state, change) => void');
1164
+ return templateRuntime ? templateRuntime.onState(listener) : () => undefined;
1165
+ },
1140
1166
  scope: async (options) => {
1141
1167
  const { shared: extra, publicShared: extraPublic, vite, ssr: ssrInput, sealed = false, app: appName, ...fields } = (options ?? {});
1142
1168
  // Audit r6: `app` goes into log records as it is, so it is checked like the other fields
@@ -1211,7 +1237,7 @@ class InertiaRuntime {
1211
1237
  }
1212
1238
  export const createPlugin = definePlugin({
1213
1239
  name: 'dokebi-template-inertia',
1214
- version: '0.4.23',
1240
+ version: '0.4.25',
1215
1241
  core: '^0.4.2',
1216
1242
  options,
1217
1243
  entry: parseEntry,
@@ -15,7 +15,7 @@ import { checkTemplateBundle, jsonValue, PAGE_META_MAX_BYTES, SHARED_DEFAULTS, S
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.23' };
18
+ const BUILDER = { name: 'dokebi-template-inertia', version: '0.4.25' };
19
19
  function defaultLogger() {
20
20
  return new ConsoleLogger({ level: 'info' }, { plugin: 'dokebi-template-inertia', process: 'template-build' });
21
21
  }
@@ -52,6 +52,55 @@ export interface TemplateAppBuild {
52
52
  /** `ssr.bundle`, when the app renders on the server. */
53
53
  readonly ssrBundle?: string;
54
54
  }
55
+ /** D-0294: why a page of a bundle is not used. */
56
+ export interface TemplatePageRefusal {
57
+ readonly page: string;
58
+ readonly reason: string;
59
+ /** PAGE_REJECTED: verifyTemplate refused it; PAGE_FAILED: its server render failed. */
60
+ readonly code: 'INERTIA_TEMPLATE_PAGE_REJECTED' | 'INERTIA_TEMPLATE_PAGE_FAILED';
61
+ /** When (Date.now()). */
62
+ readonly at: number;
63
+ }
64
+ /** D-0294: a load of a bundle that was not used. */
65
+ export interface TemplateFailure {
66
+ readonly code: 'INERTIA_TEMPLATE_UNAVAILABLE' | 'INERTIA_TEMPLATE_REJECTED' | 'INERTIA_TEMPLATE_UNVERIFIED';
67
+ readonly reason: string;
68
+ readonly at: number;
69
+ /** The buildId of the bundle that was refused, when its manifest was read. */
70
+ readonly buildId?: string;
71
+ }
72
+ /**
73
+ * D-0294: one template of one app as this process serves it.
74
+ * - `loaded`: a bundle serves the template (`buildId`, `version`; `failure` may still name a newer
75
+ * bundle that was refused while this one stayed).
76
+ * - `rejected` / `unavailable`: no bundle serves it, the app pages answer; the last load was
77
+ * refused (`INERTIA_TEMPLATE_REJECTED`, or `INERTIA_TEMPLATE_UNVERIFIED` in production) or found
78
+ * no bundle (`INERTIA_TEMPLATE_UNAVAILABLE`).
79
+ * - `default`: no bundle serves it and none failed: not looked at yet, or this process does not
80
+ * use bundles (`reason`: under dokebi dev, or not serving pages).
81
+ */
82
+ export interface TemplateState {
83
+ readonly app: string;
84
+ readonly template: string;
85
+ readonly path: string;
86
+ readonly state: 'loaded' | 'rejected' | 'unavailable' | 'default';
87
+ /** The bundle in use: its manifest's name and version, its buildId, when it was loaded. */
88
+ readonly name?: string;
89
+ readonly version?: string;
90
+ readonly buildId?: string;
91
+ readonly loadedAt?: number;
92
+ /** Pages of the bundle in use that the app's own pages answer for, and why. */
93
+ readonly rejectedPages: readonly TemplatePageRefusal[];
94
+ /** The last load that failed (cleared when a load succeeds). */
95
+ readonly failure?: TemplateFailure;
96
+ /** Why no bundle serves the template (failure's reason, or why bundles are not used here). */
97
+ readonly reason?: string;
98
+ /** The last look at the mount that found a change (a load, a refusal), Date.now(). */
99
+ readonly checkedAt?: number;
100
+ }
101
+ /** D-0294: what changed a template's state. */
102
+ export type TemplateChange = 'loaded' | 'failed' | 'page-failed' | 'removed';
103
+ export type TemplateStateListener = (state: TemplateState, change: TemplateChange) => void;
55
104
  interface PageUrls {
56
105
  readonly js: string;
57
106
  readonly css: readonly string[];
@@ -73,7 +122,13 @@ export declare class TemplateGeneration {
73
122
  readonly importMap: Readonly<Record<string, string>>;
74
123
  /** Pages the app's check refused. */
75
124
  readonly rejected: readonly string[];
125
+ /** D-0294: the refusals of `rejected`, with verifyTemplate's reasons. */
126
+ readonly rejectedWhy: readonly TemplatePageRefusal[];
76
127
  readonly setAside: Set<string>;
128
+ /** D-0294: why each page set aside at render was (and when). */
129
+ readonly setAsideWhy: Map<string, TemplatePageRefusal>;
130
+ /** D-0294: when this generation was loaded. */
131
+ readonly loadedAt: number;
77
132
  constructor(app: string, template: string, buildId: string, manifest: TemplateManifest,
78
133
  /** The checked copy in the cache. */
79
134
  dir: string,
@@ -82,11 +137,13 @@ export declare class TemplateGeneration {
82
137
  /** Accepted pages → their server modules (empty without server rendering). */
83
138
  server: ReadonlyMap<string, Readonly<Record<string, unknown>>>, importMap: Readonly<Record<string, string>>,
84
139
  /** Pages the app's check refused. */
85
- rejected: readonly string[]);
140
+ rejected: readonly string[],
141
+ /** D-0294: the refusals of `rejected`, with verifyTemplate's reasons. */
142
+ rejectedWhy?: readonly TemplatePageRefusal[]);
86
143
  /** The page table of the first HTML (JSON, without the pages set aside). */
87
144
  table(): string;
88
145
  /** Leaves `page` to the app's own page for the rest of this generation. */
89
- putAside(page: string): void;
146
+ putAside(page: string, reason?: string): void;
90
147
  /** The server module of `page`, unless it is set aside. */
91
148
  serverPage(page: string): Readonly<Record<string, unknown>> | undefined;
92
149
  }
@@ -127,6 +184,13 @@ export interface TemplateBundlesOptions {
127
184
  export declare class TemplateBundles {
128
185
  #private;
129
186
  constructor(options: TemplateBundlesOptions);
187
+ /**
188
+ * D-0294: every configured template of every app (or of `app`), as this process serves it now.
189
+ * Ordered by app, then template.
190
+ */
191
+ state(app?: string): TemplateState[];
192
+ /** D-0294: `listener` gets a template's new state whenever it changes; returns the removal. */
193
+ onState(listener: TemplateStateListener): () => void;
130
194
  /** The configured template names of an app. */
131
195
  templatesOf(app: string): readonly string[];
132
196
  /** An app's build, from its Inertia scope (the first scope of an app wins). */
@@ -40,7 +40,12 @@ export class TemplateGeneration {
40
40
  server;
41
41
  importMap;
42
42
  rejected;
43
+ rejectedWhy;
43
44
  setAside = new Set();
45
+ /** D-0294: why each page set aside at render was (and when). */
46
+ setAsideWhy = new Map();
47
+ /** D-0294: when this generation was loaded. */
48
+ loadedAt = Date.now();
44
49
  #table;
45
50
  constructor(app, template, buildId, manifest,
46
51
  /** The checked copy in the cache. */
@@ -50,7 +55,9 @@ export class TemplateGeneration {
50
55
  /** Accepted pages → their server modules (empty without server rendering). */
51
56
  server, importMap,
52
57
  /** Pages the app's check refused. */
53
- rejected) {
58
+ rejected,
59
+ /** D-0294: the refusals of `rejected`, with verifyTemplate's reasons. */
60
+ rejectedWhy = []) {
54
61
  this.app = app;
55
62
  this.template = template;
56
63
  this.buildId = buildId;
@@ -60,6 +67,7 @@ export class TemplateGeneration {
60
67
  this.server = server;
61
68
  this.importMap = importMap;
62
69
  this.rejected = rejected;
70
+ this.rejectedWhy = rejectedWhy;
63
71
  }
64
72
  /** The page table of the first HTML (JSON, without the pages set aside). */
65
73
  table() {
@@ -79,8 +87,15 @@ export class TemplateGeneration {
79
87
  return this.#table;
80
88
  }
81
89
  /** Leaves `page` to the app's own page for the rest of this generation. */
82
- putAside(page) {
90
+ putAside(page, reason = 'its server render failed') {
83
91
  this.setAside.add(page);
92
+ if (!this.setAsideWhy.has(page))
93
+ this.setAsideWhy.set(page, {
94
+ page,
95
+ reason: reason.slice(0, 500),
96
+ code: 'INERTIA_TEMPLATE_PAGE_FAILED',
97
+ at: Date.now(),
98
+ });
84
99
  this.#table = undefined;
85
100
  }
86
101
  /** The server module of `page`, unless it is set aside. */
@@ -189,6 +204,7 @@ export class TemplateBundles {
189
204
  #timer;
190
205
  #closed = false;
191
206
  #cacheRoot;
207
+ #listeners = new Set();
192
208
  constructor(options) {
193
209
  this.#logger = options.logger;
194
210
  this.#settings = options.settings;
@@ -216,6 +232,60 @@ export class TemplateBundles {
216
232
  },
217
233
  });
218
234
  }
235
+ /**
236
+ * D-0294: every configured template of every app (or of `app`), as this process serves it now.
237
+ * Ordered by app, then template.
238
+ */
239
+ state(app) {
240
+ const found = [];
241
+ for (const [name, templates] of Object.entries(this.#settings.templates)) {
242
+ if (app !== undefined && name !== app)
243
+ continue;
244
+ for (const [template, source] of Object.entries(templates)) {
245
+ const slot = this.#slots.get(`${name}/${template}`);
246
+ found.push(slot
247
+ ? stateOf(slot)
248
+ : { app: name, template, path: source.path, state: 'default', rejectedPages: [] });
249
+ }
250
+ }
251
+ return found.sort((a, b) => a.app === b.app ? (a.template < b.template ? -1 : 1) : a.app < b.app ? -1 : 1);
252
+ }
253
+ /** D-0294: `listener` gets a template's new state whenever it changes; returns the removal. */
254
+ onState(listener) {
255
+ this.#listeners.add(listener);
256
+ return () => {
257
+ this.#listeners.delete(listener);
258
+ };
259
+ }
260
+ /** Tells the listeners (a listener that throws is logged; the others still run). */
261
+ #changed(slot, change, removed = false) {
262
+ if (this.#listeners.size === 0)
263
+ return;
264
+ const state = removed
265
+ ? {
266
+ app: slot.app,
267
+ template: slot.template,
268
+ path: slot.path,
269
+ state: 'default',
270
+ rejectedPages: [],
271
+ reason: 'no longer configured',
272
+ }
273
+ : stateOf(slot);
274
+ for (const listener of this.#listeners) {
275
+ try {
276
+ listener(state, change);
277
+ }
278
+ catch (error) {
279
+ this.#logger.log('error', 'A template state listener failed', {
280
+ code: 'INERTIA_TEMPLATE_LISTENER_FAILED',
281
+ app: slot.app,
282
+ template: slot.template,
283
+ change,
284
+ error: describeError(error),
285
+ });
286
+ }
287
+ }
288
+ }
219
289
  /** The configured template names of an app. */
220
290
  templatesOf(app) {
221
291
  return Object.keys(this.#settings.templates[app] ?? {});
@@ -275,6 +345,8 @@ export class TemplateBundles {
275
345
  seen: undefined,
276
346
  loading: undefined,
277
347
  words: false,
348
+ failure: undefined,
349
+ checkedAt: undefined,
278
350
  };
279
351
  this.#slots.set(key, slot);
280
352
  }
@@ -294,6 +366,7 @@ export class TemplateBundles {
294
366
  app: slot.app,
295
367
  template: slot.template,
296
368
  });
369
+ this.#changed(slot, 'removed', true);
297
370
  }
298
371
  await Promise.all(work);
299
372
  }
@@ -313,6 +386,7 @@ export class TemplateBundles {
313
386
  if (mark === slot.seen)
314
387
  return;
315
388
  slot.seen = mark;
389
+ slot.checkedAt = Date.now();
316
390
  slot.loading = this.#load(slot).finally(() => {
317
391
  slot.loading = undefined;
318
392
  });
@@ -320,10 +394,23 @@ export class TemplateBundles {
320
394
  }
321
395
  #fail(slot, failure) {
322
396
  const code = failure instanceof Refused ? failure.code : 'INERTIA_TEMPLATE_UNAVAILABLE';
397
+ const buildId = failure instanceof Refused && typeof failure.data.buildId === 'string'
398
+ ? failure.data.buildId
399
+ : undefined;
400
+ slot.failure = {
401
+ code,
402
+ reason: failure.message.slice(0, 1000),
403
+ at: Date.now(),
404
+ ...(buildId === undefined ? {} : { buildId }),
405
+ };
406
+ this.#changed(slot, 'failed');
323
407
  const repeated = this.#repeat(`${code} ${slot.app} ${slot.template} ${failure.message}`);
324
408
  if (repeated === undefined)
325
409
  return;
326
- this.#logger.log('error', 'Template bundle not used; the app pages answer for this template', {
410
+ // The bundle in use (an older one) stays when a newer one is refused (D-0291 addendum 2).
411
+ this.#logger.log('error', slot.current
412
+ ? 'Template bundle not used; the bundle in use stays for this template'
413
+ : 'Template bundle not used; the app pages answer for this template', {
327
414
  code,
328
415
  app: slot.app,
329
416
  template: slot.template,
@@ -464,12 +551,15 @@ export class TemplateBundles {
464
551
  async #load(slot) {
465
552
  const begin = performance.now();
466
553
  const build = this.#apps.get(slot.app);
554
+ // The bundle under judgement, once its manifest was read (D-0294: the failure names it).
555
+ let refusing;
467
556
  try {
468
557
  if (!build)
469
558
  throw new Refused('INERTIA_TEMPLATE_REJECTED', `app ${slot.app} has no Inertia pages built with Vite (its inertia.vite) in this process`);
470
559
  const { dir, manifest, buildId, signature } = await this.#copy(slot);
471
560
  if (slot.current?.buildId === buildId)
472
561
  return;
562
+ refusing = buildId;
473
563
  const provided = await this.#provided(slot.app, build);
474
564
  const needed = Object.fromEntries(Object.entries(manifest.shared).filter(([module]) => provided.server !== undefined || !SERVER_ONLY_SHARED.includes(module)));
475
565
  const problems = sharedProblems(needed, provided.versions);
@@ -530,10 +620,19 @@ export class TemplateBundles {
530
620
  });
531
621
  }
532
622
  const refused = new Set();
623
+ const refusedWhy = [];
533
624
  for (const item of rejectPages) {
534
625
  if (typeof item?.page !== 'string' || !Object.hasOwn(manifest.pages, item.page))
535
626
  continue;
627
+ if (refused.has(item.page))
628
+ continue;
536
629
  refused.add(item.page);
630
+ refusedWhy.push({
631
+ page: item.page,
632
+ reason: String(item.reason ?? '').slice(0, 500),
633
+ code: 'INERTIA_TEMPLATE_PAGE_REJECTED',
634
+ at: Date.now(),
635
+ });
537
636
  this.#logger.log('warn', 'Template bundle page refused; the app page answers for it', {
538
637
  code: 'INERTIA_TEMPLATE_PAGE_REJECTED',
539
638
  app: slot.app,
@@ -580,9 +679,10 @@ export class TemplateBundles {
580
679
  const hasWords = Object.keys(manifest.files).some((file) => file.startsWith('locales/'));
581
680
  if (hasWords || slot.words)
582
681
  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]);
682
+ const generation = new TemplateGeneration(slot.app, slot.template, buildId, manifest, dir, pages, server, importMap, [...refused], refusedWhy);
584
683
  const previous = slot.current;
585
684
  slot.current = generation;
685
+ slot.failure = undefined;
586
686
  slot.kept.unshift(generation);
587
687
  const dropped = slot.kept.splice(Math.max(1, this.#settings.keep));
588
688
  this.#logger.log('info', 'Template bundle loaded; the next pages of its template use it', {
@@ -599,10 +699,13 @@ export class TemplateBundles {
599
699
  kept: slot.kept.map((kept) => kept.buildId),
600
700
  ms: Math.round(performance.now() - begin),
601
701
  });
702
+ this.#changed(slot, 'loaded');
602
703
  for (const old of dropped)
603
704
  await this.#prune(old);
604
705
  }
605
706
  catch (error) {
707
+ if (error instanceof Refused && refusing !== undefined && error.data.buildId === undefined)
708
+ error.data.buildId = refusing;
606
709
  this.#fail(slot, error);
607
710
  }
608
711
  }
@@ -683,6 +786,12 @@ export class TemplateBundles {
683
786
  const store = this.#store;
684
787
  const logger = this.#logger;
685
788
  const repeat = this.#repeat;
789
+ // D-0294: a page set aside changes the state of the template (its slot, while it is current).
790
+ const changed = (set) => {
791
+ const slot = this.#slots.get(`${set.app}/${set.template}`);
792
+ if (slot?.current === set)
793
+ this.#changed(slot, 'page-failed');
794
+ };
686
795
  return {
687
796
  version: `${baseVersion}+${generation.template}@${generation.buildId}`,
688
797
  generation,
@@ -718,8 +827,10 @@ export class TemplateBundles {
718
827
  const blame = used.has(page) && attempt === 0 ? [page] : [...used];
719
828
  if (blame.length === 0 || attempt === 2)
720
829
  throw error;
830
+ const why = error?.message ?? String(error);
721
831
  for (const key of blame)
722
- generation.putAside(key);
832
+ generation.putAside(key, `its server render failed: ${why}`);
833
+ changed(generation);
723
834
  const repeated = repeat(`page ${generation.app} ${generation.template} ${generation.buildId} ${blame.join(',')}`);
724
835
  if (repeated !== undefined)
725
836
  logger.log('error', 'Template bundle page failed to render; the app page answers for it', {
@@ -769,3 +880,35 @@ export class TemplateBundles {
769
880
  }));
770
881
  }
771
882
  }
883
+ /** D-0294: a slot as its state (frozen, for the app's own answers). */
884
+ function stateOf(slot) {
885
+ const current = slot.current;
886
+ const failure = slot.failure;
887
+ const base = {
888
+ app: slot.app,
889
+ template: slot.template,
890
+ path: slot.path,
891
+ ...(slot.checkedAt === undefined ? {} : { checkedAt: slot.checkedAt }),
892
+ ...(failure ? { failure: Object.freeze({ ...failure }) } : {}),
893
+ };
894
+ if (current)
895
+ return Object.freeze({
896
+ ...base,
897
+ state: 'loaded',
898
+ name: current.manifest.name,
899
+ version: current.manifest.version,
900
+ buildId: current.buildId,
901
+ loadedAt: current.loadedAt,
902
+ rejectedPages: Object.freeze([...current.rejectedWhy, ...current.setAsideWhy.values()]),
903
+ });
904
+ return Object.freeze({
905
+ ...base,
906
+ state: failure
907
+ ? failure.code === 'INERTIA_TEMPLATE_UNAVAILABLE'
908
+ ? 'unavailable'
909
+ : 'rejected'
910
+ : 'default',
911
+ rejectedPages: Object.freeze([]),
912
+ ...(failure ? { reason: failure.reason } : {}),
913
+ });
914
+ }
package/dist/vite-dev.js CHANGED
@@ -23,7 +23,7 @@ import { DependencyCache } from './vite-deps.js';
23
23
  import { ViteRequestErrors } from './vite-dev-errors.js';
24
24
  import { DEV_CLIENT_HEADER, dokebiDevFiles } from './vite-files.js';
25
25
  import { NotLoadedReporter } from './vite-not-loaded.js';
26
- import { vueTypeBarrels } from './vite-type-barrels.js';
26
+ import { TypeFileUpdates, vueTypeBarrels } from './vite-type-barrels.js';
27
27
  import { ServedFiles, staleEventFilter } from './vite-watch.js';
28
28
  import { registerVueTypeScript } from './vue-typescript.js';
29
29
  const { describeError } = diagnostics;
@@ -49,6 +49,11 @@ const HOST_PATH = '/__dokebi/vite-host';
49
49
  const SSR_PATH = `${HOST_PATH}/ssr`;
50
50
  /** Largest server-render request (the page JSON) the host reads. */
51
51
  const SSR_BODY_MAX_BYTES = 32 * 1024 * 1024;
52
+ /**
53
+ * D-0295: the longest a request waits for Vite to handle the type files a comparison found
54
+ * changed (clearing type caches takes milliseconds; Vite handles none for `server.hmr: false`).
55
+ */
56
+ const TYPE_SETTLE_MS = 2000;
52
57
  /** Loopback addresses of the host (a browser resolves `*.localhost` to either); never all. */
53
58
  const LOOPBACK_HOSTS = ['127.0.0.1', '::1'];
54
59
  /** Tries for a port that is free on both loopback addresses. */
@@ -265,6 +270,69 @@ export async function startViteHost(logger, root = process.cwd(), settings = {})
265
270
  sendJson(response, 500, { error: errorJson(error) });
266
271
  }
267
272
  };
273
+ /** Hands a request to Vite's middlewares, explaining what Vite answers nothing for. */
274
+ const serve = (request, response, server, cache) => {
275
+ // Vite answers 504 for a pre-bundled file it cannot serve: if the folder changed under it,
276
+ // re-optimize so the next page load gets files that exist (D-0128).
277
+ if (cache)
278
+ response.once('finish', () => {
279
+ if (response.statusCode === 504)
280
+ void cache.ensure('outdated').catch(report('deps'));
281
+ });
282
+ const url = String(request.url ?? '/');
283
+ const reporter = notLoaded;
284
+ if (reporter)
285
+ response.once('finish', () => reporter.served(url, request.method, response.statusCode));
286
+ server.middlewares(request, response, (error) => {
287
+ // D-0292: an error Vite's error middleware dropped (a module that does not compile)
288
+ // answers 500 with it, not an empty 404.
289
+ const failed = failures.take(request);
290
+ if ((error === undefined || error === null) && failed !== undefined && failed !== null) {
291
+ failures.answer(request, response, failed, url);
292
+ return;
293
+ }
294
+ // D-0292: a module URL Vite answers nothing for (it drops ERR_LOAD_URL) is explained, and
295
+ // run through Vite once more when the file is there and allowed.
296
+ const subject = reporter && (error === undefined || error === null) && !response.headersSent
297
+ ? reporter.subject(url, request.method, request.headers)
298
+ : undefined;
299
+ if (!reporter || !subject) {
300
+ viteFallthrough(response, error, report('vite'));
301
+ return;
302
+ }
303
+ void (async () => {
304
+ const diagnosis = await reporter.diagnose(subject);
305
+ if (!diagnosis.retry || response.headersSent) {
306
+ viteFallthrough(response, undefined, report('vite'));
307
+ reporter.report(diagnosis, response.statusCode);
308
+ return;
309
+ }
310
+ await reporter.refresh(subject, diagnosis);
311
+ request.url = url;
312
+ response.once('finish', () => reporter.report(diagnosis, response.statusCode));
313
+ server.middlewares(request, response, (again) => {
314
+ const failedAgain = failures.take(request);
315
+ if ((again === undefined || again === null) &&
316
+ failedAgain !== undefined &&
317
+ failedAgain !== null)
318
+ failures.answer(request, response, failedAgain, url);
319
+ else
320
+ viteFallthrough(response, again, report('vite'));
321
+ });
322
+ })().catch((failure) => {
323
+ report('not-loaded')(failure);
324
+ viteFallthrough(response, undefined, report('vite'));
325
+ });
326
+ });
327
+ };
328
+ // D-0295: a request that asked for the comparison goes on once Vite handled the type files it
329
+ // found changed (their caches cleared, the pages compiled with them invalidated).
330
+ const settle = (found) => {
331
+ const types = found.files.filter((file) => served.has(file, 'types'));
332
+ if (types.length === 0 || started?.config.server.hmr === false)
333
+ return Promise.resolve();
334
+ return typeUpdates.settled(types, TYPE_SETTLE_MS);
335
+ };
268
336
  const endpoint = await openLoopback(logger, (request, response) => {
269
337
  if (!keyMatches(expected, request.headers[VITE_HOST_KEY_HEADER])) {
270
338
  if (logger.isEnabled('debug'))
@@ -291,10 +359,12 @@ export async function startViteHost(logger, root = process.cwd(), settings = {})
291
359
  if (path === HOST_PATH && !browser) {
292
360
  // D-0283: files changed under Vite that the watcher has not reported (a `git pull` that
293
361
  // restarted the app) are read again before the app's pages are served.
294
- served.sweep('client');
362
+ const changed = settle(served.sweep('client'));
295
363
  // An app process connects (it started or restarted): it is answered once the pre-bundled
296
364
  // dependencies match what Vite serves, so its pages get hashes that load (D-0128).
297
- void (cache ? cache.ensure('client').catch(report('deps')) : Promise.resolve()).then(() => sendJson(response, 200, {
365
+ void changed
366
+ .then(() => (cache ? cache.ensure('client').catch(report('deps')) : undefined))
367
+ .then(() => sendJson(response, 200, {
298
368
  root,
299
369
  pid: process.pid,
300
370
  // D-0249: where Vite's client sends the HMR socket, when not to the page's origin.
@@ -303,71 +373,21 @@ export async function startViteHost(logger, root = process.cwd(), settings = {})
303
373
  }
304
374
  else if (path === SSR_PATH && request.method === 'POST' && !browser) {
305
375
  // D-0283: the server render reads the files as they are on disk.
306
- served.sweep('ssr');
307
- void ssr(request, response, server);
376
+ // D-0295: after Vite handled a changed type file, so the pages get the new props.
377
+ void settle(served.sweep('ssr')).then(() => ssr(request, response, server));
308
378
  }
309
- else {
379
+ else if (browser && path === `${server.config.base}@vite/client`) {
310
380
  // D-0283: a page loads Vite's client first; its modules then come as they are on disk.
311
- if (browser && path === `${server.config.base}@vite/client`)
312
- served.sweep('page');
313
- // Vite answers 504 for a pre-bundled file it cannot serve: if the folder changed under it,
314
- // re-optimize so the next page load gets files that exist (D-0128).
315
- if (cache)
316
- response.once('finish', () => {
317
- if (response.statusCode === 504)
318
- void cache.ensure('outdated').catch(report('deps'));
319
- });
320
- const url = String(request.url ?? '/');
321
- const reporter = notLoaded;
322
- if (reporter)
323
- response.once('finish', () => reporter.served(url, request.method, response.statusCode));
324
- server.middlewares(request, response, (error) => {
325
- // D-0292: an error Vite's error middleware dropped (a module that does not compile)
326
- // answers 500 with it, not an empty 404.
327
- const failed = failures.take(request);
328
- if ((error === undefined || error === null) && failed !== undefined && failed !== null) {
329
- failures.answer(request, response, failed, url);
330
- return;
331
- }
332
- // D-0292: a module URL Vite answers nothing for (it drops ERR_LOAD_URL) is explained, and
333
- // run through Vite once more when the file is there and allowed.
334
- const subject = reporter && (error === undefined || error === null) && !response.headersSent
335
- ? reporter.subject(url, request.method, request.headers)
336
- : undefined;
337
- if (!reporter || !subject) {
338
- viteFallthrough(response, error, report('vite'));
339
- return;
340
- }
341
- void (async () => {
342
- const diagnosis = await reporter.diagnose(subject);
343
- if (!diagnosis.retry || response.headersSent) {
344
- viteFallthrough(response, undefined, report('vite'));
345
- reporter.report(diagnosis, response.statusCode);
346
- return;
347
- }
348
- await reporter.refresh(subject, diagnosis);
349
- request.url = url;
350
- response.once('finish', () => reporter.report(diagnosis, response.statusCode));
351
- server.middlewares(request, response, (again) => {
352
- const failedAgain = failures.take(request);
353
- if ((again === undefined || again === null) &&
354
- failedAgain !== undefined &&
355
- failedAgain !== null)
356
- failures.answer(request, response, failedAgain, url);
357
- else
358
- viteFallthrough(response, again, report('vite'));
359
- });
360
- })().catch((failure) => {
361
- report('not-loaded')(failure);
362
- viteFallthrough(response, undefined, report('vite'));
363
- });
364
- });
381
+ void settle(served.sweep('page')).then(() => serve(request, response, server, cache));
365
382
  }
383
+ else
384
+ serve(request, response, server, cache);
366
385
  });
367
386
  // Events FSEvents still holds from before the start are no edits (D-0045 addendum 4); the same
368
387
  // records find the edits the watcher has not reported (D-0283).
369
388
  const served = new ServedFiles(logger);
370
389
  served.recordConfig(root);
390
+ const typeUpdates = new TypeFileUpdates(logger);
371
391
  const failures = new ViteRequestErrors(logger);
372
392
  // D-0292: the Vue compiler resolves imported props types through TypeScript's JS API (with
373
393
  // TypeScript 7 only @typescript/typescript6 has one). dokebiInertia() registers it; a vite.config
@@ -383,7 +403,11 @@ export async function startViteHost(logger, root = process.cwd(), settings = {})
383
403
  staleEventFilter(served, logger),
384
404
  dokebiDevFiles(logger),
385
405
  failures.plugin(),
386
- vueTypeBarrels(logger, root),
406
+ // D-0292: the type files the Vue compiler reads join the comparison with the disk, so an
407
+ // edit the watcher misses reaches the pages like one of a module Vite loads.
408
+ vueTypeBarrels(logger, root, { onTypeFile: (file) => served.record(file, 'types') }),
409
+ // D-0295: after plugin-vue, so a request can wait until Vite handled a changed type file.
410
+ typeUpdates.plugin(),
387
411
  ],
388
412
  server: {
389
413
  middlewareMode: true,
@@ -7,14 +7,79 @@ export declare class TypeBarrels {
7
7
  /** A TypeScript file changed or went away: clears the type caches of the files re-exporting it. */
8
8
  changed(file: string): Promise<string[]>;
9
9
  }
10
+ /** A module graph of Vite's (an environment's, or the one of Vite 5), as far as the waiter uses it. */
11
+ interface FileGraph {
12
+ onFileChange?(file: string): void;
13
+ }
14
+ /** The hot update context Vite gives `handleHotUpdate`, as far as the waiter uses it. */
15
+ interface SettledContext {
16
+ readonly file: string;
17
+ readonly modules: readonly {
18
+ readonly file?: string | null;
19
+ }[];
20
+ readonly server: {
21
+ readonly environments?: Record<string, {
22
+ readonly moduleGraph?: FileGraph;
23
+ }>;
24
+ readonly moduleGraph?: FileGraph;
25
+ };
26
+ }
27
+ /**
28
+ * D-0295: the host's comparison with the disk (D-0283) hands Vite a changed type file as the
29
+ * watcher's `change`. Vite then clears the type caches (vueTypeBarrels, plugin-vue) and plugin-vue
30
+ * names the pages compiled with that file, but all of that is asynchronous: the request that asked
31
+ * for the comparison (a server render, an app connecting, a page loading Vite's client) went on
32
+ * first, and the server render drew the page with the old props (the type changed, the page did
33
+ * not). `settled(files)` resolves once Vite's hot update of each file has passed plugin-vue (the
34
+ * plugin is `enforce: 'post'`). The pages plugin-vue named are invalidated there in every
35
+ * environment, so the request that waited compiles them again.
36
+ */
37
+ export declare class TypeFileUpdates {
38
+ #private;
39
+ constructor(logger: Logger);
40
+ /**
41
+ * Resolves true once Vite handled every file, false after `ms` (Vite runs no hot update for a
42
+ * config file or with `server.hmr: false`; the request then goes on as before).
43
+ */
44
+ settled(files: readonly string[], ms: number): Promise<boolean>;
45
+ /** The Vite plugin: the last `handleHotUpdate` of a file someone waits for. */
46
+ plugin(): {
47
+ name: 'dokebi-inertia:vue-type-settled';
48
+ enforce: 'post';
49
+ apply: 'serve';
50
+ handleHotUpdate(context: SettledContext): void;
51
+ };
52
+ }
53
+ /** The file access @vue/compiler-sfc takes as `script.fs` (what it reads type files through). */
54
+ export interface TypeFileSystem {
55
+ fileExists(file: string): boolean;
56
+ readFile(file: string): string | undefined;
57
+ realpath?(file: string): string;
58
+ }
10
59
  /** The part of Vite's dev server the plugin uses. */
11
60
  interface WatcherServer {
12
61
  readonly watcher?: {
13
62
  on(event: 'unlink', listener: (file: string) => void): unknown;
14
63
  };
64
+ readonly config?: {
65
+ readonly plugins?: readonly unknown[];
66
+ };
67
+ }
68
+ /**
69
+ * D-0292: the type files the compiler reads, told to `onTypeFile` (the Vite host records them for
70
+ * its comparison with the disk, D-0283 / D-0289, which before saw only the modules Vite loads). The
71
+ * compiler reads them through `script.fs` (its own, or TypeScript's `ts.sys`); the wrapper passes
72
+ * every call on to that, or to node:fs with the same answers when there is none.
73
+ */
74
+ export declare function recordingFileSystem(onTypeFile: (file: string) => void, base?: TypeFileSystem): TypeFileSystem;
75
+ export interface VueTypeBarrelsOptions {
76
+ /** The compiler's invalidateTypeCache (tests); by default vue/compiler-sfc of the project. */
77
+ readonly invalidate?: Invalidate;
78
+ /** Each type file (outside node_modules) the compiler reads (the host's comparison records it). */
79
+ readonly onTypeFile?: (file: string) => void;
15
80
  }
16
81
  /** The Vite plugin: clears the barrels before plugin-vue recompiles the components (`enforce: 'pre'`). */
17
- export declare function vueTypeBarrels(logger: Logger, root: string, invalidate?: Invalidate): {
82
+ export declare function vueTypeBarrels(logger: Logger, root: string, options?: VueTypeBarrelsOptions): {
18
83
  name: 'dokebi-inertia:vue-type-barrels';
19
84
  enforce: 'pre';
20
85
  apply: 'serve';
@@ -13,6 +13,7 @@
13
13
  // re-export them; it clears their type caches through the compiler plugin-vue uses (vue/compiler-sfc
14
14
  // resolved from the project root, as plugin-vue resolves it). plugin-vue then recompiles the
15
15
  // components that depend on the changed file, as before, and they see the new type.
16
+ import { readFileSync, realpathSync, statSync } from 'node:fs';
16
17
  import { readdir, readFile } from 'node:fs/promises';
17
18
  import { createRequire } from 'node:module';
18
19
  import { dirname, join, resolve } from 'node:path';
@@ -66,6 +67,13 @@ export class TypeBarrels {
66
67
  if (!invalidate)
67
68
  return [];
68
69
  const changed = posix(resolve(file));
70
+ // D-0295: the changed file itself first, before the walk below waits on the disk. A page that
71
+ // compiles during the walk (a server render, another page, other files of the same checkout)
72
+ // rebuilds a barrel just cleared from the cache of the file it re-exports: with that cache still
73
+ // old, the barrel kept the old types for good, also after plugin-vue cleared the file (shop dev,
74
+ // 2026-11-30, after a `git merge --ff` of 45 files). Each barrel is cleared after what it
75
+ // re-exports, so one rebuilt in between reads the new types.
76
+ invalidate(changed);
69
77
  const cleared = [];
70
78
  const seen = new Set([changed]);
71
79
  const queue = [changed];
@@ -143,9 +151,148 @@ export class TypeBarrels {
143
151
  return found;
144
152
  }
145
153
  }
154
+ /**
155
+ * D-0295: the host's comparison with the disk (D-0283) hands Vite a changed type file as the
156
+ * watcher's `change`. Vite then clears the type caches (vueTypeBarrels, plugin-vue) and plugin-vue
157
+ * names the pages compiled with that file, but all of that is asynchronous: the request that asked
158
+ * for the comparison (a server render, an app connecting, a page loading Vite's client) went on
159
+ * first, and the server render drew the page with the old props (the type changed, the page did
160
+ * not). `settled(files)` resolves once Vite's hot update of each file has passed plugin-vue (the
161
+ * plugin is `enforce: 'post'`). The pages plugin-vue named are invalidated there in every
162
+ * environment, so the request that waited compiles them again.
163
+ */
164
+ export class TypeFileUpdates {
165
+ #logger;
166
+ #waiting = new Map();
167
+ constructor(logger) {
168
+ this.#logger = logger;
169
+ }
170
+ /**
171
+ * Resolves true once Vite handled every file, false after `ms` (Vite runs no hot update for a
172
+ * config file or with `server.hmr: false`; the request then goes on as before).
173
+ */
174
+ settled(files, ms) {
175
+ const keys = [...new Set(files.map((file) => posix(resolve(file))))];
176
+ if (keys.length === 0)
177
+ return Promise.resolve(true);
178
+ const begin = performance.now();
179
+ return new Promise((answer) => {
180
+ let left = keys.length;
181
+ let over = false;
182
+ const entries = [];
183
+ const finish = (handled) => {
184
+ if (over)
185
+ return;
186
+ over = true;
187
+ clearTimeout(timer);
188
+ for (const [key, done] of entries)
189
+ this.#drop(key, done);
190
+ const fields = { files: keys.length, ms: Math.round(performance.now() - begin) };
191
+ if (!handled)
192
+ this.#logger.log('debug', 'Vite dev host went on before Vite handled every changed type file', { ...fields, left });
193
+ else if (this.#logger.isEnabled('debug'))
194
+ this.#logger.log('debug', 'Vite handled the changed type files before the request', fields);
195
+ answer(handled);
196
+ };
197
+ const timer = setTimeout(() => finish(false), ms);
198
+ for (const key of keys) {
199
+ const done = () => {
200
+ this.#drop(key, done);
201
+ left--;
202
+ if (left === 0)
203
+ finish(true);
204
+ };
205
+ entries.push([key, done]);
206
+ let waiting = this.#waiting.get(key);
207
+ if (!waiting) {
208
+ waiting = new Set();
209
+ this.#waiting.set(key, waiting);
210
+ }
211
+ waiting.add(done);
212
+ }
213
+ });
214
+ }
215
+ #drop(key, done) {
216
+ const waiting = this.#waiting.get(key);
217
+ if (!waiting)
218
+ return;
219
+ waiting.delete(done);
220
+ if (waiting.size === 0)
221
+ this.#waiting.delete(key);
222
+ }
223
+ /** The Vite plugin: the last `handleHotUpdate` of a file someone waits for. */
224
+ plugin() {
225
+ return {
226
+ name: 'dokebi-inertia:vue-type-settled',
227
+ enforce: 'post',
228
+ apply: 'serve',
229
+ handleHotUpdate: (context) => {
230
+ const key = posix(resolve(context.file));
231
+ const waiting = this.#waiting.get(key);
232
+ if (!waiting)
233
+ return;
234
+ // The pages compiled with the file (plugin-vue added them): Vite invalidates them only
235
+ // after every plugin, and the waiting request must not get them as compiled before.
236
+ const graphs = context.server.environments
237
+ ? Object.values(context.server.environments).map((environment) => environment.moduleGraph)
238
+ : [context.server.moduleGraph];
239
+ const pages = new Set();
240
+ for (const module of context.modules)
241
+ if (typeof module.file === 'string' && posix(module.file) !== key)
242
+ pages.add(module.file);
243
+ for (const page of pages)
244
+ for (const graph of graphs)
245
+ graph?.onFileChange?.(page);
246
+ if (this.#logger.isEnabled('debug'))
247
+ this.#logger.log('debug', 'Vite handled a changed type file a request waits for', {
248
+ file: key,
249
+ pages: [...pages],
250
+ });
251
+ for (const done of [...waiting])
252
+ done();
253
+ },
254
+ };
255
+ }
256
+ }
257
+ /** What TypeScript's `ts.sys` gives the compiler, on node:fs (no TypeScript needed). */
258
+ const NODE_FS = {
259
+ fileExists: (file) => statSync(file, { throwIfNoEntry: false })?.isFile() === true,
260
+ readFile: (file) => {
261
+ try {
262
+ return readFileSync(file, 'utf8');
263
+ }
264
+ catch (error) {
265
+ // As ts.sys.readFile: a file that cannot be read is undefined, and the compiler says which.
266
+ if (error.code === 'ENOENT')
267
+ return undefined;
268
+ throw error;
269
+ }
270
+ },
271
+ realpath: (file) => realpathSync.native(file),
272
+ };
273
+ /**
274
+ * D-0292: the type files the compiler reads, told to `onTypeFile` (the Vite host records them for
275
+ * its comparison with the disk, D-0283 / D-0289, which before saw only the modules Vite loads). The
276
+ * compiler reads them through `script.fs` (its own, or TypeScript's `ts.sys`); the wrapper passes
277
+ * every call on to that, or to node:fs with the same answers when there is none.
278
+ */
279
+ export function recordingFileSystem(onTypeFile, base = NODE_FS) {
280
+ const realpath = base.realpath;
281
+ return {
282
+ fileExists: (file) => base.fileExists(file),
283
+ readFile: (file) => {
284
+ const text = base.readFile(file);
285
+ if (text !== undefined && !posix(file).includes('/node_modules/'))
286
+ onTypeFile(file);
287
+ return text;
288
+ },
289
+ // Only when the base has one: TypeScript's module resolution treats links by it.
290
+ ...(realpath ? { realpath: (file) => realpath.call(base, file) } : {}),
291
+ };
292
+ }
146
293
  /** The Vite plugin: clears the barrels before plugin-vue recompiles the components (`enforce: 'pre'`). */
147
- export function vueTypeBarrels(logger, root, invalidate) {
148
- const barrels = new TypeBarrels(logger, root, invalidate);
294
+ export function vueTypeBarrels(logger, root, options = {}) {
295
+ const barrels = new TypeBarrels(logger, root, options.invalidate);
149
296
  const clear = (file) => barrels.changed(file).then(() => undefined, (error) => {
150
297
  logger.log('error', 'Vue type barrels could not be cleared', {
151
298
  code: 'INERTIA_VUE_TYPE_BARRELS_FAILED',
@@ -159,6 +306,27 @@ export function vueTypeBarrels(logger, root, invalidate) {
159
306
  apply: 'serve',
160
307
  configureServer(server) {
161
308
  server.watcher?.on('unlink', (file) => void clear(file));
309
+ const onTypeFile = options.onTypeFile;
310
+ if (!onTypeFile)
311
+ return;
312
+ // After every configResolved (plugin-vue sets its options there): its public api.options.
313
+ const vue = server.config?.plugins?.find((plugin) => plugin?.name === 'vite:vue' &&
314
+ plugin.api !== undefined);
315
+ if (!vue?.api) {
316
+ logger.log('debug', 'Vue type files are not recorded: no @vitejs/plugin-vue with an api');
317
+ return;
318
+ }
319
+ const current = vue.api.options;
320
+ vue.api.options = {
321
+ ...current,
322
+ script: {
323
+ ...current.script,
324
+ fs: recordingFileSystem(onTypeFile, current.script?.fs ?? NODE_FS),
325
+ },
326
+ };
327
+ logger.log('debug', 'Vue type files the compiler reads are recorded for the comparison', {
328
+ own: current.script?.fs !== undefined,
329
+ });
162
330
  },
163
331
  // Awaited by Vite before the next plugin's handleHotUpdate (plugin-vue's).
164
332
  handleHotUpdate: (context) => clear(context.file),
@@ -65,6 +65,8 @@ export declare class ServedFiles {
65
65
  mode?: string;
66
66
  configFileDependencies?: readonly string[];
67
67
  }): void;
68
+ /** Whether `file` has a record for `environment` (D-0295: `types`, the files Vue's compiler read). */
69
+ has(file: string, environment: string): boolean;
68
70
  /** Whether an event for `file` is no change (dropped); a change updates the records. */
69
71
  stale(file: string, event: string): boolean;
70
72
  /** The Vite whose module graphs and watcher a sweep uses (Vite's `configureServer`). */
@@ -116,6 +116,10 @@ export class ServedFiles {
116
116
  for (const file of config.configFileDependencies ?? [])
117
117
  this.record(file, STARTUP);
118
118
  }
119
+ /** Whether `file` has a record for `environment` (D-0295: `types`, the files Vue's compiler read). */
120
+ has(file, environment) {
121
+ return this.#records.get(normal(file))?.has(environment) === true;
122
+ }
119
123
  /** Whether an event for `file` is no change (dropped); a change updates the records. */
120
124
  stale(file, event) {
121
125
  const path = normal(file);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/template-inertia",
3
- "version": "0.4.23",
3
+ "version": "0.4.25",
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",
@@ -156,7 +156,7 @@
156
156
  "@dokebi/session": "0.4.11",
157
157
  "@dokebi/web": "0.4.27",
158
158
  "@dokebi/websocket": "0.4.10",
159
- "@dokebi/websocket-hub": "0.4.5",
159
+ "@dokebi/websocket-hub": "0.4.6",
160
160
  "@inertiajs/vue3": "3.9.1",
161
161
  "vue": "3.5.44"
162
162
  },