@arkstack/common 0.18.12 → 0.19.1

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.
@@ -0,0 +1,3819 @@
1
+ import { createRequire } from "node:module";
2
+ import { createJiti } from "jiti";
3
+ import "@arkstack/contract";
4
+ import { isAbsolute, join, resolve } from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ import { readdir, stat } from "node:fs/promises";
7
+ import { AsyncLocalStorage } from "node:async_hooks";
8
+ import "node:crypto";
9
+ //#region \0rolldown/runtime.js
10
+ var __create = Object.create;
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
+ var __getOwnPropNames = Object.getOwnPropertyNames;
14
+ var __getProtoOf = Object.getPrototypeOf;
15
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
16
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
19
+ key = keys[i];
20
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
21
+ get: ((k) => from[k]).bind(null, key),
22
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
23
+ });
24
+ }
25
+ return to;
26
+ };
27
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
28
+ value: mod,
29
+ enumerable: true
30
+ }) : target, mod));
31
+ //#endregion
32
+ //#region ../../node_modules/.pnpm/clear-router@2.9.3_@h3ravel+support@2.2.7_@types+node@25.6.2_h3@2.0.1-rc.22__express@5._15be2e62531296a83319dbccad2fa4ea/node_modules/clear-router/dist/ClearRequest.mjs
33
+ var ClearRequest = class {
34
+ /**
35
+ * @param body - Parsed request body
36
+ */
37
+ body;
38
+ /**
39
+ * @param query - Parsed query parameters
40
+ */
41
+ query;
42
+ /**
43
+ * @param params - Parsed route parameters
44
+ */
45
+ params;
46
+ route;
47
+ constructor(init) {
48
+ Object.assign(this, init);
49
+ }
50
+ };
51
+ //#endregion
52
+ //#region ../../node_modules/.pnpm/clear-router@2.9.3_@h3ravel+support@2.2.7_@types+node@25.6.2_h3@2.0.1-rc.22__express@5._15be2e62531296a83319dbccad2fa4ea/node_modules/clear-router/dist/Route.mjs
53
+ /**
54
+ * Parse the placeholder parameters declared in a domain/host pattern such as
55
+ * `{account}.example.com`. Mirrors the path parameter syntax (supporting the
56
+ * optional `{name?}` form) so domain parameters feel consistent with path ones.
57
+ *
58
+ * @param pattern
59
+ * @returns
60
+ */
61
+ const parseDomainParameters = (pattern) => {
62
+ if (!pattern) return [];
63
+ const parameters = [];
64
+ const seen = /* @__PURE__ */ new Set();
65
+ const matcher = /\{([^{}]+)\}/g;
66
+ let match;
67
+ while ((match = matcher.exec(pattern)) !== null) {
68
+ const raw = match[1].trim();
69
+ const optional = raw.endsWith("?");
70
+ const [name, field] = (optional ? raw.slice(0, -1) : raw).split(":", 2).map((part) => part.trim());
71
+ if (!name || seen.has(name)) continue;
72
+ seen.add(name);
73
+ parameters.push({
74
+ name,
75
+ field: field || void 0,
76
+ optional
77
+ });
78
+ }
79
+ return parameters;
80
+ };
81
+ /**
82
+ * @class clear-router Route
83
+ * @description A route describes a single enpoint on clear-router
84
+ * @author 3m1n3nc3
85
+ * @repository https://github.com/arkstack-hq/clear-router
86
+ */
87
+ var Route = class Route {
88
+ ctx;
89
+ body = {};
90
+ query = {};
91
+ params = {};
92
+ clearRequest;
93
+ methods;
94
+ path;
95
+ registrationPaths;
96
+ parameters;
97
+ routeName;
98
+ handler;
99
+ middlewares;
100
+ controllerName;
101
+ actionName;
102
+ handlerType;
103
+ middlewareCount;
104
+ domainPattern;
105
+ domainParameters;
106
+ constraints = {};
107
+ constructor(methods, path, handler, middlewares = [], options = {}) {
108
+ this.methods = methods;
109
+ this.path = path;
110
+ this.registrationPaths = options.registrationPaths || [path];
111
+ this.parameters = options.parameters || [];
112
+ this.handler = handler;
113
+ this.middlewares = middlewares;
114
+ this.handlerType = Array.isArray(handler) ? "controller" : "function";
115
+ this.middlewareCount = middlewares.length;
116
+ this.controllerName = Array.isArray(handler) ? handler[0]?.name : void 0;
117
+ this.actionName = Array.isArray(handler) ? handler[1] : typeof handler === "function" ? handler.constructor.name ?? handler.name : void 0;
118
+ this.domainPattern = options.domain;
119
+ this.domainParameters = parseDomainParameters(options.domain);
120
+ this.onName = options.onName;
121
+ this.normalizeMiddleware = options.normalizeMiddleware;
122
+ }
123
+ onName;
124
+ normalizeMiddleware;
125
+ static currentResolvers;
126
+ /**
127
+ * Wire the resolvers used by the static `current*` accessors. Called once by
128
+ * `CoreRouter` so `Route.current()` reflects the active request.
129
+ *
130
+ * @internal
131
+ * @param resolvers
132
+ */
133
+ static bindCurrentResolvers(resolvers) {
134
+ Route.currentResolvers = resolvers;
135
+ }
136
+ /**
137
+ * Get the route currently being dispatched, if any.
138
+ *
139
+ * @returns
140
+ */
141
+ static current() {
142
+ return Route.currentResolvers?.current();
143
+ }
144
+ /**
145
+ * Get the name of the route currently being dispatched.
146
+ *
147
+ * @returns
148
+ */
149
+ static currentRouteName() {
150
+ return Route.currentResolvers?.currentRouteName() ?? "";
151
+ }
152
+ /**
153
+ * Get the action (controller@method or `Closure`) of the route currently
154
+ * being dispatched.
155
+ *
156
+ * @returns
157
+ */
158
+ static currentRouteAction() {
159
+ return Route.currentResolvers?.currentRouteAction() ?? "";
160
+ }
161
+ /**
162
+ * The route action expressed as `Controller@method` for controller routes or
163
+ * `Closure` for callback routes.
164
+ */
165
+ get action() {
166
+ if (this.handlerType === "controller") {
167
+ const method = String(this.actionName ?? "");
168
+ return this.controllerName ? `${this.controllerName}@${method}` : method;
169
+ }
170
+ return "Closure";
171
+ }
172
+ /**
173
+ * Set the route name
174
+ *
175
+ * @param name
176
+ * @returns
177
+ */
178
+ name(name) {
179
+ const previousName = this.routeName;
180
+ this.routeName = name;
181
+ this.onName?.(name, this, previousName);
182
+ return this;
183
+ }
184
+ /**
185
+ * Constrain the route to a host pattern such as `{account}.example.com`.
186
+ * Any `{placeholder}` segments are exposed as route parameters once matched.
187
+ *
188
+ * @param pattern
189
+ * @returns
190
+ */
191
+ domain(pattern) {
192
+ this.domainPattern = pattern;
193
+ this.domainParameters = parseDomainParameters(pattern);
194
+ return this;
195
+ }
196
+ /**
197
+ * Constrain one or more route parameters with a regular expression. Accepts
198
+ * either `where(name, pattern)` or `where({ name: pattern, ... })`.
199
+ *
200
+ * @param name
201
+ * @param pattern
202
+ * @returns
203
+ */
204
+ where(name, pattern) {
205
+ if (typeof name === "object") Object.assign(this.constraints, name);
206
+ else if (typeof pattern !== "undefined") this.constraints[name] = pattern;
207
+ return this;
208
+ }
209
+ /**
210
+ * Constrain the given parameters to numeric values.
211
+ *
212
+ * @param names
213
+ * @returns
214
+ */
215
+ whereNumber(...names) {
216
+ return this.applyConstraint(names, "[0-9]+");
217
+ }
218
+ /**
219
+ * Constrain the given parameters to alphabetic values.
220
+ *
221
+ * @param names
222
+ * @returns
223
+ */
224
+ whereAlpha(...names) {
225
+ return this.applyConstraint(names, "[a-zA-Z]+");
226
+ }
227
+ /**
228
+ * Constrain the given parameters to alphanumeric values.
229
+ *
230
+ * @param names
231
+ * @returns
232
+ */
233
+ whereAlphaNumeric(...names) {
234
+ return this.applyConstraint(names, "[a-zA-Z0-9]+");
235
+ }
236
+ /**
237
+ * Constrain the given parameters to UUID values.
238
+ *
239
+ * @param names
240
+ * @returns
241
+ */
242
+ whereUuid(...names) {
243
+ return this.applyConstraint(names, "[\\da-fA-F]{8}-[\\da-fA-F]{4}-[\\da-fA-F]{4}-[\\da-fA-F]{4}-[\\da-fA-F]{12}");
244
+ }
245
+ /**
246
+ * Constrain the given parameters to ULID values.
247
+ *
248
+ * @param names
249
+ * @returns
250
+ */
251
+ whereUlid(...names) {
252
+ return this.applyConstraint(names, "[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}");
253
+ }
254
+ /**
255
+ * Constrain a parameter to one of the given values.
256
+ *
257
+ * @param name
258
+ * @param values
259
+ * @returns
260
+ */
261
+ whereIn(name, values) {
262
+ const escaped = values.map((value) => String(value).replace(/[.*+?^${}()|[\]\\]/g, (match) => `\\${match}`));
263
+ this.constraints[name] = escaped.join("|");
264
+ return this;
265
+ }
266
+ applyConstraint(names, pattern) {
267
+ for (const name of names) this.constraints[name] = pattern;
268
+ return this;
269
+ }
270
+ /**
271
+ * Register one or more middleware that will be executed before the route.
272
+ *
273
+ * @param middlewares
274
+ * @returns
275
+ */
276
+ middleware(middlewares) {
277
+ const normalized = (Array.isArray(middlewares) ? middlewares : [middlewares]).map((middleware) => this.normalizeMiddleware?.(middleware) ?? middleware);
278
+ this.middlewares.push(...normalized);
279
+ this.middlewareCount = this.middlewares.length;
280
+ return this;
281
+ }
282
+ /**
283
+ * Resolve the route's domain pattern into a concrete host using the given
284
+ * parameters.
285
+ *
286
+ * @param params
287
+ * @returns
288
+ */
289
+ resolveDomainHost(params) {
290
+ return this.domainPattern.replace(/\{([^{}]+)\}/g, (_, raw) => {
291
+ const optional = raw.endsWith("?");
292
+ const name = (optional ? raw.slice(0, -1) : raw).split(":", 2)[0].trim();
293
+ const value = params[name];
294
+ if (typeof value === "undefined" || value === null || value === "") {
295
+ if (optional) return "";
296
+ throw new Error(`Missing required route domain parameter: ${name}`);
297
+ }
298
+ return encodeURIComponent(String(value));
299
+ });
300
+ }
301
+ /**
302
+ * Get the path generated and accessible by this route
303
+ *
304
+ * @param params
305
+ * @returns
306
+ */
307
+ toPath(params = {}) {
308
+ const resolved = this.path.replace(/\/?\{([^{}]+)\}/g, (segment, raw) => {
309
+ const optional = raw.endsWith("?");
310
+ const [rawName, rawField] = (optional ? raw.slice(0, -1) : raw).split(":", 2);
311
+ const name = rawName.trim();
312
+ const field = rawField?.trim();
313
+ const value = params[name];
314
+ const resolved = field && value && typeof value === "object" ? value[field] : value;
315
+ if (typeof resolved === "undefined" || resolved === null || resolved === "") {
316
+ if (optional) return "";
317
+ throw new Error(`Missing required route parameter: ${name}`);
318
+ }
319
+ return `${segment.startsWith("/") ? "/" : ""}${encodeURIComponent(String(resolved))}`;
320
+ }) || "/";
321
+ if (!this.domainPattern) return resolved;
322
+ return `//${this.resolveDomainHost(params)}${resolved}`;
323
+ }
324
+ };
325
+ //#endregion
326
+ //#region ../../node_modules/.pnpm/clear-router@2.9.3_@h3ravel+support@2.2.7_@types+node@25.6.2_h3@2.0.1-rc.22__express@5._15be2e62531296a83319dbccad2fa4ea/node_modules/clear-router/dist/core/helpers.mjs
327
+ const wrap = (value) => {
328
+ if (value === null || value === void 0) return [];
329
+ return Array.isArray(value) ? value : [value];
330
+ };
331
+ /**
332
+ *
333
+ * Dynamically imports a file at the given path with full TypeScript support,
334
+ * including `tsconfig.json` path aliases.
335
+ *
336
+ * @param filePath - The path to the file to import.
337
+ * @returns The imported module typed as `T`.
338
+ *
339
+ * @example
340
+ * const config = await importFile<AppConfig>('./config/app.ts')
341
+ */
342
+ const importFile = async (filePath, userOptions, resolveOptions) => {
343
+ const resolvedPath = resolve(filePath);
344
+ return await createJiti(pathToFileURL(resolvedPath).href, {
345
+ ...userOptions,
346
+ interopDefault: false,
347
+ tsconfigPaths: true
348
+ }).import(resolvedPath, resolveOptions);
349
+ };
350
+ //#endregion
351
+ //#region ../../node_modules/.pnpm/clear-router@2.9.3_@h3ravel+support@2.2.7_@types+node@25.6.2_h3@2.0.1-rc.22__express@5._15be2e62531296a83319dbccad2fa4ea/node_modules/clear-router/dist/RouteGroup.mjs
352
+ /**
353
+ * @class clear-router RouteGroup
354
+ * @description A route group describes a collection of routes on clear-router
355
+ * @author 3m1n3nc3
356
+ * @repository https://github.com/arkstack-hq/clear-router
357
+ */
358
+ var RouteGroup = class {
359
+ checks = [];
360
+ conditions = [];
361
+ registration;
362
+ routes = /* @__PURE__ */ new Set();
363
+ unfilteredSources = /* @__PURE__ */ new Set();
364
+ constructor(options) {
365
+ this.options = options;
366
+ this.registration = this.register();
367
+ }
368
+ /**
369
+ * Returning a falsy value will stop route group registration
370
+ *
371
+ * @param condition
372
+ * @returns
373
+ */
374
+ when(condition) {
375
+ this.conditions.push(condition);
376
+ const unfilteredSources = Array.from(this.unfilteredSources);
377
+ if (unfilteredSources.length) this.checks.push(this.registration.then(async () => {
378
+ for (const source of unfilteredSources) if (!await condition(source)) {
379
+ this.rollback();
380
+ break;
381
+ }
382
+ }));
383
+ return this;
384
+ }
385
+ /**
386
+ * Register one or more middleware that will be executed before every route in the group.
387
+ *
388
+ * @param middlewares
389
+ * @returns
390
+ */
391
+ middleware(middlewares) {
392
+ this.checks.push(this.registration.then(() => {
393
+ for (const route of this.routes) route.middleware(middlewares);
394
+ }));
395
+ return this;
396
+ }
397
+ /**
398
+ * Attaches callbacks for the resolution and/or rejection of the RouteGroup.
399
+ *
400
+ * @param onfulfilled
401
+ * @param onrejected
402
+ * @returns
403
+ */
404
+ then(onfulfilled, onrejected) {
405
+ return Promise.all([this.registration, ...this.checks]).then(() => void 0).then(onfulfilled, onrejected);
406
+ }
407
+ /**
408
+ * Register the routes
409
+ */
410
+ async register() {
411
+ const current = this.options.context.getStore();
412
+ const previousPrefix = current?.prefix ?? this.options.defaultPrefix;
413
+ const previousMiddlewares = current?.groupMiddlewares ?? this.options.defaultMiddlewares;
414
+ const fullPrefix = [previousPrefix, this.options.prefix].filter(Boolean).join("/");
415
+ const nextContext = {
416
+ prefix: this.options.normalizePath(fullPrefix),
417
+ groupMiddlewares: [...previousMiddlewares, ...this.options.middlewares || []],
418
+ domain: this.options.domain ?? current?.domain,
419
+ routeCollectors: [...current?.routeCollectors ?? [], this.routes]
420
+ };
421
+ await this.options.context.run(nextContext, async () => {
422
+ for (const entry of Array.isArray(this.options.source) ? this.options.source : [this.options.source]) {
423
+ if (typeof entry === "function") {
424
+ if (!this.conditions.length) this.unfilteredSources.add(entry);
425
+ else if (!await this.accepts(entry)) continue;
426
+ await Promise.resolve(entry());
427
+ continue;
428
+ }
429
+ const resolved = await this.resolveFiles(entry);
430
+ if (!resolved.directory && !await this.accepts(entry)) continue;
431
+ for (const file of resolved.files) {
432
+ if (resolved.directory && !await this.accepts(file)) continue;
433
+ await importFile(file);
434
+ }
435
+ }
436
+ });
437
+ }
438
+ /**
439
+ * Rollback the route registration
440
+ */
441
+ rollback() {
442
+ for (const route of this.routes) this.options.removeRoute(route);
443
+ }
444
+ /**
445
+ * Check whether a callback or path should be registered.
446
+ *
447
+ * @param source
448
+ * @returns
449
+ */
450
+ async accepts(source) {
451
+ for (const condition of this.conditions) if (!await condition(source)) return false;
452
+ return true;
453
+ }
454
+ /**
455
+ * Resolve files from the group path
456
+ *
457
+ * @param source
458
+ * @returns
459
+ */
460
+ async resolveFiles(source) {
461
+ const resolved = isAbsolute(source) ? source : resolve(process.cwd(), source);
462
+ let sourceStat;
463
+ try {
464
+ sourceStat = await stat(resolved);
465
+ } catch {
466
+ throw new Error(`Route group source not found: ${source}`);
467
+ }
468
+ if (sourceStat.isFile()) return {
469
+ directory: false,
470
+ files: [resolved]
471
+ };
472
+ if (!sourceStat.isDirectory()) throw new Error(`Route group source must be a file or directory: ${source}`);
473
+ return {
474
+ directory: true,
475
+ files: await this.readDirectory(resolved)
476
+ };
477
+ }
478
+ /**
479
+ * Read all the files in the configured directory
480
+ *
481
+ * @param directory
482
+ * @returns
483
+ */
484
+ async readDirectory(directory) {
485
+ const entries = await readdir(directory, { withFileTypes: true });
486
+ const files = [];
487
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
488
+ const path = join(directory, entry.name);
489
+ if (entry.isDirectory()) files.push(...await this.readDirectory(path));
490
+ else if (entry.isFile() && /\.(?:[cm]?[jt]s)$/.test(entry.name) && !entry.name.endsWith(".d.ts")) files.push(path);
491
+ }
492
+ return files;
493
+ }
494
+ };
495
+ //#endregion
496
+ //#region ../../node_modules/.pnpm/clear-router@2.9.3_@h3ravel+support@2.2.7_@types+node@25.6.2_h3@2.0.1-rc.22__express@5._15be2e62531296a83319dbccad2fa4ea/node_modules/clear-router/dist/RouteRegistrar.mjs
497
+ /**
498
+ * @class clear-router RouteRegistrar
499
+ * @description Fluent builder returned by `Router.domain()` that lets routes be
500
+ * grouped under a shared host pattern (and optionally a prefix/middlewares),
501
+ * mirroring Laravel's route attribute registrar.
502
+ * @author 3m1n3nc3
503
+ * @repository https://github.com/arkstack-hq/clear-router
504
+ */
505
+ var RouteRegistrar = class {
506
+ attributes;
507
+ constructor(makeGroup, attributes = {}) {
508
+ this.makeGroup = makeGroup;
509
+ this.attributes = {
510
+ domain: attributes.domain,
511
+ prefix: attributes.prefix ?? "",
512
+ middlewares: attributes.middlewares ?? []
513
+ };
514
+ }
515
+ /**
516
+ * Constrain the grouped routes to a host pattern such as `{account}.example.com`.
517
+ *
518
+ * @param pattern
519
+ * @returns
520
+ */
521
+ domain(pattern) {
522
+ this.attributes.domain = pattern;
523
+ return this;
524
+ }
525
+ /**
526
+ * Prepend a path prefix to the grouped routes.
527
+ *
528
+ * @param prefix
529
+ * @returns
530
+ */
531
+ prefix(prefix) {
532
+ this.attributes.prefix = prefix;
533
+ return this;
534
+ }
535
+ /**
536
+ * Register one or more middleware shared by the grouped routes.
537
+ *
538
+ * @param middlewares
539
+ * @returns
540
+ */
541
+ middleware(middlewares) {
542
+ this.attributes.middlewares = [...this.attributes.middlewares, ...Array.isArray(middlewares) ? middlewares : [middlewares]];
543
+ return this;
544
+ }
545
+ group(prefixOrSource, sourceOrMiddlewares, middlewares) {
546
+ let prefix = this.attributes.prefix;
547
+ let source;
548
+ let extraMiddlewares;
549
+ if (typeof prefixOrSource === "string") {
550
+ prefix = prefixOrSource;
551
+ source = sourceOrMiddlewares;
552
+ extraMiddlewares = middlewares;
553
+ } else {
554
+ source = prefixOrSource;
555
+ extraMiddlewares = sourceOrMiddlewares;
556
+ }
557
+ return this.makeGroup(prefix, source, [...this.attributes.middlewares, ...extraMiddlewares ?? []], { domain: this.attributes.domain });
558
+ }
559
+ };
560
+ //#endregion
561
+ //#region ../../node_modules/.pnpm/clear-router@2.9.3_@h3ravel+support@2.2.7_@types+node@25.6.2_h3@2.0.1-rc.22__express@5._15be2e62531296a83319dbccad2fa4ea/node_modules/clear-router/dist/core/Request.mjs
562
+ var Request = class extends ClearRequest {
563
+ original;
564
+ method = "GET";
565
+ path = "/";
566
+ url = "/";
567
+ headers = {};
568
+ constructor(init) {
569
+ super(init);
570
+ Object.assign(this, init);
571
+ }
572
+ getBody() {
573
+ return this.body ?? {};
574
+ }
575
+ header(name) {
576
+ if (typeof this.headers.get === "function") return this.headers.get(name) || "";
577
+ const headers = this.headers;
578
+ const value = headers[name] ?? headers[name.toLowerCase()];
579
+ return Array.isArray(value) ? String(value[0] ?? "") : String(value ?? "");
580
+ }
581
+ param(name) {
582
+ return this.params?.[name];
583
+ }
584
+ input(name) {
585
+ return this.body?.[name] ?? this.query?.[name] ?? this.params?.[name];
586
+ }
587
+ is(method) {
588
+ return this.method.toLowerCase() === String(method).toLowerCase();
589
+ }
590
+ };
591
+ //#endregion
592
+ //#region ../../node_modules/.pnpm/clear-router@2.9.3_@h3ravel+support@2.2.7_@types+node@25.6.2_h3@2.0.1-rc.22__express@5._15be2e62531296a83319dbccad2fa4ea/node_modules/clear-router/dist/core/Response.mjs
593
+ var Response = class {
594
+ body;
595
+ headers = new Headers();
596
+ sent = false;
597
+ statusCode = 200;
598
+ statusText = "OK";
599
+ constructor(init) {
600
+ const { status: _, ...rest } = init ?? {};
601
+ Object.assign(this, rest);
602
+ if (init?.headers && !(init.headers instanceof Headers)) this.headers = new Headers(init.headers);
603
+ if (init?.status && typeof init.status === "number") this.statusCode = init?.status;
604
+ }
605
+ status(code) {
606
+ this.statusCode = code;
607
+ return this;
608
+ }
609
+ setStatusText(text) {
610
+ this.statusText = text;
611
+ return this;
612
+ }
613
+ code(code) {
614
+ return this.status(code);
615
+ }
616
+ setHeader(name, value) {
617
+ this.headers.set(name, value);
618
+ return this;
619
+ }
620
+ header(name, value) {
621
+ return this.setHeader(name, value);
622
+ }
623
+ set(name, value) {
624
+ return this.setHeader(name, value);
625
+ }
626
+ type(contentType) {
627
+ return this.setHeader("Content-Type", contentType);
628
+ }
629
+ send(body) {
630
+ this.body = body;
631
+ this.sent = true;
632
+ return this;
633
+ }
634
+ json(body) {
635
+ return this.type("application/json; charset=utf-8").send(body);
636
+ }
637
+ html(body) {
638
+ return this.type("text/html; charset=utf-8").send(body);
639
+ }
640
+ text(body) {
641
+ return this.type("text/plain; charset=utf-8").send(body);
642
+ }
643
+ noContent() {
644
+ return this.status(204).send(null);
645
+ }
646
+ };
647
+ //#endregion
648
+ //#region ../../node_modules/.pnpm/clear-router@2.9.3_@h3ravel+support@2.2.7_@types+node@25.6.2_h3@2.0.1-rc.22__express@5._15be2e62531296a83319dbccad2fa4ea/node_modules/clear-router/dist/core/bindings.mjs
649
+ const metadataKey$1 = Symbol.for("clear-router:binding-metadata");
650
+ const bindings = /* @__PURE__ */ new WeakMap();
651
+ var InjectionToken = class {
652
+ key;
653
+ constructor(description) {
654
+ this.description = description;
655
+ this.key = Symbol(description);
656
+ }
657
+ toString() {
658
+ return `InjectionToken(${this.description})`;
659
+ }
660
+ };
661
+ var ContainerResolutionError = class extends Error {
662
+ constructor(message, path) {
663
+ super(`${message}\nResolution path: ${path.map(describeToken).join(" -> ")}`);
664
+ this.path = path;
665
+ this.name = "ContainerResolutionError";
666
+ }
667
+ };
668
+ var Container = class Container {
669
+ static activeScope = new AsyncLocalStorage();
670
+ static containers = /* @__PURE__ */ new Set();
671
+ static globalContainer = new Container();
672
+ registry = /* @__PURE__ */ new Map();
673
+ instances = /* @__PURE__ */ new Map();
674
+ pending = /* @__PURE__ */ new Map();
675
+ constructor(parent, context, requestScope = false) {
676
+ this.parent = parent;
677
+ this.context = context;
678
+ this.requestScope = requestScope;
679
+ }
680
+ static get global() {
681
+ return this.globalContainer;
682
+ }
683
+ static current() {
684
+ return this.activeScope.getStore() ?? this.globalContainer;
685
+ }
686
+ static run(container, callback) {
687
+ return this.activeScope.run(container, callback);
688
+ }
689
+ static create(parent = this.globalContainer) {
690
+ const container = new Container(parent);
691
+ this.containers.add(container);
692
+ return container;
693
+ }
694
+ createRequestScope(ctx) {
695
+ return new Container(this, ctx, true);
696
+ }
697
+ static bind(token, value, options) {
698
+ this.globalContainer.bind(token, value, options);
699
+ }
700
+ static unbind(token) {
701
+ this.globalContainer.unbind(token);
702
+ }
703
+ static clear() {
704
+ this.globalContainer.clear();
705
+ for (const container of this.containers) container.clear();
706
+ }
707
+ static has(token) {
708
+ return this.current().has(token);
709
+ }
710
+ static bindings() {
711
+ return this.current().bindings();
712
+ }
713
+ static async resolve(token, ctx, autoDiscover = false) {
714
+ return this.current().resolve(token, ctx, autoDiscover);
715
+ }
716
+ bind(token, value, options) {
717
+ this.registry.set(token, normalizeProvider(value, options));
718
+ this.instances.delete(token);
719
+ }
720
+ unbind(token) {
721
+ this.registry.delete(token);
722
+ this.instances.delete(token);
723
+ }
724
+ clear() {
725
+ this.registry.clear();
726
+ this.instances.clear();
727
+ this.pending.clear();
728
+ }
729
+ has(token) {
730
+ return Boolean(this.findProvider(token));
731
+ }
732
+ entries() {
733
+ const entries = /* @__PURE__ */ new Map();
734
+ for (const container of this.lineage().reverse()) for (const [token, provider] of container.registry) entries.set(token, provider);
735
+ return entries;
736
+ }
737
+ bindings() {
738
+ return Object.fromEntries(Array.from(this.entries(), ([token, provider]) => [describeToken(token), provider]));
739
+ }
740
+ async resolve(token, ctx = this.context, autoDiscover = false) {
741
+ return this.resolveToken(token, ctx, {
742
+ autoDiscover,
743
+ stack: []
744
+ });
745
+ }
746
+ async resolveOrFail(token, ctx = this.context, autoDiscover = false) {
747
+ const resolved = await this.resolve(token, ctx, autoDiscover);
748
+ if (typeof resolved === "undefined") throw new ContainerResolutionError(`Cannot resolve ${describeToken(token)}`, [token]);
749
+ return resolved;
750
+ }
751
+ async resolveToken(token, ctx, state) {
752
+ if (token === Request) return ctx?.clearRequest;
753
+ if (token === Response) return ctx?.clearResponse;
754
+ if (state.stack.includes(token)) throw new ContainerResolutionError(`Circular dependency detected while resolving ${describeToken(token)}`, [...state.stack, token]);
755
+ const nextState = {
756
+ ...state,
757
+ stack: [...state.stack, token]
758
+ };
759
+ const found = this.findProvider(token);
760
+ if (found) return this.resolveProvider(found.token, found.provider, found.owner, ctx, nextState);
761
+ if (state.autoDiscover && typeof token === "function") return this.instantiate(token, void 0, ctx, nextState);
762
+ }
763
+ findProvider(token) {
764
+ if (this.registry.has(token)) return {
765
+ token,
766
+ provider: this.registry.get(token),
767
+ owner: this
768
+ };
769
+ const equivalent = this.findEquivalentToken(token);
770
+ if (equivalent) return {
771
+ token: equivalent,
772
+ provider: this.registry.get(equivalent),
773
+ owner: this
774
+ };
775
+ return this.parent?.findProvider(token);
776
+ }
777
+ async resolveProvider(token, provider, owner, ctx, state) {
778
+ if ("useExisting" in provider) return this.resolveToken(provider.useExisting, ctx, state);
779
+ const cache = provider.scope === "singleton" ? owner : provider.scope === "request" ? this.findRequestScope() : void 0;
780
+ if (cache?.instances.has(token)) return cache.instances.get(token);
781
+ if (cache?.pending.has(token)) return cache.pending.get(token);
782
+ const create = async () => {
783
+ if ("useValue" in provider) return provider.useValue;
784
+ if ("useClass" in provider) return this.instantiate(provider.useClass, provider.dependencies, ctx, state);
785
+ return provider.useFactory(ctx);
786
+ };
787
+ if (!cache) return create();
788
+ const promise = create();
789
+ cache.pending.set(token, promise);
790
+ try {
791
+ const resolved = await promise;
792
+ if (typeof resolved !== "undefined") cache.instances.set(token, resolved);
793
+ return resolved;
794
+ } finally {
795
+ cache.pending.delete(token);
796
+ }
797
+ }
798
+ async instantiate(Type, dependencies, ctx, state) {
799
+ const tokens = dependencies ?? getInjectTokens(Type);
800
+ const args = [];
801
+ for (const dependency of tokens) {
802
+ const resolved = await this.resolveToken(dependency, ctx, state);
803
+ if (typeof resolved === "undefined") throw new ContainerResolutionError(`Cannot resolve ${describeToken(dependency)} required by ${describeToken(Type)}`, [...state.stack, dependency]);
804
+ args.push(resolved);
805
+ }
806
+ return new Type(...args);
807
+ }
808
+ findRequestScope() {
809
+ if (this.requestScope) return this;
810
+ return this.parent?.findRequestScope();
811
+ }
812
+ lineage() {
813
+ return [this, ...this.parent?.lineage() ?? []];
814
+ }
815
+ findEquivalentToken(token) {
816
+ if (typeof token !== "function") return void 0;
817
+ const name = token.name;
818
+ if (!name) return void 0;
819
+ const tokenParent = Object.getPrototypeOf(token);
820
+ const tokenProps = this.getComparableStaticProps(token);
821
+ for (const registered of this.registry.keys()) {
822
+ if (typeof registered !== "function" || registered === token || registered.name !== name) continue;
823
+ const registeredParent = Object.getPrototypeOf(registered);
824
+ if (tokenParent && registeredParent && tokenParent.name !== registeredParent.name) continue;
825
+ const registeredProps = this.getComparableStaticProps(registered);
826
+ if (this.staticPropsMatch(token, registered, tokenProps, registeredProps)) return registered;
827
+ }
828
+ }
829
+ getComparableStaticProps(token) {
830
+ return Object.getOwnPropertyNames(token).filter((prop) => {
831
+ return ![
832
+ "length",
833
+ "name",
834
+ "prototype",
835
+ "arguments",
836
+ "caller"
837
+ ].includes(prop);
838
+ });
839
+ }
840
+ staticPropsMatch(token, registered, tokenProps, registeredProps) {
841
+ if (tokenProps.length !== registeredProps.length) return false;
842
+ for (const prop of tokenProps) if (!registeredProps.includes(prop) || Reflect.get(token, prop) !== Reflect.get(registered, prop)) return false;
843
+ return true;
844
+ }
845
+ };
846
+ function normalizeProvider(value, options) {
847
+ if (isProvider(value)) return {
848
+ scope: "transient",
849
+ ...value
850
+ };
851
+ if (isClass(value)) return {
852
+ useClass: value,
853
+ scope: options?.scope ?? "transient"
854
+ };
855
+ if (typeof value === "function") return {
856
+ useFactory: value,
857
+ scope: options?.scope ?? "transient"
858
+ };
859
+ return { useValue: value };
860
+ }
861
+ function isProvider(value) {
862
+ return Boolean(value && typeof value === "object" && ("useValue" in value || "useClass" in value || "useFactory" in value || "useExisting" in value));
863
+ }
864
+ function getInjectTokens(Type) {
865
+ return Type.inject ?? getDesignParamTypes(Type);
866
+ }
867
+ function describeToken(token) {
868
+ if (token instanceof InjectionToken) return token.toString();
869
+ if (typeof token === "symbol") return token.description ?? token.toString();
870
+ return token.name || "<anonymous class>";
871
+ }
872
+ function getStandardMetadata$1(metadata, propertyKey) {
873
+ const store = metadata && metadata[metadataKey$1];
874
+ if (!store) return void 0;
875
+ return propertyKey ? store[propertyKey] : void 0;
876
+ }
877
+ function getBindingMetadataFromTargets(targets) {
878
+ for (const { target, propertyKey } of targets) {
879
+ if (!target) continue;
880
+ const metadata = getBindingMetadata(target, propertyKey);
881
+ if (metadata) return metadata;
882
+ const standardMetadata = getStandardMetadata$1(target[Symbol.metadata], propertyKey);
883
+ if (standardMetadata) return standardMetadata;
884
+ }
885
+ }
886
+ function getBindingMetadata(target, propertyKey) {
887
+ if (propertyKey) return bindings.get(target)?.get(propertyKey);
888
+ return bindings.get(target)?.get("__route_handler__");
889
+ }
890
+ function getDesignParamTypes(target, propertyKey) {
891
+ return Reflect.getMetadata?.("design:paramtypes", target, propertyKey) ?? [];
892
+ }
893
+ function isClass(value) {
894
+ return typeof value === "function" && /^class\s/.test(Function.prototype.toString.call(value));
895
+ }
896
+ //#endregion
897
+ //#region ../../node_modules/.pnpm/clear-router@2.9.3_@h3ravel+support@2.2.7_@types+node@25.6.2_h3@2.0.1-rc.22__express@5._15be2e62531296a83319dbccad2fa4ea/node_modules/clear-router/dist/decorators/middleware.mjs
898
+ const CLASS_KEY = "__class__";
899
+ const metadataKey = Symbol.for("clear-router:middleware-metadata");
900
+ const store = /* @__PURE__ */ new WeakMap();
901
+ /**
902
+ * Collect the decorator-declared middleware for a controller route handler,
903
+ * ordered class-level first then method-level. Returns an empty array for
904
+ * non-controller (callback) handlers or handlers without any decorators.
905
+ *
906
+ * @param handler
907
+ * @returns
908
+ */
909
+ function getControllerMiddlewares(handler) {
910
+ if (!Array.isArray(handler) || handler.length !== 2) return [];
911
+ const [controller, method] = handler;
912
+ if (!controller) return [];
913
+ const constructor = typeof controller === "function" ? controller : controller.constructor;
914
+ const prototype = typeof controller === "function" ? controller.prototype : Object.getPrototypeOf(controller);
915
+ const standardMetadata = constructor?.[Symbol.metadata];
916
+ const classMiddlewares = getMiddlewareMetadata(constructor, CLASS_KEY) ?? getMiddlewareMetadata(prototype, CLASS_KEY) ?? getStandardMetadata(standardMetadata, CLASS_KEY) ?? [];
917
+ const methodMiddlewares = getMiddlewareMetadata(prototype, method) ?? getMiddlewareMetadata(constructor, method) ?? getStandardMetadata(standardMetadata, method) ?? [];
918
+ return [...classMiddlewares, ...methodMiddlewares];
919
+ }
920
+ function getMiddlewareMetadata(target, propertyKey) {
921
+ if (!target) return void 0;
922
+ return store.get(target)?.get(propertyKey);
923
+ }
924
+ function getStandardMetadata(metadata, propertyKey) {
925
+ const record = metadata && metadata[metadataKey];
926
+ return record ? record[propertyKey] : void 0;
927
+ }
928
+ //#endregion
929
+ //#region ../../node_modules/.pnpm/clear-router@2.9.3_@h3ravel+support@2.2.7_@types+node@25.6.2_h3@2.0.1-rc.22__express@5._15be2e62531296a83319dbccad2fa4ea/node_modules/clear-router/dist/ResourceRouteSelection.mjs
930
+ var ResourceRouteSelection = class {
931
+ constructor(routes) {
932
+ this.routes = routes;
933
+ }
934
+ /**
935
+ * Register one or more middleware that will be executed before the route.
936
+ *
937
+ * @param middlewares
938
+ * @returns
939
+ */
940
+ middleware(middlewares) {
941
+ for (const route of this.routes) route.middleware(middlewares);
942
+ return this;
943
+ }
944
+ all() {
945
+ return this.routes;
946
+ }
947
+ first() {
948
+ return this.routes[0];
949
+ }
950
+ };
951
+ //#endregion
952
+ //#region ../../node_modules/.pnpm/clear-router@2.9.3_@h3ravel+support@2.2.7_@types+node@25.6.2_h3@2.0.1-rc.22__express@5._15be2e62531296a83319dbccad2fa4ea/node_modules/clear-router/dist/ResourceRoutes.mjs
953
+ /**
954
+ * @class clear-router ResourceRoutes
955
+ * @description A ResourceRoutes creates a collection of resourceful routes in a single call
956
+ * @author 3m1n3nc3
957
+ * @repository https://github.com/arkstack-hq/clear-router
958
+ */
959
+ var ResourceRoutes = class ResourceRoutes {
960
+ static actions = {
961
+ index: {
962
+ method: "get",
963
+ path: "/"
964
+ },
965
+ show: {
966
+ method: "get",
967
+ path: "/:{param}"
968
+ },
969
+ create: {
970
+ method: "post",
971
+ path: "/"
972
+ },
973
+ update: {
974
+ method: "put",
975
+ path: "/:{param}"
976
+ },
977
+ destroy: {
978
+ method: "delete",
979
+ path: "/:{param}"
980
+ }
981
+ };
982
+ routes = {};
983
+ options;
984
+ chainedMiddlewares = [];
985
+ constructor(basePath, controller, paramName, options, registerRoute, removeRoute) {
986
+ this.basePath = basePath;
987
+ this.controller = controller;
988
+ this.paramName = paramName;
989
+ this.registerRoute = registerRoute;
990
+ this.removeRoute = removeRoute;
991
+ this.options = options ?? {};
992
+ }
993
+ register() {
994
+ this.clear();
995
+ const preController = typeof this.controller === "function" ? new this.controller() : this.controller;
996
+ for (const action of this.selectedActions()) {
997
+ if (typeof preController[action] !== "function") continue;
998
+ const definition = this.definitionFor(action);
999
+ const route = this.registerRoute({
1000
+ action,
1001
+ method: definition.method,
1002
+ path: `${this.basePath}${definition.path}`,
1003
+ handler: [this.controller, action],
1004
+ middlewares: this.resolveActionMiddlewares(action),
1005
+ name: `${this.nameFor(definition.path)}.${action.toLowerCase()}`
1006
+ });
1007
+ this.routes[action] = route;
1008
+ }
1009
+ for (const middlewares of this.chainedMiddlewares) this.middleware(middlewares, false);
1010
+ return this;
1011
+ }
1012
+ /**
1013
+ * Only register routes for the provided actions.
1014
+ *
1015
+ * @param action
1016
+ * @param actions
1017
+ * @returns
1018
+ */
1019
+ only(action, ...actions) {
1020
+ this.options.only = Array.from(new Set(wrap(action).concat(actions)));
1021
+ return this.register();
1022
+ }
1023
+ /**
1024
+ * Register all resource routes except the provided actions.
1025
+ *
1026
+ * @param action
1027
+ * @param actions
1028
+ * @returns
1029
+ */
1030
+ except(action, ...actions) {
1031
+ this.options.except = Array.from(new Set(wrap(action).concat(actions)));
1032
+ return this.register();
1033
+ }
1034
+ /**
1035
+ * Register one or more middleware that will be executed before the route.
1036
+ *
1037
+ * @param middlewares
1038
+ * @param remember
1039
+ * @returns
1040
+ */
1041
+ middleware(middlewares, remember = true) {
1042
+ if (remember) this.chainedMiddlewares.push(middlewares);
1043
+ for (const route of Object.values(this.routes)) route?.middleware(middlewares);
1044
+ return this;
1045
+ }
1046
+ action(action) {
1047
+ return this.routes[action];
1048
+ }
1049
+ index() {
1050
+ return this.routes.index;
1051
+ }
1052
+ show() {
1053
+ return this.routes.show;
1054
+ }
1055
+ create() {
1056
+ return this.routes.create;
1057
+ }
1058
+ update() {
1059
+ return this.routes.update;
1060
+ }
1061
+ destroy() {
1062
+ return this.routes.destroy;
1063
+ }
1064
+ get() {
1065
+ return this.byMethod("get");
1066
+ }
1067
+ post() {
1068
+ return this.byMethod("post");
1069
+ }
1070
+ put() {
1071
+ return this.byMethod("put");
1072
+ }
1073
+ delete() {
1074
+ return this.byMethod("delete");
1075
+ }
1076
+ selectedActions() {
1077
+ const actions = this.options.only?.length ? this.options.only : Object.keys(ResourceRoutes.actions);
1078
+ const except = new Set(this.options.except ?? []);
1079
+ return actions.filter((action) => !except.has(action));
1080
+ }
1081
+ definitionFor(action) {
1082
+ const definition = ResourceRoutes.actions[action];
1083
+ return {
1084
+ method: definition.method,
1085
+ path: definition.path.replace("{param}", this.paramName)
1086
+ };
1087
+ }
1088
+ resolveActionMiddlewares(action) {
1089
+ const middlewares = this.isActionMiddlewareMap(this.options.middlewares) ? this.options.middlewares[action] : this.options.middlewares;
1090
+ return Array.isArray(middlewares) ? middlewares : middlewares ? [middlewares] : void 0;
1091
+ }
1092
+ isActionMiddlewareMap(middlewares) {
1093
+ if (!middlewares || Array.isArray(middlewares) || typeof middlewares !== "object") return false;
1094
+ return Object.keys(ResourceRoutes.actions).some((action) => action in middlewares);
1095
+ }
1096
+ nameFor(path) {
1097
+ return `${this.basePath}${path}`.replace(/\/:[^/]+|\/\{[^}]+\}/g, "").replace(/\{(\w+):[^}]+\}/g, "$1").replace(/\/|:|[{}]/g, ".").replace(/\.{2,}/g, ".").replace(/^\.|\.$/g, "");
1098
+ }
1099
+ byMethod(method) {
1100
+ return new ResourceRouteSelection(Object.values(this.routes).filter((route) => Boolean(route?.methods.includes(method))));
1101
+ }
1102
+ clear() {
1103
+ for (const route of Object.values(this.routes)) if (route) this.removeRoute(route);
1104
+ for (const key of Object.keys(this.routes)) delete this.routes[key];
1105
+ }
1106
+ };
1107
+ //#endregion
1108
+ //#region ../../node_modules/.pnpm/clear-router@2.9.3_@h3ravel+support@2.2.7_@types+node@25.6.2_h3@2.0.1-rc.22__express@5._15be2e62531296a83319dbccad2fa4ea/node_modules/clear-router/dist/core/CoreRouter.mjs
1109
+ /**
1110
+ * @class clear-router CoreRouter
1111
+ * @description Core routing logic for clear-router, shared between all supported adapters (Express.js, H3, etc.)
1112
+ * @author 3m1n3nc3
1113
+ * @repository https://github.com/arkstack-hq/clear-router
1114
+ */
1115
+ var CoreRouter = class {
1116
+ static routerStateNamespace = "clear-router:core";
1117
+ static stateStoreKey = Symbol.for("clear-router:router-state");
1118
+ static stateBoundKey = Symbol.for("clear-router:router-state-bound");
1119
+ static defaultConfigKey = Symbol.for("clear-router:default-config");
1120
+ static requestProvider;
1121
+ static responseProvider;
1122
+ static domainMatcherCache = /* @__PURE__ */ new Map();
1123
+ static constraintRegexCache = /* @__PURE__ */ new Map();
1124
+ static routePatterns = /* @__PURE__ */ new Map();
1125
+ static config = {
1126
+ inferParamName: false,
1127
+ methodOverride: {
1128
+ enabled: true,
1129
+ bodyKeys: ["_method"],
1130
+ headerKeys: ["x-http-method"]
1131
+ },
1132
+ container: {
1133
+ enabled: false,
1134
+ autoDiscover: false,
1135
+ strict: false
1136
+ }
1137
+ };
1138
+ static groupContext = new AsyncLocalStorage();
1139
+ static pluginRequestContext = new AsyncLocalStorage();
1140
+ static routes = /* @__PURE__ */ new Set([]);
1141
+ static routesByPathMethod = /* @__PURE__ */ new Map();
1142
+ static routesByMethod = /* @__PURE__ */ new Map();
1143
+ static routesByName = /* @__PURE__ */ new Map();
1144
+ static prefix = "";
1145
+ static groupMiddlewares = [];
1146
+ static globalMiddlewares = [];
1147
+ /**
1148
+ * Resolve middlewares before assigning to adapter
1149
+ *
1150
+ * @param middleware
1151
+ * @returns
1152
+ */
1153
+ static resolveMiddleware(middleware) {
1154
+ if (!middleware || typeof middleware === "function" && !isClass(middleware)) return middleware;
1155
+ const instance = isClass(middleware) ? new middleware() : middleware;
1156
+ if (instance && typeof instance.handle === "function") return instance.handle.bind(instance);
1157
+ return middleware;
1158
+ }
1159
+ static resolveMiddlewares(middlewares = []) {
1160
+ return middlewares.map((middleware) => this.resolveMiddleware(middleware));
1161
+ }
1162
+ static routeSpecificity(route) {
1163
+ const path = route.registrationPaths.slice().sort((left, right) => right.length - left.length)[0] ?? route.path;
1164
+ const segments = this.normalizePath(path).split("/").filter(Boolean);
1165
+ return [
1166
+ segments.filter((segment) => !segment.startsWith(":")).length,
1167
+ segments.length,
1168
+ path.length
1169
+ ];
1170
+ }
1171
+ static orderedRoutes() {
1172
+ return Array.from(this.routes).sort((left, right) => {
1173
+ const leftScore = this.routeSpecificity(left);
1174
+ const rightScore = this.routeSpecificity(right);
1175
+ for (let index = 0; index < leftScore.length; index++) {
1176
+ const difference = rightScore[index] - leftScore[index];
1177
+ if (difference !== 0) return difference;
1178
+ }
1179
+ return 0;
1180
+ });
1181
+ }
1182
+ static removeRouteMethod(route, method, path) {
1183
+ route.methods = route.methods.filter((existingMethod) => existingMethod !== method);
1184
+ this.routesByPathMethod.delete(`${method.toUpperCase()} ${path}`);
1185
+ const methodKey = method.toUpperCase();
1186
+ this.routesByMethod.set(methodKey, (this.routesByMethod.get(methodKey) ?? []).filter((existingRoute) => existingRoute !== route));
1187
+ if (!route.methods.some((existingMethod) => existingMethod !== "options")) {
1188
+ this.routes.delete(route);
1189
+ if (route.routeName && this.routesByName.get(route.routeName) === route) this.routesByName.delete(route.routeName);
1190
+ }
1191
+ }
1192
+ static removeRoute(route) {
1193
+ this.routes.delete(route);
1194
+ if (route.routeName && this.routesByName.get(route.routeName) === route) this.routesByName.delete(route.routeName);
1195
+ for (const method of route.methods) {
1196
+ const methodKey = method.toUpperCase();
1197
+ this.routesByPathMethod.delete(`${methodKey} ${route.path}`);
1198
+ this.routesByMethod.set(methodKey, (this.routesByMethod.get(methodKey) ?? []).filter((existingRoute) => existingRoute !== route));
1199
+ }
1200
+ }
1201
+ /**
1202
+ * Resets the router to it's default state
1203
+ */
1204
+ static reset() {
1205
+ this.routes.clear();
1206
+ this.prefix = "";
1207
+ this.groupMiddlewares = [];
1208
+ this.globalMiddlewares = [];
1209
+ this.routesByPathMethod.clear();
1210
+ this.routesByMethod.clear();
1211
+ this.routesByName.clear();
1212
+ this.routePatterns.clear();
1213
+ return this;
1214
+ }
1215
+ static createBaseConfig() {
1216
+ return {
1217
+ inferParamName: false,
1218
+ methodOverride: {
1219
+ enabled: true,
1220
+ bodyKeys: ["_method"],
1221
+ headerKeys: ["x-http-method"]
1222
+ },
1223
+ container: {
1224
+ enabled: false,
1225
+ autoDiscover: false,
1226
+ strict: false
1227
+ }
1228
+ };
1229
+ }
1230
+ static mergeConfig(target, source) {
1231
+ if (!source) return target;
1232
+ if (source.methodOverride) target.methodOverride = {
1233
+ ...target.methodOverride || {},
1234
+ ...source.methodOverride
1235
+ };
1236
+ if (source.container) target.container = {
1237
+ ...target.container || {},
1238
+ ...source.container
1239
+ };
1240
+ return target;
1241
+ }
1242
+ static getDefaultConfig() {
1243
+ const g = globalThis;
1244
+ if (!g[this.defaultConfigKey]) g[this.defaultConfigKey] = this.createBaseConfig();
1245
+ return {
1246
+ inferParamName: g[this.defaultConfigKey].inferParamName,
1247
+ methodOverride: { ...g[this.defaultConfigKey].methodOverride },
1248
+ container: { ...g[this.defaultConfigKey].container }
1249
+ };
1250
+ }
1251
+ static resolveStateNamespace() {
1252
+ return String(this.routerStateNamespace || this.name || "clear-router:core");
1253
+ }
1254
+ static getStateStore() {
1255
+ const g = globalThis;
1256
+ if (!g[this.stateStoreKey]) g[this.stateStoreKey] = Object.create(null);
1257
+ return g[this.stateStoreKey];
1258
+ }
1259
+ static getPluginStore() {
1260
+ this.bindStateAccessors();
1261
+ return this.pluginStore;
1262
+ }
1263
+ static getPluginPendingStore() {
1264
+ this.bindStateAccessors();
1265
+ return this.pluginPending;
1266
+ }
1267
+ static getPluginArgumentResolvers() {
1268
+ this.bindStateAccessors();
1269
+ return this.pluginArgumentResolvers;
1270
+ }
1271
+ static getPluginHttpCtxResolvers() {
1272
+ this.bindStateAccessors();
1273
+ return this.pluginHttpCtxResolvers;
1274
+ }
1275
+ static createDefaultState() {
1276
+ return {
1277
+ config: this.getDefaultConfig(),
1278
+ groupContext: new AsyncLocalStorage(),
1279
+ routes: /* @__PURE__ */ new Set([]),
1280
+ routesByPathMethod: /* @__PURE__ */ new Map(),
1281
+ routesByMethod: /* @__PURE__ */ new Map(),
1282
+ routesByName: /* @__PURE__ */ new Map(),
1283
+ prefix: "",
1284
+ groupMiddlewares: [],
1285
+ globalMiddlewares: [],
1286
+ container: Container.create(),
1287
+ pluginStore: /* @__PURE__ */ new Set(),
1288
+ pluginPending: /* @__PURE__ */ new Set(),
1289
+ pluginArgumentResolvers: /* @__PURE__ */ new Set(),
1290
+ pluginHttpCtxResolvers: /* @__PURE__ */ new Set()
1291
+ };
1292
+ }
1293
+ static bindStateAccessors() {
1294
+ if (Object.prototype.hasOwnProperty.call(this, this.stateBoundKey)) return;
1295
+ const namespace = this.resolveStateNamespace();
1296
+ const store = this.getStateStore();
1297
+ if (!store[namespace]) store[namespace] = this.createDefaultState();
1298
+ for (const key of [
1299
+ "config",
1300
+ "groupContext",
1301
+ "routes",
1302
+ "routesByPathMethod",
1303
+ "routesByMethod",
1304
+ "routesByName",
1305
+ "prefix",
1306
+ "groupMiddlewares",
1307
+ "globalMiddlewares",
1308
+ "container",
1309
+ "pluginStore",
1310
+ "pluginPending",
1311
+ "pluginArgumentResolvers",
1312
+ "pluginHttpCtxResolvers"
1313
+ ]) Object.defineProperty(this, key, {
1314
+ get() {
1315
+ const ns = this.resolveStateNamespace();
1316
+ const registry = this.getStateStore();
1317
+ if (!registry[ns]) registry[ns] = this.createDefaultState();
1318
+ return registry[ns][key];
1319
+ },
1320
+ set(value) {
1321
+ const ns = this.resolveStateNamespace();
1322
+ const registry = this.getStateStore();
1323
+ if (!registry[ns]) registry[ns] = this.createDefaultState();
1324
+ registry[ns][key] = value;
1325
+ },
1326
+ configurable: true,
1327
+ enumerable: true
1328
+ });
1329
+ Object.defineProperty(this, this.stateBoundKey, {
1330
+ value: true,
1331
+ configurable: false,
1332
+ enumerable: false,
1333
+ writable: false
1334
+ });
1335
+ }
1336
+ static createDefaultOptionsHandler() {
1337
+ return (ctx) => {
1338
+ const allow = "GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD";
1339
+ if (ctx?.header && ctx?.status && ctx?.body) {
1340
+ ctx.header("Allow", allow);
1341
+ ctx.status(204);
1342
+ return ctx.body(null);
1343
+ }
1344
+ if (ctx?.res?.headers?.set) {
1345
+ ctx.res.headers.set("Allow", allow);
1346
+ ctx.res.status = 204;
1347
+ return;
1348
+ }
1349
+ if (ctx?.res?.set) {
1350
+ ctx.res.set("Allow", allow);
1351
+ ctx.res.sendStatus(204);
1352
+ return;
1353
+ }
1354
+ if (ctx?.reply?.header) {
1355
+ ctx.reply.header("Allow", allow);
1356
+ ctx.reply.code(204).send();
1357
+ return;
1358
+ }
1359
+ if (ctx?.set && "status" in ctx) {
1360
+ ctx.set("Allow", allow);
1361
+ ctx.status = 204;
1362
+ ctx.body = null;
1363
+ }
1364
+ };
1365
+ }
1366
+ /**
1367
+ * Default configuration used for everytime the router is reset
1368
+ *
1369
+ * @param options
1370
+ */
1371
+ static configureDefaults(options) {
1372
+ const g = globalThis;
1373
+ const defaults = this.mergeConfig(g[this.defaultConfigKey] || this.createBaseConfig(), options);
1374
+ g[this.defaultConfigKey] = defaults;
1375
+ const store = this.getStateStore();
1376
+ for (const state of Object.values(store)) state.config = this.mergeConfig(state.config || this.createBaseConfig(), options);
1377
+ }
1378
+ /**
1379
+ * Use a registered plugin
1380
+ *
1381
+ * @param this
1382
+ * @param plugin
1383
+ * @param options
1384
+ * @returns
1385
+ */
1386
+ static async use(plugin, options) {
1387
+ this.ensureState();
1388
+ const name = typeof plugin === "function" ? plugin.name : plugin.name;
1389
+ const store = this.getPluginStore();
1390
+ if (name && store.has(name)) return;
1391
+ if (name) store.add(name);
1392
+ const setup = async () => {
1393
+ const ctx = {
1394
+ container: this.container,
1395
+ bind: this.createPluginBind(),
1396
+ resolveArguments: (resolver) => {
1397
+ this.getPluginArgumentResolvers().add(resolver);
1398
+ },
1399
+ useHttpContext: (resolver) => {
1400
+ this.getPluginHttpCtxResolvers().add(resolver);
1401
+ },
1402
+ bindings: this.container.bindings(),
1403
+ configure: this.configure.bind(this),
1404
+ configureDefaults: this.configureDefaults.bind(this),
1405
+ get request() {
1406
+ return this.getRequest();
1407
+ },
1408
+ get response() {
1409
+ return this.getResponse();
1410
+ },
1411
+ getRequest: () => this.getCurrentPluginRequestContext()?.request,
1412
+ getResponse: () => this.getCurrentPluginRequestContext()?.response,
1413
+ options
1414
+ };
1415
+ if (typeof plugin === "function") await plugin(ctx);
1416
+ else await plugin.setup(ctx);
1417
+ };
1418
+ const pending = this.getPluginPendingStore();
1419
+ const promise = setup();
1420
+ pending.add(promise);
1421
+ try {
1422
+ await promise;
1423
+ } catch (error) {
1424
+ if (name) store.delete(name);
1425
+ throw error;
1426
+ } finally {
1427
+ pending.delete(promise);
1428
+ }
1429
+ }
1430
+ static async pluginsReady() {
1431
+ const pending = Array.from(this.getPluginPendingStore());
1432
+ if (!pending.length) return;
1433
+ await Promise.all(pending);
1434
+ }
1435
+ static getCurrentPluginRequestContext() {
1436
+ return this.pluginRequestContext.getStore();
1437
+ }
1438
+ static createPluginRequestContext(ctx) {
1439
+ const request = ctx.clearRequest;
1440
+ const response = ctx.clearResponse;
1441
+ return {
1442
+ ...ctx,
1443
+ ctx,
1444
+ request,
1445
+ response,
1446
+ getBindings: () => Container.current().bindings()
1447
+ };
1448
+ }
1449
+ static createPluginBind() {
1450
+ const bind = (token, value, options) => {
1451
+ if (value && typeof value === "object" && "useFactory" in value) {
1452
+ const factory = value.useFactory;
1453
+ this.container.bind(token, {
1454
+ ...value,
1455
+ useFactory: (ctx) => factory(this.createPluginRequestContext(ctx))
1456
+ });
1457
+ return;
1458
+ }
1459
+ if (typeof value === "function" && !isClass(value)) {
1460
+ const factory = value;
1461
+ this.container.bind(token, (ctx) => factory(this.createPluginRequestContext(ctx)), options);
1462
+ return;
1463
+ }
1464
+ this.container.bind(token, value, options);
1465
+ };
1466
+ return bind;
1467
+ }
1468
+ static async resolvePluginArguments(ctx, routeContext) {
1469
+ const resolvers = Array.from(this.getPluginArgumentResolvers());
1470
+ if (!resolvers.length) return void 0;
1471
+ const pluginContext = {
1472
+ ...this.createPluginRequestContext(ctx),
1473
+ ...routeContext
1474
+ };
1475
+ for (const resolver of resolvers) {
1476
+ const args = await resolver(pluginContext);
1477
+ if (Array.isArray(args)) return args;
1478
+ }
1479
+ }
1480
+ static async resolvePluginHttpCtx(ctx) {
1481
+ const resolvers = Array.from(this.getPluginHttpCtxResolvers());
1482
+ if (!resolvers.length) return void 0;
1483
+ const pluginContext = this.createPluginRequestContext(ctx);
1484
+ for (const resolver of resolvers) await resolver(pluginContext);
1485
+ }
1486
+ static ensureState() {
1487
+ this.bindStateAccessors();
1488
+ if (!this.config) this.config = { methodOverride: {
1489
+ enabled: true,
1490
+ bodyKeys: ["_method"],
1491
+ headerKeys: ["x-http-method"]
1492
+ } };
1493
+ if (!this.groupContext) this.groupContext = new AsyncLocalStorage();
1494
+ if (!this.routes || Array.isArray(this.routes)) this.routes = new Set(this.routes ?? []);
1495
+ if (!this.routesByPathMethod) this.routesByPathMethod = /* @__PURE__ */ new Map();
1496
+ if (!this.routesByMethod) this.routesByMethod = /* @__PURE__ */ new Map();
1497
+ if (!this.routesByName) this.routesByName = /* @__PURE__ */ new Map();
1498
+ if (typeof this.prefix !== "string") this.prefix = "";
1499
+ if (!Array.isArray(this.groupMiddlewares)) this.groupMiddlewares = [];
1500
+ if (!Array.isArray(this.globalMiddlewares)) this.globalMiddlewares = [];
1501
+ }
1502
+ /**
1503
+ * Normalizes a path by ensuring it starts with a single slash and does not have trailing
1504
+ * slashes, while preserving dynamic segments and parameters.
1505
+ *
1506
+ * @param path The path to normalize.
1507
+ * @returns The normalized path.
1508
+ */
1509
+ static normalizePath(path) {
1510
+ return "/" + path.split("/").filter(Boolean).join("/");
1511
+ }
1512
+ static parseRouteParameters(path) {
1513
+ const parameters = [];
1514
+ const seen = /* @__PURE__ */ new Set();
1515
+ const pattern = /\{([^{}]+)\}/g;
1516
+ let match;
1517
+ while ((match = pattern.exec(path)) !== null) {
1518
+ const raw = match[1].trim();
1519
+ const optional = raw.endsWith("?");
1520
+ const [name, field] = (optional ? raw.slice(0, -1) : raw).split(":", 2).map((part) => part.trim());
1521
+ if (!name || seen.has(name)) continue;
1522
+ seen.add(name);
1523
+ parameters.push({
1524
+ name,
1525
+ field: field || void 0,
1526
+ optional
1527
+ });
1528
+ }
1529
+ return parameters;
1530
+ }
1531
+ static expandRoutePath(path) {
1532
+ let paths = [""];
1533
+ const segments = this.normalizePath(path).split("/").filter(Boolean);
1534
+ for (const segment of segments) {
1535
+ const match = segment.match(/^\{([^{}]+)\}$/);
1536
+ if (!match) {
1537
+ paths = paths.map((current) => `${current}/${segment}`);
1538
+ continue;
1539
+ }
1540
+ const raw = match[1].trim();
1541
+ const optional = raw.endsWith("?");
1542
+ const [rawName] = (optional ? raw.slice(0, -1) : raw).split(":", 2);
1543
+ const name = rawName.trim();
1544
+ if (!name) continue;
1545
+ const parameterSegment = `/:${name}`;
1546
+ paths = optional ? paths.flatMap((current) => [current, `${current}${parameterSegment}`]) : paths.map((current) => `${current}${parameterSegment}`);
1547
+ }
1548
+ return paths.map((path) => path || "/");
1549
+ }
1550
+ static routeRegistrationPaths(path) {
1551
+ return this.expandRoutePath(path);
1552
+ }
1553
+ /**
1554
+ * Compile a host pattern such as `{account}.example.com` into a matcher and
1555
+ * the ordered list of placeholder names it captures. Results are memoized.
1556
+ *
1557
+ * @param pattern
1558
+ * @returns
1559
+ */
1560
+ static compileDomain(pattern) {
1561
+ const cached = this.domainMatcherCache.get(pattern);
1562
+ if (cached) return cached;
1563
+ const cleanPattern = pattern.split(":", 1)[0].trim();
1564
+ const escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, (match) => `\\${match}`);
1565
+ const placeholder = /\{([^{}]+)\}/g;
1566
+ const params = [];
1567
+ let source = "^";
1568
+ let lastIndex = 0;
1569
+ let match;
1570
+ while ((match = placeholder.exec(cleanPattern)) !== null) {
1571
+ source += escape(cleanPattern.slice(lastIndex, match.index));
1572
+ const raw = match[1].trim();
1573
+ const optional = raw.endsWith("?");
1574
+ const name = (optional ? raw.slice(0, -1) : raw).split(":", 1)[0].trim();
1575
+ params.push(name);
1576
+ source += optional ? "([^.]*)" : "([^.]+)";
1577
+ lastIndex = match.index + match[0].length;
1578
+ }
1579
+ source += escape(cleanPattern.slice(lastIndex));
1580
+ source += "$";
1581
+ const compiled = {
1582
+ regex: new RegExp(source, "i"),
1583
+ params
1584
+ };
1585
+ this.domainMatcherCache.set(pattern, compiled);
1586
+ return compiled;
1587
+ }
1588
+ /**
1589
+ * Match a host against a domain pattern, returning the captured parameters or
1590
+ * `null` when the host does not match.
1591
+ *
1592
+ * @param pattern
1593
+ * @param host
1594
+ * @returns
1595
+ */
1596
+ static matchDomain(pattern, host) {
1597
+ if (!pattern) return null;
1598
+ const cleanHost = String(host ?? "").split(":", 1)[0].trim().toLowerCase();
1599
+ const { regex, params } = this.compileDomain(pattern);
1600
+ const match = regex.exec(cleanHost);
1601
+ if (!match) return null;
1602
+ const result = {};
1603
+ params.forEach((name, index) => {
1604
+ const value = match[index + 1];
1605
+ if (typeof value !== "undefined") result[name] = decodeURIComponent(value);
1606
+ });
1607
+ return result;
1608
+ }
1609
+ /**
1610
+ * Best-effort extraction of the request host across every supported adapter
1611
+ * context shape (Express/Fastify plain headers, H3 `Headers`, Hono accessor,
1612
+ * Koa context).
1613
+ *
1614
+ * @param ctx
1615
+ * @returns
1616
+ */
1617
+ static extractHost(ctx) {
1618
+ const headers = ctx?.req?.headers ?? ctx?.headers;
1619
+ let host;
1620
+ if (headers) host = typeof headers.get === "function" ? headers.get("host") ?? headers.get(":authority") : headers.host ?? headers[":authority"];
1621
+ if (!host && typeof ctx?.req?.header === "function") host = ctx.req.header("host");
1622
+ if (!host && typeof ctx?.host === "string") host = ctx.host;
1623
+ if (Array.isArray(host)) host = host[0];
1624
+ return String(host ?? "").split(",", 1)[0].trim();
1625
+ }
1626
+ /**
1627
+ * Resolve the domain parameters for a route given the active request context.
1628
+ * Returns `null` when the route is not domain-constrained, `false` when it is
1629
+ * but the host does not match, or the captured parameters on a match.
1630
+ *
1631
+ * @param route
1632
+ * @param ctx
1633
+ * @returns
1634
+ */
1635
+ static matchRouteDomain(route, ctx) {
1636
+ if (!route.domainPattern) return null;
1637
+ return this.matchDomain(route.domainPattern, this.extractHost(ctx)) ?? false;
1638
+ }
1639
+ /**
1640
+ * Register a global pattern applied to every route parameter sharing the
1641
+ * given name (equivalent to Laravel's `Route::pattern`).
1642
+ *
1643
+ * @param name
1644
+ * @param pattern
1645
+ */
1646
+ static pattern(name, pattern) {
1647
+ this.ensureState();
1648
+ this.routePatterns.set(name, pattern);
1649
+ }
1650
+ /**
1651
+ * Register multiple global parameter patterns at once.
1652
+ *
1653
+ * @param patterns
1654
+ */
1655
+ static patterns(patterns) {
1656
+ for (const [name, pattern] of Object.entries(patterns)) this.pattern(name, pattern);
1657
+ }
1658
+ /**
1659
+ * Merge the global parameter patterns with the route's own constraints. Route
1660
+ * level constraints take precedence over global patterns.
1661
+ *
1662
+ * @param route
1663
+ * @returns
1664
+ */
1665
+ static resolveConstraints(route) {
1666
+ if (!this.routePatterns.size && !Object.keys(route.constraints).length) return route.constraints;
1667
+ return {
1668
+ ...Object.fromEntries(this.routePatterns),
1669
+ ...route.constraints
1670
+ };
1671
+ }
1672
+ /**
1673
+ * Compile a constraint pattern into a fully-anchored regular expression.
1674
+ *
1675
+ * @param pattern
1676
+ * @returns
1677
+ */
1678
+ static toConstraintRegex(pattern) {
1679
+ if (pattern instanceof RegExp) return new RegExp(`^(?:${pattern.source})$`, pattern.flags.replace("g", ""));
1680
+ const cached = this.constraintRegexCache.get(pattern);
1681
+ if (cached) return cached;
1682
+ const regex = new RegExp(`^(?:${pattern})$`);
1683
+ this.constraintRegexCache.set(pattern, regex);
1684
+ return regex;
1685
+ }
1686
+ /**
1687
+ * Determine whether the resolved parameters satisfy the route's constraints.
1688
+ * Absent parameters (e.g. optional ones) are ignored.
1689
+ *
1690
+ * @param route
1691
+ * @param params
1692
+ * @returns
1693
+ */
1694
+ static satisfiesConstraints(route, params) {
1695
+ const constraints = this.resolveConstraints(route);
1696
+ for (const name of Object.keys(constraints)) {
1697
+ const value = params[name];
1698
+ if (typeof value === "undefined" || value === null) continue;
1699
+ const values = Array.isArray(value) ? value : [value];
1700
+ const regex = this.toConstraintRegex(constraints[name]);
1701
+ if (!values.every((entry) => regex.test(String(entry)))) return false;
1702
+ }
1703
+ return true;
1704
+ }
1705
+ /**
1706
+ * Determine which of a route's parameters are allowed to span multiple path
1707
+ * segments (i.e. their constraint matches an encoded forward slash). These are
1708
+ * registered with the adapter's catch-all syntax.
1709
+ *
1710
+ * @param route
1711
+ * @returns
1712
+ */
1713
+ static wildcardParameters(route) {
1714
+ const wildcards = /* @__PURE__ */ new Set();
1715
+ const constraints = this.resolveConstraints(route);
1716
+ const declared = new Set(route.parameters.map((parameter) => parameter.name));
1717
+ for (const name of Object.keys(constraints)) {
1718
+ if (!declared.has(name)) continue;
1719
+ if (this.toConstraintRegex(constraints[name]).test("a/b")) wildcards.add(name);
1720
+ }
1721
+ return wildcards;
1722
+ }
1723
+ /**
1724
+ * Render a single wildcard (slash-spanning) parameter for the underlying
1725
+ * router's registration path. Overridden per adapter; the base form keeps the
1726
+ * plain `:name` placeholder.
1727
+ *
1728
+ * @param name
1729
+ * @returns
1730
+ */
1731
+ static formatWildcardParam(name) {
1732
+ return `:${name}`;
1733
+ }
1734
+ /**
1735
+ * Rewrite a route's registration paths so any wildcard parameters use the
1736
+ * adapter's catch-all syntax. Non-wildcard routes are returned unchanged.
1737
+ *
1738
+ * @param route
1739
+ * @returns
1740
+ */
1741
+ static resolveRegistrationPaths(route) {
1742
+ const wildcards = this.wildcardParameters(route);
1743
+ if (!wildcards.size) return route.registrationPaths;
1744
+ return route.registrationPaths.map((path) => path.split("/").map((segment) => {
1745
+ const name = segment.startsWith(":") ? segment.slice(1) : "";
1746
+ return name && wildcards.has(name) ? this.formatWildcardParam(name) : segment;
1747
+ }).join("/"));
1748
+ }
1749
+ /**
1750
+ * Resolve the final parameters for a dispatched route, applying domain
1751
+ * matching and constraint validation. Returns the merged parameters, or
1752
+ * `false` when the route should not handle the request (host mismatch or a
1753
+ * constraint failure) so the adapter can fall through.
1754
+ *
1755
+ * @param route
1756
+ * @param ctx
1757
+ * @param baseParams
1758
+ * @returns
1759
+ */
1760
+ static matchRoute(route, ctx, baseParams = {}) {
1761
+ const params = { ...baseParams ?? {} };
1762
+ if (route.domainPattern) {
1763
+ const domainParams = this.matchDomain(route.domainPattern, this.extractHost(ctx));
1764
+ if (!domainParams) return false;
1765
+ Object.assign(params, domainParams);
1766
+ }
1767
+ this.normalizeWildcardParams(route, params);
1768
+ if (!this.satisfiesConstraints(route, params)) return false;
1769
+ return params;
1770
+ }
1771
+ /**
1772
+ * Normalize wildcard (slash-spanning) parameters into a single string keyed by
1773
+ * the declared parameter name, smoothing over the differing shapes adapters
1774
+ * return (Express yields an array of segments, Fastify keys it under `*`).
1775
+ *
1776
+ * @param route
1777
+ * @param params
1778
+ */
1779
+ static normalizeWildcardParams(route, params) {
1780
+ const wildcards = this.wildcardParameters(route);
1781
+ if (!wildcards.size) return;
1782
+ for (const name of wildcards) {
1783
+ let value = params[name];
1784
+ if (typeof value === "undefined" && typeof params["*"] !== "undefined") {
1785
+ value = params["*"];
1786
+ delete params["*"];
1787
+ }
1788
+ if (Array.isArray(value)) value = value.join("/");
1789
+ if (typeof value !== "undefined") params[name] = value;
1790
+ }
1791
+ }
1792
+ /**
1793
+ * Get the route currently being dispatched, if any.
1794
+ *
1795
+ * @returns
1796
+ */
1797
+ static current() {
1798
+ const store = this.pluginRequestContext.getStore();
1799
+ return store?.request?.route ?? store?.ctx?.clearRequest?.route;
1800
+ }
1801
+ /**
1802
+ * Get the name of the route currently being dispatched.
1803
+ *
1804
+ * @returns
1805
+ */
1806
+ static currentRouteName() {
1807
+ return this.current()?.routeName ?? "";
1808
+ }
1809
+ /**
1810
+ * Get the action (`Controller@method` or `Closure`) of the route currently
1811
+ * being dispatched.
1812
+ *
1813
+ * @returns
1814
+ */
1815
+ static currentRouteAction() {
1816
+ return this.current()?.action ?? "";
1817
+ }
1818
+ /**
1819
+ * Configures the router with the given options, such as method override settings.
1820
+ *
1821
+ * @param this
1822
+ * @param options
1823
+ * @returns
1824
+ */
1825
+ static configure(options) {
1826
+ this.ensureState();
1827
+ this.config = this.mergeConfig(this.getDefaultConfig(), this.config);
1828
+ const container = options?.container;
1829
+ if (container) {
1830
+ if (typeof container.enabled === "boolean") this.config.container.enabled = container.enabled;
1831
+ if (typeof container.autoDiscover === "boolean") this.config.container.autoDiscover = container.autoDiscover;
1832
+ }
1833
+ if (options?.inferParamName) this.config.inferParamName = options?.inferParamName;
1834
+ const override = options?.methodOverride;
1835
+ if (override) {
1836
+ if (typeof override.enabled === "boolean") this.config.methodOverride.enabled = override.enabled;
1837
+ const bodyKeys = override.bodyKeys;
1838
+ if (typeof bodyKeys !== "undefined") this.config.methodOverride.bodyKeys = (Array.isArray(bodyKeys) ? bodyKeys : [bodyKeys]).map((e) => String(e).trim()).filter(Boolean);
1839
+ const headerKeys = override.headerKeys;
1840
+ if (typeof headerKeys !== "undefined") this.config.methodOverride.headerKeys = (Array.isArray(headerKeys) ? headerKeys : [headerKeys]).map((e) => String(e).trim().toLowerCase()).filter(Boolean);
1841
+ }
1842
+ }
1843
+ static resolveMethodOverride(method, headers, body) {
1844
+ this.ensureState();
1845
+ if (!this.config.methodOverride?.enabled || method.toLowerCase() !== "post") return null;
1846
+ let override;
1847
+ const headerValueFor = (key) => {
1848
+ if (typeof headers.get === "function") return headers.get(key);
1849
+ const value = headers?.[key];
1850
+ return Array.isArray(value) ? value[0] : value;
1851
+ };
1852
+ for (const key of this.config.methodOverride?.headerKeys || []) {
1853
+ const value = headerValueFor(key);
1854
+ if (value) {
1855
+ override = value;
1856
+ break;
1857
+ }
1858
+ }
1859
+ if (!override && body && typeof body === "object") for (const key of this.config.methodOverride?.bodyKeys || []) {
1860
+ const value = body[key];
1861
+ if (typeof value !== "undefined" && value !== null && value !== "") {
1862
+ override = value;
1863
+ break;
1864
+ }
1865
+ }
1866
+ const normalized = String(override || "").trim().toLowerCase();
1867
+ if (!normalized) return null;
1868
+ if ([
1869
+ "put",
1870
+ "patch",
1871
+ "delete",
1872
+ "post"
1873
+ ].includes(normalized)) return normalized;
1874
+ return null;
1875
+ }
1876
+ /**
1877
+ * Adds a new route to the router.
1878
+ *
1879
+ * @param this
1880
+ * @param methods
1881
+ * @param path
1882
+ * @param handler
1883
+ * @param middlewares
1884
+ */
1885
+ static add(methods, path, handler, middlewares) {
1886
+ this.ensureState();
1887
+ const context = this.groupContext.getStore();
1888
+ const activePrefix = context?.prefix ?? this.prefix;
1889
+ const activeGroupMiddlewares = context?.groupMiddlewares ?? this.groupMiddlewares;
1890
+ const activeDomain = context?.domain;
1891
+ methods = Array.isArray(methods) ? methods : [methods];
1892
+ middlewares = middlewares ? Array.isArray(middlewares) ? middlewares : [middlewares] : void 0;
1893
+ const fullPath = this.normalizePath(`${activePrefix}/${path}`);
1894
+ const registrationPaths = this.routeRegistrationPaths(fullPath);
1895
+ const parameters = this.parseRouteParameters(fullPath);
1896
+ for (const method of methods) {
1897
+ const existing = this.routesByPathMethod.get(`${method.toUpperCase()} ${fullPath}`);
1898
+ if (existing) this.removeRouteMethod(existing, method, fullPath);
1899
+ }
1900
+ const route = new Route(methods.includes("options") ? methods : methods.concat("options"), fullPath, handler, this.resolveMiddlewares([
1901
+ ...this.globalMiddlewares,
1902
+ ...activeGroupMiddlewares,
1903
+ ...getControllerMiddlewares(handler),
1904
+ ...middlewares || []
1905
+ ]), {
1906
+ registrationPaths,
1907
+ parameters,
1908
+ domain: activeDomain,
1909
+ onName: (name, route, previousName) => {
1910
+ if (previousName && this.routesByName.get(previousName) === route) this.routesByName.delete(previousName);
1911
+ this.routesByName.set(name, route);
1912
+ },
1913
+ normalizeMiddleware: (middleware) => this.resolveMiddleware(middleware)
1914
+ });
1915
+ if (!methods.includes("options") && !this.routesByPathMethod.get(`OPTIONS ${fullPath}`)) this.options(path, this.createDefaultOptionsHandler());
1916
+ this.routes.add(route);
1917
+ for (const collector of context?.routeCollectors ?? []) collector.add(route);
1918
+ for (const method of methods.map((m) => m.toUpperCase())) {
1919
+ this.routesByPathMethod.set(`${method} ${fullPath}`, route);
1920
+ if (!this.routesByMethod.has(method)) this.routesByMethod.set(method, []);
1921
+ this.routesByMethod.get(method)?.push(route);
1922
+ }
1923
+ return route;
1924
+ }
1925
+ /**
1926
+ * Define a resourceful API controller with standard CRUD routes.
1927
+ *
1928
+ * @param this
1929
+ * @param basePath
1930
+ * @param controller
1931
+ * @param options
1932
+ */
1933
+ static apiResource(basePath, controller, options) {
1934
+ let paramName = "id";
1935
+ if (!!this.config.inferParamName && this.hasPackageInstalled("@h3ravel/support")) {
1936
+ const { str } = createRequire(import.meta.url)("@h3ravel/support");
1937
+ paramName = str(basePath).singular().afterLast("/").camel().toString();
1938
+ }
1939
+ return new ResourceRoutes(basePath, controller, paramName, options, ({ method, path, handler, middlewares, name }) => {
1940
+ return this.add(method, path, handler, middlewares).name(name);
1941
+ }, (route) => this.removeRoute(route)).register();
1942
+ }
1943
+ /**
1944
+ * Adds a new GET route to the router.
1945
+ *
1946
+ * @param this The router instance.
1947
+ * @param path The path for the GET route.
1948
+ * @param handler The handler function for the GET route.
1949
+ * @param middlewares Optional middlewares to apply to the GET route.
1950
+ */
1951
+ static get(path, handler, middlewares) {
1952
+ return this.add("get", path, handler, middlewares);
1953
+ }
1954
+ /**
1955
+ * Adds a new POST route to the router.
1956
+ *
1957
+ * @param this
1958
+ * @param path
1959
+ * @param handler
1960
+ * @param middlewares
1961
+ */
1962
+ static post(path, handler, middlewares) {
1963
+ return this.add("post", path, handler, middlewares);
1964
+ }
1965
+ /**
1966
+ * Adds a new PUT route to the router.
1967
+ *
1968
+ * @param this
1969
+ * @param path
1970
+ * @param handler
1971
+ * @param middlewares
1972
+ */
1973
+ static put(path, handler, middlewares) {
1974
+ return this.add("put", path, handler, middlewares);
1975
+ }
1976
+ /**
1977
+ * Adds a new DELETE route to the router.
1978
+ *
1979
+ * @param this
1980
+ * @param path
1981
+ * @param handler
1982
+ * @param middlewares
1983
+ */
1984
+ static delete(path, handler, middlewares) {
1985
+ return this.add("delete", path, handler, middlewares);
1986
+ }
1987
+ /**
1988
+ * Adds a new PATCH route to the router.
1989
+ *
1990
+ * @param this
1991
+ * @param path
1992
+ * @param handler
1993
+ * @param middlewares
1994
+ */
1995
+ static patch(path, handler, middlewares) {
1996
+ return this.add("patch", path, handler, middlewares);
1997
+ }
1998
+ /**
1999
+ * Adds a new OPTIONS route to the router.
2000
+ *
2001
+ * @param this
2002
+ * @param path
2003
+ * @param handler
2004
+ * @param middlewares
2005
+ */
2006
+ static options(path, handler, middlewares) {
2007
+ return this.add("options", path, handler, middlewares);
2008
+ }
2009
+ /**
2010
+ * Adds a new HEAD route to the router.
2011
+ *
2012
+ * @param this
2013
+ * @param path
2014
+ * @param handler
2015
+ * @param middlewares
2016
+ */
2017
+ static head(path, handler, middlewares) {
2018
+ return this.add("head", path, handler, middlewares);
2019
+ }
2020
+ /**
2021
+ * Defines a group of routes with a common prefix.
2022
+ *
2023
+ * @param this
2024
+ * @param prefix
2025
+ * @param callback
2026
+ * @param middlewares
2027
+ */
2028
+ static group(prefix, source, middlewares) {
2029
+ return this.makeGroup(prefix, source, middlewares);
2030
+ }
2031
+ /**
2032
+ * Build a route group, optionally constrained to a host pattern. Shared by
2033
+ * `group` and the `domain` registrar.
2034
+ *
2035
+ * @param prefix
2036
+ * @param source
2037
+ * @param middlewares
2038
+ * @param extra
2039
+ */
2040
+ static makeGroup(prefix, source, middlewares, extra) {
2041
+ this.ensureState();
2042
+ return new RouteGroup({
2043
+ prefix,
2044
+ source,
2045
+ middlewares,
2046
+ domain: extra?.domain,
2047
+ context: this.groupContext,
2048
+ defaultPrefix: this.prefix,
2049
+ defaultMiddlewares: this.groupMiddlewares,
2050
+ normalizePath: (path) => this.normalizePath(path),
2051
+ removeRoute: (route) => this.removeRoute(route)
2052
+ });
2053
+ }
2054
+ /**
2055
+ * Begin a route registration constrained to a host pattern such as
2056
+ * `{account}.example.com`. Returns a registrar whose `.group()` registers the
2057
+ * routes under that domain (matched parameters become route parameters).
2058
+ *
2059
+ * @param pattern
2060
+ * @returns
2061
+ */
2062
+ static domain(pattern) {
2063
+ this.ensureState();
2064
+ return new RouteRegistrar((prefix, source, middlewares, extra) => this.makeGroup(prefix, source, middlewares, extra), { domain: pattern });
2065
+ }
2066
+ /**
2067
+ * Adds global middlewares to the router, which will be applied to all routes.
2068
+ *
2069
+ * @param this
2070
+ * @param middlewares
2071
+ * @param callback
2072
+ */
2073
+ static middleware(middlewares, callback) {
2074
+ this.ensureState();
2075
+ const prevMiddlewares = this.globalMiddlewares;
2076
+ this.globalMiddlewares = [...prevMiddlewares, ...middlewares || []];
2077
+ callback();
2078
+ this.globalMiddlewares = prevMiddlewares;
2079
+ }
2080
+ static allRoutes(type) {
2081
+ this.ensureState();
2082
+ if (type === "method") return Object.fromEntries(this.routesByMethod.entries());
2083
+ if (type === "path") return Object.fromEntries(this.routesByPathMethod.entries());
2084
+ if (type === "name") return Object.fromEntries(this.routesByName.entries());
2085
+ return Array.from(this.routes).filter((e) => e.methods.length > 1 || e.methods[0] !== "options");
2086
+ }
2087
+ static route(name) {
2088
+ this.ensureState();
2089
+ return this.routesByName.get(name);
2090
+ }
2091
+ static url(name, params) {
2092
+ return this.route(name)?.toPath(params);
2093
+ }
2094
+ /**
2095
+ * Provide a class that will overide the base Request instance
2096
+ *
2097
+ * @param provider
2098
+ */
2099
+ static setRequestProvider(provider) {
2100
+ this.requestProvider = provider;
2101
+ }
2102
+ /**
2103
+ * Provide a class that will overide the base Response instance
2104
+ *
2105
+ * @param provider
2106
+ */
2107
+ static setResponseProvider(provider) {
2108
+ this.responseProvider = provider;
2109
+ }
2110
+ static hasPackageInstalled(name) {
2111
+ try {
2112
+ createRequire(import.meta.url).resolve(name, { paths: [process.cwd()] });
2113
+ return true;
2114
+ } catch {
2115
+ return false;
2116
+ }
2117
+ }
2118
+ static initializeInstance(provider, args) {
2119
+ const isRequest = [
2120
+ "CoreRequest",
2121
+ "Request",
2122
+ "ClearRequest"
2123
+ ].includes(provider.name);
2124
+ const isResponse = [
2125
+ "CoreResponse",
2126
+ "Response",
2127
+ "ClearResponse"
2128
+ ].includes(provider.name);
2129
+ if (isRequest && this.requestProvider) return new this.requestProvider(args);
2130
+ else if (isResponse && this.responseProvider) return new this.responseProvider(args);
2131
+ return new provider(args);
2132
+ }
2133
+ static resolveHandler(route) {
2134
+ let handlerFunction;
2135
+ let instance = null;
2136
+ let bindingTarget;
2137
+ let bindingMethod;
2138
+ let bindingHandler;
2139
+ let bindingMetadata;
2140
+ if (typeof route.handler === "function") {
2141
+ handlerFunction = route.handler.bind(route);
2142
+ bindingTarget = route.handler;
2143
+ bindingHandler = route.handler;
2144
+ } else if (Array.isArray(route.handler) && route.handler.length === 2) {
2145
+ const [ControllerType, method] = route.handler;
2146
+ if (["function", "object"].includes(typeof ControllerType) && typeof ControllerType[method] === "function") {
2147
+ instance = ControllerType;
2148
+ handlerFunction = ControllerType[method].bind(ControllerType);
2149
+ bindingTarget = ControllerType;
2150
+ bindingMethod = method;
2151
+ bindingHandler = ControllerType[method];
2152
+ bindingMetadata = ControllerType[Symbol.metadata];
2153
+ } else if (typeof ControllerType === "function") {
2154
+ instance = new ControllerType();
2155
+ if (typeof instance[method] === "function") {
2156
+ handlerFunction = instance[method].bind(instance);
2157
+ bindingTarget = ControllerType.prototype;
2158
+ bindingMethod = method;
2159
+ bindingHandler = instance[method];
2160
+ bindingMetadata = ControllerType[Symbol.metadata];
2161
+ } else throw new Error(`Method "${method}" not found in controller instance "${ControllerType.name}"`);
2162
+ } else throw new Error(`Invalid controller type for route: ${route.path}`);
2163
+ } else throw new Error(`Invalid handler format for route: ${route.path}`);
2164
+ return {
2165
+ handlerFunction,
2166
+ instance,
2167
+ bindingTarget,
2168
+ bindingMethod,
2169
+ bindingHandler,
2170
+ bindingMetadata
2171
+ };
2172
+ }
2173
+ static async callHandler(handlerFunction, ctx, bindingTarget, bindingMethod, bindingHandler, bindingMetadata) {
2174
+ this.ensureState();
2175
+ const requestContainer = this.container.createRequestScope(ctx);
2176
+ return Container.run(requestContainer, () => this.pluginRequestContext.run(this.createPluginRequestContext(ctx), async () => {
2177
+ await this.pluginsReady();
2178
+ await this.resolvePluginHttpCtx(ctx);
2179
+ if (!this.config.container?.enabled) return handlerFunction(ctx, ctx.clearRequest);
2180
+ const designTokens = [...bindingTarget ? getDesignParamTypes(bindingTarget, bindingMethod) : [], ...bindingHandler ? getDesignParamTypes(bindingHandler) : []];
2181
+ const metadata = getBindingMetadataFromTargets([
2182
+ {
2183
+ target: bindingTarget,
2184
+ propertyKey: bindingMethod
2185
+ },
2186
+ { target: bindingHandler },
2187
+ {
2188
+ target: bindingTarget,
2189
+ propertyKey: "__class__"
2190
+ }
2191
+ ]) ?? getStandardMetadata$1(bindingMetadata, bindingMethod) ?? getStandardMetadata$1(bindingMetadata, "__class__");
2192
+ const tokens = metadata?.tokens?.length ? metadata.tokens : designTokens;
2193
+ const pluginArgs = await this.resolvePluginArguments(ctx, {
2194
+ target: bindingTarget,
2195
+ method: bindingMethod,
2196
+ handler: bindingHandler,
2197
+ metadata: bindingMetadata,
2198
+ tokens,
2199
+ designTokens
2200
+ });
2201
+ if (pluginArgs?.length) return handlerFunction(...pluginArgs);
2202
+ if (!metadata || !tokens.length) return handlerFunction(ctx, ctx.clearRequest);
2203
+ const args = [];
2204
+ for (const token of tokens) {
2205
+ const resolved = this.config.container?.strict ? await requestContainer.resolveOrFail(token, ctx, Boolean(this.config.container?.autoDiscover)) : await requestContainer.resolve(token, ctx, Boolean(this.config.container?.autoDiscover));
2206
+ if (typeof resolved === "undefined") return handlerFunction(ctx, ctx.clearRequest);
2207
+ args.push(resolved);
2208
+ }
2209
+ return handlerFunction(...args);
2210
+ }));
2211
+ }
2212
+ static bindRequestToInstance(ctx, instance, route, payload) {
2213
+ const clearRequest = ctx.clearRequest instanceof Request ? ctx.clearRequest : this.initializeInstance(Request, {
2214
+ ctx,
2215
+ route,
2216
+ body: payload.body,
2217
+ query: payload.query,
2218
+ params: payload.params,
2219
+ method: String(payload.method || ctx.req?.method || ctx.method || "GET").toUpperCase(),
2220
+ path: String(ctx.path || ctx.req?.path || ctx.req?.url || route.path),
2221
+ url: String(ctx.url || ctx.req?.url || ctx.req?.originalUrl || route.path),
2222
+ headers: ctx.req?.headers || ctx.headers || {},
2223
+ original: ctx.req || ctx.request || ctx
2224
+ });
2225
+ clearRequest.ctx = ctx;
2226
+ clearRequest.route = route;
2227
+ clearRequest.body = payload.body;
2228
+ clearRequest.query = payload.query;
2229
+ clearRequest.params = payload.params;
2230
+ ctx.clearRequest = clearRequest;
2231
+ if (!(ctx.clearResponse instanceof Response)) ctx.clearResponse = this.initializeInstance(Response, ctx.response ?? ctx.reply ?? ctx.res);
2232
+ if (!instance) return;
2233
+ instance.ctx = ctx;
2234
+ instance.body = payload.body;
2235
+ instance.query = payload.query;
2236
+ instance.params = payload.params;
2237
+ instance.clearRequest = clearRequest;
2238
+ }
2239
+ };
2240
+ /**
2241
+ * Expose the active request's route through the `Route` facade (`Route.current()`,
2242
+ * `Route.currentRouteName()`, `Route.currentRouteAction()`) by delegating to the
2243
+ * shared router request context.
2244
+ */
2245
+ Route.bindCurrentResolvers({
2246
+ current: () => CoreRouter.current(),
2247
+ currentRouteName: () => CoreRouter.currentRouteName(),
2248
+ currentRouteAction: () => CoreRouter.currentRouteAction()
2249
+ });
2250
+ //#endregion
2251
+ //#region ../../node_modules/.pnpm/dayjs@1.11.20/node_modules/dayjs/plugin/customParseFormat.js
2252
+ var require_customParseFormat = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2253
+ (function(e, t) {
2254
+ "object" == typeof exports && "undefined" != typeof module ? module.exports = t() : "function" == typeof define && define.amd ? define(t) : (e = "undefined" != typeof globalThis ? globalThis : e || self).dayjs_plugin_customParseFormat = t();
2255
+ })(exports, (function() {
2256
+ "use strict";
2257
+ var e = {
2258
+ LTS: "h:mm:ss A",
2259
+ LT: "h:mm A",
2260
+ L: "MM/DD/YYYY",
2261
+ LL: "MMMM D, YYYY",
2262
+ LLL: "MMMM D, YYYY h:mm A",
2263
+ LLLL: "dddd, MMMM D, YYYY h:mm A"
2264
+ }, t = /(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|Q|YYYY|YY?|ww?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g, n = /\d/, r = /\d\d/, i = /\d\d?/, o = /\d*[^-_:/,()\s\d]+/, s = {}, a = function(e) {
2265
+ return (e = +e) + (e > 68 ? 1900 : 2e3);
2266
+ };
2267
+ var f = function(e) {
2268
+ return function(t) {
2269
+ this[e] = +t;
2270
+ };
2271
+ }, h = [/[+-]\d\d:?(\d\d)?|Z/, function(e) {
2272
+ (this.zone || (this.zone = {})).offset = function(e) {
2273
+ if (!e) return 0;
2274
+ if ("Z" === e) return 0;
2275
+ var t = e.match(/([+-]|\d\d)/g), n = 60 * t[1] + (+t[2] || 0);
2276
+ return 0 === n ? 0 : "+" === t[0] ? -n : n;
2277
+ }(e);
2278
+ }], u = function(e) {
2279
+ var t = s[e];
2280
+ return t && (t.indexOf ? t : t.s.concat(t.f));
2281
+ }, d = function(e, t) {
2282
+ var n, r = s.meridiem;
2283
+ if (r) {
2284
+ for (var i = 1; i <= 24; i += 1) if (e.indexOf(r(i, 0, t)) > -1) {
2285
+ n = i > 12;
2286
+ break;
2287
+ }
2288
+ } else n = e === (t ? "pm" : "PM");
2289
+ return n;
2290
+ }, c = {
2291
+ A: [o, function(e) {
2292
+ this.afternoon = d(e, !1);
2293
+ }],
2294
+ a: [o, function(e) {
2295
+ this.afternoon = d(e, !0);
2296
+ }],
2297
+ Q: [n, function(e) {
2298
+ this.month = 3 * (e - 1) + 1;
2299
+ }],
2300
+ S: [n, function(e) {
2301
+ this.milliseconds = 100 * +e;
2302
+ }],
2303
+ SS: [r, function(e) {
2304
+ this.milliseconds = 10 * +e;
2305
+ }],
2306
+ SSS: [/\d{3}/, function(e) {
2307
+ this.milliseconds = +e;
2308
+ }],
2309
+ s: [i, f("seconds")],
2310
+ ss: [i, f("seconds")],
2311
+ m: [i, f("minutes")],
2312
+ mm: [i, f("minutes")],
2313
+ H: [i, f("hours")],
2314
+ h: [i, f("hours")],
2315
+ HH: [i, f("hours")],
2316
+ hh: [i, f("hours")],
2317
+ D: [i, f("day")],
2318
+ DD: [r, f("day")],
2319
+ Do: [o, function(e) {
2320
+ var t = s.ordinal, n = e.match(/\d+/);
2321
+ if (this.day = n[0], t) for (var r = 1; r <= 31; r += 1) t(r).replace(/\[|\]/g, "") === e && (this.day = r);
2322
+ }],
2323
+ w: [i, f("week")],
2324
+ ww: [r, f("week")],
2325
+ M: [i, f("month")],
2326
+ MM: [r, f("month")],
2327
+ MMM: [o, function(e) {
2328
+ var t = u("months"), n = (u("monthsShort") || t.map((function(e) {
2329
+ return e.slice(0, 3);
2330
+ }))).indexOf(e) + 1;
2331
+ if (n < 1) throw new Error();
2332
+ this.month = n % 12 || n;
2333
+ }],
2334
+ MMMM: [o, function(e) {
2335
+ var t = u("months").indexOf(e) + 1;
2336
+ if (t < 1) throw new Error();
2337
+ this.month = t % 12 || t;
2338
+ }],
2339
+ Y: [/[+-]?\d+/, f("year")],
2340
+ YY: [r, function(e) {
2341
+ this.year = a(e);
2342
+ }],
2343
+ YYYY: [/\d{4}/, f("year")],
2344
+ Z: h,
2345
+ ZZ: h
2346
+ };
2347
+ function l(n) {
2348
+ var r = n, i = s && s.formats;
2349
+ for (var o = (n = r.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g, (function(t, n, r) {
2350
+ var o = r && r.toUpperCase();
2351
+ return n || i[r] || e[r] || i[o].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g, (function(e, t, n) {
2352
+ return t || n.slice(1);
2353
+ }));
2354
+ }))).match(t), a = o.length, f = 0; f < a; f += 1) {
2355
+ var h = o[f], u = c[h], d = u && u[0], l = u && u[1];
2356
+ o[f] = l ? {
2357
+ regex: d,
2358
+ parser: l
2359
+ } : h.replace(/^\[|\]$/g, "");
2360
+ }
2361
+ return function(e) {
2362
+ for (var t = {}, n = 0, r = 0; n < a; n += 1) {
2363
+ var i = o[n];
2364
+ if ("string" == typeof i) r += i.length;
2365
+ else {
2366
+ var s = i.regex, f = i.parser, h = e.slice(r), u = s.exec(h)[0];
2367
+ f.call(t, u), e = e.replace(u, "");
2368
+ }
2369
+ }
2370
+ return function(e) {
2371
+ var t = e.afternoon;
2372
+ if (void 0 !== t) {
2373
+ var n = e.hours;
2374
+ t ? n < 12 && (e.hours += 12) : 12 === n && (e.hours = 0), delete e.afternoon;
2375
+ }
2376
+ }(t), t;
2377
+ };
2378
+ }
2379
+ return function(e, t, n) {
2380
+ n.p.customParseFormat = !0, e && e.parseTwoDigitYear && (a = e.parseTwoDigitYear);
2381
+ var r = t.prototype, i = r.parse;
2382
+ r.parse = function(e) {
2383
+ var t = e.date, r = e.utc, o = e.args;
2384
+ this.$u = r;
2385
+ var a = o[1];
2386
+ if ("string" == typeof a) {
2387
+ var f = !0 === o[2], h = !0 === o[3], u = f || h, d = o[2];
2388
+ h && (d = o[2]), s = this.$locale(), !f && d && (s = n.Ls[d]), this.$d = function(e, t, n, r) {
2389
+ try {
2390
+ if (["x", "X"].indexOf(t) > -1) return /* @__PURE__ */ new Date(("X" === t ? 1e3 : 1) * e);
2391
+ var i = l(t)(e), o = i.year, s = i.month, a = i.day, f = i.hours, h = i.minutes, u = i.seconds, d = i.milliseconds, c = i.zone, m = i.week, M = /* @__PURE__ */ new Date(), Y = a || (o || s ? 1 : M.getDate()), p = o || M.getFullYear(), v = 0;
2392
+ o && !s || (v = s > 0 ? s - 1 : M.getMonth());
2393
+ var D, w = f || 0, g = h || 0, y = u || 0, L = d || 0;
2394
+ return c ? new Date(Date.UTC(p, v, Y, w, g, y, L + 60 * c.offset * 1e3)) : n ? new Date(Date.UTC(p, v, Y, w, g, y, L)) : (D = new Date(p, v, Y, w, g, y, L), m && (D = r(D).week(m).toDate()), D);
2395
+ } catch (e) {
2396
+ return /* @__PURE__ */ new Date("");
2397
+ }
2398
+ }(t, a, r, n), this.init(), d && !0 !== d && (this.$L = this.locale(d).$L), u && t != this.format(a) && (this.$d = /* @__PURE__ */ new Date("")), s = {};
2399
+ } else if (a instanceof Array) for (var c = a.length, m = 1; m <= c; m += 1) {
2400
+ o[1] = a[m - 1];
2401
+ var M = n.apply(this, o);
2402
+ if (M.isValid()) {
2403
+ this.$d = M.$d, this.$L = M.$L, this.init();
2404
+ break;
2405
+ }
2406
+ m === c && (this.$d = /* @__PURE__ */ new Date(""));
2407
+ }
2408
+ else i.call(this, e);
2409
+ };
2410
+ };
2411
+ }));
2412
+ }));
2413
+ //#endregion
2414
+ //#region ../../node_modules/.pnpm/dayjs@1.11.20/node_modules/dayjs/dayjs.min.js
2415
+ var require_dayjs_min = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2416
+ (function(t, e) {
2417
+ "object" == typeof exports && "undefined" != typeof module ? module.exports = e() : "function" == typeof define && define.amd ? define(e) : (t = "undefined" != typeof globalThis ? globalThis : t || self).dayjs = e();
2418
+ })(exports, (function() {
2419
+ "use strict";
2420
+ var t = 1e3, e = 6e4, n = 36e5, r = "millisecond", i = "second", s = "minute", u = "hour", a = "day", o = "week", c = "month", f = "quarter", h = "year", d = "date", l = "Invalid Date", $ = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/, y = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g, M = {
2421
+ name: "en",
2422
+ weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
2423
+ months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
2424
+ ordinal: function(t) {
2425
+ var e = [
2426
+ "th",
2427
+ "st",
2428
+ "nd",
2429
+ "rd"
2430
+ ], n = t % 100;
2431
+ return "[" + t + (e[(n - 20) % 10] || e[n] || e[0]) + "]";
2432
+ }
2433
+ }, m = function(t, e, n) {
2434
+ var r = String(t);
2435
+ return !r || r.length >= e ? t : "" + Array(e + 1 - r.length).join(n) + t;
2436
+ }, v = {
2437
+ s: m,
2438
+ z: function(t) {
2439
+ var e = -t.utcOffset(), n = Math.abs(e), r = Math.floor(n / 60), i = n % 60;
2440
+ return (e <= 0 ? "+" : "-") + m(r, 2, "0") + ":" + m(i, 2, "0");
2441
+ },
2442
+ m: function t(e, n) {
2443
+ if (e.date() < n.date()) return -t(n, e);
2444
+ var r = 12 * (n.year() - e.year()) + (n.month() - e.month()), i = e.clone().add(r, c), s = n - i < 0, u = e.clone().add(r + (s ? -1 : 1), c);
2445
+ return +(-(r + (n - i) / (s ? i - u : u - i)) || 0);
2446
+ },
2447
+ a: function(t) {
2448
+ return t < 0 ? Math.ceil(t) || 0 : Math.floor(t);
2449
+ },
2450
+ p: function(t) {
2451
+ return {
2452
+ M: c,
2453
+ y: h,
2454
+ w: o,
2455
+ d: a,
2456
+ D: d,
2457
+ h: u,
2458
+ m: s,
2459
+ s: i,
2460
+ ms: r,
2461
+ Q: f
2462
+ }[t] || String(t || "").toLowerCase().replace(/s$/, "");
2463
+ },
2464
+ u: function(t) {
2465
+ return void 0 === t;
2466
+ }
2467
+ }, g = "en", D = {};
2468
+ D[g] = M;
2469
+ var p = "$isDayjsObject", S = function(t) {
2470
+ return t instanceof _ || !(!t || !t[p]);
2471
+ }, w = function t(e, n, r) {
2472
+ var i;
2473
+ if (!e) return g;
2474
+ if ("string" == typeof e) {
2475
+ var s = e.toLowerCase();
2476
+ D[s] && (i = s), n && (D[s] = n, i = s);
2477
+ var u = e.split("-");
2478
+ if (!i && u.length > 1) return t(u[0]);
2479
+ } else {
2480
+ var a = e.name;
2481
+ D[a] = e, i = a;
2482
+ }
2483
+ return !r && i && (g = i), i || !r && g;
2484
+ }, O = function(t, e) {
2485
+ if (S(t)) return t.clone();
2486
+ var n = "object" == typeof e ? e : {};
2487
+ return n.date = t, n.args = arguments, new _(n);
2488
+ }, b = v;
2489
+ b.l = w, b.i = S, b.w = function(t, e) {
2490
+ return O(t, {
2491
+ locale: e.$L,
2492
+ utc: e.$u,
2493
+ x: e.$x,
2494
+ $offset: e.$offset
2495
+ });
2496
+ };
2497
+ var _ = function() {
2498
+ function M(t) {
2499
+ this.$L = w(t.locale, null, !0), this.parse(t), this.$x = this.$x || t.x || {}, this[p] = !0;
2500
+ }
2501
+ var m = M.prototype;
2502
+ return m.parse = function(t) {
2503
+ this.$d = function(t) {
2504
+ var e = t.date, n = t.utc;
2505
+ if (null === e) return /* @__PURE__ */ new Date(NaN);
2506
+ if (b.u(e)) return /* @__PURE__ */ new Date();
2507
+ if (e instanceof Date) return new Date(e);
2508
+ if ("string" == typeof e && !/Z$/i.test(e)) {
2509
+ var r = e.match($);
2510
+ if (r) {
2511
+ var i = r[2] - 1 || 0, s = (r[7] || "0").substring(0, 3);
2512
+ return n ? new Date(Date.UTC(r[1], i, r[3] || 1, r[4] || 0, r[5] || 0, r[6] || 0, s)) : new Date(r[1], i, r[3] || 1, r[4] || 0, r[5] || 0, r[6] || 0, s);
2513
+ }
2514
+ }
2515
+ return new Date(e);
2516
+ }(t), this.init();
2517
+ }, m.init = function() {
2518
+ var t = this.$d;
2519
+ this.$y = t.getFullYear(), this.$M = t.getMonth(), this.$D = t.getDate(), this.$W = t.getDay(), this.$H = t.getHours(), this.$m = t.getMinutes(), this.$s = t.getSeconds(), this.$ms = t.getMilliseconds();
2520
+ }, m.$utils = function() {
2521
+ return b;
2522
+ }, m.isValid = function() {
2523
+ return !(this.$d.toString() === l);
2524
+ }, m.isSame = function(t, e) {
2525
+ var n = O(t);
2526
+ return this.startOf(e) <= n && n <= this.endOf(e);
2527
+ }, m.isAfter = function(t, e) {
2528
+ return O(t) < this.startOf(e);
2529
+ }, m.isBefore = function(t, e) {
2530
+ return this.endOf(e) < O(t);
2531
+ }, m.$g = function(t, e, n) {
2532
+ return b.u(t) ? this[e] : this.set(n, t);
2533
+ }, m.unix = function() {
2534
+ return Math.floor(this.valueOf() / 1e3);
2535
+ }, m.valueOf = function() {
2536
+ return this.$d.getTime();
2537
+ }, m.startOf = function(t, e) {
2538
+ var n = this, r = !!b.u(e) || e, f = b.p(t), l = function(t, e) {
2539
+ var i = b.w(n.$u ? Date.UTC(n.$y, e, t) : new Date(n.$y, e, t), n);
2540
+ return r ? i : i.endOf(a);
2541
+ }, $ = function(t, e) {
2542
+ return b.w(n.toDate()[t].apply(n.toDate("s"), (r ? [
2543
+ 0,
2544
+ 0,
2545
+ 0,
2546
+ 0
2547
+ ] : [
2548
+ 23,
2549
+ 59,
2550
+ 59,
2551
+ 999
2552
+ ]).slice(e)), n);
2553
+ }, y = this.$W, M = this.$M, m = this.$D, v = "set" + (this.$u ? "UTC" : "");
2554
+ switch (f) {
2555
+ case h: return r ? l(1, 0) : l(31, 11);
2556
+ case c: return r ? l(1, M) : l(0, M + 1);
2557
+ case o:
2558
+ var g = this.$locale().weekStart || 0, D = (y < g ? y + 7 : y) - g;
2559
+ return l(r ? m - D : m + (6 - D), M);
2560
+ case a:
2561
+ case d: return $(v + "Hours", 0);
2562
+ case u: return $(v + "Minutes", 1);
2563
+ case s: return $(v + "Seconds", 2);
2564
+ case i: return $(v + "Milliseconds", 3);
2565
+ default: return this.clone();
2566
+ }
2567
+ }, m.endOf = function(t) {
2568
+ return this.startOf(t, !1);
2569
+ }, m.$set = function(t, e) {
2570
+ var n, o = b.p(t), f = "set" + (this.$u ? "UTC" : ""), l = (n = {}, n[a] = f + "Date", n[d] = f + "Date", n[c] = f + "Month", n[h] = f + "FullYear", n[u] = f + "Hours", n[s] = f + "Minutes", n[i] = f + "Seconds", n[r] = f + "Milliseconds", n)[o], $ = o === a ? this.$D + (e - this.$W) : e;
2571
+ if (o === c || o === h) {
2572
+ var y = this.clone().set(d, 1);
2573
+ y.$d[l]($), y.init(), this.$d = y.set(d, Math.min(this.$D, y.daysInMonth())).$d;
2574
+ } else l && this.$d[l]($);
2575
+ return this.init(), this;
2576
+ }, m.set = function(t, e) {
2577
+ return this.clone().$set(t, e);
2578
+ }, m.get = function(t) {
2579
+ return this[b.p(t)]();
2580
+ }, m.add = function(r, f) {
2581
+ var d, l = this;
2582
+ r = Number(r);
2583
+ var $ = b.p(f), y = function(t) {
2584
+ var e = O(l);
2585
+ return b.w(e.date(e.date() + Math.round(t * r)), l);
2586
+ };
2587
+ if ($ === c) return this.set(c, this.$M + r);
2588
+ if ($ === h) return this.set(h, this.$y + r);
2589
+ if ($ === a) return y(1);
2590
+ if ($ === o) return y(7);
2591
+ var M = (d = {}, d[s] = e, d[u] = n, d[i] = t, d)[$] || 1, m = this.$d.getTime() + r * M;
2592
+ return b.w(m, this);
2593
+ }, m.subtract = function(t, e) {
2594
+ return this.add(-1 * t, e);
2595
+ }, m.format = function(t) {
2596
+ var e = this, n = this.$locale();
2597
+ if (!this.isValid()) return n.invalidDate || l;
2598
+ var r = t || "YYYY-MM-DDTHH:mm:ssZ", i = b.z(this), s = this.$H, u = this.$m, a = this.$M, o = n.weekdays, c = n.months, f = n.meridiem, h = function(t, n, i, s) {
2599
+ return t && (t[n] || t(e, r)) || i[n].slice(0, s);
2600
+ }, d = function(t) {
2601
+ return b.s(s % 12 || 12, t, "0");
2602
+ }, $ = f || function(t, e, n) {
2603
+ var r = t < 12 ? "AM" : "PM";
2604
+ return n ? r.toLowerCase() : r;
2605
+ };
2606
+ return r.replace(y, (function(t, r) {
2607
+ return r || function(t) {
2608
+ switch (t) {
2609
+ case "YY": return String(e.$y).slice(-2);
2610
+ case "YYYY": return b.s(e.$y, 4, "0");
2611
+ case "M": return a + 1;
2612
+ case "MM": return b.s(a + 1, 2, "0");
2613
+ case "MMM": return h(n.monthsShort, a, c, 3);
2614
+ case "MMMM": return h(c, a);
2615
+ case "D": return e.$D;
2616
+ case "DD": return b.s(e.$D, 2, "0");
2617
+ case "d": return String(e.$W);
2618
+ case "dd": return h(n.weekdaysMin, e.$W, o, 2);
2619
+ case "ddd": return h(n.weekdaysShort, e.$W, o, 3);
2620
+ case "dddd": return o[e.$W];
2621
+ case "H": return String(s);
2622
+ case "HH": return b.s(s, 2, "0");
2623
+ case "h": return d(1);
2624
+ case "hh": return d(2);
2625
+ case "a": return $(s, u, !0);
2626
+ case "A": return $(s, u, !1);
2627
+ case "m": return String(u);
2628
+ case "mm": return b.s(u, 2, "0");
2629
+ case "s": return String(e.$s);
2630
+ case "ss": return b.s(e.$s, 2, "0");
2631
+ case "SSS": return b.s(e.$ms, 3, "0");
2632
+ case "Z": return i;
2633
+ }
2634
+ return null;
2635
+ }(t) || i.replace(":", "");
2636
+ }));
2637
+ }, m.utcOffset = function() {
2638
+ return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
2639
+ }, m.diff = function(r, d, l) {
2640
+ var $, y = this, M = b.p(d), m = O(r), v = (m.utcOffset() - this.utcOffset()) * e, g = this - m, D = function() {
2641
+ return b.m(y, m);
2642
+ };
2643
+ switch (M) {
2644
+ case h:
2645
+ $ = D() / 12;
2646
+ break;
2647
+ case c:
2648
+ $ = D();
2649
+ break;
2650
+ case f:
2651
+ $ = D() / 3;
2652
+ break;
2653
+ case o:
2654
+ $ = (g - v) / 6048e5;
2655
+ break;
2656
+ case a:
2657
+ $ = (g - v) / 864e5;
2658
+ break;
2659
+ case u:
2660
+ $ = g / n;
2661
+ break;
2662
+ case s:
2663
+ $ = g / e;
2664
+ break;
2665
+ case i:
2666
+ $ = g / t;
2667
+ break;
2668
+ default: $ = g;
2669
+ }
2670
+ return l ? $ : b.a($);
2671
+ }, m.daysInMonth = function() {
2672
+ return this.endOf(c).$D;
2673
+ }, m.$locale = function() {
2674
+ return D[this.$L];
2675
+ }, m.locale = function(t, e) {
2676
+ if (!t) return this.$L;
2677
+ var n = this.clone(), r = w(t, e, !0);
2678
+ return r && (n.$L = r), n;
2679
+ }, m.clone = function() {
2680
+ return b.w(this.$d, this);
2681
+ }, m.toDate = function() {
2682
+ return new Date(this.valueOf());
2683
+ }, m.toJSON = function() {
2684
+ return this.isValid() ? this.toISOString() : null;
2685
+ }, m.toISOString = function() {
2686
+ return this.$d.toISOString();
2687
+ }, m.toString = function() {
2688
+ return this.$d.toUTCString();
2689
+ }, M;
2690
+ }(), k = _.prototype;
2691
+ return O.prototype = k, [
2692
+ ["$ms", r],
2693
+ ["$s", i],
2694
+ ["$m", s],
2695
+ ["$H", u],
2696
+ ["$W", a],
2697
+ ["$M", c],
2698
+ ["$y", h],
2699
+ ["$D", d]
2700
+ ].forEach((function(t) {
2701
+ k[t[1]] = function(e) {
2702
+ return this.$g(e, t[0], t[1]);
2703
+ };
2704
+ })), O.extend = function(t, e) {
2705
+ return t.$i || (t(e, _, O), t.$i = !0), O;
2706
+ }, O.locale = w, O.isDayjs = S, O.unix = function(t) {
2707
+ return O(1e3 * t);
2708
+ }, O.en = D[g], O.Ls = D, O.p = {}, O;
2709
+ }));
2710
+ }));
2711
+ //#endregion
2712
+ //#region ../../node_modules/.pnpm/kanun@1.2.0/node_modules/kanun/dist/index.js
2713
+ var import_customParseFormat = /* @__PURE__ */ __toESM(require_customParseFormat(), 1);
2714
+ var import_dayjs_min = /* @__PURE__ */ __toESM(require_dayjs_min(), 1);
2715
+ new AsyncLocalStorage();
2716
+ var locales_default = {
2717
+ en: {
2718
+ accepted: "The :attribute must be accepted.",
2719
+ accepted_if: "The :attribute must be accepted when :other is :value.",
2720
+ after: "The :attribute must be a date after :date.",
2721
+ after_or_equal: "The :attribute must be a date after or equal to :date.",
2722
+ alpha: "The :attribute must only contain letters.",
2723
+ alpha_dash: "The :attribute must only contain at least one letter or one number, and optionally dashes and underscores.",
2724
+ alpha_num: "The :attribute must only contain letters and numbers.",
2725
+ array: "The :attribute must be an array.",
2726
+ array_unique: "The :attribute must be an array with unique values.",
2727
+ before: "The :attribute must be a date before :date.",
2728
+ before_or_equal: "The :attribute must be a date before or equal to :date.",
2729
+ between: {
2730
+ number: "The :attribute must be between :min and :max.",
2731
+ string: "The :attribute must be between :min and :max characters.",
2732
+ array: "The :attribute must have between :min and :max items.",
2733
+ object: "The :attribute must have between :min and :max items."
2734
+ },
2735
+ boolean: "The :attribute field must be true or false.",
2736
+ confirmed: "The :attribute confirmation does not match.",
2737
+ date: "The :attribute is not a valid date.",
2738
+ datetime: "The :attribute must be a valid date matching the format :format.",
2739
+ date_equals: "The :attribute must be a date equal to :date.",
2740
+ declined: "The :attribute must be declined.",
2741
+ declined_if: "The :attribute must be declined when :other is :value.",
2742
+ different: "The :attribute and :other must be different.",
2743
+ distinct: "The :attribute field has a duplicate value.",
2744
+ digits: "The :attribute must be :digits digits.",
2745
+ digits_between: "The :attribute must be between :min and :max digits.",
2746
+ email: "The :attribute must be a valid email address.",
2747
+ ends_with: "The :attribute must end with one of the following: :values.",
2748
+ filled: "The :attribute field must have a value.",
2749
+ exists: "The selected :attribute is invalid.",
2750
+ gt: {
2751
+ number: "The :attribute must be greater than :value.",
2752
+ string: "The :attribute must be greater than :value characters.",
2753
+ array: "The :attribute must have more than :value items.",
2754
+ object: "The :attribute must have more than :value items."
2755
+ },
2756
+ gte: {
2757
+ number: "The :attribute must be greater than or equal :value.",
2758
+ string: "The :attribute must be greater than or equal :value characters.",
2759
+ array: "The :attribute must have :value items or more.",
2760
+ object: "The :attribute must have :value items or more."
2761
+ },
2762
+ hex: "The :attribute must be a valid hexadecimal color.",
2763
+ in: "The :attribute must be one of the following :values.",
2764
+ includes: "The :attribute must include one of the following values: :values.",
2765
+ integer: "The :attribute must be an integer.",
2766
+ ip: "The :attribute must be a valid IP address.",
2767
+ ipv4: "The :attribute must be a valid IPv4 address.",
2768
+ ipv6: "The :attribute must be a valid IPv6 address.",
2769
+ json: "The :attribute must be a valid JSON string.",
2770
+ lt: {
2771
+ number: "The :attribute must be less than :value.",
2772
+ string: "The :attribute must be less than :value characters.",
2773
+ array: "The :attribute must have less than :value items.",
2774
+ object: "The :attribute must have less than :value items."
2775
+ },
2776
+ lte: {
2777
+ number: "The :attribute must be less than or equal :value.",
2778
+ string: "The :attribute must be less than or equal :value characters.",
2779
+ array: "The :attribute must have :value items or less.",
2780
+ object: "The :attribute must have :value items or less."
2781
+ },
2782
+ max: {
2783
+ number: "The :attribute must not be greater than :max.",
2784
+ string: "The :attribute must not be greater than :max characters.",
2785
+ array: "The :attribute must not have more than :max items.",
2786
+ object: "The :attribute must not have more than :max items."
2787
+ },
2788
+ min: {
2789
+ number: "The :attribute must be at least :min.",
2790
+ string: "The :attribute must be at least :min characters.",
2791
+ array: "The :attribute must have at least :min items.",
2792
+ object: "The :attribute must have at least :min items."
2793
+ },
2794
+ mac_address: "The :attribute must be a valid MAC address.",
2795
+ not_in: "The selected :attribute is invalid.",
2796
+ not_regex: "The :attribute format is invalid.",
2797
+ not_includes: "The :attribute must not include any of the following values: :values.",
2798
+ numeric: "The :attribute must be a number.",
2799
+ object: "The :attribute must be an object.",
2800
+ password: {
2801
+ letter: "The :attribute must contain at least one letter.",
2802
+ letters: "The :attribute must contain at least :amount letters.",
2803
+ lower_case: "The :attribute must contain at least one lowercase letter.",
2804
+ lower_cases: "The :attribute must contain at least :amount lowercase letters.",
2805
+ number: "The :attribute must contain at least one number.",
2806
+ numbers: "The :attribute must contain at least :amount numbers.",
2807
+ symbol: "The :attribute must contain at least one symbol.",
2808
+ symbols: "The :attribute must contain at least :amount symbols.",
2809
+ upper_case: "The :attribute must contain at least one uppercase letter.",
2810
+ upper_cases: "The :attribute must contain at least :amount uppercase letters."
2811
+ },
2812
+ present: "The :attribute field must be present.",
2813
+ presentsame: "The :attribute field must be present.",
2814
+ prohibited: "The :attribute field is prohibited.",
2815
+ prohibited_unless: "The :attribute field is prohibited unless :other is in :values.",
2816
+ prohibits: "The :attribute field prohibits :values from being present.",
2817
+ regex: "The :attribute format is invalid.",
2818
+ required: "The :attribute field is required.",
2819
+ required_if: "The :attribute field is required when :other is :value.",
2820
+ required_unless: "The :attribute field is required unless :other is in :values.",
2821
+ required_with: "The :attribute field is required when :values is present.",
2822
+ required_with_all: "The :attribute field is required when :values are present.",
2823
+ required_without: "The :attribute field is required when :values is not present.",
2824
+ required_without_all: "The :attribute field is required when none of :values are present.",
2825
+ starts_with: "The :attribute must start with one of the following: :values.",
2826
+ same: "The :attribute and :other must match.",
2827
+ size: {
2828
+ number: "The :attribute must be :size.",
2829
+ string: "The :attribute must be :size characters.",
2830
+ array: "The :attribute must contain :size items.",
2831
+ object: "The :attribute must contain :size items."
2832
+ },
2833
+ string: "The :attribute must be a string.",
2834
+ timezone: "The :attribute must be a valid timezone.",
2835
+ unique: "The :attribute has already been taken.",
2836
+ url: "The :attribute must have a valid URL format.",
2837
+ multiple_of: "The :attribute must be a multiple of :value."
2838
+ },
2839
+ ar: {
2840
+ accepted: "يجب قبول الحقل :attribute",
2841
+ accepted_if: "الحقل :attribute مقبول في حال ما إذا كان :other يساوي :value.",
2842
+ after: "يجب على الحقل :attribute أن يكون تاريخا لاحقا للتاريخ :date.",
2843
+ after_or_equal: "الحقل :attribute يجب أن يكون تاريخاً لاحقاً أو مطابقاً للتاريخ :date.",
2844
+ alpha: "يجب أن لا يحتوي الحقل :attribute سوى على حروف",
2845
+ alpha_dash: "يجب أن يحتوي الحقل :attribute على حرف واحد أو رقم واحد على الأقل، بالإضافة إلى شرطات وشرطات سفلية بشكل اختياري",
2846
+ alpha_num: "يجب أن يحتوي :attribute على حروف وأرقام فقط",
2847
+ array: "يجب أن يكون الحقل :attribute ًمصفوفة",
2848
+ before: "يجب على الحقل :attribute أن يكون تاريخا سابقا للتاريخ :date.",
2849
+ before_or_equal: "الحقل :attribute يجب أن يكون تاريخا سابقا أو مطابقا للتاريخ :date",
2850
+ between: {
2851
+ number: "يجب أن تكون قيمة :attribute بين :min و :max.",
2852
+ string: "يجب أن يكون عدد حروف النّص :attribute بين :min و :max",
2853
+ array: "يجب أن يحتوي :attribute على عدد من العناصر بين :min و :max",
2854
+ object: "يجب أن يحتوي :attribute على عدد من العناصر بين :min و :max"
2855
+ },
2856
+ boolean: "يجب أن تكون قيمة الحقل :attribute إما true أو false",
2857
+ confirmed: "حقل التأكيد غير مُطابق للحقل :attribute",
2858
+ date: "الحقل :attribute ليس تاريخًا صحيحًا",
2859
+ datetime: "الحقل :attribute يجب أن يكون تاريخًا صالحًا يطابق الصيغة :format.",
2860
+ date_equals: "لا يساوي الحقل :attribute مع :date.",
2861
+ declined: "يجب رفض الحقل :attribute",
2862
+ declined_if: "الحقل :attribute مرفوض في حال ما إذا كان :other يساوي :value.",
2863
+ different: "يجب أن يكون الحقلان :attribute و :other مُختلفان",
2864
+ digits: "يجب أن يحتوي الحقل :attribute على :digits رقمًا/أرقام",
2865
+ digits_between: "يجب أن يحتوي الحقل :attribute بين :min و :max رقمًا/أرقام",
2866
+ email: "يجب أن يكون :attribute عنوان بريد إلكتروني صحيح البُنية",
2867
+ ends_with: "حقل :attribute يجب ان ينتهي بأحد القيم التالية :value.",
2868
+ exists: "الحقل :attribute غير موجود",
2869
+ gt: {
2870
+ number: "حقل :attribute يجب ان يكون اكبر من :value.",
2871
+ string: "حقل :attribute يجب ان يكون اكبر من :value حروفٍ/حرفًا.",
2872
+ array: "حقل :attribute يجب ان يحتوي علي اكثر من :value عناصر/عنصر.",
2873
+ object: "حقل :attribute يجب ان يحتوي علي اكثر من :value عناصر/عنصر."
2874
+ },
2875
+ gte: {
2876
+ number: "حقل :attribute يجب ان يكون اكبر من او يساوي :value.",
2877
+ string: "حقل :attribute يجب ان يكون اكبر من او يساوي :value حروفٍ/حرفًا.",
2878
+ array: "حقل :attribute يجب ان يحتوي علي :value عناصر/عنصر او اكثر.",
2879
+ object: "حقل :attribute يجب ان يحتوي علي :value عناصر/عنصر او اكثر."
2880
+ },
2881
+ hex: "الحقل :attribute يجب أن يكون لونًا سداسيًا صالحًا.",
2882
+ in: "الحقل :attribute غير صالح",
2883
+ includes: "الحقل :attribute يجب أن يحتوي على أحد القيم التالية: :values.",
2884
+ integer: "يجب أن يكون الحقل :attribute عددًا صحيحًا",
2885
+ json: "يجب أن يكون الحقل :attribute نصا من نوع JSON.",
2886
+ lt: {
2887
+ number: "حقل :attribute يجب ان يكون اقل من :value.",
2888
+ string: "حقل :attribute يجب ان يكون اقل من :value حروفٍ/حرفًا.",
2889
+ array: "حقل :attribute يجب ان يحتوي علي اقل من :value عناصر/عنصر.",
2890
+ object: "حقل :attribute يجب ان يحتوي علي اقل من :value عناصر/عنصر."
2891
+ },
2892
+ lte: {
2893
+ number: "حقل :attribute يجب ان يكون اقل من او يساوي :value.",
2894
+ string: "حقل :attribute يجب ان يكون اقل من او يساوي :value حروفٍ/حرفًا.",
2895
+ array: "حقل :attribute يجب ان يحتوي علي اكثر من :value عناصر/عنصر.",
2896
+ object: "حقل :attribute يجب ان يحتوي علي اكثر من :value عناصر/عنصر."
2897
+ },
2898
+ max: {
2899
+ number: "يجب أن تكون قيمة الحقل :attribute مساوية أو أصغر لـ :max.",
2900
+ string: "يجب أن لا يتجاوز طول نص :attribute :max حروفٍ/حرفًا",
2901
+ array: "يجب أن لا يحتوي الحقل :attribute على أكثر من :max عناصر/عنصر.",
2902
+ object: "يجب أن لا يحتوي الحقل :attribute على أكثر من :max عناصر/عنصر."
2903
+ },
2904
+ min: {
2905
+ number: "يجب أن تكون قيمة الحقل :attribute مساوية أو أكبر لـ :min.",
2906
+ string: "يجب أن يكون طول نص :attribute على الأقل :min حروفٍ/حرفًا",
2907
+ array: "يجب أن يحتوي الحقل :attribute على الأقل على :min عُنصرًا/عناصر",
2908
+ object: "يجب أن يحتوي الحقل :attribute على الأقل على :min عُنصرًا/عناصر"
2909
+ },
2910
+ not_in: "الحقل :attribute غير صالح",
2911
+ not_regex: "الحقل :attribute نوعه غير صالح",
2912
+ not_includes: "الحقل :attribute يجب ألا يحتوي على أي من القيم التالية: :values.",
2913
+ numeric: "يجب على الحقل :attribute أن يكون رقمًا",
2914
+ object: "الحقل :attribute يجب ان يكون من نوع object.",
2915
+ password: {
2916
+ letter: "يجب ان يشمل حقل :attribute على حرف واحد على الاقل.",
2917
+ letters: "يجب ان يشمل حقل :attribute على عدد :amount حروف على الاقل.",
2918
+ lower_case: "يجب ان يشمل حقل :attribute على حرف واحد من صيغة صغيرة على الاقل.",
2919
+ lower_cases: "يجب ان يشمل حقل :attribute على عدد :amount حروف صغيرة على الاقل.",
2920
+ number: "يجب ان يشمل حقل :attribute على رقم واحد على الاقل.",
2921
+ numbers: "يجب ان يشمل حقل :attribute على عدد :amount من الارقام على الاقل.",
2922
+ symbol: "يجب ان يشمل حقل :attribute على رمز واحد على الاقل.",
2923
+ symbols: "يجب ان يشمل حقل :attribute على عدد :amount رموز على الاقل.",
2924
+ upper_case: "يجب ان يشمل حقل :attribute على حرف كبير واحد على الاقل.",
2925
+ upper_cases: "يجب ان يشمل حقل :attribute على عدد :amount حروف كبيرة على الاقل."
2926
+ },
2927
+ present: "يجب تقديم الحقل :attribute",
2928
+ regex: "صيغة الحقل :attribute .غير صحيحة",
2929
+ required: "الحقل :attribute مطلوب.",
2930
+ required_if: "الحقل :attribute مطلوب في حال ما إذا كان :other يساوي :value.",
2931
+ required_unless: "الحقل :attribute مطلوب في حال ما لم يكن :other يساوي :values.",
2932
+ required_with: "الحقل :attribute اجباري إذا توفّر :values.",
2933
+ required_with_all: "الحقل :attribute اجباري إذا توفّر :values.",
2934
+ required_without: "الحقل :attribute اجباري إذا لم يتوفّر :values.",
2935
+ required_without_all: "الحقل :attribute اجباري إذا لم يتوفّر :values.",
2936
+ starts_with: "الحقل :attribute يجب ان يبدأ بأحد القيم التالية: :values.",
2937
+ same: "يجب أن يتطابق الحقل :attribute مع :other",
2938
+ size: {
2939
+ number: "يجب أن تكون قيمة الحقل :attribute مساوية لـ :size",
2940
+ string: "يجب أن يحتوي النص :attribute على :size حروفٍ/حرفًا بالظبط",
2941
+ array: "يجب أن يحتوي الحقل :attribute على :size عنصرٍ/عناصر بالظبط",
2942
+ object: "يجب أن يحتوي الحقل :attribute على :size عنصرٍ/عناصر بالظبط"
2943
+ },
2944
+ string: "يجب أن يكون الحقل :attribute نصآ.",
2945
+ unique: "الحقل :attribute مستخدم بالفعل.",
2946
+ url: "صيغة الرابط :attribute غير صحيحة"
2947
+ }
2948
+ };
2949
+ /**
2950
+ * Determine if a value is an object. Arrays and null are not considered objects.
2951
+ *
2952
+ * @param value
2953
+ * @returns
2954
+ */
2955
+ function isObject(value) {
2956
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2957
+ }
2958
+ /**
2959
+ * Deeply merge two objects.
2960
+ * The source object will overwrite the target object when there is a conflict.
2961
+ * Arrays and non-object values will be overwritten, not merged.
2962
+ *
2963
+ * @param target
2964
+ * @param source
2965
+ * @returns
2966
+ */
2967
+ function mergeDeep(target, source) {
2968
+ const output = Object.assign({}, target);
2969
+ if (!isObject(target) || !isObject(source)) return output;
2970
+ for (const key in source) if (isObject(source[key])) if (!target[key]) Object.assign(output, { [key]: source[key] });
2971
+ else output[key] = mergeDeep(target[key], source[key]);
2972
+ else Object.assign(output, { [key]: source[key] });
2973
+ return output;
2974
+ }
2975
+ (class {
2976
+ /**
2977
+ * Default lang to be used, when lang is not specified
2978
+ */
2979
+ static defaultLang = "en";
2980
+ /**
2981
+ * Determines the locale to be used when tu current one is not available
2982
+ */
2983
+ static fallbackLang = "en";
2984
+ /**
2985
+ * The existing langs that are supported by the library
2986
+ */
2987
+ static existingLangs = ["en"];
2988
+ /**
2989
+ * Store the translations passed by the user
2990
+ */
2991
+ static translations = {};
2992
+ /**
2993
+ * Store translations contributed by plugins.
2994
+ */
2995
+ static translationExtensions = {};
2996
+ /**
2997
+ * Stores the messages that are already loaded
2998
+ */
2999
+ static messages = {};
3000
+ /**
3001
+ * Stores the default messages
3002
+ */
3003
+ static defaultMessages = {};
3004
+ /**
3005
+ * Stores the fallback messages
3006
+ */
3007
+ static fallbackMessages = locales_default.en;
3008
+ /**
3009
+ * Get messages for lang
3010
+ *
3011
+ * @param lang
3012
+ * @returns
3013
+ */
3014
+ static get(lang) {
3015
+ lang ??= this.defaultLang;
3016
+ this.load(lang);
3017
+ return this.messages[lang];
3018
+ }
3019
+ /**
3020
+ * Set the translation object passed by the user
3021
+ *
3022
+ * @param translations
3023
+ */
3024
+ static setTranslationObject(translations) {
3025
+ this.translations = translations;
3026
+ this.existingLangs = Array.from(/* @__PURE__ */ new Set([...this.existingLangs, ...Object.keys(translations)]));
3027
+ this.resetLoadedMessages();
3028
+ this.setDefaultLang(this.defaultLang);
3029
+ }
3030
+ /**
3031
+ * Merge additional translations into the global catalog.
3032
+ */
3033
+ static extendTranslationObject(translations) {
3034
+ this.translationExtensions = mergeDeep(this.translationExtensions, translations);
3035
+ this.existingLangs = Array.from(/* @__PURE__ */ new Set([...this.existingLangs, ...Object.keys(translations)]));
3036
+ this.resetLoadedMessages();
3037
+ this.setDefaultLang(this.defaultLang);
3038
+ }
3039
+ /**
3040
+ * Set the default lang that should be used. And assign the default messages
3041
+ *
3042
+ * @param lang
3043
+ */
3044
+ static setDefaultLang(lang) {
3045
+ this.defaultLang = lang;
3046
+ this.load(lang);
3047
+ }
3048
+ /**
3049
+ * Set the fallback lang to be used. And assign the fallback messages
3050
+ *
3051
+ * @param lang
3052
+ */
3053
+ static setFallbackLang(lang) {
3054
+ this.fallbackLang = lang;
3055
+ this.fallbackMessages = locales_default.en;
3056
+ if (Object.prototype.hasOwnProperty.call(locales_default, lang)) this.fallbackMessages = mergeDeep(this.fallbackMessages, locales_default[lang]);
3057
+ if (Object.prototype.hasOwnProperty.call(this.translationExtensions, lang)) this.fallbackMessages = mergeDeep(this.fallbackMessages, this.translationExtensions[lang]);
3058
+ if (Object.prototype.hasOwnProperty.call(this.translations, lang)) this.fallbackMessages = mergeDeep(this.fallbackMessages, this.translations[lang]);
3059
+ }
3060
+ /**
3061
+ * Get the default language
3062
+ *
3063
+ * @returns
3064
+ */
3065
+ static getDefaultLang() {
3066
+ return this.defaultLang;
3067
+ }
3068
+ /**
3069
+ * Load the messages based on the specified language
3070
+ *
3071
+ * @param lang
3072
+ * @returns
3073
+ */
3074
+ static load(lang) {
3075
+ if (this.messages[lang]) return;
3076
+ if (Object.prototype.hasOwnProperty.call(locales_default, lang)) this.messages[lang] = mergeDeep(this.fallbackMessages, locales_default[lang]);
3077
+ else this.messages[lang] = mergeDeep({}, this.fallbackMessages);
3078
+ if (Object.prototype.hasOwnProperty.call(this.translationExtensions, lang)) this.messages[lang] = mergeDeep(this.messages[lang], this.translationExtensions[lang]);
3079
+ if (Object.prototype.hasOwnProperty.call(this.translations, lang)) this.messages[lang] = mergeDeep(this.messages[lang], this.translations[lang]);
3080
+ }
3081
+ static resetLoadedMessages() {
3082
+ this.messages = {};
3083
+ this.fallbackMessages = locales_default.en;
3084
+ }
3085
+ });
3086
+ import_dayjs_min.default.extend(import_customParseFormat.default);
3087
+ //#endregion
3088
+ //#region ../http/dist/redirect-g4KUj_g-.js
3089
+ const unwrapRequestSource = (source) => {
3090
+ if (source.original) return unwrapRequestSource(source.original);
3091
+ if (source.headers) return source;
3092
+ if (source.req) return source.req;
3093
+ if (source.request) return source.request;
3094
+ return source;
3095
+ };
3096
+ const makeHeaders = (headers) => {
3097
+ return new Headers(normalizeHeaders(headers));
3098
+ };
3099
+ const normalizeHeaders = (headers) => {
3100
+ const normalized = {};
3101
+ if (!headers) return normalized;
3102
+ if (isHeaders(headers)) {
3103
+ headers.forEach((value, key) => {
3104
+ normalized[key.toLowerCase()] = value;
3105
+ });
3106
+ return normalized;
3107
+ }
3108
+ for (const [key, value] of Object.entries(headers)) {
3109
+ const normalizedValue = normalizeHeaderValue(value);
3110
+ if (typeof normalizedValue === "string") normalized[key.toLowerCase()] = normalizedValue;
3111
+ }
3112
+ return normalized;
3113
+ };
3114
+ const normalizeHeaderValue = (value) => {
3115
+ if (Array.isArray(value)) return value.join(", ");
3116
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
3117
+ return value ?? void 0;
3118
+ };
3119
+ const isHeaders = (value) => typeof Headers !== "undefined" && value instanceof Headers;
3120
+ const isRecord = (value) => {
3121
+ return !!value && typeof value === "object" && !Array.isArray(value);
3122
+ };
3123
+ let fallbackRequest;
3124
+ const requestResolvers = /* @__PURE__ */ new Set();
3125
+ const currentRequest = () => {
3126
+ for (const resolver of requestResolvers) {
3127
+ const request = resolver();
3128
+ if (request) return request;
3129
+ }
3130
+ return fallbackRequest;
3131
+ };
3132
+ const requestHelper = ((key) => {
3133
+ const request = currentRequest();
3134
+ return key ? request?.input(key) : request;
3135
+ });
3136
+ const setFallbackRequest = (request) => {
3137
+ fallbackRequest = request;
3138
+ globalThis.request = requestHelper;
3139
+ };
3140
+ /**
3141
+ * Represents an HTTP request, providing a consistent interface for accessing request data.
3142
+ *
3143
+ * @author 3m1n3nc3
3144
+ */
3145
+ var Request$1 = class Request$1 extends Request {
3146
+ headers;
3147
+ ip;
3148
+ source;
3149
+ currentUser;
3150
+ currentAuth;
3151
+ currentAuthUser;
3152
+ currentAuthToken;
3153
+ get user() {
3154
+ return this.getSourceRequest()?.user ?? this.currentUser;
3155
+ }
3156
+ set user(user) {
3157
+ this.currentUser = user;
3158
+ }
3159
+ get auth() {
3160
+ return this.getSourceRequest()?.auth ?? this.currentAuth;
3161
+ }
3162
+ set auth(auth) {
3163
+ this.currentAuth = auth;
3164
+ }
3165
+ get authUser() {
3166
+ return this.getSourceRequest()?.authUser ?? this.currentAuthUser;
3167
+ }
3168
+ set authUser(user) {
3169
+ this.currentAuthUser = user;
3170
+ }
3171
+ get authToken() {
3172
+ return this.getSourceRequest()?.authToken ?? this.currentAuthToken;
3173
+ }
3174
+ set authToken(token) {
3175
+ this.currentAuthToken = token;
3176
+ }
3177
+ constructor(options = {}) {
3178
+ super(options);
3179
+ const source = options.source ?? options.original;
3180
+ const sourceRequest = isRecord(source) ? source : void 0;
3181
+ this.headers = normalizeHeaders(options.headers);
3182
+ if (this.method) this.method = options.method;
3183
+ if (this.url) this.url = options.url;
3184
+ if (this.path) this.path = options.path;
3185
+ this.ip = options.ip ?? sourceRequest?.ip ?? null;
3186
+ this.user = options.user ?? sourceRequest?.user;
3187
+ this.auth = options.auth ?? sourceRequest?.auth;
3188
+ this.authUser = options.authUser ?? sourceRequest?.authUser;
3189
+ this.authToken = options.authToken ?? sourceRequest?.authToken;
3190
+ this.source = source;
3191
+ setFallbackRequest(this);
3192
+ }
3193
+ static from(source) {
3194
+ if (!source) return;
3195
+ if (source instanceof Request$1) return source;
3196
+ const request = unwrapRequestSource(source);
3197
+ const unified = source;
3198
+ return new Request$1({
3199
+ body: unified.body,
3200
+ query: unified.query,
3201
+ params: unified.params,
3202
+ route: unified.route,
3203
+ ctx: unified.ctx,
3204
+ headers: request.headers,
3205
+ method: request.method,
3206
+ url: request.originalUrl ?? request.url,
3207
+ path: request.path,
3208
+ ip: request.ip ?? null,
3209
+ user: request.user,
3210
+ auth: request.auth,
3211
+ authUser: request.authUser,
3212
+ authToken: request.authToken,
3213
+ source: request,
3214
+ original: unified.original
3215
+ });
3216
+ }
3217
+ header(name) {
3218
+ return this.headers[name.toLowerCase()];
3219
+ }
3220
+ bearerToken() {
3221
+ const authorization = this.header("authorization");
3222
+ if (!authorization?.startsWith("Bearer ")) return null;
3223
+ return authorization.substring(7);
3224
+ }
3225
+ setUser(user) {
3226
+ this.user = user;
3227
+ if (isRecord(this.source)) this.source.user = user;
3228
+ return this;
3229
+ }
3230
+ setAuthentication(auth, user, token) {
3231
+ this.auth = auth;
3232
+ this.authUser = user;
3233
+ this.authToken = token;
3234
+ this.setUser(user);
3235
+ if (isRecord(this.source)) {
3236
+ this.source.auth = auth;
3237
+ this.source.authUser = user;
3238
+ this.source.authToken = token;
3239
+ }
3240
+ return this;
3241
+ }
3242
+ syncFromSource() {
3243
+ if (!isRecord(this.source)) return this;
3244
+ const source = this.source;
3245
+ this.user = source.user ?? this.user;
3246
+ this.auth = source.auth ?? this.auth;
3247
+ this.authUser = source.authUser ?? this.authUser;
3248
+ this.authToken = source.authToken ?? this.authToken;
3249
+ return this;
3250
+ }
3251
+ getSourceRequest() {
3252
+ return isRecord(this.source) ? this.source : void 0;
3253
+ }
3254
+ clearAuthentication() {
3255
+ this.auth = void 0;
3256
+ this.authUser = void 0;
3257
+ this.authToken = void 0;
3258
+ this.user = void 0;
3259
+ if (isRecord(this.source)) {
3260
+ this.source.auth = void 0;
3261
+ this.source.authUser = void 0;
3262
+ this.source.authToken = void 0;
3263
+ this.source.user = void 0;
3264
+ }
3265
+ return this;
3266
+ }
3267
+ };
3268
+ let fallbackResponse;
3269
+ const responseResolvers = /* @__PURE__ */ new Set();
3270
+ const responseHelper = () => {
3271
+ for (const resolver of responseResolvers) {
3272
+ const response = resolver();
3273
+ if (response) return response;
3274
+ }
3275
+ return fallbackResponse;
3276
+ };
3277
+ const setFallbackResponse = (response) => {
3278
+ fallbackResponse = response;
3279
+ globalThis.response = responseHelper;
3280
+ };
3281
+ /**
3282
+ * Represents an HTTP response, providing a consistent interface for accessing response data.
3283
+ *
3284
+ * @author 3m1n3nc3
3285
+ */
3286
+ var Response$1 = class Response$1 extends Response {
3287
+ body;
3288
+ source;
3289
+ constructor(options = {}) {
3290
+ super({
3291
+ body: options.body,
3292
+ headers: makeHeaders(options.headers),
3293
+ statusCode: options.statusCode ?? 200
3294
+ });
3295
+ this.body = options.body ?? {};
3296
+ this.source = options.source;
3297
+ setFallbackResponse(this);
3298
+ }
3299
+ static from(source) {
3300
+ if (!source) return;
3301
+ if (source instanceof Response$1) return source;
3302
+ return new Response$1({
3303
+ statusCode: typeof source.status === "number" ? source.status : source.statusCode,
3304
+ headers: source.headers,
3305
+ source
3306
+ });
3307
+ }
3308
+ status(code) {
3309
+ this.statusCode = code;
3310
+ if (isRecord(this.source)) if (typeof this.source.status === "function") this.source.status(code);
3311
+ else this.source.statusCode = code;
3312
+ return this;
3313
+ }
3314
+ header(name, value) {
3315
+ this.headers.set(name.toLowerCase(), value);
3316
+ if (isRecord(this.source) && typeof this.source.setHeader === "function") this.source.setHeader(name, value);
3317
+ return this;
3318
+ }
3319
+ getHeaders() {
3320
+ return normalizeHeaders(this.headers);
3321
+ }
3322
+ json(body) {
3323
+ this.body = body;
3324
+ if (isRecord(this.source) && typeof this.source.json === "function") return this.source.json(body);
3325
+ return body;
3326
+ }
3327
+ send(body) {
3328
+ this.body = body;
3329
+ if (isRecord(this.source) && typeof this.source.send === "function") return this.source.send(body);
3330
+ return body;
3331
+ }
3332
+ };
3333
+ var FlashBag = class {
3334
+ bag = {};
3335
+ sweepKeys = /* @__PURE__ */ new Set();
3336
+ constructor(items) {
3337
+ this.bag = { ...items || {} };
3338
+ this.sweepKeys = new Set(Object.keys(this.bag));
3339
+ }
3340
+ put(key, value) {
3341
+ this.bag[key] = value;
3342
+ this.sweepKeys.delete(key);
3343
+ return this;
3344
+ }
3345
+ set(key, value) {
3346
+ return this.put(key, value);
3347
+ }
3348
+ get(key, defaultValue) {
3349
+ return key in this.bag ? this.bag[key] : defaultValue;
3350
+ }
3351
+ has(key) {
3352
+ if (Array.isArray(key)) return key.every((item) => this.has(item));
3353
+ if (key) return key in this.bag;
3354
+ return this.any();
3355
+ }
3356
+ any() {
3357
+ return Object.keys(this.bag).length > 0;
3358
+ }
3359
+ isEmpty() {
3360
+ return !this.any();
3361
+ }
3362
+ isNotEmpty() {
3363
+ return this.any();
3364
+ }
3365
+ keys() {
3366
+ return Object.keys(this.bag);
3367
+ }
3368
+ all() {
3369
+ return { ...this.bag };
3370
+ }
3371
+ clear(key) {
3372
+ if (Array.isArray(key)) {
3373
+ for (const item of key) {
3374
+ delete this.bag[item];
3375
+ this.sweepKeys.delete(item);
3376
+ }
3377
+ return this;
3378
+ }
3379
+ if (key) {
3380
+ delete this.bag[key];
3381
+ this.sweepKeys.delete(key);
3382
+ return this;
3383
+ }
3384
+ this.bag = {};
3385
+ this.sweepKeys.clear();
3386
+ return this;
3387
+ }
3388
+ forget(key) {
3389
+ return this.clear(key);
3390
+ }
3391
+ markForSweep(keys = this.keys()) {
3392
+ this.sweepKeys = new Set(keys);
3393
+ return this;
3394
+ }
3395
+ sweep() {
3396
+ for (const key of this.sweepKeys) delete this.bag[key];
3397
+ this.sweepKeys = new Set(Object.keys(this.bag));
3398
+ return this;
3399
+ }
3400
+ toJSON() {
3401
+ return this.all();
3402
+ }
3403
+ };
3404
+ const asMessageRecord = (value) => {
3405
+ if (!isRecord(value)) return;
3406
+ return value;
3407
+ };
3408
+ const callRecordMethod = (source, method) => {
3409
+ if (typeof source[method] !== "function") return;
3410
+ const value = source[method]();
3411
+ return asMessageRecord(value);
3412
+ };
3413
+ const resolveMessageRecord = (source) => {
3414
+ if (!isRecord(source)) return;
3415
+ if (typeof source.getMessageBag === "function") {
3416
+ const bag = source.getMessageBag();
3417
+ if (bag && bag !== source) {
3418
+ const messages = resolveMessageRecord(bag);
3419
+ if (messages) return messages;
3420
+ }
3421
+ }
3422
+ if (typeof source.errors === "function") {
3423
+ const errors = source.errors();
3424
+ const messages = resolveMessageRecord(errors) || asMessageRecord(errors);
3425
+ if (messages) return messages;
3426
+ }
3427
+ return callRecordMethod(source, "getMessages") || callRecordMethod(source, "messagesRaw") || callRecordMethod(source, "toArray") || resolveMessageRecord(source.errors) || asMessageRecord(source.errors);
3428
+ };
3429
+ const getValidationIssueField = (issue) => {
3430
+ if (typeof issue.field === "string") return issue.field;
3431
+ if (typeof issue.attribute === "string") return issue.attribute;
3432
+ if (typeof issue.key === "string") return issue.key;
3433
+ if (typeof issue.path === "string") return issue.path;
3434
+ if (Array.isArray(issue.path)) return issue.path.join(".") || "_";
3435
+ return "_";
3436
+ };
3437
+ const toMessages = (value) => {
3438
+ if (Array.isArray(value)) return value.flatMap((item) => toMessages(item));
3439
+ if (value instanceof Error) return [value.message];
3440
+ if (isRecord(value) && typeof value.message === "string") return [value.message];
3441
+ if (value === null || typeof value === "undefined") return [];
3442
+ return [String(value)];
3443
+ };
3444
+ var ErrorBag = class ErrorBag extends FlashBag {
3445
+ constructor(errors) {
3446
+ super();
3447
+ if (errors) {
3448
+ this.merge(errors);
3449
+ this.markForSweep();
3450
+ }
3451
+ }
3452
+ add(field, message) {
3453
+ const key = field || "_";
3454
+ const messages = toMessages(message);
3455
+ if (!messages.length) return this;
3456
+ this.put(key, [...this.bag[key] || [], ...messages]);
3457
+ return this;
3458
+ }
3459
+ addIf(condition, field, message) {
3460
+ if (condition) this.add(field, message);
3461
+ return this;
3462
+ }
3463
+ merge(errors) {
3464
+ const incoming = resolveMessageRecord(errors) || (isRecord(errors) ? errors : void 0);
3465
+ if (!incoming) return this.validation(errors);
3466
+ for (const [field, messages] of Object.entries(incoming)) this.add(field, messages);
3467
+ return this;
3468
+ }
3469
+ validation(error) {
3470
+ if (!error) return this;
3471
+ if (error instanceof ErrorBag) return this.merge(error);
3472
+ const messages = resolveMessageRecord(error);
3473
+ if (messages) return this.merge(messages);
3474
+ if (Array.isArray(error)) {
3475
+ for (const item of error) if (isRecord(item) && "message" in item) this.add(getValidationIssueField(item), item.message);
3476
+ else this.add("_", item);
3477
+ return this;
3478
+ }
3479
+ if (isRecord(error)) {
3480
+ if (typeof error.errors === "function") return this.validation(error.errors());
3481
+ if (error.errors) return this.validation(error.errors);
3482
+ if (Array.isArray(error.issues)) return this.validation(error.issues);
3483
+ if ("message" in error) return this.add(getValidationIssueField(error), error.message);
3484
+ return this.merge(error);
3485
+ }
3486
+ if (error instanceof Error) return this.add("_", error.message);
3487
+ return this.add("_", error);
3488
+ }
3489
+ keys() {
3490
+ return Object.keys(this.bag);
3491
+ }
3492
+ get(field = "_") {
3493
+ return [...this.bag[field] || []];
3494
+ }
3495
+ first(field) {
3496
+ if (field) return this.bag[field]?.[0] || "";
3497
+ return this.all()[0] || "";
3498
+ }
3499
+ has(field) {
3500
+ if (Array.isArray(field)) return field.every((key) => this.has(key));
3501
+ if (field) return (this.bag[field]?.length || 0) > 0;
3502
+ return this.any();
3503
+ }
3504
+ hasAny(fields) {
3505
+ return (Array.isArray(fields) ? fields : [fields]).some((key) => this.has(key));
3506
+ }
3507
+ missing(fields) {
3508
+ return (Array.isArray(fields) ? fields : [fields]).every((key) => !this.has(key));
3509
+ }
3510
+ any() {
3511
+ return Object.values(this.bag).some((messages) => messages.length > 0);
3512
+ }
3513
+ isEmpty() {
3514
+ return !this.any();
3515
+ }
3516
+ isNotEmpty() {
3517
+ return this.any();
3518
+ }
3519
+ count() {
3520
+ return Object.values(this.bag).reduce((total, messages) => total + messages.length, 0);
3521
+ }
3522
+ all() {
3523
+ return Object.values(this.bag).flat();
3524
+ }
3525
+ unique() {
3526
+ return [...new Set(this.all())];
3527
+ }
3528
+ clear(field) {
3529
+ super.clear(field);
3530
+ return this;
3531
+ }
3532
+ forget(field) {
3533
+ return this.clear(field);
3534
+ }
3535
+ messagesRaw() {
3536
+ return this.toJSON();
3537
+ }
3538
+ getMessages() {
3539
+ return this.messagesRaw();
3540
+ }
3541
+ getMessageBag() {
3542
+ return this;
3543
+ }
3544
+ toArray() {
3545
+ return this.toJSON();
3546
+ }
3547
+ toJSON() {
3548
+ return Object.entries(this.bag).reduce((errors, [field, messages]) => {
3549
+ errors[field] = [...messages];
3550
+ return errors;
3551
+ }, {});
3552
+ }
3553
+ };
3554
+ let fallbackSession;
3555
+ const sessionResolvers = /* @__PURE__ */ new Set();
3556
+ const currentSession = () => {
3557
+ for (const resolver of sessionResolvers) {
3558
+ const session = resolver();
3559
+ if (session) return session;
3560
+ }
3561
+ return fallbackSession;
3562
+ };
3563
+ const sessionHelperTarget = (key) => {
3564
+ const session = currentSession();
3565
+ return key ? session?.get(key) : session;
3566
+ };
3567
+ const sessionHelper = new Proxy(sessionHelperTarget, { get(target, property, receiver) {
3568
+ if (Reflect.has(target, property)) return Reflect.get(target, property, receiver);
3569
+ const session = currentSession();
3570
+ const value = session?.[property];
3571
+ return typeof value === "function" ? value.bind(session) : value;
3572
+ } });
3573
+ const setFallbackSession = (session) => {
3574
+ fallbackSession = session;
3575
+ globalThis.session = sessionHelper;
3576
+ };
3577
+ var Session = class Session {
3578
+ errors;
3579
+ flashBag;
3580
+ id;
3581
+ data;
3582
+ persistent;
3583
+ saveQueue = Promise.resolve();
3584
+ constructor(initial, persistent) {
3585
+ const current = initial instanceof Session ? initial : void 0;
3586
+ const state = current ? current.snapshot() : initial && ("data" in initial || "errors" in initial || "flash" in initial) ? initial : { data: initial };
3587
+ this.id = persistent?.id ?? current?.id;
3588
+ this.persistent = persistent ?? current?.persistent;
3589
+ this.saveQueue = current?.saveQueue ?? this.saveQueue;
3590
+ this.data = current ? current.data : { ...state.data || {} };
3591
+ this.errors = current ? current.errors : state.errors instanceof ErrorBag ? state.errors : new ErrorBag(state.errors);
3592
+ this.flashBag = current ? current.flashBag : state.flash instanceof FlashBag ? state.flash : new FlashBag(state.flash);
3593
+ setFallbackSession(this);
3594
+ }
3595
+ snapshot() {
3596
+ return {
3597
+ data: this.all(),
3598
+ errors: this.errors.toJSON(),
3599
+ flash: this.flashBag.toJSON()
3600
+ };
3601
+ }
3602
+ queuePersist() {
3603
+ this.save();
3604
+ }
3605
+ async save() {
3606
+ const payload = this.snapshot();
3607
+ const previous = this.saveQueue.catch(() => void 0);
3608
+ this.saveQueue = previous.then(async () => {
3609
+ await this.persistent?.save(payload);
3610
+ });
3611
+ await this.saveQueue;
3612
+ return this;
3613
+ }
3614
+ async destroy() {
3615
+ this.data = {};
3616
+ this.errors.clear();
3617
+ this.flashBag.clear();
3618
+ await this.persistent?.destroy?.();
3619
+ return this;
3620
+ }
3621
+ /**
3622
+ * Get an item from the session bag
3623
+ *
3624
+ * @param key
3625
+ * @param defaultValue
3626
+ * @returns
3627
+ */
3628
+ get(key, defaultValue) {
3629
+ return key in this.data ? this.data[key] : defaultValue;
3630
+ }
3631
+ /**
3632
+ * Add an item to the session bag
3633
+ *
3634
+ * @param key
3635
+ * @param defaultValue
3636
+ * @returns
3637
+ */
3638
+ put(key, value) {
3639
+ this.data[key] = value;
3640
+ this.queuePersist();
3641
+ return this;
3642
+ }
3643
+ /**
3644
+ * Add an item to the session bag
3645
+ *
3646
+ * @param key
3647
+ * @param defaultValue
3648
+ * @returns
3649
+ */
3650
+ set(key, value) {
3651
+ return this.put(key, value);
3652
+ }
3653
+ /**
3654
+ * Check if an item exist in the session bag
3655
+ *
3656
+ * @param key
3657
+ * @returns
3658
+ */
3659
+ has(key) {
3660
+ return key in this.data;
3661
+ }
3662
+ /**
3663
+ * Remove an item from the session bag
3664
+ *
3665
+ * @param key
3666
+ * @returns
3667
+ */
3668
+ forget(key) {
3669
+ delete this.data[key];
3670
+ this.queuePersist();
3671
+ return this;
3672
+ }
3673
+ /**
3674
+ * Clear the session bag
3675
+ *
3676
+ * @returns
3677
+ */
3678
+ clear() {
3679
+ this.data = {};
3680
+ this.errors.clear();
3681
+ this.flashBag.clear();
3682
+ this.queuePersist();
3683
+ return this;
3684
+ }
3685
+ /**
3686
+ * Get all items in the session bag
3687
+ *
3688
+ * @returns
3689
+ */
3690
+ all() {
3691
+ return { ...this.data };
3692
+ }
3693
+ /**
3694
+ * Add a flash item for the next request
3695
+ *
3696
+ * @param key
3697
+ * @param value
3698
+ * @returns
3699
+ */
3700
+ flash(key, value) {
3701
+ this.flashBag.put(key, value);
3702
+ this.queuePersist();
3703
+ return this;
3704
+ }
3705
+ /**
3706
+ * Get a flash item
3707
+ *
3708
+ * @param key
3709
+ * @param defaultValue
3710
+ * @returns
3711
+ */
3712
+ getFlash(key, defaultValue) {
3713
+ return this.flashBag.get(key, defaultValue);
3714
+ }
3715
+ /**
3716
+ * Sweep flashed data that was loaded for this request
3717
+ *
3718
+ * @returns
3719
+ */
3720
+ async sweepFlash() {
3721
+ this.errors.sweep();
3722
+ this.flashBag.sweep();
3723
+ await this.save();
3724
+ return this;
3725
+ }
3726
+ /**
3727
+ * Add an error to the session error bag
3728
+ *
3729
+ * @param field
3730
+ * @param message
3731
+ * @returns
3732
+ */
3733
+ addError(field, message) {
3734
+ this.errors.add(field, message);
3735
+ this.queuePersist();
3736
+ return this;
3737
+ }
3738
+ /**
3739
+ * Add multiple errors to the session error bag
3740
+ *
3741
+ * @param errors
3742
+ * @returns
3743
+ */
3744
+ addErrors(errors) {
3745
+ this.errors.merge(errors);
3746
+ this.queuePersist();
3747
+ return this;
3748
+ }
3749
+ /**
3750
+ * Add a validation error to the session error bag
3751
+ *
3752
+ * @param error
3753
+ * @returns
3754
+ */
3755
+ addValidationErrors(error) {
3756
+ this.errors.validation(error);
3757
+ this.queuePersist();
3758
+ return this;
3759
+ }
3760
+ /**
3761
+ * Check if the session error bag has any errors
3762
+ *
3763
+ * @param field
3764
+ * @returns
3765
+ */
3766
+ hasErrors(field) {
3767
+ return this.errors.has(field);
3768
+ }
3769
+ /**
3770
+ * Clear all errors in the session error bag
3771
+ *
3772
+ * @param field
3773
+ * @returns
3774
+ */
3775
+ clearErrors(field) {
3776
+ this.errors.clear(field);
3777
+ this.queuePersist();
3778
+ return this;
3779
+ }
3780
+ /**
3781
+ * Parse session for views
3782
+ *
3783
+ * @returns
3784
+ */
3785
+ forView() {
3786
+ return {
3787
+ ...this.all(),
3788
+ errors: this.errors,
3789
+ flash: this.flashBag
3790
+ };
3791
+ }
3792
+ /**
3793
+ * Return session as json
3794
+ *
3795
+ * @returns
3796
+ */
3797
+ toJSON() {
3798
+ return {
3799
+ ...this.all(),
3800
+ errors: this.errors.toJSON(),
3801
+ flash: this.flashBag.toJSON()
3802
+ };
3803
+ }
3804
+ };
3805
+ const byteLength = (value) => Buffer.byteLength(value, "utf8");
3806
+ const serializeValue = (value) => {
3807
+ if (value === null || typeof value === "undefined") return "N;";
3808
+ if (typeof value === "boolean") return `b:${value ? 1 : 0};`;
3809
+ if (typeof value === "number") return Number.isInteger(value) ? `i:${value};` : `d:${value};`;
3810
+ if (typeof value === "string") return `s:${byteLength(value)}:"${value}";`;
3811
+ if (Array.isArray(value)) return serializeEntries(value.map((item, index) => [index, item]));
3812
+ if (typeof value === "object") return serializeEntries(Object.entries(value));
3813
+ return serializeValue(String(value));
3814
+ };
3815
+ const serializeEntries = (entries) => {
3816
+ return `a:${entries.length}:{${entries.map(([key, value]) => serializeValue(key) + serializeValue(value)).join("")}}`;
3817
+ };
3818
+ //#endregion
3819
+ export { Request$1 as Request, Response$1 as Response, Session };