@dokebi/template-inertia 0.4.22 → 0.4.23

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
@@ -333,6 +333,9 @@ A template can live apart from the app: a `views/<template>/` folder (Layout.vue
333
333
  - **The drain ends the open HMR sockets (0.4.18, [D-0288](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0288-dev-kills-after-the-apps-stop-deadlines.md))**: the Vite host outlives a `dokebi dev` restart, so nothing else closes a socket the app joined to it; next to @dokebi/websocket each one is a hijacked request web's drain waits for, and an open page held every restart to the drain deadline (center dev: `Web drain started pending: 2` for one tab, then the process was killed). On drain they end (debug `INERTIA_VITE_HMR_ENDED` with the count) and an HMR upgrade after that is answered 503; the page's Vite client reconnects to the next app and reloads, as it did when the process ended.
334
334
  - **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
335
  - **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
+ - **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.
338
+ - **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.
336
339
  - **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`).
337
340
  - 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`).
338
341
  - Without Vite in the project the start fails (`VITE_DEV_MISSING`; `npm install --save-dev vite`).
package/dist/index.js CHANGED
@@ -1211,7 +1211,7 @@ class InertiaRuntime {
1211
1211
  }
1212
1212
  export const createPlugin = definePlugin({
1213
1213
  name: 'dokebi-template-inertia',
1214
- version: '0.4.22',
1214
+ version: '0.4.23',
1215
1215
  core: '^0.4.2',
1216
1216
  options,
1217
1217
  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.22' };
18
+ const BUILDER = { name: 'dokebi-template-inertia', version: '0.4.23' };
19
19
  function defaultLogger() {
20
20
  return new ConsoleLogger({ level: 'info' }, { plugin: 'dokebi-template-inertia', process: 'template-build' });
21
21
  }
@@ -17,6 +17,7 @@ import { ConsoleLogger } from '@dokebi/core';
17
17
  import { InertiaError, InertiaUsageError } from './errors.js';
18
18
  import { packageEntry, templatePages } from './template-build.js';
19
19
  import { jsonValue, TEMPLATE_PAGE } from './template-bundle.js';
20
+ import { vueTypeBarrels } from './vite-type-barrels.js';
20
21
  import { registerVueTypeScript } from './vue-typescript.js';
21
22
  /** Where a page is drawn: `/__dokebi/preview/<page>?case=<case>`. */
22
23
  export const PREVIEW_PREFIX = '/__dokebi/preview/';
@@ -307,6 +308,8 @@ await createInertiaApp({
307
308
  }),
308
309
  ]
309
310
  : []),
311
+ // D-0292: a type added to a file a barrel re-exports reaches the pages without a restart.
312
+ ...(vue ? [vueTypeBarrels(logger, root)] : []),
310
313
  plugin,
311
314
  ],
312
315
  server: { port: options.port ?? 5180, host: options.host ?? '127.0.0.1', strictPort: false },
@@ -0,0 +1,41 @@
1
+ import type { Logger } from '@dokebi/core';
2
+ type Next = (error?: unknown) => void;
3
+ /** The part of Vite's dev server the plugin uses. */
4
+ interface MiddlewaresShape {
5
+ readonly middlewares: {
6
+ use(handler: (error: unknown, request: object, response: unknown, next: Next) => void): unknown;
7
+ };
8
+ }
9
+ /** The part of a request the answer reads. */
10
+ export interface FailedRequest {
11
+ readonly headers: Readonly<Record<string, string | string[] | undefined>>;
12
+ readonly socket?: {
13
+ readonly remoteAddress?: string | undefined;
14
+ };
15
+ }
16
+ /** The part of a response the answer writes. */
17
+ export interface FailedResponse {
18
+ statusCode: number;
19
+ readonly headersSent: boolean;
20
+ setHeader(name: string, value: string): unknown;
21
+ end(body?: string): unknown;
22
+ }
23
+ /** The errors Vite's middlewares met, per request, until the host answers. */
24
+ export declare class ViteRequestErrors {
25
+ #private;
26
+ constructor(logger: Logger);
27
+ /** The Vite plugin that keeps each request's error before Vite's error middleware drops it. */
28
+ plugin(): {
29
+ name: string;
30
+ configureServer(server: MiddlewaresShape): () => void;
31
+ };
32
+ /** The error Vite met for `request` (and forgets it), or undefined. */
33
+ take(request: object): unknown;
34
+ /**
35
+ * Answers 500 for a request Vite failed on, logged at error with `INERTIA_VITE_MODULE_FAILED`.
36
+ * This machine gets the message (the overlay shows it too); a remote host (a `devHosts` tunnel)
37
+ * gets no paths.
38
+ */
39
+ answer(request: FailedRequest, response: FailedResponse, error: unknown, url: string): void;
40
+ }
41
+ export {};
@@ -0,0 +1,64 @@
1
+ import { diagnostics } from '@dokebi/core/libraries';
2
+ import { isRemoteRequest } from './vite-files.js';
3
+ const { describeError } = diagnostics;
4
+ /** The longest URL text a record keeps. */
5
+ const URL_TEXT = 500;
6
+ /** The errors Vite's middlewares met, per request, until the host answers. */
7
+ export class ViteRequestErrors {
8
+ #logger;
9
+ #errors = new WeakMap();
10
+ constructor(logger) {
11
+ this.#logger = logger;
12
+ }
13
+ /** The Vite plugin that keeps each request's error before Vite's error middleware drops it. */
14
+ plugin() {
15
+ const errors = this.#errors;
16
+ return {
17
+ name: 'dokebi-inertia:dev-errors',
18
+ configureServer(server) {
19
+ // Returned: runs after Vite's internal middlewares, before its error middleware.
20
+ return () => {
21
+ server.middlewares.use(function keepViteError(error, request, _response, next) {
22
+ errors.set(request, error);
23
+ next(error);
24
+ });
25
+ };
26
+ },
27
+ };
28
+ }
29
+ /** The error Vite met for `request` (and forgets it), or undefined. */
30
+ take(request) {
31
+ const error = this.#errors.get(request);
32
+ this.#errors.delete(request);
33
+ return error;
34
+ }
35
+ /**
36
+ * Answers 500 for a request Vite failed on, logged at error with `INERTIA_VITE_MODULE_FAILED`.
37
+ * This machine gets the message (the overlay shows it too); a remote host (a `devHosts` tunnel)
38
+ * gets no paths.
39
+ */
40
+ answer(request, response, error, url) {
41
+ url = url.slice(0, URL_TEXT);
42
+ this.#logger.log('error', 'Vite dev host could not serve a module', {
43
+ code: 'INERTIA_VITE_MODULE_FAILED',
44
+ url,
45
+ error: describeError(error),
46
+ });
47
+ if (response.headersSent) {
48
+ response.end();
49
+ return;
50
+ }
51
+ const remote = isRemoteRequest(request.headers, request.socket?.remoteAddress);
52
+ response.statusCode = 500;
53
+ response.setHeader('content-type', 'text/plain; charset=utf-8');
54
+ response.setHeader('cache-control', 'no-store');
55
+ if (remote) {
56
+ response.end('500 Internal Server Error\n');
57
+ return;
58
+ }
59
+ // Vite and its plugins throw Rollup-style error objects as well as Errors.
60
+ const text = error?.message;
61
+ const message = typeof text === 'string' ? text : String(error);
62
+ response.end(`500 Internal Server Error (Vite): ${url}\n${message}\n`);
63
+ }
64
+ }
package/dist/vite-dev.js CHANGED
@@ -20,8 +20,12 @@ import { diagnostics } from '@dokebi/core/libraries';
20
20
  import { RESCAN_VARIABLE, rescanInterval } from './dev-rescan.js';
21
21
  import { InertiaError } from './errors.js';
22
22
  import { DependencyCache } from './vite-deps.js';
23
+ import { ViteRequestErrors } from './vite-dev-errors.js';
23
24
  import { DEV_CLIENT_HEADER, dokebiDevFiles } from './vite-files.js';
25
+ import { NotLoadedReporter } from './vite-not-loaded.js';
26
+ import { vueTypeBarrels } from './vite-type-barrels.js';
24
27
  import { ServedFiles, staleEventFilter } from './vite-watch.js';
28
+ import { registerVueTypeScript } from './vue-typescript.js';
25
29
  const { describeError } = diagnostics;
26
30
  export const viteDevRequested = () => process.env.DOKEBI_VITE_DEV === '1';
27
31
  /**
@@ -233,6 +237,7 @@ export async function startViteHost(logger, root = process.cwd(), settings = {})
233
237
  const expected = Buffer.from(key);
234
238
  let started;
235
239
  let deps;
240
+ let notLoaded;
236
241
  const report = (operation) => (error) => logger.log('error', 'Vite dev host request failed', {
237
242
  code: 'INERTIA_VITE_HOST_FAILED',
238
243
  operation,
@@ -312,19 +317,74 @@ export async function startViteHost(logger, root = process.cwd(), settings = {})
312
317
  if (response.statusCode === 504)
313
318
  void cache.ensure('outdated').catch(report('deps'));
314
319
  });
315
- server.middlewares(request, response, (error) => viteFallthrough(response, error, report('vite')));
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
+ });
316
365
  }
317
366
  });
318
367
  // Events FSEvents still holds from before the start are no edits (D-0045 addendum 4); the same
319
368
  // records find the edits the watcher has not reported (D-0283).
320
369
  const served = new ServedFiles(logger);
321
370
  served.recordConfig(root);
371
+ const failures = new ViteRequestErrors(logger);
372
+ // D-0292: the Vue compiler resolves imported props types through TypeScript's JS API (with
373
+ // TypeScript 7 only @typescript/typescript6 has one). dokebiInertia() registers it; a vite.config
374
+ // without it got none, and every `defineProps<Imported>()` failed in dev.
375
+ registerVueTypeScript(root, logger);
322
376
  try {
323
377
  started = await vite.createServer({
324
378
  root,
325
379
  appType: 'custom',
326
380
  // D-0129: the dev file policy for a vite.config without dokebiInertia() (which carries it).
327
- plugins: [staleEventFilter(served, logger), dokebiDevFiles(logger)],
381
+ // D-0292: errors Vite's error middleware would drop; Vue type caches of re-exporting files.
382
+ plugins: [
383
+ staleEventFilter(served, logger),
384
+ dokebiDevFiles(logger),
385
+ failures.plugin(),
386
+ vueTypeBarrels(logger, root),
387
+ ],
328
388
  server: {
329
389
  middlewareMode: true,
330
390
  // Hosts are checked by the dev routes of the plugin (see index.ts) and HTTP needs the key,
@@ -362,6 +422,7 @@ export async function startViteHost(logger, root = process.cwd(), settings = {})
362
422
  throw error;
363
423
  }
364
424
  deps = cache;
425
+ notLoaded = new NotLoadedReporter(logger, server, vite.isFileLoadingAllowed);
365
426
  // D-0289: the same comparison every DOKEBI_DEV_RESCAN_MS (2 s), so an edit the watcher reports
366
427
  // late (FSEvents: seconds, a minute when fseventsd is busy) reaches HMR and the next request
367
428
  // within that time, without a page load. A sweep stats the files Vite read (a few ms for a
@@ -0,0 +1,91 @@
1
+ import type { Logger } from '@dokebi/core';
2
+ /** A module of Vite's graph, as far as the diagnosis reads it. */
3
+ interface ModuleShape {
4
+ readonly id?: string | null;
5
+ readonly file?: string | null;
6
+ readonly url?: string;
7
+ readonly transformResult?: unknown;
8
+ readonly lastInvalidationTimestamp?: number;
9
+ }
10
+ interface GraphShape {
11
+ getModuleByUrl(url: string): Promise<ModuleShape | undefined> | ModuleShape | undefined;
12
+ invalidateModule(module: never): void;
13
+ readonly urlToModuleMap?: Map<string, unknown>;
14
+ }
15
+ /** The part of Vite's dev server the diagnosis uses (structural: no Vite types here). */
16
+ export interface NotLoadedServer {
17
+ readonly config: {
18
+ readonly root: string;
19
+ readonly base: string;
20
+ };
21
+ readonly environments?: {
22
+ readonly client?: {
23
+ readonly moduleGraph?: GraphShape;
24
+ transformRequest?(url: string): Promise<unknown>;
25
+ };
26
+ };
27
+ }
28
+ /** Vite's own check (`import { isFileLoadingAllowed } from 'vite'`), when this Vite exports it. */
29
+ export type LoadingCheck = (config: never, file: string) => boolean;
30
+ /** A request that may be a module Vite failed to load. */
31
+ export interface NotLoadedSubject {
32
+ /** The request URL as the browser sent it (with the base, without the host). */
33
+ readonly url: string;
34
+ /** The module URL Vite looks up: the base removed, decoded, without `t` and `import`. */
35
+ readonly module: string;
36
+ /** The file it names (absolute), when it names one (`/@fs/…` or a path under the root). */
37
+ readonly file: string | undefined;
38
+ }
39
+ /** What this process sees for a module URL that Vite answered 404. */
40
+ export interface NotLoadedDiagnosis {
41
+ readonly url: string;
42
+ readonly module: string;
43
+ readonly root: string;
44
+ readonly file?: string;
45
+ /** `file` is a regular file here. */
46
+ readonly exists: boolean;
47
+ /** Why the stat failed (ENOENT, EACCES, …), or `directory` / `other` for a non-file. */
48
+ readonly missing?: string;
49
+ readonly readable?: boolean;
50
+ /** The real path, when it differs from `file` (a link). */
51
+ readonly real?: string;
52
+ /** Vite's isFileLoadingAllowed for `file`; absent when this Vite does not export it. */
53
+ readonly allowed?: boolean;
54
+ /** The module graph's entry for the URL, if any. */
55
+ readonly graph?: {
56
+ readonly id: string | null;
57
+ readonly file: string | null;
58
+ /** The entry's id names another file than the URL. */
59
+ readonly stale: boolean;
60
+ readonly transformed: boolean;
61
+ readonly invalidatedAt?: number;
62
+ };
63
+ /** The error of one more transformRequest: the message Vite dropped (`ERR_LOAD_URL` …). */
64
+ readonly cause?: {
65
+ readonly code?: string;
66
+ readonly message: string;
67
+ };
68
+ /** One more transformRequest produced the module (Vite's state changed since its answer). */
69
+ readonly loadsNow?: boolean;
70
+ /** The file is there, readable and allowed: the request goes through Vite once more. */
71
+ readonly retry: boolean;
72
+ }
73
+ /** Why a module URL answered 404, logged once per URL until it is served again. */
74
+ export declare class NotLoadedReporter {
75
+ #private;
76
+ constructor(logger: Logger, server: NotLoadedServer, allowed?: LoadingCheck);
77
+ /** The module request behind `url`, or undefined for anything else (a page, a folder, a virtual id). */
78
+ subject(url: string, method: string | undefined, headers: Readonly<Record<string, string | string[] | undefined>>): NotLoadedSubject | undefined;
79
+ /** What this process sees for the subject (never throws: a step that fails is recorded). */
80
+ diagnose(subject: NotLoadedSubject): Promise<NotLoadedDiagnosis>;
81
+ /**
82
+ * Before the one more run through Vite: the module is invalidated, and a URL entry whose id
83
+ * names another file is dropped, so Vite resolves the URL again.
84
+ */
85
+ refresh(subject: NotLoadedSubject, diagnosis: NotLoadedDiagnosis): Promise<void>;
86
+ /** Logs the 404 (warn the first time for a URL, then debug with the count) with its outcome. */
87
+ report(diagnosis: NotLoadedDiagnosis, status: number): void;
88
+ /** A response for `url` that was served: a later 404 for it warns again. */
89
+ served(url: string, method: string | undefined, status: number): void;
90
+ }
91
+ export {};
@@ -0,0 +1,242 @@
1
+ // D-0292: why the Vite dev host answered 404 for a module URL. Vite's transform middleware turns
2
+ // `ERR_LOAD_URL` ("Failed to load url … (resolved id: …) in <importer>. Does the file exist?")
3
+ // into `next()` without the error, and when its static middleware does not serve the file either
4
+ // the host answers an empty 404: nothing in the log says which id Vite tried or why it read
5
+ // nothing (shop dev, 2026-11-28: three rewritten pages answered 404 for ten minutes while the
6
+ // files were on disk; a restart cleared it, and no trace was left).
7
+ //
8
+ // For a module request (a script, `?import`, a module or style extension) that ends that way, the
9
+ // host asks Vite again in the same process: the module graph's entry for the URL (its id and file),
10
+ // the file as this process sees it (stat, read access, real path), whether Vite's
11
+ // `isFileLoadingAllowed` admits it, and the error of one more `transformRequest` (the dropped
12
+ // message). It logs that as `INERTIA_VITE_NOT_LOADED` (warn, once per URL until the URL is served
13
+ // again; repeats at debug with their count).
14
+ //
15
+ // When the file is there, readable and allowed, the 404 is Vite's state, not the file's (a stale
16
+ // graph entry is the likeliest, which is what a restart clears): the host invalidates the module,
17
+ // drops a URL entry whose id names another file, and runs the request through Vite once more.
18
+ import { constants } from 'node:fs';
19
+ import { access, realpath, stat } from 'node:fs/promises';
20
+ import { join } from 'node:path';
21
+ import { diagnostics } from '@dokebi/core/libraries';
22
+ const { describeError } = diagnostics;
23
+ /** Extensions of the modules and styles a page loads through Vite (`.html` is never a module). */
24
+ const MODULE_FILE = /\.(?:vue|[cm]?[jt]sx?|css|scss|sass|less|styl|stylus|pcss|postcss|sss|json|svg|wasm)$/i;
25
+ /** The longest URL text a record keeps. */
26
+ const URL_TEXT = 500;
27
+ const errorCode = (error) => {
28
+ const code = error?.code;
29
+ return typeof code === 'string' ? code : undefined;
30
+ };
31
+ /** Why a module URL answered 404, logged once per URL until it is served again. */
32
+ export class NotLoadedReporter {
33
+ #logger;
34
+ #server;
35
+ #allowed;
36
+ /** URL path → requests answered 404 since the warning (a later 2xx/3xx clears it). */
37
+ #reported = new Map();
38
+ constructor(logger, server, allowed) {
39
+ this.#logger = logger;
40
+ this.#server = server;
41
+ this.#allowed = allowed;
42
+ }
43
+ /** The module request behind `url`, or undefined for anything else (a page, a folder, a virtual id). */
44
+ subject(url, method, headers) {
45
+ if (method !== 'GET' && method !== 'HEAD')
46
+ return undefined;
47
+ const base = this.#server.config.base || '/';
48
+ const [rawPath = '/', query = ''] = url.split('#', 1)[0]?.split('?', 2) ?? [];
49
+ if (!rawPath.startsWith(base))
50
+ return undefined;
51
+ let path;
52
+ try {
53
+ path = decodeURI(`/${rawPath.slice(base.length)}`);
54
+ }
55
+ catch (error) {
56
+ if (!(error instanceof URIError))
57
+ throw error;
58
+ return undefined;
59
+ }
60
+ if (path.endsWith('/') || path.includes('\0'))
61
+ return undefined;
62
+ const params = new URLSearchParams(query);
63
+ const script = headers['sec-fetch-dest'] === 'script';
64
+ if (!script && !params.has('import') && !MODULE_FILE.test(path))
65
+ return undefined;
66
+ params.delete('t');
67
+ params.delete('import');
68
+ const rest = params.toString().replace(/=(?=&|$)/g, '');
69
+ const module = rest ? `${path}?${rest}` : path;
70
+ let file;
71
+ if (path.startsWith('/@fs/'))
72
+ file = path.slice(4);
73
+ else if (!path.startsWith('/@'))
74
+ file = join(this.#server.config.root, path);
75
+ return { url, module, file };
76
+ }
77
+ /** What this process sees for the subject (never throws: a step that fails is recorded). */
78
+ async diagnose(subject) {
79
+ const root = this.#server.config.root;
80
+ const client = this.#server.environments?.client;
81
+ let exists = false;
82
+ let missing;
83
+ let readable;
84
+ let real;
85
+ let allowed;
86
+ const file = subject.file;
87
+ if (file !== undefined) {
88
+ try {
89
+ const info = await stat(file);
90
+ exists = info.isFile();
91
+ if (!exists)
92
+ missing = info.isDirectory() ? 'directory' : 'other';
93
+ }
94
+ catch (error) {
95
+ missing = errorCode(error) ?? 'failed';
96
+ }
97
+ if (exists) {
98
+ readable = await access(file, constants.R_OK).then(() => true, () => false);
99
+ const resolved = await realpath(file).then((path) => path, (error) => {
100
+ if (this.#logger.isEnabled('debug'))
101
+ this.#logger.log('debug', 'Vite dev host cannot resolve the real path of a module', {
102
+ file,
103
+ error: describeError(error),
104
+ });
105
+ return undefined;
106
+ });
107
+ if (resolved !== undefined && resolved !== file)
108
+ real = resolved;
109
+ }
110
+ if (this.#allowed) {
111
+ try {
112
+ allowed = this.#allowed(this.#server.config, file.split('\\').join('/'));
113
+ }
114
+ catch (error) {
115
+ this.#logger.log('error', 'Vite isFileLoadingAllowed failed', {
116
+ code: 'INERTIA_VITE_NOT_LOADED',
117
+ file,
118
+ error: describeError(error),
119
+ });
120
+ }
121
+ }
122
+ }
123
+ let graph;
124
+ const entry = await this.#module(subject.module);
125
+ if (entry) {
126
+ const id = typeof entry.id === 'string' ? entry.id : null;
127
+ const entryFile = typeof entry.file === 'string' ? entry.file : null;
128
+ const named = entryFile ?? (id === null ? null : (id.split('?', 1)[0] ?? null));
129
+ graph = {
130
+ id,
131
+ file: entryFile,
132
+ stale: file !== undefined && named !== null && named !== file && named !== real,
133
+ transformed: entry.transformResult != null,
134
+ ...(typeof entry.lastInvalidationTimestamp === 'number' &&
135
+ entry.lastInvalidationTimestamp > 0
136
+ ? { invalidatedAt: entry.lastInvalidationTimestamp }
137
+ : {}),
138
+ };
139
+ }
140
+ let cause;
141
+ let loadsNow;
142
+ if (client?.transformRequest) {
143
+ try {
144
+ loadsNow = (await client.transformRequest(subject.module)) != null;
145
+ }
146
+ catch (error) {
147
+ const code = errorCode(error);
148
+ cause = {
149
+ ...(code === undefined ? {} : { code }),
150
+ message: error instanceof Error ? error.message : String(error),
151
+ };
152
+ }
153
+ }
154
+ return {
155
+ url: subject.url.slice(0, URL_TEXT),
156
+ module: subject.module.slice(0, URL_TEXT),
157
+ root,
158
+ ...(file === undefined ? {} : { file }),
159
+ exists,
160
+ ...(missing === undefined ? {} : { missing }),
161
+ ...(readable === undefined ? {} : { readable }),
162
+ ...(real === undefined ? {} : { real }),
163
+ ...(allowed === undefined ? {} : { allowed }),
164
+ ...(graph === undefined ? {} : { graph }),
165
+ ...(cause === undefined ? {} : { cause }),
166
+ ...(loadsNow === undefined ? {} : { loadsNow }),
167
+ retry: exists && readable === true && allowed !== false,
168
+ };
169
+ }
170
+ /**
171
+ * Before the one more run through Vite: the module is invalidated, and a URL entry whose id
172
+ * names another file is dropped, so Vite resolves the URL again.
173
+ */
174
+ async refresh(subject, diagnosis) {
175
+ const graph = this.#server.environments?.client?.moduleGraph;
176
+ if (!graph)
177
+ return;
178
+ const entry = await this.#module(subject.module);
179
+ if (!entry)
180
+ return;
181
+ try {
182
+ graph.invalidateModule(entry);
183
+ if (diagnosis.graph?.stale && typeof entry.url === 'string')
184
+ graph.urlToModuleMap?.delete(entry.url);
185
+ }
186
+ catch (error) {
187
+ this.#logger.log('error', 'Vite dev host could not invalidate a module it answered 404', {
188
+ code: 'INERTIA_VITE_NOT_LOADED',
189
+ module: subject.module.slice(0, URL_TEXT),
190
+ error: describeError(error),
191
+ });
192
+ }
193
+ }
194
+ /** Logs the 404 (warn the first time for a URL, then debug with the count) with its outcome. */
195
+ report(diagnosis, status) {
196
+ const key = diagnosis.module;
197
+ const served = status < 400;
198
+ const repeats = this.#reported.get(key);
199
+ if (served)
200
+ this.#reported.delete(key);
201
+ else
202
+ this.#reported.set(key, (repeats ?? -1) + 1);
203
+ const fields = {
204
+ code: 'INERTIA_VITE_NOT_LOADED',
205
+ ...diagnosis,
206
+ ...(diagnosis.retry ? { retried: status } : {}),
207
+ };
208
+ if (repeats === undefined)
209
+ this.#logger.log('warn', served
210
+ ? 'Vite dev host answered 404 for a module, then served it after invalidating it'
211
+ : 'Vite dev host answered 404 for a module', fields);
212
+ else if (this.#logger.isEnabled('debug'))
213
+ this.#logger.log('debug', 'Vite dev host answered 404 for a module again', {
214
+ ...fields,
215
+ repeats: repeats + 1,
216
+ });
217
+ }
218
+ /** A response for `url` that was served: a later 404 for it warns again. */
219
+ served(url, method, status) {
220
+ if (this.#reported.size === 0 || status >= 400)
221
+ return;
222
+ const subject = this.subject(url, method, {});
223
+ if (subject)
224
+ this.#reported.delete(subject.module);
225
+ }
226
+ async #module(url) {
227
+ const graph = this.#server.environments?.client?.moduleGraph;
228
+ if (!graph)
229
+ return undefined;
230
+ try {
231
+ return (await graph.getModuleByUrl(url)) ?? undefined;
232
+ }
233
+ catch (error) {
234
+ if (this.#logger.isEnabled('debug'))
235
+ this.#logger.log('debug', 'Vite dev host cannot look a module up by its URL', {
236
+ url: url.slice(0, URL_TEXT),
237
+ error: describeError(error),
238
+ });
239
+ return undefined;
240
+ }
241
+ }
242
+ }
@@ -0,0 +1,26 @@
1
+ import type { Logger } from '@dokebi/core';
2
+ type Invalidate = (file: string) => void;
3
+ /** The re-exporting files of changed TypeScript sources, cleared in Vue's type cache. */
4
+ export declare class TypeBarrels {
5
+ #private;
6
+ constructor(logger: Logger, root: string, invalidate?: Invalidate);
7
+ /** A TypeScript file changed or went away: clears the type caches of the files re-exporting it. */
8
+ changed(file: string): Promise<string[]>;
9
+ }
10
+ /** The part of Vite's dev server the plugin uses. */
11
+ interface WatcherServer {
12
+ readonly watcher?: {
13
+ on(event: 'unlink', listener: (file: string) => void): unknown;
14
+ };
15
+ }
16
+ /** 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): {
18
+ name: 'dokebi-inertia:vue-type-barrels';
19
+ enforce: 'pre';
20
+ apply: 'serve';
21
+ configureServer(server: WatcherServer): void;
22
+ handleHotUpdate(context: {
23
+ file: string;
24
+ }): Promise<void>;
25
+ };
26
+ export {};
@@ -0,0 +1,166 @@
1
+ // D-0292: Vue's type cache of a file that re-exports a changed one (`export * from './event'`) is
2
+ // cleared with it. `defineProps<X>()` resolves X through @vue/compiler-sfc's type scopes, cached
3
+ // per file. For `export *` the compiler copies the source file's exported types into the
4
+ // re-exporting file's scope; @vitejs/plugin-vue clears only the changed file's cache. So a new type
5
+ // in an existing file that a barrel re-exports stayed unknown to the dev compiler
6
+ // (`Unresolvable type reference`) until the barrel itself changed or dev restarted, while vue-tsc,
7
+ // the build and the tests passed (shop dev, 2026-11-29, @vue/compiler-sfc 3.5.44, plugin-vue
8
+ // 6.0.10).
9
+ //
10
+ // On a change or removal of a TypeScript file this plugin finds the files that `export *` (or
11
+ // `export type *`) from it — in the file's own folder and each folder above it up to its package
12
+ // root (the nearest package.json), where barrels sit — and from those, the same way, the files that
13
+ // re-export them; it clears their type caches through the compiler plugin-vue uses (vue/compiler-sfc
14
+ // resolved from the project root, as plugin-vue resolves it). plugin-vue then recompiles the
15
+ // components that depend on the changed file, as before, and they see the new type.
16
+ import { readdir, readFile } from 'node:fs/promises';
17
+ import { createRequire } from 'node:module';
18
+ import { dirname, join, resolve } from 'node:path';
19
+ import { diagnostics } from '@dokebi/core/libraries';
20
+ const { describeError } = diagnostics;
21
+ /** TypeScript sources a type can come from. */
22
+ const TYPE_FILE = /\.(?:[cm]?tsx?)$/i;
23
+ /** `export * from '…'` and `export type * from '…'` (not `export * as name`, a named export). */
24
+ const EXPORT_ALL = /\bexport\s+(?:type\s+)?\*\s+from\s*(['"])([^'"\n]+)\1/g;
25
+ /** Extensions a re-export specifier may name (TypeScript's `.js` for `.ts` included). */
26
+ const SPECIFIER_EXTENSION = /\.(?:d\.[cm]?ts|[cm]?[jt]sx?)$/i;
27
+ const stem = (file) => file.replace(SPECIFIER_EXTENSION, '');
28
+ const posix = (path) => path.split('\\').join('/');
29
+ /** The re-exporting files of changed TypeScript sources, cleared in Vue's type cache. */
30
+ export class TypeBarrels {
31
+ #logger;
32
+ #root;
33
+ #invalidate;
34
+ constructor(logger, root, invalidate) {
35
+ this.#logger = logger;
36
+ this.#root = resolve(root);
37
+ this.#invalidate = invalidate;
38
+ }
39
+ /** vue/compiler-sfc's invalidateTypeCache, as @vitejs/plugin-vue resolves the compiler. */
40
+ #compiler() {
41
+ if (this.#invalidate !== undefined)
42
+ return this.#invalidate;
43
+ try {
44
+ const require = createRequire(join(this.#root, 'package.json'));
45
+ const version = require(require.resolve('vue/package.json', { paths: [this.#root] })).version;
46
+ const compiler = typeof version === 'string' && Number(version.split('.')[0]) >= 3
47
+ ? require(require.resolve('vue/compiler-sfc', { paths: [this.#root] }))
48
+ : undefined;
49
+ this.#invalidate =
50
+ typeof compiler?.invalidateTypeCache === 'function' ? compiler.invalidateTypeCache : null;
51
+ }
52
+ catch (error) {
53
+ this.#invalidate = null;
54
+ this.#logger.log('debug', 'Vue type barrels: no vue/compiler-sfc in the project', {
55
+ root: this.#root,
56
+ error: describeError(error),
57
+ });
58
+ }
59
+ return this.#invalidate;
60
+ }
61
+ /** A TypeScript file changed or went away: clears the type caches of the files re-exporting it. */
62
+ async changed(file) {
63
+ if (!TYPE_FILE.test(file))
64
+ return [];
65
+ const invalidate = this.#compiler();
66
+ if (!invalidate)
67
+ return [];
68
+ const changed = posix(resolve(file));
69
+ const cleared = [];
70
+ const seen = new Set([changed]);
71
+ const queue = [changed];
72
+ // `seen` ends a cycle of re-exports.
73
+ while (queue.length) {
74
+ const target = queue.shift();
75
+ for (const barrel of await this.#reexporters(target)) {
76
+ if (seen.has(barrel))
77
+ continue;
78
+ seen.add(barrel);
79
+ invalidate(barrel);
80
+ cleared.push(barrel);
81
+ queue.push(barrel);
82
+ }
83
+ }
84
+ if (cleared.length && this.#logger.isEnabled('debug'))
85
+ this.#logger.log('debug', 'Vue type caches of re-exporting files cleared', {
86
+ file: changed,
87
+ barrels: cleared,
88
+ });
89
+ return cleared;
90
+ }
91
+ /** Files in `target`'s folder and the folders above it (to its package root) that `export *` it. */
92
+ async #reexporters(target) {
93
+ const wanted = stem(target);
94
+ const found = [];
95
+ for (let dir = dirname(target);; dir = dirname(dir)) {
96
+ let names;
97
+ try {
98
+ names = await readdir(dir);
99
+ }
100
+ catch (error) {
101
+ this.#logger.log('debug', 'Vue type barrels: a folder could not be read', {
102
+ dir,
103
+ error: describeError(error),
104
+ });
105
+ break;
106
+ }
107
+ for (const name of names) {
108
+ if (!TYPE_FILE.test(name))
109
+ continue;
110
+ const candidate = posix(join(dir, name));
111
+ if (candidate === target)
112
+ continue;
113
+ let text;
114
+ try {
115
+ text = await readFile(candidate, 'utf8');
116
+ }
117
+ catch (error) {
118
+ this.#logger.log('debug', 'Vue type barrels: a file could not be read', {
119
+ file: candidate,
120
+ error: describeError(error),
121
+ });
122
+ continue;
123
+ }
124
+ if (!text.includes('*'))
125
+ continue;
126
+ for (const match of text.matchAll(EXPORT_ALL)) {
127
+ const specifier = match[2];
128
+ if (!specifier.startsWith('.'))
129
+ continue;
130
+ const named = stem(posix(resolve(dir, specifier)));
131
+ if (named === wanted || `${named}/index` === wanted) {
132
+ found.push(candidate);
133
+ break;
134
+ }
135
+ }
136
+ }
137
+ // The package root (or the project root) is the last folder a barrel of this file sits in.
138
+ if (names.includes('package.json') || posix(dir) === posix(this.#root))
139
+ break;
140
+ if (dirname(dir) === dir)
141
+ break;
142
+ }
143
+ return found;
144
+ }
145
+ }
146
+ /** 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);
149
+ const clear = (file) => barrels.changed(file).then(() => undefined, (error) => {
150
+ logger.log('error', 'Vue type barrels could not be cleared', {
151
+ code: 'INERTIA_VUE_TYPE_BARRELS_FAILED',
152
+ file,
153
+ error: describeError(error),
154
+ });
155
+ });
156
+ return {
157
+ name: 'dokebi-inertia:vue-type-barrels',
158
+ enforce: 'pre',
159
+ apply: 'serve',
160
+ configureServer(server) {
161
+ server.watcher?.on('unlink', (file) => void clear(file));
162
+ },
163
+ // Awaited by Vite before the next plugin's handleHotUpdate (plugin-vue's).
164
+ handleHotUpdate: (context) => clear(context.file),
165
+ };
166
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/template-inertia",
3
- "version": "0.4.22",
3
+ "version": "0.4.23",
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",