@dokebi/template-inertia 0.4.19 → 0.4.20
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 +21 -0
- package/README.md +4 -0
- package/dist/errors.d.ts +2 -2
- package/dist/errors.js +3 -0
- package/dist/index.js +1 -1
- package/dist/template-build.d.ts +43 -0
- package/dist/template-build.js +335 -0
- package/dist/template-bundle.d.ts +102 -0
- package/dist/template-bundle.js +344 -0
- package/dist/template-shared.d.ts +93 -0
- package/dist/template-shared.js +197 -0
- package/dist/template.d.ts +3 -0
- package/dist/template.js +5 -0
- package/dist/vite-plugin.d.ts +20 -2
- package/dist/vite-plugin.js +24 -0
- package/package.json +6 -2
package/AI.md
CHANGED
|
@@ -247,6 +247,24 @@ A module keeps its Vue pages in its own views folder (@dokebi/module AI.md §4a)
|
|
|
247
247
|
- 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).
|
|
248
248
|
- 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`.
|
|
249
249
|
|
|
250
|
+
### 4.3 Template bundles (0.4.20, D-0291: the build side)
|
|
251
|
+
|
|
252
|
+
A template can live apart from the app: a `views/<template>/` folder (Layout.vue, `Pages/**`, its components and styles) built in another repository into a **bundle** that the app loads while it runs. 0.4.20 is the build side. The loading side (options `templates.<app>.<template>.path`, the import map, server rendering, swapping without downtime, `verifyTemplate`) comes in the next stage; until then a bundle is built and checked, not served.
|
|
253
|
+
|
|
254
|
+
- **The app provides the shared modules.** In both vite configs of the app (`vite.config.ts` and `vite.ssr.config.ts`), give the same list:
|
|
255
|
+
```ts snippet
|
|
256
|
+
dokebiInertia({ templates: { shared: ['@shop/sdk', '@shop/sdk/components'] } })
|
|
257
|
+
```
|
|
258
|
+
Every `vite build` then adds one entry per shared module (`dokebi-shared/<module>`: every export of the module and its default) and writes `<outDir>/.vite/dokebi-shared.json` (`{ format: 1, ssr, base, modules: { <module>: { file, version } } }`). vue, vue/server-renderer (server build only), @inertiajs/vue3 and @dokebi/template-inertia/{i18n,pages} are always provided. Entries of one build share module instances, so a bundle page that imports `vue` or the SDK through them gets the app's own instance: one reactivity, one provide/inject, one `pageI18n`. Name the SDK as a package (a workspace package, or a package of the app), not a relative path: the bundle imports it by that name. Without `templates` the build is as before.
|
|
259
|
+
- **The template repository builds the bundle:** `npx dokebi template build <dir> --shared @shop/sdk` (it needs `@dokebi/template-inertia`, `vite`, `@vitejs/plugin-vue`, `vue` and the SDK package installed; `--name` defaults to the folder name, `--version` to package.json). It runs a browser build and a server build with one entry per page, keeps every shared module an import, and writes `dist/template/<name>/`:
|
|
260
|
+
- `dokebi-template.json` (format 1): `name`, `version`, `builtWith`, `shared` (each shared module the pages import, with the version it was built with), `pages` (`Layout`, `Pages/<path>` → `browser`, `css`, `preload`, `ssr`, `meta`), `files` (every file's `bytes` and `sha256`).
|
|
261
|
+
- `browser/`, `ssr/`: the modules, chunks, stylesheets and assets (relative URLs, so the bundle can be served under any path).
|
|
262
|
+
- A page's contract goes in a plain `<script>` block beside `<script setup>`: `export const meta = { contract: 'checkout@2' }`. The build reads it from the server module and writes it into `pages.<page>.meta` (JSON data, at most 4 KiB). The framework never interprets it; the app's check will.
|
|
263
|
+
- The signature (`dokebi-template.sig`) is the template repository's next step: sign the manifest (its file hashes cover the rest).
|
|
264
|
+
- The same source builds the same bundle (`buildId` = the first 12 hex of the manifest's sha256).
|
|
265
|
+
- **`npx dokebi template check <dir>`** checks a bundle as the app will: the manifest's shape and format, every file's size and sha256, no file the manifest does not list, no link, the size limit; `--against <app>/dist/.vite/dokebi-shared.json` also checks that the app provides every shared module the bundle imports, in the same major version (0.x: minor). Codes: `TEMPLATE_MANIFEST_MISSING`, `TEMPLATE_MANIFEST_INVALID`, `TEMPLATE_FORMAT_UNSUPPORTED`, `TEMPLATE_FILE_MISSING`, `TEMPLATE_FILE_CHANGED`, `TEMPLATE_FILE_EXTRA`, `TEMPLATE_FILE_LINK`, `TEMPLATE_TOO_LARGE`, `TEMPLATE_PAGE_FILE_UNKNOWN`, `TEMPLATE_SHARED_MISSING`, `TEMPLATE_SHARED_VERSION`. Run it in the template repository's CI after the build.
|
|
266
|
+
- The same API is `@dokebi/template-inertia/template`: `buildTemplateBundle(options)`, `checkTemplateBundle(dir, limits)`, `sharedProblems(bundle, provided)`.
|
|
267
|
+
|
|
250
268
|
## 5. SSR (D-0039)
|
|
251
269
|
|
|
252
270
|
- `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).
|
|
@@ -327,6 +345,9 @@ A module keeps its Vue pages in its own views folder (@dokebi/module AI.md §4a)
|
|
|
327
345
|
| `INVALID_URL` | `InertiaUsageError` | a redirect or asset that is not a local absolute URL; a location that is neither that nor an http(s) URL |
|
|
328
346
|
| `INVALID_PROP_HELPER` | `InertiaUsageError` | bad arguments to `defer`, `merge` or `once` |
|
|
329
347
|
| `SSR_INVALID_RESULT` | `InertiaUsageError` | the SSR `render` did not return `{ head, body }` or the body has no root element |
|
|
348
|
+
| `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) |
|
|
349
|
+
| `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) |
|
|
350
|
+
| `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) |
|
|
330
351
|
| `INVALID_PRUNE` | `InertiaUsageError` | `pruneBuildFiles` without a manifest path, or an `olderThanMs`, `maxManifestBytes` or `now` that is not a whole number from 0 |
|
|
331
352
|
|
|
332
353
|
## 7. Cautions
|
package/README.md
CHANGED
|
@@ -92,6 +92,10 @@ With `DOKEBI_VITE_DEV=1` (set by `dokebi dev`) the project's Vite starts in midd
|
|
|
92
92
|
|
|
93
93
|
The dev server serves only what the browser loads (D-0129): the views folders of the apps, the folders of the browser entries, `node_modules` and the files those modules import. `dokebi.yaml`, `.env`, `.dokebi/`, keys, compose files and the server code (`src/` outside `views/`, `tests/`, `scripts/`) answer 403 by every spelling (`?raw`, `/@fs/`, encoded, other letter cases, symlinks), and a remote host such as a `devHosts` tunnel gets a short 403 without paths. `dokebiInertia()` enforces this and the Vite host of `dokebi dev` adds it to a config without the plugin; the app may add to `server.fs.allow` and `deny` (or `dokebiInertia({ allow, deny })`) but never remove the framework's entries. Details: AI.md §5.2.
|
|
94
94
|
|
|
95
|
+
## Template bundles (0.4.20, [D-0291](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0291-template-bundles-at-runtime.md), build side)
|
|
96
|
+
|
|
97
|
+
A `views/<template>/` folder can be built in another repository into a bundle an app loads while it runs. `dokebiInertia({ templates: { shared: ['@shop/sdk'] } })` makes the app's builds provide the shared modules (vue, @inertiajs/vue3, the SDK) and list them in `dist/.vite/dokebi-shared.json`; `npx dokebi template build <dir> --shared @shop/sdk` builds the bundle (`dokebi-template.json`, `browser/`, `ssr/`, page `meta`, file hashes) and `npx dokebi template check <dir>` checks it. Loading bundles in the app is the next stage. Details in AI.md §4.3.
|
|
98
|
+
|
|
95
99
|
## Public pages (0.4.6, D-0195)
|
|
96
100
|
|
|
97
101
|
`render(request, reply, component, props, { public: true, head })` marks a page whose first HTML is the same for every visitor: it carries the render's props and the public shared props (view data a plugin calls public, such as @dokebi/i18n's, and `publicShared` of the entry and the scope), while the visitor's own (`auth`, `csrf`, the entry's `shared`) are named in the deferred group `dokebi-visitor` and fetched by the client right after it starts. On a seal host that HTML is plain and server rendered (with `<meta name="dokebi-seal" content="host">`, which tells `sealInertia` to seal everything after it), so crawlers read the page. `public: { cacheControl }` lets a shared cache keep it (an answer that sets a cookie stays `no-store`). `head` writes escaped title, description, canonical, robots, `hreflang` alternates and meta tags into the first HTML of any page, sealed ones included. Details: AI.md §3.5; example `examples/80-sealed-public-ssr`.
|
package/dist/errors.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
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' | 'MODULE_PAGES_APP_MISSING' | 'MODULE_PAGES_FAILED';
|
|
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';
|
|
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';
|
|
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';
|
|
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
|
@@ -13,6 +13,7 @@ const FIX = {
|
|
|
13
13
|
CLOSED: 'Render only while the application runs.',
|
|
14
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
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.",
|
|
16
|
+
TEMPLATE_BUILD_FAILED: 'Fix what the cause names (a page that does not compile, a module that is neither installed nor shared, a meta export that is not JSON data), then run npx dokebi template build again (D-0291).',
|
|
16
17
|
INVALID_ENTRY: 'The Inertia entry (src/infra/inertia/shared.ts) exports only shared: (request) => props and publicShared: (request) => props.',
|
|
17
18
|
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.',
|
|
18
19
|
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).',
|
|
@@ -21,6 +22,8 @@ const FIX = {
|
|
|
21
22
|
INVALID_PROP_HELPER: 'defer(fn, { group? }), merge(value, { deep?, matchOn? }), once(value, { key? }): a JSON value or a function, with the documented options.',
|
|
22
23
|
SSR_INVALID_RESULT: 'The SSR render(page) must return { head: string[], body: string } whose body has the root element (rootId).',
|
|
23
24
|
INVALID_PRUNE: "pruneBuildFiles({ manifest: 'dist/.vite/manifest.json', olderThanMs?, dryRun?, maxManifestBytes?, now? }): a manifest path, and whole non-negative numbers.",
|
|
25
|
+
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).",
|
|
26
|
+
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).',
|
|
24
27
|
};
|
|
25
28
|
/** Failures of @dokebi/template-inertia; compare `code`, not the class. */
|
|
26
29
|
export class InertiaError extends DokebiError {
|
package/dist/index.js
CHANGED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { type Logger } from '@dokebi/core';
|
|
2
|
+
export interface TemplateBuildOptions {
|
|
3
|
+
/** The project (template repository) root: its node_modules has vite and @vitejs/plugin-vue. Default: the working directory. */
|
|
4
|
+
readonly root?: string;
|
|
5
|
+
/** The template folder, relative to root (Layout.vue, Pages/**). */
|
|
6
|
+
readonly dir: string;
|
|
7
|
+
/** Where the bundle goes, inside root. Default: dist/template/<name>. Emptied first. */
|
|
8
|
+
readonly out?: string;
|
|
9
|
+
/** The template name. Default: the folder name. */
|
|
10
|
+
readonly name?: string;
|
|
11
|
+
/** The template version. Default: the version of root's package.json. */
|
|
12
|
+
readonly version?: string;
|
|
13
|
+
/** The app's modules the pages import and the app provides (its SDK), besides the defaults. */
|
|
14
|
+
readonly shared?: readonly string[];
|
|
15
|
+
/** The largest bundle allowed (default 50 MiB, like the app's default limit). */
|
|
16
|
+
readonly maxBytes?: number;
|
|
17
|
+
/** A vite config file of the project to merge (aliases, more plugins). Default: none. */
|
|
18
|
+
readonly config?: string;
|
|
19
|
+
readonly logger?: Logger;
|
|
20
|
+
}
|
|
21
|
+
export interface TemplateBuildResult {
|
|
22
|
+
/** The bundle folder (absolute). */
|
|
23
|
+
readonly out: string;
|
|
24
|
+
readonly name: string;
|
|
25
|
+
readonly version: string;
|
|
26
|
+
readonly buildId: string;
|
|
27
|
+
readonly pages: readonly string[];
|
|
28
|
+
/** The shared modules the pages import → their versions in this project. */
|
|
29
|
+
readonly shared: Readonly<Record<string, string | null>>;
|
|
30
|
+
readonly files: number;
|
|
31
|
+
readonly bytes: number;
|
|
32
|
+
readonly ms: number;
|
|
33
|
+
}
|
|
34
|
+
/** The ESM entry file of an installed package of the project (exports `.` → import/default, else module/main). */
|
|
35
|
+
export declare function packageEntry(root: string, name: string): string | undefined;
|
|
36
|
+
/** The pages of a template folder: `Layout` and `Pages/<path>` → their .vue file. */
|
|
37
|
+
export declare function templatePages(folder: string): Promise<Map<string, string>>;
|
|
38
|
+
/**
|
|
39
|
+
* Builds the template folder `options.dir` of `options.root` into a bundle at `options.out`
|
|
40
|
+
* (D-0291). Throws INVALID_TEMPLATE_BUILD for wrong options and TEMPLATE_BUILD_FAILED for a
|
|
41
|
+
* build that fails, with the cause.
|
|
42
|
+
*/
|
|
43
|
+
export declare function buildTemplateBundle(options: TemplateBuildOptions): Promise<TemplateBuildResult>;
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
// D-0291 §7: `dokebi template build` — builds a template folder (`views/<template>/` shape:
|
|
2
|
+
// Layout.vue, Pages/**/*.vue, the components and styles they import) into a bundle
|
|
3
|
+
// (template-bundle.ts) apart from any app. Runs in the template repository, with the project's own
|
|
4
|
+
// Vite and @vitejs/plugin-vue: one browser build and one server build, an entry per page, the
|
|
5
|
+
// shared modules (vue, @inertiajs/vue3, the app's SDK, …) left as imports, then the manifest with
|
|
6
|
+
// each page's files, stylesheets, preloads and `meta`, and the sha256 of every file. The bundle
|
|
7
|
+
// is checked like the app will check it before it is returned.
|
|
8
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
9
|
+
import { lstat, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
|
10
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
11
|
+
import { pathToFileURL } from 'node:url';
|
|
12
|
+
import { ConsoleLogger } from '@dokebi/core';
|
|
13
|
+
import { InertiaError, InertiaUsageError } from './errors.js';
|
|
14
|
+
import { checkTemplateBundle, jsonValue, PAGE_META_MAX_BYTES, SHARED_DEFAULTS, SHARED_SPECIFIER, sha256, TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_MAX_BYTES, TEMPLATE_NAME, TEMPLATE_PAGE, TEMPLATE_VERSION, } from './template-bundle.js';
|
|
15
|
+
import { packageVersion } from './template-shared.js';
|
|
16
|
+
/** The builder written into `builtWith` (scripts/testing/check-metadata.mjs keeps it the package version). */
|
|
17
|
+
const BUILDER = { name: 'dokebi-template-inertia', version: '0.4.20' };
|
|
18
|
+
function defaultLogger() {
|
|
19
|
+
return new ConsoleLogger({ level: 'info' }, { plugin: 'dokebi-template-inertia', process: 'template-build' });
|
|
20
|
+
}
|
|
21
|
+
const usage = (message) => new InertiaUsageError('INVALID_TEMPLATE_BUILD', message);
|
|
22
|
+
/** `a` is `b` or inside it. */
|
|
23
|
+
function within(a, b) {
|
|
24
|
+
const path = relative(b, a);
|
|
25
|
+
return path === '' || (!path.startsWith('..') && !isAbsolute(path));
|
|
26
|
+
}
|
|
27
|
+
/** The ESM entry file of an installed package of the project (exports `.` → import/default, else module/main). */
|
|
28
|
+
export function packageEntry(root, name) {
|
|
29
|
+
for (let dir = resolve(root);; dir = dirname(dir)) {
|
|
30
|
+
const folder = join(dir, 'node_modules', name);
|
|
31
|
+
const file = join(folder, 'package.json');
|
|
32
|
+
if (existsSync(file)) {
|
|
33
|
+
const json = JSON.parse(readFileSync(file, 'utf8'));
|
|
34
|
+
const pick = (value) => {
|
|
35
|
+
if (typeof value === 'string')
|
|
36
|
+
return value;
|
|
37
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
38
|
+
return undefined;
|
|
39
|
+
const record = value;
|
|
40
|
+
if ('.' in record)
|
|
41
|
+
return pick(record['.']);
|
|
42
|
+
return pick(record.import) ?? pick(record.default) ?? pick(record.node);
|
|
43
|
+
};
|
|
44
|
+
const entry = pick(json.exports) ?? json.module ?? json.main ?? 'index.js';
|
|
45
|
+
return join(folder, entry);
|
|
46
|
+
}
|
|
47
|
+
if (dirname(dir) === dir)
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
async function importPackage(root, name, fix) {
|
|
52
|
+
const entry = packageEntry(root, name);
|
|
53
|
+
if (entry === undefined)
|
|
54
|
+
throw new InertiaError('TEMPLATE_BUILD_FAILED', `${name} is not installed in ${root}`, {
|
|
55
|
+
fix,
|
|
56
|
+
});
|
|
57
|
+
return (await import(pathToFileURL(entry).href));
|
|
58
|
+
}
|
|
59
|
+
/** The pages of a template folder: `Layout` and `Pages/<path>` → their .vue file. */
|
|
60
|
+
export async function templatePages(folder) {
|
|
61
|
+
const pages = new Map();
|
|
62
|
+
const layout = join(folder, 'Layout.vue');
|
|
63
|
+
if (existsSync(layout))
|
|
64
|
+
pages.set('Layout', layout);
|
|
65
|
+
const walk = async (dir) => {
|
|
66
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
67
|
+
const path = join(dir, entry.name);
|
|
68
|
+
if (entry.isDirectory())
|
|
69
|
+
await walk(path);
|
|
70
|
+
else if (entry.isFile() && entry.name.endsWith('.vue')) {
|
|
71
|
+
const key = relative(folder, path).split(sep).join('/').slice(0, -'.vue'.length);
|
|
72
|
+
if (!TEMPLATE_PAGE.test(key))
|
|
73
|
+
throw usage(`${relative(folder, path)} is not a page name: Pages/ paths are letters, digits, _, . and - (at most 16 folders deep)`);
|
|
74
|
+
pages.set(key, path);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
if (existsSync(join(folder, 'Pages')))
|
|
79
|
+
await walk(join(folder, 'Pages'));
|
|
80
|
+
return pages;
|
|
81
|
+
}
|
|
82
|
+
/** Every file under a folder, relative with `/`. */
|
|
83
|
+
async function listFiles(dir, root = dir, found = []) {
|
|
84
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
85
|
+
const path = join(dir, entry.name);
|
|
86
|
+
if (entry.isDirectory())
|
|
87
|
+
await listFiles(path, root, found);
|
|
88
|
+
else if (entry.isFile())
|
|
89
|
+
found.push(relative(root, path).split(sep).join('/'));
|
|
90
|
+
}
|
|
91
|
+
return found;
|
|
92
|
+
}
|
|
93
|
+
const outputs = (result) => (Array.isArray(result) ? result : [result]).flatMap((item) => item.output ?? []);
|
|
94
|
+
/**
|
|
95
|
+
* Builds the template folder `options.dir` of `options.root` into a bundle at `options.out`
|
|
96
|
+
* (D-0291). Throws INVALID_TEMPLATE_BUILD for wrong options and TEMPLATE_BUILD_FAILED for a
|
|
97
|
+
* build that fails, with the cause.
|
|
98
|
+
*/
|
|
99
|
+
export async function buildTemplateBundle(options) {
|
|
100
|
+
const begin = performance.now();
|
|
101
|
+
const logger = options.logger ?? defaultLogger();
|
|
102
|
+
const root = resolve(options.root ?? process.cwd());
|
|
103
|
+
if (typeof options.dir !== 'string' || options.dir === '')
|
|
104
|
+
throw usage('dir is required');
|
|
105
|
+
const folder = resolve(root, options.dir);
|
|
106
|
+
if (!within(folder, root) || folder === root)
|
|
107
|
+
throw usage(`${options.dir} must be a folder inside ${root}, not the project itself`);
|
|
108
|
+
if (!existsSync(folder) || !(await stat(folder)).isDirectory())
|
|
109
|
+
throw usage(`${options.dir} is not a folder`);
|
|
110
|
+
const name = options.name ?? basename(folder);
|
|
111
|
+
if (!TEMPLATE_NAME.test(name))
|
|
112
|
+
throw usage(`${name} is not a template name (^[a-z][a-z0-9-]{0,31}$); pass --name`);
|
|
113
|
+
let version = options.version;
|
|
114
|
+
if (version === undefined) {
|
|
115
|
+
try {
|
|
116
|
+
const own = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
|
|
117
|
+
if (typeof own.version === 'string')
|
|
118
|
+
version = own.version;
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
// No readable package.json: --version is needed (the usage error below says so).
|
|
122
|
+
logger.log('debug', 'Template version not read from package.json', {
|
|
123
|
+
root,
|
|
124
|
+
error: error.message,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (version === undefined || !TEMPLATE_VERSION.test(version))
|
|
129
|
+
throw usage(`the template version ${version === undefined ? 'is missing' : `${version} is not letters, digits, . + -`}: pass --version or set version in package.json`);
|
|
130
|
+
const own = options.shared ?? [];
|
|
131
|
+
for (const module of own)
|
|
132
|
+
if (typeof module !== 'string' || !SHARED_SPECIFIER.test(module))
|
|
133
|
+
throw new InertiaUsageError('INVALID_TEMPLATE_SHARED', `--shared ${String(module)} is not a package name with an optional subpath`);
|
|
134
|
+
const shared = [...new Set([...SHARED_DEFAULTS, ...own])];
|
|
135
|
+
const out = resolve(root, options.out ?? join('dist', 'template', name));
|
|
136
|
+
if (!within(out, root) || within(root, out) || within(folder, out) || within(out, folder))
|
|
137
|
+
throw usage(`--out ${relative(root, out) || '.'} must be a folder inside the project, apart from the template folder (the build imports the server pages from there)`);
|
|
138
|
+
if (existsSync(out)) {
|
|
139
|
+
const info = await lstat(out);
|
|
140
|
+
if (!info.isDirectory())
|
|
141
|
+
throw usage(`--out ${out} is not a folder`);
|
|
142
|
+
const present = await readdir(out);
|
|
143
|
+
if (present.length && !present.includes(TEMPLATE_MANIFEST))
|
|
144
|
+
throw usage(`--out ${out} holds files and no ${TEMPLATE_MANIFEST}: it is not an earlier bundle, so it is not emptied`);
|
|
145
|
+
await rm(out, { recursive: true, force: true });
|
|
146
|
+
}
|
|
147
|
+
const pages = await templatePages(folder);
|
|
148
|
+
if (pages.size === 0)
|
|
149
|
+
throw usage(`${options.dir} has no Layout.vue and no Pages/**/*.vue`);
|
|
150
|
+
const input = Object.fromEntries(pages);
|
|
151
|
+
const vite = await importPackage(root, 'vite', 'Install Vite in the template repository: npm install --save-dev vite');
|
|
152
|
+
const vue = options.config
|
|
153
|
+
? undefined
|
|
154
|
+
: await importPackage(root, '@vitejs/plugin-vue', 'Install the Vue plugin in the template repository: npm install --save-dev @vitejs/plugin-vue');
|
|
155
|
+
const isShared = (id) => shared.includes(id);
|
|
156
|
+
logger.log('info', 'Template bundle build started', {
|
|
157
|
+
code: 'INERTIA_TEMPLATE_BUILD_STARTED',
|
|
158
|
+
name,
|
|
159
|
+
version,
|
|
160
|
+
dir: relative(root, folder),
|
|
161
|
+
out: relative(root, out),
|
|
162
|
+
pages: pages.size,
|
|
163
|
+
shared,
|
|
164
|
+
});
|
|
165
|
+
const common = {
|
|
166
|
+
root,
|
|
167
|
+
configFile: options.config ? resolve(root, options.config) : false,
|
|
168
|
+
logLevel: 'warn',
|
|
169
|
+
publicDir: false,
|
|
170
|
+
plugins: vue ? [vue.default()] : [],
|
|
171
|
+
};
|
|
172
|
+
const imported = new Set();
|
|
173
|
+
const collect = (items) => {
|
|
174
|
+
for (const item of items)
|
|
175
|
+
for (const id of [...(item.imports ?? []), ...(item.dynamicImports ?? [])])
|
|
176
|
+
if (isShared(id))
|
|
177
|
+
imported.add(id);
|
|
178
|
+
};
|
|
179
|
+
let browserItems;
|
|
180
|
+
let serverItems;
|
|
181
|
+
try {
|
|
182
|
+
browserItems = outputs(await vite.build({
|
|
183
|
+
...common,
|
|
184
|
+
base: './',
|
|
185
|
+
build: {
|
|
186
|
+
outDir: join(out, 'browser'),
|
|
187
|
+
emptyOutDir: true,
|
|
188
|
+
manifest: true,
|
|
189
|
+
cssCodeSplit: true,
|
|
190
|
+
modulePreload: false,
|
|
191
|
+
copyPublicDir: false,
|
|
192
|
+
rollupOptions: {
|
|
193
|
+
input,
|
|
194
|
+
external: isShared,
|
|
195
|
+
preserveEntrySignatures: 'strict',
|
|
196
|
+
output: {
|
|
197
|
+
entryFileNames: 'pages/[name]-[hash].js',
|
|
198
|
+
chunkFileNames: 'chunks/[name]-[hash].js',
|
|
199
|
+
assetFileNames: 'assets/[name]-[hash][extname]',
|
|
200
|
+
},
|
|
201
|
+
},
|
|
202
|
+
},
|
|
203
|
+
}));
|
|
204
|
+
serverItems = outputs(await vite.build({
|
|
205
|
+
...common,
|
|
206
|
+
ssr: { noExternal: true },
|
|
207
|
+
build: {
|
|
208
|
+
ssr: true,
|
|
209
|
+
outDir: join(out, 'ssr'),
|
|
210
|
+
emptyOutDir: true,
|
|
211
|
+
copyPublicDir: false,
|
|
212
|
+
rollupOptions: {
|
|
213
|
+
input,
|
|
214
|
+
external: isShared,
|
|
215
|
+
preserveEntrySignatures: 'strict',
|
|
216
|
+
output: {
|
|
217
|
+
format: 'es',
|
|
218
|
+
entryFileNames: 'pages/[name].js',
|
|
219
|
+
chunkFileNames: 'chunks/[name]-[hash].js',
|
|
220
|
+
},
|
|
221
|
+
},
|
|
222
|
+
},
|
|
223
|
+
}));
|
|
224
|
+
}
|
|
225
|
+
catch (cause) {
|
|
226
|
+
throw new InertiaError('TEMPLATE_BUILD_FAILED', `The Vite build of ${name} failed`, { cause });
|
|
227
|
+
}
|
|
228
|
+
collect(browserItems);
|
|
229
|
+
collect(serverItems);
|
|
230
|
+
// The browser manifest gives each page its stylesheets and the chunks it imports.
|
|
231
|
+
const manifestPath = join(out, 'browser', '.vite', 'manifest.json');
|
|
232
|
+
const vm = JSON.parse(await readFile(manifestPath, 'utf8'));
|
|
233
|
+
await rm(join(out, 'browser', '.vite'), { recursive: true, force: true });
|
|
234
|
+
const byName = new Map();
|
|
235
|
+
for (const entry of Object.values(vm))
|
|
236
|
+
if (entry.isEntry && entry.name)
|
|
237
|
+
byName.set(entry.name, entry);
|
|
238
|
+
const server = new Map();
|
|
239
|
+
for (const item of serverItems)
|
|
240
|
+
if (item.type === 'chunk' && item.isEntry && item.name)
|
|
241
|
+
server.set(item.name, item.fileName);
|
|
242
|
+
const pageEntries = {};
|
|
243
|
+
for (const page of pages.keys()) {
|
|
244
|
+
const entry = byName.get(page);
|
|
245
|
+
const ssrFile = server.get(page);
|
|
246
|
+
if (entry === undefined || ssrFile === undefined)
|
|
247
|
+
throw new InertiaError('TEMPLATE_BUILD_FAILED', `The build has no entry for ${page} (browser ${entry ? 'yes' : 'no'}, server ${ssrFile ? 'yes' : 'no'})`);
|
|
248
|
+
const css = [];
|
|
249
|
+
const preload = [];
|
|
250
|
+
const seen = new Set();
|
|
251
|
+
const visit = (key) => {
|
|
252
|
+
if (seen.has(key))
|
|
253
|
+
return;
|
|
254
|
+
seen.add(key);
|
|
255
|
+
const chunk = vm[key];
|
|
256
|
+
if (!chunk)
|
|
257
|
+
return;
|
|
258
|
+
for (const next of chunk.imports ?? [])
|
|
259
|
+
visit(next);
|
|
260
|
+
if (chunk !== entry)
|
|
261
|
+
preload.push(`browser/${chunk.file}`);
|
|
262
|
+
for (const file of chunk.css ?? [])
|
|
263
|
+
if (!css.includes(`browser/${file}`))
|
|
264
|
+
css.push(`browser/${file}`);
|
|
265
|
+
};
|
|
266
|
+
const key = Object.keys(vm).find((candidate) => vm[candidate] === entry);
|
|
267
|
+
visit(key);
|
|
268
|
+
let meta;
|
|
269
|
+
try {
|
|
270
|
+
const module = (await import(`${pathToFileURL(join(out, 'ssr', ssrFile)).href}?build=${Date.now()}`));
|
|
271
|
+
meta = module.meta;
|
|
272
|
+
}
|
|
273
|
+
catch (cause) {
|
|
274
|
+
throw new InertiaError('TEMPLATE_BUILD_FAILED', `The server module of ${page} could not be imported to read its meta: ${cause.message}`, { cause });
|
|
275
|
+
}
|
|
276
|
+
if (meta !== undefined) {
|
|
277
|
+
if (!jsonValue(meta))
|
|
278
|
+
throw new InertiaError('TEMPLATE_BUILD_FAILED', `${page} exports a meta that is not JSON data`);
|
|
279
|
+
if (Buffer.byteLength(JSON.stringify(meta)) > PAGE_META_MAX_BYTES)
|
|
280
|
+
throw new InertiaError('TEMPLATE_BUILD_FAILED', `${page} exports a meta larger than ${PAGE_META_MAX_BYTES} bytes`);
|
|
281
|
+
}
|
|
282
|
+
pageEntries[page] = {
|
|
283
|
+
browser: `browser/${entry.file}`,
|
|
284
|
+
css,
|
|
285
|
+
preload,
|
|
286
|
+
ssr: `ssr/${ssrFile}`,
|
|
287
|
+
...(meta === undefined ? {} : { meta }),
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
const files = {};
|
|
291
|
+
for (const top of ['browser', 'ssr'])
|
|
292
|
+
for (const file of await listFiles(join(out, top))) {
|
|
293
|
+
const content = await readFile(join(out, top, file));
|
|
294
|
+
files[`${top}/${file}`] = { bytes: content.length, sha256: sha256(content) };
|
|
295
|
+
}
|
|
296
|
+
const manifest = {
|
|
297
|
+
format: TEMPLATE_FORMAT,
|
|
298
|
+
name,
|
|
299
|
+
version,
|
|
300
|
+
builtWith: BUILDER.version,
|
|
301
|
+
shared: Object.fromEntries([...imported].sort().map((module) => [module, packageVersion(root, module)])),
|
|
302
|
+
pages: pageEntries,
|
|
303
|
+
files,
|
|
304
|
+
};
|
|
305
|
+
await writeFile(join(out, TEMPLATE_MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
306
|
+
const check = await checkTemplateBundle(out, {
|
|
307
|
+
maxBytes: options.maxBytes ?? TEMPLATE_MAX_BYTES,
|
|
308
|
+
});
|
|
309
|
+
if (check.problems.length || check.buildId === undefined)
|
|
310
|
+
throw new InertiaError('TEMPLATE_BUILD_FAILED', `The built bundle does not pass its own check: ${check.problems.map((problem) => problem.message).join('; ')}`);
|
|
311
|
+
const result = {
|
|
312
|
+
out,
|
|
313
|
+
name,
|
|
314
|
+
version,
|
|
315
|
+
buildId: check.buildId,
|
|
316
|
+
pages: Object.keys(pageEntries),
|
|
317
|
+
shared: manifest.shared,
|
|
318
|
+
files: Object.keys(files).length,
|
|
319
|
+
bytes: check.bytes,
|
|
320
|
+
ms: Math.round(performance.now() - begin),
|
|
321
|
+
};
|
|
322
|
+
logger.log('info', 'Template bundle built', {
|
|
323
|
+
code: 'INERTIA_TEMPLATE_BUILT',
|
|
324
|
+
name,
|
|
325
|
+
version,
|
|
326
|
+
buildId: result.buildId,
|
|
327
|
+
out: relative(root, out),
|
|
328
|
+
pages: result.pages.length,
|
|
329
|
+
files: result.files,
|
|
330
|
+
bytes: result.bytes,
|
|
331
|
+
shared: manifest.shared,
|
|
332
|
+
ms: result.ms,
|
|
333
|
+
});
|
|
334
|
+
return result;
|
|
335
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/** The manifest file of a bundle. */
|
|
2
|
+
export declare const TEMPLATE_MANIFEST = "dokebi-template.json";
|
|
3
|
+
/** The signature file of a bundle (optional; its form is the app's). */
|
|
4
|
+
export declare const TEMPLATE_SIGNATURE = "dokebi-template.sig";
|
|
5
|
+
/** The manifest format this version writes and reads. */
|
|
6
|
+
export declare const TEMPLATE_FORMAT = 1;
|
|
7
|
+
/** A template name: the folder name of `views/<template>/` and `domains.<host>.template`. */
|
|
8
|
+
export declare const TEMPLATE_NAME: RegExp;
|
|
9
|
+
/** A template version (the template repository's): 1 to 64 of letters, digits, `.`, `+`, `-`. */
|
|
10
|
+
export declare const TEMPLATE_VERSION: RegExp;
|
|
11
|
+
/** A page of a bundle: `Layout`, or `Pages/<path>` without the `.vue`. */
|
|
12
|
+
export declare const TEMPLATE_PAGE: RegExp;
|
|
13
|
+
/** A shared module specifier: a package name with an optional subpath. */
|
|
14
|
+
export declare const SHARED_SPECIFIER: RegExp;
|
|
15
|
+
/** A page's `meta` (JSON) may take this many bytes. */
|
|
16
|
+
export declare const PAGE_META_MAX_BYTES = 4096;
|
|
17
|
+
/** Default limits of one bundle. */
|
|
18
|
+
export declare const TEMPLATE_MAX_BYTES: number;
|
|
19
|
+
export declare const TEMPLATE_MAX_FILES = 4096;
|
|
20
|
+
/**
|
|
21
|
+
* The shared modules every bundle may import and every app build provides (when it opts in with
|
|
22
|
+
* `dokebiInertia({ templates })`). `vue/server-renderer` is provided by the server build only.
|
|
23
|
+
*/
|
|
24
|
+
export declare const SHARED_DEFAULTS: readonly string[];
|
|
25
|
+
/** The defaults the server build alone provides. */
|
|
26
|
+
export declare const SERVER_ONLY_SHARED: readonly string[];
|
|
27
|
+
/** One page of a bundle. */
|
|
28
|
+
export interface TemplatePage {
|
|
29
|
+
/** The browser entry (`browser/pages/…js`). */
|
|
30
|
+
readonly browser: string;
|
|
31
|
+
/** The stylesheets the page needs (its own and its chunks'), in load order. */
|
|
32
|
+
readonly css: readonly string[];
|
|
33
|
+
/** The chunks the browser entry imports, for `modulepreload`. */
|
|
34
|
+
readonly preload: readonly string[];
|
|
35
|
+
/** The server-render module (`ssr/pages/…js`). */
|
|
36
|
+
readonly ssr: string;
|
|
37
|
+
/** What the page exports as `meta` (JSON, at most 4 KiB): the app judges it (a contract). */
|
|
38
|
+
readonly meta?: unknown;
|
|
39
|
+
}
|
|
40
|
+
/** `dokebi-template.json`, format 1. */
|
|
41
|
+
export interface TemplateManifest {
|
|
42
|
+
readonly format: 1;
|
|
43
|
+
readonly name: string;
|
|
44
|
+
readonly version: string;
|
|
45
|
+
/** The @dokebi/template-inertia version that built it. */
|
|
46
|
+
readonly builtWith: string;
|
|
47
|
+
/** The shared modules its code imports → the version of their package when it was built. */
|
|
48
|
+
readonly shared: Readonly<Record<string, string | null>>;
|
|
49
|
+
readonly pages: Readonly<Record<string, TemplatePage>>;
|
|
50
|
+
/** Every file under browser/ and ssr/ → its size and sha256 (hex). */
|
|
51
|
+
readonly files: Readonly<Record<string, {
|
|
52
|
+
readonly bytes: number;
|
|
53
|
+
readonly sha256: string;
|
|
54
|
+
}>>;
|
|
55
|
+
}
|
|
56
|
+
/** What is wrong with a bundle (one entry per problem; the code is stable). */
|
|
57
|
+
export interface TemplateProblem {
|
|
58
|
+
readonly code: 'TEMPLATE_MANIFEST_MISSING' | 'TEMPLATE_MANIFEST_INVALID' | 'TEMPLATE_FORMAT_UNSUPPORTED' | 'TEMPLATE_FILE_MISSING' | 'TEMPLATE_FILE_CHANGED' | 'TEMPLATE_FILE_EXTRA' | 'TEMPLATE_FILE_LINK' | 'TEMPLATE_TOO_LARGE' | 'TEMPLATE_PAGE_FILE_UNKNOWN' | 'TEMPLATE_SHARED_MISSING' | 'TEMPLATE_SHARED_VERSION';
|
|
59
|
+
readonly message: string;
|
|
60
|
+
readonly file?: string;
|
|
61
|
+
readonly page?: string;
|
|
62
|
+
readonly module?: string;
|
|
63
|
+
}
|
|
64
|
+
/** The check of one bundle folder. */
|
|
65
|
+
export interface TemplateCheck {
|
|
66
|
+
/** The manifest, when it could be read and has the right shape. */
|
|
67
|
+
readonly manifest?: TemplateManifest;
|
|
68
|
+
/** The first 12 hex of the manifest's sha256: the same in every process that reads it. */
|
|
69
|
+
readonly buildId?: string;
|
|
70
|
+
/** The bytes of the files under browser/ and ssr/ that were read. */
|
|
71
|
+
readonly bytes: number;
|
|
72
|
+
readonly problems: readonly TemplateProblem[];
|
|
73
|
+
}
|
|
74
|
+
export interface TemplateCheckLimits {
|
|
75
|
+
readonly maxBytes?: number;
|
|
76
|
+
readonly maxFiles?: number;
|
|
77
|
+
}
|
|
78
|
+
/** The JSON `meta` value of a page is plain data (objects, arrays, strings, finite numbers…). */
|
|
79
|
+
export declare function jsonValue(value: unknown, depth?: number): boolean;
|
|
80
|
+
/** The problem of a manifest's shape, or undefined (paths, names, page references). */
|
|
81
|
+
export declare function manifestProblem(value: unknown): string | undefined;
|
|
82
|
+
/** sha256 (hex) of bytes. */
|
|
83
|
+
export declare function sha256(bytes: Uint8Array): string;
|
|
84
|
+
/**
|
|
85
|
+
* Checks one bundle folder: the manifest's shape, every file's size and sha256, no file the
|
|
86
|
+
* manifest does not list (but the manifest and the signature), no link, the limits. Reads only;
|
|
87
|
+
* never throws for what the folder holds (a missing folder is TEMPLATE_MANIFEST_MISSING).
|
|
88
|
+
*/
|
|
89
|
+
export declare function checkTemplateBundle(dir: string, limits?: TemplateCheckLimits): Promise<TemplateCheck>;
|
|
90
|
+
/** A shared module the app build provides (its `dokebi-shared.json` entry). */
|
|
91
|
+
export interface ProvidedShared {
|
|
92
|
+
readonly file: string;
|
|
93
|
+
readonly version: string | null;
|
|
94
|
+
}
|
|
95
|
+
/** The major part of a version for compatibility: `3` of 3.5.1, `0.4` of 0.4.19. */
|
|
96
|
+
export declare function compatibleLine(version: string): string | undefined;
|
|
97
|
+
/**
|
|
98
|
+
* The problems of a bundle's shared modules against what an app build provides: a module the app
|
|
99
|
+
* does not provide, or one whose package is another major (0.x: minor) than the bundle was built
|
|
100
|
+
* with. A version unknown on either side (a local alias) is not compared.
|
|
101
|
+
*/
|
|
102
|
+
export declare function sharedProblems(bundle: Readonly<Record<string, string | null>>, provided: Readonly<Record<string, ProvidedShared>>): TemplateProblem[];
|