@devp0nt/route0 1.0.0-next.8 → 1.0.0-next.81

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,955 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var index_exports = {};
20
+ __export(index_exports, {
21
+ Route0: () => Route0,
22
+ Routes: () => Routes
23
+ });
24
+ module.exports = __toCommonJS(index_exports);
25
+ var import_flat0 = require("@devp0nt/flat0");
26
+ const escapeRegex = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
27
+ const collapseDuplicateSlashes = (value) => value.replace(/\/{2,}/g, "/");
28
+ class Route0 {
29
+ definition;
30
+ params;
31
+ _origin;
32
+ _callable;
33
+ _routeSegments;
34
+ _routeTokens;
35
+ _routePatternCandidates;
36
+ _pathParamsDefinition;
37
+ _definitionWithoutTrailingWildcard;
38
+ _routeRegexBaseStringRaw;
39
+ _regexBaseString;
40
+ _regexString;
41
+ _regex;
42
+ _regexAncestor;
43
+ _regexDescendantMatchers;
44
+ _captureKeys;
45
+ _normalizedDefinition;
46
+ _definitionParts;
47
+ static normalizeSlash = (value) => {
48
+ const collapsed = collapseDuplicateSlashes(value);
49
+ if (collapsed === "" || collapsed === "/") return "/";
50
+ const withLeadingSlash = collapsed.startsWith("/") ? collapsed : `/${collapsed}`;
51
+ return withLeadingSlash.length > 1 && withLeadingSlash.endsWith("/") ? withLeadingSlash.slice(0, -1) : withLeadingSlash;
52
+ };
53
+ static _getRouteSegments(definition) {
54
+ if (definition === "" || definition === "/") return [];
55
+ return definition.split("/").filter(Boolean);
56
+ }
57
+ static _validateRouteDefinition(definition) {
58
+ const segments = Route0._getRouteSegments(definition);
59
+ const wildcardSegments = segments.filter((segment) => segment.includes("*"));
60
+ if (wildcardSegments.length === 0) return;
61
+ if (wildcardSegments.length > 1) {
62
+ throw new Error(`Invalid route definition "${definition}": only one wildcard segment is allowed`);
63
+ }
64
+ const wildcardSegmentIndex = segments.findIndex((segment) => segment.includes("*"));
65
+ const wildcardSegment = segments[wildcardSegmentIndex];
66
+ if (!wildcardSegment.match(/^(?:\*|\*\?|[^*]+\*|\S+\*\?)$/)) {
67
+ throw new Error(`Invalid route definition "${definition}": wildcard must be trailing in its segment`);
68
+ }
69
+ if (wildcardSegmentIndex !== segments.length - 1) {
70
+ throw new Error(`Invalid route definition "${definition}": wildcard segment is allowed only at the end`);
71
+ }
72
+ }
73
+ Infer = null;
74
+ /** Base URL used when generating absolute URLs (`abs: true`). */
75
+ get origin() {
76
+ if (!this._origin) {
77
+ throw new Error(
78
+ "origin for route " + this.definition + ' is not set, please provide it like Route0.create(route, {origin: "https://example.com"}) in config or set via clones like routes._.clone({origin: "https://example.com"})'
79
+ );
80
+ }
81
+ return this._origin;
82
+ }
83
+ set origin(origin) {
84
+ this._origin = origin;
85
+ }
86
+ constructor(definition, config = {}) {
87
+ const normalizedDefinition = Route0.normalizeSlash(definition);
88
+ Route0._validateRouteDefinition(normalizedDefinition);
89
+ this.definition = normalizedDefinition;
90
+ this.params = this.pathParamsDefinition;
91
+ const { origin } = config;
92
+ if (origin && typeof origin === "string" && origin.length) {
93
+ this._origin = origin;
94
+ } else {
95
+ const g = globalThis;
96
+ if (typeof g?.location?.origin === "string" && g.location.origin.length > 0) {
97
+ this._origin = g.location.origin;
98
+ } else {
99
+ this._origin = void 0;
100
+ }
101
+ }
102
+ const callable = this.get.bind(this);
103
+ Object.setPrototypeOf(callable, this);
104
+ Object.defineProperty(callable, Symbol.toStringTag, {
105
+ value: this.definition
106
+ });
107
+ this._callable = callable;
108
+ }
109
+ /**
110
+ * Creates a callable route instance.
111
+ *
112
+ * If an existing route/callable route is provided, it is cloned.
113
+ */
114
+ static create(definition, config) {
115
+ if (typeof definition === "function" || typeof definition === "object") {
116
+ return definition.clone(config);
117
+ }
118
+ const original = new Route0(
119
+ Route0.normalizeSlash(definition),
120
+ config
121
+ );
122
+ return original._callable;
123
+ }
124
+ /**
125
+ * Normalizes a definition/route into a callable route.
126
+ *
127
+ * Unlike `create`, passing a callable route returns the same instance.
128
+ */
129
+ static from(definition) {
130
+ if (typeof definition === "function") {
131
+ return definition;
132
+ }
133
+ const original = typeof definition === "object" ? definition : new Route0(
134
+ Route0.normalizeSlash(definition)
135
+ );
136
+ return original._callable;
137
+ }
138
+ static _getAbsPath(origin, url) {
139
+ return new URL(url, origin).toString().replace(/\/$/, "");
140
+ }
141
+ search() {
142
+ return this._callable;
143
+ }
144
+ /** Extends the current route definition by appending a suffix route. */
145
+ extend(suffixDefinition) {
146
+ const definition = Route0.normalizeSlash(`${this.definitionWithoutTrailingWildcard}/${suffixDefinition}`);
147
+ return Route0.create(
148
+ definition,
149
+ {
150
+ origin: this._origin
151
+ }
152
+ );
153
+ }
154
+ // implementation
155
+ get(...args) {
156
+ const { searchInput, paramsInput, absInput, absOriginInput, hashInput } = (() => {
157
+ if (args.length === 0) {
158
+ return {
159
+ searchInput: {},
160
+ paramsInput: {},
161
+ absInput: false,
162
+ absOriginInput: void 0,
163
+ hashInput: void 0
164
+ };
165
+ }
166
+ const [input, abs] = (() => {
167
+ if (typeof args[0] === "object" && args[0] !== null) {
168
+ return [args[0], args[1]];
169
+ }
170
+ if (typeof args[1] === "object" && args[1] !== null) {
171
+ return [args[1], args[0]];
172
+ }
173
+ if (typeof args[0] === "boolean" || typeof args[0] === "string") {
174
+ return [{}, args[0]];
175
+ }
176
+ if (typeof args[1] === "boolean" || typeof args[1] === "string") {
177
+ return [{}, args[1]];
178
+ }
179
+ return [{}, void 0];
180
+ })();
181
+ let searchInput2 = {};
182
+ let hashInput2 = void 0;
183
+ const paramsInput2 = {};
184
+ for (const [key, value] of Object.entries(input)) {
185
+ if (key === "?" && typeof value === "object" && value !== null) {
186
+ searchInput2 = value;
187
+ } else if (key === "#" && (typeof value === "string" || typeof value === "number")) {
188
+ hashInput2 = String(value);
189
+ } else if (key in this.params && (typeof value === "string" || typeof value === "number")) {
190
+ Object.assign(paramsInput2, { [key]: String(value) });
191
+ }
192
+ }
193
+ const absOriginInput2 = typeof abs === "string" && abs.length > 0 ? abs : void 0;
194
+ return {
195
+ searchInput: searchInput2,
196
+ paramsInput: paramsInput2,
197
+ absInput: absOriginInput2 !== void 0 || abs === true,
198
+ absOriginInput: absOriginInput2,
199
+ hashInput: hashInput2
200
+ };
201
+ })();
202
+ let url = this.definition;
203
+ url = url.replace(/\/:([A-Za-z0-9_]+)\?/g, (_m, k) => {
204
+ const value = paramsInput[k];
205
+ if (value === void 0) return "";
206
+ return `/${encodeURIComponent(String(value))}`;
207
+ });
208
+ url = url.replace(/:([A-Za-z0-9_]+)(?!\?)/g, (_m, k) => encodeURIComponent(String(paramsInput?.[k] ?? "undefined")));
209
+ url = url.replace(/\/\*\?/g, () => {
210
+ const value = paramsInput["*"];
211
+ if (value === void 0) return "";
212
+ const stringValue = String(value);
213
+ return stringValue.startsWith("/") ? stringValue : `/${stringValue}`;
214
+ });
215
+ url = url.replace(/\/\*/g, () => {
216
+ const value = String(paramsInput["*"] ?? "");
217
+ return value.startsWith("/") ? value : `/${value}`;
218
+ });
219
+ url = url.replace(/\*\?/g, () => String(paramsInput["*"] ?? ""));
220
+ url = url.replace(/\*/g, () => String(paramsInput["*"] ?? ""));
221
+ const searchString = (0, import_flat0.stringify)(searchInput, { arrayIndexes: false });
222
+ url = [url, searchString].filter(Boolean).join("?");
223
+ url = collapseDuplicateSlashes(url);
224
+ url = absInput ? Route0._getAbsPath(absOriginInput || this.origin, url) : url;
225
+ if (hashInput !== void 0) {
226
+ url = `${url}#${hashInput}`;
227
+ }
228
+ return url;
229
+ }
230
+ /** Returns path param keys extracted from route definition. */
231
+ getParamsKeys() {
232
+ return Object.keys(this.params);
233
+ }
234
+ getTokens() {
235
+ return this.routeTokens.map((token) => ({ ...token }));
236
+ }
237
+ /** Clones route with optional config override. */
238
+ clone(config) {
239
+ return Route0.create(this.definition, config);
240
+ }
241
+ get regexBaseString() {
242
+ if (this._regexBaseString === void 0) {
243
+ this._regexBaseString = this.routeRegexBaseStringRaw.replace(/\/+$/, "") + "/?";
244
+ }
245
+ return this._regexBaseString;
246
+ }
247
+ get regexString() {
248
+ if (this._regexString === void 0) {
249
+ this._regexString = `^${this.regexBaseString}$`;
250
+ }
251
+ return this._regexString;
252
+ }
253
+ get regex() {
254
+ if (this._regex === void 0) {
255
+ this._regex = new RegExp(this.regexString);
256
+ }
257
+ return this._regex;
258
+ }
259
+ get regexAncestor() {
260
+ if (this._regexAncestor === void 0) {
261
+ this._regexAncestor = new RegExp(`^${this.regexBaseString}(?:/.*)?$`);
262
+ }
263
+ return this._regexAncestor;
264
+ }
265
+ get regexDescendantMatchers() {
266
+ if (this._regexDescendantMatchers === void 0) {
267
+ const matchers = [];
268
+ if (this.definitionParts[0] !== "/") {
269
+ let pattern = "";
270
+ const captureKeys = [];
271
+ for (const part of this.definitionParts) {
272
+ if (part.startsWith(":")) {
273
+ pattern += "/([^/]+)";
274
+ captureKeys.push(part.replace(/^:/, "").replace(/\?$/, ""));
275
+ } else if (part.includes("*")) {
276
+ const prefix = part.replace(/\*\??$/, "");
277
+ pattern += `/${escapeRegex(prefix)}[^/]*`;
278
+ captureKeys.push("*");
279
+ } else {
280
+ pattern += `/${escapeRegex(part)}`;
281
+ }
282
+ matchers.push({
283
+ regex: new RegExp(`^${pattern}/?$`),
284
+ captureKeys: [...captureKeys]
285
+ });
286
+ }
287
+ }
288
+ this._regexDescendantMatchers = matchers;
289
+ }
290
+ return this._regexDescendantMatchers;
291
+ }
292
+ get captureKeys() {
293
+ if (this._captureKeys === void 0) {
294
+ this._captureKeys = this.routeTokens.filter((token) => token.kind !== "static").map((token) => token.kind === "param" ? token.name : "*");
295
+ }
296
+ return this._captureKeys;
297
+ }
298
+ get routeSegments() {
299
+ if (this._routeSegments === void 0) {
300
+ this._routeSegments = Route0._getRouteSegments(this.definition);
301
+ }
302
+ return this._routeSegments;
303
+ }
304
+ get routeTokens() {
305
+ if (this._routeTokens === void 0) {
306
+ this._routeTokens = this.routeSegments.map((segment) => {
307
+ const param = segment.match(/^:([A-Za-z0-9_]+)(\?)?$/);
308
+ if (param) {
309
+ return { kind: "param", name: param[1], optional: param[2] === "?" };
310
+ }
311
+ if (segment === "*" || segment === "*?") {
312
+ return { kind: "wildcard", prefix: "", optional: segment.endsWith("?") };
313
+ }
314
+ const wildcard = segment.match(/^(.*)\*(\?)?$/);
315
+ if (wildcard && !segment.includes("\\*")) {
316
+ return { kind: "wildcard", prefix: wildcard[1], optional: wildcard[2] === "?" };
317
+ }
318
+ return { kind: "static", value: segment };
319
+ });
320
+ }
321
+ return this._routeTokens;
322
+ }
323
+ get routePatternCandidates() {
324
+ if (this._routePatternCandidates === void 0) {
325
+ const values = (token) => {
326
+ if (token.kind === "static") return [token.value];
327
+ if (token.kind === "param") return token.optional ? ["", "x", "y"] : ["x", "y"];
328
+ if (token.prefix.length > 0)
329
+ return [token.prefix, `${token.prefix}-x`, `${token.prefix}/x`, `${token.prefix}/y/z`];
330
+ return ["", "x", "y", "x/y"];
331
+ };
332
+ let acc = [""];
333
+ for (const token of this.routeTokens) {
334
+ const next = [];
335
+ for (const base of acc) {
336
+ for (const value of values(token)) {
337
+ if (value === "") {
338
+ next.push(base);
339
+ } else if (value.startsWith("/")) {
340
+ next.push(`${base}${value}`);
341
+ } else {
342
+ next.push(`${base}/${value}`);
343
+ }
344
+ }
345
+ }
346
+ acc = next.length > 512 ? next.slice(0, 512) : next;
347
+ }
348
+ this._routePatternCandidates = acc.length === 0 ? ["/"] : Array.from(new Set(acc.map((x) => x === "" ? "/" : collapseDuplicateSlashes(x))));
349
+ }
350
+ return this._routePatternCandidates;
351
+ }
352
+ get pathParamsDefinition() {
353
+ if (this._pathParamsDefinition === void 0) {
354
+ const entries = this.routeTokens.filter((t) => t.kind !== "static").map((t) => t.kind === "param" ? [t.name, !t.optional] : ["*", !t.optional]);
355
+ this._pathParamsDefinition = Object.fromEntries(entries);
356
+ }
357
+ return this._pathParamsDefinition;
358
+ }
359
+ get definitionWithoutTrailingWildcard() {
360
+ if (this._definitionWithoutTrailingWildcard === void 0) {
361
+ this._definitionWithoutTrailingWildcard = this.definition.replace(/\*\??$/, "");
362
+ }
363
+ return this._definitionWithoutTrailingWildcard;
364
+ }
365
+ get routeRegexBaseStringRaw() {
366
+ if (this._routeRegexBaseStringRaw === void 0) {
367
+ if (this.routeTokens.length === 0) {
368
+ this._routeRegexBaseStringRaw = "";
369
+ } else {
370
+ let pattern = "";
371
+ for (const token of this.routeTokens) {
372
+ if (token.kind === "static") {
373
+ pattern += `/${escapeRegex(token.value)}`;
374
+ continue;
375
+ }
376
+ if (token.kind === "param") {
377
+ pattern += token.optional ? "(?:/([^/]+))?" : "/([^/]+)";
378
+ continue;
379
+ }
380
+ if (token.prefix.length > 0) {
381
+ pattern += `/${escapeRegex(token.prefix)}(.*)`;
382
+ } else {
383
+ pattern += "(?:/(.*))?";
384
+ }
385
+ }
386
+ this._routeRegexBaseStringRaw = pattern;
387
+ }
388
+ }
389
+ return this._routeRegexBaseStringRaw;
390
+ }
391
+ get normalizedDefinition() {
392
+ if (this._normalizedDefinition === void 0) {
393
+ this._normalizedDefinition = this.definition.length > 1 && this.definition.endsWith("/") ? this.definition.slice(0, -1) : this.definition;
394
+ }
395
+ return this._normalizedDefinition;
396
+ }
397
+ get definitionParts() {
398
+ if (this._definitionParts === void 0) {
399
+ this._definitionParts = this.normalizedDefinition === "/" ? ["/"] : this.normalizedDefinition.split("/").filter(Boolean);
400
+ }
401
+ return this._definitionParts;
402
+ }
403
+ /** Fast pathname exact match check without building a full relation object. */
404
+ isExact(pathname, normalize = true) {
405
+ const normalizedPathname = normalize ? Route0.normalizeSlash(pathname) : pathname;
406
+ return this.regex.test(normalizedPathname);
407
+ }
408
+ /** Fast pathname exact or ancestor match check without building a full relation object. */
409
+ isExactOrAncestor(pathname, normalize = true) {
410
+ const normalizedPathname = normalize ? Route0.normalizeSlash(pathname) : pathname;
411
+ return this.regex.test(normalizedPathname) || this.regexAncestor.test(normalizedPathname);
412
+ }
413
+ /** True when route is ancestor of pathname (pathname is deeper). */
414
+ isAncestor(pathname, normalize = true) {
415
+ const normalizedPathname = normalize ? Route0.normalizeSlash(pathname) : pathname;
416
+ return !this.regex.test(normalizedPathname) && this.regexAncestor.test(normalizedPathname);
417
+ }
418
+ /** True when route is descendant of pathname (pathname is shallower). */
419
+ isDescendant(pathname, normalize = true) {
420
+ const normalizedPathname = normalize ? Route0.normalizeSlash(pathname) : pathname;
421
+ if (this.regex.test(normalizedPathname) || this.regexAncestor.test(normalizedPathname)) {
422
+ return false;
423
+ }
424
+ for (const matcher of this.regexDescendantMatchers) {
425
+ if (normalizedPathname.match(matcher.regex)) {
426
+ return true;
427
+ }
428
+ }
429
+ return false;
430
+ }
431
+ /** Creates a grouped regex pattern string from many routes. */
432
+ static getRegexStringGroup(routes) {
433
+ const patterns = routes.map((route) => route.regexString).join("|");
434
+ return `(${patterns})`;
435
+ }
436
+ /** Creates a grouped regex from many routes. */
437
+ static getRegexGroup(routes) {
438
+ const patterns = Route0.getRegexStringGroup(routes);
439
+ return new RegExp(`^(${patterns})$`);
440
+ }
441
+ /** Converts any location shape to relative form (removes host/origin fields). */
442
+ static toRelLocation(location) {
443
+ return {
444
+ ...location,
445
+ abs: false,
446
+ origin: void 0,
447
+ href: void 0,
448
+ port: void 0,
449
+ host: void 0,
450
+ hostname: void 0
451
+ };
452
+ }
453
+ /** Converts a location to absolute form using provided origin URL. */
454
+ static toAbsLocation(location, origin) {
455
+ const relLoc = Route0.toRelLocation(location);
456
+ const url = new URL(relLoc.hrefRel, origin);
457
+ return {
458
+ ...location,
459
+ abs: true,
460
+ origin: url.origin,
461
+ href: url.href,
462
+ port: url.port,
463
+ host: url.host,
464
+ hostname: url.hostname
465
+ };
466
+ }
467
+ static getLocation(hrefOrHrefRelOrLocation) {
468
+ if (hrefOrHrefRelOrLocation instanceof URL) {
469
+ return Route0.getLocation(hrefOrHrefRelOrLocation.href);
470
+ }
471
+ if (typeof hrefOrHrefRelOrLocation !== "string") {
472
+ hrefOrHrefRelOrLocation = hrefOrHrefRelOrLocation.href || hrefOrHrefRelOrLocation.hrefRel;
473
+ }
474
+ const abs = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(hrefOrHrefRelOrLocation);
475
+ const base = abs ? void 0 : "http://example.com";
476
+ const url = new URL(hrefOrHrefRelOrLocation, base);
477
+ const hrefRel = url.pathname + url.search + url.hash;
478
+ let _search;
479
+ const location = {
480
+ pathname: url.pathname,
481
+ get search() {
482
+ if (_search === void 0) {
483
+ _search = (0, import_flat0.parse)(url.search);
484
+ }
485
+ return _search;
486
+ },
487
+ searchString: url.search,
488
+ hash: url.hash,
489
+ origin: abs ? url.origin : void 0,
490
+ href: abs ? url.href : void 0,
491
+ hrefRel,
492
+ abs,
493
+ // extra host-related fields (available even for relative with dummy base)
494
+ host: abs ? url.host : void 0,
495
+ hostname: abs ? url.hostname : void 0,
496
+ port: abs ? url.port || void 0 : void 0,
497
+ // specific to UnknownLocation
498
+ params: void 0,
499
+ route: void 0
500
+ };
501
+ return location;
502
+ }
503
+ getRelation(hrefOrHrefRelOrLocation) {
504
+ if (hrefOrHrefRelOrLocation instanceof URL) {
505
+ return this.getRelation(hrefOrHrefRelOrLocation.href);
506
+ }
507
+ if (typeof hrefOrHrefRelOrLocation !== "string") {
508
+ hrefOrHrefRelOrLocation = hrefOrHrefRelOrLocation.href || hrefOrHrefRelOrLocation.hrefRel;
509
+ }
510
+ const pathname = Route0.normalizeSlash(new URL(hrefOrHrefRelOrLocation, "http://example.com").pathname);
511
+ const paramNames = this.captureKeys;
512
+ const exactRe = this.regex;
513
+ const exactMatch = pathname.match(exactRe);
514
+ if (exactMatch) {
515
+ const values = exactMatch.slice(1, 1 + paramNames.length);
516
+ const params = Object.fromEntries(
517
+ paramNames.map((n, i) => {
518
+ const value = values[i];
519
+ return [n, value === void 0 ? void 0 : decodeURIComponent(value)];
520
+ })
521
+ );
522
+ return {
523
+ type: "exact",
524
+ route: this.definition,
525
+ params,
526
+ exact: true,
527
+ ascendant: false,
528
+ descendant: false,
529
+ unmatched: false
530
+ };
531
+ }
532
+ const ancestorRe = this.regexAncestor;
533
+ const ancestorMatch = pathname.match(ancestorRe);
534
+ if (ancestorMatch) {
535
+ const values = ancestorMatch.slice(1, 1 + paramNames.length);
536
+ const params = Object.fromEntries(
537
+ paramNames.map((n, i) => {
538
+ const value = values[i];
539
+ return [n, value === void 0 ? void 0 : decodeURIComponent(value)];
540
+ })
541
+ );
542
+ return {
543
+ type: "ascendant",
544
+ route: this.definition,
545
+ params,
546
+ exact: false,
547
+ ascendant: true,
548
+ descendant: false,
549
+ unmatched: false
550
+ };
551
+ }
552
+ let descendantMatch = null;
553
+ let descendantCaptureKeys = [];
554
+ for (const matcher of this.regexDescendantMatchers) {
555
+ const match = pathname.match(matcher.regex);
556
+ if (!match) continue;
557
+ descendantMatch = match;
558
+ descendantCaptureKeys = matcher.captureKeys;
559
+ break;
560
+ }
561
+ if (descendantMatch) {
562
+ const values = descendantMatch.slice(1, 1 + descendantCaptureKeys.length);
563
+ const params = Object.fromEntries(
564
+ descendantCaptureKeys.map((key, index) => [key, decodeURIComponent(values[index])])
565
+ );
566
+ return {
567
+ type: "descendant",
568
+ route: this.definition,
569
+ params,
570
+ exact: false,
571
+ ascendant: false,
572
+ descendant: true,
573
+ unmatched: false
574
+ };
575
+ }
576
+ return {
577
+ type: "unmatched",
578
+ route: this.definition,
579
+ params: {},
580
+ exact: false,
581
+ ascendant: false,
582
+ descendant: false,
583
+ unmatched: true
584
+ };
585
+ }
586
+ _validateParamsInput(input) {
587
+ const paramsEntries = Object.entries(this.params);
588
+ const paramsMap = this.params;
589
+ const requiredParamsKeys = paramsEntries.filter(([, required]) => required).map(([k]) => k);
590
+ const paramsKeys = paramsEntries.map(([k]) => k);
591
+ if (input === void 0) {
592
+ if (requiredParamsKeys.length) {
593
+ return {
594
+ issues: [
595
+ {
596
+ message: `Missing params: ${requiredParamsKeys.map((k) => `"${k}"`).join(", ")}`
597
+ }
598
+ ]
599
+ };
600
+ }
601
+ input = {};
602
+ }
603
+ if (typeof input !== "object" || input === null) {
604
+ return {
605
+ issues: [{ message: "Invalid route params: expected object" }]
606
+ };
607
+ }
608
+ const inputObj = input;
609
+ const inputKeys = Object.keys(inputObj);
610
+ const notDefinedKeys = requiredParamsKeys.filter((k) => !inputKeys.includes(k));
611
+ if (notDefinedKeys.length) {
612
+ return {
613
+ issues: [
614
+ {
615
+ message: `Missing params: ${notDefinedKeys.map((k) => `"${k}"`).join(", ")}`
616
+ }
617
+ ]
618
+ };
619
+ }
620
+ const data = {};
621
+ for (const k of paramsKeys) {
622
+ const v = inputObj[k];
623
+ const required = paramsMap[k];
624
+ if (v === void 0 && !required) {
625
+ data[k] = void 0;
626
+ } else if (typeof v === "string") {
627
+ data[k] = v;
628
+ } else if (typeof v === "number") {
629
+ data[k] = String(v);
630
+ } else {
631
+ return {
632
+ issues: [{ message: `Invalid route params: expected string, number, got ${typeof v} for "${k}"` }]
633
+ };
634
+ }
635
+ }
636
+ return {
637
+ value: data
638
+ };
639
+ }
640
+ _safeParseSchemaResult(result) {
641
+ if ("issues" in result) {
642
+ return {
643
+ success: false,
644
+ data: void 0,
645
+ error: new Error(result.issues?.[0]?.message ?? "Invalid input")
646
+ };
647
+ }
648
+ return {
649
+ success: true,
650
+ data: result.value,
651
+ error: void 0
652
+ };
653
+ }
654
+ _parseSchemaResult(result) {
655
+ const safeResult = this._safeParseSchemaResult(result);
656
+ if (safeResult.error) {
657
+ throw safeResult.error;
658
+ }
659
+ return safeResult.data;
660
+ }
661
+ /** Standard Schema for route params input. */
662
+ schema = {
663
+ "~standard": {
664
+ version: 1,
665
+ vendor: "route0",
666
+ validate: (value) => this._validateParamsInput(value),
667
+ types: void 0
668
+ },
669
+ parse: (value) => this._parseSchemaResult(this._validateParamsInput(value)),
670
+ safeParse: (value) => this._safeParseSchemaResult(this._validateParamsInput(value))
671
+ };
672
+ // /** True when path structure is equal (param names are ignored). */
673
+ // isSame(other: AnyRoute): boolean {
674
+ // const thisShape = this.routeTokens
675
+ // .map((t) => {
676
+ // if (t.kind === 'static') return `s:${t.value}`
677
+ // if (t.kind === 'param') return `p:${t.optional ? 'o' : 'r'}`
678
+ // return `w:${t.prefix}:${t.optional ? 'o' : 'r'}`
679
+ // })
680
+ // .join('/')
681
+ // const otherRoute = Route0.from(other) as Route0<string, UnknownSearchInput>
682
+ // const otherShape = otherRoute.routeTokens
683
+ // .map((t) => {
684
+ // if (t.kind === 'static') return `s:${t.value}`
685
+ // if (t.kind === 'param') return `p:${t.optional ? 'o' : 'r'}`
686
+ // return `w:${t.prefix}:${t.optional ? 'o' : 'r'}`
687
+ // })
688
+ // .join('/')
689
+ // return thisShape === otherShape
690
+ // }
691
+ // /** Static convenience wrapper for `isSame`. */
692
+ // static isSame(a: AnyRoute | string | undefined, b: AnyRoute | string | undefined): boolean {
693
+ // if (!a) {
694
+ // if (!b) return true
695
+ // return false
696
+ // }
697
+ // if (!b) {
698
+ // return false
699
+ // }
700
+ // return Route0.create(a).isSame(Route0.create(b))
701
+ // }
702
+ // /** True when current route is more specific/deeper than `other`. */
703
+ // isDescendant(other: AnyRoute | string | undefined): boolean {
704
+ // if (!other) return false
705
+ // other = Route0.create(other)
706
+ // // this is a descendant of other if:
707
+ // // - paths are not exactly the same
708
+ // // - other's path is a prefix of this path, matching params as wildcards
709
+ // const getParts = (path: string) => (path === '/' ? ['/'] : path.split('/').filter(Boolean))
710
+ // // Root is ancestor of any non-root; thus any non-root is a descendant of root
711
+ // if (other.definition === '/' && this.definition !== '/') {
712
+ // return true
713
+ // }
714
+ // const thisParts = getParts(this.definition)
715
+ // const otherParts = getParts(other.definition)
716
+ // // A descendant must be deeper
717
+ // if (thisParts.length <= otherParts.length) return false
718
+ // const matchesPatternPart = (patternPart: string, valuePart: string): { match: boolean; wildcard: boolean } => {
719
+ // if (patternPart.startsWith(':')) return { match: true, wildcard: false }
720
+ // const wildcardIndex = patternPart.indexOf('*')
721
+ // if (wildcardIndex >= 0) {
722
+ // const prefix = patternPart.slice(0, wildcardIndex)
723
+ // return { match: prefix.length === 0 || valuePart.startsWith(prefix), wildcard: true }
724
+ // }
725
+ // return { match: patternPart === valuePart, wildcard: false }
726
+ // }
727
+ // for (let i = 0; i < otherParts.length; i++) {
728
+ // const otherPart = otherParts[i]
729
+ // const thisPart = thisParts[i]
730
+ // const result = matchesPatternPart(otherPart, thisPart)
731
+ // if (!result.match) return false
732
+ // if (result.wildcard) return true
733
+ // }
734
+ // // Not equal (depth already ensures not equal)
735
+ // return true
736
+ // }
737
+ // /** True when current route is broader/shallower than `other`. */
738
+ // isAncestor(other: AnyRoute | string | undefined): boolean {
739
+ // if (!other) return false
740
+ // other = Route0.create(other)
741
+ // // this is an ancestor of other if:
742
+ // // - paths are not exactly the same
743
+ // // - this path is a prefix of other path, matching params as wildcards
744
+ // const getParts = (path: string) => (path === '/' ? ['/'] : path.split('/').filter(Boolean))
745
+ // // Root is ancestor of any non-root path
746
+ // if (this.definition === '/' && other.definition !== '/') {
747
+ // return true
748
+ // }
749
+ // const thisParts = getParts(this.definition)
750
+ // const otherParts = getParts(other.definition)
751
+ // // An ancestor must be shallower
752
+ // if (thisParts.length >= otherParts.length) return false
753
+ // const matchesPatternPart = (patternPart: string, valuePart: string): { match: boolean; wildcard: boolean } => {
754
+ // if (patternPart.startsWith(':')) return { match: true, wildcard: false }
755
+ // const wildcardIndex = patternPart.indexOf('*')
756
+ // if (wildcardIndex >= 0) {
757
+ // const prefix = patternPart.slice(0, wildcardIndex)
758
+ // return { match: prefix.length === 0 || valuePart.startsWith(prefix), wildcard: true }
759
+ // }
760
+ // return { match: patternPart === valuePart, wildcard: false }
761
+ // }
762
+ // for (let i = 0; i < thisParts.length; i++) {
763
+ // const thisPart = thisParts[i]
764
+ // const otherPart = otherParts[i]
765
+ // const result = matchesPatternPart(thisPart, otherPart)
766
+ // if (!result.match) return false
767
+ // if (result.wildcard) return true
768
+ // }
769
+ // // Not equal (depth already ensures not equal)
770
+ // return true
771
+ // }
772
+ /** True when two route patterns can match the same concrete URL. */
773
+ isOverlap(other) {
774
+ if (!other) return false;
775
+ const otherRoute = Route0.from(other);
776
+ const thisRegex = this.regex;
777
+ const otherRegex = otherRoute.regex;
778
+ const thisCandidates = this.routePatternCandidates;
779
+ const otherCandidates = otherRoute.routePatternCandidates;
780
+ if (thisCandidates.some((path) => otherRegex.test(path))) return true;
781
+ if (otherCandidates.some((path) => thisRegex.test(path))) return true;
782
+ return false;
783
+ }
784
+ /**
785
+ * True when overlap is not resolvable by route ordering inside one route set.
786
+ *
787
+ * Non-conflicting overlap means one route is a strict subset of another
788
+ * (e.g. `/x/y` is a strict subset of `/x/:id`) and can be safely ordered first.
789
+ */
790
+ isConflict(other) {
791
+ if (!other) return false;
792
+ const otherRoute = Route0.from(other);
793
+ if (!this.isOverlap(otherRoute)) return false;
794
+ const thisRegex = this.regex;
795
+ const otherRegex = otherRoute.regex;
796
+ const thisCandidates = this.routePatternCandidates;
797
+ const otherCandidates = otherRoute.routePatternCandidates;
798
+ const thisExclusive = thisCandidates.some((path) => thisRegex.test(path) && !otherRegex.test(path));
799
+ const otherExclusive = otherCandidates.some((path) => otherRegex.test(path) && !thisRegex.test(path));
800
+ if (thisExclusive !== otherExclusive) return false;
801
+ return true;
802
+ }
803
+ /** Specificity comparator used for deterministic route ordering. */
804
+ isMoreSpecificThan(other) {
805
+ if (!other) return false;
806
+ other = Route0.create(other);
807
+ const getParts = (path) => {
808
+ if (path === "/") return ["/"];
809
+ return path.split("/").filter(Boolean);
810
+ };
811
+ const rank = (part) => {
812
+ if (part.includes("*")) return -1;
813
+ if (part.startsWith(":") && part.endsWith("?")) return 0;
814
+ if (part.startsWith(":")) return 1;
815
+ return 2;
816
+ };
817
+ const thisParts = getParts(this.definition);
818
+ const otherParts = getParts(other.definition);
819
+ for (let i = 0; i < Math.min(thisParts.length, otherParts.length); i++) {
820
+ const thisRank = rank(thisParts[i]);
821
+ const otherRank = rank(otherParts[i]);
822
+ if (thisRank > otherRank) return true;
823
+ if (thisRank < otherRank) return false;
824
+ }
825
+ return this.definition < other.definition;
826
+ }
827
+ }
828
+ class Routes {
829
+ _routes;
830
+ _pathsOrdering;
831
+ _keysOrdering;
832
+ _ordered;
833
+ _;
834
+ constructor({
835
+ routes,
836
+ isHydrated = false,
837
+ pathsOrdering,
838
+ keysOrdering,
839
+ ordered
840
+ }) {
841
+ this._routes = isHydrated ? routes : Routes.hydrate(routes);
842
+ if (!pathsOrdering || !keysOrdering || !ordered) {
843
+ const ordering = Routes.makeOrdering(this._routes);
844
+ this._pathsOrdering = ordering.pathsOrdering;
845
+ this._keysOrdering = ordering.keysOrdering;
846
+ this._ordered = this._keysOrdering.map((key) => this._routes[key]);
847
+ } else {
848
+ this._pathsOrdering = pathsOrdering;
849
+ this._keysOrdering = keysOrdering;
850
+ this._ordered = ordered;
851
+ }
852
+ this._ = {
853
+ routes: this._routes,
854
+ getLocation: this._getLocation.bind(this),
855
+ clone: this._clone.bind(this),
856
+ pathsOrdering: this._pathsOrdering,
857
+ keysOrdering: this._keysOrdering,
858
+ ordered: this._ordered
859
+ };
860
+ }
861
+ /** Creates and hydrates a typed routes collection. */
862
+ static create(routes, override) {
863
+ const result = Routes.prettify(new Routes({ routes }));
864
+ if (!override) {
865
+ return result;
866
+ }
867
+ return result._.clone(override);
868
+ }
869
+ static prettify(instance) {
870
+ Object.setPrototypeOf(instance, Routes.prototype);
871
+ Object.defineProperty(instance, Symbol.toStringTag, {
872
+ value: "Routes"
873
+ });
874
+ Object.assign(instance, {
875
+ clone: instance._clone.bind(instance)
876
+ });
877
+ Object.assign(instance, instance._routes);
878
+ return instance;
879
+ }
880
+ static hydrate(routes) {
881
+ const result = {};
882
+ for (const key in routes) {
883
+ if (Object.hasOwn(routes, key)) {
884
+ const value = routes[key];
885
+ result[key] = typeof value === "string" ? Route0.create(value) : value;
886
+ }
887
+ }
888
+ return result;
889
+ }
890
+ _getLocation(hrefOrHrefRelOrLocation) {
891
+ const input = hrefOrHrefRelOrLocation;
892
+ const location = Route0.getLocation(input);
893
+ for (const route of this._ordered) {
894
+ if (route.isExact(location.pathname, false)) {
895
+ const relation = route.getRelation(input);
896
+ return Object.assign(location, {
897
+ route: route.definition,
898
+ params: relation.params
899
+ });
900
+ }
901
+ }
902
+ return location;
903
+ }
904
+ static makeOrdering(routes) {
905
+ const hydrated = Routes.hydrate(routes);
906
+ const entries = Object.entries(hydrated);
907
+ const getParts = (path) => {
908
+ if (path === "/") return ["/"];
909
+ return path.split("/").filter(Boolean);
910
+ };
911
+ entries.sort(([_keyA, routeA], [_keyB, routeB]) => {
912
+ const partsA = getParts(routeA.definition);
913
+ const partsB = getParts(routeB.definition);
914
+ if (routeA.isOverlap(routeB)) {
915
+ if (routeA.isMoreSpecificThan(routeB)) return -1;
916
+ if (routeB.isMoreSpecificThan(routeA)) return 1;
917
+ }
918
+ if (partsA.length !== partsB.length) {
919
+ return partsA.length - partsB.length;
920
+ }
921
+ return routeA.definition.localeCompare(routeB.definition);
922
+ });
923
+ const pathsOrdering = entries.map(([_key, route]) => route.definition);
924
+ const keysOrdering = entries.map(([_key]) => _key);
925
+ return { pathsOrdering, keysOrdering };
926
+ }
927
+ /** Returns a cloned routes collection with config applied to each route. */
928
+ _clone(config) {
929
+ const newRoutes = {};
930
+ for (const key in this._routes) {
931
+ if (Object.hasOwn(this._routes, key)) {
932
+ newRoutes[key] = this._routes[key].clone(config);
933
+ }
934
+ }
935
+ const instance = new Routes({
936
+ routes: newRoutes,
937
+ isHydrated: true,
938
+ pathsOrdering: this._pathsOrdering,
939
+ keysOrdering: this._keysOrdering,
940
+ ordered: this._keysOrdering.map((key) => newRoutes[key])
941
+ });
942
+ return Routes.prettify(instance);
943
+ }
944
+ static _ = {
945
+ prettify: Routes.prettify.bind(Routes),
946
+ hydrate: Routes.hydrate.bind(Routes),
947
+ makeOrdering: Routes.makeOrdering.bind(Routes)
948
+ };
949
+ }
950
+ // Annotate the CommonJS export names for ESM import in node:
951
+ 0 && (module.exports = {
952
+ Route0,
953
+ Routes
954
+ });
955
+ //# sourceMappingURL=index.cjs.map