@qwik.dev/router 2.0.0-beta.8 → 2.0.0-rc.0

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 (80) hide show
  1. package/lib/adapters/azure-swa/vite/index.d.ts +2 -2
  2. package/lib/adapters/azure-swa/vite/index.mjs +44 -57
  3. package/lib/adapters/bun-server/vite/index.d.ts +2 -2
  4. package/lib/adapters/bun-server/vite/index.mjs +16 -22
  5. package/lib/adapters/cloud-run/vite/index.d.ts +2 -2
  6. package/lib/adapters/cloud-run/vite/index.mjs +15 -19
  7. package/lib/adapters/cloudflare-pages/vite/index.d.ts +2 -2
  8. package/lib/adapters/cloudflare-pages/vite/index.mjs +45 -76
  9. package/lib/adapters/deno-server/vite/index.d.ts +2 -2
  10. package/lib/adapters/deno-server/vite/index.mjs +25 -34
  11. package/lib/adapters/netlify-edge/vite/index.d.ts +2 -2
  12. package/lib/adapters/netlify-edge/vite/index.mjs +49 -89
  13. package/lib/adapters/node-server/vite/index.d.ts +2 -2
  14. package/lib/adapters/node-server/vite/index.mjs +16 -22
  15. package/lib/adapters/shared/vite/index.d.ts +9 -16
  16. package/lib/adapters/shared/vite/index.mjs +280 -293
  17. package/lib/adapters/ssg/vite/index.d.ts +1 -1
  18. package/lib/adapters/ssg/vite/index.mjs +13 -299
  19. package/lib/adapters/vercel-edge/vite/index.d.ts +3 -3
  20. package/lib/adapters/vercel-edge/vite/index.mjs +75 -79
  21. package/lib/chunks/dev-preloaded-route-loader.mjs +2 -0
  22. package/lib/chunks/format.mjs +24 -0
  23. package/lib/chunks/fs.mjs +143 -0
  24. package/lib/chunks/head.qwik.mjs +1570 -0
  25. package/lib/chunks/http-error.qwik.mjs +28 -0
  26. package/lib/chunks/pathname.mjs +58 -0
  27. package/lib/chunks/request-body-limit.mjs +27 -0
  28. package/lib/chunks/request-path.mjs +53 -0
  29. package/lib/chunks/route-trie-key.mjs +10 -0
  30. package/lib/chunks/routes.mjs +26 -0
  31. package/lib/chunks/server-error.mjs +38 -0
  32. package/lib/chunks/static-file.mjs +70 -0
  33. package/lib/chunks/system.mjs +271 -0
  34. package/lib/chunks/user-response.mjs +1883 -0
  35. package/lib/chunks/worker-thread.mjs +274 -0
  36. package/lib/index.d.ts +550 -182
  37. package/lib/index.qwik.mjs +1742 -2030
  38. package/lib/middleware/aws-lambda/index.d.ts +15 -17
  39. package/lib/middleware/aws-lambda/index.mjs +46 -50
  40. package/lib/middleware/azure-swa/index.mjs +85 -294
  41. package/lib/middleware/bun/index.d.ts +20 -5
  42. package/lib/middleware/bun/index.mjs +117 -201
  43. package/lib/middleware/cloudflare-pages/index.mjs +101 -101
  44. package/lib/middleware/deno/index.d.ts +22 -5
  45. package/lib/middleware/deno/index.mjs +103 -191
  46. package/lib/middleware/firebase/index.mjs +22 -31
  47. package/lib/middleware/netlify-edge/index.mjs +63 -80
  48. package/lib/middleware/node/index.d.ts +17 -5
  49. package/lib/middleware/node/index.mjs +298 -269
  50. package/lib/middleware/request-handler/index.d.ts +259 -58
  51. package/lib/middleware/request-handler/index.mjs +108 -1730
  52. package/lib/middleware/vercel-edge/index.mjs +76 -100
  53. package/lib/modules.d.ts +7 -4
  54. package/lib/service-worker/index.mjs +14 -0
  55. package/lib/ssg/index.d.ts +50 -26
  56. package/lib/ssg/index.mjs +257 -43
  57. package/lib/vite/index.d.ts +59 -11
  58. package/lib/vite/index.mjs +2533 -27535
  59. package/modules.d.ts +7 -4
  60. package/package.json +53 -70
  61. package/lib/adapters/azure-swa/vite/index.cjs +0 -96
  62. package/lib/adapters/bun-server/vite/index.cjs +0 -50
  63. package/lib/adapters/cloud-run/vite/index.cjs +0 -47
  64. package/lib/adapters/cloudflare-pages/vite/index.cjs +0 -115
  65. package/lib/adapters/deno-server/vite/index.cjs +0 -62
  66. package/lib/adapters/netlify-edge/vite/index.cjs +0 -130
  67. package/lib/adapters/node-server/vite/index.cjs +0 -50
  68. package/lib/adapters/shared/vite/index.cjs +0 -338
  69. package/lib/adapters/ssg/vite/index.cjs +0 -339
  70. package/lib/adapters/vercel-edge/vite/index.cjs +0 -118
  71. package/lib/index.qwik.cjs +0 -2085
  72. package/lib/middleware/node/index.cjs +0 -310
  73. package/lib/middleware/request-handler/index.cjs +0 -1766
  74. package/lib/service-worker.cjs +0 -17
  75. package/lib/service-worker.mjs +0 -15
  76. package/lib/ssg/deno.mjs +0 -8
  77. package/lib/ssg/index.cjs +0 -67
  78. package/lib/ssg/node.cjs +0 -1126
  79. package/lib/ssg/node.mjs +0 -1088
  80. package/lib/vite/index.cjs +0 -27607
@@ -1,2066 +1,1778 @@
1
- import { jsx, Fragment, jsxs } from "@qwik.dev/core/jsx-runtime";
2
- import { component$, useErrorBoundary, useOnWindow, $, Slot, createAsyncComputed$, isBrowser, createContextId, implicit$FirstArg, useContext, useVisibleTask$, noSerialize, useServerData, useSignal, untrack, sync$, isDev, withLocale, event$, useStyles$, isServer, useStore, useContextProvider, useTask$, getLocale, jsx as jsx$1, SkipRender, createElement } from "@qwik.dev/core";
3
- import { p } from "@qwik.dev/core/preloader";
4
- import { _deserialize, _UNINITIALIZED, _getContextContainer, SerializerSymbol, _getContextElement, _getQContainerElement, _waitUntilRendered, _resolveContextWithoutSequentialScope, _getContextEvent, _serialize } from "@qwik.dev/core/internal";
5
- import * as qwikRouterConfig from "@qwik-router-config";
1
+ import { t as ensureSlash } from "./chunks/pathname.mjs";
2
+ import { $ as RoutePreventNavigateContext, B as _setRouterConfig, C as getRequestEvent, F as routeLoader$, G as ContentContext, H as getRouterConfig, I as routeLoaderQrl, J as HttpStatusContext, K as ContentInternalContext, L as setLoaderSignalValue, M as prepareRouteLoaders, P as restoreRouteLoaders, Q as RouteNavigateContext, S as getModuleRouteLoaders, U as getRoutes, V as getBasePathname, W as getTrailingSlash, X as RouteLoaderCtxContext, Y as RouteActionContext, Z as RouteLocationContext, _ as commitRouteLoaders, a as isPromise, b as getClientRouteLoaders, c as shouldPreload, d as loadRoute, et as RouteStateContext, h as clearNavFetchCache, i as getClientNavPath, it as Q_ROUTE, k as isImmutableLoader, l as toPath, m as abortRouteLoaderNavigation, n as resolveHead, nt as QDATA_KEY, o as isSameOrigin, q as DocumentHeadContext, rt as QFN_KEY, s as isSamePath, t as createDocumentHead, tt as QACTION_KEY, u as toUrl, v as ensureRouteLoaderSignals, y as fetchRouteLoaderData, z as _getServiceWorkerUrl } from "./chunks/head.qwik.mjs";
3
+ import { SkipRender, Slot, _capturesObj, _fnSignal, _getConstProps, _getVarProps, _jsxSorted, _jsxSplit, _qrlSync, _restProps, _wrapProp, componentQrl, createComputedQrl, createElement, eventQrl, getLocale, implicit$FirstArg, inlinedQrl, isBrowser, isDev, isServer, noSerialize, untrack, useContext, useContextProvider, useServerData, useSignal, useStore, useTaskQrl, useVisibleTaskQrl, withLocale } from "@qwik.dev/core";
4
+ import { _deserialize, _getContextContainer, _getContextHostElement, _hasStoreEffects, _regInlinedQrl, _requestPreload, _serialize, _waitUntilRendered, forceStoreEffects } from "@qwik.dev/core/internal";
5
+ import { Fragment } from "@qwik.dev/core/jsx-runtime";
6
+ import * as v from "valibot";
7
+ import * as z$1 from "zod";
6
8
  import { z } from "zod";
7
- import { z as z2 } from "zod";
8
- import swRegister from "@qwik-router-sw-register";
9
9
  import { renderToStream } from "@qwik.dev/core/server";
10
- const ErrorBoundary = component$((props) => {
11
- const store2 = useErrorBoundary();
12
- useOnWindow("qerror", $((e) => {
13
- store2.error = e.detail.error;
14
- }));
15
- if (store2.error && props.fallback$) {
16
- return /* @__PURE__ */ jsx(Fragment, {
17
- children: props.fallback$(store2.error)
18
- });
19
- }
20
- return /* @__PURE__ */ jsx(Slot, {});
21
- });
22
- const MODULE_CACHE = /* @__PURE__ */ new WeakMap();
23
- const CLIENT_DATA_CACHE = /* @__PURE__ */ new Map();
24
- const QACTION_KEY = "qaction";
25
- const QLOADER_KEY = "qloaders";
26
- const QFN_KEY = "qfunc";
27
- const QDATA_KEY = "qdata";
28
- const Q_ROUTE = "q:route";
29
- const DEFAULT_LOADERS_SERIALIZATION_STRATEGY = globalThis.__DEFAULT_LOADERS_SERIALIZATION_STRATEGY__ || "never";
30
- const MAX_Q_DATA_RETRY_COUNT = 3;
31
- const loadClientData = async (url, element, opts, retryCount = 0) => {
32
- const pagePathname = url.pathname;
33
- const pageSearch = url.search;
34
- const clientDataPath = getClientDataPath(pagePathname, pageSearch, {
35
- actionId: opts?.action?.id,
36
- loaderIds: opts?.loaderIds
37
- });
38
- let qData;
39
- if (!opts?.action) {
40
- qData = CLIENT_DATA_CACHE.get(clientDataPath);
41
- }
42
- if (opts?.prefetchSymbols !== false) {
43
- prefetchSymbols(pagePathname);
44
- }
45
- let resolveFn;
46
- if (!qData) {
47
- const fetchOptions = getFetchOptions(opts?.action, opts?.clearCache);
48
- if (opts?.action) {
49
- opts.action.data = void 0;
50
- }
51
- qData = fetch(clientDataPath, fetchOptions).then((rsp) => {
52
- if (rsp.status === 404 && opts?.loaderIds && retryCount < MAX_Q_DATA_RETRY_COUNT) {
53
- opts.loaderIds = void 0;
54
- return loadClientData(url, element, opts, retryCount + 1);
55
- }
56
- if (rsp.redirected) {
57
- const redirectedURL = new URL(rsp.url);
58
- const isQData = redirectedURL.pathname.endsWith("/q-data.json");
59
- if (!isQData || redirectedURL.origin !== location.origin) {
60
- location.href = redirectedURL.href;
61
- return;
62
- }
63
- }
64
- if ((rsp.headers.get("content-type") || "").includes("json")) {
65
- return rsp.text().then((text) => {
66
- const [clientData] = _deserialize(text, element);
67
- if (!clientData) {
68
- location.href = url.href;
69
- return;
70
- }
71
- if (opts?.clearCache) {
72
- CLIENT_DATA_CACHE.delete(clientDataPath);
73
- }
74
- if (clientData.redirect) {
75
- location.href = clientData.redirect;
76
- } else if (opts?.action) {
77
- const { action } = opts;
78
- const actionData = clientData.loaders[action.id];
79
- resolveFn = () => {
80
- action.resolve({
81
- status: rsp.status,
82
- result: actionData
83
- });
84
- };
85
- }
86
- return clientData;
87
- });
88
- } else {
89
- if (opts?.isPrefetch !== true) {
90
- location.href = url.href;
91
- }
92
- return void 0;
93
- }
94
- });
95
- if (!opts?.action) {
96
- CLIENT_DATA_CACHE.set(clientDataPath, qData);
97
- }
98
- }
99
- return qData.then((v) => {
100
- if (!v) {
101
- CLIENT_DATA_CACHE.delete(clientDataPath);
102
- }
103
- resolveFn && resolveFn();
104
- return v;
105
- });
106
- };
107
- const getFetchOptions = (action, noCache) => {
108
- const actionData = action?.data;
109
- if (!actionData) {
110
- if (noCache) {
111
- return {
112
- cache: "no-cache",
113
- headers: {
114
- "Cache-Control": "no-cache",
115
- Pragma: "no-cache"
116
- }
117
- };
118
- }
119
- return void 0;
120
- }
121
- if (actionData instanceof FormData) {
122
- return {
123
- method: "POST",
124
- body: actionData
125
- };
126
- } else {
127
- return {
128
- method: "POST",
129
- body: JSON.stringify(actionData),
130
- headers: {
131
- "Content-Type": "application/json; charset=UTF-8"
132
- }
133
- };
134
- }
10
+ /**
11
+ * Prefetch a route's JS bundles and optionally its loader data.
12
+ *
13
+ * Resolves the route from the trie to get the routeName (for the bundle graph preloader) and
14
+ * `$loaders$` (for data prefetching). The bundle graph is keyed by route name (e.g.
15
+ * `products/[id]/`), not by actual pathname (e.g. `products/123/`).
16
+ *
17
+ * @param url - The URL pathname to prefetch
18
+ * @param prefetchData - Whether to prefetch loader data
19
+ * @param probability - Bundle preload probability (0-1, default 0.8)
20
+ * @param manifestHash - Build manifest hash for loader URLs (from `useDocumentHead().manifestHash`)
21
+ * @param prefetchBundle - Whether to prefetch route JS bundles
22
+ */
23
+ async function prefetchRoute(url, prefetchData, probability = .8, manifestHash, prefetchBundle = true) {
24
+ if (!isBrowser || isDev) return;
25
+ try {
26
+ const { routes, cacheModules } = await getRouterConfig();
27
+ const loadedRoute = await loadRoute(routes, cacheModules, url.pathname);
28
+ if (!loadedRoute) return;
29
+ if (prefetchBundle) {
30
+ let routeName = loadedRoute.$routeName$;
31
+ routeName = ensureSlash(routeName);
32
+ if (routeName.length > 1 && routeName.startsWith("/")) routeName = routeName.slice(1);
33
+ _requestPreload(routeName, probability);
34
+ }
35
+ if (!prefetchData || !manifestHash) return;
36
+ prefetchLoaderData(loadedRoute, url, manifestHash);
37
+ } catch {}
38
+ }
39
+ /**
40
+ * Prefetch a route's loader data in parallel (fire-and-forget). The per-nav fetch map dedupes
41
+ * repeat hovers and shares the promise with the navigation's own fetch; the browser HTTP cache
42
+ * handles freshness. Immutable loaders are skipped: they download lazily on first actual read and
43
+ * are then browser-cached for the life of the deploy.
44
+ */
45
+ var prefetchLoaderData = (loadedRoute, url, manifestHash) => {
46
+ if (!loadedRoute.$loaders$?.length || !loadedRoute.$loaderPaths$) return;
47
+ const immutableIds = new Set(getModuleRouteLoaders(loadedRoute.$mods$).filter((loader) => loader.__cacheControl === "immutable").map((loader) => loader.__id));
48
+ const basePath = getBasePathname();
49
+ for (const hash of loadedRoute.$loaders$) {
50
+ if (immutableIds.has(hash)) continue;
51
+ let loaderPath = loadedRoute.$loaderPaths$[hash];
52
+ if (!loaderPath) continue;
53
+ if (basePath !== "/" && !loaderPath.startsWith(basePath)) loaderPath = basePath + loaderPath.slice(1);
54
+ fetchRouteLoaderData(hash, loaderPath, manifestHash, {
55
+ pageUrl: url,
56
+ basePath
57
+ }).catch(() => {});
58
+ }
135
59
  };
136
- const toPath = (url) => url.pathname + url.search + url.hash;
137
- const toUrl = (url, baseUrl) => new URL(url, baseUrl.href);
138
- const isSameOrigin = (a, b) => a.origin === b.origin;
139
- const withSlash = (path) => path.endsWith("/") ? path : path + "/";
140
- const isSamePathname = ({ pathname: a }, { pathname: b }) => {
141
- const lDiff = Math.abs(a.length - b.length);
142
- return lDiff === 0 ? a === b : lDiff === 1 && withSlash(a) === withSlash(b);
60
+ /** @public */
61
+ var useHttpStatus = () => useContext(HttpStatusContext).value;
62
+ /** @public */
63
+ var useContent = () => useContext(ContentContext);
64
+ /**
65
+ * Returns the document head for the current page. The generic type describes the front matter.
66
+ *
67
+ * @public
68
+ */
69
+ var useDocumentHead = () => useContext(DocumentHeadContext);
70
+ /** @public */
71
+ var useLocation = () => useContext(RouteLocationContext);
72
+ /** @public */
73
+ var useNavigate = () => useContext(RouteNavigateContext);
74
+ /** @internal Implementation of usePreventNavigate$ */
75
+ var usePreventNavigateQrl = (fn) => {
76
+ const registerPreventNav = useContext(RoutePreventNavigateContext);
77
+ useVisibleTaskQrl(/*#__PURE__*/ inlinedQrl(() => {
78
+ let fn = _capturesObj._[0], registerPreventNav = _capturesObj._[1];
79
+ return registerPreventNav(fn);
80
+ }, "usePreventNavigateQrl_useVisibleTask_BsYUaz9XhUs", [fn, registerPreventNav]));
143
81
  };
144
- const isSameSearchQuery = (a, b) => a.search === b.search;
145
- const isSamePath = (a, b) => isSameSearchQuery(a, b) && isSamePathname(a, b);
146
- const getClientDataPath = (pathname, pageSearch, options) => {
147
- let search = pageSearch ?? "";
148
- if (options?.actionId) {
149
- search += (search ? "&" : "?") + QACTION_KEY + "=" + encodeURIComponent(options.actionId);
150
- }
151
- if (options?.loaderIds) {
152
- for (const loaderId of options.loaderIds) {
153
- search += (search ? "&" : "?") + QLOADER_KEY + "=" + encodeURIComponent(loaderId);
154
- }
155
- }
156
- return pathname + (pathname.endsWith("/") ? "" : "/") + "q-data.json" + search;
82
+ /**
83
+ * Prevent navigation attempts. This hook registers a callback that will be called before SPA or
84
+ * browser navigation.
85
+ *
86
+ * Return `true` to prevent navigation.
87
+ *
88
+ * #### SPA Navigation
89
+ *
90
+ * For Single-Page-App (SPA) navigation (via `<Link />`, `const nav = useNavigate()`, and browser
91
+ * backwards/forwards inside SPA history), the callback will be provided with the target, either a
92
+ * URL or a number. It will only be a number if `nav(number)` was called to navigate forwards or
93
+ * backwards in SPA history.
94
+ *
95
+ * If you return a Promise, the navigation will be blocked until the promise resolves.
96
+ *
97
+ * This can be used to show a nice dialog to the user, and wait for the user to confirm, or to
98
+ * record the url, prevent the navigation, and navigate there later via `nav(url)`.
99
+ *
100
+ * #### Browser Navigation
101
+ *
102
+ * However, when the user navigates away by clicking on a regular `<a />`, reloading, or moving
103
+ * backwards/forwards outside SPA history, this callback will not be awaited. This is because the
104
+ * browser does not provide a way to asynchronously prevent these navigations.
105
+ *
106
+ * In this case, returning returning `true` will tell the browser to show a confirmation dialog,
107
+ * which cannot be customized. You are also not able to show your own `window.confirm()` dialog
108
+ * during the callback, the browser won't allow it. If you return a Promise, it will be considered
109
+ * as `true`.
110
+ *
111
+ * When the callback is called from the browser, no url will be provided. Use this to know whether
112
+ * you can show a dialog or just return `true` to prevent the navigation.
113
+ *
114
+ * @public
115
+ */
116
+ var usePreventNavigate$ = implicit$FirstArg(usePreventNavigateQrl);
117
+ var useAction = () => useContext(RouteActionContext);
118
+ var useQwikRouterEnv = () => noSerialize(useServerData("qwikrouter"));
119
+ /** @public */
120
+ var Link = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl((props) => {
121
+ const nav = useNavigate();
122
+ const loc = useLocation();
123
+ const head = useDocumentHead();
124
+ const { onClick$, prefetch: prefetchProp, reload, replaceState, scroll, prefetchBundles: prefetchBundlesProp = "visible", prefetchData: prefetchDataProp = prefetchProp === "js" ? "off" : "intent", ...linkProps } = props;
125
+ const clientNavPath = untrack(getClientNavPath, {
126
+ ...linkProps,
127
+ reload
128
+ }, loc);
129
+ linkProps.href = clientNavPath || props.href;
130
+ const isDepratedPrefetchDisabled = prefetchProp === false;
131
+ const shouldPrefetch = untrack(shouldPreload, clientNavPath, loc);
132
+ const shouldVisiblePrefetchBundles = !!clientNavPath && shouldPrefetch && !isDepratedPrefetchDisabled && (prefetchBundlesProp === "visible" || prefetchProp === "js" || prefetchProp === true);
133
+ const shouldVisiblePrefetchData = !!clientNavPath && shouldPrefetch && !isDepratedPrefetchDisabled && (prefetchDataProp === "visible" || prefetchProp === true);
134
+ const shouldPrefetchBundles = !!clientNavPath && prefetchBundlesProp !== "off" && shouldPrefetch && !isDepratedPrefetchDisabled;
135
+ const shouldPrefetchData = !!clientNavPath && prefetchDataProp !== "off" && shouldPrefetch && !isDepratedPrefetchDisabled;
136
+ const handleBundlePrefetch = shouldPrefetchBundles ? /*#__PURE__*/ inlinedQrl((_, elm) => {
137
+ if (navigator.connection?.saveData) return;
138
+ if (elm && elm.href) prefetchRoute(new URL(elm.href), false, .8);
139
+ }, "Link_component_handleBundlePrefetch_ZttUP0kLKj0") : null;
140
+ const handleDataPrefetch = shouldPrefetchData ? /*#__PURE__*/ inlinedQrl((_, elm) => {
141
+ let head = _capturesObj._[0];
142
+ if (navigator.connection?.saveData) return;
143
+ if (elm && elm.href) prefetchRoute(new URL(elm.href), true, .8, head.manifestHash, false);
144
+ }, "Link_component_handleDataPrefetch_lcd4O9LHbbA", [head]) : null;
145
+ const preventDefault = clientNavPath ? _qrlSync((event) => {
146
+ if (!(event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)) event.preventDefault();
147
+ }, "event=>{if(!(event.metaKey||event.ctrlKey||event.shiftKey||event.altKey)){event.preventDefault();}}") : null;
148
+ const prefetchData = /*#__PURE__*/ inlinedQrl(async (_, elm) => {
149
+ let handleDataPrefetch = _capturesObj._[0];
150
+ handleDataPrefetch?.(null, elm);
151
+ }, "Link_component_prefetchData_UwVx4NhHkSo", [handleDataPrefetch]);
152
+ const onEnterKeyDown = /*#__PURE__*/ inlinedQrl((event, element) => {
153
+ let handleBundlePrefetch = _capturesObj._[0], prefetchBundlesProp = _capturesObj._[1], prefetchData = _capturesObj._[2], prefetchDataProp = _capturesObj._[3];
154
+ if (event.key !== "Enter") return;
155
+ if (prefetchDataProp === "commit") prefetchData(null, element);
156
+ if (prefetchBundlesProp === "commit") handleBundlePrefetch?.(null, element);
157
+ }, "Link_component_onEnterKeyDown_z274ws00irY", [
158
+ handleBundlePrefetch,
159
+ prefetchBundlesProp,
160
+ prefetchData,
161
+ prefetchDataProp
162
+ ]);
163
+ const handleClientSideNavigation = clientNavPath ? /*#__PURE__*/ inlinedQrl((event, elm) => {
164
+ let nav = _capturesObj._[0], reload = _capturesObj._[1], replaceState = _capturesObj._[2], scroll = _capturesObj._[3];
165
+ if (event.defaultPrevented) {
166
+ if (elm.href) {
167
+ elm.setAttribute("aria-pressed", "true");
168
+ nav(elm.href, {
169
+ forceReload: reload,
170
+ replaceState,
171
+ scroll
172
+ }).then(() => {
173
+ elm.removeAttribute("aria-pressed");
174
+ });
175
+ }
176
+ }
177
+ }, "Link_component_handleClientSideNavigation_h3qenoGeI6M", [
178
+ nav,
179
+ reload,
180
+ replaceState,
181
+ scroll
182
+ ]) : null;
183
+ return /*#__PURE__*/ _jsxSplit("a", {
184
+ ..._getVarProps({ "q:link": !!clientNavPath }),
185
+ ..._getConstProps({ "q:link": !!clientNavPath }),
186
+ ...linkProps,
187
+ "data-q-prefetch": shouldVisiblePrefetchBundles && shouldVisiblePrefetchData ? "bd" : shouldVisiblePrefetchBundles ? "b" : shouldVisiblePrefetchData ? "d" : null,
188
+ "q-e:click": [
189
+ preventDefault,
190
+ /*#__PURE__*/ inlinedQrl((_, elm) => {
191
+ prefetchRoute(new URL(elm.href), false, 1);
192
+ }, "Link_component_handlePreload_AAemwtuBjsE"),
193
+ onClick$,
194
+ handleClientSideNavigation
195
+ ],
196
+ "q-e:pointerenter": [
197
+ linkProps.onPointerEnter$,
198
+ prefetchDataProp === "intent" ? prefetchData : null,
199
+ prefetchBundlesProp === "intent" ? handleBundlePrefetch : null
200
+ ],
201
+ "q-e:focus": [
202
+ linkProps.onFocus$,
203
+ prefetchDataProp === "intent" ? prefetchData : null,
204
+ prefetchBundlesProp === "intent" ? handleBundlePrefetch : null
205
+ ],
206
+ "q-e:pointerdown": [
207
+ linkProps.onPointerDown$,
208
+ prefetchDataProp === "commit" ? prefetchData : null,
209
+ prefetchBundlesProp === "commit" ? handleBundlePrefetch : null
210
+ ],
211
+ "q-e:keydown": [linkProps.onKeyDown$, prefetchDataProp === "commit" || prefetchBundlesProp === "commit" ? onEnterKeyDown : null]
212
+ }, null, /*#__PURE__*/ _jsxSorted(Slot, null, null, null, 3, "xa_0"), 0, "xa_1");
213
+ }, "Link_component_VPmar9tb3t4"));
214
+ var clientNavigate = (win, navType, fromURL, toURL, replaceState = false) => {
215
+ if (navType !== "popstate") {
216
+ const samePath = isSamePath(fromURL, toURL);
217
+ const sameHash = fromURL.hash === toURL.hash;
218
+ if (!samePath || !sameHash) {
219
+ const newState = { _qRouterScroll: newScrollState() };
220
+ if (replaceState) win.history.replaceState(newState, "", toPath(toURL));
221
+ else win.history.pushState(newState, "", toPath(toURL));
222
+ }
223
+ }
157
224
  };
158
- const getClientNavPath = (props, baseUrl) => {
159
- const href = props.href;
160
- if (typeof href === "string" && typeof props.target !== "string" && !props.reload) {
161
- try {
162
- const linkUrl = toUrl(href.trim(), baseUrl.url);
163
- const currentUrl = toUrl("", baseUrl.url);
164
- if (isSameOrigin(linkUrl, currentUrl)) {
165
- return toPath(linkUrl);
166
- }
167
- } catch (e) {
168
- console.error(e);
169
- }
170
- } else if (props.reload) {
171
- return toPath(toUrl("", baseUrl.url));
172
- }
173
- return null;
225
+ var newScrollState = () => {
226
+ return {
227
+ x: 0,
228
+ y: 0,
229
+ w: 0,
230
+ h: 0
231
+ };
174
232
  };
175
- const shouldPreload = (clientNavPath, currentLoc) => {
176
- if (clientNavPath) {
177
- const prefetchUrl = toUrl(clientNavPath, currentLoc.url);
178
- const currentUrl = toUrl("", currentLoc.url);
179
- return !isSamePathname(prefetchUrl, currentUrl);
180
- }
181
- return false;
233
+ var preloadRouteBundles = (path, probability = .8) => {
234
+ if (isBrowser) {
235
+ path = ensureSlash(path);
236
+ path = path.length > 1 && path.startsWith("/") ? path.slice(1) : path;
237
+ _requestPreload(path, probability);
238
+ }
182
239
  };
183
- const isPromise = (value) => {
184
- return value && typeof value.then === "function";
240
+ var prefetchedLinks = /* @__PURE__ */ new WeakSet();
241
+ var cleanupPrefetchObserver;
242
+ var resetLinkPrefetchState = () => {
243
+ prefetchedLinks = /* @__PURE__ */ new WeakSet();
185
244
  };
186
- const deepFreeze = (obj) => {
187
- if (obj == null) {
188
- return obj;
189
- }
190
- Object.getOwnPropertyNames(obj).forEach((prop) => {
191
- const value = obj[prop];
192
- if (value && typeof value === "object" && !Object.isFrozen(value)) {
193
- deepFreeze(value);
194
- }
195
- });
196
- return Object.freeze(obj);
245
+ var refreshLinkPrefetchObserver = (manifestHash) => {
246
+ resetLinkPrefetchState();
247
+ cleanupPrefetchObserver?.();
248
+ cleanupPrefetchObserver = createLinkPrefetchObserver(manifestHash);
197
249
  };
198
- const createLoaderSignal = (loadersObject, loaderId, url, serializationStrategy, container) => {
199
- return createAsyncComputed$(async () => {
200
- if (isBrowser && loadersObject[loaderId] === _UNINITIALIZED) {
201
- const data = await loadClientData(url, void 0, {
202
- loaderIds: [
203
- loaderId
204
- ]
205
- });
206
- loadersObject[loaderId] = data?.loaders[loaderId] ?? _UNINITIALIZED;
207
- }
208
- return loadersObject[loaderId];
209
- }, {
210
- container,
211
- serializationStrategy
212
- });
250
+ var linkPrefetchInit = eventQrl(/*#__PURE__*/ inlinedQrl((_, element) => {
251
+ refreshLinkPrefetchObserver(element.closest("[q\\:manifest-hash]")?.getAttribute("q:manifest-hash") || void 0);
252
+ }, "linkPrefetchInit_event_hoZr9O26Irg"));
253
+ var createLinkPrefetchObserver = (manifestHash) => {
254
+ const anchors = document.querySelectorAll("a[q\\:link][data-q-prefetch]");
255
+ const prefetchAnchor = (anchor, observer) => {
256
+ if (prefetchedLinks.has(anchor)) return;
257
+ prefetchedLinks.add(anchor);
258
+ observer?.unobserve(anchor);
259
+ if (navigator.connection?.saveData || !anchor.href) return;
260
+ let url;
261
+ try {
262
+ url = new URL(anchor.href);
263
+ } catch {
264
+ return;
265
+ }
266
+ const currentUrl = new URL(location.href);
267
+ if (!isSameOrigin(url, currentUrl) || !shouldPreload(toPath(url), { url: currentUrl })) return;
268
+ const mode = anchor.getAttribute("data-q-prefetch") || "";
269
+ if (mode.includes("b")) preloadRouteBundles(url.pathname);
270
+ if (mode.includes("d")) prefetchRoute(url, true, .8, manifestHash, false);
271
+ };
272
+ if (typeof IntersectionObserver === "undefined") {
273
+ anchors.forEach((anchor) => prefetchAnchor(anchor));
274
+ return () => {};
275
+ }
276
+ const observer = new IntersectionObserver((entries) => {
277
+ for (const entry of entries) if (entry.isIntersecting) prefetchAnchor(entry.target, observer);
278
+ });
279
+ anchors.forEach((anchor) => observer.observe(anchor));
280
+ return () => {
281
+ observer.disconnect();
282
+ };
213
283
  };
214
- const clientNavigate = (win, navType, fromURL, toURL, replaceState = false) => {
215
- if (navType !== "popstate") {
216
- const samePath = isSamePath(fromURL, toURL);
217
- const sameHash = fromURL.hash === toURL.hash;
218
- if (!samePath || !sameHash) {
219
- const newState = {
220
- _qRouterScroll: newScrollState()
221
- };
222
- if (replaceState) {
223
- win.history.replaceState(newState, "", toPath(toURL));
224
- } else {
225
- win.history.pushState(newState, "", toPath(toURL));
226
- }
227
- }
228
- }
284
+ function callRestoreScrollOnDocument() {
285
+ if (document.__q_scroll_restore__) {
286
+ document.__q_scroll_restore__();
287
+ document.__q_scroll_restore__ = void 0;
288
+ }
289
+ }
290
+ var restoreScroll = (type, toUrl, fromUrl, scroller, scrollState) => {
291
+ if (type === "popstate" && scrollState) scroller.scrollTo(scrollState.x, scrollState.y);
292
+ else if (type === "link" || type === "form") {
293
+ if (!hashScroll(toUrl, fromUrl)) scroller.scrollTo(0, 0);
294
+ }
229
295
  };
230
- const newScrollState = () => {
231
- return {
232
- x: 0,
233
- y: 0,
234
- w: 0,
235
- h: 0
236
- };
296
+ var hashScroll = (toUrl, fromUrl) => {
297
+ const elmId = toUrl.hash.slice(1);
298
+ const elm = elmId && document.getElementById(elmId);
299
+ if (elm) {
300
+ elm.scrollIntoView();
301
+ return true;
302
+ } else if (!elm && toUrl.hash && isSamePath(toUrl, fromUrl)) return true;
303
+ return false;
237
304
  };
238
- const prefetchSymbols = (path) => {
239
- if (isBrowser) {
240
- path = path.endsWith("/") ? path : path + "/";
241
- path = path.length > 1 && path.startsWith("/") ? path.slice(1) : path;
242
- p(path, 0.8);
243
- }
305
+ var currentScrollState = (elm) => {
306
+ return {
307
+ x: elm.scrollLeft,
308
+ y: elm.scrollTop,
309
+ w: Math.max(elm.scrollWidth, elm.clientWidth),
310
+ h: Math.max(elm.scrollHeight, elm.clientHeight)
311
+ };
244
312
  };
245
- const RouteStateContext = /* @__PURE__ */ createContextId("qc-s");
246
- const ContentContext = /* @__PURE__ */ createContextId("qc-c");
247
- const ContentInternalContext = /* @__PURE__ */ createContextId("qc-ic");
248
- const DocumentHeadContext = /* @__PURE__ */ createContextId("qc-h");
249
- const RouteLocationContext = /* @__PURE__ */ createContextId("qc-l");
250
- const RouteNavigateContext = /* @__PURE__ */ createContextId("qc-n");
251
- const RouteActionContext = /* @__PURE__ */ createContextId("qc-a");
252
- const RouteInternalContext = /* @__PURE__ */ createContextId("qc-ir");
253
- const RoutePreventNavigateContext = /* @__PURE__ */ createContextId("qc-p");
254
- const useContent = () => useContext(ContentContext);
255
- const useDocumentHead = () => useContext(DocumentHeadContext);
256
- const useLocation = () => useContext(RouteLocationContext);
257
- const useNavigate = () => useContext(RouteNavigateContext);
258
- const usePreventNavigateQrl = (fn) => {
259
- if (!__EXPERIMENTAL__.preventNavigate) {
260
- throw new Error('usePreventNavigate$ is experimental and must be enabled with `experimental: ["preventNavigate"]` in the `qwikVite` plugin.');
261
- }
262
- const registerPreventNav = useContext(RoutePreventNavigateContext);
263
- useVisibleTask$(() => registerPreventNav(fn));
313
+ var getScrollHistory = () => {
314
+ return history.state?._qRouterScroll;
264
315
  };
265
- const usePreventNavigate$ = implicit$FirstArg(usePreventNavigateQrl);
266
- const useAction = () => useContext(RouteActionContext);
267
- const useQwikRouterEnv = () => noSerialize(useServerData("qwikrouter"));
268
- const Link = component$((props) => {
269
- const nav = useNavigate();
270
- const loc = useLocation();
271
- const originalHref = props.href;
272
- const anchorRef = useSignal();
273
- const { onClick$, prefetch: prefetchProp, reload, replaceState, scroll, ...linkProps } = /* @__PURE__ */ (() => props)();
274
- const clientNavPath = untrack(() => getClientNavPath({
275
- ...linkProps,
276
- reload
277
- }, loc));
278
- linkProps.href = clientNavPath || originalHref;
279
- const prefetchData = untrack(() => !!clientNavPath && prefetchProp !== false && prefetchProp !== "js" || void 0);
280
- const prefetch = untrack(() => prefetchData || !!clientNavPath && prefetchProp !== false && shouldPreload(clientNavPath, loc));
281
- const handlePrefetch = prefetch ? $((_, elm) => {
282
- if (navigator.connection?.saveData) {
283
- return;
284
- }
285
- if (elm && elm.href) {
286
- const url = new URL(elm.href);
287
- prefetchSymbols(url.pathname);
288
- if (elm.hasAttribute("data-prefetch")) {
289
- loadClientData(url, elm, {
290
- prefetchSymbols: false,
291
- isPrefetch: true
292
- });
293
- }
294
- }
295
- }) : void 0;
296
- const preventDefault = clientNavPath ? sync$((event) => {
297
- if (!(event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)) {
298
- event.preventDefault();
299
- }
300
- }) : void 0;
301
- const handleClick = clientNavPath ? $(async (event, elm) => {
302
- if (event.defaultPrevented) {
303
- if (elm.href) {
304
- elm.setAttribute("aria-pressed", "true");
305
- await nav(elm.href, {
306
- forceReload: reload,
307
- replaceState,
308
- scroll
309
- });
310
- elm.removeAttribute("aria-pressed");
311
- }
312
- }
313
- }) : void 0;
314
- useVisibleTask$(({ track }) => {
315
- track(() => loc.url.pathname);
316
- const handler = linkProps.onQVisible$;
317
- if (handler) {
318
- const event = new CustomEvent("qvisible");
319
- if (Array.isArray(handler)) {
320
- handler.flat(10).forEach((handler2) => handler2?.(event, anchorRef.value));
321
- } else {
322
- handler?.(event, anchorRef.value);
323
- }
324
- }
325
- if (!isDev && anchorRef.value) {
326
- handlePrefetch?.(void 0, anchorRef.value);
327
- }
328
- });
329
- return /* @__PURE__ */ jsx("a", {
330
- ref: anchorRef,
331
- "q:link": !!clientNavPath,
332
- ...linkProps,
333
- onClick$: [
334
- preventDefault,
335
- onClick$,
336
- handleClick
337
- ],
338
- "data-prefetch": prefetchData,
339
- onMouseOver$: [
340
- linkProps.onMouseOver$,
341
- handlePrefetch
342
- ],
343
- onFocus$: [
344
- linkProps.onFocus$,
345
- handlePrefetch
346
- ],
347
- // We need to prevent the onQVisible$ from being called twice since it is handled in the visible task
348
- onQVisible$: [],
349
- children: /* @__PURE__ */ jsx(Slot, {})
350
- });
351
- });
352
- const resolveHead = (endpoint, routeLocation, contentModules, locale, defaults) => {
353
- const head = createDocumentHead(defaults);
354
- const getData = (loaderOrAction) => {
355
- const id = loaderOrAction.__id;
356
- if (loaderOrAction.__brand === "server_loader") {
357
- if (!(id in endpoint.loaders)) {
358
- throw new Error("You can not get the returned data of a loader that has not been executed for this request.");
359
- }
360
- }
361
- const data = endpoint.loaders[id];
362
- if (isPromise(data)) {
363
- throw new Error("Loaders returning a promise can not be resolved for the head function.");
364
- }
365
- return data;
366
- };
367
- const headProps = {
368
- head,
369
- withLocale: (fn) => withLocale(locale, fn),
370
- resolveValue: getData,
371
- ...routeLocation
372
- };
373
- for (let i = contentModules.length - 1; i >= 0; i--) {
374
- const contentModuleHead = contentModules[i] && contentModules[i].head;
375
- if (contentModuleHead) {
376
- if (typeof contentModuleHead === "function") {
377
- resolveDocumentHead(head, withLocale(locale, () => contentModuleHead(headProps)));
378
- } else if (typeof contentModuleHead === "object") {
379
- resolveDocumentHead(head, contentModuleHead);
380
- }
381
- }
382
- }
383
- return headProps.head;
316
+ var saveScrollHistory = (scrollState) => {
317
+ const state = history.state || {};
318
+ state._qRouterScroll = scrollState;
319
+ history.replaceState(state, "");
384
320
  };
385
- const resolveDocumentHead = (resolvedHead, updatedHead) => {
386
- if (typeof updatedHead.title === "string") {
387
- resolvedHead.title = updatedHead.title;
388
- }
389
- mergeArray(resolvedHead.meta, updatedHead.meta);
390
- mergeArray(resolvedHead.links, updatedHead.links);
391
- mergeArray(resolvedHead.styles, updatedHead.styles);
392
- mergeArray(resolvedHead.scripts, updatedHead.scripts);
393
- Object.assign(resolvedHead.frontmatter, updatedHead.frontmatter);
321
+ var Q_ROUTER_POPSTATE_EVENT = "qrouterpopstate";
322
+ var createCurrentPathTracker = (initialPath) => {
323
+ let currentPath = initialPath;
324
+ return (nextPath) => {
325
+ if (currentPath !== nextPath) {
326
+ currentPath = nextPath;
327
+ return true;
328
+ }
329
+ return false;
330
+ };
394
331
  };
395
- const mergeArray = (existingArr, newArr) => {
396
- if (Array.isArray(newArr)) {
397
- for (const newItem of newArr) {
398
- if (typeof newItem.key === "string") {
399
- const existingIndex = existingArr.findIndex((i) => i.key === newItem.key);
400
- if (existingIndex > -1) {
401
- existingArr[existingIndex] = newItem;
402
- continue;
403
- }
404
- }
405
- existingArr.push(newItem);
406
- }
407
- }
332
+ var dispatchRouterPopstate = (document1, href) => {
333
+ document1.dispatchEvent(new CustomEvent(Q_ROUTER_POPSTATE_EVENT, { detail: { href } }));
408
334
  };
409
- const createDocumentHead = (defaults) => ({
410
- title: defaults?.title || "",
411
- meta: [
412
- ...defaults?.meta || []
413
- ],
414
- links: [
415
- ...defaults?.links || []
416
- ],
417
- styles: [
418
- ...defaults?.styles || []
419
- ],
420
- scripts: [
421
- ...defaults?.scripts || []
422
- ],
423
- frontmatter: {
424
- ...defaults?.frontmatter
425
- }
426
- });
427
- function matchRoute(route, path) {
428
- const routeIdx = startIdxSkipSlash(route);
429
- const routeLength = lengthNoTrailingSlash(route);
430
- const pathIdx = startIdxSkipSlash(path);
431
- const pathLength = lengthNoTrailingSlash(path);
432
- return matchRoutePart(route, routeIdx, routeLength, path, pathIdx, pathLength);
433
- }
434
- function matchRoutePart(route, routeIdx, routeLength, path, pathIdx, pathLength) {
435
- let params = null;
436
- while (routeIdx < routeLength) {
437
- const routeCh = route.charCodeAt(routeIdx++);
438
- const pathCh = path.charCodeAt(pathIdx++);
439
- if (routeCh === 91) {
440
- const isMany = isThreeDots(route, routeIdx);
441
- const paramNameStart = routeIdx + (isMany ? 3 : 0);
442
- const paramNameEnd = scan(route, paramNameStart, routeLength, 93);
443
- const paramName = route.substring(paramNameStart, paramNameEnd);
444
- const paramSuffixEnd = scan(route, paramNameEnd + 1, routeLength, 47);
445
- const suffix = route.substring(paramNameEnd + 1, paramSuffixEnd);
446
- routeIdx = paramNameEnd + 1;
447
- const paramValueStart = pathIdx - 1;
448
- if (isMany) {
449
- const match = recursiveScan(paramName, suffix, path, paramValueStart, pathLength, route, routeIdx + suffix.length + 1, routeLength);
450
- if (match) {
451
- return Object.assign(params || (params = {}), match);
452
- }
453
- }
454
- const paramValueEnd = scan(path, paramValueStart, pathLength, 47, suffix);
455
- if (paramValueEnd == -1) {
456
- return null;
457
- }
458
- const paramValue = path.substring(paramValueStart, paramValueEnd);
459
- if (!isMany && !suffix && !paramValue) {
460
- return null;
461
- }
462
- pathIdx = paramValueEnd;
463
- (params || (params = {}))[paramName] = decodeURIComponent(paramValue);
464
- } else if (routeCh !== pathCh) {
465
- if (!(isNaN(pathCh) && isRestParameter(route, routeIdx))) {
466
- return null;
467
- }
468
- }
469
- }
470
- if (allConsumed(route, routeIdx) && allConsumed(path, pathIdx)) {
471
- return params || {};
472
- } else {
473
- return null;
474
- }
475
- }
476
- function isRestParameter(text, idx) {
477
- return text.charCodeAt(idx) === 91 && isThreeDots(text, idx + 1);
478
- }
479
- function lengthNoTrailingSlash(text) {
480
- const length = text.length;
481
- return length > 1 && text.charCodeAt(length - 1) === 47 ? length - 1 : length;
482
- }
483
- function allConsumed(text, idx) {
484
- const length = text.length;
485
- return idx >= length || idx == length - 1 && text.charCodeAt(idx) === 47;
486
- }
487
- function startIdxSkipSlash(text) {
488
- return text.charCodeAt(0) === 47 ? 1 : 0;
489
- }
490
- function isThreeDots(text, idx) {
491
- return text.charCodeAt(idx) === 46 && text.charCodeAt(idx + 1) === 46 && text.charCodeAt(idx + 2) === 46;
335
+ var spa_init_default = eventQrl(/*#__PURE__*/ inlinedQrl((_, el) => {
336
+ if (!window._qRouterSPA && !window._qRouterInitPopstate) {
337
+ const hasPathChanged = createCurrentPathTracker(location.pathname + location.search);
338
+ const checkAndScroll = (scrollState) => {
339
+ if (scrollState) window.scrollTo(scrollState.x, scrollState.y);
340
+ };
341
+ const currentScrollState = () => {
342
+ const elm = document.documentElement;
343
+ return {
344
+ x: elm.scrollLeft,
345
+ y: elm.scrollTop,
346
+ w: Math.max(elm.scrollWidth, elm.clientWidth),
347
+ h: Math.max(elm.scrollHeight, elm.clientHeight)
348
+ };
349
+ };
350
+ const saveScrollState = (scrollState) => {
351
+ const state = history.state || {};
352
+ state._qRouterScroll = scrollState || currentScrollState();
353
+ history.replaceState(state, "");
354
+ };
355
+ saveScrollState();
356
+ window._qRouterInitPopstate = () => {
357
+ if (window._qRouterSPA) return;
358
+ window._qRouterScrollEnabled = false;
359
+ clearTimeout(window._qRouterScrollDebounce);
360
+ if (hasPathChanged(location.pathname + location.search)) dispatchRouterPopstate(document, location.href);
361
+ else if (history.scrollRestoration === "manual") {
362
+ const scrollState = history.state?._qRouterScroll;
363
+ checkAndScroll(scrollState);
364
+ window._qRouterScrollEnabled = true;
365
+ }
366
+ };
367
+ if (!window._qRouterHistoryPatch) {
368
+ window._qRouterHistoryPatch = true;
369
+ const pushState = history.pushState;
370
+ const replaceState = history.replaceState;
371
+ const prepareState = (state) => {
372
+ if (state === null || typeof state === "undefined") state = {};
373
+ else if (state?.constructor !== Object) {
374
+ state = { _data: state };
375
+ if (isDev) 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`");
376
+ }
377
+ state._qRouterScroll = state._qRouterScroll || currentScrollState();
378
+ return state;
379
+ };
380
+ history.pushState = (state, title, url) => {
381
+ state = prepareState(state);
382
+ return pushState.call(history, state, title, url);
383
+ };
384
+ history.replaceState = (state, title, url) => {
385
+ state = prepareState(state);
386
+ return replaceState.call(history, state, title, url);
387
+ };
388
+ }
389
+ window._qRouterInitAnchors = (event) => {
390
+ if (window._qRouterSPA || event.defaultPrevented) return;
391
+ const target = event.target.closest("a[href]");
392
+ if (target && !target.hasAttribute("preventdefault:click")) {
393
+ const href = target.getAttribute("href");
394
+ const prev = new URL(location.href);
395
+ const dest = new URL(href, prev);
396
+ const sameOrigin = dest.origin === prev.origin;
397
+ const samePath = dest.pathname + dest.search === prev.pathname + prev.search;
398
+ if (sameOrigin && samePath) {
399
+ event.preventDefault();
400
+ if (dest.href !== prev.href) history.pushState(null, "", dest);
401
+ if (!dest.hash) {
402
+ if (dest.href.endsWith("#")) window.scrollTo(0, 0);
403
+ else {
404
+ window._qRouterScrollEnabled = false;
405
+ clearTimeout(window._qRouterScrollDebounce);
406
+ saveScrollState({
407
+ ...currentScrollState(),
408
+ x: 0,
409
+ y: 0
410
+ });
411
+ location.reload();
412
+ }
413
+ } else {
414
+ const elmId = dest.hash.slice(1);
415
+ const elm = document.getElementById(elmId);
416
+ if (elm) elm.scrollIntoView();
417
+ }
418
+ }
419
+ }
420
+ };
421
+ window._qRouterInitVisibility = () => {
422
+ if (!window._qRouterSPA && window._qRouterScrollEnabled && document.visibilityState === "hidden") saveScrollState();
423
+ };
424
+ window._qRouterInitScroll = () => {
425
+ if (window._qRouterSPA || !window._qRouterScrollEnabled) return;
426
+ clearTimeout(window._qRouterScrollDebounce);
427
+ window._qRouterScrollDebounce = setTimeout(() => {
428
+ saveScrollState();
429
+ window._qRouterScrollDebounce = void 0;
430
+ }, 200);
431
+ };
432
+ window._qRouterScrollEnabled = true;
433
+ window.addEventListener("popstate", window._qRouterInitPopstate);
434
+ window.addEventListener("scroll", window._qRouterInitScroll, { passive: true });
435
+ document.addEventListener("click", window._qRouterInitAnchors);
436
+ if (!window.navigation) document.addEventListener("visibilitychange", window._qRouterInitVisibility, { passive: true });
437
+ }
438
+ }, "spa_init_event_igI1pUsax0E"));
439
+ /**
440
+ * Submit an action to the server and get the result.
441
+ *
442
+ * POSTs to the route URL with `qaction={actionId}` appended and `Accept: application/json`. The
443
+ * server runs the action and returns the action result, optionally with the loader hashes that
444
+ * should be invalidated.
445
+ */
446
+ async function submitAction(action, routeUrl) {
447
+ const pathBase = ensureSlash(routeUrl.pathname);
448
+ const searchParams = new URLSearchParams(routeUrl.search);
449
+ searchParams.set(QACTION_KEY, action.id);
450
+ const url = `${pathBase}?${searchParams.toString()}`;
451
+ const actionData = action.data;
452
+ action.data = void 0;
453
+ let fetchOptions;
454
+ if (actionData instanceof FormData) fetchOptions = {
455
+ method: "POST",
456
+ body: actionData,
457
+ headers: { Accept: "application/json" }
458
+ };
459
+ else fetchOptions = {
460
+ method: "POST",
461
+ body: JSON.stringify(actionData),
462
+ headers: {
463
+ "Content-Type": "application/json; charset=UTF-8",
464
+ Accept: "application/json"
465
+ }
466
+ };
467
+ const response = await fetch(url, fetchOptions);
468
+ if (response.redirected) return {
469
+ status: response.status,
470
+ result: void 0,
471
+ redirect: new URL(response.url)
472
+ };
473
+ if ((response.headers.get("content-type") || "").includes("json")) {
474
+ const text = await response.text();
475
+ const data = await _deserialize(text);
476
+ return {
477
+ status: response.status,
478
+ result: data?.result,
479
+ redirect: data?.redirect,
480
+ loaderHashes: data?.loaderHashes
481
+ };
482
+ }
492
483
  }
493
- function scan(text, idx, end, ch, suffix = "") {
494
- while (idx < end && text.charCodeAt(idx) !== ch) {
495
- idx++;
496
- }
497
- const suffixLength = suffix.length;
498
- for (let i = 0; i < suffixLength; i++) {
499
- if (text.charCodeAt(idx - suffixLength + i) !== suffix.charCodeAt(i)) {
500
- return -1;
501
- }
502
- }
503
- return idx - suffixLength;
504
- }
505
- function recursiveScan(paramName, suffix, path, pathStart, pathLength, route, routeStart, routeLength) {
506
- if (path.charCodeAt(pathStart) === 47) {
507
- pathStart++;
508
- }
509
- let pathIdx = pathLength;
510
- const sep = suffix + "/";
511
- while (pathIdx >= pathStart) {
512
- const match = matchRoutePart(route, routeStart, routeLength, path, pathIdx, pathLength);
513
- if (match) {
514
- let value = path.substring(pathStart, Math.min(pathIdx, pathLength));
515
- if (value.endsWith(sep)) {
516
- value = value.substring(0, value.length - sep.length);
517
- }
518
- match[paramName] = decodeURIComponent(value);
519
- return match;
520
- }
521
- const newPathIdx = lastIndexOf(path, pathStart, sep, pathIdx, pathStart - 1) + sep.length;
522
- if (pathIdx === newPathIdx) {
523
- break;
524
- }
525
- pathIdx = newPathIdx;
526
- }
527
- return null;
528
- }
529
- function lastIndexOf(text, start, match, searchIdx, notFoundIdx) {
530
- let idx = text.lastIndexOf(match, searchIdx);
531
- if (idx == searchIdx - match.length) {
532
- idx = text.lastIndexOf(match, searchIdx - match.length - 1);
533
- }
534
- return idx > start ? idx : notFoundIdx;
535
- }
536
- var RouteDataProp = /* @__PURE__ */ function(RouteDataProp2) {
537
- RouteDataProp2[RouteDataProp2["RouteName"] = 0] = "RouteName";
538
- RouteDataProp2[RouteDataProp2["Loaders"] = 1] = "Loaders";
539
- RouteDataProp2[RouteDataProp2["OriginalPathname"] = 2] = "OriginalPathname";
540
- RouteDataProp2[RouteDataProp2["RouteBundleNames"] = 3] = "RouteBundleNames";
541
- return RouteDataProp2;
542
- }({});
543
- var MenuDataProp = /* @__PURE__ */ function(MenuDataProp2) {
544
- MenuDataProp2[MenuDataProp2["Pathname"] = 0] = "Pathname";
545
- MenuDataProp2[MenuDataProp2["MenuLoader"] = 1] = "MenuLoader";
546
- return MenuDataProp2;
547
- }({});
548
- const loadRoute = async (routes, menus, cacheModules, pathname) => {
549
- if (!Array.isArray(routes)) {
550
- return null;
551
- }
552
- for (const routeData of routes) {
553
- const routeName = routeData[RouteDataProp.RouteName];
554
- const params = matchRoute(routeName, pathname);
555
- if (!params) {
556
- continue;
557
- }
558
- const loaders = routeData[RouteDataProp.Loaders];
559
- const routeBundleNames = routeData[RouteDataProp.RouteBundleNames];
560
- const modules = new Array(loaders.length);
561
- const pendingLoads = [];
562
- loaders.forEach((moduleLoader, i) => {
563
- loadModule(moduleLoader, pendingLoads, (routeModule) => modules[i] = routeModule, cacheModules);
564
- });
565
- const menuLoader = getMenuLoader(menus, pathname);
566
- let menu = void 0;
567
- loadModule(menuLoader, pendingLoads, (menuModule) => menu = menuModule?.default, cacheModules);
568
- if (pendingLoads.length > 0) {
569
- await Promise.all(pendingLoads);
570
- }
571
- return [
572
- routeName,
573
- params,
574
- modules,
575
- deepFreeze(menu),
576
- routeBundleNames
577
- ];
578
- }
579
- return null;
580
- };
581
- const loadModule = (moduleLoader, pendingLoads, moduleSetter, cacheModules) => {
582
- if (typeof moduleLoader === "function") {
583
- const loadedModule = MODULE_CACHE.get(moduleLoader);
584
- if (loadedModule) {
585
- moduleSetter(loadedModule);
586
- } else {
587
- const moduleOrPromise = moduleLoader();
588
- if (typeof moduleOrPromise.then === "function") {
589
- pendingLoads.push(moduleOrPromise.then((loadedModule2) => {
590
- if (cacheModules !== false) {
591
- MODULE_CACHE.set(moduleLoader, loadedModule2);
592
- }
593
- moduleSetter(loadedModule2);
594
- }));
595
- } else if (moduleOrPromise) {
596
- moduleSetter(moduleOrPromise);
597
- }
598
- }
599
- }
600
- };
601
- const getMenuLoader = (menus, pathname) => {
602
- if (menus) {
603
- pathname = pathname.endsWith("/") ? pathname : pathname + "/";
604
- const menu = menus.find((m) => m[MenuDataProp.Pathname] === pathname || pathname.startsWith(m[MenuDataProp.Pathname] + (pathname.endsWith("/") ? "" : "/")));
605
- if (menu) {
606
- return menu[MenuDataProp.MenuLoader];
607
- }
608
- }
609
- };
610
- function callRestoreScrollOnDocument() {
611
- if (document.__q_scroll_restore__) {
612
- document.__q_scroll_restore__();
613
- document.__q_scroll_restore__ = void 0;
614
- }
615
- }
616
- const restoreScroll = (type, toUrl2, fromUrl, scroller, scrollState) => {
617
- if (type === "popstate" && scrollState) {
618
- scroller.scrollTo(scrollState.x, scrollState.y);
619
- } else if (type === "link" || type === "form") {
620
- if (!hashScroll(toUrl2, fromUrl)) {
621
- scroller.scrollTo(0, 0);
622
- }
623
- }
624
- };
625
- const hashScroll = (toUrl2, fromUrl) => {
626
- const elmId = toUrl2.hash.slice(1);
627
- const elm = elmId && document.getElementById(elmId);
628
- if (elm) {
629
- elm.scrollIntoView();
630
- return true;
631
- } else if (!elm && toUrl2.hash && isSamePath(toUrl2, fromUrl)) {
632
- return true;
633
- }
634
- return false;
484
+ var qwik_view_transition_default = "@layer qwik{@supports selector(html:active-view-transition-type(type)){html:active-view-transition-type(qwik-navigation){& :root{view-transition-name:none}}}@supports not selector(html:active-view-transition-type(type)){:root{view-transition-name:none}}}";
485
+ /** View transitions are opt-in and require browser support. */
486
+ var shouldStartViewTransition = (viewTransition) => viewTransition === true && "startViewTransition" in document;
487
+ var VIEW_TRANSITION_STYLE_ID = "qwik-view-transition";
488
+ /** Inject the view-transition stylesheet once, only when a transition actually runs. */
489
+ var ensureViewTransitionStyles = () => {
490
+ if (document.getElementById(VIEW_TRANSITION_STYLE_ID)) return;
491
+ const style = document.createElement("style");
492
+ style.id = VIEW_TRANSITION_STYLE_ID;
493
+ style.textContent = qwik_view_transition_default;
494
+ document.head.appendChild(style);
635
495
  };
636
- const currentScrollState = (elm) => {
637
- return {
638
- x: elm.scrollLeft,
639
- y: elm.scrollTop,
640
- w: Math.max(elm.scrollWidth, elm.clientWidth),
641
- h: Math.max(elm.scrollHeight, elm.clientHeight)
642
- };
496
+ var startViewTransition = (params) => {
497
+ if ("startViewTransition" in document) {
498
+ ensureViewTransitionStyles();
499
+ let transition;
500
+ try {
501
+ transition = document.startViewTransition(params);
502
+ } catch {
503
+ transition = document.startViewTransition(params.update);
504
+ }
505
+ const event = new CustomEvent("qviewtransition", { detail: transition });
506
+ document.dispatchEvent(event);
507
+ return {
508
+ ready: transition.ready,
509
+ transition
510
+ };
511
+ } else return { ready: params.update() };
643
512
  };
644
- const getScrollHistory = () => {
645
- const state = history.state;
646
- return state?._qRouterScroll;
513
+ /**
514
+ * @deprecated Use `QWIK_ROUTER_SCROLLER` instead (will be removed in V3)
515
+ * @public
516
+ */
517
+ var QWIK_CITY_SCROLLER = "_qCityScroller";
518
+ /** @public */
519
+ var QWIK_ROUTER_SCROLLER = "_qRouterScroller";
520
+ var preventNav = {};
521
+ var internalState = {
522
+ navCount: 0,
523
+ attemptCount: 0
647
524
  };
648
- const saveScrollHistory = (scrollState) => {
649
- const state = history.state || {};
650
- state._qRouterScroll = scrollState;
651
- history.replaceState(state, "");
525
+ var getScroller = () => {
526
+ let scroller = document.getElementById(QWIK_ROUTER_SCROLLER);
527
+ if (!scroller) {
528
+ scroller = document.getElementById(QWIK_CITY_SCROLLER);
529
+ if (scroller && isDev) console.warn(`Please update your scroller ID to "${QWIK_ROUTER_SCROLLER}" as "${QWIK_CITY_SCROLLER}" is deprecated and will be removed in V3`);
530
+ }
531
+ return scroller ?? document.documentElement;
652
532
  };
653
- const spaInit = event$((_, el) => {
654
- const win = window;
655
- const spa = "_qRouterSPA";
656
- const initPopstate = "_qRouterInitPopstate";
657
- const initAnchors = "_qRouterInitAnchors";
658
- const initVisibility = "_qRouterInitVisibility";
659
- const initScroll = "_qRouterInitScroll";
660
- if (!win[spa] && !win[initPopstate] && !win[initAnchors] && !win[initVisibility] && !win[initScroll]) {
661
- const currentPath = location.pathname + location.search;
662
- const historyPatch = "_qRouterHistoryPatch";
663
- const scrollEnabled = "_qRouterScrollEnabled";
664
- const debounceTimeout = "_qRouterScrollDebounce";
665
- const scrollHistory = "_qRouterScroll";
666
- const checkAndScroll = (scrollState) => {
667
- if (scrollState) {
668
- win.scrollTo(scrollState.x, scrollState.y);
669
- }
670
- };
671
- const currentScrollState2 = () => {
672
- const elm = document.documentElement;
673
- return {
674
- x: elm.scrollLeft,
675
- y: elm.scrollTop,
676
- w: Math.max(elm.scrollWidth, elm.clientWidth),
677
- h: Math.max(elm.scrollHeight, elm.clientHeight)
678
- };
679
- };
680
- const saveScrollState = (scrollState) => {
681
- const state = history.state || {};
682
- state[scrollHistory] = scrollState || currentScrollState2();
683
- history.replaceState(state, "");
684
- };
685
- saveScrollState();
686
- win[initPopstate] = () => {
687
- if (win[spa]) {
688
- return;
689
- }
690
- win[scrollEnabled] = false;
691
- clearTimeout(win[debounceTimeout]);
692
- if (currentPath !== location.pathname + location.search) {
693
- const getContainer = (el2) => el2.closest("[q\\:container]:not([q\\:container=html]):not([q\\:container=text])");
694
- const container = getContainer(el);
695
- const domContainer = container.qContainer;
696
- const hostElement = domContainer.vNodeLocate(el);
697
- const nav = domContainer?.resolveContext(hostElement, {
698
- id: "qc--n"
699
- });
700
- if (nav) {
701
- nav(location.href, {
702
- type: "popstate"
703
- });
704
- } else {
705
- location.reload();
706
- }
707
- } else {
708
- if (history.scrollRestoration === "manual") {
709
- const scrollState = history.state?.[scrollHistory];
710
- checkAndScroll(scrollState);
711
- win[scrollEnabled] = true;
712
- }
713
- }
714
- };
715
- if (!win[historyPatch]) {
716
- win[historyPatch] = true;
717
- const pushState = history.pushState;
718
- const replaceState = history.replaceState;
719
- const prepareState = (state) => {
720
- if (state === null || typeof state === "undefined") {
721
- state = {};
722
- } else if (state?.constructor !== Object) {
723
- state = {
724
- _data: state
725
- };
726
- if (isDev) {
727
- 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`");
728
- }
729
- }
730
- state._qRouterScroll = state._qRouterScroll || currentScrollState2();
731
- return state;
732
- };
733
- history.pushState = (state, title, url) => {
734
- state = prepareState(state);
735
- return pushState.call(history, state, title, url);
736
- };
737
- history.replaceState = (state, title, url) => {
738
- state = prepareState(state);
739
- return replaceState.call(history, state, title, url);
740
- };
741
- }
742
- win[initAnchors] = (event) => {
743
- if (win[spa] || event.defaultPrevented) {
744
- return;
745
- }
746
- const target = event.target.closest("a[href]");
747
- if (target && !target.hasAttribute("preventdefault:click")) {
748
- const href = target.getAttribute("href");
749
- const prev = new URL(location.href);
750
- const dest = new URL(href, prev);
751
- const sameOrigin = dest.origin === prev.origin;
752
- const samePath = dest.pathname + dest.search === prev.pathname + prev.search;
753
- if (sameOrigin && samePath) {
754
- event.preventDefault();
755
- if (dest.href !== prev.href) {
756
- history.pushState(null, "", dest);
757
- }
758
- if (!dest.hash) {
759
- if (dest.href.endsWith("#")) {
760
- window.scrollTo(0, 0);
761
- } else {
762
- win[scrollEnabled] = false;
763
- clearTimeout(win[debounceTimeout]);
764
- saveScrollState({
765
- ...currentScrollState2(),
766
- x: 0,
767
- y: 0
768
- });
769
- location.reload();
770
- }
771
- } else {
772
- const elmId = dest.hash.slice(1);
773
- const elm = document.getElementById(elmId);
774
- if (elm) {
775
- elm.scrollIntoView();
776
- }
777
- }
778
- }
779
- }
780
- };
781
- win[initVisibility] = () => {
782
- if (!win[spa] && win[scrollEnabled] && document.visibilityState === "hidden") {
783
- saveScrollState();
784
- }
785
- };
786
- win[initScroll] = () => {
787
- if (win[spa] || !win[scrollEnabled]) {
788
- return;
789
- }
790
- clearTimeout(win[debounceTimeout]);
791
- win[debounceTimeout] = setTimeout(() => {
792
- saveScrollState();
793
- win[debounceTimeout] = void 0;
794
- }, 200);
795
- };
796
- win[scrollEnabled] = true;
797
- setTimeout(() => {
798
- win.addEventListener("popstate", win[initPopstate]);
799
- win.addEventListener("scroll", win[initScroll], {
800
- passive: true
801
- });
802
- document.body.addEventListener("click", win[initAnchors]);
803
- if (!win.navigation) {
804
- document.addEventListener("visibilitychange", win[initVisibility], {
805
- passive: true
806
- });
807
- }
808
- }, 0);
809
- }
810
- });
811
- const startViewTransition = (params) => {
812
- if (!params.update) {
813
- return;
814
- }
815
- if ("startViewTransition" in document) {
816
- let transition;
817
- try {
818
- transition = document.startViewTransition(params);
819
- } catch {
820
- transition = document.startViewTransition(params.update);
821
- }
822
- const event = new CustomEvent("qviewtransition", {
823
- detail: transition
824
- });
825
- document.dispatchEvent(event);
826
- return transition;
827
- } else {
828
- params.update?.();
829
- }
533
+ /**
534
+ * @public
535
+ * This hook initializes Qwik Router, providing the necessary context for it to work.
536
+ *
537
+ * This hook should be used once, at the root of your application.
538
+ */
539
+ var useQwikRouter = (props) => {
540
+ if (!isServer) throw new Error("useQwikRouter can only run during SSR on the server. If you are seeing this, it means you are re-rendering the root of your application. Fix that or use the <QwikRouterProvider> component around the root of your application.");
541
+ const env = useQwikRouterEnv();
542
+ if (!env?.params) throw new Error(`Missing Qwik Router Env Data for help visit https://github.com/QwikDev/qwik/issues/6237`);
543
+ const urlEnv = useServerData("url");
544
+ if (!urlEnv) throw new Error(`Missing Qwik URL Env Data`);
545
+ const serverHead = useServerData("documentHead");
546
+ const manifestHash = useServerData("containerAttributes")?.["q:manifest-hash"];
547
+ const url = new URL(urlEnv);
548
+ const routeLocationTarget = {
549
+ url,
550
+ params: env.params,
551
+ isNavigating: false,
552
+ prevUrl: void 0
553
+ };
554
+ const routeLocation = useStore(routeLocationTarget, { deep: false });
555
+ const navResolver = {};
556
+ const routeLoaderCtx = useStore(env.routeLoaderCtx);
557
+ routeLoaderCtx.manifestHash = manifestHash;
558
+ const loaderState = {};
559
+ const contentModulesForInit = env.loadedRoute.$mods$;
560
+ const loaders = ensureRouteLoaderSignals(contentModulesForInit, loaderState, routeLoaderCtx, env.ev);
561
+ for (const loader of loaders) if (loader.__id in env.loaderValues) {
562
+ const value = env.loaderValues[loader.__id];
563
+ setLoaderSignalValue(loaderState[loader.__id], value);
564
+ }
565
+ const routeInternal = useSignal({
566
+ type: "initial",
567
+ dest: url
568
+ });
569
+ const documentHead = useStore(() => createDocumentHead(serverHead, manifestHash));
570
+ const content = useStore({
571
+ headings: void 0,
572
+ menu: void 0
573
+ });
574
+ const contentInternal = useSignal();
575
+ /**
576
+ * Non-serializable navigation context passed from the nav task to the navigation task. Only the
577
+ * data that can't be derived from existing stores/signals.
578
+ */
579
+ const navContext = useSignal();
580
+ const httpStatus = useSignal({
581
+ status: env.response.status,
582
+ message: env.loadedRoute.$notFound$ ? "Not Found" : env.response.statusMessage ?? ""
583
+ });
584
+ const currentActionId = env.response.action;
585
+ const currentAction = currentActionId ? env.response.actionResult : void 0;
586
+ const actionState = useSignal(currentAction ? {
587
+ id: currentActionId,
588
+ data: env.response.formData,
589
+ output: {
590
+ result: currentAction,
591
+ status: env.response.status
592
+ }
593
+ } : void 0);
594
+ const actionDataSignal = useSignal(currentActionId ? {
595
+ action: currentActionId,
596
+ actionResult: currentAction,
597
+ status: env.response.status
598
+ } : void 0);
599
+ const registerPreventNav = /*#__PURE__*/ inlinedQrl((fn$) => {
600
+ if (!isBrowser) return;
601
+ preventNav.$handler$ ||= (event) => {
602
+ internalState.attemptCount++;
603
+ if (!preventNav.$cbs$) return;
604
+ if ([...preventNav.$cbs$.values()].map((cb) => cb.resolved ? cb.resolved() : cb()).some(Boolean)) {
605
+ event.preventDefault();
606
+ event.returnValue = true;
607
+ }
608
+ };
609
+ (preventNav.$cbs$ ||= /* @__PURE__ */ new Set()).add(fn$);
610
+ fn$.resolve();
611
+ window.addEventListener("beforeunload", preventNav.$handler$);
612
+ return () => {
613
+ if (preventNav.$cbs$) {
614
+ preventNav.$cbs$.delete(fn$);
615
+ if (!preventNav.$cbs$.size) {
616
+ preventNav.$cbs$ = void 0;
617
+ window.removeEventListener("beforeunload", preventNav.$handler$);
618
+ }
619
+ }
620
+ };
621
+ }, "useQwikRouter_registerPreventNav_69B0DK0eZJc");
622
+ /**
623
+ * This is the `nav()` function that `useNavigation()` returns. It is also used internally for SPA
624
+ * navigations and is provided in context for use in loaders and actions.
625
+ *
626
+ * Note: when goto is called, the address bar change must happen in the same tick for Safari to
627
+ * treat it as a user-initiated navigation and allow scroll restoration to work. For this reason,
628
+ * make sure to change the address bar before awaiting anything.
629
+ */
630
+ const goto = /*#__PURE__*/ inlinedQrl(async (path, opt) => {
631
+ let actionState = _capturesObj._[0], manifestHash = _capturesObj._[1], navResolver = _capturesObj._[2], routeInternal = _capturesObj._[3], routeLoaderCtx = _capturesObj._[4], routeLocation = _capturesObj._[5];
632
+ const { type = "link", forceReload = path === void 0, replaceState = false, scroll = true } = typeof opt === "object" ? opt : { forceReload: opt };
633
+ if (isBrowser && type === "link" && routeInternal.value.type === "initial") {
634
+ const url = new URL(window.location.href);
635
+ routeInternal.value.dest = url;
636
+ routeLocation.url = url;
637
+ }
638
+ const lastDest = routeInternal.value.dest;
639
+ const dest = path === void 0 ? lastDest : typeof path === "number" ? path : toUrl(path, routeLocation.url);
640
+ if (navResolver.p && !forceReload && typeof dest !== "number" && isSamePath(dest, lastDest) && dest.href === lastDest.href) return navResolver.p;
641
+ const attemptCount = ++internalState.attemptCount;
642
+ if (preventNav.$cbs$ && (forceReload || typeof dest === "number" || !isSamePath(dest, lastDest) || !isSameOrigin(dest, lastDest))) {
643
+ const prevents = await Promise.all([...preventNav.$cbs$.values()].map((cb) => cb(dest)));
644
+ if (attemptCount !== internalState.attemptCount || prevents.some(Boolean)) {
645
+ if (attemptCount === internalState.attemptCount && type === "popstate") history.pushState(null, "", lastDest);
646
+ return;
647
+ }
648
+ }
649
+ if (typeof dest === "number") {
650
+ if (isBrowser) history.go(dest);
651
+ return;
652
+ }
653
+ if (!isSameOrigin(dest, lastDest)) {
654
+ if (isBrowser) location.href = dest.href;
655
+ return;
656
+ }
657
+ if (!forceReload && isSamePath(dest, lastDest)) {
658
+ if (isBrowser) {
659
+ if (type === "link" && dest.href !== location.href) history.pushState(null, "", dest);
660
+ const scroller = getScroller();
661
+ restoreScroll(type, dest, new URL(location.href), scroller, getScrollHistory());
662
+ if (type === "popstate") window._qRouterScrollEnabled = true;
663
+ }
664
+ if (dest.href !== routeLocation.url.href) {
665
+ const newUrl = new URL(dest.href);
666
+ routeInternal.value.dest = newUrl;
667
+ routeLocation.url = newUrl;
668
+ }
669
+ return navResolver.p;
670
+ }
671
+ const navCount = ++internalState.navCount;
672
+ internalState.currentTransition?.skipTransition();
673
+ navResolver.cancel?.();
674
+ navResolver.cancel = void 0;
675
+ navResolver.r?.();
676
+ let historyUpdated = false;
677
+ if (isBrowser) getClientRouteLoaders(routeLoaderCtx, routeLocation.url.href);
678
+ if (isBrowser && type === "link" && !forceReload) {
679
+ const scroller = getScroller();
680
+ window._qRouterScrollEnabled = false;
681
+ clearTimeout(window._qRouterScrollDebounce);
682
+ saveScrollHistory(currentScrollState(scroller));
683
+ clientNavigate(window, type, new URL(location.href), dest, replaceState);
684
+ historyUpdated = true;
685
+ }
686
+ const wasNavigating = routeLocation.isNavigating;
687
+ routeLocation.isNavigating = true;
688
+ const container = isBrowser ? _getContextContainer() : void 0;
689
+ if (container && !wasNavigating) {
690
+ await _waitUntilRendered(container);
691
+ if (navCount !== internalState.navCount) return;
692
+ }
693
+ actionState.value = void 0;
694
+ routeInternal.value = {
695
+ type,
696
+ dest,
697
+ forceReload,
698
+ replaceState,
699
+ scroll,
700
+ historyUpdated
701
+ };
702
+ if (wasNavigating) abortRouteLoaderNavigation(routeLoaderCtx);
703
+ if (isBrowser) prefetchRoute(dest, false, .8, manifestHash, true);
704
+ navResolver.p = new Promise((resolve) => {
705
+ navResolver.r = () => {
706
+ navResolver.r = void 0;
707
+ navResolver.p = void 0;
708
+ resolve();
709
+ };
710
+ });
711
+ return navResolver.p;
712
+ }, "useQwikRouter_goto_8j8Vrz2yUIM", [
713
+ actionState,
714
+ manifestHash,
715
+ navResolver,
716
+ routeInternal,
717
+ routeLoaderCtx,
718
+ routeLocation
719
+ ]);
720
+ useContextProvider(ContentContext, content);
721
+ useContextProvider(ContentInternalContext, contentInternal);
722
+ useContextProvider(DocumentHeadContext, documentHead);
723
+ useContextProvider(HttpStatusContext, httpStatus);
724
+ useContextProvider(RouteLocationContext, routeLocation);
725
+ useContextProvider(RouteNavigateContext, goto);
726
+ useContextProvider(RouteStateContext, loaderState);
727
+ useContextProvider(RouteLoaderCtxContext, routeLoaderCtx);
728
+ useContextProvider(RouteActionContext, actionState);
729
+ useContextProvider(RoutePreventNavigateContext, registerPreventNav);
730
+ /**
731
+ * This is split in 3 tasks because we need to update the head once we figured out the route, and
732
+ * before we trigger the render, and we need to subscribe only head to loader signal updates
733
+ */
734
+ useTaskQrl(/*#__PURE__*/ inlinedQrl(async ({ track }) => {
735
+ let actionDataSignal = _capturesObj._[0], actionState = _capturesObj._[1], content = _capturesObj._[2], contentInternal = _capturesObj._[3], env = _capturesObj._[4], goto = _capturesObj._[5], httpStatus = _capturesObj._[6], loaderState = _capturesObj._[7], navContext = _capturesObj._[8], navResolver = _capturesObj._[9], routeInternal = _capturesObj._[10], routeLoaderCtx = _capturesObj._[11], routeLocation = _capturesObj._[12], routeLocationTarget = _capturesObj._[13];
736
+ const navigation = track(routeInternal);
737
+ const action = track(actionState);
738
+ action?.resolveDispatch?.();
739
+ if (action) action.resolveDispatch = void 0;
740
+ const prevUrl = routeLocation.url;
741
+ const navType = action ? "form" : navigation.type;
742
+ const replaceState = navigation.replaceState;
743
+ const navCountBefore = internalState.navCount;
744
+ let trackUrl;
745
+ let endpointResponse;
746
+ let actionData;
747
+ let actionLoaderHashes;
748
+ let loadedRoute;
749
+ if (isServer) {
750
+ trackUrl = new URL(navigation.dest, routeLocation.url);
751
+ loadedRoute = env.loadedRoute;
752
+ endpointResponse = env.response;
753
+ actionData = endpointResponse;
754
+ } else {
755
+ trackUrl = new URL(navigation.dest, location);
756
+ const canceled = new Promise((resolve) => {
757
+ navResolver.cancel = () => resolve(void 0);
758
+ });
759
+ if (trackUrl.pathname.endsWith("/")) {
760
+ if (globalThis.__NO_TRAILING_SLASH__) trackUrl.pathname = trackUrl.pathname.slice(0, -1);
761
+ } else if (!globalThis.__NO_TRAILING_SLASH__) trackUrl.pathname = ensureSlash(trackUrl.pathname);
762
+ const loadRoutePromise = getRouterConfig().then((config) => {
763
+ if (internalState.navCount !== navCountBefore) return;
764
+ return loadRoute(config.routes, config.cacheModules, trackUrl.pathname);
765
+ });
766
+ try {
767
+ const route = await Promise.race([loadRoutePromise, canceled]);
768
+ if (!route) return;
769
+ loadedRoute = route;
770
+ } catch (e) {
771
+ if (internalState.navCount !== navCountBefore) return;
772
+ const preparedNavCount = getClientRouteLoaders(routeLoaderCtx).navCount;
773
+ if (preparedNavCount !== void 0) restoreRouteLoaders(loaderState, routeLoaderCtx, preparedNavCount);
774
+ console.error(`Could not load route ${trackUrl.pathname}, reloading:`, e);
775
+ window.location.href = trackUrl.href;
776
+ return;
777
+ }
778
+ if (internalState.navCount !== navCountBefore) return;
779
+ if (action) {
780
+ const result = await Promise.race([submitAction(action, trackUrl).then((result) => {
781
+ if (result && action.resolve) {
782
+ action.resolve({
783
+ status: result.status,
784
+ result: result.result
785
+ });
786
+ action.resolve = void 0;
787
+ }
788
+ return result;
789
+ }), canceled]);
790
+ if (internalState.navCount !== navCountBefore || action !== actionState.untrackedValue) return;
791
+ navResolver.cancel = void 0;
792
+ if (!result) {
793
+ routeInternal.untrackedValue = {
794
+ type: navType,
795
+ dest: trackUrl
796
+ };
797
+ return;
798
+ }
799
+ if (result.redirect) {
800
+ if (result.redirect instanceof URL) location.href = result.redirect.href;
801
+ else goto(result.redirect, { replaceState: true });
802
+ return;
803
+ }
804
+ actionData = {
805
+ status: result.status,
806
+ action: action.id,
807
+ actionResult: result.result
808
+ };
809
+ actionLoaderHashes = result.loaderHashes;
810
+ }
811
+ navResolver.cancel = void 0;
812
+ }
813
+ const { $routeName$, $params$, $mods$, $menu$, $notFound$ } = loadedRoute;
814
+ const contentModules = $mods$;
815
+ if (!isServer) routeLoaderCtx.goto = noSerialize(goto);
816
+ let routeLoaders;
817
+ if (isServer) {
818
+ Object.assign(routeLoaderCtx.loaderPaths, loadedRoute.$loaderPaths$);
819
+ routeLoaders = ensureRouteLoaderSignals(contentModules, loaderState, routeLoaderCtx, env.ev);
820
+ } else routeLoaders = prepareRouteLoaders(contentModules, loaderState, routeLoaderCtx, loadedRoute.$loaderPaths$, trackUrl, prevUrl, navCountBefore, action ? actionLoaderHashes ?? null : void 0, action ?? navigation);
821
+ if (routeLoaders.length > 0) for (let i = 0; i < routeLoaders.length; i++) {
822
+ const loader = routeLoaders[i];
823
+ if (!isImmutableLoader(loader.__id)) loaderState[loader.__id].untrackedPending;
824
+ }
825
+ if (!isServer) clearNavFetchCache();
826
+ if (internalState.navCount !== navCountBefore) return;
827
+ if ($notFound$) httpStatus.value = {
828
+ status: 404,
829
+ message: "Not Found"
830
+ };
831
+ else if (endpointResponse) httpStatus.value = {
832
+ status: endpointResponse.status,
833
+ message: endpointResponse.statusMessage ?? "OK"
834
+ };
835
+ else if (actionData) httpStatus.value = {
836
+ status: actionData.status,
837
+ message: "OK"
838
+ };
839
+ else httpStatus.value = {
840
+ status: 200,
841
+ message: "OK"
842
+ };
843
+ const pageModule = contentModules[contentModules.length - 1];
844
+ if (isSamePath(trackUrl, navigation.dest)) trackUrl.hash = navigation.dest.hash;
845
+ if (navigation.dest.search && !!isSamePath(trackUrl, prevUrl)) trackUrl.search = navigation.dest.search;
846
+ let shouldForcePrevUrl = false;
847
+ let shouldForceUrl = false;
848
+ let shouldForceParams = false;
849
+ if (!isSamePath(trackUrl, prevUrl)) {
850
+ if (_hasStoreEffects(routeLocation, "prevUrl")) shouldForcePrevUrl = true;
851
+ routeLocationTarget.prevUrl = prevUrl;
852
+ }
853
+ if (routeLocationTarget.url !== trackUrl) {
854
+ if (_hasStoreEffects(routeLocation, "url")) shouldForceUrl = true;
855
+ routeLocationTarget.url = trackUrl;
856
+ }
857
+ if (routeLocationTarget.params !== $params$) {
858
+ if (_hasStoreEffects(routeLocation, "params")) shouldForceParams = true;
859
+ routeLocationTarget.params = $params$;
860
+ }
861
+ const nextRouteInternal = {
862
+ type: navType,
863
+ dest: trackUrl
864
+ };
865
+ if (navigation.forceReload !== void 0) nextRouteInternal.forceReload = navigation.forceReload;
866
+ if (navigation.replaceState !== void 0) nextRouteInternal.replaceState = navigation.replaceState;
867
+ if (navigation.scroll !== void 0) nextRouteInternal.scroll = navigation.scroll;
868
+ if (navigation.historyUpdated !== void 0) nextRouteInternal.historyUpdated = navigation.historyUpdated;
869
+ routeInternal.untrackedValue = nextRouteInternal;
870
+ content.headings = pageModule.headings;
871
+ content.menu = $menu$;
872
+ contentInternal.untrackedValue = noSerialize(contentModules);
873
+ actionDataSignal.value = actionData;
874
+ navContext.value = noSerialize({
875
+ routeName: $routeName$,
876
+ navType,
877
+ prevUrl,
878
+ replaceState,
879
+ shouldForcePrevUrl,
880
+ shouldForceUrl,
881
+ shouldForceParams,
882
+ navCount: navCountBefore
883
+ });
884
+ }, "useQwikRouter_useTask_XpalYii770E", [
885
+ actionDataSignal,
886
+ actionState,
887
+ content,
888
+ contentInternal,
889
+ env,
890
+ goto,
891
+ httpStatus,
892
+ loaderState,
893
+ navContext,
894
+ navResolver,
895
+ routeInternal,
896
+ routeLoaderCtx,
897
+ routeLocation,
898
+ routeLocationTarget
899
+ ]), { deferUpdates: isServer });
900
+ /**
901
+ * Calc head. This is in a separate task so that loader updates can trigger head recalculation
902
+ * without re-running the navigation logic.
903
+ *
904
+ * Note that on the server these tasks run sequentially.
905
+ */
906
+ useTaskQrl(/*#__PURE__*/ inlinedQrl(({ track }) => {
907
+ let actionDataSignal = _capturesObj._[0], contentInternal = _capturesObj._[1], documentHead = _capturesObj._[2], loaderState = _capturesObj._[3], navContext = _capturesObj._[4], routeLocation = _capturesObj._[5], serverHead = _capturesObj._[6];
908
+ const contentModules = track(contentInternal);
909
+ const nav = navContext.untrackedValue;
910
+ if (!isServer && routeLocation.isNavigating && nav && nav.navCount !== internalState.navCount) return;
911
+ if (!contentModules) return;
912
+ const actionData = track(actionDataSignal);
913
+ let head;
914
+ try {
915
+ head = track(() => resolveHead(actionData, loaderState, routeLocation, contentModules, getLocale(""), serverHead));
916
+ } catch (error) {
917
+ if (isServer || isPromise(error)) throw error;
918
+ console.error(error);
919
+ return;
920
+ }
921
+ documentHead.links = head.links;
922
+ documentHead.meta = head.meta;
923
+ documentHead.styles = head.styles;
924
+ documentHead.scripts = head.scripts;
925
+ documentHead.title = head.title;
926
+ documentHead.frontmatter = head.frontmatter;
927
+ }, "useQwikRouter_useTask_1_1sKEZ9Pg1ow", [
928
+ actionDataSignal,
929
+ contentInternal,
930
+ documentHead,
931
+ loaderState,
932
+ navContext,
933
+ routeLocation,
934
+ serverHead
935
+ ]), { deferUpdates: isServer });
936
+ /** Actual navigation */
937
+ useTaskQrl(/*#__PURE__*/ inlinedQrl(({ track }) => {
938
+ let contentInternal = _capturesObj._[0], goto = _capturesObj._[1], loaderState = _capturesObj._[2], manifestHash = _capturesObj._[3], navContext = _capturesObj._[4], navResolver = _capturesObj._[5], props = _capturesObj._[6], routeInternal = _capturesObj._[7], routeLoaderCtx = _capturesObj._[8], routeLocation = _capturesObj._[9];
939
+ const nav = track(navContext);
940
+ if (isServer || !nav) return;
941
+ if (nav.navCount !== internalState.navCount) return;
942
+ const container = _getContextContainer();
943
+ const navigation = routeInternal.untrackedValue;
944
+ const { navType, prevUrl, replaceState, routeName } = nav;
945
+ const trackUrl = routeLocation.url;
946
+ const scroller = getScroller();
947
+ let scrollState;
948
+ if (navType === "popstate") scrollState = getScrollHistory();
949
+ if (navigation.scroll && (!navigation.forceReload || !isSamePath(trackUrl, prevUrl)) && (navType === "link" || navType === "popstate") || navType === "form" && !isSamePath(trackUrl, prevUrl)) document.__q_scroll_restore__ = () => restoreScroll(navType, trackUrl, prevUrl, scroller, scrollState);
950
+ initializeSPA(goto, scroller);
951
+ if (navType !== "popstate") {
952
+ window._qRouterScrollEnabled = false;
953
+ clearTimeout(window._qRouterScrollDebounce);
954
+ if (!navigation.historyUpdated) saveScrollHistory(currentScrollState(scroller));
955
+ }
956
+ let didNavigate = false;
957
+ let navigatePromise;
958
+ let currentTransition;
959
+ const navigate = () => {
960
+ if (navigatePromise) return navigatePromise;
961
+ if (nav.navCount !== internalState.navCount) return Promise.resolve();
962
+ didNavigate = true;
963
+ if (navigation.historyUpdated) {
964
+ const currentPath = location.pathname + location.search + location.hash;
965
+ const nextPath = toPath(trackUrl);
966
+ if (currentPath !== nextPath) history.replaceState(history.state, "", nextPath);
967
+ } else clientNavigate(window, navType, prevUrl, trackUrl, replaceState);
968
+ contentInternal.trigger();
969
+ return navigatePromise = _waitUntilRendered(container).then(() => {
970
+ if (nav.navCount === internalState.navCount) commitRouteLoaders(loaderState, routeLoaderCtx, nav.navCount);
971
+ }, (error) => {
972
+ if (nav.navCount === internalState.navCount) restoreRouteLoaders(loaderState, routeLoaderCtx, nav.navCount);
973
+ throw error;
974
+ });
975
+ };
976
+ const _waitNextPage = () => {
977
+ if (!shouldStartViewTransition(props?.viewTransition)) return navigate().then(() => void 0);
978
+ const { ready, transition } = startViewTransition({
979
+ update: navigate,
980
+ types: ["qwik-navigation"]
981
+ });
982
+ currentTransition = transition;
983
+ internalState.currentTransition = transition;
984
+ return ready.then(() => transition, (reason) => {
985
+ if (!didNavigate && nav.navCount === internalState.navCount) return navigate().then(() => transition);
986
+ if (reason?.name === "AbortError") return transition;
987
+ throw reason;
988
+ });
989
+ };
990
+ _waitNextPage().finally(() => {
991
+ if (currentTransition && internalState.currentTransition === currentTransition) internalState.currentTransition = void 0;
992
+ if (nav.navCount !== internalState.navCount) return;
993
+ container.element.setAttribute?.(Q_ROUTE, routeName);
994
+ saveScrollHistory(currentScrollState(scroller));
995
+ window._qRouterScrollEnabled = true;
996
+ callRestoreScrollOnDocument();
997
+ refreshLinkPrefetchObserver(manifestHash);
998
+ if (nav.shouldForcePrevUrl) forceStoreEffects(routeLocation, "prevUrl");
999
+ if (nav.shouldForceUrl) forceStoreEffects(routeLocation, "url");
1000
+ if (nav.shouldForceParams) forceStoreEffects(routeLocation, "params");
1001
+ routeLocation.isNavigating = false;
1002
+ navResolver.r?.();
1003
+ });
1004
+ }, "useQwikRouter_useTask_2_yw17chooOac", [
1005
+ contentInternal,
1006
+ goto,
1007
+ loaderState,
1008
+ manifestHash,
1009
+ navContext,
1010
+ navResolver,
1011
+ props,
1012
+ routeInternal,
1013
+ routeLoaderCtx,
1014
+ routeLocation
1015
+ ]), { deferUpdates: false });
830
1016
  };
831
- const QWIK_CITY_SCROLLER = "_qCityScroller";
832
- const QWIK_ROUTER_SCROLLER = "_qRouterScroller";
833
- const preventNav = {};
834
- const internalState = {
835
- navCount: 0
836
- };
837
- const useQwikRouter = (props) => {
838
- useStyles$(`
839
- @layer qwik {
840
- @supports selector(html:active-view-transition-type(type)) {
841
- html:active-view-transition-type(qwik-navigation) {
842
- :root{view-transition-name:none}
843
- }
844
- }
845
- @supports not selector(html:active-view-transition-type(type)) {
846
- :root{view-transition-name:none}
847
- }
848
- }
849
- `);
850
- const env = useQwikRouterEnv();
851
- if (!env?.params) {
852
- throw new Error(`Missing Qwik Router Env Data for help visit https://github.com/QwikDev/qwik/issues/6237`);
853
- }
854
- const urlEnv = useServerData("url");
855
- if (!urlEnv) {
856
- throw new Error(`Missing Qwik URL Env Data`);
857
- }
858
- const serverHead = useServerData("documentHead");
859
- if (isServer) {
860
- if (env.ev.originalUrl.pathname !== env.ev.url.pathname && !__EXPERIMENTAL__.enableRequestRewrite) {
861
- 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.`);
862
- }
863
- }
864
- const url = new URL(urlEnv);
865
- const routeLocation = useStore({
866
- url,
867
- params: env.params,
868
- isNavigating: false,
869
- prevUrl: void 0
870
- }, {
871
- deep: false
872
- });
873
- const navResolver = {};
874
- const container = _getContextContainer();
875
- const getSerializationStrategy = (loaderId) => {
876
- return env.response.loadersSerializationStrategy.get(loaderId) || DEFAULT_LOADERS_SERIALIZATION_STRATEGY;
877
- };
878
- const loadersObject = {};
879
- const loaderState = {};
880
- for (const [key, value] of Object.entries(env.response.loaders)) {
881
- loadersObject[key] = value;
882
- loaderState[key] = createLoaderSignal(loadersObject, key, url, getSerializationStrategy(key), container);
883
- }
884
- loadersObject[SerializerSymbol] = (obj) => {
885
- const loadersSerializationObject = {};
886
- for (const [k, v] of Object.entries(obj)) {
887
- loadersSerializationObject[k] = getSerializationStrategy(k) === "always" ? v : _UNINITIALIZED;
888
- }
889
- return loadersSerializationObject;
890
- };
891
- const routeInternal = useSignal({
892
- type: "initial",
893
- dest: url,
894
- forceReload: false,
895
- replaceState: false,
896
- scroll: true
897
- });
898
- const documentHead = useStore(() => createDocumentHead(serverHead));
899
- const content = useStore({
900
- headings: void 0,
901
- menu: void 0
902
- });
903
- const contentInternal = useSignal();
904
- const currentActionId = env.response.action;
905
- const currentAction = currentActionId ? env.response.loaders[currentActionId] : void 0;
906
- const actionState = useSignal(currentAction ? {
907
- id: currentActionId,
908
- data: env.response.formData,
909
- output: {
910
- result: currentAction,
911
- status: env.response.status
912
- }
913
- } : void 0);
914
- const registerPreventNav = $((fn$) => {
915
- if (!isBrowser) {
916
- return;
917
- }
918
- preventNav.$handler$ || (preventNav.$handler$ = (event) => {
919
- internalState.navCount++;
920
- if (!preventNav.$cbs$) {
921
- return;
922
- }
923
- const prevents = [
924
- ...preventNav.$cbs$.values()
925
- ].map((cb) => cb.resolved ? cb.resolved() : cb());
926
- if (prevents.some(Boolean)) {
927
- event.preventDefault();
928
- event.returnValue = true;
929
- }
930
- });
931
- (preventNav.$cbs$ || (preventNav.$cbs$ = /* @__PURE__ */ new Set())).add(fn$);
932
- fn$.resolve();
933
- window.addEventListener("beforeunload", preventNav.$handler$);
934
- return () => {
935
- if (preventNav.$cbs$) {
936
- preventNav.$cbs$.delete(fn$);
937
- if (!preventNav.$cbs$.size) {
938
- preventNav.$cbs$ = void 0;
939
- window.removeEventListener("beforeunload", preventNav.$handler$);
940
- }
941
- }
942
- };
943
- });
944
- const goto = $(async (path, opt) => {
945
- const { type = "link", forceReload = path === void 0, replaceState = false, scroll = true } = typeof opt === "object" ? opt : {
946
- forceReload: opt
947
- };
948
- internalState.navCount++;
949
- const lastDest = routeInternal.value.dest;
950
- const dest = path === void 0 ? lastDest : typeof path === "number" ? path : toUrl(path, routeLocation.url);
951
- if (preventNav.$cbs$ && (forceReload || typeof dest === "number" || !isSamePath(dest, lastDest) || !isSameOrigin(dest, lastDest))) {
952
- const ourNavId = internalState.navCount;
953
- const prevents = await Promise.all([
954
- ...preventNav.$cbs$.values()
955
- ].map((cb) => cb(dest)));
956
- if (ourNavId !== internalState.navCount || prevents.some(Boolean)) {
957
- if (ourNavId === internalState.navCount && type === "popstate") {
958
- history.pushState(null, "", lastDest);
959
- }
960
- return;
961
- }
962
- }
963
- if (typeof dest === "number") {
964
- if (isBrowser) {
965
- history.go(dest);
966
- }
967
- return;
968
- }
969
- if (!isSameOrigin(dest, lastDest)) {
970
- if (isBrowser) {
971
- location.href = dest.href;
972
- }
973
- return;
974
- }
975
- if (!forceReload && isSamePath(dest, lastDest)) {
976
- if (isBrowser) {
977
- if (type === "link" && dest.href !== location.href) {
978
- history.pushState(null, "", dest);
979
- }
980
- let scroller = document.getElementById(QWIK_ROUTER_SCROLLER);
981
- if (!scroller) {
982
- scroller = document.getElementById(QWIK_CITY_SCROLLER);
983
- if (scroller && isDev) {
984
- console.warn(`Please update your scroller ID to "${QWIK_ROUTER_SCROLLER}" as "${QWIK_CITY_SCROLLER}" is deprecated and will be removed in V3`);
985
- }
986
- }
987
- if (!scroller) {
988
- scroller = document.documentElement;
989
- }
990
- restoreScroll(type, dest, new URL(location.href), scroller, getScrollHistory());
991
- if (type === "popstate") {
992
- window._qRouterScrollEnabled = true;
993
- }
994
- }
995
- return;
996
- }
997
- routeInternal.value = {
998
- type,
999
- dest,
1000
- forceReload,
1001
- replaceState,
1002
- scroll
1003
- };
1004
- if (isBrowser) {
1005
- loadClientData(dest, _getContextElement());
1006
- loadRoute(qwikRouterConfig.routes, qwikRouterConfig.menus, qwikRouterConfig.cacheModules, dest.pathname);
1007
- }
1008
- actionState.value = void 0;
1009
- routeLocation.isNavigating = true;
1010
- return new Promise((resolve) => {
1011
- navResolver.r = resolve;
1012
- });
1013
- });
1014
- useContextProvider(ContentContext, content);
1015
- useContextProvider(ContentInternalContext, contentInternal);
1016
- useContextProvider(DocumentHeadContext, documentHead);
1017
- useContextProvider(RouteLocationContext, routeLocation);
1018
- useContextProvider(RouteNavigateContext, goto);
1019
- useContextProvider(RouteStateContext, loaderState);
1020
- useContextProvider(RouteActionContext, actionState);
1021
- useContextProvider(RouteInternalContext, routeInternal);
1022
- useContextProvider(RoutePreventNavigateContext, registerPreventNav);
1023
- useTask$(({ track }) => {
1024
- async function run() {
1025
- const [navigation, action] = track(() => [
1026
- routeInternal.value,
1027
- actionState.value
1028
- ]);
1029
- const locale = getLocale("");
1030
- const prevUrl = routeLocation.url;
1031
- const navType = action ? "form" : navigation.type;
1032
- const replaceState = navigation.replaceState;
1033
- let trackUrl;
1034
- let clientPageData;
1035
- let loadedRoute = null;
1036
- let elm;
1037
- if (isServer) {
1038
- trackUrl = new URL(navigation.dest, routeLocation.url);
1039
- loadedRoute = env.loadedRoute;
1040
- clientPageData = env.response;
1041
- } else {
1042
- trackUrl = new URL(navigation.dest, location);
1043
- if (trackUrl.pathname.endsWith("/")) {
1044
- if (globalThis.__NO_TRAILING_SLASH__) {
1045
- trackUrl.pathname = trackUrl.pathname.slice(0, -1);
1046
- }
1047
- } else if (!globalThis.__NO_TRAILING_SLASH__) {
1048
- trackUrl.pathname += "/";
1049
- }
1050
- let loadRoutePromise = loadRoute(qwikRouterConfig.routes, qwikRouterConfig.menus, qwikRouterConfig.cacheModules, trackUrl.pathname);
1051
- elm = _getContextElement();
1052
- const pageData = clientPageData = await loadClientData(trackUrl, elm, {
1053
- action,
1054
- clearCache: true
1055
- });
1056
- if (!pageData) {
1057
- routeInternal.untrackedValue = {
1058
- type: navType,
1059
- dest: trackUrl
1060
- };
1061
- return;
1062
- }
1063
- const newHref = pageData.href;
1064
- const newURL = new URL(newHref, trackUrl);
1065
- if (!isSamePath(newURL, trackUrl)) {
1066
- if (!pageData.isRewrite) {
1067
- trackUrl = newURL;
1068
- }
1069
- loadRoutePromise = loadRoute(
1070
- qwikRouterConfig.routes,
1071
- qwikRouterConfig.menus,
1072
- qwikRouterConfig.cacheModules,
1073
- newURL.pathname
1074
- // Load the actual required path.
1075
- );
1076
- }
1077
- try {
1078
- loadedRoute = await loadRoutePromise;
1079
- } catch (e) {
1080
- console.error(e);
1081
- window.location.href = newHref;
1082
- return;
1083
- }
1084
- }
1085
- if (loadedRoute) {
1086
- const [routeName, params, mods, menu] = loadedRoute;
1087
- const contentModules = mods;
1088
- const pageModule = contentModules[contentModules.length - 1];
1089
- if (navigation.dest.search && !!isSamePath(trackUrl, prevUrl)) {
1090
- trackUrl.search = navigation.dest.search;
1091
- }
1092
- if (!isSamePath(trackUrl, prevUrl)) {
1093
- routeLocation.prevUrl = prevUrl;
1094
- }
1095
- routeLocation.url = trackUrl;
1096
- routeLocation.params = {
1097
- ...params
1098
- };
1099
- routeInternal.untrackedValue = {
1100
- type: navType,
1101
- dest: trackUrl
1102
- };
1103
- const resolvedHead = resolveHead(clientPageData, routeLocation, contentModules, locale, serverHead);
1104
- content.headings = pageModule.headings;
1105
- content.menu = menu;
1106
- contentInternal.value = noSerialize(contentModules);
1107
- documentHead.links = resolvedHead.links;
1108
- documentHead.meta = resolvedHead.meta;
1109
- documentHead.styles = resolvedHead.styles;
1110
- documentHead.scripts = resolvedHead.scripts;
1111
- documentHead.title = resolvedHead.title;
1112
- documentHead.frontmatter = resolvedHead.frontmatter;
1113
- if (isBrowser) {
1114
- let scrollState;
1115
- if (navType === "popstate") {
1116
- scrollState = getScrollHistory();
1117
- }
1118
- const scroller = document.getElementById(QWIK_ROUTER_SCROLLER) ?? document.documentElement;
1119
- if (navigation.scroll && (!navigation.forceReload || !isSamePath(trackUrl, prevUrl)) && (navType === "link" || navType === "popstate") || navType === "form" && !isSamePath(trackUrl, prevUrl)) {
1120
- document.__q_scroll_restore__ = () => restoreScroll(navType, trackUrl, prevUrl, scroller, scrollState);
1121
- }
1122
- const loaders = clientPageData?.loaders;
1123
- if (loaders) {
1124
- const container2 = _getContextContainer();
1125
- for (const [key, value] of Object.entries(loaders)) {
1126
- const signal = loaderState[key];
1127
- const awaitedValue = await value;
1128
- loadersObject[key] = awaitedValue;
1129
- if (!signal) {
1130
- loaderState[key] = createLoaderSignal(loadersObject, key, trackUrl, DEFAULT_LOADERS_SERIALIZATION_STRATEGY, container2);
1131
- } else {
1132
- signal.invalidate();
1133
- }
1134
- }
1135
- }
1136
- CLIENT_DATA_CACHE.clear();
1137
- const win = window;
1138
- if (!win._qRouterSPA) {
1139
- win._qRouterSPA = true;
1140
- history.scrollRestoration = "manual";
1141
- win.addEventListener("popstate", () => {
1142
- win._qRouterScrollEnabled = false;
1143
- clearTimeout(win._qRouterScrollDebounce);
1144
- goto(location.href, {
1145
- type: "popstate"
1146
- });
1147
- });
1148
- win.removeEventListener("popstate", win._qRouterInitPopstate);
1149
- win._qRouterInitPopstate = void 0;
1150
- if (!win._qRouterHistoryPatch) {
1151
- win._qRouterHistoryPatch = true;
1152
- const pushState = history.pushState;
1153
- const replaceState2 = history.replaceState;
1154
- const prepareState = (state) => {
1155
- if (state === null || typeof state === "undefined") {
1156
- state = {};
1157
- } else if (state?.constructor !== Object) {
1158
- state = {
1159
- _data: state
1160
- };
1161
- if (isDev) {
1162
- 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`");
1163
- }
1164
- }
1165
- state._qRouterScroll = state._qRouterScroll || currentScrollState(scroller);
1166
- return state;
1167
- };
1168
- history.pushState = (state, title, url2) => {
1169
- state = prepareState(state);
1170
- return pushState.call(history, state, title, url2);
1171
- };
1172
- history.replaceState = (state, title, url2) => {
1173
- state = prepareState(state);
1174
- return replaceState2.call(history, state, title, url2);
1175
- };
1176
- }
1177
- document.body.addEventListener("click", (event) => {
1178
- if (event.defaultPrevented) {
1179
- return;
1180
- }
1181
- const target = event.target.closest("a[href]");
1182
- if (target && !target.hasAttribute("preventdefault:click")) {
1183
- const href = target.getAttribute("href");
1184
- const prev = new URL(location.href);
1185
- const dest = new URL(href, prev);
1186
- if (isSameOrigin(dest, prev) && isSamePath(dest, prev)) {
1187
- event.preventDefault();
1188
- if (!dest.hash && !dest.href.endsWith("#")) {
1189
- if (dest.href !== prev.href) {
1190
- history.pushState(null, "", dest);
1191
- }
1192
- win._qRouterScrollEnabled = false;
1193
- clearTimeout(win._qRouterScrollDebounce);
1194
- saveScrollHistory({
1195
- ...currentScrollState(scroller),
1196
- x: 0,
1197
- y: 0
1198
- });
1199
- location.reload();
1200
- return;
1201
- }
1202
- goto(target.getAttribute("href"));
1203
- }
1204
- }
1205
- });
1206
- document.body.removeEventListener("click", win._qRouterInitAnchors);
1207
- win._qRouterInitAnchors = void 0;
1208
- if (!window.navigation) {
1209
- document.addEventListener("visibilitychange", () => {
1210
- if ((win._qRouterScrollEnabled || win._qCityScrollEnabled) && document.visibilityState === "hidden") {
1211
- if (win._qCityScrollEnabled) {
1212
- console.warn('"_qCityScrollEnabled" is deprecated. Use "_qRouterScrollEnabled" instead.');
1213
- }
1214
- const scrollState2 = currentScrollState(scroller);
1215
- saveScrollHistory(scrollState2);
1216
- }
1217
- }, {
1218
- passive: true
1219
- });
1220
- document.removeEventListener("visibilitychange", win._qRouterInitVisibility);
1221
- win._qRouterInitVisibility = void 0;
1222
- }
1223
- win.addEventListener("scroll", () => {
1224
- if (!win._qRouterScrollEnabled && !win._qCityScrollEnabled) {
1225
- return;
1226
- }
1227
- clearTimeout(win._qRouterScrollDebounce);
1228
- win._qRouterScrollDebounce = setTimeout(() => {
1229
- const scrollState2 = currentScrollState(scroller);
1230
- saveScrollHistory(scrollState2);
1231
- win._qRouterScrollDebounce = void 0;
1232
- }, 200);
1233
- }, {
1234
- passive: true
1235
- });
1236
- removeEventListener("scroll", win._qRouterInitScroll);
1237
- win._qRouterInitScroll = void 0;
1238
- spaInit.resolve();
1239
- }
1240
- if (navType !== "popstate") {
1241
- win._qRouterScrollEnabled = false;
1242
- clearTimeout(win._qRouterScrollDebounce);
1243
- const scrollState2 = currentScrollState(scroller);
1244
- saveScrollHistory(scrollState2);
1245
- }
1246
- const navigate = () => {
1247
- clientNavigate(window, navType, prevUrl, trackUrl, replaceState);
1248
- return _waitUntilRendered(elm);
1249
- };
1250
- const _waitNextPage = () => {
1251
- if (isServer || props?.viewTransition === false) {
1252
- return navigate();
1253
- } else {
1254
- const viewTransition = startViewTransition({
1255
- update: navigate,
1256
- types: [
1257
- "qwik-navigation"
1258
- ]
1259
- });
1260
- if (!viewTransition) {
1261
- return Promise.resolve();
1262
- }
1263
- return viewTransition.ready;
1264
- }
1265
- };
1266
- _waitNextPage().then(() => {
1267
- const container2 = _getQContainerElement(elm);
1268
- container2.setAttribute(Q_ROUTE, routeName);
1269
- const scrollState2 = currentScrollState(scroller);
1270
- saveScrollHistory(scrollState2);
1271
- win._qRouterScrollEnabled = true;
1272
- if (isBrowser) {
1273
- callRestoreScrollOnDocument();
1274
- }
1275
- routeLocation.isNavigating = false;
1276
- navResolver.r?.();
1277
- });
1278
- }
1279
- }
1280
- }
1281
- if (isServer) {
1282
- return run();
1283
- } else {
1284
- run();
1285
- }
1286
- });
1017
+ /** @public This is a wrapper around the `useQwikRouter()` hook. We recommend using the hook instead of this component, unless you have a good reason to make your root component reactive. */
1018
+ function initializeSPA(goto, scroller) {
1019
+ if (!window._qRouterSPA) {
1020
+ window._qRouterSPA = true;
1021
+ history.scrollRestoration = "manual";
1022
+ window.addEventListener("popstate", () => {
1023
+ window._qRouterScrollEnabled = false;
1024
+ clearTimeout(window._qRouterScrollDebounce);
1025
+ goto(location.href, { type: "popstate" });
1026
+ });
1027
+ window.removeEventListener("popstate", window._qRouterInitPopstate);
1028
+ window._qRouterInitPopstate = void 0;
1029
+ if (!window._qRouterHistoryPatch) {
1030
+ window._qRouterHistoryPatch = true;
1031
+ const pushState = history.pushState;
1032
+ const replaceState = history.replaceState;
1033
+ const prepareState = (state) => {
1034
+ if (state === null || typeof state === "undefined") state = {};
1035
+ else if (state?.constructor !== Object) {
1036
+ state = { _data: state };
1037
+ if (isDev) 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`");
1038
+ }
1039
+ state._qRouterScroll = state._qRouterScroll || currentScrollState(scroller);
1040
+ return state;
1041
+ };
1042
+ history.pushState = (state, title, url) => {
1043
+ state = prepareState(state);
1044
+ return pushState.call(history, state, title, url);
1045
+ };
1046
+ history.replaceState = (state, title, url) => {
1047
+ state = prepareState(state);
1048
+ return replaceState.call(history, state, title, url);
1049
+ };
1050
+ }
1051
+ document.addEventListener("click", (event) => {
1052
+ if (event.defaultPrevented) return;
1053
+ const target = event.target.closest("a[href]");
1054
+ if (target && !target.hasAttribute("preventdefault:click")) {
1055
+ const href = target.getAttribute("href");
1056
+ const prev = new URL(location.href);
1057
+ const dest = new URL(href, prev);
1058
+ if (isSameOrigin(dest, prev) && isSamePath(dest, prev)) {
1059
+ event.preventDefault();
1060
+ if (!dest.hash && !dest.href.endsWith("#")) {
1061
+ if (dest.href !== prev.href) history.pushState(null, "", dest);
1062
+ window._qRouterScrollEnabled = false;
1063
+ clearTimeout(window._qRouterScrollDebounce);
1064
+ saveScrollHistory({
1065
+ ...currentScrollState(scroller),
1066
+ x: 0,
1067
+ y: 0
1068
+ });
1069
+ location.reload();
1070
+ return;
1071
+ }
1072
+ goto(target.getAttribute("href"));
1073
+ }
1074
+ }
1075
+ });
1076
+ document.removeEventListener("click", window._qRouterInitAnchors);
1077
+ window._qRouterInitAnchors = void 0;
1078
+ if (!window.navigation) {
1079
+ document.addEventListener("visibilitychange", () => {
1080
+ if (window._qRouterScrollEnabled && document.visibilityState === "hidden") saveScrollHistory(currentScrollState(scroller));
1081
+ }, { passive: true });
1082
+ document.removeEventListener("visibilitychange", window._qRouterInitVisibility);
1083
+ window._qRouterInitVisibility = void 0;
1084
+ }
1085
+ window.addEventListener("scroll", () => {
1086
+ if (!window._qRouterScrollEnabled) return;
1087
+ clearTimeout(window._qRouterScrollDebounce);
1088
+ window._qRouterScrollDebounce = setTimeout(() => {
1089
+ saveScrollHistory(currentScrollState(scroller));
1090
+ window._qRouterScrollDebounce = void 0;
1091
+ }, 200);
1092
+ }, { passive: true });
1093
+ removeEventListener("scroll", window._qRouterInitScroll);
1094
+ window._qRouterInitScroll = void 0;
1095
+ spa_init_default.resolve();
1096
+ }
1097
+ }
1098
+ var QwikRouterMockProvider = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl((props) => {
1099
+ useQwikMockRouter(props);
1100
+ return /*#__PURE__*/ _jsxSorted(Slot, null, null, null, 3, "dU_1");
1101
+ }, "QwikRouterMockProvider_component_IN4dVpT0x74"));
1102
+ var useQwikMockRouter = (props) => {
1103
+ const urlEnv = props.url ?? "http://localhost/";
1104
+ const url = new URL(urlEnv);
1105
+ const routeLocation = useStore({
1106
+ url,
1107
+ params: props.params ?? {},
1108
+ isNavigating: false,
1109
+ prevUrl: void 0
1110
+ }, { deep: false });
1111
+ const loadersData = props.loaders?.reduce((acc, { loader, data }) => {
1112
+ acc[loader.__id] = data;
1113
+ return acc;
1114
+ }, {});
1115
+ const loadersState = useStore({}, { deep: false });
1116
+ for (const [loaderId, data] of Object.entries(loadersData ?? {})) loadersState[loaderId] ||= createComputedQrl(/*#__PURE__*/ inlinedQrl(() => {
1117
+ return _capturesObj._[0];
1118
+ }, "useQwikMockRouter_createComputed_JL6bChMwwyc", [data]));
1119
+ const goto = props.goto ?? /*#__PURE__*/ inlinedQrl(async () => {
1120
+ console.warn("QwikRouterMockProvider: goto not provided");
1121
+ }, "useQwikMockRouter_goto_aViHFxQ1a3s");
1122
+ const documentHead = useStore(createDocumentHead, { deep: false });
1123
+ const content = useStore({
1124
+ headings: void 0,
1125
+ menu: void 0
1126
+ }, { deep: false });
1127
+ const contentInternal = useSignal();
1128
+ const actionState = useSignal();
1129
+ const httpStatus = useSignal({
1130
+ status: 200,
1131
+ message: ""
1132
+ });
1133
+ useContextProvider(ContentContext, content);
1134
+ useContextProvider(ContentInternalContext, contentInternal);
1135
+ useContextProvider(DocumentHeadContext, documentHead);
1136
+ useContextProvider(HttpStatusContext, httpStatus);
1137
+ useContextProvider(RouteLocationContext, routeLocation);
1138
+ useContextProvider(RouteNavigateContext, goto);
1139
+ useContextProvider(RouteStateContext, loadersState);
1140
+ useContextProvider(RouteActionContext, actionState);
1141
+ const actionsMocks = props.actions?.reduce((acc, { action, handler }) => {
1142
+ acc[action.__id] = handler;
1143
+ return acc;
1144
+ }, {});
1145
+ useTaskQrl(/*#__PURE__*/ inlinedQrl(async ({ track }) => {
1146
+ let actionState = _capturesObj._[0], actionsMocks = _capturesObj._[1];
1147
+ const action = track(actionState);
1148
+ action?.resolveDispatch?.();
1149
+ if (action) action.resolveDispatch = void 0;
1150
+ if (!action?.resolve) return;
1151
+ const mock = actionsMocks?.[action.id];
1152
+ if (mock) {
1153
+ const actionResult = await mock(action.data);
1154
+ action.resolve(actionResult);
1155
+ }
1156
+ }, "useQwikMockRouter_useTask_tXTLR4tzCy0", [actionState, actionsMocks]));
1287
1157
  };
1288
- const QwikRouterProvider = component$((props) => {
1289
- useQwikRouter(props);
1290
- return /* @__PURE__ */ jsx(Slot, {});
1291
- });
1292
- const QwikCityProvider = QwikRouterProvider;
1293
- const useQwikMockRouter = (props) => {
1294
- const urlEnv = props.url ?? "http://localhost/";
1295
- const url = new URL(urlEnv);
1296
- const routeLocation = useStore({
1297
- url,
1298
- params: props.params ?? {},
1299
- isNavigating: false,
1300
- prevUrl: void 0
1301
- }, {
1302
- deep: false
1303
- });
1304
- const loaderState = {};
1305
- const routeInternal = useSignal({
1306
- type: "initial",
1307
- dest: url
1308
- });
1309
- const goto = props.goto ?? $(async () => {
1310
- console.warn("QwikRouterMockProvider: goto not provided");
1311
- });
1312
- const documentHead = useStore(createDocumentHead, {
1313
- deep: false
1314
- });
1315
- const content = useStore({
1316
- headings: void 0,
1317
- menu: void 0
1318
- }, {
1319
- deep: false
1320
- });
1321
- const contentInternal = useSignal();
1322
- const actionState = useSignal();
1323
- useContextProvider(ContentContext, content);
1324
- useContextProvider(ContentInternalContext, contentInternal);
1325
- useContextProvider(DocumentHeadContext, documentHead);
1326
- useContextProvider(RouteLocationContext, routeLocation);
1327
- useContextProvider(RouteNavigateContext, goto);
1328
- useContextProvider(RouteStateContext, loaderState);
1329
- useContextProvider(RouteActionContext, actionState);
1330
- useContextProvider(RouteInternalContext, routeInternal);
1158
+ var QwikRouterProvider = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl((props) => {
1159
+ useQwikRouter(props);
1160
+ return /*#__PURE__*/ _jsxSorted(Slot, null, null, null, 3, "dU_0");
1161
+ }, "QwikRouterProvider_component_6Kjfa79mqlY"));
1162
+ /**
1163
+ * @deprecated Use `useQwikRouter()` instead. Will be removed in v3.
1164
+ * @public
1165
+ */
1166
+ var QwikCityProvider = QwikRouterProvider;
1167
+ /** @public */
1168
+ /** @public */
1169
+ /**
1170
+ * @deprecated Use `useQwikMockRouter()` instead. Will be removed in V3
1171
+ * @public
1172
+ */
1173
+ var QwikCityMockProvider = QwikRouterMockProvider;
1174
+ var handleRouterPopstate = (nav, event) => {
1175
+ const href = event.detail?.href;
1176
+ if (href) return nav(href, { type: "popstate" });
1331
1177
  };
1332
- const QwikRouterMockProvider = component$((props) => {
1333
- useQwikMockRouter(props);
1334
- return /* @__PURE__ */ jsx(Slot, {});
1335
- });
1336
- const QwikCityMockProvider = QwikRouterMockProvider;
1337
- const RouterOutlet = component$(() => {
1338
- const serverData = useServerData("containerAttributes");
1339
- if (!serverData) {
1340
- throw new Error("PrefetchServiceWorker component must be rendered on the server.");
1341
- }
1342
- const { value } = useContext(ContentInternalContext);
1343
- if (value && value.length > 0) {
1344
- const contentsLen = value.length;
1345
- let cmp = null;
1346
- for (let i = contentsLen - 1; i >= 0; i--) {
1347
- if (value[i].default) {
1348
- cmp = jsx$1(value[i].default, {
1349
- children: cmp
1350
- });
1351
- }
1352
- }
1353
- return /* @__PURE__ */ jsxs(Fragment, {
1354
- children: [
1355
- cmp,
1356
- !__EXPERIMENTAL__.noSPA && /* @__PURE__ */ jsx("script", {
1357
- "document:onQCInit$": spaInit,
1358
- "document:onQInit$": sync$(() => {
1359
- ((w, h) => {
1360
- if (!w._qcs && h.scrollRestoration === "manual") {
1361
- w._qcs = true;
1362
- const s = h.state?._qRouterScroll;
1363
- if (s) {
1364
- w.scrollTo(s.x, s.y);
1365
- }
1366
- document.dispatchEvent(new Event("qcinit"));
1367
- }
1368
- })(window, history);
1369
- })
1370
- })
1371
- ]
1372
- });
1373
- }
1374
- return SkipRender;
1375
- });
1376
- var store;
1377
- function getGlobalConfig(config2) {
1378
- return {
1379
- lang: config2?.lang ?? store?.lang,
1380
- message: config2?.message,
1381
- abortEarly: config2?.abortEarly ?? store?.abortEarly,
1382
- abortPipeEarly: config2?.abortPipeEarly ?? store?.abortPipeEarly
1383
- };
1384
- }
1385
- function getDotPath(issue) {
1386
- if (issue.path) {
1387
- let key = "";
1388
- for (const item of issue.path) {
1389
- if (typeof item.key === "string" || typeof item.key === "number") {
1390
- if (key) {
1391
- key += `.${item.key}`;
1392
- } else {
1393
- key += item.key;
1394
- }
1395
- } else {
1396
- return null;
1397
- }
1398
- }
1399
- return key;
1400
- }
1401
- return null;
1178
+ /** @public */
1179
+ var RouterOutlet = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl(() => {
1180
+ if (!useServerData("containerAttributes")) throw new Error("PrefetchServiceWorker component must be rendered on the server.");
1181
+ const internalContext = useContext(ContentInternalContext);
1182
+ const nav = useNavigate();
1183
+ const contents = internalContext.value;
1184
+ if (contents && contents.length > 0) {
1185
+ let cmp = null;
1186
+ for (let i = contents.length - 1; i >= 0; i--) if (contents[i].default) cmp = /*#__PURE__*/ _jsxSorted(contents[i].default, null, null, cmp, 1, "yd_0");
1187
+ return /*#__PURE__*/ _jsxSorted(Fragment, null, null, [cmp, !__EXPERIMENTAL__.noSPA && /*#__PURE__*/ _jsxSorted("script", {
1188
+ "q-d:qcinit": [spa_init_default, linkPrefetchInit],
1189
+ "q-d:qinit": _qrlSync(() => {
1190
+ ((w, h) => {
1191
+ if (!w._qcs) {
1192
+ w._qcs = true;
1193
+ const s = h.state?._qRouterScroll;
1194
+ if (s) {
1195
+ h.scrollRestoration = "manual";
1196
+ w.scrollTo(s.x, s.y);
1197
+ }
1198
+ document.dispatchEvent(new Event("qcinit"));
1199
+ }
1200
+ })(window, history);
1201
+ }, "()=>{((w,h)=>{if(!w._qcs){w._qcs=!0;const s=h.state?._qRouterScroll;if(s){h.scrollRestoration=\"manual\";w.scrollTo(s.x,s.y);}document.dispatchEvent(new Event(\"qcinit\"));}})(window,history);}"),
1202
+ "q:p": nav
1203
+ }, { "q-d:qrouterpopstate": /*#__PURE__*/ inlinedQrl((event, _1, nav) => handleRouterPopstate(nav, event), "RouterOutlet_component_Fragment_script_q_d_qrouterpopstate_aRL6GvFyews").m() }, null, 6, "yd_0")], 1, "yd_1");
1204
+ }
1205
+ return SkipRender;
1206
+ }, "RouterOutlet_component_QwONcWD5gIg"));
1207
+ /**
1208
+ * Hoisted function declarations (not consts) on purpose, like `routeLoaderQrl`: the app's route
1209
+ * modules call these factories during their own evaluation, which a bundle may run before this
1210
+ * module, where a `const` binding would throw a TDZ ReferenceError.
1211
+ *
1212
+ * @public
1213
+ */
1214
+ function routeActionQrl(actionQrl, ...rest) {
1215
+ const { id, validators, invalidate } = getValidators(rest, actionQrl);
1216
+ function action() {
1217
+ const loc = useLocation();
1218
+ const currentAction = useAction();
1219
+ const initialState = {
1220
+ actionPath: `?${QACTION_KEY}=${id}`,
1221
+ submitted: false,
1222
+ isRunning: false,
1223
+ status: void 0,
1224
+ value: void 0,
1225
+ formData: void 0
1226
+ };
1227
+ const state = useStore(() => {
1228
+ const value = currentAction.value;
1229
+ if (value && value?.id === id) {
1230
+ const data = value.data;
1231
+ if (data instanceof FormData) initialState.formData = data;
1232
+ if (value.output) {
1233
+ const { status, result } = value.output;
1234
+ initialState.status = status;
1235
+ initialState.value = result;
1236
+ }
1237
+ }
1238
+ return initialState;
1239
+ });
1240
+ initialState.submit = /* @__PURE__ */ inlinedQrl((input = {}) => {
1241
+ let currentAction = _capturesObj._[0], id = _capturesObj._[1], latestSubmission = _capturesObj._[2], loc = _capturesObj._[3], state = _capturesObj._[4];
1242
+ if (isServer) throw new Error(`Actions can not be invoked within the server during SSR.
1243
+ Action.run() can only be called on the browser, for example when a user clicks a button, or submits a form.`);
1244
+ let data;
1245
+ let form;
1246
+ if (input instanceof SubmitEvent) {
1247
+ form = input.target;
1248
+ data = new FormData(form);
1249
+ if ((input.submitter instanceof HTMLInputElement || input.submitter instanceof HTMLButtonElement) && input.submitter.name) {
1250
+ if (input.submitter.name) data.append(input.submitter.name, input.submitter.value);
1251
+ }
1252
+ } else data = input;
1253
+ const submission = {};
1254
+ latestSubmission.current = submission;
1255
+ const previousDispatch = currentAction.pendingDispatch ?? Promise.resolve();
1256
+ let resolveDispatch;
1257
+ currentAction.pendingDispatch = noSerialize(new Promise((resolve) => {
1258
+ resolveDispatch = resolve;
1259
+ }));
1260
+ return previousDispatch.then(() => new Promise((resolve) => {
1261
+ if (data instanceof FormData) state.formData = data;
1262
+ state.submitted = true;
1263
+ state.isRunning = true;
1264
+ loc.isNavigating = true;
1265
+ currentAction.value = {
1266
+ data,
1267
+ id,
1268
+ resolve: noSerialize(resolve),
1269
+ resolveDispatch: noSerialize(resolveDispatch)
1270
+ };
1271
+ })).then(({ result, status }) => {
1272
+ const isLatestSubmission = latestSubmission.current === submission;
1273
+ if (isLatestSubmission) {
1274
+ state.isRunning = false;
1275
+ state.status = status;
1276
+ state.value = result;
1277
+ }
1278
+ if (form) {
1279
+ if (isLatestSubmission && form.getAttribute("data-spa-reset") === "true") form.reset();
1280
+ const detail = {
1281
+ status,
1282
+ value: result
1283
+ };
1284
+ form.dispatchEvent(new CustomEvent("submitcompleted", {
1285
+ bubbles: false,
1286
+ cancelable: false,
1287
+ composed: false,
1288
+ detail
1289
+ }));
1290
+ }
1291
+ return {
1292
+ status,
1293
+ value: result
1294
+ };
1295
+ });
1296
+ }, "routeActionQrl_action_submit_YuS5bpdQ360", [
1297
+ currentAction,
1298
+ id,
1299
+ { current: void 0 },
1300
+ loc,
1301
+ state
1302
+ ]);
1303
+ return state;
1304
+ }
1305
+ action.__brand = "server_action";
1306
+ action.__validators = validators;
1307
+ action.__qrl = actionQrl;
1308
+ action.__id = id;
1309
+ action.__invalidate = invalidate;
1310
+ Object.freeze(action);
1311
+ return action;
1402
1312
  }
1403
- function flatten(issues) {
1404
- const flatErrors = {};
1405
- for (const issue of issues) {
1406
- if (issue.path) {
1407
- const dotPath = getDotPath(issue);
1408
- if (dotPath) {
1409
- if (!flatErrors.nested) {
1410
- flatErrors.nested = {};
1411
- }
1412
- if (flatErrors.nested[dotPath]) {
1413
- flatErrors.nested[dotPath].push(issue.message);
1414
- } else {
1415
- flatErrors.nested[dotPath] = [issue.message];
1416
- }
1417
- } else {
1418
- if (flatErrors.other) {
1419
- flatErrors.other.push(issue.message);
1420
- } else {
1421
- flatErrors.other = [issue.message];
1422
- }
1423
- }
1424
- } else {
1425
- if (flatErrors.root) {
1426
- flatErrors.root.push(issue.message);
1427
- } else {
1428
- flatErrors.root = [issue.message];
1429
- }
1430
- }
1431
- }
1432
- return flatErrors;
1313
+ /** @internal */
1314
+ function globalActionQrl(actionQrl, ...rest) {
1315
+ const action = routeActionQrl(actionQrl, ...rest);
1316
+ if (isServer) {
1317
+ if (typeof globalThis._qwikActionsMap === "undefined") globalThis._qwikActionsMap = /* @__PURE__ */ new Map();
1318
+ globalThis._qwikActionsMap.set(action.__id, action);
1319
+ }
1320
+ return action;
1433
1321
  }
1434
- async function safeParseAsync(schema, input, config2) {
1435
- const dataset = await schema._run(
1436
- { typed: false, value: input },
1437
- getGlobalConfig(config2)
1438
- );
1439
- return {
1440
- typed: dataset.typed,
1441
- success: !dataset.issues,
1442
- output: dataset.value,
1443
- issues: dataset.issues
1444
- };
1322
+ /**
1323
+ * Define a route action that handles form submissions or programmatic invocations.
1324
+ *
1325
+ * Actions run on the server when submitted from the client. The result is returned as an
1326
+ * `ActionStore` with `.value` for success data and `.error` for errors (including validation errors
1327
+ * from `zod$`/`valibot$` where `.fieldErrors` etc. are accessible directly on `.error`).
1328
+ *
1329
+ * By default, after an action completes, ALL current route loaders are invalidated on the client
1330
+ * and re-fetched as needed (so that the browser cache is correct). This can be controlled with:
1331
+ *
1332
+ * - `invalidate: [loader1, loader2]`: Only invalidate specific loaders. The client re-fetches them
1333
+ * individually. Other loaders keep their current data.
1334
+ * - `invalidate: []`: No loaders are invalidated. The action response only contains the action
1335
+ * result. Use this when the action doesn't affect any loader data.
1336
+ *
1337
+ * The `strictLoaders` Vite plugin option applies `invalidate: []` globally for all actions that
1338
+ * don't specify an explicit `invalidate` option.
1339
+ *
1340
+ * @public
1341
+ */
1342
+ var routeAction$ = /*#__PURE__*/ implicit$FirstArg(routeActionQrl);
1343
+ /** @public */
1344
+ var globalAction$ = /*#__PURE__*/ implicit$FirstArg(globalActionQrl);
1345
+ /** @internal */
1346
+ function validatorQrl(validator) {
1347
+ if (isServer) return { validate: validator };
1445
1348
  }
1446
- const routeActionQrl = (actionQrl, ...rest) => {
1447
- const { id, validators } = getValidators(rest, actionQrl);
1448
- function action() {
1449
- const loc = useLocation();
1450
- const currentAction = useAction();
1451
- const initialState = {
1452
- actionPath: `?${QACTION_KEY}=${id}`,
1453
- submitted: false,
1454
- isRunning: false,
1455
- status: void 0,
1456
- value: void 0,
1457
- formData: void 0
1458
- };
1459
- const state = useStore(() => {
1460
- const value = currentAction.value;
1461
- if (value && value?.id === id) {
1462
- const data = value.data;
1463
- if (data instanceof FormData) {
1464
- initialState.formData = data;
1465
- }
1466
- if (value.output) {
1467
- const { status, result } = value.output;
1468
- initialState.status = status;
1469
- initialState.value = result;
1470
- }
1471
- }
1472
- return initialState;
1473
- });
1474
- const submit = $((input = {}) => {
1475
- if (isServer) {
1476
- throw new Error(`Actions can not be invoked within the server during SSR.
1477
- Action.run() can only be called on the browser, for example when a user clicks a button, or submits a form.`);
1478
- }
1479
- let data;
1480
- let form;
1481
- if (input instanceof SubmitEvent) {
1482
- form = input.target;
1483
- data = new FormData(form);
1484
- if ((input.submitter instanceof HTMLInputElement || input.submitter instanceof HTMLButtonElement) && input.submitter.name) {
1485
- if (input.submitter.name) {
1486
- data.append(input.submitter.name, input.submitter.value);
1487
- }
1488
- }
1489
- } else {
1490
- data = input;
1491
- }
1492
- return new Promise((resolve) => {
1493
- if (data instanceof FormData) {
1494
- state.formData = data;
1495
- }
1496
- state.submitted = true;
1497
- state.isRunning = true;
1498
- loc.isNavigating = true;
1499
- currentAction.value = {
1500
- data,
1501
- id,
1502
- resolve: noSerialize(resolve)
1503
- };
1504
- }).then(({ result, status }) => {
1505
- state.isRunning = false;
1506
- state.status = status;
1507
- state.value = result;
1508
- if (form) {
1509
- if (form.getAttribute("data-spa-reset") === "true") {
1510
- form.reset();
1511
- }
1512
- const detail = {
1513
- status,
1514
- value: result
1515
- };
1516
- form.dispatchEvent(new CustomEvent("submitcompleted", {
1517
- bubbles: false,
1518
- cancelable: false,
1519
- composed: false,
1520
- detail
1521
- }));
1522
- }
1523
- return {
1524
- status,
1525
- value: result
1526
- };
1527
- });
1528
- });
1529
- initialState.submit = submit;
1530
- return state;
1531
- }
1532
- action.__brand = "server_action";
1533
- action.__validators = validators;
1534
- action.__qrl = actionQrl;
1535
- action.__id = id;
1536
- Object.freeze(action);
1537
- return action;
1538
- };
1539
- const globalActionQrl = (actionQrl, ...rest) => {
1540
- const action = routeActionQrl(actionQrl, ...rest);
1541
- if (isServer) {
1542
- if (typeof globalThis._qwikActionsMap === "undefined") {
1543
- globalThis._qwikActionsMap = /* @__PURE__ */ new Map();
1544
- }
1545
- globalThis._qwikActionsMap.set(action.__id, action);
1546
- }
1547
- return action;
1548
- };
1549
- const routeAction$ = /* @__PURE__ */ implicit$FirstArg(routeActionQrl);
1550
- const globalAction$ = /* @__PURE__ */ implicit$FirstArg(globalActionQrl);
1551
- const routeLoaderQrl = (loaderQrl, ...rest) => {
1552
- const { id, validators, serializationStrategy } = getValidators(rest, loaderQrl);
1553
- function loader() {
1554
- const state = _resolveContextWithoutSequentialScope(RouteStateContext);
1555
- if (!(id in state)) {
1556
- throw new Error(`routeLoader$ "${loaderQrl.getSymbol()}" was invoked in a route where it was not declared.
1557
- This is because the routeLoader$ was not exported in a 'layout.tsx' or 'index.tsx' file of the existing route.
1558
- For more information check: https://qwik.dev/docs/route-loader/
1559
-
1560
- 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.
1561
- For more information check: https://qwik.dev/docs/re-exporting-loaders/`);
1562
- }
1563
- untrack(() => state[id].value);
1564
- return state[id];
1565
- }
1566
- loader.__brand = "server_loader";
1567
- loader.__qrl = loaderQrl;
1568
- loader.__validators = validators;
1569
- loader.__id = id;
1570
- loader.__serializationStrategy = serializationStrategy;
1571
- Object.freeze(loader);
1572
- return loader;
1573
- };
1574
- const routeLoader$ = /* @__PURE__ */ implicit$FirstArg(routeLoaderQrl);
1575
- const validatorQrl = (validator) => {
1576
- if (isServer) {
1577
- return {
1578
- validate: validator
1579
- };
1580
- }
1581
- return void 0;
1582
- };
1583
- const validator$ = /* @__PURE__ */ implicit$FirstArg(validatorQrl);
1584
- const flattenValibotIssues = (issues) => {
1585
- return issues.reduce((acc, issue) => {
1586
- if (issue.path) {
1587
- const hasArrayType = issue.path.some((path) => path.type === "array");
1588
- if (hasArrayType) {
1589
- const keySuffix = issue.expected === "Array" ? "[]" : "";
1590
- const key = issue.path.map((item) => item.type === "array" ? "*" : item.key).join(".").replace(/\.\*/g, "[]") + keySuffix;
1591
- acc[key] = acc[key] || [];
1592
- if (Array.isArray(acc[key])) {
1593
- acc[key].push(issue.message);
1594
- }
1595
- return acc;
1596
- } else {
1597
- acc[issue.path.map((item) => item.key).join(".")] = issue.message;
1598
- }
1599
- }
1600
- return acc;
1601
- }, {});
1349
+ /** @public */
1350
+ var validator$ = /*#__PURE__*/ implicit$FirstArg(validatorQrl);
1351
+ var flattenValibotIssues = (issues) => {
1352
+ return issues.reduce((acc, issue) => {
1353
+ if (issue.path) {
1354
+ if (issue.path.some((path) => path.type === "array")) {
1355
+ const keySuffix = issue.expected === "Array" ? "[]" : "";
1356
+ const key = issue.path.map((item) => item.type === "array" ? "*" : item.key).join(".").replace(/\.\*/g, "[]") + keySuffix;
1357
+ acc[key] = acc[key] || [];
1358
+ if (Array.isArray(acc[key])) acc[key].push(issue.message);
1359
+ return acc;
1360
+ } else acc[issue.path.map((item) => item.key).join(".")] = issue.message;
1361
+ }
1362
+ return acc;
1363
+ }, {});
1602
1364
  };
1603
- const valibotQrl = (qrl) => {
1604
- if (!__EXPERIMENTAL__.valibot) {
1605
- 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.');
1606
- }
1607
- if (isServer) {
1608
- return {
1609
- __brand: "valibot",
1610
- async validate(ev, inputData) {
1611
- const schema = await qrl.resolve().then((obj) => typeof obj === "function" ? obj(ev) : obj);
1612
- const data = inputData ?? await ev.parseBody();
1613
- const result = await safeParseAsync(schema, data);
1614
- if (result.success) {
1615
- return {
1616
- success: true,
1617
- data: result.output
1618
- };
1619
- } else {
1620
- if (isDev) {
1621
- console.error("ERROR: Valibot validation failed", result.issues);
1622
- }
1623
- return {
1624
- success: false,
1625
- status: 400,
1626
- error: {
1627
- formErrors: flatten(result.issues).root ?? [],
1628
- fieldErrors: flattenValibotIssues(result.issues)
1629
- }
1630
- };
1631
- }
1632
- }
1633
- };
1634
- }
1635
- return void 0;
1636
- };
1637
- const valibot$ = /* @__PURE__ */ implicit$FirstArg(valibotQrl);
1638
- const flattenZodIssues = (issues) => {
1639
- issues = Array.isArray(issues) ? issues : [
1640
- issues
1641
- ];
1642
- return issues.reduce((acc, issue) => {
1643
- const isExpectingArray = "expected" in issue && issue.expected === "array";
1644
- const hasArrayType = issue.path.some((path) => typeof path === "number") || isExpectingArray;
1645
- if (hasArrayType) {
1646
- const keySuffix = "expected" in issue && issue.expected === "array" ? "[]" : "";
1647
- const key = issue.path.map((path) => typeof path === "number" ? "*" : path).join(".").replace(/\.\*/g, "[]") + keySuffix;
1648
- acc[key] = acc[key] || [];
1649
- if (Array.isArray(acc[key])) {
1650
- acc[key].push(issue.message);
1651
- }
1652
- return acc;
1653
- } else {
1654
- acc[issue.path.join(".")] = issue.message;
1655
- }
1656
- return acc;
1657
- }, {});
1658
- };
1659
- const zodQrl = (qrl) => {
1660
- if (isServer) {
1661
- return {
1662
- __brand: "zod",
1663
- async validate(ev, inputData) {
1664
- const schema = await qrl.resolve().then((obj) => {
1665
- if (typeof obj === "function") {
1666
- obj = obj(z, ev);
1667
- }
1668
- if (obj instanceof z.Schema) {
1669
- return obj;
1670
- } else {
1671
- return z.object(obj);
1672
- }
1673
- });
1674
- const data = inputData ?? await ev.parseBody();
1675
- const result = await withLocale(ev.locale(), () => schema.safeParseAsync(data));
1676
- if (result.success) {
1677
- return result;
1678
- } else {
1679
- if (isDev) {
1680
- console.error("ERROR: Zod validation failed", result.error.issues);
1681
- }
1682
- return {
1683
- success: false,
1684
- status: 400,
1685
- error: {
1686
- formErrors: result.error.flatten().formErrors,
1687
- fieldErrors: flattenZodIssues(result.error.issues)
1688
- }
1689
- };
1690
- }
1691
- }
1692
- };
1693
- }
1694
- return void 0;
1695
- };
1696
- const zod$ = /* @__PURE__ */ implicit$FirstArg(zodQrl);
1697
- const serverQrl = (qrl, options) => {
1698
- if (isServer) {
1699
- const captured = qrl.getCaptured();
1700
- if (captured && captured.length > 0 && !_getContextElement()) {
1701
- throw new Error("For security reasons, we cannot serialize QRLs that capture lexical scope.");
1702
- }
1703
- }
1704
- const method = options?.method?.toUpperCase?.() || "POST";
1705
- const headers = options?.headers || {};
1706
- const origin = options?.origin || "";
1707
- const fetchOptions = options?.fetchOptions || {};
1708
- function rpc() {
1709
- return $(async function(...args) {
1710
- const abortSignal = args.length > 0 && args[0] instanceof AbortSignal ? args.shift() : void 0;
1711
- if (isServer) {
1712
- let requestEvent = globalThis.qcAsyncRequestStore?.getStore();
1713
- if (!requestEvent) {
1714
- const contexts = [
1715
- useQwikRouterEnv()?.ev,
1716
- this,
1717
- _getContextEvent()
1718
- ];
1719
- requestEvent = contexts.find((v2) => v2 && Object.prototype.hasOwnProperty.call(v2, "sharedMap") && Object.prototype.hasOwnProperty.call(v2, "cookie"));
1720
- }
1721
- return qrl.apply(requestEvent, isDev ? deepFreeze(args) : args);
1722
- } else {
1723
- const ctxElm = _getContextElement();
1724
- const filteredArgs = args.map((arg) => {
1725
- if (arg instanceof SubmitEvent && arg.target instanceof HTMLFormElement) {
1726
- return new FormData(arg.target);
1727
- } else if (arg instanceof Event) {
1728
- return null;
1729
- } else if (arg instanceof Node) {
1730
- return null;
1731
- }
1732
- return arg;
1733
- });
1734
- const qrlHash = qrl.getHash();
1735
- let query = "";
1736
- const config = {
1737
- ...fetchOptions,
1738
- method,
1739
- headers: {
1740
- ...headers,
1741
- "Content-Type": "application/qwik-json",
1742
- Accept: "application/json, application/qwik-json, text/qwik-json-stream, text/plain",
1743
- // Required so we don't call accidentally
1744
- "X-QRL": qrlHash
1745
- },
1746
- signal: abortSignal
1747
- };
1748
- const body = await _serialize([
1749
- qrl,
1750
- ...filteredArgs
1751
- ]);
1752
- if (method === "GET") {
1753
- query += `&${QDATA_KEY}=${encodeURIComponent(body)}`;
1754
- } else {
1755
- config.body = body;
1756
- }
1757
- const res = await fetch(`${origin}?${QFN_KEY}=${qrlHash}${query}`, config);
1758
- const contentType = res.headers.get("Content-Type");
1759
- if (res.ok && contentType === "text/qwik-json-stream" && res.body) {
1760
- return async function* () {
1761
- try {
1762
- for await (const result of deserializeStream(res.body, ctxElm ?? document.documentElement, abortSignal)) {
1763
- yield result;
1764
- }
1765
- } finally {
1766
- if (!abortSignal?.aborted) {
1767
- await res.body.cancel();
1768
- }
1769
- }
1770
- }();
1771
- } else if (contentType === "application/qwik-json") {
1772
- const str = await res.text();
1773
- const [obj] = _deserialize(str, ctxElm ?? document.documentElement);
1774
- if (res.status >= 400) {
1775
- throw obj;
1776
- }
1777
- return obj;
1778
- } else if (contentType === "application/json") {
1779
- const obj = await res.json();
1780
- if (res.status >= 400) {
1781
- throw obj;
1782
- }
1783
- return obj;
1784
- } else if (contentType === "text/plain" || contentType === "text/html") {
1785
- const str = await res.text();
1786
- if (res.status >= 400) {
1787
- throw str;
1788
- }
1789
- return str;
1790
- }
1791
- }
1792
- });
1793
- }
1794
- return rpc();
1795
- };
1796
- const server$ = /* @__PURE__ */ implicit$FirstArg(serverQrl);
1797
- const getValidators = (rest, qrl) => {
1798
- let id;
1799
- let serializationStrategy = DEFAULT_LOADERS_SERIALIZATION_STRATEGY;
1800
- const validators = [];
1801
- if (rest.length === 1) {
1802
- const options = rest[0];
1803
- if (options && typeof options === "object") {
1804
- if ("validate" in options) {
1805
- validators.push(options);
1806
- } else {
1807
- id = options.id;
1808
- if (options.serializationStrategy) {
1809
- serializationStrategy = options.serializationStrategy;
1810
- }
1811
- if (options.validation) {
1812
- validators.push(...options.validation);
1813
- }
1814
- }
1815
- }
1816
- } else if (rest.length > 1) {
1817
- validators.push(...rest.filter((v2) => !!v2));
1818
- }
1819
- if (typeof id === "string") {
1820
- if (isDev) {
1821
- if (!/^[\w/.-]+$/.test(id)) {
1822
- throw new Error(`Invalid id: ${id}, id can only contain [a-zA-Z0-9_.-]`);
1823
- }
1824
- }
1825
- id = `id_${id}`;
1826
- } else {
1827
- id = qrl.getHash();
1828
- }
1829
- return {
1830
- validators: validators.reverse(),
1831
- id,
1832
- serializationStrategy
1833
- };
1365
+ /** @internal */
1366
+ function valibotQrl(qrl) {
1367
+ if (!__EXPERIMENTAL__.valibot) 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.");
1368
+ if (isServer) return {
1369
+ __brand: "valibot",
1370
+ async validate(ev, inputData) {
1371
+ const schema = await qrl.resolve().then((obj) => typeof obj === "function" ? obj(ev) : obj);
1372
+ const data = inputData ?? await ev.parseBody();
1373
+ const result = await v.safeParseAsync(schema, data);
1374
+ if (result.success) return {
1375
+ success: true,
1376
+ data: result.output
1377
+ };
1378
+ else {
1379
+ if (isDev) console.error("ERROR: Valibot validation failed", result.issues);
1380
+ return {
1381
+ success: false,
1382
+ status: 400,
1383
+ error: {
1384
+ formErrors: v.flatten(result.issues).root ?? [],
1385
+ fieldErrors: flattenValibotIssues(result.issues)
1386
+ }
1387
+ };
1388
+ }
1389
+ }
1390
+ };
1391
+ }
1392
+ /** @beta */
1393
+ var valibot$ = /*#__PURE__*/ implicit$FirstArg(valibotQrl);
1394
+ var flattenZodIssues = (issues) => {
1395
+ issues = Array.isArray(issues) ? issues : [issues];
1396
+ return issues.reduce((acc, issue) => {
1397
+ const isExpectingArray = "expected" in issue && issue.expected === "array";
1398
+ if (issue.path.some((path) => typeof path === "number") || isExpectingArray) {
1399
+ const keySuffix = "expected" in issue && issue.expected === "array" ? "[]" : "";
1400
+ const key = issue.path.map((path) => typeof path === "number" ? "*" : path).join(".").replace(/\.\*/g, "[]") + keySuffix;
1401
+ acc[key] = acc[key] || [];
1402
+ if (Array.isArray(acc[key])) acc[key].push(issue.message);
1403
+ return acc;
1404
+ } else acc[issue.path.join(".")] = issue.message;
1405
+ return acc;
1406
+ }, {});
1834
1407
  };
1835
- const deserializeStream = async function* (stream, ctxElm, abortSignal) {
1836
- const reader = stream.getReader();
1837
- try {
1838
- let buffer = "";
1839
- const decoder = new TextDecoder();
1840
- while (!abortSignal?.aborted) {
1841
- const result = await reader.read();
1842
- if (result.done) {
1843
- break;
1844
- }
1845
- buffer += decoder.decode(result.value, {
1846
- stream: true
1847
- });
1848
- const lines = buffer.split(/\n/);
1849
- buffer = lines.pop();
1850
- for (const line of lines) {
1851
- const [deserializedData] = _deserialize(line, ctxElm);
1852
- yield deserializedData;
1853
- }
1854
- }
1855
- } finally {
1856
- reader.releaseLock();
1857
- }
1408
+ /** @internal */
1409
+ function zodQrl(qrl) {
1410
+ if (isServer) return {
1411
+ __brand: "zod",
1412
+ async validate(ev, inputData) {
1413
+ const schema = await qrl.resolve().then((obj) => {
1414
+ if (typeof obj === "function") obj = obj(z$1, ev);
1415
+ if (obj instanceof z$1.ZodType) return obj;
1416
+ else return z$1.object(obj);
1417
+ });
1418
+ const data = inputData ?? await ev.parseBody();
1419
+ const result = await withLocale(ev.locale(), () => schema.safeParseAsync(data));
1420
+ if (result.success) return result;
1421
+ else {
1422
+ if (isDev) console.error("ERROR: Zod validation failed", result.error.issues);
1423
+ return {
1424
+ success: false,
1425
+ status: 400,
1426
+ error: {
1427
+ formErrors: result.error.flatten().formErrors,
1428
+ fieldErrors: flattenZodIssues(result.error.issues)
1429
+ }
1430
+ };
1431
+ }
1432
+ }
1433
+ };
1434
+ }
1435
+ /** @public */
1436
+ var zod$ = /*#__PURE__*/ implicit$FirstArg(zodQrl);
1437
+ /** @internal */
1438
+ function serverQrl(qrl, options) {
1439
+ if (isServer) {
1440
+ _regInlinedQrl(qrl);
1441
+ const captured = qrl.getCaptured();
1442
+ if (captured && captured.length > 0 && !_getContextHostElement()) throw new Error("For security reasons, we cannot serialize QRLs that capture lexical scope.");
1443
+ }
1444
+ const method = options?.method?.toUpperCase?.() || "POST";
1445
+ const headers = options?.headers || {};
1446
+ const origin = options?.origin || "";
1447
+ const fetchOptions = options?.fetchOptions || {};
1448
+ return /*#__PURE__*/ inlinedQrl(async function(...args) {
1449
+ let fetchOptions = _capturesObj._[0], headers = _capturesObj._[1], method = _capturesObj._[2], origin = _capturesObj._[3], qrl = _capturesObj._[4];
1450
+ const abortSignal = args.length > 0 && args[0] instanceof AbortSignal ? args.shift() : void 0;
1451
+ if (isServer) return qrl.apply(getRequestEvent(this), args);
1452
+ else {
1453
+ let filteredArgs = args.map((arg) => {
1454
+ if (arg instanceof SubmitEvent && arg.target instanceof HTMLFormElement) return new FormData(arg.target);
1455
+ else if (arg instanceof Event) return null;
1456
+ else if (arg instanceof Node) return null;
1457
+ return arg;
1458
+ });
1459
+ if (!filteredArgs.length) filteredArgs = void 0;
1460
+ const qrlHash = qrl.getHash();
1461
+ let query = "";
1462
+ const config = {
1463
+ ...fetchOptions,
1464
+ method,
1465
+ headers: {
1466
+ ...headers,
1467
+ "Content-Type": "application/qwik-json",
1468
+ Accept: "application/json, application/qwik-json, text/qwik-json-stream, text/plain",
1469
+ "X-QRL": qrlHash
1470
+ },
1471
+ signal: abortSignal
1472
+ };
1473
+ const captured = qrl.getCaptured();
1474
+ let toSend = [filteredArgs];
1475
+ if (captured?.length) toSend = [filteredArgs, ...captured];
1476
+ else toSend = filteredArgs ? [filteredArgs] : [];
1477
+ const body = await _serialize(toSend);
1478
+ if (method === "GET") query += `&${QDATA_KEY}=${encodeURIComponent(body)}`;
1479
+ else config.body = body;
1480
+ const res = await fetch(`${origin}?${QFN_KEY}=${qrlHash}${query}`, config);
1481
+ const contentType = res.headers.get("Content-Type");
1482
+ if (res.ok && contentType === "text/qwik-json-stream" && res.body) return (async function* () {
1483
+ try {
1484
+ for await (const result of deserializeStream(res.body, abortSignal)) yield result;
1485
+ } finally {
1486
+ if (!abortSignal?.aborted) await res.body.cancel();
1487
+ }
1488
+ })();
1489
+ else if (contentType === "application/qwik-json") {
1490
+ const str = await res.text();
1491
+ const obj = await _deserialize(str);
1492
+ if (res.status >= 400) throw obj;
1493
+ return obj;
1494
+ } else if (contentType === "application/json") {
1495
+ const obj = await res.json();
1496
+ if (res.status >= 400) throw obj;
1497
+ return obj;
1498
+ } else if (contentType === "text/plain" || contentType === "text/html") {
1499
+ const str = await res.text();
1500
+ if (res.status >= 400) throw str;
1501
+ return str;
1502
+ }
1503
+ }
1504
+ }, "serverQrl_w03grD0Ag68", [
1505
+ fetchOptions,
1506
+ headers,
1507
+ method,
1508
+ origin,
1509
+ qrl
1510
+ ]);
1511
+ }
1512
+ /** @public */
1513
+ var server$ = /*#__PURE__*/ implicit$FirstArg(serverQrl);
1514
+ function getValidators(rest, qrl) {
1515
+ let id;
1516
+ let invalidate;
1517
+ const validators = [];
1518
+ if (rest.length === 1) {
1519
+ const options = rest[0];
1520
+ if (options && typeof options === "object") {
1521
+ if ("validate" in options) validators.push(options);
1522
+ else {
1523
+ id = options.id;
1524
+ if (options.validation) validators.push(...options.validation);
1525
+ if (options.invalidate) invalidate = options.invalidate.map((loader) => loader.__id);
1526
+ }
1527
+ }
1528
+ } else if (rest.length > 1) validators.push(...rest.filter((v) => !!v));
1529
+ if (typeof id === "string") {
1530
+ if (isDev) {
1531
+ if (!/^[\w/.-]+$/.test(id)) throw new Error(`Invalid id: ${id}, id can only contain [a-zA-Z0-9_.-]`);
1532
+ }
1533
+ id = `id_${id}`;
1534
+ } else id = qrl.getHash();
1535
+ return {
1536
+ validators: validators.reverse(),
1537
+ id,
1538
+ invalidate
1539
+ };
1540
+ }
1541
+ var deserializeStream = async function* (stream, abortSignal) {
1542
+ const reader = stream.getReader();
1543
+ try {
1544
+ let buffer = "";
1545
+ const decoder = new TextDecoder();
1546
+ while (!abortSignal?.aborted) {
1547
+ const result = await reader.read();
1548
+ if (result.done) break;
1549
+ buffer += decoder.decode(result.value, { stream: true });
1550
+ const lines = buffer.split(/\n/);
1551
+ buffer = lines.pop();
1552
+ for (const line of lines) yield await _deserialize(line);
1553
+ }
1554
+ } finally {
1555
+ reader.releaseLock();
1556
+ }
1858
1557
  };
1859
- const ServiceWorkerRegister = (props) => /* @__PURE__ */ jsx("script", {
1860
- type: "module",
1861
- dangerouslySetInnerHTML: swRegister,
1862
- nonce: props.nonce
1863
- });
1864
- const Form = ({ action, spaReset, reloadDocument, onSubmit$, ...rest }, key) => {
1865
- if (action) {
1866
- const isArrayApi = Array.isArray(onSubmit$);
1867
- if (isArrayApi) {
1868
- return jsx$1("form", {
1869
- ...rest,
1870
- action: action.actionPath,
1871
- "preventdefault:submit": !reloadDocument,
1872
- onSubmit$: [
1873
- ...onSubmit$,
1874
- // action.submit "submitcompleted" event for onSubmitCompleted$ events
1875
- !reloadDocument ? $((evt) => {
1876
- if (!action.submitted) {
1877
- return action.submit(evt);
1878
- }
1879
- }) : void 0
1880
- ],
1881
- method: "post",
1882
- ["data-spa-reset"]: spaReset ? "true" : void 0
1883
- }, key);
1884
- }
1885
- return jsx$1("form", {
1886
- ...rest,
1887
- action: action.actionPath,
1888
- "preventdefault:submit": !reloadDocument,
1889
- onSubmit$: [
1890
- // Since v2, this fires before the action is executed so it can be prevented
1891
- onSubmit$,
1892
- // action.submit "submitcompleted" event for onSubmitCompleted$ events
1893
- !reloadDocument ? action.submit : void 0
1894
- ],
1895
- method: "post",
1896
- ["data-spa-reset"]: spaReset ? "true" : void 0
1897
- }, key);
1898
- } else {
1899
- return /* @__PURE__ */ jsx(GetForm, {
1900
- spaReset,
1901
- reloadDocument,
1902
- onSubmit$,
1903
- ...rest
1904
- }, key);
1905
- }
1558
+ var SW_REGISTER = `(()=>{if("serviceWorker"in navigator){navigator.serviceWorker.register("__url").catch(e=>console.error(e));"caches"in window&&caches.keys().then(r=>{const e=r.find(c=>c.startsWith("QwikBuild"));e&&caches.delete(e).catch(console.error)}).catch(console.error)}else console.log("Service worker not supported in this browser.")})()`;
1559
+ var SW_UNREGISTER = `"serviceWorker"in navigator&&navigator.serviceWorker.getRegistrations().then(r=>{for(const e of r){const c="__url".split("/").pop();e.active?.scriptURL.endsWith(c||"service-worker.js")&&e.unregister().catch(console.error)}}),"caches"in window&&caches.keys().then(r=>{const e=r.find(c=>c.startsWith("QwikBuild"));e&&caches.delete(e).catch(console.error)}).catch(console.error)`;
1560
+ /** @internal */
1561
+ var _getServiceWorkerScript = (serviceWorkerUrl) => (serviceWorkerUrl ? SW_REGISTER : SW_UNREGISTER).replace("__url", serviceWorkerUrl ?? "/service-worker.js");
1562
+ /**
1563
+ * Loads the service workers that are defined in the routes. Any file named `service-worker.*` (all
1564
+ * JS extensions are allowed) will be picked up, bundled into a separate file, and registered as a
1565
+ * service worker.
1566
+ *
1567
+ * Qwik 1.14.0 and above now use `<link rel="modulepreload">` by default. If you didn't add custom
1568
+ * service-worker logic, you should remove your service-worker.ts file(s) for the
1569
+ * `ServiceWorkerRegister` Component to actually unregister the service-worker.js and delete its
1570
+ * related cache. Make sure to keep the `ServiceWorkerRegister` Component in your app (without any
1571
+ * service-worker.ts file) as long as you want to unregister the service-worker.js for your users.
1572
+ *
1573
+ * @public
1574
+ */
1575
+ var ServiceWorkerRegister = (props) => /*#__PURE__*/ _jsxSorted("script", {
1576
+ dangerouslySetInnerHTML: _getServiceWorkerScript(_getServiceWorkerUrl()),
1577
+ nonce: _wrapProp(props, "nonce")
1578
+ }, { type: "module" }, null, 3, "UM_0");
1579
+ var _hf0 = (p0) => p0.spaReset ? "true" : void 0;
1580
+ var _hf0_str = "p0.spaReset?\"true\":undefined";
1581
+ /** @public */
1582
+ var Form = ({ action, spaReset, reloadDocument, onSubmit$, ...rest }, key) => {
1583
+ if (action) {
1584
+ if (Array.isArray(onSubmit$)) return /*#__PURE__*/ _jsxSplit("form", {
1585
+ ..._getVarProps(rest),
1586
+ ..._getConstProps(rest),
1587
+ action: _wrapProp(action, "actionPath"),
1588
+ "preventdefault:submit": !reloadDocument,
1589
+ "q-e:submit": [...onSubmit$, !reloadDocument ? /*#__PURE__*/ inlinedQrl((evt) => {
1590
+ let action = _capturesObj._[0];
1591
+ if (!action.submitted) return action.submit(evt);
1592
+ }, "Form_form_q_e_submit_6i0Jq5q8JFg", [action]) : void 0],
1593
+ ["data-spa-reset"]: spaReset ? "true" : void 0
1594
+ }, { method: "post" }, null, 0, key);
1595
+ return /*#__PURE__*/ _jsxSplit("form", {
1596
+ ..._getVarProps(rest),
1597
+ ..._getConstProps(rest),
1598
+ action: _wrapProp(action, "actionPath"),
1599
+ "preventdefault:submit": !reloadDocument,
1600
+ "q-e:submit": [onSubmit$, !reloadDocument ? action.submit : void 0],
1601
+ ["data-spa-reset"]: spaReset ? "true" : void 0
1602
+ }, { method: "post" }, null, 0, key);
1603
+ } else return /*#__PURE__*/ createElement(GetForm, {
1604
+ ...rest,
1605
+ spaReset,
1606
+ reloadDocument,
1607
+ onSubmit$,
1608
+ key
1609
+ });
1906
1610
  };
1907
- const GetForm = component$(({ action: _0, spaReset, reloadDocument, onSubmit$, ...rest }) => {
1908
- const nav = useNavigate();
1909
- return /* @__PURE__ */ jsx("form", {
1910
- action: "get",
1911
- "preventdefault:submit": !reloadDocument,
1912
- "data-spa-reset": spaReset ? "true" : void 0,
1913
- ...rest,
1914
- onSubmit$: [
1915
- ...Array.isArray(onSubmit$) ? onSubmit$ : [
1916
- onSubmit$
1917
- ],
1918
- $(async (_evt, form) => {
1919
- const formData = new FormData(form);
1920
- const params = new URLSearchParams();
1921
- formData.forEach((value, key) => {
1922
- if (typeof value === "string") {
1923
- params.append(key, value);
1924
- }
1925
- });
1926
- await nav("?" + params.toString(), {
1927
- type: "form",
1928
- forceReload: true
1929
- });
1930
- }),
1931
- $((_evt, form) => {
1932
- if (form.getAttribute("data-spa-reset") === "true") {
1933
- form.reset();
1934
- }
1935
- form.dispatchEvent(new CustomEvent("submitcompleted", {
1936
- bubbles: false,
1937
- cancelable: false,
1938
- composed: false,
1939
- detail: {
1940
- status: 200
1941
- }
1942
- }));
1943
- })
1944
- ],
1945
- children: /* @__PURE__ */ jsx(Slot, {})
1946
- });
1947
- });
1948
- const untypedAppUrl = function appUrl(route, params, paramsPrefix = "") {
1949
- const path = route.split("/");
1950
- for (let i = 0; i < path.length; i++) {
1951
- const segment = path[i];
1952
- if (segment.startsWith("[") && segment.endsWith("]")) {
1953
- const isSpread = segment.startsWith("[...");
1954
- const key = segment.substring(segment.startsWith("[...") ? 4 : 1, segment.length - 1);
1955
- const value = params ? params[paramsPrefix + key] || params[key] : "";
1956
- path[i] = isSpread ? value : encodeURIComponent(value);
1957
- }
1958
- if (segment.startsWith("(") && segment.endsWith(")")) {
1959
- path.splice(i, 1);
1960
- }
1961
- }
1962
- let url = path.join("/");
1963
- let baseURL = "/";
1964
- if (baseURL) {
1965
- if (!baseURL.endsWith("/")) {
1966
- baseURL += "/";
1967
- }
1968
- while (url.startsWith("/")) {
1969
- url = url.substring(1);
1970
- }
1971
- url = baseURL + url;
1972
- }
1973
- return url;
1611
+ var GetForm = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl((_rawProps) => {
1612
+ const rest = _restProps(_rawProps, [
1613
+ "action",
1614
+ "spaReset",
1615
+ "reloadDocument",
1616
+ "onSubmit$"
1617
+ ]);
1618
+ const nav = useNavigate();
1619
+ return /*#__PURE__*/ _jsxSplit("form", {
1620
+ action: "get",
1621
+ "data-spa-reset": _fnSignal(_hf0, [_rawProps], _hf0_str),
1622
+ ..._getVarProps(rest),
1623
+ "q-e:submit": [
1624
+ ...Array.isArray(_rawProps.onSubmit$) ? _rawProps.onSubmit$ : [_rawProps.onSubmit$],
1625
+ /*#__PURE__*/ inlinedQrl(async (_evt, form) => {
1626
+ let nav = _capturesObj._[0];
1627
+ const formData = new FormData(form);
1628
+ const params = new URLSearchParams();
1629
+ formData.forEach((value, key) => {
1630
+ if (typeof value === "string") params.append(key, value);
1631
+ });
1632
+ await nav("?" + params.toString(), {
1633
+ type: "form",
1634
+ forceReload: true
1635
+ });
1636
+ }, "GetForm_component_form_q_e_submit_r3dkP9d2cF8", [nav]),
1637
+ /*#__PURE__*/ inlinedQrl((_evt, form) => {
1638
+ if (form.getAttribute("data-spa-reset") === "true") form.reset();
1639
+ form.dispatchEvent(new CustomEvent("submitcompleted", {
1640
+ bubbles: false,
1641
+ cancelable: false,
1642
+ composed: false,
1643
+ detail: { status: 200 }
1644
+ }));
1645
+ }, "GetForm_component_form_q_e_submit_1_cuYklZAOHrA")
1646
+ ]
1647
+ }, {
1648
+ ..._getConstProps(rest),
1649
+ "preventdefault:submit": true
1650
+ }, /*#__PURE__*/ _jsxSorted(Slot, null, null, null, 3, "TF_0"), 0, "TF_1");
1651
+ }, "GetForm_component_2U5Z2Z8ryc0"));
1652
+ /**
1653
+ * @beta
1654
+ * @experimental
1655
+ */
1656
+ var untypedAppUrl = function appUrl(route, params, paramsPrefix = "") {
1657
+ const path = route.split("/");
1658
+ for (let i = 0; i < path.length; i++) {
1659
+ const segment = path[i];
1660
+ if (segment.startsWith("[") && segment.endsWith("]")) {
1661
+ const isSpread = segment.startsWith("[...");
1662
+ const key = segment.substring(segment.startsWith("[...") ? 4 : 1, segment.length - 1);
1663
+ const value = params ? params[paramsPrefix + key] || params[key] : "";
1664
+ path[i] = isSpread ? value : encodeURIComponent(value);
1665
+ }
1666
+ if (segment.startsWith("(") && segment.endsWith(")")) path.splice(i, 1);
1667
+ }
1668
+ let url = path.join("/");
1669
+ let baseURL = "/";
1670
+ if (baseURL) {
1671
+ baseURL = ensureSlash(baseURL);
1672
+ while (url.startsWith("/")) url = url.substring(1);
1673
+ url = baseURL + url;
1674
+ }
1675
+ return url;
1974
1676
  };
1677
+ /**
1678
+ * Creates a new object from `obj` by omitting a set of `keys`.
1679
+ *
1680
+ * @beta
1681
+ * @experimental
1682
+ */
1975
1683
  function omitProps(obj, keys) {
1976
- const omittedObj = {};
1977
- for (const key in obj) {
1978
- if (!key.startsWith("param:") && !keys.includes(key)) {
1979
- omittedObj[key] = obj[key];
1980
- }
1981
- }
1982
- return omittedObj;
1684
+ const omittedObj = {};
1685
+ for (const key in obj) if (!key.startsWith("param:") && !keys.includes(key)) omittedObj[key] = obj[key];
1686
+ return omittedObj;
1983
1687
  }
1984
- const createRenderer = (getOptions) => {
1985
- return (opts) => {
1986
- const { jsx: jsx2, options } = getOptions(opts);
1987
- return renderToStream(jsx2, options);
1988
- };
1989
- };
1990
- const DocumentHeadTags = component$((props) => {
1991
- let head = useDocumentHead();
1992
- if (props) {
1993
- head = {
1994
- ...head,
1995
- ...props
1996
- };
1997
- }
1998
- return /* @__PURE__ */ jsxs(Fragment, {
1999
- children: [
2000
- head.title && /* @__PURE__ */ jsx("title", {
2001
- children: head.title
2002
- }),
2003
- head.meta.map((m) => /* @__PURE__ */ jsx("meta", {
2004
- ...m
2005
- })),
2006
- head.links.map((l) => /* @__PURE__ */ jsx("link", {
2007
- ...l
2008
- })),
2009
- head.styles.map((s) => {
2010
- const props2 = s.props || s;
2011
- return /* @__PURE__ */ createElement("style", {
2012
- ...props2,
2013
- dangerouslySetInnerHTML: s.style || props2.dangerouslySetInnerHTML,
2014
- key: s.key
2015
- });
2016
- }),
2017
- head.scripts.map((s) => {
2018
- const props2 = s.props || s;
2019
- return /* @__PURE__ */ createElement("script", {
2020
- ...props2,
2021
- dangerouslySetInnerHTML: s.script || props2.dangerouslySetInnerHTML,
2022
- key: s.key
2023
- });
2024
- })
2025
- ]
2026
- });
2027
- });
2028
- export {
2029
- DocumentHeadTags,
2030
- ErrorBoundary,
2031
- Form,
2032
- Link,
2033
- QWIK_CITY_SCROLLER,
2034
- QWIK_ROUTER_SCROLLER,
2035
- QwikCityMockProvider,
2036
- QwikCityProvider,
2037
- QwikRouterMockProvider,
2038
- QwikRouterProvider,
2039
- RouterOutlet,
2040
- ServiceWorkerRegister,
2041
- createRenderer,
2042
- globalAction$,
2043
- globalActionQrl,
2044
- omitProps,
2045
- routeAction$,
2046
- routeActionQrl,
2047
- routeLoader$,
2048
- routeLoaderQrl,
2049
- server$,
2050
- serverQrl,
2051
- untypedAppUrl,
2052
- useContent,
2053
- useDocumentHead,
2054
- useLocation,
2055
- useNavigate,
2056
- usePreventNavigate$,
2057
- usePreventNavigateQrl,
2058
- useQwikRouter,
2059
- valibot$,
2060
- valibotQrl,
2061
- validator$,
2062
- validatorQrl,
2063
- z2 as z,
2064
- zod$,
2065
- zodQrl
1688
+ /**
1689
+ * Creates the `render()` function that is required by `createQwikRouter()`. It requires a function
1690
+ * that returns the `jsx` and `options` for the renderer.
1691
+ *
1692
+ * @example
1693
+ *
1694
+ * ```tsx
1695
+ * const renderer = createRenderer((opts) => {
1696
+ * if (opts.requestHeaders['x-hello'] === 'world') {
1697
+ * return { jsx: <Hello />, options: opts };
1698
+ * }
1699
+ * return { jsx: <Root />, options: {
1700
+ * ...opts,
1701
+ * serverData: {
1702
+ * ...opts.serverData,
1703
+ * documentHead: {
1704
+ * meta: [
1705
+ * { name: 'renderedAt', content: new Date().toISOString() },
1706
+ * ],
1707
+ * },
1708
+ * },
1709
+ * } };
1710
+ * });
1711
+ * ```
1712
+ *
1713
+ * @public
1714
+ */
1715
+ var createRenderer = (getOptions) => {
1716
+ return ((opts) => {
1717
+ const { jsx, options } = getOptions(opts);
1718
+ const renderOptions = opts.serverData.renderMode === "static" ? {
1719
+ ...options,
1720
+ streaming: {
1721
+ ...options.streaming,
1722
+ outOfOrder: false
1723
+ }
1724
+ } : options;
1725
+ return renderToStream(jsx, renderOptions);
1726
+ });
2066
1727
  };
1728
+ /**
1729
+ * This renders all the tags collected from `head`.
1730
+ *
1731
+ * You can partially override the head, for example if you want to change the title:
1732
+ *
1733
+ * ```tsx
1734
+ * import { DocumentHeadTags, useDocumentHead } from '@qwik.dev/router';
1735
+ *
1736
+ * export default component$(() => {
1737
+ * const head = useDocumentHead();
1738
+ * return <DocumentHeadTags title={`${head.title} - My App`} />;
1739
+ * });
1740
+ * ```
1741
+ *
1742
+ * You don't have to use this component, you can also do it yourself for full control. Just copy the
1743
+ * code from this component and modify it to your needs.
1744
+ *
1745
+ * Note that this component normally only runs once, during SSR. You can use Signals in your
1746
+ * `src/root.tsx` to make runtime changes to `<head>` if needed.
1747
+ *
1748
+ * @public
1749
+ */
1750
+ var DocumentHeadTags = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl((props) => {
1751
+ let head = useDocumentHead();
1752
+ if (props) head = {
1753
+ ...head,
1754
+ ...props
1755
+ };
1756
+ return /*#__PURE__*/ _jsxSorted(Fragment, null, null, [
1757
+ head.title && /*#__PURE__*/ _jsxSorted("title", null, null, head.title, 1, "eL_0"),
1758
+ head.meta.map((m) => /*#__PURE__*/ _jsxSplit("meta", { ..._getVarProps(m) }, _getConstProps(m), null, 0, "eL_1")),
1759
+ head.links.map((l) => /*#__PURE__*/ _jsxSplit("link", { ..._getVarProps(l) }, _getConstProps(l), null, 0, "eL_2")),
1760
+ head.styles.map((s) => {
1761
+ const props = s.props || s;
1762
+ return /*#__PURE__*/ createElement("style", {
1763
+ ...props,
1764
+ dangerouslySetInnerHTML: s.style || props.dangerouslySetInnerHTML,
1765
+ key: s.key
1766
+ });
1767
+ }),
1768
+ head.scripts.map((s) => {
1769
+ const props = s.props || s;
1770
+ return /*#__PURE__*/ createElement("script", {
1771
+ ...props,
1772
+ dangerouslySetInnerHTML: s.script || props.dangerouslySetInnerHTML,
1773
+ key: s.key
1774
+ });
1775
+ })
1776
+ ], 1, "eL_3");
1777
+ }, "DocumentHeadTags_component_9CrWYOoCpgY"));
1778
+ export { DocumentHeadTags, Form, Link, QWIK_CITY_SCROLLER, QWIK_ROUTER_SCROLLER, QwikCityMockProvider, QwikCityProvider, QwikRouterMockProvider, QwikRouterProvider, RouterOutlet, ServiceWorkerRegister, _getServiceWorkerScript, _setRouterConfig, createRenderer, getBasePathname, getRequestEvent, getRouterConfig, getRoutes, getTrailingSlash, globalAction$, globalActionQrl, omitProps, routeAction$, routeActionQrl, routeLoader$, routeLoaderQrl, server$, serverQrl, untypedAppUrl, useContent, useDocumentHead, useHttpStatus, useLocation, useNavigate, usePreventNavigate$, usePreventNavigateQrl, useQwikRouter, valibot$, valibotQrl, validator$, validatorQrl, z, zod$, zodQrl };