@qwik.dev/router 0.0.0 → 2.0.0-alpha.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 (98) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +15 -0
  3. package/adapters/azure-swa/vite.d.ts +2 -0
  4. package/adapters/bun-server/vite.d.ts +2 -0
  5. package/adapters/cloud-run/vite.d.ts +2 -0
  6. package/adapters/cloudflare-pages/vite.d.ts +2 -0
  7. package/adapters/deno-server/vite.d.ts +2 -0
  8. package/adapters/netlify-edge/vite.d.ts +2 -0
  9. package/adapters/node-server/vite.d.ts +2 -0
  10. package/adapters/shared/vite.d.ts +2 -0
  11. package/adapters/static/vite.d.ts +2 -0
  12. package/adapters/vercel-edge/vite.d.ts +2 -0
  13. package/index.d.ts +2 -0
  14. package/lib/adapters/azure-swa/vite/index.cjs +96 -0
  15. package/lib/adapters/azure-swa/vite/index.d.ts +13 -0
  16. package/lib/adapters/azure-swa/vite/index.mjs +61 -0
  17. package/lib/adapters/bun-server/vite/index.cjs +50 -0
  18. package/lib/adapters/bun-server/vite/index.d.ts +14 -0
  19. package/lib/adapters/bun-server/vite/index.mjs +25 -0
  20. package/lib/adapters/cloud-run/vite/index.cjs +47 -0
  21. package/lib/adapters/cloud-run/vite/index.d.ts +13 -0
  22. package/lib/adapters/cloud-run/vite/index.mjs +22 -0
  23. package/lib/adapters/cloudflare-pages/vite/index.cjs +115 -0
  24. package/lib/adapters/cloudflare-pages/vite/index.d.ts +27 -0
  25. package/lib/adapters/cloudflare-pages/vite/index.mjs +80 -0
  26. package/lib/adapters/deno-server/vite/index.cjs +62 -0
  27. package/lib/adapters/deno-server/vite/index.d.ts +14 -0
  28. package/lib/adapters/deno-server/vite/index.mjs +37 -0
  29. package/lib/adapters/netlify-edge/vite/index.cjs +129 -0
  30. package/lib/adapters/netlify-edge/vite/index.d.ts +44 -0
  31. package/lib/adapters/netlify-edge/vite/index.mjs +92 -0
  32. package/lib/adapters/node-server/vite/index.cjs +50 -0
  33. package/lib/adapters/node-server/vite/index.d.ts +14 -0
  34. package/lib/adapters/node-server/vite/index.mjs +25 -0
  35. package/lib/adapters/shared/vite/index.cjs +371 -0
  36. package/lib/adapters/shared/vite/index.d.ts +114 -0
  37. package/lib/adapters/shared/vite/index.mjs +331 -0
  38. package/lib/adapters/static/vite/index.cjs +361 -0
  39. package/lib/adapters/static/vite/index.d.ts +10 -0
  40. package/lib/adapters/static/vite/index.mjs +324 -0
  41. package/lib/adapters/vercel-edge/vite/index.cjs +118 -0
  42. package/lib/adapters/vercel-edge/vite/index.d.ts +45 -0
  43. package/lib/adapters/vercel-edge/vite/index.mjs +83 -0
  44. package/lib/index.d.ts +803 -0
  45. package/lib/index.qwik.cjs +1876 -0
  46. package/lib/index.qwik.mjs +1857 -0
  47. package/lib/middleware/aws-lambda/index.d.ts +50 -0
  48. package/lib/middleware/aws-lambda/index.mjs +55 -0
  49. package/lib/middleware/azure-swa/index.d.ts +28 -0
  50. package/lib/middleware/azure-swa/index.mjs +297 -0
  51. package/lib/middleware/bun/index.d.ts +35 -0
  52. package/lib/middleware/bun/index.mjs +208 -0
  53. package/lib/middleware/cloudflare-pages/index.d.ts +35 -0
  54. package/lib/middleware/cloudflare-pages/index.mjs +107 -0
  55. package/lib/middleware/deno/index.d.ts +47 -0
  56. package/lib/middleware/deno/index.mjs +195 -0
  57. package/lib/middleware/firebase/index.d.ts +26 -0
  58. package/lib/middleware/firebase/index.mjs +36 -0
  59. package/lib/middleware/netlify-edge/index.d.ts +27 -0
  60. package/lib/middleware/netlify-edge/index.mjs +83 -0
  61. package/lib/middleware/node/index.cjs +314 -0
  62. package/lib/middleware/node/index.d.ts +66 -0
  63. package/lib/middleware/node/index.mjs +287 -0
  64. package/lib/middleware/request-handler/index.cjs +1544 -0
  65. package/lib/middleware/request-handler/index.d.ts +681 -0
  66. package/lib/middleware/request-handler/index.mjs +1501 -0
  67. package/lib/middleware/vercel-edge/index.d.ts +26 -0
  68. package/lib/middleware/vercel-edge/index.mjs +109 -0
  69. package/lib/modules.d.ts +38 -0
  70. package/lib/service-worker.cjs +267 -0
  71. package/lib/service-worker.d.ts +4 -0
  72. package/lib/service-worker.mjs +265 -0
  73. package/lib/static/deno.mjs +8 -0
  74. package/lib/static/index.cjs +67 -0
  75. package/lib/static/index.d.ts +98 -0
  76. package/lib/static/index.mjs +48 -0
  77. package/lib/static/node.cjs +1124 -0
  78. package/lib/static/node.mjs +1086 -0
  79. package/lib/vite/index.cjs +27496 -0
  80. package/lib/vite/index.d.ts +154 -0
  81. package/lib/vite/index.mjs +27484 -0
  82. package/middleware/aws-lambda.d.ts +2 -0
  83. package/middleware/azure-swa.d.ts +2 -0
  84. package/middleware/bun.d.ts +2 -0
  85. package/middleware/cloudflare-pages.d.ts +2 -0
  86. package/middleware/deno.d.ts +2 -0
  87. package/middleware/firebase.d.ts +2 -0
  88. package/middleware/netlify-edge.d.ts +2 -0
  89. package/middleware/node.d.ts +2 -0
  90. package/middleware/request-handler/generated/not-found-paths.ts +7 -0
  91. package/middleware/request-handler/generated/static-paths.ts +35 -0
  92. package/middleware/request-handler.d.ts +2 -0
  93. package/middleware/vercel-edge.d.ts +2 -0
  94. package/modules.d.ts +38 -0
  95. package/package.json +171 -165
  96. package/service-worker.d.ts +2 -0
  97. package/static.d.ts +2 -0
  98. package/vite.d.ts +2 -0
@@ -0,0 +1,1876 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const jsxRuntime = require("@qwik.dev/core/jsx-runtime");
4
+ const core = require("@qwik.dev/core");
5
+ const build = require("@qwik.dev/core/build");
6
+ const internal = require("@qwik.dev/core/internal");
7
+ const qwikRouterConfig = require("@qwik-router-config");
8
+ const zod = require("zod");
9
+ const swRegister = require("@qwik-router-sw-register");
10
+ function _interopNamespaceDefault(e) {
11
+ const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
12
+ if (e) {
13
+ for (const k in e) {
14
+ if (k !== "default") {
15
+ const d = Object.getOwnPropertyDescriptor(e, k);
16
+ Object.defineProperty(n, k, d.get ? d : {
17
+ enumerable: true,
18
+ get: () => e[k]
19
+ });
20
+ }
21
+ }
22
+ }
23
+ n.default = e;
24
+ return Object.freeze(n);
25
+ }
26
+ const qwikRouterConfig__namespace = /* @__PURE__ */ _interopNamespaceDefault(qwikRouterConfig);
27
+ const MODULE_CACHE = /* @__PURE__ */ new WeakMap();
28
+ const CLIENT_DATA_CACHE = /* @__PURE__ */ new Map();
29
+ const PREFETCHED_NAVIGATE_PATHS = /* @__PURE__ */ new Set();
30
+ const QACTION_KEY = "qaction";
31
+ const QFN_KEY = "qfunc";
32
+ const QDATA_KEY = "qdata";
33
+ const toPath = (url) => url.pathname + url.search + url.hash;
34
+ const toUrl = (url, baseUrl) => new URL(url, baseUrl.href);
35
+ const isSameOrigin = (a, b) => a.origin === b.origin;
36
+ const withSlash = (path) => path.endsWith("/") ? path : path + "/";
37
+ const isSamePathname = ({ pathname: a }, { pathname: b }) => {
38
+ const lDiff = Math.abs(a.length - b.length);
39
+ return lDiff === 0 ? a === b : lDiff === 1 && withSlash(a) === withSlash(b);
40
+ };
41
+ const isSameSearchQuery = (a, b) => a.search === b.search;
42
+ const isSamePath = (a, b) => isSameSearchQuery(a, b) && isSamePathname(a, b);
43
+ const getClientDataPath = (pathname, pageSearch, action) => {
44
+ let search = pageSearch ?? "";
45
+ if (action) {
46
+ search += (search ? "&" : "?") + QACTION_KEY + "=" + encodeURIComponent(action.id);
47
+ }
48
+ return pathname + (pathname.endsWith("/") ? "" : "/") + "q-data.json" + search;
49
+ };
50
+ const getClientNavPath = (props, baseUrl) => {
51
+ const href = props.href;
52
+ if (typeof href === "string" && typeof props.target !== "string" && !props.reload) {
53
+ try {
54
+ const linkUrl = toUrl(href.trim(), baseUrl.url);
55
+ const currentUrl = toUrl("", baseUrl.url);
56
+ if (isSameOrigin(linkUrl, currentUrl)) {
57
+ return toPath(linkUrl);
58
+ }
59
+ } catch (e) {
60
+ console.error(e);
61
+ }
62
+ } else if (props.reload) {
63
+ return toPath(toUrl("", baseUrl.url));
64
+ }
65
+ return null;
66
+ };
67
+ const shouldPrefetchData = (clientNavPath, currentLoc) => {
68
+ if (clientNavPath) {
69
+ const prefetchUrl = toUrl(clientNavPath, currentLoc.url);
70
+ const currentUrl = toUrl("", currentLoc.url);
71
+ return !isSamePath(prefetchUrl, currentUrl);
72
+ }
73
+ return false;
74
+ };
75
+ const shouldPrefetchSymbols = (clientNavPath, currentLoc) => {
76
+ if (clientNavPath) {
77
+ const prefetchUrl = toUrl(clientNavPath, currentLoc.url);
78
+ const currentUrl = toUrl("", currentLoc.url);
79
+ return !isSamePathname(prefetchUrl, currentUrl);
80
+ }
81
+ return false;
82
+ };
83
+ const isPromise = (value) => {
84
+ return value && typeof value.then === "function";
85
+ };
86
+ const deepFreeze = (obj) => {
87
+ if (obj == null) {
88
+ return obj;
89
+ }
90
+ Object.getOwnPropertyNames(obj).forEach((prop) => {
91
+ const value = obj[prop];
92
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
93
+ deepFreeze(value);
94
+ }
95
+ });
96
+ return Object.freeze(obj);
97
+ };
98
+ const clientNavigate = (win, navType, fromURL, toURL, replaceState = false) => {
99
+ if (navType !== "popstate") {
100
+ const samePath = isSamePath(fromURL, toURL);
101
+ const sameHash = fromURL.hash === toURL.hash;
102
+ if (!samePath || !sameHash) {
103
+ const newState = {
104
+ _qRouterScroll: newScrollState()
105
+ };
106
+ if (replaceState) {
107
+ win.history.replaceState(newState, "", toPath(toURL));
108
+ } else {
109
+ win.history.pushState(newState, "", toPath(toURL));
110
+ }
111
+ }
112
+ }
113
+ };
114
+ const newScrollState = () => {
115
+ return {
116
+ x: 0,
117
+ y: 0,
118
+ w: 0,
119
+ h: 0
120
+ };
121
+ };
122
+ const prefetchSymbols = (path) => {
123
+ if (build.isBrowser) {
124
+ path = path.endsWith("/") ? path : path + "/";
125
+ if (!PREFETCHED_NAVIGATE_PATHS.has(path)) {
126
+ PREFETCHED_NAVIGATE_PATHS.add(path);
127
+ document.dispatchEvent(new CustomEvent("qprefetch", {
128
+ detail: {
129
+ links: [
130
+ path
131
+ ]
132
+ }
133
+ }));
134
+ }
135
+ }
136
+ };
137
+ const loadClientData = async (url, element, opts) => {
138
+ const pagePathname = url.pathname;
139
+ const pageSearch = url.search;
140
+ const clientDataPath = getClientDataPath(pagePathname, pageSearch, opts?.action);
141
+ let qData;
142
+ if (!opts?.action) {
143
+ qData = CLIENT_DATA_CACHE.get(clientDataPath);
144
+ }
145
+ if (opts?.prefetchSymbols !== false) {
146
+ prefetchSymbols(pagePathname);
147
+ }
148
+ let resolveFn;
149
+ if (!qData) {
150
+ const fetchOptions = getFetchOptions(opts?.action);
151
+ if (opts?.action) {
152
+ opts.action.data = void 0;
153
+ }
154
+ qData = fetch(clientDataPath, fetchOptions).then((rsp) => {
155
+ if (rsp.redirected) {
156
+ const redirectedURL = new URL(rsp.url);
157
+ const isQData = redirectedURL.pathname.endsWith("/q-data.json");
158
+ if (!isQData || redirectedURL.origin !== location.origin) {
159
+ location.href = redirectedURL.href;
160
+ return;
161
+ }
162
+ }
163
+ if ((rsp.headers.get("content-type") || "").includes("json")) {
164
+ return rsp.text().then((text) => {
165
+ const [clientData] = internal._deserialize(text, element);
166
+ if (!clientData) {
167
+ location.href = url.href;
168
+ return;
169
+ }
170
+ if (opts?.clearCache) {
171
+ CLIENT_DATA_CACHE.delete(clientDataPath);
172
+ }
173
+ if (clientData.redirect) {
174
+ location.href = clientData.redirect;
175
+ } else if (opts?.action) {
176
+ const { action } = opts;
177
+ const actionData = clientData.loaders[action.id];
178
+ resolveFn = () => {
179
+ action.resolve({
180
+ status: rsp.status,
181
+ result: actionData
182
+ });
183
+ };
184
+ }
185
+ return clientData;
186
+ });
187
+ } else {
188
+ if (opts?.isPrefetch !== true) {
189
+ location.href = url.href;
190
+ }
191
+ return void 0;
192
+ }
193
+ });
194
+ if (!opts?.action) {
195
+ CLIENT_DATA_CACHE.set(clientDataPath, qData);
196
+ }
197
+ }
198
+ return qData.then((v) => {
199
+ if (!v) {
200
+ CLIENT_DATA_CACHE.delete(clientDataPath);
201
+ }
202
+ resolveFn && resolveFn();
203
+ return v;
204
+ });
205
+ };
206
+ const getFetchOptions = (action) => {
207
+ const actionData = action?.data;
208
+ if (!actionData) {
209
+ return {
210
+ cache: "no-cache",
211
+ headers: {
212
+ "Cache-Control": "no-cache",
213
+ Pragma: "no-cache"
214
+ }
215
+ };
216
+ }
217
+ if (actionData instanceof FormData) {
218
+ return {
219
+ method: "POST",
220
+ body: actionData
221
+ };
222
+ } else {
223
+ return {
224
+ method: "POST",
225
+ body: JSON.stringify(actionData),
226
+ headers: {
227
+ "Content-Type": "application/json, charset=UTF-8"
228
+ }
229
+ };
230
+ }
231
+ };
232
+ const RouteStateContext = /* @__PURE__ */ core.createContextId("qc-s");
233
+ const ContentContext = /* @__PURE__ */ core.createContextId("qc-c");
234
+ const ContentInternalContext = /* @__PURE__ */ core.createContextId("qc-ic");
235
+ const DocumentHeadContext = /* @__PURE__ */ core.createContextId("qc-h");
236
+ const RouteLocationContext = /* @__PURE__ */ core.createContextId("qc-l");
237
+ const RouteNavigateContext = /* @__PURE__ */ core.createContextId("qc-n");
238
+ const RouteActionContext = /* @__PURE__ */ core.createContextId("qc-a");
239
+ const RouteInternalContext = /* @__PURE__ */ core.createContextId("qc-ir");
240
+ const RoutePreventNavigateContext = /* @__PURE__ */ core.createContextId("qc-p");
241
+ const useContent = () => core.useContext(ContentContext);
242
+ const useDocumentHead = () => core.useContext(DocumentHeadContext);
243
+ const useLocation = () => core.useContext(RouteLocationContext);
244
+ const useNavigate = () => core.useContext(RouteNavigateContext);
245
+ const usePreventNavigateQrl = (fn) => {
246
+ if (!__EXPERIMENTAL__.preventNavigate) {
247
+ throw new Error('usePreventNavigate$ is experimental and must be enabled with `experimental: ["preventNavigate"]` in the `qwikVite` plugin.');
248
+ }
249
+ const registerPreventNav = core.useContext(RoutePreventNavigateContext);
250
+ core.useVisibleTask$(() => registerPreventNav(fn));
251
+ };
252
+ const usePreventNavigate$ = core.implicit$FirstArg(usePreventNavigateQrl);
253
+ const useAction = () => core.useContext(RouteActionContext);
254
+ const useQwikRouterEnv = () => core.noSerialize(core.useServerData("qwikrouter"));
255
+ const Link = core.component$((props) => {
256
+ const nav = useNavigate();
257
+ const loc = useLocation();
258
+ const originalHref = props.href;
259
+ const { onClick$, prefetch: prefetchProp, reload, replaceState, scroll, ...linkProps } = /* @__PURE__ */ (() => props)();
260
+ const clientNavPath = core.untrack(() => getClientNavPath({
261
+ ...linkProps,
262
+ reload
263
+ }, loc));
264
+ linkProps.href = clientNavPath || originalHref;
265
+ const prefetchData = core.untrack(() => !!clientNavPath && prefetchProp !== false && prefetchProp !== "js" && shouldPrefetchData(clientNavPath, loc) || void 0);
266
+ const prefetch = core.untrack(() => prefetchData || !!clientNavPath && prefetchProp !== false && shouldPrefetchSymbols(clientNavPath, loc));
267
+ const handlePrefetch = prefetch ? core.$((_, elm) => {
268
+ if (navigator.connection?.saveData) {
269
+ return;
270
+ }
271
+ if (elm && elm.href) {
272
+ const url = new URL(elm.href);
273
+ prefetchSymbols(url.pathname);
274
+ if (elm.hasAttribute("data-prefetch")) {
275
+ loadClientData(url, elm, {
276
+ prefetchSymbols: false,
277
+ isPrefetch: true
278
+ });
279
+ }
280
+ }
281
+ }) : void 0;
282
+ const preventDefault = clientNavPath ? core.sync$((event, target) => {
283
+ if (!(event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)) {
284
+ event.preventDefault();
285
+ }
286
+ }) : void 0;
287
+ const handleClick = clientNavPath ? core.$(async (event, elm) => {
288
+ if (event.defaultPrevented) {
289
+ if (elm.hasAttribute("q:nbs")) {
290
+ await nav(location.href, {
291
+ type: "popstate"
292
+ });
293
+ } else if (elm.href) {
294
+ elm.setAttribute("aria-pressed", "true");
295
+ await nav(elm.href, {
296
+ forceReload: reload,
297
+ replaceState,
298
+ scroll
299
+ });
300
+ elm.removeAttribute("aria-pressed");
301
+ }
302
+ }
303
+ }) : void 0;
304
+ return /* @__PURE__ */ jsxRuntime.jsx("a", {
305
+ "q:link": !!clientNavPath,
306
+ ...linkProps,
307
+ onClick$: [
308
+ preventDefault,
309
+ onClick$,
310
+ handleClick
311
+ ],
312
+ "data-prefetch": prefetchData,
313
+ onMouseOver$: [
314
+ linkProps.onMouseOver$,
315
+ handlePrefetch
316
+ ],
317
+ onFocus$: [
318
+ linkProps.onFocus$,
319
+ handlePrefetch
320
+ ],
321
+ // Don't prefetch on visible in dev mode
322
+ onQVisible$: [
323
+ linkProps.onQVisible$,
324
+ !build.isDev ? handlePrefetch : void 0
325
+ ],
326
+ children: /* @__PURE__ */ jsxRuntime.jsx(core.Slot, {})
327
+ });
328
+ });
329
+ const resolveHead = (endpoint, routeLocation, contentModules, locale) => {
330
+ const head = createDocumentHead();
331
+ const getData = (loaderOrAction) => {
332
+ const id = loaderOrAction.__id;
333
+ if (loaderOrAction.__brand === "server_loader") {
334
+ if (!(id in endpoint.loaders)) {
335
+ throw new Error("You can not get the returned data of a loader that has not been executed for this request.");
336
+ }
337
+ }
338
+ const data = endpoint.loaders[id];
339
+ if (isPromise(data)) {
340
+ throw new Error("Loaders returning a promise can not be resolved for the head function.");
341
+ }
342
+ return data;
343
+ };
344
+ const headProps = {
345
+ head,
346
+ withLocale: (fn) => core.withLocale(locale, fn),
347
+ resolveValue: getData,
348
+ ...routeLocation
349
+ };
350
+ for (let i = contentModules.length - 1; i >= 0; i--) {
351
+ const contentModuleHead = contentModules[i] && contentModules[i].head;
352
+ if (contentModuleHead) {
353
+ if (typeof contentModuleHead === "function") {
354
+ resolveDocumentHead(head, core.withLocale(locale, () => contentModuleHead(headProps)));
355
+ } else if (typeof contentModuleHead === "object") {
356
+ resolveDocumentHead(head, contentModuleHead);
357
+ }
358
+ }
359
+ }
360
+ return headProps.head;
361
+ };
362
+ const resolveDocumentHead = (resolvedHead, updatedHead) => {
363
+ if (typeof updatedHead.title === "string") {
364
+ resolvedHead.title = updatedHead.title;
365
+ }
366
+ mergeArray(resolvedHead.meta, updatedHead.meta);
367
+ mergeArray(resolvedHead.links, updatedHead.links);
368
+ mergeArray(resolvedHead.styles, updatedHead.styles);
369
+ mergeArray(resolvedHead.scripts, updatedHead.scripts);
370
+ Object.assign(resolvedHead.frontmatter, updatedHead.frontmatter);
371
+ };
372
+ const mergeArray = (existingArr, newArr) => {
373
+ if (Array.isArray(newArr)) {
374
+ for (const newItem of newArr) {
375
+ if (typeof newItem.key === "string") {
376
+ const existingIndex = existingArr.findIndex((i) => i.key === newItem.key);
377
+ if (existingIndex > -1) {
378
+ existingArr[existingIndex] = newItem;
379
+ continue;
380
+ }
381
+ }
382
+ existingArr.push(newItem);
383
+ }
384
+ }
385
+ };
386
+ const createDocumentHead = () => ({
387
+ title: "",
388
+ meta: [],
389
+ links: [],
390
+ styles: [],
391
+ scripts: [],
392
+ frontmatter: {}
393
+ });
394
+ function matchRoute(route, path) {
395
+ const routeIdx = startIdxSkipSlash(route);
396
+ const routeLength = lengthNoTrailingSlash(route);
397
+ const pathIdx = startIdxSkipSlash(path);
398
+ const pathLength = lengthNoTrailingSlash(path);
399
+ return matchRoutePart(route, routeIdx, routeLength, path, pathIdx, pathLength);
400
+ }
401
+ function matchRoutePart(route, routeIdx, routeLength, path, pathIdx, pathLength) {
402
+ let params = null;
403
+ while (routeIdx < routeLength) {
404
+ const routeCh = route.charCodeAt(routeIdx++);
405
+ const pathCh = path.charCodeAt(pathIdx++);
406
+ if (routeCh === 91) {
407
+ const isMany = isThreeDots(route, routeIdx);
408
+ const paramNameStart = routeIdx + (isMany ? 3 : 0);
409
+ const paramNameEnd = scan(route, paramNameStart, routeLength, 93);
410
+ const paramName = route.substring(paramNameStart, paramNameEnd);
411
+ const paramSuffixEnd = scan(route, paramNameEnd + 1, routeLength, 47);
412
+ const suffix = route.substring(paramNameEnd + 1, paramSuffixEnd);
413
+ routeIdx = paramNameEnd + 1;
414
+ const paramValueStart = pathIdx - 1;
415
+ if (isMany) {
416
+ const match = recursiveScan(paramName, suffix, path, paramValueStart, pathLength, route, routeIdx + suffix.length + 1, routeLength);
417
+ if (match) {
418
+ return Object.assign(params || (params = {}), match);
419
+ }
420
+ }
421
+ const paramValueEnd = scan(path, paramValueStart, pathLength, 47, suffix);
422
+ if (paramValueEnd == -1) {
423
+ return null;
424
+ }
425
+ const paramValue = path.substring(paramValueStart, paramValueEnd);
426
+ if (!isMany && !suffix && !paramValue) {
427
+ return null;
428
+ }
429
+ pathIdx = paramValueEnd;
430
+ (params || (params = {}))[paramName] = decodeURIComponent(paramValue);
431
+ } else if (routeCh !== pathCh) {
432
+ if (!(isNaN(pathCh) && isRestParameter(route, routeIdx))) {
433
+ return null;
434
+ }
435
+ }
436
+ }
437
+ if (allConsumed(route, routeIdx) && allConsumed(path, pathIdx)) {
438
+ return params || {};
439
+ } else {
440
+ return null;
441
+ }
442
+ }
443
+ function isRestParameter(text, idx) {
444
+ return text.charCodeAt(idx) === 91 && isThreeDots(text, idx + 1);
445
+ }
446
+ function lengthNoTrailingSlash(text) {
447
+ const length = text.length;
448
+ return length > 1 && text.charCodeAt(length - 1) === 47 ? length - 1 : length;
449
+ }
450
+ function allConsumed(text, idx) {
451
+ const length = text.length;
452
+ return idx >= length || idx == length - 1 && text.charCodeAt(idx) === 47;
453
+ }
454
+ function startIdxSkipSlash(text) {
455
+ return text.charCodeAt(0) === 47 ? 1 : 0;
456
+ }
457
+ function isThreeDots(text, idx) {
458
+ return text.charCodeAt(idx) === 46 && text.charCodeAt(idx + 1) === 46 && text.charCodeAt(idx + 2) === 46;
459
+ }
460
+ function scan(text, idx, end, ch, suffix = "") {
461
+ while (idx < end && text.charCodeAt(idx) !== ch) {
462
+ idx++;
463
+ }
464
+ const suffixLength = suffix.length;
465
+ for (let i = 0; i < suffixLength; i++) {
466
+ if (text.charCodeAt(idx - suffixLength + i) !== suffix.charCodeAt(i)) {
467
+ return -1;
468
+ }
469
+ }
470
+ return idx - suffixLength;
471
+ }
472
+ function recursiveScan(paramName, suffix, path, pathStart, pathLength, route, routeStart, routeLength) {
473
+ if (path.charCodeAt(pathStart) === 47) {
474
+ pathStart++;
475
+ }
476
+ let pathIdx = pathLength;
477
+ const sep = suffix + "/";
478
+ while (pathIdx >= pathStart) {
479
+ const match = matchRoutePart(route, routeStart, routeLength, path, pathIdx, pathLength);
480
+ if (match) {
481
+ let value = path.substring(pathStart, Math.min(pathIdx, pathLength));
482
+ if (value.endsWith(sep)) {
483
+ value = value.substring(0, value.length - sep.length);
484
+ }
485
+ match[paramName] = decodeURIComponent(value);
486
+ return match;
487
+ }
488
+ const newPathIdx = lastIndexOf(path, pathStart, sep, pathIdx, pathStart - 1) + sep.length;
489
+ if (pathIdx === newPathIdx) {
490
+ break;
491
+ }
492
+ pathIdx = newPathIdx;
493
+ }
494
+ return null;
495
+ }
496
+ function lastIndexOf(text, start, match, searchIdx, notFoundIdx) {
497
+ let idx = text.lastIndexOf(match, searchIdx);
498
+ if (idx == searchIdx - match.length) {
499
+ idx = text.lastIndexOf(match, searchIdx - match.length - 1);
500
+ }
501
+ return idx > start ? idx : notFoundIdx;
502
+ }
503
+ const loadRoute = async (routes, menus, cacheModules, pathname) => {
504
+ if (!Array.isArray(routes)) {
505
+ return null;
506
+ }
507
+ for (const routeData of routes) {
508
+ const routeName = routeData[0];
509
+ const params = matchRoute(routeName, pathname);
510
+ if (!params) {
511
+ continue;
512
+ }
513
+ const loaders = routeData[1];
514
+ const routeBundleNames = routeData[3];
515
+ const modules = new Array(loaders.length);
516
+ const pendingLoads = [];
517
+ loaders.forEach((moduleLoader, i) => {
518
+ loadModule(moduleLoader, pendingLoads, (routeModule) => modules[i] = routeModule, cacheModules);
519
+ });
520
+ const menuLoader = getMenuLoader(menus, pathname);
521
+ let menu = void 0;
522
+ loadModule(menuLoader, pendingLoads, (menuModule) => menu = menuModule?.default, cacheModules);
523
+ if (pendingLoads.length > 0) {
524
+ await Promise.all(pendingLoads);
525
+ }
526
+ return [
527
+ routeName,
528
+ params,
529
+ modules,
530
+ deepFreeze(menu),
531
+ routeBundleNames
532
+ ];
533
+ }
534
+ return null;
535
+ };
536
+ const loadModule = (moduleLoader, pendingLoads, moduleSetter, cacheModules) => {
537
+ if (typeof moduleLoader === "function") {
538
+ const loadedModule = MODULE_CACHE.get(moduleLoader);
539
+ if (loadedModule) {
540
+ moduleSetter(loadedModule);
541
+ } else {
542
+ const moduleOrPromise = moduleLoader();
543
+ if (typeof moduleOrPromise.then === "function") {
544
+ pendingLoads.push(moduleOrPromise.then((loadedModule2) => {
545
+ if (cacheModules !== false) {
546
+ MODULE_CACHE.set(moduleLoader, loadedModule2);
547
+ }
548
+ moduleSetter(loadedModule2);
549
+ }));
550
+ } else if (moduleOrPromise) {
551
+ moduleSetter(moduleOrPromise);
552
+ }
553
+ }
554
+ }
555
+ };
556
+ const getMenuLoader = (menus, pathname) => {
557
+ if (menus) {
558
+ pathname = pathname.endsWith("/") ? pathname : pathname + "/";
559
+ const menu = menus.find((m) => m[0] === pathname || pathname.startsWith(m[0] + (pathname.endsWith("/") ? "" : "/")));
560
+ if (menu) {
561
+ return menu[1];
562
+ }
563
+ }
564
+ };
565
+ function callRestoreScrollOnDocument() {
566
+ if (document.__q_scroll_restore__) {
567
+ document.__q_scroll_restore__();
568
+ document.__q_scroll_restore__ = void 0;
569
+ }
570
+ }
571
+ const restoreScroll = (type, toUrl2, fromUrl, scroller, scrollState) => {
572
+ if (type === "popstate" && scrollState) {
573
+ scroller.scrollTo(scrollState.x, scrollState.y);
574
+ } else if (type === "link" || type === "form") {
575
+ if (!hashScroll(toUrl2, fromUrl)) {
576
+ scroller.scrollTo(0, 0);
577
+ }
578
+ }
579
+ };
580
+ const hashScroll = (toUrl2, fromUrl) => {
581
+ const elmId = toUrl2.hash.slice(1);
582
+ const elm = elmId && document.getElementById(elmId);
583
+ if (elm) {
584
+ elm.scrollIntoView();
585
+ return true;
586
+ } else if (!elm && toUrl2.hash && isSamePath(toUrl2, fromUrl)) {
587
+ return true;
588
+ }
589
+ return false;
590
+ };
591
+ const currentScrollState = (elm) => {
592
+ return {
593
+ x: elm.scrollLeft,
594
+ y: elm.scrollTop,
595
+ w: Math.max(elm.scrollWidth, elm.clientWidth),
596
+ h: Math.max(elm.scrollHeight, elm.clientHeight)
597
+ };
598
+ };
599
+ const getScrollHistory = () => {
600
+ const state = history.state;
601
+ return state?._qRouterScroll;
602
+ };
603
+ const saveScrollHistory = (scrollState) => {
604
+ const state = history.state || {};
605
+ state._qRouterScroll = scrollState;
606
+ history.replaceState(state, "");
607
+ };
608
+ const spaInit = core.event$((_, el) => {
609
+ const win = window;
610
+ const spa = "_qRouterSPA";
611
+ const initPopstate = "_qRouterInitPopstate";
612
+ const initAnchors = "_qRouterInitAnchors";
613
+ const initVisibility = "_qRouterInitVisibility";
614
+ const initScroll = "_qRouterInitScroll";
615
+ if (!win[spa] && !win[initPopstate] && !win[initAnchors] && !win[initVisibility] && !win[initScroll]) {
616
+ const currentPath = location.pathname + location.search;
617
+ const historyPatch = "_qRouterHistoryPatch";
618
+ const bootstrap = "_qRouterBootstrap";
619
+ const scrollEnabled = "_qRouterScrollEnabled";
620
+ const debounceTimeout = "_qRouterScrollDebounce";
621
+ const scrollHistory = "_qRouterScroll";
622
+ const checkAndScroll = (scrollState) => {
623
+ if (scrollState) {
624
+ win.scrollTo(scrollState.x, scrollState.y);
625
+ }
626
+ };
627
+ const currentScrollState2 = () => {
628
+ const elm = document.documentElement;
629
+ return {
630
+ x: elm.scrollLeft,
631
+ y: elm.scrollTop,
632
+ w: Math.max(elm.scrollWidth, elm.clientWidth),
633
+ h: Math.max(elm.scrollHeight, elm.clientHeight)
634
+ };
635
+ };
636
+ const saveScrollState = (scrollState) => {
637
+ const state = history.state || {};
638
+ state[scrollHistory] = scrollState || currentScrollState2();
639
+ history.replaceState(state, "");
640
+ };
641
+ saveScrollState();
642
+ win[initPopstate] = () => {
643
+ if (win[spa]) {
644
+ return;
645
+ }
646
+ win[scrollEnabled] = false;
647
+ clearTimeout(win[debounceTimeout]);
648
+ if (currentPath !== location.pathname + location.search) {
649
+ const getContainer = (el2) => el2.closest("[q\\:container]:not([q\\:container=html]):not([q\\:container=text])");
650
+ const link = getContainer(el)?.querySelector("a[q\\:link]");
651
+ if (link) {
652
+ const container = getContainer(link);
653
+ const bootstrapLink = link.cloneNode();
654
+ bootstrapLink.setAttribute("q:nbs", "");
655
+ bootstrapLink.style.display = "none";
656
+ container.appendChild(bootstrapLink);
657
+ win[bootstrap] = bootstrapLink;
658
+ bootstrapLink.click();
659
+ } else {
660
+ location.reload();
661
+ }
662
+ } else {
663
+ if (history.scrollRestoration === "manual") {
664
+ const scrollState = history.state?.[scrollHistory];
665
+ checkAndScroll(scrollState);
666
+ win[scrollEnabled] = true;
667
+ }
668
+ }
669
+ };
670
+ if (!win[historyPatch]) {
671
+ win[historyPatch] = true;
672
+ const pushState = history.pushState;
673
+ const replaceState = history.replaceState;
674
+ const prepareState = (state) => {
675
+ if (state === null || typeof state === "undefined") {
676
+ state = {};
677
+ } else if (state?.constructor !== Object) {
678
+ state = {
679
+ _data: state
680
+ };
681
+ if (build.isDev) {
682
+ console.warn("In a Qwik SPA context, `history.state` is used to store scroll state. Direct calls to `pushState()` and `replaceState()` must supply an actual Object type. We need to be able to automatically attach the scroll state to your state object. A new state object has been created, your data has been moved to: `history.state._data`");
683
+ }
684
+ }
685
+ state._qRouterScroll = state._qRouterScroll || currentScrollState2();
686
+ return state;
687
+ };
688
+ history.pushState = (state, title, url) => {
689
+ state = prepareState(state);
690
+ return pushState.call(history, state, title, url);
691
+ };
692
+ history.replaceState = (state, title, url) => {
693
+ state = prepareState(state);
694
+ return replaceState.call(history, state, title, url);
695
+ };
696
+ }
697
+ win[initAnchors] = (event) => {
698
+ if (win[spa] || event.defaultPrevented) {
699
+ return;
700
+ }
701
+ const target = event.target.closest("a[href]");
702
+ if (target && !target.hasAttribute("preventdefault:click")) {
703
+ const href = target.getAttribute("href");
704
+ const prev = new URL(location.href);
705
+ const dest = new URL(href, prev);
706
+ const sameOrigin = dest.origin === prev.origin;
707
+ const samePath = dest.pathname + dest.search === prev.pathname + prev.search;
708
+ if (sameOrigin && samePath) {
709
+ event.preventDefault();
710
+ if (dest.href !== prev.href) {
711
+ history.pushState(null, "", dest);
712
+ }
713
+ if (!dest.hash) {
714
+ if (dest.href.endsWith("#")) {
715
+ window.scrollTo(0, 0);
716
+ } else {
717
+ win[scrollEnabled] = false;
718
+ clearTimeout(win[debounceTimeout]);
719
+ saveScrollState({
720
+ ...currentScrollState2(),
721
+ x: 0,
722
+ y: 0
723
+ });
724
+ location.reload();
725
+ }
726
+ } else {
727
+ const elmId = dest.hash.slice(1);
728
+ const elm = document.getElementById(elmId);
729
+ if (elm) {
730
+ elm.scrollIntoView();
731
+ }
732
+ }
733
+ }
734
+ }
735
+ };
736
+ win[initVisibility] = () => {
737
+ if (!win[spa] && win[scrollEnabled] && document.visibilityState === "hidden") {
738
+ saveScrollState();
739
+ }
740
+ };
741
+ win[initScroll] = () => {
742
+ if (win[spa] || !win[scrollEnabled]) {
743
+ return;
744
+ }
745
+ clearTimeout(win[debounceTimeout]);
746
+ win[debounceTimeout] = setTimeout(() => {
747
+ saveScrollState();
748
+ win[debounceTimeout] = void 0;
749
+ }, 200);
750
+ };
751
+ win[scrollEnabled] = true;
752
+ setTimeout(() => {
753
+ addEventListener("popstate", win[initPopstate]);
754
+ addEventListener("scroll", win[initScroll], {
755
+ passive: true
756
+ });
757
+ document.body.addEventListener("click", win[initAnchors]);
758
+ if (!win.navigation) {
759
+ document.addEventListener("visibilitychange", win[initVisibility], {
760
+ passive: true
761
+ });
762
+ }
763
+ }, 0);
764
+ }
765
+ });
766
+ const QWIK_CITY_SCROLLER = "_qCityScroller";
767
+ const QWIK_ROUTER_SCROLLER = "_qRouterScroller";
768
+ const preventNav = {};
769
+ const internalState = {
770
+ navCount: 0
771
+ };
772
+ const QwikRouterProvider = core.component$((props) => {
773
+ core.useStyles$(`:root{view-transition-name:none}`);
774
+ const env = useQwikRouterEnv();
775
+ if (!env?.params) {
776
+ throw new Error(`Missing Qwik Router Env Data for help visit https://github.com/QwikDev/qwik/issues/6237`);
777
+ }
778
+ const urlEnv = core.useServerData("url");
779
+ if (!urlEnv) {
780
+ throw new Error(`Missing Qwik URL Env Data`);
781
+ }
782
+ const url = new URL(urlEnv);
783
+ const routeLocation = core.useStore({
784
+ url,
785
+ params: env.params,
786
+ isNavigating: false,
787
+ prevUrl: void 0
788
+ }, {
789
+ deep: false
790
+ });
791
+ const navResolver = {};
792
+ const loaderState = internal._weakSerialize(core.useStore(env.response.loaders, {
793
+ deep: false
794
+ }));
795
+ const routeInternal = core.useSignal({
796
+ type: "initial",
797
+ dest: url,
798
+ forceReload: false,
799
+ replaceState: false,
800
+ scroll: true
801
+ });
802
+ const documentHead = core.useStore(createDocumentHead);
803
+ const content = core.useStore({
804
+ headings: void 0,
805
+ menu: void 0
806
+ });
807
+ const contentInternal = core.useSignal();
808
+ const currentActionId = env.response.action;
809
+ const currentAction = currentActionId ? env.response.loaders[currentActionId] : void 0;
810
+ const actionState = core.useSignal(currentAction ? {
811
+ id: currentActionId,
812
+ data: env.response.formData,
813
+ output: {
814
+ result: currentAction,
815
+ status: env.response.status
816
+ }
817
+ } : void 0);
818
+ const registerPreventNav = core.$((fn$) => {
819
+ if (!build.isBrowser) {
820
+ return;
821
+ }
822
+ preventNav.$handler$ || (preventNav.$handler$ = (event) => {
823
+ internalState.navCount++;
824
+ if (!preventNav.$cbs$) {
825
+ return;
826
+ }
827
+ const prevents = [
828
+ ...preventNav.$cbs$.values()
829
+ ].map((cb) => cb.resolved ? cb.resolved() : cb());
830
+ if (prevents.some(Boolean)) {
831
+ event.preventDefault();
832
+ event.returnValue = true;
833
+ }
834
+ });
835
+ (preventNav.$cbs$ || (preventNav.$cbs$ = /* @__PURE__ */ new Set())).add(fn$);
836
+ fn$.resolve();
837
+ window.addEventListener("beforeunload", preventNav.$handler$);
838
+ return () => {
839
+ if (preventNav.$cbs$) {
840
+ preventNav.$cbs$.delete(fn$);
841
+ if (!preventNav.$cbs$.size) {
842
+ preventNav.$cbs$ = void 0;
843
+ window.removeEventListener("beforeunload", preventNav.$handler$);
844
+ }
845
+ }
846
+ };
847
+ });
848
+ const goto = core.$(async (path, opt) => {
849
+ const { type = "link", forceReload = path === void 0, replaceState = false, scroll = true } = typeof opt === "object" ? opt : {
850
+ forceReload: opt
851
+ };
852
+ internalState.navCount++;
853
+ const lastDest = routeInternal.value.dest;
854
+ const dest = path === void 0 ? lastDest : typeof path === "number" ? path : toUrl(path, routeLocation.url);
855
+ if (preventNav.$cbs$ && (forceReload || typeof dest === "number" || !isSamePath(dest, lastDest) || !isSameOrigin(dest, lastDest))) {
856
+ const ourNavId = internalState.navCount;
857
+ const prevents = await Promise.all([
858
+ ...preventNav.$cbs$.values()
859
+ ].map((cb) => cb(dest)));
860
+ if (ourNavId !== internalState.navCount || prevents.some(Boolean)) {
861
+ if (ourNavId === internalState.navCount && type === "popstate") {
862
+ history.pushState(null, "", lastDest);
863
+ }
864
+ return;
865
+ }
866
+ }
867
+ if (typeof dest === "number") {
868
+ if (build.isBrowser) {
869
+ history.go(dest);
870
+ }
871
+ return;
872
+ }
873
+ if (!isSameOrigin(dest, lastDest)) {
874
+ if (build.isBrowser) {
875
+ location.href = dest.href;
876
+ }
877
+ return;
878
+ }
879
+ if (!forceReload && isSamePath(dest, lastDest)) {
880
+ if (build.isBrowser) {
881
+ if (type === "link" && dest.href !== location.href) {
882
+ history.pushState(null, "", dest);
883
+ }
884
+ let scroller = document.getElementById(QWIK_ROUTER_SCROLLER);
885
+ if (!scroller) {
886
+ scroller = document.getElementById(QWIK_CITY_SCROLLER);
887
+ if (scroller) {
888
+ console.warn(`Please update your scroller ID to "${QWIK_ROUTER_SCROLLER}" as "${QWIK_CITY_SCROLLER}" is deprecated and will be removed in V3`);
889
+ }
890
+ }
891
+ if (!scroller) {
892
+ scroller = document.documentElement;
893
+ }
894
+ restoreScroll(type, dest, new URL(location.href), scroller, getScrollHistory());
895
+ if (type === "popstate") {
896
+ window._qRouterScrollEnabled = true;
897
+ }
898
+ }
899
+ return;
900
+ }
901
+ routeInternal.value = {
902
+ type,
903
+ dest,
904
+ forceReload,
905
+ replaceState,
906
+ scroll
907
+ };
908
+ if (build.isBrowser) {
909
+ loadClientData(dest, internal._getContextElement());
910
+ loadRoute(qwikRouterConfig__namespace.routes, qwikRouterConfig__namespace.menus, qwikRouterConfig__namespace.cacheModules, dest.pathname);
911
+ }
912
+ actionState.value = void 0;
913
+ routeLocation.isNavigating = true;
914
+ return new Promise((resolve) => {
915
+ navResolver.r = resolve;
916
+ });
917
+ });
918
+ core.useContextProvider(ContentContext, content);
919
+ core.useContextProvider(ContentInternalContext, contentInternal);
920
+ core.useContextProvider(DocumentHeadContext, documentHead);
921
+ core.useContextProvider(RouteLocationContext, routeLocation);
922
+ core.useContextProvider(RouteNavigateContext, goto);
923
+ core.useContextProvider(RouteStateContext, loaderState);
924
+ core.useContextProvider(RouteActionContext, actionState);
925
+ core.useContextProvider(RouteInternalContext, routeInternal);
926
+ core.useContextProvider(RoutePreventNavigateContext, registerPreventNav);
927
+ core.useTask$(({ track }) => {
928
+ async function run() {
929
+ const [navigation, action] = track(() => [
930
+ routeInternal.value,
931
+ actionState.value
932
+ ]);
933
+ const locale = core.getLocale("");
934
+ const prevUrl = routeLocation.url;
935
+ const navType = action ? "form" : navigation.type;
936
+ const replaceState = navigation.replaceState;
937
+ let trackUrl;
938
+ let clientPageData;
939
+ let loadedRoute = null;
940
+ let elm;
941
+ if (build.isServer) {
942
+ trackUrl = new URL(navigation.dest, routeLocation.url);
943
+ loadedRoute = env.loadedRoute;
944
+ clientPageData = env.response;
945
+ } else {
946
+ trackUrl = new URL(navigation.dest, location);
947
+ if (trackUrl.pathname.endsWith("/")) {
948
+ if (!qwikRouterConfig__namespace.trailingSlash) {
949
+ trackUrl.pathname = trackUrl.pathname.slice(0, -1);
950
+ }
951
+ } else if (qwikRouterConfig__namespace.trailingSlash) {
952
+ trackUrl.pathname += "/";
953
+ }
954
+ let loadRoutePromise = loadRoute(qwikRouterConfig__namespace.routes, qwikRouterConfig__namespace.menus, qwikRouterConfig__namespace.cacheModules, trackUrl.pathname);
955
+ elm = internal._getContextElement();
956
+ const pageData = clientPageData = await loadClientData(trackUrl, elm, {
957
+ action,
958
+ clearCache: true
959
+ });
960
+ if (!pageData) {
961
+ routeInternal.untrackedValue = {
962
+ type: navType,
963
+ dest: trackUrl
964
+ };
965
+ return;
966
+ }
967
+ const newHref = pageData.href;
968
+ const newURL = new URL(newHref, trackUrl);
969
+ if (!isSamePath(newURL, trackUrl)) {
970
+ trackUrl = newURL;
971
+ loadRoutePromise = loadRoute(qwikRouterConfig__namespace.routes, qwikRouterConfig__namespace.menus, qwikRouterConfig__namespace.cacheModules, trackUrl.pathname);
972
+ }
973
+ try {
974
+ loadedRoute = await loadRoutePromise;
975
+ } catch (e) {
976
+ window.location.href = newHref;
977
+ return;
978
+ }
979
+ }
980
+ if (loadedRoute) {
981
+ const [routeName, params, mods, menu] = loadedRoute;
982
+ const contentModules = mods;
983
+ const pageModule = contentModules[contentModules.length - 1];
984
+ const isRedirect = navType === "form" && !isSamePath(trackUrl, prevUrl);
985
+ if (navigation.dest.search && !isRedirect) {
986
+ trackUrl.search = navigation.dest.search;
987
+ }
988
+ routeLocation.prevUrl = prevUrl;
989
+ routeLocation.url = trackUrl;
990
+ routeLocation.params = {
991
+ ...params
992
+ };
993
+ routeInternal.untrackedValue = {
994
+ type: navType,
995
+ dest: trackUrl
996
+ };
997
+ const resolvedHead = resolveHead(clientPageData, routeLocation, contentModules, locale);
998
+ content.headings = pageModule.headings;
999
+ content.menu = menu;
1000
+ contentInternal.value = core.noSerialize(contentModules);
1001
+ documentHead.links = resolvedHead.links;
1002
+ documentHead.meta = resolvedHead.meta;
1003
+ documentHead.styles = resolvedHead.styles;
1004
+ documentHead.scripts = resolvedHead.scripts;
1005
+ documentHead.title = resolvedHead.title;
1006
+ documentHead.frontmatter = resolvedHead.frontmatter;
1007
+ if (build.isBrowser) {
1008
+ if (props.viewTransition !== false) {
1009
+ document.__q_view_transition__ = true;
1010
+ }
1011
+ let scrollState;
1012
+ if (navType === "popstate") {
1013
+ scrollState = getScrollHistory();
1014
+ }
1015
+ const scroller = document.getElementById(QWIK_ROUTER_SCROLLER) ?? document.documentElement;
1016
+ if (navigation.scroll && (!navigation.forceReload || !isSamePath(trackUrl, prevUrl)) && (navType === "link" || navType === "popstate") || isRedirect) {
1017
+ document.__q_scroll_restore__ = () => restoreScroll(navType, trackUrl, prevUrl, scroller, scrollState);
1018
+ }
1019
+ const loaders = clientPageData?.loaders;
1020
+ const win = window;
1021
+ if (loaders) {
1022
+ Object.assign(loaderState, loaders);
1023
+ }
1024
+ CLIENT_DATA_CACHE.clear();
1025
+ if (!win._qRouterSPA) {
1026
+ win._qRouterSPA = true;
1027
+ history.scrollRestoration = "manual";
1028
+ win.addEventListener("popstate", () => {
1029
+ win._qRouterScrollEnabled = false;
1030
+ clearTimeout(win._qRouterScrollDebounce);
1031
+ goto(location.href, {
1032
+ type: "popstate"
1033
+ });
1034
+ });
1035
+ win.removeEventListener("popstate", win._qRouterInitPopstate);
1036
+ win._qRouterInitPopstate = void 0;
1037
+ if (!win._qRouterHistoryPatch) {
1038
+ win._qRouterHistoryPatch = true;
1039
+ const pushState = history.pushState;
1040
+ const replaceState2 = history.replaceState;
1041
+ const prepareState = (state) => {
1042
+ if (state === null || typeof state === "undefined") {
1043
+ state = {};
1044
+ } else if (state?.constructor !== Object) {
1045
+ state = {
1046
+ _data: state
1047
+ };
1048
+ if (build.isDev) {
1049
+ console.warn("In a Qwik SPA context, `history.state` is used to store scroll state. Direct calls to `pushState()` and `replaceState()` must supply an actual Object type. We need to be able to automatically attach the scroll state to your state object. A new state object has been created, your data has been moved to: `history.state._data`");
1050
+ }
1051
+ }
1052
+ state._qRouterScroll = state._qRouterScroll || currentScrollState(scroller);
1053
+ return state;
1054
+ };
1055
+ history.pushState = (state, title, url2) => {
1056
+ state = prepareState(state);
1057
+ return pushState.call(history, state, title, url2);
1058
+ };
1059
+ history.replaceState = (state, title, url2) => {
1060
+ state = prepareState(state);
1061
+ return replaceState2.call(history, state, title, url2);
1062
+ };
1063
+ }
1064
+ document.body.addEventListener("click", (event) => {
1065
+ if (event.defaultPrevented) {
1066
+ return;
1067
+ }
1068
+ const target = event.target.closest("a[href]");
1069
+ if (target && !target.hasAttribute("preventdefault:click")) {
1070
+ const href = target.getAttribute("href");
1071
+ const prev = new URL(location.href);
1072
+ const dest = new URL(href, prev);
1073
+ if (isSameOrigin(dest, prev) && isSamePath(dest, prev)) {
1074
+ event.preventDefault();
1075
+ if (!dest.hash && !dest.href.endsWith("#")) {
1076
+ if (dest.href !== prev.href) {
1077
+ history.pushState(null, "", dest);
1078
+ }
1079
+ win._qRouterScrollEnabled = false;
1080
+ clearTimeout(win._qRouterScrollDebounce);
1081
+ saveScrollHistory({
1082
+ ...currentScrollState(scroller),
1083
+ x: 0,
1084
+ y: 0
1085
+ });
1086
+ location.reload();
1087
+ return;
1088
+ }
1089
+ goto(target.getAttribute("href"));
1090
+ }
1091
+ }
1092
+ });
1093
+ document.body.removeEventListener("click", win._qRouterInitAnchors);
1094
+ win._qRouterInitAnchors = void 0;
1095
+ if (!window.navigation) {
1096
+ document.addEventListener("visibilitychange", () => {
1097
+ if ((win._qRouterScrollEnabled || win._qCityScrollEnabled) && document.visibilityState === "hidden") {
1098
+ if (win._qCityScrollEnabled) {
1099
+ console.warn('"_qCityScrollEnabled" is deprecated. Use "_qRouterScrollEnabled" instead.');
1100
+ }
1101
+ const scrollState2 = currentScrollState(scroller);
1102
+ saveScrollHistory(scrollState2);
1103
+ }
1104
+ }, {
1105
+ passive: true
1106
+ });
1107
+ document.removeEventListener("visibilitychange", win._qRouterInitVisibility);
1108
+ win._qRouterInitVisibility = void 0;
1109
+ }
1110
+ win.addEventListener("scroll", () => {
1111
+ if (!win._qRouterScrollEnabled && !win._qCityScrollEnabled) {
1112
+ return;
1113
+ }
1114
+ clearTimeout(win._qRouterScrollDebounce);
1115
+ win._qRouterScrollDebounce = setTimeout(() => {
1116
+ const scrollState2 = currentScrollState(scroller);
1117
+ saveScrollHistory(scrollState2);
1118
+ win._qRouterScrollDebounce = void 0;
1119
+ }, 200);
1120
+ }, {
1121
+ passive: true
1122
+ });
1123
+ removeEventListener("scroll", win._qRouterInitScroll);
1124
+ win._qRouterInitScroll = void 0;
1125
+ win._qRouterBootstrap?.remove();
1126
+ win._qRouterBootstrap = void 0;
1127
+ spaInit.resolve();
1128
+ }
1129
+ if (navType !== "popstate") {
1130
+ win._qRouterScrollEnabled = false;
1131
+ clearTimeout(win._qRouterScrollDebounce);
1132
+ const scrollState2 = currentScrollState(scroller);
1133
+ saveScrollHistory(scrollState2);
1134
+ }
1135
+ clientNavigate(window, navType, prevUrl, trackUrl, replaceState);
1136
+ internal._waitUntilRendered(elm).then(() => {
1137
+ const container = internal._getQContainerElement(elm);
1138
+ container.setAttribute("q:route", routeName);
1139
+ const scrollState2 = currentScrollState(scroller);
1140
+ saveScrollHistory(scrollState2);
1141
+ win._qRouterScrollEnabled = true;
1142
+ if (build.isBrowser) {
1143
+ callRestoreScrollOnDocument();
1144
+ }
1145
+ routeLocation.isNavigating = false;
1146
+ navResolver.r?.();
1147
+ });
1148
+ }
1149
+ }
1150
+ }
1151
+ const promise = run();
1152
+ if (build.isServer) {
1153
+ return promise;
1154
+ } else {
1155
+ return;
1156
+ }
1157
+ });
1158
+ return /* @__PURE__ */ jsxRuntime.jsx(core.Slot, {});
1159
+ });
1160
+ const QwikCityProvider = QwikRouterProvider;
1161
+ const QwikRouterMockProvider = core.component$((props) => {
1162
+ const urlEnv = props.url ?? "http://localhost/";
1163
+ const url = new URL(urlEnv);
1164
+ const routeLocation = core.useStore({
1165
+ url,
1166
+ params: props.params ?? {},
1167
+ isNavigating: false,
1168
+ prevUrl: void 0
1169
+ }, {
1170
+ deep: false
1171
+ });
1172
+ const loaderState = core.useSignal({});
1173
+ const routeInternal = core.useSignal({
1174
+ type: "initial",
1175
+ dest: url
1176
+ });
1177
+ const goto = props.goto ?? core.$(async () => {
1178
+ console.warn("QwikRouterMockProvider: goto not provided");
1179
+ });
1180
+ const documentHead = core.useStore(createDocumentHead, {
1181
+ deep: false
1182
+ });
1183
+ const content = core.useStore({
1184
+ headings: void 0,
1185
+ menu: void 0
1186
+ }, {
1187
+ deep: false
1188
+ });
1189
+ const contentInternal = core.useSignal();
1190
+ const actionState = core.useSignal();
1191
+ core.useContextProvider(ContentContext, content);
1192
+ core.useContextProvider(ContentInternalContext, contentInternal);
1193
+ core.useContextProvider(DocumentHeadContext, documentHead);
1194
+ core.useContextProvider(RouteLocationContext, routeLocation);
1195
+ core.useContextProvider(RouteNavigateContext, goto);
1196
+ core.useContextProvider(RouteStateContext, loaderState);
1197
+ core.useContextProvider(RouteActionContext, actionState);
1198
+ core.useContextProvider(RouteInternalContext, routeInternal);
1199
+ return /* @__PURE__ */ jsxRuntime.jsx(core.Slot, {});
1200
+ });
1201
+ const QwikCityMockProvider = QwikRouterMockProvider;
1202
+ const RouterOutlet = core.component$(() => {
1203
+ const serverData = core.useServerData("containerAttributes");
1204
+ if (!serverData) {
1205
+ throw new Error("PrefetchServiceWorker component must be rendered on the server.");
1206
+ }
1207
+ const { value } = core.useContext(ContentInternalContext);
1208
+ if (value && value.length > 0) {
1209
+ const contentsLen = value.length;
1210
+ let cmp = null;
1211
+ for (let i = contentsLen - 1; i >= 0; i--) {
1212
+ if (value[i].default) {
1213
+ cmp = core.jsx(value[i].default, {
1214
+ children: cmp
1215
+ });
1216
+ }
1217
+ }
1218
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, {
1219
+ children: [
1220
+ cmp,
1221
+ !__EXPERIMENTAL__.noSPA && /* @__PURE__ */ jsxRuntime.jsx("script", {
1222
+ "document:onQCInit$": spaInit,
1223
+ "document:onQInit$": core.sync$(() => {
1224
+ ((w, h) => {
1225
+ if (!w._qcs && h.scrollRestoration === "manual") {
1226
+ w._qcs = true;
1227
+ const s = h.state?._qRouterScroll;
1228
+ if (s) {
1229
+ w.scrollTo(s.x, s.y);
1230
+ }
1231
+ document.dispatchEvent(new Event("qcinit"));
1232
+ }
1233
+ })(window, history);
1234
+ })
1235
+ })
1236
+ ]
1237
+ });
1238
+ }
1239
+ return core.SkipRender;
1240
+ });
1241
+ var store;
1242
+ function getGlobalConfig(config2) {
1243
+ return {
1244
+ lang: config2?.lang ?? store?.lang,
1245
+ message: config2?.message,
1246
+ abortEarly: config2?.abortEarly ?? store?.abortEarly,
1247
+ abortPipeEarly: config2?.abortPipeEarly ?? store?.abortPipeEarly
1248
+ };
1249
+ }
1250
+ function getDotPath(issue) {
1251
+ if (issue.path) {
1252
+ let key = "";
1253
+ for (const item of issue.path) {
1254
+ if (typeof item.key === "string" || typeof item.key === "number") {
1255
+ if (key) {
1256
+ key += `.${item.key}`;
1257
+ } else {
1258
+ key += item.key;
1259
+ }
1260
+ } else {
1261
+ return null;
1262
+ }
1263
+ }
1264
+ return key;
1265
+ }
1266
+ return null;
1267
+ }
1268
+ function flatten(issues) {
1269
+ const flatErrors = {};
1270
+ for (const issue of issues) {
1271
+ if (issue.path) {
1272
+ const dotPath = getDotPath(issue);
1273
+ if (dotPath) {
1274
+ if (!flatErrors.nested) {
1275
+ flatErrors.nested = {};
1276
+ }
1277
+ if (flatErrors.nested[dotPath]) {
1278
+ flatErrors.nested[dotPath].push(issue.message);
1279
+ } else {
1280
+ flatErrors.nested[dotPath] = [issue.message];
1281
+ }
1282
+ } else {
1283
+ if (flatErrors.other) {
1284
+ flatErrors.other.push(issue.message);
1285
+ } else {
1286
+ flatErrors.other = [issue.message];
1287
+ }
1288
+ }
1289
+ } else {
1290
+ if (flatErrors.root) {
1291
+ flatErrors.root.push(issue.message);
1292
+ } else {
1293
+ flatErrors.root = [issue.message];
1294
+ }
1295
+ }
1296
+ }
1297
+ return flatErrors;
1298
+ }
1299
+ async function safeParseAsync(schema, input, config2) {
1300
+ const dataset = await schema._run(
1301
+ { typed: false, value: input },
1302
+ getGlobalConfig(config2)
1303
+ );
1304
+ return {
1305
+ typed: dataset.typed,
1306
+ success: !dataset.issues,
1307
+ output: dataset.value,
1308
+ issues: dataset.issues
1309
+ };
1310
+ }
1311
+ const routeActionQrl = (actionQrl, ...rest) => {
1312
+ const { id, validators } = getValidators(rest, actionQrl);
1313
+ function action() {
1314
+ const loc = useLocation();
1315
+ const currentAction = useAction();
1316
+ const initialState = {
1317
+ actionPath: `?${QACTION_KEY}=${id}`,
1318
+ submitted: false,
1319
+ isRunning: false,
1320
+ status: void 0,
1321
+ value: void 0,
1322
+ formData: void 0
1323
+ };
1324
+ const state = core.useStore(() => {
1325
+ const value = currentAction.value;
1326
+ if (value && value?.id === id) {
1327
+ const data = value.data;
1328
+ if (data instanceof FormData) {
1329
+ initialState.formData = data;
1330
+ }
1331
+ if (value.output) {
1332
+ const { status, result } = value.output;
1333
+ initialState.status = status;
1334
+ initialState.value = result;
1335
+ }
1336
+ }
1337
+ return initialState;
1338
+ });
1339
+ const submit = core.$((input = {}) => {
1340
+ if (build.isServer) {
1341
+ throw new Error(`Actions can not be invoked within the server during SSR.
1342
+ Action.run() can only be called on the browser, for example when a user clicks a button, or submits a form.`);
1343
+ }
1344
+ let data;
1345
+ let form;
1346
+ if (input instanceof SubmitEvent) {
1347
+ form = input.target;
1348
+ data = new FormData(form);
1349
+ if ((input.submitter instanceof HTMLInputElement || input.submitter instanceof HTMLButtonElement) && input.submitter.name) {
1350
+ if (input.submitter.name) {
1351
+ data.append(input.submitter.name, input.submitter.value);
1352
+ }
1353
+ }
1354
+ } else {
1355
+ data = input;
1356
+ }
1357
+ return new Promise((resolve) => {
1358
+ if (data instanceof FormData) {
1359
+ state.formData = data;
1360
+ }
1361
+ state.submitted = true;
1362
+ state.isRunning = true;
1363
+ loc.isNavigating = true;
1364
+ currentAction.value = {
1365
+ data,
1366
+ id,
1367
+ resolve: core.noSerialize(resolve)
1368
+ };
1369
+ }).then(({ result, status }) => {
1370
+ state.isRunning = false;
1371
+ state.status = status;
1372
+ state.value = result;
1373
+ if (form) {
1374
+ if (form.getAttribute("data-spa-reset") === "true") {
1375
+ form.reset();
1376
+ }
1377
+ const detail = {
1378
+ status,
1379
+ value: result
1380
+ };
1381
+ form.dispatchEvent(new CustomEvent("submitcompleted", {
1382
+ bubbles: false,
1383
+ cancelable: false,
1384
+ composed: false,
1385
+ detail
1386
+ }));
1387
+ }
1388
+ return {
1389
+ status,
1390
+ value: result
1391
+ };
1392
+ });
1393
+ });
1394
+ initialState.submit = submit;
1395
+ return state;
1396
+ }
1397
+ action.__brand = "server_action";
1398
+ action.__validators = validators;
1399
+ action.__qrl = actionQrl;
1400
+ action.__id = id;
1401
+ Object.freeze(action);
1402
+ return action;
1403
+ };
1404
+ const globalActionQrl = (actionQrl, ...rest) => {
1405
+ const action = routeActionQrl(actionQrl, ...rest);
1406
+ if (build.isServer) {
1407
+ if (typeof globalThis._qwikActionsMap === "undefined") {
1408
+ globalThis._qwikActionsMap = /* @__PURE__ */ new Map();
1409
+ }
1410
+ globalThis._qwikActionsMap.set(action.__id, action);
1411
+ }
1412
+ return action;
1413
+ };
1414
+ const routeAction$ = /* @__PURE__ */ core.implicit$FirstArg(routeActionQrl);
1415
+ const globalAction$ = /* @__PURE__ */ core.implicit$FirstArg(globalActionQrl);
1416
+ const routeLoaderQrl = (loaderQrl, ...rest) => {
1417
+ const { id, validators } = getValidators(rest, loaderQrl);
1418
+ function loader() {
1419
+ return core.useContext(RouteStateContext, (state) => {
1420
+ if (!(id in state)) {
1421
+ throw new Error(`routeLoader$ "${loaderQrl.getSymbol()}" was invoked in a route where it was not declared.
1422
+ This is because the routeLoader$ was not exported in a 'layout.tsx' or 'index.tsx' file of the existing route.
1423
+ For more information check: https://qwik.dev/docs/route-loader/
1424
+
1425
+ If your are managing reusable logic or a library it is essential that this function is re-exported from within 'layout.tsx' or 'index.tsx file of the existing route otherwise it will not run or throw exception.
1426
+ For more information check: https://qwik.dev/docs/cookbook/re-exporting-loaders/`);
1427
+ }
1428
+ return internal._wrapProp(state, id);
1429
+ });
1430
+ }
1431
+ loader.__brand = "server_loader";
1432
+ loader.__qrl = loaderQrl;
1433
+ loader.__validators = validators;
1434
+ loader.__id = id;
1435
+ Object.freeze(loader);
1436
+ return loader;
1437
+ };
1438
+ const routeLoader$ = /* @__PURE__ */ core.implicit$FirstArg(routeLoaderQrl);
1439
+ const validatorQrl = (validator) => {
1440
+ if (build.isServer) {
1441
+ return {
1442
+ validate: validator
1443
+ };
1444
+ }
1445
+ return void 0;
1446
+ };
1447
+ const validator$ = /* @__PURE__ */ core.implicit$FirstArg(validatorQrl);
1448
+ const flattenValibotIssues = (issues) => {
1449
+ return issues.reduce((acc, issue) => {
1450
+ if (issue.path) {
1451
+ const hasArrayType = issue.path.some((path) => path.type === "array");
1452
+ if (hasArrayType) {
1453
+ const keySuffix = issue.expected === "Array" ? "[]" : "";
1454
+ const key = issue.path.map((item) => item.type === "array" ? "*" : item.key).join(".").replace(/\.\*/g, "[]") + keySuffix;
1455
+ acc[key] = acc[key] || [];
1456
+ if (Array.isArray(acc[key])) {
1457
+ acc[key].push(issue.message);
1458
+ }
1459
+ return acc;
1460
+ } else {
1461
+ acc[issue.path.map((item) => item.key).join(".")] = issue.message;
1462
+ }
1463
+ }
1464
+ return acc;
1465
+ }, {});
1466
+ };
1467
+ const valibotQrl = (qrl) => {
1468
+ if (!__EXPERIMENTAL__.valibot) {
1469
+ throw new Error('Valibot is an experimental feature and is not enabled. Please enable the feature flag by adding `experimental: ["valibot"]` to your qwikVite plugin options.');
1470
+ }
1471
+ if (build.isServer) {
1472
+ return {
1473
+ __brand: "valibot",
1474
+ async validate(ev, inputData) {
1475
+ const schema = await qrl.resolve().then((obj) => typeof obj === "function" ? obj(ev) : obj);
1476
+ const data = inputData ?? await ev.parseBody();
1477
+ const result = await safeParseAsync(schema, data);
1478
+ if (result.success) {
1479
+ return {
1480
+ success: true,
1481
+ data: result.output
1482
+ };
1483
+ } else {
1484
+ if (build.isDev) {
1485
+ console.error("ERROR: Valibot validation failed", result.issues);
1486
+ }
1487
+ return {
1488
+ success: false,
1489
+ status: 400,
1490
+ error: {
1491
+ formErrors: flatten(result.issues).root ?? [],
1492
+ fieldErrors: flattenValibotIssues(result.issues)
1493
+ }
1494
+ };
1495
+ }
1496
+ }
1497
+ };
1498
+ }
1499
+ return void 0;
1500
+ };
1501
+ const valibot$ = /* @__PURE__ */ core.implicit$FirstArg(valibotQrl);
1502
+ const flattenZodIssues = (issues) => {
1503
+ issues = Array.isArray(issues) ? issues : [
1504
+ issues
1505
+ ];
1506
+ return issues.reduce((acc, issue) => {
1507
+ const isExpectingArray = "expected" in issue && issue.expected === "array";
1508
+ const hasArrayType = issue.path.some((path) => typeof path === "number") || isExpectingArray;
1509
+ if (hasArrayType) {
1510
+ const keySuffix = "expected" in issue && issue.expected === "array" ? "[]" : "";
1511
+ const key = issue.path.map((path) => typeof path === "number" ? "*" : path).join(".").replace(/\.\*/g, "[]") + keySuffix;
1512
+ acc[key] = acc[key] || [];
1513
+ if (Array.isArray(acc[key])) {
1514
+ acc[key].push(issue.message);
1515
+ }
1516
+ return acc;
1517
+ } else {
1518
+ acc[issue.path.join(".")] = issue.message;
1519
+ }
1520
+ return acc;
1521
+ }, {});
1522
+ };
1523
+ const zodQrl = (qrl) => {
1524
+ if (build.isServer) {
1525
+ return {
1526
+ __brand: "zod",
1527
+ async validate(ev, inputData) {
1528
+ const schema = await qrl.resolve().then((obj) => {
1529
+ if (typeof obj === "function") {
1530
+ obj = obj(zod.z, ev);
1531
+ }
1532
+ if (obj instanceof zod.z.Schema) {
1533
+ return obj;
1534
+ } else {
1535
+ return zod.z.object(obj);
1536
+ }
1537
+ });
1538
+ const data = inputData ?? await ev.parseBody();
1539
+ const result = await schema.safeParseAsync(data);
1540
+ if (result.success) {
1541
+ return result;
1542
+ } else {
1543
+ if (build.isDev) {
1544
+ console.error("ERROR: Zod validation failed", result.error.issues);
1545
+ }
1546
+ return {
1547
+ success: false,
1548
+ status: 400,
1549
+ error: {
1550
+ formErrors: result.error.flatten().formErrors,
1551
+ fieldErrors: flattenZodIssues(result.error.issues)
1552
+ }
1553
+ };
1554
+ }
1555
+ }
1556
+ };
1557
+ }
1558
+ return void 0;
1559
+ };
1560
+ const zod$ = /* @__PURE__ */ core.implicit$FirstArg(zodQrl);
1561
+ const serverQrl = (qrl, options) => {
1562
+ if (build.isServer) {
1563
+ const captured = qrl.getCaptured();
1564
+ if (captured && captured.length > 0 && !internal._getContextElement()) {
1565
+ throw new Error("For security reasons, we cannot serialize QRLs that capture lexical scope.");
1566
+ }
1567
+ }
1568
+ const method = options?.method?.toUpperCase?.() || "POST";
1569
+ const headers = options?.headers || {};
1570
+ const origin = options?.origin || "";
1571
+ const fetchOptions = options?.fetchOptions || {};
1572
+ function rpc() {
1573
+ return core.$(async function(...args) {
1574
+ const abortSignal = args.length > 0 && args[0] instanceof AbortSignal ? args.shift() : void 0;
1575
+ if (build.isServer) {
1576
+ let requestEvent = globalThis.qcAsyncRequestStore?.getStore();
1577
+ if (!requestEvent) {
1578
+ const contexts = [
1579
+ useQwikRouterEnv()?.ev,
1580
+ this,
1581
+ internal._getContextEvent()
1582
+ ];
1583
+ requestEvent = contexts.find((v2) => v2 && Object.prototype.hasOwnProperty.call(v2, "sharedMap") && Object.prototype.hasOwnProperty.call(v2, "cookie"));
1584
+ }
1585
+ return qrl.apply(requestEvent, build.isDev ? deepFreeze(args) : args);
1586
+ } else {
1587
+ const ctxElm = internal._getContextElement();
1588
+ const filteredArgs = args.map((arg) => {
1589
+ if (arg instanceof SubmitEvent && arg.target instanceof HTMLFormElement) {
1590
+ return new FormData(arg.target);
1591
+ } else if (arg instanceof Event) {
1592
+ return null;
1593
+ } else if (arg instanceof Node) {
1594
+ return null;
1595
+ }
1596
+ return arg;
1597
+ });
1598
+ const qrlHash = qrl.getHash();
1599
+ let query = "";
1600
+ const config = {
1601
+ ...fetchOptions,
1602
+ method,
1603
+ headers: {
1604
+ ...headers,
1605
+ "Content-Type": "application/qwik-json",
1606
+ // Required so we don't call accidentally
1607
+ "X-QRL": qrlHash
1608
+ },
1609
+ signal: abortSignal
1610
+ };
1611
+ const body = await internal._serialize([
1612
+ qrl,
1613
+ ...filteredArgs
1614
+ ]);
1615
+ if (method === "GET") {
1616
+ query += `&${QDATA_KEY}=${encodeURIComponent(body)}`;
1617
+ } else {
1618
+ config.body = body;
1619
+ }
1620
+ const res = await fetch(`${origin}?${QFN_KEY}=${qrlHash}${query}`, config);
1621
+ const contentType = res.headers.get("Content-Type");
1622
+ if (res.ok && contentType === "text/qwik-json-stream" && res.body) {
1623
+ return async function* () {
1624
+ try {
1625
+ for await (const result of deserializeStream(res.body, ctxElm ?? document.documentElement, abortSignal)) {
1626
+ yield result;
1627
+ }
1628
+ } finally {
1629
+ if (!abortSignal?.aborted) {
1630
+ await res.body.cancel();
1631
+ }
1632
+ }
1633
+ }();
1634
+ } else if (contentType === "application/qwik-json") {
1635
+ const str = await res.text();
1636
+ const [obj] = internal._deserialize(str, ctxElm ?? document.documentElement);
1637
+ if (res.status === 500) {
1638
+ throw obj;
1639
+ }
1640
+ return obj;
1641
+ } else if (contentType === "application/json") {
1642
+ const obj = await res.json();
1643
+ if (res.status === 500) {
1644
+ throw obj;
1645
+ }
1646
+ return obj;
1647
+ } else if (contentType === "text/plain" || contentType === "text/html") {
1648
+ const str = await res.text();
1649
+ if (res.status === 500) {
1650
+ throw str;
1651
+ }
1652
+ return str;
1653
+ }
1654
+ }
1655
+ });
1656
+ }
1657
+ return rpc();
1658
+ };
1659
+ const server$ = /* @__PURE__ */ core.implicit$FirstArg(serverQrl);
1660
+ const getValidators = (rest, qrl) => {
1661
+ let id;
1662
+ const validators = [];
1663
+ if (rest.length === 1) {
1664
+ const options = rest[0];
1665
+ if (options && typeof options === "object") {
1666
+ if ("validate" in options) {
1667
+ validators.push(options);
1668
+ } else {
1669
+ id = options.id;
1670
+ if (options.validation) {
1671
+ validators.push(...options.validation);
1672
+ }
1673
+ }
1674
+ }
1675
+ } else if (rest.length > 1) {
1676
+ validators.push(...rest.filter((v2) => !!v2));
1677
+ }
1678
+ if (typeof id === "string") {
1679
+ if (build.isDev) {
1680
+ if (!/^[\w/.-]+$/.test(id)) {
1681
+ throw new Error(`Invalid id: ${id}, id can only contain [a-zA-Z0-9_.-]`);
1682
+ }
1683
+ }
1684
+ id = `id_${id}`;
1685
+ } else {
1686
+ id = qrl.getHash();
1687
+ }
1688
+ return {
1689
+ validators: validators.reverse(),
1690
+ id
1691
+ };
1692
+ };
1693
+ const deserializeStream = async function* (stream, ctxElm, abortSignal) {
1694
+ const reader = stream.getReader();
1695
+ try {
1696
+ let buffer = "";
1697
+ const decoder = new TextDecoder();
1698
+ while (!abortSignal?.aborted) {
1699
+ const result = await reader.read();
1700
+ if (result.done) {
1701
+ break;
1702
+ }
1703
+ buffer += decoder.decode(result.value, {
1704
+ stream: true
1705
+ });
1706
+ const lines = buffer.split(/\n/);
1707
+ buffer = lines.pop();
1708
+ for (const line of lines) {
1709
+ const [deserializedData] = internal._deserialize(line, ctxElm);
1710
+ yield deserializedData;
1711
+ }
1712
+ }
1713
+ } finally {
1714
+ reader.releaseLock();
1715
+ }
1716
+ };
1717
+ const ServiceWorkerRegister = (props) => core.jsx("script", {
1718
+ dangerouslySetInnerHTML: swRegister,
1719
+ nonce: props.nonce
1720
+ });
1721
+ const Form = ({ action, spaReset, reloadDocument, onSubmit$, ...rest }, key) => {
1722
+ if (action) {
1723
+ const isArrayApi = Array.isArray(onSubmit$);
1724
+ if (isArrayApi) {
1725
+ return core.jsx("form", {
1726
+ ...rest,
1727
+ action: action.actionPath,
1728
+ "preventdefault:submit": !reloadDocument,
1729
+ onSubmit$: [
1730
+ ...onSubmit$,
1731
+ // action.submit "submitcompleted" event for onSubmitCompleted$ events
1732
+ !reloadDocument ? core.$((evt) => {
1733
+ if (!action.submitted) {
1734
+ return action.submit(evt);
1735
+ }
1736
+ }) : void 0
1737
+ ],
1738
+ method: "post",
1739
+ ["data-spa-reset"]: spaReset ? "true" : void 0
1740
+ }, key);
1741
+ }
1742
+ return core.jsx("form", {
1743
+ ...rest,
1744
+ action: action.actionPath,
1745
+ "preventdefault:submit": !reloadDocument,
1746
+ onSubmit$: [
1747
+ // Since v2, this fires before the action is executed so it can be prevented
1748
+ onSubmit$,
1749
+ // action.submit "submitcompleted" event for onSubmitCompleted$ events
1750
+ !reloadDocument ? action.submit : void 0
1751
+ ],
1752
+ method: "post",
1753
+ ["data-spa-reset"]: spaReset ? "true" : void 0
1754
+ }, key);
1755
+ } else {
1756
+ return /* @__PURE__ */ jsxRuntime.jsx(GetForm, {
1757
+ spaReset,
1758
+ reloadDocument,
1759
+ onSubmit$,
1760
+ ...rest
1761
+ }, key);
1762
+ }
1763
+ };
1764
+ const GetForm = core.component$(({ action: _0, spaReset, reloadDocument, onSubmit$, ...rest }) => {
1765
+ const nav = useNavigate();
1766
+ return /* @__PURE__ */ jsxRuntime.jsx("form", {
1767
+ action: "get",
1768
+ "preventdefault:submit": !reloadDocument,
1769
+ "data-spa-reset": spaReset ? "true" : void 0,
1770
+ ...rest,
1771
+ onSubmit$: [
1772
+ ...Array.isArray(onSubmit$) ? onSubmit$ : [
1773
+ onSubmit$
1774
+ ],
1775
+ core.$(async (_evt, form) => {
1776
+ const formData = new FormData(form);
1777
+ const params = new URLSearchParams();
1778
+ formData.forEach((value, key) => {
1779
+ if (typeof value === "string") {
1780
+ params.append(key, value);
1781
+ }
1782
+ });
1783
+ await nav("?" + params.toString(), {
1784
+ type: "form",
1785
+ forceReload: true
1786
+ });
1787
+ }),
1788
+ core.$((_evt, form) => {
1789
+ if (form.getAttribute("data-spa-reset") === "true") {
1790
+ form.reset();
1791
+ }
1792
+ form.dispatchEvent(new CustomEvent("submitcompleted", {
1793
+ bubbles: false,
1794
+ cancelable: false,
1795
+ composed: false,
1796
+ detail: {
1797
+ status: 200
1798
+ }
1799
+ }));
1800
+ })
1801
+ ],
1802
+ children: /* @__PURE__ */ jsxRuntime.jsx(core.Slot, {})
1803
+ });
1804
+ });
1805
+ const untypedAppUrl = function appUrl(route, params, paramsPrefix = "") {
1806
+ const path = route.split("/");
1807
+ for (let i = 0; i < path.length; i++) {
1808
+ const segment = path[i];
1809
+ if (segment.startsWith("[") && segment.endsWith("]")) {
1810
+ const isSpread = segment.startsWith("[...");
1811
+ const key = segment.substring(segment.startsWith("[...") ? 4 : 1, segment.length - 1);
1812
+ const value = params ? params[paramsPrefix + key] || params[key] : "";
1813
+ path[i] = isSpread ? value : encodeURIComponent(value);
1814
+ }
1815
+ if (segment.startsWith("(") && segment.endsWith(")")) {
1816
+ path.splice(i, 1);
1817
+ }
1818
+ }
1819
+ let url = path.join("/");
1820
+ let baseURL = "/";
1821
+ if (baseURL) {
1822
+ if (!baseURL.endsWith("/")) {
1823
+ baseURL += "/";
1824
+ }
1825
+ while (url.startsWith("/")) {
1826
+ url = url.substring(1);
1827
+ }
1828
+ url = baseURL + url;
1829
+ }
1830
+ return url;
1831
+ };
1832
+ function omitProps(obj, keys) {
1833
+ const omittedObj = {};
1834
+ for (const key in obj) {
1835
+ if (!key.startsWith("param:") && !keys.includes(key)) {
1836
+ omittedObj[key] = obj[key];
1837
+ }
1838
+ }
1839
+ return omittedObj;
1840
+ }
1841
+ Object.defineProperty(exports, "z", {
1842
+ enumerable: true,
1843
+ get: () => zod.z
1844
+ });
1845
+ exports.Form = Form;
1846
+ exports.Link = Link;
1847
+ exports.QWIK_CITY_SCROLLER = QWIK_CITY_SCROLLER;
1848
+ exports.QWIK_ROUTER_SCROLLER = QWIK_ROUTER_SCROLLER;
1849
+ exports.QwikCityMockProvider = QwikCityMockProvider;
1850
+ exports.QwikCityProvider = QwikCityProvider;
1851
+ exports.QwikRouterMockProvider = QwikRouterMockProvider;
1852
+ exports.QwikRouterProvider = QwikRouterProvider;
1853
+ exports.RouterOutlet = RouterOutlet;
1854
+ exports.ServiceWorkerRegister = ServiceWorkerRegister;
1855
+ exports.globalAction$ = globalAction$;
1856
+ exports.globalActionQrl = globalActionQrl;
1857
+ exports.omitProps = omitProps;
1858
+ exports.routeAction$ = routeAction$;
1859
+ exports.routeActionQrl = routeActionQrl;
1860
+ exports.routeLoader$ = routeLoader$;
1861
+ exports.routeLoaderQrl = routeLoaderQrl;
1862
+ exports.server$ = server$;
1863
+ exports.serverQrl = serverQrl;
1864
+ exports.untypedAppUrl = untypedAppUrl;
1865
+ exports.useContent = useContent;
1866
+ exports.useDocumentHead = useDocumentHead;
1867
+ exports.useLocation = useLocation;
1868
+ exports.useNavigate = useNavigate;
1869
+ exports.usePreventNavigate$ = usePreventNavigate$;
1870
+ exports.usePreventNavigateQrl = usePreventNavigateQrl;
1871
+ exports.valibot$ = valibot$;
1872
+ exports.valibotQrl = valibotQrl;
1873
+ exports.validator$ = validator$;
1874
+ exports.validatorQrl = validatorQrl;
1875
+ exports.zod$ = zod$;
1876
+ exports.zodQrl = zodQrl;