@qwik.dev/router 2.0.0-beta.2 → 2.0.0-beta.21

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