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

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.
@@ -29,7 +29,7 @@ export declare interface NetlifyEdgeAdapterOptions extends ServerAdapterOptions
29
29
  * - /build/*
30
30
  * - /favicon.ico
31
31
  * - /robots.txt
32
- * - /mainifest.json
32
+ * - /manifest.json
33
33
  * - /~partytown/*
34
34
  * - /service-worker.js
35
35
  * - /sitemap.xml
@@ -31,7 +31,7 @@ function netlifyEdgeAdapter(opts = {}) {
31
31
  const excludedPath = [];
32
32
  if (typeof opts.excludedPath === "string") excludedPath.push(opts.excludedPath);
33
33
  else if (Array.isArray(opts.excludedPath)) excludedPath.push(...opts.excludedPath);
34
- else excludedPath.push("/build/*", "/favicon.ico", "/robots.txt", "/mainifest.json", "/~partytown/*", "/service-worker.js", "/sitemap.xml");
34
+ else excludedPath.push("/build/*", "/favicon.ico", "/robots.txt", "/manifest.json", "/~partytown/*", "/service-worker.js", "/sitemap.xml");
35
35
  const netlifyEdgeManifest = {
36
36
  functions: [{
37
37
  path: basePathname + "*",
@@ -1,9 +1,9 @@
1
1
  import { t as ensureSlash } from "./pathname.mjs";
2
2
  import { o as getLoaderName } from "./request-path.mjs";
3
3
  import { i as RedirectMessage, n as throwIfControlFlowSignal, t as ServerError } from "./server-error.mjs";
4
- import { r as unescapeStaticTrieKey, t as escapeStaticTrieKey } from "./route-trie-key.mjs";
4
+ import { n as isStaticTrieKey, r as unescapeStaticTrieKey, t as escapeStaticTrieKey } from "./route-trie-key.mjs";
5
5
  import { _capturesObj, createComputedQrl, createContextId, implicit$FirstArg, inlinedQrl, isBrowser, isDev, isServer, untrack, useServerData, withLocale } from "@qwik.dev/core";
6
- import { SerializerSymbol, _UNINITIALIZED, _deserialize, _getAsyncLocalStorage, _injectAsyncSignalValue, _markSignalAsExternallyOwned, _qwikSymbol, _registerSingleton, _resolveContextWithoutSequentialScope, _verifySerializable } from "@qwik.dev/core/internal";
6
+ import { SerializerSymbol, _deserialize, _getAsyncLocalStorage, _injectAsyncSignalValue, _markSignalAsExternallyOwned, _qwikSymbol, _registerSingleton, _resolveContextWithoutSequentialScope, _verifySerializable } from "@qwik.dev/core/internal";
7
7
  import { isServer as isServer$1 } from "@qwik.dev/core/build";
8
8
  var createRequestStore = () => {
9
9
  const AsyncLocalStorage = _getAsyncLocalStorage();
@@ -37,8 +37,40 @@ var DocumentHeadContext = /*#__PURE__*/ createContextId("qr-h");
37
37
  var RouteLocationContext = /*#__PURE__*/ createContextId("qr-l");
38
38
  var RouteNavigateContext = /*#__PURE__*/ createContextId("qr-n");
39
39
  var RouteActionContext = /*#__PURE__*/ createContextId("qr-a");
40
- var RoutePreventNavigateContext = /*#__PURE__*/ createContextId("qr-p");
40
+ var RouteActionRunnerContext = /*#__PURE__*/ createContextId("qr-ar");
41
41
  var HttpStatusContext = /*#__PURE__*/ createContextId("qr-hs");
42
+ /** Passed to the router's navigate function to run the action set on the action context. */
43
+ var RUN_PENDING_ACTION = Symbol();
44
+ /** Passed to the router's navigate function to re-resolve the document head. */
45
+ var REFRESH_HEAD = Symbol();
46
+ var preventNav = {};
47
+ var internalState = {
48
+ navCount: 0,
49
+ attemptCount: 0
50
+ };
51
+ var registerPreventNav = (fn$) => {
52
+ if (!isBrowser) return;
53
+ preventNav.$handler$ ||= (event) => {
54
+ internalState.attemptCount++;
55
+ if (!preventNav.$cbs$) return;
56
+ if ([...preventNav.$cbs$.values()].map((cb) => cb.resolved ? cb.resolved() : cb()).some(Boolean)) {
57
+ event.preventDefault();
58
+ event.returnValue = true;
59
+ }
60
+ };
61
+ (preventNav.$cbs$ ||= /* @__PURE__ */ new Set()).add(fn$);
62
+ fn$.resolve();
63
+ window.addEventListener("beforeunload", preventNav.$handler$);
64
+ return () => {
65
+ if (preventNav.$cbs$) {
66
+ preventNav.$cbs$.delete(fn$);
67
+ if (!preventNav.$cbs$.size) {
68
+ preventNav.$cbs$ = void 0;
69
+ window.removeEventListener("beforeunload", preventNav.$handler$);
70
+ }
71
+ }
72
+ };
73
+ };
42
74
  var holder = {};
43
75
  /** The config this router copy holds, else the one of the app serving the current request. */
44
76
  var findRouterConfig = () => holder.config ?? getServingRouterConfig();
@@ -113,7 +145,6 @@ var REQUEST_ROUTE_LOADERS = "@routeLoaders";
113
145
  var REQUEST_ROUTE_LOADER_PROMISES = "@routeLoaderPromises";
114
146
  var REQUEST_ROUTE_LOADER_EVENTS = "@routeLoaderEvents";
115
147
  var REQUEST_ROUTE_LOADER_ROOT_EVENT = "@routeLoaderRootEvent";
116
- var ROUTE_LOADER_VALUE_PREFIX = "__qwik_route_loader_value__";
117
148
  /** Header name sent by client to tell the server the actual page URL for loader requests. */
118
149
  var FULLPATH_HEADER = "X-Qwik-fullpath";
119
150
  /** Dev route hint that preserves the loader URL. */
@@ -124,6 +155,8 @@ var ROUTE_PATH_HEADER = "X-Qwik-route-path";
124
155
  * across navigations the browser HTTP cache is the freshness authority.
125
156
  */
126
157
  var navFetchCache = /* @__PURE__ */ new Map();
158
+ /** Entries a loader signal already used: they only dedupe prefetches, so `invalidate()` refetches. */
159
+ var signalFetches = /* @__PURE__ */ new WeakSet();
127
160
  var clearNavFetchCache = () => {
128
161
  navFetchCache = /* @__PURE__ */ new Map();
129
162
  };
@@ -176,7 +209,6 @@ function assertCurrentLoaderRequest(ctx, signal, request, abortSignal) {
176
209
  abortSignal.throwIfAborted();
177
210
  if (!request.active || clientRouteLoaders.get(ctx)?.current.requests.get(signal) !== request) throw new DOMException(isDev ? "Route loader navigation was superseded" : "", "AbortError");
178
211
  }
179
- var getRouteLoaderValueStateKey = (loaderId) => `${ROUTE_LOADER_VALUE_PREFIX}${loaderId}`;
180
212
  var ServerRouteLoaderCapture = class {
181
213
  hash;
182
214
  qrl;
@@ -227,7 +259,12 @@ var fetchRouteLoaderData = async (loaderId, routePath, manifestHash, opts) => {
227
259
  const cache = navFetchCache;
228
260
  if (!opts?.ignoreCache) {
229
261
  const entry = cache.get(cacheKey);
230
- if (entry) return opts?.signal ? wrapWithAbort(entry, opts.signal) : entry;
262
+ const signal = opts?.signal;
263
+ if (entry && !signal) return entry;
264
+ if (entry && signal && !signalFetches.has(entry)) {
265
+ signalFetches.add(entry);
266
+ return wrapWithAbort(entry, signal);
267
+ }
231
268
  }
232
269
  const request = async () => {
233
270
  opts?.signal?.throwIfAborted();
@@ -250,7 +287,11 @@ var fetchRouteLoaderData = async (loaderId, routePath, manifestHash, opts) => {
250
287
  if (opts?.ignoreCache) return request();
251
288
  if (opts?.signal) return request().then((value) => {
252
289
  opts.signal.throwIfAborted();
253
- if (value !== void 0 && !cache.has(cacheKey)) cache.set(cacheKey, Promise.resolve(value));
290
+ if (value !== void 0 && !cache.has(cacheKey)) {
291
+ const settled = Promise.resolve(value);
292
+ signalFetches.add(settled);
293
+ cache.set(cacheKey, settled);
294
+ }
254
295
  return value;
255
296
  });
256
297
  const promise = request().then((value) => {
@@ -263,34 +304,31 @@ var fetchRouteLoaderData = async (loaderId, routePath, manifestHash, opts) => {
263
304
  cache.set(cacheKey, promise);
264
305
  return promise;
265
306
  };
307
+ var retainLoaderValue = (previous, abortSignal) => {
308
+ if (previous !== void 0) return previous;
309
+ return new Promise((_, reject) => {
310
+ abortSignal.throwIfAborted();
311
+ abortSignal.addEventListener("abort", () => reject(abortSignal.reason), { once: true });
312
+ });
313
+ };
266
314
  var createRouteLoaderSignal = (loader, routeLoaderCtx, state, requestEv3) => {
267
315
  const id = loader.__id;
268
- const stateValues = state;
269
- const resumeValueKey = getRouteLoaderValueStateKey(id);
270
316
  const capture = isServer ? new ServerRouteLoaderCapture(id, loader.__qrl, loader.__validators, loader.__blockSSR, requestEv3 ?? useServerData("qwikrouter")?.ev) : id;
271
317
  const searchFilter = loader.__search;
272
318
  const loaderHash = isDev ? loader.__qrl.getHash() : id;
273
319
  const signal = createComputedQrl(/*#__PURE__*/ inlinedQrl(async (ctx) => {
274
- let capture = _capturesObj._[0], id = _capturesObj._[1], lastFetch = _capturesObj._[2], loaderHash = _capturesObj._[3], resumeValueKey = _capturesObj._[4], routeLoaderCtx = _capturesObj._[5], searchFilter = _capturesObj._[6], state = _capturesObj._[7], stateValues = _capturesObj._[8];
320
+ let capture = _capturesObj._[0], id = _capturesObj._[1], lastFetch = _capturesObj._[2], loaderHash = _capturesObj._[3], routeLoaderCtx = _capturesObj._[4], searchFilter = _capturesObj._[5], state = _capturesObj._[6];
275
321
  if (!!ctx.info && typeof ctx.info === "object" && "__v" in ctx.info) {
276
322
  const value = ctx.info.__v;
277
- if (!isServer && resumeValueKey in stateValues) stateValues[resumeValueKey] = value;
278
323
  lastFetch.raw = void 0;
279
324
  return value;
280
325
  }
281
326
  if (isServer) return capture.load();
282
327
  const request = getLoaderRequest(routeLoaderCtx, state, id, loaderHash);
283
- if (!request.active) {
284
- if (ctx.previous === void 0) return new Promise((_, reject) => {
285
- ctx.abortSignal.throwIfAborted();
286
- ctx.abortSignal.addEventListener("abort", () => reject(ctx.abortSignal.reason), { once: true });
287
- });
288
- return ctx.previous;
289
- }
328
+ if (!request.active) return retainLoaderValue(ctx.previous, ctx.abortSignal);
290
329
  const pageUrl = new URL(request.pageUrl);
291
330
  const mHash = untrack(() => routeLoaderCtx.manifestHash) || "dev";
292
331
  const basePath = getBasePathname();
293
- const needsResumeFetch = stateValues[resumeValueKey] === _UNINITIALIZED;
294
332
  let fetchUrl = pageUrl;
295
333
  if (searchFilter) {
296
334
  fetchUrl = new URL(pageUrl.href);
@@ -316,22 +354,21 @@ var createRouteLoaderSignal = (loader, routeLoaderCtx, state, requestEv3) => {
316
354
  const goto = routeLoaderCtx.goto;
317
355
  if (goto) goto(response.r, { replaceState: true });
318
356
  else location.href = response.r;
319
- return ctx.previous;
357
+ return retainLoaderValue(ctx.previous, ctx.abortSignal);
320
358
  }
321
359
  if (response.e) throw response.e;
322
360
  lastFetch.raw = result.raw;
323
- if (needsResumeFetch) stateValues[resumeValueKey] = response.d;
361
+ const onValue = routeLoaderCtx.onValue;
362
+ if (onValue) Promise.resolve().then(() => state[id].promise()).then(() => onValue(REFRESH_HEAD));
324
363
  return response.d;
325
364
  }, "createRouteLoaderSignal_signal_createComputed_4s4ZDCYhDOA", [
326
365
  capture,
327
366
  id,
328
367
  {},
329
368
  loaderHash,
330
- resumeValueKey,
331
369
  routeLoaderCtx,
332
370
  searchFilter,
333
- state,
334
- stateValues
371
+ state
335
372
  ]), { serializationStrategy: loader.__serializationStrategy });
336
373
  _markSignalAsExternallyOwned(signal);
337
374
  return signal;
@@ -491,9 +528,7 @@ function prepareRouteLoaders(mods, state, ctx, paths, pageUrl, previousUrl, navC
491
528
  const client = getClientRouteLoaders(ctx, previousUrl.href);
492
529
  if (navigationKey && client.navigationKey === navigationKey) return ensureRouteLoaderSignals(mods, state, ctx);
493
530
  const previous = client.current;
494
- if (client.navCount === void 0) {
495
- for (const id in state) if (!id.startsWith(ROUTE_LOADER_VALUE_PREFIX)) getLoaderRequest(ctx, state, id, id);
496
- }
531
+ if (client.navCount === void 0) for (const id in state) getLoaderRequest(ctx, state, id, id);
497
532
  client.navCount = navCount;
498
533
  client.navigationKey = navigationKey;
499
534
  const current = client.current = {
@@ -508,7 +543,6 @@ function prepareRouteLoaders(mods, state, ctx, paths, pageUrl, previousUrl, navC
508
543
  current.paths[loader.__id] ||= current.paths[loader.__qrl.getHash()] || pageUrl.pathname;
509
544
  }
510
545
  for (const id in state) {
511
- if (id.startsWith(ROUTE_LOADER_VALUE_PREFIX)) continue;
512
546
  const signal = state[id];
513
547
  const old = previous.requests.get(signal);
514
548
  const loader = routeLoaders.get(id);
@@ -539,7 +573,6 @@ function pruneRouteLoaders(state, ctx) {
539
573
  const { requests } = clientRouteLoaders.get(ctx).current;
540
574
  const paths = {};
541
575
  for (const id in state) {
542
- if (id.startsWith(ROUTE_LOADER_VALUE_PREFIX)) continue;
543
576
  const signal = state[id];
544
577
  const request = requests.get(signal);
545
578
  if (request?.active) paths[id] = request.routePath;
@@ -547,7 +580,6 @@ function pruneRouteLoaders(state, ctx) {
547
580
  signal.$dispose();
548
581
  requests.delete(signal);
549
582
  delete state[id];
550
- delete state[getRouteLoaderValueStateKey(id)];
551
583
  }
552
584
  }
553
585
  ctx.loaderPaths = paths;
@@ -568,7 +600,6 @@ function restoreRouteLoaders(state, ctx, navCount) {
568
600
  }
569
601
  var ensureRouteLoaderSignal = (loader, state, routeLoaderCtx, requestEv12) => {
570
602
  if (loader.__cacheControl === "immutable") immutableLoaderIds.add(loader.__id);
571
- if (isServer && loader.__serializationStrategy === "never") state[getRouteLoaderValueStateKey(loader.__id)] = _UNINITIALIZED;
572
603
  return state[loader.__id] ||= createRouteLoaderSignal(loader, routeLoaderCtx, state, requestEv12);
573
604
  };
574
605
  var ensureRouteLoaderSignals = (mods, state, routeLoaderCtx, requestEv13) => {
@@ -630,22 +661,27 @@ var getLoaderRequestEvent = (loader, requestEv16) => {
630
661
  const url = new URL(rootRequestEv.url);
631
662
  const pathname = globalThis.__STRICT_LOADERS__ ? getRouteLoaderCtx(rootRequestEv).loaderPaths[loader.__id] || rootRequestEv.url.pathname : rootRequestEv.url.pathname;
632
663
  const filteredSearch = loader.__search ? filterSearchParams(url.searchParams, loader.__search) : rootRequestEv.url.search;
633
- if (pathname === rootRequestEv.url.pathname && filteredSearch === rootRequestEv.url.search) return rootRequestEv;
634
- const params = pathname === rootRequestEv.url.pathname ? rootRequestEv.params : getRouteLoaderParams(rootRequestEv)[loader.__id] || {};
664
+ const isSameUrl = pathname === rootRequestEv.url.pathname && filteredSearch === rootRequestEv.url.search;
665
+ const params = globalThis.__STRICT_LOADERS__ ? getRouteLoaderParams(rootRequestEv)[loader.__id] ?? (pathname === rootRequestEv.url.pathname ? rootRequestEv.params : {}) : rootRequestEv.params;
666
+ if (isSameUrl && params === rootRequestEv.params) return rootRequestEv;
635
667
  let events = rootRequestEv.sharedMap.get(REQUEST_ROUTE_LOADER_EVENTS);
636
668
  if (!events) {
637
669
  events = /* @__PURE__ */ new Map();
638
670
  rootRequestEv.sharedMap.set(REQUEST_ROUTE_LOADER_EVENTS, events);
639
671
  }
640
- const eventKey = `${pathname}\n${filteredSearch}`;
672
+ const eventKey = `${pathname}\n${filteredSearch}\n${params === rootRequestEv.params ? "" : loader.__id}`;
641
673
  let loaderRequestEv = events.get(eventKey);
642
674
  if (!loaderRequestEv) {
643
675
  url.pathname = pathname;
644
676
  url.search = filteredSearch;
645
- const request = new Request(url, rootRequestEv.request);
677
+ const request = new Request(url, {
678
+ method: rootRequestEv.request.method,
679
+ headers: rootRequestEv.request.headers,
680
+ signal: rootRequestEv.request.signal
681
+ });
646
682
  loaderRequestEv = Object.create(rootRequestEv, {
647
683
  originalUrl: {
648
- value: new URL(url),
684
+ value: isSameUrl ? rootRequestEv.originalUrl : new URL(url),
649
685
  enumerable: true
650
686
  },
651
687
  params: {
@@ -834,6 +870,18 @@ var deepFreeze = (obj) => {
834
870
  var MODULE_CACHE = /*#__PURE__*/ new WeakMap();
835
871
  var loadRoute = async (routes, cacheModules, pathname) => {
836
872
  const { loaders, params, routeParts, notFound, routeBundleNames, loaderPathsByHash, loaderParamsByHash, menuLoader, errorLoader } = matchRouteTree(routes, pathname);
873
+ const loaderEndpoints = /* @__PURE__ */ new Map();
874
+ const pagePath = ensureSlash(pathname);
875
+ for (const hash in loaderPathsByHash) {
876
+ const loaderPath = loaderPathsByHash[hash];
877
+ if (loaderPath === pagePath) continue;
878
+ let endpoint = loaderEndpoints.get(loaderPath);
879
+ if (!endpoint) {
880
+ endpoint = matchRouteTree(routes, loaderPath);
881
+ loaderEndpoints.set(loaderPath, endpoint);
882
+ }
883
+ if (!endpoint.notFound && !endpoint.loaderPathsByHash?.[hash]) loaderPathsByHash[hash] = pagePath;
884
+ }
837
885
  const routeName = "/" + routeParts.join("/");
838
886
  const modules = new Array(loaders.length);
839
887
  const pendingLoads = [];
@@ -1066,6 +1114,34 @@ function matchRestNode(node, parts, partIndex) {
1066
1114
  };
1067
1115
  }
1068
1116
  }
1117
+ /** Whether a `[...rest]` node has route segments below it, e.g. `[...path]/product/[id]`. */
1118
+ function hasChildSegments(node) {
1119
+ for (const key in node) if (key === "_W" || key === "_A" || key === "_M" || isStaticTrieKey(key)) return true;
1120
+ return false;
1121
+ }
1122
+ /**
1123
+ * Partial matches of a node's `[...rest]` child that leave segments for the routes below it, so
1124
+ * `[...path]/product/[id]` matches `/a/b/product/1` (path `a/b`) and `/product/1` (path empty). The
1125
+ * longest rest comes first, like a greedy `(.*)`. Without child segments there is nothing to leave
1126
+ * room for and `matchRestNode` alone applies.
1127
+ */
1128
+ function matchRestSpans(node, parts, partIndex) {
1129
+ const next = node._A;
1130
+ if (!next || !hasChildSegments(next)) return [];
1131
+ const paramName = next._P;
1132
+ const spans = [];
1133
+ for (let span = parts.length - partIndex - 1; span >= 0; span--) spans.push({
1134
+ next,
1135
+ groups: [],
1136
+ routePart: `[...${paramName}]`,
1137
+ done: false,
1138
+ kind: ChildMatchKind.Rest,
1139
+ paramName,
1140
+ paramValue: parts.slice(partIndex, partIndex + span).join("/"),
1141
+ span
1142
+ });
1143
+ return spans;
1144
+ }
1069
1145
  /**
1070
1146
  * Every child of `node` that could match `partLower`, in the same priority order `findChild` walks:
1071
1147
  * exact match → `_M` groups (recursively) → `_W` wildcard → `_A` rest wildcard.
@@ -1099,6 +1175,7 @@ function findChildAll(node, part, partLower, parts, partIndex) {
1099
1175
  ...wildcard,
1100
1176
  groups: []
1101
1177
  });
1178
+ candidates.push(...matchRestSpans(node, parts, partIndex));
1102
1179
  const rest = matchRestNode(node, parts, partIndex);
1103
1180
  if (rest) candidates.push({
1104
1181
  ...rest,
@@ -1116,6 +1193,7 @@ function findChildAll(node, part, partLower, parts, partIndex) {
1116
1193
  */
1117
1194
  function findMatchChain(node, parts, i, toBeat) {
1118
1195
  if (i === parts.length) return !toBeat && (findIndexNode(node) || findRestNode(node)) ? [] : void 0;
1196
+ if (toBeat && toBeat.length === 0) return;
1119
1197
  const part = parts[i];
1120
1198
  const candidates = findChildAll(node, part, part.toLowerCase(), parts, i).sort((a, b) => a.kind - b.kind);
1121
1199
  let best;
@@ -1124,12 +1202,12 @@ function findMatchChain(node, parts, i, toBeat) {
1124
1202
  const bound = best ?? toBeat;
1125
1203
  if (bound && found.kind > bound[0].kind) break;
1126
1204
  const tailToBeat = bound && found.kind === bound[0].kind ? bound.slice(1) : void 0;
1127
- const tail = found.done ? matchRestTail(found.next, tailToBeat) : findMatchChain(found.next, parts, i + 1, tailToBeat);
1205
+ const tail = found.done ? matchRestTail(found.next, tailToBeat) : findMatchChain(found.next, parts, i + (found.span ?? 1), tailToBeat);
1128
1206
  if (tail) best = [found, ...tail];
1129
1207
  }
1130
1208
  return best;
1131
1209
  }
1132
- /** A `[...rest]` match ends the chain; it only counts when it has a page and beats the bound. */
1210
+ /** A full `[...rest]` match ends the chain; it only counts when it has a page and beats the bound. */
1133
1211
  function matchRestTail(restNode, toBeat) {
1134
1212
  return !toBeat && isRouteNode(restNode) ? [] : void 0;
1135
1213
  }
@@ -1229,15 +1307,17 @@ function matchRouteTree(root = {}, pathname) {
1229
1307
  });
1230
1308
  let done = false;
1231
1309
  let matched = true;
1232
- const parts = pathname.split("/").filter((p) => p.length > 0).map(decodeURIComponent);
1310
+ const encodedParts = pathname.split("/").filter((p) => p.length > 0);
1311
+ const parts = encodedParts.map(decodeURIComponent);
1233
1312
  let restFallback;
1234
1313
  let i = 0;
1235
1314
  const len = parts.length;
1236
1315
  const chain = findMatchChain(root, parts, 0);
1237
- for (; !done && i < len; i++) {
1316
+ let chainIndex = 0;
1317
+ while (!done && i < len) {
1238
1318
  const part = parts[i];
1239
1319
  const partLower = part.toLowerCase();
1240
- const found = chain ? chain[i] : findChild(node, part, partLower, parts, i);
1320
+ const found = chain ? chain[chainIndex++] : findChild(node, part, partLower, parts, i);
1241
1321
  if (!found) {
1242
1322
  matched = false;
1243
1323
  break;
@@ -1263,12 +1343,15 @@ function matchRouteTree(root = {}, pathname) {
1263
1343
  routeParts.push(found.routePart);
1264
1344
  done = found.done;
1265
1345
  node = found.next;
1266
- const matchedPathname = `/${parts.slice(0, found.done ? len : i + 1).join("/")}/`;
1346
+ const span = found.span ?? 1;
1347
+ const matchedParts = encodedParts.slice(0, found.done ? len : i + span);
1348
+ const matchedPathname = matchedParts.length ? `/${matchedParts.join("/")}/` : "/";
1267
1349
  collectNodeMeta(node, found.groups, layouts, errorLoaderRef, notFoundLoaderRef, menuLoaderRef, loaderPathsByHash, matchedPathname, loaderParamsByHash, { ...params });
1268
1350
  if (node._M) groupNodes.push({
1269
1351
  node,
1270
1352
  depth: layouts.length
1271
1353
  });
1354
+ i += span;
1272
1355
  }
1273
1356
  if (matched && !done && i === len) {
1274
1357
  if (!node._I && node._G == null) {
@@ -1567,4 +1650,4 @@ var createDocumentHead = (defaults, manifestHash) => ({
1567
1650
  frontmatter: { ...defaults?.frontmatter },
1568
1651
  manifestHash: manifestHash || "dev"
1569
1652
  });
1570
- export { RoutePreventNavigateContext as $, loadRouteLoader as A, _setRouterConfig as B, getRequestEvent as C, getRouteLoaderValues as D, getRouteLoaderResponse as E, routeLoader$ as F, ContentContext as G, getRouterConfig as H, routeLoaderQrl as I, HttpStatusContext as J, ContentInternalContext as K, setLoaderSignalValue as L, prepareRouteLoaders as M, resolveRouteLoaderByHash as N, getRouteLoaders as O, restoreRouteLoaders as P, RouteNavigateContext as Q, setRouteLoaders as R, getModuleRouteLoaders as S, getRouteLoaderParams as T, getRoutes as U, getBasePathname as V, getTrailingSlash as W, RouteLoaderCtxContext as X, RouteActionContext as Y, RouteLocationContext as Z, commitRouteLoaders as _, isPromise as a, RequestEvRouterConfig as at, getClientRouteLoaders as b, shouldPreload as c, loadRoute as d, RouteStateContext as et, FULLPATH_HEADER as f, clearRouteLoaderData as g, clearNavFetchCache as h, getClientNavPath as i, Q_ROUTE as it, matchesRouteLoaderId as j, isImmutableLoader as k, toPath as l, abortRouteLoaderNavigation as m, resolveHead as n, QDATA_KEY as nt, isSameOrigin as o, _asyncRequestStore as ot, ROUTE_PATH_HEADER as p, DocumentHeadContext as q, resolveRouteConfig as r, QFN_KEY as rt, isSamePath as s, createDocumentHead as t, QACTION_KEY as tt, toUrl as u, ensureRouteLoaderSignals as v, getRouteLoaderCtx as w, getLoaderRequestEvent as x, fetchRouteLoaderData as y, _getServiceWorkerUrl as z };
1653
+ export { ContentInternalContext as $, isImmutableLoader as A, _getServiceWorkerUrl as B, getModuleRouteLoaders as C, getRouteLoaderResponse as D, getRouteLoaderParams as E, restoreRouteLoaders as F, getRoutes as G, findRouterConfig as H, routeLoader$ as I, RUN_PENDING_ACTION as J, getTrailingSlash as K, routeLoaderQrl as L, matchesRouteLoaderId as M, prepareRouteLoaders as N, getRouteLoaderValues as O, resolveRouteLoaderByHash as P, ContentContext as Q, setLoaderSignalValue as R, getLoaderRequestEvent as S, getRouteLoaderCtx as T, getBasePathname as U, _setRouterConfig as V, getRouterConfig as W, preventNav as X, internalState as Y, registerPreventNav as Z, clearRouteLoaderData as _, isPromise as a, RouteLocationContext as at, fetchRouteLoaderData as b, shouldPreload as c, QACTION_KEY as ct, loadRoute as d, Q_ROUTE as dt, DocumentHeadContext as et, matchRouteTree as f, RequestEvRouterConfig as ft, clearNavFetchCache as g, abortRouteLoaderNavigation as h, getClientNavPath as i, RouteLoaderCtxContext as it, loadRouteLoader as j, getRouteLoaders as k, toPath as l, QDATA_KEY as lt, ROUTE_PATH_HEADER as m, resolveHead as n, RouteActionContext as nt, isSameOrigin as o, RouteNavigateContext as ot, FULLPATH_HEADER as p, _asyncRequestStore as pt, REFRESH_HEAD as q, resolveRouteConfig as r, RouteActionRunnerContext as rt, isSamePath as s, RouteStateContext as st, createDocumentHead as t, HttpStatusContext as tt, toUrl as u, QFN_KEY as ut, commitRouteLoaders as v, getRequestEvent as w, getClientRouteLoaders as x, ensureRouteLoaderSignals as y, setRouteLoaders as z };
@@ -1,5 +1,5 @@
1
1
  import { t as ensureSlash } from "./pathname.mjs";
2
- import { A as loadRouteLoader, D as getRouteLoaderValues, E as getRouteLoaderResponse, N as resolveRouteLoaderByHash, R as setRouteLoaders, T as getRouteLoaderParams, a as isPromise, at as RequestEvRouterConfig, f as FULLPATH_HEADER, g as clearRouteLoaderData, it as Q_ROUTE, j as matchesRouteLoaderId, nt as QDATA_KEY, ot as _asyncRequestStore, r as resolveRouteConfig, rt as QFN_KEY, tt as QACTION_KEY, w as getRouteLoaderCtx, x as getLoaderRequestEvent } from "./head.qwik.mjs";
2
+ import { D as getRouteLoaderResponse, E as getRouteLoaderParams, M as matchesRouteLoaderId, O as getRouteLoaderValues, P as resolveRouteLoaderByHash, S as getLoaderRequestEvent, T as getRouteLoaderCtx, _ as clearRouteLoaderData, a as isPromise, ct as QACTION_KEY, dt as Q_ROUTE, ft as RequestEvRouterConfig, j as loadRouteLoader, lt as QDATA_KEY, p as FULLPATH_HEADER, pt as _asyncRequestStore, r as resolveRouteConfig, ut as QFN_KEY, z as setRouteLoaders } from "./head.qwik.mjs";
3
3
  import { a as QLoaderId, c as resolveValidInternalFullPathname, i as QActionId, s as recognizeRequest, t as IsQAction, u as trimRecognizedInternalPathname } from "./request-path.mjs";
4
4
  import { a as shareClassIdentity, i as RedirectMessage, n as throwIfControlFlowSignal, r as AbortMessage, t as ServerError } from "./server-error.mjs";
5
5
  import { inlinedQrl, isDev } from "@qwik.dev/core";
@@ -79,14 +79,14 @@ function createCacheControl(cacheControl) {
79
79
  sMaxAge: cacheControl
80
80
  };
81
81
  if (cacheControl.immutable) controls.push("immutable");
82
- if (cacheControl.maxAge) controls.push(`max-age=${cacheControl.maxAge}`);
83
- if (cacheControl.sMaxAge) controls.push(`s-maxage=${cacheControl.sMaxAge}`);
82
+ if (cacheControl.maxAge !== void 0) controls.push(`max-age=${cacheControl.maxAge}`);
83
+ if (cacheControl.sMaxAge !== void 0) controls.push(`s-maxage=${cacheControl.sMaxAge}`);
84
84
  if (cacheControl.noStore) controls.push("no-store");
85
85
  if (cacheControl.noCache) controls.push("no-cache");
86
86
  if (cacheControl.private) controls.push("private");
87
87
  if (cacheControl.public) controls.push("public");
88
- if (cacheControl.staleWhileRevalidate) controls.push(`stale-while-revalidate=${cacheControl.staleWhileRevalidate}`);
89
- if (cacheControl.staleIfError) controls.push(`stale-if-error=${cacheControl.staleIfError}`);
88
+ if (cacheControl.staleWhileRevalidate !== void 0) controls.push(`stale-while-revalidate=${cacheControl.staleWhileRevalidate}`);
89
+ if (cacheControl.staleIfError !== void 0) controls.push(`stale-if-error=${cacheControl.staleIfError}`);
90
90
  return controls.join(", ");
91
91
  }
92
92
  var SAMESITE = {
@@ -352,7 +352,9 @@ function createRequestEvent(serverRequestEv, loadedRoute, requestHandlers, baseP
352
352
  exit,
353
353
  cacheControl: (cacheControl, target = "Cache-Control") => {
354
354
  check();
355
- headers.set(target, createCacheControl(cacheControl));
355
+ const directives = createCacheControl(cacheControl);
356
+ if (!directives) return;
357
+ headers.set(target, directives);
356
358
  },
357
359
  resolveValue: (async (loaderOrAction) => {
358
360
  if (loaderOrAction.__brand === "server_loader") {
@@ -536,6 +538,7 @@ var formToObj = (formData) => {
536
538
  const childNode = pathNode.children.get(key);
537
539
  const nextValue = object[key];
538
540
  if (nextValue !== void 0) {
541
+ if (!Array.isArray(nextValue) && Object.getPrototypeOf(nextValue) !== null) break;
539
542
  object = nextValue;
540
543
  pathNode = childNode;
541
544
  continue;
@@ -596,13 +599,15 @@ function resolveCacheKey(cacheKeyExport, defaultKey, requestEv, eTag) {
596
599
  /** Build the default SSR cache key. eTag slot is dropped when no eTag was resolved. */
597
600
  function defaultSsrCacheKey(requestEv, eTag) {
598
601
  const status = requestEv.status();
599
- const pathname = requestEv.originalUrl.pathname;
600
- return eTag ? `${status}|${eTag}|${pathname}` : `${status}|${pathname}`;
602
+ const { origin, pathname } = requestEv.originalUrl;
603
+ const url = origin + pathname;
604
+ return eTag ? `${status}|${eTag}|${url}` : `${status}|${url}`;
601
605
  }
602
606
  /** Build the default loader cache key. eTag slot is dropped when no eTag was resolved. */
603
607
  function defaultLoaderCacheKey(requestEv, eTag) {
604
608
  const loaderId = requestEv.sharedMap.get(QLoaderId);
605
- const base = `${requestEv.url.pathname}|${requestEv.url.search}|${loaderId}`;
609
+ const { origin, pathname, search } = requestEv.url;
610
+ const base = `${origin}${pathname}|${search}|${loaderId}`;
606
611
  return eTag ? `${base}|${eTag}` : base;
607
612
  }
608
613
  /** Get a cached SSR entry by key (LRU touch). */
@@ -669,7 +674,7 @@ function loaderHandler(routeLoaders, route) {
669
674
  return;
670
675
  }
671
676
  setRouteLoaderData(requestEv, routeLoaders, route);
672
- await runBlockingLoadersBeforeTarget(routeLoaders, loader, requestEv);
677
+ await runRouteGuards(routeLoaders, loader, requestEv);
673
678
  const loaderRequestEv = createLoaderRequestEventFactory(requestEv)(loader);
674
679
  const cacheControl = resolveLoaderCacheControl(loader.__cacheControl, loaderRequestEv);
675
680
  const applyCacheControl = () => {
@@ -699,6 +704,7 @@ function loaderHandler(routeLoaders, route) {
699
704
  body: data
700
705
  });
701
706
  if (!normalizedETag && finalETag && performETagMatch(loaderRequestEv, finalETag, applyCacheControl)) return;
707
+ if (responseData.e || failed) requestEv.headers.set("Cache-Control", "no-store");
702
708
  await sendLoaderResponse(requestEv, data, cacheControl);
703
709
  };
704
710
  }
@@ -710,11 +716,9 @@ function resolveLoaderCacheControl(option, requestEv) {
710
716
  const value = typeof option === "function" ? option(requestEv) : option;
711
717
  return value === void 0 ? "private" : value;
712
718
  }
713
- async function runBlockingLoadersBeforeTarget(routeLoaders, targetLoader, requestEv) {
714
- for (const loader of routeLoaders) {
715
- if (loader === targetLoader) return;
716
- if (loader.__blockSSR) await loadRouteLoader(loader, requestEv);
717
- }
719
+ /** Blocking loaders guard the route, so they all run whatever the export order. */
720
+ async function runRouteGuards(routeLoaders, targetLoader, requestEv) {
721
+ for (const loader of routeLoaders) if (loader !== targetLoader && loader.__blockSSR) await loadRouteLoader(loader, requestEv);
718
722
  }
719
723
  function setRouteLoaderData(requestEv, routeLoaders, route) {
720
724
  if (route?.$loaderPaths$) Object.assign(getRouteLoaderCtx(requestEv).loaderPaths, route.$loaderPaths$);
@@ -785,6 +789,7 @@ function jsonRequestWrapper() {
785
789
  if (isLoader) await sendJsonResponse(requestEv, { r: location });
786
790
  else await sendActionResponse(requestEv, { redirect: location });
787
791
  } else if (err instanceof ServerError) {
792
+ requestEv.headers.set("Cache-Control", "no-store");
788
793
  if (isLoader) await sendJsonResponse(requestEv, { e: err });
789
794
  else await sendActionResponse(requestEv, {
790
795
  e: err,
@@ -792,6 +797,7 @@ function jsonRequestWrapper() {
792
797
  });
793
798
  } else if (err instanceof Error) {
794
799
  console.error("JSON request error:", err);
800
+ requestEv.headers.set("Cache-Control", "no-store");
795
801
  const message = isDev ? `${err.message}\n(this is only visible in dev mode)` : "Internal Server Error";
796
802
  const se = new ServerError(500, message);
797
803
  if (isLoader) await sendJsonResponse(requestEv, { e: se });
@@ -1844,6 +1850,7 @@ async function runNext(requestEv, rebuildRouteInfo, resolve) {
1844
1850
  } else if (e instanceof AbortMessage) return;
1845
1851
  else if (e instanceof ServerError && !requestEv.headersSent) {
1846
1852
  const status = e.status;
1853
+ requestEv.headers.set("Cache-Control", "no-store");
1847
1854
  const accept = requestEv.request.headers.get("Accept");
1848
1855
  if (accept && !accept.includes("text/html")) {
1849
1856
  requestEv.headers.set("Content-Type", "application/qwik-json");
@@ -1,4 +1,4 @@
1
- import { D as getRouteLoaderValues, O as getRouteLoaders, d as loadRoute } from "./head.qwik.mjs";
1
+ import { O as getRouteLoaderValues, d as loadRoute, k as getRouteLoaders } from "./head.qwik.mjs";
2
2
  import { l as trimInternalPathname } from "./request-path.mjs";
3
3
  import { i as resolveRequestHandlers, r as renderQwikMiddleware, t as runQwikRouter } from "./user-response.mjs";
4
4
  import { _serialize } from "@qwik.dev/core/internal";
package/lib/index.d.ts CHANGED
@@ -9,6 +9,7 @@ import { CookieOptions } from '@qwik.dev/router/middleware/request-handler';
9
9
  import { CookieValue } from '@qwik.dev/router/middleware/request-handler';
10
10
  import { DeferReturn } from '@qwik.dev/router/middleware/request-handler';
11
11
  import type { EnvGetter } from '@qwik.dev/router/middleware/request-handler';
12
+ import { EventHandler } from '@qwik.dev/core';
12
13
  import { InternalRequest } from '@qwik.dev/router/middleware/request-handler';
13
14
  import { JSXOutput } from '@qwik.dev/core';
14
15
  import { NoSerialize } from '@qwik.dev/core';
@@ -27,7 +28,6 @@ import { RequestHandler } from '@qwik.dev/router/middleware/request-handler';
27
28
  import type { ResolveSyncValue } from '@qwik.dev/router/middleware/request-handler';
28
29
  import type { SerializationStrategy } from '@qwik.dev/core/internal';
29
30
  import type { ServerError } from '@qwik.dev/router/middleware/request-handler';
30
- import type { Signal } from '@qwik.dev/core';
31
31
  import * as v from 'valibot';
32
32
  import { ValueOrPromise } from '@qwik.dev/core';
33
33
  import { ValueOrPromise as ValueOrPromise_2 } from '@qwik.dev/core/internal';
@@ -157,10 +157,10 @@ declare type AnchorAttributes = QwikIntrinsicElements['a'];
157
157
  *
158
158
  * - `true`: use the surface's default key.
159
159
  *
160
- * - SSR default: `${status}|${eTag}|${pathname}` when an eTag is set, otherwise
161
- * `${status}|${pathname}`.
162
- * - Loader default: `${pathname}|${filteredSearch}|${loaderId}|${eTag}` when an eTag is set,
163
- * otherwise `${pathname}|${filteredSearch}|${loaderId}`.
160
+ * - SSR default: `${status}|${eTag}|${origin}${pathname}` when an eTag is set, otherwise
161
+ * `${status}|${origin}${pathname}`.
162
+ * - Loader default: `${origin}${pathname}|${filteredSearch}|${loaderId}|${eTag}` when an eTag is set,
163
+ * otherwise `${origin}${pathname}|${filteredSearch}|${loaderId}`.
164
164
  * - Function: receives the request event and the normalized, unquoted eTag (or an empty string when
165
165
  * none was provided). Return the cache key string, or `null` or `''` to skip caching for this
166
166
  * request. Loader callbacks receive the loader-scoped request event, with `url`, `query`, and
@@ -416,8 +416,11 @@ export declare interface FormProps<O, I> extends Omit<QwikJSX.IntrinsicElements[
416
416
  * Defaults to `false`
417
417
  */
418
418
  spaReset?: boolean;
419
- /** Event handler executed right after the action is executed successfully and returns some data. */
420
- onSubmitCompleted$?: QRLEventHandlerMulti<CustomEvent<FormSubmitSuccessDetail<O>>, HTMLFormElement> | undefined;
419
+ /**
420
+ * Event handler executed right after the action is executed successfully and returns some data.
421
+ * Like the native `on*$` events, it accepts an inline function as well as a QRL.
422
+ */
423
+ onSubmitCompleted$?: QRLEventHandlerMulti<CustomEvent<FormSubmitSuccessDetail<O>>, HTMLFormElement> | EventHandler<CustomEvent<FormSubmitSuccessDetail<O>>, HTMLFormElement> | undefined;
421
424
  key?: string | number | null;
422
425
  }
423
426
 
@@ -656,8 +659,8 @@ declare type LoaderOptions = {
656
659
  /**
657
660
  * Enable in-memory server-side caching of this loader's serialized JSON response.
658
661
  *
659
- * - `true` — use the default key `${pathname}|${filteredSearch}|${loaderId}` (suffixed with
660
- * `|${eTag}` when an eTag is set).
662
+ * - `true` — use the default key `${origin}${pathname}|${filteredSearch}|${loaderId}` (suffixed
663
+ * with `|${eTag}` when an eTag is set).
661
664
  * - Function `(requestEv, eTag) => string | null` — return a custom key, or `null` to skip caching
662
665
  * this request. For user-specific data, include user identity and relevant permissions in the
663
666
  * key or disable this cache.
@@ -697,7 +700,8 @@ declare type LoaderOptions = {
697
700
  };
698
701
 
699
702
  /** @public */
700
- export declare type LoaderSignal<TYPE> = (TYPE extends () => ValueOrPromise<infer VALIDATOR> ? Signal<ValueOrPromise<VALIDATOR>> : Signal<TYPE>) & Pick<ComputedSignal<any>, 'promise'>;
703
+ export declare interface LoaderSignal<TYPE> extends ComputedSignal<TYPE extends () => ValueOrPromise<infer VALIDATOR> ? ValueOrPromise<VALIDATOR> : TYPE> {
704
+ }
701
705
 
702
706
  declare interface MenuModule {
703
707
  readonly default: ContentMenu;
@@ -1100,7 +1104,11 @@ export declare const routeLoader$: LoaderConstructor;
1100
1104
  declare type RouteLoaderCtx = {
1101
1105
  loaderPaths: Record<string, string | undefined>;
1102
1106
  /** SPA navigation function. Client-only and intentionally omitted from SSR state. */
1103
- goto?: NoSerialize<RouteNavigate>;
1107
+ goto?: NoSerialize<(path: string, options: {
1108
+ replaceState: boolean;
1109
+ }) => unknown>;
1110
+ /** Router callback that re-resolves the document head after a loader gets a new value. */
1111
+ onValue?: RouteNavigate;
1104
1112
  /** Client manifest hash for q-loader fetch URLs. */
1105
1113
  manifestHash?: string;
1106
1114
  };