@dudousxd/nestjs-inertia 1.0.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.cjs ADDED
@@ -0,0 +1,2314 @@
1
+ const __importMetaUrl = require('url').pathToFileURL(__filename).href;
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from2, except, desc) => {
16
+ if (from2 && typeof from2 === "object" || typeof from2 === "function") {
17
+ for (let key of __getOwnPropNames(from2))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from2[key], enumerable: !(desc = __getOwnPropDesc(from2, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
24
+
25
+ // src/errors/exceptions.ts
26
+ var import_common4, InvalidInertiaConfigException, InertiaServiceNotAvailableException, UnsupportedRootViewExtensionException, MissingTemplateEngineDepException, MissingCookieDepException, InvalidCsrfTokenException;
27
+ var init_exceptions = __esm({
28
+ "src/errors/exceptions.ts"() {
29
+ "use strict";
30
+ import_common4 = require("@nestjs/common");
31
+ InvalidInertiaConfigException = class extends Error {
32
+ static {
33
+ __name(this, "InvalidInertiaConfigException");
34
+ }
35
+ constructor(message) {
36
+ super(`[nestjs-inertia] Invalid config: ${message}`);
37
+ this.name = "InvalidInertiaConfigException";
38
+ }
39
+ };
40
+ InertiaServiceNotAvailableException = class extends Error {
41
+ static {
42
+ __name(this, "InertiaServiceNotAvailableException");
43
+ }
44
+ constructor() {
45
+ super("[nestjs-inertia] req.inertia is not defined \u2014 middleware did not run. Ensure InertiaModule is imported and the middleware applies to this route.");
46
+ this.name = "InertiaServiceNotAvailableException";
47
+ }
48
+ };
49
+ UnsupportedRootViewExtensionException = class extends Error {
50
+ static {
51
+ __name(this, "UnsupportedRootViewExtensionException");
52
+ }
53
+ constructor(extension) {
54
+ super(`[nestjs-inertia] rootView extension "${extension}" is not supported. Supported extensions: .html, .htm, .hbs, .handlebars, .ejs, .pug, .liquid, .liquidjs. Or pass a (ctx) => string function for full control.`);
55
+ this.name = "UnsupportedRootViewExtensionException";
56
+ }
57
+ };
58
+ MissingTemplateEngineDepException = class extends Error {
59
+ static {
60
+ __name(this, "MissingTemplateEngineDepException");
61
+ }
62
+ constructor(engine, packageName) {
63
+ super(`[nestjs-inertia] Template engine "${engine}" requires "${packageName}" as a peer dependency. Install with: pnpm add ${packageName}`);
64
+ this.name = "MissingTemplateEngineDepException";
65
+ }
66
+ };
67
+ MissingCookieDepException = class extends Error {
68
+ static {
69
+ __name(this, "MissingCookieDepException");
70
+ }
71
+ constructor(platform) {
72
+ const dep = platform === "express" ? "cookie-parser" : "@fastify/cookie";
73
+ super(`[nestjs-inertia] CSRF requires "${dep}" as a peer dependency for ${platform}. Install with: pnpm add ${dep}`);
74
+ this.name = "MissingCookieDepException";
75
+ }
76
+ };
77
+ InvalidCsrfTokenException = class extends import_common4.ForbiddenException {
78
+ static {
79
+ __name(this, "InvalidCsrfTokenException");
80
+ }
81
+ constructor() {
82
+ super("[nestjs-inertia] CSRF token is missing or invalid.");
83
+ }
84
+ };
85
+ }
86
+ });
87
+
88
+ // src/shell/handlebars.adapter.ts
89
+ var handlebars_adapter_exports = {};
90
+ __export(handlebars_adapter_exports, {
91
+ handlebarsAdapter: () => handlebarsAdapter
92
+ });
93
+ function loadHandlebars() {
94
+ try {
95
+ return require2("handlebars");
96
+ } catch {
97
+ throw new MissingTemplateEngineDepException("Handlebars", "handlebars");
98
+ }
99
+ }
100
+ var import_node_module, require2, handlebarsAdapter;
101
+ var init_handlebars_adapter = __esm({
102
+ "src/shell/handlebars.adapter.ts"() {
103
+ "use strict";
104
+ import_node_module = require("module");
105
+ init_exceptions();
106
+ require2 = (0, import_node_module.createRequire)(__importMetaUrl);
107
+ __name(loadHandlebars, "loadHandlebars");
108
+ handlebarsAdapter = {
109
+ extension: ".hbs",
110
+ packageName: "handlebars",
111
+ compile(templateSource) {
112
+ const hbs = loadHandlebars();
113
+ const compiled = hbs.compile(templateSource);
114
+ return (locals) => compiled(locals);
115
+ }
116
+ };
117
+ }
118
+ });
119
+
120
+ // src/shell/ejs.adapter.ts
121
+ var ejs_adapter_exports = {};
122
+ __export(ejs_adapter_exports, {
123
+ ejsAdapter: () => ejsAdapter
124
+ });
125
+ function loadEjs() {
126
+ try {
127
+ return require3("ejs");
128
+ } catch {
129
+ throw new MissingTemplateEngineDepException("EJS", "ejs");
130
+ }
131
+ }
132
+ var import_node_module2, require3, ejsAdapter;
133
+ var init_ejs_adapter = __esm({
134
+ "src/shell/ejs.adapter.ts"() {
135
+ "use strict";
136
+ import_node_module2 = require("module");
137
+ init_exceptions();
138
+ require3 = (0, import_node_module2.createRequire)(__importMetaUrl);
139
+ __name(loadEjs, "loadEjs");
140
+ ejsAdapter = {
141
+ extension: ".ejs",
142
+ packageName: "ejs",
143
+ compile(templateSource, absPath) {
144
+ const ejs = loadEjs();
145
+ const compiled = ejs.compile(templateSource, {
146
+ filename: absPath,
147
+ async: false
148
+ });
149
+ return (locals) => compiled(locals);
150
+ }
151
+ };
152
+ }
153
+ });
154
+
155
+ // src/shell/pug.adapter.ts
156
+ var pug_adapter_exports = {};
157
+ __export(pug_adapter_exports, {
158
+ pugAdapter: () => pugAdapter
159
+ });
160
+ function loadPug() {
161
+ try {
162
+ return require4("pug");
163
+ } catch {
164
+ throw new MissingTemplateEngineDepException("Pug", "pug");
165
+ }
166
+ }
167
+ var import_node_module3, require4, pugAdapter;
168
+ var init_pug_adapter = __esm({
169
+ "src/shell/pug.adapter.ts"() {
170
+ "use strict";
171
+ import_node_module3 = require("module");
172
+ init_exceptions();
173
+ require4 = (0, import_node_module3.createRequire)(__importMetaUrl);
174
+ __name(loadPug, "loadPug");
175
+ pugAdapter = {
176
+ extension: ".pug",
177
+ packageName: "pug",
178
+ compile(templateSource, absPath) {
179
+ const pug = loadPug();
180
+ const compiled = pug.compile(templateSource, {
181
+ filename: absPath
182
+ });
183
+ return (locals) => compiled(locals);
184
+ }
185
+ };
186
+ }
187
+ });
188
+
189
+ // src/shell/liquid.adapter.ts
190
+ var liquid_adapter_exports = {};
191
+ __export(liquid_adapter_exports, {
192
+ liquidAdapter: () => liquidAdapter
193
+ });
194
+ function loadLiquid() {
195
+ try {
196
+ const mod = require5("liquidjs");
197
+ return mod.Liquid;
198
+ } catch {
199
+ throw new MissingTemplateEngineDepException("Liquid", "liquidjs");
200
+ }
201
+ }
202
+ var import_node_module4, require5, liquidAdapter;
203
+ var init_liquid_adapter = __esm({
204
+ "src/shell/liquid.adapter.ts"() {
205
+ "use strict";
206
+ import_node_module4 = require("module");
207
+ init_exceptions();
208
+ require5 = (0, import_node_module4.createRequire)(__importMetaUrl);
209
+ __name(loadLiquid, "loadLiquid");
210
+ liquidAdapter = {
211
+ extension: ".liquid",
212
+ packageName: "liquidjs",
213
+ compile(templateSource) {
214
+ const Liquid = loadLiquid();
215
+ const engine = new Liquid({
216
+ outputEscape: "escape"
217
+ });
218
+ return async (locals) => engine.parseAndRender(templateSource, locals);
219
+ }
220
+ };
221
+ }
222
+ });
223
+
224
+ // src/middleware/fastify-method-spoof.middleware.ts
225
+ var fastify_method_spoof_middleware_exports = {};
226
+ __export(fastify_method_spoof_middleware_exports, {
227
+ registerFastifyMethodSpoof: () => registerFastifyMethodSpoof
228
+ });
229
+ function registerFastifyMethodSpoof(app, options) {
230
+ if (options.methodSpoofing !== true) return;
231
+ app.addHook("preHandler", async (req) => {
232
+ const r = req;
233
+ if (r.method !== "POST") return;
234
+ const contentType = (r.headers["content-type"] ?? "").toString().toLowerCase();
235
+ if (!contentType.startsWith("multipart/")) return;
236
+ const spoofed = String(r.body?._method ?? "").toUpperCase();
237
+ if (ALLOWED2.has(spoofed)) {
238
+ r.method = spoofed;
239
+ if (r.body && typeof r.body === "object") {
240
+ r.body._method = void 0;
241
+ }
242
+ }
243
+ });
244
+ }
245
+ var ALLOWED2;
246
+ var init_fastify_method_spoof_middleware = __esm({
247
+ "src/middleware/fastify-method-spoof.middleware.ts"() {
248
+ "use strict";
249
+ ALLOWED2 = /* @__PURE__ */ new Set([
250
+ "PUT",
251
+ "PATCH",
252
+ "DELETE"
253
+ ]);
254
+ __name(registerFastifyMethodSpoof, "registerFastifyMethodSpoof");
255
+ }
256
+ });
257
+
258
+ // src/index.ts
259
+ var index_exports = {};
260
+ __export(index_exports, {
261
+ CsrfCookieInterceptor: () => CsrfCookieInterceptor,
262
+ CsrfGuard: () => CsrfGuard,
263
+ ErrorBagInterceptor: () => ErrorBagInterceptor,
264
+ INERTIA_ASSET_VERSION: () => INERTIA_ASSET_VERSION,
265
+ INERTIA_DEFAULT_SCOPE: () => INERTIA_DEFAULT_SCOPE,
266
+ INERTIA_FEATURE_OPTIONS: () => INERTIA_FEATURE_OPTIONS,
267
+ INERTIA_MANIFEST: () => INERTIA_MANIFEST,
268
+ INERTIA_MODULE_OPTIONS: () => INERTIA_MODULE_OPTIONS,
269
+ INERTIA_RENDER_COMPONENT: () => INERTIA_RENDER_COMPONENT,
270
+ INERTIA_USE_SCOPE: () => INERTIA_USE_SCOPE,
271
+ Inertia: () => Inertia,
272
+ InertiaModule: () => InertiaModule,
273
+ InertiaRenderInterceptor: () => InertiaRenderInterceptor,
274
+ InertiaService: () => InertiaService,
275
+ InertiaServiceNotAvailableException: () => InertiaServiceNotAvailableException,
276
+ InvalidCsrfTokenException: () => InvalidCsrfTokenException,
277
+ InvalidInertiaConfigException: () => InvalidInertiaConfigException,
278
+ MethodSpoofMiddleware: () => MethodSpoofMiddleware,
279
+ MissingCookieDepException: () => MissingCookieDepException,
280
+ MissingTemplateEngineDepException: () => MissingTemplateEngineDepException,
281
+ RedirectInterceptor: () => RedirectInterceptor,
282
+ UnsupportedRootViewExtensionException: () => UnsupportedRootViewExtensionException,
283
+ UseInertia: () => UseInertia,
284
+ VERSION: () => VERSION,
285
+ featureToken: () => featureToken,
286
+ generateCsrfToken: () => generateCsrfToken,
287
+ rotateCsrfToken: () => rotateCsrfToken,
288
+ timingSafeEqualSafe: () => timingSafeEqualSafe,
289
+ verifyCsrfToken: () => verifyCsrfToken
290
+ });
291
+ module.exports = __toCommonJS(index_exports);
292
+
293
+ // src/interceptor/error-bag.interceptor.ts
294
+ var import_common = require("@nestjs/common");
295
+ var import_operators = require("rxjs/operators");
296
+ function _ts_decorate(decorators, target, key, desc) {
297
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
298
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
299
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
300
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
301
+ }
302
+ __name(_ts_decorate, "_ts_decorate");
303
+ var ErrorBagInterceptor = class {
304
+ static {
305
+ __name(this, "ErrorBagInterceptor");
306
+ }
307
+ intercept(context, next) {
308
+ const req = context.switchToHttp().getRequest();
309
+ const bag = req.header("X-Inertia-Error-Bag");
310
+ if (!bag) return next.handle();
311
+ return next.handle().pipe((0, import_operators.map)((value) => {
312
+ if (typeof value !== "object" || value === null) return value;
313
+ const v = value;
314
+ if (v.errors === void 0) return value;
315
+ return {
316
+ ...v,
317
+ errors: {
318
+ [bag]: v.errors
319
+ }
320
+ };
321
+ }));
322
+ }
323
+ };
324
+ ErrorBagInterceptor = _ts_decorate([
325
+ (0, import_common.Injectable)()
326
+ ], ErrorBagInterceptor);
327
+
328
+ // src/interceptor/redirect.interceptor.ts
329
+ var import_common2 = require("@nestjs/common");
330
+ var import_operators2 = require("rxjs/operators");
331
+
332
+ // src/tokens.ts
333
+ var INERTIA_MODULE_OPTIONS = /* @__PURE__ */ Symbol("INERTIA_MODULE_OPTIONS");
334
+ var INERTIA_FEATURE_OPTIONS = /* @__PURE__ */ Symbol("INERTIA_FEATURE_OPTIONS");
335
+ var INERTIA_MANIFEST = /* @__PURE__ */ Symbol("INERTIA_MANIFEST");
336
+ var INERTIA_ASSET_VERSION = /* @__PURE__ */ Symbol("INERTIA_ASSET_VERSION");
337
+ var INERTIA_DEFAULT_SCOPE = "default";
338
+ var RESERVED_SCOPES = /* @__PURE__ */ new Set([
339
+ "default"
340
+ ]);
341
+ var _featureTokenCache = /* @__PURE__ */ new Map();
342
+ function featureToken(kind, scope, rootId) {
343
+ const key = rootId ? `${kind}:${scope}:${rootId}` : `${kind}:${scope}`;
344
+ const cached = _featureTokenCache.get(key);
345
+ if (cached) return cached;
346
+ const sym = /* @__PURE__ */ Symbol(`INERTIA_FEATURE_${kind}:${scope}${rootId ? `:${rootId}` : ""}`);
347
+ _featureTokenCache.set(key, sym);
348
+ return sym;
349
+ }
350
+ __name(featureToken, "featureToken");
351
+ function assertScopeNotReserved(scope) {
352
+ if (RESERVED_SCOPES.has(scope)) {
353
+ throw new Error(`[nestjs-inertia] Scope "${scope}" is reserved. Use forRoot() for the default scope.`);
354
+ }
355
+ }
356
+ __name(assertScopeNotReserved, "assertScopeNotReserved");
357
+
358
+ // src/interceptor/redirect.interceptor.ts
359
+ function _ts_decorate2(decorators, target, key, desc) {
360
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
361
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
362
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
363
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
364
+ }
365
+ __name(_ts_decorate2, "_ts_decorate");
366
+ function _ts_metadata(k, v) {
367
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
368
+ }
369
+ __name(_ts_metadata, "_ts_metadata");
370
+ function _ts_param(paramIndex, decorator) {
371
+ return function(target, key) {
372
+ decorator(target, key, paramIndex);
373
+ };
374
+ }
375
+ __name(_ts_param, "_ts_param");
376
+ var SAFE_METHODS = /* @__PURE__ */ new Set([
377
+ "PUT",
378
+ "PATCH",
379
+ "DELETE"
380
+ ]);
381
+ function getHeader(req, name) {
382
+ const r = req;
383
+ if (typeof r.header === "function") return r.header(name);
384
+ const v = r.headers?.[name.toLowerCase()];
385
+ return Array.isArray(v) ? v[0] : v;
386
+ }
387
+ __name(getHeader, "getHeader");
388
+ var RedirectInterceptor = class {
389
+ static {
390
+ __name(this, "RedirectInterceptor");
391
+ }
392
+ options;
393
+ constructor(options) {
394
+ this.options = options;
395
+ }
396
+ intercept(context, next) {
397
+ if (this.options.autoUpgrade303 === false) return next.handle();
398
+ const req = context.switchToHttp().getRequest();
399
+ const res = context.switchToHttp().getResponse();
400
+ const method = req.method;
401
+ if (SAFE_METHODS.has(method) && getHeader(req, "X-Inertia")) {
402
+ if (typeof res.redirect === "function") {
403
+ const originalRedirect = res.redirect.bind(res);
404
+ res.redirect = /* @__PURE__ */ __name(function patchedRedirect(statusOrUrl, url) {
405
+ if (typeof statusOrUrl === "number" && statusOrUrl === 302) {
406
+ originalRedirect(303, url);
407
+ } else if (typeof statusOrUrl === "string") {
408
+ originalRedirect(303, statusOrUrl);
409
+ } else {
410
+ originalRedirect(statusOrUrl, url);
411
+ }
412
+ }, "patchedRedirect");
413
+ }
414
+ const resAny = res;
415
+ if (typeof resAny.code === "function") {
416
+ const originalCode = resAny.code.bind(res);
417
+ resAny.code = /* @__PURE__ */ __name(function patchedCode(n) {
418
+ return originalCode(n === 302 ? 303 : n);
419
+ }, "patchedCode");
420
+ }
421
+ }
422
+ return next.handle().pipe((0, import_operators2.tap)(() => {
423
+ if (res.statusCode === 302 && SAFE_METHODS.has(method) && getHeader(req, "X-Inertia")) {
424
+ res.statusCode = 303;
425
+ }
426
+ }));
427
+ }
428
+ };
429
+ RedirectInterceptor = _ts_decorate2([
430
+ (0, import_common2.Injectable)(),
431
+ _ts_param(0, (0, import_common2.Inject)(INERTIA_MODULE_OPTIONS)),
432
+ _ts_metadata("design:type", Function),
433
+ _ts_metadata("design:paramtypes", [
434
+ typeof InertiaModuleOptions === "undefined" ? Object : InertiaModuleOptions
435
+ ])
436
+ ], RedirectInterceptor);
437
+
438
+ // src/middleware/method-spoof.middleware.ts
439
+ var import_common3 = require("@nestjs/common");
440
+ function _ts_decorate3(decorators, target, key, desc) {
441
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
442
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
443
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
444
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
445
+ }
446
+ __name(_ts_decorate3, "_ts_decorate");
447
+ function _ts_metadata2(k, v) {
448
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
449
+ }
450
+ __name(_ts_metadata2, "_ts_metadata");
451
+ function _ts_param2(paramIndex, decorator) {
452
+ return function(target, key) {
453
+ decorator(target, key, paramIndex);
454
+ };
455
+ }
456
+ __name(_ts_param2, "_ts_param");
457
+ var ALLOWED = /* @__PURE__ */ new Set([
458
+ "PUT",
459
+ "PATCH",
460
+ "DELETE"
461
+ ]);
462
+ var MethodSpoofMiddleware = class {
463
+ static {
464
+ __name(this, "MethodSpoofMiddleware");
465
+ }
466
+ options;
467
+ constructor(options) {
468
+ this.options = options;
469
+ }
470
+ use(req, _res, next) {
471
+ if (this.options.methodSpoofing !== true) return next();
472
+ if (req.method !== "POST") return next();
473
+ const contentType = (req.headers["content-type"] ?? "").toString().toLowerCase();
474
+ if (!contentType.startsWith("multipart/")) return next();
475
+ const spoofed = String(req.body?._method ?? "").toUpperCase();
476
+ if (ALLOWED.has(spoofed)) {
477
+ req.method = spoofed;
478
+ if (req.body && typeof req.body === "object") {
479
+ req.body._method = void 0;
480
+ }
481
+ }
482
+ next();
483
+ }
484
+ };
485
+ MethodSpoofMiddleware = _ts_decorate3([
486
+ (0, import_common3.Injectable)(),
487
+ _ts_param2(0, (0, import_common3.Inject)(INERTIA_MODULE_OPTIONS)),
488
+ _ts_metadata2("design:type", Function),
489
+ _ts_metadata2("design:paramtypes", [
490
+ typeof InertiaModuleOptions === "undefined" ? Object : InertiaModuleOptions
491
+ ])
492
+ ], MethodSpoofMiddleware);
493
+
494
+ // src/index.ts
495
+ init_exceptions();
496
+
497
+ // src/decorator/inertia.decorator.ts
498
+ var import_common5 = require("@nestjs/common");
499
+ var INERTIA_RENDER_COMPONENT = /* @__PURE__ */ Symbol("INERTIA_RENDER_COMPONENT");
500
+ function createInertiaDecorator(component) {
501
+ return (0, import_common5.SetMetadata)(INERTIA_RENDER_COMPONENT, component);
502
+ }
503
+ __name(createInertiaDecorator, "createInertiaDecorator");
504
+
505
+ // src/markers.ts
506
+ var MARKER = /* @__PURE__ */ Symbol("inertia.marker");
507
+ function make(kind, value, meta = {}) {
508
+ return {
509
+ [MARKER]: true,
510
+ kind,
511
+ value,
512
+ meta
513
+ };
514
+ }
515
+ __name(make, "make");
516
+ function inertiaDecorator(component) {
517
+ return createInertiaDecorator(component);
518
+ }
519
+ __name(inertiaDecorator, "inertiaDecorator");
520
+ function always(fn) {
521
+ return make("always", fn);
522
+ }
523
+ __name(always, "always");
524
+ function optional(fn) {
525
+ return make("optional", fn);
526
+ }
527
+ __name(optional, "optional");
528
+ var _lazyWarned = false;
529
+ function lazy(fn) {
530
+ if (!_lazyWarned) {
531
+ _lazyWarned = true;
532
+ console.warn("[nestjs-inertia] Inertia.lazy() is deprecated and will be removed in a future version. Use Inertia.optional() instead (Inertia v3).");
533
+ }
534
+ return optional(fn);
535
+ }
536
+ __name(lazy, "lazy");
537
+ function defer(fn, group = "default") {
538
+ return make("defer", fn, {
539
+ group
540
+ });
541
+ }
542
+ __name(defer, "defer");
543
+ function once(fn) {
544
+ return make("once", fn);
545
+ }
546
+ __name(once, "once");
547
+ function merge(fn, opts) {
548
+ const meta = {
549
+ deep: opts?.deep ?? false
550
+ };
551
+ if (opts?.matchOn !== void 0) meta.matchOn = opts.matchOn;
552
+ return make("merge", fn, meta);
553
+ }
554
+ __name(merge, "merge");
555
+ var Inertia = Object.assign(inertiaDecorator, {
556
+ always,
557
+ optional,
558
+ lazy,
559
+ defer,
560
+ once,
561
+ merge
562
+ });
563
+ function isMarker(value) {
564
+ return typeof value === "object" && value !== null && value[MARKER] === true;
565
+ }
566
+ __name(isMarker, "isMarker");
567
+ function getMarkerKind(marker) {
568
+ return marker.kind;
569
+ }
570
+ __name(getMarkerKind, "getMarkerKind");
571
+ function getMarkerValue(marker) {
572
+ return marker.value;
573
+ }
574
+ __name(getMarkerValue, "getMarkerValue");
575
+ function getMarkerMeta(marker) {
576
+ return marker.meta;
577
+ }
578
+ __name(getMarkerMeta, "getMarkerMeta");
579
+
580
+ // src/decorator/use-inertia.decorator.ts
581
+ var import_common6 = require("@nestjs/common");
582
+ var INERTIA_USE_SCOPE = "INERTIA_USE_SCOPE";
583
+ function UseInertia(scope) {
584
+ return (0, import_common6.SetMetadata)(INERTIA_USE_SCOPE, scope);
585
+ }
586
+ __name(UseInertia, "UseInertia");
587
+
588
+ // src/interceptor/render.interceptor.ts
589
+ var import_common7 = require("@nestjs/common");
590
+ var import_core = require("@nestjs/core");
591
+ var import_rxjs = require("rxjs");
592
+ var import_operators3 = require("rxjs/operators");
593
+ init_exceptions();
594
+ function _ts_decorate4(decorators, target, key, desc) {
595
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
596
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
597
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
598
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
599
+ }
600
+ __name(_ts_decorate4, "_ts_decorate");
601
+ function _ts_metadata3(k, v) {
602
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
603
+ }
604
+ __name(_ts_metadata3, "_ts_metadata");
605
+ function _ts_param3(paramIndex, decorator) {
606
+ return function(target, key) {
607
+ decorator(target, key, paramIndex);
608
+ };
609
+ }
610
+ __name(_ts_param3, "_ts_param");
611
+ var InertiaRenderInterceptor = class {
612
+ static {
613
+ __name(this, "InertiaRenderInterceptor");
614
+ }
615
+ reflector;
616
+ constructor(reflector) {
617
+ this.reflector = reflector;
618
+ }
619
+ intercept(context, next) {
620
+ const component = this.reflector.get(INERTIA_RENDER_COMPONENT, context.getHandler());
621
+ if (!component) {
622
+ return next.handle();
623
+ }
624
+ const req = context.switchToHttp().getRequest();
625
+ const res = context.switchToHttp().getResponse();
626
+ return next.handle().pipe((0, import_operators3.switchMap)((returnValue) => {
627
+ if (res.headersSent) {
628
+ return (0, import_rxjs.of)(void 0);
629
+ }
630
+ if (!req.inertia) {
631
+ throw new InertiaServiceNotAvailableException();
632
+ }
633
+ const props = returnValue ?? {};
634
+ return (0, import_rxjs.from)(req.inertia.render(component, props)).pipe((0, import_operators3.switchMap)(() => (0, import_rxjs.of)(void 0)));
635
+ }));
636
+ }
637
+ };
638
+ InertiaRenderInterceptor = _ts_decorate4([
639
+ (0, import_common7.Injectable)(),
640
+ _ts_param3(0, (0, import_common7.Inject)(import_core.Reflector)),
641
+ _ts_metadata3("design:type", Function),
642
+ _ts_metadata3("design:paramtypes", [
643
+ typeof import_core.Reflector === "undefined" ? Object : import_core.Reflector
644
+ ])
645
+ ], InertiaRenderInterceptor);
646
+
647
+ // src/service.ts
648
+ var import_common8 = require("@nestjs/common");
649
+
650
+ // src/helpers/nullify-undefined.ts
651
+ function nullifyUndefined(props) {
652
+ const out = {};
653
+ for (const [k, v] of Object.entries(props)) {
654
+ out[k] = v === void 0 ? null : v;
655
+ }
656
+ return out;
657
+ }
658
+ __name(nullifyUndefined, "nullifyUndefined");
659
+
660
+ // src/helpers/set-nested.ts
661
+ var FORBIDDEN_KEYS = /* @__PURE__ */ new Set([
662
+ "__proto__",
663
+ "prototype",
664
+ "constructor"
665
+ ]);
666
+ function assertSafeKey(key) {
667
+ if (FORBIDDEN_KEYS.has(key)) {
668
+ throw new Error(`[nestjs-inertia] Disallowed property key in nested path: "${key}"`);
669
+ }
670
+ }
671
+ __name(assertSafeKey, "assertSafeKey");
672
+ function setNested(target, path, value) {
673
+ if (path.length === 0) return;
674
+ let cur = target;
675
+ for (let i = 0; i < path.length - 1; i++) {
676
+ const key = path[i];
677
+ assertSafeKey(key);
678
+ const existing = cur[key];
679
+ if (existing === void 0) {
680
+ cur[key] = {};
681
+ } else if (typeof existing !== "object" || existing === null || Array.isArray(existing)) {
682
+ throw new Error(`[nestjs-inertia] dot-notation conflict at key "${path.slice(0, i + 1).join(".")}": expected object, got ${Array.isArray(existing) ? "array" : typeof existing}`);
683
+ }
684
+ cur = cur[key];
685
+ }
686
+ const finalKey = path[path.length - 1];
687
+ assertSafeKey(finalKey);
688
+ cur[finalKey] = value;
689
+ }
690
+ __name(setNested, "setNested");
691
+ function unpackDotKeys(props) {
692
+ const out = {};
693
+ const dotKeysParents = /* @__PURE__ */ new Set();
694
+ for (const key of Object.keys(props)) {
695
+ if (key.includes(".")) {
696
+ dotKeysParents.add(key.split(".")[0]);
697
+ }
698
+ }
699
+ for (const parent of dotKeysParents) {
700
+ if (props[parent] !== void 0 && (typeof props[parent] !== "object" || props[parent] === null || Array.isArray(props[parent]))) {
701
+ throw new Error(`[nestjs-inertia] dot-notation conflict at key "${parent}": exists as scalar AND as parent of a dot key`);
702
+ }
703
+ }
704
+ for (const [key, value] of Object.entries(props)) {
705
+ if (key.includes(".")) {
706
+ setNested(out, key.split("."), value);
707
+ } else {
708
+ out[key] = value;
709
+ }
710
+ }
711
+ return out;
712
+ }
713
+ __name(unpackDotKeys, "unpackDotKeys");
714
+
715
+ // src/service.ts
716
+ function validateLocationUrl(url) {
717
+ if (url.startsWith("/")) return url;
718
+ try {
719
+ const parsed = new URL(url);
720
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
721
+ throw new Error(`[nestjs-inertia] location() rejected unsafe URL scheme: ${url}`);
722
+ }
723
+ throw new Error(`[nestjs-inertia] location() rejected absolute URL to external host: ${url}. Use a relative path (e.g. "/dashboard") instead.`);
724
+ } catch (err) {
725
+ if (err instanceof TypeError) {
726
+ return url;
727
+ }
728
+ throw err;
729
+ }
730
+ }
731
+ __name(validateLocationUrl, "validateLocationUrl");
732
+ var OMIT = /* @__PURE__ */ Symbol("inertia.omit");
733
+ function containsAlwaysMarker(value) {
734
+ if (isMarker(value)) {
735
+ return getMarkerKind(value) === "always";
736
+ }
737
+ if (Array.isArray(value)) {
738
+ return value.some(containsAlwaysMarker);
739
+ }
740
+ if (typeof value === "object" && value !== null) {
741
+ return Object.values(value).some(containsAlwaysMarker);
742
+ }
743
+ return false;
744
+ }
745
+ __name(containsAlwaysMarker, "containsAlwaysMarker");
746
+ async function resolveNestedObjectValue(obj, topKey, subKeep, deferredProps) {
747
+ const out = {};
748
+ for (const [k, v] of Object.entries(obj)) {
749
+ const resolved = await resolveNestedValueInner(v, k, topKey, subKeep, deferredProps);
750
+ if (resolved !== OMIT) out[k] = resolved;
751
+ }
752
+ return out;
753
+ }
754
+ __name(resolveNestedObjectValue, "resolveNestedObjectValue");
755
+ async function resolveNestedValueInner(value, relPath, topKey, subKeep, deferredProps) {
756
+ if (isMarker(value)) {
757
+ return resolveMarker(value, relPath, topKey, subKeep, deferredProps);
758
+ }
759
+ if (Array.isArray(value)) {
760
+ const out = [];
761
+ for (const item of value) {
762
+ const resolved = await resolveNestedValueInner(item, relPath, topKey, subKeep, deferredProps);
763
+ if (resolved !== OMIT) out.push(resolved);
764
+ }
765
+ return out;
766
+ }
767
+ if (typeof value === "object" && value !== null) {
768
+ const obj = value;
769
+ const out = {};
770
+ for (const [k, v] of Object.entries(obj)) {
771
+ const childPath = `${relPath}.${k}`;
772
+ const resolved = await resolveNestedValueInner(v, childPath, topKey, subKeep, deferredProps);
773
+ if (resolved !== OMIT) out[k] = resolved;
774
+ }
775
+ return out;
776
+ }
777
+ if (subKeep !== null) {
778
+ const included = subKeep.some((k) => k === relPath || k.startsWith(`${relPath}.`));
779
+ if (!included) return OMIT;
780
+ }
781
+ return value;
782
+ }
783
+ __name(resolveNestedValueInner, "resolveNestedValueInner");
784
+ async function resolveMarker(marker, relPath, topKey, subKeep, deferredProps) {
785
+ const kind = getMarkerKind(marker);
786
+ const fullPath = `${topKey}.${relPath}`;
787
+ if (kind === "always") {
788
+ return getMarkerValue(marker)();
789
+ }
790
+ if (kind === "optional") {
791
+ if (subKeep?.includes(relPath)) {
792
+ return getMarkerValue(marker)();
793
+ }
794
+ return OMIT;
795
+ }
796
+ if (kind === "once") {
797
+ if (subKeep === null) {
798
+ return getMarkerValue(marker)();
799
+ }
800
+ return OMIT;
801
+ }
802
+ if (kind === "defer") {
803
+ if (subKeep !== null) {
804
+ if (subKeep.includes(relPath)) return getMarkerValue(marker)();
805
+ return OMIT;
806
+ }
807
+ const meta = getMarkerMeta(marker);
808
+ const group = meta.group;
809
+ const existing = deferredProps[group];
810
+ if (existing) existing.push(fullPath);
811
+ else deferredProps[group] = [
812
+ fullPath
813
+ ];
814
+ return OMIT;
815
+ }
816
+ if (kind === "merge") {
817
+ if (subKeep !== null && !subKeep.includes(relPath)) return OMIT;
818
+ return getMarkerValue(marker)();
819
+ }
820
+ return OMIT;
821
+ }
822
+ __name(resolveMarker, "resolveMarker");
823
+ var InertiaService = class _InertiaService {
824
+ static {
825
+ __name(this, "InertiaService");
826
+ }
827
+ req;
828
+ res;
829
+ deps;
830
+ logger = new import_common8.Logger(_InertiaService.name);
831
+ shared = [];
832
+ encryptHistoryFlag;
833
+ clearHistoryFlag = false;
834
+ constructor(req, res, deps) {
835
+ this.req = req;
836
+ this.res = res;
837
+ this.deps = deps;
838
+ }
839
+ share(input) {
840
+ this.shared.push(input);
841
+ return this;
842
+ }
843
+ /**
844
+ * Perform an Inertia redirect. For Inertia XHR requests, issues a 409 with
845
+ * `X-Inertia-Location`; for plain browser visits, issues a 302 redirect.
846
+ *
847
+ * Only relative URLs (starting with `/`) or same-origin absolute URLs are
848
+ * accepted. Absolute URLs pointing to a different host are rejected to prevent
849
+ * open-redirect vulnerabilities.
850
+ *
851
+ * @param url Relative path (e.g. `/dashboard`) or same-origin absolute URL.
852
+ * @throws Error when `url` is an absolute URL pointing to a different origin.
853
+ */
854
+ location(url) {
855
+ const safeUrl = validateLocationUrl(url);
856
+ if (this.req.header("X-Inertia")) {
857
+ this.res.status(409).setHeader("X-Inertia-Location", safeUrl).end();
858
+ } else {
859
+ this.res.status(302).setHeader("Location", safeUrl).end();
860
+ }
861
+ }
862
+ encryptHistory(value = true) {
863
+ this.encryptHistoryFlag = value;
864
+ return this;
865
+ }
866
+ clearHistory() {
867
+ this.clearHistoryFlag = true;
868
+ return this;
869
+ }
870
+ async resolveShared() {
871
+ const sources = [];
872
+ if (this.deps.moduleShare !== void 0) sources.push(this.deps.moduleShare);
873
+ if (this.deps.featureShare !== void 0) sources.push(this.deps.featureShare);
874
+ sources.push(...this.shared);
875
+ const out = {};
876
+ for (const s of sources) {
877
+ const resolved = typeof s === "function" ? await s(this.req) : s;
878
+ Object.assign(out, resolved);
879
+ }
880
+ return out;
881
+ }
882
+ async render(component, props = {}) {
883
+ const clientVersion = this.req.header("X-Inertia-Version");
884
+ if (this.req.method === "GET" && this.req.header("X-Inertia") && clientVersion !== void 0 && clientVersion !== this.deps.assetVersion) {
885
+ this.res.status(409).setHeader("X-Inertia-Location", this.req.originalUrl).end();
886
+ return;
887
+ }
888
+ if (this.deps.flashStore && props.errors === void 0) {
889
+ try {
890
+ const flashed = await this.deps.flashStore.read(this.req.raw);
891
+ if (flashed && Object.keys(flashed).length > 0) {
892
+ this.share({
893
+ errors: flashed
894
+ });
895
+ }
896
+ } catch (err) {
897
+ this.logger.warn(`FlashStore.read() threw: ${err instanceof Error ? err.message : String(err)}`);
898
+ }
899
+ }
900
+ const sharedProps = await this.resolveShared();
901
+ const rawProps = {
902
+ ...sharedProps,
903
+ ...props
904
+ };
905
+ if (rawProps.errors === void 0) rawProps.errors = {};
906
+ const partialComponent = this.req.header("X-Inertia-Partial-Component");
907
+ const isPartial = partialComponent === component;
908
+ const partialDataHeader = this.req.header("X-Inertia-Partial-Data");
909
+ const keepList = isPartial && partialDataHeader ? partialDataHeader.split(",").filter(Boolean) : null;
910
+ const keep = keepList && keepList.length > 0 ? keepList : null;
911
+ const resetHeader = this.req.header("X-Inertia-Reset");
912
+ const resetKeys = (resetHeader ?? "").split(",").filter(Boolean);
913
+ const resetOnceHeader = this.req.header("X-Inertia-Reset-Once");
914
+ const resetOnceKeys = (resetOnceHeader ?? "").split(",").filter(Boolean);
915
+ const exceptHeader = this.req.header("X-Inertia-Partial-Except");
916
+ const exceptKeys = isPartial ? (exceptHeader ?? "").split(",").filter(Boolean) : [];
917
+ const finalProps = {};
918
+ const deferredProps = {};
919
+ const mergeProps = [];
920
+ const deepMergeProps = [];
921
+ const matchPropsOn = {};
922
+ for (const [key, value] of Object.entries(rawProps)) {
923
+ if (exceptKeys.includes(key) && key !== "errors") continue;
924
+ if (isMarker(value)) {
925
+ const kind = getMarkerKind(value);
926
+ if (kind === "always") {
927
+ finalProps[key] = await getMarkerValue(value)();
928
+ continue;
929
+ }
930
+ if (kind === "optional") {
931
+ if (keep?.includes(key)) {
932
+ finalProps[key] = await getMarkerValue(value)();
933
+ }
934
+ continue;
935
+ }
936
+ if (kind === "once") {
937
+ if (!keep || resetOnceKeys.includes(key)) {
938
+ finalProps[key] = await getMarkerValue(value)();
939
+ }
940
+ continue;
941
+ }
942
+ if (kind === "defer") {
943
+ if (keep) {
944
+ if (keep.includes(key)) finalProps[key] = await getMarkerValue(value)();
945
+ continue;
946
+ }
947
+ const meta = getMarkerMeta(value);
948
+ const group = meta.group;
949
+ const existing = deferredProps[group];
950
+ if (existing) existing.push(key);
951
+ else deferredProps[group] = [
952
+ key
953
+ ];
954
+ continue;
955
+ }
956
+ if (kind === "merge") {
957
+ const meta = getMarkerMeta(value);
958
+ if (keep && !keep.includes(key) && key !== "errors") continue;
959
+ const resolved2 = await getMarkerValue(value)();
960
+ finalProps[key] = resolved2;
961
+ if (!resetKeys.includes(key)) {
962
+ if (meta.deep) deepMergeProps.push(key);
963
+ else mergeProps.push(key);
964
+ }
965
+ if (meta.matchOn !== void 0) matchPropsOn[key] = meta.matchOn;
966
+ continue;
967
+ }
968
+ }
969
+ const hasNestedKeepPath = keep?.some((k) => k.startsWith(`${key}.`)) ?? false;
970
+ const hasNestedAlways = keep ? containsAlwaysMarker(value) : false;
971
+ if (keep && !keep.includes(key) && key !== "errors" && !hasNestedKeepPath && !hasNestedAlways) continue;
972
+ let resolved = value;
973
+ if (typeof value === "function") {
974
+ resolved = await value();
975
+ }
976
+ let nestedKeep = null;
977
+ if (keep !== null) {
978
+ if (keep.includes(key)) {
979
+ nestedKeep = null;
980
+ } else {
981
+ nestedKeep = keep.filter((k) => k.startsWith(`${key}.`)).map((k) => k.slice(key.length + 1));
982
+ }
983
+ }
984
+ if (typeof resolved === "object" && resolved !== null && !Array.isArray(resolved)) {
985
+ resolved = await resolveNestedObjectValue(resolved, key, nestedKeep, deferredProps);
986
+ }
987
+ finalProps[key] = resolved;
988
+ }
989
+ const unpackedProps = unpackDotKeys(finalProps);
990
+ const wireProps = nullifyUndefined(unpackedProps);
991
+ const page = {
992
+ component,
993
+ props: wireProps,
994
+ url: this.req.originalUrl,
995
+ version: this.deps.assetVersion
996
+ };
997
+ if (Object.keys(deferredProps).length > 0) page.deferredProps = deferredProps;
998
+ if (mergeProps.length > 0) page.mergeProps = mergeProps;
999
+ if (deepMergeProps.length > 0) page.deepMergeProps = deepMergeProps;
1000
+ if (Object.keys(matchPropsOn).length > 0) page.matchPropsOn = matchPropsOn;
1001
+ const encryptHistory = this.encryptHistoryFlag !== void 0 ? this.encryptHistoryFlag : this.deps.historyEncryptionDefault ?? false;
1002
+ if (encryptHistory) page.encryptHistory = true;
1003
+ if (this.clearHistoryFlag) page.clearHistory = true;
1004
+ if (this.req.header("X-Inertia")) {
1005
+ this.res.setHeader("X-Inertia", "true").setHeader("Vary", "X-Inertia").json(page);
1006
+ return;
1007
+ }
1008
+ const ssrModule = await this.deps.ssrLoader.load();
1009
+ const ssr = ssrModule ? await ssrModule.render(page) : null;
1010
+ const html = await this.deps.rootViewRender({
1011
+ page,
1012
+ ssr,
1013
+ manifest: this.deps.manifest,
1014
+ assetVersion: this.deps.assetVersion,
1015
+ ctx: {
1016
+ req: this.req.raw,
1017
+ res: this.res.raw
1018
+ }
1019
+ });
1020
+ this.res.setHeader("Vary", "X-Inertia").html(html);
1021
+ }
1022
+ };
1023
+
1024
+ // src/module.ts
1025
+ var import_common12 = require("@nestjs/common");
1026
+ var import_core3 = require("@nestjs/core");
1027
+
1028
+ // src/asset/version.provider.ts
1029
+ var import_node_crypto = require("crypto");
1030
+ var import_node_fs = require("fs");
1031
+ var import_node_path = require("path");
1032
+ var DEFAULT_MANIFEST_PATH = "dist/inertia/client/.vite/manifest.json";
1033
+ function assertManifestShape(parsed, path) {
1034
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1035
+ throw new Error(`Vite manifest at ${path} has unexpected shape: expected a JSON object, got ${Array.isArray(parsed) ? "array" : typeof parsed}`);
1036
+ }
1037
+ for (const [key, entry] of Object.entries(parsed)) {
1038
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
1039
+ throw new Error(`Vite manifest at ${path} has unexpected shape: entry "${key}" is not an object`);
1040
+ }
1041
+ const e = entry;
1042
+ if (typeof e.file !== "string") {
1043
+ throw new Error(`Vite manifest at ${path} has unexpected shape: entry "${key}" is missing required string field "file"`);
1044
+ }
1045
+ }
1046
+ return parsed;
1047
+ }
1048
+ __name(assertManifestShape, "assertManifestShape");
1049
+ function loadManifest(path) {
1050
+ try {
1051
+ const abs = (0, import_node_path.isAbsolute)(path) ? path : (0, import_node_path.resolve)(process.cwd(), path);
1052
+ const raw = (0, import_node_fs.readFileSync)(abs, "utf8");
1053
+ const parsed = JSON.parse(raw);
1054
+ return assertManifestShape(parsed, abs);
1055
+ } catch (err) {
1056
+ if (err instanceof Error && err.message.includes("Vite manifest at")) {
1057
+ throw err;
1058
+ }
1059
+ return null;
1060
+ }
1061
+ }
1062
+ __name(loadManifest, "loadManifest");
1063
+ function computeAssetVersion(manifest) {
1064
+ if (manifest) {
1065
+ return (0, import_node_crypto.createHash)("sha1").update(JSON.stringify(manifest)).digest("hex").slice(0, 32);
1066
+ }
1067
+ return (0, import_node_crypto.randomUUID)().replace(/-/g, "");
1068
+ }
1069
+ __name(computeAssetVersion, "computeAssetVersion");
1070
+ var manifestProvider = {
1071
+ provide: INERTIA_MANIFEST,
1072
+ inject: [
1073
+ INERTIA_MODULE_OPTIONS
1074
+ ],
1075
+ useFactory: /* @__PURE__ */ __name((opts) => {
1076
+ if (process.env.NODE_ENV !== "production") return null;
1077
+ const path = opts.vite?.manifestPath ?? DEFAULT_MANIFEST_PATH;
1078
+ return loadManifest(path);
1079
+ }, "useFactory")
1080
+ };
1081
+ var assetVersionProvider = {
1082
+ provide: INERTIA_ASSET_VERSION,
1083
+ inject: [
1084
+ INERTIA_MANIFEST,
1085
+ INERTIA_MODULE_OPTIONS
1086
+ ],
1087
+ useFactory: /* @__PURE__ */ __name(async (manifest, opts) => {
1088
+ if (opts.version !== void 0) {
1089
+ return typeof opts.version === "function" ? await opts.version() : opts.version;
1090
+ }
1091
+ return computeAssetVersion(manifest);
1092
+ }, "useFactory")
1093
+ };
1094
+
1095
+ // src/module.ts
1096
+ init_exceptions();
1097
+
1098
+ // src/interceptor/scope-switcher.interceptor.ts
1099
+ var import_common9 = require("@nestjs/common");
1100
+ var import_core2 = require("@nestjs/core");
1101
+
1102
+ // src/adapter/express.ts
1103
+ var expressAdapter = {
1104
+ adaptRequest(raw) {
1105
+ const r = raw;
1106
+ const req = {
1107
+ method: r.method,
1108
+ originalUrl: r.originalUrl,
1109
+ url: r.url,
1110
+ header(name) {
1111
+ if (typeof r.header === "function") return r.header(name);
1112
+ const v = r.headers[name.toLowerCase()];
1113
+ return Array.isArray(v) ? v[0] : v;
1114
+ },
1115
+ raw
1116
+ };
1117
+ if (r.body !== void 0) req.body = r.body;
1118
+ if (r.query !== void 0) req.query = r.query;
1119
+ return req;
1120
+ },
1121
+ adaptResponse(raw) {
1122
+ const r = raw;
1123
+ const wrapper = {
1124
+ get statusCode() {
1125
+ return r.statusCode;
1126
+ },
1127
+ get headersSent() {
1128
+ return r.headersSent;
1129
+ },
1130
+ status(code) {
1131
+ r.status(code);
1132
+ return wrapper;
1133
+ },
1134
+ setHeader(name, value) {
1135
+ r.setHeader(name, value);
1136
+ return wrapper;
1137
+ },
1138
+ getHeader(name) {
1139
+ return r.getHeader(name);
1140
+ },
1141
+ json(body) {
1142
+ r.json(body);
1143
+ },
1144
+ html(body) {
1145
+ r.setHeader("Content-Type", "text/html; charset=utf-8");
1146
+ r.send(body);
1147
+ },
1148
+ end() {
1149
+ r.end();
1150
+ },
1151
+ raw
1152
+ };
1153
+ return wrapper;
1154
+ }
1155
+ };
1156
+
1157
+ // src/adapter/fastify.ts
1158
+ var fastifyAdapter = {
1159
+ adaptRequest(raw) {
1160
+ const r = raw;
1161
+ const req = {
1162
+ method: r.method,
1163
+ originalUrl: r.raw?.originalUrl ?? r.url,
1164
+ url: r.url,
1165
+ header(name) {
1166
+ const v = r.headers[name.toLowerCase()];
1167
+ return Array.isArray(v) ? v[0] : v;
1168
+ },
1169
+ raw
1170
+ };
1171
+ if (r.body !== void 0) req.body = r.body;
1172
+ if (r.query !== void 0) req.query = r.query;
1173
+ return req;
1174
+ },
1175
+ adaptResponse(raw) {
1176
+ const r = raw;
1177
+ const wrapper = {
1178
+ get statusCode() {
1179
+ return r.statusCode;
1180
+ },
1181
+ get headersSent() {
1182
+ return r.sent;
1183
+ },
1184
+ status(code) {
1185
+ r.code(code);
1186
+ return wrapper;
1187
+ },
1188
+ setHeader(name, value) {
1189
+ r.header(name, value);
1190
+ return wrapper;
1191
+ },
1192
+ getHeader(name) {
1193
+ return r.getHeader(name);
1194
+ },
1195
+ json(body) {
1196
+ r.send(body);
1197
+ },
1198
+ html(body) {
1199
+ r.header("Content-Type", "text/html; charset=utf-8");
1200
+ r.send(body);
1201
+ },
1202
+ end() {
1203
+ r.send("");
1204
+ },
1205
+ raw
1206
+ };
1207
+ return wrapper;
1208
+ }
1209
+ };
1210
+
1211
+ // src/interceptor/scope-switcher.interceptor.ts
1212
+ function _ts_decorate5(decorators, target, key, desc) {
1213
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1214
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1215
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1216
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1217
+ }
1218
+ __name(_ts_decorate5, "_ts_decorate");
1219
+ function _ts_metadata4(k, v) {
1220
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1221
+ }
1222
+ __name(_ts_metadata4, "_ts_metadata");
1223
+ function _ts_param4(paramIndex, decorator) {
1224
+ return function(target, key) {
1225
+ decorator(target, key, paramIndex);
1226
+ };
1227
+ }
1228
+ __name(_ts_param4, "_ts_param");
1229
+ var InertiaScopeSwitcherInterceptor = class {
1230
+ static {
1231
+ __name(this, "InertiaScopeSwitcherInterceptor");
1232
+ }
1233
+ reflector;
1234
+ moduleRef;
1235
+ httpAdapterHost;
1236
+ constructor(reflector, moduleRef, httpAdapterHost) {
1237
+ this.reflector = reflector;
1238
+ this.moduleRef = moduleRef;
1239
+ this.httpAdapterHost = httpAdapterHost;
1240
+ }
1241
+ intercept(ctx, next) {
1242
+ const scope = this.reflector.getAllAndOverride(INERTIA_USE_SCOPE, [
1243
+ ctx.getHandler(),
1244
+ ctx.getClass()
1245
+ ]);
1246
+ if (scope && scope !== "default") {
1247
+ const opts = this.moduleRef.get(featureToken("OPTIONS", scope), {
1248
+ strict: false
1249
+ });
1250
+ const manifest = this.moduleRef.get(featureToken("MANIFEST", scope), {
1251
+ strict: false
1252
+ });
1253
+ const assetVersion = this.moduleRef.get(featureToken("ASSET_VERSION", scope), {
1254
+ strict: false
1255
+ });
1256
+ const shellRenderer = this.moduleRef.get(featureToken("SHELL_RENDERER", scope), {
1257
+ strict: false
1258
+ });
1259
+ const ssrLoader = this.moduleRef.get(featureToken("SSR_LOADER", scope), {
1260
+ strict: false
1261
+ });
1262
+ const req = ctx.switchToHttp().getRequest();
1263
+ const res = ctx.switchToHttp().getResponse();
1264
+ const deps = {
1265
+ assetVersion,
1266
+ manifest,
1267
+ ssrLoader,
1268
+ rootViewRender: /* @__PURE__ */ __name((c) => shellRenderer.render(c), "rootViewRender"),
1269
+ moduleShare: opts.share,
1270
+ featureShare: void 0,
1271
+ historyEncryptionDefault: opts.historyEncryption?.default ?? false,
1272
+ flashStore: opts.flashStore
1273
+ };
1274
+ const platform = this.httpAdapterHost.httpAdapter?.getType();
1275
+ const adapter = platform === "fastify" ? fastifyAdapter : expressAdapter;
1276
+ req.inertia = new InertiaService(adapter.adaptRequest(req), adapter.adaptResponse(res), deps);
1277
+ }
1278
+ return next.handle();
1279
+ }
1280
+ };
1281
+ InertiaScopeSwitcherInterceptor = _ts_decorate5([
1282
+ (0, import_common9.Injectable)(),
1283
+ _ts_param4(0, (0, import_common9.Inject)(import_core2.Reflector)),
1284
+ _ts_param4(1, (0, import_common9.Inject)(import_core2.ModuleRef)),
1285
+ _ts_param4(2, (0, import_common9.Inject)(import_core2.HttpAdapterHost)),
1286
+ _ts_metadata4("design:type", Function),
1287
+ _ts_metadata4("design:paramtypes", [
1288
+ typeof import_core2.Reflector === "undefined" ? Object : import_core2.Reflector,
1289
+ typeof import_core2.ModuleRef === "undefined" ? Object : import_core2.ModuleRef,
1290
+ typeof import_core2.HttpAdapterHost === "undefined" ? Object : import_core2.HttpAdapterHost
1291
+ ])
1292
+ ], InertiaScopeSwitcherInterceptor);
1293
+
1294
+ // src/middleware/express.middleware.ts
1295
+ var import_common10 = require("@nestjs/common");
1296
+
1297
+ // src/helpers/suppress-post-send-writes.ts
1298
+ var KEYS = [
1299
+ "status",
1300
+ "json",
1301
+ "send",
1302
+ "header",
1303
+ "setHeader",
1304
+ "end"
1305
+ ];
1306
+ function suppressPostSendWrites(res) {
1307
+ for (const key of KEYS) {
1308
+ const original = res[key].bind(res);
1309
+ res[key] = (...args) => res.headersSent ? res : original(...args);
1310
+ }
1311
+ }
1312
+ __name(suppressPostSendWrites, "suppressPostSendWrites");
1313
+
1314
+ // src/middleware/express.middleware.ts
1315
+ function _ts_decorate6(decorators, target, key, desc) {
1316
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1317
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1318
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1319
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1320
+ }
1321
+ __name(_ts_decorate6, "_ts_decorate");
1322
+ function _ts_metadata5(k, v) {
1323
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1324
+ }
1325
+ __name(_ts_metadata5, "_ts_metadata");
1326
+ function _ts_param5(paramIndex, decorator) {
1327
+ return function(target, key) {
1328
+ decorator(target, key, paramIndex);
1329
+ };
1330
+ }
1331
+ __name(_ts_param5, "_ts_param");
1332
+ var InertiaMiddleware = class {
1333
+ static {
1334
+ __name(this, "InertiaMiddleware");
1335
+ }
1336
+ assetVersion;
1337
+ manifest;
1338
+ options;
1339
+ shellRenderer;
1340
+ ssrLoader;
1341
+ constructor(assetVersion, manifest, options, shellRenderer, ssrLoader) {
1342
+ this.assetVersion = assetVersion;
1343
+ this.manifest = manifest;
1344
+ this.options = options;
1345
+ this.shellRenderer = shellRenderer;
1346
+ this.ssrLoader = ssrLoader;
1347
+ }
1348
+ use(req, res, next) {
1349
+ const adaptedReq = expressAdapter.adaptRequest(req);
1350
+ const adaptedRes = expressAdapter.adaptResponse(res);
1351
+ req.inertia = new InertiaService(adaptedReq, adaptedRes, {
1352
+ assetVersion: this.assetVersion,
1353
+ manifest: this.manifest,
1354
+ ssrLoader: this.ssrLoader,
1355
+ rootViewRender: /* @__PURE__ */ __name((ctx) => this.shellRenderer.render(ctx), "rootViewRender"),
1356
+ moduleShare: this.options.share,
1357
+ featureShare: void 0,
1358
+ historyEncryptionDefault: this.options.historyEncryption?.default ?? false,
1359
+ flashStore: this.options.flashStore
1360
+ });
1361
+ suppressPostSendWrites(res);
1362
+ next();
1363
+ }
1364
+ };
1365
+ InertiaMiddleware = _ts_decorate6([
1366
+ (0, import_common10.Injectable)(),
1367
+ _ts_param5(0, (0, import_common10.Inject)(INERTIA_ASSET_VERSION)),
1368
+ _ts_param5(1, (0, import_common10.Inject)(INERTIA_MANIFEST)),
1369
+ _ts_param5(2, (0, import_common10.Inject)(INERTIA_MODULE_OPTIONS)),
1370
+ _ts_param5(3, (0, import_common10.Inject)("INERTIA_SHELL_RENDERER")),
1371
+ _ts_param5(4, (0, import_common10.Inject)("INERTIA_SSR_LOADER")),
1372
+ _ts_metadata5("design:type", Function),
1373
+ _ts_metadata5("design:paramtypes", [
1374
+ String,
1375
+ Object,
1376
+ typeof InertiaModuleOptions === "undefined" ? Object : InertiaModuleOptions,
1377
+ typeof ShellRenderer === "undefined" ? Object : ShellRenderer,
1378
+ typeof SsrLoader === "undefined" ? Object : SsrLoader
1379
+ ])
1380
+ ], InertiaMiddleware);
1381
+
1382
+ // src/middleware/fastify.middleware.ts
1383
+ function registerFastifyInertia(app, depsFactory) {
1384
+ const appAsAny = app;
1385
+ if (appAsAny._inertiaRegistered) return;
1386
+ appAsAny._inertiaRegistered = true;
1387
+ app.decorateRequest("inertia", null);
1388
+ app.addHook("onRequest", async (req, reply) => {
1389
+ const adaptedReq = fastifyAdapter.adaptRequest(req);
1390
+ const adaptedRes = fastifyAdapter.adaptResponse(reply);
1391
+ req.inertia = new InertiaService(adaptedReq, adaptedRes, depsFactory());
1392
+ });
1393
+ }
1394
+ __name(registerFastifyInertia, "registerFastifyInertia");
1395
+
1396
+ // src/shell/file-shell.renderer.ts
1397
+ var import_node_fs2 = require("fs");
1398
+ var import_node_path2 = require("path");
1399
+ init_exceptions();
1400
+
1401
+ // src/shell/directives.ts
1402
+ var VITE_REFRESH_PREAMBLE = `<script type="module">
1403
+ import RefreshRuntime from "/@react-refresh"
1404
+ RefreshRuntime.injectIntoGlobalHook(window)
1405
+ window.$RefreshReg$ = () => {}
1406
+ window.$RefreshSig$ = () => (type) => type
1407
+ window.__vite_plugin_react_preamble_installed__ = true
1408
+ </script>`;
1409
+ function processDirectives(template, ctx) {
1410
+ let out = template;
1411
+ out = out.replace(/@inertiaHead\b/g, () => ctx.ssrHead);
1412
+ out = out.replace(/@inertia(?![a-zA-Z(])/g, () => {
1413
+ if (ctx.ssrBody) return ctx.ssrBody;
1414
+ return `<div id="app"></div>
1415
+ <script id="inertia-page" type="application/json">${ctx.pageJson}</script>`;
1416
+ });
1417
+ out = out.replace(/@viteRefresh\b/g, () => ctx.isDev ? VITE_REFRESH_PREAMBLE : "");
1418
+ out = out.replace(/@vite\(\s*['"]([^'"]+)['"]\s*\)/g, (_full, entry) => {
1419
+ if (ctx.isDev) {
1420
+ return `<script type="module" src="/@vite/client"></script>
1421
+ <script type="module" src="/${entry}"></script>`;
1422
+ }
1423
+ const entryRecord = ctx.manifest?.[entry];
1424
+ if (!entryRecord) {
1425
+ throw new Error(`[nestjs-inertia] manifest entry not found for "${entry}"`);
1426
+ }
1427
+ const scriptTag = `<script type="module" src="/${entryRecord.file}"></script>`;
1428
+ const cssTags = (entryRecord.css ?? []).map((href) => `<link rel="stylesheet" href="/${href}" />`).join("\n");
1429
+ return [
1430
+ scriptTag,
1431
+ cssTags
1432
+ ].filter(Boolean).join("\n");
1433
+ });
1434
+ out = out.replace(/@asset\(\s*['"]([^'"]+)['"]\s*\)/g, (_full, path) => {
1435
+ if (ctx.isDev) return `/${path}`;
1436
+ const entry = ctx.manifest?.[path];
1437
+ return entry ? `/${entry.file}` : `/${path}`;
1438
+ });
1439
+ return out;
1440
+ }
1441
+ __name(processDirectives, "processDirectives");
1442
+
1443
+ // src/shell/serialize-page.ts
1444
+ var LS = "\u2028";
1445
+ var PS = "\u2029";
1446
+ var UNSAFE_CHARS = new RegExp(`[<>&${LS}${PS}]`, "g");
1447
+ function serializePageData(page) {
1448
+ return JSON.stringify(page).replace(UNSAFE_CHARS, (c) => {
1449
+ switch (c) {
1450
+ case "<":
1451
+ return "\\u003c";
1452
+ case ">":
1453
+ return "\\u003e";
1454
+ case "&":
1455
+ return "\\u0026";
1456
+ case LS:
1457
+ return "\\u2028";
1458
+ case PS:
1459
+ return "\\u2029";
1460
+ default:
1461
+ return c;
1462
+ }
1463
+ });
1464
+ }
1465
+ __name(serializePageData, "serializePageData");
1466
+
1467
+ // src/shell/template-engine.registry.ts
1468
+ init_exceptions();
1469
+ var registry = {
1470
+ ".hbs": /* @__PURE__ */ __name(() => Promise.resolve().then(() => (init_handlebars_adapter(), handlebars_adapter_exports)).then((m) => m.handlebarsAdapter), ".hbs"),
1471
+ ".handlebars": /* @__PURE__ */ __name(() => Promise.resolve().then(() => (init_handlebars_adapter(), handlebars_adapter_exports)).then((m) => m.handlebarsAdapter), ".handlebars"),
1472
+ ".ejs": /* @__PURE__ */ __name(() => Promise.resolve().then(() => (init_ejs_adapter(), ejs_adapter_exports)).then((m) => m.ejsAdapter), ".ejs"),
1473
+ ".pug": /* @__PURE__ */ __name(() => Promise.resolve().then(() => (init_pug_adapter(), pug_adapter_exports)).then((m) => m.pugAdapter), ".pug"),
1474
+ ".liquid": /* @__PURE__ */ __name(() => Promise.resolve().then(() => (init_liquid_adapter(), liquid_adapter_exports)).then((m) => m.liquidAdapter), ".liquid"),
1475
+ ".liquidjs": /* @__PURE__ */ __name(() => Promise.resolve().then(() => (init_liquid_adapter(), liquid_adapter_exports)).then((m) => m.liquidAdapter), ".liquidjs")
1476
+ };
1477
+ async function resolveTemplateEngine(extension) {
1478
+ const loader = registry[extension.toLowerCase()];
1479
+ if (!loader) {
1480
+ throw new UnsupportedRootViewExtensionException(extension);
1481
+ }
1482
+ return loader();
1483
+ }
1484
+ __name(resolveTemplateEngine, "resolveTemplateEngine");
1485
+
1486
+ // src/shell/file-shell.renderer.ts
1487
+ var PLAIN_HTML = /* @__PURE__ */ new Set([
1488
+ ".html",
1489
+ ".htm"
1490
+ ]);
1491
+ var TEMPLATE_EXTENSIONS = /* @__PURE__ */ new Set([
1492
+ ".hbs",
1493
+ ".handlebars",
1494
+ ".ejs",
1495
+ ".pug",
1496
+ ".liquid",
1497
+ ".liquidjs"
1498
+ ]);
1499
+ var FileBasedShellRenderer = class {
1500
+ static {
1501
+ __name(this, "FileBasedShellRenderer");
1502
+ }
1503
+ cachedTemplate = null;
1504
+ engineRenderer = null;
1505
+ adapterPromise = null;
1506
+ absPath;
1507
+ ext;
1508
+ constructor(rootViewPath) {
1509
+ const ext = (0, import_node_path2.extname)(rootViewPath).toLowerCase();
1510
+ if (!PLAIN_HTML.has(ext) && !TEMPLATE_EXTENSIONS.has(ext)) {
1511
+ throw new UnsupportedRootViewExtensionException(ext);
1512
+ }
1513
+ this.ext = ext;
1514
+ this.absPath = (0, import_node_path2.isAbsolute)(rootViewPath) ? rootViewPath : (0, import_node_path2.resolve)(process.cwd(), rootViewPath);
1515
+ }
1516
+ async render(ctx) {
1517
+ if (this.cachedTemplate === null) {
1518
+ this.cachedTemplate = (0, import_node_fs2.readFileSync)(this.absPath, "utf8");
1519
+ }
1520
+ const pageJson = serializePageData(ctx.page);
1521
+ const ssrHead = ctx.ssr?.head.join("\n") ?? "";
1522
+ const ssrBody = ctx.ssr?.body ?? null;
1523
+ const isDev = process.env.NODE_ENV !== "production";
1524
+ const manifest = ctx.manifest;
1525
+ if (PLAIN_HTML.has(this.ext)) {
1526
+ return processDirectives(this.cachedTemplate, {
1527
+ pageJson,
1528
+ ssrHead,
1529
+ ssrBody,
1530
+ manifest,
1531
+ isDev
1532
+ });
1533
+ }
1534
+ if (this.adapterPromise === null) {
1535
+ this.adapterPromise = resolveTemplateEngine(this.ext);
1536
+ }
1537
+ if (this.engineRenderer === null) {
1538
+ const adapter = await this.adapterPromise;
1539
+ this.engineRenderer = adapter.compile(this.cachedTemplate, this.absPath);
1540
+ }
1541
+ const inertiaHtml = ssrBody ?? `<div id="app"></div>
1542
+ <script id="inertia-page" type="application/json">${pageJson}</script>`;
1543
+ const directiveCtx = {
1544
+ pageJson,
1545
+ ssrHead,
1546
+ ssrBody,
1547
+ manifest,
1548
+ isDev
1549
+ };
1550
+ const locals = {
1551
+ page: ctx.page,
1552
+ inertia: inertiaHtml,
1553
+ inertiaHead: ssrHead,
1554
+ vite: /* @__PURE__ */ __name((entry) => processDirectives(`@vite('${entry}')`, directiveCtx), "vite"),
1555
+ viteRefresh: processDirectives("@viteRefresh", directiveCtx),
1556
+ asset: /* @__PURE__ */ __name((p) => processDirectives(`@asset('${p}')`, directiveCtx), "asset")
1557
+ };
1558
+ let output = await this.engineRenderer(locals);
1559
+ output = processDirectives(output, directiveCtx);
1560
+ return output;
1561
+ }
1562
+ };
1563
+
1564
+ // src/shell/shell.ts
1565
+ var DefaultShellRenderer = class {
1566
+ static {
1567
+ __name(this, "DefaultShellRenderer");
1568
+ }
1569
+ async render(ctx) {
1570
+ const pageJson = serializePageData(ctx.page);
1571
+ return `<!doctype html>
1572
+ <html lang="en">
1573
+ <head>
1574
+ <meta charset="utf-8" />
1575
+ <title>Inertia</title>
1576
+ </head>
1577
+ <body>
1578
+ <div id="app"></div>
1579
+ <script id="inertia-page" type="application/json">${pageJson}</script>
1580
+ </body>
1581
+ </html>`;
1582
+ }
1583
+ };
1584
+
1585
+ // src/ssr/ssr-loader.service.ts
1586
+ var import_node_fs3 = require("fs");
1587
+ var import_node_path3 = require("path");
1588
+ var import_node_url = require("url");
1589
+ var import_common11 = require("@nestjs/common");
1590
+ function _ts_decorate7(decorators, target, key, desc) {
1591
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1592
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1593
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1594
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1595
+ }
1596
+ __name(_ts_decorate7, "_ts_decorate");
1597
+ function _ts_metadata6(k, v) {
1598
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1599
+ }
1600
+ __name(_ts_metadata6, "_ts_metadata");
1601
+ function _ts_param6(paramIndex, decorator) {
1602
+ return function(target, key) {
1603
+ decorator(target, key, paramIndex);
1604
+ };
1605
+ }
1606
+ __name(_ts_param6, "_ts_param");
1607
+ function isVitest() {
1608
+ return process.env.VITEST === "true" || process.env.NODE_ENV === "test";
1609
+ }
1610
+ __name(isVitest, "isVitest");
1611
+ var SsrLoaderService = class _SsrLoaderService {
1612
+ static {
1613
+ __name(this, "SsrLoaderService");
1614
+ }
1615
+ opts;
1616
+ logger = new import_common11.Logger(_SsrLoaderService.name);
1617
+ cached = null;
1618
+ failed = false;
1619
+ constructor(opts) {
1620
+ this.opts = opts;
1621
+ }
1622
+ async load() {
1623
+ if (!this.opts.ssr?.enabled) return null;
1624
+ if (this.cached) return this.cached;
1625
+ if (this.failed) return null;
1626
+ try {
1627
+ const bundlePath = (0, import_node_path3.resolve)(process.cwd(), this.opts.ssr.bundlePath ?? "dist/inertia/ssr/ssr.mjs");
1628
+ let mod;
1629
+ if (isVitest()) {
1630
+ const code = (0, import_node_fs3.readFileSync)(bundlePath, "utf8");
1631
+ const dataUrl = `data:text/javascript;base64,${Buffer.from(code, "utf8").toString("base64")}`;
1632
+ mod = await import(
1633
+ /* @vite-ignore */
1634
+ dataUrl
1635
+ );
1636
+ } else {
1637
+ const fileUrl = (0, import_node_url.pathToFileURL)(bundlePath).href;
1638
+ mod = await import(
1639
+ /* @vite-ignore */
1640
+ fileUrl
1641
+ );
1642
+ }
1643
+ if (mod.default && typeof mod.default.render === "function") {
1644
+ this.cached = mod.default;
1645
+ } else if (typeof mod.render === "function") {
1646
+ this.cached = {
1647
+ render: mod.render
1648
+ };
1649
+ } else {
1650
+ if (this.opts.ssr.throwOnError) throw new Error("SSR bundle exports neither default nor render()");
1651
+ this.failed = true;
1652
+ this.logger.warn("SSR bundle missing required exports; falling back to CSR.");
1653
+ return null;
1654
+ }
1655
+ return this.cached;
1656
+ } catch (err) {
1657
+ this.failed = true;
1658
+ if (this.opts.ssr.throwOnError) throw err;
1659
+ this.logger.warn(`SSR bundle not loaded, falling back to CSR: ${err.message}`);
1660
+ return null;
1661
+ }
1662
+ }
1663
+ };
1664
+ SsrLoaderService = _ts_decorate7([
1665
+ (0, import_common11.Injectable)(),
1666
+ _ts_param6(0, (0, import_common11.Inject)(INERTIA_MODULE_OPTIONS)),
1667
+ _ts_metadata6("design:type", Function),
1668
+ _ts_metadata6("design:paramtypes", [
1669
+ typeof InertiaModuleOptions === "undefined" ? Object : InertiaModuleOptions
1670
+ ])
1671
+ ], SsrLoaderService);
1672
+
1673
+ // src/module.ts
1674
+ function _ts_decorate8(decorators, target, key, desc) {
1675
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1676
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1677
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1678
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1679
+ }
1680
+ __name(_ts_decorate8, "_ts_decorate");
1681
+ function _ts_metadata7(k, v) {
1682
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1683
+ }
1684
+ __name(_ts_metadata7, "_ts_metadata");
1685
+ function _ts_param7(paramIndex, decorator) {
1686
+ return function(target, key) {
1687
+ decorator(target, key, paramIndex);
1688
+ };
1689
+ }
1690
+ __name(_ts_param7, "_ts_param");
1691
+ var InertiaModule = class _InertiaModule {
1692
+ static {
1693
+ __name(this, "InertiaModule");
1694
+ }
1695
+ httpAdapterHost;
1696
+ options;
1697
+ assetVersion;
1698
+ manifest;
1699
+ shellRenderer;
1700
+ ssrLoader;
1701
+ /**
1702
+ * Shared provider set for both `forRoot` and `forRootAsync`.
1703
+ * Does NOT include the options provider(s) — callers prepend those themselves.
1704
+ */
1705
+ static buildModuleProviders() {
1706
+ const shellProvider = {
1707
+ provide: "INERTIA_SHELL_RENDERER",
1708
+ inject: [
1709
+ INERTIA_MODULE_OPTIONS
1710
+ ],
1711
+ useFactory: /* @__PURE__ */ __name((opts) => {
1712
+ const rv = opts.rootView;
1713
+ if (typeof rv === "function") {
1714
+ const fn = rv;
1715
+ return {
1716
+ render: /* @__PURE__ */ __name(async (ctx) => fn(ctx), "render")
1717
+ };
1718
+ }
1719
+ if (typeof rv === "string") {
1720
+ return new FileBasedShellRenderer(rv);
1721
+ }
1722
+ return new DefaultShellRenderer();
1723
+ }, "useFactory")
1724
+ };
1725
+ const ssrProvider = {
1726
+ provide: "INERTIA_SSR_LOADER",
1727
+ useClass: SsrLoaderService
1728
+ };
1729
+ return [
1730
+ manifestProvider,
1731
+ assetVersionProvider,
1732
+ shellProvider,
1733
+ ssrProvider,
1734
+ InertiaMiddleware,
1735
+ MethodSpoofMiddleware,
1736
+ {
1737
+ provide: import_core3.APP_INTERCEPTOR,
1738
+ useClass: InertiaScopeSwitcherInterceptor
1739
+ },
1740
+ {
1741
+ provide: import_core3.APP_INTERCEPTOR,
1742
+ useClass: InertiaRenderInterceptor
1743
+ },
1744
+ {
1745
+ provide: import_core3.APP_INTERCEPTOR,
1746
+ useClass: RedirectInterceptor
1747
+ }
1748
+ ];
1749
+ }
1750
+ static moduleExports = [
1751
+ INERTIA_MODULE_OPTIONS,
1752
+ INERTIA_MANIFEST,
1753
+ INERTIA_ASSET_VERSION,
1754
+ "INERTIA_SHELL_RENDERER",
1755
+ "INERTIA_SSR_LOADER",
1756
+ InertiaMiddleware
1757
+ ];
1758
+ static forRoot(options = {}) {
1759
+ const optionsProvider = {
1760
+ provide: INERTIA_MODULE_OPTIONS,
1761
+ useValue: options
1762
+ };
1763
+ return {
1764
+ module: _InertiaModule,
1765
+ global: true,
1766
+ providers: [
1767
+ optionsProvider,
1768
+ ..._InertiaModule.buildModuleProviders()
1769
+ ],
1770
+ exports: [
1771
+ ..._InertiaModule.moduleExports
1772
+ ]
1773
+ };
1774
+ }
1775
+ static forRootAsync(asyncOptions) {
1776
+ _InertiaModule.validateAsyncOptions(asyncOptions);
1777
+ const optionsProviders = _InertiaModule.createAsyncOptionsProviders(asyncOptions);
1778
+ const injectProviders = (asyncOptions.inject ?? []).filter((token) => typeof token === "function").map((token) => token);
1779
+ return {
1780
+ module: _InertiaModule,
1781
+ global: true,
1782
+ imports: asyncOptions.imports ?? [],
1783
+ providers: [
1784
+ ...injectProviders,
1785
+ ...optionsProviders,
1786
+ ..._InertiaModule.buildModuleProviders()
1787
+ ],
1788
+ exports: [
1789
+ ..._InertiaModule.moduleExports
1790
+ ]
1791
+ };
1792
+ }
1793
+ static forFeature(options) {
1794
+ assertScopeNotReserved(options.scope);
1795
+ const optionsProvider = {
1796
+ provide: featureToken("OPTIONS", options.scope),
1797
+ useValue: options
1798
+ };
1799
+ return {
1800
+ module: _InertiaModule,
1801
+ global: true,
1802
+ providers: [
1803
+ optionsProvider,
1804
+ ..._InertiaModule.createFeatureProviders(options.scope)
1805
+ ],
1806
+ exports: [
1807
+ featureToken("OPTIONS", options.scope),
1808
+ featureToken("MANIFEST", options.scope),
1809
+ featureToken("ASSET_VERSION", options.scope),
1810
+ featureToken("SHELL_RENDERER", options.scope),
1811
+ featureToken("SSR_LOADER", options.scope)
1812
+ ]
1813
+ };
1814
+ }
1815
+ static forFeatureAsync(asyncOptions) {
1816
+ assertScopeNotReserved(asyncOptions.scope);
1817
+ const has = /* @__PURE__ */ __name((k) => asyncOptions[k] !== void 0, "has");
1818
+ const declared = [
1819
+ has("useFactory"),
1820
+ has("useClass"),
1821
+ has("useExisting")
1822
+ ].filter(Boolean).length;
1823
+ if (declared === 0) {
1824
+ throw new InvalidInertiaConfigException("forFeatureAsync requires one of: useFactory, useClass, useExisting");
1825
+ }
1826
+ if (declared > 1) {
1827
+ throw new InvalidInertiaConfigException("forFeatureAsync accepts exactly one of: useFactory, useClass, useExisting (got multiple)");
1828
+ }
1829
+ const scope = asyncOptions.scope;
1830
+ const optionsToken = featureToken("OPTIONS", scope);
1831
+ const injectProviders = (asyncOptions.inject ?? []).filter((token) => typeof token === "function").map((token) => token);
1832
+ let optionsProviders;
1833
+ if (asyncOptions.useFactory) {
1834
+ optionsProviders = [
1835
+ {
1836
+ provide: optionsToken,
1837
+ useFactory: /* @__PURE__ */ __name(async (...args) => {
1838
+ const opts = await asyncOptions.useFactory(...args);
1839
+ return {
1840
+ ...opts,
1841
+ scope
1842
+ };
1843
+ }, "useFactory"),
1844
+ inject: asyncOptions.inject ?? []
1845
+ }
1846
+ ];
1847
+ } else if (asyncOptions.useClass) {
1848
+ optionsProviders = [
1849
+ asyncOptions.useClass,
1850
+ {
1851
+ provide: optionsToken,
1852
+ useFactory: /* @__PURE__ */ __name(async (factory) => ({
1853
+ ...await factory.createInertiaOptions(),
1854
+ scope
1855
+ }), "useFactory"),
1856
+ inject: [
1857
+ asyncOptions.useClass
1858
+ ]
1859
+ }
1860
+ ];
1861
+ } else if (asyncOptions.useExisting) {
1862
+ optionsProviders = [
1863
+ {
1864
+ provide: optionsToken,
1865
+ useFactory: /* @__PURE__ */ __name(async (factory) => ({
1866
+ ...await factory.createInertiaOptions(),
1867
+ scope
1868
+ }), "useFactory"),
1869
+ inject: [
1870
+ asyncOptions.useExisting
1871
+ ]
1872
+ }
1873
+ ];
1874
+ } else {
1875
+ optionsProviders = [];
1876
+ }
1877
+ return {
1878
+ module: _InertiaModule,
1879
+ global: true,
1880
+ imports: asyncOptions.imports ?? [],
1881
+ providers: [
1882
+ ...injectProviders,
1883
+ ...optionsProviders,
1884
+ ..._InertiaModule.createFeatureProviders(scope)
1885
+ ],
1886
+ exports: [
1887
+ optionsToken,
1888
+ featureToken("MANIFEST", scope),
1889
+ featureToken("ASSET_VERSION", scope),
1890
+ featureToken("SHELL_RENDERER", scope),
1891
+ featureToken("SSR_LOADER", scope)
1892
+ ]
1893
+ };
1894
+ }
1895
+ static createFeatureProviders(scope) {
1896
+ return [
1897
+ {
1898
+ provide: featureToken("MANIFEST", scope),
1899
+ inject: [
1900
+ featureToken("OPTIONS", scope)
1901
+ ],
1902
+ useFactory: /* @__PURE__ */ __name((opts) => {
1903
+ if (process.env.NODE_ENV !== "production") return null;
1904
+ return loadManifest(opts.vite?.manifestPath ?? "dist/inertia/client/.vite/manifest.json");
1905
+ }, "useFactory")
1906
+ },
1907
+ {
1908
+ provide: featureToken("ASSET_VERSION", scope),
1909
+ inject: [
1910
+ featureToken("MANIFEST", scope),
1911
+ featureToken("OPTIONS", scope)
1912
+ ],
1913
+ useFactory: /* @__PURE__ */ __name(async (manifest, opts) => {
1914
+ if (opts.version !== void 0) {
1915
+ return typeof opts.version === "function" ? await opts.version() : opts.version;
1916
+ }
1917
+ return computeAssetVersion(manifest);
1918
+ }, "useFactory")
1919
+ },
1920
+ {
1921
+ provide: featureToken("SHELL_RENDERER", scope),
1922
+ inject: [
1923
+ featureToken("OPTIONS", scope)
1924
+ ],
1925
+ useFactory: /* @__PURE__ */ __name((opts) => {
1926
+ const rv = opts.rootView;
1927
+ if (typeof rv === "function") {
1928
+ const fn = rv;
1929
+ return {
1930
+ render: /* @__PURE__ */ __name(async (ctx) => fn(ctx), "render")
1931
+ };
1932
+ }
1933
+ if (typeof rv === "string") {
1934
+ return new FileBasedShellRenderer(rv);
1935
+ }
1936
+ return new DefaultShellRenderer();
1937
+ }, "useFactory")
1938
+ },
1939
+ {
1940
+ provide: featureToken("SSR_LOADER", scope),
1941
+ inject: [
1942
+ featureToken("OPTIONS", scope)
1943
+ ],
1944
+ useFactory: /* @__PURE__ */ __name((opts) => new SsrLoaderService(opts), "useFactory")
1945
+ }
1946
+ ];
1947
+ }
1948
+ static validateAsyncOptions(asyncOptions) {
1949
+ const has = /* @__PURE__ */ __name((k) => asyncOptions[k] !== void 0, "has");
1950
+ const declared = [
1951
+ has("useFactory"),
1952
+ has("useClass"),
1953
+ has("useExisting")
1954
+ ].filter(Boolean).length;
1955
+ if (declared === 0) {
1956
+ throw new InvalidInertiaConfigException("forRootAsync requires one of: useFactory, useClass, useExisting");
1957
+ }
1958
+ if (declared > 1) {
1959
+ throw new InvalidInertiaConfigException("forRootAsync accepts exactly one of: useFactory, useClass, useExisting (got multiple)");
1960
+ }
1961
+ }
1962
+ static createAsyncOptionsProviders(asyncOptions) {
1963
+ if (asyncOptions.useFactory) {
1964
+ return [
1965
+ {
1966
+ provide: INERTIA_MODULE_OPTIONS,
1967
+ useFactory: asyncOptions.useFactory,
1968
+ inject: asyncOptions.inject ?? []
1969
+ }
1970
+ ];
1971
+ }
1972
+ if (asyncOptions.useClass) {
1973
+ return [
1974
+ asyncOptions.useClass,
1975
+ {
1976
+ provide: INERTIA_MODULE_OPTIONS,
1977
+ useFactory: /* @__PURE__ */ __name(async (factory) => factory.createInertiaOptions(), "useFactory"),
1978
+ inject: [
1979
+ asyncOptions.useClass
1980
+ ]
1981
+ }
1982
+ ];
1983
+ }
1984
+ return [
1985
+ asyncOptions.useExisting,
1986
+ {
1987
+ provide: INERTIA_MODULE_OPTIONS,
1988
+ useFactory: /* @__PURE__ */ __name(async (factory) => factory.createInertiaOptions(), "useFactory"),
1989
+ inject: [
1990
+ asyncOptions.useExisting
1991
+ ]
1992
+ }
1993
+ ];
1994
+ }
1995
+ logger = new import_common12.Logger(_InertiaModule.name);
1996
+ codegenWatcher = null;
1997
+ constructor(httpAdapterHost, options, assetVersion, manifest, shellRenderer, ssrLoader) {
1998
+ this.httpAdapterHost = httpAdapterHost;
1999
+ this.options = options;
2000
+ this.assetVersion = assetVersion;
2001
+ this.manifest = manifest;
2002
+ this.shellRenderer = shellRenderer;
2003
+ this.ssrLoader = ssrLoader;
2004
+ }
2005
+ /**
2006
+ * Test seam: override in a subclass or via `Object.defineProperty` to inject a stub
2007
+ * codegen module without touching NestJS DI. Production callers never touch this.
2008
+ *
2009
+ * @internal
2010
+ */
2011
+ _resolveCodegenModule() {
2012
+ const dynamicImport = new Function("s", "return import(s)");
2013
+ return dynamicImport("@dudousxd/nestjs-inertia-codegen");
2014
+ }
2015
+ async onApplicationBootstrap() {
2016
+ const adapter = this.httpAdapterHost.httpAdapter;
2017
+ if (adapter) {
2018
+ const platform = adapter.getType();
2019
+ if (platform === "fastify") {
2020
+ const fastifyApp = adapter.getInstance();
2021
+ registerFastifyInertia(fastifyApp, () => ({
2022
+ assetVersion: this.assetVersion,
2023
+ manifest: this.manifest,
2024
+ ssrLoader: this.ssrLoader,
2025
+ rootViewRender: /* @__PURE__ */ __name((ctx) => this.shellRenderer.render(ctx), "rootViewRender"),
2026
+ moduleShare: this.options.share,
2027
+ featureShare: void 0,
2028
+ historyEncryptionDefault: this.options.historyEncryption?.default ?? false,
2029
+ flashStore: this.options.flashStore
2030
+ }));
2031
+ const { registerFastifyMethodSpoof: registerFastifyMethodSpoof2 } = await Promise.resolve().then(() => (init_fastify_method_spoof_middleware(), fastify_method_spoof_middleware_exports));
2032
+ registerFastifyMethodSpoof2(fastifyApp, this.options);
2033
+ }
2034
+ }
2035
+ await this._startCodegenWatcher();
2036
+ }
2037
+ /**
2038
+ * Auto-starts the codegen file watcher in dev mode.
2039
+ *
2040
+ * Rules (all must pass for the watcher to start):
2041
+ * 1. `process.env.NODE_ENV !== 'production'`
2042
+ * 2. `options.codegen?.enabled !== false`
2043
+ * 3. `@dudousxd/nestjs-inertia-codegen` is resolvable (peer-optional)
2044
+ * 4. A `nestjs-inertia.config.ts` (or equivalent) is present in `process.cwd()`
2045
+ *
2046
+ * If the CLI watcher already holds the lock file, the codegen package returns a
2047
+ * no-op watcher — no conflict occurs.
2048
+ *
2049
+ * This method NEVER throws; any unexpected error is logged as a warning.
2050
+ */
2051
+ async _startCodegenWatcher() {
2052
+ try {
2053
+ if (process.env.NODE_ENV === "production") return;
2054
+ if (process.env.NESTJS_INERTIA_DISABLE_AUTO_CODEGEN === "1") return;
2055
+ if (this.options.codegen?.enabled === false) return;
2056
+ let codegen;
2057
+ try {
2058
+ codegen = await this._resolveCodegenModule();
2059
+ } catch (err) {
2060
+ const message = err instanceof Error ? err.message : String(err);
2061
+ this.logger.warn(`Codegen auto-watch: failed to import @dudousxd/nestjs-inertia-codegen: ${message}`);
2062
+ return;
2063
+ }
2064
+ let config;
2065
+ try {
2066
+ config = await codegen.loadConfig(process.cwd());
2067
+ } catch (err) {
2068
+ const message = err instanceof Error ? err.message : String(err);
2069
+ this.logger.warn(`Codegen auto-watch: failed to load config: ${message}`);
2070
+ return;
2071
+ }
2072
+ this.codegenWatcher = await codegen.watch(config);
2073
+ this.logger.log("Codegen auto-watch started (dev mode).");
2074
+ } catch (err) {
2075
+ const message = err instanceof Error ? err.message : String(err);
2076
+ this.logger.warn(`Codegen auto-watch failed to start: ${message}. Install @dudousxd/nestjs-inertia-codegen and add nestjs-inertia.config.ts to enable auto-watch, or set codegen: { enabled: false } to suppress this warning.`);
2077
+ }
2078
+ }
2079
+ async onApplicationShutdown() {
2080
+ await this.codegenWatcher?.close();
2081
+ this.codegenWatcher = null;
2082
+ }
2083
+ configure(consumer) {
2084
+ const adapter = this.httpAdapterHost.httpAdapter;
2085
+ if (!adapter || adapter.getType() === "express") {
2086
+ consumer.apply(MethodSpoofMiddleware).forRoutes({
2087
+ path: "{*path}",
2088
+ method: import_common12.RequestMethod.ALL
2089
+ });
2090
+ consumer.apply(InertiaMiddleware).forRoutes({
2091
+ path: "{*path}",
2092
+ method: import_common12.RequestMethod.ALL
2093
+ });
2094
+ }
2095
+ }
2096
+ };
2097
+ InertiaModule = _ts_decorate8([
2098
+ (0, import_common12.Module)({}),
2099
+ _ts_param7(0, (0, import_common12.Inject)(import_core3.HttpAdapterHost)),
2100
+ _ts_param7(1, (0, import_common12.Inject)(INERTIA_MODULE_OPTIONS)),
2101
+ _ts_param7(2, (0, import_common12.Inject)(INERTIA_ASSET_VERSION)),
2102
+ _ts_param7(3, (0, import_common12.Inject)(INERTIA_MANIFEST)),
2103
+ _ts_param7(4, (0, import_common12.Inject)("INERTIA_SHELL_RENDERER")),
2104
+ _ts_param7(5, (0, import_common12.Inject)("INERTIA_SSR_LOADER")),
2105
+ _ts_metadata7("design:type", Function),
2106
+ _ts_metadata7("design:paramtypes", [
2107
+ typeof import_core3.HttpAdapterHost === "undefined" ? Object : import_core3.HttpAdapterHost,
2108
+ typeof InertiaModuleOptions === "undefined" ? Object : InertiaModuleOptions,
2109
+ String,
2110
+ Object,
2111
+ typeof ShellRenderer === "undefined" ? Object : ShellRenderer,
2112
+ Object
2113
+ ])
2114
+ ], InertiaModule);
2115
+
2116
+ // src/csrf/csrf-cookie.interceptor.ts
2117
+ var import_common13 = require("@nestjs/common");
2118
+
2119
+ // src/csrf/csrf-token.ts
2120
+ var import_node_crypto2 = require("crypto");
2121
+ function generateCsrfToken(secret, context) {
2122
+ const raw = (0, import_node_crypto2.randomBytes)(32).toString("base64url");
2123
+ if (context !== void 0 && context !== "") {
2124
+ const ctx = Buffer.from(context).toString("hex");
2125
+ const sig2 = (0, import_node_crypto2.createHmac)("sha256", secret).update(`${raw}:${context}`).digest("base64url");
2126
+ return `${raw}.${ctx}.${sig2}`;
2127
+ }
2128
+ const sig = (0, import_node_crypto2.createHmac)("sha256", secret).update(raw).digest("base64url");
2129
+ return `${raw}.${sig}`;
2130
+ }
2131
+ __name(generateCsrfToken, "generateCsrfToken");
2132
+ function timingSafeEqualSafe(a, b) {
2133
+ if (a.byteLength !== b.byteLength) return false;
2134
+ return (0, import_node_crypto2.timingSafeEqual)(a, b);
2135
+ }
2136
+ __name(timingSafeEqualSafe, "timingSafeEqualSafe");
2137
+ function verifyCsrfToken(token, secret, context) {
2138
+ if (typeof token !== "string") return false;
2139
+ const parts = token.split(".");
2140
+ if (parts.length === 3) {
2141
+ const [raw, ctxHex, sig] = parts;
2142
+ if (!raw || !ctxHex || !sig) return false;
2143
+ let storedContext;
2144
+ try {
2145
+ storedContext = Buffer.from(ctxHex, "hex").toString();
2146
+ } catch {
2147
+ return false;
2148
+ }
2149
+ if (context !== void 0 && context !== "" && storedContext !== context) return false;
2150
+ const expectedContext = context !== void 0 && context !== "" ? context : storedContext;
2151
+ const expected = (0, import_node_crypto2.createHmac)("sha256", secret).update(`${raw}:${expectedContext}`).digest("base64url");
2152
+ return timingSafeEqualSafe(Buffer.from(sig), Buffer.from(expected));
2153
+ }
2154
+ if (parts.length === 2) {
2155
+ const [raw, sig] = parts;
2156
+ if (!raw || !sig) return false;
2157
+ if (context !== void 0 && context !== "") return false;
2158
+ const expected = (0, import_node_crypto2.createHmac)("sha256", secret).update(raw).digest("base64url");
2159
+ return timingSafeEqualSafe(Buffer.from(sig), Buffer.from(expected));
2160
+ }
2161
+ return false;
2162
+ }
2163
+ __name(verifyCsrfToken, "verifyCsrfToken");
2164
+
2165
+ // src/csrf/csrf-cookie.interceptor.ts
2166
+ function _ts_decorate9(decorators, target, key, desc) {
2167
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2168
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2169
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2170
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2171
+ }
2172
+ __name(_ts_decorate9, "_ts_decorate");
2173
+ function _ts_metadata8(k, v) {
2174
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2175
+ }
2176
+ __name(_ts_metadata8, "_ts_metadata");
2177
+ function writeCsrfCookie(res, cookieName, token, cookieOpts) {
2178
+ if (typeof res.cookie === "function") {
2179
+ res.cookie(cookieName, token, cookieOpts);
2180
+ } else if (typeof res.setCookie === "function") {
2181
+ res.setCookie(cookieName, token, cookieOpts);
2182
+ }
2183
+ }
2184
+ __name(writeCsrfCookie, "writeCsrfCookie");
2185
+ function rotateCsrfToken(res, options, context) {
2186
+ const cookieName = options.cookieName ?? "XSRF-TOKEN";
2187
+ const token = generateCsrfToken(options.secret, context);
2188
+ const cookieOpts = {
2189
+ httpOnly: options.httpOnly ?? false,
2190
+ sameSite: options.sameSite ?? "lax",
2191
+ secure: options.secure ?? process.env.NODE_ENV === "production",
2192
+ path: "/"
2193
+ };
2194
+ writeCsrfCookie(res, cookieName, token, cookieOpts);
2195
+ }
2196
+ __name(rotateCsrfToken, "rotateCsrfToken");
2197
+ var CsrfCookieInterceptor = class {
2198
+ static {
2199
+ __name(this, "CsrfCookieInterceptor");
2200
+ }
2201
+ options;
2202
+ cookieName;
2203
+ constructor(options) {
2204
+ this.options = options;
2205
+ this.cookieName = options.cookieName ?? "XSRF-TOKEN";
2206
+ }
2207
+ intercept(context, next) {
2208
+ const req = context.switchToHttp().getRequest();
2209
+ const res = context.switchToHttp().getResponse();
2210
+ const ctx = this.options.tokenContext ? this.options.tokenContext(req) : void 0;
2211
+ const existing = req.cookies?.[this.cookieName];
2212
+ if (!existing || !verifyCsrfToken(existing, this.options.secret, ctx)) {
2213
+ rotateCsrfToken(res, this.options, ctx);
2214
+ }
2215
+ return next.handle();
2216
+ }
2217
+ };
2218
+ CsrfCookieInterceptor = _ts_decorate9([
2219
+ (0, import_common13.Injectable)(),
2220
+ _ts_metadata8("design:type", Function),
2221
+ _ts_metadata8("design:paramtypes", [
2222
+ typeof CsrfCookieOptions === "undefined" ? Object : CsrfCookieOptions
2223
+ ])
2224
+ ], CsrfCookieInterceptor);
2225
+
2226
+ // src/csrf/csrf.guard.ts
2227
+ var import_common14 = require("@nestjs/common");
2228
+ init_exceptions();
2229
+ function _ts_decorate10(decorators, target, key, desc) {
2230
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2231
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2232
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2233
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2234
+ }
2235
+ __name(_ts_decorate10, "_ts_decorate");
2236
+ function _ts_metadata9(k, v) {
2237
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
2238
+ }
2239
+ __name(_ts_metadata9, "_ts_metadata");
2240
+ var SAFE = /* @__PURE__ */ new Set([
2241
+ "GET",
2242
+ "HEAD",
2243
+ "OPTIONS"
2244
+ ]);
2245
+ var CsrfGuard = class {
2246
+ static {
2247
+ __name(this, "CsrfGuard");
2248
+ }
2249
+ options;
2250
+ cookieName;
2251
+ headerName;
2252
+ constructor(options) {
2253
+ this.options = options;
2254
+ this.cookieName = options.cookieName ?? "XSRF-TOKEN";
2255
+ this.headerName = (options.headerName ?? "X-XSRF-TOKEN").toLowerCase();
2256
+ }
2257
+ canActivate(ctx) {
2258
+ const req = ctx.switchToHttp().getRequest();
2259
+ if (SAFE.has(req.method)) return true;
2260
+ const cookieToken = req.cookies?.[this.cookieName];
2261
+ const headerRaw = req.headers[this.headerName];
2262
+ const headerToken = Array.isArray(headerRaw) ? headerRaw[0] : headerRaw;
2263
+ if (!cookieToken || !headerToken) throw new InvalidCsrfTokenException();
2264
+ if (!timingSafeEqualSafe(Buffer.from(cookieToken), Buffer.from(headerToken))) {
2265
+ throw new InvalidCsrfTokenException();
2266
+ }
2267
+ const context = this.options.tokenContext ? this.options.tokenContext(req) : void 0;
2268
+ if (!verifyCsrfToken(cookieToken, this.options.secret, context)) throw new InvalidCsrfTokenException();
2269
+ return true;
2270
+ }
2271
+ };
2272
+ CsrfGuard = _ts_decorate10([
2273
+ (0, import_common14.Injectable)(),
2274
+ _ts_metadata9("design:type", Function),
2275
+ _ts_metadata9("design:paramtypes", [
2276
+ typeof CsrfGuardOptions === "undefined" ? Object : CsrfGuardOptions
2277
+ ])
2278
+ ], CsrfGuard);
2279
+
2280
+ // src/index.ts
2281
+ var VERSION = "1.0.0";
2282
+ // Annotate the CommonJS export names for ESM import in node:
2283
+ 0 && (module.exports = {
2284
+ CsrfCookieInterceptor,
2285
+ CsrfGuard,
2286
+ ErrorBagInterceptor,
2287
+ INERTIA_ASSET_VERSION,
2288
+ INERTIA_DEFAULT_SCOPE,
2289
+ INERTIA_FEATURE_OPTIONS,
2290
+ INERTIA_MANIFEST,
2291
+ INERTIA_MODULE_OPTIONS,
2292
+ INERTIA_RENDER_COMPONENT,
2293
+ INERTIA_USE_SCOPE,
2294
+ Inertia,
2295
+ InertiaModule,
2296
+ InertiaRenderInterceptor,
2297
+ InertiaService,
2298
+ InertiaServiceNotAvailableException,
2299
+ InvalidCsrfTokenException,
2300
+ InvalidInertiaConfigException,
2301
+ MethodSpoofMiddleware,
2302
+ MissingCookieDepException,
2303
+ MissingTemplateEngineDepException,
2304
+ RedirectInterceptor,
2305
+ UnsupportedRootViewExtensionException,
2306
+ UseInertia,
2307
+ VERSION,
2308
+ featureToken,
2309
+ generateCsrfToken,
2310
+ rotateCsrfToken,
2311
+ timingSafeEqualSafe,
2312
+ verifyCsrfToken
2313
+ });
2314
+ //# sourceMappingURL=index.cjs.map