@forinda/kickjs-inertia 0.2.0 → 0.4.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 CHANGED
@@ -75,6 +75,89 @@ 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 `<meta>` or `<link>` for the page's `<head>`, built with {@link h}. */
80
+ interface HeadTag {
81
+ tag: 'meta' | 'link';
82
+ attrs: Record<string, string>;
83
+ /** A later tag with the same key replaces it — a page's over the defaults'. */
84
+ key: string;
85
+ }
86
+ /** A page's title, description and social tags. Every value is escaped on output. */
87
+ interface PageMeta {
88
+ title?: string;
89
+ /** `<html lang>` of the first visit; the template's `Seo` keeps it in sync on later ones. */
90
+ lang?: string;
91
+ description?: string;
92
+ /** A path (`'/posts/1'`, made absolute with `baseUrl`) or a full URL. */
93
+ canonical?: string;
94
+ /** E.g. `'noindex, nofollow'`. */
95
+ robots?: string;
96
+ /** Open Graph, without the `og:` prefix: `{ type: 'article', image: '/cover.png' }`. */
97
+ og?: Record<string, string>;
98
+ /** Twitter cards, without the `twitter:` prefix: `{ card: 'summary_large_image' }`. */
99
+ twitter?: Record<string, string>;
100
+ /** Structured data, rendered as `<script type="application/ld+json">`. */
101
+ jsonLd?: Record<string, unknown> | Record<string, unknown>[];
102
+ /** Any other `<meta>` / `<link>` — hreflang alternates, theme-color, preloads. See {@link h}. */
103
+ head?: HeadTag[];
104
+ }
105
+ /** Adapter-wide meta, under each page's. */
106
+ interface MetaDefaults extends PageMeta {
107
+ /** Wraps a page's title: `'%s · My App'`. Not applied to the default `title`. */
108
+ titleTemplate?: string;
109
+ }
110
+ /**
111
+ * A head tag for `meta.head`, like Vue's `h()`:
112
+ *
113
+ * ```ts
114
+ * meta: {
115
+ * head: [
116
+ * h('link', { rel: 'alternate', hreflang: 'fr', href: '/fr/posts/1' }),
117
+ * h('meta', { name: 'theme-color', content: '#0f172a' }),
118
+ * ],
119
+ * }
120
+ * ```
121
+ *
122
+ * Only `meta` and `link`, and no `on*` attributes — values are escaped, but a
123
+ * handler is still script. A `meta` needs a `name`, `property` or
124
+ * `http-equiv`, a `link` a `rel`: that is what a later tag replaces it by.
125
+ */
126
+ export declare function h(tag: 'meta' | 'link', attrs: Record<string, string>): HeadTag;
127
+ interface SitemapEntry {
128
+ /** A full URL, or a path made absolute with `baseUrl`. */
129
+ loc: string;
130
+ /** A `Date`, or a W3C date string (`'2026-10-16'`). */
131
+ lastmod?: Date | string;
132
+ changefreq?: 'always' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'never';
133
+ /** 0.0 – 1.0. */
134
+ priority?: number;
135
+ }
136
+ /**
137
+ * Answer `/sitemap.xml`. Return it from a handler:
138
+ *
139
+ * ```ts
140
+ * @Get('/sitemap.xml')
141
+ * sitemap() {
142
+ * return sitemap([{ loc: '/' }, { loc: '/posts', changefreq: 'daily' }], { baseUrl: getEnv('APP_URL') })
143
+ * }
144
+ * ```
145
+ */
146
+ export declare function sitemap(entries: Iterable<SitemapEntry>, options?: {
147
+ baseUrl?: string;
148
+ }): Respondable;
149
+ interface RobotsOptions {
150
+ /** Default `'*'`. */
151
+ userAgent?: string;
152
+ allow?: string[];
153
+ disallow?: string[];
154
+ /** Sitemap URL(s) — a path is made absolute with `baseUrl`. */
155
+ sitemap?: string | string[];
156
+ baseUrl?: string;
157
+ }
158
+ /** Answer `/robots.txt`. */
159
+ export declare function robots(options?: RobotsOptions): Respondable;
160
+ //#endregion
78
161
  //#region src/inertia.d.ts
79
162
  /** The page object the Inertia client renders — see the protocol docs. */
80
163
  interface Page {
@@ -102,6 +185,8 @@ interface Page {
102
185
  encryptHistory?: boolean;
103
186
  clearHistory?: boolean;
104
187
  preserveFragment?: boolean;
188
+ /** Title, description and social tags — see `PageOptions.meta`. */
189
+ meta?: PageMeta;
105
190
  }
106
191
  interface PageOptions {
107
192
  /** Encrypt this page's history entry in the browser. */
@@ -110,6 +195,13 @@ interface PageOptions {
110
195
  clearHistory?: boolean;
111
196
  /** Response status. Default 200; error pages send theirs (404, 500). */
112
197
  status?: number;
198
+ /**
199
+ * Title, description, canonical URL and social tags, under the adapter's
200
+ * `meta` defaults. Rendered into the first-visit HTML and sent as the
201
+ * page's `meta` on every visit, for a `<Head>` in the client to keep the
202
+ * browser's head in sync. A server-rendered `<Head>` tag wins over the same tag here.
203
+ */
204
+ meta?: PageMeta;
113
205
  }
114
206
  export declare function isInertiaRequest(ctx: RequestContext): boolean;
115
207
  /** Flash data for the next page, sent as the page's top-level `flash`. */
@@ -156,8 +248,9 @@ export declare function location(url: string): Respondable;
156
248
  export declare function isPageRequest(headers: Record<string, string | string[] | undefined>): boolean;
157
249
  /**
158
250
  * The configured error page as a response, with `{ status, message }` as its
159
- * props. A 5xx message is replaced in production — an exception's text is
160
- * for the log, not the visitor.
251
+ * props. A 5xx message is replaced unless NODE_ENV is development or test —
252
+ * an exception's text is for the log, not the visitor, and a deploy that
253
+ * forgot NODE_ENV must not show it.
161
254
  */
162
255
  export declare function errorPage(component: string, status: number, error?: unknown): Respondable;
163
256
  //#endregion
@@ -170,6 +263,12 @@ interface HtmlParts {
170
263
  page: Page;
171
264
  }
172
265
  type HtmlTemplate = (parts: HtmlParts) => string;
266
+ /**
267
+ * The default shell. Its `<title>` is a fallback: left out when the head
268
+ * already has one (a server-rendered `<Head>`). In the browser, Inertia drops
269
+ * it itself once a page's `<Head>` sets a title. `<html lang>` is the page's
270
+ * `meta.lang`, else `'en'`.
271
+ */
173
272
  export declare const defaultTemplate: (title: string) => HtmlTemplate;
174
273
  /**
175
274
  * The page as `<script data-page="app" type="application/json">` — where the
@@ -185,24 +284,45 @@ interface InertiaAdapterOptions {
185
284
  * `createInertiaApp`. Served by Vite in dev, looked up in the build
186
285
  * manifest in production. Default: `'src/client/main.tsx'`.
187
286
  */
188
- entry: string;
189
- /** Where `vite build` wrote the client, with `build.manifest: true`. Default: `'dist/client'`. */
190
- clientDir: string;
287
+ entry?: string;
288
+ /**
289
+ * Where `vite build` wrote the client, with `build.manifest: true`. Default: `'dist/client'`.
290
+ * Under NODE_ENV development or test a missing build is not an error: pages render without
291
+ * asset tags (a warning says so), so tests run before the client is built.
292
+ */
293
+ clientDir?: string;
191
294
  /**
192
295
  * Asset version. A client on another version reloads the page on its next
193
296
  * visit. Default: a hash of the build manifest in production, none in dev
194
- * (Vite reloads changed modules itself).
297
+ * (Vite reloads changed modules itself) or without a build. A test that
298
+ * sends `X-Inertia` requests pins it (`version: 'test'`) and sends the same
299
+ * value as `X-Inertia-Version`, so a built client doesn't turn them into 409s.
195
300
  */
196
301
  version?: string | (() => string);
197
302
  /** Props every page gets — the current user, app name. */
198
303
  share?: (ctx: RequestContext) => Record<string, unknown> | Promise<Record<string, unknown>>;
199
- /** `<title>` of the default HTML shell. */
200
- title: string;
201
304
  /**
202
- * Tags added to every page's `<head>` — a favicon, meta tags, fonts. Per-page
203
- * titles and meta belong in the page, with Inertia's `<Head>` component.
305
+ * `<title>` of the default HTML shell, until a page sets its own with
306
+ * Inertia's `<Head>`. Default: `'KickJS'`.
307
+ */
308
+ title?: string;
309
+ /**
310
+ * Tags added to every page's `<head>` — a favicon, fonts. Titles and meta
311
+ * tags: `meta` here and per page, or Inertia's `<Head>` in the page.
204
312
  */
205
313
  head?: string;
314
+ /**
315
+ * Meta every page starts from, under the `meta` a handler passes to
316
+ * `inertia()`: `{ titleTemplate: '%s · My App', description, og: { image } }`.
317
+ */
318
+ meta?: MetaDefaults;
319
+ /**
320
+ * The site's public URL, e.g. `getEnv('APP_URL')`. Canonical URLs and
321
+ * meta image paths are made absolute with it, and a page without a
322
+ * `canonical` gets this + its path. Never taken from the request's Host
323
+ * header, which the client chooses.
324
+ */
325
+ baseUrl?: string;
206
326
  /** Replace the HTML shell entirely. */
207
327
  template?: HtmlTemplate;
208
328
  /**
@@ -230,7 +350,9 @@ interface SsrResult {
230
350
  head: string[];
231
351
  body: string;
232
352
  }
233
- export declare const InertiaAdapter: import("@forinda/kickjs").AdapterFactory<InertiaAdapterOptions, unknown>;
353
+ /** The options with their defaults applied. */
354
+ type ResolvedOptions = InertiaAdapterOptions & Required<Pick<InertiaAdapterOptions, 'entry' | 'clientDir' | 'title'>>;
355
+ export declare const InertiaAdapter: import("@forinda/kickjs").AdapterFactory<ResolvedOptions, unknown>;
234
356
  //#endregion
235
357
  //#region src/errors.d.ts
236
358
  type ErrorHandler = (err: any, req: any, res: RuntimeResponse, next: (err?: unknown) => void) => unknown;
@@ -268,5 +390,5 @@ type NotFoundHandler = (req: any, res: RuntimeResponse, next: (err?: unknown) =>
268
390
  */
269
391
  export declare function inertiaNotFound(): NotFoundHandler;
270
392
  //#endregion
271
- export type { HtmlParts, HtmlTemplate, InertiaAdapterOptions, InertiaProp, Page, PageOptions, RedirectOptions, ScrollMeta, SsrResult };
393
+ export type { HeadTag, HtmlParts, HtmlTemplate, InertiaAdapterOptions, InertiaProp, MetaDefaults, Page, PageMeta, PageOptions, RedirectOptions, RobotsOptions, ScrollMeta, SitemapEntry, SsrResult };
272
394
  //# sourceMappingURL=index.d.mts.map
@@ -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,MAA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AoB,WAAU,eAAgC;KA2CzE,mBACH,UACA,KAAK,iBACL,OAAO,kCACG;;;;;;wBAOI,mBAAmB"}
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,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;;;;UC5FE;EACf;EACA,OAAO;;EAEP;;;UAIe;EACf;;EAEA;EACA;;EAEA;;EAEA;;EAEA,KAAK;;EAEL,UAAU;;EAEV,SAAS,0BAA0B;;EAEnC,OAAO;;;UAIQ,qBAAqB;;EAEpC;;;;;;;;;;;;;;;;;;wBA6Cc,EAAE,sBAAsB,OAAO,yBAAyB;UAwJvD;;EAEf;;EAEA,UAAU;EACV;;EAEA;;;;;;;;;;;;wBAmCc,QACd,SAAS,SAAS,eAClB;EAAW;IACV;UASc;;EAEf;EACA;EACA;;EAEA;EACA;;;wBAiBc,OAAO,UAAS,gBAAqB;;;;UCxSpC;EACf;EACA,OAAO;IAA4B,QAAQ;;EAC3C;EACA;EACA,OAAO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2.0
2
+ * @forinda/kickjs-inertia v0.4.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -96,6 +96,212 @@ 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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
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
+ /** What a `meta` / `link` sets, from its attributes — two tags with the same key are duplicates. */
115
+ function headKey(tag, attr) {
116
+ if (tag === "meta") {
117
+ const key = attr("name") ?? attr("property") ?? attr("http-equiv");
118
+ return key ? `meta:${key.toLowerCase()}` : null;
119
+ }
120
+ if (tag === "link") {
121
+ const rel = attr("rel")?.toLowerCase();
122
+ if (!rel) return null;
123
+ if (rel === "canonical") return "canonical";
124
+ return `link:${rel}:${(attr("hreflang") ?? attr("href") ?? "").toLowerCase()}`;
125
+ }
126
+ return null;
127
+ }
128
+ const ATTR_NAME = /^[a-z][a-z0-9:-]*$/i;
129
+ /**
130
+ * A head tag for `meta.head`, like Vue's `h()`:
131
+ *
132
+ * ```ts
133
+ * meta: {
134
+ * head: [
135
+ * h('link', { rel: 'alternate', hreflang: 'fr', href: '/fr/posts/1' }),
136
+ * h('meta', { name: 'theme-color', content: '#0f172a' }),
137
+ * ],
138
+ * }
139
+ * ```
140
+ *
141
+ * Only `meta` and `link`, and no `on*` attributes — values are escaped, but a
142
+ * handler is still script. A `meta` needs a `name`, `property` or
143
+ * `http-equiv`, a `link` a `rel`: that is what a later tag replaces it by.
144
+ */
145
+ function h(tag, attrs) {
146
+ if (tag !== "meta" && tag !== "link") throw new Error(`h(): only meta and link tags, got '${String(tag)}'.`);
147
+ for (const name of Object.keys(attrs)) if (!ATTR_NAME.test(name) || /^on/i.test(name)) throw new Error(`h(): attribute '${name}' is not allowed.`);
148
+ const key = headKey(tag, (name) => attrs[name]);
149
+ if (!key) throw new Error(tag === "meta" ? "h('meta'): needs a name, property or http-equiv." : "h('link'): needs a rel.");
150
+ return {
151
+ tag,
152
+ attrs: { ...attrs },
153
+ key
154
+ };
155
+ }
156
+ /**
157
+ * The meta a page is sent with: `defaults` under `meta`, the title template
158
+ * applied, and paths made absolute with `baseUrl`. Without a `canonical`, a
159
+ * successful page gets `baseUrl` + its path (no query) — never the request's
160
+ * Host header, which the client chooses.
161
+ */
162
+ function resolveMeta(defaults = {}, meta = {}, options = {}) {
163
+ const { titleTemplate, ...base } = defaults;
164
+ const { baseUrl, path, status = 200 } = options;
165
+ const title = meta.title !== void 0 && titleTemplate ? titleTemplate.replace("%s", () => meta.title) : meta.title ?? base.title;
166
+ const description = meta.description ?? base.description;
167
+ let canonical = meta.canonical ?? base.canonical;
168
+ if (canonical === void 0 && baseUrl && path !== void 0 && status < 300) canonical = path.split(/[?#]/)[0].replace(/(.)\/+$/, "$1");
169
+ canonical = absolute(canonical, baseUrl);
170
+ const og = {
171
+ ...base.og,
172
+ ...meta.og
173
+ };
174
+ og.title ??= meta.title ?? base.title;
175
+ og.description ??= description;
176
+ og.url ??= canonical;
177
+ og.image = absolute(og.image, baseUrl);
178
+ const twitter = {
179
+ ...base.twitter,
180
+ ...meta.twitter
181
+ };
182
+ twitter.image = absolute(twitter.image, baseUrl);
183
+ const head = /* @__PURE__ */ new Map();
184
+ for (const t of [...base.head ?? [], ...meta.head ?? []]) {
185
+ const href = t.tag === "link" && t.attrs.rel?.toLowerCase() === "alternate" ? t.attrs.href : void 0;
186
+ head.set(t.key, href ? {
187
+ ...t,
188
+ attrs: {
189
+ ...t.attrs,
190
+ href: absolute(href, baseUrl)
191
+ }
192
+ } : t);
193
+ }
194
+ const strip = (r) => Object.fromEntries(Object.entries(r).filter(([, v]) => v !== void 0));
195
+ const out = {
196
+ title,
197
+ lang: meta.lang ?? base.lang,
198
+ description,
199
+ canonical,
200
+ robots: meta.robots ?? base.robots,
201
+ og: strip(og),
202
+ twitter: strip(twitter),
203
+ jsonLd: meta.jsonLd ?? base.jsonLd,
204
+ head: [...head.values()]
205
+ };
206
+ for (const key of Object.keys(out)) {
207
+ const v = out[key];
208
+ if (v === void 0 || typeof v === "object" && !Object.keys(v).length) delete out[key];
209
+ }
210
+ return Object.keys(out).length ? out : void 0;
211
+ }
212
+ /** JSON for a `<script>` body: `<` escaped, so a value can't close the tag. */
213
+ function scriptJson(value) {
214
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026");
215
+ }
216
+ /**
217
+ * The meta as head tags. Each carries `data-inertia="<key>"` — what Inertia's
218
+ * `<Head>` gives a tag with that `head-key` — so the client takes them over
219
+ * and replaces them on the next visit instead of leaving them behind.
220
+ */
221
+ function metaTags(meta) {
222
+ if (!meta) return [];
223
+ const tags = [];
224
+ const m = (attr, key, value) => tags.push(`<meta data-inertia="${escapeHtml$1(key)}" ${attr}="${escapeHtml$1(key)}" content="${escapeHtml$1(value)}" />`);
225
+ if (meta.title !== void 0) tags.push(`<title data-inertia="">${escapeHtml$1(meta.title)}</title>`);
226
+ if (meta.description !== void 0) m("name", "description", meta.description);
227
+ if (meta.robots !== void 0) m("name", "robots", meta.robots);
228
+ if (meta.canonical !== void 0) tags.push(`<link data-inertia="canonical" rel="canonical" href="${escapeHtml$1(meta.canonical)}" />`);
229
+ for (const [k, v] of Object.entries(meta.og ?? {})) m("property", `og:${k}`, v);
230
+ for (const [k, v] of Object.entries(meta.twitter ?? {})) m("name", `twitter:${k}`, v);
231
+ if (meta.jsonLd !== void 0) tags.push(`<script data-inertia="json-ld" type="application/ld+json">${scriptJson(meta.jsonLd)}<\/script>`);
232
+ for (const t of meta.head ?? []) {
233
+ const attrs = Object.entries(t.attrs).map(([k, v]) => `${k}="${escapeHtml$1(v)}"`).join(" ");
234
+ tags.push(`<${t.tag} data-inertia="${escapeHtml$1(t.key)}" ${attrs} />`);
235
+ }
236
+ return tags;
237
+ }
238
+ /** What a head tag sets — two tags with the same key are duplicates. */
239
+ function tagKey(tag) {
240
+ const attr = (name) => tag.match(new RegExp(`\\s${name}\\s*=\\s*["']([^"']*)["']`, "i"))?.[1]?.toLowerCase();
241
+ if (/^<title[\s>]/i.test(tag)) return "title";
242
+ if (/^<script\s/i.test(tag) && attr("type") === "application/ld+json") return "json-ld";
243
+ const name = tag.match(/^<(meta|link)\s/i)?.[1];
244
+ return name ? headKey(name.toLowerCase(), attr) : null;
245
+ }
246
+ /** `tags` minus the ones `winners` (a server-rendered `<Head>`) already set. */
247
+ function dedupeHead(tags, winners) {
248
+ const taken = new Set(winners.map((t) => tagKey(t.trim())).filter(Boolean));
249
+ return tags.filter((t) => !taken.has(tagKey(t)));
250
+ }
251
+ const escapeXml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
252
+ /** The sitemap XML for `entries`. Paths are made absolute with `baseUrl`. */
253
+ function sitemapXml(entries, baseUrl) {
254
+ return `<?xml version="1.0" encoding="UTF-8"?>
255
+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
256
+ ${[...entries].map((e) => {
257
+ const lastmod = e.lastmod instanceof Date ? e.lastmod.toISOString() : e.lastmod;
258
+ return [
259
+ " <url>",
260
+ ` <loc>${escapeXml(absolute(e.loc, baseUrl))}</loc>`,
261
+ lastmod && ` <lastmod>${escapeXml(lastmod)}</lastmod>`,
262
+ e.changefreq && ` <changefreq>${e.changefreq}</changefreq>`,
263
+ e.priority !== void 0 && ` <priority>${Number(e.priority).toFixed(1)}</priority>`,
264
+ " </url>"
265
+ ].filter(Boolean).join("\n");
266
+ }).join("\n")}
267
+ </urlset>
268
+ `;
269
+ }
270
+ /**
271
+ * Answer `/sitemap.xml`. Return it from a handler:
272
+ *
273
+ * ```ts
274
+ * @Get('/sitemap.xml')
275
+ * sitemap() {
276
+ * return sitemap([{ loc: '/' }, { loc: '/posts', changefreq: 'daily' }], { baseUrl: getEnv('APP_URL') })
277
+ * }
278
+ * ```
279
+ */
280
+ function sitemap(entries, options = {}) {
281
+ const xml = sitemapXml(entries, options.baseUrl);
282
+ return { [RESPOND](ctx) {
283
+ ctx.send(xml, { type: "application/xml; charset=utf-8" });
284
+ } };
285
+ }
286
+ /** The robots.txt text. Line breaks in values are dropped, so one can't add a rule. */
287
+ function robotsTxt(options = {}) {
288
+ const clean = (v) => v.replace(/[\r\n]+/g, "");
289
+ const lines = [`User-agent: ${clean(options.userAgent ?? "*")}`];
290
+ for (const p of options.allow ?? []) lines.push(`Allow: ${clean(p)}`);
291
+ for (const p of options.disallow ?? []) lines.push(`Disallow: ${clean(p)}`);
292
+ if (!options.allow?.length && !options.disallow?.length) lines.push("Allow: /");
293
+ const maps = options.sitemap === void 0 ? [] : [options.sitemap].flat();
294
+ if (maps.length) lines.push("", ...maps.map((s) => `Sitemap: ${clean(absolute(s, options.baseUrl))}`));
295
+ return `${lines.join("\n")}\n`;
296
+ }
297
+ /** Answer `/robots.txt`. */
298
+ function robots(options = {}) {
299
+ const text = robotsTxt(options);
300
+ return { [RESPOND](ctx) {
301
+ ctx.send(text);
302
+ } };
303
+ }
304
+
99
305
  //#endregion
100
306
  //#region src/inertia.ts
101
307
  /**
@@ -245,6 +451,12 @@ async function buildPage(ctx, component, props, options = {}) {
245
451
  delete ctx.session.data[FRAGMENT_KEY];
246
452
  page.preserveFragment = true;
247
453
  }
454
+ const meta = resolveMeta(rt.meta, options.meta, {
455
+ baseUrl: rt.baseUrl,
456
+ path: page.url,
457
+ status: options.status
458
+ });
459
+ if (meta) page.meta = meta;
248
460
  if (options.encryptHistory) page.encryptHistory = true;
249
461
  if (options.clearHistory) page.clearHistory = true;
250
462
  return page;
@@ -356,16 +568,24 @@ const STATUS_TEXT = {
356
568
  };
357
569
  /**
358
570
  * The configured error page as a response, with `{ status, message }` as its
359
- * props. A 5xx message is replaced in production — an exception's text is
360
- * for the log, not the visitor.
571
+ * props. A 5xx message is replaced unless NODE_ENV is development or test —
572
+ * an exception's text is for the log, not the visitor, and a deploy that
573
+ * forgot NODE_ENV must not show it.
361
574
  */
362
575
  function errorPage(component, status, error) {
363
576
  const fallback = STATUS_TEXT[status] ?? (status >= 500 ? "Server Error" : "Error");
364
577
  const raw = error instanceof Error && error.message ? error.message : fallback;
578
+ const dev = process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test";
365
579
  return inertia(component, {
366
580
  status,
367
- message: status >= 500 && process.env.NODE_ENV === "production" ? fallback : raw
368
- }, { status });
581
+ message: status >= 500 && !dev ? fallback : raw
582
+ }, {
583
+ status,
584
+ meta: {
585
+ title: fallback,
586
+ robots: "noindex"
587
+ }
588
+ });
369
589
  }
370
590
 
371
591
  //#endregion
@@ -377,12 +597,18 @@ function errorPage(component, status, error) {
377
597
  * @module @forinda/kickjs-inertia/html
378
598
  */
379
599
  const escapeHtml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
380
- const defaultTemplate = (title) => ({ head, body }) => `<!doctype html>
381
- <html lang="en">
600
+ /**
601
+ * The default shell. Its `<title>` is a fallback: left out when the head
602
+ * already has one (a server-rendered `<Head>`). In the browser, Inertia drops
603
+ * it itself once a page's `<Head>` sets a title. `<html lang>` is the page's
604
+ * `meta.lang`, else `'en'`.
605
+ */
606
+ const defaultTemplate = (title) => ({ head, body, page }) => `<!doctype html>
607
+ <html lang="${escapeHtml(page.meta?.lang ?? "en")}">
382
608
  <head>
383
609
  <meta charset="utf-8" />
384
610
  <meta name="viewport" content="width=device-width, initial-scale=1" />
385
- <title>${escapeHtml(title)}</title>
611
+ ${/<title[\s>]/i.test(head) ? "" : `<title>${escapeHtml(title)}</title>`}
386
612
  ${head}
387
613
  </head>
388
614
  <body>
@@ -401,9 +627,39 @@ function pageBody(page, id = "app") {
401
627
  function devHead(entry) {
402
628
  return `<script type="module" src="/${entry.replace(/^\/+/, "")}"><\/script>`;
403
629
  }
630
+ function readManifest(clientDir) {
631
+ return JSON.parse(readFileSync(join(clientDir, ".vite", "manifest.json"), "utf8"));
632
+ }
633
+ /** Vite's default `[name]-[hash]`: an 8-character base64url hash before the extension. */
634
+ const HASHED_NAME = /[.-]([\w-]{8})\.\w+$/;
635
+ /**
636
+ * Whether a build file's name carries a hash. Eight characters alone also fit
637
+ * a word (`app-darkmode.css`), so the segment must have a digit or a capital
638
+ * past its first letter, which a word rarely has and a hash almost always
639
+ * does. A hash that misses it only loses the long cache; a word that passes
640
+ * would be cached for a year.
641
+ */
642
+ function isHashedName(file) {
643
+ const hash = HASHED_NAME.exec(file)?.[1];
644
+ return !!hash && /\d|.[A-Z]/.test(hash);
645
+ }
646
+ /**
647
+ * URL paths of the content-hashed files in the build manifest. A name without
648
+ * a hash (an `entryFileNames` that leaves it out) is skipped: its content can
649
+ * change under the same URL.
650
+ */
651
+ function hashedFiles(clientDir) {
652
+ const files = /* @__PURE__ */ new Set();
653
+ for (const chunk of Object.values(readManifest(clientDir))) for (const f of [
654
+ chunk.file,
655
+ ...chunk.css ?? [],
656
+ ...chunk.assets ?? []
657
+ ]) if (isHashedName(f)) files.add(`/${f}`);
658
+ return files;
659
+ }
404
660
  /** Production: the entry's script, its CSS, and the CSS and preloads of what it imports. */
405
661
  function manifestHead(clientDir, entry) {
406
- const manifest = JSON.parse(readFileSync(join(clientDir, ".vite", "manifest.json"), "utf8"));
662
+ const manifest = readManifest(clientDir);
407
663
  const chunk = manifest[entry];
408
664
  if (!chunk) throw new Error(`InertiaAdapter: '${entry}' is not in ${clientDir}/.vite/manifest.json — build the client with build.manifest and this entry as an input.`);
409
665
  const css = /* @__PURE__ */ new Set();
@@ -436,6 +692,7 @@ function manifestHead(clientDir, entry) {
436
692
  *
437
693
  * @module @forinda/kickjs-inertia/adapter
438
694
  */
695
+ let warnedNoBuild = false;
439
696
  const log$1 = Logger.for("InertiaAdapter");
440
697
  const CSS_REQUEST = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
441
698
  /**
@@ -497,6 +754,7 @@ const InertiaAdapter = defineAdapter({
497
754
  build: (config) => {
498
755
  const clientDir = fromAppRoot(config.clientDir);
499
756
  const template = config.template ?? defaultTemplate(config.title);
757
+ 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
758
  let version = () => null;
501
759
  let runtime = null;
502
760
  const protocol = (req, res, next) => {
@@ -523,11 +781,18 @@ const InertiaAdapter = defineAdapter({
523
781
  beforeMount({ http }) {
524
782
  const vite = viteServer();
525
783
  let head;
784
+ const manifest = join(clientDir, ".vite", "manifest.json");
526
785
  if (vite) head = () => devHead(config.entry);
527
- else {
786
+ else if (["development", "test"].includes(process.env.NODE_ENV ?? "") && !existsSync(manifest)) {
787
+ head = () => "";
788
+ if (!warnedNoBuild) {
789
+ warnedNoBuild = true;
790
+ log$1.warn(`No client build at ${manifest} — pages render without their scripts. Build the client, or run kick dev.`);
791
+ }
792
+ } else {
528
793
  const tags = manifestHead(clientDir, config.entry);
529
794
  head = () => tags;
530
- const hash = createHash("sha1").update(readFileSync(join(clientDir, ".vite", "manifest.json"))).digest("hex").slice(0, 12);
795
+ const hash = createHash("sha1").update(readFileSync(manifest)).digest("hex").slice(0, 12);
531
796
  version = () => hash;
532
797
  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
798
  const hidden = new Set(readdirSync(clientDir).filter((name) => name.startsWith(".")));
@@ -541,6 +806,12 @@ const InertiaAdapter = defineAdapter({
541
806
  next();
542
807
  };
543
808
  http.use(hideBuildFiles);
809
+ const hashed = hashedFiles(clientDir);
810
+ const cacheHashed = (req, res, next) => {
811
+ if (hashed.has(safeDecode((req.url ?? "/").split("?")[0]))) res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
812
+ next();
813
+ };
814
+ http.use(cacheHashed);
544
815
  http.serveStatic("/", clientDir);
545
816
  }
546
817
  if (config.version !== void 0) {
@@ -572,15 +843,20 @@ const InertiaAdapter = defineAdapter({
572
843
  version: () => version(),
573
844
  share: config.share,
574
845
  errorPage: config.errorPage,
846
+ meta: config.meta,
847
+ baseUrl: config.baseUrl,
575
848
  async renderHtml(page, ctx) {
576
849
  const rendered = await render(page);
577
850
  const styles = vite && rendered && ssr ? devStylesheets(vite, ssr.entry) : [];
851
+ const ssrHead = rendered?.head ?? [];
852
+ const meta = dedupeHead(metaTags(page.meta), ssrHead);
578
853
  const html = template({
579
854
  head: [
855
+ ...meta,
856
+ ...ssrHead,
580
857
  config.head ?? "",
581
858
  head(page),
582
- ...styles,
583
- ...rendered?.head ?? []
859
+ ...styles
584
860
  ].filter(Boolean).join("\n "),
585
861
  body: rendered?.body ?? pageBody(page),
586
862
  page
@@ -720,5 +996,5 @@ function inertiaNotFound() {
720
996
  }
721
997
 
722
998
  //#endregion
723
- export { InertiaAdapter, always, back, buildPage, defaultTemplate, defer, errorPage, flash, inertia, inertiaErrorHandler, inertiaNotFound, isInertiaRequest, isPageRequest, location, merge, once, optional, pageBody, precognitive, redirect, scroll };
999
+ export { InertiaAdapter, always, back, buildPage, defaultTemplate, defer, errorPage, flash, h, inertia, inertiaErrorHandler, inertiaNotFound, isInertiaRequest, isPageRequest, location, merge, once, optional, pageBody, precognitive, redirect, robots, scroll, sitemap };
724
1000
  //# sourceMappingURL=index.mjs.map
@@ -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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;')\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, '&quot;')}\"` : ''\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;;;;;;AAOA,SAAgB,KACd,OACA,UAA0C,CAAC,GAC3B;CAChB,OAAO,KAAK,QAAQ,OAAO,OAAO;AACpC;;;;;;;;;AAUA,SAAgB,OACd,OACA,UAKI,CAAC,GACW;CAChB,OAAO,KAAK,UAAU,OAAO;EAC3B,UAAU,QAAQ,YAAY;EAC9B,SAAS,QAAQ,WAAW;EAC5B,SAAS,OAAO,QAAQ,OAAO;EAC/B,MAAM,QAAQ,QAAQ;CACxB,CAAC;AACH;AAEA,SAAS,OAAO,OAA4D;CAC1E,OAAO,UAAU,SAAY,SAAY,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;AAChF;AAEA,SAAS,cAAc,OAA4B;CACjD,MAAM,OAAQ,OAA8E;CAC5F,IAAI,OAAO,MAAM,SAAS,UACxB,MAAM,IAAI,MACR,8GACF;CAEF,OAAO;EACL,aAAa,KAAK;EAClB,UAAU,KAAK,UA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,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"}
1
+ {"version":3,"file":"index.mjs","names":["escapeHtml","log"],"sources":["../src/props.ts","../src/seo.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 `<meta>` or `<link>` for the page's `<head>`, built with {@link h}. */\nexport interface HeadTag {\n tag: 'meta' | 'link'\n attrs: Record<string, string>\n /** A later tag with the same key replaces it — a page's over the defaults'. */\n key: string\n}\n\n/** A page's title, description and social tags. Every value is escaped on output. */\nexport interface PageMeta {\n title?: string\n /** `<html lang>` of the first visit; the template's `Seo` keeps it in sync on later ones. */\n lang?: 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 /** Any other `<meta>` / `<link>` — hreflang alternates, theme-color, preloads. See {@link h}. */\n head?: HeadTag[]\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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;')\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/** What a `meta` / `link` sets, from its attributes — two tags with the same key are duplicates. */\nfunction headKey(tag: string, attr: (name: string) => string | undefined): string | null {\n if (tag === 'meta') {\n const key = attr('name') ?? attr('property') ?? attr('http-equiv')\n return key ? `meta:${key.toLowerCase()}` : null\n }\n if (tag === 'link') {\n const rel = attr('rel')?.toLowerCase()\n if (!rel) return null\n if (rel === 'canonical') return 'canonical'\n return `link:${rel}:${(attr('hreflang') ?? attr('href') ?? '').toLowerCase()}`\n }\n return null\n}\n\nconst ATTR_NAME = /^[a-z][a-z0-9:-]*$/i\n\n/**\n * A head tag for `meta.head`, like Vue's `h()`:\n *\n * ```ts\n * meta: {\n * head: [\n * h('link', { rel: 'alternate', hreflang: 'fr', href: '/fr/posts/1' }),\n * h('meta', { name: 'theme-color', content: '#0f172a' }),\n * ],\n * }\n * ```\n *\n * Only `meta` and `link`, and no `on*` attributes — values are escaped, but a\n * handler is still script. A `meta` needs a `name`, `property` or\n * `http-equiv`, a `link` a `rel`: that is what a later tag replaces it by.\n */\nexport function h(tag: 'meta' | 'link', attrs: Record<string, string>): HeadTag {\n if (tag !== 'meta' && tag !== 'link') {\n throw new Error(`h(): only meta and link tags, got '${String(tag)}'.`)\n }\n for (const name of Object.keys(attrs)) {\n if (!ATTR_NAME.test(name) || /^on/i.test(name)) {\n throw new Error(`h(): attribute '${name}' is not allowed.`)\n }\n }\n const key = headKey(tag, (name) => attrs[name])\n if (!key) {\n throw new Error(\n tag === 'meta'\n ? \"h('meta'): needs a name, property or http-equiv.\"\n : \"h('link'): needs a rel.\",\n )\n }\n return { tag, attrs: { ...attrs }, key }\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 // `/posts/` and `/posts` are one page: one canonical.\n canonical = path.split(/[?#]/)[0]!.replace(/(.)\\/+$/, '$1')\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 // A page's tag replaces the default with the same key. An hreflang\n // alternate must be absolute, like the canonical.\n const head = new Map<string, HeadTag>()\n for (const t of [...(base.head ?? []), ...(meta.head ?? [])]) {\n const href =\n t.tag === 'link' && t.attrs.rel?.toLowerCase() === 'alternate' ? t.attrs.href : undefined\n head.set(t.key, href ? { ...t, attrs: { ...t.attrs, href: absolute(href, baseUrl)! } } : t)\n }\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 lang: meta.lang ?? base.lang,\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 head: [...head.values()],\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 for (const t of meta.head ?? []) {\n const attrs = Object.entries(t.attrs)\n .map(([k, v]) => `${k}=\"${escapeHtml(v)}\"`)\n .join(' ')\n tags.push(`<${t.tag} data-inertia=\"${escapeHtml(t.key)}\" ${attrs} />`)\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 (/^<script\\s/i.test(tag) && attr('type') === 'application/ld+json') return 'json-ld'\n const name = tag.match(/^<(meta|link)\\s/i)?.[1]\n return name ? headKey(name.toLowerCase(), attr) : 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, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;')\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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;')\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. `<html lang>` is the page's\n * `meta.lang`, else `'en'`.\n */\nexport const defaultTemplate =\n (title: string): HtmlTemplate =>\n ({ head, body, page }) =>\n `<!doctype html>\n<html lang=\"${escapeHtml(page.meta?.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 assets?: string[]\n imports?: string[]\n}\n\nfunction readManifest(clientDir: string): Record<string, ManifestChunk> {\n return JSON.parse(readFileSync(join(clientDir, '.vite', 'manifest.json'), 'utf8')) as Record<\n string,\n ManifestChunk\n >\n}\n\n/** Vite's default `[name]-[hash]`: an 8-character base64url hash before the extension. */\nconst HASHED_NAME = /[.-]([\\w-]{8})\\.\\w+$/\n\n/**\n * Whether a build file's name carries a hash. Eight characters alone also fit\n * a word (`app-darkmode.css`), so the segment must have a digit or a capital\n * past its first letter, which a word rarely has and a hash almost always\n * does. A hash that misses it only loses the long cache; a word that passes\n * would be cached for a year.\n */\nfunction isHashedName(file: string): boolean {\n const hash = HASHED_NAME.exec(file)?.[1]\n return !!hash && /\\d|.[A-Z]/.test(hash)\n}\n\n/**\n * URL paths of the content-hashed files in the build manifest. A name without\n * a hash (an `entryFileNames` that leaves it out) is skipped: its content can\n * change under the same URL.\n */\nexport function hashedFiles(clientDir: string): Set<string> {\n const files = new Set<string>()\n for (const chunk of Object.values(readManifest(clientDir))) {\n for (const f of [chunk.file, ...(chunk.css ?? []), ...(chunk.assets ?? [])]) {\n if (isHashedName(f)) files.add(`/${f}`)\n }\n }\n return files\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 = readManifest(clientDir)\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 {\n defaultTemplate,\n devHead,\n hashedFiles,\n manifestHead,\n pageBody,\n type HtmlTemplate,\n} 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, '&quot;')}\"` : ''\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 // What the manifest lists is content-hashed: a changed file gets a\n // new name, so a browser can keep these for good. Only those — a\n // public/ file (favicon, robots.txt) keeps its name across builds.\n const hashed = hashedFiles(clientDir)\n const cacheHashed: NodeMiddleware = (req, res, next) => {\n if (hashed.has(safeDecode((req.url ?? '/').split('?')[0]!))) {\n res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')\n }\n next()\n }\n http.use(cacheHashed 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 // Title and meta first, then the asset tags.\n head: [...meta, ...ssrHead, config.head ?? '', head(page), ...styles]\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;;;;;;AAOA,SAAgB,KACd,OACA,UAA0C,CAAC,GAC3B;CAChB,OAAO,K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AQ,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.2.0",
3
+ "version": "0.4.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.1.0"
38
+ "@forinda/kickjs": "10.8.0"
39
39
  },
40
40
  "peerDependencies": {
41
41
  "@forinda/kickjs": ">=10.0.0"