@qwik.dev/router 2.0.0-rc.4 → 2.0.0-rc.6

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.
@@ -1,12 +1,39 @@
1
1
  import { t as ensureSlash } from "./chunks/pathname.mjs";
2
- import { $ as ContentInternalContext, A as isImmutableLoader, B as _getServiceWorkerUrl, C as getModuleRouteLoaders, F as restoreRouteLoaders, G as getRoutes, H as findRouterConfig, I as routeLoader$, J as RUN_PENDING_ACTION, K as getTrailingSlash, L as routeLoaderQrl, N as prepareRouteLoaders, Q as ContentContext, R as setLoaderSignalValue, U as getBasePathname, V as _setRouterConfig, W as getRouterConfig, X as preventNav, Y as internalState, Z as registerPreventNav, a as isPromise, at as RouteLocationContext, b as fetchRouteLoaderData, c as shouldPreload, ct as QACTION_KEY, d as loadRoute, dt as Q_ROUTE, et as DocumentHeadContext, f as matchRouteTree, g as clearNavFetchCache, h as abortRouteLoaderNavigation, i as getClientNavPath, it as RouteLoaderCtxContext, l as toPath, lt as QDATA_KEY, n as resolveHead, nt as RouteActionContext, o as isSameOrigin, ot as RouteNavigateContext, q as REFRESH_HEAD, rt as RouteActionRunnerContext, s as isSamePath, st as RouteStateContext, t as createDocumentHead, tt as HttpStatusContext, u as toUrl, ut as QFN_KEY, v as commitRouteLoaders, w as getRequestEvent, x as getClientRouteLoaders, y as ensureRouteLoaderSignals } from "./chunks/head.qwik.mjs";
2
+ import { $ as RouteLoaderCtxContext, A as restoreRouteLoaders, B as getRoutes, F as _getServiceWorkerUrl, G as preventNav, H as REFRESH_HEAD, I as _setRouterConfig, J as ContentInternalContext, K as registerPreventNav, L as findRouterConfig, M as routeLoaderQrl, N as setLoaderSignalValue, O as prepareRouteLoaders, Q as RouteActionRunnerContext, R as getBasePathname, T as isImmutableLoader, U as RUN_PENDING_ACTION, V as getTrailingSlash, W as internalState, X as HttpStatusContext, Y as DocumentHeadContext, Z as RouteActionContext, _t as isSamePath, a as getNewLayoutKeys, at as QFN_KEY, bt as toSafeRedirectUrl, d as clearNavFetchCache, et as RouteLocationContext, g as getClientRouteLoaders, gt as isSameOrigin, h as fetchRouteLoaderData, ht as isPromise, i as getLayoutKeys, it as QDATA_KEY, j as routeLoader$, m as ensureRouteLoaderSignals, mt as getClientNavPath, n as resolveHead, nt as RouteStateContext, o as loadRoute, ot as Q_ROUTE, p as commitRouteLoaders, q as ContentContext, rt as QACTION_KEY, s as matchRouteTree, t as createDocumentHead, tt as RouteNavigateContext, u as abortRouteLoaderNavigation, v as getModuleRouteLoaders, vt as shouldPreload, xt as toUrl, y as getRequestEvent, yt as toPath, z as getRouterConfig } from "./chunks/head.qwik.mjs";
3
3
  import { SkipRender, Slot, _capturesObj, _fnSignal, _getConstProps, _getVarProps, _jsxSorted, _jsxSplit, _qrlSync, _restProps, _wrapProp, componentQrl, createComputedQrl, 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, _getDomContainer, _hasStoreEffects, _regInlinedQrl, _requestPreload, _serialize, _waitOn, _waitUntilRendered, forceStoreEffects } from "@qwik.dev/core/internal";
4
+ import { _deserialize, _getContextContainer, _getContextHostElement, _getDomContainer, _hasStoreEffects, _isSyncQrl, _regInlinedQrl, _requestPreload, _waitOn, _waitUntilRendered, forceStoreEffects } from "@qwik.dev/core/internal";
5
5
  import { Fragment } from "@qwik.dev/core/jsx-runtime";
6
+ import { _serialize } from "@qwik.dev/core/internal/serializer";
6
7
  import * as v from "valibot";
7
8
  import * as z$1 from "zod";
8
9
  import { z } from "zod";
9
10
  import { renderToStream } from "@qwik.dev/core/server";
11
+ var clientNavigate = (win, navType, fromURL, toURL, replaceState = false) => {
12
+ if (navType !== "popstate") {
13
+ const samePath = isSamePath(fromURL, toURL);
14
+ const sameHash = fromURL.hash === toURL.hash;
15
+ if (!samePath || !sameHash) {
16
+ const newState = { _qRouterScroll: newScrollState() };
17
+ if (replaceState) win.history.replaceState(newState, "", toPath(toURL));
18
+ else win.history.pushState(newState, "", toPath(toURL));
19
+ }
20
+ }
21
+ };
22
+ var newScrollState = () => {
23
+ return {
24
+ x: 0,
25
+ y: 0,
26
+ w: 0,
27
+ h: 0
28
+ };
29
+ };
30
+ var preloadRouteBundles = (routeName, priority = .8, newLayoutKeys = []) => {
31
+ if (isBrowser) {
32
+ routeName = ensureSlash(routeName);
33
+ routeName = routeName.length > 1 && routeName.startsWith("/") ? routeName.slice(1) : routeName;
34
+ _requestPreload([...newLayoutKeys, routeName], priority, true);
35
+ }
36
+ };
10
37
  /**
11
38
  * Prefetch a route's JS bundles and optionally its loader data.
12
39
  *
@@ -16,23 +43,26 @@ import { renderToStream } from "@qwik.dev/core/server";
16
43
  *
17
44
  * @param url - The URL pathname to prefetch
18
45
  * @param prefetchData - Whether to prefetch loader data
19
- * @param probability - Bundle preload probability (0-1, default 0.8)
46
+ * @param priority - Preload priority of the route's bundles (0-1, default 0.8)
20
47
  * @param manifestHash - Build manifest hash for loader URLs (from `useDocumentHead().manifestHash`)
21
48
  * @param prefetchBundle - Whether to prefetch route JS bundles
49
+ * @param currentUrl - The page the navigation leaves, when `location` already shows the new one
22
50
  */
23
- async function prefetchRoute(url, prefetchData, probability = .8, manifestHash, prefetchBundle = true) {
51
+ async function prefetchRoute(url, prefetchData, priority = .8, manifestHash, prefetchBundle = true, currentUrl) {
24
52
  if (!isBrowser || isDev) return;
25
53
  try {
26
54
  const { routes, cacheModules } = await getRouterConfig();
27
- const loadedRoute = await loadRoute(routes, cacheModules, url.pathname);
28
- if (!loadedRoute) return;
29
55
  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);
56
+ const destRoute = matchRouteTree(routes, url.pathname);
57
+ const currentRoute = matchRouteTree(routes, (currentUrl ?? location).pathname);
58
+ const newLayoutKeys = getNewLayoutKeys(getLayoutKeys(currentRoute.loaders), getLayoutKeys(destRoute.loaders));
59
+ preloadRouteBundles("/" + destRoute.routeParts.join("/"), priority, newLayoutKeys);
34
60
  }
35
- if (!prefetchData || !manifestHash) return;
61
+ const isNavigating = priority === 1;
62
+ const shouldPrefetchData = !!prefetchData && !!manifestHash;
63
+ if (!isNavigating && !shouldPrefetchData) return;
64
+ const loadedRoute = await loadRoute(routes, cacheModules, url.pathname);
65
+ if (!loadedRoute || !shouldPrefetchData) return;
36
66
  prefetchLoaderData(loadedRoute, url, manifestHash);
37
67
  } catch {}
38
68
  }
@@ -119,28 +149,37 @@ var usePreventNavigateQrl = (fn) => {
119
149
  var usePreventNavigate$ = implicit$FirstArg(usePreventNavigateQrl);
120
150
  var useAction = () => useContext(RouteActionContext);
121
151
  var useQwikRouterEnv = () => noSerialize(useServerData("qwikrouter"));
152
+ var INTENT_PRIORITY = .9;
122
153
  /** @public */
123
154
  var Link = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl((props) => {
124
155
  const nav = useNavigate();
125
156
  const loc = useLocation();
126
157
  const head = useDocumentHead();
158
+ const originalHref = props.href;
127
159
  const { onClick$, prefetch: prefetchProp, reload, replaceState, scroll, prefetchBundles: prefetchBundlesProp = "visible", prefetchData: prefetchDataProp = prefetchProp === "js" ? "off" : "intent", ...linkProps } = props;
128
160
  const clientNavPath = untrack(getClientNavPath, {
129
161
  ...linkProps,
130
162
  reload
131
163
  }, loc);
132
- linkProps.href = clientNavPath || props.href;
164
+ linkProps.href = clientNavPath || originalHref;
133
165
  const isDepratedPrefetchDisabled = prefetchProp === false;
134
166
  const shouldPrefetch = untrack(shouldPreload, clientNavPath, loc);
135
167
  const shouldVisiblePrefetchBundles = !!clientNavPath && shouldPrefetch && !isDepratedPrefetchDisabled && (prefetchBundlesProp === "visible" || prefetchProp === "js" || prefetchProp === true);
136
168
  const shouldVisiblePrefetchData = !!clientNavPath && shouldPrefetch && !isDepratedPrefetchDisabled && (prefetchDataProp === "visible" || prefetchProp === true);
137
- const routes = shouldVisiblePrefetchBundles && findRouterConfig()?.routes;
138
- const route = routes && untrack(() => matchRouteTree(routes, new URL(clientNavPath, loc.url).pathname));
169
+ const routes = !!clientNavPath && findRouterConfig()?.routes;
170
+ const route = routes && untrack(() => {
171
+ try {
172
+ return matchRouteTree(routes, new URL(clientNavPath, loc.url).pathname);
173
+ } catch {
174
+ return;
175
+ }
176
+ });
177
+ const newLayoutKeys = shouldVisiblePrefetchBundles && routes && route && !route.notFound ? untrack(() => getNewLayoutKeys(getLayoutKeys(matchRouteTree(routes, loc.url.pathname).loaders), getLayoutKeys(route.loaders))) : void 0;
139
178
  const shouldPrefetchBundles = !!clientNavPath && prefetchBundlesProp !== "off" && shouldPrefetch && !isDepratedPrefetchDisabled;
140
179
  const shouldPrefetchData = !!clientNavPath && prefetchDataProp !== "off" && shouldPrefetch && !isDepratedPrefetchDisabled;
141
180
  const handleBundlePrefetch = shouldPrefetchBundles ? /*#__PURE__*/ inlinedQrl((_, elm) => {
142
181
  if (navigator.connection?.saveData) return;
143
- if (elm && elm.href) prefetchRoute(new URL(elm.href), false, .8);
182
+ if (elm && elm.href) prefetchRoute(new URL(elm.href), false, INTENT_PRIORITY);
144
183
  }, "Link_component_handleBundlePrefetch_ZttUP0kLKj0") : null;
145
184
  const handleDataPrefetch = shouldPrefetchData ? /*#__PURE__*/ inlinedQrl((_, elm) => {
146
185
  let head = _capturesObj._[0];
@@ -190,9 +229,12 @@ var Link = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl((props) => {
190
229
  ...linkProps,
191
230
  "data-q-prefetch": shouldVisiblePrefetchBundles && shouldVisiblePrefetchData ? "bd" : shouldVisiblePrefetchBundles ? "b" : shouldVisiblePrefetchData ? "d" : null,
192
231
  "data-q-route": route && !route.notFound ? "/" + route.routeParts.join("/") : void 0,
232
+ "data-q-layouts": newLayoutKeys?.length ? newLayoutKeys.join(" ") : void 0,
193
233
  "q-e:click": [
194
234
  preventDefault,
195
235
  /*#__PURE__*/ inlinedQrl((_, elm) => {
236
+ const routeName = elm.getAttribute("data-q-route");
237
+ if (routeName) preloadRouteBundles(routeName, 1);
196
238
  prefetchRoute(new URL(elm.href), false, 1);
197
239
  }, "Link_component_handlePreload_AAemwtuBjsE"),
198
240
  onClick$,
@@ -201,12 +243,12 @@ var Link = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl((props) => {
201
243
  "q-e:pointerenter": [
202
244
  linkProps.onPointerEnter$,
203
245
  prefetchDataProp === "intent" ? prefetchData : null,
204
- prefetchBundlesProp === "intent" ? handleBundlePrefetch : null
246
+ prefetchBundlesProp === "commit" ? null : handleBundlePrefetch
205
247
  ],
206
248
  "q-e:focus": [
207
249
  linkProps.onFocus$,
208
250
  prefetchDataProp === "intent" ? prefetchData : null,
209
- prefetchBundlesProp === "intent" ? handleBundlePrefetch : null
251
+ prefetchBundlesProp === "commit" ? null : handleBundlePrefetch
210
252
  ],
211
253
  "q-e:pointerdown": [
212
254
  linkProps.onPointerDown$,
@@ -216,32 +258,7 @@ var Link = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl((props) => {
216
258
  "q-e:keydown": [linkProps.onKeyDown$, prefetchDataProp === "commit" || prefetchBundlesProp === "commit" ? onEnterKeyDown : null]
217
259
  }, null, /*#__PURE__*/ _jsxSorted(Slot, null, null, null, 3, "xa_0"), 0, "xa_1");
218
260
  }, "Link_component_VPmar9tb3t4"));
219
- var clientNavigate = (win, navType, fromURL, toURL, replaceState = false) => {
220
- if (navType !== "popstate") {
221
- const samePath = isSamePath(fromURL, toURL);
222
- const sameHash = fromURL.hash === toURL.hash;
223
- if (!samePath || !sameHash) {
224
- const newState = { _qRouterScroll: newScrollState() };
225
- if (replaceState) win.history.replaceState(newState, "", toPath(toURL));
226
- else win.history.pushState(newState, "", toPath(toURL));
227
- }
228
- }
229
- };
230
- var newScrollState = () => {
231
- return {
232
- x: 0,
233
- y: 0,
234
- w: 0,
235
- h: 0
236
- };
237
- };
238
- var preloadRouteBundles = (routeName, probability = .8) => {
239
- if (isBrowser) {
240
- routeName = ensureSlash(routeName);
241
- routeName = routeName.length > 1 && routeName.startsWith("/") ? routeName.slice(1) : routeName;
242
- _requestPreload(routeName, probability);
243
- }
244
- };
261
+ var VISIBLE_LINK_PRIORITY = .5;
245
262
  var prefetchedLinks = /* @__PURE__ */ new WeakSet();
246
263
  var cleanupPrefetchObserver;
247
264
  var resetLinkPrefetchState = () => {
@@ -272,7 +289,10 @@ var createLinkPrefetchObserver = (manifestHash) => {
272
289
  if (!isSameOrigin(url, currentUrl) || !shouldPreload(toPath(url), { url: currentUrl })) return;
273
290
  const mode = anchor.getAttribute("data-q-prefetch") || "";
274
291
  const routeName = anchor.getAttribute("data-q-route");
275
- if (mode.includes("b") && routeName) preloadRouteBundles(routeName);
292
+ if (mode.includes("b") && routeName) {
293
+ const newLayoutKeys = anchor.getAttribute("data-q-layouts")?.split(" ");
294
+ preloadRouteBundles(routeName, VISIBLE_LINK_PRIORITY, newLayoutKeys);
295
+ }
276
296
  if (mode.includes("d")) prefetchRoute(url, true, .8, manifestHash, false);
277
297
  };
278
298
  if (typeof IntersectionObserver === "undefined") {
@@ -366,8 +386,10 @@ var spa_init_default = eventQrl(/*#__PURE__*/ inlinedQrl((_, el) => {
366
386
  if (window._qRouterSPA) return;
367
387
  window._qRouterScrollEnabled = false;
368
388
  clearTimeout(window._qRouterScrollDebounce);
369
- if (hasPathChanged(location.pathname + location.search)) dispatchRouterPopstate(document, location.href);
370
- else if (history.scrollRestoration === "manual") {
389
+ if (hasPathChanged(location.pathname + location.search)) {
390
+ if (window._qRouterInitNavigate) window._qRouterInitNavigate(location.href, { type: "popstate" });
391
+ else dispatchRouterPopstate(document, location.href);
392
+ } else if (history.scrollRestoration === "manual") {
371
393
  const scrollState = history.state?._qRouterScroll;
372
394
  checkAndScroll(scrollState);
373
395
  window._qRouterScrollEnabled = true;
@@ -388,11 +410,15 @@ var spa_init_default = eventQrl(/*#__PURE__*/ inlinedQrl((_, el) => {
388
410
  };
389
411
  history.pushState = (state, title, url) => {
390
412
  state = prepareState(state);
391
- return pushState.call(history, state, title, url);
413
+ const result = pushState.call(history, state, title, url);
414
+ hasPathChanged(location.pathname + location.search);
415
+ return result;
392
416
  };
393
417
  history.replaceState = (state, title, url) => {
394
418
  state = prepareState(state);
395
- return replaceState.call(history, state, title, url);
419
+ const result = replaceState.call(history, state, title, url);
420
+ hasPathChanged(location.pathname + location.search);
421
+ return result;
396
422
  };
397
423
  }
398
424
  window._qRouterInitAnchors = (event) => {
@@ -490,8 +516,9 @@ async function submitAction(action, routeUrl) {
490
516
  loaderHashes: data?.loaderHashes
491
517
  };
492
518
  }
519
+ throw new Error(`Unexpected action response (${response.status}): expected JSON`);
493
520
  }
494
- 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}}}";
521
+ var qwik_view_transition_default = "@layer qwik{@supports selector(html:active-view-transition-type(type)){html:active-view-transition-type(qwik-navigation){view-transition-name:none}}@supports not selector(html:active-view-transition-type(type)){:root{view-transition-name:none}}}";
495
522
  /** View transitions are opt-in and require browser support. */
496
523
  var shouldStartViewTransition = (viewTransition) => viewTransition === true && "startViewTransition" in document;
497
524
  var VIEW_TRANSITION_STYLE_ID = "qwik-view-transition";
@@ -521,16 +548,75 @@ var startViewTransition = (params) => {
521
548
  } else return { ready: params.update() };
522
549
  };
523
550
  /**
551
+ * Qwik Router Component
552
+ *
553
+ * This file contains the main Qwik Router component, which initializes the router and provides the
554
+ * necessary context for it to work. It also contains the logic for handling navigation, including
555
+ * updating the URL, managing scroll restoration, and resolving document head changes.
556
+ *
557
+ * Note: This component is designed to work both on the server and the client. During server-side
558
+ * rendering (SSR), it initializes the router state based on the URL and route data provided by the
559
+ * server environment. On the client, it handles navigation events and updates the router state
560
+ * accordingly.
561
+ *
562
+ * SSR is _required_ for the initial load.
563
+ *
564
+ * The flow of navigation is as follows:
565
+ *
566
+ * 1. During SSR, the server environment parses the initial URL and collects the route data.
567
+ * 2. It runs the middleware hooks (`onRequest`, `onGet`, `onPost`, etc.), and responds to q-loader,
568
+ * action$ and server$ requests.
569
+ * 3. If SSR is deemed appropriate, the route data is provided via `useServerData` and this component
570
+ * uses it to initialize the router contexts, register Tasks, and render the Slot. This component
571
+ * will never render again.
572
+ * 4. Then, slotted components like `<DocumentHeadTags />` and `<RouterOutlet />` can consume the route
573
+ * data to render the page.
574
+ * 5. On the client, when a navigation event occurs, this calls `goto()`, which updates the URL in the
575
+ * same tick, loads the route data and adjusts the router context.
576
+ * 6. The changed contexts trigger the slotted components to re-render with the new route data.
577
+ *
578
+ * Since the head data can depend on route loaders and they get their data asynchronously and can
579
+ * update without navigation, the head is resolved in a separate Task that tracks the relevant
580
+ * signals.
581
+ */
582
+ var LEFT_PAGE_PRIORITY = .6;
583
+ /**
524
584
  * @deprecated Use `QWIK_ROUTER_SCROLLER` instead (will be removed in V3)
525
585
  * @public
526
586
  */
527
587
  var QWIK_CITY_SCROLLER = "_qCityScroller";
528
588
  /** @public */
529
589
  var QWIK_ROUTER_SCROLLER = "_qRouterScroller";
590
+ var NavigationStartType = /* @__PURE__ */ function(NavigationStartType) {
591
+ NavigationStartType[NavigationStartType["Unchanged"] = 0] = "Unchanged";
592
+ NavigationStartType[NavigationStartType["Duplicate"] = 1] = "Duplicate";
593
+ NavigationStartType[NavigationStartType["Prepared"] = 2] = "Prepared";
594
+ NavigationStartType[NavigationStartType["Superseded"] = 3] = "Superseded";
595
+ NavigationStartType[NavigationStartType["External"] = 4] = "External";
596
+ return NavigationStartType;
597
+ }(NavigationStartType || {});
530
598
  var ensureRouteInternal = (routeInternal, routeLocation) => routeInternal.untrackedValue ||= {
531
599
  type: "initial",
532
600
  dest: routeLocation.url
533
601
  };
602
+ /**
603
+ * A URL the client can't render itself (no matching page) may be a server `rewrite()`. Ask the
604
+ * server where it routes to. Returns the target pathname, `'reload'` if the server redirects, or
605
+ * `undefined` when the URL is not rewritten.
606
+ */
607
+ var resolveServerRewrite = async (url) => {
608
+ try {
609
+ const response = await fetch(`${ensureSlash(url.pathname)}q-route.json${url.search}`, {
610
+ redirect: "manual",
611
+ headers: { accept: "application/json" }
612
+ });
613
+ if (response.type === "opaqueredirect" || response.status >= 300 && response.status < 400) return "reload";
614
+ if (response.ok) {
615
+ const { p } = await response.json();
616
+ return typeof p === "string" ? p : void 0;
617
+ }
618
+ } catch {}
619
+ };
534
620
  var getRouterContainer = () => _getDomContainer(document.documentElement);
535
621
  var getServerHttpStatus = (notFound, response) => {
536
622
  if (notFound) return {
@@ -657,6 +743,32 @@ var useQwikRouter = (props) => {
657
743
  return;
658
744
  }
659
745
  if (path === RUN_PENDING_ACTION) return loadNavigation(ensureRouteInternal(routeInternal, routeLocation), actionState.value, getRouterContainer());
746
+ return prepareNavigation(path, opt).started.then((started) => started.finished);
747
+ };
748
+ const prepareNavigation = (path, opt) => {
749
+ let resolvePreparation;
750
+ let rejectPreparation;
751
+ const prepared = new Promise((resolve, reject) => {
752
+ resolvePreparation = resolve;
753
+ rejectPreparation = reject;
754
+ });
755
+ prepared.catch(() => {});
756
+ const preparation = {
757
+ promise: prepared,
758
+ resolve: resolvePreparation
759
+ };
760
+ const started = beginNavigation(path, opt, preparation);
761
+ started.then(async (result) => {
762
+ if (result.type !== NavigationStartType.Duplicate && navResolver.preparation !== preparation && preparation.navCount !== internalState.navCount || result.type === NavigationStartType.Superseded || result.type === NavigationStartType.External) return;
763
+ await navResolver.routePreparation?.started;
764
+ if (getClientRouteLoaders(routeLoaderCtx).navCount === internalState.navCount) resolvePreparation();
765
+ }, rejectPreparation).catch(rejectPreparation);
766
+ return {
767
+ prepared,
768
+ started
769
+ };
770
+ };
771
+ const beginNavigation = async (path, opt, preparation) => {
660
772
  const { type = "link", forceReload = path === void 0, replaceState = false, scroll = true } = typeof opt === "object" ? opt : { forceReload: opt };
661
773
  const current = ensureRouteInternal(routeInternal, routeLocation);
662
774
  if (isBrowser && type === "link" && current.type === "initial") {
@@ -666,24 +778,31 @@ var useQwikRouter = (props) => {
666
778
  }
667
779
  const lastDest = current.dest;
668
780
  const dest = path === void 0 ? lastDest : typeof path === "number" ? path : toUrl(path, routeLocation.url);
669
- if (navResolver.p && !forceReload && typeof dest !== "number" && isSamePath(dest, lastDest) && dest.href === lastDest.href) return navResolver.p;
781
+ if (navResolver.p && !forceReload && typeof dest !== "number" && isSamePath(dest, lastDest) && dest.href === lastDest.href) return {
782
+ type: NavigationStartType.Duplicate,
783
+ finished: navResolver.p
784
+ };
785
+ const previousPreparation = navResolver.preparation;
786
+ navResolver.preparation = preparation;
787
+ if (previousPreparation?.navCount === void 0) previousPreparation?.resolve(preparation.promise);
670
788
  const attemptCount = ++internalState.attemptCount;
671
789
  if (preventNav.$cbs$ && (forceReload || typeof dest === "number" || !isSamePath(dest, lastDest) || !isSameOrigin(dest, lastDest))) {
672
790
  const prevents = await Promise.all([...preventNav.$cbs$.values()].map((cb) => cb(dest)));
673
- if (attemptCount !== internalState.attemptCount || prevents.some(Boolean)) {
674
- if (attemptCount === internalState.attemptCount && type === "popstate") history.pushState(null, "", lastDest);
675
- return;
791
+ if (attemptCount !== internalState.attemptCount) return { type: NavigationStartType.Superseded };
792
+ if (prevents.some(Boolean)) {
793
+ if (type === "popstate") history.pushState(null, "", lastDest);
794
+ return { type: NavigationStartType.Unchanged };
676
795
  }
677
796
  }
678
797
  if (typeof dest === "number") {
679
798
  if (isBrowser) history.go(dest);
680
- return;
799
+ return { type: NavigationStartType.External };
681
800
  }
682
801
  if (!isSameOrigin(dest, lastDest)) {
683
802
  if (isBrowser) location.href = dest.href;
684
- return;
803
+ return { type: NavigationStartType.External };
685
804
  }
686
- if (!forceReload && isSamePath(dest, lastDest)) {
805
+ if (!forceReload && isSamePath(dest, lastDest) && (!navResolver.dest || isSamePath(navResolver.dest, dest) && navResolver.dest.href === dest.href)) {
687
806
  if (isBrowser) {
688
807
  if (type === "link" && dest.href !== location.href) history.pushState(null, "", dest);
689
808
  const scroller = getScroller();
@@ -697,13 +816,34 @@ var useQwikRouter = (props) => {
697
816
  const contentModules = contentInternal.untrackedValue;
698
817
  if (contentModules) updateHead(contentModules, actionDataSignal.untrackedValue, internalState.navCount);
699
818
  }
700
- return navResolver.p;
819
+ return {
820
+ type: NavigationStartType.Unchanged,
821
+ finished: navResolver.p
822
+ };
701
823
  }
702
824
  const navCount = ++internalState.navCount;
825
+ preparation.navCount = navCount;
826
+ navResolver.routePreparation?.preparation.resolve(preparation.promise);
703
827
  internalState.currentTransition?.skipTransition();
704
828
  navResolver.cancel?.();
705
829
  navResolver.cancel = void 0;
706
830
  navResolver.r?.();
831
+ navResolver.dest = dest;
832
+ const preparing = preparePageNavigation({
833
+ type,
834
+ dest,
835
+ forceReload,
836
+ replaceState,
837
+ scroll
838
+ }, navCount);
839
+ navResolver.routePreparation = {
840
+ started: preparing,
841
+ preparation
842
+ };
843
+ return preparing;
844
+ };
845
+ const preparePageNavigation = async (navigation, navCount) => {
846
+ const { type, dest, forceReload, replaceState } = navigation;
707
847
  let historyUpdated = false;
708
848
  if (isBrowser) getClientRouteLoaders(routeLoaderCtx, routeLocation.url.href);
709
849
  if (isBrowser && type === "link" && !forceReload) {
@@ -719,20 +859,17 @@ var useQwikRouter = (props) => {
719
859
  const container = isBrowser ? _getContextContainer() : void 0;
720
860
  if (container && !wasNavigating) {
721
861
  await _waitUntilRendered(container);
722
- if (navCount !== internalState.navCount) return;
862
+ if (navCount !== internalState.navCount) return { type: NavigationStartType.Superseded };
723
863
  }
724
864
  actionState.value = void 0;
725
- const navigation = {
726
- type,
727
- dest,
728
- forceReload,
729
- replaceState,
730
- scroll,
731
- historyUpdated
732
- };
865
+ navigation.historyUpdated = historyUpdated;
733
866
  routeInternal.value = navigation;
867
+ navResolver.dest = void 0;
734
868
  if (wasNavigating) abortRouteLoaderNavigation(routeLoaderCtx);
735
- if (isBrowser) prefetchRoute(dest, false, .8, manifestHash, true);
869
+ if (isBrowser) {
870
+ prefetchRoute(dest, false, 1, manifestHash, true, routeLocation.url);
871
+ if (!isSamePath(dest, routeLocation.url)) prefetchRoute(routeLocation.url, false, LEFT_PAGE_PRIORITY, manifestHash, true, dest);
872
+ }
736
873
  navResolver.p = new Promise((resolve) => {
737
874
  navResolver.r = () => {
738
875
  navResolver.r = void 0;
@@ -741,8 +878,11 @@ var useQwikRouter = (props) => {
741
878
  };
742
879
  });
743
880
  const navigated = navResolver.p;
744
- loadNavigation(navigation, void 0, container ?? getRouterContainer());
745
- return navigated;
881
+ await loadNavigation(navigation, void 0, container ?? getRouterContainer());
882
+ return {
883
+ type: NavigationStartType.Prepared,
884
+ finished: navigated
885
+ };
746
886
  };
747
887
  const loadNavigation = async (navigation, action, container) => {
748
888
  action?.resolveDispatch?.();
@@ -758,6 +898,13 @@ var useQwikRouter = (props) => {
758
898
  const canceled = new Promise((resolve) => {
759
899
  navResolver.cancel = () => resolve(void 0);
760
900
  });
901
+ const abandonAction = () => {
902
+ action?.reject?.(/* @__PURE__ */ new Error("Action submission was superseded by a navigation"));
903
+ if (action) {
904
+ action.resolve = void 0;
905
+ action.reject = void 0;
906
+ }
907
+ };
761
908
  if (trackUrl.pathname.endsWith("/")) {
762
909
  if (globalThis.__NO_TRAILING_SLASH__) trackUrl.pathname = trackUrl.pathname.slice(0, -1);
763
910
  } else if (!globalThis.__NO_TRAILING_SLASH__) trackUrl.pathname = ensureSlash(trackUrl.pathname);
@@ -767,27 +914,72 @@ var useQwikRouter = (props) => {
767
914
  });
768
915
  try {
769
916
  const route = await Promise.race([loadRoutePromise, canceled]);
770
- if (!route) return;
917
+ if (!route) {
918
+ abandonAction();
919
+ return;
920
+ }
771
921
  loadedRoute = route;
772
922
  } catch (e) {
773
- if (internalState.navCount !== navCountBefore) return;
923
+ if (internalState.navCount !== navCountBefore) {
924
+ abandonAction();
925
+ return;
926
+ }
774
927
  const preparedNavCount = getClientRouteLoaders(routeLoaderCtx).navCount;
775
928
  if (preparedNavCount !== void 0) restoreRouteLoaders(loaderState, routeLoaderCtx, preparedNavCount);
776
929
  console.error(`Could not load route ${trackUrl.pathname}, reloading:`, e);
777
930
  window.location.href = trackUrl.href;
778
931
  return;
779
932
  }
780
- if (internalState.navCount !== navCountBefore) return;
933
+ if (internalState.navCount !== navCountBefore) {
934
+ abandonAction();
935
+ return;
936
+ }
937
+ let rewrittenTo;
938
+ const lastModule = loadedRoute.$mods$[loadedRoute.$mods$.length - 1];
939
+ if (loadedRoute.$notFound$ || typeof lastModule?.default !== "function" || loadedRoute.$routeName$.includes("[")) {
940
+ const resolved = await Promise.race([resolveServerRewrite(trackUrl), canceled]);
941
+ if (internalState.navCount !== navCountBefore) {
942
+ abandonAction();
943
+ return;
944
+ }
945
+ if (resolved === "reload") {
946
+ if (!action) {
947
+ window.location.href = trackUrl.href;
948
+ return;
949
+ }
950
+ } else if (resolved && resolved !== trackUrl.pathname) {
951
+ try {
952
+ const config = await getRouterConfig();
953
+ loadedRoute = await loadRoute(config.routes, config.cacheModules, resolved);
954
+ rewrittenTo = resolved;
955
+ } catch (e) {
956
+ if (internalState.navCount !== navCountBefore) {
957
+ abandonAction();
958
+ return;
959
+ }
960
+ console.error(`Could not load rewritten route ${resolved}, reloading:`, e);
961
+ window.location.href = trackUrl.href;
962
+ return;
963
+ }
964
+ if (internalState.navCount !== navCountBefore) {
965
+ abandonAction();
966
+ return;
967
+ }
968
+ }
969
+ }
781
970
  if (action) {
782
971
  const result = await Promise.race([submitAction(action, trackUrl).then((result) => {
783
- if (result && action.resolve) {
784
- action.resolve({
785
- status: result.status,
786
- result: result.result
787
- });
788
- action.resolve = void 0;
789
- }
972
+ action.resolve?.({
973
+ status: result.status,
974
+ result: result.result
975
+ });
976
+ action.resolve = void 0;
977
+ action.reject = void 0;
790
978
  return result;
979
+ }, (error) => {
980
+ action.reject?.(error);
981
+ action.reject = void 0;
982
+ action.resolve = void 0;
791
983
  }), canceled]);
792
984
  if (internalState.navCount !== navCountBefore || action !== actionState.untrackedValue) return;
793
985
  navResolver.cancel = void 0;
@@ -796,11 +988,14 @@ var useQwikRouter = (props) => {
796
988
  type: navType,
797
989
  dest: trackUrl
798
990
  };
991
+ routeLocation.isNavigating = false;
992
+ navResolver.r?.();
799
993
  return;
800
994
  }
801
995
  if (result.redirect) {
802
- if (result.redirect instanceof URL) location.href = result.redirect.href;
803
- else startNavigation(result.redirect, { replaceState: true });
996
+ const redirectUrl = toSafeRedirectUrl(result.redirect, routeLocation.url);
997
+ if (result.redirect instanceof URL) location.href = redirectUrl.href;
998
+ else startNavigation(redirectUrl, { replaceState: true });
804
999
  return;
805
1000
  }
806
1001
  actionData = {
@@ -813,8 +1008,8 @@ var useQwikRouter = (props) => {
813
1008
  navResolver.cancel = void 0;
814
1009
  const { $routeName$, $params$, $mods$, $menu$, $notFound$ } = loadedRoute;
815
1010
  const contentModules = $mods$;
816
- routeLoaderCtx.goto = noSerialize(startNavigation);
817
- const routeLoaders = prepareRouteLoaders(contentModules, loaderState, routeLoaderCtx, loadedRoute.$loaderPaths$, trackUrl, prevUrl, navCountBefore, action ? actionLoaderHashes ?? null : void 0, action ?? navigation);
1011
+ routeLoaderCtx.goto = noSerialize((path, opt) => prepareNavigation(path, opt).prepared);
1012
+ const routeLoaders = prepareRouteLoaders(contentModules, loaderState, routeLoaderCtx, rewrittenTo ? void 0 : loadedRoute.$loaderPaths$, trackUrl, prevUrl, navCountBefore, action ? actionLoaderHashes ?? null : void 0, action ?? navigation, navigation.forceReload);
818
1013
  await whenReady(() => {
819
1014
  for (let i = 0; i < routeLoaders.length; i++) {
820
1015
  const loader = routeLoaders[i];
@@ -962,6 +1157,7 @@ var useQwikRouter = (props) => {
962
1157
  });
963
1158
  });
964
1159
  };
1160
+ if (isBrowser && !window._qRouterSPA) window._qRouterInitNavigate = startNavigation;
965
1161
  return startNavigation(path, opt);
966
1162
  }, "useQwikRouter_goto_8j8Vrz2yUIM", [
967
1163
  actionDataSignal,
@@ -1005,6 +1201,7 @@ function initializeSPA(goto, scroller) {
1005
1201
  });
1006
1202
  window.removeEventListener("popstate", window._qRouterInitPopstate);
1007
1203
  window._qRouterInitPopstate = void 0;
1204
+ window._qRouterInitNavigate = void 0;
1008
1205
  if (!window._qRouterHistoryPatch) {
1009
1206
  window._qRouterHistoryPatch = true;
1010
1207
  const pushState = history.pushState;
@@ -1161,8 +1358,9 @@ var RouterOutlet = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl(() => {
1161
1358
  const nav = useNavigate();
1162
1359
  const contents = internalContext.value;
1163
1360
  if (contents && contents.length > 0) {
1361
+ const contentsLen = contents.length;
1164
1362
  let cmp = null;
1165
- 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");
1363
+ for (let i = contentsLen - 1; i >= 0; i--) if (contents[i].default) cmp = /*#__PURE__*/ _jsxSorted(contents[i].default, null, null, cmp, 1, "yd_0");
1166
1364
  return /*#__PURE__*/ _jsxSorted(Fragment, null, null, [cmp, !__EXPERIMENTAL__.noSPA && /*#__PURE__*/ _jsxSorted("script", {
1167
1365
  "q-d:qcinit": [spa_init_default, linkPrefetchInit],
1168
1366
  "q-d:qinit": _qrlSync(() => {
@@ -1226,34 +1424,33 @@ Action.run() can only be called on the browser, for example when a user clicks a
1226
1424
  let form;
1227
1425
  if (input instanceof SubmitEvent) {
1228
1426
  form = input.target;
1229
- data = new FormData(form);
1230
- if ((input.submitter instanceof HTMLInputElement || input.submitter instanceof HTMLButtonElement) && input.submitter.name) {
1231
- if (input.submitter.name) data.append(input.submitter.name, input.submitter.value);
1232
- }
1427
+ data = new FormData(form, input.submitter);
1233
1428
  } else data = input;
1234
1429
  const submission = {};
1235
1430
  latestSubmission.current = submission;
1431
+ state.isRunning = true;
1236
1432
  const previousDispatch = currentAction.pendingDispatch ?? Promise.resolve();
1237
1433
  let resolveDispatch;
1238
1434
  currentAction.pendingDispatch = noSerialize(new Promise((resolve) => {
1239
1435
  resolveDispatch = resolve;
1240
1436
  }));
1241
- return previousDispatch.then(() => new Promise((resolve) => {
1437
+ return previousDispatch.then(() => new Promise((resolve, reject) => {
1242
1438
  if (data instanceof FormData) state.formData = data;
1243
1439
  state.submitted = true;
1244
- state.isRunning = true;
1245
1440
  loc.isNavigating = true;
1246
1441
  currentAction.value = {
1247
1442
  data,
1248
1443
  id,
1249
1444
  resolve: noSerialize(resolve),
1445
+ reject: noSerialize(reject),
1250
1446
  resolveDispatch: noSerialize(resolveDispatch)
1251
1447
  };
1252
1448
  runAction?.(RUN_PENDING_ACTION);
1253
- })).then(({ result, status }) => {
1449
+ })).finally(() => {
1450
+ if (latestSubmission.current === submission) state.isRunning = false;
1451
+ }).then(({ result, status }) => {
1254
1452
  const isLatestSubmission = latestSubmission.current === submission;
1255
1453
  if (isLatestSubmission) {
1256
- state.isRunning = false;
1257
1454
  state.status = status;
1258
1455
  state.value = result;
1259
1456
  }
@@ -1460,29 +1657,7 @@ function serverQrl(qrl, options) {
1460
1657
  const body = await _serialize(toSend);
1461
1658
  if (method === "GET") query += `&${QDATA_KEY}=${encodeURIComponent(body)}`;
1462
1659
  else config.body = body;
1463
- const res = await fetch(`${origin}?${QFN_KEY}=${qrlHash}${query}`, config);
1464
- const contentType = res.headers.get("Content-Type");
1465
- if (res.ok && contentType === "text/qwik-json-stream" && res.body) return (async function* () {
1466
- try {
1467
- for await (const result of deserializeStream(res.body, abortSignal)) yield result;
1468
- } finally {
1469
- if (!abortSignal?.aborted) await res.body.cancel();
1470
- }
1471
- })();
1472
- else if (contentType === "application/qwik-json") {
1473
- const str = await res.text();
1474
- const obj = await _deserialize(str);
1475
- if (res.status >= 400) throw obj;
1476
- return obj;
1477
- } else if (contentType === "application/json") {
1478
- const obj = await res.json();
1479
- if (res.status >= 400) throw obj;
1480
- return obj;
1481
- } else if (contentType === "text/plain" || contentType === "text/html") {
1482
- const str = await res.text();
1483
- if (res.status >= 400) throw str;
1484
- return str;
1485
- }
1660
+ return readServerFunctionResponse(await fetch(`${origin}?${QFN_KEY}=${qrlHash}${query}`, config), abortSignal);
1486
1661
  }
1487
1662
  }, "serverQrl_w03grD0Ag68", [
1488
1663
  fetchOptions,
@@ -1492,6 +1667,32 @@ function serverQrl(qrl, options) {
1492
1667
  qrl
1493
1668
  ]);
1494
1669
  }
1670
+ /** @internal Exported for tests */
1671
+ async function readServerFunctionResponse(res, abortSignal) {
1672
+ const contentType = res.headers.get("Content-Type")?.split(";")[0].trim().toLowerCase();
1673
+ if (res.ok && contentType === "text/qwik-json-stream" && res.body) return (async function* () {
1674
+ try {
1675
+ for await (const result of deserializeStream(res.body, abortSignal)) yield result;
1676
+ } finally {
1677
+ if (!abortSignal?.aborted) await res.body.cancel();
1678
+ }
1679
+ })();
1680
+ else if (contentType === "application/qwik-json") {
1681
+ const str = await res.text();
1682
+ const obj = await _deserialize(str);
1683
+ if (res.status >= 400) throw obj;
1684
+ return obj;
1685
+ } else if (contentType === "application/json") {
1686
+ const obj = await res.json();
1687
+ if (res.status >= 400) throw obj;
1688
+ return obj;
1689
+ } else if (contentType === "text/plain") {
1690
+ const str = await res.text();
1691
+ if (res.status >= 400) throw str;
1692
+ return str;
1693
+ }
1694
+ throw new Error(`server$ got an unexpected response: ${res.status} ${res.headers.get("Content-Type") ?? "(no Content-Type)"}`);
1695
+ }
1495
1696
  /** @public */
1496
1697
  var server$ = /*#__PURE__*/ implicit$FirstArg(serverQrl);
1497
1698
  function getValidators(rest, qrl) {
@@ -1564,23 +1765,34 @@ var _hf0_str$1 = "p0.spaReset?\"true\":undefined";
1564
1765
  /** @public */
1565
1766
  var Form = ({ action, spaReset, reloadDocument, onSubmit$, ...rest }, key) => {
1566
1767
  if (action) {
1567
- if (Array.isArray(onSubmit$)) return /*#__PURE__*/ _jsxSplit("form", {
1568
- ..._getVarProps(rest),
1569
- ..._getConstProps(rest),
1570
- action: _wrapProp(action, "actionPath"),
1571
- "preventdefault:submit": !reloadDocument,
1572
- "q-e:submit": [...onSubmit$, !reloadDocument ? /*#__PURE__*/ inlinedQrl((evt) => {
1573
- let action = _capturesObj._[0];
1574
- if (!action.submitted) return action.submit(evt);
1575
- }, "Form_form_q_e_submit_6i0Jq5q8JFg", [action]) : void 0],
1576
- ["data-spa-reset"]: spaReset ? "true" : void 0
1577
- }, { method: "post" }, null, 0, key);
1768
+ const submitHandlers = [onSubmit$].flat(Infinity);
1769
+ const firstAsyncHandler = submitHandlers.findIndex((handler) => handler && !_isSyncQrl(handler));
1770
+ const syncHandlers = firstAsyncHandler === -1 ? submitHandlers : submitHandlers.slice(0, firstAsyncHandler);
1771
+ const asyncHandlers = firstAsyncHandler === -1 ? [] : submitHandlers.slice(firstAsyncHandler);
1578
1772
  return /*#__PURE__*/ _jsxSplit("form", {
1579
1773
  ..._getVarProps(rest),
1580
1774
  ..._getConstProps(rest),
1581
1775
  action: _wrapProp(action, "actionPath"),
1582
1776
  "preventdefault:submit": !reloadDocument,
1583
- "q-e:submit": [onSubmit$, !reloadDocument ? action.submit : void 0],
1777
+ "q-e:submit": [
1778
+ !reloadDocument ? _qrlSync((event, form) => {
1779
+ form._qSubmit ??= event;
1780
+ }, "(event,form)=>{form._qSubmit??=event;}") : void 0,
1781
+ ...!reloadDocument ? syncHandlers : [],
1782
+ !reloadDocument ? /*#__PURE__*/ inlinedQrl(async (event, form) => {
1783
+ let action = _capturesObj._[0], asyncHandlers = _capturesObj._[1];
1784
+ if (form._qSubmit !== event) return;
1785
+ try {
1786
+ for (const handler of asyncHandlers) await handler?.(event, form);
1787
+ await action.submit(event);
1788
+ } finally {
1789
+ delete form._qSubmit;
1790
+ }
1791
+ }, "Form_form_q_e_submit_6i0Jq5q8JFg", [action, asyncHandlers]) : onSubmit$,
1792
+ !reloadDocument ? _qrlSync((event, form) => {
1793
+ if (form._qSubmit === event) delete form._qSubmit;
1794
+ }, "(event,form)=>{if(form._qSubmit===event){delete form._qSubmit;}}") : void 0
1795
+ ],
1584
1796
  ["data-spa-reset"]: spaReset ? "true" : void 0
1585
1797
  }, { method: "post" }, null, 0, key);
1586
1798
  } else return /*#__PURE__*/ _jsxSplit(GetForm, {
@@ -1603,9 +1815,9 @@ var GetForm = /*#__PURE__*/ componentQrl(/*#__PURE__*/ inlinedQrl((_rawProps) =>
1603
1815
  ..._getVarProps(rest),
1604
1816
  "q-e:submit": [
1605
1817
  ...Array.isArray(_rawProps.onSubmit$) ? _rawProps.onSubmit$ : [_rawProps.onSubmit$],
1606
- /*#__PURE__*/ inlinedQrl(async (_evt, form) => {
1818
+ /*#__PURE__*/ inlinedQrl(async (evt, form) => {
1607
1819
  let nav = _capturesObj._[0];
1608
- const formData = new FormData(form);
1820
+ const formData = new FormData(form, evt.submitter);
1609
1821
  const params = new URLSearchParams();
1610
1822
  formData.forEach((value, key) => {
1611
1823
  if (typeof value === "string") params.append(key, value);