hermium 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/bin/hermium.mjs +103 -58
  2. package/dist/api.mjs +35 -0
  3. package/dist/public/assets/css/styles-o9LLzp-x.css +1 -0
  4. package/dist/public/assets/js/{ChatInputBlock-Bw7AL70H.js → ChatInputBlock-BgJMx5nW.js} +1 -1
  5. package/dist/public/assets/js/{MarkdownMessage-8d7Y6VL-.js → MarkdownMessage-Dd6VsKhk.js} +1 -1
  6. package/dist/public/assets/js/{base-ui-BvQbAt_1.js → base-ui-Ls-HE_Zl.js} +1 -1
  7. package/dist/public/assets/js/{chat._sessionId-BG6lVraH.js → chat._sessionId-Yif-J0_7.js} +1 -1
  8. package/dist/public/assets/js/{chat.index-D2zdMPTT.js → chat.index-QgwoSqOs.js} +1 -1
  9. package/dist/public/assets/js/{index-C0AK45FU.js → index-BDLsrzTe.js} +26 -26
  10. package/dist/public/assets/js/{index-Cx5En4FK.js → index-DRH0t4ti.js} +1 -1
  11. package/dist/public/assets/js/{memory-CeSRdTkW.js → memory-CHpNNtU2.js} +1 -1
  12. package/dist/public/assets/js/{router-8uDKazL-.js → router-B8BATVn7.js} +1 -1
  13. package/dist/public/assets/js/{settings-Bc3Y5zXO.js → settings-CRV3Pp8x.js} +1 -1
  14. package/dist/public/assets/js/{skills-DZv7sA_5.js → skills-C8G72gXr.js} +1 -1
  15. package/dist/public/assets/js/{usage-DXQsT9_b.js → usage-Bev8hqwh.js} +1 -1
  16. package/dist/server/__23tanstack-start-plugin-adapters-Cwee5PKy.mjs +6 -0
  17. package/dist/server/_chunks/ssr-renderer.mjs +22 -0
  18. package/dist/server/_libs/bail.mjs +8 -0
  19. package/dist/server/_libs/base-ui__react.mjs +9858 -0
  20. package/dist/server/_libs/base-ui__utils.mjs +1106 -0
  21. package/dist/server/_libs/ccount.mjs +16 -0
  22. package/dist/server/_libs/character-entities.mjs +2130 -0
  23. package/dist/server/_libs/class-variance-authority.mjs +44 -0
  24. package/dist/server/_libs/clsx.mjs +16 -0
  25. package/dist/server/_libs/comma-separated-tokens.mjs +10 -0
  26. package/dist/server/_libs/cookie-es.mjs +1 -0
  27. package/dist/server/_libs/croner.mjs +1 -0
  28. package/dist/server/_libs/crossws.mjs +1 -0
  29. package/dist/server/_libs/decode-named-character-reference+[...].mjs +8 -0
  30. package/dist/server/_libs/devlop.mjs +8 -0
  31. package/dist/server/_libs/escape-string-regexp.mjs +9 -0
  32. package/dist/server/_libs/estree-util-is-identifier-name.mjs +11 -0
  33. package/dist/server/_libs/extend.mjs +97 -0
  34. package/dist/server/_libs/floating-ui__core.mjs +663 -0
  35. package/dist/server/_libs/floating-ui__dom.mjs +624 -0
  36. package/dist/server/_libs/floating-ui__react-dom.mjs +279 -0
  37. package/dist/server/_libs/floating-ui__utils.mjs +322 -0
  38. package/dist/server/_libs/h3.mjs +408 -0
  39. package/dist/server/_libs/hast-util-is-element.mjs +75 -0
  40. package/dist/server/_libs/hast-util-to-jsx-runtime.mjs +388 -0
  41. package/dist/server/_libs/hast-util-to-text.mjs +305 -0
  42. package/dist/server/_libs/hast-util-whitespace.mjs +10 -0
  43. package/dist/server/_libs/highlight.js.mjs +14756 -0
  44. package/dist/server/_libs/hookable.mjs +1 -0
  45. package/dist/server/_libs/html-url-attributes.mjs +26 -0
  46. package/dist/server/_libs/inline-style-parser.mjs +142 -0
  47. package/dist/server/_libs/is-plain-obj.mjs +10 -0
  48. package/dist/server/_libs/isbot.mjs +21 -0
  49. package/dist/server/_libs/longest-streak.mjs +25 -0
  50. package/dist/server/_libs/lowlight.mjs +262 -0
  51. package/dist/server/_libs/markdown-table.mjs +142 -0
  52. package/dist/server/_libs/mdast-util-find-and-replace.mjs +109 -0
  53. package/dist/server/_libs/mdast-util-from-markdown.mjs +717 -0
  54. package/dist/server/_libs/mdast-util-gfm-autolink-literal+[...].mjs +156 -0
  55. package/dist/server/_libs/mdast-util-gfm-footnote.mjs +117 -0
  56. package/dist/server/_libs/mdast-util-gfm-strikethrough.mjs +54 -0
  57. package/dist/server/_libs/mdast-util-gfm-table.mjs +157 -0
  58. package/dist/server/_libs/mdast-util-gfm-task-list-item.mjs +77 -0
  59. package/dist/server/_libs/mdast-util-gfm.mjs +29 -0
  60. package/dist/server/_libs/mdast-util-phrasing.mjs +30 -0
  61. package/dist/server/_libs/mdast-util-to-hast.mjs +710 -0
  62. package/dist/server/_libs/mdast-util-to-markdown.mjs +798 -0
  63. package/dist/server/_libs/mdast-util-to-string.mjs +38 -0
  64. package/dist/server/_libs/micromark-core-commonmark.mjs +2259 -0
  65. package/dist/server/_libs/micromark-extension-gfm-autolink-literal+[...].mjs +344 -0
  66. package/dist/server/_libs/micromark-extension-gfm-footnote+[...].mjs +279 -0
  67. package/dist/server/_libs/micromark-extension-gfm-strikethrough+[...].mjs +98 -0
  68. package/dist/server/_libs/micromark-extension-gfm-table.mjs +491 -0
  69. package/dist/server/_libs/micromark-extension-gfm-tagfilter+[...].mjs +1 -0
  70. package/dist/server/_libs/micromark-extension-gfm-task-list-item+[...].mjs +77 -0
  71. package/dist/server/_libs/micromark-extension-gfm.mjs +18 -0
  72. package/dist/server/_libs/micromark-factory-destination.mjs +94 -0
  73. package/dist/server/_libs/micromark-factory-label.mjs +63 -0
  74. package/dist/server/_libs/micromark-factory-space.mjs +24 -0
  75. package/dist/server/_libs/micromark-factory-title.mjs +65 -0
  76. package/dist/server/_libs/micromark-factory-whitespace.mjs +22 -0
  77. package/dist/server/_libs/micromark-util-character.mjs +44 -0
  78. package/dist/server/_libs/micromark-util-chunked.mjs +36 -0
  79. package/dist/server/_libs/micromark-util-classify-character+[...].mjs +12 -0
  80. package/dist/server/_libs/micromark-util-combine-extensions+[...].mjs +41 -0
  81. package/dist/server/_libs/micromark-util-decode-numeric-character-reference+[...].mjs +19 -0
  82. package/dist/server/_libs/micromark-util-decode-string.mjs +21 -0
  83. package/dist/server/_libs/micromark-util-encode.mjs +1 -0
  84. package/dist/server/_libs/micromark-util-html-tag-name.mjs +69 -0
  85. package/dist/server/_libs/micromark-util-normalize-identifier+[...].mjs +6 -0
  86. package/dist/server/_libs/micromark-util-resolve-all.mjs +15 -0
  87. package/dist/server/_libs/micromark-util-sanitize-uri.mjs +41 -0
  88. package/dist/server/_libs/micromark-util-subtokenize.mjs +346 -0
  89. package/dist/server/_libs/micromark.mjs +906 -0
  90. package/dist/server/_libs/ocache.mjs +1 -0
  91. package/dist/server/_libs/ohash.mjs +1 -0
  92. package/dist/server/_libs/property-information.mjs +1209 -0
  93. package/dist/server/_libs/react-dom.mjs +10779 -0
  94. package/dist/server/_libs/react-markdown.mjs +147 -0
  95. package/dist/server/_libs/react.mjs +513 -0
  96. package/dist/server/_libs/rehype-highlight.mjs +94 -0
  97. package/dist/server/_libs/remark-gfm.mjs +20 -0
  98. package/dist/server/_libs/remark-parse.mjs +19 -0
  99. package/dist/server/_libs/remark-rehype.mjs +21 -0
  100. package/dist/server/_libs/reselect.mjs +1 -0
  101. package/dist/server/_libs/rou3.mjs +8 -0
  102. package/dist/server/_libs/seroval-plugins.mjs +1 -0
  103. package/dist/server/_libs/seroval.mjs +1 -0
  104. package/dist/server/_libs/space-separated-tokens.mjs +6 -0
  105. package/dist/server/_libs/srvx.mjs +781 -0
  106. package/dist/server/_libs/style-to-js.mjs +72 -0
  107. package/dist/server/_libs/style-to-object.mjs +38 -0
  108. package/dist/server/_libs/tabler__icons-react.mjs +140 -0
  109. package/dist/server/_libs/tailwind-merge.mjs +3255 -0
  110. package/dist/server/_libs/tanstack__history.mjs +29 -0
  111. package/dist/server/_libs/tanstack__react-router.mjs +1120 -0
  112. package/dist/server/_libs/tanstack__react-store.mjs +2 -0
  113. package/dist/server/_libs/tanstack__router-core.mjs +3594 -0
  114. package/dist/server/_libs/tanstack__store.mjs +1 -0
  115. package/dist/server/_libs/trim-lines.mjs +41 -0
  116. package/dist/server/_libs/trough.mjs +85 -0
  117. package/dist/server/_libs/ufo.mjs +54 -0
  118. package/dist/server/_libs/unctx.mjs +1 -0
  119. package/dist/server/_libs/ungap__structured-clone.mjs +224 -0
  120. package/dist/server/_libs/unified.mjs +661 -0
  121. package/dist/server/_libs/unist-util-find-after.mjs +41 -0
  122. package/dist/server/_libs/unist-util-is.mjs +100 -0
  123. package/dist/server/_libs/unist-util-position.mjs +27 -0
  124. package/dist/server/_libs/unist-util-stringify-position.mjs +27 -0
  125. package/dist/server/_libs/unist-util-visit-parents.mjs +83 -0
  126. package/dist/server/_libs/unist-util-visit.mjs +24 -0
  127. package/dist/server/_libs/unstorage.mjs +1 -0
  128. package/dist/server/_libs/use-sync-external-store.mjs +139 -0
  129. package/dist/server/_libs/vfile-message.mjs +138 -0
  130. package/dist/server/_libs/vfile.mjs +467 -0
  131. package/dist/server/_libs/zustand.mjs +43 -0
  132. package/dist/server/_libs/zwitch.mjs +1 -0
  133. package/dist/server/_ssr/ChatInputBlock-Bu2-iop_.mjs +220 -0
  134. package/dist/server/_ssr/MarkdownMessage-CNS7OSKN.mjs +68 -0
  135. package/dist/server/_ssr/chat._sessionId-P02iSfut.mjs +477 -0
  136. package/dist/server/_ssr/chat.index-BYB_48NC.mjs +64 -0
  137. package/dist/server/_ssr/index-C1mT_2d8.mjs +4890 -0
  138. package/dist/server/_ssr/index-DFV9_oCk.mjs +43 -0
  139. package/dist/server/_ssr/memory-CW_fSOG9.mjs +257 -0
  140. package/dist/server/_ssr/router-CUAfx91O.mjs +2035 -0
  141. package/dist/server/_ssr/settings-DoXurzvn.mjs +10 -0
  142. package/dist/server/_ssr/skills-Cs7A5ZwO.mjs +422 -0
  143. package/dist/server/_ssr/theme-BK4-7E2h.mjs +42 -0
  144. package/dist/server/_ssr/usage-Bs2-LXGz.mjs +298 -0
  145. package/dist/server/_tanstack-start-manifest_v-C7Upe2TI.mjs +4 -0
  146. package/dist/server/index.mjs +506 -0
  147. package/dist/server/public/assets/css/index-Dfs9RUU9.css +1 -0
  148. package/dist/server/public/assets/css/styles-o9LLzp-x.css +1 -0
  149. package/dist/server/public/assets/js/ChatInputBlock-BgJMx5nW.js +1 -0
  150. package/dist/server/public/assets/js/MarkdownMessage-Dd6VsKhk.js +1 -0
  151. package/dist/server/public/assets/js/base-ui-Ls-HE_Zl.js +1 -0
  152. package/dist/server/public/assets/js/chat._sessionId-Yif-J0_7.js +1 -0
  153. package/dist/server/public/assets/js/chat.index-QgwoSqOs.js +1 -0
  154. package/dist/server/public/assets/js/index-BDLsrzTe.js +60 -0
  155. package/dist/server/public/assets/js/index-DRH0t4ti.js +1 -0
  156. package/dist/server/public/assets/js/memory-CHpNNtU2.js +3 -0
  157. package/dist/server/public/assets/js/router-B8BATVn7.js +1 -0
  158. package/dist/server/public/assets/js/settings-CRV3Pp8x.js +1 -0
  159. package/dist/server/public/assets/js/skills-C8G72gXr.js +1 -0
  160. package/dist/server/public/assets/js/theme-CPkdkpaj.js +1 -0
  161. package/dist/server/public/assets/js/usage-Bev8hqwh.js +1 -0
  162. package/dist/server/public/assets/woff2/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  163. package/dist/server/public/assets/woff2/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  164. package/dist/server/public/assets/woff2/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  165. package/dist/server/public/assets/woff2/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  166. package/dist/server/public/assets/woff2/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  167. package/dist/server/public/favicon.ico +0 -0
  168. package/dist/server/public/logo.png +0 -0
  169. package/dist/server/public/manifest.json +25 -0
  170. package/dist/server/public/robots.txt +3 -0
  171. package/package.json +4 -3
  172. package/dist/public/assets/css/styles-B8p6jk5Z.css +0 -1
@@ -0,0 +1,3594 @@
1
+ import { p as parseHref } from "./tanstack__history.mjs";
2
+ import { ReadableStream as ReadableStream$1 } from "node:stream/web";
3
+ import { Readable } from "node:stream";
4
+ const isServer = true;
5
+ function last(arr) {
6
+ return arr[arr.length - 1];
7
+ }
8
+ function isFunction(d) {
9
+ return typeof d === "function";
10
+ }
11
+ function functionalUpdate(updater, previous) {
12
+ if (isFunction(updater)) return updater(previous);
13
+ return updater;
14
+ }
15
+ const hasOwn = Object.prototype.hasOwnProperty;
16
+ function hasKeys(obj) {
17
+ for (const key in obj) if (hasOwn.call(obj, key)) return true;
18
+ return false;
19
+ }
20
+ const createNull = () => /* @__PURE__ */ Object.create(null);
21
+ const nullReplaceEqualDeep = (prev, next) => replaceEqualDeep(prev, next, createNull);
22
+ function replaceEqualDeep(prev, _next, _makeObj = () => ({}), _depth = 0) {
23
+ return _next;
24
+ }
25
+ function isPlainObject(o) {
26
+ if (!hasObjectPrototype(o)) return false;
27
+ const ctor = o.constructor;
28
+ if (typeof ctor === "undefined") return true;
29
+ const prot = ctor.prototype;
30
+ if (!hasObjectPrototype(prot)) return false;
31
+ if (!prot.hasOwnProperty("isPrototypeOf")) return false;
32
+ return true;
33
+ }
34
+ function hasObjectPrototype(o) {
35
+ return Object.prototype.toString.call(o) === "[object Object]";
36
+ }
37
+ function deepEqual(a, b, opts) {
38
+ if (a === b) return true;
39
+ if (typeof a !== typeof b) return false;
40
+ if (Array.isArray(a) && Array.isArray(b)) {
41
+ if (a.length !== b.length) return false;
42
+ for (let i = 0, l = a.length; i < l; i++) if (!deepEqual(a[i], b[i], opts)) return false;
43
+ return true;
44
+ }
45
+ if (isPlainObject(a) && isPlainObject(b)) {
46
+ const ignoreUndefined = opts?.ignoreUndefined ?? true;
47
+ if (opts?.partial) {
48
+ for (const k in b) if (!ignoreUndefined || b[k] !== void 0) {
49
+ if (!deepEqual(a[k], b[k], opts)) return false;
50
+ }
51
+ return true;
52
+ }
53
+ let aCount = 0;
54
+ if (!ignoreUndefined) aCount = Object.keys(a).length;
55
+ else for (const k in a) if (a[k] !== void 0) aCount++;
56
+ let bCount = 0;
57
+ for (const k in b) if (!ignoreUndefined || b[k] !== void 0) {
58
+ bCount++;
59
+ if (bCount > aCount || !deepEqual(a[k], b[k], opts)) return false;
60
+ }
61
+ return aCount === bCount;
62
+ }
63
+ return false;
64
+ }
65
+ function createControlledPromise(onResolve) {
66
+ let resolveLoadPromise;
67
+ let rejectLoadPromise;
68
+ const controlledPromise = new Promise((resolve, reject) => {
69
+ resolveLoadPromise = resolve;
70
+ rejectLoadPromise = reject;
71
+ });
72
+ controlledPromise.status = "pending";
73
+ controlledPromise.resolve = (value) => {
74
+ controlledPromise.status = "resolved";
75
+ controlledPromise.value = value;
76
+ resolveLoadPromise(value);
77
+ onResolve?.(value);
78
+ };
79
+ controlledPromise.reject = (e) => {
80
+ controlledPromise.status = "rejected";
81
+ rejectLoadPromise(e);
82
+ };
83
+ return controlledPromise;
84
+ }
85
+ function isModuleNotFoundError(error) {
86
+ if (typeof error?.message !== "string") return false;
87
+ 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");
88
+ }
89
+ function isPromise(value) {
90
+ return Boolean(value && typeof value === "object" && typeof value.then === "function");
91
+ }
92
+ function sanitizePathSegment(segment) {
93
+ return segment.replace(/[\x00-\x1f\x7f]/g, "");
94
+ }
95
+ function decodeSegment(segment) {
96
+ let decoded;
97
+ try {
98
+ decoded = decodeURI(segment);
99
+ } catch {
100
+ decoded = segment.replaceAll(/%[0-9A-F]{2}/gi, (match) => {
101
+ try {
102
+ return decodeURI(match);
103
+ } catch {
104
+ return match;
105
+ }
106
+ });
107
+ }
108
+ return sanitizePathSegment(decoded);
109
+ }
110
+ const DEFAULT_PROTOCOL_ALLOWLIST = [
111
+ "http:",
112
+ "https:",
113
+ "mailto:",
114
+ "tel:"
115
+ ];
116
+ function isDangerousProtocol(url, allowlist) {
117
+ if (!url) return false;
118
+ try {
119
+ const parsed = new URL(url);
120
+ return !allowlist.has(parsed.protocol);
121
+ } catch {
122
+ return false;
123
+ }
124
+ }
125
+ const HTML_ESCAPE_LOOKUP = {
126
+ "&": "\\u0026",
127
+ ">": "\\u003e",
128
+ "<": "\\u003c",
129
+ "\u2028": "\\u2028",
130
+ "\u2029": "\\u2029"
131
+ };
132
+ const HTML_ESCAPE_REGEX = /[&><\u2028\u2029]/g;
133
+ function escapeHtml(str) {
134
+ return str.replace(HTML_ESCAPE_REGEX, (match) => HTML_ESCAPE_LOOKUP[match]);
135
+ }
136
+ function decodePath(path) {
137
+ if (!path) return {
138
+ path,
139
+ handledProtocolRelativeURL: false
140
+ };
141
+ if (!/[%\\\x00-\x1f\x7f]/.test(path) && !path.startsWith("//")) return {
142
+ path,
143
+ handledProtocolRelativeURL: false
144
+ };
145
+ const re = /%25|%5C/gi;
146
+ let cursor = 0;
147
+ let result = "";
148
+ let match;
149
+ while (null !== (match = re.exec(path))) {
150
+ result += decodeSegment(path.slice(cursor, match.index)) + match[0];
151
+ cursor = re.lastIndex;
152
+ }
153
+ result = result + decodeSegment(cursor ? path.slice(cursor) : path);
154
+ let handledProtocolRelativeURL = false;
155
+ if (result.startsWith("//")) {
156
+ handledProtocolRelativeURL = true;
157
+ result = "/" + result.replace(/^\/+/, "");
158
+ }
159
+ return {
160
+ path: result,
161
+ handledProtocolRelativeURL
162
+ };
163
+ }
164
+ function encodePathLikeUrl(path) {
165
+ if (!/\s|[^\u0000-\u007F]/.test(path)) return path;
166
+ return path.replace(/\s|[^\u0000-\u007F]/gu, encodeURIComponent);
167
+ }
168
+ function arraysEqual(a, b) {
169
+ if (a === b) return true;
170
+ if (a.length !== b.length) return false;
171
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
172
+ return true;
173
+ }
174
+ function invariant() {
175
+ throw new Error("Invariant failed");
176
+ }
177
+ function createLRUCache(max) {
178
+ const cache = /* @__PURE__ */ new Map();
179
+ let oldest;
180
+ let newest;
181
+ const touch = (entry) => {
182
+ if (!entry.next) return;
183
+ if (!entry.prev) {
184
+ entry.next.prev = void 0;
185
+ oldest = entry.next;
186
+ entry.next = void 0;
187
+ if (newest) {
188
+ entry.prev = newest;
189
+ newest.next = entry;
190
+ }
191
+ } else {
192
+ entry.prev.next = entry.next;
193
+ entry.next.prev = entry.prev;
194
+ entry.next = void 0;
195
+ if (newest) {
196
+ newest.next = entry;
197
+ entry.prev = newest;
198
+ }
199
+ }
200
+ newest = entry;
201
+ };
202
+ return {
203
+ get(key) {
204
+ const entry = cache.get(key);
205
+ if (!entry) return void 0;
206
+ touch(entry);
207
+ return entry.value;
208
+ },
209
+ set(key, value) {
210
+ if (cache.size >= max && oldest) {
211
+ const toDelete = oldest;
212
+ cache.delete(toDelete.key);
213
+ if (toDelete.next) {
214
+ oldest = toDelete.next;
215
+ toDelete.next.prev = void 0;
216
+ }
217
+ if (toDelete === newest) newest = void 0;
218
+ }
219
+ const existing = cache.get(key);
220
+ if (existing) {
221
+ existing.value = value;
222
+ touch(existing);
223
+ } else {
224
+ const entry = {
225
+ key,
226
+ value,
227
+ prev: newest
228
+ };
229
+ if (newest) newest.next = entry;
230
+ newest = entry;
231
+ if (!oldest) oldest = entry;
232
+ cache.set(key, entry);
233
+ }
234
+ },
235
+ clear() {
236
+ cache.clear();
237
+ oldest = void 0;
238
+ newest = void 0;
239
+ }
240
+ };
241
+ }
242
+ const SEGMENT_TYPE_INDEX = 4;
243
+ const SEGMENT_TYPE_PATHLESS = 5;
244
+ function getOpenAndCloseBraces(part) {
245
+ const openBrace = part.indexOf("{");
246
+ if (openBrace === -1) return null;
247
+ const closeBrace = part.indexOf("}", openBrace);
248
+ if (closeBrace === -1) return null;
249
+ if (openBrace + 1 >= part.length) return null;
250
+ return [openBrace, closeBrace];
251
+ }
252
+ function parseSegment(path, start, output = new Uint16Array(6)) {
253
+ const next = path.indexOf("/", start);
254
+ const end = next === -1 ? path.length : next;
255
+ const part = path.substring(start, end);
256
+ if (!part || !part.includes("$")) {
257
+ output[0] = 0;
258
+ output[1] = start;
259
+ output[2] = start;
260
+ output[3] = end;
261
+ output[4] = end;
262
+ output[5] = end;
263
+ return output;
264
+ }
265
+ if (part === "$") {
266
+ const total = path.length;
267
+ output[0] = 2;
268
+ output[1] = start;
269
+ output[2] = start;
270
+ output[3] = total;
271
+ output[4] = total;
272
+ output[5] = total;
273
+ return output;
274
+ }
275
+ if (part.charCodeAt(0) === 36) {
276
+ output[0] = 1;
277
+ output[1] = start;
278
+ output[2] = start + 1;
279
+ output[3] = end;
280
+ output[4] = end;
281
+ output[5] = end;
282
+ return output;
283
+ }
284
+ const braces = getOpenAndCloseBraces(part);
285
+ if (braces) {
286
+ const [openBrace, closeBrace] = braces;
287
+ const firstChar = part.charCodeAt(openBrace + 1);
288
+ if (firstChar === 45) {
289
+ if (openBrace + 2 < part.length && part.charCodeAt(openBrace + 2) === 36) {
290
+ const paramStart = openBrace + 3;
291
+ const paramEnd = closeBrace;
292
+ if (paramStart < paramEnd) {
293
+ output[0] = 3;
294
+ output[1] = start + openBrace;
295
+ output[2] = start + paramStart;
296
+ output[3] = start + paramEnd;
297
+ output[4] = start + closeBrace + 1;
298
+ output[5] = end;
299
+ return output;
300
+ }
301
+ }
302
+ } else if (firstChar === 36) {
303
+ const dollarPos = openBrace + 1;
304
+ const afterDollar = openBrace + 2;
305
+ if (afterDollar === closeBrace) {
306
+ output[0] = 2;
307
+ output[1] = start + openBrace;
308
+ output[2] = start + dollarPos;
309
+ output[3] = start + afterDollar;
310
+ output[4] = start + closeBrace + 1;
311
+ output[5] = path.length;
312
+ return output;
313
+ }
314
+ output[0] = 1;
315
+ output[1] = start + openBrace;
316
+ output[2] = start + afterDollar;
317
+ output[3] = start + closeBrace;
318
+ output[4] = start + closeBrace + 1;
319
+ output[5] = end;
320
+ return output;
321
+ }
322
+ }
323
+ output[0] = 0;
324
+ output[1] = start;
325
+ output[2] = start;
326
+ output[3] = end;
327
+ output[4] = end;
328
+ output[5] = end;
329
+ return output;
330
+ }
331
+ function parseSegments(defaultCaseSensitive, data, route, start, node, depth, onRoute) {
332
+ onRoute?.(route);
333
+ let cursor = start;
334
+ {
335
+ const path = route.fullPath ?? route.from;
336
+ const length = path.length;
337
+ const caseSensitive = route.options?.caseSensitive ?? defaultCaseSensitive;
338
+ const parseParams = route.options?.params?.parse ?? route.options?.parseParams;
339
+ while (cursor < length) {
340
+ const segment = parseSegment(path, cursor, data);
341
+ let nextNode;
342
+ const start2 = cursor;
343
+ const end = segment[5];
344
+ cursor = end + 1;
345
+ depth++;
346
+ switch (segment[0]) {
347
+ case 0: {
348
+ const value = path.substring(segment[2], segment[3]);
349
+ if (caseSensitive) {
350
+ const existingNode = node.static?.get(value);
351
+ if (existingNode) nextNode = existingNode;
352
+ else {
353
+ node.static ??= /* @__PURE__ */ new Map();
354
+ const next = createStaticNode(route.fullPath ?? route.from);
355
+ next.parent = node;
356
+ next.depth = depth;
357
+ nextNode = next;
358
+ node.static.set(value, next);
359
+ }
360
+ } else {
361
+ const name = value.toLowerCase();
362
+ const existingNode = node.staticInsensitive?.get(name);
363
+ if (existingNode) nextNode = existingNode;
364
+ else {
365
+ node.staticInsensitive ??= /* @__PURE__ */ new Map();
366
+ const next = createStaticNode(route.fullPath ?? route.from);
367
+ next.parent = node;
368
+ next.depth = depth;
369
+ nextNode = next;
370
+ node.staticInsensitive.set(name, next);
371
+ }
372
+ }
373
+ break;
374
+ }
375
+ case 1: {
376
+ const prefix_raw = path.substring(start2, segment[1]);
377
+ const suffix_raw = path.substring(segment[4], end);
378
+ const actuallyCaseSensitive = caseSensitive && !!(prefix_raw || suffix_raw);
379
+ const prefix = !prefix_raw ? void 0 : actuallyCaseSensitive ? prefix_raw : prefix_raw.toLowerCase();
380
+ const suffix = !suffix_raw ? void 0 : actuallyCaseSensitive ? suffix_raw : suffix_raw.toLowerCase();
381
+ const existingNode = !parseParams && node.dynamic?.find((s) => !s.parse && s.caseSensitive === actuallyCaseSensitive && s.prefix === prefix && s.suffix === suffix);
382
+ if (existingNode) nextNode = existingNode;
383
+ else {
384
+ const next = createDynamicNode(1, route.fullPath ?? route.from, actuallyCaseSensitive, prefix, suffix);
385
+ nextNode = next;
386
+ next.depth = depth;
387
+ next.parent = node;
388
+ node.dynamic ??= [];
389
+ node.dynamic.push(next);
390
+ }
391
+ break;
392
+ }
393
+ case 3: {
394
+ const prefix_raw = path.substring(start2, segment[1]);
395
+ const suffix_raw = path.substring(segment[4], end);
396
+ const actuallyCaseSensitive = caseSensitive && !!(prefix_raw || suffix_raw);
397
+ const prefix = !prefix_raw ? void 0 : actuallyCaseSensitive ? prefix_raw : prefix_raw.toLowerCase();
398
+ const suffix = !suffix_raw ? void 0 : actuallyCaseSensitive ? suffix_raw : suffix_raw.toLowerCase();
399
+ const existingNode = !parseParams && node.optional?.find((s) => !s.parse && s.caseSensitive === actuallyCaseSensitive && s.prefix === prefix && s.suffix === suffix);
400
+ if (existingNode) nextNode = existingNode;
401
+ else {
402
+ const next = createDynamicNode(3, route.fullPath ?? route.from, actuallyCaseSensitive, prefix, suffix);
403
+ nextNode = next;
404
+ next.parent = node;
405
+ next.depth = depth;
406
+ node.optional ??= [];
407
+ node.optional.push(next);
408
+ }
409
+ break;
410
+ }
411
+ case 2: {
412
+ const prefix_raw = path.substring(start2, segment[1]);
413
+ const suffix_raw = path.substring(segment[4], end);
414
+ const actuallyCaseSensitive = caseSensitive && !!(prefix_raw || suffix_raw);
415
+ const prefix = !prefix_raw ? void 0 : actuallyCaseSensitive ? prefix_raw : prefix_raw.toLowerCase();
416
+ const suffix = !suffix_raw ? void 0 : actuallyCaseSensitive ? suffix_raw : suffix_raw.toLowerCase();
417
+ const next = createDynamicNode(2, route.fullPath ?? route.from, actuallyCaseSensitive, prefix, suffix);
418
+ nextNode = next;
419
+ next.parent = node;
420
+ next.depth = depth;
421
+ node.wildcard ??= [];
422
+ node.wildcard.push(next);
423
+ }
424
+ }
425
+ node = nextNode;
426
+ }
427
+ if (parseParams && route.children && !route.isRoot && route.id && route.id.charCodeAt(route.id.lastIndexOf("/") + 1) === 95) {
428
+ const pathlessNode = createStaticNode(route.fullPath ?? route.from);
429
+ pathlessNode.kind = SEGMENT_TYPE_PATHLESS;
430
+ pathlessNode.parent = node;
431
+ depth++;
432
+ pathlessNode.depth = depth;
433
+ node.pathless ??= [];
434
+ node.pathless.push(pathlessNode);
435
+ node = pathlessNode;
436
+ }
437
+ const isLeaf = (route.path || !route.children) && !route.isRoot;
438
+ if (isLeaf && path.endsWith("/")) {
439
+ const indexNode = createStaticNode(route.fullPath ?? route.from);
440
+ indexNode.kind = SEGMENT_TYPE_INDEX;
441
+ indexNode.parent = node;
442
+ depth++;
443
+ indexNode.depth = depth;
444
+ node.index = indexNode;
445
+ node = indexNode;
446
+ }
447
+ node.parse = parseParams ?? null;
448
+ node.priority = route.options?.params?.priority ?? 0;
449
+ if (isLeaf && !node.route) {
450
+ node.route = route;
451
+ node.fullPath = route.fullPath ?? route.from;
452
+ }
453
+ }
454
+ if (route.children) for (const child of route.children) parseSegments(defaultCaseSensitive, data, child, cursor, node, depth, onRoute);
455
+ }
456
+ function sortDynamic(a, b) {
457
+ if (a.parse && !b.parse) return -1;
458
+ if (!a.parse && b.parse) return 1;
459
+ if (a.parse && b.parse && (a.priority || b.priority)) return b.priority - a.priority;
460
+ if (a.prefix && b.prefix && a.prefix !== b.prefix) {
461
+ if (a.prefix.startsWith(b.prefix)) return -1;
462
+ if (b.prefix.startsWith(a.prefix)) return 1;
463
+ }
464
+ if (a.suffix && b.suffix && a.suffix !== b.suffix) {
465
+ if (a.suffix.endsWith(b.suffix)) return -1;
466
+ if (b.suffix.endsWith(a.suffix)) return 1;
467
+ }
468
+ if (a.prefix && !b.prefix) return -1;
469
+ if (!a.prefix && b.prefix) return 1;
470
+ if (a.suffix && !b.suffix) return -1;
471
+ if (!a.suffix && b.suffix) return 1;
472
+ if (a.caseSensitive && !b.caseSensitive) return -1;
473
+ if (!a.caseSensitive && b.caseSensitive) return 1;
474
+ return 0;
475
+ }
476
+ function sortTreeNodes(node) {
477
+ if (node.pathless) for (const child of node.pathless) sortTreeNodes(child);
478
+ if (node.static) for (const child of node.static.values()) sortTreeNodes(child);
479
+ if (node.staticInsensitive) for (const child of node.staticInsensitive.values()) sortTreeNodes(child);
480
+ if (node.dynamic?.length) {
481
+ node.dynamic.sort(sortDynamic);
482
+ for (const child of node.dynamic) sortTreeNodes(child);
483
+ }
484
+ if (node.optional?.length) {
485
+ node.optional.sort(sortDynamic);
486
+ for (const child of node.optional) sortTreeNodes(child);
487
+ }
488
+ if (node.wildcard?.length) {
489
+ node.wildcard.sort(sortDynamic);
490
+ for (const child of node.wildcard) sortTreeNodes(child);
491
+ }
492
+ }
493
+ function createStaticNode(fullPath) {
494
+ return {
495
+ kind: 0,
496
+ depth: 0,
497
+ pathless: null,
498
+ index: null,
499
+ static: null,
500
+ staticInsensitive: null,
501
+ dynamic: null,
502
+ optional: null,
503
+ wildcard: null,
504
+ route: null,
505
+ fullPath,
506
+ parent: null,
507
+ parse: null,
508
+ priority: 0
509
+ };
510
+ }
511
+ function createDynamicNode(kind, fullPath, caseSensitive, prefix, suffix) {
512
+ return {
513
+ kind,
514
+ depth: 0,
515
+ pathless: null,
516
+ index: null,
517
+ static: null,
518
+ staticInsensitive: null,
519
+ dynamic: null,
520
+ optional: null,
521
+ wildcard: null,
522
+ route: null,
523
+ fullPath,
524
+ parent: null,
525
+ parse: null,
526
+ priority: 0,
527
+ caseSensitive,
528
+ prefix,
529
+ suffix
530
+ };
531
+ }
532
+ function processRouteMasks(routeList, processedTree) {
533
+ const segmentTree = createStaticNode("/");
534
+ const data = new Uint16Array(6);
535
+ for (const route of routeList) parseSegments(false, data, route, 1, segmentTree, 0);
536
+ sortTreeNodes(segmentTree);
537
+ processedTree.masksTree = segmentTree;
538
+ processedTree.flatCache = createLRUCache(1e3);
539
+ }
540
+ function findFlatMatch(path, processedTree) {
541
+ path ||= "/";
542
+ const cached = processedTree.flatCache.get(path);
543
+ if (cached) return cached;
544
+ const result = findMatch(path, processedTree.masksTree);
545
+ processedTree.flatCache.set(path, result);
546
+ return result;
547
+ }
548
+ function findSingleMatch(from, caseSensitive, fuzzy, path, processedTree) {
549
+ from ||= "/";
550
+ path ||= "/";
551
+ const key = caseSensitive ? `case\0${from}` : from;
552
+ let tree = processedTree.singleCache.get(key);
553
+ if (!tree) {
554
+ tree = createStaticNode("/");
555
+ parseSegments(caseSensitive, new Uint16Array(6), { from }, 1, tree, 0);
556
+ processedTree.singleCache.set(key, tree);
557
+ }
558
+ return findMatch(path, tree, fuzzy);
559
+ }
560
+ function findRouteMatch(path, processedTree, fuzzy = false) {
561
+ const key = fuzzy ? path : `nofuzz\0${path}`;
562
+ const cached = processedTree.matchCache.get(key);
563
+ if (cached !== void 0) return cached;
564
+ path ||= "/";
565
+ let result;
566
+ try {
567
+ result = findMatch(path, processedTree.segmentTree, fuzzy);
568
+ } catch (err) {
569
+ if (err instanceof URIError) result = null;
570
+ else throw err;
571
+ }
572
+ if (result) result.branch = buildRouteBranch(result.route);
573
+ processedTree.matchCache.set(key, result);
574
+ return result;
575
+ }
576
+ function trimPathRight$1(path) {
577
+ return path === "/" ? path : path.replace(/\/{1,}$/, "");
578
+ }
579
+ function processRouteTree(routeTree, caseSensitive = false, initRoute) {
580
+ const segmentTree = createStaticNode(routeTree.fullPath);
581
+ const data = new Uint16Array(6);
582
+ const routesById = {};
583
+ const routesByPath = {};
584
+ let index = 0;
585
+ parseSegments(caseSensitive, data, routeTree, 1, segmentTree, 0, (route) => {
586
+ initRoute?.(route, index);
587
+ if (route.id in routesById) {
588
+ invariant();
589
+ }
590
+ routesById[route.id] = route;
591
+ if (index !== 0 && route.path) {
592
+ const trimmedFullPath = trimPathRight$1(route.fullPath);
593
+ if (!routesByPath[trimmedFullPath] || route.fullPath.endsWith("/")) routesByPath[trimmedFullPath] = route;
594
+ }
595
+ index++;
596
+ });
597
+ sortTreeNodes(segmentTree);
598
+ return {
599
+ processedTree: {
600
+ segmentTree,
601
+ singleCache: createLRUCache(1e3),
602
+ matchCache: createLRUCache(1e3),
603
+ flatCache: null,
604
+ masksTree: null
605
+ },
606
+ routesById,
607
+ routesByPath
608
+ };
609
+ }
610
+ function findMatch(path, segmentTree, fuzzy = false) {
611
+ const parts = path.split("/");
612
+ const leaf = getNodeMatch(path, parts, segmentTree, fuzzy);
613
+ if (!leaf) return null;
614
+ const [rawParams] = extractParams(path, parts, leaf);
615
+ return {
616
+ route: leaf.node.route,
617
+ rawParams
618
+ };
619
+ }
620
+ function extractParams(path, parts, leaf) {
621
+ const list = buildBranch(leaf.node);
622
+ let nodeParts = null;
623
+ const rawParams = /* @__PURE__ */ Object.create(null);
624
+ let partIndex = leaf.extract?.part ?? 0;
625
+ let nodeIndex = leaf.extract?.node ?? 0;
626
+ let pathIndex = leaf.extract?.path ?? 0;
627
+ let segmentCount = leaf.extract?.segment ?? 0;
628
+ for (; nodeIndex < list.length; partIndex++, nodeIndex++, pathIndex++, segmentCount++) {
629
+ const node = list[nodeIndex];
630
+ if (node.kind === SEGMENT_TYPE_INDEX) break;
631
+ if (node.kind === SEGMENT_TYPE_PATHLESS) {
632
+ segmentCount--;
633
+ partIndex--;
634
+ pathIndex--;
635
+ continue;
636
+ }
637
+ const part = parts[partIndex];
638
+ const currentPathIndex = pathIndex;
639
+ if (part) pathIndex += part.length;
640
+ if (node.kind === 1) {
641
+ nodeParts ??= leaf.node.fullPath.split("/");
642
+ const nodePart = nodeParts[segmentCount];
643
+ const preLength = node.prefix?.length ?? 0;
644
+ if (nodePart.charCodeAt(preLength) === 123) {
645
+ const sufLength = node.suffix?.length ?? 0;
646
+ const name = nodePart.substring(preLength + 2, nodePart.length - sufLength - 1);
647
+ const value = part.substring(preLength, part.length - sufLength);
648
+ rawParams[name] = decodeURIComponent(value);
649
+ } else {
650
+ const name = nodePart.substring(1);
651
+ rawParams[name] = decodeURIComponent(part);
652
+ }
653
+ } else if (node.kind === 3) {
654
+ if (leaf.skipped & 1 << nodeIndex) {
655
+ partIndex--;
656
+ pathIndex = currentPathIndex - 1;
657
+ continue;
658
+ }
659
+ nodeParts ??= leaf.node.fullPath.split("/");
660
+ const nodePart = nodeParts[segmentCount];
661
+ const preLength = node.prefix?.length ?? 0;
662
+ const sufLength = node.suffix?.length ?? 0;
663
+ const name = nodePart.substring(preLength + 3, nodePart.length - sufLength - 1);
664
+ const value = node.suffix || node.prefix ? part.substring(preLength, part.length - sufLength) : part;
665
+ if (value) rawParams[name] = decodeURIComponent(value);
666
+ } else if (node.kind === 2) {
667
+ const n = node;
668
+ const value = path.substring(currentPathIndex + (n.prefix?.length ?? 0), path.length - (n.suffix?.length ?? 0));
669
+ const splat = decodeURIComponent(value);
670
+ rawParams["*"] = splat;
671
+ rawParams._splat = splat;
672
+ break;
673
+ }
674
+ }
675
+ if (leaf.rawParams) Object.assign(rawParams, leaf.rawParams);
676
+ return [rawParams, {
677
+ part: partIndex,
678
+ node: nodeIndex,
679
+ path: pathIndex,
680
+ segment: segmentCount
681
+ }];
682
+ }
683
+ function buildRouteBranch(route) {
684
+ const list = [route];
685
+ while (route.parentRoute) {
686
+ route = route.parentRoute;
687
+ list.push(route);
688
+ }
689
+ list.reverse();
690
+ return list;
691
+ }
692
+ function buildBranch(node) {
693
+ const list = Array(node.depth + 1);
694
+ do {
695
+ list[node.depth] = node;
696
+ node = node.parent;
697
+ } while (node);
698
+ return list;
699
+ }
700
+ function getNodeMatch(path, parts, segmentTree, fuzzy) {
701
+ if (path === "/" && segmentTree.index) return {
702
+ node: segmentTree.index,
703
+ skipped: 0
704
+ };
705
+ const trailingSlash = !last(parts);
706
+ const pathIsIndex = trailingSlash && path !== "/";
707
+ const partsLength = parts.length - (trailingSlash ? 1 : 0);
708
+ const stack = [{
709
+ node: segmentTree,
710
+ index: 1,
711
+ skipped: 0,
712
+ depth: 1,
713
+ statics: 0,
714
+ dynamics: 0,
715
+ optionals: 0
716
+ }];
717
+ let bestFuzzy = null;
718
+ let bestMatch = null;
719
+ while (stack.length) {
720
+ const frame = stack.pop();
721
+ const { node, index, skipped, depth, statics, dynamics, optionals } = frame;
722
+ let { extract, rawParams } = frame;
723
+ if (node.kind === 2 && node.route && !isFrameMoreSpecific(bestMatch, frame)) continue;
724
+ if (node.parse) {
725
+ if (!validateParseParams(path, parts, frame)) continue;
726
+ rawParams = frame.rawParams;
727
+ extract = frame.extract;
728
+ }
729
+ if (fuzzy && node.route && node.kind !== SEGMENT_TYPE_INDEX && isFrameMoreSpecific(bestFuzzy, frame)) bestFuzzy = frame;
730
+ const isBeyondPath = index === partsLength;
731
+ if (isBeyondPath) {
732
+ if (node.route && (!pathIsIndex || node.kind === SEGMENT_TYPE_INDEX || node.kind === 2) && isFrameMoreSpecific(bestMatch, frame)) bestMatch = frame;
733
+ if (!node.optional && !node.wildcard && !node.index && !node.pathless) continue;
734
+ }
735
+ const part = isBeyondPath ? void 0 : parts[index];
736
+ let lowerPart;
737
+ if (isBeyondPath && node.index) {
738
+ const indexFrame = {
739
+ node: node.index,
740
+ index,
741
+ skipped,
742
+ depth: depth + 1,
743
+ statics,
744
+ dynamics,
745
+ optionals,
746
+ extract,
747
+ rawParams
748
+ };
749
+ let indexValid = true;
750
+ if (node.index.parse) {
751
+ if (!validateParseParams(path, parts, indexFrame)) indexValid = false;
752
+ }
753
+ if (indexValid) {
754
+ if (!dynamics && !optionals && !skipped && isPerfectStaticMatch(statics, partsLength)) return indexFrame;
755
+ if (isFrameMoreSpecific(bestMatch, indexFrame)) bestMatch = indexFrame;
756
+ }
757
+ }
758
+ if (node.wildcard) for (let i = node.wildcard.length - 1; i >= 0; i--) {
759
+ const segment = node.wildcard[i];
760
+ const { prefix, suffix } = segment;
761
+ if (prefix) {
762
+ if (isBeyondPath) continue;
763
+ if (!(segment.caseSensitive ? part : lowerPart ??= part.toLowerCase()).startsWith(prefix)) continue;
764
+ }
765
+ if (suffix) {
766
+ if (isBeyondPath) continue;
767
+ const end = parts.slice(index).join("/").slice(-suffix.length);
768
+ if ((segment.caseSensitive ? end : end.toLowerCase()) !== suffix) continue;
769
+ }
770
+ stack.push({
771
+ node: segment,
772
+ index: partsLength,
773
+ skipped,
774
+ depth: depth + 1,
775
+ statics,
776
+ dynamics,
777
+ optionals,
778
+ extract,
779
+ rawParams
780
+ });
781
+ }
782
+ if (node.optional) {
783
+ const nextSkipped = skipped | 1 << depth;
784
+ const nextDepth = depth + 1;
785
+ for (let i = node.optional.length - 1; i >= 0; i--) {
786
+ const segment = node.optional[i];
787
+ stack.push({
788
+ node: segment,
789
+ index,
790
+ skipped: nextSkipped,
791
+ depth: nextDepth,
792
+ statics,
793
+ dynamics,
794
+ optionals,
795
+ extract,
796
+ rawParams
797
+ });
798
+ }
799
+ if (!isBeyondPath) for (let i = node.optional.length - 1; i >= 0; i--) {
800
+ const segment = node.optional[i];
801
+ const { prefix, suffix } = segment;
802
+ if (prefix || suffix) {
803
+ const casePart = segment.caseSensitive ? part : lowerPart ??= part.toLowerCase();
804
+ if (prefix && !casePart.startsWith(prefix)) continue;
805
+ if (suffix && !casePart.endsWith(suffix)) continue;
806
+ }
807
+ stack.push({
808
+ node: segment,
809
+ index: index + 1,
810
+ skipped,
811
+ depth: nextDepth,
812
+ statics,
813
+ dynamics,
814
+ optionals: optionals + segmentScore(partsLength, index),
815
+ extract,
816
+ rawParams
817
+ });
818
+ }
819
+ }
820
+ if (!isBeyondPath && node.dynamic && part) for (let i = node.dynamic.length - 1; i >= 0; i--) {
821
+ const segment = node.dynamic[i];
822
+ const { prefix, suffix } = segment;
823
+ if (prefix || suffix) {
824
+ const casePart = segment.caseSensitive ? part : lowerPart ??= part.toLowerCase();
825
+ if (prefix && !casePart.startsWith(prefix)) continue;
826
+ if (suffix && !casePart.endsWith(suffix)) continue;
827
+ }
828
+ stack.push({
829
+ node: segment,
830
+ index: index + 1,
831
+ skipped,
832
+ depth: depth + 1,
833
+ statics,
834
+ dynamics: dynamics + segmentScore(partsLength, index),
835
+ optionals,
836
+ extract,
837
+ rawParams
838
+ });
839
+ }
840
+ if (!isBeyondPath && node.staticInsensitive) {
841
+ const match = node.staticInsensitive.get(lowerPart ??= part.toLowerCase());
842
+ if (match) stack.push({
843
+ node: match,
844
+ index: index + 1,
845
+ skipped,
846
+ depth: depth + 1,
847
+ statics: statics + segmentScore(partsLength, index),
848
+ dynamics,
849
+ optionals,
850
+ extract,
851
+ rawParams
852
+ });
853
+ }
854
+ if (!isBeyondPath && node.static) {
855
+ const match = node.static.get(part);
856
+ if (match) stack.push({
857
+ node: match,
858
+ index: index + 1,
859
+ skipped,
860
+ depth: depth + 1,
861
+ statics: statics + segmentScore(partsLength, index),
862
+ dynamics,
863
+ optionals,
864
+ extract,
865
+ rawParams
866
+ });
867
+ }
868
+ if (node.pathless) {
869
+ const nextDepth = depth + 1;
870
+ for (let i = node.pathless.length - 1; i >= 0; i--) {
871
+ const segment = node.pathless[i];
872
+ stack.push({
873
+ node: segment,
874
+ index,
875
+ skipped,
876
+ depth: nextDepth,
877
+ statics,
878
+ dynamics,
879
+ optionals,
880
+ extract,
881
+ rawParams
882
+ });
883
+ }
884
+ }
885
+ }
886
+ if (bestMatch) return bestMatch;
887
+ if (fuzzy && bestFuzzy) {
888
+ let sliceIndex = bestFuzzy.index;
889
+ for (let i = 0; i < bestFuzzy.index; i++) sliceIndex += parts[i].length;
890
+ const splat = sliceIndex === path.length ? "/" : path.slice(sliceIndex);
891
+ bestFuzzy.rawParams ??= /* @__PURE__ */ Object.create(null);
892
+ bestFuzzy.rawParams["**"] = decodeURIComponent(splat);
893
+ return bestFuzzy;
894
+ }
895
+ return null;
896
+ }
897
+ function segmentScore(partsLength, index) {
898
+ return 2 ** (partsLength - index - 1);
899
+ }
900
+ function isPerfectStaticMatch(statics, partsLength) {
901
+ return statics === 2 ** (partsLength - 1) - 1;
902
+ }
903
+ function validateParseParams(path, parts, frame) {
904
+ let rawParams;
905
+ let state;
906
+ try {
907
+ [rawParams, state] = extractParams(path, parts, frame);
908
+ } catch {
909
+ return null;
910
+ }
911
+ frame.rawParams = rawParams;
912
+ frame.extract = state;
913
+ if (!frame.node.parse) return true;
914
+ try {
915
+ if (frame.node.parse(rawParams) === false) return null;
916
+ } catch {
917
+ }
918
+ return true;
919
+ }
920
+ function isFrameMoreSpecific(prev, next) {
921
+ if (!prev) return true;
922
+ 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.depth > prev.depth)));
923
+ }
924
+ function joinPaths(paths) {
925
+ return cleanPath(paths.filter((val) => {
926
+ return val !== void 0;
927
+ }).join("/"));
928
+ }
929
+ function cleanPath(path) {
930
+ return path.replace(/\/{2,}/g, "/");
931
+ }
932
+ function trimPathLeft(path) {
933
+ return path === "/" ? path : path.replace(/^\/{1,}/, "");
934
+ }
935
+ function trimPathRight(path) {
936
+ const len = path.length;
937
+ return len > 1 && path[len - 1] === "/" ? path.replace(/\/{1,}$/, "") : path;
938
+ }
939
+ function trimPath(path) {
940
+ return trimPathRight(trimPathLeft(path));
941
+ }
942
+ function removeTrailingSlash(value, basepath) {
943
+ if (value?.endsWith("/") && value !== "/" && value !== `${basepath}/`) return value.slice(0, -1);
944
+ return value;
945
+ }
946
+ function exactPathTest(pathName1, pathName2, basepath) {
947
+ return removeTrailingSlash(pathName1, basepath) === removeTrailingSlash(pathName2, basepath);
948
+ }
949
+ function resolvePath({ base, to, trailingSlash = "never", cache }) {
950
+ const isAbsolute = to.startsWith("/");
951
+ const isBase = !isAbsolute && to === ".";
952
+ let key;
953
+ if (cache) {
954
+ key = isAbsolute ? to : isBase ? base : base + "\0" + to;
955
+ const cached = cache.get(key);
956
+ if (cached) return cached;
957
+ }
958
+ let baseSegments;
959
+ if (isBase) baseSegments = base.split("/");
960
+ else if (isAbsolute) baseSegments = to.split("/");
961
+ else {
962
+ baseSegments = base.split("/");
963
+ while (baseSegments.length > 1 && last(baseSegments) === "") baseSegments.pop();
964
+ const toSegments = to.split("/");
965
+ for (let index = 0, length = toSegments.length; index < length; index++) {
966
+ const value = toSegments[index];
967
+ if (value === "") {
968
+ if (!index) baseSegments = [value];
969
+ else if (index === length - 1) baseSegments.push(value);
970
+ } else if (value === "..") baseSegments.pop();
971
+ else if (value === ".") ;
972
+ else baseSegments.push(value);
973
+ }
974
+ }
975
+ if (baseSegments.length > 1) {
976
+ if (last(baseSegments) === "") {
977
+ if (trailingSlash === "never") baseSegments.pop();
978
+ } else if (trailingSlash === "always") baseSegments.push("");
979
+ }
980
+ const result = cleanPath(baseSegments.join("/")) || "/";
981
+ if (key && cache) cache.set(key, result);
982
+ return result;
983
+ }
984
+ function compileDecodeCharMap(pathParamsAllowedCharacters) {
985
+ const charMap = new Map(pathParamsAllowedCharacters.map((char) => [encodeURIComponent(char), char]));
986
+ const pattern = Array.from(charMap.keys()).map((key) => key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
987
+ const regex = new RegExp(pattern, "g");
988
+ return (encoded) => encoded.replace(regex, (match) => charMap.get(match) ?? match);
989
+ }
990
+ function encodeParam(key, params, decoder) {
991
+ const value = params[key];
992
+ if (typeof value !== "string") return value;
993
+ if (key === "_splat") {
994
+ if (/^[a-zA-Z0-9\-._~!/]*$/.test(value)) return value;
995
+ return value.split("/").map((segment) => encodePathParam(segment, decoder)).join("/");
996
+ } else return encodePathParam(value, decoder);
997
+ }
998
+ function interpolatePath({ path, params, decoder, ...rest }) {
999
+ let isMissingParams = false;
1000
+ const usedParams = /* @__PURE__ */ Object.create(null);
1001
+ if (!path || path === "/") return {
1002
+ interpolatedPath: "/",
1003
+ usedParams,
1004
+ isMissingParams
1005
+ };
1006
+ if (!path.includes("$")) return {
1007
+ interpolatedPath: path,
1008
+ usedParams,
1009
+ isMissingParams
1010
+ };
1011
+ {
1012
+ if (path.indexOf("{") === -1) {
1013
+ const length2 = path.length;
1014
+ let cursor2 = 0;
1015
+ let joined2 = "";
1016
+ while (cursor2 < length2) {
1017
+ while (cursor2 < length2 && path.charCodeAt(cursor2) === 47) cursor2++;
1018
+ if (cursor2 >= length2) break;
1019
+ const start = cursor2;
1020
+ let end = path.indexOf("/", cursor2);
1021
+ if (end === -1) end = length2;
1022
+ cursor2 = end;
1023
+ const part = path.substring(start, end);
1024
+ if (!part) continue;
1025
+ if (part.charCodeAt(0) === 36) if (part.length === 1) {
1026
+ const splat = params._splat;
1027
+ usedParams._splat = splat;
1028
+ usedParams["*"] = splat;
1029
+ if (!splat) {
1030
+ isMissingParams = true;
1031
+ continue;
1032
+ }
1033
+ const value = encodeParam("_splat", params, decoder);
1034
+ joined2 += "/" + value;
1035
+ } else {
1036
+ const key = part.substring(1);
1037
+ if (!isMissingParams && !(key in params)) isMissingParams = true;
1038
+ usedParams[key] = params[key];
1039
+ const value = encodeParam(key, params, decoder) ?? "undefined";
1040
+ joined2 += "/" + value;
1041
+ }
1042
+ else joined2 += "/" + part;
1043
+ }
1044
+ if (path.endsWith("/")) joined2 += "/";
1045
+ return {
1046
+ usedParams,
1047
+ interpolatedPath: joined2 || "/",
1048
+ isMissingParams
1049
+ };
1050
+ }
1051
+ }
1052
+ const length = path.length;
1053
+ let cursor = 0;
1054
+ let segment;
1055
+ let joined = "";
1056
+ while (cursor < length) {
1057
+ const start = cursor;
1058
+ segment = parseSegment(path, start, segment);
1059
+ const end = segment[5];
1060
+ cursor = end + 1;
1061
+ if (start === end) continue;
1062
+ const kind = segment[0];
1063
+ if (kind === 0) {
1064
+ joined += "/" + path.substring(start, end);
1065
+ continue;
1066
+ }
1067
+ if (kind === 2) {
1068
+ const splat = params._splat;
1069
+ usedParams._splat = splat;
1070
+ usedParams["*"] = splat;
1071
+ const prefix = path.substring(start, segment[1]);
1072
+ const suffix = path.substring(segment[4], end);
1073
+ if (!splat) {
1074
+ isMissingParams = true;
1075
+ if (prefix || suffix) joined += "/" + prefix + suffix;
1076
+ continue;
1077
+ }
1078
+ const value = encodeParam("_splat", params, decoder);
1079
+ joined += "/" + prefix + value + suffix;
1080
+ continue;
1081
+ }
1082
+ if (kind === 1) {
1083
+ const key = path.substring(segment[2], segment[3]);
1084
+ if (!isMissingParams && !(key in params)) isMissingParams = true;
1085
+ usedParams[key] = params[key];
1086
+ const prefix = path.substring(start, segment[1]);
1087
+ const suffix = path.substring(segment[4], end);
1088
+ const value = encodeParam(key, params, decoder) ?? "undefined";
1089
+ joined += "/" + prefix + value + suffix;
1090
+ continue;
1091
+ }
1092
+ if (kind === 3) {
1093
+ const key = path.substring(segment[2], segment[3]);
1094
+ const valueRaw = params[key];
1095
+ if (valueRaw == null) continue;
1096
+ usedParams[key] = valueRaw;
1097
+ const prefix = path.substring(start, segment[1]);
1098
+ const suffix = path.substring(segment[4], end);
1099
+ const value = encodeParam(key, params, decoder) ?? "";
1100
+ joined += "/" + prefix + value + suffix;
1101
+ continue;
1102
+ }
1103
+ }
1104
+ if (path.endsWith("/")) joined += "/";
1105
+ return {
1106
+ usedParams,
1107
+ interpolatedPath: joined || "/",
1108
+ isMissingParams
1109
+ };
1110
+ }
1111
+ function encodePathParam(value, decoder) {
1112
+ const encoded = encodeURIComponent(value);
1113
+ return decoder?.(encoded) ?? encoded;
1114
+ }
1115
+ function isNotFound(obj) {
1116
+ return obj?.isNotFound === true;
1117
+ }
1118
+ function getSafeSessionStorage() {
1119
+ try {
1120
+ return typeof window !== "undefined" && typeof window.sessionStorage === "object" ? window.sessionStorage : void 0;
1121
+ } catch {
1122
+ return;
1123
+ }
1124
+ }
1125
+ const storageKey = "tsr-scroll-restoration-v1_3";
1126
+ function createScrollRestorationCache() {
1127
+ const safeSessionStorage = getSafeSessionStorage();
1128
+ if (!safeSessionStorage) return null;
1129
+ let state = {};
1130
+ try {
1131
+ const parsed = JSON.parse(safeSessionStorage.getItem("tsr-scroll-restoration-v1_3") || "{}");
1132
+ if (isPlainObject(parsed)) state = parsed;
1133
+ } catch {
1134
+ }
1135
+ const persist = () => {
1136
+ try {
1137
+ safeSessionStorage.setItem(storageKey, JSON.stringify(state));
1138
+ } catch {
1139
+ }
1140
+ };
1141
+ return {
1142
+ get state() {
1143
+ return state;
1144
+ },
1145
+ set: (updater) => {
1146
+ state = functionalUpdate(updater, state) || state;
1147
+ },
1148
+ persist
1149
+ };
1150
+ }
1151
+ createScrollRestorationCache();
1152
+ const defaultGetScrollRestorationKey = (location) => {
1153
+ return location.state.__TSR_key || location.href;
1154
+ };
1155
+ function encode(obj, stringify = String) {
1156
+ const result = new URLSearchParams();
1157
+ for (const key in obj) {
1158
+ const val = obj[key];
1159
+ if (val !== void 0) result.set(key, stringify(val));
1160
+ }
1161
+ return result.toString();
1162
+ }
1163
+ function toValue(str) {
1164
+ if (!str) return "";
1165
+ if (str === "false") return false;
1166
+ if (str === "true") return true;
1167
+ return +str * 0 === 0 && +str + "" === str ? +str : str;
1168
+ }
1169
+ function decode(str) {
1170
+ const searchParams = new URLSearchParams(str);
1171
+ const result = /* @__PURE__ */ Object.create(null);
1172
+ for (const [key, value] of searchParams.entries()) {
1173
+ const previousValue = result[key];
1174
+ if (previousValue == null) result[key] = toValue(value);
1175
+ else if (Array.isArray(previousValue)) previousValue.push(toValue(value));
1176
+ else result[key] = [previousValue, toValue(value)];
1177
+ }
1178
+ return result;
1179
+ }
1180
+ const defaultParseSearch = parseSearchWith(JSON.parse);
1181
+ const defaultStringifySearch = stringifySearchWith(JSON.stringify, JSON.parse);
1182
+ function parseSearchWith(parser) {
1183
+ return (searchStr) => {
1184
+ if (searchStr[0] === "?") searchStr = searchStr.substring(1);
1185
+ const query = decode(searchStr);
1186
+ for (const key in query) {
1187
+ const value = query[key];
1188
+ if (typeof value === "string") try {
1189
+ query[key] = parser(value);
1190
+ } catch (_err) {
1191
+ }
1192
+ }
1193
+ return query;
1194
+ };
1195
+ }
1196
+ function stringifySearchWith(stringify, parser) {
1197
+ const hasParser = typeof parser === "function";
1198
+ function stringifyValue(val) {
1199
+ if (typeof val === "object" && val !== null) try {
1200
+ return stringify(val);
1201
+ } catch (_err) {
1202
+ }
1203
+ else if (hasParser && typeof val === "string") try {
1204
+ parser(val);
1205
+ return stringify(val);
1206
+ } catch (_err) {
1207
+ }
1208
+ return val;
1209
+ }
1210
+ return (search) => {
1211
+ const searchStr = encode(search, stringifyValue);
1212
+ return searchStr ? `?${searchStr}` : "";
1213
+ };
1214
+ }
1215
+ const rootRouteId = "__root__";
1216
+ function redirect(opts) {
1217
+ opts.statusCode = opts.statusCode || opts.code || 307;
1218
+ if (!opts._builtLocation && !opts.reloadDocument && typeof opts.href === "string") try {
1219
+ new URL(opts.href);
1220
+ opts.reloadDocument = true;
1221
+ } catch {
1222
+ }
1223
+ const headers = new Headers(opts.headers);
1224
+ if (opts.href && headers.get("Location") === null) headers.set("Location", opts.href);
1225
+ const response = new Response(null, {
1226
+ status: opts.statusCode,
1227
+ headers
1228
+ });
1229
+ response.options = opts;
1230
+ if (opts.throw) throw response;
1231
+ return response;
1232
+ }
1233
+ function isRedirect(obj) {
1234
+ return obj instanceof Response && !!obj.options;
1235
+ }
1236
+ function composeRewrites(rewrites) {
1237
+ return {
1238
+ input: ({ url }) => {
1239
+ for (const rewrite of rewrites) url = executeRewriteInput(rewrite, url);
1240
+ return url;
1241
+ },
1242
+ output: ({ url }) => {
1243
+ for (let i = rewrites.length - 1; i >= 0; i--) url = executeRewriteOutput(rewrites[i], url);
1244
+ return url;
1245
+ }
1246
+ };
1247
+ }
1248
+ function rewriteBasepath(opts) {
1249
+ const trimmedBasepath = trimPath(opts.basepath);
1250
+ const normalizedBasepath = `/${trimmedBasepath}`;
1251
+ const normalizedBasepathWithSlash = `${normalizedBasepath}/`;
1252
+ const checkBasepath = opts.caseSensitive ? normalizedBasepath : normalizedBasepath.toLowerCase();
1253
+ const checkBasepathWithSlash = opts.caseSensitive ? normalizedBasepathWithSlash : normalizedBasepathWithSlash.toLowerCase();
1254
+ return {
1255
+ input: ({ url }) => {
1256
+ const pathname = opts.caseSensitive ? url.pathname : url.pathname.toLowerCase();
1257
+ if (pathname === checkBasepath) url.pathname = "/";
1258
+ else if (pathname.startsWith(checkBasepathWithSlash)) url.pathname = url.pathname.slice(normalizedBasepath.length);
1259
+ return url;
1260
+ },
1261
+ output: ({ url }) => {
1262
+ url.pathname = joinPaths([
1263
+ "/",
1264
+ trimmedBasepath,
1265
+ url.pathname
1266
+ ]);
1267
+ return url;
1268
+ }
1269
+ };
1270
+ }
1271
+ function executeRewriteInput(rewrite, url) {
1272
+ const res = rewrite?.input?.({ url });
1273
+ if (res) {
1274
+ if (typeof res === "string") return new URL(res);
1275
+ else if (res instanceof URL) return res;
1276
+ }
1277
+ return url;
1278
+ }
1279
+ function executeRewriteOutput(rewrite, url) {
1280
+ const res = rewrite?.output?.({ url });
1281
+ if (res) {
1282
+ if (typeof res === "string") return new URL(res);
1283
+ else if (res instanceof URL) return res;
1284
+ }
1285
+ return url;
1286
+ }
1287
+ function createNonReactiveMutableStore(initialValue) {
1288
+ let value = initialValue;
1289
+ return {
1290
+ get() {
1291
+ return value;
1292
+ },
1293
+ set(nextOrUpdater) {
1294
+ value = functionalUpdate(nextOrUpdater, value);
1295
+ }
1296
+ };
1297
+ }
1298
+ function createNonReactiveReadonlyStore(read) {
1299
+ return { get() {
1300
+ return read();
1301
+ } };
1302
+ }
1303
+ function createRouterStores(initialState, config) {
1304
+ const { createMutableStore, createReadonlyStore, batch, init } = config;
1305
+ const matchStores = /* @__PURE__ */ new Map();
1306
+ const pendingMatchStores = /* @__PURE__ */ new Map();
1307
+ const cachedMatchStores = /* @__PURE__ */ new Map();
1308
+ const status = createMutableStore(initialState.status);
1309
+ const loadedAt = createMutableStore(initialState.loadedAt);
1310
+ const isLoading = createMutableStore(initialState.isLoading);
1311
+ const isTransitioning = createMutableStore(initialState.isTransitioning);
1312
+ const location = createMutableStore(initialState.location);
1313
+ const resolvedLocation = createMutableStore(initialState.resolvedLocation);
1314
+ const statusCode = createMutableStore(initialState.statusCode);
1315
+ const redirect2 = createMutableStore(initialState.redirect);
1316
+ const matchesId = createMutableStore([]);
1317
+ const pendingIds = createMutableStore([]);
1318
+ const cachedIds = createMutableStore([]);
1319
+ const matches = createReadonlyStore(() => readPoolMatches(matchStores, matchesId.get()));
1320
+ const pendingMatches = createReadonlyStore(() => readPoolMatches(pendingMatchStores, pendingIds.get()));
1321
+ const cachedMatches = createReadonlyStore(() => readPoolMatches(cachedMatchStores, cachedIds.get()));
1322
+ const firstId = createReadonlyStore(() => matchesId.get()[0]);
1323
+ const hasPending = createReadonlyStore(() => matchesId.get().some((matchId) => {
1324
+ return matchStores.get(matchId)?.get().status === "pending";
1325
+ }));
1326
+ const matchRouteDeps = createReadonlyStore(() => ({
1327
+ locationHref: location.get().href,
1328
+ resolvedLocationHref: resolvedLocation.get()?.href,
1329
+ status: status.get()
1330
+ }));
1331
+ const __store = createReadonlyStore(() => ({
1332
+ status: status.get(),
1333
+ loadedAt: loadedAt.get(),
1334
+ isLoading: isLoading.get(),
1335
+ isTransitioning: isTransitioning.get(),
1336
+ matches: matches.get(),
1337
+ location: location.get(),
1338
+ resolvedLocation: resolvedLocation.get(),
1339
+ statusCode: statusCode.get(),
1340
+ redirect: redirect2.get()
1341
+ }));
1342
+ const matchStoreByRouteIdCache = createLRUCache(64);
1343
+ function getRouteMatchStore(routeId) {
1344
+ let cached = matchStoreByRouteIdCache.get(routeId);
1345
+ if (!cached) {
1346
+ cached = createReadonlyStore(() => {
1347
+ const ids = matchesId.get();
1348
+ for (const id of ids) {
1349
+ const matchStore = matchStores.get(id);
1350
+ if (matchStore && matchStore.routeId === routeId) return matchStore.get();
1351
+ }
1352
+ });
1353
+ matchStoreByRouteIdCache.set(routeId, cached);
1354
+ }
1355
+ return cached;
1356
+ }
1357
+ const store = {
1358
+ status,
1359
+ loadedAt,
1360
+ isLoading,
1361
+ isTransitioning,
1362
+ location,
1363
+ resolvedLocation,
1364
+ statusCode,
1365
+ redirect: redirect2,
1366
+ matchesId,
1367
+ pendingIds,
1368
+ cachedIds,
1369
+ matches,
1370
+ pendingMatches,
1371
+ cachedMatches,
1372
+ firstId,
1373
+ hasPending,
1374
+ matchRouteDeps,
1375
+ matchStores,
1376
+ pendingMatchStores,
1377
+ cachedMatchStores,
1378
+ __store,
1379
+ getRouteMatchStore,
1380
+ setMatches,
1381
+ setPending,
1382
+ setCached
1383
+ };
1384
+ setMatches(initialState.matches);
1385
+ init?.(store);
1386
+ function setMatches(nextMatches) {
1387
+ reconcileMatchPool(nextMatches, matchStores, matchesId, createMutableStore, batch);
1388
+ }
1389
+ function setPending(nextMatches) {
1390
+ reconcileMatchPool(nextMatches, pendingMatchStores, pendingIds, createMutableStore, batch);
1391
+ }
1392
+ function setCached(nextMatches) {
1393
+ reconcileMatchPool(nextMatches, cachedMatchStores, cachedIds, createMutableStore, batch);
1394
+ }
1395
+ return store;
1396
+ }
1397
+ function readPoolMatches(pool, ids) {
1398
+ const matches = [];
1399
+ for (const id of ids) {
1400
+ const matchStore = pool.get(id);
1401
+ if (matchStore) matches.push(matchStore.get());
1402
+ }
1403
+ return matches;
1404
+ }
1405
+ function reconcileMatchPool(nextMatches, pool, idStore, createMutableStore, batch) {
1406
+ const nextIds = nextMatches.map((d) => d.id);
1407
+ const nextIdSet = new Set(nextIds);
1408
+ batch(() => {
1409
+ for (const id of pool.keys()) if (!nextIdSet.has(id)) pool.delete(id);
1410
+ for (const nextMatch of nextMatches) {
1411
+ const existing = pool.get(nextMatch.id);
1412
+ if (!existing) {
1413
+ const matchStore = createMutableStore(nextMatch);
1414
+ matchStore.routeId = nextMatch.routeId;
1415
+ pool.set(nextMatch.id, matchStore);
1416
+ continue;
1417
+ }
1418
+ existing.routeId = nextMatch.routeId;
1419
+ if (existing.get() !== nextMatch) existing.set(nextMatch);
1420
+ }
1421
+ if (!arraysEqual(idStore.get(), nextIds)) idStore.set(nextIds);
1422
+ });
1423
+ }
1424
+ const triggerOnReady = (inner) => {
1425
+ if (!inner.rendered) {
1426
+ inner.rendered = true;
1427
+ return inner.onReady?.();
1428
+ }
1429
+ };
1430
+ const resolvePreload = (inner, matchId) => {
1431
+ return !!(inner.preload && !inner.router.stores.matchStores.has(matchId));
1432
+ };
1433
+ const buildMatchContext = (inner, index, includeCurrentMatch = true) => {
1434
+ const context = { ...inner.router.options.context ?? {} };
1435
+ const end = includeCurrentMatch ? index : index - 1;
1436
+ for (let i = 0; i <= end; i++) {
1437
+ const innerMatch = inner.matches[i];
1438
+ if (!innerMatch) continue;
1439
+ const m = inner.router.getMatch(innerMatch.id);
1440
+ if (!m) continue;
1441
+ Object.assign(context, m.__routeContext, m.__beforeLoadContext);
1442
+ }
1443
+ return context;
1444
+ };
1445
+ const getNotFoundBoundaryIndex = (inner, err) => {
1446
+ if (!inner.matches.length) return;
1447
+ const requestedRouteId = err.routeId;
1448
+ const matchedRootIndex = inner.matches.findIndex((m) => m.routeId === inner.router.routeTree.id);
1449
+ const rootIndex = matchedRootIndex >= 0 ? matchedRootIndex : 0;
1450
+ let startIndex = requestedRouteId ? inner.matches.findIndex((match) => match.routeId === requestedRouteId) : inner.firstBadMatchIndex ?? inner.matches.length - 1;
1451
+ if (startIndex < 0) startIndex = rootIndex;
1452
+ for (let i = startIndex; i >= 0; i--) {
1453
+ const match = inner.matches[i];
1454
+ if (inner.router.looseRoutesById[match.routeId].options.notFoundComponent) return i;
1455
+ }
1456
+ return requestedRouteId ? startIndex : rootIndex;
1457
+ };
1458
+ const handleRedirectAndNotFound = (inner, match, err) => {
1459
+ if (!isRedirect(err) && !isNotFound(err)) return;
1460
+ if (isRedirect(err) && err.redirectHandled && !err.options.reloadDocument) throw err;
1461
+ if (match) {
1462
+ match._nonReactive.beforeLoadPromise?.resolve();
1463
+ match._nonReactive.loaderPromise?.resolve();
1464
+ match._nonReactive.beforeLoadPromise = void 0;
1465
+ match._nonReactive.loaderPromise = void 0;
1466
+ match._nonReactive.error = err;
1467
+ inner.updateMatch(match.id, (prev) => ({
1468
+ ...prev,
1469
+ status: isRedirect(err) ? "redirected" : isNotFound(err) ? "notFound" : prev.status === "pending" ? "success" : prev.status,
1470
+ context: buildMatchContext(inner, match.index),
1471
+ isFetching: false,
1472
+ error: err
1473
+ }));
1474
+ if (isNotFound(err) && !err.routeId) err.routeId = match.routeId;
1475
+ match._nonReactive.loadPromise?.resolve();
1476
+ }
1477
+ if (isRedirect(err)) {
1478
+ inner.rendered = true;
1479
+ err.options._fromLocation = inner.location;
1480
+ err.redirectHandled = true;
1481
+ err = inner.router.resolveRedirect(err);
1482
+ }
1483
+ throw err;
1484
+ };
1485
+ const shouldSkipLoader = (inner, matchId) => {
1486
+ const match = inner.router.getMatch(matchId);
1487
+ if (!match) return true;
1488
+ if (match.ssr === false) return true;
1489
+ return false;
1490
+ };
1491
+ const syncMatchContext = (inner, matchId, index) => {
1492
+ const nextContext = buildMatchContext(inner, index);
1493
+ inner.updateMatch(matchId, (prev) => {
1494
+ return {
1495
+ ...prev,
1496
+ context: nextContext
1497
+ };
1498
+ });
1499
+ };
1500
+ const handleSerialError = (inner, index, err, routerCode) => {
1501
+ const { id: matchId, routeId } = inner.matches[index];
1502
+ const route = inner.router.looseRoutesById[routeId];
1503
+ if (err instanceof Promise) throw err;
1504
+ err.routerCode = routerCode;
1505
+ inner.firstBadMatchIndex ??= index;
1506
+ handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err);
1507
+ try {
1508
+ route.options.onError?.(err);
1509
+ } catch (errorHandlerErr) {
1510
+ err = errorHandlerErr;
1511
+ handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err);
1512
+ }
1513
+ inner.updateMatch(matchId, (prev) => {
1514
+ prev._nonReactive.beforeLoadPromise?.resolve();
1515
+ prev._nonReactive.beforeLoadPromise = void 0;
1516
+ prev._nonReactive.loadPromise?.resolve();
1517
+ return {
1518
+ ...prev,
1519
+ error: err,
1520
+ status: "error",
1521
+ isFetching: false,
1522
+ updatedAt: Date.now(),
1523
+ abortController: new AbortController()
1524
+ };
1525
+ });
1526
+ if (!inner.preload && !isRedirect(err) && !isNotFound(err)) inner.serialError ??= err;
1527
+ };
1528
+ const isBeforeLoadSsr = (inner, matchId, index, route) => {
1529
+ const existingMatch = inner.router.getMatch(matchId);
1530
+ const parentMatchId = inner.matches[index - 1]?.id;
1531
+ const parentMatch = parentMatchId ? inner.router.getMatch(parentMatchId) : void 0;
1532
+ if (inner.router.isShell()) {
1533
+ existingMatch.ssr = route.id === rootRouteId;
1534
+ return;
1535
+ }
1536
+ if (parentMatch?.ssr === false) {
1537
+ existingMatch.ssr = false;
1538
+ return;
1539
+ }
1540
+ const parentOverride = (tempSsr2) => {
1541
+ if (tempSsr2 === true && parentMatch?.ssr === "data-only") return "data-only";
1542
+ return tempSsr2;
1543
+ };
1544
+ const defaultSsr = inner.router.options.defaultSsr ?? true;
1545
+ if (route.options.ssr === void 0) {
1546
+ existingMatch.ssr = parentOverride(defaultSsr);
1547
+ return;
1548
+ }
1549
+ if (typeof route.options.ssr !== "function") {
1550
+ existingMatch.ssr = parentOverride(route.options.ssr);
1551
+ return;
1552
+ }
1553
+ const { search, params } = existingMatch;
1554
+ const ssrFnContext = {
1555
+ search: makeMaybe(search, existingMatch.searchError),
1556
+ params: makeMaybe(params, existingMatch.paramsError),
1557
+ location: inner.location,
1558
+ matches: inner.matches.map((match) => ({
1559
+ index: match.index,
1560
+ pathname: match.pathname,
1561
+ fullPath: match.fullPath,
1562
+ staticData: match.staticData,
1563
+ id: match.id,
1564
+ routeId: match.routeId,
1565
+ search: makeMaybe(match.search, match.searchError),
1566
+ params: makeMaybe(match.params, match.paramsError),
1567
+ ssr: match.ssr
1568
+ }))
1569
+ };
1570
+ const tempSsr = route.options.ssr(ssrFnContext);
1571
+ if (isPromise(tempSsr)) return tempSsr.then((ssr) => {
1572
+ existingMatch.ssr = parentOverride(ssr ?? defaultSsr);
1573
+ });
1574
+ existingMatch.ssr = parentOverride(tempSsr ?? defaultSsr);
1575
+ };
1576
+ const setupPendingTimeout = (inner, matchId, route, match) => {
1577
+ if (match._nonReactive.pendingTimeout !== void 0) return;
1578
+ const pendingMs = route.options.pendingMs ?? inner.router.options.defaultPendingMs;
1579
+ if (!!(inner.onReady && false)) {
1580
+ const pendingTimeout = setTimeout(() => {
1581
+ triggerOnReady(inner);
1582
+ }, pendingMs);
1583
+ match._nonReactive.pendingTimeout = pendingTimeout;
1584
+ }
1585
+ };
1586
+ const preBeforeLoadSetup = (inner, matchId, route) => {
1587
+ const existingMatch = inner.router.getMatch(matchId);
1588
+ if (!existingMatch._nonReactive.beforeLoadPromise && !existingMatch._nonReactive.loaderPromise) return;
1589
+ setupPendingTimeout(inner, matchId, route, existingMatch);
1590
+ const then = () => {
1591
+ const match = inner.router.getMatch(matchId);
1592
+ if (match.preload && (match.status === "redirected" || match.status === "notFound")) handleRedirectAndNotFound(inner, match, match.error);
1593
+ };
1594
+ return existingMatch._nonReactive.beforeLoadPromise ? existingMatch._nonReactive.beforeLoadPromise.then(then) : then();
1595
+ };
1596
+ const executeBeforeLoad = (inner, matchId, index, route) => {
1597
+ const match = inner.router.getMatch(matchId);
1598
+ let prevLoadPromise = match._nonReactive.loadPromise;
1599
+ match._nonReactive.loadPromise = createControlledPromise(() => {
1600
+ prevLoadPromise?.resolve();
1601
+ prevLoadPromise = void 0;
1602
+ });
1603
+ const { paramsError, searchError } = match;
1604
+ if (paramsError) handleSerialError(inner, index, paramsError, "PARSE_PARAMS");
1605
+ if (searchError) handleSerialError(inner, index, searchError, "VALIDATE_SEARCH");
1606
+ setupPendingTimeout(inner, matchId, route, match);
1607
+ const abortController = new AbortController();
1608
+ let isPending = false;
1609
+ const pending = () => {
1610
+ if (isPending) return;
1611
+ isPending = true;
1612
+ inner.updateMatch(matchId, (prev) => ({
1613
+ ...prev,
1614
+ isFetching: "beforeLoad",
1615
+ fetchCount: prev.fetchCount + 1,
1616
+ abortController
1617
+ }));
1618
+ };
1619
+ const resolve = () => {
1620
+ match._nonReactive.beforeLoadPromise?.resolve();
1621
+ match._nonReactive.beforeLoadPromise = void 0;
1622
+ inner.updateMatch(matchId, (prev) => ({
1623
+ ...prev,
1624
+ isFetching: false
1625
+ }));
1626
+ };
1627
+ if (!route.options.beforeLoad) {
1628
+ inner.router.batch(() => {
1629
+ pending();
1630
+ resolve();
1631
+ });
1632
+ return;
1633
+ }
1634
+ match._nonReactive.beforeLoadPromise = createControlledPromise();
1635
+ const context = {
1636
+ ...buildMatchContext(inner, index, false),
1637
+ ...match.__routeContext
1638
+ };
1639
+ const { search, params, cause } = match;
1640
+ const preload = resolvePreload(inner, matchId);
1641
+ const beforeLoadFnContext = {
1642
+ search,
1643
+ abortController,
1644
+ params,
1645
+ preload,
1646
+ context,
1647
+ location: inner.location,
1648
+ navigate: (opts) => inner.router.navigate({
1649
+ ...opts,
1650
+ _fromLocation: inner.location
1651
+ }),
1652
+ buildLocation: inner.router.buildLocation,
1653
+ cause: preload ? "preload" : cause,
1654
+ matches: inner.matches,
1655
+ routeId: route.id,
1656
+ ...inner.router.options.additionalContext
1657
+ };
1658
+ const updateContext = (beforeLoadContext2) => {
1659
+ if (beforeLoadContext2 === void 0) {
1660
+ inner.router.batch(() => {
1661
+ pending();
1662
+ resolve();
1663
+ });
1664
+ return;
1665
+ }
1666
+ if (isRedirect(beforeLoadContext2) || isNotFound(beforeLoadContext2)) {
1667
+ pending();
1668
+ handleSerialError(inner, index, beforeLoadContext2, "BEFORE_LOAD");
1669
+ }
1670
+ inner.router.batch(() => {
1671
+ pending();
1672
+ inner.updateMatch(matchId, (prev) => ({
1673
+ ...prev,
1674
+ __beforeLoadContext: beforeLoadContext2
1675
+ }));
1676
+ resolve();
1677
+ });
1678
+ };
1679
+ let beforeLoadContext;
1680
+ try {
1681
+ beforeLoadContext = route.options.beforeLoad(beforeLoadFnContext);
1682
+ if (isPromise(beforeLoadContext)) {
1683
+ pending();
1684
+ return beforeLoadContext.catch((err) => {
1685
+ handleSerialError(inner, index, err, "BEFORE_LOAD");
1686
+ }).then(updateContext);
1687
+ }
1688
+ } catch (err) {
1689
+ pending();
1690
+ handleSerialError(inner, index, err, "BEFORE_LOAD");
1691
+ }
1692
+ updateContext(beforeLoadContext);
1693
+ };
1694
+ const handleBeforeLoad = (inner, index) => {
1695
+ const { id: matchId, routeId } = inner.matches[index];
1696
+ const route = inner.router.looseRoutesById[routeId];
1697
+ const serverSsr = () => {
1698
+ {
1699
+ const maybePromise = isBeforeLoadSsr(inner, matchId, index, route);
1700
+ if (isPromise(maybePromise)) return maybePromise.then(queueExecution);
1701
+ }
1702
+ return queueExecution();
1703
+ };
1704
+ const execute = () => executeBeforeLoad(inner, matchId, index, route);
1705
+ const queueExecution = () => {
1706
+ if (shouldSkipLoader(inner, matchId)) return;
1707
+ const result = preBeforeLoadSetup(inner, matchId, route);
1708
+ return isPromise(result) ? result.then(execute) : execute();
1709
+ };
1710
+ return serverSsr();
1711
+ };
1712
+ const executeHead = (inner, matchId, route) => {
1713
+ const match = inner.router.getMatch(matchId);
1714
+ if (!match) return;
1715
+ if (!route.options.head && !route.options.scripts && !route.options.headers) return;
1716
+ const assetContext = {
1717
+ ssr: inner.router.options.ssr,
1718
+ matches: inner.matches,
1719
+ match,
1720
+ params: match.params,
1721
+ loaderData: match.loaderData
1722
+ };
1723
+ return Promise.all([
1724
+ route.options.head?.(assetContext),
1725
+ route.options.scripts?.(assetContext),
1726
+ route.options.headers?.(assetContext)
1727
+ ]).then(([headFnContent, scripts, headers]) => {
1728
+ return {
1729
+ meta: headFnContent?.meta,
1730
+ links: headFnContent?.links,
1731
+ headScripts: headFnContent?.scripts,
1732
+ headers,
1733
+ scripts,
1734
+ styles: headFnContent?.styles
1735
+ };
1736
+ });
1737
+ };
1738
+ const getLoaderContext = (inner, matchPromises, matchId, index, route) => {
1739
+ const parentMatchPromise = matchPromises[index - 1];
1740
+ const { params, loaderDeps, abortController, cause } = inner.router.getMatch(matchId);
1741
+ const context = buildMatchContext(inner, index);
1742
+ const preload = resolvePreload(inner, matchId);
1743
+ return {
1744
+ params,
1745
+ deps: loaderDeps,
1746
+ preload: !!preload,
1747
+ parentMatchPromise,
1748
+ abortController,
1749
+ context,
1750
+ location: inner.location,
1751
+ navigate: (opts) => inner.router.navigate({
1752
+ ...opts,
1753
+ _fromLocation: inner.location
1754
+ }),
1755
+ cause: preload ? "preload" : cause,
1756
+ route,
1757
+ ...inner.router.options.additionalContext
1758
+ };
1759
+ };
1760
+ const runLoader = async (inner, matchPromises, matchId, index, route) => {
1761
+ try {
1762
+ const match = inner.router.getMatch(matchId);
1763
+ try {
1764
+ if (!(isServer ?? inner.router.isServer) || match.ssr === true) loadRouteChunk(route);
1765
+ const routeLoader = route.options.loader;
1766
+ const loader = typeof routeLoader === "function" ? routeLoader : routeLoader?.handler;
1767
+ const loaderResult = loader?.(getLoaderContext(inner, matchPromises, matchId, index, route));
1768
+ const loaderResultIsPromise = !!loader && isPromise(loaderResult);
1769
+ if (!!(loaderResultIsPromise || route._lazyPromise || route._componentsPromise || route.options.head || route.options.scripts || route.options.headers || match._nonReactive.minPendingPromise)) inner.updateMatch(matchId, (prev) => ({
1770
+ ...prev,
1771
+ isFetching: "loader"
1772
+ }));
1773
+ if (loader) {
1774
+ const loaderData = loaderResultIsPromise ? await loaderResult : loaderResult;
1775
+ handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), loaderData);
1776
+ if (loaderData !== void 0) inner.updateMatch(matchId, (prev) => ({
1777
+ ...prev,
1778
+ loaderData
1779
+ }));
1780
+ }
1781
+ if (route._lazyPromise) await route._lazyPromise;
1782
+ const pendingPromise = match._nonReactive.minPendingPromise;
1783
+ if (pendingPromise) await pendingPromise;
1784
+ if (route._componentsPromise) await route._componentsPromise;
1785
+ inner.updateMatch(matchId, (prev) => ({
1786
+ ...prev,
1787
+ error: void 0,
1788
+ context: buildMatchContext(inner, index),
1789
+ status: "success",
1790
+ isFetching: false,
1791
+ updatedAt: Date.now()
1792
+ }));
1793
+ } catch (e) {
1794
+ let error = e;
1795
+ if (error?.name === "AbortError") {
1796
+ if (match.abortController.signal.aborted) {
1797
+ match._nonReactive.loaderPromise?.resolve();
1798
+ match._nonReactive.loaderPromise = void 0;
1799
+ return;
1800
+ }
1801
+ inner.updateMatch(matchId, (prev) => ({
1802
+ ...prev,
1803
+ status: prev.status === "pending" ? "success" : prev.status,
1804
+ isFetching: false,
1805
+ context: buildMatchContext(inner, index)
1806
+ }));
1807
+ return;
1808
+ }
1809
+ const pendingPromise = match._nonReactive.minPendingPromise;
1810
+ if (pendingPromise) await pendingPromise;
1811
+ if (isNotFound(e)) await route.options.notFoundComponent?.preload?.();
1812
+ handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), e);
1813
+ try {
1814
+ route.options.onError?.(e);
1815
+ } catch (onErrorError) {
1816
+ error = onErrorError;
1817
+ handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), onErrorError);
1818
+ }
1819
+ if (!isRedirect(error) && !isNotFound(error)) await loadRouteChunk(route, ["errorComponent"]);
1820
+ inner.updateMatch(matchId, (prev) => ({
1821
+ ...prev,
1822
+ error,
1823
+ context: buildMatchContext(inner, index),
1824
+ status: "error",
1825
+ isFetching: false
1826
+ }));
1827
+ }
1828
+ } catch (err) {
1829
+ const match = inner.router.getMatch(matchId);
1830
+ if (match) match._nonReactive.loaderPromise = void 0;
1831
+ handleRedirectAndNotFound(inner, match, err);
1832
+ }
1833
+ };
1834
+ const loadRouteMatch = async (inner, matchPromises, index) => {
1835
+ async function handleLoader(preload, prevMatch, previousRouteMatchId, match2, route2) {
1836
+ const age = Date.now() - prevMatch.updatedAt;
1837
+ const staleAge = preload ? route2.options.preloadStaleTime ?? inner.router.options.defaultPreloadStaleTime ?? 3e4 : route2.options.staleTime ?? inner.router.options.defaultStaleTime ?? 0;
1838
+ const shouldReloadOption = route2.options.shouldReload;
1839
+ const shouldReload = typeof shouldReloadOption === "function" ? shouldReloadOption(getLoaderContext(inner, matchPromises, matchId, index, route2)) : shouldReloadOption;
1840
+ const { status, invalid } = match2;
1841
+ const staleMatchShouldReload = age >= staleAge && (!!inner.forceStaleReload || match2.cause === "enter" || previousRouteMatchId !== void 0 && previousRouteMatchId !== match2.id);
1842
+ loaderShouldRunAsync = status === "success" && (invalid || (shouldReload ?? staleMatchShouldReload));
1843
+ if (preload && route2.options.preload === false) ;
1844
+ else if (loaderShouldRunAsync && !inner.sync && shouldReloadInBackground) {
1845
+ loaderIsRunningAsync = true;
1846
+ (async () => {
1847
+ try {
1848
+ await runLoader(inner, matchPromises, matchId, index, route2);
1849
+ const match3 = inner.router.getMatch(matchId);
1850
+ match3._nonReactive.loaderPromise?.resolve();
1851
+ match3._nonReactive.loadPromise?.resolve();
1852
+ match3._nonReactive.loaderPromise = void 0;
1853
+ match3._nonReactive.loadPromise = void 0;
1854
+ } catch (err) {
1855
+ if (isRedirect(err)) await inner.router.navigate(err.options);
1856
+ }
1857
+ })();
1858
+ } else if (status !== "success" || loaderShouldRunAsync) await runLoader(inner, matchPromises, matchId, index, route2);
1859
+ else syncMatchContext(inner, matchId, index);
1860
+ }
1861
+ const { id: matchId, routeId } = inner.matches[index];
1862
+ let loaderShouldRunAsync = false;
1863
+ let loaderIsRunningAsync = false;
1864
+ const route = inner.router.looseRoutesById[routeId];
1865
+ const routeLoader = route.options.loader;
1866
+ const shouldReloadInBackground = ((typeof routeLoader === "function" ? void 0 : routeLoader?.staleReloadMode) ?? inner.router.options.defaultStaleReloadMode) !== "blocking";
1867
+ if (shouldSkipLoader(inner, matchId)) {
1868
+ if (!inner.router.getMatch(matchId)) return inner.matches[index];
1869
+ syncMatchContext(inner, matchId, index);
1870
+ return inner.router.getMatch(matchId);
1871
+ } else {
1872
+ const prevMatch = inner.router.getMatch(matchId);
1873
+ const activeIdAtIndex = inner.router.stores.matchesId.get()[index];
1874
+ const previousRouteMatchId = (activeIdAtIndex && inner.router.stores.matchStores.get(activeIdAtIndex) || null)?.routeId === routeId ? activeIdAtIndex : inner.router.stores.matches.get().find((d) => d.routeId === routeId)?.id;
1875
+ const preload = resolvePreload(inner, matchId);
1876
+ if (prevMatch._nonReactive.loaderPromise) {
1877
+ if (prevMatch.status === "success" && !inner.sync && !prevMatch.preload && shouldReloadInBackground) return prevMatch;
1878
+ await prevMatch._nonReactive.loaderPromise;
1879
+ const match2 = inner.router.getMatch(matchId);
1880
+ const error = match2._nonReactive.error || match2.error;
1881
+ if (error) handleRedirectAndNotFound(inner, match2, error);
1882
+ if (match2.status === "pending") await handleLoader(preload, prevMatch, previousRouteMatchId, match2, route);
1883
+ } else {
1884
+ const nextPreload = preload && !inner.router.stores.matchStores.has(matchId);
1885
+ const match2 = inner.router.getMatch(matchId);
1886
+ match2._nonReactive.loaderPromise = createControlledPromise();
1887
+ if (nextPreload !== match2.preload) inner.updateMatch(matchId, (prev) => ({
1888
+ ...prev,
1889
+ preload: nextPreload
1890
+ }));
1891
+ await handleLoader(preload, prevMatch, previousRouteMatchId, match2, route);
1892
+ }
1893
+ }
1894
+ const match = inner.router.getMatch(matchId);
1895
+ if (!loaderIsRunningAsync) {
1896
+ match._nonReactive.loaderPromise?.resolve();
1897
+ match._nonReactive.loadPromise?.resolve();
1898
+ match._nonReactive.loadPromise = void 0;
1899
+ }
1900
+ clearTimeout(match._nonReactive.pendingTimeout);
1901
+ match._nonReactive.pendingTimeout = void 0;
1902
+ if (!loaderIsRunningAsync) match._nonReactive.loaderPromise = void 0;
1903
+ match._nonReactive.dehydrated = void 0;
1904
+ const nextIsFetching = loaderIsRunningAsync ? match.isFetching : false;
1905
+ if (nextIsFetching !== match.isFetching || match.invalid !== false) {
1906
+ inner.updateMatch(matchId, (prev) => ({
1907
+ ...prev,
1908
+ isFetching: nextIsFetching,
1909
+ invalid: false
1910
+ }));
1911
+ return inner.router.getMatch(matchId);
1912
+ } else return match;
1913
+ };
1914
+ async function loadMatches(arg) {
1915
+ const inner = arg;
1916
+ const matchPromises = [];
1917
+ let beforeLoadNotFound;
1918
+ for (let i = 0; i < inner.matches.length; i++) {
1919
+ try {
1920
+ const beforeLoad = handleBeforeLoad(inner, i);
1921
+ if (isPromise(beforeLoad)) await beforeLoad;
1922
+ } catch (err) {
1923
+ if (isRedirect(err)) throw err;
1924
+ if (isNotFound(err)) beforeLoadNotFound = err;
1925
+ else if (!inner.preload) throw err;
1926
+ break;
1927
+ }
1928
+ if (inner.serialError || inner.firstBadMatchIndex != null) break;
1929
+ }
1930
+ const baseMaxIndexExclusive = inner.firstBadMatchIndex ?? inner.matches.length;
1931
+ const boundaryIndex = beforeLoadNotFound && !inner.preload ? getNotFoundBoundaryIndex(inner, beforeLoadNotFound) : void 0;
1932
+ const maxIndexExclusive = beforeLoadNotFound && inner.preload ? 0 : boundaryIndex !== void 0 ? Math.min(boundaryIndex + 1, baseMaxIndexExclusive) : baseMaxIndexExclusive;
1933
+ let firstNotFound;
1934
+ let firstUnhandledRejection;
1935
+ for (let i = 0; i < maxIndexExclusive; i++) matchPromises.push(loadRouteMatch(inner, matchPromises, i));
1936
+ try {
1937
+ await Promise.all(matchPromises);
1938
+ } catch {
1939
+ const settled = await Promise.allSettled(matchPromises);
1940
+ for (const result of settled) {
1941
+ if (result.status !== "rejected") continue;
1942
+ const reason = result.reason;
1943
+ if (isRedirect(reason)) throw reason;
1944
+ if (isNotFound(reason)) firstNotFound ??= reason;
1945
+ else firstUnhandledRejection ??= reason;
1946
+ }
1947
+ if (firstUnhandledRejection !== void 0) throw firstUnhandledRejection;
1948
+ }
1949
+ const notFoundToThrow = firstNotFound ?? (beforeLoadNotFound && !inner.preload ? beforeLoadNotFound : void 0);
1950
+ let headMaxIndex = inner.firstBadMatchIndex !== void 0 ? inner.firstBadMatchIndex : inner.matches.length - 1;
1951
+ if (!notFoundToThrow && beforeLoadNotFound && inner.preload) return inner.matches;
1952
+ if (notFoundToThrow) {
1953
+ const renderedBoundaryIndex = getNotFoundBoundaryIndex(inner, notFoundToThrow);
1954
+ if (renderedBoundaryIndex === void 0) {
1955
+ invariant();
1956
+ }
1957
+ const boundaryMatch = inner.matches[renderedBoundaryIndex];
1958
+ const boundaryRoute = inner.router.looseRoutesById[boundaryMatch.routeId];
1959
+ const defaultNotFoundComponent = inner.router.options?.defaultNotFoundComponent;
1960
+ if (!boundaryRoute.options.notFoundComponent && defaultNotFoundComponent) boundaryRoute.options.notFoundComponent = defaultNotFoundComponent;
1961
+ notFoundToThrow.routeId = boundaryMatch.routeId;
1962
+ const boundaryIsRoot = boundaryMatch.routeId === inner.router.routeTree.id;
1963
+ inner.updateMatch(boundaryMatch.id, (prev) => ({
1964
+ ...prev,
1965
+ ...boundaryIsRoot ? {
1966
+ status: "success",
1967
+ globalNotFound: true,
1968
+ error: void 0
1969
+ } : {
1970
+ status: "notFound",
1971
+ error: notFoundToThrow
1972
+ },
1973
+ isFetching: false
1974
+ }));
1975
+ headMaxIndex = renderedBoundaryIndex;
1976
+ await loadRouteChunk(boundaryRoute, ["notFoundComponent"]);
1977
+ } else if (!inner.preload) {
1978
+ const rootMatch = inner.matches[0];
1979
+ if (!rootMatch.globalNotFound) {
1980
+ if (inner.router.getMatch(rootMatch.id)?.globalNotFound) inner.updateMatch(rootMatch.id, (prev) => ({
1981
+ ...prev,
1982
+ globalNotFound: false,
1983
+ error: void 0
1984
+ }));
1985
+ }
1986
+ }
1987
+ if (inner.serialError && inner.firstBadMatchIndex !== void 0) {
1988
+ const errorRoute = inner.router.looseRoutesById[inner.matches[inner.firstBadMatchIndex].routeId];
1989
+ await loadRouteChunk(errorRoute, ["errorComponent"]);
1990
+ }
1991
+ for (let i = 0; i <= headMaxIndex; i++) {
1992
+ const { id: matchId, routeId } = inner.matches[i];
1993
+ const route = inner.router.looseRoutesById[routeId];
1994
+ try {
1995
+ const headResult = executeHead(inner, matchId, route);
1996
+ if (headResult) {
1997
+ const head = await headResult;
1998
+ inner.updateMatch(matchId, (prev) => ({
1999
+ ...prev,
2000
+ ...head
2001
+ }));
2002
+ }
2003
+ } catch (err) {
2004
+ console.error(`Error executing head for route ${routeId}:`, err);
2005
+ }
2006
+ }
2007
+ const readyPromise = triggerOnReady(inner);
2008
+ if (isPromise(readyPromise)) await readyPromise;
2009
+ if (notFoundToThrow) throw notFoundToThrow;
2010
+ if (inner.serialError && !inner.preload && !inner.onReady) throw inner.serialError;
2011
+ return inner.matches;
2012
+ }
2013
+ function preloadRouteComponents(route, componentTypesToLoad) {
2014
+ const preloads = componentTypesToLoad.map((type) => route.options[type]?.preload?.()).filter(Boolean);
2015
+ if (preloads.length === 0) return void 0;
2016
+ return Promise.all(preloads);
2017
+ }
2018
+ function loadRouteChunk(route, componentTypesToLoad = componentTypes) {
2019
+ if (!route._lazyLoaded && route._lazyPromise === void 0) if (route.lazyFn) route._lazyPromise = route.lazyFn().then((lazyRoute) => {
2020
+ const { id: _id, ...options } = lazyRoute.options;
2021
+ Object.assign(route.options, options);
2022
+ route._lazyLoaded = true;
2023
+ route._lazyPromise = void 0;
2024
+ });
2025
+ else route._lazyLoaded = true;
2026
+ const runAfterLazy = () => route._componentsLoaded ? void 0 : componentTypesToLoad === componentTypes ? (() => {
2027
+ if (route._componentsPromise === void 0) {
2028
+ const componentsPromise = preloadRouteComponents(route, componentTypes);
2029
+ if (componentsPromise) route._componentsPromise = componentsPromise.then(() => {
2030
+ route._componentsLoaded = true;
2031
+ route._componentsPromise = void 0;
2032
+ });
2033
+ else route._componentsLoaded = true;
2034
+ }
2035
+ return route._componentsPromise;
2036
+ })() : preloadRouteComponents(route, componentTypesToLoad);
2037
+ return route._lazyPromise ? route._lazyPromise.then(runAfterLazy) : runAfterLazy();
2038
+ }
2039
+ function makeMaybe(value, error) {
2040
+ if (error) return {
2041
+ status: "error",
2042
+ error
2043
+ };
2044
+ return {
2045
+ status: "success",
2046
+ value
2047
+ };
2048
+ }
2049
+ function routeNeedsPreload(route) {
2050
+ for (const componentType of componentTypes) if (route.options[componentType]?.preload) return true;
2051
+ return false;
2052
+ }
2053
+ const componentTypes = [
2054
+ "component",
2055
+ "errorComponent",
2056
+ "pendingComponent",
2057
+ "notFoundComponent"
2058
+ ];
2059
+ function getLocationChangeInfo(location, resolvedLocation) {
2060
+ const fromLocation = resolvedLocation;
2061
+ const toLocation = location;
2062
+ return {
2063
+ fromLocation,
2064
+ toLocation,
2065
+ pathChanged: fromLocation?.pathname !== toLocation.pathname,
2066
+ hrefChanged: fromLocation?.href !== toLocation.href,
2067
+ hashChanged: fromLocation?.hash !== toLocation.hash
2068
+ };
2069
+ }
2070
+ var RouterCore = class {
2071
+ /**
2072
+ * @deprecated Use the `createRouter` function instead
2073
+ */
2074
+ constructor(options, getStoreConfig) {
2075
+ this.tempLocationKey = `${Math.round(Math.random() * 1e7)}`;
2076
+ this.resetNextScroll = true;
2077
+ this.shouldViewTransition = void 0;
2078
+ this.isViewTransitionTypesSupported = void 0;
2079
+ this.subscribers = /* @__PURE__ */ new Set();
2080
+ this.isScrollRestoring = false;
2081
+ this.isScrollRestorationSetup = false;
2082
+ this.routeBranchCache = /* @__PURE__ */ new WeakMap();
2083
+ this.startTransition = (fn) => fn();
2084
+ this.update = (newOptions) => {
2085
+ const prevOptions = this.options;
2086
+ const prevBasepath = this.basepath ?? prevOptions?.basepath ?? "/";
2087
+ const basepathWasUnset = this.basepath === void 0;
2088
+ const prevRewriteOption = prevOptions?.rewrite;
2089
+ this.options = {
2090
+ ...prevOptions,
2091
+ ...newOptions
2092
+ };
2093
+ this.isServer = this.options.isServer ?? typeof document === "undefined";
2094
+ this.protocolAllowlist = new Set(this.options.protocolAllowlist);
2095
+ if (this.options.pathParamsAllowedCharacters) this.pathParamsDecoder = compileDecodeCharMap(this.options.pathParamsAllowedCharacters);
2096
+ if (!this.history || this.options.history && this.options.history !== this.history) if (!this.options.history) ;
2097
+ else this.history = this.options.history;
2098
+ this.origin = this.options.origin;
2099
+ if (!this.origin) this.origin = "http://localhost";
2100
+ if (this.history) this.updateLatestLocation();
2101
+ if (this.options.routeTree !== this.routeTree) {
2102
+ this.routeTree = this.options.routeTree;
2103
+ let processRouteTreeResult;
2104
+ if (globalThis.__TSR_CACHE__ && globalThis.__TSR_CACHE__.routeTree === this.routeTree) {
2105
+ const cached = globalThis.__TSR_CACHE__;
2106
+ this.resolvePathCache = cached.resolvePathCache;
2107
+ processRouteTreeResult = cached.processRouteTreeResult;
2108
+ } else {
2109
+ this.resolvePathCache = createLRUCache(1e3);
2110
+ processRouteTreeResult = this.buildRouteTree();
2111
+ if (globalThis.__TSR_CACHE__ === void 0) globalThis.__TSR_CACHE__ = {
2112
+ routeTree: this.routeTree,
2113
+ processRouteTreeResult,
2114
+ resolvePathCache: this.resolvePathCache
2115
+ };
2116
+ }
2117
+ this.setRoutes(processRouteTreeResult);
2118
+ }
2119
+ if (!this.stores && this.latestLocation) {
2120
+ const config = this.getStoreConfig(this);
2121
+ this.batch = config.batch;
2122
+ this.stores = createRouterStores(getInitialRouterState(this.latestLocation), config);
2123
+ }
2124
+ let needsLocationUpdate = false;
2125
+ const nextBasepath = this.options.basepath ?? "/";
2126
+ const nextRewriteOption = this.options.rewrite;
2127
+ if (basepathWasUnset || prevBasepath !== nextBasepath || prevRewriteOption !== nextRewriteOption) {
2128
+ this.basepath = nextBasepath;
2129
+ const rewrites = [];
2130
+ const trimmed = trimPath(nextBasepath);
2131
+ if (trimmed && trimmed !== "/") rewrites.push(rewriteBasepath({ basepath: nextBasepath }));
2132
+ if (nextRewriteOption) rewrites.push(nextRewriteOption);
2133
+ this.rewrite = rewrites.length === 0 ? void 0 : rewrites.length === 1 ? rewrites[0] : composeRewrites(rewrites);
2134
+ if (this.history) this.updateLatestLocation();
2135
+ needsLocationUpdate = true;
2136
+ }
2137
+ if (needsLocationUpdate && this.stores) this.stores.location.set(this.latestLocation);
2138
+ if (typeof window !== "undefined" && "CSS" in window && typeof window.CSS?.supports === "function") this.isViewTransitionTypesSupported = window.CSS.supports("selector(:active-view-transition-type(a))");
2139
+ };
2140
+ this.updateLatestLocation = () => {
2141
+ this.latestLocation = this.parseLocation(this.history.location, this.latestLocation);
2142
+ };
2143
+ this.buildRouteTree = () => {
2144
+ const result = processRouteTree(this.routeTree, this.options.caseSensitive, (route, i) => {
2145
+ route.init({ originalIndex: i });
2146
+ });
2147
+ if (this.options.routeMasks) processRouteMasks(this.options.routeMasks, result.processedTree);
2148
+ return result;
2149
+ };
2150
+ this.subscribe = (eventType, fn) => {
2151
+ const listener = {
2152
+ eventType,
2153
+ fn
2154
+ };
2155
+ this.subscribers.add(listener);
2156
+ return () => {
2157
+ this.subscribers.delete(listener);
2158
+ };
2159
+ };
2160
+ this.emit = (routerEvent) => {
2161
+ this.subscribers.forEach((listener) => {
2162
+ if (listener.eventType === routerEvent.type) listener.fn(routerEvent);
2163
+ });
2164
+ };
2165
+ this.parseLocation = (locationToParse, previousLocation) => {
2166
+ const parse = ({ pathname, search, hash, href, state }) => {
2167
+ if (!this.rewrite && !/[ \x00-\x1f\x7f\u0080-\uffff]/.test(pathname)) {
2168
+ const parsedSearch2 = this.options.parseSearch(search);
2169
+ const searchStr2 = this.options.stringifySearch(parsedSearch2);
2170
+ return {
2171
+ href: pathname + searchStr2 + hash,
2172
+ publicHref: pathname + searchStr2 + hash,
2173
+ pathname: decodePath(pathname).path,
2174
+ external: false,
2175
+ searchStr: searchStr2,
2176
+ search: nullReplaceEqualDeep(previousLocation?.search, parsedSearch2),
2177
+ hash: decodePath(hash.slice(1)).path,
2178
+ state: replaceEqualDeep(previousLocation?.state, state)
2179
+ };
2180
+ }
2181
+ const fullUrl = new URL(href, this.origin);
2182
+ const url = executeRewriteInput(this.rewrite, fullUrl);
2183
+ const parsedSearch = this.options.parseSearch(url.search);
2184
+ const searchStr = this.options.stringifySearch(parsedSearch);
2185
+ url.search = searchStr;
2186
+ return {
2187
+ href: url.href.replace(url.origin, ""),
2188
+ publicHref: href,
2189
+ pathname: decodePath(url.pathname).path,
2190
+ external: !!this.rewrite && url.origin !== this.origin,
2191
+ searchStr,
2192
+ search: nullReplaceEqualDeep(previousLocation?.search, parsedSearch),
2193
+ hash: decodePath(url.hash.slice(1)).path,
2194
+ state: replaceEqualDeep(previousLocation?.state, state)
2195
+ };
2196
+ };
2197
+ const location = parse(locationToParse);
2198
+ const { __tempLocation, __tempKey } = location.state;
2199
+ if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
2200
+ const parsedTempLocation = parse(__tempLocation);
2201
+ parsedTempLocation.state.key = location.state.key;
2202
+ parsedTempLocation.state.__TSR_key = location.state.__TSR_key;
2203
+ delete parsedTempLocation.state.__tempLocation;
2204
+ return {
2205
+ ...parsedTempLocation,
2206
+ maskedLocation: location
2207
+ };
2208
+ }
2209
+ return location;
2210
+ };
2211
+ this.resolvePathWithBase = (from, path) => {
2212
+ return resolvePath({
2213
+ base: from,
2214
+ to: path.includes("//") ? cleanPath(path) : path,
2215
+ trailingSlash: this.options.trailingSlash,
2216
+ cache: this.resolvePathCache
2217
+ });
2218
+ };
2219
+ this.matchRoutes = (pathnameOrNext, locationSearchOrOpts, opts) => {
2220
+ if (typeof pathnameOrNext === "string") return this.matchRoutesInternal({
2221
+ pathname: pathnameOrNext,
2222
+ search: locationSearchOrOpts
2223
+ }, opts);
2224
+ return this.matchRoutesInternal(pathnameOrNext, locationSearchOrOpts);
2225
+ };
2226
+ this.getMatchedRoutes = (pathname) => {
2227
+ return getMatchedRoutes({
2228
+ pathname,
2229
+ routesById: this.routesById,
2230
+ processedTree: this.processedTree
2231
+ });
2232
+ };
2233
+ this.cancelMatch = (id) => {
2234
+ const match = this.getMatch(id);
2235
+ if (!match) return;
2236
+ match.abortController.abort();
2237
+ clearTimeout(match._nonReactive.pendingTimeout);
2238
+ match._nonReactive.pendingTimeout = void 0;
2239
+ };
2240
+ this.cancelMatches = () => {
2241
+ this.stores.pendingIds.get().forEach((matchId) => {
2242
+ this.cancelMatch(matchId);
2243
+ });
2244
+ this.stores.matchesId.get().forEach((matchId) => {
2245
+ if (this.stores.pendingMatchStores.has(matchId)) return;
2246
+ const match = this.stores.matchStores.get(matchId)?.get();
2247
+ if (!match) return;
2248
+ if (match.status === "pending" || match.isFetching === "loader") this.cancelMatch(matchId);
2249
+ });
2250
+ };
2251
+ this.buildLocation = (opts) => {
2252
+ const build = (dest = {}) => {
2253
+ const currentLocation = dest._fromLocation || this.pendingBuiltLocation || this.latestLocation;
2254
+ const lightweightResult = this.matchRoutesLightweight(currentLocation);
2255
+ if (dest.from && false) ;
2256
+ const defaultedFromPath = dest.unsafeRelative === "path" ? currentLocation.pathname : dest.from ?? lightweightResult.fullPath;
2257
+ const destTo = dest.to ? `${dest.to}` : void 0;
2258
+ const fromSearch = lightweightResult.search;
2259
+ const fromParams = Object.assign(/* @__PURE__ */ Object.create(null), lightweightResult.params);
2260
+ const sourcePath = destTo?.charCodeAt(0) === 47 ? "/" : this.resolvePathWithBase(defaultedFromPath, ".");
2261
+ const nextTo = destTo ? this.resolvePathWithBase(sourcePath, destTo) : sourcePath;
2262
+ const nextParams = dest.params === false || dest.params === null ? /* @__PURE__ */ Object.create(null) : (dest.params ?? true) === true ? fromParams : Object.assign(fromParams, functionalUpdate(dest.params, fromParams));
2263
+ const destRoute = this.routesByPath[trimPathRight(nextTo)];
2264
+ let destRoutes;
2265
+ if (destRoute) destRoutes = this.getRouteBranch(destRoute);
2266
+ else if (nextTo.includes("$")) destRoutes = [];
2267
+ else {
2268
+ const destMatchResult = this.getMatchedRoutes(nextTo);
2269
+ destRoutes = destMatchResult.matchedRoutes;
2270
+ if (this.options.notFoundRoute && (!destMatchResult.foundRoute || destMatchResult.foundRoute.path !== "/" && destMatchResult.routeParams["**"])) destRoutes = [...destRoutes, this.options.notFoundRoute];
2271
+ }
2272
+ if (destRoutes.length && hasKeys(nextParams)) for (const route of destRoutes) {
2273
+ const fn = route.options.params?.stringify ?? route.options.stringifyParams;
2274
+ if (fn) try {
2275
+ Object.assign(nextParams, fn(nextParams));
2276
+ } catch {
2277
+ }
2278
+ }
2279
+ const nextPathname = opts.leaveParams ? nextTo : decodePath(interpolatePath({
2280
+ path: nextTo,
2281
+ params: nextParams,
2282
+ decoder: this.pathParamsDecoder,
2283
+ server: this.isServer
2284
+ }).interpolatedPath).path;
2285
+ let nextSearch = fromSearch;
2286
+ if (opts._includeValidateSearch && this.options.search?.strict) {
2287
+ const validatedSearch = {};
2288
+ destRoutes.forEach((route) => {
2289
+ if (route.options.validateSearch) try {
2290
+ Object.assign(validatedSearch, validateSearch(route.options.validateSearch, {
2291
+ ...validatedSearch,
2292
+ ...nextSearch
2293
+ }));
2294
+ } catch {
2295
+ }
2296
+ });
2297
+ nextSearch = validatedSearch;
2298
+ }
2299
+ nextSearch = applySearchMiddleware({
2300
+ search: nextSearch,
2301
+ dest,
2302
+ destRoutes,
2303
+ _includeValidateSearch: opts._includeValidateSearch
2304
+ });
2305
+ nextSearch = nullReplaceEqualDeep(fromSearch, nextSearch);
2306
+ const searchStr = this.options.stringifySearch(nextSearch);
2307
+ const hash = dest.hash === true ? currentLocation.hash : dest.hash ? functionalUpdate(dest.hash, currentLocation.hash) : void 0;
2308
+ const hashStr = hash ? `#${hash}` : "";
2309
+ let nextState = dest.state === true ? currentLocation.state : dest.state ? functionalUpdate(dest.state, currentLocation.state) : {};
2310
+ nextState = replaceEqualDeep(currentLocation.state, nextState);
2311
+ const fullPath = `${nextPathname}${searchStr}${hashStr}`;
2312
+ let href;
2313
+ let publicHref;
2314
+ let external = false;
2315
+ if (this.rewrite) {
2316
+ const url = new URL(fullPath, this.origin);
2317
+ const rewrittenUrl = executeRewriteOutput(this.rewrite, url);
2318
+ href = url.href.replace(url.origin, "");
2319
+ if (rewrittenUrl.origin !== this.origin) {
2320
+ publicHref = rewrittenUrl.href;
2321
+ external = true;
2322
+ } else publicHref = rewrittenUrl.pathname + rewrittenUrl.search + rewrittenUrl.hash;
2323
+ } else {
2324
+ href = encodePathLikeUrl(fullPath);
2325
+ publicHref = href;
2326
+ }
2327
+ return {
2328
+ publicHref,
2329
+ href,
2330
+ pathname: nextPathname,
2331
+ search: nextSearch,
2332
+ searchStr,
2333
+ state: nextState,
2334
+ hash: hash ?? "",
2335
+ external,
2336
+ unmaskOnReload: dest.unmaskOnReload
2337
+ };
2338
+ };
2339
+ const buildWithMatches = (dest = {}, maskedDest) => {
2340
+ const next = build(dest);
2341
+ let maskedNext = maskedDest ? build(maskedDest) : void 0;
2342
+ if (!maskedNext) {
2343
+ const params = /* @__PURE__ */ Object.create(null);
2344
+ if (this.options.routeMasks) {
2345
+ const match = findFlatMatch(next.pathname, this.processedTree);
2346
+ if (match) {
2347
+ Object.assign(params, match.rawParams);
2348
+ const { from: _from, params: maskParams, ...maskProps } = match.route;
2349
+ const nextParams = maskParams === false || maskParams === null ? /* @__PURE__ */ Object.create(null) : (maskParams ?? true) === true ? params : Object.assign(params, functionalUpdate(maskParams, params));
2350
+ maskedDest = {
2351
+ from: opts.from,
2352
+ ...maskProps,
2353
+ params: nextParams
2354
+ };
2355
+ maskedNext = build(maskedDest);
2356
+ }
2357
+ }
2358
+ }
2359
+ if (maskedNext) next.maskedLocation = maskedNext;
2360
+ return next;
2361
+ };
2362
+ if (opts.mask) return buildWithMatches(opts, {
2363
+ from: opts.from,
2364
+ ...opts.mask
2365
+ });
2366
+ return buildWithMatches(opts);
2367
+ };
2368
+ this.commitLocation = async ({ viewTransition, ignoreBlocker, ...next }) => {
2369
+ const isSameState = () => {
2370
+ const ignoredProps = [
2371
+ "key",
2372
+ "__TSR_key",
2373
+ "__TSR_index",
2374
+ "__hashScrollIntoViewOptions"
2375
+ ];
2376
+ ignoredProps.forEach((prop) => {
2377
+ next.state[prop] = this.latestLocation.state[prop];
2378
+ });
2379
+ const isEqual = deepEqual(next.state, this.latestLocation.state);
2380
+ ignoredProps.forEach((prop) => {
2381
+ delete next.state[prop];
2382
+ });
2383
+ return isEqual;
2384
+ };
2385
+ const isSameUrl = trimPathRight(this.latestLocation.href) === trimPathRight(next.href);
2386
+ let previousCommitPromise = this.commitLocationPromise;
2387
+ this.commitLocationPromise = createControlledPromise(() => {
2388
+ previousCommitPromise?.resolve();
2389
+ previousCommitPromise = void 0;
2390
+ });
2391
+ if (isSameUrl && isSameState()) this.load();
2392
+ else {
2393
+ let { maskedLocation, hashScrollIntoView, ...nextHistory } = next;
2394
+ if (maskedLocation) {
2395
+ nextHistory = {
2396
+ ...maskedLocation,
2397
+ state: {
2398
+ ...maskedLocation.state,
2399
+ __tempKey: void 0,
2400
+ __tempLocation: {
2401
+ ...nextHistory,
2402
+ search: nextHistory.searchStr,
2403
+ state: {
2404
+ ...nextHistory.state,
2405
+ __tempKey: void 0,
2406
+ __tempLocation: void 0,
2407
+ __TSR_key: void 0,
2408
+ key: void 0
2409
+ }
2410
+ }
2411
+ }
2412
+ };
2413
+ if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload ?? false) nextHistory.state.__tempKey = this.tempLocationKey;
2414
+ }
2415
+ nextHistory.state.__hashScrollIntoViewOptions = hashScrollIntoView ?? this.options.defaultHashScrollIntoView ?? true;
2416
+ this.shouldViewTransition = viewTransition;
2417
+ this.history[next.replace ? "replace" : "push"](nextHistory.publicHref, nextHistory.state, { ignoreBlocker });
2418
+ }
2419
+ this.resetNextScroll = next.resetScroll ?? true;
2420
+ if (!this.history.subscribers.size) this.load();
2421
+ return this.commitLocationPromise;
2422
+ };
2423
+ this.buildAndCommitLocation = ({ replace, resetScroll, hashScrollIntoView, viewTransition, ignoreBlocker, href, ...rest } = {}) => {
2424
+ if (href) {
2425
+ const currentIndex = this.history.location.state.__TSR_index;
2426
+ const parsed = parseHref(href, { __TSR_index: replace ? currentIndex : currentIndex + 1 });
2427
+ const hrefUrl = new URL(parsed.pathname, this.origin);
2428
+ rest.to = executeRewriteInput(this.rewrite, hrefUrl).pathname;
2429
+ rest.search = this.options.parseSearch(parsed.search);
2430
+ rest.hash = parsed.hash.slice(1);
2431
+ }
2432
+ const location = this.buildLocation({
2433
+ ...rest,
2434
+ _includeValidateSearch: true
2435
+ });
2436
+ this.pendingBuiltLocation = location;
2437
+ const commitPromise = this.commitLocation({
2438
+ ...location,
2439
+ viewTransition,
2440
+ replace,
2441
+ resetScroll,
2442
+ hashScrollIntoView,
2443
+ ignoreBlocker
2444
+ });
2445
+ Promise.resolve().then(() => {
2446
+ if (this.pendingBuiltLocation === location) this.pendingBuiltLocation = void 0;
2447
+ });
2448
+ return commitPromise;
2449
+ };
2450
+ this.navigate = async ({ to, reloadDocument, href, publicHref, ...rest }) => {
2451
+ let hrefIsUrl = false;
2452
+ if (href) try {
2453
+ new URL(`${href}`);
2454
+ hrefIsUrl = true;
2455
+ } catch {
2456
+ }
2457
+ if (hrefIsUrl && !reloadDocument) reloadDocument = true;
2458
+ if (reloadDocument) {
2459
+ if (to !== void 0 || !href) {
2460
+ const location = this.buildLocation({
2461
+ to,
2462
+ ...rest
2463
+ });
2464
+ href = href ?? location.publicHref;
2465
+ publicHref = publicHref ?? location.publicHref;
2466
+ }
2467
+ const reloadHref = !hrefIsUrl && publicHref ? publicHref : href;
2468
+ if (isDangerousProtocol(reloadHref, this.protocolAllowlist)) {
2469
+ return Promise.resolve();
2470
+ }
2471
+ if (!rest.ignoreBlocker) {
2472
+ const blockers = this.history.getBlockers?.() ?? [];
2473
+ for (const blocker of blockers) if (blocker?.blockerFn) {
2474
+ if (await blocker.blockerFn({
2475
+ currentLocation: this.latestLocation,
2476
+ nextLocation: this.latestLocation,
2477
+ action: "PUSH"
2478
+ })) return Promise.resolve();
2479
+ }
2480
+ }
2481
+ if (rest.replace) window.location.replace(reloadHref);
2482
+ else window.location.href = reloadHref;
2483
+ return Promise.resolve();
2484
+ }
2485
+ return this.buildAndCommitLocation({
2486
+ ...rest,
2487
+ href,
2488
+ to,
2489
+ _isNavigate: true
2490
+ });
2491
+ };
2492
+ this.beforeLoad = () => {
2493
+ this.cancelMatches();
2494
+ this.updateLatestLocation();
2495
+ {
2496
+ const nextLocation = this.buildLocation({
2497
+ to: this.latestLocation.pathname,
2498
+ search: true,
2499
+ params: true,
2500
+ hash: true,
2501
+ state: true,
2502
+ _includeValidateSearch: true
2503
+ });
2504
+ if (this.latestLocation.publicHref !== nextLocation.publicHref) {
2505
+ const href = this.getParsedLocationHref(nextLocation);
2506
+ if (nextLocation.external) throw redirect({ href });
2507
+ else throw redirect({
2508
+ href,
2509
+ _builtLocation: nextLocation
2510
+ });
2511
+ }
2512
+ }
2513
+ const pendingMatches = this.matchRoutes(this.latestLocation);
2514
+ const nextCachedMatches = this.stores.cachedMatches.get().filter((d) => !pendingMatches.some((e) => e.id === d.id));
2515
+ this.batch(() => {
2516
+ this.stores.status.set("pending");
2517
+ this.stores.statusCode.set(200);
2518
+ this.stores.isLoading.set(true);
2519
+ this.stores.location.set(this.latestLocation);
2520
+ this.stores.setPending(pendingMatches);
2521
+ this.stores.setCached(nextCachedMatches);
2522
+ });
2523
+ };
2524
+ this.load = async (opts) => {
2525
+ let redirect2;
2526
+ let notFound;
2527
+ let loadPromise;
2528
+ const previousLocation = this.stores.resolvedLocation.get() ?? this.stores.location.get();
2529
+ loadPromise = new Promise((resolve) => {
2530
+ this.startTransition(async () => {
2531
+ try {
2532
+ this.beforeLoad();
2533
+ const next = this.latestLocation;
2534
+ const locationChangeInfo = getLocationChangeInfo(next, this.stores.resolvedLocation.get());
2535
+ if (!this.stores.redirect.get()) this.emit({
2536
+ type: "onBeforeNavigate",
2537
+ ...locationChangeInfo
2538
+ });
2539
+ this.emit({
2540
+ type: "onBeforeLoad",
2541
+ ...locationChangeInfo
2542
+ });
2543
+ await loadMatches({
2544
+ router: this,
2545
+ sync: opts?.sync,
2546
+ forceStaleReload: previousLocation.href === next.href,
2547
+ matches: this.stores.pendingMatches.get(),
2548
+ location: next,
2549
+ updateMatch: this.updateMatch,
2550
+ onReady: async () => {
2551
+ this.startTransition(() => {
2552
+ this.startViewTransition(async () => {
2553
+ let exitingMatches = null;
2554
+ let hookExitingMatches = null;
2555
+ let hookEnteringMatches = null;
2556
+ let hookStayingMatches = null;
2557
+ this.batch(() => {
2558
+ const pendingMatches = this.stores.pendingMatches.get();
2559
+ const mountPending = pendingMatches.length;
2560
+ const currentMatches = this.stores.matches.get();
2561
+ exitingMatches = mountPending ? currentMatches.filter((match) => !this.stores.pendingMatchStores.has(match.id)) : null;
2562
+ const pendingRouteIds = /* @__PURE__ */ new Set();
2563
+ for (const s of this.stores.pendingMatchStores.values()) if (s.routeId) pendingRouteIds.add(s.routeId);
2564
+ const activeRouteIds = /* @__PURE__ */ new Set();
2565
+ for (const s of this.stores.matchStores.values()) if (s.routeId) activeRouteIds.add(s.routeId);
2566
+ hookExitingMatches = mountPending ? currentMatches.filter((match) => !pendingRouteIds.has(match.routeId)) : null;
2567
+ hookEnteringMatches = mountPending ? pendingMatches.filter((match) => !activeRouteIds.has(match.routeId)) : null;
2568
+ hookStayingMatches = mountPending ? pendingMatches.filter((match) => activeRouteIds.has(match.routeId)) : currentMatches;
2569
+ this.stores.isLoading.set(false);
2570
+ this.stores.loadedAt.set(Date.now());
2571
+ if (mountPending) {
2572
+ this.stores.setMatches(pendingMatches);
2573
+ this.stores.setPending([]);
2574
+ this.stores.setCached([...this.stores.cachedMatches.get(), ...exitingMatches.filter((d) => d.status !== "error" && d.status !== "notFound" && d.status !== "redirected")]);
2575
+ this.clearExpiredCache();
2576
+ }
2577
+ });
2578
+ for (const [matches, hook] of [
2579
+ [hookExitingMatches, "onLeave"],
2580
+ [hookEnteringMatches, "onEnter"],
2581
+ [hookStayingMatches, "onStay"]
2582
+ ]) {
2583
+ if (!matches) continue;
2584
+ for (const match of matches) this.looseRoutesById[match.routeId].options[hook]?.(match);
2585
+ }
2586
+ });
2587
+ });
2588
+ }
2589
+ });
2590
+ } catch (err) {
2591
+ if (isRedirect(err)) {
2592
+ redirect2 = err;
2593
+ } else if (isNotFound(err)) notFound = err;
2594
+ const nextStatusCode = redirect2 ? redirect2.status : notFound ? 404 : this.stores.matches.get().some((d) => d.status === "error") ? 500 : 200;
2595
+ this.batch(() => {
2596
+ this.stores.statusCode.set(nextStatusCode);
2597
+ this.stores.redirect.set(redirect2);
2598
+ });
2599
+ }
2600
+ if (this.latestLoadPromise === loadPromise) {
2601
+ this.commitLocationPromise?.resolve();
2602
+ this.latestLoadPromise = void 0;
2603
+ this.commitLocationPromise = void 0;
2604
+ }
2605
+ resolve();
2606
+ });
2607
+ });
2608
+ this.latestLoadPromise = loadPromise;
2609
+ await loadPromise;
2610
+ while (this.latestLoadPromise && loadPromise !== this.latestLoadPromise) await this.latestLoadPromise;
2611
+ let newStatusCode = void 0;
2612
+ if (this.hasNotFoundMatch()) newStatusCode = 404;
2613
+ else if (this.stores.matches.get().some((d) => d.status === "error")) newStatusCode = 500;
2614
+ if (newStatusCode !== void 0) this.stores.statusCode.set(newStatusCode);
2615
+ };
2616
+ this.startViewTransition = (fn) => {
2617
+ const shouldViewTransition = this.shouldViewTransition ?? this.options.defaultViewTransition;
2618
+ this.shouldViewTransition = void 0;
2619
+ if (shouldViewTransition && typeof document !== "undefined" && "startViewTransition" in document && typeof document.startViewTransition === "function") {
2620
+ let startViewTransitionParams;
2621
+ if (typeof shouldViewTransition === "object" && this.isViewTransitionTypesSupported) {
2622
+ const next = this.latestLocation;
2623
+ const prevLocation = this.stores.resolvedLocation.get();
2624
+ const resolvedViewTransitionTypes = typeof shouldViewTransition.types === "function" ? shouldViewTransition.types(getLocationChangeInfo(next, prevLocation)) : shouldViewTransition.types;
2625
+ if (resolvedViewTransitionTypes === false) {
2626
+ fn();
2627
+ return;
2628
+ }
2629
+ startViewTransitionParams = {
2630
+ update: fn,
2631
+ types: resolvedViewTransitionTypes
2632
+ };
2633
+ } else startViewTransitionParams = fn;
2634
+ document.startViewTransition(startViewTransitionParams);
2635
+ } else fn();
2636
+ };
2637
+ this.updateMatch = (id, updater) => {
2638
+ this.startTransition(() => {
2639
+ const pendingMatch = this.stores.pendingMatchStores.get(id);
2640
+ if (pendingMatch) {
2641
+ pendingMatch.set(updater);
2642
+ return;
2643
+ }
2644
+ const activeMatch = this.stores.matchStores.get(id);
2645
+ if (activeMatch) {
2646
+ activeMatch.set(updater);
2647
+ return;
2648
+ }
2649
+ const cachedMatch = this.stores.cachedMatchStores.get(id);
2650
+ if (cachedMatch) {
2651
+ const next = updater(cachedMatch.get());
2652
+ if (next.status === "redirected") {
2653
+ if (this.stores.cachedMatchStores.delete(id)) this.stores.cachedIds.set((prev) => prev.filter((matchId) => matchId !== id));
2654
+ } else cachedMatch.set(next);
2655
+ }
2656
+ });
2657
+ };
2658
+ this.getMatch = (matchId) => {
2659
+ return this.stores.cachedMatchStores.get(matchId)?.get() ?? this.stores.pendingMatchStores.get(matchId)?.get() ?? this.stores.matchStores.get(matchId)?.get();
2660
+ };
2661
+ this.invalidate = (opts) => {
2662
+ const invalidate = (d) => {
2663
+ if (opts?.filter?.(d) ?? true) return {
2664
+ ...d,
2665
+ invalid: true,
2666
+ ...opts?.forcePending || d.status === "error" || d.status === "notFound" ? {
2667
+ status: "pending",
2668
+ error: void 0
2669
+ } : void 0
2670
+ };
2671
+ return d;
2672
+ };
2673
+ this.batch(() => {
2674
+ this.stores.setMatches(this.stores.matches.get().map(invalidate));
2675
+ this.stores.setCached(this.stores.cachedMatches.get().map(invalidate));
2676
+ this.stores.setPending(this.stores.pendingMatches.get().map(invalidate));
2677
+ });
2678
+ this.shouldViewTransition = false;
2679
+ return this.load({ sync: opts?.sync });
2680
+ };
2681
+ this.getParsedLocationHref = (location) => {
2682
+ return location.publicHref || "/";
2683
+ };
2684
+ this.resolveRedirect = (redirect2) => {
2685
+ const locationHeader = redirect2.headers.get("Location");
2686
+ if (!redirect2.options.href || redirect2.options._builtLocation) {
2687
+ const location = redirect2.options._builtLocation ?? this.buildLocation(redirect2.options);
2688
+ const href = this.getParsedLocationHref(location);
2689
+ redirect2.options.href = href;
2690
+ redirect2.headers.set("Location", href);
2691
+ } else if (locationHeader) try {
2692
+ const url = new URL(locationHeader);
2693
+ if (this.origin && url.origin === this.origin) {
2694
+ const href = url.pathname + url.search + url.hash;
2695
+ redirect2.options.href = href;
2696
+ redirect2.headers.set("Location", href);
2697
+ }
2698
+ } catch {
2699
+ }
2700
+ if (redirect2.options.href && !redirect2.options._builtLocation && isDangerousProtocol(redirect2.options.href, this.protocolAllowlist)) throw new Error("Redirect blocked: unsafe protocol");
2701
+ if (!redirect2.headers.get("Location")) redirect2.headers.set("Location", redirect2.options.href);
2702
+ return redirect2;
2703
+ };
2704
+ this.clearCache = (opts) => {
2705
+ const filter = opts?.filter;
2706
+ if (filter !== void 0) this.stores.setCached(this.stores.cachedMatches.get().filter((m) => !filter(m)));
2707
+ else this.stores.setCached([]);
2708
+ };
2709
+ this.clearExpiredCache = () => {
2710
+ const now = Date.now();
2711
+ const filter = (d) => {
2712
+ const route = this.looseRoutesById[d.routeId];
2713
+ if (!route.options.loader) return true;
2714
+ const gcTime = (d.preload ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime : route.options.gcTime ?? this.options.defaultGcTime) ?? 300 * 1e3;
2715
+ if (d.status === "error") return true;
2716
+ return now - d.updatedAt >= gcTime;
2717
+ };
2718
+ this.clearCache({ filter });
2719
+ };
2720
+ this.loadRouteChunk = loadRouteChunk;
2721
+ this.preloadRoute = async (opts) => {
2722
+ const next = opts._builtLocation ?? this.buildLocation(opts);
2723
+ let matches = this.matchRoutes(next, {
2724
+ throwOnError: true,
2725
+ preload: true,
2726
+ dest: opts
2727
+ });
2728
+ const activeMatchIds = /* @__PURE__ */ new Set([...this.stores.matchesId.get(), ...this.stores.pendingIds.get()]);
2729
+ const loadedMatchIds = /* @__PURE__ */ new Set([...activeMatchIds, ...this.stores.cachedIds.get()]);
2730
+ const matchesToCache = matches.filter((match) => !loadedMatchIds.has(match.id));
2731
+ if (matchesToCache.length) {
2732
+ const cachedMatches = this.stores.cachedMatches.get();
2733
+ this.stores.setCached([...cachedMatches, ...matchesToCache]);
2734
+ }
2735
+ try {
2736
+ matches = await loadMatches({
2737
+ router: this,
2738
+ matches,
2739
+ location: next,
2740
+ preload: true,
2741
+ updateMatch: (id, updater) => {
2742
+ if (activeMatchIds.has(id)) matches = matches.map((d) => d.id === id ? updater(d) : d);
2743
+ else this.updateMatch(id, updater);
2744
+ }
2745
+ });
2746
+ return matches;
2747
+ } catch (err) {
2748
+ if (isRedirect(err)) {
2749
+ if (err.options.reloadDocument) return;
2750
+ return await this.preloadRoute({
2751
+ ...err.options,
2752
+ _fromLocation: next
2753
+ });
2754
+ }
2755
+ if (!isNotFound(err)) console.error(err);
2756
+ return;
2757
+ }
2758
+ };
2759
+ this.matchRoute = (location, opts) => {
2760
+ const matchLocation = {
2761
+ ...location,
2762
+ to: location.to ? this.resolvePathWithBase(location.from || "", location.to) : void 0,
2763
+ params: location.params || {},
2764
+ leaveParams: true
2765
+ };
2766
+ const next = this.buildLocation(matchLocation);
2767
+ if (opts?.pending && this.stores.status.get() !== "pending") return false;
2768
+ const baseLocation = (opts?.pending === void 0 ? !this.stores.isLoading.get() : opts.pending) ? this.latestLocation : this.stores.resolvedLocation.get() || this.stores.location.get();
2769
+ const match = findSingleMatch(next.pathname, opts?.caseSensitive ?? false, opts?.fuzzy ?? false, baseLocation.pathname, this.processedTree);
2770
+ if (!match) return false;
2771
+ if (location.params) {
2772
+ if (!deepEqual(match.rawParams, location.params, { partial: true })) return false;
2773
+ }
2774
+ if (opts?.includeSearch ?? true) return deepEqual(baseLocation.search, next.search, { partial: true }) ? match.rawParams : false;
2775
+ return match.rawParams;
2776
+ };
2777
+ this.hasNotFoundMatch = () => {
2778
+ return this.stores.matches.get().some((d) => d.status === "notFound" || d.globalNotFound);
2779
+ };
2780
+ this.getStoreConfig = getStoreConfig;
2781
+ this.update({
2782
+ defaultPreloadDelay: 50,
2783
+ defaultPendingMs: 1e3,
2784
+ defaultPendingMinMs: 500,
2785
+ context: void 0,
2786
+ ...options,
2787
+ caseSensitive: options.caseSensitive ?? false,
2788
+ notFoundMode: options.notFoundMode ?? "fuzzy",
2789
+ stringifySearch: options.stringifySearch ?? defaultStringifySearch,
2790
+ parseSearch: options.parseSearch ?? defaultParseSearch,
2791
+ protocolAllowlist: options.protocolAllowlist ?? DEFAULT_PROTOCOL_ALLOWLIST
2792
+ });
2793
+ if (typeof document !== "undefined") self.__TSR_ROUTER__ = this;
2794
+ }
2795
+ isShell() {
2796
+ return !!this.options.isShell;
2797
+ }
2798
+ isPrerendering() {
2799
+ return !!this.options.isPrerendering;
2800
+ }
2801
+ get state() {
2802
+ return this.stores.__store.get();
2803
+ }
2804
+ setRoutes({ routesById, routesByPath, processedTree }) {
2805
+ this.routesById = routesById;
2806
+ this.routesByPath = routesByPath;
2807
+ this.processedTree = processedTree;
2808
+ const notFoundRoute = this.options.notFoundRoute;
2809
+ if (notFoundRoute) {
2810
+ notFoundRoute.init({ originalIndex: 99999999999 });
2811
+ this.routesById[notFoundRoute.id] = notFoundRoute;
2812
+ }
2813
+ }
2814
+ getRouteBranch(route) {
2815
+ let branch = this.routeBranchCache.get(route);
2816
+ if (!branch) {
2817
+ branch = buildRouteBranch(route);
2818
+ this.routeBranchCache.set(route, branch);
2819
+ }
2820
+ return branch;
2821
+ }
2822
+ get looseRoutesById() {
2823
+ return this.routesById;
2824
+ }
2825
+ getParentContext(parentMatch) {
2826
+ return !parentMatch?.id ? this.options.context ?? void 0 : parentMatch.context ?? this.options.context ?? void 0;
2827
+ }
2828
+ matchRoutesInternal(next, opts) {
2829
+ const matchedRoutesResult = this.getMatchedRoutes(next.pathname);
2830
+ const { foundRoute, routeParams } = matchedRoutesResult;
2831
+ let { matchedRoutes } = matchedRoutesResult;
2832
+ let isGlobalNotFound = false;
2833
+ if (foundRoute ? foundRoute.path !== "/" && routeParams["**"] : trimPathRight(next.pathname)) if (this.options.notFoundRoute) matchedRoutes = [...matchedRoutes, this.options.notFoundRoute];
2834
+ else isGlobalNotFound = true;
2835
+ const globalNotFoundRouteId = isGlobalNotFound ? findGlobalNotFoundRouteId(this.options.notFoundMode, matchedRoutes) : void 0;
2836
+ const matches = new Array(matchedRoutes.length);
2837
+ const previousActiveMatchesByRouteId = /* @__PURE__ */ new Map();
2838
+ for (const store of this.stores.matchStores.values()) if (store.routeId) previousActiveMatchesByRouteId.set(store.routeId, store.get());
2839
+ for (let index = 0; index < matchedRoutes.length; index++) {
2840
+ const route = matchedRoutes[index];
2841
+ const parentMatch = matches[index - 1];
2842
+ let preMatchSearch;
2843
+ let strictMatchSearch;
2844
+ let searchError;
2845
+ {
2846
+ const parentSearch = parentMatch?.search ?? next.search;
2847
+ const parentStrictSearch = parentMatch?._strictSearch ?? void 0;
2848
+ try {
2849
+ const strictSearch = validateSearch(route.options.validateSearch, { ...parentSearch }) ?? void 0;
2850
+ preMatchSearch = {
2851
+ ...parentSearch,
2852
+ ...strictSearch
2853
+ };
2854
+ strictMatchSearch = {
2855
+ ...parentStrictSearch,
2856
+ ...strictSearch
2857
+ };
2858
+ searchError = void 0;
2859
+ } catch (err) {
2860
+ let searchParamError = err;
2861
+ if (!(err instanceof SearchParamError)) searchParamError = new SearchParamError(err.message, { cause: err });
2862
+ if (opts?.throwOnError) throw searchParamError;
2863
+ preMatchSearch = parentSearch;
2864
+ strictMatchSearch = {};
2865
+ searchError = searchParamError;
2866
+ }
2867
+ }
2868
+ const loaderDeps = route.options.loaderDeps?.({ search: preMatchSearch }) ?? "";
2869
+ const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : "";
2870
+ const { interpolatedPath, usedParams } = interpolatePath({
2871
+ path: route.fullPath,
2872
+ params: routeParams,
2873
+ decoder: this.pathParamsDecoder,
2874
+ server: this.isServer
2875
+ });
2876
+ const matchId = route.id + interpolatedPath + loaderDepsHash;
2877
+ const existingMatch = this.getMatch(matchId);
2878
+ const previousMatch = previousActiveMatchesByRouteId.get(route.id);
2879
+ const strictParams = existingMatch?._strictParams ?? usedParams;
2880
+ let paramsError = void 0;
2881
+ if (!existingMatch) try {
2882
+ extractStrictParams(route, strictParams);
2883
+ } catch (err) {
2884
+ if (isNotFound(err) || isRedirect(err)) paramsError = err;
2885
+ else paramsError = new PathParamError(err.message, { cause: err });
2886
+ if (opts?.throwOnError) throw paramsError;
2887
+ }
2888
+ Object.assign(routeParams, strictParams);
2889
+ const cause = previousMatch ? "stay" : "enter";
2890
+ let match;
2891
+ if (existingMatch) match = {
2892
+ ...existingMatch,
2893
+ cause,
2894
+ params: previousMatch?.params ?? routeParams,
2895
+ _strictParams: strictParams,
2896
+ search: previousMatch ? nullReplaceEqualDeep(previousMatch.search, preMatchSearch) : nullReplaceEqualDeep(existingMatch.search, preMatchSearch),
2897
+ _strictSearch: strictMatchSearch
2898
+ };
2899
+ else {
2900
+ const status = route.options.loader || route.options.beforeLoad || route.lazyFn || routeNeedsPreload(route) ? "pending" : "success";
2901
+ match = {
2902
+ id: matchId,
2903
+ ssr: void 0,
2904
+ index,
2905
+ routeId: route.id,
2906
+ params: previousMatch?.params ?? routeParams,
2907
+ _strictParams: strictParams,
2908
+ pathname: interpolatedPath,
2909
+ updatedAt: Date.now(),
2910
+ search: previousMatch ? nullReplaceEqualDeep(previousMatch.search, preMatchSearch) : preMatchSearch,
2911
+ _strictSearch: strictMatchSearch,
2912
+ searchError: void 0,
2913
+ status,
2914
+ isFetching: false,
2915
+ error: void 0,
2916
+ paramsError,
2917
+ __routeContext: void 0,
2918
+ _nonReactive: { loadPromise: createControlledPromise() },
2919
+ __beforeLoadContext: void 0,
2920
+ context: {},
2921
+ abortController: new AbortController(),
2922
+ fetchCount: 0,
2923
+ cause,
2924
+ loaderDeps: previousMatch ? replaceEqualDeep(previousMatch.loaderDeps, loaderDeps) : loaderDeps,
2925
+ invalid: false,
2926
+ preload: false,
2927
+ links: void 0,
2928
+ scripts: void 0,
2929
+ headScripts: void 0,
2930
+ meta: void 0,
2931
+ staticData: route.options.staticData || {},
2932
+ fullPath: route.fullPath
2933
+ };
2934
+ }
2935
+ if (!opts?.preload) match.globalNotFound = globalNotFoundRouteId === route.id;
2936
+ match.searchError = searchError;
2937
+ const parentContext = this.getParentContext(parentMatch);
2938
+ match.context = {
2939
+ ...parentContext,
2940
+ ...match.__routeContext,
2941
+ ...match.__beforeLoadContext
2942
+ };
2943
+ matches[index] = match;
2944
+ }
2945
+ for (let index = 0; index < matches.length; index++) {
2946
+ const match = matches[index];
2947
+ const route = this.looseRoutesById[match.routeId];
2948
+ const existingMatch = this.getMatch(match.id);
2949
+ const previousMatch = previousActiveMatchesByRouteId.get(match.routeId);
2950
+ match.params = previousMatch ? nullReplaceEqualDeep(previousMatch.params, routeParams) : routeParams;
2951
+ if (!existingMatch) {
2952
+ const parentMatch = matches[index - 1];
2953
+ const parentContext = this.getParentContext(parentMatch);
2954
+ if (route.options.context) {
2955
+ const contextFnContext = {
2956
+ deps: match.loaderDeps,
2957
+ params: match.params,
2958
+ context: parentContext ?? {},
2959
+ location: next,
2960
+ navigate: (opts2) => this.navigate({
2961
+ ...opts2,
2962
+ _fromLocation: next
2963
+ }),
2964
+ buildLocation: this.buildLocation,
2965
+ cause: match.cause,
2966
+ abortController: match.abortController,
2967
+ preload: !!match.preload,
2968
+ matches,
2969
+ routeId: route.id
2970
+ };
2971
+ match.__routeContext = route.options.context(contextFnContext) ?? void 0;
2972
+ }
2973
+ match.context = {
2974
+ ...parentContext,
2975
+ ...match.__routeContext,
2976
+ ...match.__beforeLoadContext
2977
+ };
2978
+ }
2979
+ }
2980
+ return matches;
2981
+ }
2982
+ /**
2983
+ * Lightweight route matching for buildLocation.
2984
+ * Only computes fullPath, accumulated search, and params - skipping expensive
2985
+ * operations like AbortController, ControlledPromise, loaderDeps, and full match objects.
2986
+ */
2987
+ matchRoutesLightweight(location) {
2988
+ const { matchedRoutes, routeParams } = this.getMatchedRoutes(location.pathname);
2989
+ const lastRoute = last(matchedRoutes);
2990
+ const accumulatedSearch = { ...location.search };
2991
+ for (const route of matchedRoutes) try {
2992
+ Object.assign(accumulatedSearch, validateSearch(route.options.validateSearch, accumulatedSearch));
2993
+ } catch {
2994
+ }
2995
+ const lastStateMatchId = last(this.stores.matchesId.get());
2996
+ const lastStateMatch = lastStateMatchId && this.stores.matchStores.get(lastStateMatchId)?.get();
2997
+ const canReuseParams = lastStateMatch && lastStateMatch.routeId === lastRoute.id && lastStateMatch.pathname === location.pathname;
2998
+ let params;
2999
+ if (canReuseParams) params = lastStateMatch.params;
3000
+ else {
3001
+ const strictParams = Object.assign(/* @__PURE__ */ Object.create(null), routeParams);
3002
+ for (const route of matchedRoutes) try {
3003
+ extractStrictParams(route, strictParams);
3004
+ } catch {
3005
+ }
3006
+ params = strictParams;
3007
+ }
3008
+ return {
3009
+ matchedRoutes,
3010
+ fullPath: lastRoute.fullPath,
3011
+ search: accumulatedSearch,
3012
+ params
3013
+ };
3014
+ }
3015
+ };
3016
+ var SearchParamError = class extends Error {
3017
+ };
3018
+ var PathParamError = class extends Error {
3019
+ };
3020
+ function getInitialRouterState(location) {
3021
+ return {
3022
+ loadedAt: 0,
3023
+ isLoading: false,
3024
+ isTransitioning: false,
3025
+ status: "idle",
3026
+ resolvedLocation: void 0,
3027
+ location,
3028
+ matches: [],
3029
+ statusCode: 200
3030
+ };
3031
+ }
3032
+ function validateSearch(validateSearch2, input) {
3033
+ if (validateSearch2 == null) return {};
3034
+ if ("~standard" in validateSearch2) {
3035
+ const result = validateSearch2["~standard"].validate(input);
3036
+ if (result instanceof Promise) throw new SearchParamError("Async validation not supported");
3037
+ if (result.issues) throw new SearchParamError(JSON.stringify(result.issues, void 0, 2), { cause: result });
3038
+ return result.value;
3039
+ }
3040
+ if ("parse" in validateSearch2) return validateSearch2.parse(input);
3041
+ if (typeof validateSearch2 === "function") return validateSearch2(input);
3042
+ return {};
3043
+ }
3044
+ function getMatchedRoutes({ pathname, routesById, processedTree }) {
3045
+ const routeParams = /* @__PURE__ */ Object.create(null);
3046
+ const trimmedPath = trimPathRight(pathname);
3047
+ let foundRoute = void 0;
3048
+ const match = findRouteMatch(trimmedPath, processedTree, true);
3049
+ if (match) {
3050
+ foundRoute = match.route;
3051
+ Object.assign(routeParams, match.rawParams);
3052
+ }
3053
+ return {
3054
+ matchedRoutes: match?.branch || [routesById["__root__"]],
3055
+ routeParams,
3056
+ foundRoute
3057
+ };
3058
+ }
3059
+ function applySearchMiddleware({ search, dest, destRoutes, _includeValidateSearch }) {
3060
+ return buildMiddlewareChain(destRoutes)(search, dest, _includeValidateSearch ?? false);
3061
+ }
3062
+ function buildMiddlewareChain(destRoutes) {
3063
+ const context = {
3064
+ dest: null,
3065
+ _includeValidateSearch: false,
3066
+ middlewares: []
3067
+ };
3068
+ for (const route of destRoutes) {
3069
+ if ("search" in route.options) {
3070
+ if (route.options.search?.middlewares) context.middlewares.push(...route.options.search.middlewares);
3071
+ } else if (route.options.preSearchFilters || route.options.postSearchFilters) {
3072
+ const legacyMiddleware = ({ search, next }) => {
3073
+ let nextSearch = search;
3074
+ if ("preSearchFilters" in route.options && route.options.preSearchFilters) nextSearch = route.options.preSearchFilters.reduce((prev, next2) => next2(prev), search);
3075
+ const result = next(nextSearch);
3076
+ if ("postSearchFilters" in route.options && route.options.postSearchFilters) return route.options.postSearchFilters.reduce((prev, next2) => next2(prev), result);
3077
+ return result;
3078
+ };
3079
+ context.middlewares.push(legacyMiddleware);
3080
+ }
3081
+ if (route.options.validateSearch) {
3082
+ const validate = ({ search, next }) => {
3083
+ const result = next(search);
3084
+ if (!context._includeValidateSearch) return result;
3085
+ try {
3086
+ return {
3087
+ ...result,
3088
+ ...validateSearch(route.options.validateSearch, result) ?? void 0
3089
+ };
3090
+ } catch {
3091
+ return result;
3092
+ }
3093
+ };
3094
+ context.middlewares.push(validate);
3095
+ }
3096
+ }
3097
+ const final = ({ search }) => {
3098
+ const dest = context.dest;
3099
+ if (!dest.search) return {};
3100
+ if (dest.search === true) return search;
3101
+ return functionalUpdate(dest.search, search);
3102
+ };
3103
+ context.middlewares.push(final);
3104
+ const applyNext = (index, currentSearch, middlewares) => {
3105
+ if (index >= middlewares.length) return currentSearch;
3106
+ const middleware = middlewares[index];
3107
+ const next = (newSearch) => {
3108
+ return applyNext(index + 1, newSearch, middlewares);
3109
+ };
3110
+ return middleware({
3111
+ search: currentSearch,
3112
+ next
3113
+ });
3114
+ };
3115
+ return function middleware(search, dest, _includeValidateSearch) {
3116
+ context.dest = dest;
3117
+ context._includeValidateSearch = _includeValidateSearch;
3118
+ return applyNext(0, search, context.middlewares);
3119
+ };
3120
+ }
3121
+ function findGlobalNotFoundRouteId(notFoundMode, routes) {
3122
+ if (notFoundMode !== "root") for (let i = routes.length - 1; i >= 0; i--) {
3123
+ const route = routes[i];
3124
+ if (route.children) return route.id;
3125
+ }
3126
+ return rootRouteId;
3127
+ }
3128
+ function extractStrictParams(route, accumulatedParams) {
3129
+ const parseParams = route.options.params?.parse ?? route.options.parseParams;
3130
+ if (parseParams) {
3131
+ const result = parseParams(accumulatedParams);
3132
+ if (result === false) throw new Error("Route params.parse returned false for a matched route");
3133
+ Object.assign(accumulatedParams, result);
3134
+ }
3135
+ }
3136
+ function getAssetCrossOrigin(assetCrossOrigin, kind) {
3137
+ if (!assetCrossOrigin) return;
3138
+ if (typeof assetCrossOrigin === "string") return assetCrossOrigin;
3139
+ return assetCrossOrigin[kind];
3140
+ }
3141
+ function resolveManifestAssetLink(link) {
3142
+ if (typeof link === "string") return {
3143
+ href: link,
3144
+ crossOrigin: void 0
3145
+ };
3146
+ return link;
3147
+ }
3148
+ function getStylesheetHref(asset) {
3149
+ if (asset.tag !== "link") return void 0;
3150
+ const rel = asset.attrs?.rel;
3151
+ const href = asset.attrs?.href;
3152
+ if (typeof href !== "string") return void 0;
3153
+ if (!(typeof rel === "string" ? rel.split(/\s+/) : []).includes("stylesheet")) return void 0;
3154
+ return href;
3155
+ }
3156
+ function isInlinableStylesheet(manifest, asset) {
3157
+ const href = getStylesheetHref(asset);
3158
+ return !!href && manifest?.inlineCss?.styles[href] !== void 0;
3159
+ }
3160
+ var BaseRoute = class {
3161
+ get to() {
3162
+ return this._to;
3163
+ }
3164
+ get id() {
3165
+ return this._id;
3166
+ }
3167
+ get path() {
3168
+ return this._path;
3169
+ }
3170
+ get fullPath() {
3171
+ return this._fullPath;
3172
+ }
3173
+ constructor(options) {
3174
+ this.init = (opts) => {
3175
+ this.originalIndex = opts.originalIndex;
3176
+ const options2 = this.options;
3177
+ const isRoot = !options2?.path && !options2?.id;
3178
+ this.parentRoute = this.options.getParentRoute?.();
3179
+ if (isRoot) this._path = rootRouteId;
3180
+ else if (!this.parentRoute) {
3181
+ invariant();
3182
+ }
3183
+ let path = isRoot ? rootRouteId : options2?.path;
3184
+ if (path && path !== "/") path = trimPathLeft(path);
3185
+ const customId = options2?.id || path;
3186
+ let id = isRoot ? rootRouteId : joinPaths([this.parentRoute.id === "__root__" ? "" : this.parentRoute.id, customId]);
3187
+ if (path === "__root__") path = "/";
3188
+ if (id !== "__root__") id = joinPaths(["/", id]);
3189
+ const fullPath = id === "__root__" ? "/" : joinPaths([this.parentRoute.fullPath, path]);
3190
+ this._path = path;
3191
+ this._id = id;
3192
+ this._fullPath = fullPath;
3193
+ this._to = trimPathRight(fullPath);
3194
+ };
3195
+ this.addChildren = (children) => {
3196
+ return this._addFileChildren(children);
3197
+ };
3198
+ this._addFileChildren = (children) => {
3199
+ if (Array.isArray(children)) this.children = children;
3200
+ if (typeof children === "object" && children !== null) this.children = Object.values(children);
3201
+ return this;
3202
+ };
3203
+ this._addFileTypes = () => {
3204
+ return this;
3205
+ };
3206
+ this.updateLoader = (options2) => {
3207
+ Object.assign(this.options, options2);
3208
+ return this;
3209
+ };
3210
+ this.update = (options2) => {
3211
+ Object.assign(this.options, options2);
3212
+ return this;
3213
+ };
3214
+ this.lazy = (lazyFn) => {
3215
+ this.lazyFn = lazyFn;
3216
+ return this;
3217
+ };
3218
+ this.redirect = (opts) => redirect({
3219
+ from: this.fullPath,
3220
+ ...opts
3221
+ });
3222
+ this.options = options || {};
3223
+ this.isRoot = !options?.getParentRoute;
3224
+ if (options?.id && options?.path) throw new Error(`Route cannot have both an 'id' and a 'path' option.`);
3225
+ }
3226
+ };
3227
+ var BaseRootRoute = class extends BaseRoute {
3228
+ constructor(options) {
3229
+ super(options);
3230
+ }
3231
+ };
3232
+ var scroll_restoration_inline_default = 'function(t){let s;try{s=JSON.parse(sessionStorage.getItem(t.storageKey)||"{}")}catch(e){console.error(e);return}const c=t.key||window.history.state?.__TSR_key,r=c?s[c]:void 0;if(t.shouldScrollRestoration&&r&&typeof r=="object"&&Object.keys(r).length>0){for(const e in r){const o=r[e];if(!o||typeof o!="object")continue;const l=o.scrollX,i=o.scrollY;if(!(!Number.isFinite(l)||!Number.isFinite(i))){if(e==="window")window.scrollTo({top:i,left:l,behavior:t.behavior});else if(e){let n;try{n=document.querySelector(e)}catch{continue}n&&(n.scrollLeft=l,n.scrollTop=i)}}}return}const a=window.location.hash.split("#",2)[1];if(a){const e=window.history.state?.__hashScrollIntoViewOptions??!0;if(e){const o=document.getElementById(a);o&&o.scrollIntoView(e)}return}window.scrollTo({top:0,left:0,behavior:t.behavior})}';
3233
+ const defaultInlineScrollRestorationScript = `(${scroll_restoration_inline_default})(${escapeHtml(JSON.stringify({
3234
+ storageKey,
3235
+ shouldScrollRestoration: true
3236
+ }))})`;
3237
+ function getScrollRestorationScript(options) {
3238
+ if (options.storageKey === "tsr-scroll-restoration-v1_3" && options.shouldScrollRestoration === true && options.key === void 0 && options.behavior === void 0) return defaultInlineScrollRestorationScript;
3239
+ return `(${scroll_restoration_inline_default})(${escapeHtml(JSON.stringify(options))})`;
3240
+ }
3241
+ function getScrollRestorationScriptForRouter(router) {
3242
+ if (typeof router.options.scrollRestoration === "function" && !router.options.scrollRestoration({ location: router.latestLocation })) return null;
3243
+ const getKey = router.options.getScrollRestorationKey;
3244
+ if (!getKey) return defaultInlineScrollRestorationScript;
3245
+ const location = router.latestLocation;
3246
+ const userKey = getKey(location);
3247
+ if (userKey === defaultGetScrollRestorationKey(location)) return defaultInlineScrollRestorationScript;
3248
+ return getScrollRestorationScript({
3249
+ storageKey,
3250
+ shouldScrollRestoration: true,
3251
+ key: userKey
3252
+ });
3253
+ }
3254
+ function defineHandlerCallback(handler) {
3255
+ return handler;
3256
+ }
3257
+ function transformReadableStreamWithRouter(router, routerStream) {
3258
+ return transformStreamWithRouter(router, routerStream);
3259
+ }
3260
+ function transformPipeableStreamWithRouter(router, routerStream) {
3261
+ return Readable.fromWeb(transformStreamWithRouter(router, Readable.toWeb(routerStream)));
3262
+ }
3263
+ const BODY_END_TAG = "</body>";
3264
+ const HTML_END_TAG = "</html>";
3265
+ const MIN_CLOSING_TAG_LENGTH = 4;
3266
+ const DEFAULT_SERIALIZATION_TIMEOUT_MS = 6e4;
3267
+ const DEFAULT_LIFETIME_TIMEOUT_MS = 6e4;
3268
+ const textEncoder = new TextEncoder();
3269
+ function findLastClosingTagEnd(str) {
3270
+ const len = str.length;
3271
+ if (len < MIN_CLOSING_TAG_LENGTH) return -1;
3272
+ let i = len - 1;
3273
+ while (i >= MIN_CLOSING_TAG_LENGTH - 1) {
3274
+ if (str.charCodeAt(i) === 62) {
3275
+ let j = i - 1;
3276
+ while (j >= 1) {
3277
+ const code = str.charCodeAt(j);
3278
+ if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 || code === 95 || code === 58 || code === 46 || code === 45) j--;
3279
+ else break;
3280
+ }
3281
+ const tagNameStart = j + 1;
3282
+ if (tagNameStart < i) {
3283
+ const startCode = str.charCodeAt(tagNameStart);
3284
+ if (startCode >= 97 && startCode <= 122 || startCode >= 65 && startCode <= 90) {
3285
+ if (j >= 1 && str.charCodeAt(j) === 47 && str.charCodeAt(j - 1) === 60) return i + 1;
3286
+ }
3287
+ }
3288
+ }
3289
+ i--;
3290
+ }
3291
+ return -1;
3292
+ }
3293
+ function transformStreamWithRouter(router, appStream, opts) {
3294
+ const serializationAlreadyFinished = router.serverSsr?.isSerializationFinished() ?? false;
3295
+ const initialBufferedHtml = router.serverSsr?.takeBufferedHtml();
3296
+ if (serializationAlreadyFinished && !initialBufferedHtml) {
3297
+ let cleanedUp2 = false;
3298
+ let controller2;
3299
+ let isStreamClosed2 = false;
3300
+ let lifetimeTimeoutHandle2;
3301
+ const cleanup2 = () => {
3302
+ if (cleanedUp2) return;
3303
+ cleanedUp2 = true;
3304
+ if (lifetimeTimeoutHandle2 !== void 0) {
3305
+ clearTimeout(lifetimeTimeoutHandle2);
3306
+ lifetimeTimeoutHandle2 = void 0;
3307
+ }
3308
+ router.serverSsr?.cleanup();
3309
+ };
3310
+ const safeClose2 = () => {
3311
+ if (isStreamClosed2) return;
3312
+ isStreamClosed2 = true;
3313
+ try {
3314
+ controller2?.close();
3315
+ } catch {
3316
+ }
3317
+ };
3318
+ const safeError2 = (error) => {
3319
+ if (isStreamClosed2) return;
3320
+ isStreamClosed2 = true;
3321
+ try {
3322
+ controller2?.error(error);
3323
+ } catch {
3324
+ }
3325
+ };
3326
+ const lifetimeMs2 = DEFAULT_LIFETIME_TIMEOUT_MS;
3327
+ lifetimeTimeoutHandle2 = setTimeout(() => {
3328
+ if (!cleanedUp2 && !isStreamClosed2) {
3329
+ console.warn(`SSR stream transform exceeded maximum lifetime (${lifetimeMs2}ms), forcing cleanup`);
3330
+ safeError2(/* @__PURE__ */ new Error("Stream lifetime exceeded"));
3331
+ cleanup2();
3332
+ }
3333
+ }, lifetimeMs2);
3334
+ const stream2 = new ReadableStream$1({
3335
+ start(c) {
3336
+ controller2 = c;
3337
+ },
3338
+ cancel() {
3339
+ isStreamClosed2 = true;
3340
+ cleanup2();
3341
+ }
3342
+ });
3343
+ (async () => {
3344
+ const reader = appStream.getReader();
3345
+ try {
3346
+ while (true) {
3347
+ const { done, value } = await reader.read();
3348
+ if (done) break;
3349
+ if (cleanedUp2 || isStreamClosed2) return;
3350
+ controller2?.enqueue(value);
3351
+ }
3352
+ if (cleanedUp2 || isStreamClosed2) return;
3353
+ router.serverSsr?.setRenderFinished();
3354
+ safeClose2();
3355
+ cleanup2();
3356
+ } catch (error) {
3357
+ if (cleanedUp2) return;
3358
+ console.error("Error reading appStream:", error);
3359
+ router.serverSsr?.setRenderFinished();
3360
+ safeError2(error);
3361
+ cleanup2();
3362
+ } finally {
3363
+ reader.releaseLock();
3364
+ }
3365
+ })().catch((error) => {
3366
+ if (cleanedUp2) return;
3367
+ console.error("Error in stream transform:", error);
3368
+ safeError2(error);
3369
+ cleanup2();
3370
+ });
3371
+ return stream2;
3372
+ }
3373
+ let stopListeningToInjectedHtml;
3374
+ let stopListeningToSerializationFinished;
3375
+ let serializationTimeoutHandle;
3376
+ let lifetimeTimeoutHandle;
3377
+ let cleanedUp = false;
3378
+ let controller;
3379
+ let isStreamClosed = false;
3380
+ const textDecoder = new TextDecoder();
3381
+ let pendingRouterHtml = initialBufferedHtml ?? "";
3382
+ let leftover = "";
3383
+ let pendingClosingTags = "";
3384
+ const MAX_LEFTOVER_CHARS = 2048;
3385
+ let isAppRendering = true;
3386
+ let streamBarrierLifted = false;
3387
+ let serializationFinished = serializationAlreadyFinished;
3388
+ function safeEnqueue(chunk) {
3389
+ if (isStreamClosed) return;
3390
+ if (typeof chunk === "string") controller.enqueue(textEncoder.encode(chunk));
3391
+ else controller.enqueue(chunk);
3392
+ }
3393
+ function safeClose() {
3394
+ if (isStreamClosed) return;
3395
+ isStreamClosed = true;
3396
+ try {
3397
+ controller.close();
3398
+ } catch {
3399
+ }
3400
+ }
3401
+ function safeError(error) {
3402
+ if (isStreamClosed) return;
3403
+ isStreamClosed = true;
3404
+ try {
3405
+ controller.error(error);
3406
+ } catch {
3407
+ }
3408
+ }
3409
+ function cleanup() {
3410
+ if (cleanedUp) return;
3411
+ cleanedUp = true;
3412
+ try {
3413
+ stopListeningToInjectedHtml?.();
3414
+ stopListeningToSerializationFinished?.();
3415
+ } catch {
3416
+ }
3417
+ stopListeningToInjectedHtml = void 0;
3418
+ stopListeningToSerializationFinished = void 0;
3419
+ if (serializationTimeoutHandle !== void 0) {
3420
+ clearTimeout(serializationTimeoutHandle);
3421
+ serializationTimeoutHandle = void 0;
3422
+ }
3423
+ if (lifetimeTimeoutHandle !== void 0) {
3424
+ clearTimeout(lifetimeTimeoutHandle);
3425
+ lifetimeTimeoutHandle = void 0;
3426
+ }
3427
+ pendingRouterHtml = "";
3428
+ leftover = "";
3429
+ pendingClosingTags = "";
3430
+ router.serverSsr?.cleanup();
3431
+ }
3432
+ const stream = new ReadableStream$1({
3433
+ start(c) {
3434
+ controller = c;
3435
+ },
3436
+ cancel() {
3437
+ isStreamClosed = true;
3438
+ cleanup();
3439
+ }
3440
+ });
3441
+ function flushPendingRouterHtml() {
3442
+ if (!pendingRouterHtml) return;
3443
+ safeEnqueue(pendingRouterHtml);
3444
+ pendingRouterHtml = "";
3445
+ }
3446
+ function appendRouterHtml(html) {
3447
+ if (!html) return;
3448
+ pendingRouterHtml += html;
3449
+ }
3450
+ function tryFinish() {
3451
+ if (isAppRendering || !serializationFinished) return;
3452
+ if (cleanedUp || isStreamClosed) return;
3453
+ if (serializationTimeoutHandle !== void 0) {
3454
+ clearTimeout(serializationTimeoutHandle);
3455
+ serializationTimeoutHandle = void 0;
3456
+ }
3457
+ const decoderRemainder = textDecoder.decode();
3458
+ if (leftover) safeEnqueue(leftover);
3459
+ if (decoderRemainder) safeEnqueue(decoderRemainder);
3460
+ flushPendingRouterHtml();
3461
+ if (pendingClosingTags) safeEnqueue(pendingClosingTags);
3462
+ safeClose();
3463
+ cleanup();
3464
+ }
3465
+ const lifetimeMs = DEFAULT_LIFETIME_TIMEOUT_MS;
3466
+ lifetimeTimeoutHandle = setTimeout(() => {
3467
+ if (!cleanedUp && !isStreamClosed) {
3468
+ console.warn(`SSR stream transform exceeded maximum lifetime (${lifetimeMs}ms), forcing cleanup`);
3469
+ safeError(/* @__PURE__ */ new Error("Stream lifetime exceeded"));
3470
+ cleanup();
3471
+ }
3472
+ }, lifetimeMs);
3473
+ if (!serializationAlreadyFinished) {
3474
+ stopListeningToInjectedHtml = router.subscribe("onInjectedHtml", () => {
3475
+ if (cleanedUp || isStreamClosed) return;
3476
+ const html = router.serverSsr?.takeBufferedHtml();
3477
+ if (!html) return;
3478
+ if (isAppRendering || leftover || pendingClosingTags) appendRouterHtml(html);
3479
+ else {
3480
+ flushPendingRouterHtml();
3481
+ safeEnqueue(html);
3482
+ }
3483
+ });
3484
+ stopListeningToSerializationFinished = router.subscribe("onSerializationFinished", () => {
3485
+ serializationFinished = true;
3486
+ tryFinish();
3487
+ });
3488
+ }
3489
+ (async () => {
3490
+ const reader = appStream.getReader();
3491
+ try {
3492
+ while (true) {
3493
+ const { done, value } = await reader.read();
3494
+ if (done) break;
3495
+ if (cleanedUp || isStreamClosed) return;
3496
+ const text = value instanceof Uint8Array ? textDecoder.decode(value, { stream: true }) : String(value);
3497
+ const chunkString = leftover ? leftover + text : text;
3498
+ if (!streamBarrierLifted) {
3499
+ if (chunkString.includes("$tsr-stream-barrier")) {
3500
+ streamBarrierLifted = true;
3501
+ router.serverSsr?.liftScriptBarrier();
3502
+ }
3503
+ }
3504
+ if (pendingClosingTags) {
3505
+ pendingClosingTags += chunkString;
3506
+ leftover = "";
3507
+ continue;
3508
+ }
3509
+ const bodyEndIndex = chunkString.indexOf(BODY_END_TAG);
3510
+ const htmlEndIndex = chunkString.indexOf(HTML_END_TAG);
3511
+ if (bodyEndIndex !== -1 && htmlEndIndex !== -1 && bodyEndIndex < htmlEndIndex) {
3512
+ pendingClosingTags = chunkString.slice(bodyEndIndex);
3513
+ safeEnqueue(chunkString.slice(0, bodyEndIndex));
3514
+ flushPendingRouterHtml();
3515
+ leftover = "";
3516
+ continue;
3517
+ }
3518
+ const lastClosingTagEnd = findLastClosingTagEnd(chunkString);
3519
+ if (lastClosingTagEnd > 0) {
3520
+ safeEnqueue(chunkString.slice(0, lastClosingTagEnd));
3521
+ flushPendingRouterHtml();
3522
+ leftover = chunkString.slice(lastClosingTagEnd);
3523
+ if (leftover.length > MAX_LEFTOVER_CHARS) {
3524
+ safeEnqueue(leftover.slice(0, leftover.length - MAX_LEFTOVER_CHARS));
3525
+ leftover = leftover.slice(-MAX_LEFTOVER_CHARS);
3526
+ }
3527
+ } else {
3528
+ const combined = chunkString;
3529
+ if (combined.length > MAX_LEFTOVER_CHARS) {
3530
+ const flushUpto = combined.length - MAX_LEFTOVER_CHARS;
3531
+ safeEnqueue(combined.slice(0, flushUpto));
3532
+ leftover = combined.slice(flushUpto);
3533
+ } else leftover = combined;
3534
+ }
3535
+ }
3536
+ if (cleanedUp || isStreamClosed) return;
3537
+ isAppRendering = false;
3538
+ router.serverSsr?.setRenderFinished();
3539
+ if (serializationFinished) tryFinish();
3540
+ else {
3541
+ const timeoutMs = opts?.timeoutMs ?? DEFAULT_SERIALIZATION_TIMEOUT_MS;
3542
+ serializationTimeoutHandle = setTimeout(() => {
3543
+ if (!cleanedUp && !isStreamClosed) {
3544
+ console.error("Serialization timeout after app render finished");
3545
+ safeError(/* @__PURE__ */ new Error("Serialization timeout after app render finished"));
3546
+ cleanup();
3547
+ }
3548
+ }, timeoutMs);
3549
+ }
3550
+ } catch (error) {
3551
+ if (cleanedUp) return;
3552
+ console.error("Error reading appStream:", error);
3553
+ isAppRendering = false;
3554
+ router.serverSsr?.setRenderFinished();
3555
+ safeError(error);
3556
+ cleanup();
3557
+ } finally {
3558
+ reader.releaseLock();
3559
+ }
3560
+ })().catch((error) => {
3561
+ if (cleanedUp) return;
3562
+ console.error("Error in stream transform:", error);
3563
+ safeError(error);
3564
+ cleanup();
3565
+ });
3566
+ return stream;
3567
+ }
3568
+ export {
3569
+ BaseRootRoute as B,
3570
+ RouterCore as R,
3571
+ BaseRoute as a,
3572
+ createNonReactiveReadonlyStore as b,
3573
+ createNonReactiveMutableStore as c,
3574
+ deepEqual as d,
3575
+ defineHandlerCallback as e,
3576
+ escapeHtml as f,
3577
+ exactPathTest as g,
3578
+ functionalUpdate as h,
3579
+ getAssetCrossOrigin as i,
3580
+ getScrollRestorationScriptForRouter as j,
3581
+ hasKeys as k,
3582
+ invariant as l,
3583
+ isDangerousProtocol as m,
3584
+ isInlinableStylesheet as n,
3585
+ isModuleNotFoundError as o,
3586
+ isNotFound as p,
3587
+ isRedirect as q,
3588
+ isServer as r,
3589
+ removeTrailingSlash as s,
3590
+ resolveManifestAssetLink as t,
3591
+ rootRouteId as u,
3592
+ transformPipeableStreamWithRouter as v,
3593
+ transformReadableStreamWithRouter as w
3594
+ };