@dokebi/template-inertia 0.4.6 → 0.4.8

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
@@ -59,6 +59,7 @@ route.post('/orders', async (request, reply, page) => {
59
59
  - The Vue side is type-checked too: `dokebi app add --inertia` makes `npm run typecheck` run `vue-tsc` after `tsc` (`node typecheck-vue.mjs -p tsconfig.vue.json`), which checks the `<script>` and the `<template>` of every `.vue` file. Write pages as `<script setup lang="ts">` with `defineProps<{ … }>()`; the shared props (`$page.props`, `usePage().props`) are typed in `src/infra/inertia/page.d.ts` (add a key there for what `src/infra/inertia/shared.ts` returns), and a prop only some pages get with `usePage<{ … }>()`. A Vite build is not a Vue type check.
60
60
  - `redirect(request, reply, localUrl)`: 302 for GET/HEAD, 303 for mutations; an Inertia `#` navigation gets 409 + `X-Inertia-Redirect`.
61
61
  - `location(request, reply, url)`: a local or external http(s) navigation. Inertia requests get 409 + `X-Inertia-Location`.
62
+ - Both write the URL into a response header: characters outside printable ASCII (a Korean path or query value) are percent-encoded as UTF-8 for you, and what is already encoded (`%EA%B0%80`) stays as it is; text that is not well formed (a lone surrogate) is `INVALID_URL`.
62
63
 
63
64
  ### 3.1 deferred, merge and once props (D-0052)
64
65
 
@@ -232,6 +233,19 @@ const answer = await sealedFetch('/posts/preview', { method: 'POST', body: { tit
232
233
  - `dokebiInertia({ allow?, deny? })` also carries the dev file policy (§5.2): `allow` adds files or folders the browser loads (relative to the Vite root), `deny` adds Vite globs that are never served. Do not set `server.fs` in vite.config: the plugin forces `strict: true` and keeps its deny list anyway, and `dokebi check` warns (`vite-dev-files`).
233
234
  - Never load `/dokebi/seal/http.mjs` by URL (`import(/* @vite-ignore */ …)`) next to an import of `@dokebi/seal/http`: with the plugin there is no need, and without it they are two instances.
234
235
 
236
+ ### 4.2 Module pages (`virtual:dokebi/module-pages`, 0.4.8, D-0218)
237
+
238
+ A module keeps its Vue pages in its own views folder (@dokebi/module AI.md §4a): `<module>/views/<template>/Pages/**/*.vue`, rendered as `<module>/<path>` (`board/List`). `dokebiInertia()` answers `import modulePages from 'virtual:dokebi/module-pages'` in an app's `views/app.js` and `views/ssr.js`:
239
+
240
+ - The app is the folder above the importer's nearest `views` folder; its `app.ts` (`app.mts`, `app.js`, `app.mjs`) is imported in the Vite process (Node runs the TypeScript, as `node src/main.ts` does) and asked for its module page sources by structure (`Symbol.for('dokebi.app.modulePages')`, @dokebi/app 0.4.9: each mounted module with views, its folder and the sets the app did not choose).
241
+ - The module text is one static import per page file and `export default modulePages({ <module>: { '<template>/<path>': page } })`. Left out: pages of sets the app did not choose (`Pages/<set>/**`), and a page the app overrides in `views/default/Pages/<module>/` (the app's file wins for every template). At most 2000 page files per app (warn `INERTIA_MODULE_PAGES_LIMIT`).
242
+ - `modulePages(table)` of `@dokebi/template-inertia/pages` (no imports, browser and SSR bundles) gives `{ modules, page(template, name) }`: the module's page of `template`, else of `default`, else undefined. The entries look up the app's own page first: `` pick(`Pages/${name}`) ?? modulePages.page(template, name) ``.
243
+ - Types: `/// <reference types="@dokebi/template-inertia/module-pages" />` in `src/infra/inertia/page.d.ts` (the generated file has it) declares the virtual module for vue-tsc and `dokebi check`, whose browser program now reads the project's `.d.ts` files too.
244
+ - The dev server serves each module's views folder like an app's (§5.2), and reloads the browser when a `.vue` file is added to or removed from a module folder or the app's views, or the app file changes.
245
+ - `vite.ssr.config.ts` needs `dokebiInertia()` too (the SSR build resolves the same import; server rendering still leaves the seal imports to Node). `npx dokebi doctor` names an entry without the import while a module under `src/` has Vue pages (`TEMPLATE_FIX_MISSING`, `module-pages`) and a Vite config without `dokebiInertia()` while an entry imports it (`module-pages-plugin`).
246
+ - An app package without the sources (before @dokebi/app 0.4.9): no module pages, warn `INERTIA_MODULE_PAGES_UNSUPPORTED`. Failures are coded errors of the build: `MODULE_PAGES_APP_MISSING` (imported outside an app's views folder), `MODULE_PAGES_FAILED` (the app file cannot be imported, exports no definition, or a module folder cannot be read; the cause is kept).
247
+ - Debug logs: `Inertia module pages gathered` (app, page count per module, skipped sets, ms), `Inertia module pages changed; the browser reloads` (event, path), `Inertia dev file policy allows a module views folder`.
248
+
235
249
  ## 5. SSR (D-0039)
236
250
 
237
251
  - `ssr.bundle` is a build file that exports `render(page) → { head: string[]; body: string }`. In Inertia v3, calling `createInertiaApp({ resolve, layout })` on the server without a page returns a `(page, renderToString)` function (see the `views/ssr.js` that `--ssr` creates).
@@ -299,6 +313,8 @@ const answer = await sealedFetch('/posts/preview', { method: 'POST', body: { tit
299
313
  | `VITE_DEV_UNAVAILABLE` | `InertiaError` | The Vite host of `dokebi dev` (`DOKEBI_VITE_DEV_URL`) cannot be reached or refuses the key, the URL is not loopback, or the key is missing |
300
314
  | `METHOD_NOT_ALLOWED` | `InertiaError` | `render` for a request that is not GET or HEAD |
301
315
  | `CLOSED` | `InertiaError` | `render` after the app stopped |
316
+ | `MODULE_PAGES_APP_MISSING` | `InertiaError` | (Vite build) `virtual:dokebi/module-pages` imported from a file in no app's `views` folder beside an `app.ts` (§4.2) |
317
+ | `MODULE_PAGES_FAILED` | `InertiaError` | (Vite build) the app file cannot be imported or exports no `defineApp` definition, or a module's views folder cannot be read; the original error is the `cause` (§4.2) |
302
318
  | `INVALID_ENTRY` | `InertiaUsageError` | the entry exports something other than the `shared` and `publicShared` functions |
303
319
  | `INVALID_SCOPE` | `InertiaUsageError` | bad `scope()` settings (`app`, `sealed`, `shared`, `publicShared`, `vite`, `ssr`, asset URLs) |
304
320
  | `INVALID_RENDER` | `InertiaUsageError` | bad component name or render options (`public`, `head`, unknown keys, §3.5) |
package/dist/errors.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { DokebiError, type DokebiErrorOptions } from '@dokebi/core';
2
2
  /** Codes of `InertiaError` (failures of setup, files and the page flow). */
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';
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';
4
4
  /** Codes of `InertiaUsageError` (a wrong argument: a TypeError, as before 0.4.0). */
5
5
  export type InertiaUsageErrorCode = 'INVALID_ENTRY' | 'INVALID_SCOPE' | 'INVALID_RENDER' | 'INVALID_PROPS' | 'INVALID_URL' | 'INVALID_PROP_HELPER' | 'SSR_INVALID_RESULT' | 'INVALID_PRUNE';
6
6
  /** Failures of @dokebi/template-inertia; compare `code`, not the class. */
package/dist/errors.js CHANGED
@@ -11,6 +11,8 @@ const FIX = {
11
11
  VITE_DEV_UNAVAILABLE: 'Run the app with dokebi dev, which starts one Vite dev host and sets DOKEBI_VITE_DEV_URL and DOKEBI_VITE_DEV_KEY; or unset both to start Vite in this process.',
12
12
  METHOD_NOT_ALLOWED: 'Render pages for GET/HEAD; redirect after POST/PUT/PATCH/DELETE (303).',
13
13
  CLOSED: 'Render only while the application runs.',
14
+ MODULE_PAGES_APP_MISSING: "Import 'virtual:dokebi/module-pages' only from an app's views/app.js or views/ssr.js: the app folder beside views/ must hold app.ts (defineApp), whose modules it reads.",
15
+ MODULE_PAGES_FAILED: "Fix the app file or the module folder the cause names: the Inertia build imports the app's app.ts (defineApp) and reads the views folders of the modules it mounts.",
14
16
  INVALID_ENTRY: 'The Inertia entry (src/infra/inertia/shared.ts) exports only shared: (request) => props and publicShared: (request) => props.',
15
17
  INVALID_SCOPE: 'Give scope() document settings (title, rootId, version, scripts, styles or vite, ssr, encryptHistory), shared and publicShared as functions and sealed as a boolean; vite replaces version, scripts and styles.',
16
18
  INVALID_RENDER: 'render(request, reply, component, props?, { encryptHistory?, clearHistory?, public?, head? }): component is names of letters, digits, _ or - joined by /; public is true or { cacheControl }; head holds title, description, canonical, robots, alternates and meta as documented (AI.md §3.5).',
package/dist/i18n.js CHANGED
@@ -267,7 +267,10 @@ export class I18n {
267
267
  const formats = this.#formatsOf(locale);
268
268
  let formatter = formats.numbers.get(format);
269
269
  if (!formatter) {
270
- const preset = format === 'default' ? {} : this.#settings.numberFormats[format];
270
+ // Own names only: the settings are parsed JSON, where `constructor` or `toString` would
271
+ // name an Object.prototype member and format with the default (audit R9-g13-7).
272
+ const presets = this.#settings.numberFormats;
273
+ const preset = format === 'default' ? {} : Object.hasOwn(presets, format) ? presets[format] : undefined;
271
274
  if (!preset)
272
275
  throw new PageI18nError('INVALID_FORMAT', 'Unknown number format');
273
276
  try {
@@ -294,7 +297,8 @@ export class I18n {
294
297
  const formats = this.#formatsOf(locale);
295
298
  let formatter = formats.dates.get(format);
296
299
  if (!formatter) {
297
- const preset = format === 'default' ? {} : this.#settings.dateFormats[format];
300
+ const presets = this.#settings.dateFormats;
301
+ const preset = format === 'default' ? {} : Object.hasOwn(presets, format) ? presets[format] : undefined;
298
302
  if (!preset)
299
303
  throw new PageI18nError('INVALID_FORMAT', 'Unknown date format');
300
304
  try {
package/dist/index.js CHANGED
@@ -1036,7 +1036,7 @@ class InertiaRuntime {
1036
1036
  }
1037
1037
  export const createPlugin = definePlugin({
1038
1038
  name: 'dokebi-template-inertia',
1039
- version: '0.4.6',
1039
+ version: '0.4.8',
1040
1040
  core: '^0.4.2',
1041
1041
  options,
1042
1042
  entry: parseEntry,
@@ -0,0 +1,41 @@
1
+ import type { Logger } from '@dokebi/core';
2
+ /** The specifier views/app.js and views/ssr.js import. */
3
+ export declare const MODULE_PAGES_ID = "virtual:dokebi/module-pages";
4
+ /** The part of Vite's dev server the watcher uses (structural: no Vite types here). */
5
+ export interface PagesDevServer {
6
+ readonly watcher?: {
7
+ add(paths: string | readonly string[]): unknown;
8
+ on(event: 'add' | 'unlink' | 'change', listener: (path: string) => void): unknown;
9
+ };
10
+ readonly moduleGraph?: GraphShape;
11
+ readonly environments?: Readonly<Record<string, {
12
+ readonly moduleGraph?: GraphShape;
13
+ }>>;
14
+ readonly ws?: {
15
+ send(payload: {
16
+ type: 'full-reload';
17
+ }): void;
18
+ };
19
+ }
20
+ interface GraphShape {
21
+ getModuleById(id: string): unknown;
22
+ invalidateModule(module: never): void;
23
+ }
24
+ /** The virtual module of every app of one Vite config (one dokebiInertia() instance). */
25
+ export declare class ModulePagesSource {
26
+ #private;
27
+ /** `allow` hands each module views folder to the dev file policy (D-0129). */
28
+ constructor(logger: Logger, allow: (folder: string) => void);
29
+ /** The command of the resolved config (`serve` re-reads the app file on every load). */
30
+ set command(command: 'build' | 'serve');
31
+ /**
32
+ * The virtual id for an importer (views/app.js, views/ssr.js): the app file (app.ts) of the
33
+ * folder that holds the importer's nearest `views` folder. Null for other specifiers.
34
+ */
35
+ resolve(source: string, importer: string | undefined): string | null;
36
+ /** The module text of a virtual id; null for other ids. */
37
+ load(id: string): Promise<string | null>;
38
+ /** The dev server: page files added or removed in a module folder reload the browser. */
39
+ configureServer(server: PagesDevServer): void;
40
+ }
41
+ export {};
@@ -0,0 +1,239 @@
1
+ // D-0218: `virtual:dokebi/module-pages`, the Inertia pages of the modules an app mounts. A module
2
+ // keeps its Vue pages in its own views folder (`<template>/Pages/**/*.vue`, beside its EJS views),
3
+ // so they travel with the module and leave the bundle with it. views/app.js and views/ssr.js of an
4
+ // app import this module; dokebiInertia() answers it per app: it imports the app's app.ts (the
5
+ // defineApp definition beside views/), asks @dokebi/app for the module page sources (by structure:
6
+ // `Symbol.for('dokebi.app.modulePages')`, @dokebi/app 0.4.9) and writes one static import per page
7
+ // file. Pages of sets the app did not choose (`Pages/<set>/**`) are left out. In the dev server it
8
+ // watches the module folders and the app file: a page added or removed reloads the browser.
9
+ import { existsSync } from 'node:fs';
10
+ import { readdir } from 'node:fs/promises';
11
+ import { basename, dirname, join, relative, sep } from 'node:path';
12
+ import { pathToFileURL } from 'node:url';
13
+ import { InertiaError } from './errors.js';
14
+ /** The specifier views/app.js and views/ssr.js import. */
15
+ export const MODULE_PAGES_ID = 'virtual:dokebi/module-pages';
16
+ /** Vite's mark of a virtual module, then the app file the module is for. */
17
+ const PREFIX = '\0dokebi-module-pages:';
18
+ const APP_FILES = ['app.ts', 'app.mts', 'app.js', 'app.mjs'];
19
+ /** How far above the importer the `views` folder is looked for (views/<template>/… → views). */
20
+ const MAX_UP = 4;
21
+ const MAX_FILES = 2000;
22
+ const MAX_DEPTH = 8;
23
+ const PAGES_KEY = Symbol.for('dokebi.app.modulePages');
24
+ const slash = (path) => path.split(sep).join('/');
25
+ const within = (path, folder) => path === folder || path.startsWith(folder.endsWith(sep) ? folder : folder + sep);
26
+ function isSource(value) {
27
+ const source = value;
28
+ return (typeof source === 'object' &&
29
+ source !== null &&
30
+ typeof source.module === 'string' &&
31
+ typeof source.folder === 'string' &&
32
+ Array.isArray(source.skip) &&
33
+ source.skip.every((set) => typeof set === 'string'));
34
+ }
35
+ /** `.vue` files under `<folder>/<template>/Pages/`, as `[template, path under Pages, file]`. */
36
+ async function pageFiles(source, appViews) {
37
+ const found = [];
38
+ const walk = async (directory, depth, visit) => {
39
+ if (depth > MAX_DEPTH || found.length >= MAX_FILES)
40
+ return;
41
+ const entries = await readdir(directory, { withFileTypes: true });
42
+ entries.sort((a, b) => a.name.localeCompare(b.name));
43
+ for (const entry of entries) {
44
+ if (entry.name.startsWith('.') || entry.name === 'node_modules')
45
+ continue;
46
+ const path = join(directory, entry.name);
47
+ if (entry.isDirectory())
48
+ await walk(path, depth + 1, visit);
49
+ else if (entry.isFile() && entry.name.endsWith('.vue'))
50
+ visit(path);
51
+ }
52
+ };
53
+ const templates = (await readdir(source.folder, { withFileTypes: true })).filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'));
54
+ templates.sort((a, b) => a.name.localeCompare(b.name));
55
+ for (const template of templates) {
56
+ const pages = join(source.folder, template.name, 'Pages');
57
+ if (!existsSync(pages))
58
+ continue;
59
+ await walk(pages, 0, (file) => {
60
+ const rest = slash(relative(pages, file)).slice(0, -'.vue'.length);
61
+ if (source.skip.some((set) => rest.startsWith(`${set}/`)))
62
+ return;
63
+ // The app's own page of the same name in `default` wins for every template: the module's
64
+ // file would never be shown.
65
+ if (existsSync(join(appViews, 'default', 'Pages', source.module, `${rest}.vue`)))
66
+ return;
67
+ found.push([template.name, rest, file]);
68
+ });
69
+ }
70
+ return found;
71
+ }
72
+ /** The virtual module of every app of one Vite config (one dokebiInertia() instance). */
73
+ export class ModulePagesSource {
74
+ #logger;
75
+ #serve = false;
76
+ #server;
77
+ /** Virtual id → the folders and the app file a change of which reloads it. */
78
+ #watched = new Map();
79
+ #allow;
80
+ /** `allow` hands each module views folder to the dev file policy (D-0129). */
81
+ constructor(logger, allow) {
82
+ this.#logger = logger;
83
+ this.#allow = allow;
84
+ }
85
+ /** The command of the resolved config (`serve` re-reads the app file on every load). */
86
+ set command(command) {
87
+ this.#serve = command === 'serve';
88
+ }
89
+ /**
90
+ * The virtual id for an importer (views/app.js, views/ssr.js): the app file (app.ts) of the
91
+ * folder that holds the importer's nearest `views` folder. Null for other specifiers.
92
+ */
93
+ resolve(source, importer) {
94
+ if (source !== MODULE_PAGES_ID)
95
+ return null;
96
+ const from = importer?.split('?', 1)[0];
97
+ let folder = from && !from.startsWith('\0') ? dirname(from) : undefined;
98
+ for (let up = 0; folder && up <= MAX_UP; up++) {
99
+ if (basename(folder) === 'views') {
100
+ const app = dirname(folder);
101
+ for (const name of APP_FILES) {
102
+ const file = join(app, name);
103
+ if (existsSync(file))
104
+ return PREFIX + file;
105
+ }
106
+ break;
107
+ }
108
+ const parent = dirname(folder);
109
+ if (parent === folder)
110
+ break;
111
+ folder = parent;
112
+ }
113
+ throw new InertiaError('MODULE_PAGES_APP_MISSING', `${MODULE_PAGES_ID} is imported by ${importer ?? 'an unknown file'}, which is in no app's views folder beside an app.ts`);
114
+ }
115
+ /** The module text of a virtual id; null for other ids. */
116
+ async load(id) {
117
+ if (!id.startsWith(PREFIX))
118
+ return null;
119
+ const app = id.slice(PREFIX.length);
120
+ const begin = performance.now();
121
+ let definition;
122
+ try {
123
+ // The dev server reads the app file again after it changed (a module mounted or removed);
124
+ // the modules it imports stay as Node cached them.
125
+ const url = pathToFileURL(app).href + (this.#serve ? `?dokebi-pages=${Date.now()}` : '');
126
+ definition = (await import(url)).default;
127
+ }
128
+ catch (cause) {
129
+ throw new InertiaError('MODULE_PAGES_FAILED', `The Inertia build could not import ${app} to find its module pages`, { cause });
130
+ }
131
+ if (definition === null || typeof definition !== 'object')
132
+ throw new InertiaError('MODULE_PAGES_FAILED', `${app} has no default export made by defineApp of @dokebi/app`);
133
+ const list = definition[PAGES_KEY];
134
+ let sources = [];
135
+ if (typeof list !== 'function')
136
+ this.#logger.log('warn', 'The app package does not list module pages; module pages are left out of this app (update @dokebi/app to 0.4.9 or later)', { code: 'INERTIA_MODULE_PAGES_UNSUPPORTED', app });
137
+ else {
138
+ const value = list();
139
+ if (!Array.isArray(value) || !value.every(isSource))
140
+ throw new InertiaError('MODULE_PAGES_FAILED', `The module page sources of ${app} are not { module, folder, skip } entries`);
141
+ sources = value;
142
+ }
143
+ const imports = [];
144
+ const table = [];
145
+ const counts = {};
146
+ let total = 0;
147
+ for (const source of sources) {
148
+ let files;
149
+ try {
150
+ files = await pageFiles(source, join(dirname(app), 'views'));
151
+ }
152
+ catch (cause) {
153
+ throw new InertiaError('MODULE_PAGES_FAILED', `The views folder of module ${source.module} (${source.folder}) cannot be read`, { cause });
154
+ }
155
+ const entries = [];
156
+ for (const [template, rest, file] of files) {
157
+ if (total >= MAX_FILES)
158
+ break;
159
+ const name = `p${total++}`;
160
+ imports.push(`import * as ${name} from ${JSON.stringify(slash(file))};`);
161
+ entries.push(`${JSON.stringify(`${template}/${rest}`)}: ${name}`);
162
+ }
163
+ counts[source.module] = entries.length;
164
+ table.push(` ${JSON.stringify(source.module)}: { ${entries.join(', ')} },`);
165
+ }
166
+ if (total >= MAX_FILES)
167
+ this.#logger.log('warn', 'Module pages beyond the limit were left out', {
168
+ code: 'INERTIA_MODULE_PAGES_LIMIT',
169
+ app,
170
+ limit: MAX_FILES,
171
+ });
172
+ this.#watch(id, app, sources);
173
+ this.#logger.log('debug', 'Inertia module pages gathered', {
174
+ app,
175
+ modules: counts,
176
+ skipped: Object.fromEntries(sources.filter((s) => s.skip.length).map((s) => [s.module, s.skip])),
177
+ ms: Math.round(performance.now() - begin),
178
+ });
179
+ return [
180
+ "import { modulePages } from '@dokebi/template-inertia/pages';",
181
+ ...imports,
182
+ 'export default modulePages({',
183
+ ...table,
184
+ '});',
185
+ '',
186
+ ].join('\n');
187
+ }
188
+ /** The dev server: page files added or removed in a module folder reload the browser. */
189
+ configureServer(server) {
190
+ this.#server = server;
191
+ const changed = (event) => (path) => {
192
+ for (const [id, watched] of this.#watched) {
193
+ const page = event !== 'change' &&
194
+ path.endsWith('.vue') &&
195
+ watched.folders.some((folder) => within(path, folder));
196
+ if (!page && path !== watched.app)
197
+ continue;
198
+ this.#invalidate(id, event, path);
199
+ }
200
+ };
201
+ server.watcher?.on('add', changed('add'));
202
+ server.watcher?.on('unlink', changed('unlink'));
203
+ server.watcher?.on('change', changed('change'));
204
+ }
205
+ #watch(id, app, sources) {
206
+ // The app's own views too: a page added or removed there changes which module pages it hides.
207
+ const folders = [join(dirname(app), 'views'), ...sources.map((source) => source.folder)];
208
+ this.#watched.set(id, { app, folders });
209
+ if (!this.#serve)
210
+ return;
211
+ for (const source of sources)
212
+ this.#allow(source.folder);
213
+ this.#server?.watcher?.add([app, ...folders]);
214
+ }
215
+ #invalidate(id, event, path) {
216
+ const server = this.#server;
217
+ if (!server)
218
+ return;
219
+ const graphs = [
220
+ server.moduleGraph,
221
+ ...Object.values(server.environments ?? {}).map((environment) => environment.moduleGraph),
222
+ ];
223
+ let found = 0;
224
+ for (const graph of graphs) {
225
+ const module = graph?.getModuleById(id);
226
+ if (module) {
227
+ graph?.invalidateModule(module);
228
+ found++;
229
+ }
230
+ }
231
+ this.#logger.log('debug', 'Inertia module pages changed; the browser reloads', {
232
+ event,
233
+ path,
234
+ modules: found,
235
+ });
236
+ if (found)
237
+ server.ws?.send({ type: 'full-reload' });
238
+ }
239
+ }
@@ -0,0 +1,15 @@
1
+ /** A page module as Vite's eager import gives it (`default` is the component). */
2
+ export type PageModule = Readonly<Record<string, unknown>>;
3
+ /** `{ <module>: { '<template>/<path under Pages>': module } }`, written by dokebiInertia(). */
4
+ export type ModulePageTable = Readonly<Record<string, Readonly<Record<string, PageModule>>>>;
5
+ export interface ModulePages {
6
+ /** The module names that have pages in this app's bundle. */
7
+ readonly modules: readonly string[];
8
+ /**
9
+ * The page `<module>/<path>` of `template`, else of `default`; undefined when no module has it
10
+ * (a name without a module part, a module the app does not mount, a set the app did not choose).
11
+ */
12
+ page(template: string, name: string): PageModule | undefined;
13
+ }
14
+ /** The lookup over the table the virtual module writes. */
15
+ export declare function modulePages(table: ModulePageTable): ModulePages;
package/dist/pages.js ADDED
@@ -0,0 +1,27 @@
1
+ // `@dokebi/template-inertia/pages` (D-0218): the browser side of the module pages. The virtual
2
+ // module `virtual:dokebi/module-pages` of dokebiInertia() imports the Inertia pages of the modules
3
+ // an app mounts and hands them to modulePages(); views/app.js and views/ssr.js look a page up in
4
+ // the app first (an app file of the same name overrides the module's) and then here. No imports:
5
+ // it runs in the browser bundle and in the SSR bundle.
6
+ /** The lookup over the table the virtual module writes. */
7
+ export function modulePages(table) {
8
+ const modules = Object.freeze(Object.keys(table));
9
+ return Object.freeze({
10
+ modules,
11
+ page(template, name) {
12
+ const slash = name.indexOf('/');
13
+ if (slash < 1)
14
+ return undefined;
15
+ const module = name.slice(0, slash);
16
+ if (!Object.hasOwn(table, module))
17
+ return undefined;
18
+ const pages = table[module];
19
+ const rest = name.slice(slash + 1);
20
+ const own = `${template}/${rest}`;
21
+ if (Object.hasOwn(pages, own))
22
+ return pages[own];
23
+ const fallback = `default/${rest}`;
24
+ return Object.hasOwn(pages, fallback) ? pages[fallback] : undefined;
25
+ },
26
+ });
27
+ }
package/dist/responder.js CHANGED
@@ -41,6 +41,36 @@ function localUrl(value) {
41
41
  throw new InertiaUsageError('INVALID_URL', 'Expected a local absolute URL');
42
42
  return value;
43
43
  }
44
+ /**
45
+ * A checked redirect or location URL as a response header can carry it (audit R9-g13-3). Node
46
+ * refuses a header value with a character above U+00FF, and Fastify then destroys the socket:
47
+ * a redirect to a path with Korean text was a dropped connection, not a redirect.
48
+ * Printable ASCII (`%XX` included) is written as it is; anything else is percent-encoded as
49
+ * UTF-8, as a browser does with the same text in a link (an external URL through the URL
50
+ * parser, so its host becomes punycode). Text that is not well formed (a lone surrogate) is
51
+ * INVALID_URL.
52
+ */
53
+ const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
54
+ function headerUrl(url) {
55
+ if (/^[\x21-\x7e]*$/.test(url))
56
+ return url;
57
+ if (LONE_SURROGATE.test(url))
58
+ throw new InertiaUsageError('INVALID_URL', 'Expected a URL of well-formed text');
59
+ return url.startsWith('/')
60
+ ? url.replace(/[^\x21-\x7e]+/g, (text) => encodeURIComponent(text))
61
+ : new URL(url).href;
62
+ }
63
+ /**
64
+ * The location of a version mismatch (409): the request's own path and query. A request target
65
+ * is client input: `//host/x` or `/\host/x` as a location would send the browser to that host
66
+ * (and was refused with INVALID_URL, a 500 any client could ask for; audit R9-g13-4), so the
67
+ * leading slashes become one and a backslash is written `%5C`. A target that is no path (`*`,
68
+ * an absolute form) goes to `/`.
69
+ */
70
+ function ownLocation(url) {
71
+ const path = url.replace(/^\/+/, '/').replace(/\\/g, '%5C');
72
+ return path.startsWith('/') ? path : '/';
73
+ }
44
74
  export function vary(reply) {
45
75
  const values = String(reply.getHeader('vary') ?? '')
46
76
  .split(',')
@@ -301,7 +331,7 @@ export class InertiaResponder {
301
331
  request.headers['x-inertia-version'] !== this.options.version) {
302
332
  return reply
303
333
  .code(409)
304
- .header('X-Inertia-Location', localUrl(request.url))
334
+ .header('X-Inertia-Location', ownLocation(request.url))
305
335
  .header('X-Inertia-Version', this.options.version)
306
336
  .send();
307
337
  }
@@ -553,11 +583,11 @@ export class InertiaResponder {
553
583
  }
554
584
  redirect(request, reply, url) {
555
585
  this.#check();
556
- localUrl(url);
586
+ const target = headerUrl(localUrl(url));
557
587
  vary(reply);
558
- if (request.headers['x-inertia'] === 'true' && url.includes('#'))
559
- return reply.code(409).header('X-Inertia-Redirect', url).send();
560
- return reply.redirect(url, ['GET', 'HEAD'].includes(request.method) ? 302 : 303);
588
+ if (request.headers['x-inertia'] === 'true' && target.includes('#'))
589
+ return reply.code(409).header('X-Inertia-Redirect', target).send();
590
+ return reply.redirect(target, ['GET', 'HEAD'].includes(request.method) ? 302 : 303);
561
591
  }
562
592
  location(request, reply, url) {
563
593
  this.#check();
@@ -568,10 +598,11 @@ export class InertiaResponder {
568
598
  !/^https?:$/.test(new URL(url).protocol) ||
569
599
  /[\r\n]/.test(url))
570
600
  throw new InertiaUsageError('INVALID_URL', 'Invalid location');
601
+ const target = headerUrl(url);
571
602
  vary(reply);
572
603
  return request.headers['x-inertia'] === 'true'
573
- ? reply.code(409).header('X-Inertia-Location', url).send()
574
- : reply.redirect(url, 302);
604
+ ? reply.code(409).header('X-Inertia-Location', target).send()
605
+ : reply.redirect(target, 302);
575
606
  }
576
607
  }
577
608
  const RESCUED = Symbol('rescued');
@@ -104,6 +104,11 @@ export declare class DevFilesPolicy {
104
104
  config(raw: unknown, command: 'build' | 'serve'): DevFilesPatch | null;
105
105
  /** The `configResolved` hook: repairs what a later plugin loosened and keeps the live config. */
106
106
  configResolved(config: ResolvedFilesShape): void;
107
+ /**
108
+ * D-0218: a module's views folder whose Inertia pages an app imports (`virtual:dokebi/module-pages`)
109
+ * is served like an app's views folder.
110
+ */
111
+ allowFolder(folder: string): void;
107
112
  /** The middleware to add before Vite's own (undefined when this copy is inactive). */
108
113
  middleware(): DevMiddleware | undefined;
109
114
  }
@@ -395,6 +395,22 @@ export class DevFilesPolicy {
395
395
  if (restored.length || this.#deny.length !== fs.deny.length)
396
396
  this.#deny = fs.deny.map((glob) => ({ glob, pattern: denyPattern(glob) }));
397
397
  }
398
+ /**
399
+ * D-0218: a module's views folder whose Inertia pages an app imports (`virtual:dokebi/module-pages`)
400
+ * is served like an app's views folder.
401
+ */
402
+ allowFolder(folder) {
403
+ const fs = this.#fs;
404
+ if (!this.#active || !fs)
405
+ return;
406
+ const path = slash(folder);
407
+ if (fs.allow.some((dir) => within(dir, path)))
408
+ return;
409
+ fs.allow.push(path);
410
+ this.#logger.log('debug', 'Inertia dev file policy allows a module views folder', {
411
+ folder: path,
412
+ });
413
+ }
398
414
  /** The middleware to add before Vite's own (undefined when this copy is inactive). */
399
415
  middleware() {
400
416
  if (!this.#active)
@@ -1,5 +1,7 @@
1
1
  import { type Logger } from '@dokebi/core';
2
+ import { type PagesDevServer } from './module-pages.js';
2
3
  import { type DevFilesOptions, type DevFilesPatch, type DevMiddleware, type ResolvedFilesShape } from './vite-files.js';
4
+ export { MODULE_PAGES_ID } from './module-pages.js';
3
5
  export { DEV_FILES_DENY, type DevFilesOptions, type DokebiDevFilesPlugin, dokebiDevFiles, } from './vite-files.js';
4
6
  /** Specifier → the URL the app serves it at (@dokebi/seal, `GET /dokebi/seal/*`). */
5
7
  export declare const SERVED_MODULES: Readonly<Record<string, string>>;
@@ -15,7 +17,7 @@ export interface DokebiInertiaViteOptions extends DevFilesOptions {
15
17
  /** The part of Vite's resolved config this plugin reads. */
16
18
  type ResolvedConfigShape = ResolvedFilesShape;
17
19
  /** The part of Vite's dev server this plugin uses (connect middlewares). */
18
- interface DevServerShape {
20
+ interface DevServerShape extends PagesDevServer {
19
21
  readonly middlewares: {
20
22
  use(handler: DevMiddleware): unknown;
21
23
  };
@@ -57,8 +59,8 @@ export interface DokebiInertiaVitePlugin {
57
59
  }): {
58
60
  id: string;
59
61
  external: true | 'absolute';
60
- } | null;
61
- load(id: string): string | null;
62
+ } | string | null;
63
+ load(id: string): string | null | Promise<string | null>;
62
64
  configureServer(server: DevServerShape): void;
63
65
  }
64
66
  /**
@@ -28,7 +28,9 @@
28
28
  // serve: strict, a narrowed allow list, a deny list the app cannot shrink, a short 403 for
29
29
  // remote hosts), so an upgrade of this package secures every vite.config that uses it.
30
30
  import { ConsoleLogger } from '@dokebi/core';
31
+ import { MODULE_PAGES_ID, ModulePagesSource } from './module-pages.js';
31
32
  import { DevFilesPolicy, } from './vite-files.js';
33
+ export { MODULE_PAGES_ID } from './module-pages.js';
32
34
  export { DEV_FILES_DENY, dokebiDevFiles, } from './vite-files.js';
33
35
  /** Specifier → the URL the app serves it at (@dokebi/seal, `GET /dokebi/seal/*`). */
34
36
  export const SERVED_MODULES = Object.freeze({
@@ -84,6 +86,8 @@ export function dokebiInertia(options = {}) {
84
86
  }, 'dokebi-inertia');
85
87
  let command = 'serve';
86
88
  let base = '/';
89
+ // D-0218: `virtual:dokebi/module-pages`, the Inertia pages of the modules each app mounts.
90
+ const pages = new ModulePagesSource(logger, (folder) => files.allowFolder(folder));
87
91
  /** Dev re-export id → the served URL it re-exports. */
88
92
  const dev = new Map(Object.values(SERVED_MODULES).map((served) => [devId(served), served]));
89
93
  /** Request path (with and without `base`) → the module text the dev server answers. */
@@ -108,6 +112,7 @@ export function dokebiInertia(options = {}) {
108
112
  configResolved(config) {
109
113
  files.configResolved(config);
110
114
  command = config.command;
115
+ pages.command = command;
111
116
  base = config.base || '/';
112
117
  answers.clear();
113
118
  for (const [id, served] of dev) {
@@ -122,6 +127,8 @@ export function dokebiInertia(options = {}) {
122
127
  });
123
128
  },
124
129
  resolveId(source, importer, resolveOptions) {
130
+ if (source === MODULE_PAGES_ID)
131
+ return pages.resolve(source, importer);
125
132
  const served = SERVED_MODULES[source];
126
133
  if (served === undefined)
127
134
  return null;
@@ -139,6 +146,8 @@ export function dokebiInertia(options = {}) {
139
146
  return command === 'build' ? { id, external: 'absolute' } : { id, external: true };
140
147
  },
141
148
  load(id) {
149
+ if (id.startsWith('\0dokebi-module-pages:'))
150
+ return pages.load(id);
142
151
  // Vite pre-transforms the imports it sees, the dev re-export too. The middleware below
143
152
  // answers its URL before Vite does, so this text only fills Vite's module graph; were it
144
153
  // ever served, the page would fail loudly instead of running without the served module.
@@ -152,6 +161,7 @@ export function dokebiInertia(options = {}) {
152
161
  const guard = files.middleware();
153
162
  if (guard)
154
163
  server.middlewares.use(guard);
164
+ pages.configureServer(server);
155
165
  // Added before Vite's own middlewares (the hook returns nothing): the re-export is served
156
166
  // as written, without Vite's import rewriting (which would prefix the path with `base`).
157
167
  server.middlewares.use((request, response, next) => {
@@ -0,0 +1,8 @@
1
+ // The types of `virtual:dokebi/module-pages` (D-0218), which dokebiInertia() of
2
+ // @dokebi/template-inertia/vite writes for an app's views/app.js and views/ssr.js. A project's
3
+ // src/infra/inertia/page.d.ts references it:
4
+ // /// <reference types="@dokebi/template-inertia/module-pages" />
5
+ declare module 'virtual:dokebi/module-pages' {
6
+ const pages: import('@dokebi/template-inertia/pages').ModulePages;
7
+ export default pages;
8
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/template-inertia",
3
- "version": "0.4.6",
3
+ "version": "0.4.8",
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",
@@ -33,6 +33,13 @@
33
33
  "./i18n": {
34
34
  "types": "./dist/i18n.d.ts",
35
35
  "import": "./dist/i18n.js"
36
+ },
37
+ "./pages": {
38
+ "types": "./dist/pages.d.ts",
39
+ "import": "./dist/pages.js"
40
+ },
41
+ "./module-pages": {
42
+ "types": "./module-pages.d.ts"
36
43
  }
37
44
  },
38
45
  "files": [
@@ -41,7 +48,8 @@
41
48
  "README.md",
42
49
  "AI.md",
43
50
  "LICENSE",
44
- "templates"
51
+ "templates",
52
+ "module-pages.d.ts"
45
53
  ],
46
54
  "engines": {
47
55
  "node": ">=24.0.0"
@@ -135,11 +143,11 @@
135
143
  ]
136
144
  },
137
145
  "devDependencies": {
138
- "@dokebi/i18n": "0.2.2",
139
- "@dokebi/session": "0.4.6",
140
- "@dokebi/web": "0.4.6",
141
- "@dokebi/websocket": "0.4.2",
142
- "@dokebi/websocket-hub": "0.4.2",
146
+ "@dokebi/i18n": "0.2.5",
147
+ "@dokebi/session": "0.4.8",
148
+ "@dokebi/web": "0.4.7",
149
+ "@dokebi/websocket": "0.4.4",
150
+ "@dokebi/websocket-hub": "0.4.3",
143
151
  "@inertiajs/vue3": "3.9.1",
144
152
  "vue": "3.5.44"
145
153
  },