@dokebi/template-inertia 0.4.21 → 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
@@ -301,6 +301,17 @@ A template can live apart from the app: a `views/<template>/` folder (Layout.vue
301
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`.
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
303
 
304
+ **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
+
306
+ **Working on a template (0.4.22).**
307
+
308
+ - **Preview:** `npx dokebi template preview <dir> [--port 5180] [--host 127.0.0.1] [--config <vite config>]` in the template repository starts a Vite dev server (HMR, the repository's real vue, Inertia and SDK packages; no app server). `/` lists every page and its cases; `/__dokebi/preview/<page>?case=<case>` draws one in the template's Layout, and a `<Link>` to another preview URL is an Inertia visit. API: `startTemplatePreview(options)` of `@dokebi/template-inertia/template` → `{ url, pages, close() }`.
309
+ - `Pages/<page>.preview.json` beside the page: an object of named cases, `{ "default": { "total": 12000 }, "empty cart": { "total": 0 } }` (JSON data, case names letters, digits, space, `_ . -`; a page without one gets the case `default` with no props). The first case is the one `/__dokebi/preview/<page>` draws.
310
+ - `preview.json` of the template folder: `{ "shared": { "app": { "name": "site", "template": "luxe" }, "auth": { … } } }`, under every case (the props the app's shared data gives in production).
311
+ - The preview files are not in the bundle: `template build` builds the `.vue` pages only.
312
+ - The template's own words (`locales/`) become the `i18n` prop of every case (in `preview.json`'s `locale`, else the first locale folder), so pages that call `t()` draw; a case that gives its own `i18n` keeps it. Keys only the app's catalogs have show as their key in the preview.
313
+ - **doctor** (`npx dokebi doctor`, `--production` on the server where the bundles are mounted) checks every bundle of `templates` as the app will: a key that is not an app (`TEMPLATE_APP_UNKNOWN`), a missing bundle (`TEMPLATE_BUNDLE_MISSING`), one the app would refuse (`TEMPLATE_BUNDLE_INVALID`, the check's problems in `details`), shared modules the app build does not provide in the same major version (`TEMPLATE_BUNDLE_SHARED`, against `dist/.vite/dokebi-shared.json` and `dist/ssr/.vite/dokebi-shared.json`; `TEMPLATE_SHARED_FILE_MISSING` without them), and an Inertia entry without `verifyTemplate` (`TEMPLATE_BUNDLE_UNVERIFIED`). With `--production` a missing bundle, a missing shared file and a missing `verifyTemplate` are errors; without, warnings (a laptop has no mounts).
314
+
304
315
  ## 5. SSR (D-0039)
305
316
 
306
317
  - `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).
@@ -322,6 +333,9 @@ A template can live apart from the app: a `views/<template>/` folder (Layout.vue
322
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.
323
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).
324
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.
325
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`).
326
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`).
327
341
  - Without Vite in the project the start fails (`VITE_DEV_MISSING`; `npm install --save-dev vite`).
@@ -384,6 +398,7 @@ A template can live apart from the app: a `views/<template>/` folder (Layout.vue
384
398
  | `TEMPLATE_APP_UNKNOWN` | `InertiaError` | (D-0291) a key of `templates` is not an app of @dokebi/app (`data.apps`): stops the start, fails a reload (§4.3) |
385
399
  | `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) |
386
400
  | `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
+ | `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) |
387
402
  | `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) |
388
403
  | `INVALID_PRUNE` | `InertiaUsageError` | `pruneBuildFiles` without a manifest path, or an `olderThanMs`, `maxManifestBytes` or `now` that is not a whole number from 0 |
389
404
 
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';
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';
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
@@ -24,6 +24,7 @@ const FIX = {
24
24
  SSR_INVALID_RESULT: 'The SSR render(page) must return { head: string[], body: string } whose body has the root element (rootId).',
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
+ 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).',
27
28
  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).',
28
29
  };
29
30
  /** Failures of @dokebi/template-inertia; compare `code`, not the class. */
package/dist/index.js CHANGED
@@ -299,6 +299,7 @@ const session = optionalDependency({
299
299
  name: 'dokebi-session',
300
300
  version: '^0.4.0',
301
301
  });
302
+ const i18n = optionalDependency({ name: 'dokebi-i18n', version: '^0.2.0' });
302
303
  /** The boot text of a scope for its debug record: the CSP hashes of its inline style and script. */
303
304
  function bootLog(options) {
304
305
  const boot = options.bootFallback;
@@ -863,11 +864,18 @@ class InertiaRuntime {
863
864
  const templateApps = Object.keys(this.settings.templates.templates);
864
865
  let templateRuntime;
865
866
  if (serving && !describing && !develop) {
867
+ const translations = context.getOptionalDependency(i18n);
866
868
  const loaded = new TemplateBundles({
867
869
  logger,
868
870
  settings: this.settings.templates,
869
871
  verify: this.entry.verifyTemplate,
870
872
  repeat: (key) => repeats.take(key),
873
+ // D-0291 stage 3b: a bundle's locales/ become its template's screen words.
874
+ ...(typeof translations?.templateBundle === 'function'
875
+ ? {
876
+ words: (app, template, directory) => translations.templateBundle(app, template, directory),
877
+ }
878
+ : {}),
871
879
  });
872
880
  templateRuntime = loaded;
873
881
  this.#templates = { bundles: loaded, server };
@@ -1203,12 +1211,12 @@ class InertiaRuntime {
1203
1211
  }
1204
1212
  export const createPlugin = definePlugin({
1205
1213
  name: 'dokebi-template-inertia',
1206
- version: '0.4.21',
1214
+ version: '0.4.23',
1207
1215
  core: '^0.4.2',
1208
1216
  options,
1209
1217
  entry: parseEntry,
1210
1218
  contributes: [viewEngines],
1211
1219
  collects: [viewData],
1212
- dependencies: () => [web, session],
1220
+ dependencies: () => [web, session, i18n],
1213
1221
  instance: ({ options, entry }) => new InertiaRuntime(settings(options), entry ?? {}),
1214
1222
  });
@@ -6,7 +6,7 @@
6
6
  // each page's files, stylesheets, preloads and `meta`, and the sha256 of every file. The bundle
7
7
  // is checked like the app will check it before it is returned.
8
8
  import { existsSync, readFileSync, realpathSync } from 'node:fs';
9
- import { lstat, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
9
+ import { lstat, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
10
10
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
11
11
  import { pathToFileURL } from 'node:url';
12
12
  import { ConsoleLogger } from '@dokebi/core';
@@ -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.21' };
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
  }
@@ -317,8 +317,31 @@ export async function buildTemplateBundle(options) {
317
317
  ...(meta === undefined ? {} : { meta }),
318
318
  };
319
319
  }
320
+ // D-0291 stage 3b: the template's screen words, locales/<locale>/<namespace>.json, as they are
321
+ // (the app's @dokebi/i18n reads them with its own loader and rules).
322
+ const wordsFolder = join(folder, 'locales');
323
+ let wordFiles = 0;
324
+ if (existsSync(wordsFolder))
325
+ for (const file of await listFiles(wordsFolder)) {
326
+ if (file.split('/').some((part) => part.startsWith('.')))
327
+ continue;
328
+ if (!/^[A-Za-z][A-Za-z0-9_-]{0,34}(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,99}){1,8}\.json$/.test(file))
329
+ throw usage(`locales/${file} is not a screen-word file: locales/<locale>/<namespace>.json (letters, digits, _ . -)`);
330
+ const text = await readFile(join(wordsFolder, file), 'utf8');
331
+ try {
332
+ const parsed = JSON.parse(text);
333
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
334
+ throw new Error('not an object of keys');
335
+ }
336
+ catch (cause) {
337
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `locales/${file} is not a JSON object of words: ${cause.message}`, { cause });
338
+ }
339
+ await mkdir(dirname(join(out, 'locales', file)), { recursive: true });
340
+ await writeFile(join(out, 'locales', file), text);
341
+ wordFiles++;
342
+ }
320
343
  const files = {};
321
- for (const top of ['browser', 'ssr'])
344
+ for (const top of wordFiles ? ['browser', 'ssr', 'locales'] : ['browser', 'ssr'])
322
345
  for (const file of await listFiles(join(out, top))) {
323
346
  const content = await readFile(join(out, top, file));
324
347
  files[`${top}/${file}`] = { bytes: content.length, sha256: sha256(content) };
@@ -356,6 +379,7 @@ export async function buildTemplateBundle(options) {
356
379
  buildId: result.buildId,
357
380
  out: relative(root, out),
358
381
  pages: result.pages.length,
382
+ words: wordFiles,
359
383
  files: result.files,
360
384
  bytes: result.bytes,
361
385
  shared: manifest.shared,
@@ -26,8 +26,13 @@ export const TEMPLATE_NAME = /^[a-z][a-z0-9-]{0,31}$/;
26
26
  export const TEMPLATE_VERSION = /^[0-9A-Za-z][0-9A-Za-z.+-]{0,63}$/;
27
27
  /** A page of a bundle: `Layout`, or `Pages/<path>` without the `.vue`. */
28
28
  export const TEMPLATE_PAGE = /^(?:Layout|Pages(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}){1,16})$/;
29
- /** A file of a bundle: under browser/ or ssr/, plain path segments only. */
30
- const FILE = /^(?:browser|ssr)(?:\/[A-Za-z0-9_@+][A-Za-z0-9_.@+-]{0,199}){1,32}$/;
29
+ /**
30
+ * A file of a bundle: under browser/ or ssr/, or a screen-word file `locales/<locale>/<ns>.json`
31
+ * (D-0291 stage 3b), plain path segments only.
32
+ */
33
+ const FILE = /^(?:(?:browser|ssr)(?:\/[A-Za-z0-9_@+][A-Za-z0-9_.@+-]{0,199}){1,32}|locales\/[A-Za-z][A-Za-z0-9_-]{0,34}(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,99}){1,8}\.json)$/;
34
+ /** The folders of a bundle. */
35
+ const FOLDERS = ['browser', 'ssr', 'locales'];
31
36
  /** A shared module specifier: a package name with an optional subpath. */
32
37
  export const SHARED_SPECIFIER = /^(?:@[a-z0-9][a-z0-9._-]{0,213}\/)?[a-z0-9][a-z0-9._-]{0,213}(?:\/[A-Za-z0-9_.@+-]{1,200}){0,16}$/;
33
38
  /** A page's `meta` (JSON) may take this many bytes. */
@@ -86,7 +91,7 @@ export function manifestProblem(value) {
86
91
  return 'files must be an object of path → { bytes, sha256 }';
87
92
  for (const [file, entry] of Object.entries(value.files)) {
88
93
  if (!FILE.test(file) || file.split('/').some((part) => part === '..' || part === '.'))
89
- return `file ${file} is not a path under browser/ or ssr/`;
94
+ return `file ${file} is not a path under browser/ or ssr/, or a locales/<locale>/<namespace>.json`;
90
95
  if (!plain(entry) ||
91
96
  !Number.isSafeInteger(entry.bytes) ||
92
97
  entry.bytes < 0 ||
@@ -238,7 +243,7 @@ export async function checkTemplateBundle(dir, limits = {}) {
238
243
  return { manifest, buildId, bytes: 0, problems };
239
244
  const found = [];
240
245
  const links = [];
241
- for (const top of ['browser', 'ssr']) {
246
+ for (const top of FOLDERS) {
242
247
  try {
243
248
  const info = await lstat(join(dir, top));
244
249
  if (!info.isDirectory()) {
@@ -255,12 +260,11 @@ export async function checkTemplateBundle(dir, limits = {}) {
255
260
  for (const entry of await readdir(dir, { withFileTypes: true }))
256
261
  if (entry.name !== TEMPLATE_MANIFEST &&
257
262
  entry.name !== TEMPLATE_SIGNATURE &&
258
- entry.name !== 'browser' &&
259
- entry.name !== 'ssr')
263
+ !FOLDERS.includes(entry.name))
260
264
  problems.push({
261
265
  code: 'TEMPLATE_FILE_EXTRA',
262
266
  file: entry.name,
263
- message: `${entry.name} is not part of a bundle (only ${TEMPLATE_MANIFEST}, ${TEMPLATE_SIGNATURE}, browser/ and ssr/)`,
267
+ message: `${entry.name} is not part of a bundle (only ${TEMPLATE_MANIFEST}, ${TEMPLATE_SIGNATURE}, browser/, ssr/ and locales/)`,
264
268
  });
265
269
  for (const link of links)
266
270
  problems.push({
@@ -0,0 +1,38 @@
1
+ import { type Logger } from '@dokebi/core';
2
+ /** Where a page is drawn: `/__dokebi/preview/<page>?case=<case>`. */
3
+ export declare const PREVIEW_PREFIX = "/__dokebi/preview/";
4
+ export interface TemplatePreviewOptions {
5
+ /** The template repository root (its node_modules has vite and @vitejs/plugin-vue). */
6
+ readonly root?: string;
7
+ /** The template folder, relative to root. */
8
+ readonly dir: string;
9
+ /** 0 picks a free port (default 5180). */
10
+ readonly port?: number;
11
+ /** Default 127.0.0.1 (loopback only). */
12
+ readonly host?: string;
13
+ /** A vite config of the project to merge; @vitejs/plugin-vue is added unless it has its own. */
14
+ readonly config?: string;
15
+ readonly logger?: Logger;
16
+ }
17
+ export interface TemplatePreviewPage {
18
+ /** The page name (`Home`, `board/List`), as `render(…, 'Home')` names it. */
19
+ readonly page: string;
20
+ readonly cases: readonly string[];
21
+ }
22
+ export interface TemplatePreview {
23
+ readonly url: string;
24
+ readonly pages: readonly TemplatePreviewPage[];
25
+ close(): Promise<void>;
26
+ }
27
+ /** The cases of one page (`<Page>.preview.json`): case → props, checked. */
28
+ export declare function previewCases(file: string): Promise<Record<string, Record<string, unknown>>>;
29
+ /**
30
+ * D-0291 stage 3b: the `i18n` page prop of the preview from the template's own words
31
+ * (`locales/<locale>/<namespace>.json`), so pages that call t() draw; undefined without words.
32
+ */
33
+ export declare function previewWords(folder: string, wanted?: string): Promise<Record<string, unknown> | undefined>;
34
+ /**
35
+ * Starts the preview of the template folder `options.dir` (D-0291 stage 3). Resolves once the
36
+ * server listens; `close()` stops it.
37
+ */
38
+ export declare function startTemplatePreview(options: TemplatePreviewOptions): Promise<TemplatePreview>;
@@ -0,0 +1,339 @@
1
+ // D-0291 stage 3: `dokebi template preview` — a Vite dev server in the template repository that
2
+ // draws every page of a template folder with made-up props, without an app server. `/` lists the
3
+ // pages and their cases; `/__dokebi/preview/<page>?case=<case>` draws one, in the template's
4
+ // Layout, with HMR. The props of a page are its `<Page>.preview.json` beside the .vue file:
5
+ //
6
+ // { "<case>": { …props }, "<another case>": { … } }
7
+ //
8
+ // (a page without one gets the case `default` with no props), over the `shared` of the
9
+ // template folder's `preview.json` (`{ "shared": { …props every page gets } }`). The shared
10
+ // modules (vue, @inertiajs/vue3, the SDK) are the template repository's installed packages.
11
+ // Inertia visits (a <Link> to another preview URL) are answered too.
12
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
13
+ import { readdir, readFile } from 'node:fs/promises';
14
+ import { basename, join, relative, resolve, sep } from 'node:path';
15
+ import { pathToFileURL } from 'node:url';
16
+ import { ConsoleLogger } from '@dokebi/core';
17
+ import { InertiaError, InertiaUsageError } from './errors.js';
18
+ import { packageEntry, templatePages } from './template-build.js';
19
+ import { jsonValue, TEMPLATE_PAGE } from './template-bundle.js';
20
+ import { vueTypeBarrels } from './vite-type-barrels.js';
21
+ import { registerVueTypeScript } from './vue-typescript.js';
22
+ /** Where a page is drawn: `/__dokebi/preview/<page>?case=<case>`. */
23
+ export const PREVIEW_PREFIX = '/__dokebi/preview/';
24
+ const ENTRY_URL = '/@dokebi-preview/entry.js';
25
+ const ENTRY_ID = '\0dokebi-preview-entry';
26
+ /** A preview file may take this many bytes. */
27
+ const PREVIEW_MAX_BYTES = 1024 * 1024;
28
+ /** A case name: what a URL may carry. */
29
+ const CASE = /^[A-Za-z0-9][A-Za-z0-9 _.-]{0,63}$/;
30
+ /** The cases of one page (`<Page>.preview.json`): case → props, checked. */
31
+ export async function previewCases(file) {
32
+ if (!existsSync(file))
33
+ return { default: {} };
34
+ const text = await readFile(file, 'utf8');
35
+ if (Buffer.byteLength(text) > PREVIEW_MAX_BYTES)
36
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${file} is larger than 1 MiB`);
37
+ let parsed;
38
+ try {
39
+ parsed = JSON.parse(text);
40
+ }
41
+ catch (error) {
42
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${file} is not JSON: ${error.message}`);
43
+ }
44
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
45
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${file} must be an object of case name → props ({ "default": { … } })`);
46
+ const cases = {};
47
+ for (const [name, props] of Object.entries(parsed)) {
48
+ if (!CASE.test(name))
49
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${file}: case ${JSON.stringify(name)} is not a case name (letters, digits, space, _ . -)`);
50
+ if (props === null || typeof props !== 'object' || Array.isArray(props) || !jsonValue(props))
51
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${file}: case ${name} must be an object of props (JSON data)`);
52
+ cases[name] = props;
53
+ }
54
+ if (Object.keys(cases).length === 0)
55
+ cases.default = {};
56
+ return cases;
57
+ }
58
+ /** The plural categories: an object of only these is one message, not a folder of keys. */
59
+ const PLURAL = new Set(['zero', 'one', 'two', 'few', 'many', 'other']);
60
+ /** `{ a: { b: 'x' } }` → `{ 'ns.a.b': 'x' }` (plural objects kept whole). */
61
+ function flatten(input, prefix, out) {
62
+ for (const [key, value] of Object.entries(input)) {
63
+ const name = `${prefix}.${key}`;
64
+ if (value !== null &&
65
+ typeof value === 'object' &&
66
+ !Array.isArray(value) &&
67
+ !Object.keys(value).every((part) => PLURAL.has(part)))
68
+ flatten(value, name, out);
69
+ else
70
+ out[name] = value;
71
+ }
72
+ }
73
+ /**
74
+ * D-0291 stage 3b: the `i18n` page prop of the preview from the template's own words
75
+ * (`locales/<locale>/<namespace>.json`), so pages that call t() draw; undefined without words.
76
+ */
77
+ export async function previewWords(folder, wanted) {
78
+ const root = join(folder, 'locales');
79
+ if (!existsSync(root))
80
+ return undefined;
81
+ const locales = (await readdir(root, { withFileTypes: true }))
82
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
83
+ .map((entry) => entry.name)
84
+ .sort();
85
+ const locale = wanted !== undefined && locales.includes(wanted) ? wanted : locales[0];
86
+ if (locale === undefined)
87
+ return undefined;
88
+ const messages = {};
89
+ const namespaces = [];
90
+ for (const entry of await readdir(join(root, locale), { withFileTypes: true })) {
91
+ if (!entry.isFile() || !entry.name.endsWith('.json') || entry.name.startsWith('.'))
92
+ continue;
93
+ const namespace = entry.name.slice(0, -'.json'.length);
94
+ namespaces.push(namespace);
95
+ flatten(JSON.parse(await readFile(join(root, locale, entry.name), 'utf8')), namespace, messages);
96
+ }
97
+ return {
98
+ locale,
99
+ version: 'preview',
100
+ fallback: [locale],
101
+ namespaces: namespaces.sort(),
102
+ messages: { [locale]: messages },
103
+ };
104
+ }
105
+ /** `preview.json` of the template folder: `{ shared, locale? }`. */
106
+ async function previewLocale(folder) {
107
+ const file = join(folder, 'preview.json');
108
+ if (!existsSync(file))
109
+ return undefined;
110
+ try {
111
+ const locale = JSON.parse(await readFile(file, 'utf8'))
112
+ ?.locale;
113
+ return typeof locale === 'string' ? locale : undefined;
114
+ }
115
+ catch {
116
+ // Its shape is reported by previewShared.
117
+ return undefined;
118
+ }
119
+ }
120
+ /** `preview.json` of the template folder: `{ shared }`. */
121
+ async function previewShared(folder) {
122
+ const file = join(folder, 'preview.json');
123
+ if (!existsSync(file))
124
+ return {};
125
+ let parsed;
126
+ try {
127
+ parsed = JSON.parse(await readFile(file, 'utf8'));
128
+ }
129
+ catch (error) {
130
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${file} is not JSON: ${error.message}`);
131
+ }
132
+ const shared = parsed?.shared ?? {};
133
+ if (shared === null || typeof shared !== 'object' || Array.isArray(shared) || !jsonValue(shared))
134
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${file} must be { "shared": { …props every page gets } }`);
135
+ return shared;
136
+ }
137
+ const escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]);
138
+ const scriptJson = (value) => JSON.stringify(value).replace(/</g, '\\u003c');
139
+ /**
140
+ * Starts the preview of the template folder `options.dir` (D-0291 stage 3). Resolves once the
141
+ * server listens; `close()` stops it.
142
+ */
143
+ export async function startTemplatePreview(options) {
144
+ const logger = options.logger ??
145
+ new ConsoleLogger({ level: 'info' }, { plugin: 'dokebi-template-inertia', process: 'template-preview' });
146
+ const root = resolve(options.root ?? process.cwd());
147
+ const folder = resolve(root, options.dir);
148
+ const inside = relative(root, folder);
149
+ if (!inside || inside.startsWith('..') || !existsSync(folder))
150
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${options.dir} must be a template folder inside ${root}`);
151
+ const pages = await templatePages(folder);
152
+ if (![...pages.keys()].some((key) => key.startsWith('Pages/')))
153
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${options.dir} has no Pages/**/*.vue`);
154
+ const viteEntry = packageEntry(root, 'vite');
155
+ if (!viteEntry)
156
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `vite is not installed in ${root}`, {
157
+ fix: 'npm install --save-dev vite @vitejs/plugin-vue',
158
+ });
159
+ const vite = (await import(pathToFileURL(viteEntry).href));
160
+ const configFile = options.config ? resolve(root, options.config) : undefined;
161
+ let ownVue = false;
162
+ if (configFile) {
163
+ const loaded = (await vite.loadConfigFromFile({ command: 'serve', mode: 'development' }, configFile, root)) ?? {
164
+ config: {},
165
+ };
166
+ ownVue = (loaded.config.plugins ?? [])
167
+ .flat(Infinity)
168
+ .some((plugin) => plugin?.name === 'vite:vue');
169
+ }
170
+ const vueEntry = ownVue ? undefined : packageEntry(root, '@vitejs/plugin-vue');
171
+ if (!ownVue && !vueEntry)
172
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `@vitejs/plugin-vue is not installed in ${root}`, {
173
+ fix: 'npm install --save-dev @vitejs/plugin-vue',
174
+ });
175
+ const vue = vueEntry
176
+ ? (await import(pathToFileURL(vueEntry).href))
177
+ .default
178
+ : undefined;
179
+ registerVueTypeScript(root, logger);
180
+ const folderUrl = `/${inside.split(sep).join('/')}`;
181
+ const names = [...pages.keys()]
182
+ .filter((key) => key.startsWith('Pages/'))
183
+ .map((key) => key.slice(6));
184
+ /** The page object of one preview URL. */
185
+ const pageObject = async (name, wanted) => {
186
+ const cases = await previewCases(join(folder, 'Pages', `${name}.preview.json`));
187
+ const chosen = wanted !== null && Object.hasOwn(cases, wanted) ? wanted : Object.keys(cases)[0];
188
+ const props = {
189
+ errors: {},
190
+ ...(await previewShared(folder)),
191
+ ...cases[chosen],
192
+ };
193
+ // D-0291 stage 3b: the template's own words, unless the case gives its own i18n.
194
+ if (props.i18n === undefined) {
195
+ const words = await previewWords(folder, await previewLocale(folder));
196
+ if (words) {
197
+ props.i18n = words;
198
+ props.locale ??= words.locale;
199
+ }
200
+ }
201
+ return {
202
+ cases: Object.keys(cases),
203
+ chosen,
204
+ page: {
205
+ component: name,
206
+ props,
207
+ url: `${PREVIEW_PREFIX}${name}?case=${encodeURIComponent(chosen)}`,
208
+ version: 'preview',
209
+ clearHistory: false,
210
+ encryptHistory: false,
211
+ },
212
+ };
213
+ };
214
+ const plugin = {
215
+ name: 'dokebi-template-preview',
216
+ enforce: 'pre',
217
+ resolveId: (source) => (source === ENTRY_URL ? ENTRY_ID : null),
218
+ load(id) {
219
+ if (id !== ENTRY_ID)
220
+ return null;
221
+ return `import { createInertiaApp, router } from '@inertiajs/vue3';
222
+ import { pageI18n } from '@dokebi/template-inertia/i18n';
223
+ import { createApp, h } from 'vue';
224
+ const files = import.meta.glob(${JSON.stringify(`${folderUrl}/{Layout,Pages/**/*}.vue`)});
225
+ const layoutFile = files[${JSON.stringify(`${folderUrl}/Layout.vue`)}];
226
+ const layout = layoutFile ? (await layoutFile()).default : undefined;
227
+ await createInertiaApp({
228
+ resolve: async (name) => {
229
+ const file = files[${JSON.stringify(`${folderUrl}/Pages/`)} + name + '.vue'];
230
+ if (!file) throw new Error('Unknown page: ' + name);
231
+ return file();
232
+ },
233
+ layout: () => layout,
234
+ setup({ el, App, props, plugin }) {
235
+ createApp({ render: () => h(App, props) }).use(plugin).use(pageI18n(props.initialPage, { router })).mount(el);
236
+ },
237
+ });
238
+ `;
239
+ },
240
+ configureServer(server) {
241
+ server.middlewares.use((request, response, next) => {
242
+ const url = new URL(request.url ?? '/', 'http://preview');
243
+ if (request.method !== 'GET' && request.method !== 'HEAD')
244
+ return next();
245
+ const send = (status, type, body, headers = {}) => {
246
+ response.statusCode = status;
247
+ response.setHeader('content-type', type);
248
+ response.setHeader('cache-control', 'no-store');
249
+ for (const [name, value] of Object.entries(headers))
250
+ response.setHeader(name, value);
251
+ response.end(request.method === 'HEAD' ? '' : body);
252
+ };
253
+ const fail = (error) => {
254
+ logger.log('error', 'Template preview could not draw a page', {
255
+ code: 'INERTIA_TEMPLATE_PREVIEW_FAILED',
256
+ url: url.pathname,
257
+ error: error.message,
258
+ });
259
+ send(500, 'text/html; charset=utf-8', `<!doctype html><pre>${escapeHtml(error.message)}</pre>`);
260
+ };
261
+ if (url.pathname === '/') {
262
+ Promise.all(names.map(async (name) => ({
263
+ name,
264
+ cases: Object.keys(await previewCases(join(folder, 'Pages', `${name}.preview.json`))),
265
+ }))).then((listed) => send(200, 'text/html; charset=utf-8', `<!doctype html><html><head><meta charset="utf-8"><title>${escapeHtml(basename(folder))} preview</title></head><body><h1>${escapeHtml(basename(folder))}</h1><ul>${listed
266
+ .map((item) => `<li data-page="${escapeHtml(item.name)}">${escapeHtml(item.name)}: ${item.cases
267
+ .map((name) => `<a href="${PREVIEW_PREFIX}${escapeHtml(item.name)}?case=${encodeURIComponent(name)}">${escapeHtml(name)}</a>`)
268
+ .join(' · ')}</li>`)
269
+ .join('')}</ul></body></html>`), fail);
270
+ return;
271
+ }
272
+ if (!url.pathname.startsWith(PREVIEW_PREFIX))
273
+ return next();
274
+ const name = decodeURIComponent(url.pathname.slice(PREVIEW_PREFIX.length));
275
+ if (!TEMPLATE_PAGE.test(`Pages/${name}`) || !names.includes(name))
276
+ return send(404, 'text/plain; charset=utf-8', `No page ${name} in ${options.dir}`);
277
+ pageObject(name, url.searchParams.get('case')).then(async ({ page }) => {
278
+ if (request.headers['x-inertia'] === 'true')
279
+ return send(200, 'application/json; charset=utf-8', JSON.stringify(page), {
280
+ 'x-inertia': 'true',
281
+ vary: 'X-Inertia',
282
+ });
283
+ const html = await server.transformIndexHtml(url.pathname, `<!doctype html><html><head><meta charset="utf-8"><title>${escapeHtml(name)} · preview</title><script type="module" src="${ENTRY_URL}"></script></head><body><script data-page="app" type="application/json">${scriptJson(page)}</script><div id="app"></div></body></html>`);
284
+ send(200, 'text/html; charset=utf-8', html);
285
+ }, fail);
286
+ });
287
+ },
288
+ };
289
+ let server;
290
+ try {
291
+ server = await vite.createServer({
292
+ root,
293
+ configFile: configFile ?? false,
294
+ logLevel: 'warn',
295
+ publicDir: false,
296
+ appType: 'custom',
297
+ plugins: [
298
+ ...(vue
299
+ ? [
300
+ vue({
301
+ script: {
302
+ fs: {
303
+ fileExists: (file) => existsSync(file),
304
+ readFile: (file) => readFileSync(file, 'utf8'),
305
+ realpath: (file) => realpathSync(file),
306
+ },
307
+ },
308
+ }),
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)] : []),
313
+ plugin,
314
+ ],
315
+ server: { port: options.port ?? 5180, host: options.host ?? '127.0.0.1', strictPort: false },
316
+ });
317
+ await server.listen();
318
+ }
319
+ catch (cause) {
320
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `The preview server of ${options.dir} did not start`, {
321
+ cause,
322
+ });
323
+ }
324
+ const address = server.httpServer?.address();
325
+ const port = typeof address === 'object' && address ? address.port : (options.port ?? 5180);
326
+ const host = options.host ?? '127.0.0.1';
327
+ const url = `http://${host.includes(':') ? `[${host}]` : host}:${port}/`;
328
+ const listed = await Promise.all(names.map(async (name) => ({
329
+ page: name,
330
+ cases: Object.keys(await previewCases(join(folder, 'Pages', `${name}.preview.json`))),
331
+ })));
332
+ logger.log('info', 'Template preview started', {
333
+ code: 'INERTIA_TEMPLATE_PREVIEW',
334
+ url,
335
+ dir: options.dir,
336
+ pages: listed.length,
337
+ });
338
+ return { url, pages: listed, close: () => server.close() };
339
+ }
@@ -110,6 +110,18 @@ export interface TemplateBundlesOptions {
110
110
  /** `logRepeatWindowMs`: a failure of the same cause is said once per window. */
111
111
  readonly repeat: (key: string) => number | false | undefined;
112
112
  readonly production?: boolean;
113
+ /**
114
+ * D-0291 stage 3b: puts a bundle's `locales/` into the page bundles of its template
115
+ * (@dokebi/i18n `templateBundle`); `undefined` takes them out. Absent without @dokebi/i18n.
116
+ */
117
+ readonly words?: (app: string, template: string, directory: string | undefined) => Promise<{
118
+ ok: true;
119
+ keys: number;
120
+ locales: readonly string[];
121
+ } | {
122
+ ok: false;
123
+ reason: string;
124
+ }>;
113
125
  }
114
126
  /** Every app's template bundles. */
115
127
  export declare class TemplateBundles {