@forinda/kickjs-inertia 0.2.0 → 0.3.0
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/dist/index.d.mts +105 -12
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +194 -10
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.d.mts
CHANGED
|
@@ -75,6 +75,61 @@ export declare function scroll<T>(value: Resolver<T>, options?: {
|
|
|
75
75
|
meta?: (value: T) => ScrollMeta;
|
|
76
76
|
}): InertiaProp<T>;
|
|
77
77
|
//#endregion
|
|
78
|
+
//#region src/seo.d.ts
|
|
79
|
+
/** A page's title, description and social tags. Every value is escaped on output. */
|
|
80
|
+
interface PageMeta {
|
|
81
|
+
title?: string;
|
|
82
|
+
description?: string;
|
|
83
|
+
/** A path (`'/posts/1'`, made absolute with `baseUrl`) or a full URL. */
|
|
84
|
+
canonical?: string;
|
|
85
|
+
/** E.g. `'noindex, nofollow'`. */
|
|
86
|
+
robots?: string;
|
|
87
|
+
/** Open Graph, without the `og:` prefix: `{ type: 'article', image: '/cover.png' }`. */
|
|
88
|
+
og?: Record<string, string>;
|
|
89
|
+
/** Twitter cards, without the `twitter:` prefix: `{ card: 'summary_large_image' }`. */
|
|
90
|
+
twitter?: Record<string, string>;
|
|
91
|
+
/** Structured data, rendered as `<script type="application/ld+json">`. */
|
|
92
|
+
jsonLd?: Record<string, unknown> | Record<string, unknown>[];
|
|
93
|
+
}
|
|
94
|
+
/** Adapter-wide meta, under each page's. */
|
|
95
|
+
interface MetaDefaults extends PageMeta {
|
|
96
|
+
/** Wraps a page's title: `'%s · My App'`. Not applied to the default `title`. */
|
|
97
|
+
titleTemplate?: string;
|
|
98
|
+
}
|
|
99
|
+
interface SitemapEntry {
|
|
100
|
+
/** A full URL, or a path made absolute with `baseUrl`. */
|
|
101
|
+
loc: string;
|
|
102
|
+
/** A `Date`, or a W3C date string (`'2026-10-16'`). */
|
|
103
|
+
lastmod?: Date | string;
|
|
104
|
+
changefreq?: 'always' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'never';
|
|
105
|
+
/** 0.0 – 1.0. */
|
|
106
|
+
priority?: number;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Answer `/sitemap.xml`. Return it from a handler:
|
|
110
|
+
*
|
|
111
|
+
* ```ts
|
|
112
|
+
* @Get('/sitemap.xml')
|
|
113
|
+
* sitemap() {
|
|
114
|
+
* return sitemap([{ loc: '/' }, { loc: '/posts', changefreq: 'daily' }], { baseUrl: getEnv('APP_URL') })
|
|
115
|
+
* }
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
export declare function sitemap(entries: Iterable<SitemapEntry>, options?: {
|
|
119
|
+
baseUrl?: string;
|
|
120
|
+
}): Respondable;
|
|
121
|
+
interface RobotsOptions {
|
|
122
|
+
/** Default `'*'`. */
|
|
123
|
+
userAgent?: string;
|
|
124
|
+
allow?: string[];
|
|
125
|
+
disallow?: string[];
|
|
126
|
+
/** Sitemap URL(s) — a path is made absolute with `baseUrl`. */
|
|
127
|
+
sitemap?: string | string[];
|
|
128
|
+
baseUrl?: string;
|
|
129
|
+
}
|
|
130
|
+
/** Answer `/robots.txt`. */
|
|
131
|
+
export declare function robots(options?: RobotsOptions): Respondable;
|
|
132
|
+
//#endregion
|
|
78
133
|
//#region src/inertia.d.ts
|
|
79
134
|
/** The page object the Inertia client renders — see the protocol docs. */
|
|
80
135
|
interface Page {
|
|
@@ -102,6 +157,8 @@ interface Page {
|
|
|
102
157
|
encryptHistory?: boolean;
|
|
103
158
|
clearHistory?: boolean;
|
|
104
159
|
preserveFragment?: boolean;
|
|
160
|
+
/** Title, description and social tags — see `PageOptions.meta`. */
|
|
161
|
+
meta?: PageMeta;
|
|
105
162
|
}
|
|
106
163
|
interface PageOptions {
|
|
107
164
|
/** Encrypt this page's history entry in the browser. */
|
|
@@ -110,6 +167,13 @@ interface PageOptions {
|
|
|
110
167
|
clearHistory?: boolean;
|
|
111
168
|
/** Response status. Default 200; error pages send theirs (404, 500). */
|
|
112
169
|
status?: number;
|
|
170
|
+
/**
|
|
171
|
+
* Title, description, canonical URL and social tags, under the adapter's
|
|
172
|
+
* `meta` defaults. Rendered into the first-visit HTML and sent as the
|
|
173
|
+
* page's `meta` on every visit, for a `<Head>` in the client to keep the
|
|
174
|
+
* browser's head in sync. A server-rendered `<Head>` tag wins over the same tag here.
|
|
175
|
+
*/
|
|
176
|
+
meta?: PageMeta;
|
|
113
177
|
}
|
|
114
178
|
export declare function isInertiaRequest(ctx: RequestContext): boolean;
|
|
115
179
|
/** Flash data for the next page, sent as the page's top-level `flash`. */
|
|
@@ -156,8 +220,9 @@ export declare function location(url: string): Respondable;
|
|
|
156
220
|
export declare function isPageRequest(headers: Record<string, string | string[] | undefined>): boolean;
|
|
157
221
|
/**
|
|
158
222
|
* The configured error page as a response, with `{ status, message }` as its
|
|
159
|
-
* props. A 5xx message is replaced
|
|
160
|
-
* for the log, not the visitor
|
|
223
|
+
* props. A 5xx message is replaced unless NODE_ENV is development or test —
|
|
224
|
+
* an exception's text is for the log, not the visitor, and a deploy that
|
|
225
|
+
* forgot NODE_ENV must not show it.
|
|
161
226
|
*/
|
|
162
227
|
export declare function errorPage(component: string, status: number, error?: unknown): Respondable;
|
|
163
228
|
//#endregion
|
|
@@ -170,6 +235,11 @@ interface HtmlParts {
|
|
|
170
235
|
page: Page;
|
|
171
236
|
}
|
|
172
237
|
type HtmlTemplate = (parts: HtmlParts) => string;
|
|
238
|
+
/**
|
|
239
|
+
* The default shell. Its `<title>` is a fallback: left out when the head
|
|
240
|
+
* already has one (a server-rendered `<Head>`). In the browser, Inertia drops
|
|
241
|
+
* it itself once a page's `<Head>` sets a title.
|
|
242
|
+
*/
|
|
173
243
|
export declare const defaultTemplate: (title: string) => HtmlTemplate;
|
|
174
244
|
/**
|
|
175
245
|
* The page as `<script data-page="app" type="application/json">` — where the
|
|
@@ -185,24 +255,45 @@ interface InertiaAdapterOptions {
|
|
|
185
255
|
* `createInertiaApp`. Served by Vite in dev, looked up in the build
|
|
186
256
|
* manifest in production. Default: `'src/client/main.tsx'`.
|
|
187
257
|
*/
|
|
188
|
-
entry
|
|
189
|
-
/**
|
|
190
|
-
|
|
258
|
+
entry?: string;
|
|
259
|
+
/**
|
|
260
|
+
* Where `vite build` wrote the client, with `build.manifest: true`. Default: `'dist/client'`.
|
|
261
|
+
* Under NODE_ENV development or test a missing build is not an error: pages render without
|
|
262
|
+
* asset tags (a warning says so), so tests run before the client is built.
|
|
263
|
+
*/
|
|
264
|
+
clientDir?: string;
|
|
191
265
|
/**
|
|
192
266
|
* Asset version. A client on another version reloads the page on its next
|
|
193
267
|
* visit. Default: a hash of the build manifest in production, none in dev
|
|
194
|
-
* (Vite reloads changed modules itself).
|
|
268
|
+
* (Vite reloads changed modules itself) or without a build. A test that
|
|
269
|
+
* sends `X-Inertia` requests pins it (`version: 'test'`) and sends the same
|
|
270
|
+
* value as `X-Inertia-Version`, so a built client doesn't turn them into 409s.
|
|
195
271
|
*/
|
|
196
272
|
version?: string | (() => string);
|
|
197
273
|
/** Props every page gets — the current user, app name. */
|
|
198
274
|
share?: (ctx: RequestContext) => Record<string, unknown> | Promise<Record<string, unknown>>;
|
|
199
|
-
/** `<title>` of the default HTML shell. */
|
|
200
|
-
title: string;
|
|
201
275
|
/**
|
|
202
|
-
*
|
|
203
|
-
*
|
|
276
|
+
* `<title>` of the default HTML shell, until a page sets its own with
|
|
277
|
+
* Inertia's `<Head>`. Default: `'KickJS'`.
|
|
278
|
+
*/
|
|
279
|
+
title?: string;
|
|
280
|
+
/**
|
|
281
|
+
* Tags added to every page's `<head>` — a favicon, fonts. Titles and meta
|
|
282
|
+
* tags: `meta` here and per page, or Inertia's `<Head>` in the page.
|
|
204
283
|
*/
|
|
205
284
|
head?: string;
|
|
285
|
+
/**
|
|
286
|
+
* Meta every page starts from, under the `meta` a handler passes to
|
|
287
|
+
* `inertia()`: `{ titleTemplate: '%s · My App', description, og: { image } }`.
|
|
288
|
+
*/
|
|
289
|
+
meta?: MetaDefaults;
|
|
290
|
+
/**
|
|
291
|
+
* The site's public URL, e.g. `getEnv('APP_URL')`. Canonical URLs and
|
|
292
|
+
* meta image paths are made absolute with it, and a page without a
|
|
293
|
+
* `canonical` gets this + its path. Never taken from the request's Host
|
|
294
|
+
* header, which the client chooses.
|
|
295
|
+
*/
|
|
296
|
+
baseUrl?: string;
|
|
206
297
|
/** Replace the HTML shell entirely. */
|
|
207
298
|
template?: HtmlTemplate;
|
|
208
299
|
/**
|
|
@@ -230,7 +321,9 @@ interface SsrResult {
|
|
|
230
321
|
head: string[];
|
|
231
322
|
body: string;
|
|
232
323
|
}
|
|
233
|
-
|
|
324
|
+
/** The options with their defaults applied. */
|
|
325
|
+
type ResolvedOptions = InertiaAdapterOptions & Required<Pick<InertiaAdapterOptions, 'entry' | 'clientDir' | 'title'>>;
|
|
326
|
+
export declare const InertiaAdapter: import("@forinda/kickjs").AdapterFactory<ResolvedOptions, unknown>;
|
|
234
327
|
//#endregion
|
|
235
328
|
//#region src/errors.d.ts
|
|
236
329
|
type ErrorHandler = (err: any, req: any, res: RuntimeResponse, next: (err?: unknown) => void) => unknown;
|
|
@@ -268,5 +361,5 @@ type NotFoundHandler = (req: any, res: RuntimeResponse, next: (err?: unknown) =>
|
|
|
268
361
|
*/
|
|
269
362
|
export declare function inertiaNotFound(): NotFoundHandler;
|
|
270
363
|
//#endregion
|
|
271
|
-
export type { HtmlParts, HtmlTemplate, InertiaAdapterOptions, InertiaProp, Page, PageOptions, RedirectOptions, ScrollMeta, SsrResult };
|
|
364
|
+
export type { HtmlParts, HtmlTemplate, InertiaAdapterOptions, InertiaProp, MetaDefaults, Page, PageMeta, PageOptions, RedirectOptions, RobotsOptions, ScrollMeta, SitemapEntry, SsrResult };
|
|
272
365
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/props.ts","../src/inertia.ts","../src/html.ts","../src/adapter.ts","../src/errors.ts"],"mappings":";;;;;;;;;;KAQK,SAAS,KAAK,WAAW,IAAI,QAAQ;cAEpC;KAEM;;UAGK;EACf;EACA;EACA;;UAGe,YAAY;YACjB,OAAO;WACR,OAAO,SAAS;;WAEhB;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;WACA;WACA,QAAQ,eAAe;;;wBAQlB,SAAS,GAAG,aAAa,IAAI,QAAQ,KAAK,YAAY;;wBAKtD,OAAO,GAAG,OAAO,SAAS,KAAK,YAAY;;;;;wBAQ3C,MAAM,GAAG,aAAa,IAAI,QAAQ,IAAI,iBAAoB,YAAY;;;;;wBAQtE,MAAM,GACpB,OAAO,SAAS,IAChB,sCACA;EAAW;IACV,YAAY;;;;;;wBASC,KAAK,GACnB,OAAO,SAAS,IAChB;EAAW;EAAc;IACxB,YAAY;;;;;;;;;wBAYC,OAAO,GACrB,OAAO,SAAS,IAChB;EACE;EACA;EACA;EACA,QAAQ,OAAO,MAAM;IAEtB,YAAY;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/props.ts","../src/seo.ts","../src/inertia.ts","../src/html.ts","../src/adapter.ts","../src/errors.ts"],"mappings":";;;;;;;;;;KAQK,SAAS,KAAK,WAAW,IAAI,QAAQ;cAEpC;KAEM;;UAGK;EACf;EACA;EACA;;UAGe,YAAY;YACjB,OAAO;WACR,OAAO,SAAS;;WAEhB;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;WACA;WACA,QAAQ,eAAe;;;wBAQlB,SAAS,GAAG,aAAa,IAAI,QAAQ,KAAK,YAAY;;wBAKtD,OAAO,GAAG,OAAO,SAAS,KAAK,YAAY;;;;;wBAQ3C,MAAM,GAAG,aAAa,IAAI,QAAQ,IAAI,iBAAoB,YAAY;;;;;wBAQtE,MAAM,GACpB,OAAO,SAAS,IAChB,sCACA;EAAW;IACV,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;;;;EAQA;;EAEA,SAAS,KAAK,mBAAmB,0BAA0B,QAAQ;;;;;EAKnE;;;;;EAKA;;;;;EAKA,OAAO;;;;;;;EAOP;;EAEA,WAAW;;;;;;;EAOX;;;;;;;;;EASA;IAAQ;IAAe;;;;UAIR;EACf;EACA;;;KAMG,kBAAkB,wBACrB,SAAS,KAAK;qBAmFH,0CAAc,eAAA;;;KC9JtB,gBACH,UACA,UACA,KAAK,iBACL,OAAO;;;;;;;;;;;;;;qBA8DI,cAAc,kBAAkB;;;;;;;;;;;;wBAkB7B,oBAAoB,WAAU,eAAgC;KA2CzE,mBACH,UACA,KAAK,iBACL,OAAO,kCACG;;;;;;wBAOI,mBAAmB"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-inertia v0.
|
|
2
|
+
* @forinda/kickjs-inertia v0.3.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -96,6 +96,157 @@ async function resolveProp(value) {
|
|
|
96
96
|
return typeof raw === "function" ? await raw() : await raw;
|
|
97
97
|
}
|
|
98
98
|
|
|
99
|
+
//#endregion
|
|
100
|
+
//#region src/seo.ts
|
|
101
|
+
/**
|
|
102
|
+
* Search-engine support: page meta set by the handler (rendered into the
|
|
103
|
+
* first-visit HTML and sent to the client on every visit), plus
|
|
104
|
+
* `sitemap()` and `robots()` responses.
|
|
105
|
+
*
|
|
106
|
+
* @module @forinda/kickjs-inertia/seo
|
|
107
|
+
*/
|
|
108
|
+
const escapeHtml$1 = (value) => value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
109
|
+
/** A site path made absolute with `baseUrl`; anything else is left as it is. */
|
|
110
|
+
function absolute(value, baseUrl) {
|
|
111
|
+
if (!value || !baseUrl || !/^\/(?![/\\])/.test(value)) return value;
|
|
112
|
+
return baseUrl.replace(/\/+$/, "") + value;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* The meta a page is sent with: `defaults` under `meta`, the title template
|
|
116
|
+
* applied, and paths made absolute with `baseUrl`. Without a `canonical`, a
|
|
117
|
+
* successful page gets `baseUrl` + its path (no query) — never the request's
|
|
118
|
+
* Host header, which the client chooses.
|
|
119
|
+
*/
|
|
120
|
+
function resolveMeta(defaults = {}, meta = {}, options = {}) {
|
|
121
|
+
const { titleTemplate, ...base } = defaults;
|
|
122
|
+
const { baseUrl, path, status = 200 } = options;
|
|
123
|
+
const title = meta.title !== void 0 && titleTemplate ? titleTemplate.replace("%s", () => meta.title) : meta.title ?? base.title;
|
|
124
|
+
const description = meta.description ?? base.description;
|
|
125
|
+
let canonical = meta.canonical ?? base.canonical;
|
|
126
|
+
if (canonical === void 0 && baseUrl && path !== void 0 && status < 300) canonical = path.split(/[?#]/)[0];
|
|
127
|
+
canonical = absolute(canonical, baseUrl);
|
|
128
|
+
const og = {
|
|
129
|
+
...base.og,
|
|
130
|
+
...meta.og
|
|
131
|
+
};
|
|
132
|
+
og.title ??= meta.title ?? base.title;
|
|
133
|
+
og.description ??= description;
|
|
134
|
+
og.url ??= canonical;
|
|
135
|
+
og.image = absolute(og.image, baseUrl);
|
|
136
|
+
const twitter = {
|
|
137
|
+
...base.twitter,
|
|
138
|
+
...meta.twitter
|
|
139
|
+
};
|
|
140
|
+
twitter.image = absolute(twitter.image, baseUrl);
|
|
141
|
+
const strip = (r) => Object.fromEntries(Object.entries(r).filter(([, v]) => v !== void 0));
|
|
142
|
+
const out = {
|
|
143
|
+
title,
|
|
144
|
+
description,
|
|
145
|
+
canonical,
|
|
146
|
+
robots: meta.robots ?? base.robots,
|
|
147
|
+
og: strip(og),
|
|
148
|
+
twitter: strip(twitter),
|
|
149
|
+
jsonLd: meta.jsonLd ?? base.jsonLd
|
|
150
|
+
};
|
|
151
|
+
for (const key of Object.keys(out)) {
|
|
152
|
+
const v = out[key];
|
|
153
|
+
if (v === void 0 || typeof v === "object" && !Object.keys(v).length) delete out[key];
|
|
154
|
+
}
|
|
155
|
+
return Object.keys(out).length ? out : void 0;
|
|
156
|
+
}
|
|
157
|
+
/** JSON for a `<script>` body: `<` escaped, so a value can't close the tag. */
|
|
158
|
+
function scriptJson(value) {
|
|
159
|
+
return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026");
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* The meta as head tags. Each carries `data-inertia="<key>"` — what Inertia's
|
|
163
|
+
* `<Head>` gives a tag with that `head-key` — so the client takes them over
|
|
164
|
+
* and replaces them on the next visit instead of leaving them behind.
|
|
165
|
+
*/
|
|
166
|
+
function metaTags(meta) {
|
|
167
|
+
if (!meta) return [];
|
|
168
|
+
const tags = [];
|
|
169
|
+
const m = (attr, key, value) => tags.push(`<meta data-inertia="${escapeHtml$1(key)}" ${attr}="${escapeHtml$1(key)}" content="${escapeHtml$1(value)}" />`);
|
|
170
|
+
if (meta.title !== void 0) tags.push(`<title data-inertia="">${escapeHtml$1(meta.title)}</title>`);
|
|
171
|
+
if (meta.description !== void 0) m("name", "description", meta.description);
|
|
172
|
+
if (meta.robots !== void 0) m("name", "robots", meta.robots);
|
|
173
|
+
if (meta.canonical !== void 0) tags.push(`<link data-inertia="canonical" rel="canonical" href="${escapeHtml$1(meta.canonical)}" />`);
|
|
174
|
+
for (const [k, v] of Object.entries(meta.og ?? {})) m("property", `og:${k}`, v);
|
|
175
|
+
for (const [k, v] of Object.entries(meta.twitter ?? {})) m("name", `twitter:${k}`, v);
|
|
176
|
+
if (meta.jsonLd !== void 0) tags.push(`<script data-inertia="json-ld" type="application/ld+json">${scriptJson(meta.jsonLd)}<\/script>`);
|
|
177
|
+
return tags;
|
|
178
|
+
}
|
|
179
|
+
/** What a head tag sets — two tags with the same key are duplicates. */
|
|
180
|
+
function tagKey(tag) {
|
|
181
|
+
const attr = (name) => tag.match(new RegExp(`\\s${name}\\s*=\\s*["']([^"']*)["']`, "i"))?.[1]?.toLowerCase();
|
|
182
|
+
if (/^<title[\s>]/i.test(tag)) return "title";
|
|
183
|
+
if (/^<meta\s/i.test(tag)) {
|
|
184
|
+
const key = attr("name") ?? attr("property");
|
|
185
|
+
return key ? `meta:${key}` : null;
|
|
186
|
+
}
|
|
187
|
+
if (/^<link\s/i.test(tag) && attr("rel") === "canonical") return "canonical";
|
|
188
|
+
if (/^<script\s/i.test(tag) && attr("type") === "application/ld+json") return "json-ld";
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
/** `tags` minus the ones `winners` (a server-rendered `<Head>`) already set. */
|
|
192
|
+
function dedupeHead(tags, winners) {
|
|
193
|
+
const taken = new Set(winners.map((t) => tagKey(t.trim())).filter(Boolean));
|
|
194
|
+
return tags.filter((t) => !taken.has(tagKey(t)));
|
|
195
|
+
}
|
|
196
|
+
const escapeXml = (value) => value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
197
|
+
/** The sitemap XML for `entries`. Paths are made absolute with `baseUrl`. */
|
|
198
|
+
function sitemapXml(entries, baseUrl) {
|
|
199
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
200
|
+
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
|
201
|
+
${[...entries].map((e) => {
|
|
202
|
+
const lastmod = e.lastmod instanceof Date ? e.lastmod.toISOString() : e.lastmod;
|
|
203
|
+
return [
|
|
204
|
+
" <url>",
|
|
205
|
+
` <loc>${escapeXml(absolute(e.loc, baseUrl))}</loc>`,
|
|
206
|
+
lastmod && ` <lastmod>${escapeXml(lastmod)}</lastmod>`,
|
|
207
|
+
e.changefreq && ` <changefreq>${e.changefreq}</changefreq>`,
|
|
208
|
+
e.priority !== void 0 && ` <priority>${Number(e.priority).toFixed(1)}</priority>`,
|
|
209
|
+
" </url>"
|
|
210
|
+
].filter(Boolean).join("\n");
|
|
211
|
+
}).join("\n")}
|
|
212
|
+
</urlset>
|
|
213
|
+
`;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Answer `/sitemap.xml`. Return it from a handler:
|
|
217
|
+
*
|
|
218
|
+
* ```ts
|
|
219
|
+
* @Get('/sitemap.xml')
|
|
220
|
+
* sitemap() {
|
|
221
|
+
* return sitemap([{ loc: '/' }, { loc: '/posts', changefreq: 'daily' }], { baseUrl: getEnv('APP_URL') })
|
|
222
|
+
* }
|
|
223
|
+
* ```
|
|
224
|
+
*/
|
|
225
|
+
function sitemap(entries, options = {}) {
|
|
226
|
+
const xml = sitemapXml(entries, options.baseUrl);
|
|
227
|
+
return { [RESPOND](ctx) {
|
|
228
|
+
ctx.send(xml, { type: "application/xml; charset=utf-8" });
|
|
229
|
+
} };
|
|
230
|
+
}
|
|
231
|
+
/** The robots.txt text. Line breaks in values are dropped, so one can't add a rule. */
|
|
232
|
+
function robotsTxt(options = {}) {
|
|
233
|
+
const clean = (v) => v.replace(/[\r\n]+/g, "");
|
|
234
|
+
const lines = [`User-agent: ${clean(options.userAgent ?? "*")}`];
|
|
235
|
+
for (const p of options.allow ?? []) lines.push(`Allow: ${clean(p)}`);
|
|
236
|
+
for (const p of options.disallow ?? []) lines.push(`Disallow: ${clean(p)}`);
|
|
237
|
+
if (!options.allow?.length && !options.disallow?.length) lines.push("Allow: /");
|
|
238
|
+
const maps = options.sitemap === void 0 ? [] : [options.sitemap].flat();
|
|
239
|
+
if (maps.length) lines.push("", ...maps.map((s) => `Sitemap: ${clean(absolute(s, options.baseUrl))}`));
|
|
240
|
+
return `${lines.join("\n")}\n`;
|
|
241
|
+
}
|
|
242
|
+
/** Answer `/robots.txt`. */
|
|
243
|
+
function robots(options = {}) {
|
|
244
|
+
const text = robotsTxt(options);
|
|
245
|
+
return { [RESPOND](ctx) {
|
|
246
|
+
ctx.send(text);
|
|
247
|
+
} };
|
|
248
|
+
}
|
|
249
|
+
|
|
99
250
|
//#endregion
|
|
100
251
|
//#region src/inertia.ts
|
|
101
252
|
/**
|
|
@@ -245,6 +396,12 @@ async function buildPage(ctx, component, props, options = {}) {
|
|
|
245
396
|
delete ctx.session.data[FRAGMENT_KEY];
|
|
246
397
|
page.preserveFragment = true;
|
|
247
398
|
}
|
|
399
|
+
const meta = resolveMeta(rt.meta, options.meta, {
|
|
400
|
+
baseUrl: rt.baseUrl,
|
|
401
|
+
path: page.url,
|
|
402
|
+
status: options.status
|
|
403
|
+
});
|
|
404
|
+
if (meta) page.meta = meta;
|
|
248
405
|
if (options.encryptHistory) page.encryptHistory = true;
|
|
249
406
|
if (options.clearHistory) page.clearHistory = true;
|
|
250
407
|
return page;
|
|
@@ -356,16 +513,24 @@ const STATUS_TEXT = {
|
|
|
356
513
|
};
|
|
357
514
|
/**
|
|
358
515
|
* The configured error page as a response, with `{ status, message }` as its
|
|
359
|
-
* props. A 5xx message is replaced
|
|
360
|
-
* for the log, not the visitor
|
|
516
|
+
* props. A 5xx message is replaced unless NODE_ENV is development or test —
|
|
517
|
+
* an exception's text is for the log, not the visitor, and a deploy that
|
|
518
|
+
* forgot NODE_ENV must not show it.
|
|
361
519
|
*/
|
|
362
520
|
function errorPage(component, status, error) {
|
|
363
521
|
const fallback = STATUS_TEXT[status] ?? (status >= 500 ? "Server Error" : "Error");
|
|
364
522
|
const raw = error instanceof Error && error.message ? error.message : fallback;
|
|
523
|
+
const dev = process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test";
|
|
365
524
|
return inertia(component, {
|
|
366
525
|
status,
|
|
367
|
-
message: status >= 500 &&
|
|
368
|
-
}, {
|
|
526
|
+
message: status >= 500 && !dev ? fallback : raw
|
|
527
|
+
}, {
|
|
528
|
+
status,
|
|
529
|
+
meta: {
|
|
530
|
+
title: fallback,
|
|
531
|
+
robots: "noindex"
|
|
532
|
+
}
|
|
533
|
+
});
|
|
369
534
|
}
|
|
370
535
|
|
|
371
536
|
//#endregion
|
|
@@ -377,12 +542,17 @@ function errorPage(component, status, error) {
|
|
|
377
542
|
* @module @forinda/kickjs-inertia/html
|
|
378
543
|
*/
|
|
379
544
|
const escapeHtml = (value) => value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
545
|
+
/**
|
|
546
|
+
* The default shell. Its `<title>` is a fallback: left out when the head
|
|
547
|
+
* already has one (a server-rendered `<Head>`). In the browser, Inertia drops
|
|
548
|
+
* it itself once a page's `<Head>` sets a title.
|
|
549
|
+
*/
|
|
380
550
|
const defaultTemplate = (title) => ({ head, body }) => `<!doctype html>
|
|
381
551
|
<html lang="en">
|
|
382
552
|
<head>
|
|
383
553
|
<meta charset="utf-8" />
|
|
384
554
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
385
|
-
|
|
555
|
+
${/<title[\s>]/i.test(head) ? "" : `<title>${escapeHtml(title)}</title>`}
|
|
386
556
|
${head}
|
|
387
557
|
</head>
|
|
388
558
|
<body>
|
|
@@ -436,6 +606,7 @@ function manifestHead(clientDir, entry) {
|
|
|
436
606
|
*
|
|
437
607
|
* @module @forinda/kickjs-inertia/adapter
|
|
438
608
|
*/
|
|
609
|
+
let warnedNoBuild = false;
|
|
439
610
|
const log$1 = Logger.for("InertiaAdapter");
|
|
440
611
|
const CSS_REQUEST = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
|
|
441
612
|
/**
|
|
@@ -497,6 +668,7 @@ const InertiaAdapter = defineAdapter({
|
|
|
497
668
|
build: (config) => {
|
|
498
669
|
const clientDir = fromAppRoot(config.clientDir);
|
|
499
670
|
const template = config.template ?? defaultTemplate(config.title);
|
|
671
|
+
if (config.baseUrl !== void 0 && !/^https?:\/\/[^/]/.test(config.baseUrl)) throw new Error(`InertiaAdapter: baseUrl must be an absolute http(s) URL, got '${config.baseUrl}'.`);
|
|
500
672
|
let version = () => null;
|
|
501
673
|
let runtime = null;
|
|
502
674
|
const protocol = (req, res, next) => {
|
|
@@ -523,11 +695,18 @@ const InertiaAdapter = defineAdapter({
|
|
|
523
695
|
beforeMount({ http }) {
|
|
524
696
|
const vite = viteServer();
|
|
525
697
|
let head;
|
|
698
|
+
const manifest = join(clientDir, ".vite", "manifest.json");
|
|
526
699
|
if (vite) head = () => devHead(config.entry);
|
|
527
|
-
else {
|
|
700
|
+
else if (["development", "test"].includes(process.env.NODE_ENV ?? "") && !existsSync(manifest)) {
|
|
701
|
+
head = () => "";
|
|
702
|
+
if (!warnedNoBuild) {
|
|
703
|
+
warnedNoBuild = true;
|
|
704
|
+
log$1.warn(`No client build at ${manifest} — pages render without their scripts. Build the client, or run kick dev.`);
|
|
705
|
+
}
|
|
706
|
+
} else {
|
|
528
707
|
const tags = manifestHead(clientDir, config.entry);
|
|
529
708
|
head = () => tags;
|
|
530
|
-
const hash = createHash("sha1").update(readFileSync(
|
|
709
|
+
const hash = createHash("sha1").update(readFileSync(manifest)).digest("hex").slice(0, 12);
|
|
531
710
|
version = () => hash;
|
|
532
711
|
if (existsSync(join(clientDir, "package.json"))) throw new Error(`InertiaAdapter: clientDir ${clientDir} looks like a project root — it must be the client build output (default dist/client), which is served as-is.`);
|
|
533
712
|
const hidden = new Set(readdirSync(clientDir).filter((name) => name.startsWith(".")));
|
|
@@ -572,15 +751,20 @@ const InertiaAdapter = defineAdapter({
|
|
|
572
751
|
version: () => version(),
|
|
573
752
|
share: config.share,
|
|
574
753
|
errorPage: config.errorPage,
|
|
754
|
+
meta: config.meta,
|
|
755
|
+
baseUrl: config.baseUrl,
|
|
575
756
|
async renderHtml(page, ctx) {
|
|
576
757
|
const rendered = await render(page);
|
|
577
758
|
const styles = vite && rendered && ssr ? devStylesheets(vite, ssr.entry) : [];
|
|
759
|
+
const ssrHead = rendered?.head ?? [];
|
|
760
|
+
const meta = dedupeHead(metaTags(page.meta), ssrHead);
|
|
578
761
|
const html = template({
|
|
579
762
|
head: [
|
|
580
763
|
config.head ?? "",
|
|
581
764
|
head(page),
|
|
582
765
|
...styles,
|
|
583
|
-
...
|
|
766
|
+
...meta,
|
|
767
|
+
...ssrHead
|
|
584
768
|
].filter(Boolean).join("\n "),
|
|
585
769
|
body: rendered?.body ?? pageBody(page),
|
|
586
770
|
page
|
|
@@ -720,5 +904,5 @@ function inertiaNotFound() {
|
|
|
720
904
|
}
|
|
721
905
|
|
|
722
906
|
//#endregion
|
|
723
|
-
export { InertiaAdapter, always, back, buildPage, defaultTemplate, defer, errorPage, flash, inertia, inertiaErrorHandler, inertiaNotFound, isInertiaRequest, isPageRequest, location, merge, once, optional, pageBody, precognitive, redirect, scroll };
|
|
907
|
+
export { InertiaAdapter, always, back, buildPage, defaultTemplate, defer, errorPage, flash, inertia, inertiaErrorHandler, inertiaNotFound, isInertiaRequest, isPageRequest, location, merge, once, optional, pageBody, precognitive, redirect, robots, scroll, sitemap };
|
|
724
908
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["log"],"sources":["../src/props.ts","../src/inertia.ts","../src/html.ts","../src/adapter.ts","../src/errors.ts"],"sourcesContent":["/**\n * Prop wrappers that change when a prop is sent. A plain value or a function\n * is sent on every full visit and on a partial reload that asks for it; a\n * function is only called when the prop is actually sent.\n *\n * @module @forinda/kickjs-inertia/props\n */\n\ntype Resolver<T> = T | (() => T | Promise<T>)\n\nconst PROP = Symbol.for('kickjs.inertia.prop')\n\nexport type PropKind = 'optional' | 'always' | 'defer' | 'merge' | 'once' | 'scroll'\n\n/** Where an infinite-scroll prop is in its pages; `null` past either end. */\nexport interface ScrollMeta {\n currentPage: number | string | null\n nextPage: number | string | null\n previousPage: number | string | null\n}\n\nexport interface InertiaProp<T = unknown> {\n readonly [PROP]: PropKind\n readonly value: Resolver<T>\n /** `defer` only — props in one group load in one request. */\n readonly group?: string\n /** `merge` only — append, prepend or deep-merge into the client's copy. */\n readonly mode?: 'append' | 'prepend' | 'deep'\n /** `merge` and `scroll` — item fields that identify a row, e.g. `['id']`. */\n readonly matchOn?: string[]\n /** `once` only — the name the client caches it under. */\n readonly key?: string\n /** `once` only — milliseconds the client may keep it. */\n readonly ttl?: number\n /** `scroll` only. */\n readonly pageName?: string\n readonly wrapper?: string\n readonly meta?: (value: any) => ScrollMeta\n}\n\nfunction prop<T>(kind: PropKind, value: Resolver<T>, extra?: object): InertiaProp<T> {\n return { [PROP]: kind, value, ...extra }\n}\n\n/** Sent only when a partial reload names it (`router.reload({ only: [...] })`). */\nexport function optional<T>(value: () => T | Promise<T>): InertiaProp<T> {\n return prop('optional', value)\n}\n\n/** Sent on every response, including partial reloads that did not name it. */\nexport function always<T>(value: Resolver<T>): InertiaProp<T> {\n return prop('always', value)\n}\n\n/**\n * Left out of the first response; the client fetches it right after the page\n * renders, one request per `group`.\n */\nexport function defer<T>(value: () => T | Promise<T>, group = 'default'): InertiaProp<T> {\n return prop('defer', value, { group })\n}\n\n/**\n * Merged into the client's current value on a partial reload instead of\n * replacing it — paginated lists, infinite scroll.\n */\nexport function merge<T>(\n value: Resolver<T>,\n mode: 'append' | 'prepend' | 'deep' = 'append',\n options: { matchOn?: string | string[] } = {},\n): InertiaProp<T> {\n return prop('merge', value, { mode, matchOn: toList(options.matchOn) })\n}\n\n/**\n * Resolved once, then kept by the client: later visits skip it until `ttl`\n * runs out. For data that rarely changes — plans, countries, a settings\n * list. Pages that share a `key` share the cached value.\n */\nexport function once<T>(\n value: Resolver<T>,\n options: { key?: string; ttl?: number } = {},\n): InertiaProp<T> {\n return prop('once', value, options)\n}\n\n/**\n * One page of an infinite list, for Inertia's `<InfiniteScroll>`. The client\n * asks for the next or previous page with `?page=N` and appends or prepends\n * the rows under `wrapper`.\n *\n * The value is read as `{ data, meta: { page, hasNext, hasPrev } }` — the\n * `PaginatedResponse` shape; pass `meta` to read another one.\n */\nexport function scroll<T>(\n value: Resolver<T>,\n options: {\n pageName?: string\n wrapper?: string\n matchOn?: string | string[]\n meta?: (value: T) => ScrollMeta\n } = {},\n): InertiaProp<T> {\n return prop('scroll', value, {\n pageName: options.pageName ?? 'page',\n wrapper: options.wrapper ?? 'data',\n matchOn: toList(options.matchOn),\n meta: options.meta ?? paginatedMeta,\n })\n}\n\nfunction toList(value: string | string[] | undefined): string[] | undefined {\n return value === undefined ? undefined : Array.isArray(value) ? value : [value]\n}\n\nfunction paginatedMeta(value: unknown): ScrollMeta {\n const meta = (value as { meta?: { page?: number; hasNext?: boolean; hasPrev?: boolean } })?.meta\n if (typeof meta?.page !== 'number') {\n throw new Error(\n 'scroll(): the value has no `meta.page` — return `{ data, meta: { page, hasNext, hasPrev } }` or pass `meta`.',\n )\n }\n return {\n currentPage: meta.page,\n nextPage: meta.hasNext ? meta.page + 1 : null,\n previousPage: meta.hasPrev ? meta.page - 1 : null,\n }\n}\n\nexport function isInertiaProp(value: unknown): value is InertiaProp {\n return typeof value === 'object' && value !== null && PROP in value\n}\n\nexport function propKind(value: InertiaProp): PropKind {\n return value[PROP]\n}\n\n/** Unwrap a wrapper, call a function, await a promise. */\nexport async function resolveProp(value: unknown): Promise<unknown> {\n const raw = isInertiaProp(value) ? value.value : value\n return typeof raw === 'function' ? await (raw as () => unknown)() : await raw\n}\n","/**\n * Page responses. `inertia(component, props)` is a handler return value: on a\n * first visit it renders the HTML shell with the page embedded, on an Inertia\n * visit (`X-Inertia: true`) it sends the page object as JSON.\n *\n * @module @forinda/kickjs-inertia/inertia\n */\nimport { RESPOND, type RequestContext, type Respondable } from '@forinda/kickjs'\nimport { isInertiaProp, propKind, resolveProp, type ScrollMeta } from './props'\n\nexport const ERRORS_KEY = '__inertia_errors'\nexport const FLASH_KEY = '__inertia_flash'\n/** URL of the last page rendered — where a failed submit goes back to. */\nexport const PREVIOUS_KEY = '__inertia_previous'\n/** Set by `redirect(url, { preserveFragment: true })` for the next page. */\nexport const FRAGMENT_KEY = '__inertia_fragment'\n\n/** The page object the Inertia client renders — see the protocol docs. */\nexport interface Page {\n component: string\n props: Record<string, unknown> & { errors: Record<string, unknown> }\n url: string\n version: string | null\n flash: Record<string, unknown>\n sharedProps?: string[]\n deferredProps?: Record<string, string[]>\n mergeProps?: string[]\n prependProps?: string[]\n deepMergeProps?: string[]\n matchPropsOn?: string[]\n scrollProps?: Record<string, ScrollMeta & { pageName: string; reset: boolean }>\n onceProps?: Record<string, { prop: string; expiresAt?: number }>\n encryptHistory?: boolean\n clearHistory?: boolean\n preserveFragment?: boolean\n}\n\nexport interface PageOptions {\n /** Encrypt this page's history entry in the browser. */\n encryptHistory?: boolean\n /** Wipe the browser's Inertia history, e.g. after logout. */\n clearHistory?: boolean\n /** Response status. Default 200; error pages send theirs (404, 500). */\n status?: number\n}\n\n/** What the adapter hands the page renderer. Set in `beforeMount`. */\nexport interface InertiaRuntime {\n version(): string | null\n share?(ctx: RequestContext): Record<string, unknown> | Promise<Record<string, unknown>>\n renderHtml(page: Page, ctx: RequestContext): Promise<string>\n /** Component that renders error and not-found pages, when configured. */\n errorPage?: string\n}\n\n/**\n * Where the adapter's middleware leaves its runtime on each request, so every\n * helper uses the adapter of the app that is handling that request — two apps\n * in one process (tests, a reload that overlaps the old app) never share one.\n */\nconst RUNTIME_SLOT = Symbol.for('kickjs.inertia.runtime')\n\nexport function bindInertiaRuntime(req: object, runtime: InertiaRuntime): void {\n ;(req as Record<symbol, unknown>)[RUNTIME_SLOT] = runtime\n}\n\n/** The runtime of the adapter that handled this request, or null without one. */\nexport function inertiaRuntimeFor(req: unknown): InertiaRuntime | null {\n return ((req as Record<symbol, unknown> | null)?.[RUNTIME_SLOT] as InertiaRuntime) ?? null\n}\n\nfunction runtime(ctx: RequestContext): InertiaRuntime {\n const rt = inertiaRuntimeFor(ctx.req)\n if (!rt) {\n throw new Error(\n 'inertia() needs InertiaAdapter — add it to bootstrap({ adapters: [InertiaAdapter({ entry })] }).',\n )\n }\n return rt\n}\n\nfunction header(ctx: RequestContext, name: string): string | undefined {\n const value = (ctx.headers as Record<string, string | string[] | undefined>)[name]\n return Array.isArray(value) ? value[0] : value\n}\n\nfunction list(value: string | undefined): string[] {\n return value\n ? value\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n : []\n}\n\nexport function requestUrl(req: unknown): string {\n const r = req as { originalUrl?: string; url?: string }\n return r.originalUrl ?? r.url ?? '/'\n}\n\nexport function isInertiaRequest(ctx: RequestContext): boolean {\n return header(ctx, 'x-inertia') === 'true'\n}\n\n/** Read and remove a one-request value from the session. */\nfunction take(ctx: RequestContext, key: string): Record<string, unknown> {\n const data = ctx.session?.data\n if (!data || data[key] === undefined) return {}\n const value = data[key] as Record<string, unknown>\n delete data[key]\n return value\n}\n\n/** Flash data for the next page, sent as the page's top-level `flash`. */\nexport function flash(ctx: RequestContext, data: Record<string, unknown>): void {\n const session = ctx.session\n if (!session) throw new Error('flash() needs the session() middleware.')\n session.data[FLASH_KEY] = { ...(session.data[FLASH_KEY] as object), ...data }\n}\n\nexport async function buildPage(\n ctx: RequestContext,\n component: string,\n props: Record<string, unknown>,\n options: PageOptions = {},\n): Promise<Page> {\n const rt = runtime(ctx)\n const shared = (await rt.share?.(ctx)) ?? {}\n const all: Record<string, unknown> = { ...shared, ...props }\n\n const partial = header(ctx, 'x-inertia-partial-component') === component\n const only = partial ? list(header(ctx, 'x-inertia-partial-data')) : []\n const except = partial ? list(header(ctx, 'x-inertia-partial-except')) : []\n const reset = list(header(ctx, 'x-inertia-reset'))\n // Once props the client already holds; it fills them in from its cache.\n const cachedOnce = list(header(ctx, 'x-inertia-except-once-props'))\n const scrollIntent =\n header(ctx, 'x-inertia-infinite-scroll-merge-intent') === 'prepend' ? 'prepend' : 'append'\n\n // A dot path in `only` ('users.data') still selects its top-level prop.\n const named = (key: string) => only.some((o) => o === key || o.startsWith(`${key}.`))\n\n const resolved: Record<string, unknown> = {}\n const deferredProps: Record<string, string[]> = {}\n const merges = { append: [] as string[], prepend: [] as string[], deep: [] as string[] }\n const matchPropsOn: string[] = []\n const scrollProps: NonNullable<Page['scrollProps']> = {}\n const onceProps: NonNullable<Page['onceProps']> = {}\n\n for (const [key, value] of Object.entries(all)) {\n const kind = isInertiaProp(value) ? propKind(value) : undefined\n let send: boolean\n if (kind === 'always') send = true\n else if (partial) send = (only.length === 0 || named(key)) && !except.includes(key)\n else send = kind !== 'optional' && kind !== 'defer'\n\n if (kind === 'once' && isInertiaProp(value)) {\n const onceKey = value.key ?? key\n onceProps[onceKey] = {\n prop: key,\n ...(value.ttl === undefined ? {} : { expiresAt: Date.now() + value.ttl }),\n }\n // Asked for by name, it is sent even when cached.\n if (cachedOnce.includes(onceKey) && !(partial && named(key))) send = false\n }\n\n if (!send) {\n if (!partial && kind === 'defer' && isInertiaProp(value)) {\n const group = value.group ?? 'default'\n ;(deferredProps[group] ??= []).push(key)\n }\n continue\n }\n resolved[key] = await resolveProp(value)\n if (kind === 'merge' && isInertiaProp(value) && !reset.includes(key)) {\n merges[value.mode ?? 'append'].push(key)\n for (const field of value.matchOn ?? []) matchPropsOn.push(`${key}.${field}`)\n }\n if (kind === 'scroll' && isInertiaProp(value)) {\n const path = `${key}.${value.wrapper}`\n const isReset = reset.includes(key)\n scrollProps[key] = {\n pageName: value.pageName!,\n ...value.meta!(resolved[key]),\n reset: isReset,\n }\n if (!isReset) merges[scrollIntent].push(path)\n for (const field of value.matchOn ?? []) matchPropsOn.push(`${path}.${field}`)\n }\n }\n\n const page: Page = {\n component,\n props: { ...resolved, errors: take(ctx, ERRORS_KEY) },\n url: requestUrl(ctx.req),\n version: rt.version(),\n flash: take(ctx, FLASH_KEY),\n }\n const sharedKeys = Object.keys(shared)\n if (sharedKeys.length) page.sharedProps = sharedKeys\n if (Object.keys(deferredProps).length) page.deferredProps = deferredProps\n if (merges.append.length) page.mergeProps = merges.append\n if (merges.prepend.length) page.prependProps = merges.prepend\n if (merges.deep.length) page.deepMergeProps = merges.deep\n if (matchPropsOn.length) page.matchPropsOn = matchPropsOn\n if (Object.keys(scrollProps).length) page.scrollProps = scrollProps\n if (Object.keys(onceProps).length) page.onceProps = onceProps\n if (ctx.session?.data[FRAGMENT_KEY]) {\n delete ctx.session.data[FRAGMENT_KEY]\n page.preserveFragment = true\n }\n if (options.encryptHistory) page.encryptHistory = true\n if (options.clearHistory) page.clearHistory = true\n return page\n}\n\n/**\n * Render an Inertia page. Return it from a handler:\n *\n * ```ts\n * @Get('/users')\n * async index() {\n * return inertia('Users/Index', { users: await this.users.list() })\n * }\n * ```\n */\nexport function inertia(\n component: string,\n props: Record<string, unknown> = {},\n options?: PageOptions,\n): Respondable {\n return {\n async [RESPOND](ctx: RequestContext) {\n const page = await buildPage(ctx, component, props, options)\n // Remembered for back(): helmet's default Referrer-Policy (no-referrer)\n // means the browser sends no Referer to go back to.\n if (ctx.session) ctx.session.data[PREVIOUS_KEY] = page.url\n // `Vary: X-Inertia` is added by the adapter's middleware, which can\n // append to a Vary another layer set instead of replacing it.\n if (isInertiaRequest(ctx)) {\n ctx.setHeader('X-Inertia', 'true')\n ctx.json(page, options?.status ?? 200)\n return\n }\n ctx.html(await runtime(ctx).renderHtml(page, ctx), options?.status ?? 200)\n },\n }\n}\n\nexport interface RedirectOptions {\n /**\n * Keep the `#fragment` of the URL the request was sent to — a form that\n * posts to `/posts/1/comments#comments` lands on `#comments` of the page\n * this redirects to. Needs `session()`.\n */\n preserveFragment?: boolean\n}\n\n/**\n * Redirect after a form submit. Uses 303 for anything but GET, so the browser\n * follows with a GET, and saves the session first so flashed errors and\n * messages are there when that GET arrives.\n *\n * A URL with a `#fragment` is sent to an Inertia visit as 409 +\n * `X-Inertia-Redirect`: a redirect followed inside a fetch drops the\n * fragment, so the client makes the visit itself.\n */\nexport function redirect(url: string, options: RedirectOptions = {}): Respondable {\n return {\n async [RESPOND](ctx: RequestContext) {\n if (options.preserveFragment && ctx.session) ctx.session.data[FRAGMENT_KEY] = true\n await ctx.session?.save()\n if (url.includes('#') && isInertiaRequest(ctx)) {\n ctx.setHeader('X-Inertia-Redirect', url)\n ctx.html('', 409)\n return\n }\n const method = (ctx.req as { method?: string }).method ?? 'GET'\n ctx.redirect(url, method === 'GET' ? 302 : 303)\n },\n }\n}\n\n/** A path on this site — not `//host` or `/\\\\host`, which browsers treat as another origin. */\nfunction localPath(value: unknown): string | undefined {\n return typeof value === 'string' && /^\\/(?![/\\\\])/.test(value) ? value : undefined\n}\n\n/** The path of a Referer, only when it points at this host. */\nfunction sameOriginPath(referer: string | undefined, host: string | undefined): string | undefined {\n if (!referer || !host) return undefined\n try {\n const url = new URL(referer)\n return url.host === host ? localPath(url.pathname + url.search) : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Where \"back\" is: the last page this session rendered, else a same-origin\n * Referer, else `fallback`. Never another site — a form on another site that\n * posts here must not be able to choose where the user lands.\n */\nexport function previousUrl(\n session: { data: Record<string, unknown> } | undefined,\n headers: { referer?: string | string[]; host?: string | string[] },\n fallback = '/',\n): string {\n const one = (v: string | string[] | undefined) => (Array.isArray(v) ? v[0] : v)\n return (\n localPath(session?.data[PREVIOUS_KEY]) ??\n sameOriginPath(one(headers.referer), one(headers.host)) ??\n fallback\n )\n}\n\n/** Redirect back to the page the request came from. */\nexport function back(ctx: RequestContext, fallback = '/', options?: RedirectOptions): Respondable {\n return redirect(\n previousUrl(\n ctx.session,\n { referer: header(ctx, 'referer'), host: header(ctx, 'host') },\n fallback,\n ),\n options,\n )\n}\n\n/**\n * A full browser visit, outside Inertia — another site, or a page that is not\n * an Inertia page. An Inertia request gets 409 + `X-Inertia-Location`, which\n * the client turns into `window.location`.\n */\nexport function location(url: string): Respondable {\n return {\n async [RESPOND](ctx: RequestContext) {\n if (isInertiaRequest(ctx)) {\n ctx.setHeader('X-Inertia-Location', url)\n ctx.html('', 409)\n return\n }\n ctx.redirect(url)\n },\n }\n}\n\n/** A browser navigation or an Inertia visit — not an API or asset request. */\nexport function isPageRequest(headers: Record<string, string | string[] | undefined>): boolean {\n const accept = String(headers.accept ?? '')\n return headers['x-inertia'] === 'true' || accept.includes('text/html')\n}\n\nconst STATUS_TEXT: Record<number, string> = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Page Not Found',\n 405: 'Method Not Allowed',\n 419: 'Page Expired',\n 429: 'Too Many Requests',\n 500: 'Server Error',\n 503: 'Service Unavailable',\n}\n\n/**\n * The configured error page as a response, with `{ status, message }` as its\n * props. A 5xx message is replaced in production — an exception's text is\n * for the log, not the visitor.\n */\nexport function errorPage(component: string, status: number, error?: unknown): Respondable {\n const fallback = STATUS_TEXT[status] ?? (status >= 500 ? 'Server Error' : 'Error')\n const raw = error instanceof Error && error.message ? error.message : fallback\n const message = status >= 500 && process.env.NODE_ENV === 'production' ? fallback : raw\n return inertia(component, { status, message }, { status })\n}\n","/**\n * The HTML shell for a first visit, and the script tags that load the client:\n * Vite's dev server while `kick dev` runs, the build manifest in production.\n *\n * @module @forinda/kickjs-inertia/html\n */\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { Page } from './inertia'\n\nexport interface HtmlParts {\n /** Script and style tags for the client entry. Put inside `<head>`. */\n head: string\n /** The page data and the mount element. Put inside `<body>`. */\n body: string\n page: Page\n}\n\nexport type HtmlTemplate = (parts: HtmlParts) => string\n\nconst escapeHtml = (value: string): string =>\n value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"')\n\nexport const defaultTemplate =\n (title: string): HtmlTemplate =>\n ({ head, body }) =>\n `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>${escapeHtml(title)}</title>\n ${head}\n </head>\n <body>\n ${body}\n </body>\n</html>`\n\n/**\n * The page as `<script data-page=\"app\" type=\"application/json\">` — where the\n * v3 client reads it — followed by the mount element. `<` and `/` are escaped\n * so a prop containing `</script>` cannot end the tag.\n */\nexport function pageBody(page: Page, id = 'app'): string {\n const json = JSON.stringify(page, (_k, v) => (typeof v === 'bigint' ? v.toString() : v))\n .replace(/</g, '\\\\u003c')\n .replace(/\\//g, '\\\\/')\n return `<script data-page=\"${id}\" type=\"application/json\">${json}</script>\\n <div id=\"${id}\"></div>`\n}\n\n/** Dev: one module script; Vite's `transformIndexHtml` adds its client and plugin preambles. */\nexport function devHead(entry: string): string {\n return `<script type=\"module\" src=\"/${entry.replace(/^\\/+/, '')}\"></script>`\n}\n\ninterface ManifestChunk {\n file: string\n css?: string[]\n imports?: string[]\n}\n\n/** Production: the entry's script, its CSS, and the CSS and preloads of what it imports. */\nexport function manifestHead(clientDir: string, entry: string): string {\n const manifest = JSON.parse(\n readFileSync(join(clientDir, '.vite', 'manifest.json'), 'utf8'),\n ) as Record<string, ManifestChunk>\n const chunk = manifest[entry]\n if (!chunk) {\n throw new Error(\n `InertiaAdapter: '${entry}' is not in ${clientDir}/.vite/manifest.json — build the client with build.manifest and this entry as an input.`,\n )\n }\n const css = new Set<string>()\n const preload = new Set<string>()\n const walk = (key: string, root: boolean) => {\n const c = manifest[key]\n if (!c) return\n for (const f of c.css ?? []) css.add(f)\n if (!root) preload.add(c.file)\n for (const i of c.imports ?? []) walk(i, false)\n }\n walk(entry, true)\n return [\n ...[...css].map((f) => `<link rel=\"stylesheet\" href=\"/${f}\" />`),\n ...[...preload].map((f) => `<link rel=\"modulepreload\" href=\"/${f}\" />`),\n `<script type=\"module\" src=\"/${chunk.file}\"></script>`,\n ].join('\\n ')\n}\n","/**\n * `InertiaAdapter` — wires the protocol into the app:\n *\n * - makes `inertia()` able to render (HTML shell, asset tags, version);\n * - answers a stale Inertia GET with 409 so the client reloads the page;\n * - turns a 302 after PUT / PATCH / DELETE into 303, so the browser follows\n * with a GET instead of repeating the method;\n * - in production, serves the built client's `assets/`.\n *\n * @module @forinda/kickjs-inertia/adapter\n */\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync, readdirSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { defineAdapter, Logger, type RequestContext } from '@forinda/kickjs'\nimport { bindInertiaRuntime, requestUrl, type InertiaRuntime, type Page } from './inertia'\nimport { defaultTemplate, devHead, manifestHead, pageBody, type HtmlTemplate } from './html'\n\nexport interface InertiaAdapterOptions {\n /**\n * The client entry, relative to the project root — the file that calls\n * `createInertiaApp`. Served by Vite in dev, looked up in the build\n * manifest in production. Default: `'src/client/main.tsx'`.\n */\n entry: string\n /** Where `vite build` wrote the client, with `build.manifest: true`. Default: `'dist/client'`. */\n clientDir: string\n /**\n * Asset version. A client on another version reloads the page on its next\n * visit. Default: a hash of the build manifest in production, none in dev\n * (Vite reloads changed modules itself).\n */\n version?: string | (() => string)\n /** Props every page gets — the current user, app name. */\n share?: (ctx: RequestContext) => Record<string, unknown> | Promise<Record<string, unknown>>\n /** `<title>` of the default HTML shell. */\n title: string\n /**\n * Tags added to every page's `<head>` — a favicon, meta tags, fonts. Per-page\n * titles and meta belong in the page, with Inertia's `<Head>` component.\n */\n head?: string\n /** Replace the HTML shell entirely. */\n template?: HtmlTemplate\n /**\n * Page component for errors and unknown URLs, e.g. `'Error'`. It receives\n * `{ status, message }`. Rendered for page requests by `inertiaErrorHandler()`\n * (thrown errors) and `inertiaNotFound()` (unknown URLs); API and asset\n * requests keep the usual JSON answers.\n */\n errorPage?: string\n /**\n * Render pages on the server. `entry` is a module whose default export is\n * `(page) => Promise<{ head: string[]; body: string }>` — what\n * `createInertiaApp({ page, render: renderToString, ... })` returns. Loaded\n * through Vite in dev; in production from `bundle`, the output of\n * `vite build --ssr <entry>` (default `'dist/ssr/ssr.js'`). A render that\n * throws falls back to client rendering for that request.\n */\n ssr?: { entry: string; bundle?: string }\n}\n\n/** What an SSR entry's default export returns. */\nexport interface SsrResult {\n head: string[]\n body: string\n}\n\ntype SsrRender = (page: Page) => Promise<SsrResult>\n\nconst log = Logger.for('InertiaAdapter')\n\ninterface ViteModuleLike {\n url: string\n id: string | null\n importedModules: Set<ViteModuleLike>\n}\n\ninterface ViteDevServerLike {\n config: { root: string }\n environments: { ssr: { moduleGraph: { getModuleById(id: string): ViteModuleLike | undefined } } }\n transformIndexHtml(url: string, html: string): Promise<string>\n ssrLoadModule(url: string): Promise<Record<string, unknown>>\n ssrFixStacktrace(err: Error): void\n}\n\nconst CSS_REQUEST = /\\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\\?)/\n\n/**\n * Dev only: the stylesheets the SSR entry imports, as `<link>` tags. In dev\n * Vite injects CSS from JavaScript, so server-rendered HTML would show\n * unstyled until the scripts run. `data-vite-dev-id` lets Vite's client\n * recognize these and not inject the same styles again.\n */\nfunction devStylesheets(vite: ViteDevServerLike, entry: string): string[] {\n const root = vite.environments.ssr.moduleGraph.getModuleById(resolve(vite.config.root, entry))\n if (!root) return []\n const links: string[] = []\n const seen = new Set<ViteModuleLike>()\n const walk = (mod: ViteModuleLike) => {\n if (seen.has(mod)) return\n seen.add(mod)\n if (CSS_REQUEST.test(mod.url)) {\n const devId = mod.id ? ` data-vite-dev-id=\"${mod.id.replace(/\"/g, '"')}\"` : ''\n links.push(`<link rel=\"stylesheet\" href=\"${mod.url}\"${devId} />`)\n return\n }\n for (const imported of mod.importedModules) walk(imported)\n }\n walk(root)\n return links\n}\n\nfunction viteServer(): ViteDevServerLike | null {\n return (\n (globalThis as { __kickjs_viteServer?: ViteDevServerLike | null }).__kickjs_viteServer ?? null\n )\n}\n\n/**\n * A build path, relative to the app: the working directory, or\n * `KICK_APP_ROOT` when set — the Netlify and Vercel functions `kick build:*`\n * writes set it to where they packaged the build, since the platform starts\n * them elsewhere.\n */\nfunction fromAppRoot(path: string): string {\n return resolve(process.env.KICK_APP_ROOT ?? process.cwd(), path)\n}\n\nfunction appendVary(res: ServerResponse, field: string): void {\n const current = res.getHeader('Vary')\n const list = (Array.isArray(current) ? current.join(',') : String(current ?? ''))\n .split(',')\n .map((v) => v.trim())\n .filter(Boolean)\n if (list.includes('*') || list.some((v) => v.toLowerCase() === field.toLowerCase())) return\n res.setHeader('Vary', [...list, field].join(', '))\n}\n\nfunction safeDecode(path: string): string {\n try {\n return decodeURIComponent(path)\n } catch {\n return path\n }\n}\n\ntype NodeMiddleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => void\n\nexport const InertiaAdapter = defineAdapter<InertiaAdapterOptions>({\n name: 'InertiaAdapter',\n defaults: {\n entry: 'src/client/main.tsx',\n clientDir: 'dist/client',\n title: 'KickJS',\n },\n build: (config) => {\n const clientDir = fromAppRoot(config.clientDir)\n const template = config.template ?? defaultTemplate(config.title)\n let version: () => string | null = () => null\n\n // Built in beforeMount, once the dev server / build is known.\n let runtime: InertiaRuntime | null = null\n\n const protocol: NodeMiddleware = (req, res, next) => {\n if (runtime) bindInertiaRuntime(req, runtime)\n // The same URL answers HTML or JSON depending on X-Inertia, so a shared\n // cache must key on it. Appended, not set: replacing a Vary another\n // layer added (Origin, Accept-Encoding) lets a cache serve one\n // client's variant to another.\n appendVary(res, 'X-Inertia')\n // A Precognition request gets a validation answer instead of the\n // route's response.\n if (req.headers.precognition === 'true') appendVary(res, 'Precognition')\n if (req.headers['x-inertia'] !== 'true') return next()\n\n const current = version()\n if (req.method === 'GET' && current && req.headers['x-inertia-version'] !== current) {\n res.statusCode = 409\n res.setHeader('X-Inertia-Location', requestUrl(req))\n res.end()\n return\n }\n\n if (req.method === 'PUT' || req.method === 'PATCH' || req.method === 'DELETE') {\n // Node sends every status through writeHead — also the implicit one\n // behind res.end() — so this catches a 302 from any code path.\n const writeHead = res.writeHead\n res.writeHead = function (this: ServerResponse, status: number, ...rest: unknown[]) {\n return (writeHead as (...a: unknown[]) => ServerResponse).call(\n this,\n status === 302 ? 303 : status,\n ...rest,\n )\n } as typeof res.writeHead\n }\n next()\n }\n\n return {\n beforeMount({ http }) {\n const vite = viteServer()\n let head: (page: Page) => string\n\n if (vite) {\n head = () => devHead(config.entry)\n } else {\n const tags = manifestHead(clientDir, config.entry)\n head = () => tags\n const hash = createHash('sha1')\n .update(readFileSync(join(clientDir, '.vite', 'manifest.json')))\n .digest('hex')\n .slice(0, 12)\n version = () => hash\n // The whole build: hashed `assets/` plus what Vite copied from\n // `public/` — favicon, robots.txt, a static sitemap.\n if (existsSync(join(clientDir, 'package.json'))) {\n throw new Error(\n `InertiaAdapter: clientDir ${clientDir} looks like a project root — it must be the client build output (default dist/client), which is served as-is.`,\n )\n }\n // Not every engine's static handler skips dotfiles, so the build's\n // own (`.vite/manifest.json`) are refused here, before it runs.\n const hidden = new Set(readdirSync(clientDir).filter((name) => name.startsWith('.')))\n const hideBuildFiles: NodeMiddleware = (req, res, next) => {\n const first = safeDecode((req.url ?? '/').split('?')[0]!)\n .split('/')\n .find(Boolean)\n if (first && hidden.has(first)) {\n res.statusCode = 404\n res.end()\n return\n }\n next()\n }\n http.use(hideBuildFiles as never)\n http.serveStatic('/', clientDir)\n }\n if (config.version !== undefined) {\n const v = config.version\n version = typeof v === 'function' ? v : () => v\n }\n\n const ssr = config.ssr\n let prodRender: Promise<SsrRender> | undefined\n const loadRender = async (): Promise<SsrRender> => {\n if (vite) {\n // Every request in dev, so an edited page renders fresh.\n const mod = await vite.ssrLoadModule(`/${ssr!.entry.replace(/^\\/+/, '')}`)\n return mod.default as SsrRender\n }\n const url = pathToFileURL(fromAppRoot(ssr!.bundle ?? 'dist/ssr/ssr.js')).href\n // The app's own build output, chosen at runtime — nothing for Vite to analyze.\n prodRender ??= import(/* @vite-ignore */ url).then((mod) => mod.default as SsrRender)\n return prodRender\n }\n const render = async (page: Page): Promise<SsrResult | null> => {\n if (!ssr) return null\n try {\n return await (\n await loadRender()\n )(page)\n } catch (err) {\n if (vite && err instanceof Error) vite.ssrFixStacktrace(err)\n log.error(err, `SSR failed for ${page.component} — sending it client-rendered`)\n return null\n }\n }\n\n runtime = {\n version: () => version(),\n share: config.share,\n errorPage: config.errorPage,\n async renderHtml(page, ctx) {\n const rendered = await render(page)\n const styles = vite && rendered && ssr ? devStylesheets(vite, ssr.entry) : []\n const html = template({\n head: [config.head ?? '', head(page), ...styles, ...(rendered?.head ?? [])]\n .filter(Boolean)\n .join('\\n '),\n body: rendered?.body ?? pageBody(page),\n page,\n })\n return vite ? vite.transformIndexHtml(requestUrl(ctx.req), html) : html\n },\n }\n },\n\n middleware() {\n return [{ handler: protocol as never, phase: 'afterGlobal' as const }]\n },\n }\n },\n})\n","/**\n * Validation errors the Inertia way: on an Inertia request, a 422 from route\n * validation becomes a redirect back with the errors in the session, and the\n * next page gets them as `props.errors`. Everything else goes to the usual\n * error handler.\n *\n * @module @forinda/kickjs-inertia/errors\n */\nimport {\n errorHandler,\n HttpException,\n Logger,\n RequestContext,\n RESPOND,\n type MiddlewareHandler,\n type RuntimeResponse,\n} from '@forinda/kickjs'\nimport { ERRORS_KEY, errorPage, inertiaRuntimeFor, isPageRequest, previousUrl } from './inertia'\n\nconst log = Logger.for('Inertia')\n\ntype ErrorHandler = (\n err: any,\n req: any,\n res: RuntimeResponse,\n next: (err?: unknown) => void,\n) => unknown\n\ninterface SessionLike {\n data: Record<string, unknown>\n save(): Promise<void>\n}\n\n/** `[{ field, message }]` from route validation → `{ field: firstMessage }`. */\nfunction toErrors(details: unknown): Record<string, string> | null {\n if (!Array.isArray(details)) return null\n const errors: Record<string, string> = {}\n for (const d of details as Array<{ field?: string; message?: string }>) {\n const field = d.field || 'form'\n errors[field] ??= d.message ?? 'Invalid value'\n }\n return errors\n}\n\nfunction isPrecognitive(req: any): boolean {\n return req?.headers?.precognition === 'true'\n}\n\n/**\n * A Precognition answer: 204 when nothing the client asked about failed,\n * else 422 with those fields' errors. `Precognition-Validate-Only` names the\n * fields a form has touched, so errors on the rest are not shown yet.\n */\nfunction precognitionResult(req: any, res: RuntimeResponse, errors: Record<string, string>) {\n const only = String(req.headers['precognition-validate-only'] ?? '')\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n const shown = only.length\n ? Object.fromEntries(\n Object.entries(errors).filter(([field]) =>\n only.some((o) => field === o || field.startsWith(`${o}.`)),\n ),\n )\n : errors\n res.setHeader('Precognition', 'true')\n if (Object.keys(shown).length === 0) {\n res.setHeader('Precognition-Success', 'true')\n res.status(204).end()\n return\n }\n res.status(422).json({ message: 'The given data was invalid.', errors: shown })\n}\n\n/**\n * Live validation for Inertia's `useForm().validate()` — Laravel Precognition.\n * Put it on a route that validates its body; a precognitive request runs the\n * validation and stops before the handler:\n *\n * ```ts\n * @Post('/users', { body: createUserSchema })\n * @Middleware(precognitive)\n * create(ctx: RequestContext) { ... }\n * ```\n *\n * A failed check is answered by `inertiaErrorHandler()`.\n */\nexport const precognitive: MiddlewareHandler<RequestContext> = (ctx, next) => {\n if (!isPrecognitive(ctx.req)) return next()\n ctx.setHeader('Precognition', 'true')\n ctx.setHeader('Precognition-Success', 'true')\n ctx.noContent()\n}\n\n/**\n * Pass to `bootstrap({ onError: inertiaErrorHandler() })`.\n *\n * - A validation 422 on a Precognition request is answered with the errors\n * of the fields it asked about (see `precognitive`).\n * - A validation 422 on an Inertia visit goes back to the form with the\n * errors (needs the `session()` middleware to carry them).\n * - Any other error on a page request renders the adapter's `errorPage`,\n * when one is configured.\n * - Everything else — API calls, assets — goes to `fallback`.\n */\nexport function inertiaErrorHandler(fallback: ErrorHandler = errorHandler()): ErrorHandler {\n let warned = false\n return (err, req, res, next) => {\n if (res.headersSent) return fallback(err, req, res, next)\n\n const errors = err instanceof HttpException && err.status === 422 ? toErrors(err.details) : null\n if (errors && isPrecognitive(req)) return precognitionResult(req, res, errors)\n if (errors && req?.headers?.['x-inertia'] === 'true') {\n const session = req.session as SessionLike | undefined\n if (session) {\n const bag = req.headers['x-inertia-error-bag'] as string | undefined\n session.data[ERRORS_KEY] = bag ? { [bag]: errors } : errors\n // Returned, so an engine that waits on async handlers waits on this.\n return session\n .save()\n .then(() => {\n res.status(303).setHeader('location', previousUrl(session, req.headers))\n res.end()\n })\n .catch((saveErr) => fallback(saveErr, req, res, next))\n }\n if (!warned) {\n log.warn(\n 'Validation failed on an Inertia request, but there is no session() middleware to carry the errors — answering 422 instead.',\n )\n warned = true\n }\n return fallback(err, req, res, next)\n }\n\n const component = inertiaRuntimeFor(req)?.errorPage\n if (component && req?.headers && isPageRequest(req.headers)) {\n const status = err instanceof HttpException ? err.status : 500\n if (status >= 500) log.error(err, 'Unhandled error on a page request')\n const ctx = new RequestContext(req, res as never, next, res)\n return Promise.resolve(errorPage(component, status, err)[RESPOND](ctx)).catch((renderErr) =>\n fallback(renderErr, req, res, next),\n )\n }\n return fallback(err, req, res, next)\n }\n}\n\ntype NotFoundHandler = (\n req: any,\n res: RuntimeResponse,\n next: (err?: unknown) => void,\n) => void | Promise<void>\n\n/**\n * Pass to `bootstrap({ onNotFound: inertiaNotFound() })`. A browser or Inertia\n * request for an unknown URL gets the adapter's `errorPage` with 404; anything\n * else — API calls, other methods — goes on to the built-in 404 / 405.\n */\nexport function inertiaNotFound(): NotFoundHandler {\n return (req, res, next) => {\n const component = inertiaRuntimeFor(req)?.errorPage\n const method = req?.method ?? 'GET'\n if (\n !component ||\n (method !== 'GET' && method !== 'HEAD') ||\n !isPageRequest(req.headers ?? {})\n ) {\n return next()\n }\n const ctx = new RequestContext(req, res as never, next, res)\n return Promise.resolve(errorPage(component, 404)[RESPOND](ctx)).catch(next)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAUA,MAAM,OAAO,OAAO,IAAI,qBAAqB;AA8B7C,SAAS,KAAQ,MAAgB,OAAoB,OAAgC;CACnF,OAAO;GAAG,OAAO;EAAM;EAAO,GAAG;CAAM;AACzC;;AAGA,SAAgB,SAAY,OAA6C;CACvE,OAAO,KAAK,YAAY,KAAK;AAC/B;;AAGA,SAAgB,OAAU,OAAoC;CAC5D,OAAO,KAAK,UAAU,KAAK;AAC7B;;;;;AAMA,SAAgB,MAAS,OAA6B,QAAQ,WAA2B;CACvF,OAAO,KAAK,SAAS,OAAO,EAAE,MAAM,CAAC;AACvC;;;;;AAMA,SAAgB,MACd,OACA,OAAsC,UACtC,UAA2C,CAAC,GAC5B;CAChB,OAAO,KAAK,SAAS,OAAO;EAAE;EAAM,SAAS,OAAO,QAAQ,OAAO;CAAE,CAAC;AACxE;;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o.ts","../src/inertia.ts","../src/html.ts","../src/adapter.ts","../src/errors.ts"],"sourcesContent":["/**\n * Prop wrappers that change when a prop is sent. A plain value or a function\n * is sent on every full visit and on a partial reload that asks for it; a\n * function is only called when the prop is actually sent.\n *\n * @module @forinda/kickjs-inertia/props\n */\n\ntype Resolver<T> = T | (() => T | Promise<T>)\n\nconst PROP = Symbol.for('kickjs.inertia.prop')\n\nexport type PropKind = 'optional' | 'always' | 'defer' | 'merge' | 'once' | 'scroll'\n\n/** Where an infinite-scroll prop is in its pages; `null` past either end. */\nexport interface ScrollMeta {\n currentPage: number | string | null\n nextPage: number | string | null\n previousPage: number | string | null\n}\n\nexport interface InertiaProp<T = unknown> {\n readonly [PROP]: PropKind\n readonly value: Resolver<T>\n /** `defer` only — props in one group load in one request. */\n readonly group?: string\n /** `merge` only — append, prepend or deep-merge into the client's copy. */\n readonly mode?: 'append' | 'prepend' | 'deep'\n /** `merge` and `scroll` — item fields that identify a row, e.g. `['id']`. */\n readonly matchOn?: string[]\n /** `once` only — the name the client caches it under. */\n readonly key?: string\n /** `once` only — milliseconds the client may keep it. */\n readonly ttl?: number\n /** `scroll` only. */\n readonly pageName?: string\n readonly wrapper?: string\n readonly meta?: (value: any) => ScrollMeta\n}\n\nfunction prop<T>(kind: PropKind, value: Resolver<T>, extra?: object): InertiaProp<T> {\n return { [PROP]: kind, value, ...extra }\n}\n\n/** Sent only when a partial reload names it (`router.reload({ only: [...] })`). */\nexport function optional<T>(value: () => T | Promise<T>): InertiaProp<T> {\n return prop('optional', value)\n}\n\n/** Sent on every response, including partial reloads that did not name it. */\nexport function always<T>(value: Resolver<T>): InertiaProp<T> {\n return prop('always', value)\n}\n\n/**\n * Left out of the first response; the client fetches it right after the page\n * renders, one request per `group`.\n */\nexport function defer<T>(value: () => T | Promise<T>, group = 'default'): InertiaProp<T> {\n return prop('defer', value, { group })\n}\n\n/**\n * Merged into the client's current value on a partial reload instead of\n * replacing it — paginated lists, infinite scroll.\n */\nexport function merge<T>(\n value: Resolver<T>,\n mode: 'append' | 'prepend' | 'deep' = 'append',\n options: { matchOn?: string | string[] } = {},\n): InertiaProp<T> {\n return prop('merge', value, { mode, matchOn: toList(options.matchOn) })\n}\n\n/**\n * Resolved once, then kept by the client: later visits skip it until `ttl`\n * runs out. For data that rarely changes — plans, countries, a settings\n * list. Pages that share a `key` share the cached value.\n */\nexport function once<T>(\n value: Resolver<T>,\n options: { key?: string; ttl?: number } = {},\n): InertiaProp<T> {\n return prop('once', value, options)\n}\n\n/**\n * One page of an infinite list, for Inertia's `<InfiniteScroll>`. The client\n * asks for the next or previous page with `?page=N` and appends or prepends\n * the rows under `wrapper`.\n *\n * The value is read as `{ data, meta: { page, hasNext, hasPrev } }` — the\n * `PaginatedResponse` shape; pass `meta` to read another one.\n */\nexport function scroll<T>(\n value: Resolver<T>,\n options: {\n pageName?: string\n wrapper?: string\n matchOn?: string | string[]\n meta?: (value: T) => ScrollMeta\n } = {},\n): InertiaProp<T> {\n return prop('scroll', value, {\n pageName: options.pageName ?? 'page',\n wrapper: options.wrapper ?? 'data',\n matchOn: toList(options.matchOn),\n meta: options.meta ?? paginatedMeta,\n })\n}\n\nfunction toList(value: string | string[] | undefined): string[] | undefined {\n return value === undefined ? undefined : Array.isArray(value) ? value : [value]\n}\n\nfunction paginatedMeta(value: unknown): ScrollMeta {\n const meta = (value as { meta?: { page?: number; hasNext?: boolean; hasPrev?: boolean } })?.meta\n if (typeof meta?.page !== 'number') {\n throw new Error(\n 'scroll(): the value has no `meta.page` — return `{ data, meta: { page, hasNext, hasPrev } }` or pass `meta`.',\n )\n }\n return {\n currentPage: meta.page,\n nextPage: meta.hasNext ? meta.page + 1 : null,\n previousPage: meta.hasPrev ? meta.page - 1 : null,\n }\n}\n\nexport function isInertiaProp(value: unknown): value is InertiaProp {\n return typeof value === 'object' && value !== null && PROP in value\n}\n\nexport function propKind(value: InertiaProp): PropKind {\n return value[PROP]\n}\n\n/** Unwrap a wrapper, call a function, await a promise. */\nexport async function resolveProp(value: unknown): Promise<unknown> {\n const raw = isInertiaProp(value) ? value.value : value\n return typeof raw === 'function' ? await (raw as () => unknown)() : await raw\n}\n","/**\n * Search-engine support: page meta set by the handler (rendered into the\n * first-visit HTML and sent to the client on every visit), plus\n * `sitemap()` and `robots()` responses.\n *\n * @module @forinda/kickjs-inertia/seo\n */\nimport { RESPOND, type RequestContext, type Respondable } from '@forinda/kickjs'\n\n/** A page's title, description and social tags. Every value is escaped on output. */\nexport interface PageMeta {\n title?: string\n description?: string\n /** A path (`'/posts/1'`, made absolute with `baseUrl`) or a full URL. */\n canonical?: string\n /** E.g. `'noindex, nofollow'`. */\n robots?: string\n /** Open Graph, without the `og:` prefix: `{ type: 'article', image: '/cover.png' }`. */\n og?: Record<string, string>\n /** Twitter cards, without the `twitter:` prefix: `{ card: 'summary_large_image' }`. */\n twitter?: Record<string, string>\n /** Structured data, rendered as `<script type=\"application/ld+json\">`. */\n jsonLd?: Record<string, unknown> | Record<string, unknown>[]\n}\n\n/** Adapter-wide meta, under each page's. */\nexport interface MetaDefaults extends PageMeta {\n /** Wraps a page's title: `'%s · My App'`. Not applied to the default `title`. */\n titleTemplate?: string\n}\n\nconst escapeHtml = (value: string): string =>\n value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"')\n\n/** A site path made absolute with `baseUrl`; anything else is left as it is. */\nfunction absolute(value: string | undefined, baseUrl: string | undefined): string | undefined {\n if (!value || !baseUrl || !/^\\/(?![/\\\\])/.test(value)) return value\n return baseUrl.replace(/\\/+$/, '') + value\n}\n\n/**\n * The meta a page is sent with: `defaults` under `meta`, the title template\n * applied, and paths made absolute with `baseUrl`. Without a `canonical`, a\n * successful page gets `baseUrl` + its path (no query) — never the request's\n * Host header, which the client chooses.\n */\nexport function resolveMeta(\n defaults: MetaDefaults = {},\n meta: PageMeta = {},\n options: { baseUrl?: string; path?: string; status?: number } = {},\n): PageMeta | undefined {\n const { titleTemplate, ...base } = defaults\n const { baseUrl, path, status = 200 } = options\n const title =\n meta.title !== undefined && titleTemplate\n ? // A function, so `$&` / `$'` in a title aren't replacement patterns.\n titleTemplate.replace('%s', () => meta.title!)\n : (meta.title ?? base.title)\n const description = meta.description ?? base.description\n let canonical = meta.canonical ?? base.canonical\n if (canonical === undefined && baseUrl && path !== undefined && status < 300) {\n canonical = path.split(/[?#]/)[0]\n }\n canonical = absolute(canonical, baseUrl)\n\n const og = { ...base.og, ...meta.og }\n og.title ??= meta.title ?? base.title!\n og.description ??= description!\n og.url ??= canonical!\n og.image = absolute(og.image, baseUrl)!\n const twitter = { ...base.twitter, ...meta.twitter }\n twitter.image = absolute(twitter.image, baseUrl)!\n\n const strip = (r: Record<string, string>) =>\n Object.fromEntries(Object.entries(r).filter(([, v]) => v !== undefined))\n const out: PageMeta = {\n title,\n description,\n canonical,\n robots: meta.robots ?? base.robots,\n og: strip(og),\n twitter: strip(twitter),\n jsonLd: meta.jsonLd ?? base.jsonLd,\n }\n for (const key of Object.keys(out) as (keyof PageMeta)[]) {\n const v = out[key]\n if (v === undefined || (typeof v === 'object' && !Object.keys(v).length)) delete out[key]\n }\n return Object.keys(out).length ? out : undefined\n}\n\n/** JSON for a `<script>` body: `<` escaped, so a value can't close the tag. */\nfunction scriptJson(value: unknown): string {\n return JSON.stringify(value)\n .replace(/</g, '\\\\u003c')\n .replace(/>/g, '\\\\u003e')\n .replace(/&/g, '\\\\u0026')\n}\n\n/**\n * The meta as head tags. Each carries `data-inertia=\"<key>\"` — what Inertia's\n * `<Head>` gives a tag with that `head-key` — so the client takes them over\n * and replaces them on the next visit instead of leaving them behind.\n */\nexport function metaTags(meta: PageMeta | undefined): string[] {\n if (!meta) return []\n const tags: string[] = []\n const m = (attr: 'name' | 'property', key: string, value: string) =>\n tags.push(\n `<meta data-inertia=\"${escapeHtml(key)}\" ${attr}=\"${escapeHtml(key)}\" content=\"${escapeHtml(value)}\" />`,\n )\n if (meta.title !== undefined)\n tags.push(`<title data-inertia=\"\">${escapeHtml(meta.title)}</title>`)\n if (meta.description !== undefined) m('name', 'description', meta.description)\n if (meta.robots !== undefined) m('name', 'robots', meta.robots)\n if (meta.canonical !== undefined) {\n tags.push(\n `<link data-inertia=\"canonical\" rel=\"canonical\" href=\"${escapeHtml(meta.canonical)}\" />`,\n )\n }\n for (const [k, v] of Object.entries(meta.og ?? {})) m('property', `og:${k}`, v)\n for (const [k, v] of Object.entries(meta.twitter ?? {})) m('name', `twitter:${k}`, v)\n if (meta.jsonLd !== undefined) {\n tags.push(\n `<script data-inertia=\"json-ld\" type=\"application/ld+json\">${scriptJson(meta.jsonLd)}</script>`,\n )\n }\n return tags\n}\n\n/** What a head tag sets — two tags with the same key are duplicates. */\nfunction tagKey(tag: string): string | null {\n const attr = (name: string) =>\n tag.match(new RegExp(`\\\\s${name}\\\\s*=\\\\s*[\"']([^\"']*)[\"']`, 'i'))?.[1]?.toLowerCase()\n if (/^<title[\\s>]/i.test(tag)) return 'title'\n if (/^<meta\\s/i.test(tag)) {\n const key = attr('name') ?? attr('property')\n return key ? `meta:${key}` : null\n }\n if (/^<link\\s/i.test(tag) && attr('rel') === 'canonical') return 'canonical'\n if (/^<script\\s/i.test(tag) && attr('type') === 'application/ld+json') return 'json-ld'\n return null\n}\n\n/** `tags` minus the ones `winners` (a server-rendered `<Head>`) already set. */\nexport function dedupeHead(tags: string[], winners: string[]): string[] {\n const taken = new Set(winners.map((t) => tagKey(t.trim())).filter(Boolean))\n return tags.filter((t) => !taken.has(tagKey(t)))\n}\n\nconst escapeXml = (value: string): string =>\n value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n\nexport interface SitemapEntry {\n /** A full URL, or a path made absolute with `baseUrl`. */\n loc: string\n /** A `Date`, or a W3C date string (`'2026-10-16'`). */\n lastmod?: Date | string\n changefreq?: 'always' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'never'\n /** 0.0 – 1.0. */\n priority?: number\n}\n\n/** The sitemap XML for `entries`. Paths are made absolute with `baseUrl`. */\nexport function sitemapXml(entries: Iterable<SitemapEntry>, baseUrl?: string): string {\n const urls = [...entries].map((e) => {\n const lastmod = e.lastmod instanceof Date ? e.lastmod.toISOString() : e.lastmod\n return [\n ' <url>',\n ` <loc>${escapeXml(absolute(e.loc, baseUrl)!)}</loc>`,\n lastmod && ` <lastmod>${escapeXml(lastmod)}</lastmod>`,\n e.changefreq && ` <changefreq>${e.changefreq}</changefreq>`,\n e.priority !== undefined && ` <priority>${Number(e.priority).toFixed(1)}</priority>`,\n ' </url>',\n ]\n .filter(Boolean)\n .join('\\n')\n })\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n${urls.join('\\n')}\n</urlset>\n`\n}\n\n/**\n * Answer `/sitemap.xml`. Return it from a handler:\n *\n * ```ts\n * @Get('/sitemap.xml')\n * sitemap() {\n * return sitemap([{ loc: '/' }, { loc: '/posts', changefreq: 'daily' }], { baseUrl: getEnv('APP_URL') })\n * }\n * ```\n */\nexport function sitemap(\n entries: Iterable<SitemapEntry>,\n options: { baseUrl?: string } = {},\n): Respondable {\n const xml = sitemapXml(entries, options.baseUrl)\n return {\n [RESPOND](ctx: RequestContext) {\n ctx.send(xml, { type: 'application/xml; charset=utf-8' })\n },\n }\n}\n\nexport interface RobotsOptions {\n /** Default `'*'`. */\n userAgent?: string\n allow?: string[]\n disallow?: string[]\n /** Sitemap URL(s) — a path is made absolute with `baseUrl`. */\n sitemap?: string | string[]\n baseUrl?: string\n}\n\n/** The robots.txt text. Line breaks in values are dropped, so one can't add a rule. */\nexport function robotsTxt(options: RobotsOptions = {}): string {\n const clean = (v: string) => v.replace(/[\\r\\n]+/g, '')\n const lines = [`User-agent: ${clean(options.userAgent ?? '*')}`]\n for (const p of options.allow ?? []) lines.push(`Allow: ${clean(p)}`)\n for (const p of options.disallow ?? []) lines.push(`Disallow: ${clean(p)}`)\n if (!options.allow?.length && !options.disallow?.length) lines.push('Allow: /')\n const maps = options.sitemap === undefined ? [] : [options.sitemap].flat()\n if (maps.length)\n lines.push('', ...maps.map((s) => `Sitemap: ${clean(absolute(s, options.baseUrl)!)}`))\n return `${lines.join('\\n')}\\n`\n}\n\n/** Answer `/robots.txt`. */\nexport function robots(options: RobotsOptions = {}): Respondable {\n const text = robotsTxt(options)\n return {\n [RESPOND](ctx: RequestContext) {\n ctx.send(text)\n },\n }\n}\n","/**\n * Page responses. `inertia(component, props)` is a handler return value: on a\n * first visit it renders the HTML shell with the page embedded, on an Inertia\n * visit (`X-Inertia: true`) it sends the page object as JSON.\n *\n * @module @forinda/kickjs-inertia/inertia\n */\nimport { RESPOND, type RequestContext, type Respondable } from '@forinda/kickjs'\nimport { isInertiaProp, propKind, resolveProp, type ScrollMeta } from './props'\nimport { resolveMeta, type MetaDefaults, type PageMeta } from './seo'\n\nexport const ERRORS_KEY = '__inertia_errors'\nexport const FLASH_KEY = '__inertia_flash'\n/** URL of the last page rendered — where a failed submit goes back to. */\nexport const PREVIOUS_KEY = '__inertia_previous'\n/** Set by `redirect(url, { preserveFragment: true })` for the next page. */\nexport const FRAGMENT_KEY = '__inertia_fragment'\n\n/** The page object the Inertia client renders — see the protocol docs. */\nexport interface Page {\n component: string\n props: Record<string, unknown> & { errors: Record<string, unknown> }\n url: string\n version: string | null\n flash: Record<string, unknown>\n sharedProps?: string[]\n deferredProps?: Record<string, string[]>\n mergeProps?: string[]\n prependProps?: string[]\n deepMergeProps?: string[]\n matchPropsOn?: string[]\n scrollProps?: Record<string, ScrollMeta & { pageName: string; reset: boolean }>\n onceProps?: Record<string, { prop: string; expiresAt?: number }>\n encryptHistory?: boolean\n clearHistory?: boolean\n preserveFragment?: boolean\n /** Title, description and social tags — see `PageOptions.meta`. */\n meta?: PageMeta\n}\n\nexport interface PageOptions {\n /** Encrypt this page's history entry in the browser. */\n encryptHistory?: boolean\n /** Wipe the browser's Inertia history, e.g. after logout. */\n clearHistory?: boolean\n /** Response status. Default 200; error pages send theirs (404, 500). */\n status?: number\n /**\n * Title, description, canonical URL and social tags, under the adapter's\n * `meta` defaults. Rendered into the first-visit HTML and sent as the\n * page's `meta` on every visit, for a `<Head>` in the client to keep the\n * browser's head in sync. A server-rendered `<Head>` tag wins over the same tag here.\n */\n meta?: PageMeta\n}\n\n/** What the adapter hands the page renderer. Set in `beforeMount`. */\nexport interface InertiaRuntime {\n version(): string | null\n share?(ctx: RequestContext): Record<string, unknown> | Promise<Record<string, unknown>>\n renderHtml(page: Page, ctx: RequestContext): Promise<string>\n /** Component that renders error and not-found pages, when configured. */\n errorPage?: string\n /** Meta every page starts from. */\n meta?: MetaDefaults\n /** Origin (and base path) for canonical and absolute URLs. */\n baseUrl?: string\n}\n\n/**\n * Where the adapter's middleware leaves its runtime on each request, so every\n * helper uses the adapter of the app that is handling that request — two apps\n * in one process (tests, a reload that overlaps the old app) never share one.\n */\nconst RUNTIME_SLOT = Symbol.for('kickjs.inertia.runtime')\n\nexport function bindInertiaRuntime(req: object, runtime: InertiaRuntime): void {\n ;(req as Record<symbol, unknown>)[RUNTIME_SLOT] = runtime\n}\n\n/** The runtime of the adapter that handled this request, or null without one. */\nexport function inertiaRuntimeFor(req: unknown): InertiaRuntime | null {\n return ((req as Record<symbol, unknown> | null)?.[RUNTIME_SLOT] as InertiaRuntime) ?? null\n}\n\nfunction runtime(ctx: RequestContext): InertiaRuntime {\n const rt = inertiaRuntimeFor(ctx.req)\n if (!rt) {\n throw new Error(\n 'inertia() needs InertiaAdapter — add it to bootstrap({ adapters: [InertiaAdapter({ entry })] }).',\n )\n }\n return rt\n}\n\nfunction header(ctx: RequestContext, name: string): string | undefined {\n const value = (ctx.headers as Record<string, string | string[] | undefined>)[name]\n return Array.isArray(value) ? value[0] : value\n}\n\nfunction list(value: string | undefined): string[] {\n return value\n ? value\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n : []\n}\n\nexport function requestUrl(req: unknown): string {\n const r = req as { originalUrl?: string; url?: string }\n return r.originalUrl ?? r.url ?? '/'\n}\n\nexport function isInertiaRequest(ctx: RequestContext): boolean {\n return header(ctx, 'x-inertia') === 'true'\n}\n\n/** Read and remove a one-request value from the session. */\nfunction take(ctx: RequestContext, key: string): Record<string, unknown> {\n const data = ctx.session?.data\n if (!data || data[key] === undefined) return {}\n const value = data[key] as Record<string, unknown>\n delete data[key]\n return value\n}\n\n/** Flash data for the next page, sent as the page's top-level `flash`. */\nexport function flash(ctx: RequestContext, data: Record<string, unknown>): void {\n const session = ctx.session\n if (!session) throw new Error('flash() needs the session() middleware.')\n session.data[FLASH_KEY] = { ...(session.data[FLASH_KEY] as object), ...data }\n}\n\nexport async function buildPage(\n ctx: RequestContext,\n component: string,\n props: Record<string, unknown>,\n options: PageOptions = {},\n): Promise<Page> {\n const rt = runtime(ctx)\n const shared = (await rt.share?.(ctx)) ?? {}\n const all: Record<string, unknown> = { ...shared, ...props }\n\n const partial = header(ctx, 'x-inertia-partial-component') === component\n const only = partial ? list(header(ctx, 'x-inertia-partial-data')) : []\n const except = partial ? list(header(ctx, 'x-inertia-partial-except')) : []\n const reset = list(header(ctx, 'x-inertia-reset'))\n // Once props the client already holds; it fills them in from its cache.\n const cachedOnce = list(header(ctx, 'x-inertia-except-once-props'))\n const scrollIntent =\n header(ctx, 'x-inertia-infinite-scroll-merge-intent') === 'prepend' ? 'prepend' : 'append'\n\n // A dot path in `only` ('users.data') still selects its top-level prop.\n const named = (key: string) => only.some((o) => o === key || o.startsWith(`${key}.`))\n\n const resolved: Record<string, unknown> = {}\n const deferredProps: Record<string, string[]> = {}\n const merges = { append: [] as string[], prepend: [] as string[], deep: [] as string[] }\n const matchPropsOn: string[] = []\n const scrollProps: NonNullable<Page['scrollProps']> = {}\n const onceProps: NonNullable<Page['onceProps']> = {}\n\n for (const [key, value] of Object.entries(all)) {\n const kind = isInertiaProp(value) ? propKind(value) : undefined\n let send: boolean\n if (kind === 'always') send = true\n else if (partial) send = (only.length === 0 || named(key)) && !except.includes(key)\n else send = kind !== 'optional' && kind !== 'defer'\n\n if (kind === 'once' && isInertiaProp(value)) {\n const onceKey = value.key ?? key\n onceProps[onceKey] = {\n prop: key,\n ...(value.ttl === undefined ? {} : { expiresAt: Date.now() + value.ttl }),\n }\n // Asked for by name, it is sent even when cached.\n if (cachedOnce.includes(onceKey) && !(partial && named(key))) send = false\n }\n\n if (!send) {\n if (!partial && kind === 'defer' && isInertiaProp(value)) {\n const group = value.group ?? 'default'\n ;(deferredProps[group] ??= []).push(key)\n }\n continue\n }\n resolved[key] = await resolveProp(value)\n if (kind === 'merge' && isInertiaProp(value) && !reset.includes(key)) {\n merges[value.mode ?? 'append'].push(key)\n for (const field of value.matchOn ?? []) matchPropsOn.push(`${key}.${field}`)\n }\n if (kind === 'scroll' && isInertiaProp(value)) {\n const path = `${key}.${value.wrapper}`\n const isReset = reset.includes(key)\n scrollProps[key] = {\n pageName: value.pageName!,\n ...value.meta!(resolved[key]),\n reset: isReset,\n }\n if (!isReset) merges[scrollIntent].push(path)\n for (const field of value.matchOn ?? []) matchPropsOn.push(`${path}.${field}`)\n }\n }\n\n const page: Page = {\n component,\n props: { ...resolved, errors: take(ctx, ERRORS_KEY) },\n url: requestUrl(ctx.req),\n version: rt.version(),\n flash: take(ctx, FLASH_KEY),\n }\n const sharedKeys = Object.keys(shared)\n if (sharedKeys.length) page.sharedProps = sharedKeys\n if (Object.keys(deferredProps).length) page.deferredProps = deferredProps\n if (merges.append.length) page.mergeProps = merges.append\n if (merges.prepend.length) page.prependProps = merges.prepend\n if (merges.deep.length) page.deepMergeProps = merges.deep\n if (matchPropsOn.length) page.matchPropsOn = matchPropsOn\n if (Object.keys(scrollProps).length) page.scrollProps = scrollProps\n if (Object.keys(onceProps).length) page.onceProps = onceProps\n if (ctx.session?.data[FRAGMENT_KEY]) {\n delete ctx.session.data[FRAGMENT_KEY]\n page.preserveFragment = true\n }\n const meta = resolveMeta(rt.meta, options.meta, {\n baseUrl: rt.baseUrl,\n path: page.url,\n status: options.status,\n })\n if (meta) page.meta = meta\n if (options.encryptHistory) page.encryptHistory = true\n if (options.clearHistory) page.clearHistory = true\n return page\n}\n\n/**\n * Render an Inertia page. Return it from a handler:\n *\n * ```ts\n * @Get('/users')\n * async index() {\n * return inertia('Users/Index', { users: await this.users.list() })\n * }\n * ```\n */\nexport function inertia(\n component: string,\n props: Record<string, unknown> = {},\n options?: PageOptions,\n): Respondable {\n return {\n async [RESPOND](ctx: RequestContext) {\n const page = await buildPage(ctx, component, props, options)\n // Remembered for back(): helmet's default Referrer-Policy (no-referrer)\n // means the browser sends no Referer to go back to.\n if (ctx.session) ctx.session.data[PREVIOUS_KEY] = page.url\n // `Vary: X-Inertia` is added by the adapter's middleware, which can\n // append to a Vary another layer set instead of replacing it.\n if (isInertiaRequest(ctx)) {\n ctx.setHeader('X-Inertia', 'true')\n ctx.json(page, options?.status ?? 200)\n return\n }\n ctx.html(await runtime(ctx).renderHtml(page, ctx), options?.status ?? 200)\n },\n }\n}\n\nexport interface RedirectOptions {\n /**\n * Keep the `#fragment` of the URL the request was sent to — a form that\n * posts to `/posts/1/comments#comments` lands on `#comments` of the page\n * this redirects to. Needs `session()`.\n */\n preserveFragment?: boolean\n}\n\n/**\n * Redirect after a form submit. Uses 303 for anything but GET, so the browser\n * follows with a GET, and saves the session first so flashed errors and\n * messages are there when that GET arrives.\n *\n * A URL with a `#fragment` is sent to an Inertia visit as 409 +\n * `X-Inertia-Redirect`: a redirect followed inside a fetch drops the\n * fragment, so the client makes the visit itself.\n */\nexport function redirect(url: string, options: RedirectOptions = {}): Respondable {\n return {\n async [RESPOND](ctx: RequestContext) {\n if (options.preserveFragment && ctx.session) ctx.session.data[FRAGMENT_KEY] = true\n await ctx.session?.save()\n if (url.includes('#') && isInertiaRequest(ctx)) {\n ctx.setHeader('X-Inertia-Redirect', url)\n ctx.html('', 409)\n return\n }\n const method = (ctx.req as { method?: string }).method ?? 'GET'\n ctx.redirect(url, method === 'GET' ? 302 : 303)\n },\n }\n}\n\n/** A path on this site — not `//host` or `/\\\\host`, which browsers treat as another origin. */\nfunction localPath(value: unknown): string | undefined {\n return typeof value === 'string' && /^\\/(?![/\\\\])/.test(value) ? value : undefined\n}\n\n/** The path of a Referer, only when it points at this host. */\nfunction sameOriginPath(referer: string | undefined, host: string | undefined): string | undefined {\n if (!referer || !host) return undefined\n try {\n const url = new URL(referer)\n return url.host === host ? localPath(url.pathname + url.search) : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Where \"back\" is: the last page this session rendered, else a same-origin\n * Referer, else `fallback`. Never another site — a form on another site that\n * posts here must not be able to choose where the user lands.\n */\nexport function previousUrl(\n session: { data: Record<string, unknown> } | undefined,\n headers: { referer?: string | string[]; host?: string | string[] },\n fallback = '/',\n): string {\n const one = (v: string | string[] | undefined) => (Array.isArray(v) ? v[0] : v)\n return (\n localPath(session?.data[PREVIOUS_KEY]) ??\n sameOriginPath(one(headers.referer), one(headers.host)) ??\n fallback\n )\n}\n\n/** Redirect back to the page the request came from. */\nexport function back(ctx: RequestContext, fallback = '/', options?: RedirectOptions): Respondable {\n return redirect(\n previousUrl(\n ctx.session,\n { referer: header(ctx, 'referer'), host: header(ctx, 'host') },\n fallback,\n ),\n options,\n )\n}\n\n/**\n * A full browser visit, outside Inertia — another site, or a page that is not\n * an Inertia page. An Inertia request gets 409 + `X-Inertia-Location`, which\n * the client turns into `window.location`.\n */\nexport function location(url: string): Respondable {\n return {\n async [RESPOND](ctx: RequestContext) {\n if (isInertiaRequest(ctx)) {\n ctx.setHeader('X-Inertia-Location', url)\n ctx.html('', 409)\n return\n }\n ctx.redirect(url)\n },\n }\n}\n\n/** A browser navigation or an Inertia visit — not an API or asset request. */\nexport function isPageRequest(headers: Record<string, string | string[] | undefined>): boolean {\n const accept = String(headers.accept ?? '')\n return headers['x-inertia'] === 'true' || accept.includes('text/html')\n}\n\nconst STATUS_TEXT: Record<number, string> = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Page Not Found',\n 405: 'Method Not Allowed',\n 419: 'Page Expired',\n 429: 'Too Many Requests',\n 500: 'Server Error',\n 503: 'Service Unavailable',\n}\n\n/**\n * The configured error page as a response, with `{ status, message }` as its\n * props. A 5xx message is replaced unless NODE_ENV is development or test —\n * an exception's text is for the log, not the visitor, and a deploy that\n * forgot NODE_ENV must not show it.\n */\nexport function errorPage(component: string, status: number, error?: unknown): Respondable {\n const fallback = STATUS_TEXT[status] ?? (status >= 500 ? 'Server Error' : 'Error')\n const raw = error instanceof Error && error.message ? error.message : fallback\n const dev = process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test'\n const message = status >= 500 && !dev ? fallback : raw\n // Not for search results: no canonical, and `noindex`.\n return inertia(\n component,\n { status, message },\n { status, meta: { title: fallback, robots: 'noindex' } },\n )\n}\n","/**\n * The HTML shell for a first visit, and the script tags that load the client:\n * Vite's dev server while `kick dev` runs, the build manifest in production.\n *\n * @module @forinda/kickjs-inertia/html\n */\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { Page } from './inertia'\n\nexport interface HtmlParts {\n /** Script and style tags for the client entry. Put inside `<head>`. */\n head: string\n /** The page data and the mount element. Put inside `<body>`. */\n body: string\n page: Page\n}\n\nexport type HtmlTemplate = (parts: HtmlParts) => string\n\nconst escapeHtml = (value: string): string =>\n value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"')\n\n/**\n * The default shell. Its `<title>` is a fallback: left out when the head\n * already has one (a server-rendered `<Head>`). In the browser, Inertia drops\n * it itself once a page's `<Head>` sets a title.\n */\nexport const defaultTemplate =\n (title: string): HtmlTemplate =>\n ({ head, body }) =>\n `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n ${/<title[\\s>]/i.test(head) ? '' : `<title>${escapeHtml(title)}</title>`}\n ${head}\n </head>\n <body>\n ${body}\n </body>\n</html>`\n\n/**\n * The page as `<script data-page=\"app\" type=\"application/json\">` — where the\n * v3 client reads it — followed by the mount element. `<` and `/` are escaped\n * so a prop containing `</script>` cannot end the tag.\n */\nexport function pageBody(page: Page, id = 'app'): string {\n const json = JSON.stringify(page, (_k, v) => (typeof v === 'bigint' ? v.toString() : v))\n .replace(/</g, '\\\\u003c')\n .replace(/\\//g, '\\\\/')\n return `<script data-page=\"${id}\" type=\"application/json\">${json}</script>\\n <div id=\"${id}\"></div>`\n}\n\n/** Dev: one module script; Vite's `transformIndexHtml` adds its client and plugin preambles. */\nexport function devHead(entry: string): string {\n return `<script type=\"module\" src=\"/${entry.replace(/^\\/+/, '')}\"></script>`\n}\n\ninterface ManifestChunk {\n file: string\n css?: string[]\n imports?: string[]\n}\n\n/** Production: the entry's script, its CSS, and the CSS and preloads of what it imports. */\nexport function manifestHead(clientDir: string, entry: string): string {\n const manifest = JSON.parse(\n readFileSync(join(clientDir, '.vite', 'manifest.json'), 'utf8'),\n ) as Record<string, ManifestChunk>\n const chunk = manifest[entry]\n if (!chunk) {\n throw new Error(\n `InertiaAdapter: '${entry}' is not in ${clientDir}/.vite/manifest.json — build the client with build.manifest and this entry as an input.`,\n )\n }\n const css = new Set<string>()\n const preload = new Set<string>()\n const walk = (key: string, root: boolean) => {\n const c = manifest[key]\n if (!c) return\n for (const f of c.css ?? []) css.add(f)\n if (!root) preload.add(c.file)\n for (const i of c.imports ?? []) walk(i, false)\n }\n walk(entry, true)\n return [\n ...[...css].map((f) => `<link rel=\"stylesheet\" href=\"/${f}\" />`),\n ...[...preload].map((f) => `<link rel=\"modulepreload\" href=\"/${f}\" />`),\n `<script type=\"module\" src=\"/${chunk.file}\"></script>`,\n ].join('\\n ')\n}\n","/**\n * `InertiaAdapter` — wires the protocol into the app:\n *\n * - makes `inertia()` able to render (HTML shell, asset tags, version);\n * - answers a stale Inertia GET with 409 so the client reloads the page;\n * - turns a 302 after PUT / PATCH / DELETE into 303, so the browser follows\n * with a GET instead of repeating the method;\n * - in production, serves the built client's `assets/`.\n *\n * @module @forinda/kickjs-inertia/adapter\n */\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync, readdirSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { defineAdapter, Logger, type RequestContext } from '@forinda/kickjs'\nimport { bindInertiaRuntime, requestUrl, type InertiaRuntime, type Page } from './inertia'\nimport { defaultTemplate, devHead, manifestHead, pageBody, type HtmlTemplate } from './html'\nimport { dedupeHead, metaTags, type MetaDefaults } from './seo'\n\nexport interface InertiaAdapterOptions {\n /**\n * The client entry, relative to the project root — the file that calls\n * `createInertiaApp`. Served by Vite in dev, looked up in the build\n * manifest in production. Default: `'src/client/main.tsx'`.\n */\n entry?: string\n /**\n * Where `vite build` wrote the client, with `build.manifest: true`. Default: `'dist/client'`.\n * Under NODE_ENV development or test a missing build is not an error: pages render without\n * asset tags (a warning says so), so tests run before the client is built.\n */\n clientDir?: string\n /**\n * Asset version. A client on another version reloads the page on its next\n * visit. Default: a hash of the build manifest in production, none in dev\n * (Vite reloads changed modules itself) or without a build. A test that\n * sends `X-Inertia` requests pins it (`version: 'test'`) and sends the same\n * value as `X-Inertia-Version`, so a built client doesn't turn them into 409s.\n */\n version?: string | (() => string)\n /** Props every page gets — the current user, app name. */\n share?: (ctx: RequestContext) => Record<string, unknown> | Promise<Record<string, unknown>>\n /**\n * `<title>` of the default HTML shell, until a page sets its own with\n * Inertia's `<Head>`. Default: `'KickJS'`.\n */\n title?: string\n /**\n * Tags added to every page's `<head>` — a favicon, fonts. Titles and meta\n * tags: `meta` here and per page, or Inertia's `<Head>` in the page.\n */\n head?: string\n /**\n * Meta every page starts from, under the `meta` a handler passes to\n * `inertia()`: `{ titleTemplate: '%s · My App', description, og: { image } }`.\n */\n meta?: MetaDefaults\n /**\n * The site's public URL, e.g. `getEnv('APP_URL')`. Canonical URLs and\n * meta image paths are made absolute with it, and a page without a\n * `canonical` gets this + its path. Never taken from the request's Host\n * header, which the client chooses.\n */\n baseUrl?: string\n /** Replace the HTML shell entirely. */\n template?: HtmlTemplate\n /**\n * Page component for errors and unknown URLs, e.g. `'Error'`. It receives\n * `{ status, message }`. Rendered for page requests by `inertiaErrorHandler()`\n * (thrown errors) and `inertiaNotFound()` (unknown URLs); API and asset\n * requests keep the usual JSON answers.\n */\n errorPage?: string\n /**\n * Render pages on the server. `entry` is a module whose default export is\n * `(page) => Promise<{ head: string[]; body: string }>` — what\n * `createInertiaApp({ page, render: renderToString, ... })` returns. Loaded\n * through Vite in dev; in production from `bundle`, the output of\n * `vite build --ssr <entry>` (default `'dist/ssr/ssr.js'`). A render that\n * throws falls back to client rendering for that request.\n */\n ssr?: { entry: string; bundle?: string }\n}\n\n/** What an SSR entry's default export returns. */\nexport interface SsrResult {\n head: string[]\n body: string\n}\n\ntype SsrRender = (page: Page) => Promise<SsrResult>\n\n/** The options with their defaults applied. */\ntype ResolvedOptions = InertiaAdapterOptions &\n Required<Pick<InertiaAdapterOptions, 'entry' | 'clientDir' | 'title'>>\n\nlet warnedNoBuild = false\n\nconst log = Logger.for('InertiaAdapter')\n\ninterface ViteModuleLike {\n url: string\n id: string | null\n importedModules: Set<ViteModuleLike>\n}\n\ninterface ViteDevServerLike {\n config: { root: string }\n environments: { ssr: { moduleGraph: { getModuleById(id: string): ViteModuleLike | undefined } } }\n transformIndexHtml(url: string, html: string): Promise<string>\n ssrLoadModule(url: string): Promise<Record<string, unknown>>\n ssrFixStacktrace(err: Error): void\n}\n\nconst CSS_REQUEST = /\\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\\?)/\n\n/**\n * Dev only: the stylesheets the SSR entry imports, as `<link>` tags. In dev\n * Vite injects CSS from JavaScript, so server-rendered HTML would show\n * unstyled until the scripts run. `data-vite-dev-id` lets Vite's client\n * recognize these and not inject the same styles again.\n */\nfunction devStylesheets(vite: ViteDevServerLike, entry: string): string[] {\n const root = vite.environments.ssr.moduleGraph.getModuleById(resolve(vite.config.root, entry))\n if (!root) return []\n const links: string[] = []\n const seen = new Set<ViteModuleLike>()\n const walk = (mod: ViteModuleLike) => {\n if (seen.has(mod)) return\n seen.add(mod)\n if (CSS_REQUEST.test(mod.url)) {\n const devId = mod.id ? ` data-vite-dev-id=\"${mod.id.replace(/\"/g, '"')}\"` : ''\n links.push(`<link rel=\"stylesheet\" href=\"${mod.url}\"${devId} />`)\n return\n }\n for (const imported of mod.importedModules) walk(imported)\n }\n walk(root)\n return links\n}\n\nfunction viteServer(): ViteDevServerLike | null {\n return (\n (globalThis as { __kickjs_viteServer?: ViteDevServerLike | null }).__kickjs_viteServer ?? null\n )\n}\n\n/**\n * A build path, relative to the app: the working directory, or\n * `KICK_APP_ROOT` when set — the Netlify and Vercel functions `kick build:*`\n * writes set it to where they packaged the build, since the platform starts\n * them elsewhere.\n */\nfunction fromAppRoot(path: string): string {\n return resolve(process.env.KICK_APP_ROOT ?? process.cwd(), path)\n}\n\nfunction appendVary(res: ServerResponse, field: string): void {\n const current = res.getHeader('Vary')\n const list = (Array.isArray(current) ? current.join(',') : String(current ?? ''))\n .split(',')\n .map((v) => v.trim())\n .filter(Boolean)\n if (list.includes('*') || list.some((v) => v.toLowerCase() === field.toLowerCase())) return\n res.setHeader('Vary', [...list, field].join(', '))\n}\n\nfunction safeDecode(path: string): string {\n try {\n return decodeURIComponent(path)\n } catch {\n return path\n }\n}\n\ntype NodeMiddleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => void\n\nexport const InertiaAdapter = defineAdapter<ResolvedOptions>({\n name: 'InertiaAdapter',\n defaults: {\n entry: 'src/client/main.tsx',\n clientDir: 'dist/client',\n title: 'KickJS',\n },\n build: (config) => {\n const clientDir = fromAppRoot(config.clientDir)\n const template = config.template ?? defaultTemplate(config.title)\n if (config.baseUrl !== undefined && !/^https?:\\/\\/[^/]/.test(config.baseUrl)) {\n throw new Error(\n `InertiaAdapter: baseUrl must be an absolute http(s) URL, got '${config.baseUrl}'.`,\n )\n }\n let version: () => string | null = () => null\n\n // Built in beforeMount, once the dev server / build is known.\n let runtime: InertiaRuntime | null = null\n\n const protocol: NodeMiddleware = (req, res, next) => {\n if (runtime) bindInertiaRuntime(req, runtime)\n // The same URL answers HTML or JSON depending on X-Inertia, so a shared\n // cache must key on it. Appended, not set: replacing a Vary another\n // layer added (Origin, Accept-Encoding) lets a cache serve one\n // client's variant to another.\n appendVary(res, 'X-Inertia')\n // A Precognition request gets a validation answer instead of the\n // route's response.\n if (req.headers.precognition === 'true') appendVary(res, 'Precognition')\n if (req.headers['x-inertia'] !== 'true') return next()\n\n const current = version()\n if (req.method === 'GET' && current && req.headers['x-inertia-version'] !== current) {\n res.statusCode = 409\n res.setHeader('X-Inertia-Location', requestUrl(req))\n res.end()\n return\n }\n\n if (req.method === 'PUT' || req.method === 'PATCH' || req.method === 'DELETE') {\n // Node sends every status through writeHead — also the implicit one\n // behind res.end() — so this catches a 302 from any code path.\n const writeHead = res.writeHead\n res.writeHead = function (this: ServerResponse, status: number, ...rest: unknown[]) {\n return (writeHead as (...a: unknown[]) => ServerResponse).call(\n this,\n status === 302 ? 303 : status,\n ...rest,\n )\n } as typeof res.writeHead\n }\n next()\n }\n\n return {\n beforeMount({ http }) {\n const vite = viteServer()\n let head: (page: Page) => string\n\n const manifest = join(clientDir, '.vite', 'manifest.json')\n if (vite) {\n head = () => devHead(config.entry)\n } else if (\n // Only where a missing build is expected. Production and an unset\n // NODE_ENV (a deploy that forgot it) fail at startup instead of\n // serving pages without their scripts.\n ['development', 'test'].includes(process.env.NODE_ENV ?? '') &&\n !existsSync(manifest)\n ) {\n // Tests and a fresh clone: pages render (as JSON or a shell without\n // scripts), there is no asset version, and nothing to serve.\n head = () => ''\n if (!warnedNoBuild) {\n warnedNoBuild = true\n log.warn(\n `No client build at ${manifest} — pages render without their scripts. Build the client, or run kick dev.`,\n )\n }\n } else {\n const tags = manifestHead(clientDir, config.entry)\n head = () => tags\n const hash = createHash('sha1').update(readFileSync(manifest)).digest('hex').slice(0, 12)\n version = () => hash\n // The whole build: hashed `assets/` plus what Vite copied from\n // `public/` — favicon, robots.txt, a static sitemap.\n if (existsSync(join(clientDir, 'package.json'))) {\n throw new Error(\n `InertiaAdapter: clientDir ${clientDir} looks like a project root — it must be the client build output (default dist/client), which is served as-is.`,\n )\n }\n // Not every engine's static handler skips dotfiles, so the build's\n // own (`.vite/manifest.json`) are refused here, before it runs.\n const hidden = new Set(readdirSync(clientDir).filter((name) => name.startsWith('.')))\n const hideBuildFiles: NodeMiddleware = (req, res, next) => {\n const first = safeDecode((req.url ?? '/').split('?')[0]!)\n .split('/')\n .find(Boolean)\n if (first && hidden.has(first)) {\n res.statusCode = 404\n res.end()\n return\n }\n next()\n }\n http.use(hideBuildFiles as never)\n http.serveStatic('/', clientDir)\n }\n if (config.version !== undefined) {\n const v = config.version\n version = typeof v === 'function' ? v : () => v\n }\n\n const ssr = config.ssr\n let prodRender: Promise<SsrRender> | undefined\n const loadRender = async (): Promise<SsrRender> => {\n if (vite) {\n // Every request in dev, so an edited page renders fresh.\n const mod = await vite.ssrLoadModule(`/${ssr!.entry.replace(/^\\/+/, '')}`)\n return mod.default as SsrRender\n }\n const url = pathToFileURL(fromAppRoot(ssr!.bundle ?? 'dist/ssr/ssr.js')).href\n // The app's own build output, chosen at runtime — nothing for Vite to analyze.\n prodRender ??= import(/* @vite-ignore */ url).then((mod) => mod.default as SsrRender)\n return prodRender\n }\n const render = async (page: Page): Promise<SsrResult | null> => {\n if (!ssr) return null\n try {\n return await (\n await loadRender()\n )(page)\n } catch (err) {\n if (vite && err instanceof Error) vite.ssrFixStacktrace(err)\n log.error(err, `SSR failed for ${page.component} — sending it client-rendered`)\n return null\n }\n }\n\n runtime = {\n version: () => version(),\n share: config.share,\n errorPage: config.errorPage,\n meta: config.meta,\n baseUrl: config.baseUrl,\n async renderHtml(page, ctx) {\n const rendered = await render(page)\n const styles = vite && rendered && ssr ? devStylesheets(vite, ssr.entry) : []\n const ssrHead = rendered?.head ?? []\n // A tag the server-rendered <Head> set wins over the same one from meta.\n const meta = dedupeHead(metaTags(page.meta), ssrHead)\n const html = template({\n head: [config.head ?? '', head(page), ...styles, ...meta, ...ssrHead]\n .filter(Boolean)\n .join('\\n '),\n body: rendered?.body ?? pageBody(page),\n page,\n })\n return vite ? vite.transformIndexHtml(requestUrl(ctx.req), html) : html\n },\n }\n },\n\n middleware() {\n return [{ handler: protocol as never, phase: 'afterGlobal' as const }]\n },\n }\n },\n})\n","/**\n * Validation errors the Inertia way: on an Inertia request, a 422 from route\n * validation becomes a redirect back with the errors in the session, and the\n * next page gets them as `props.errors`. Everything else goes to the usual\n * error handler.\n *\n * @module @forinda/kickjs-inertia/errors\n */\nimport {\n errorHandler,\n HttpException,\n Logger,\n RequestContext,\n RESPOND,\n type MiddlewareHandler,\n type RuntimeResponse,\n} from '@forinda/kickjs'\nimport { ERRORS_KEY, errorPage, inertiaRuntimeFor, isPageRequest, previousUrl } from './inertia'\n\nconst log = Logger.for('Inertia')\n\ntype ErrorHandler = (\n err: any,\n req: any,\n res: RuntimeResponse,\n next: (err?: unknown) => void,\n) => unknown\n\ninterface SessionLike {\n data: Record<string, unknown>\n save(): Promise<void>\n}\n\n/** `[{ field, message }]` from route validation → `{ field: firstMessage }`. */\nfunction toErrors(details: unknown): Record<string, string> | null {\n if (!Array.isArray(details)) return null\n const errors: Record<string, string> = {}\n for (const d of details as Array<{ field?: string; message?: string }>) {\n const field = d.field || 'form'\n errors[field] ??= d.message ?? 'Invalid value'\n }\n return errors\n}\n\nfunction isPrecognitive(req: any): boolean {\n return req?.headers?.precognition === 'true'\n}\n\n/**\n * A Precognition answer: 204 when nothing the client asked about failed,\n * else 422 with those fields' errors. `Precognition-Validate-Only` names the\n * fields a form has touched, so errors on the rest are not shown yet.\n */\nfunction precognitionResult(req: any, res: RuntimeResponse, errors: Record<string, string>) {\n const only = String(req.headers['precognition-validate-only'] ?? '')\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n const shown = only.length\n ? Object.fromEntries(\n Object.entries(errors).filter(([field]) =>\n only.some((o) => field === o || field.startsWith(`${o}.`)),\n ),\n )\n : errors\n res.setHeader('Precognition', 'true')\n if (Object.keys(shown).length === 0) {\n res.setHeader('Precognition-Success', 'true')\n res.status(204).end()\n return\n }\n res.status(422).json({ message: 'The given data was invalid.', errors: shown })\n}\n\n/**\n * Live validation for Inertia's `useForm().validate()` — Laravel Precognition.\n * Put it on a route that validates its body; a precognitive request runs the\n * validation and stops before the handler:\n *\n * ```ts\n * @Post('/users', { body: createUserSchema })\n * @Middleware(precognitive)\n * create(ctx: RequestContext) { ... }\n * ```\n *\n * A failed check is answered by `inertiaErrorHandler()`.\n */\nexport const precognitive: MiddlewareHandler<RequestContext> = (ctx, next) => {\n if (!isPrecognitive(ctx.req)) return next()\n ctx.setHeader('Precognition', 'true')\n ctx.setHeader('Precognition-Success', 'true')\n ctx.noContent()\n}\n\n/**\n * Pass to `bootstrap({ onError: inertiaErrorHandler() })`.\n *\n * - A validation 422 on a Precognition request is answered with the errors\n * of the fields it asked about (see `precognitive`).\n * - A validation 422 on an Inertia visit goes back to the form with the\n * errors (needs the `session()` middleware to carry them).\n * - Any other error on a page request renders the adapter's `errorPage`,\n * when one is configured.\n * - Everything else — API calls, assets — goes to `fallback`.\n */\nexport function inertiaErrorHandler(fallback: ErrorHandler = errorHandler()): ErrorHandler {\n let warned = false\n return (err, req, res, next) => {\n if (res.headersSent) return fallback(err, req, res, next)\n\n const errors = err instanceof HttpException && err.status === 422 ? toErrors(err.details) : null\n if (errors && isPrecognitive(req)) return precognitionResult(req, res, errors)\n if (errors && req?.headers?.['x-inertia'] === 'true') {\n const session = req.session as SessionLike | undefined\n if (session) {\n const bag = req.headers['x-inertia-error-bag'] as string | undefined\n session.data[ERRORS_KEY] = bag ? { [bag]: errors } : errors\n // Returned, so an engine that waits on async handlers waits on this.\n return session\n .save()\n .then(() => {\n res.status(303).setHeader('location', previousUrl(session, req.headers))\n res.end()\n })\n .catch((saveErr) => fallback(saveErr, req, res, next))\n }\n if (!warned) {\n log.warn(\n 'Validation failed on an Inertia request, but there is no session() middleware to carry the errors — answering 422 instead.',\n )\n warned = true\n }\n return fallback(err, req, res, next)\n }\n\n const component = inertiaRuntimeFor(req)?.errorPage\n if (component && req?.headers && isPageRequest(req.headers)) {\n const status = err instanceof HttpException ? err.status : 500\n if (status >= 500) log.error(err, 'Unhandled error on a page request')\n const ctx = new RequestContext(req, res as never, next, res)\n return Promise.resolve(errorPage(component, status, err)[RESPOND](ctx)).catch((renderErr) =>\n fallback(renderErr, req, res, next),\n )\n }\n return fallback(err, req, res, next)\n }\n}\n\ntype NotFoundHandler = (\n req: any,\n res: RuntimeResponse,\n next: (err?: unknown) => void,\n) => void | Promise<void>\n\n/**\n * Pass to `bootstrap({ onNotFound: inertiaNotFound() })`. A browser or Inertia\n * request for an unknown URL gets the adapter's `errorPage` with 404; anything\n * else — API calls, other methods — goes on to the built-in 404 / 405.\n */\nexport function inertiaNotFound(): NotFoundHandler {\n return (req, res, next) => {\n const component = inertiaRuntimeFor(req)?.errorPage\n const method = req?.method ?? 'GET'\n if (\n !component ||\n (method !== 'GET' && method !== 'HEAD') ||\n !isPageRequest(req.headers ?? {})\n ) {\n return next()\n }\n const ctx = new RequestContext(req, res as never, next, res)\n return Promise.resolve(errorPage(component, 404)[RESPOND](ctx)).catch(next)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAUA,MAAM,OAAO,OAAO,IAAI,qBAAqB;AA8B7C,SAAS,KAAQ,MAAgB,OAAoB,OAAgC;CACnF,OAAO;GAAG,OAAO;EAAM;EAAO,GAAG;CAAM;AACzC;;AAGA,SAAgB,SAAY,OAA6C;CACvE,OAAO,KAAK,YAAY,KAAK;AAC/B;;AAGA,SAAgB,OAAU,OAAoC;CAC5D,OAAO,KAAK,UAAU,KAAK;AAC7B;;;;;AAMA,SAAgB,MAAS,OAA6B,QAAQ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A,SAAS;GACX;GACA,OAAO,SAAS,KAAK,KAAK,KAAK,IAAI;EACrC;EAEA,MAAM,YAAY,kBAAkB,GAAG,CAAC,EAAE;EAC1C,IAAI,aAAa,KAAK,WAAW,cAAc,IAAI,OAAO,GAAG;GAC3D,MAAM,SAAS,eAAe,gBAAgB,IAAI,SAAS;GAC3D,IAAI,UAAU,KAAK,IAAI,MAAM,KAAK,mCAAmC;GACrE,MAAM,MAAM,IAAI,eAAe,KAAK,KAAc,MAAM,GAAG;GAC3D,OAAO,QAAQ,QAAQ,UAAU,WAAW,QAAQ,GAAG,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,cAC7E,SAAS,WAAW,KAAK,KAAK,IAAI,CACpC;EACF;EACA,OAAO,SAAS,KAAK,KAAK,KAAK,IAAI;CACrC;AACF;;;;;;AAaA,SAAgB,kBAAmC;CACjD,QAAQ,KAAK,KAAK,SAAS;EACzB,MAAM,YAAY,kBAAkB,GAAG,CAAC,EAAE;EAC1C,MAAM,SAAS,KAAK,UAAU;EAC9B,IACE,CAAC,aACA,WAAW,SAAS,WAAW,UAChC,CAAC,cAAc,IAAI,WAAW,CAAC,CAAC,GAEhC,OAAO,KAAK;EAEd,MAAM,MAAM,IAAI,eAAe,KAAK,KAAc,MAAM,GAAG;EAC3D,OAAO,QAAQ,QAAQ,UAAU,WAAW,GAAG,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,IAAI;CAC5E;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@forinda/kickjs-inertia",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Inertia.js adapter for KickJS — server-driven pages rendered by React, Vue or Svelte",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"kickjs",
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"supertest": "^7.3.1",
|
|
36
36
|
"typescript": "^7.0.2",
|
|
37
37
|
"vitest": "^5.0.3",
|
|
38
|
-
"@forinda/kickjs": "10.
|
|
38
|
+
"@forinda/kickjs": "10.4.0"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
41
|
"@forinda/kickjs": ">=10.0.0"
|