@cartanova/qgrid-cli 2.19.1 → 2.19.3

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.
Files changed (71) hide show
  1. package/bundle/dist/application/qgrid/qgrid-run-lifecycle.js +5 -2
  2. package/bundle/dist/application/qgrid/qgrid.dispatcher.js +3 -1
  3. package/bundle/dist/application/qgrid/qgrid.frame.js +225 -6
  4. package/bundle/dist/application/qgrid/qgrid.types.js +74 -2
  5. package/bundle/dist/application/request-log/request-log.model.js +11 -1
  6. package/bundle/dist/application/sonamu.generated.js +5 -3
  7. package/bundle/dist/i18n/sd.generated.js +3 -2
  8. package/bundle/dist/utils/providers/common/model-cost.js +8 -2
  9. package/bundle/dist/utils/providers/openai/openai-dispatcher.js +18 -1
  10. package/bundle/dist/utils/providers/openai/openai-realtime-protocol.js +120 -2
  11. package/bundle/dist/utils/providers/openai/openai-voice-client.js +184 -6
  12. package/bundle/src/application/qgrid/qgrid-run-lifecycle.test.ts +13 -0
  13. package/bundle/src/application/qgrid/qgrid-run-lifecycle.ts +11 -1
  14. package/bundle/src/application/qgrid/qgrid.dispatcher.test.ts +17 -0
  15. package/bundle/src/application/qgrid/qgrid.dispatcher.ts +8 -0
  16. package/bundle/src/application/qgrid/qgrid.frame.test.ts +223 -0
  17. package/bundle/src/application/qgrid/qgrid.frame.ts +304 -3
  18. package/bundle/src/application/qgrid/qgrid.types.ts +121 -0
  19. package/bundle/src/application/request-log/request-log.entity.json +3 -2
  20. package/bundle/src/application/request-log/request-log.model.test.ts +19 -0
  21. package/bundle/src/application/request-log/request-log.model.ts +20 -1
  22. package/bundle/src/application/sonamu.generated.http +28 -0
  23. package/bundle/src/application/sonamu.generated.ts +2 -1
  24. package/bundle/src/i18n/sd.generated.ts +2 -1
  25. package/bundle/src/utils/providers/common/model-cost.ts +15 -0
  26. package/bundle/src/utils/providers/openai/openai-dispatcher.test.ts +16 -0
  27. package/bundle/src/utils/providers/openai/openai-dispatcher.ts +26 -0
  28. package/bundle/src/utils/providers/openai/openai-realtime-protocol.ts +160 -0
  29. package/bundle/src/utils/providers/openai/openai-voice-client.test.ts +205 -0
  30. package/bundle/src/utils/providers/openai/openai-voice-client.ts +284 -5
  31. package/bundle/web-dist/client/assets/index-B5yorZqv.js +104 -0
  32. package/bundle/web-dist/client/assets/index-CpOwNalw.css +1 -0
  33. package/bundle/web-dist/client/assets/logs-Bx_jXEDZ.js +1 -0
  34. package/bundle/web-dist/client/assets/monit-CPQ18s_m.js +1 -0
  35. package/bundle/web-dist/client/assets/{routes--6kS1pgJ.js → routes-S4D5Ld4L.js} +2 -2
  36. package/bundle/web-dist/client/assets/{settings-Dah87LB2.js → settings-M4h_UV87.js} +1 -1
  37. package/bundle/web-dist/client/assets/show-BchF-T1a.js +2 -0
  38. package/bundle/web-dist/client/assets/{tokens-CIHja806.js → tokens-BgBD07ru.js} +1 -1
  39. package/bundle/web-dist/client/assets/{use-oauth-login-flow-DeJCqHDJ.js → use-oauth-login-flow-D_wI9MzM.js} +1 -1
  40. package/bundle/web-dist/client/assets/use-update-token-mutation-IvuH3Qje.js +1 -0
  41. package/bundle/web-dist/client/assets/{vendor-tanstack-6B86itGS.js → vendor-tanstack-DMgmqjm4.js} +1 -1
  42. package/bundle/web-dist/client/assets/voice-CnIiQMbo.js +1 -0
  43. package/bundle/web-dist/client/index.html +3 -3
  44. package/bundle/web-dist/server/assets/{TimedPlayer-DAwjkP4z.js → TimedPlayer-COqaTQSl.js} +1 -1
  45. package/bundle/web-dist/server/assets/{logs-BmBpBe-j.js → logs-HPho1SkC.js} +5 -6
  46. package/bundle/web-dist/server/assets/{monit-Db1WrIls.js → monit-Bl2kSkSF.js} +3 -3
  47. package/bundle/web-dist/server/assets/{plus-CW9y_K7l.js → plus-CQ8AHpih.js} +1 -1
  48. package/bundle/web-dist/server/assets/{refresh-cw-CRgcH5bT.js → refresh-cw-pYSuvt4c.js} +1 -1
  49. package/bundle/web-dist/server/assets/{request-model-DRF7hmJC.js → request-model-ZulJMbGm.js} +1 -1
  50. package/bundle/web-dist/server/assets/{routes-CARZj7or.js → routes-BNHCX4VI.js} +4 -4
  51. package/bundle/web-dist/server/assets/{services.generated-B6QpnL_N.js → services.generated-C3b31_vt.js} +23209 -22930
  52. package/bundle/web-dist/server/assets/{settings-B4jdpP5N.js → settings-NJUyaSrJ.js} +4 -4
  53. package/bundle/web-dist/server/assets/{show-CnLDFCtW.js → show-Dz5QGL7l.js} +8 -9
  54. package/bundle/web-dist/server/assets/{tokens-TDQguTdh.js → tokens-BPQvjIGq.js} +5 -5
  55. package/bundle/web-dist/server/assets/{use-oauth-login-flow-du7pOh_H.js → use-oauth-login-flow-CCc8LEmn.js} +1 -1
  56. package/bundle/web-dist/server/assets/{use-update-token-mutation-DA6HiiWS.js → use-update-token-mutation-Ba-sEhq1.js} +1 -1
  57. package/bundle/web-dist/server/assets/{voice-BvAl-vTr.js → voice-xFFT4zqK.js} +307 -22
  58. package/bundle/web-dist/server/entry-server.generated.js +5590 -71
  59. package/package.json +1 -1
  60. package/skills/qgrid/references/decision-rationale.md +4 -0
  61. package/skills/qgrid/references/openai-codex-runtime.md +16 -0
  62. package/skills/qgrid/references/request-log-run-lifecycle.md +2 -1
  63. package/skills/qgrid/references/sonamu-api-web-flow.md +2 -2
  64. package/bundle/web-dist/client/assets/index-Co8uAhSV.css +0 -1
  65. package/bundle/web-dist/client/assets/index-DvW4Yb82.js +0 -104
  66. package/bundle/web-dist/client/assets/logs-DAif2re1.js +0 -1
  67. package/bundle/web-dist/client/assets/monit-DYczkiu0.js +0 -1
  68. package/bundle/web-dist/client/assets/show-DQWFaVDW.js +0 -2
  69. package/bundle/web-dist/client/assets/use-update-token-mutation-Cn_Po_rH.js +0 -1
  70. package/bundle/web-dist/client/assets/voice-6i785ieC.js +0 -1
  71. package/bundle/web-dist/server/assets/link-DrdV092C.js +0 -4919
@@ -1,4919 +0,0 @@
1
- import { J as require_react, Q as __toESM, q as require_jsx_runtime } from "./services.generated-B6QpnL_N.js";
2
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/not-found.js
3
- var import_react = /* @__PURE__ */ __toESM(require_react(), 1);
4
- /** Determine if a value is a TanStack Router not-found error. */
5
- function isNotFound(obj) {
6
- return obj?.isNotFound === true;
7
- }
8
- //#endregion
9
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/root.js
10
- /** Stable identifier used for the root route in a route tree. */
11
- var rootRouteId = "__root__";
12
- //#endregion
13
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/redirect.js
14
- /**
15
- * Create a redirect Response understood by TanStack Router.
16
- *
17
- * Use from route `loader`/`beforeLoad` or server functions to trigger a
18
- * navigation. If `throw: true` is set, the redirect is thrown instead of
19
- * returned. External `href` values are classified as full-document
20
- * navigations when the router resolves the redirect.
21
- *
22
- * @param opts Options for the redirect. Common fields:
23
- * - `href`: absolute URL for external redirects.
24
- * - `statusCode`: HTTP status code to use (defaults to 307).
25
- * - `headers`: additional headers to include on the Response.
26
- * - Standard navigation options like `to`, `params`, `search`, `replace`,
27
- * and `reloadDocument` for internal redirects.
28
- * @returns A Response augmented with router navigation options.
29
- * @link https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction
30
- */
31
- function redirect(opts) {
32
- opts.statusCode = opts.statusCode || opts.code || 307;
33
- const headers = new Headers(opts.headers);
34
- if (opts.href && headers.get("Location") === null) headers.set("Location", opts.href);
35
- const response = new Response(null, {
36
- status: opts.statusCode,
37
- headers
38
- });
39
- response.options = opts;
40
- if (opts.throw) throw response;
41
- return response;
42
- }
43
- /** Check whether a value is a TanStack Router redirect Response. */
44
- function isRedirect(obj) {
45
- return obj instanceof Response && !!obj.options;
46
- }
47
- //#endregion
48
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/utils.js
49
- /**
50
- * Return the last element of an array.
51
- * Intended for non-empty arrays used within router internals.
52
- */
53
- function last(arr) {
54
- return arr[arr.length - 1];
55
- }
56
- /**
57
- * Apply a value-or-updater to a previous value.
58
- * Accepts either a literal value or a function of the previous value.
59
- */
60
- function functionalUpdate(updater, previous) {
61
- if (typeof updater === "function") return updater(previous);
62
- return updater;
63
- }
64
- var hasOwn = Object.prototype.hasOwnProperty;
65
- function hasKeys(obj) {
66
- for (const key in obj) if (hasOwn.call(obj, key)) return true;
67
- return false;
68
- }
69
- var createNull = () => Object.create(null);
70
- var nullReplaceEqualDeep = (prev, next) => replaceEqualDeep(prev, next, true);
71
- function replaceEqualDeep(prev, next, _nullProto, _depth = 0) {
72
- if (isServer) return next;
73
- if (prev === next) return prev;
74
- if (_depth++ > 500) return next;
75
- const array = Array.isArray(prev) && Array.isArray(next);
76
- if (!array && !(isPlainObject(prev) && isPlainObject(next))) return next;
77
- const prevKeys = Object.keys(prev);
78
- const previousCount = prevKeys.length;
79
- const nextKeys = Object.keys(next);
80
- const length = nextKeys.length;
81
- if (array ? previousCount !== prev.length || length !== next.length || previousCount && last(prevKeys) !== `${previousCount - 1}` || length && last(nextKeys) !== `${length - 1}` : previousCount !== Object.getOwnPropertyNames(prev).length || length !== Object.getOwnPropertyNames(next).length || Object.getOwnPropertySymbols(next).length) return next;
82
- let i = 0;
83
- let child;
84
- let previous;
85
- let key;
86
- if (array) {
87
- for (; i < length; i++) {
88
- key = i;
89
- previous = prev[key];
90
- child = next[key];
91
- child = previous === child ? previous : typeof previous === "object" ? replaceEqualDeep(previous, child, _nullProto, _depth) : child;
92
- if (child !== previous) break;
93
- }
94
- if (i === length && previousCount === length) return prev;
95
- } else {
96
- let equal = previousCount === length;
97
- let unchanged = true;
98
- for (; i < length; i++) {
99
- key = nextKeys[i];
100
- previous = prev[key];
101
- const incoming = next[key];
102
- child = previous === incoming ? previous : typeof previous === "object" ? replaceEqualDeep(previous, incoming, _nullProto, _depth) : incoming;
103
- equal &&= child === previous && (prevKeys[i] === key || hasOwn.call(prev, key));
104
- unchanged &&= Object.is(child, incoming);
105
- prevKeys[i] = child;
106
- }
107
- if (equal) return Object.getOwnPropertySymbols(prev).length ? next : prev;
108
- if (unchanged) return next;
109
- }
110
- const copy = array ? nextKeys.fill(0) : _nullProto ? createNull() : {};
111
- for (let j = 0; j < length; j++) {
112
- key = array ? j : nextKeys[j];
113
- if (array) {
114
- previous = prev[key];
115
- if (j > i) {
116
- child = next[key];
117
- child = previous === child ? previous : typeof previous === "object" ? replaceEqualDeep(previous, child, _nullProto, _depth) : child;
118
- }
119
- copy[key] = j < i ? previous : child;
120
- } else copy[key] = prevKeys[j];
121
- }
122
- return copy;
123
- }
124
- function isPlainObject(o) {
125
- if (!o || typeof o !== "object") return false;
126
- return (Object.getPrototypeOf(o)?.constructor ?? Object) === Object;
127
- }
128
- /**
129
- * Perform a deep equality check optimized for router state comparisons.
130
- *
131
- * - `partial`: `b` may omit keys that `a` has (arrays stay length-exact).
132
- * - `explicitUndefined`: keys holding `undefined` take part in the comparison
133
- * instead of being ignored.
134
- *
135
- * Internal: the flags are positional so hot callers pass no options object.
136
- */
137
- function deepEqual(a, b, partial, explicitUndefined) {
138
- if (a === b) return true;
139
- if (Array.isArray(a) && Array.isArray(b)) {
140
- if (a.length !== b.length) return false;
141
- for (let i = 0, l = a.length; i < l; i++) {
142
- const av = a[i];
143
- const bv = b[i];
144
- if (av !== bv && !deepEqual(av, bv, partial, explicitUndefined)) return false;
145
- }
146
- return true;
147
- }
148
- if (isPlainObject(a) && isPlainObject(b)) {
149
- if (partial) {
150
- for (const k in b) if (explicitUndefined || b[k] !== void 0) {
151
- if (!deepEqual(a[k], b[k], partial, explicitUndefined)) return false;
152
- }
153
- return true;
154
- }
155
- let aCount = 0;
156
- if (explicitUndefined) aCount = Object.keys(a).length;
157
- else for (const k in a) if (a[k] !== void 0) aCount++;
158
- for (const k in b) if (explicitUndefined || b[k] !== void 0) {
159
- if (aCount-- === 0 || !deepEqual(a[k], b[k], partial, explicitUndefined)) return false;
160
- }
161
- return aCount === 0;
162
- }
163
- return false;
164
- }
165
- /**
166
- * Heuristically detect dynamic import "module not found" errors
167
- * across major browsers for lazy route component handling.
168
- */
169
- function isModuleNotFoundError(error) {
170
- if (typeof error?.message !== "string") return false;
171
- return error.message.startsWith("Failed to fetch dynamically imported module") || error.message.startsWith("error loading dynamically imported module") || error.message.startsWith("Importing a module script failed");
172
- }
173
- function findLast(array, predicate) {
174
- for (let i = array.length - 1; i >= 0; i--) {
175
- const item = array[i];
176
- if (predicate(item)) return item;
177
- }
178
- }
179
- /**
180
- * Re-encode characters that are unsafe in URL paths.
181
- * Includes ASCII control characters (0x00-0x1F, 0x7F) and a subset of the
182
- * WHATWG URL "path percent-encode set" (", <, >, `, {, }).
183
- *
184
- * Space (0x20) is intentionally excluded — decodeURI decodes %20 to space
185
- * and the router stores decoded spaces in location.pathname. The existing
186
- * encodePathLikeUrl already handles re-encoding spaces for outgoing URLs.
187
- *
188
- * These characters are decoded by decodeURI but must remain percent-encoded
189
- * in paths to match how upstream layers (CDNs, edge middleware, browsers)
190
- * interpret the URL, preventing infinite redirect loops and path mismatches.
191
- */
192
- var PATH_UNSAFE_RE = /[\x00-\x1f\x7f"<>`{}]/g;
193
- function sanitizePathSegment(segment) {
194
- return segment.replace(PATH_UNSAFE_RE, (ch) => "%" + ch.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0"));
195
- }
196
- function decodeSegment(segment) {
197
- let decoded;
198
- try {
199
- decoded = decodeURI(segment);
200
- } catch {
201
- decoded = segment.replaceAll(/%[0-9A-F]{2}/gi, (match) => {
202
- try {
203
- return decodeURI(match);
204
- } catch {
205
- return match;
206
- }
207
- });
208
- }
209
- return sanitizePathSegment(decoded);
210
- }
211
- /**
212
- * Default list of URL protocols to allow in links, redirects, and navigation.
213
- * Any absolute URL protocol not in this list is treated as dangerous by default.
214
- */
215
- var DEFAULT_PROTOCOL_ALLOWLIST = [
216
- "http:",
217
- "https:",
218
- "mailto:",
219
- "tel:"
220
- ];
221
- /**
222
- * Extract the explicit URL scheme, including its colon, using WHATWG
223
- * normalization rules. This does not validate the rest of the URL.
224
- *
225
- * Returning `undefined` means "no explicit scheme", not "safe URL";
226
- * protocol-relative URLs such as "//evil.example" require a separate check.
227
- */
228
- function getUrlScheme(url) {
229
- if (url[0] === "/") return;
230
- if (!url.includes(":")) return;
231
- return /^[\x00-\x20]*([a-z][a-z\d+.\t\n\r-]*:)/i.exec(url)?.[1]?.replace(/[\t\n\r]/g, "").toLowerCase();
232
- }
233
- var protocolRelativePrefixRegex = /^[\x00-\x20]*[\\/][\t\n\r]*[\\/]/;
234
- /**
235
- * Check if a URL string uses a protocol that is not in the allowlist or is
236
- * protocol-relative (e.g. "//evil.example"), which can navigate to another host.
237
- * Returns true for blocked protocols like javascript:, blob:, and data:, as
238
- * well as slash/backslash variants of protocol-relative URLs.
239
- *
240
- * Scheme parsing normalizes:
241
- * - Mixed case (JavaScript: → javascript:)
242
- * - Whitespace/control characters (java\nscript: → javascript:)
243
- * - Leading whitespace
244
- *
245
- * For relative URLs without a protocol-relative prefix, returns false.
246
- *
247
- * @param url - The URL string to check
248
- * @param allowlist - Set of protocols to allow
249
- * @returns true if the URL uses a protocol that is not allowed or can escape
250
- * the current origin through a protocol-relative URL
251
- */
252
- function isDangerousProtocol(url, allowlist) {
253
- if (!url) return false;
254
- if (protocolRelativePrefixRegex.test(url)) return true;
255
- const scheme = getUrlScheme(url);
256
- return scheme ? !allowlist.has(scheme) : false;
257
- }
258
- var HTML_ESCAPE_LOOKUP = {
259
- "&": "\\u0026",
260
- ">": "\\u003e",
261
- "<": "\\u003c",
262
- "\u2028": "\\u2028",
263
- "\u2029": "\\u2029"
264
- };
265
- var HTML_ESCAPE_REGEX = /[&><\u2028\u2029]/g;
266
- /**
267
- * Escape HTML special characters in a string to prevent XSS attacks
268
- * when embedding strings in script tags during SSR.
269
- *
270
- * This is essential for preventing XSS vulnerabilities when user-controlled
271
- * content is embedded in inline scripts.
272
- */
273
- function escapeHtml(str) {
274
- return str.replace(HTML_ESCAPE_REGEX, (match) => HTML_ESCAPE_LOOKUP[match]);
275
- }
276
- function decodePath(path) {
277
- if (!path) return path;
278
- let result = path;
279
- if (/[%\\\x00-\x1f\x7f]/.test(path)) {
280
- const re = /%25|%5C/gi;
281
- let cursor = 0;
282
- let match;
283
- result = "";
284
- while (null !== (match = re.exec(path))) {
285
- result += decodeSegment(path.slice(cursor, match.index)) + match[0];
286
- cursor = re.lastIndex;
287
- }
288
- result += decodeSegment(cursor ? path.slice(cursor) : path);
289
- }
290
- return result;
291
- }
292
- /**
293
- * Encodes a path the same way `new URL()` would, but without the overhead of full URL parsing.
294
- *
295
- * This function encodes:
296
- * - Whitespace characters (spaces → %20, tabs → %09, etc.)
297
- * - Non-ASCII/Unicode characters (emojis, accented characters, etc.)
298
- *
299
- * It preserves:
300
- * - Already percent-encoded sequences (won't double-encode %2F, %25, etc.)
301
- * - ASCII special characters valid in URL paths (@, $, &, +, etc.)
302
- * - Forward slashes as path separators
303
- *
304
- * Used to generate proper href values for SSR without constructing URL objects.
305
- *
306
- * @example
307
- * encodePathLikeUrl('/path/file name.pdf') // '/path/file%20name.pdf'
308
- * encodePathLikeUrl('/path/日本語') // '/path/%E6%97%A5%E6%9C%AC%E8%AA%9E'
309
- * encodePathLikeUrl('/path/already%20encoded') // '/path/already%20encoded' (preserved)
310
- */
311
- function encodePathLikeUrl(path) {
312
- if (!/[\s\u0080-\uFFFF]/.test(path)) return path;
313
- return path.replace(/\s|[^\u0000-\u007F]/gu, encodeURIComponent);
314
- }
315
- function arraysEqual(a, b) {
316
- if (a === b) return true;
317
- if (a.length !== b.length) return false;
318
- for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
319
- return true;
320
- }
321
- //#endregion
322
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/path.js
323
- /** Remove repeated slashes from a path string. */
324
- function cleanPath(path) {
325
- return path.replace(/\/{2,}/g, "/");
326
- }
327
- /** Trim leading slashes (except preserving root '/'). */
328
- function trimPathLeft(path) {
329
- return path === "/" ? path : path.replace(/^\/+/, "");
330
- }
331
- /** Trim trailing slashes (except preserving root '/'). */
332
- function trimPathRight(path) {
333
- const len = path.length;
334
- return len > 1 && path[len - 1] === "/" ? path.replace(/\/+$/, "") : path;
335
- }
336
- /** Trim both leading and trailing slashes. */
337
- function trimPath(path) {
338
- return trimPathRight(trimPathLeft(path));
339
- }
340
- /** Remove a trailing slash from value when appropriate for comparisons. */
341
- function removeTrailingSlash(value, basepath) {
342
- if (value?.endsWith("/") && value !== "/" && value !== `${basepath}/`) return value.slice(0, -1);
343
- return value;
344
- }
345
- /**
346
- * Resolve a destination path against a base, honoring trailing-slash policy
347
- * and supporting relative segments (`.`/`..`) and absolute `to` values.
348
- *
349
- * Internal: parameters are positional so the router's hot callers pass no
350
- * options object.
351
- */
352
- function resolvePath(base, to, trailingSlash = "never", cache) {
353
- if (to.includes("//")) to = cleanPath(to);
354
- if (to.startsWith("/")) {
355
- if (to.length === 1 || trailingSlash === "preserve") return to;
356
- if (trailingSlash === "always") return to.endsWith("/") ? to : `${to}/`;
357
- return to.endsWith("/") ? to.slice(0, -1) : to;
358
- }
359
- const isBase = to === ".";
360
- let key;
361
- if (cache) {
362
- key = isBase ? base : base + "\0" + to;
363
- const cached = cache.get(key);
364
- if (cached) return cached;
365
- }
366
- let baseSegments;
367
- if (isBase) baseSegments = base.split("/");
368
- else {
369
- if (base.includes("//")) base = cleanPath(base);
370
- baseSegments = base.split("/");
371
- while (baseSegments.length > 1 && last(baseSegments) === "") baseSegments.pop();
372
- const toSegments = to.split("/");
373
- for (let index = 0, length = toSegments.length; index < length; index++) {
374
- const value = toSegments[index];
375
- if (value === "") {
376
- if (!index) baseSegments = [value];
377
- else if (index === length - 1) baseSegments.push(value);
378
- } else if (value === "..") {
379
- if (baseSegments.length > 1) baseSegments.pop();
380
- else baseSegments = [""];
381
- } else if (value === ".") {} else baseSegments.push(value);
382
- }
383
- }
384
- if (baseSegments.length > 1) {
385
- if (last(baseSegments) === "") {
386
- if (trailingSlash === "never") baseSegments.pop();
387
- } else if (trailingSlash === "always") baseSegments.push("");
388
- }
389
- const joined = baseSegments.join("/");
390
- const result = (isBase ? cleanPath(joined) : joined) || "/";
391
- if (key && cache) cache.set(key, result);
392
- return result;
393
- }
394
- /**
395
- * Create a pre-compiled decode config from allowed characters.
396
- * Created once for the router's fixed encoding configuration.
397
- */
398
- function compileDecodeCharMap(pathParamsAllowedCharacters) {
399
- const charMap = new Map(pathParamsAllowedCharacters.map((char) => [encodeURIComponent(char), char]));
400
- const regex = new RegExp([...charMap.keys()].join("|").replace(/[.*()]/g, "\\$&"), "g");
401
- return (encoded) => encoded.replace(regex, (match) => charMap.get(match) ?? match);
402
- }
403
- /** A splat is missing when it has no value; `0` and `false` are stringified like any other param. */
404
- function isMissingSplat(value) {
405
- return value == null || value === "";
406
- }
407
- function encodeParam(key, value, decoder) {
408
- if (typeof value !== "string") return "" + (value ?? void 0);
409
- const splat = key === "_splat";
410
- if (splat && (!value || /^[a-zA-Z0-9\-._~!/]*$/.test(value))) return value;
411
- let encoded = encodeURIComponent(value);
412
- if (splat) encoded = encoded.replaceAll("%2F", "/");
413
- return decoder ? decoder(encoded) : encoded;
414
- }
415
- /** Substitute current values into parsed segments, optionally collecting raw params. */
416
- function interpolatePath(path, segments, params, decoder, usedParams) {
417
- const trailingSlash = path.endsWith("/") ? "/" : "";
418
- let joined = "";
419
- for (const part of segments) {
420
- if (typeof part === "string") {
421
- joined += part;
422
- continue;
423
- }
424
- const [kind, key, prefix, rawSuffix] = part;
425
- const splat = kind === 2;
426
- const suffix = splat && rawSuffix !== void 0 ? rawSuffix + trailingSlash : rawSuffix;
427
- let paramValue = params[key];
428
- if (kind === 3 && paramValue == null) continue;
429
- if (usedParams) {
430
- usedParams[key] = paramValue;
431
- if (splat) usedParams["*"] = paramValue;
432
- }
433
- if (splat && isMissingSplat(paramValue)) {
434
- if (prefix === "/" && !suffix) continue;
435
- paramValue = "";
436
- }
437
- joined += prefix + encodeParam(key, paramValue, decoder) + (suffix || "");
438
- }
439
- return joined + trailingSlash || "/";
440
- }
441
- //#endregion
442
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/sieve-cache.js
443
- /**
444
- * A fixed-capacity cache using the SIEVE eviction algorithm
445
- * (https://cachemon.github.io/SIEVE-website/).
446
- *
447
- * Entries live in the Map's FIFO insertion order; a hit only flips a `visited`
448
- * bit instead of relinking the entry, which makes `get` (by far the hottest
449
- * operation here) one `Map.get` plus a boolean store. Eviction sweeps a `hand`
450
- * from the oldest entry towards the newest, clearing `visited` bits until it
451
- * finds an unvisited entry to drop, so entries touched since the last sweep
452
- * survive one more round. This keeps LRU-like hit ratios while being
453
- * scan-resistant.
454
- */
455
- function createSieveCache(max) {
456
- const cache = /* @__PURE__ */ new Map();
457
- let hand;
458
- let newest;
459
- return {
460
- get(key) {
461
- const entry = cache.get(key);
462
- if (!entry) return;
463
- entry.visited = true;
464
- return entry.value;
465
- },
466
- set(key, value) {
467
- const existing = cache.get(key);
468
- if (existing) {
469
- existing.value = value;
470
- return;
471
- }
472
- if (cache.size >= max) {
473
- let node = hand?.next().value;
474
- while (!node || node.visited) {
475
- if (node) node.visited = false;
476
- else hand = cache.values();
477
- node = hand.next().value;
478
- }
479
- if (node === newest) hand = void 0;
480
- cache.delete(node.key);
481
- }
482
- const entry = {
483
- key,
484
- value,
485
- visited: false
486
- };
487
- newest = entry;
488
- cache.set(key, entry);
489
- },
490
- clear() {
491
- cache.clear();
492
- hand = void 0;
493
- newest = void 0;
494
- }
495
- };
496
- }
497
- //#endregion
498
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/invariant.js
499
- function invariant() {
500
- throw new Error("Invariant failed");
501
- }
502
- //#endregion
503
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/new-process-route-tree.js
504
- var SEGMENT_TYPE_INDEX = 4;
505
- var SEGMENT_TYPE_PATHLESS = 5;
506
- function getParamNames(data) {
507
- const cached = data.names;
508
- if (cached) return cached;
509
- const keys = [];
510
- for (const segment of data) if (typeof segment !== "string") keys.push(segment[1]);
511
- return data.names = keys;
512
- }
513
- /** Parse one segment for matching and retain the same record for interpolation. */
514
- function parseSegment(path, start, end) {
515
- const part = path.slice(start, end);
516
- if (part.charCodeAt(0) === 36) return part.length === 1 ? [
517
- 2,
518
- "_splat",
519
- "",
520
- void 0
521
- ] : [
522
- 1,
523
- part.slice(1),
524
- "",
525
- ""
526
- ];
527
- const open = part.indexOf("{");
528
- if (open >= 0) {
529
- const close = part.indexOf("}", open);
530
- const optional = part.charCodeAt(open + 1) === 45;
531
- const nameStart = open + (optional ? 3 : 2);
532
- if (close >= 0 && part.charCodeAt(nameStart - 1) === 36 && (!optional || nameStart < close)) {
533
- const key = part.slice(nameStart, close);
534
- return [
535
- optional ? 3 : key ? 1 : 2,
536
- key || "_splat",
537
- part.slice(0, open),
538
- path.slice(start + close + 1, key ? end : path.length)
539
- ];
540
- }
541
- }
542
- return part;
543
- }
544
- function parseSegments(defaultCaseSensitive, route, start, node, dynamicListsToSort, parentInterpolation) {
545
- let cursor = start;
546
- const path = route.fullPath ?? route.from;
547
- const options = route.options;
548
- const length = path.length;
549
- const literalEnd = path.endsWith("/") ? length - 1 : length;
550
- const caseSensitive = options?.caseSensitive ?? defaultCaseSensitive;
551
- const parseParams = options?.params?.parse ?? options?.parseParams;
552
- let interpolation;
553
- let literalStart = parentInterpolation ? start - 1 : 0;
554
- if (!node || path.includes("$")) {
555
- interpolation = parentInterpolation?.slice() ?? [];
556
- const tail = last(interpolation);
557
- if (tail && typeof tail !== "string" && tail[0] === 2) {
558
- interpolation[interpolation.length - 1] = [
559
- tail[0],
560
- tail[1],
561
- tail[2],
562
- tail[3] === void 0 ? void 0 : tail[3] + path.substring(start - (path[start - 2] === "/" ? 2 : 1), literalEnd)
563
- ];
564
- literalStart = length;
565
- }
566
- }
567
- while (cursor < length) {
568
- const start = cursor;
569
- const next = path.indexOf("/", start);
570
- let end = next === -1 ? length : next;
571
- const segment = parseSegment(path, start, end);
572
- cursor = end + 1;
573
- let nextNode;
574
- if (typeof segment === "string") {
575
- if (!node) continue;
576
- let name = segment;
577
- let staticChildren;
578
- if (caseSensitive) staticChildren = node.static ??= /* @__PURE__ */ new Map();
579
- else {
580
- name = segment.toLowerCase();
581
- staticChildren = node.staticInsensitive ??= /* @__PURE__ */ new Map();
582
- }
583
- const existingNode = staticChildren.get(name);
584
- if (existingNode) nextNode = existingNode;
585
- else {
586
- const next = createSegmentNode(node);
587
- nextNode = next;
588
- staticChildren.set(name, next);
589
- }
590
- } else {
591
- const kind = segment[0];
592
- let prefix = segment[2];
593
- let suffix = segment[3] ?? "";
594
- if (kind === 2) {
595
- end = length;
596
- cursor = end + 1;
597
- }
598
- if (interpolation && literalStart < end) {
599
- if (literalStart < start - 1) interpolation.push(path.slice(literalStart, start - 1));
600
- segment[2] = "/" + prefix;
601
- if (kind === 2 && segment[3] !== void 0 && literalEnd < length) segment[3] = suffix.slice(0, -1);
602
- interpolation.push(segment);
603
- literalStart = end;
604
- }
605
- if (!node) continue;
606
- const actuallyCaseSensitive = caseSensitive && !!(prefix || suffix);
607
- if (!caseSensitive) {
608
- prefix = prefix.toLowerCase();
609
- suffix = suffix.toLowerCase();
610
- }
611
- const siblings = kind === 1 ? node.dynamic ??= [] : kind === 3 ? node.optional ??= [] : node.wildcard ??= [];
612
- const existingNode = kind !== 2 && !parseParams && siblings.find((s) => !s.parse && s.caseSensitive === actuallyCaseSensitive && s.prefix === prefix && s.suffix === suffix);
613
- if (existingNode) nextNode = existingNode;
614
- else {
615
- const next = createSegmentNode(node, kind, actuallyCaseSensitive, prefix, suffix);
616
- nextNode = next;
617
- siblings.push(next);
618
- if (siblings.length === 2) dynamicListsToSort?.push(siblings);
619
- }
620
- }
621
- node = nextNode;
622
- }
623
- if (interpolation && literalStart < literalEnd) interpolation.push(path.slice(literalStart, literalEnd));
624
- const segmentData = interpolation?.slice();
625
- if (!node) return segmentData;
626
- if (parseParams && route.children && !route.isRoot && route.id && route.id.charCodeAt(route.id.lastIndexOf("/") + 1) === 95) {
627
- const pathlessNode = createSegmentNode(node, SEGMENT_TYPE_PATHLESS);
628
- (node.pathless ??= []).push(pathlessNode);
629
- node = pathlessNode;
630
- }
631
- const isLeaf = (route.path || !route.children) && !route.isRoot;
632
- if (isLeaf && literalEnd < length) {
633
- const indexNode = createSegmentNode(node, SEGMENT_TYPE_INDEX);
634
- node.index = indexNode;
635
- node = indexNode;
636
- }
637
- node.parse = parseParams ?? null;
638
- node.priority = options?.params?.priority ?? 0;
639
- if (!node.route) {
640
- node.data = segmentData;
641
- if (isLeaf) node.route = route;
642
- }
643
- return [
644
- node,
645
- cursor,
646
- segmentData
647
- ];
648
- }
649
- function sortDynamic(a, b) {
650
- if (a.parse && !b.parse) return -1;
651
- if (!a.parse && b.parse) return 1;
652
- if (a.parse && b.parse && (a.priority || b.priority)) return b.priority - a.priority;
653
- if (a.prefix && b.prefix && a.prefix !== b.prefix) {
654
- if (a.prefix.startsWith(b.prefix)) return -1;
655
- if (b.prefix.startsWith(a.prefix)) return 1;
656
- }
657
- if (a.suffix && b.suffix && a.suffix !== b.suffix) {
658
- if (a.suffix.endsWith(b.suffix)) return -1;
659
- if (b.suffix.endsWith(a.suffix)) return 1;
660
- }
661
- if (a.prefix && !b.prefix) return -1;
662
- if (!a.prefix && b.prefix) return 1;
663
- if (a.suffix && !b.suffix) return -1;
664
- if (!a.suffix && b.suffix) return 1;
665
- if (a.caseSensitive && !b.caseSensitive) return -1;
666
- if (!a.caseSensitive && b.caseSensitive) return 1;
667
- return 0;
668
- }
669
- function createSegmentNode(parent, kind = 0, caseSensitive, prefix, suffix) {
670
- return {
671
- kind,
672
- depth: parent ? parent.depth + 1 : 0,
673
- pathless: null,
674
- index: null,
675
- static: null,
676
- staticInsensitive: null,
677
- dynamic: null,
678
- optional: null,
679
- wildcard: null,
680
- route: null,
681
- data: void 0,
682
- parent,
683
- parse: null,
684
- priority: 0,
685
- caseSensitive,
686
- prefix,
687
- suffix
688
- };
689
- }
690
- function processRouteMasks(routeList, processedTree) {
691
- const segmentTree = createSegmentNode();
692
- const dynamicListsToSort = [];
693
- function visit(route, start, parentNode, parentInterpolation) {
694
- const [node, cursor, segments] = parseSegments(false, route, start, parentNode, dynamicListsToSort, parentInterpolation);
695
- if (route.children) for (const child of route.children) visit(child, cursor, node, segments);
696
- }
697
- for (const route of routeList) visit(route, 1, segmentTree);
698
- for (const nodes of dynamicListsToSort) nodes.sort(sortDynamic);
699
- processedTree.masksTree = segmentTree;
700
- processedTree.flatCache = createSieveCache(1e3);
701
- }
702
- /**
703
- * Take an arbitrary list of routes, create a tree from them (if it hasn't been created already), and match a path against it.
704
- */
705
- function findFlatMatch(path, processedTree) {
706
- path ||= "/";
707
- const cached = processedTree.flatCache.get(path);
708
- if (cached !== void 0) return cached;
709
- const result = findMatch(path, processedTree.masksTree);
710
- processedTree.flatCache.set(path, result);
711
- return result;
712
- }
713
- /**
714
- * @deprecated keep until v2 so that `router.matchRoute` can keep not caring about the actual route tree
715
- */
716
- function findSingleMatch(from, caseSensitive, fuzzy, path, processedTree) {
717
- from ||= "/";
718
- path ||= "/";
719
- const key = caseSensitive ? `case\0${from}` : from;
720
- let tree = processedTree.singleCache.get(key);
721
- if (!tree) {
722
- tree = createSegmentNode();
723
- parseSegments(caseSensitive, { from }, 1, tree);
724
- processedTree.singleCache.set(key, tree);
725
- }
726
- return findMatch(path, tree, fuzzy);
727
- }
728
- function findRouteMatch(path, processedTree, fuzzy = false) {
729
- const key = fuzzy ? path : `nofuzz\0${path}`;
730
- const cached = processedTree.matchCache.get(key);
731
- if (cached !== void 0) return cached;
732
- path ||= "/";
733
- let result;
734
- try {
735
- result = findMatch(path, processedTree.segmentTree, fuzzy);
736
- } catch (err) {
737
- if (err instanceof URIError) result = null;
738
- else throw err;
739
- }
740
- if (result) result.branch = buildRouteBranch(result.route);
741
- processedTree.matchCache.set(key, result);
742
- return result;
743
- }
744
- /**
745
- * Processes a route tree into a segment trie for efficient path matching.
746
- * Also builds lookup maps for routes by ID and by trimmed full path.
747
- */
748
- function processRouteTree(routeTree, caseSensitive = false) {
749
- const segmentTree = createSegmentNode();
750
- const dynamicListsToSort = [];
751
- const routesById = {};
752
- const routesByPath = {};
753
- let index = 0;
754
- function visit(route, start, parentNode, parentInterpolation) {
755
- route.init(index);
756
- if (route.id in routesById) {
757
- if (process.env.NODE_ENV !== "production") throw new Error(`Invariant failed: Duplicate routes found with id: ${String(route.id)}`);
758
- invariant();
759
- }
760
- routesById[route.id] = route;
761
- if (index !== 0 && route.path) {
762
- const trimmedFullPath = trimPathRight(route.fullPath);
763
- if (!routesByPath[trimmedFullPath] || route.fullPath.endsWith("/")) routesByPath[trimmedFullPath] = route;
764
- }
765
- index++;
766
- const [node, cursor, segments] = parseSegments(caseSensitive, route, start, parentNode, dynamicListsToSort, parentInterpolation);
767
- route._interpolation = segments;
768
- if (route.children) for (const child of route.children) visit(child, cursor, node, segments);
769
- }
770
- visit(routeTree, 1, segmentTree);
771
- for (const nodes of dynamicListsToSort) nodes.sort(sortDynamic);
772
- return {
773
- processedTree: {
774
- segmentTree,
775
- singleCache: createSieveCache(1e3),
776
- matchCache: createSieveCache(1e3),
777
- flatCache: null,
778
- masksTree: null
779
- },
780
- routesById,
781
- routesByPath
782
- };
783
- }
784
- function findMatch(path, segmentTree, fuzzy = false) {
785
- const parts = path.split("/");
786
- const leaf = getNodeMatch(path, parts, segmentTree, fuzzy);
787
- if (!leaf) return null;
788
- const [rawParams] = extractParams(path, parts, leaf);
789
- return {
790
- route: leaf.node.route,
791
- rawParams
792
- };
793
- }
794
- /**
795
- * This function is "resumable":
796
- * - the `leaf` input can contain `extract` and `rawParams` properties from a previous `extractParams` call
797
- * - the returned `state` can be passed back as `extract` in a future call to continue extracting params from where we left off
798
- *
799
- * Inputs are *not* mutated.
800
- */
801
- function extractParams(path, parts, leaf) {
802
- const list = buildBranch(leaf.node);
803
- const names = leaf.node.data && getParamNames(leaf.node.data);
804
- const rawParams = Object.create(null);
805
- /** which segment of the path we're currently processing */
806
- let partIndex = leaf.extract?.part ?? 0;
807
- /** which node of the route tree branch we're currently processing */
808
- let nodeIndex = leaf.extract?.node ?? 0;
809
- /** index of the 1st character of the segment we're processing in the path string */
810
- let pathIndex = leaf.extract?.path ?? 0;
811
- /** Next original parameter name, independent of pathless/static nodes. */
812
- let paramIndex = leaf.extract?.param ?? 0;
813
- for (; nodeIndex < list.length; partIndex++, nodeIndex++, pathIndex++) {
814
- const node = list[nodeIndex];
815
- if (node.kind === SEGMENT_TYPE_INDEX) break;
816
- if (node.kind === SEGMENT_TYPE_PATHLESS) {
817
- partIndex--;
818
- pathIndex--;
819
- continue;
820
- }
821
- const part = parts[partIndex];
822
- const currentPathIndex = pathIndex;
823
- if (part) pathIndex += part.length;
824
- if (node.kind === 1 || node.kind === 3) {
825
- const name = names[paramIndex++];
826
- if (node.kind === 3 && leaf.skipped & 1 << nodeIndex) {
827
- partIndex--;
828
- pathIndex = currentPathIndex - 1;
829
- continue;
830
- }
831
- const value = node.suffix || node.prefix ? part.substring(node.prefix.length, part.length - node.suffix.length) : part;
832
- if (value || node.kind === 1) rawParams[name] = decodeURIComponent(value);
833
- } else if (node.kind === 2) {
834
- const n = node;
835
- const value = path.substring(currentPathIndex + n.prefix.length, path.length - n.suffix.length);
836
- const splat = decodeURIComponent(value);
837
- rawParams["*"] = splat;
838
- rawParams._splat = splat;
839
- break;
840
- }
841
- }
842
- if (leaf.rawParams) Object.assign(rawParams, leaf.rawParams);
843
- return [rawParams, {
844
- part: partIndex,
845
- node: nodeIndex,
846
- path: pathIndex,
847
- param: paramIndex
848
- }];
849
- }
850
- function buildRouteBranch(route) {
851
- const list = [route];
852
- while (route.parentRoute) {
853
- route = route.parentRoute;
854
- list.push(route);
855
- }
856
- list.reverse();
857
- return list;
858
- }
859
- function buildBranch(node) {
860
- const list = Array(node.depth + 1);
861
- do {
862
- list[node.depth] = node;
863
- node = node.parent;
864
- } while (node);
865
- return list;
866
- }
867
- function getNodeMatch(path, parts, segmentTree, fuzzy) {
868
- if (path === "/" && segmentTree.index) return {
869
- node: segmentTree.index,
870
- skipped: 0
871
- };
872
- const trailingSlash = !last(parts);
873
- const pathIsIndex = trailingSlash && path !== "/";
874
- const partsLength = parts.length - (trailingSlash ? 1 : 0);
875
- const stack = [{
876
- node: segmentTree,
877
- index: 1,
878
- skipped: 0,
879
- statics: 0,
880
- dynamics: 0,
881
- optionals: 0
882
- }];
883
- let bestFuzzy = null;
884
- let bestMatch = null;
885
- while (stack.length) {
886
- const frame = stack.pop();
887
- const { node, index, skipped, statics, dynamics, optionals } = frame;
888
- let { extract, rawParams } = frame;
889
- if (node.kind === 2 && node.route && !isFrameMoreSpecific(bestMatch, frame)) continue;
890
- if (node.parse) {
891
- if (!validateParseParams(path, parts, frame)) continue;
892
- rawParams = frame.rawParams;
893
- extract = frame.extract;
894
- }
895
- if (fuzzy && node.route && node.kind !== SEGMENT_TYPE_INDEX && isFrameMoreSpecific(bestFuzzy, frame)) bestFuzzy = frame;
896
- const isBeyondPath = index === partsLength;
897
- if (isBeyondPath) {
898
- if (node.route && (!pathIsIndex || node.kind === SEGMENT_TYPE_INDEX || node.kind === 2) && isFrameMoreSpecific(bestMatch, frame)) bestMatch = frame;
899
- if (!node.optional && !node.wildcard && !node.index && !node.pathless) continue;
900
- }
901
- const part = isBeyondPath ? void 0 : parts[index];
902
- let lowerPart;
903
- if (isBeyondPath && node.index) {
904
- const indexFrame = {
905
- node: node.index,
906
- index,
907
- skipped,
908
- statics,
909
- dynamics,
910
- optionals,
911
- extract,
912
- rawParams
913
- };
914
- let indexValid = true;
915
- if (node.index.parse) {
916
- if (!validateParseParams(path, parts, indexFrame)) indexValid = false;
917
- }
918
- if (indexValid) {
919
- if (!dynamics && !optionals && !skipped && isPerfectStaticMatch(statics, partsLength)) return indexFrame;
920
- if (isFrameMoreSpecific(bestMatch, indexFrame)) bestMatch = indexFrame;
921
- }
922
- }
923
- if (node.wildcard) for (let i = node.wildcard.length - 1; i >= 0; i--) {
924
- const segment = node.wildcard[i];
925
- const { prefix, suffix } = segment;
926
- if (prefix) {
927
- if (isBeyondPath) continue;
928
- if (!(segment.caseSensitive ? part : lowerPart ??= part.toLowerCase()).startsWith(prefix)) continue;
929
- }
930
- if (suffix) {
931
- if (isBeyondPath) continue;
932
- const end = parts.slice(index).join("/");
933
- const suffixPart = end.slice(-suffix.length);
934
- if ((segment.caseSensitive ? suffixPart : suffixPart.toLowerCase()) !== suffix || end.length - suffix.length < prefix.length) continue;
935
- }
936
- stack.push({
937
- node: segment,
938
- index: partsLength,
939
- skipped,
940
- statics,
941
- dynamics,
942
- optionals,
943
- extract,
944
- rawParams
945
- });
946
- }
947
- if (node.optional) {
948
- const nextSkipped = skipped | 1 << node.depth + 1;
949
- for (let i = node.optional.length - 1; i >= 0; i--) {
950
- const segment = node.optional[i];
951
- stack.push({
952
- node: segment,
953
- index,
954
- skipped: nextSkipped,
955
- statics,
956
- dynamics,
957
- optionals,
958
- extract,
959
- rawParams
960
- });
961
- }
962
- if (!isBeyondPath) for (let i = node.optional.length - 1; i >= 0; i--) {
963
- const segment = node.optional[i];
964
- const { prefix, suffix } = segment;
965
- if (prefix || suffix) {
966
- const casePart = segment.caseSensitive ? part : lowerPart ??= part.toLowerCase();
967
- if (prefix && !casePart.startsWith(prefix)) continue;
968
- if (suffix && casePart.indexOf(suffix, casePart.length - suffix.length) < prefix.length) continue;
969
- }
970
- stack.push({
971
- node: segment,
972
- index: index + 1,
973
- skipped,
974
- statics,
975
- dynamics,
976
- optionals: optionals + segmentScore(partsLength, index),
977
- extract,
978
- rawParams
979
- });
980
- }
981
- }
982
- if (!isBeyondPath && node.dynamic && part) for (let i = node.dynamic.length - 1; i >= 0; i--) {
983
- const segment = node.dynamic[i];
984
- const { prefix, suffix } = segment;
985
- if (prefix || suffix) {
986
- const casePart = segment.caseSensitive ? part : lowerPart ??= part.toLowerCase();
987
- if (prefix && !casePart.startsWith(prefix)) continue;
988
- if (suffix && casePart.indexOf(suffix, casePart.length - suffix.length) < prefix.length) continue;
989
- }
990
- stack.push({
991
- node: segment,
992
- index: index + 1,
993
- skipped,
994
- statics,
995
- dynamics: dynamics + segmentScore(partsLength, index),
996
- optionals,
997
- extract,
998
- rawParams
999
- });
1000
- }
1001
- if (!isBeyondPath && node.staticInsensitive) {
1002
- const match = node.staticInsensitive.get(lowerPart ??= part.toLowerCase());
1003
- if (match) stack.push({
1004
- node: match,
1005
- index: index + 1,
1006
- skipped,
1007
- statics: statics + segmentScore(partsLength, index),
1008
- dynamics,
1009
- optionals,
1010
- extract,
1011
- rawParams
1012
- });
1013
- }
1014
- if (!isBeyondPath && node.static) {
1015
- const match = node.static.get(part);
1016
- if (match) stack.push({
1017
- node: match,
1018
- index: index + 1,
1019
- skipped,
1020
- statics: statics + segmentScore(partsLength, index),
1021
- dynamics,
1022
- optionals,
1023
- extract,
1024
- rawParams
1025
- });
1026
- }
1027
- if (node.pathless) for (let i = node.pathless.length - 1; i >= 0; i--) {
1028
- const segment = node.pathless[i];
1029
- stack.push({
1030
- node: segment,
1031
- index,
1032
- skipped,
1033
- statics,
1034
- dynamics,
1035
- optionals,
1036
- extract,
1037
- rawParams
1038
- });
1039
- }
1040
- }
1041
- if (bestMatch) return bestMatch;
1042
- if (fuzzy && bestFuzzy) {
1043
- let sliceIndex = bestFuzzy.index;
1044
- for (let i = 0; i < bestFuzzy.index; i++) sliceIndex += parts[i].length;
1045
- const splat = sliceIndex === path.length ? "/" : path.slice(sliceIndex);
1046
- bestFuzzy.rawParams ??= Object.create(null);
1047
- bestFuzzy.rawParams["**"] = decodeURIComponent(splat);
1048
- return bestFuzzy;
1049
- }
1050
- return null;
1051
- }
1052
- function segmentScore(partsLength, index) {
1053
- return 2 ** (partsLength - index - 1);
1054
- }
1055
- function isPerfectStaticMatch(statics, partsLength) {
1056
- return statics === 2 ** (partsLength - 1) - 1;
1057
- }
1058
- function validateParseParams(path, parts, frame) {
1059
- let rawParams;
1060
- let state;
1061
- try {
1062
- [rawParams, state] = extractParams(path, parts, frame);
1063
- } catch {
1064
- return null;
1065
- }
1066
- frame.rawParams = rawParams;
1067
- frame.extract = state;
1068
- if (!frame.node.parse) return true;
1069
- try {
1070
- if (frame.node.parse(rawParams) === false) return null;
1071
- } catch {}
1072
- return true;
1073
- }
1074
- function isFrameMoreSpecific(prev, next) {
1075
- if (!prev) return true;
1076
- return next.statics > prev.statics || next.statics === prev.statics && (next.dynamics > prev.dynamics || next.dynamics === prev.dynamics && (next.optionals > prev.optionals || next.optionals === prev.optionals && ((next.node.kind === SEGMENT_TYPE_INDEX) > (prev.node.kind === SEGMENT_TYPE_INDEX) || next.node.kind === SEGMENT_TYPE_INDEX === (prev.node.kind === SEGMENT_TYPE_INDEX) && next.node.depth > prev.node.depth)));
1077
- }
1078
- //#endregion
1079
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/scroll-restoration.js
1080
- function getSafeSessionStorage() {
1081
- try {
1082
- return sessionStorage;
1083
- } catch {
1084
- return;
1085
- }
1086
- }
1087
- var storageKey = "tsr-scroll-restoration-v1_3";
1088
- var safeSessionStorage = getSafeSessionStorage();
1089
- function createScrollRestorationCache() {
1090
- try {
1091
- return JSON.parse(safeSessionStorage?.getItem("tsr-scroll-restoration-v1_3") || "{}");
1092
- } catch {
1093
- return {};
1094
- }
1095
- }
1096
- var scrollRestorationCache = /* @__PURE__ */ createScrollRestorationCache();
1097
- var scrollRestorationIdAttribute = "data-scroll-restoration-id";
1098
- /**
1099
- * The default `getKey` function for `useScrollRestoration`.
1100
- * It returns the `key` from the location state or the `href` of the location.
1101
- *
1102
- * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.
1103
- */
1104
- var defaultGetScrollRestorationKey = (location) => {
1105
- return location.state.__TSR_key || location.href;
1106
- };
1107
- function getScrollRestorationSelector(element) {
1108
- const attrId = element.getAttribute(scrollRestorationIdAttribute);
1109
- if (attrId) return `[${scrollRestorationIdAttribute}="${attrId}"]`;
1110
- let selector = "";
1111
- let el = element;
1112
- let parent;
1113
- while (parent = el.parentNode) {
1114
- let index = 1;
1115
- let sibling = el;
1116
- while (sibling = sibling.previousElementSibling) index++;
1117
- const part = `${el.localName}:nth-child(${index})`;
1118
- selector = selector ? `${part} > ${selector}` : part;
1119
- el = parent;
1120
- }
1121
- return selector;
1122
- }
1123
- var ignoreScroll = false;
1124
- var windowScrollTarget = "window";
1125
- function getElement(selector) {
1126
- try {
1127
- return typeof selector === "function" ? selector() : document.querySelector(selector);
1128
- } catch {}
1129
- }
1130
- function getScrollToTopElements(scrollToTopSelectors) {
1131
- const elements = /* @__PURE__ */ new Set();
1132
- for (const selector of scrollToTopSelectors) {
1133
- if (selector === windowScrollTarget) continue;
1134
- const element = getElement(selector);
1135
- if (element) elements.add(element);
1136
- }
1137
- return elements;
1138
- }
1139
- function setupScrollRestoration(router, force) {
1140
- const shouldSetupScrollRestoration = force ?? router.options.scrollRestoration;
1141
- const scroll = router._scroll;
1142
- if (shouldSetupScrollRestoration) scroll.e = true;
1143
- if (isServer ?? router.isServer) return;
1144
- const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
1145
- const trackedScrollTargets = /* @__PURE__ */ new Set();
1146
- const snapshotCurrentScrollTargets = (restoreKey) => {
1147
- const keyEntry = scrollRestorationCache[restoreKey] ||= {};
1148
- for (const target of trackedScrollTargets) if (target === document) keyEntry[windowScrollTarget] = {
1149
- scrollX,
1150
- scrollY
1151
- };
1152
- else if (target.isConnected) keyEntry[getScrollRestorationSelector(target)] = {
1153
- scrollX: target.scrollLeft,
1154
- scrollY: target.scrollTop
1155
- };
1156
- };
1157
- if (shouldSetupScrollRestoration && !scroll.s) {
1158
- scroll.s = true;
1159
- ignoreScroll = false;
1160
- history.scrollRestoration = "manual";
1161
- document.addEventListener("scroll", (event) => {
1162
- if (ignoreScroll) return;
1163
- trackedScrollTargets.add(event.target);
1164
- }, true);
1165
- router.subscribe("onBeforeLoad", (event) => {
1166
- if (event.fromLocation) snapshotCurrentScrollTargets(getKey(event.fromLocation));
1167
- trackedScrollTargets.clear();
1168
- });
1169
- addEventListener("pagehide", () => {
1170
- history.scrollRestoration = "auto";
1171
- snapshotCurrentScrollTargets(getKey(router.stores.resolvedLocation.get() ?? router.stores.location.get()));
1172
- try {
1173
- safeSessionStorage?.setItem(storageKey, JSON.stringify(scrollRestorationCache));
1174
- } catch {
1175
- if (process.env.NODE_ENV !== "production") console.warn("[ts-router] Could not persist scroll restoration state to sessionStorage.");
1176
- }
1177
- });
1178
- addEventListener("pageshow", (event) => {
1179
- if (event.persisted) history.scrollRestoration = "manual";
1180
- });
1181
- }
1182
- if (scroll.r) return;
1183
- scroll.r = true;
1184
- router.subscribe("onRendered", (event) => {
1185
- const behavior = router.options.scrollRestorationBehavior;
1186
- const scrollToTopSelectors = router.options.scrollToTopSelectors;
1187
- const shouldResetScroll = scroll.n;
1188
- const hashNavigation = scroll.h;
1189
- let scrollToTopElements;
1190
- trackedScrollTargets.clear();
1191
- scroll.n = true;
1192
- scroll.h = false;
1193
- if (typeof router.options.scrollRestoration === "function" && !router.options.scrollRestoration({ location: router.latestLocation })) return;
1194
- const cacheKey = getKey(event.toLocation);
1195
- const fromCacheKey = event.fromLocation && getKey(event.fromLocation);
1196
- if (scroll.e && fromCacheKey && fromCacheKey !== cacheKey) {
1197
- const fromElementEntries = scrollRestorationCache[fromCacheKey];
1198
- if (fromElementEntries) {
1199
- let toElementEntries = scrollRestorationCache[cacheKey];
1200
- for (const elementSelector in fromElementEntries) {
1201
- if (elementSelector === windowScrollTarget) {
1202
- if (shouldResetScroll) continue;
1203
- } else {
1204
- const element = getElement(elementSelector);
1205
- if (!element) continue;
1206
- if (shouldResetScroll && scrollToTopSelectors) {
1207
- scrollToTopElements ??= getScrollToTopElements(scrollToTopSelectors);
1208
- if (scrollToTopElements.has(element)) continue;
1209
- }
1210
- }
1211
- if (!toElementEntries) toElementEntries = scrollRestorationCache[cacheKey] = {};
1212
- toElementEntries[elementSelector] ??= fromElementEntries[elementSelector];
1213
- }
1214
- }
1215
- }
1216
- ignoreScroll = true;
1217
- try {
1218
- const hash = event.toLocation.hash;
1219
- const hashScrollIntoViewOptions = event.toLocation.state.__hashScrollIntoViewOptions ?? true;
1220
- let windowRestored = false;
1221
- if (shouldResetScroll) {
1222
- if (!hash && scrollToTopSelectors) scrollToTopElements ??= getScrollToTopElements(scrollToTopSelectors);
1223
- const skipWindowRestore = hash && hashScrollIntoViewOptions && hashNavigation;
1224
- const elementEntries = scroll.e ? scrollRestorationCache[cacheKey] : void 0;
1225
- if (elementEntries) for (const elementSelector in elementEntries) {
1226
- const { scrollX, scrollY } = elementEntries[elementSelector];
1227
- if (elementSelector === windowScrollTarget) {
1228
- if (skipWindowRestore) continue;
1229
- scrollTo({
1230
- top: scrollY,
1231
- left: scrollX,
1232
- behavior
1233
- });
1234
- windowRestored = true;
1235
- } else {
1236
- const element = getElement(elementSelector);
1237
- if (element) {
1238
- element.scrollLeft = scrollX;
1239
- element.scrollTop = scrollY;
1240
- scrollToTopElements?.delete(element);
1241
- }
1242
- }
1243
- }
1244
- if (!hash) {
1245
- const scrollOptions = {
1246
- top: 0,
1247
- left: 0,
1248
- behavior
1249
- };
1250
- if (!windowRestored) scrollTo(scrollOptions);
1251
- if (scrollToTopElements) for (const element of scrollToTopElements) element.scrollTo(scrollOptions);
1252
- }
1253
- }
1254
- if (!windowRestored && hash && hashScrollIntoViewOptions) document.getElementById(hash)?.scrollIntoView(hashScrollIntoViewOptions);
1255
- } finally {
1256
- ignoreScroll = false;
1257
- }
1258
- });
1259
- }
1260
- //#endregion
1261
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/qss.js
1262
- /**
1263
- * Program is a reimplementation of the `qss` package:
1264
- * Copyright (c) Luke Edwards luke.edwards05@gmail.com, MIT License
1265
- * https://github.com/lukeed/qss/blob/master/license.md
1266
- *
1267
- * This reimplementation uses modern browser APIs
1268
- * (namely URLSearchParams) and TypeScript while still
1269
- * maintaining the original functionality and interface.
1270
- *
1271
- * Update: this implementation has also been mangled to
1272
- * fit exactly our use-case (single value per key in encoding).
1273
- */
1274
- /**
1275
- * Encodes an object into a query string.
1276
- * @param obj - The object to encode into a query string.
1277
- * @param stringify - An optional custom stringify function.
1278
- * @returns The encoded query string.
1279
- * @example
1280
- * ```
1281
- * // Example input: encode({ token: 'foo', key: 'value' })
1282
- * // Expected output: "token=foo&key=value"
1283
- * ```
1284
- */
1285
- function encode(obj, stringify = String) {
1286
- let result;
1287
- for (const key in obj) {
1288
- const val = obj[key];
1289
- if (val !== void 0) (result ||= new URLSearchParams()).set(key, stringify(val));
1290
- }
1291
- return result ? result.toString() : "";
1292
- }
1293
- /**
1294
- * Converts a string value to its appropriate type (string, number, boolean).
1295
- * @param mix - The string value to convert.
1296
- * @returns The converted value.
1297
- * @example
1298
- * // Example input: toValue("123")
1299
- * // Expected output: 123
1300
- */
1301
- function toValue(str) {
1302
- if (!str) return "";
1303
- if (str === "false") return false;
1304
- if (str === "true") return true;
1305
- return +str * 0 === 0 && +str + "" === str ? +str : str;
1306
- }
1307
- /**
1308
- * Decodes a query string into an object.
1309
- * @param str - The query string to decode.
1310
- * @returns The decoded key-value pairs in an object format.
1311
- * @example
1312
- * // Example input: decode("token=foo&key=value")
1313
- * // Expected output: { "token": "foo", "key": "value" }
1314
- */
1315
- function decode(str) {
1316
- const searchParams = new URLSearchParams(str);
1317
- const result = Object.create(null);
1318
- for (const [key, value] of searchParams.entries()) {
1319
- const previousValue = result[key];
1320
- if (previousValue == null) result[key] = toValue(value);
1321
- else if (Array.isArray(previousValue)) previousValue.push(toValue(value));
1322
- else result[key] = [previousValue, toValue(value)];
1323
- }
1324
- return result;
1325
- }
1326
- //#endregion
1327
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/searchParams.js
1328
- var jsonStart = /^(?:\s|["[{\d-]|fa|nu|tr)/;
1329
- /** Default `parseSearch` that strips leading '?' and JSON-parses values. */
1330
- var defaultParseSearch = parseSearchWith(JSON.parse);
1331
- /** Default `stringifySearch` using JSON.stringify for complex values. */
1332
- var defaultStringifySearch = stringifySearchWith(JSON.stringify, JSON.parse);
1333
- /**
1334
- * Build a `parseSearch` function using a provided JSON-like parser.
1335
- *
1336
- * The returned function strips a leading `?`, decodes values, and attempts to
1337
- * JSON-parse string values using the given `parser`.
1338
- *
1339
- * @param parser Function to parse a string value (e.g. `JSON.parse`).
1340
- * @returns A `parseSearch` function compatible with `Router` options.
1341
- * @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization
1342
- */
1343
- function parseSearchWith(parser) {
1344
- const isJsonParser = parser === JSON.parse;
1345
- return (searchStr) => {
1346
- if (searchStr[0] === "?") searchStr = searchStr.slice(1);
1347
- const query = decode(searchStr);
1348
- for (const key in query) {
1349
- const value = query[key];
1350
- if (typeof value === "string") {
1351
- if (isJsonParser && !jsonStart.test(value)) continue;
1352
- try {
1353
- query[key] = parser(value);
1354
- } catch (_err) {}
1355
- }
1356
- }
1357
- return query;
1358
- };
1359
- }
1360
- /**
1361
- * Build a `stringifySearch` function using a provided serializer.
1362
- *
1363
- * Non-primitive values are serialized with `stringify`. If a `parser` is
1364
- * supplied, string values that are parseable are re-serialized to ensure
1365
- * symmetry with `parseSearch`.
1366
- *
1367
- * @param stringify Function to serialize a value (e.g. `JSON.stringify`).
1368
- * @param parser Optional parser to detect parseable strings.
1369
- * @returns A `stringifySearch` function compatible with `Router` options.
1370
- * @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization
1371
- */
1372
- function stringifySearchWith(stringify, parser) {
1373
- const isJsonParser = parser === JSON.parse;
1374
- function stringifyValue(val) {
1375
- if (val && typeof val === "object") try {
1376
- return stringify(val);
1377
- } catch (_err) {}
1378
- else if (parser && typeof val === "string") {
1379
- if (isJsonParser && !jsonStart.test(val)) return val;
1380
- try {
1381
- parser(val);
1382
- return stringify(val);
1383
- } catch (_err) {}
1384
- }
1385
- return val;
1386
- }
1387
- return (search) => {
1388
- const searchStr = encode(search, stringifyValue);
1389
- return searchStr ? `?${searchStr}` : "";
1390
- };
1391
- }
1392
- //#endregion
1393
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/rewrite.js
1394
- /** Create a rewrite pair that strips/adds a basepath on input/output. */
1395
- function rewriteBasepath(basepath, caseSensitive, rewrite) {
1396
- const trimmedBasepath = trimPath(basepath);
1397
- const normalizedBasepath = `/${trimmedBasepath}`;
1398
- const checkBasepath = caseSensitive ? normalizedBasepath : normalizedBasepath.toLowerCase();
1399
- const checkBasepathWithSlash = `${checkBasepath}/`;
1400
- const basepathRewrite = {
1401
- input: ({ url }) => {
1402
- const pathname = caseSensitive ? url.pathname : url.pathname.toLowerCase();
1403
- if (pathname === checkBasepath) url.pathname = "/";
1404
- else if (pathname.startsWith(checkBasepathWithSlash)) url.pathname = url.pathname.slice(normalizedBasepath.length);
1405
- return url;
1406
- },
1407
- output: ({ url }) => {
1408
- url.pathname = cleanPath(`/${trimmedBasepath}${url.pathname}`);
1409
- return url;
1410
- }
1411
- };
1412
- return rewrite ? {
1413
- input: ({ url }) => executeRewriteInput(rewrite, basepathRewrite.input({ url })),
1414
- output: ({ url }) => basepathRewrite.output({ url: executeRewriteOutput(rewrite, url) })
1415
- } : basepathRewrite;
1416
- }
1417
- /** Execute a location input rewrite if provided. */
1418
- function executeRewriteInput(rewrite, url) {
1419
- const res = rewrite?.input?.({ url });
1420
- if (res) {
1421
- if (typeof res === "string") return new URL(res);
1422
- else if (res instanceof URL) return res;
1423
- }
1424
- return url;
1425
- }
1426
- /** Execute a location output rewrite if provided. */
1427
- function executeRewriteOutput(rewrite, url) {
1428
- const res = rewrite?.output?.({ url });
1429
- if (res) {
1430
- if (typeof res === "string") return new URL(res);
1431
- else if (res instanceof URL) return res;
1432
- }
1433
- return url;
1434
- }
1435
- //#endregion
1436
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/stores.js
1437
- /** SSR non-reactive createMutableStore */
1438
- function createNonReactiveMutableStore(initialValue) {
1439
- let value = initialValue;
1440
- return {
1441
- get() {
1442
- return value;
1443
- },
1444
- set(nextOrUpdater) {
1445
- value = functionalUpdate(nextOrUpdater, value);
1446
- }
1447
- };
1448
- }
1449
- /** SSR non-reactive createReadonlyStore */
1450
- function createNonReactiveReadonlyStore(read) {
1451
- return { get() {
1452
- return read();
1453
- } };
1454
- }
1455
- function createRouterStores(initialLocation, config) {
1456
- const { createMutableStore, createReadonlyStore, batch } = config;
1457
- const byRoute = /* @__PURE__ */ new Map();
1458
- const status = createMutableStore("idle");
1459
- const location = createMutableStore(initialLocation);
1460
- const resolvedLocation = createMutableStore(void 0);
1461
- const ids = createMutableStore([]);
1462
- const matches = createReadonlyStore(() => ids.get().map((id) => byRoute.get(id).get()));
1463
- const __store = createReadonlyStore(() => ({
1464
- status: status.get(),
1465
- isLoading: status.get() === "pending",
1466
- matches: matches.get(),
1467
- location: location.get(),
1468
- resolvedLocation: resolvedLocation.get()
1469
- }));
1470
- function getMatchStore(routeId) {
1471
- let matchStore = byRoute.get(routeId);
1472
- if (!matchStore) {
1473
- matchStore = createMutableStore(void 0);
1474
- byRoute.set(routeId, matchStore);
1475
- }
1476
- return matchStore;
1477
- }
1478
- const store = {
1479
- status,
1480
- location,
1481
- resolvedLocation,
1482
- ids,
1483
- matches,
1484
- byRoute,
1485
- __store,
1486
- getMatchStore,
1487
- setMatches
1488
- };
1489
- function setMatches(nextMatches) {
1490
- const previousIds = ids.get();
1491
- const nextIds = nextMatches.map((match) => match.routeId);
1492
- batch(() => {
1493
- if (!arraysEqual(previousIds, nextIds)) ids.set(nextIds);
1494
- for (const id of previousIds) if (!nextIds.includes(id)) byRoute.get(id).set(() => void 0);
1495
- for (const nextMatch of nextMatches) {
1496
- const matchStore = getMatchStore(nextMatch.routeId);
1497
- if (matchStore.get() !== nextMatch) matchStore.set(nextMatch);
1498
- }
1499
- });
1500
- }
1501
- return store;
1502
- }
1503
- //#endregion
1504
- //#region ../../node_modules/.pnpm/@tanstack+history@1.162.5/node_modules/@tanstack/history/dist/esm/index.js
1505
- var stateIndexKey = "__TSR_index";
1506
- var popStateEvent = "popstate";
1507
- var beforeUnloadEvent = "beforeunload";
1508
- /**
1509
- * Turn protocol-relative inputs such as "//evil.example" into paths
1510
- * such as "/evil.example", keeping navigation on the current origin.
1511
- *
1512
- * For HTTP(S) URLs, WHATWG parsing ignores leading C0 controls and spaces,
1513
- * removes tabs/newlines, and treats backslashes as slashes, so inputs like
1514
- * "/\evil.example" also need normalization. This only allocates when those
1515
- * rules would make the input protocol-relative.
1516
- */
1517
- var protocolRelativePrefix = /^[\x00-\x20]*(?:[\\/][\t\n\r]*){2,}/;
1518
- function normalizeProtocolRelative(url) {
1519
- const match = protocolRelativePrefix.exec(url);
1520
- return match ? "/" + url.slice(match[0].length) : url;
1521
- }
1522
- function normalizeHref(href) {
1523
- if (/[\x00-\x1f\x7f]/.test(href)) href = href.replace(/[\x00-\x1f\x7f]/g, (character) => " \n\r".includes(character) ? "" : encodeURIComponent(character));
1524
- return normalizeProtocolRelative(href);
1525
- }
1526
- function createHistory(opts) {
1527
- let location = opts.getLocation();
1528
- const subscribers = /* @__PURE__ */ new Set();
1529
- const notify = (action) => {
1530
- location = opts.getLocation();
1531
- subscribers.forEach((subscriber) => subscriber({
1532
- location,
1533
- action
1534
- }));
1535
- };
1536
- const handleIndexChange = (action) => {
1537
- if (opts.notifyOnIndexChange ?? true) notify(action);
1538
- else location = opts.getLocation();
1539
- };
1540
- const tryNavigation = async (args) => {
1541
- const blockers = args.navigateOpts?.ignoreBlocker ? void 0 : opts.getBlockers?.();
1542
- if (typeof document !== "undefined" && blockers?.length && (args.type === "PUSH" || args.type === "REPLACE")) for (const blocker of blockers) {
1543
- const nextLocation = parseHref(args.path, args.state);
1544
- if (await blocker.blockerFn({
1545
- currentLocation: location,
1546
- nextLocation,
1547
- action: args.type
1548
- })) {
1549
- opts.onBlocked?.();
1550
- return;
1551
- }
1552
- }
1553
- args.task();
1554
- };
1555
- return {
1556
- get location() {
1557
- return location;
1558
- },
1559
- get length() {
1560
- return opts.getLength();
1561
- },
1562
- subscribers,
1563
- subscribe: (cb) => {
1564
- subscribers.add(cb);
1565
- return () => {
1566
- subscribers.delete(cb);
1567
- };
1568
- },
1569
- push: (path, state, navigateOpts) => {
1570
- const currentIndex = location.state[stateIndexKey];
1571
- state = assignKeyAndIndex(currentIndex + 1, state);
1572
- tryNavigation({
1573
- task: () => {
1574
- opts.pushState(path, state);
1575
- notify({ type: "PUSH" });
1576
- },
1577
- navigateOpts,
1578
- type: "PUSH",
1579
- path,
1580
- state
1581
- });
1582
- },
1583
- replace: (path, state, navigateOpts) => {
1584
- const currentIndex = location.state[stateIndexKey];
1585
- state = assignKeyAndIndex(currentIndex, state);
1586
- tryNavigation({
1587
- task: () => {
1588
- opts.replaceState(path, state);
1589
- notify({ type: "REPLACE" });
1590
- },
1591
- navigateOpts,
1592
- type: "REPLACE",
1593
- path,
1594
- state
1595
- });
1596
- },
1597
- go: (index, navigateOpts) => {
1598
- tryNavigation({
1599
- task: () => {
1600
- opts.go(index, navigateOpts?.ignoreBlocker ?? false);
1601
- handleIndexChange({
1602
- type: "GO",
1603
- index
1604
- });
1605
- },
1606
- navigateOpts,
1607
- type: "GO"
1608
- });
1609
- },
1610
- back: (navigateOpts) => {
1611
- tryNavigation({
1612
- task: () => {
1613
- opts.back(navigateOpts?.ignoreBlocker ?? false);
1614
- handleIndexChange({ type: "BACK" });
1615
- },
1616
- navigateOpts,
1617
- type: "BACK"
1618
- });
1619
- },
1620
- forward: (navigateOpts) => {
1621
- tryNavigation({
1622
- task: () => {
1623
- opts.forward(navigateOpts?.ignoreBlocker ?? false);
1624
- handleIndexChange({ type: "FORWARD" });
1625
- },
1626
- navigateOpts,
1627
- type: "FORWARD"
1628
- });
1629
- },
1630
- canGoBack: () => location.state[stateIndexKey] !== 0,
1631
- createHref: (str) => opts.createHref(str),
1632
- block: (blocker) => {
1633
- if (!opts.setBlockers) return () => {};
1634
- const blockers = opts.getBlockers?.() ?? [];
1635
- opts.setBlockers([...blockers, blocker]);
1636
- return () => {
1637
- const blockers = opts.getBlockers?.() ?? [];
1638
- opts.setBlockers?.(blockers.filter((b) => b !== blocker));
1639
- };
1640
- },
1641
- flush: () => opts.flush?.(),
1642
- destroy: () => opts.destroy?.(),
1643
- notify,
1644
- _getBlockers: () => opts.getBlockers?.() ?? []
1645
- };
1646
- }
1647
- function assignKeyAndIndex(index, state) {
1648
- const key = createRandomKey();
1649
- return {
1650
- ...state,
1651
- key,
1652
- __TSR_key: key,
1653
- [stateIndexKey]: index
1654
- };
1655
- }
1656
- /**
1657
- * Creates a history object that can be used to interact with the browser's
1658
- * navigation. This is a lightweight API wrapping the browser's native methods.
1659
- * It is designed to work with TanStack Router, but could be used as a standalone API as well.
1660
- * IMPORTANT: This API implements history throttling via a microtask to prevent
1661
- * excessive calls to the history API. In some browsers, calling history.pushState or
1662
- * history.replaceState in quick succession can cause the browser to ignore subsequent
1663
- * calls. This API smooths out those differences and ensures that your application
1664
- * state will *eventually* match the browser state. In most cases, this is not a problem,
1665
- * but if you need to ensure that the browser state is up to date, you can use the
1666
- * `history.flush` method to immediately flush all pending state changes to the browser URL.
1667
- * @param opts
1668
- * @param opts.getHref A function that returns the current href (path + search + hash)
1669
- * @param opts.createHref A function that takes a path and returns a href (path + search + hash)
1670
- * @returns A history instance
1671
- */
1672
- function createBrowserHistory(opts) {
1673
- const win = opts?.window ?? (typeof document !== "undefined" ? window : void 0);
1674
- const originalPushState = win.history.pushState;
1675
- const originalReplaceState = win.history.replaceState;
1676
- let blockers = [];
1677
- const _getBlockers = () => blockers;
1678
- const _setBlockers = (newBlockers) => blockers = newBlockers;
1679
- const createHref = (path) => normalizeHref(opts?.createHref ? opts.createHref(path) : path);
1680
- const parseLocation = opts?.parseLocation ?? (() => parseHref(`${win.location.pathname}${win.location.search}${win.location.hash}`, win.history.state));
1681
- if (!win.history.state?.__TSR_key && !win.history.state?.key) {
1682
- const addedKey = createRandomKey();
1683
- win.history.replaceState({
1684
- [stateIndexKey]: 0,
1685
- key: addedKey,
1686
- __TSR_key: addedKey
1687
- }, "");
1688
- }
1689
- let currentLocation = parseLocation();
1690
- let rollbackLocation;
1691
- let nextPopIsGo = false;
1692
- let ignoreNextPop = false;
1693
- let skipBlockerNextPop = false;
1694
- let ignoreNextBeforeUnload = false;
1695
- const getLocation = () => currentLocation;
1696
- let next;
1697
- const flush = () => {
1698
- if (!next) return;
1699
- history._ignoreSubscribers = true;
1700
- (next[2] ? win.history.pushState : win.history.replaceState)(next[1], "", next[0]);
1701
- history._ignoreSubscribers = false;
1702
- next = void 0;
1703
- rollbackLocation = void 0;
1704
- };
1705
- const queueHistoryAction = (isPush, destHref, state) => {
1706
- const href = opts?.createHref ? createHref(destHref) : void 0;
1707
- const hasPendingAction = !!next;
1708
- if (!hasPendingAction) rollbackLocation = currentLocation;
1709
- currentLocation = parseHref(destHref, state);
1710
- next = [
1711
- href ?? currentLocation.href,
1712
- state,
1713
- next?.[2] || isPush
1714
- ];
1715
- if (!hasPendingAction) queueMicrotask(() => flush());
1716
- };
1717
- const onPushPop = (type) => {
1718
- currentLocation = parseLocation();
1719
- history.notify({ type });
1720
- };
1721
- const onPushPopEvent = async () => {
1722
- ignoreNextBeforeUnload = false;
1723
- if (ignoreNextPop) {
1724
- ignoreNextPop = false;
1725
- return;
1726
- }
1727
- const nextLocation = parseLocation();
1728
- const delta = nextLocation.state[stateIndexKey] - currentLocation.state[stateIndexKey];
1729
- const isForward = delta === 1;
1730
- const isBack = delta === -1;
1731
- const isGo = !isForward && !isBack || nextPopIsGo;
1732
- nextPopIsGo = false;
1733
- const action = isGo ? "GO" : isBack ? "BACK" : "FORWARD";
1734
- const notify = isGo ? {
1735
- type: "GO",
1736
- index: delta
1737
- } : { type: isBack ? "BACK" : "FORWARD" };
1738
- if (skipBlockerNextPop) skipBlockerNextPop = false;
1739
- else {
1740
- const blockers = _getBlockers();
1741
- if (typeof document !== "undefined" && blockers.length) {
1742
- for (const blocker of blockers) if (await blocker.blockerFn({
1743
- currentLocation,
1744
- nextLocation,
1745
- action
1746
- })) {
1747
- ignoreNextPop = true;
1748
- win.history.go(-delta);
1749
- history.notify(notify);
1750
- return;
1751
- }
1752
- }
1753
- }
1754
- currentLocation = parseLocation();
1755
- history.notify(notify);
1756
- };
1757
- const onBeforeUnload = (e) => {
1758
- if (ignoreNextBeforeUnload) {
1759
- ignoreNextBeforeUnload = false;
1760
- return;
1761
- }
1762
- let shouldBlock = false;
1763
- const blockers = _getBlockers();
1764
- if (typeof document !== "undefined" && blockers.length) for (const blocker of blockers) {
1765
- const shouldHaveBeforeUnload = blocker.enableBeforeUnload ?? true;
1766
- if (shouldHaveBeforeUnload === true) {
1767
- shouldBlock = true;
1768
- break;
1769
- }
1770
- if (typeof shouldHaveBeforeUnload === "function" && shouldHaveBeforeUnload() === true) {
1771
- shouldBlock = true;
1772
- break;
1773
- }
1774
- }
1775
- if (shouldBlock) {
1776
- e.preventDefault();
1777
- return e.returnValue = "";
1778
- }
1779
- };
1780
- const history = createHistory({
1781
- getLocation,
1782
- getLength: () => win.history.length,
1783
- pushState: (href, state) => queueHistoryAction(true, href, state),
1784
- replaceState: (href, state) => queueHistoryAction(false, href, state),
1785
- back: (ignoreBlocker) => {
1786
- if (ignoreBlocker) {
1787
- skipBlockerNextPop = true;
1788
- ignoreNextBeforeUnload = true;
1789
- }
1790
- return win.history.back();
1791
- },
1792
- forward: (ignoreBlocker) => {
1793
- if (ignoreBlocker) {
1794
- skipBlockerNextPop = true;
1795
- ignoreNextBeforeUnload = true;
1796
- }
1797
- win.history.forward();
1798
- },
1799
- go: (n, ignoreBlocker) => {
1800
- nextPopIsGo = true;
1801
- if (ignoreBlocker) {
1802
- skipBlockerNextPop = true;
1803
- ignoreNextBeforeUnload = true;
1804
- }
1805
- win.history.go(n);
1806
- },
1807
- createHref,
1808
- flush,
1809
- destroy: () => {
1810
- win.history.pushState = originalPushState;
1811
- win.history.replaceState = originalReplaceState;
1812
- win.removeEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true });
1813
- win.removeEventListener(popStateEvent, onPushPopEvent);
1814
- },
1815
- onBlocked: () => {
1816
- if (rollbackLocation && currentLocation !== rollbackLocation) currentLocation = rollbackLocation;
1817
- },
1818
- getBlockers: _getBlockers,
1819
- setBlockers: _setBlockers,
1820
- notifyOnIndexChange: false
1821
- });
1822
- history._ignoreNextBeforeUnload = (href) => {
1823
- ignoreNextBeforeUnload = false;
1824
- try {
1825
- href = new URL(href, win.document.baseURI).href;
1826
- ignoreNextBeforeUnload = /^https?:/.test(href) && (!href.includes("#") || href.split("#")[0] !== win.location.href.split("#")[0]);
1827
- } catch {}
1828
- };
1829
- win.addEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true });
1830
- win.addEventListener(popStateEvent, onPushPopEvent);
1831
- win.history.pushState = function(...args) {
1832
- const res = originalPushState.apply(win.history, args);
1833
- if (!history._ignoreSubscribers) onPushPop("PUSH");
1834
- return res;
1835
- };
1836
- win.history.replaceState = function(...args) {
1837
- const res = originalReplaceState.apply(win.history, args);
1838
- if (!history._ignoreSubscribers) onPushPop("REPLACE");
1839
- return res;
1840
- };
1841
- return history;
1842
- }
1843
- /**
1844
- * Create an in-memory history implementation.
1845
- * Ideal for server rendering, tests, and non-DOM environments.
1846
- * @link https://tanstack.com/router/latest/docs/framework/react/guide/history-types
1847
- */
1848
- function createMemoryHistory(opts = { initialEntries: ["/"] }) {
1849
- const entries = opts.initialEntries;
1850
- let index = opts.initialIndex ? Math.min(Math.max(opts.initialIndex, 0), entries.length - 1) : entries.length - 1;
1851
- const states = entries.map((_entry, index) => assignKeyAndIndex(index, void 0));
1852
- const getLocation = () => parseHref(entries[index], states[index]);
1853
- let blockers = [];
1854
- const _getBlockers = () => blockers;
1855
- const _setBlockers = (newBlockers) => blockers = newBlockers;
1856
- return createHistory({
1857
- getLocation,
1858
- getLength: () => entries.length,
1859
- pushState: (path, state) => {
1860
- index = index < entries.length - 1 ? index + 1 : entries.length;
1861
- states[index] = state;
1862
- entries[index] = path;
1863
- if (index < entries.length - 1) {
1864
- entries.length = index + 1;
1865
- states.length = index + 1;
1866
- }
1867
- },
1868
- replaceState: (path, state) => {
1869
- states[index] = state;
1870
- entries[index] = path;
1871
- },
1872
- back: () => {
1873
- index = Math.max(index - 1, 0);
1874
- },
1875
- forward: () => {
1876
- index = Math.min(index + 1, entries.length - 1);
1877
- },
1878
- go: (n) => {
1879
- index = Math.min(Math.max(index + n, 0), entries.length - 1);
1880
- },
1881
- createHref: normalizeHref,
1882
- getBlockers: _getBlockers,
1883
- setBlockers: _setBlockers
1884
- });
1885
- }
1886
- function parseHref(href, state) {
1887
- const sanitizedHref = normalizeHref(href);
1888
- const hashIndex = sanitizedHref.indexOf("#");
1889
- const searchIndex = sanitizedHref.indexOf("?");
1890
- if (!state) {
1891
- const key = createRandomKey();
1892
- state = {
1893
- [stateIndexKey]: 0,
1894
- key,
1895
- __TSR_key: key
1896
- };
1897
- }
1898
- return {
1899
- href: sanitizedHref,
1900
- pathname: sanitizedHref.slice(0, hashIndex > -1 ? searchIndex > -1 ? Math.min(hashIndex, searchIndex) : hashIndex : searchIndex > -1 ? searchIndex : sanitizedHref.length),
1901
- hash: hashIndex > -1 ? sanitizedHref.slice(hashIndex) : "",
1902
- search: searchIndex > -1 ? sanitizedHref.slice(searchIndex, hashIndex === -1 ? void 0 : hashIndex) : "",
1903
- state
1904
- };
1905
- }
1906
- function createRandomKey() {
1907
- return (Math.random() + 1).toString(36).slice(7);
1908
- }
1909
- //#endregion
1910
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/router.js
1911
- function isExternalUrl(url, origin) {
1912
- return url.protocol !== "http:" && url.protocol !== "https:" || url.origin !== origin || !!url.username || !!url.password;
1913
- }
1914
- function getUrlPath(url) {
1915
- return url.pathname + url.search + url.hash;
1916
- }
1917
- function routeNeedsLoad(route) {
1918
- return route.options.loader || route.options.beforeLoad || route.lazyFn || route.options.component?.preload || route.options.pendingComponent?.preload;
1919
- }
1920
- /**
1921
- * Compute whether path, href or hash changed between previous and current
1922
- * resolved locations.
1923
- */
1924
- function getLocationChangeInfo(location, resolvedLocation) {
1925
- return {
1926
- fromLocation: resolvedLocation,
1927
- toLocation: location,
1928
- pathChanged: resolvedLocation?.pathname !== location.pathname,
1929
- hrefChanged: resolvedLocation?.href !== location.href,
1930
- hashChanged: resolvedLocation?.hash !== location.hash
1931
- };
1932
- }
1933
- /**
1934
- * Return only state owned by the application, excluding volatile history
1935
- * bookkeeping. Mask payloads (`__tempLocation`/`__tempKey`) are kept: they
1936
- * distinguish otherwise-identical locations.
1937
- */
1938
- function _getUserHistoryState({ key: _key, __TSR_key: _tsrKey, __TSR_index: _tsrIndex, __hashScrollIntoViewOptions: _hashScroll, ...state }) {
1939
- return state;
1940
- }
1941
- function lifecycleEnd(matches) {
1942
- return matches.findIndex((match) => match.status === "error" || match.status === "notFound" || match._notFound) + 1;
1943
- }
1944
- /** Run route lifecycle callbacks in leave/enter/stay phases. */
1945
- function runRouteLifecycle(router, previous, matches, previousEnd, nextEnd, owner) {
1946
- if (previousEnd) previous = previous.slice(0, previousEnd);
1947
- if (nextEnd) matches = matches.slice(0, nextEnd);
1948
- for (const match of previous) {
1949
- if (owner && router._tx !== owner) return;
1950
- if (!matches.some((candidate) => candidate.routeId === match.routeId)) router.routesById[match.routeId].options.onLeave?.(match);
1951
- }
1952
- for (const match of matches) {
1953
- if (owner && router._tx !== owner) return;
1954
- router.routesById[match.routeId].options[previous.some((candidate) => candidate.routeId === match.routeId) ? "onStay" : "onEnter"]?.(match);
1955
- }
1956
- }
1957
- /**
1958
- * Core, framework-agnostic router engine that powers TanStack Router.
1959
- *
1960
- * Provides navigation, matching, loading, preloading, caching and event APIs
1961
- * used by framework adapters (React/Solid). Prefer framework helpers like
1962
- * `createRouter` in app code.
1963
- *
1964
- * @link https://tanstack.com/router/latest/docs/framework/react/api/router/RouterType
1965
- */
1966
- var RouterCore = class {
1967
- /**
1968
- * @deprecated Use the `createRouter` function instead
1969
- */
1970
- constructor(options, getStoreConfig) {
1971
- this.tempLocationKey = `${Math.round(Math.random() * 1e7)}`;
1972
- this._scroll = { n: true };
1973
- this.subscribers = /* @__PURE__ */ new Set();
1974
- this._cache = /* @__PURE__ */ new Map();
1975
- this._committed = [];
1976
- this.startTransition = async (fn) => {
1977
- fn();
1978
- return false;
1979
- };
1980
- this.update = (newOptions) => {
1981
- if (process.env.NODE_ENV !== "production") {
1982
- if (newOptions.notFoundRoute) console.warn("The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/framework/react/guide/not-found-errors#migrating-from-notfoundroute for more info.");
1983
- }
1984
- const prevOptions = this.options;
1985
- this.options = {
1986
- ...prevOptions,
1987
- ...newOptions
1988
- };
1989
- this.isServer = this.options.isServer ?? isServer ?? typeof document === "undefined";
1990
- if (!(isServer ?? this.isServer)) this.staticLocations = /* @__PURE__ */ new WeakMap();
1991
- this.protocolAllowlist = new Set(this.options.protocolAllowlist);
1992
- if (!this.history || this.options.history && this.options.history !== this.history) {
1993
- if (!this.options.history) {
1994
- if (!(isServer ?? this.isServer)) this.history = createBrowserHistory();
1995
- } else this.history = this.options.history;
1996
- }
1997
- this.origin = this.options.origin;
1998
- if (!this.origin) {
1999
- if (!(isServer ?? this.isServer) && window?.origin && window.origin !== "null") this.origin = window.origin;
2000
- else this.origin = "http://localhost";
2001
- }
2002
- const nextBasepath = this.options.basepath ?? "/";
2003
- const nextRewriteOption = this.options.rewrite;
2004
- const rewriteChanged = this.basepath !== nextBasepath || prevOptions?.rewrite !== nextRewriteOption || prevOptions?.caseSensitive !== this.options.caseSensitive;
2005
- if (rewriteChanged) {
2006
- this.basepath = nextBasepath;
2007
- this.rewrite = nextBasepath !== "/" && trimPath(nextBasepath) ? rewriteBasepath(nextBasepath, this.options.caseSensitive, nextRewriteOption) : nextRewriteOption;
2008
- }
2009
- if (this.history) this.updateLatestLocation();
2010
- if (this.options.routeTree !== this.routeTree || (isServer ?? this.isServer) && prevOptions?.caseSensitive !== this.options.caseSensitive) {
2011
- this.routeTree = this.options.routeTree;
2012
- let processRouteTreeResult;
2013
- if (process.env.NODE_ENV !== "development" && (isServer ?? this.isServer) && globalThis.__TSR_CACHE__ && globalThis.__TSR_CACHE__.routeTree === this.routeTree && globalThis.__TSR_CACHE__.caseSensitive === this.options.caseSensitive) processRouteTreeResult = globalThis.__TSR_CACHE__.processRouteTreeResult;
2014
- else {
2015
- processRouteTreeResult = this.buildRouteTree();
2016
- if (process.env.NODE_ENV !== "development" && (isServer ?? this.isServer) && globalThis.__TSR_CACHE__ === void 0) globalThis.__TSR_CACHE__ = {
2017
- routeTree: this.routeTree,
2018
- caseSensitive: this.options.caseSensitive,
2019
- processRouteTreeResult
2020
- };
2021
- }
2022
- this.setRoutes(processRouteTreeResult);
2023
- }
2024
- if (!this.stores) {
2025
- if (this.latestLocation) {
2026
- const config = this.getStoreConfig(this);
2027
- this.batch = config.batch;
2028
- this.stores = createRouterStores(this.latestLocation, config);
2029
- if (!(isServer ?? this.isServer)) setupScrollRestoration(this);
2030
- }
2031
- } else if (rewriteChanged) this.stores.location.set(this.latestLocation);
2032
- };
2033
- this.updateLatestLocation = () => {
2034
- this.latestLocation = this.parseLocation(this.history.location, this.latestLocation);
2035
- };
2036
- this.buildRouteTree = () => {
2037
- const result = processRouteTree(this.routeTree, this.options.caseSensitive);
2038
- if (this.options.routeMasks) processRouteMasks(this.options.routeMasks, result.processedTree);
2039
- return {
2040
- ...result,
2041
- resolvePathCache: createSieveCache(1e3)
2042
- };
2043
- };
2044
- this.subscribe = (eventType, fn) => {
2045
- const listener = {
2046
- eventType,
2047
- fn
2048
- };
2049
- this.subscribers.add(listener);
2050
- return () => {
2051
- this.subscribers.delete(listener);
2052
- };
2053
- };
2054
- this.emit = (routerEvent) => {
2055
- for (const listener of this.subscribers) if (listener.eventType === routerEvent.type) try {
2056
- listener.fn(routerEvent);
2057
- } catch (e) {
2058
- console.error(e);
2059
- }
2060
- };
2061
- this.parseLocation = (locationToParse, previousLocation) => {
2062
- const parse = ({ pathname, search, hash, href }, state) => {
2063
- if (!this.rewrite && !/[ \x00-\x1f\x7f\u0080-\uffff]/.test(pathname)) {
2064
- const parsedSearch = this.options.parseSearch(search);
2065
- const searchStr = this.options.stringifySearch(parsedSearch);
2066
- return {
2067
- href: pathname + searchStr + hash,
2068
- publicHref: pathname + searchStr + hash,
2069
- pathname: decodePath(pathname),
2070
- external: false,
2071
- searchStr,
2072
- search: nullReplaceEqualDeep(previousLocation?.search, parsedSearch),
2073
- hash: decodePath(hash.slice(1)),
2074
- state: replaceEqualDeep(previousLocation?.state, state)
2075
- };
2076
- }
2077
- const url = executeRewriteInput(this.rewrite, new URL(href, this.origin));
2078
- const parsedSearch = this.options.parseSearch(url.search);
2079
- const searchStr = this.options.stringifySearch(parsedSearch);
2080
- url.search = searchStr;
2081
- return {
2082
- href: url.href.replace(url.origin, ""),
2083
- publicHref: href,
2084
- pathname: decodePath(normalizeProtocolRelative(url.pathname)),
2085
- external: !!this.rewrite && isExternalUrl(url, this.origin),
2086
- searchStr,
2087
- search: nullReplaceEqualDeep(previousLocation?.search, parsedSearch),
2088
- hash: decodePath(url.hash.slice(1)),
2089
- state: replaceEqualDeep(previousLocation?.state, state)
2090
- };
2091
- };
2092
- const location = parse(locationToParse, locationToParse.state);
2093
- const { __tempLocation, __tempKey } = location.state;
2094
- if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
2095
- const parsedTempLocation = parse(__tempLocation, {
2096
- ...__tempLocation.state,
2097
- __tempLocation: void 0,
2098
- key: location.state.key,
2099
- __TSR_key: location.state.__TSR_key
2100
- });
2101
- parsedTempLocation.maskedLocation = location;
2102
- return parsedTempLocation;
2103
- }
2104
- return location;
2105
- };
2106
- this.matchRoutes = (pathnameOrNext, locationSearchOrOpts, opts) => {
2107
- if (typeof pathnameOrNext === "string") return this.matchRoutesInternal({
2108
- pathname: pathnameOrNext,
2109
- search: locationSearchOrOpts
2110
- }, opts);
2111
- return this.matchRoutesInternal(pathnameOrNext, locationSearchOrOpts);
2112
- };
2113
- this.getMatchedRoutes = (pathname) => {
2114
- const rawParams = Object.create(null);
2115
- const match = findRouteMatch(trimPathRight(pathname), this.processedTree, true);
2116
- if (match) Object.assign(rawParams, match.rawParams);
2117
- return [
2118
- match?.branch || [this.routesById["__root__"]],
2119
- rawParams,
2120
- match?.route
2121
- ];
2122
- };
2123
- this.buildLocation = (opts) => {
2124
- if (!(isServer ?? this.isServer)) {
2125
- const cached = this.staticLocations.get(opts);
2126
- if (cached) return cached;
2127
- }
2128
- let usedCurrent = false;
2129
- const build = (dest = {}) => {
2130
- if (dest.href) {
2131
- const parsed = parseHref(dest.href, {});
2132
- dest = {
2133
- ...dest,
2134
- to: executeRewriteInput(this.rewrite, new URL(parsed.pathname, this.origin)).pathname,
2135
- search: this.options.parseSearch(parsed.search),
2136
- hash: parsed.hash.slice(1)
2137
- };
2138
- }
2139
- const currentLocation = opts._fromLocation || this._pendingLocation || this.latestLocation;
2140
- let lightweight;
2141
- const current = () => {
2142
- usedCurrent = true;
2143
- return currentLocation;
2144
- };
2145
- const currentMatch = () => lightweight ??= this.matchRoutesLightweight(current());
2146
- if (process.env.NODE_ENV !== "production" && dest.from && dest._isNavigate) {
2147
- const [allFromMatches] = this.getMatchedRoutes(dest.from);
2148
- const [matchedRoutes, fullPath] = currentMatch();
2149
- const matchedFrom = findLast(matchedRoutes, (d) => {
2150
- return comparePaths(d.fullPath, dest.from);
2151
- });
2152
- const matchedCurrent = findLast(allFromMatches, (d) => {
2153
- return comparePaths(d.fullPath, fullPath);
2154
- });
2155
- if (!matchedFrom && !matchedCurrent) console.warn(`Could not find match for from: ${dest.from}`);
2156
- }
2157
- const to = dest.to ? `${dest.to}` : ".";
2158
- const nextTo = resolvePath(to[0] === "/" ? "" : dest.unsafeRelative === "path" ? current().pathname : dest.from ?? currentMatch()[1], to, this.options.trailingSlash, this.resolvePathCache);
2159
- const destRoute = this.routesByPath[trimPathRight(nextTo)];
2160
- const isTemplate = nextTo.includes("$");
2161
- let destRoutes;
2162
- if (destRoute) destRoutes = destRoute._branch ??= buildRouteBranch(destRoute);
2163
- else if (isTemplate) destRoutes = [];
2164
- else {
2165
- const [matchedRoutes, rawParams, foundRoute] = this.getMatchedRoutes(nextTo);
2166
- destRoutes = matchedRoutes;
2167
- if (this.options.notFoundRoute && (!foundRoute || foundRoute.path !== "/" && rawParams["**"])) destRoutes = [...destRoutes, this.options.notFoundRoute];
2168
- }
2169
- const interpolation = isTemplate ? destRoute?._interpolation ?? parseSegments(false, { fullPath: nextTo }, 0) : void 0;
2170
- let nextParams;
2171
- for (const route of destRoutes) {
2172
- const fn = route.options.params?.stringify ?? route.options.stringifyParams;
2173
- if (fn) {
2174
- const fromParams = currentMatch()[3];
2175
- nextParams ??= resolveNextParams(dest.params, fromParams);
2176
- if (!hasKeys(nextParams)) break;
2177
- if (nextParams === fromParams) nextParams = Object.assign(createNull(), nextParams);
2178
- try {
2179
- Object.assign(nextParams, fn(nextParams));
2180
- } catch {}
2181
- }
2182
- }
2183
- nextParams ??= resolveNextParams(dest.params, needsInheritedParams(dest.params, interpolation) ? currentMatch()[3] : EMPTY_RECORD);
2184
- const nextPathname = opts.leaveParams ? nextTo : normalizeProtocolRelative(decodePath(interpolation ? interpolatePath(nextTo, interpolation, nextParams, this.pathParamsDecoder) : nextTo));
2185
- if (process.env.NODE_ENV !== "production" && destRoute && !opts.leaveParams) try {
2186
- const foundRoute = this.getMatchedRoutes(nextPathname)[2];
2187
- if (foundRoute?.id !== destRoute.id) console.warn(`Generated path "${nextPathname}" for route "${destRoute.id}" matched route "${foundRoute?.id}" instead. This can happen when multiple route templates resolve to the same URL. Use the route template that matches the intended route, or adjust params.stringify if it changed the target path.`);
2188
- } catch {}
2189
- const middlewares = getSearchMiddlewares(destRoutes, opts._includeValidateSearch);
2190
- const fromSearch = () => {
2191
- let search = currentMatch()[2];
2192
- if (opts._includeValidateSearch && this.options.search?.strict) {
2193
- const validatedSearch = {};
2194
- destRoutes.forEach((route) => {
2195
- if (route.options.validateSearch) try {
2196
- Object.assign(validatedSearch, validateSearch(route.options.validateSearch, {
2197
- ...validatedSearch,
2198
- ...search
2199
- }));
2200
- } catch {}
2201
- });
2202
- search = validatedSearch;
2203
- }
2204
- return search;
2205
- };
2206
- const nextSearch = middlewares.length ? applySearchMiddleware(middlewares, fromSearch(), dest) : dest.search === true ? fromSearch() : typeof dest.search === "function" ? dest.search(fromSearch()) : dest.search || EMPTY_RECORD;
2207
- const searchStr = this.options.stringifySearch(nextSearch);
2208
- const hash = dest.hash === true ? current().hash : typeof dest.hash === "function" ? dest.hash(current().hash) : dest.hash || void 0;
2209
- const hashStr = hash ? `#${hash}` : "";
2210
- const nextState = !dest.state ? EMPTY_RECORD : dest.state === true ? current().state : typeof dest.state === "function" ? dest.state(current().state) : dest.state;
2211
- const fullPath = `${nextPathname}${searchStr}${hashStr}`;
2212
- let href;
2213
- let publicHref;
2214
- let external = false;
2215
- if (this.rewrite) {
2216
- const url = new URL(fullPath, this.origin);
2217
- const origin = url.origin;
2218
- const rewrittenUrl = executeRewriteOutput(this.rewrite, url);
2219
- href = getUrlPath(url);
2220
- if (isExternalUrl(rewrittenUrl, origin)) {
2221
- publicHref = rewrittenUrl.href;
2222
- external = true;
2223
- } else publicHref = normalizeProtocolRelative(getUrlPath(rewrittenUrl));
2224
- } else {
2225
- href = encodePathLikeUrl(fullPath);
2226
- publicHref = href;
2227
- }
2228
- return {
2229
- publicHref,
2230
- href,
2231
- pathname: nextPathname,
2232
- search: nextSearch,
2233
- searchStr,
2234
- state: nextState,
2235
- hash: hash ?? "",
2236
- external,
2237
- unmaskOnReload: dest.unmaskOnReload
2238
- };
2239
- };
2240
- const next = build(opts);
2241
- if (opts.mask) next.maskedLocation = build({
2242
- from: opts.from,
2243
- ...opts.mask
2244
- });
2245
- else if (this.options.routeMasks) {
2246
- const match = findFlatMatch(next.pathname, this.processedTree);
2247
- if (match) {
2248
- const params = Object.assign(createNull(), match.rawParams);
2249
- const { from: _from, params: maskParams, ...maskProps } = match.route;
2250
- const nextParams = resolveNextParams(maskParams, params);
2251
- next.maskedLocation = build({
2252
- from: opts.from,
2253
- ...maskProps,
2254
- params: nextParams
2255
- });
2256
- }
2257
- }
2258
- if (!(isServer ?? this.isServer) && !usedCurrent && opts._fromLocation) this.staticLocations.set(opts, next);
2259
- return next;
2260
- };
2261
- this.commitLocation = async ({ viewTransition, ignoreBlocker, ...next }) => {
2262
- if (isServer ?? this.isServer) return;
2263
- const nextLocation = next.maskedLocation ?? next;
2264
- if (nextLocation.external && !(isServer ?? this.isServer)) return documentNavigation(this, nextLocation.publicHref, {
2265
- replace: next.replace,
2266
- ignoreBlocker
2267
- });
2268
- let historyAction;
2269
- const isSameLocation = trimPathRight(this.latestLocation.href) === trimPathRight(next.href) && deepEqual(_getUserHistoryState(next.state), _getUserHistoryState(this.latestLocation.state));
2270
- const previousCommitPromise = this._commitPromise;
2271
- let resolve;
2272
- const commitPromise = new Promise((done) => {
2273
- resolve = done;
2274
- });
2275
- commitPromise.resolve = () => {
2276
- resolve();
2277
- previousCommitPromise?.resolve();
2278
- };
2279
- this._commitPromise = commitPromise;
2280
- if (isSameLocation) this.load();
2281
- else {
2282
- let { maskedLocation, hashScrollIntoView, ...nextHistory } = next;
2283
- if (maskedLocation) {
2284
- nextHistory = {
2285
- ...maskedLocation,
2286
- state: {
2287
- ...maskedLocation.state,
2288
- __tempKey: void 0,
2289
- __tempLocation: {
2290
- ...nextHistory,
2291
- search: nextHistory.searchStr,
2292
- state: {
2293
- ...nextHistory.state,
2294
- __tempKey: void 0,
2295
- __tempLocation: void 0,
2296
- __TSR_key: void 0,
2297
- key: void 0
2298
- }
2299
- }
2300
- }
2301
- };
2302
- if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload ?? false) nextHistory.state.__tempKey = this.tempLocationKey;
2303
- }
2304
- nextHistory.state = {
2305
- ...nextHistory.state,
2306
- __hashScrollIntoViewOptions: hashScrollIntoView ?? this.options.defaultHashScrollIntoView ?? true
2307
- };
2308
- this.shouldViewTransition = viewTransition;
2309
- historyAction = next.replace ? "REPLACE" : "PUSH";
2310
- this.history[historyAction === "REPLACE" ? "replace" : "push"](nextHistory.publicHref, nextHistory.state, { ignoreBlocker });
2311
- if (!this.history.subscribers.size) this.load({ action: { type: historyAction } });
2312
- }
2313
- this._scroll.n = next.resetScroll ?? true;
2314
- return this._commitPromise;
2315
- };
2316
- this.buildAndCommitLocation = ({ replace, resetScroll, hashScrollIntoView, viewTransition, ignoreBlocker, ...rest } = {}) => {
2317
- if (isServer ?? this.isServer) return Promise.resolve();
2318
- const location = this.buildLocation({
2319
- ...rest,
2320
- _includeValidateSearch: true
2321
- });
2322
- this._pendingLocation = location;
2323
- const commitPromise = this.commitLocation({
2324
- ...location,
2325
- viewTransition,
2326
- replace,
2327
- resetScroll,
2328
- hashScrollIntoView,
2329
- ignoreBlocker
2330
- });
2331
- queueMicrotask(() => {
2332
- if (this._pendingLocation === location) this._pendingLocation = void 0;
2333
- });
2334
- return commitPromise;
2335
- };
2336
- this.navigate = async ({ to, reloadDocument, href, publicHref, ...rest }) => {
2337
- if (isServer ?? this.isServer) return;
2338
- const hrefScheme = href ? getUrlScheme(href) : void 0;
2339
- if (hrefScheme || reloadDocument) {
2340
- if (to !== void 0 || !href) {
2341
- const location = this.buildLocation({
2342
- to,
2343
- ...rest
2344
- });
2345
- const publicLocation = location.maskedLocation ?? location;
2346
- href ??= publicLocation.publicHref;
2347
- publicHref ??= publicLocation.publicHref;
2348
- }
2349
- const reloadHref = !hrefScheme && publicHref ? publicHref : href;
2350
- return documentNavigation(this, reloadHref, rest);
2351
- }
2352
- return this.buildAndCommitLocation({
2353
- ...rest,
2354
- href,
2355
- to,
2356
- _isNavigate: true
2357
- });
2358
- };
2359
- this.load = async (opts) => {
2360
- if (isServer ?? this.isServer) return loadServerRoute(this, opts);
2361
- this.updateLatestLocation();
2362
- if (opts?.action) this._scroll.h = opts.action.type === "PUSH" || opts.action.type === "REPLACE";
2363
- await loadClientRoute(this, opts);
2364
- };
2365
- this.startViewTransition = (fn) => {
2366
- const shouldViewTransition = this.shouldViewTransition ?? this.options.defaultViewTransition;
2367
- this.shouldViewTransition = void 0;
2368
- if (shouldViewTransition && !(isServer ?? typeof document === "undefined") && typeof document.startViewTransition === "function") {
2369
- let startViewTransitionParams;
2370
- if (typeof shouldViewTransition === "object" && window.CSS?.supports?.("selector(:active-view-transition-type(a))")) {
2371
- const next = this.latestLocation;
2372
- const prevLocation = this.stores.resolvedLocation.get();
2373
- const resolvedViewTransitionTypes = typeof shouldViewTransition.types === "function" ? shouldViewTransition.types(getLocationChangeInfo(next, prevLocation)) : shouldViewTransition.types;
2374
- if (resolvedViewTransitionTypes === false) return fn();
2375
- startViewTransitionParams = {
2376
- update: fn,
2377
- types: resolvedViewTransitionTypes
2378
- };
2379
- } else startViewTransitionParams = fn;
2380
- return document.startViewTransition(startViewTransitionParams).updateCallbackDone;
2381
- }
2382
- return fn();
2383
- };
2384
- this.invalidate = (opts) => {
2385
- const committedMatches = this._committed;
2386
- const filter = opts?.filter;
2387
- const preloads = this._preloads;
2388
- const invalidIds = /* @__PURE__ */ new Set();
2389
- const consider = (match) => {
2390
- if (!filter || filter(match)) invalidIds.add(match.id);
2391
- };
2392
- committedMatches.forEach(consider);
2393
- this._cache.forEach(consider);
2394
- preloads?.forEach((matches) => matches.forEach(consider));
2395
- this._tx?.[3].forEach(consider);
2396
- const abort = [];
2397
- for (const [controller, matches] of preloads ?? []) if (matches.some((match) => invalidIds.has(match.id))) {
2398
- preloads.delete(controller);
2399
- abort.push(controller);
2400
- }
2401
- const invalidate = (d) => {
2402
- if (invalidIds.has(d.id)) {
2403
- const route = this.routesById[d.routeId];
2404
- const next = {
2405
- ...d,
2406
- invalid: true,
2407
- ...(opts?.forcePending || d.status === "error" || d.status === "notFound") && routeNeedsLoad(route) ? {
2408
- status: "pending",
2409
- error: void 0
2410
- } : void 0
2411
- };
2412
- d._flight = void 0;
2413
- return next;
2414
- }
2415
- return d;
2416
- };
2417
- this._committed = committedMatches.map(invalidate);
2418
- for (const [id, match] of this._cache) if (invalidIds.has(id)) {
2419
- match.invalid = true;
2420
- if (opts?.forcePending) match.status = "pending";
2421
- }
2422
- for (const id of invalidIds) {
2423
- const flight = this._flights?.get(id);
2424
- this._flights?.delete(id);
2425
- if (flight && !flight[2]) abort.push(flight[1]);
2426
- }
2427
- for (const controller of abort) controller.abort();
2428
- this.shouldViewTransition = false;
2429
- return this.load({ sync: opts?.sync });
2430
- };
2431
- this.resolveRedirect = (redirect) => {
2432
- const options = redirect.options;
2433
- let href = redirect.headers.get("Location") || options.href;
2434
- if (!href) {
2435
- const location = this.buildLocation(options);
2436
- href = (location.maskedLocation ?? location).publicHref || "/";
2437
- }
2438
- let scheme;
2439
- if (protocolRelativePrefixRegex.test(href) || (scheme = getUrlScheme(href)) && !this.protocolAllowlist.has(scheme)) throw new Error(process.env.NODE_ENV !== "production" ? `Redirect blocked: unsafe protocol in href "${href}". Allowed protocols: ${Array.from(this.protocolAllowlist).join(", ")}.` : "Redirect blocked: unsafe protocol");
2440
- if (scheme === "http:" || scheme === "https:") {
2441
- const url = new URL(href);
2442
- if (url.pathname.startsWith("//")) href = url.href;
2443
- else if (!isExternalUrl(url, this.origin)) {
2444
- href = getUrlPath(url);
2445
- scheme = void 0;
2446
- }
2447
- }
2448
- if (scheme) options.reloadDocument = true;
2449
- options.href = href;
2450
- redirect.headers.set("Location", href);
2451
- return redirect;
2452
- };
2453
- this.clearCache = (opts) => {
2454
- const cached = this._cache;
2455
- const preloads = this._preloads;
2456
- const filter = opts?.filter;
2457
- const discarded = [];
2458
- const discardedIds = [];
2459
- for (const [id, match] of cached) if (!filter || filter(match)) {
2460
- discardedIds.push(id);
2461
- discarded.push(match);
2462
- }
2463
- const abort = [];
2464
- for (const [controller, matches] of preloads ?? []) if (!filter || matches.some(filter)) {
2465
- abort.push(controller);
2466
- discarded.push(...matches);
2467
- }
2468
- for (const id of discardedIds) cached.delete(id);
2469
- for (const controller of abort) preloads.delete(controller);
2470
- for (const match of discarded) {
2471
- const flight = match._flight;
2472
- match._flight = void 0;
2473
- if (flight && !--flight[2]) {
2474
- if (this._flights?.get(match.id) === flight) this._flights.delete(match.id);
2475
- abort.push(flight[1]);
2476
- }
2477
- }
2478
- for (const controller of abort) controller.abort();
2479
- };
2480
- this.loadRouteChunk = loadRouteChunk;
2481
- this.preloadRoute = (opts) => preloadClientRoute(this, opts);
2482
- this.matchRoute = (location, opts) => {
2483
- const matchLocation = {
2484
- ...location,
2485
- to: location.to ? resolvePath(location.from || "", location.to, this.options.trailingSlash, this.resolvePathCache) : void 0,
2486
- params: location.params || {},
2487
- leaveParams: true
2488
- };
2489
- const next = this.buildLocation(matchLocation);
2490
- const isPending = this.stores.status.get() === "pending";
2491
- if (opts?.pending && !isPending) return false;
2492
- const baseLocation = opts?.pending ?? !isPending ? this.latestLocation : this.stores.resolvedLocation.get() || this.stores.location.get();
2493
- const match = findSingleMatch(next.pathname, opts?.caseSensitive ?? false, opts?.fuzzy ?? false, baseLocation.pathname, this.processedTree);
2494
- if (!match) return false;
2495
- if (location.params) {
2496
- if (!deepEqual(match.rawParams, location.params, true)) return false;
2497
- }
2498
- if (opts?.includeSearch ?? true) return deepEqual(baseLocation.search, next.search, true) ? match.rawParams : false;
2499
- return match.rawParams;
2500
- };
2501
- this.getStoreConfig = getStoreConfig;
2502
- if (options.pathParamsAllowedCharacters?.length) this.pathParamsDecoder = compileDecodeCharMap(options.pathParamsAllowedCharacters);
2503
- this.update({
2504
- defaultPreloadDelay: 50,
2505
- defaultPendingMs: 1e3,
2506
- defaultPendingMinMs: 500,
2507
- context: void 0,
2508
- ...options,
2509
- caseSensitive: options.caseSensitive ?? false,
2510
- notFoundMode: options.notFoundMode ?? "fuzzy",
2511
- stringifySearch: options.stringifySearch ?? defaultStringifySearch,
2512
- parseSearch: options.parseSearch ?? defaultParseSearch,
2513
- protocolAllowlist: options.protocolAllowlist ?? DEFAULT_PROTOCOL_ALLOWLIST
2514
- });
2515
- if (!(isServer ?? typeof document === "undefined")) self.__TSR_ROUTER__ = this;
2516
- }
2517
- isShell() {
2518
- return !!this.options.isShell;
2519
- }
2520
- get state() {
2521
- return this.stores.__store.get();
2522
- }
2523
- setRoutes(caches) {
2524
- Object.assign(this, caches);
2525
- this.lightweightCache = /* @__PURE__ */ new WeakMap();
2526
- if (!(isServer ?? this.isServer)) this.staticLocations = /* @__PURE__ */ new WeakMap();
2527
- const notFoundRoute = this.options.notFoundRoute;
2528
- if (notFoundRoute) {
2529
- notFoundRoute.init(99999999999);
2530
- if (this.routesById[notFoundRoute.id] !== notFoundRoute) notFoundRoute._interpolation = parseSegments(false, notFoundRoute, 0);
2531
- this.routesById[notFoundRoute.id] = notFoundRoute;
2532
- }
2533
- }
2534
- matchRoutesInternal(next, opts) {
2535
- const [initialMatchedRoutes, rawParams, foundRoute] = this.getMatchedRoutes(next.pathname);
2536
- let matchedRoutes = initialMatchedRoutes;
2537
- let isGlobalNotFound = false;
2538
- if (foundRoute ? foundRoute.path !== "/" && rawParams["**"] : trimPathRight(next.pathname)) {
2539
- if (this.options.notFoundRoute) matchedRoutes = [...matchedRoutes, this.options.notFoundRoute];
2540
- else isGlobalNotFound = true;
2541
- }
2542
- const _notFoundRouteId = isGlobalNotFound ? findGlobalNotFoundRouteId(this.options.notFoundMode, matchedRoutes) : void 0;
2543
- const matches = new Array(matchedRoutes.length);
2544
- const committed = this._committed;
2545
- const previousAt = (route, index) => {
2546
- const match = committed[index];
2547
- return match?.routeId === route.id ? match : route === this.options.notFoundRoute ? committed.find((candidate) => candidate.routeId === route.id) : void 0;
2548
- };
2549
- let strictParams;
2550
- for (let index = 0; index < matchedRoutes.length; index++) {
2551
- const route = matchedRoutes[index];
2552
- const parentMatch = matches[index - 1];
2553
- let preMatchSearch;
2554
- let strictMatchSearch;
2555
- let searchError;
2556
- {
2557
- const parentSearch = parentMatch?.search ?? next.search;
2558
- const parentStrictSearch = parentMatch?._strictSearch ?? void 0;
2559
- try {
2560
- const strictSearch = validateSearch(route.options.validateSearch, { ...parentSearch }) ?? void 0;
2561
- preMatchSearch = {
2562
- ...parentSearch,
2563
- ...strictSearch
2564
- };
2565
- strictMatchSearch = {
2566
- ...parentStrictSearch,
2567
- ...strictSearch
2568
- };
2569
- } catch (err) {
2570
- let searchParamError = err;
2571
- if (!(err instanceof SearchParamError)) searchParamError = new SearchParamError(err.message, { cause: err });
2572
- if (opts?.throwOnError) throw searchParamError;
2573
- preMatchSearch = parentSearch;
2574
- strictMatchSearch = {};
2575
- searchError = searchParamError;
2576
- }
2577
- }
2578
- let loaderDeps = "";
2579
- let loaderDepsHash = "";
2580
- try {
2581
- loaderDeps = route.options.loaderDeps?.({ search: preMatchSearch }) ?? "";
2582
- loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) || "" : "";
2583
- } catch (cause) {
2584
- if (opts?.throwOnError) throw cause;
2585
- searchError ??= cause;
2586
- }
2587
- const usedParams = createNull();
2588
- const interpolatedPath = route._interpolation ? interpolatePath(route.fullPath, route._interpolation, rawParams, this.pathParamsDecoder, usedParams) : route.fullPath;
2589
- const matchId = route.id + interpolatedPath + loaderDepsHash;
2590
- const previousMatch = previousAt(route, index);
2591
- const existingMatch = process.env.NODE_ENV !== "production" && opts?._rematerialize ? void 0 : this._cache.get(matchId) ?? (previousMatch?.id === matchId ? previousMatch : void 0);
2592
- strictParams = existingMatch?._strictParams ?? Object.assign(usedParams, strictParams);
2593
- let paramsError;
2594
- if (!existingMatch) try {
2595
- extractStrictParams(route, strictParams);
2596
- } catch (err) {
2597
- if (isNotFound(err) || isRedirect(err)) paramsError = err;
2598
- else paramsError = new PathParamError(err.message, { cause: err });
2599
- if (opts?.throwOnError) throw paramsError;
2600
- }
2601
- const cause = previousMatch ? "stay" : "enter";
2602
- let match;
2603
- if (existingMatch) match = {
2604
- ...existingMatch,
2605
- cause,
2606
- search: previousMatch ? nullReplaceEqualDeep(previousMatch.search, preMatchSearch) : nullReplaceEqualDeep(existingMatch.search, preMatchSearch),
2607
- _strictSearch: strictMatchSearch,
2608
- searchError
2609
- };
2610
- else {
2611
- const status = routeNeedsLoad(route) ? "pending" : "success";
2612
- match = {
2613
- id: matchId,
2614
- ssr: isServer ?? this.isServer ? void 0 : route.options.ssr,
2615
- index,
2616
- routeId: route.id,
2617
- params: previousMatch?.params ?? strictParams,
2618
- _strictParams: strictParams,
2619
- pathname: interpolatedPath,
2620
- updatedAt: Date.now(),
2621
- search: previousMatch ? nullReplaceEqualDeep(previousMatch.search, preMatchSearch) : preMatchSearch,
2622
- _strictSearch: strictMatchSearch,
2623
- searchError,
2624
- status,
2625
- isFetching: false,
2626
- error: void 0,
2627
- paramsError,
2628
- context: {},
2629
- abortController: opts?._controller ?? new AbortController(),
2630
- cause,
2631
- loaderDeps: previousMatch ? replaceEqualDeep(previousMatch.loaderDeps, loaderDeps) : loaderDeps,
2632
- invalid: false,
2633
- preload: false,
2634
- staticData: route.options.staticData || {},
2635
- fullPath: route.fullPath
2636
- };
2637
- }
2638
- const _notFound = _notFoundRouteId === route.id;
2639
- if (match._notFound && !_notFound) match.error = void 0;
2640
- match._notFound = _notFound;
2641
- matches[index] = match;
2642
- }
2643
- for (let index = 0; index < matches.length; index++) {
2644
- const match = matches[index];
2645
- match.params = match.cause === "stay" ? nullReplaceEqualDeep(match.params, strictParams) : strictParams;
2646
- if (opts?._controller) match.context = {};
2647
- }
2648
- return matches;
2649
- }
2650
- /**
2651
- * Lightweight route matching for buildLocation.
2652
- * Only computes fullPath, accumulated search, and params - skipping expensive
2653
- * operations like AbortController, loaderDeps, and full match objects.
2654
- */
2655
- matchRoutesLightweight(location) {
2656
- const lastRouteId = last(this.stores.ids.get());
2657
- const lastStateMatch = lastRouteId ? this.stores.byRoute.get(lastRouteId).get() : void 0;
2658
- const lastStateMatchId = lastStateMatch?.id;
2659
- const cached = this.lightweightCache.get(location);
2660
- if (cached && cached[0] === lastStateMatchId) return cached[1];
2661
- const [matchedRoutes, rawParams] = this.getMatchedRoutes(location.pathname);
2662
- const lastRoute = last(matchedRoutes);
2663
- const accumulatedSearch = { ...location.search };
2664
- for (const route of matchedRoutes) try {
2665
- Object.assign(accumulatedSearch, validateSearch(route.options.validateSearch, accumulatedSearch));
2666
- } catch {}
2667
- const canReuseParams = lastStateMatch && lastStateMatch.routeId === lastRoute.id && lastStateMatch.pathname === location.pathname;
2668
- let params;
2669
- if (canReuseParams) params = lastStateMatch.params;
2670
- else {
2671
- const strictParams = rawParams;
2672
- for (const route of matchedRoutes) try {
2673
- extractStrictParams(route, strictParams);
2674
- } catch {}
2675
- params = strictParams;
2676
- }
2677
- const result = [
2678
- matchedRoutes,
2679
- lastRoute.fullPath,
2680
- accumulatedSearch,
2681
- params
2682
- ];
2683
- this.lightweightCache.set(location, [lastStateMatchId, result]);
2684
- return result;
2685
- }
2686
- };
2687
- async function documentNavigation(router, href, { replace, ignoreBlocker }) {
2688
- if (isDangerousProtocol(href, router.protocolAllowlist)) {
2689
- if (process.env.NODE_ENV !== "production") console.warn(`Blocked navigation to dangerous protocol: ${href}`);
2690
- return;
2691
- }
2692
- if (!ignoreBlocker) {
2693
- const blockers = router.history._getBlockers();
2694
- for (const blocker of blockers) if (blocker?.blockerFn) {
2695
- if (await blocker.blockerFn({
2696
- currentLocation: router.history.location,
2697
- nextLocation: router.history.location,
2698
- action: replace ? "REPLACE" : "PUSH"
2699
- })) return;
2700
- }
2701
- }
2702
- router.history._ignoreNextBeforeUnload?.(href);
2703
- if (replace) window.location.replace(href);
2704
- else window.location.href = href;
2705
- }
2706
- /**
2707
- * In non-production environments,
2708
- * augment the RouterCore class with a `_refreshRoute` method
2709
- * dedicated to HMR.
2710
- */
2711
- if (process.env.NODE_ENV !== "production") {
2712
- RouterCore.prototype._replaceRouteChunk = replaceRouteChunk;
2713
- RouterCore.prototype._refreshRoute = async function() {
2714
- this._serverResult = void 0;
2715
- this.updateLatestLocation();
2716
- await refreshClientRoute(this);
2717
- };
2718
- }
2719
- /** Error thrown when search parameter validation fails. */
2720
- var SearchParamError = class extends Error {};
2721
- /** Error thrown when path parameter parsing/validation fails. */
2722
- var PathParamError = class extends Error {};
2723
- var normalize$2 = (str) => str.endsWith("/") && str.length > 1 ? str.slice(0, -1) : str;
2724
- function comparePaths(a, b) {
2725
- return normalize$2(a) === normalize$2(b);
2726
- }
2727
- function validateSearch(validateSearch, input) {
2728
- if (validateSearch == null) return {};
2729
- if ("~standard" in validateSearch) {
2730
- const result = validateSearch["~standard"].validate(input);
2731
- if (result instanceof Promise) throw new SearchParamError("Async validation not supported");
2732
- if (result.issues) throw new SearchParamError(JSON.stringify(result.issues, void 0, 2), { cause: result });
2733
- return result.value;
2734
- }
2735
- if ("parse" in validateSearch) return validateSearch.parse(input);
2736
- if (typeof validateSearch === "function") return validateSearch(input);
2737
- return {};
2738
- }
2739
- function resolveNextParams(spec, base) {
2740
- if (spec === void 0 || spec === true) return base;
2741
- const next = Object.create(null);
2742
- if (spec === false || spec === null) return next;
2743
- if (typeof spec === "function") {
2744
- Object.assign(next, base);
2745
- return Object.assign(next, spec(next));
2746
- }
2747
- return Object.assign(next, base, spec);
2748
- }
2749
- function needsInheritedParams(spec, interpolation) {
2750
- if (typeof spec === "function") return true;
2751
- if (!interpolation || spec === false || spec === null) return false;
2752
- return spec === void 0 || spec === true || interpolation.some((part) => typeof part !== "string" && !hasOwn.call(spec, part[1]));
2753
- }
2754
- var EMPTY_RECORD = Object.freeze({});
2755
- function getSearchMiddlewares(destRoutes, includeValidateSearch) {
2756
- const middlewares = [];
2757
- for (let i = 0; i < destRoutes.length; i++) {
2758
- const routeOptions = destRoutes[i].options;
2759
- if ("search" in routeOptions) {
2760
- if (routeOptions.search?.middlewares) middlewares.push(...routeOptions.search.middlewares);
2761
- } else if (routeOptions.preSearchFilters || routeOptions.postSearchFilters) {
2762
- const legacyMiddleware = ({ search, next }) => {
2763
- const result = next(routeOptions.preSearchFilters ? routeOptions.preSearchFilters.reduce((prev, next) => next(prev), search) : search);
2764
- return routeOptions.postSearchFilters ? routeOptions.postSearchFilters.reduce((prev, next) => next(prev), result) : result;
2765
- };
2766
- middlewares.push(legacyMiddleware);
2767
- }
2768
- const routeValidateSearch = routeOptions.validateSearch;
2769
- if (includeValidateSearch && routeValidateSearch) {
2770
- const validate = ({ search, next, meta }) => {
2771
- const result = next(search);
2772
- try {
2773
- const validated = validateSearch(routeValidateSearch, result);
2774
- if (meta && validated) {
2775
- for (const key in validated) if (!(key in result)) (meta.defaulted ||= /* @__PURE__ */ new Map()).set(key, validated[key]);
2776
- }
2777
- return {
2778
- ...result,
2779
- ...validated
2780
- };
2781
- } catch {}
2782
- return result;
2783
- };
2784
- middlewares.push(validate);
2785
- }
2786
- }
2787
- return middlewares;
2788
- }
2789
- function applySearchMiddleware(middlewares, search, dest) {
2790
- const applyNext = (index, currentSearch, meta) => {
2791
- if (index >= middlewares.length) {
2792
- if (!dest.search) return {};
2793
- if (dest.search === true) return currentSearch;
2794
- const result = functionalUpdate(dest.search, currentSearch);
2795
- if (meta) meta.explicit = result;
2796
- return result;
2797
- }
2798
- const next = (newSearch, collectMeta) => {
2799
- if (collectMeta) {
2800
- const nextMeta = meta || {};
2801
- return {
2802
- search: applyNext(index + 1, newSearch, nextMeta),
2803
- meta: nextMeta
2804
- };
2805
- }
2806
- return applyNext(index + 1, newSearch, meta);
2807
- };
2808
- return middlewares[index]({
2809
- search: currentSearch,
2810
- next,
2811
- meta
2812
- });
2813
- };
2814
- return applyNext(0, search);
2815
- }
2816
- function findGlobalNotFoundRouteId(notFoundMode, routes) {
2817
- if (notFoundMode !== "root") {
2818
- let fallback;
2819
- for (let i = routes.length - 1; i >= 0; i--) {
2820
- const route = routes[i];
2821
- if (route.options.notFoundComponent) return route.id;
2822
- fallback ||= route.children && route.id;
2823
- }
2824
- if (fallback) return fallback;
2825
- }
2826
- return rootRouteId;
2827
- }
2828
- function extractStrictParams(route, accumulatedParams) {
2829
- const parseParams = route.options.params?.parse ?? route.options.parseParams;
2830
- if (parseParams) Object.assign(accumulatedParams, parseParams(accumulatedParams));
2831
- }
2832
- //#endregion
2833
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/load-client.js
2834
- function replaceRouteChunk(route, lazyFn) {
2835
- route.lazyFn = lazyFn ?? route.lazyFn;
2836
- route._lazy = void 0;
2837
- }
2838
- function preloadComponent(route, type) {
2839
- return route.options[type]?.preload?.();
2840
- }
2841
- function loadComponents(route, onPendingReady) {
2842
- const component = preloadComponent(route, "component");
2843
- let pending = preloadComponent(route, "pendingComponent");
2844
- if (onPendingReady) {
2845
- if (pending) pending = pending.then(onPendingReady);
2846
- else onPendingReady();
2847
- }
2848
- if (component && pending) return Promise.all([component, pending]).then(() => {});
2849
- return component ?? pending;
2850
- }
2851
- function loadRouteChunk(route, componentType, onPendingReady) {
2852
- const afterLazy = () => componentType === false ? void 0 : componentType ? preloadComponent(route, componentType) : loadComponents(route, onPendingReady);
2853
- const current = route._lazy;
2854
- if (current) return current === true ? afterLazy() : current.then(afterLazy);
2855
- if (!route.lazyFn) return afterLazy();
2856
- const promise = route.lazyFn().then((lazyRoute) => {
2857
- if (process.env.NODE_ENV === "production" || route._lazy === promise) {
2858
- const { id: _id, ...options } = lazyRoute.options;
2859
- Object.assign(route.options, options);
2860
- route._lazy = true;
2861
- }
2862
- }, (error) => {
2863
- if (process.env.NODE_ENV === "production" || route._lazy === promise) route._lazy = void 0;
2864
- throw error;
2865
- });
2866
- route._lazy = promise;
2867
- return promise.then(afterLazy);
2868
- }
2869
- /** Return the structural lane through the first terminal render boundary. */
2870
- function _getRenderedMatches(matches) {
2871
- const end = matches.findIndex((match) => match.status !== "success" || match._notFound) + 1;
2872
- return end && end < matches.length ? matches.slice(0, end) : matches;
2873
- }
2874
- /**
2875
- * Truthy when the transaction publishing `location` leaves `routeId` out of its
2876
- * matches, so subscribers scoped to that route can skip the publication: the
2877
- * route unmounts when the transaction commits, and a transaction that ends
2878
- * otherwise is superseded or redirected by a newer publication. Only valid
2879
- * synchronously inside the publication: the transaction's matches are emptied
2880
- * at commit and before following a redirect. Publications without a matching
2881
- * transaction (hydration) and scopes without a route never depart.
2882
- */
2883
- function _isRouteDeparting(router, routeId, location) {
2884
- const tx = router._tx;
2885
- return routeId && tx?.[2] === location && !tx[3].some((match) => match.routeId === routeId);
2886
- }
2887
- /** Return the lane whose document assets belong to the current presentation. */
2888
- function _getAssetMatches(matches) {
2889
- let end = matches.length;
2890
- for (let index = 0; index < end; index++) {
2891
- const match = matches[index];
2892
- if (match._assetEnd !== void 0) {
2893
- end = Math.min(end, Math.max(index + 1, match._assetEnd));
2894
- continue;
2895
- }
2896
- if (match.status !== "success" || match._notFound) {
2897
- end = index + 1;
2898
- break;
2899
- }
2900
- }
2901
- return end < matches.length ? matches.slice(0, end) : matches;
2902
- }
2903
- var SUCCESS$1 = 0;
2904
- var ERROR$1 = 1;
2905
- var NOT_FOUND$1 = 2;
2906
- var REDIRECTED$1 = 3;
2907
- var CANCELED_OUTCOME = [4];
2908
- function isControl(result) {
2909
- return typeof result[0] === "number";
2910
- }
2911
- function waitFor$1(value, signal) {
2912
- if (signal.aborted) return Promise.race([Promise.reject(signal), value]);
2913
- return new Promise((resolve, reject) => {
2914
- const abort = () => reject(signal);
2915
- signal.addEventListener("abort", abort, { once: true });
2916
- Promise.resolve(value).then(resolve, reject).then(() => signal.removeEventListener("abort", abort));
2917
- });
2918
- }
2919
- function getRoute$1(router, match) {
2920
- return router.routesById[match.routeId];
2921
- }
2922
- function normalize$1(value, rejected, routeId) {
2923
- if (isRedirect(value)) return [REDIRECTED$1, value];
2924
- if (isNotFound(value)) {
2925
- value.routeId ||= routeId;
2926
- return [NOT_FOUND$1, value];
2927
- }
2928
- if (!rejected) return [SUCCESS$1, value];
2929
- if (typeof value?.then === "function") value = new Error("A Promise was thrown", { cause: value });
2930
- return [ERROR$1, value];
2931
- }
2932
- function normalizeError$1(route, cause) {
2933
- let outcome = normalize$1(cause, true, route.id);
2934
- if (outcome[0] !== ERROR$1) return outcome;
2935
- try {
2936
- route.options.onError?.(outcome[1]);
2937
- } catch (onErrorCause) {
2938
- outcome = normalize$1(onErrorCause, true, route.id);
2939
- }
2940
- return outcome;
2941
- }
2942
- function normalizeLaneError(router, lane, route, cause, options) {
2943
- if (options[0].signal.aborted) return CANCELED_OUTCOME;
2944
- return materializeRedirect$1(router, lane, route, normalizeError$1(route, cause), options);
2945
- }
2946
- async function contextualize$1(router, lane, options, end, planSuccessfulLane, retainedEnd) {
2947
- const [location, matches] = lane;
2948
- const signal = options[0].signal;
2949
- const preload = !!options[3];
2950
- for (let index = options[6] ?? 0; index < end; index++) {
2951
- const match = matches[index];
2952
- const route = getRoute$1(router, match);
2953
- match.abortController = options[0];
2954
- const parentContext = matches[index - 1]?.context ?? router.options.context ?? {};
2955
- const common = {
2956
- params: match.params,
2957
- location,
2958
- navigate: (opts) => router.navigate({
2959
- ...opts,
2960
- _fromLocation: location
2961
- }),
2962
- buildLocation: router.buildLocation,
2963
- cause: preload ? "preload" : match.cause,
2964
- abortController: options[0],
2965
- preload,
2966
- matches,
2967
- routeId: route.id
2968
- };
2969
- try {
2970
- const routeContext = match._ctx ||= route.options.context ? route.options.context({
2971
- ...common,
2972
- deps: match.loaderDeps,
2973
- context: parentContext
2974
- }) || {} : void 0;
2975
- match.context = {
2976
- ...parentContext,
2977
- ...routeContext
2978
- };
2979
- } catch (cause) {
2980
- releaseFlight(router, match);
2981
- return [index, normalizeLaneError(router, lane, route, cause, options)];
2982
- }
2983
- if (signal.aborted) return [index, CANCELED_OUTCOME];
2984
- const validationError = match.paramsError ?? match.searchError;
2985
- if (validationError !== void 0) {
2986
- releaseFlight(router, match);
2987
- return [index, normalizeLaneError(router, lane, route, validationError, options)];
2988
- }
2989
- const beforeLoad = route.options.beforeLoad;
2990
- if (!beforeLoad) continue;
2991
- const previousStatus = match.status;
2992
- if (index >= retainedEnd) {
2993
- match.status = "pending";
2994
- options[7]?.();
2995
- }
2996
- try {
2997
- setFetching(router, match, "beforeLoad", options[0]);
2998
- const value = beforeLoad({
2999
- ...common,
3000
- search: match.search,
3001
- context: match.context,
3002
- ...router.options.additionalContext
3003
- });
3004
- const result = await (typeof value?.then === "function" ? waitFor$1(value, signal) : value);
3005
- if (signal.aborted) return [index, CANCELED_OUTCOME];
3006
- const outcome = materializeRedirect$1(router, lane, route, normalize$1(result, false, route.id), options);
3007
- if (outcome[0] !== SUCCESS$1) {
3008
- releaseFlight(router, match);
3009
- return [index, outcome];
3010
- }
3011
- match.context = {
3012
- ...match.context,
3013
- ...result
3014
- };
3015
- } catch (cause) {
3016
- releaseFlight(router, match);
3017
- return [index, normalizeLaneError(router, lane, route, cause, options)];
3018
- } finally {
3019
- match.status = previousStatus;
3020
- setFetching(router, match, false, options[0]);
3021
- }
3022
- }
3023
- planSuccessfulLane();
3024
- }
3025
- function releaseOwnedFlight(router, match, flight) {
3026
- if (!flight || --flight[2]) return;
3027
- if (router._flights?.get(match.id) === flight) {
3028
- const current = router._tx;
3029
- if (current && !current[0].signal.aborted && !current[3].includes(match) && current[3].some((candidate) => candidate.id === match.id) && current[3].some((candidate) => candidate.isFetching === "beforeLoad")) return;
3030
- router._flights.delete(match.id);
3031
- }
3032
- return flight[1];
3033
- }
3034
- function releaseFlight(router, match) {
3035
- const flight = match._flight;
3036
- match._flight = void 0;
3037
- releaseOwnedFlight(router, match, flight)?.abort();
3038
- }
3039
- /**
3040
- * Not passing in a `next` ownership recipient
3041
- * is equivalent to discarding the match resources
3042
- */
3043
- function transferMatchResources(router, previous, next, deferSameIdFlight) {
3044
- const abort = [];
3045
- for (const match of previous) if (!next?.includes(match)) {
3046
- const flight = match._flight;
3047
- match._flight = void 0;
3048
- if (deferSameIdFlight && flight?.[2] === 1 && router._flights?.get(match.id) === flight && next?.some((candidate) => candidate.id === match.id)) flight[2] = 0;
3049
- else {
3050
- const controller = releaseOwnedFlight(router, match, flight);
3051
- if (controller) abort.push(controller);
3052
- }
3053
- }
3054
- for (const controller of abort) controller.abort();
3055
- }
3056
- function acquireMatchResources(matches) {
3057
- for (const match of matches) {
3058
- const flight = match._flight;
3059
- if (flight) flight[2]++;
3060
- }
3061
- }
3062
- function setFetching(router, match, value, owner) {
3063
- match.isFetching = value;
3064
- if (owner && router._tx?.[0] !== owner) return;
3065
- const store = router.stores.byRoute.get(match.routeId);
3066
- const presented = store?.get();
3067
- if (presented?.id === match.id) store.set({
3068
- ...presented,
3069
- isFetching: value
3070
- });
3071
- }
3072
- function getLoaderContext$1(router, lane, match, route, controller, parentMatchPromise, preload) {
3073
- const location = lane[0];
3074
- return {
3075
- params: match.params,
3076
- location,
3077
- navigate: (opts) => router.navigate({
3078
- ...opts,
3079
- _fromLocation: location
3080
- }),
3081
- cause: preload ? "preload" : match.cause,
3082
- abortController: controller,
3083
- preload,
3084
- deps: match.loaderDeps,
3085
- parentMatchPromise,
3086
- context: match.context,
3087
- route,
3088
- ...router.options.additionalContext
3089
- };
3090
- }
3091
- async function loadResource(router, lane, match, route, loader, parentMatchPromise, options) {
3092
- const owner = options[0];
3093
- const signal = owner.signal;
3094
- if (signal.aborted) return CANCELED_OUTCOME;
3095
- if (!loader) return [SUCCESS$1, void 0];
3096
- let flight = match._flight;
3097
- setFetching(router, match, "loader", owner);
3098
- try {
3099
- if (!flight) {
3100
- const controller = new AbortController();
3101
- flight = [
3102
- Promise.resolve().then(() => loader(getLoaderContext$1(router, lane, match, route, controller, parentMatchPromise, !!options[3]))).then((value) => normalize$1(value, false, route.id), (cause) => normalize$1(cause, true, route.id)).then((result) => {
3103
- if (result[0] !== SUCCESS$1 && router._flights?.get(match.id) === flight) {
3104
- router._flights.delete(match.id);
3105
- if (!flight[2]) controller.abort();
3106
- }
3107
- return result[0] === ERROR$1 && flight[2] ? normalizeError$1(route, result[1]) : result;
3108
- }),
3109
- controller,
3110
- 1
3111
- ];
3112
- (router._flights ??= /* @__PURE__ */ new Map()).set(match.id, flight);
3113
- }
3114
- match._flight = flight;
3115
- match.abortController = flight[1];
3116
- return materializeRedirect$1(router, lane, route, await waitFor$1(flight[0], signal), options);
3117
- } catch (cause) {
3118
- if (cause !== signal || !signal.aborted) throw cause;
3119
- releaseFlight(router, match);
3120
- return CANCELED_OUTCOME;
3121
- } finally {
3122
- setFetching(router, match, false, owner);
3123
- }
3124
- }
3125
- function settleInto(match, result, preload) {
3126
- if (result[0] === REDIRECTED$1) return;
3127
- match.status = "success";
3128
- match.error = void 0;
3129
- if (result[0] === SUCCESS$1) {
3130
- match.loaderData = result[1];
3131
- match.invalid = false;
3132
- match.updatedAt = Date.now();
3133
- match.preload = preload;
3134
- } else match.invalid = true;
3135
- }
3136
- function cacheLoaderMatch(router, match, planned) {
3137
- const current = router._cache.get(match.id);
3138
- if (current !== planned || router._committed.some((candidate) => candidate.id === match.id && candidate._flight === match._flight)) return;
3139
- const cached = {
3140
- ...match,
3141
- _notFound: void 0,
3142
- context: {}
3143
- };
3144
- if (cached._flight) cached._flight[2]++;
3145
- router._cache.set(match.id, cached);
3146
- if (current) releaseFlight(router, current);
3147
- }
3148
- function getParentSnapshot(match, outcome) {
3149
- if (outcome[0] === ERROR$1 || outcome[0] === NOT_FOUND$1) return {
3150
- ...match,
3151
- status: outcome[0] === ERROR$1 ? "error" : "notFound",
3152
- error: outcome[1],
3153
- _flight: void 0
3154
- };
3155
- return match;
3156
- }
3157
- function createLoaderTask$1(router, lane, index, tasks, semanticParent, options, retainedEnd) {
3158
- const match = lane[1][index];
3159
- const route = getRoute$1(router, match);
3160
- const preload = !!options[3];
3161
- const plannedCacheMatch = router._cache.get(match.id);
3162
- let configured;
3163
- let reload = false;
3164
- let reloadFailure;
3165
- try {
3166
- if (match.status === "success") {
3167
- configured = route.options.shouldReload;
3168
- if (typeof configured === "function") configured = configured(getLoaderContext$1(router, lane, match, route, options[0], semanticParent, preload));
3169
- if (options[0].signal.aborted) reloadFailure = CANCELED_OUTCOME;
3170
- }
3171
- if (!reloadFailure) {
3172
- if (match.status !== "success") reload = true;
3173
- else {
3174
- const staleAge = preload || match.preload ? route.options.preloadStaleTime ?? router.options.defaultPreloadStaleTime ?? 3e4 : route.options.staleTime ?? router.options.defaultStaleTime ?? 0;
3175
- reload = !!(match.invalid || configured || configured === void 0 && Date.now() - match.updatedAt >= staleAge && (options[5] || match.cause === "enter" || options[2].some((candidate) => candidate.routeId === match.routeId && candidate.id !== match.id)));
3176
- }
3177
- }
3178
- } catch (cause) {
3179
- match.invalid = true;
3180
- releaseFlight(router, match);
3181
- reloadFailure = normalizeLaneError(router, lane, route, cause, options);
3182
- }
3183
- const routeLoader = route.options.loader;
3184
- const isLoaderFn = typeof routeLoader === "function";
3185
- const loader = isLoaderFn ? routeLoader : routeLoader?.handler;
3186
- const preloadable = !preload || route.options.preload !== false;
3187
- let donor = preloadable && routeLoader && !(process.env.NODE_ENV !== "production" && router._tx?.[6]) ? router._flights?.get(match.id) : void 0;
3188
- if (donor === match._flight || reloadFailure) donor = void 0;
3189
- else if (donor && !reload && !preload && configured === void 0) reload = true;
3190
- else if (!reload) donor = void 0;
3191
- const background = !!(routeLoader && reload && match.status === "success" && !preload && !options[4] && ((isLoaderFn ? void 0 : routeLoader.staleReloadMode) ?? router.options.defaultStaleReloadMode) !== "blocking");
3192
- const loaded = reload && preloadable;
3193
- const blocking = loaded && !background && (match.status !== "success" || !!routeLoader);
3194
- const onReady = index >= retainedEnd ? options[7] : void 0;
3195
- const onLazyReady = route.lazyFn && route._lazy !== true ? onReady : void 0;
3196
- if (loaded && !routeLoader) {
3197
- match.invalid = false;
3198
- match.updatedAt = Date.now();
3199
- }
3200
- if (donor) donor[2]++;
3201
- if (blocking) {
3202
- const acceptedFlight = match._flight;
3203
- match._flight = donor;
3204
- releaseOwnedFlight(router, match, acceptedFlight)?.abort();
3205
- if (index >= retainedEnd) match.status = "pending";
3206
- onReady?.();
3207
- }
3208
- if (!loaded) match.isFetching = false;
3209
- const outcome = !reloadFailure && blocking ? loadResource(router, lane, match, route, loader, semanticParent, options).then((result) => {
3210
- settleInto(match, result, preload);
3211
- if (result[0] === SUCCESS$1) {
3212
- if (routeLoader && !options[0].signal.aborted) cacheLoaderMatch(router, match, plannedCacheMatch);
3213
- if (index >= retainedEnd) match.status = "pending";
3214
- }
3215
- return result;
3216
- }) : Promise.resolve(reloadFailure ?? [SUCCESS$1, match.loaderData]);
3217
- const chunkFailure = (async () => {
3218
- try {
3219
- const chunk = loadRouteChunk(route, void 0, onLazyReady);
3220
- if (chunk) await waitFor$1(chunk, options[0].signal);
3221
- } catch (cause) {
3222
- if (!lane[1].some((candidate, candidateIndex) => candidateIndex <= index && (candidate.status === "error" || candidate.status === "notFound" || candidate._notFound))) return [index, normalizeLaneError(router, lane, route, cause, options)];
3223
- }
3224
- const result = await outcome;
3225
- if (blocking && result[0] === SUCCESS$1 && match.status === "pending" && !options[0].signal.aborted) {
3226
- match.status = "success";
3227
- onReady?.();
3228
- }
3229
- })();
3230
- tasks.push([
3231
- index,
3232
- outcome,
3233
- chunkFailure
3234
- ]);
3235
- if (!background) return outcome.then((result) => getParentSnapshot(match, result));
3236
- const candidate = {
3237
- ...match,
3238
- status: "pending",
3239
- preload: false,
3240
- _flight: donor
3241
- };
3242
- match.invalid = false;
3243
- match.isFetching = "loader";
3244
- const backgroundOutcome = loadResource(router, lane, candidate, route, loader, semanticParent, options).then((result) => {
3245
- match.isFetching = false;
3246
- settleInto(candidate, result, false);
3247
- return result;
3248
- });
3249
- (lane[2] ??= []).push([
3250
- index,
3251
- backgroundOutcome,
3252
- chunkFailure,
3253
- candidate
3254
- ]);
3255
- return backgroundOutcome.then((result) => getParentSnapshot(candidate, result));
3256
- }
3257
- async function getNotFoundBoundary$1(router, matches, indexed, signal, fallback = 0) {
3258
- const cause = indexed?.[1][1];
3259
- let index = cause?.routeId ? matches.findIndex((match) => match.routeId === cause.routeId) : indexed?.[0] ?? matches.length - 1;
3260
- if (index < 0) index = 0;
3261
- for (let i = index; i >= 0; i--) {
3262
- const route = getRoute$1(router, matches[i]);
3263
- try {
3264
- const loading = loadRouteChunk(route, false);
3265
- if (loading) await waitFor$1(loading, signal);
3266
- } catch (cause) {
3267
- if (cause === signal && signal.aborted) throw cause;
3268
- }
3269
- if (route.options.notFoundComponent) return i;
3270
- }
3271
- return cause?.routeId ? index : fallback;
3272
- }
3273
- function discardBackground(router, lane) {
3274
- if (lane[2]) {
3275
- transferMatchResources(router, lane[2].map((task) => task[3]));
3276
- lane[2] = void 0;
3277
- }
3278
- }
3279
- async function settleTasks(tasks, serialFailure, redirectTasks, gate) {
3280
- let loaderFailure;
3281
- try {
3282
- await Promise.all(tasks.map((task) => task[1].then(async (outcome) => {
3283
- const taskIndex = task[0];
3284
- if (gate && taskIndex >= await gate) return;
3285
- if (outcome[0] >= REDIRECTED$1) throw [taskIndex, outcome];
3286
- if (!loaderFailure && outcome[0] !== SUCCESS$1) {
3287
- loaderFailure = [taskIndex, outcome];
3288
- await Promise.all((redirectTasks ?? []).map((nextTask) => {
3289
- if (nextTask[0] <= taskIndex) return;
3290
- return nextTask[1].then((nextOutcome) => {
3291
- if (nextOutcome[0] === REDIRECTED$1) throw [nextTask[0], nextOutcome];
3292
- });
3293
- }));
3294
- }
3295
- })));
3296
- } catch (cause) {
3297
- return cause;
3298
- }
3299
- return serialFailure ?? loaderFailure;
3300
- }
3301
- function materializeRedirect$1(router, lane, route, outcome, options, failed) {
3302
- while (outcome[0] === REDIRECTED$1) {
3303
- const redirect = outcome[1];
3304
- const redirectOptions = redirect.options;
3305
- try {
3306
- if (redirectOptions.href || redirect.headers.has("Location")) {
3307
- router.resolveRedirect(redirect);
3308
- if (redirectOptions.reloadDocument) return outcome;
3309
- }
3310
- if (redirectOptions.reloadDocument ? options[3] : options[1] >= 20) return outcome;
3311
- const location = router.buildLocation({
3312
- ...redirectOptions,
3313
- _fromLocation: lane[0],
3314
- _includeValidateSearch: true
3315
- });
3316
- const publicLocation = location.maskedLocation ?? location;
3317
- if (publicLocation.external) {
3318
- const resolved = redirect.clone();
3319
- resolved.options = { ...redirectOptions };
3320
- resolved.headers.set("Location", publicLocation.publicHref);
3321
- router.resolveRedirect(resolved);
3322
- return options[3] ? [REDIRECTED$1, resolved] : [
3323
- REDIRECTED$1,
3324
- resolved,
3325
- publicLocation
3326
- ];
3327
- }
3328
- return [
3329
- REDIRECTED$1,
3330
- redirect,
3331
- location
3332
- ];
3333
- } catch (cause) {
3334
- outcome = failed ? [ERROR$1, cause] : normalizeError$1(route, cause);
3335
- failed = true;
3336
- }
3337
- }
3338
- return outcome;
3339
- }
3340
- async function reduceLane(router, lane, tasks, controller, settlement, onReady) {
3341
- const matches = lane[1];
3342
- let failure = await settlement;
3343
- let redirectLimitExceeded = false;
3344
- const plannedBoundary = matches.findIndex((match) => match._notFound);
3345
- const boundaryOf = (found) => found[1][0] === NOT_FOUND$1 ? getNotFoundBoundary$1(router, matches, found, controller.signal) : found[0];
3346
- let readinessEnd = plannedBoundary < 0 ? matches.length : plannedBoundary;
3347
- if ((failure?.[1][0] ?? 0) >= REDIRECTED$1) readinessEnd = 0;
3348
- else if (failure) {
3349
- readinessEnd = failure[2] ??= await boundaryOf(failure);
3350
- for (const task of tasks) {
3351
- if (task[0] >= readinessEnd) break;
3352
- const outcome = await task[1];
3353
- if (outcome[0] !== SUCCESS$1 && outcome[0] < REDIRECTED$1 && !("loaderData" in matches[task[0]])) {
3354
- failure = [task[0], outcome];
3355
- readinessEnd = failure[2] = await boundaryOf(failure);
3356
- break;
3357
- }
3358
- }
3359
- }
3360
- for (const task of tasks) {
3361
- if (task[0] >= readinessEnd) break;
3362
- const chunkFailure = await task[2];
3363
- if (!chunkFailure) continue;
3364
- failure = chunkFailure;
3365
- break;
3366
- }
3367
- if ((failure?.[1][0] ?? 0) >= REDIRECTED$1) {
3368
- const outcome = failure[1];
3369
- if (outcome[0] !== REDIRECTED$1 || outcome[1].options.reloadDocument || outcome[2]) {
3370
- discardBackground(router, lane);
3371
- return outcome;
3372
- }
3373
- redirectLimitExceeded = true;
3374
- failure = [0, [ERROR$1, /* @__PURE__ */ new Error("Too many redirects")]];
3375
- }
3376
- const boundary = failure ? failure[2] ?? await boundaryOf(failure) : plannedBoundary;
3377
- if (boundary >= 0) {
3378
- const outcome = failure?.[1];
3379
- const kind = outcome?.[0];
3380
- const match = matches[boundary];
3381
- const cause = outcome?.[1];
3382
- const install = () => {
3383
- if (outcome) {
3384
- match._notFound = void 0;
3385
- if (kind === ERROR$1) match.status = "error";
3386
- else {
3387
- cause.routeId = match.routeId;
3388
- if (match.routeId === router.routeTree.id) {
3389
- match.status = "success";
3390
- match._notFound = true;
3391
- } else match.status = "notFound";
3392
- }
3393
- match.error = cause;
3394
- match.isFetching = false;
3395
- }
3396
- };
3397
- install();
3398
- if (!outcome) onReady?.();
3399
- const route = getRoute$1(router, match);
3400
- try {
3401
- await waitFor$1(outcome ? Promise.resolve().then(() => loadRouteChunk(route, kind === ERROR$1 ? "errorComponent" : "notFoundComponent")) : Promise.all([loadRouteChunk(route), loadRouteChunk(route, "notFoundComponent")]), controller.signal);
3402
- } catch (cause) {
3403
- if (cause === controller.signal && controller.signal.aborted) {
3404
- discardBackground(router, lane);
3405
- return CANCELED_OUTCOME;
3406
- }
3407
- }
3408
- if (!outcome) match.status = "success";
3409
- else if (redirectLimitExceeded) {
3410
- controller.abort();
3411
- await Promise.all([
3412
- ...tasks.map((task) => task[1]),
3413
- ...tasks.map((task) => task[2]),
3414
- ...(lane[2] ?? []).map((task) => task[1])
3415
- ]);
3416
- discardBackground(router, lane);
3417
- transferMatchResources(router, matches);
3418
- install();
3419
- }
3420
- }
3421
- return lane;
3422
- }
3423
- async function projectLane$1(router, lane, signal, start = 0, end = lane[1].length) {
3424
- const matches = lane[1];
3425
- for (let index = start; index < end; index++) {
3426
- const match = matches[index];
3427
- const routeOptions = getRoute$1(router, match).options;
3428
- if (routeOptions.head || routeOptions.scripts) try {
3429
- const context = {
3430
- ssr: router.options.ssr,
3431
- matches,
3432
- match,
3433
- params: match.params,
3434
- loaderData: match.loaderData
3435
- };
3436
- const [head, scripts] = await waitFor$1(Promise.all([routeOptions.head?.(context), routeOptions.scripts?.(context)]), signal);
3437
- match.meta = head?.meta;
3438
- match.links = head?.links;
3439
- match.headScripts = head?.scripts;
3440
- match.styles = head?.styles;
3441
- match.scripts = scripts;
3442
- } catch (cause) {
3443
- if (cause === signal && signal.aborted) break;
3444
- console.error(cause);
3445
- }
3446
- if (match.status !== "success" || match._notFound) break;
3447
- }
3448
- return lane;
3449
- }
3450
- async function executeClientLane(router, location, matches, options) {
3451
- const matched = [location, matches];
3452
- const signal = options[0].signal;
3453
- let reduced;
3454
- try {
3455
- const presented = router.stores.matches.get();
3456
- let plannedBoundary = matches.findIndex((match) => match._notFound);
3457
- if (router.options.notFoundMode !== "root" && plannedBoundary >= 0) {
3458
- const boundary = await getNotFoundBoundary$1(router, matches, void 0, signal, plannedBoundary);
3459
- matches[plannedBoundary]._notFound = void 0;
3460
- matches[boundary]._notFound = true;
3461
- plannedBoundary = boundary;
3462
- }
3463
- let end = plannedBoundary < 0 ? matches.length : plannedBoundary + 1;
3464
- let retainedEnd = 0;
3465
- while (retainedEnd < end && retainedEnd !== plannedBoundary) {
3466
- const match = matches[retainedEnd];
3467
- const committed = options[2][retainedEnd];
3468
- const visible = presented[retainedEnd];
3469
- if (committed?.id !== match.id || committed.status !== "success" || match.preload || visible?.id !== match.id || visible.status !== "success") break;
3470
- retainedEnd++;
3471
- if (committed._notFound || visible._notFound) break;
3472
- }
3473
- const tasks = [];
3474
- const start = options[6] ?? 0;
3475
- let semanticParent = start ? Promise.resolve(matches[start - 1]) : void 0;
3476
- const planSuccessfulLane = () => {
3477
- for (let index = start; index < end; index++) {
3478
- if (signal.aborted) break;
3479
- semanticParent = createLoaderTask$1(router, matched, index, tasks, semanticParent, options, retainedEnd);
3480
- }
3481
- };
3482
- const failure = await contextualize$1(router, matched, options, end, planSuccessfulLane, retainedEnd);
3483
- if (failure) {
3484
- options[4] = true;
3485
- end = failure[0];
3486
- if (failure[1][0] === NOT_FOUND$1) {
3487
- const boundary = await getNotFoundBoundary$1(router, matches, failure, signal);
3488
- failure[2] = boundary;
3489
- end = Math.min(end, boundary + 1);
3490
- } else if (failure[1][0] >= REDIRECTED$1) end = 0;
3491
- planSuccessfulLane();
3492
- }
3493
- if (!signal.aborted && !options[3]) {
3494
- const abort = [];
3495
- for (const [id, flight] of router._flights ?? []) if (!flight[2]) {
3496
- router._flights.delete(id);
3497
- abort.push(flight[1]);
3498
- }
3499
- for (const controller of abort) controller.abort();
3500
- }
3501
- const reduction = reduceLane(router, matched, tasks, options[0], settleTasks(tasks, failure, matched[2]), options[7]);
3502
- if (matched[2]?.length) matched[3] = settleTasks(matched[2], void 0, void 0, reduction.then((foreground) => isControl(foreground) ? 0 : _getRenderedMatches(matches).length, () => 0));
3503
- reduced = await reduction;
3504
- } catch (cause) {
3505
- discardBackground(router, matched);
3506
- if (cause === signal && signal.aborted) return CANCELED_OUTCOME;
3507
- throw cause;
3508
- }
3509
- if (isControl(reduced)) return reduced;
3510
- return projectLane$1(router, reduced, signal, options[6] === matches.length ? options[6] : 0);
3511
- }
3512
- /**
3513
- * Waits for `pendingMs`, then presents the complete lane. Rendering applies the
3514
- * selected boundary cutoff while retaining every match's structural state.
3515
- * A replacement load for the same match keeps the timer; choosing a different
3516
- * match resets it. `pendingMinMs` starts after the fallback renders.
3517
- */
3518
- function offerPending(router, tx) {
3519
- if (router._tx !== tx) return;
3520
- const matches = tx[3];
3521
- const presented = router.stores.matches.get();
3522
- let session = router._pending;
3523
- for (let index = 0; index < matches.length; index++) {
3524
- const match = matches[index];
3525
- const success = match.status === "success" && !match._notFound;
3526
- const presentedPending = presented[index]?.id === match.id && presented[index]?.status === "pending";
3527
- if (success && !presentedPending) continue;
3528
- const route = getRoute$1(router, match);
3529
- const delay = success || match.invalid ? 0 : route.options.pendingMs ?? router.options.defaultPendingMs;
3530
- const component = route.options.pendingComponent ?? router.options.defaultPendingComponent;
3531
- if (!component || typeof delay !== "number" || delay === Infinity) {
3532
- if (session) {
3533
- session[0] = tx;
3534
- session[2] = 0;
3535
- session[4] = true;
3536
- }
3537
- return;
3538
- }
3539
- const min = route.options.pendingMinMs ?? router.options.defaultPendingMinMs ?? 0;
3540
- let tookOver = false;
3541
- if (session?.[1] === match.id) {
3542
- tookOver = session[0] !== tx;
3543
- session[0] = tx;
3544
- } else {
3545
- clearTimeout(session?.[3]);
3546
- router._pending = session = void 0;
3547
- }
3548
- if (!session) router._pending = session = [
3549
- tx,
3550
- match.id,
3551
- presentedPending ? Date.now() + min : tx[4] + delay,
3552
- void 0,
3553
- presentedPending || void 0,
3554
- component
3555
- ];
3556
- if (session[4] && !tookOver && session[5] === component) return;
3557
- session[5] = component;
3558
- if (!session[4]) {
3559
- clearTimeout(session[3]);
3560
- const remaining = session[2] - Date.now();
3561
- if (remaining > 0) {
3562
- session[3] = setTimeout(() => offerPending(router, tx), remaining);
3563
- return;
3564
- }
3565
- session[2] = 0;
3566
- }
3567
- const offered = matches.map((match) => ({
3568
- ...match,
3569
- _flight: void 0
3570
- }));
3571
- offered[index].status = "pending";
3572
- const ack = session[4] = router.startTransition(() => router.stores.setMatches(offered), offered).then((rendered) => {
3573
- if (rendered && router._pending === session && session[4] === ack && !session[2]) session[2] = Date.now() + min;
3574
- return rendered;
3575
- });
3576
- return;
3577
- }
3578
- }
3579
- /**
3580
- * Cancels pending UI timing unless the current successor can take over the
3581
- * same boundary that remains painted.
3582
- */
3583
- function finishPending(router, tx) {
3584
- const session = router._pending;
3585
- if (router._tx === tx || !router._tx?.[3].some((match) => match.id === session?.[1])) {
3586
- clearTimeout(session?.[3]);
3587
- router._pending = void 0;
3588
- }
3589
- }
3590
- async function awaitPendingMinimum(router, tx) {
3591
- const session = router._pending;
3592
- if (!session) return;
3593
- clearTimeout(session[3]);
3594
- const remaining = session[2] - Date.now();
3595
- if (!session[4] || remaining <= 0 || !_getRenderedMatches(tx[3]).some((match) => match.id === session[1])) return;
3596
- let timer;
3597
- try {
3598
- await waitFor$1(new Promise((resolve) => {
3599
- timer = setTimeout(resolve, remaining);
3600
- }), tx[0].signal);
3601
- } catch {}
3602
- clearTimeout(timer);
3603
- }
3604
- function publishMatches(router, matches) {
3605
- router._committed = matches;
3606
- router.stores.setMatches(matches);
3607
- }
3608
- function commitMatches(router, tx, matches, resolvedPrefix) {
3609
- const previous = router._committed;
3610
- const previousEnd = router._lifecycleEnd;
3611
- const previousCached = router._cache;
3612
- for (const match of matches) {
3613
- match.preload = false;
3614
- if (resolvedPrefix) match._assetEnd = void 0;
3615
- }
3616
- const cut = _getRenderedMatches(matches).length;
3617
- const cached = /* @__PURE__ */ new Map();
3618
- if (process.env.NODE_ENV === "production" || !tx[6]) {
3619
- const now = Date.now();
3620
- const superseded = /* @__PURE__ */ new Set();
3621
- for (let index = 0; index < matches.length; index++) {
3622
- const match = matches[index];
3623
- if (index < cut || match.status === "success") superseded.add(match.id);
3624
- }
3625
- for (const match of [...previous, ...previousCached.values()]) {
3626
- if (match.status !== "success" || superseded.has(match.id)) continue;
3627
- const route = getRoute$1(router, match);
3628
- if (!route.options.loader || now - match.updatedAt >= (match.preload ? route.options.preloadGcTime ?? router.options.defaultPreloadGcTime ?? 3e5 : route.options.gcTime ?? router.options.defaultGcTime ?? 3e5)) continue;
3629
- cached.set(match.id, previousCached.get(match.id) === match ? match : {
3630
- ...match,
3631
- _flight: void 0,
3632
- isFetching: false,
3633
- context: {}
3634
- });
3635
- }
3636
- }
3637
- tx[3] = [];
3638
- router._cache = cached;
3639
- const nextEnd = router._lifecycleEnd = lifecycleEnd(matches);
3640
- publishMatches(router, matches);
3641
- transferMatchResources(router, [...previousCached.values(), ...previous].filter((match) => match._flight && cached.get(match.id) !== match), matches);
3642
- if (process.env.NODE_ENV !== "production") {
3643
- const handoff = tx[6]?.[0];
3644
- if (handoff && router._handoff === handoff) handoff[1]();
3645
- }
3646
- runRouteLifecycle(router, previous, matches, previousEnd, nextEnd, tx);
3647
- }
3648
- /**
3649
- * Resolve once the router has settled on a transaction other than `owner`.
3650
- * Each transaction's completion follows its current successor, so all waiters
3651
- * share the same chain instead of polling every successor independently.
3652
- */
3653
- async function awaitCurrent(router, owner) {
3654
- let current = router._tx;
3655
- while (current && current !== owner) {
3656
- owner = current;
3657
- await current[5];
3658
- current = router._tx;
3659
- }
3660
- }
3661
- function followRedirect(router, tx, outcome) {
3662
- const options = outcome[1].options;
3663
- const location = outcome[2];
3664
- if (!location) return router.navigate({
3665
- ...options,
3666
- replace: true,
3667
- ignoreBlocker: true
3668
- });
3669
- if (options.reloadDocument) return router.navigate({
3670
- href: (location.maskedLocation ?? location).publicHref,
3671
- reloadDocument: true,
3672
- replace: true,
3673
- ignoreBlocker: true
3674
- });
3675
- location._redirects = tx[1] + 1;
3676
- router._pendingLocation = location;
3677
- const committed = router.commitLocation({
3678
- ...location,
3679
- viewTransition: options.viewTransition,
3680
- replace: true,
3681
- resetScroll: options.resetScroll,
3682
- hashScrollIntoView: options.hashScrollIntoView,
3683
- ignoreBlocker: true
3684
- });
3685
- queueMicrotask(() => {
3686
- if (router._pendingLocation === location) router._pendingLocation = void 0;
3687
- });
3688
- return committed;
3689
- }
3690
- async function runBackground(router, tx, base, tasks, settlement) {
3691
- const next = base.map((match) => ({ ...match }));
3692
- acquireMatchResources(next);
3693
- for (const task of tasks) {
3694
- releaseFlight(router, next[task[0]]);
3695
- next[task[0]] = task[3];
3696
- }
3697
- const lane = [tx[2], next];
3698
- let reduced;
3699
- try {
3700
- reduced = await reduceLane(router, lane, tasks, tx[0], settlement);
3701
- } catch (cause) {
3702
- transferMatchResources(router, next);
3703
- throw cause;
3704
- }
3705
- if (isControl(reduced)) {
3706
- transferMatchResources(router, next);
3707
- if (reduced[0] === REDIRECTED$1 && router._tx === tx && router._committed === base) await followRedirect(router, tx, reduced);
3708
- return;
3709
- }
3710
- await projectLane$1(router, reduced, tx[0].signal);
3711
- if (router._tx !== tx || router._committed !== base) {
3712
- transferMatchResources(router, next);
3713
- return;
3714
- }
3715
- for (const match of next) {
3716
- const cached = router._cache.get(match.id);
3717
- if (cached?._flight && cached._flight === match._flight) {
3718
- router._cache.delete(match.id);
3719
- releaseFlight(router, cached);
3720
- }
3721
- }
3722
- publishMatches(router, next);
3723
- transferMatchResources(router, base, next);
3724
- }
3725
- async function runClientTransaction(router, tx, forceStaleReload, onReady, sync, resolvedPrefix) {
3726
- const result = await executeClientLane(router, tx[2], tx[3], [
3727
- tx[0],
3728
- tx[1],
3729
- router._committed,
3730
- void 0,
3731
- sync,
3732
- forceStaleReload,
3733
- resolvedPrefix,
3734
- onReady
3735
- ]);
3736
- if (isControl(result)) {
3737
- const follow = result[0] === REDIRECTED$1 && router._tx === tx;
3738
- if (!follow || result[1].options.reloadDocument) finishPending(router, tx);
3739
- transferMatchResources(router, tx[3]);
3740
- tx[3] = [];
3741
- if (!follow) return;
3742
- if (router._tx !== tx) {
3743
- finishPending(router, tx);
3744
- return;
3745
- }
3746
- if (process.env.NODE_ENV !== "production" && tx[6]) router._refreshNextLoad = true;
3747
- await followRedirect(router, tx, result);
3748
- return;
3749
- }
3750
- const matches = result[1];
3751
- if (router._tx === tx) await awaitPendingMinimum(router, tx);
3752
- if (router._tx !== tx) {
3753
- finishPending(router, tx);
3754
- transferMatchResources(router, matches);
3755
- discardBackground(router, result);
3756
- return;
3757
- }
3758
- const toLocation = tx[2];
3759
- const changeInfo = getLocationChangeInfo(toLocation, router.stores.resolvedLocation.get());
3760
- const background = result[2];
3761
- await router.startViewTransition(async () => {
3762
- if (router._tx === tx) await awaitPendingMinimum(router, tx);
3763
- if (router._tx !== tx) {
3764
- finishPending(router, tx);
3765
- transferMatchResources(router, matches);
3766
- discardBackground(router, result);
3767
- return;
3768
- }
3769
- const commit = () => {
3770
- finishPending(router, tx);
3771
- commitMatches(router, tx, matches, resolvedPrefix);
3772
- if (router._tx !== tx) return;
3773
- router.emit({
3774
- type: "onLoad",
3775
- ...changeInfo
3776
- });
3777
- if (router._tx === tx) router.emit({
3778
- type: "onBeforeRouteMount",
3779
- ...changeInfo
3780
- });
3781
- };
3782
- const rendered = await router.startTransition(commit, matches);
3783
- if (process.env.NODE_ENV !== "production" && tx[6]) tx[6] = void 0;
3784
- if (router._tx !== tx) {
3785
- discardBackground(router, result);
3786
- return;
3787
- }
3788
- if (background?.length) runBackground(router, tx, matches, background, result[3]).catch(console.error);
3789
- router.batch(() => {
3790
- router.stores.resolvedLocation.set(toLocation);
3791
- router.stores.status.set("idle");
3792
- if (router._tx === tx) router.emit({
3793
- type: "onResolved",
3794
- ...changeInfo
3795
- });
3796
- if (rendered && router._tx === tx) router.emit({
3797
- type: "onRendered",
3798
- ...changeInfo
3799
- });
3800
- });
3801
- if (router._tx !== tx) return;
3802
- router._commitPromise?.resolve();
3803
- router._commitPromise = void 0;
3804
- });
3805
- }
3806
- async function loadClientRoute(router, opts) {
3807
- let rematerialize = false;
3808
- if (process.env.NODE_ENV !== "production") rematerialize = !!router._refreshNextLoad || !!router._tx?.[6];
3809
- const previousOwner = router._tx;
3810
- const resolvedLocation = router.stores.resolvedLocation.get();
3811
- const previousLocation = resolvedLocation ?? router.stores.location.get();
3812
- const location = router.latestLocation;
3813
- const pendingLocation = router._pendingLocation;
3814
- const redirects = pendingLocation?.href === location.href ? pendingLocation._redirects ?? 0 : 0;
3815
- const handoff = router._handoff;
3816
- const hydrationController = rematerialize ? void 0 : handoff?.[0]();
3817
- const preflight = new AbortController();
3818
- const previousPreflight = router._preflight;
3819
- router._preflight = preflight;
3820
- if (!rematerialize && !hydrationController) handoff?.[1]();
3821
- previousPreflight?.abort();
3822
- if (!preflight.signal.aborted) {
3823
- const changeInfo = getLocationChangeInfo(location, resolvedLocation);
3824
- router.emit({
3825
- type: "onBeforeNavigate",
3826
- ...changeInfo
3827
- });
3828
- if (!preflight.signal.aborted) router.emit({
3829
- type: "onBeforeLoad",
3830
- ...changeInfo
3831
- });
3832
- }
3833
- if (preflight.signal.aborted) {
3834
- await awaitCurrent(router, previousOwner);
3835
- return;
3836
- }
3837
- const sameHref = previousLocation.href === location.href;
3838
- let controller = preflight;
3839
- const matches = process.env.NODE_ENV !== "production" && rematerialize ? router.matchRoutes(location, {
3840
- _controller: preflight,
3841
- _rematerialize: true
3842
- }) : router.matchRoutes(location, { _controller: preflight });
3843
- acquireMatchResources(matches);
3844
- const resolvedPrefix = hydrationController ? handoff[1](matches) : void 0;
3845
- if (resolvedPrefix) controller = hydrationController;
3846
- else hydrationController?.abort();
3847
- if (preflight.signal.aborted) {
3848
- transferMatchResources(router, matches);
3849
- await awaitCurrent(router, previousOwner);
3850
- return;
3851
- }
3852
- router._preflight = void 0;
3853
- let settle;
3854
- const run = () => runClientTransaction(router, tx, sameHref, () => offerPending(router, tx), opts?.sync, resolvedPrefix);
3855
- const done = opts?.sync ? new Promise((resolve) => settle = resolve) : Promise.resolve().then(run);
3856
- const tx = [
3857
- controller,
3858
- redirects,
3859
- location,
3860
- matches,
3861
- Date.now(),
3862
- done.then(() => awaitCurrent(router, tx))
3863
- ];
3864
- if (process.env.NODE_ENV !== "production" && rematerialize) {
3865
- tx[6] = [handoff];
3866
- router._refreshNextLoad = void 0;
3867
- }
3868
- router._tx = tx;
3869
- if (previousOwner) {
3870
- for (const match of router.stores.matches.get()) {
3871
- if (router._tx !== tx) break;
3872
- if (match.isFetching) setFetching(router, match, false);
3873
- }
3874
- previousOwner[0].abort();
3875
- transferMatchResources(router, previousOwner[3], tx[3], true);
3876
- }
3877
- if (router._tx !== tx) {
3878
- transferMatchResources(router, tx[3]);
3879
- tx[3] = [];
3880
- settle?.();
3881
- await awaitCurrent(router, tx);
3882
- return;
3883
- }
3884
- router.batch(() => {
3885
- router.stores.status.set("pending");
3886
- router.stores.location.set(location);
3887
- });
3888
- if (resolvedPrefix || !router._committed.length && matches[0]?.status !== "success" && !matches.some((match) => match._notFound)) offerPending(router, tx);
3889
- settle?.(run());
3890
- await tx[5];
3891
- }
3892
- async function refreshClientRoute(router) {
3893
- const pending = router._tx;
3894
- if (pending && !pending[6] && router.stores.status.get() === "pending") {
3895
- await pending[5];
3896
- if (router._tx !== pending) await awaitCurrent(router, pending);
3897
- }
3898
- router._flights?.clear();
3899
- router.clearCache();
3900
- router._refreshNextLoad = true;
3901
- await loadClientRoute(router, { sync: true });
3902
- }
3903
- async function preloadClientRoute(router, opts) {
3904
- if (process.env.NODE_ENV !== "production" && (router._refreshNextLoad || router._tx?.[6])) return;
3905
- let location = router.buildLocation(opts);
3906
- for (let redirects = 0;; redirects++) {
3907
- const base = router._committed;
3908
- const controller = new AbortController();
3909
- let matches;
3910
- let active;
3911
- let result;
3912
- try {
3913
- try {
3914
- matches = router.matchRoutes(location, { _controller: controller });
3915
- acquireMatchResources(matches);
3916
- active = (router._preloads ??= /* @__PURE__ */ new Map()).set(controller, matches);
3917
- result = await executeClientLane(router, location, matches, [
3918
- controller,
3919
- redirects,
3920
- base,
3921
- true
3922
- ]);
3923
- } finally {
3924
- if (active) {
3925
- active = active.delete(controller);
3926
- transferMatchResources(router, matches);
3927
- }
3928
- controller.abort();
3929
- }
3930
- if (!isControl(result)) return result[1];
3931
- if (!active || result.length < 3 || process.env.NODE_ENV !== "production" && (router._refreshNextLoad || router._tx?.[6])) return;
3932
- location = result[2];
3933
- } catch (cause) {
3934
- if (!isNotFound(cause)) console.error(cause);
3935
- return;
3936
- }
3937
- }
3938
- }
3939
- //#endregion
3940
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/await-signal.js
3941
- function observeLate(callback, value) {
3942
- if (!callback) return;
3943
- try {
3944
- const result = callback(value);
3945
- if (result !== void 0) Promise.resolve(result).catch(() => {});
3946
- } catch {}
3947
- }
3948
- /**
3949
- * Await `value` unless `signal` aborts first. A result that settles after the
3950
- * abort is passed to `onLate` / `onLateError` instead.
3951
- *
3952
- * One abort listener per wait: SSR requests nest at most a few waits on one
3953
- * signal, so pooling them was measurably slower than this.
3954
- */
3955
- function waitForReason(value, signal, onLate, onLateError) {
3956
- const promise = Promise.resolve(value);
3957
- if (signal.aborted) {
3958
- promise.then((result) => observeLate(onLate, result), (error) => observeLate(onLateError, error));
3959
- return Promise.reject(signal.reason);
3960
- }
3961
- return new Promise((resolve, reject) => {
3962
- const abort = () => reject(signal.reason);
3963
- signal.addEventListener("abort", abort, { once: true });
3964
- promise.then((result) => {
3965
- signal.removeEventListener("abort", abort);
3966
- if (signal.aborted) observeLate(onLate, result);
3967
- else resolve(result);
3968
- }, (error) => {
3969
- signal.removeEventListener("abort", abort);
3970
- if (signal.aborted) observeLate(onLateError, error);
3971
- else reject(error);
3972
- });
3973
- });
3974
- }
3975
- //#endregion
3976
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/load-server.js
3977
- var SUCCESS = 0;
3978
- var ERROR = 1;
3979
- var NOT_FOUND = 2;
3980
- var REDIRECTED = 3;
3981
- var SKIPPED = 4;
3982
- var MATCH_SETTLED_ABORT_REASON = Object.freeze({
3983
- name: "AbortError",
3984
- message: "TanStack Router aborted this server match because it settled."
3985
- });
3986
- var REDIRECT_ABORT_REASON = Object.freeze({
3987
- name: "AbortError",
3988
- message: "TanStack Router aborted this server match because of a redirect."
3989
- });
3990
- function getRoute(router, match) {
3991
- return router.routesById[match.routeId];
3992
- }
3993
- function normalize(value, rejected) {
3994
- if (isRedirect(value)) return [REDIRECTED, value];
3995
- if (isNotFound(value)) return [NOT_FOUND, value];
3996
- if (rejected && typeof value?.then === "function") value = new Error("A Promise was thrown", { cause: value });
3997
- return rejected ? [ERROR, value] : [SUCCESS, value];
3998
- }
3999
- function normalizeError(router, lane, route, cause, signal, notify = true) {
4000
- signal?.throwIfAborted();
4001
- let outcome = normalize(cause, true);
4002
- if (outcome[0] !== ERROR) return materializeRedirect(router, lane, route, outcome, signal, notify);
4003
- try {
4004
- route.options.onError?.(outcome[1]);
4005
- } catch (onErrorCause) {
4006
- outcome = normalize(onErrorCause, true);
4007
- }
4008
- signal?.throwIfAborted();
4009
- return materializeRedirect(router, lane, route, outcome, signal, notify);
4010
- }
4011
- function materializeRedirect(router, lane, route, outcome, signal, notify = true) {
4012
- if (outcome[0] !== REDIRECTED) return outcome;
4013
- signal?.throwIfAborted();
4014
- try {
4015
- outcome[1].options._fromLocation = lane.location;
4016
- router.resolveRedirect(outcome[1]);
4017
- signal?.throwIfAborted();
4018
- return outcome;
4019
- } catch (cause) {
4020
- signal?.throwIfAborted();
4021
- return notify ? normalizeError(router, lane, route, cause, signal, false) : [ERROR, cause];
4022
- }
4023
- }
4024
- function maybe(value, cause) {
4025
- if (cause !== void 0) return {
4026
- status: "error",
4027
- error: cause
4028
- };
4029
- return {
4030
- status: "success",
4031
- value
4032
- };
4033
- }
4034
- function navigateFrom(router, location) {
4035
- return (options) => router.navigate({
4036
- ...options,
4037
- _fromLocation: location
4038
- });
4039
- }
4040
- function waitFor(value, signal) {
4041
- return signal ? waitForReason(value, signal) : value;
4042
- }
4043
- function resolveSsr(router, lane, index) {
4044
- const match = lane.matches[index];
4045
- const route = getRoute(router, match);
4046
- const parentSsr = lane.matches[index - 1]?.ssr;
4047
- if (router.isShell()) return route.id === rootRouteId;
4048
- if (parentSsr === false) return false;
4049
- const inherit = (value) => {
4050
- return value === true && parentSsr === "data-only" ? "data-only" : value;
4051
- };
4052
- const defaultSsr = router.options.defaultSsr ?? true;
4053
- const inheritedDefault = inherit(defaultSsr);
4054
- match.ssr = inheritedDefault;
4055
- const option = route.options.ssr;
4056
- if (option === void 0) return inheritedDefault;
4057
- if (typeof option !== "function") return inherit(option);
4058
- const context = {
4059
- search: maybe(match.search, match.searchError),
4060
- params: maybe(match.params, match.paramsError),
4061
- location: lane.location,
4062
- matches: lane.matches.map((candidate) => ({
4063
- index: candidate.index,
4064
- pathname: candidate.pathname,
4065
- fullPath: candidate.fullPath,
4066
- staticData: candidate.staticData,
4067
- id: candidate.id,
4068
- routeId: candidate.routeId,
4069
- search: maybe(candidate.search, candidate.searchError),
4070
- params: maybe(candidate.params, candidate.paramsError),
4071
- ssr: candidate.ssr
4072
- }))
4073
- };
4074
- try {
4075
- return Promise.resolve(option(context)).then((value) => inherit(value ?? defaultSsr));
4076
- } catch (cause) {
4077
- return Promise.reject(cause);
4078
- }
4079
- }
4080
- function stampNotFound(match, outcome) {
4081
- if (outcome[0] === NOT_FOUND && !outcome[1].routeId) outcome[1].routeId = match.routeId;
4082
- return outcome;
4083
- }
4084
- async function contextualize(router, lane, signal) {
4085
- const globalBoundary = lane.matches.findIndex((match) => match._notFound);
4086
- let end = globalBoundary < 0 ? lane.matches.length : globalBoundary + 1;
4087
- let failure;
4088
- let parentContext = { ...router.options.context ?? {} };
4089
- for (let index = 0; index < end; index++) {
4090
- const match = lane.matches[index];
4091
- const route = getRoute(router, match);
4092
- try {
4093
- const ssr = resolveSsr(router, lane, index);
4094
- match.ssr = ssr instanceof Promise ? await ssr : ssr;
4095
- } catch (cause) {
4096
- signal?.throwIfAborted();
4097
- failure = [index, stampNotFound(match, normalizeError(router, lane, route, cause, signal))];
4098
- end = index;
4099
- }
4100
- signal?.throwIfAborted();
4101
- if (failure?.[1][0] === REDIRECTED) break;
4102
- match.__beforeLoadContext = void 0;
4103
- let context = parentContext;
4104
- try {
4105
- let routeContext;
4106
- if (route.options.context) {
4107
- const routeContextOptions = {
4108
- deps: match.loaderDeps,
4109
- params: match.params,
4110
- context: parentContext,
4111
- location: lane.location,
4112
- navigate: navigateFrom(router, lane.location),
4113
- buildLocation: router.buildLocation,
4114
- cause: match.cause,
4115
- abortController: match.abortController,
4116
- preload: false,
4117
- matches: lane.matches,
4118
- routeId: route.id
4119
- };
4120
- routeContext = route.options.context(routeContextOptions) ?? void 0;
4121
- }
4122
- context = {
4123
- ...parentContext,
4124
- ...routeContext
4125
- };
4126
- match.context = context;
4127
- } catch (cause) {
4128
- signal?.throwIfAborted();
4129
- if (!failure) failure = [index, stampNotFound(match, normalizeError(router, lane, route, cause, signal))];
4130
- end = index;
4131
- break;
4132
- }
4133
- signal?.throwIfAborted();
4134
- if (failure) break;
4135
- const validationError = match.paramsError ?? match.searchError;
4136
- if (validationError !== void 0) {
4137
- failure = [index, stampNotFound(match, normalizeError(router, lane, route, validationError, signal))];
4138
- end = index;
4139
- break;
4140
- }
4141
- signal?.throwIfAborted();
4142
- if (match.ssr === false || !route.options.beforeLoad) {
4143
- parentContext = context;
4144
- continue;
4145
- }
4146
- const abortController = match.abortController;
4147
- const options = {
4148
- search: match.search,
4149
- abortController,
4150
- params: match.params,
4151
- preload: false,
4152
- context,
4153
- location: lane.location,
4154
- navigate: navigateFrom(router, lane.location),
4155
- buildLocation: router.buildLocation,
4156
- cause: match.cause,
4157
- matches: lane.matches,
4158
- routeId: route.id,
4159
- ...router.options.additionalContext
4160
- };
4161
- try {
4162
- const beforeLoadContext = await route.options.beforeLoad(options);
4163
- signal?.throwIfAborted();
4164
- const outcome = stampNotFound(match, materializeRedirect(router, lane, route, normalize(beforeLoadContext, false), signal));
4165
- if (outcome[0] !== SUCCESS) {
4166
- failure = [index, outcome];
4167
- end = index;
4168
- break;
4169
- }
4170
- match.__beforeLoadContext = beforeLoadContext;
4171
- match.context = {
4172
- ...context,
4173
- ...beforeLoadContext
4174
- };
4175
- parentContext = match.context;
4176
- } catch (cause) {
4177
- signal?.throwIfAborted();
4178
- failure = [index, stampNotFound(match, normalizeError(router, lane, route, cause, signal))];
4179
- end = index;
4180
- break;
4181
- }
4182
- }
4183
- return {
4184
- location: lane.location,
4185
- matches: lane.matches,
4186
- end,
4187
- failure
4188
- };
4189
- }
4190
- function getLoaderContext(router, lane, match, route, index, tasks) {
4191
- return {
4192
- params: match.params,
4193
- deps: match.loaderDeps,
4194
- preload: false,
4195
- parentMatchPromise: tasks[index - 1]?.match,
4196
- abortController: match.abortController,
4197
- context: match.context,
4198
- location: lane.location,
4199
- navigate: navigateFrom(router, lane.location),
4200
- cause: match.cause,
4201
- route,
4202
- ...router.options.additionalContext
4203
- };
4204
- }
4205
- function createLoaderTask(router, lane, index, tasks, signal) {
4206
- const match = lane.matches[index];
4207
- const route = getRoute(router, match);
4208
- let outcome;
4209
- if (match.ssr === false) outcome = Promise.resolve([SKIPPED]);
4210
- else {
4211
- const routeLoader = route.options.loader;
4212
- const loader = typeof routeLoader === "function" ? routeLoader : routeLoader?.handler;
4213
- if (!loader) outcome = Promise.resolve([SUCCESS, void 0]);
4214
- else outcome = Promise.resolve().then(() => loader(getLoaderContext(router, lane, match, route, index, tasks))).then((result) => normalize(result, false), (cause) => normalize(cause, true)).then((result) => {
4215
- if (signal?.aborted || match.abortController.signal.reason === REDIRECT_ABORT_REASON) return [SKIPPED];
4216
- if (result[0] === ERROR) result = normalizeError(router, lane, route, result[1], signal);
4217
- else result = materializeRedirect(router, lane, route, result, signal);
4218
- return stampNotFound(match, result);
4219
- });
4220
- }
4221
- const parentMatch = outcome.then((result) => {
4222
- const snapshot = { ...match };
4223
- if (result[0] === SUCCESS) {
4224
- snapshot.loaderData = result[1];
4225
- snapshot.status = "success";
4226
- snapshot.error = void 0;
4227
- snapshot.invalid = false;
4228
- snapshot.isFetching = false;
4229
- } else if (result[0] === ERROR) {
4230
- snapshot.status = "error";
4231
- snapshot.error = result[1];
4232
- } else if (result[0] === NOT_FOUND) {
4233
- snapshot.status = "notFound";
4234
- snapshot.error = result[1];
4235
- }
4236
- return snapshot;
4237
- });
4238
- return {
4239
- index,
4240
- outcome,
4241
- match: parentMatch
4242
- };
4243
- }
4244
- async function getNotFoundBoundary(router, matches, indexed, signal, fallback = 0) {
4245
- const cause = indexed?.[1][1];
4246
- let index = cause?.routeId ? matches.findIndex((match) => match.routeId === cause.routeId) : indexed?.[0] ?? matches.length - 1;
4247
- if (index < 0) index = 0;
4248
- for (let candidate = index; candidate >= 0; candidate--) {
4249
- const route = getRoute(router, matches[candidate]);
4250
- try {
4251
- const loading = loadRouteChunk(route, false);
4252
- if (loading) await loading;
4253
- } catch {
4254
- signal?.throwIfAborted();
4255
- }
4256
- signal?.throwIfAborted();
4257
- if (route.options.notFoundComponent) return candidate;
4258
- }
4259
- return cause?.routeId ? index : fallback;
4260
- }
4261
- function abortMatches(matches, start = 0, reason = MATCH_SETTLED_ABORT_REASON) {
4262
- for (let index = start; index < matches.length; index++) matches[index].abortController.abort(reason);
4263
- }
4264
- async function applyFailure(router, lane, indexed, signal) {
4265
- if (!indexed) {
4266
- const boundary = lane.matches.findIndex((match) => match._notFound);
4267
- if (boundary >= 0) {
4268
- abortMatches(lane.matches, boundary + 1);
4269
- return {
4270
- status: 404,
4271
- boundary,
4272
- kind: NOT_FOUND
4273
- };
4274
- }
4275
- return { status: 200 };
4276
- }
4277
- const [index, outcome] = indexed;
4278
- if (outcome[0] === ERROR) {
4279
- const match = lane.matches[index];
4280
- match._notFound = void 0;
4281
- match.status = "error";
4282
- match.error = outcome[1];
4283
- match.isFetching = false;
4284
- abortMatches(lane.matches, index + 1);
4285
- return {
4286
- status: 500,
4287
- boundary: index,
4288
- kind: ERROR
4289
- };
4290
- }
4291
- const boundary = indexed[2] ?? await getNotFoundBoundary(router, lane.matches, indexed, signal);
4292
- const match = lane.matches[boundary];
4293
- const cause = outcome[1];
4294
- cause.routeId = match.routeId;
4295
- match._notFound = void 0;
4296
- if (match.routeId === router.routeTree.id) {
4297
- match.status = "success";
4298
- match._notFound = true;
4299
- match.error = cause;
4300
- } else {
4301
- match.status = "notFound";
4302
- match.error = cause;
4303
- }
4304
- match.isFetching = false;
4305
- abortMatches(lane.matches, boundary + 1);
4306
- return {
4307
- status: 404,
4308
- boundary,
4309
- kind: NOT_FOUND
4310
- };
4311
- }
4312
- async function loadNormalChunks(router, lane, end, signal) {
4313
- const chunks = [];
4314
- for (let index = 0; index < lane.matches.length; index++) {
4315
- const match = lane.matches[index];
4316
- if (index >= end || match.ssr !== true || match.status !== "success") continue;
4317
- const route = getRoute(router, match);
4318
- try {
4319
- const loading = loadRouteChunk(route);
4320
- if (loading) {
4321
- const chunk = loading.then(() => {
4322
- signal?.throwIfAborted();
4323
- }, (cause) => {
4324
- signal?.throwIfAborted();
4325
- return [index, stampNotFound(match, normalizeError(router, lane, route, cause, signal))];
4326
- });
4327
- chunk.catch(() => {});
4328
- chunks.push(chunk);
4329
- }
4330
- } catch (cause) {
4331
- signal?.throwIfAborted();
4332
- chunks.push([index, stampNotFound(match, normalizeError(router, lane, route, cause, signal))]);
4333
- }
4334
- }
4335
- for (const chunk of chunks) {
4336
- const indexed = Array.isArray(chunk) ? chunk : await chunk;
4337
- if (indexed) return indexed;
4338
- }
4339
- }
4340
- async function projectLane(router, lane, signal) {
4341
- for (const match of lane.matches) {
4342
- const routeOptions = getRoute(router, match).options;
4343
- if (routeOptions.head || routeOptions.scripts || routeOptions.headers) {
4344
- const context = {
4345
- ssr: router.options.ssr,
4346
- matches: lane.matches,
4347
- match,
4348
- params: match.params,
4349
- loaderData: match.loaderData
4350
- };
4351
- try {
4352
- const [head, scripts, headers] = await Promise.all([
4353
- routeOptions.head?.(context),
4354
- routeOptions.scripts?.(context),
4355
- routeOptions.headers?.(context)
4356
- ]);
4357
- signal?.throwIfAborted();
4358
- match.meta = head?.meta;
4359
- match.links = head?.links;
4360
- match.headScripts = head?.scripts;
4361
- match.styles = head?.styles;
4362
- match.scripts = scripts;
4363
- match.headers = headers;
4364
- } catch (cause) {
4365
- signal?.throwIfAborted();
4366
- console.error(cause);
4367
- }
4368
- }
4369
- if (match.ssr === false || match.status !== "success" || match._notFound) break;
4370
- }
4371
- }
4372
- async function executeServerLane(router, location, matchedMatches, signal) {
4373
- const matched = {
4374
- location,
4375
- matches: matchedMatches.map((match) => ({
4376
- ...match,
4377
- __beforeLoadContext: void 0,
4378
- context: {},
4379
- isFetching: false,
4380
- abortController: new AbortController()
4381
- }))
4382
- };
4383
- const abortLane = () => abortMatches(matched.matches, 0, signal?.reason ?? MATCH_SETTLED_ABORT_REASON);
4384
- if (signal?.aborted) {
4385
- abortLane();
4386
- signal.throwIfAborted();
4387
- }
4388
- signal?.addEventListener("abort", abortLane, { once: true });
4389
- try {
4390
- const plannedGlobalBoundary = matched.matches.findIndex((match) => match._notFound);
4391
- if (router.options.notFoundMode !== "root" && plannedGlobalBoundary >= 0) {
4392
- const boundary = await getNotFoundBoundary(router, matched.matches, void 0, signal, plannedGlobalBoundary);
4393
- if (boundary !== plannedGlobalBoundary) {
4394
- matched.matches[plannedGlobalBoundary]._notFound = void 0;
4395
- matched.matches[boundary]._notFound = true;
4396
- }
4397
- }
4398
- const lane = await contextualize(router, matched, signal);
4399
- signal?.throwIfAborted();
4400
- let loaderEnd = lane.end;
4401
- if (lane.failure?.[1][0] === REDIRECTED) loaderEnd = 0;
4402
- else if (lane.failure?.[1][0] === NOT_FOUND) {
4403
- lane.failure[2] = await getNotFoundBoundary(router, lane.matches, lane.failure, signal);
4404
- loaderEnd = Math.min(loaderEnd, lane.failure[2] + 1);
4405
- }
4406
- const tasks = [];
4407
- for (let index = 0; index < loaderEnd; index++) {
4408
- const task = createLoaderTask(router, lane, index, tasks, signal);
4409
- tasks.push(task);
4410
- }
4411
- let loaderFailure;
4412
- let control = lane.failure?.[1][0] === REDIRECTED ? lane.failure : void 0;
4413
- try {
4414
- await Promise.all(tasks.map((task) => task.outcome.then((loadedOutcome) => {
4415
- const match = lane.matches[task.index];
4416
- const outcome = loadedOutcome;
4417
- if (outcome[0] === SUCCESS) {
4418
- match.loaderData = outcome[1];
4419
- match.status = "success";
4420
- match.error = void 0;
4421
- match.invalid = false;
4422
- match.isFetching = false;
4423
- match.updatedAt = Date.now();
4424
- } else if (outcome[0] === REDIRECTED) {
4425
- control = [task.index, outcome];
4426
- throw control;
4427
- } else {
4428
- if (match.ssr !== false) {
4429
- match.status = "success";
4430
- match.error = void 0;
4431
- match.invalid = true;
4432
- match.isFetching = false;
4433
- }
4434
- if (!loaderFailure && outcome[0] !== SKIPPED) loaderFailure = [task.index, outcome];
4435
- }
4436
- })));
4437
- } catch (cause) {
4438
- if (!Array.isArray(cause)) throw cause;
4439
- control = cause;
4440
- }
4441
- signal?.throwIfAborted();
4442
- if (control?.[1][0] === REDIRECTED) {
4443
- abortMatches(lane.matches, 0, REDIRECT_ABORT_REASON);
4444
- return {
4445
- type: "redirect",
4446
- redirect: control[1][1]
4447
- };
4448
- }
4449
- let failure = lane.failure ?? loaderFailure;
4450
- const plannedBoundary = lane.matches.findIndex((match) => match._notFound);
4451
- let readinessEnd;
4452
- if (failure) {
4453
- const outcomeEnd = failure[2] ??= failure[1][0] === NOT_FOUND ? await getNotFoundBoundary(router, lane.matches, failure, signal) : failure[0];
4454
- for (const task of tasks) {
4455
- if (task.index >= outcomeEnd) break;
4456
- const outcome = await task.outcome;
4457
- if (outcome[0] !== SUCCESS && outcome[0] < REDIRECTED && !("loaderData" in lane.matches[task.index])) {
4458
- failure = [task.index, outcome];
4459
- failure[2] = outcome[0] === NOT_FOUND ? await getNotFoundBoundary(router, lane.matches, failure, signal) : task.index;
4460
- break;
4461
- }
4462
- }
4463
- readinessEnd = failure[2];
4464
- } else readinessEnd = plannedBoundary < 0 ? lane.matches.length : plannedBoundary;
4465
- const requiredFailure = await loadNormalChunks(router, lane, readinessEnd, signal);
4466
- signal?.throwIfAborted();
4467
- if (requiredFailure) {
4468
- if (requiredFailure[1][0] === REDIRECTED) {
4469
- abortMatches(lane.matches, 0, REDIRECT_ABORT_REASON);
4470
- return {
4471
- type: "redirect",
4472
- redirect: requiredFailure[1][1]
4473
- };
4474
- }
4475
- failure = requiredFailure;
4476
- }
4477
- const terminal = await applyFailure(router, lane, failure, signal);
4478
- if (terminal.boundary !== void 0) {
4479
- const match = lane.matches[terminal.boundary];
4480
- if (match.ssr === true) {
4481
- const route = getRoute(router, match);
4482
- try {
4483
- if (terminal.kind === ERROR) await loadRouteChunk(route, "errorComponent");
4484
- else if (match._notFound) await Promise.all([loadRouteChunk(route), loadRouteChunk(route, "notFoundComponent")]);
4485
- else await loadRouteChunk(route, "notFoundComponent");
4486
- } catch {}
4487
- signal?.throwIfAborted();
4488
- }
4489
- }
4490
- signal?.throwIfAborted();
4491
- await projectLane(router, {
4492
- location: lane.location,
4493
- matches: lane.matches
4494
- }, signal);
4495
- signal?.throwIfAborted();
4496
- router.serverSsr?.onCleanup((settled) => {
4497
- if (!settled) abortLane();
4498
- });
4499
- return {
4500
- type: "render",
4501
- status: terminal.status,
4502
- matches: lane.matches
4503
- };
4504
- } finally {
4505
- signal?.removeEventListener("abort", abortLane);
4506
- }
4507
- }
4508
- async function loadServerRoute(router, opts) {
4509
- if (!opts?._skipLocationUpdate) router.updateLatestLocation();
4510
- const next = router.latestLocation;
4511
- const previous = router._committed;
4512
- const previousEnd = router._lifecycleEnd;
4513
- let result;
4514
- try {
4515
- const canonical = router.buildLocation({
4516
- to: next.pathname,
4517
- search: true,
4518
- params: true,
4519
- hash: true,
4520
- state: true,
4521
- _includeValidateSearch: true
4522
- });
4523
- if (next.publicHref !== canonical.publicHref) throw redirect({ href: canonical.publicHref || "/" });
4524
- const changeInfo = getLocationChangeInfo(next, router.stores.resolvedLocation.get());
4525
- router.emit({
4526
- type: "onBeforeNavigate",
4527
- ...changeInfo
4528
- });
4529
- router.emit({
4530
- type: "onBeforeLoad",
4531
- ...changeInfo
4532
- });
4533
- opts?._signal?.throwIfAborted();
4534
- result = await waitFor(executeServerLane(router, next, router.matchRoutes(next), opts?._signal), opts?._signal);
4535
- opts?._signal?.throwIfAborted();
4536
- } catch (cause) {
4537
- opts?._signal?.throwIfAborted();
4538
- if (!isRedirect(cause)) throw cause;
4539
- cause.options._fromLocation = next;
4540
- result = {
4541
- type: "redirect",
4542
- redirect: router.resolveRedirect(cause)
4543
- };
4544
- }
4545
- router._serverResult = result;
4546
- let nextEnd = 0;
4547
- router.batch(() => {
4548
- router.stores.location.set(next);
4549
- router.stores.status.set("idle");
4550
- if (result.type === "render") {
4551
- router._committed = result.matches;
4552
- nextEnd = router._lifecycleEnd = lifecycleEnd(result.matches);
4553
- router.stores.setMatches(result.matches);
4554
- router.stores.resolvedLocation.set(next);
4555
- }
4556
- });
4557
- if (result.type === "render") runRouteLifecycle(router, previous, result.matches, previousEnd, nextEnd);
4558
- router._commitPromise?.resolve();
4559
- router._commitPromise = void 0;
4560
- }
4561
- //#endregion
4562
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/isServer/server.js
4563
- var isServer = process.env.NODE_ENV === "test" ? void 0 : true;
4564
- //#endregion
4565
- //#region ../../node_modules/.pnpm/@tanstack+router-core@1.171.38/node_modules/@tanstack/router-core/dist/esm/link.js
4566
- var preloadWarning = "Error preloading route! ☝️";
4567
- //#endregion
4568
- //#region ../../node_modules/.pnpm/@tanstack+react-router@1.170.45_react-dom@19.3.1_react@19.3.1__react@19.3.1/node_modules/@tanstack/react-router/dist/esm/routerContext.js
4569
- var routerContext = import_react.createContext(null);
4570
- //#endregion
4571
- //#region ../../node_modules/.pnpm/@tanstack+react-router@1.170.45_react-dom@19.3.1_react@19.3.1__react@19.3.1/node_modules/@tanstack/react-router/dist/esm/useRouter.js
4572
- /**
4573
- * Access the current TanStack Router instance from React context.
4574
- * Must be used within a `RouterProvider`.
4575
- *
4576
- * Options:
4577
- * - `warn`: Log a warning if no router context is found (default: true).
4578
- *
4579
- * @returns The registered router instance.
4580
- * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useRouterHook
4581
- */
4582
- function useRouter(opts) {
4583
- const value = import_react.useContext(routerContext);
4584
- if (!value) warnMissingRouter(opts);
4585
- return value;
4586
- }
4587
- function warnMissingRouter(opts) {
4588
- if (process.env.NODE_ENV !== "production" && (opts?.warn ?? true)) console.warn("Warning: useRouter must be used inside a <RouterProvider> component!");
4589
- }
4590
- //#endregion
4591
- //#region ../../node_modules/.pnpm/@tanstack+react-router@1.170.45_react-dom@19.3.1_react@19.3.1__react@19.3.1/node_modules/@tanstack/react-router/dist/esm/matchContext.js
4592
- function createLinkScope(router, routeId) {
4593
- const store = router.stores.location;
4594
- const listeners = /* @__PURE__ */ new Set();
4595
- let source;
4596
- let unsubscribe;
4597
- const update = (location) => {
4598
- if (!_isRouteDeparting(router, routeId, location)) {
4599
- source = location;
4600
- listeners.forEach((listener) => listener());
4601
- }
4602
- };
4603
- return [() => source ?? store.get(), (listener) => {
4604
- if (!listeners.size) {
4605
- source = store.get();
4606
- unsubscribe = store.subscribe(update).unsubscribe;
4607
- }
4608
- listeners.add(listener);
4609
- return () => {
4610
- listeners.delete(listener);
4611
- if (!listeners.size) {
4612
- unsubscribe();
4613
- source = void 0;
4614
- }
4615
- };
4616
- }];
4617
- }
4618
- var matchContext = import_react.createContext(void 0);
4619
- var dummyMatchContext = import_react.createContext(void 0);
4620
- require_jsx_runtime();
4621
- function useStableValues(...values) {
4622
- const ref = import_react.useRef(values);
4623
- const stable = ref.current;
4624
- values.forEach((value, index) => {
4625
- if (!deepEqual(stable[index], value, false, true)) stable[index] = value;
4626
- });
4627
- return ref.current;
4628
- }
4629
- function preloadLink(router, options) {
4630
- router.preloadRoute(options).catch((err) => {
4631
- console.warn(err);
4632
- console.warn(preloadWarning);
4633
- });
4634
- }
4635
- function resolveExternalLink(to, protocolAllowlist) {
4636
- const scheme = typeof to === "string" && getUrlScheme(to);
4637
- if (!scheme) return;
4638
- if (!protocolAllowlist.has(scheme)) {
4639
- if (process.env.NODE_ENV !== "production") console.warn(`Blocked Link with dangerous protocol: ${to}`);
4640
- return null;
4641
- }
4642
- return to;
4643
- }
4644
- function resolveIsActive(location, next, activeOptions, basepath) {
4645
- const currentPath = removeTrailingSlash(location.pathname, basepath);
4646
- const nextPath = removeTrailingSlash(next.pathname, basepath);
4647
- if (activeOptions?.exact ? currentPath !== nextPath : !(currentPath.startsWith(nextPath) && (currentPath.length === nextPath.length || currentPath[nextPath.length] === "/"))) return false;
4648
- if (activeOptions?.includeSearch ?? true) {
4649
- if (!deepEqual(location.search, next.search, !activeOptions?.exact, activeOptions?.explicitUndefined)) return false;
4650
- }
4651
- return !activeOptions?.includeHash || location.hash === next.hash;
4652
- }
4653
- function useLinkProps(options, forwardedRef, host) {
4654
- const router = useRouter();
4655
- if (isServer ?? router.isServer) return getServerLinkProps(router, options, forwardedRef, host);
4656
- const innerRef = import_react.useRef(null);
4657
- const mergedRef = import_react.useCallback((element) => {
4658
- innerRef.current = element;
4659
- if (typeof forwardedRef === "function") return forwardedRef(element);
4660
- if (forwardedRef) forwardedRef.current = element;
4661
- }, [forwardedRef]);
4662
- const { activeOptions, to, preload: userPreload, preloadDelay: userPreloadDelay, disabled, target, onClick, onBlur, onFocus, onMouseEnter, onMouseLeave, onTouchStart } = options;
4663
- const [stableSearch, stableParams, stableActiveOptions] = useStableValues(options.search, options.params, activeOptions);
4664
- const routeId = import_react.useContext(matchContext);
4665
- const scope = (router.stores._linkScopes ??= {})[routeId] ??= createLinkScope(router, routeId);
4666
- const [dest, getLinkState, getHydrationState] = import_react.useMemo(() => {
4667
- const directExternalLink = resolveExternalLink(to, router.protocolAllowlist);
4668
- if (directExternalLink !== void 0) {
4669
- const state = [directExternalLink ?? void 0];
4670
- return [options, () => state];
4671
- }
4672
- const dest = { ...options };
4673
- let source;
4674
- let state;
4675
- let hydrationState;
4676
- const getLinkState = () => {
4677
- const location = scope[0]();
4678
- if (location !== source) {
4679
- dest._fromLocation = location;
4680
- const next = router.buildLocation(dest);
4681
- const href = getHrefOption(next, router, disabled);
4682
- const isActive = disabled || href && !getUrlScheme(href) ? resolveIsActive(location, next, stableActiveOptions, router.basepath) : void 0;
4683
- if (!state || state[0] !== href || state[1] !== isActive) state = [href, isActive];
4684
- source = location;
4685
- }
4686
- return state;
4687
- };
4688
- return [
4689
- dest,
4690
- getLinkState,
4691
- stableActiveOptions?.includeHash && (() => {
4692
- const state = getLinkState();
4693
- return state[1] ? hydrationState ??= [state[0], false] : state;
4694
- })
4695
- ];
4696
- }, [
4697
- router,
4698
- scope,
4699
- options.from,
4700
- options.hash,
4701
- options.href,
4702
- to,
4703
- stableSearch,
4704
- stableParams,
4705
- options.state,
4706
- options.mask,
4707
- options.unsafeRelative,
4708
- stableActiveOptions,
4709
- disabled
4710
- ]);
4711
- const [href, isActive] = import_react.useSyncExternalStore(scope[1], getLinkState, getHydrationState || getLinkState);
4712
- const externalLink = isActive === void 0 && href;
4713
- const linkDisabled = disabled || href === void 0;
4714
- const hasRenderFetched = import_react.useRef(false);
4715
- const preload = options.reloadDocument || externalLink || linkDisabled ? false : userPreload ?? router.options.defaultPreload;
4716
- const preloadDelay = userPreloadDelay ?? router.options.defaultPreloadDelay ?? 0;
4717
- const enqueuePreload = import_react.useCallback((e) => {
4718
- const isIntersecting = e?.isIntersecting;
4719
- if (!(isIntersecting ?? preload === "intent")) {
4720
- if (isIntersecting === false) cancelPreload(innerRef);
4721
- return;
4722
- }
4723
- if (!preloadDelay) {
4724
- preloadLink(router, dest);
4725
- return;
4726
- }
4727
- innerRef.t ??= setTimeout(() => {
4728
- innerRef.t = void 0;
4729
- preloadLink(router, dest);
4730
- }, preloadDelay);
4731
- }, [
4732
- router,
4733
- dest,
4734
- innerRef,
4735
- preload,
4736
- preloadDelay
4737
- ]);
4738
- import_react.useEffect(() => {
4739
- if (!preload) return;
4740
- if (preload === "render" && !hasRenderFetched.current) {
4741
- hasRenderFetched.current = true;
4742
- preloadLink(router, dest);
4743
- }
4744
- let active = true;
4745
- let observer;
4746
- if (preload === "viewport" && innerRef.current && typeof IntersectionObserver === "function") {
4747
- observer = new IntersectionObserver((entries) => {
4748
- if (active) enqueuePreload(entries.pop());
4749
- }, { rootMargin: "100px" });
4750
- observer.observe(innerRef.current);
4751
- }
4752
- return () => {
4753
- active = false;
4754
- observer?.disconnect();
4755
- cancelPreload(innerRef);
4756
- };
4757
- }, [
4758
- router,
4759
- dest,
4760
- preload,
4761
- enqueuePreload,
4762
- innerRef
4763
- ]);
4764
- const props = collectElementProps(options, host);
4765
- props.ref = forwardedRef ? mergedRef : innerRef;
4766
- if (externalLink) {
4767
- props.href = externalLink;
4768
- return props;
4769
- }
4770
- const handleClick = (e) => {
4771
- const effectiveTarget = target ?? e.currentTarget.getAttribute("target");
4772
- if (!linkDisabled && !(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) && !e.defaultPrevented && (!effectiveTarget || effectiveTarget === "_self") && e.button === 0) {
4773
- e.preventDefault();
4774
- cancelPreload(innerRef);
4775
- router.navigate({
4776
- ...options,
4777
- _fromLocation: dest._fromLocation
4778
- });
4779
- }
4780
- };
4781
- const handleTouchStart = () => {
4782
- if (preload === "intent") preloadLink(router, dest);
4783
- };
4784
- const handleLeave = () => {
4785
- if (preload === "intent") cancelPreload(innerRef);
4786
- };
4787
- props.onClick = composeHandlers(onClick, handleClick);
4788
- props.onBlur = composeHandlers(onBlur, handleLeave);
4789
- props.onFocus = composeHandlers(onFocus, enqueuePreload);
4790
- props.onMouseEnter = composeHandlers(onMouseEnter, enqueuePreload);
4791
- props.onMouseLeave = composeHandlers(onMouseLeave, handleLeave);
4792
- props.onTouchStart = composeHandlers(onTouchStart, handleTouchStart);
4793
- return applyLinkState(props, options, isActive, href, linkDisabled, host);
4794
- }
4795
- var STATIC_EMPTY_OBJECT = {};
4796
- var STATIC_ACTIVE_OBJECT = { className: "active" };
4797
- var ROUTER_OPTION_KEYS = /* @__PURE__ */ new Set([
4798
- "to",
4799
- "params",
4800
- "search",
4801
- "hash",
4802
- "state",
4803
- "mask",
4804
- "from",
4805
- "unsafeRelative",
4806
- "reloadDocument",
4807
- "preload",
4808
- "preloadDelay",
4809
- "preloadIntentProximity",
4810
- "hashScrollIntoView",
4811
- "replace",
4812
- "startTransition",
4813
- "resetScroll",
4814
- "viewTransition",
4815
- "ignoreBlocker",
4816
- "activeProps",
4817
- "inactiveProps",
4818
- "activeOptions",
4819
- "_asChild"
4820
- ]);
4821
- function collectElementProps(options, host) {
4822
- const props = {};
4823
- for (const key in options) {
4824
- if (ROUTER_OPTION_KEYS.has(key) || key === "type" && host !== void 0 || key === "disabled" && host === "a") continue;
4825
- props[key] = options[key];
4826
- }
4827
- return props;
4828
- }
4829
- function applyLinkState(props, options, isActive, href, linkDisabled, host) {
4830
- const { activeProps, inactiveProps, className, style, target } = options;
4831
- const stateProps = functionalUpdate(isActive ? activeProps : inactiveProps, {}) ?? (isActive ? STATIC_ACTIVE_OBJECT : STATIC_EMPTY_OBJECT);
4832
- Object.assign(props, stateProps);
4833
- props.href = href;
4834
- if (host !== "a") props.disabled = linkDisabled;
4835
- props.target = target;
4836
- const stateStyle = stateProps.style;
4837
- if (style || stateStyle) props.style = style && stateStyle ? {
4838
- ...style,
4839
- ...stateStyle
4840
- } : style || stateStyle;
4841
- const stateClassName = stateProps.className;
4842
- if (className || stateClassName) props.className = className ? stateClassName ? `${className} ${stateClassName}` : className : stateClassName;
4843
- if (linkDisabled) {
4844
- props.role = "link";
4845
- props["aria-disabled"] = true;
4846
- }
4847
- if (isActive) {
4848
- props["data-status"] = "active";
4849
- props["aria-current"] = "page";
4850
- }
4851
- return props;
4852
- }
4853
- function getServerLinkProps(router, options, forwardedRef, host) {
4854
- const { to, disabled, activeOptions } = options;
4855
- const directExternalLink = resolveExternalLink(to, router.protocolAllowlist);
4856
- const next = directExternalLink === void 0 ? router.buildLocation(options) : void 0;
4857
- const hrefOption = next ? getHrefOption(next, router, disabled) : directExternalLink ?? void 0;
4858
- const linkDisabled = disabled || !hrefOption;
4859
- const externalLink = directExternalLink ?? (hrefOption && getUrlScheme(hrefOption) ? hrefOption : void 0);
4860
- const props = collectElementProps(options, host);
4861
- props.ref = forwardedRef;
4862
- if (externalLink) {
4863
- props.href = externalLink;
4864
- return props;
4865
- }
4866
- return applyLinkState(props, options, !!next && !(!disabled && !hrefOption) && !activeOptions?.includeHash && resolveIsActive(router.stores.location.get(), next, activeOptions, router.basepath), hrefOption, linkDisabled, host);
4867
- }
4868
- var cancelPreload = (ref) => {
4869
- clearTimeout(ref.t);
4870
- ref.t = void 0;
4871
- };
4872
- var composeHandlers = (first, second) => {
4873
- if (!first) return second;
4874
- return (event) => event.defaultPrevented || (first(event), event.defaultPrevented || second(event));
4875
- };
4876
- function getHrefOption(next, router, disabled) {
4877
- if (disabled) return;
4878
- const location = next.maskedLocation ?? next;
4879
- const href = location.external ? location.publicHref : router.history.createHref(location.publicHref) || "/";
4880
- if ((location.external || href !== location.publicHref) && isDangerousProtocol(href, router.protocolAllowlist)) {
4881
- if (process.env.NODE_ENV !== "production") console.warn(`Blocked Link with dangerous protocol: ${href}`);
4882
- return;
4883
- }
4884
- return href;
4885
- }
4886
- /**
4887
- * A strongly-typed anchor component for declarative navigation.
4888
- * Handles path, search, hash and state updates with optional route preloading
4889
- * and active-state styling.
4890
- *
4891
- * Props:
4892
- * - `preload`: Controls route preloading (eg. 'intent', 'render', 'viewport', true/false)
4893
- * - `preloadDelay`: Delay in ms before preloading on focus, hover, or viewport entry
4894
- * - `activeProps`/`inactiveProps`: Additional props merged when link is active/inactive
4895
- * - `resetScroll`/`hashScrollIntoView`: Control scroll behavior on navigation
4896
- * - `viewTransition`/`startTransition`: Use View Transitions/React transitions for navigation
4897
- * - `ignoreBlocker`: Bypass registered blockers
4898
- *
4899
- * @returns An anchor-like element that navigates without full page reloads.
4900
- * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkComponent
4901
- */
4902
- var Link = import_react.memo(import_react.forwardRef((props, ref) => {
4903
- const host = props._asChild || "a";
4904
- const linkProps = useLinkProps(props, ref, host);
4905
- const children = typeof props.children === "function" ? props.children({ isActive: linkProps["data-status"] === "active" }) : props.children;
4906
- return import_react.createElement(host, linkProps, children);
4907
- }), areLinkPropsEqual);
4908
- function areLinkPropsEqual(prev, next) {
4909
- let extraKeys = 0;
4910
- for (const key in next) {
4911
- extraKeys++;
4912
- if (prev[key] === next[key]) continue;
4913
- if (!ROUTER_OPTION_KEYS.has(key) || !deepEqual(prev[key], next[key], false, true)) return false;
4914
- }
4915
- for (const _key in prev) extraKeys--;
4916
- return extraKeys === 0;
4917
- }
4918
- //#endregion
4919
- export { replaceEqualDeep as C, isNotFound as E, isModuleNotFoundError as S, rootRouteId as T, trimPathLeft as _, routerContext as a, escapeHtml as b, RouterCore as c, createNonReactiveMutableStore as d, createNonReactiveReadonlyStore as f, cleanPath as g, invariant as h, useRouter as i, getLocationChangeInfo as l, storageKey as m, dummyMatchContext as n, isServer as o, defaultGetScrollRestorationKey as p, matchContext as r, _getAssetMatches as s, Link as t, createMemoryHistory as u, trimPathRight as v, redirect as w, hasKeys as x, deepEqual as y };