@qwik.dev/router 2.0.0-rc.3 → 2.0.0-rc.5

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,5 +1,5 @@
1
1
  import { t as ensureSlash } from "../../../chunks/pathname.mjs";
2
- import { r as LOADER_REGEX } from "../../../chunks/request-path.mjs";
2
+ import { i as LOADER_REGEX } from "../../../chunks/request-path.mjs";
3
3
  import fs from "node:fs";
4
4
  import { basename, dirname, join, resolve } from "node:path";
5
5
  import { spawn } from "node:child_process";
@@ -1,5 +1,5 @@
1
1
  import { t as ensureSlash } from "./pathname.mjs";
2
- import { o as getLoaderName } from "./request-path.mjs";
2
+ import { s as getLoaderName } from "./request-path.mjs";
3
3
  import { i as RedirectMessage, n as throwIfControlFlowSignal, t as ServerError } from "./server-error.mjs";
4
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";
@@ -21,6 +21,66 @@ var _asyncRequestStore = isServer$1 ? _registerSingleton("routerRequestStore", c
21
21
  var RequestEvRouterConfig = /*#__PURE__*/ _qwikSymbol("router.config");
22
22
  /** The config of the app serving the current request, for a router copy that holds none. */
23
23
  var getServingRouterConfig = () => _asyncRequestStore?.getStore()?.[RequestEvRouterConfig];
24
+ /**
25
+ * FNV-1a 32-bit hash for generating eTags from response data. Cheap to compute, sufficient
26
+ * collision resistance for cache validation (not cryptographic).
27
+ */
28
+ function hash(str) {
29
+ let hash = 2166136261;
30
+ for (let i = 0; i < str.length; i++) {
31
+ hash ^= str.charCodeAt(i);
32
+ hash = hash * 16777619 | 0;
33
+ }
34
+ return (hash >>> 0).toString(36);
35
+ }
36
+ /**
37
+ * Normalize an ETag header value (or a single `If-None-Match` entry) into a canonical form so byte
38
+ * equality compares the same logical tag. Strips weak ETag syntax (`W/"..."`), quotes, and any
39
+ * character outside RFC 7232's `etagc` grammar (printable ASCII except DQUOTE — no escape mechanism
40
+ * exists, and non-ASCII bytes are mangled by many HTTP stacks even though `obs-text` technically
41
+ * permits them). Idempotent.
42
+ */
43
+ function normalizeETag(raw) {
44
+ let tag = raw.trim();
45
+ if (tag.endsWith("\"") && tag.startsWith("W/\"")) tag = tag.slice(3);
46
+ tag = tag.replace(/[^!#-~]/g, "");
47
+ return tag;
48
+ }
49
+ function setETagHeader(requestEv, normalizedETag) {
50
+ const headerETag = `"${normalizedETag}"`;
51
+ requestEv.headers.set("ETag", headerETag);
52
+ }
53
+ /**
54
+ * Set the strong ETag header on the response and check the request's `If-None-Match` against it.
55
+ * The eTag argument must already be normalized. Returns true if a 304 was sent (caller should stop
56
+ * processing).
57
+ */
58
+ function performETagMatch(requestEv, normalizedETag, beforeNotModified) {
59
+ setETagHeader(requestEv, normalizedETag);
60
+ const ifNoneMatch = requestEv.request.headers.get("If-None-Match");
61
+ if (ifNoneMatch) {
62
+ let found = ifNoneMatch.trim() === "*";
63
+ if (!found) {
64
+ for (const entry of ifNoneMatch.split(",")) if (normalizeETag(entry) === normalizedETag) {
65
+ found = true;
66
+ break;
67
+ }
68
+ }
69
+ if (found) {
70
+ beforeNotModified?.();
71
+ requestEv.status(304);
72
+ requestEv.send(304, "");
73
+ return true;
74
+ }
75
+ }
76
+ return false;
77
+ }
78
+ /** Resolve eTag from a static string or function (before running the loader). */
79
+ function resolvePreETag(eTagOption, requestEv) {
80
+ if (typeof eTagOption === "string") return normalizeETag(eTagOption);
81
+ const result = eTagOption(requestEv);
82
+ return result ? normalizeETag(result) : "";
83
+ }
24
84
  var QACTION_KEY = "qaction";
25
85
  var QFN_KEY = "qfunc";
26
86
  var QDATA_KEY = "qdata";
@@ -132,6 +192,45 @@ var getBasePathname = () => findRouterConfig()?.basePathname ?? globalThis.__QWI
132
192
  var getTrailingSlash = () => findRouterConfig()?.trailingSlash ?? !globalThis.__NO_TRAILING_SLASH__;
133
193
  /** @internal */
134
194
  var _getServiceWorkerUrl = () => findRouterConfig()?.serviceWorkerUrl;
195
+ /** Gets an absolute url path string (url.pathname + url.search + url.hash) */
196
+ var toPath = (url) => url.pathname + url.search + url.hash;
197
+ /** Create a URL from a string and baseUrl */
198
+ var toUrl = (url, baseUrl) => new URL(url, baseUrl.href);
199
+ /** Resolves a redirect without allowing executable URL schemes. */
200
+ var toSafeRedirectUrl = (url, baseUrl) => {
201
+ const redirectUrl = toUrl(url, baseUrl);
202
+ if (redirectUrl.protocol !== "http:" && redirectUrl.protocol !== "https:") throw new Error(`Unsupported redirect protocol: ${redirectUrl.protocol}`);
203
+ return redirectUrl;
204
+ };
205
+ /** Checks only if the origins are the same. */
206
+ var isSameOrigin = (a, b) => a.origin === b.origin;
207
+ /** Checks only if the pathnames are the same for the URLs (doesn't include search and hash) */
208
+ var isSamePathname = ({ pathname: a }, { pathname: b }) => {
209
+ const lDiff = Math.abs(a.length - b.length);
210
+ return lDiff === 0 ? a === b : lDiff === 1 && ensureSlash(a) === ensureSlash(b);
211
+ };
212
+ /** Checks only if the search query strings are the same for the URLs */
213
+ var isSameSearchQuery = (a, b) => a.search === b.search;
214
+ /** Checks only if the pathname + search are the same for the URLs. */
215
+ var isSamePath = (a, b) => isSameSearchQuery(a, b) && isSamePathname(a, b);
216
+ var getClientNavPath = (props, baseUrl) => {
217
+ const href = props.href;
218
+ if (typeof href === "string" && typeof props.target !== "string" && !props.reload) try {
219
+ const linkUrl = toUrl(href.trim(), baseUrl.url);
220
+ if (isSameOrigin(linkUrl, toUrl("", baseUrl.url))) return toPath(linkUrl);
221
+ } catch (e) {
222
+ console.error(e);
223
+ }
224
+ else if (props.reload) return toPath(toUrl("", baseUrl.url));
225
+ return null;
226
+ };
227
+ var shouldPreload = (clientNavPath, currentLoc) => {
228
+ if (clientNavPath) return !isSamePathname(toUrl(clientNavPath, currentLoc.url), toUrl("", currentLoc.url));
229
+ return false;
230
+ };
231
+ var isPromise = (value) => {
232
+ return value && typeof value.then === "function";
233
+ };
135
234
  /**
136
235
  * Route loaders read data before the route rendering starts, based on the route being navigated to.
137
236
  * They automatically update when the route changes on the client.
@@ -214,14 +313,21 @@ var ServerRouteLoaderCapture = class {
214
313
  qrl;
215
314
  validators;
216
315
  blockSSR;
316
+ loader;
217
317
  requestEv;
218
- constructor(hash2, qrl1, validators1, blockSSR1, requestEv1) {
318
+ constructor(hash2, qrl1, validators1, blockSSR1, loader1, requestEv1) {
219
319
  this.hash = hash2;
220
320
  this.qrl = qrl1;
221
321
  this.validators = validators1;
222
322
  this.blockSSR = blockSSR1;
323
+ this.loader = loader1;
223
324
  this.requestEv = requestEv1;
224
325
  }
326
+ /** The eTag the q-loader endpoint will send for a value that isn't serialized. */
327
+ eTag() {
328
+ const option = this.loader.__eTag;
329
+ if (this.requestEv && option !== void 0 && this.loader.__serializationStrategy !== "always") return resolvePreETag(option, getLoaderRequestEvent(this.loader, this.requestEv));
330
+ }
225
331
  load() {
226
332
  const requestEv2 = this.requestEv;
227
333
  if (!requestEv2) throw new Error("Unable to determine the current RequestEvent.");
@@ -255,7 +361,7 @@ var fetchRouteLoaderData = async (loaderId, routePath, manifestHash, opts) => {
255
361
  if (!globalThis.__STRICT_LOADERS__) headers[FULLPATH_HEADER] = pageUrl.pathname;
256
362
  else if (isDev) headers[ROUTE_PATH_HEADER] = pageUrl.pathname;
257
363
  }
258
- const cacheKey = `${url}\n${headers["X-Qwik-fullpath"] ?? ""}`;
364
+ const cacheKey = `${url}\n${headers["X-Qwik-fullpath"] ?? headers["X-Qwik-route-path"] ?? ""}`;
259
365
  const cache = navFetchCache;
260
366
  if (!opts?.ignoreCache) {
261
367
  const entry = cache.get(cacheKey);
@@ -282,7 +388,10 @@ var fetchRouteLoaderData = async (loaderId, routePath, manifestHash, opts) => {
282
388
  if (!response.ok) return;
283
389
  const raw = await response.text();
284
390
  opts?.signal?.throwIfAborted();
285
- return { raw };
391
+ return {
392
+ raw,
393
+ eTag: response.headers.get("ETag") ?? void 0
394
+ };
286
395
  };
287
396
  if (opts?.ignoreCache) return request();
288
397
  if (opts?.signal) return request().then((value) => {
@@ -304,36 +413,41 @@ var fetchRouteLoaderData = async (loaderId, routePath, manifestHash, opts) => {
304
413
  cache.set(cacheKey, promise);
305
414
  return promise;
306
415
  };
307
- var createRouteLoaderSignal = (loader, routeLoaderCtx, state, requestEv3) => {
308
- const id = loader.__id;
309
- const capture = isServer ? new ServerRouteLoaderCapture(id, loader.__qrl, loader.__validators, loader.__blockSSR, requestEv3 ?? useServerData("qwikrouter")?.ev) : id;
310
- const searchFilter = loader.__search;
311
- const loaderHash = isDev ? loader.__qrl.getHash() : id;
416
+ var retainLoaderValue = (previous, abortSignal) => {
417
+ if (previous !== void 0) return previous;
418
+ return new Promise((_, reject) => {
419
+ abortSignal.throwIfAborted();
420
+ abortSignal.addEventListener("abort", () => reject(abortSignal.reason), { once: true });
421
+ });
422
+ };
423
+ var createRouteLoaderSignal = (loader2, routeLoaderCtx, state, requestEv3) => {
424
+ const id = loader2.__id;
425
+ const capture = isServer ? new ServerRouteLoaderCapture(id, loader2.__qrl, loader2.__validators, loader2.__blockSSR, loader2, requestEv3 ?? useServerData("qwikrouter")?.ev) : id;
426
+ const searchFilter = loader2.__search;
427
+ const loaderHash = isDev ? loader2.__qrl.getHash() : id;
312
428
  const signal = createComputedQrl(/*#__PURE__*/ inlinedQrl(async (ctx) => {
313
429
  let capture = _capturesObj._[0], id = _capturesObj._[1], lastFetch = _capturesObj._[2], loaderHash = _capturesObj._[3], routeLoaderCtx = _capturesObj._[4], searchFilter = _capturesObj._[5], state = _capturesObj._[6];
314
- if (!!ctx.info && typeof ctx.info === "object" && "__v" in ctx.info) {
430
+ const hasInjectedValue = !!ctx.info && typeof ctx.info === "object" && "__v" in ctx.info;
431
+ const eTag1 = isServer && capture.eTag();
432
+ if (eTag1) lastFetch.e = eTag1;
433
+ if (hasInjectedValue) {
315
434
  const value = ctx.info.__v;
316
435
  lastFetch.raw = void 0;
317
436
  return value;
318
437
  }
319
438
  if (isServer) return capture.load();
320
439
  const request = getLoaderRequest(routeLoaderCtx, state, id, loaderHash);
321
- if (!request.active) {
322
- if (ctx.previous === void 0) return new Promise((_, reject) => {
323
- ctx.abortSignal.throwIfAborted();
324
- ctx.abortSignal.addEventListener("abort", () => reject(ctx.abortSignal.reason), { once: true });
325
- });
326
- return ctx.previous;
327
- }
440
+ if (!request.active) return retainLoaderValue(ctx.previous, ctx.abortSignal);
328
441
  const pageUrl = new URL(request.pageUrl);
329
442
  const mHash = untrack(() => routeLoaderCtx.manifestHash) || "dev";
330
443
  const basePath = getBasePathname();
444
+ const fetchRoutePath = request.routePath;
331
445
  let fetchUrl = pageUrl;
332
446
  if (searchFilter) {
333
447
  fetchUrl = new URL(pageUrl.href);
334
448
  fetchUrl.search = filterSearchParams(pageUrl.searchParams, searchFilter);
335
449
  }
336
- const result = await fetchRouteLoaderData(id, request.routePath, mHash, {
450
+ const result = await fetchRouteLoaderData(id, fetchRoutePath, mHash, {
337
451
  pageUrl: fetchUrl,
338
452
  basePath,
339
453
  ignoreCache: ctx.info === true,
@@ -350,13 +464,30 @@ var createRouteLoaderSignal = (loader, routeLoaderCtx, state, requestEv3) => {
350
464
  }
351
465
  assertCurrentLoaderRequest(routeLoaderCtx, state[id], request, ctx.abortSignal);
352
466
  if (response.r) {
467
+ const redirectUrl = toSafeRedirectUrl(response.r, pageUrl);
353
468
  const goto = routeLoaderCtx.goto;
354
- if (goto) goto(response.r, { replaceState: true });
355
- else location.href = response.r;
356
- return ctx.previous;
469
+ const prepared = Promise.resolve().then(() => {
470
+ assertCurrentLoaderRequest(routeLoaderCtx, state[id], request, ctx.abortSignal);
471
+ if (goto) return goto(redirectUrl.href, { replaceState: true });
472
+ location.href = redirectUrl.href;
473
+ return new Promise(() => {});
474
+ });
475
+ request.redirect = prepared;
476
+ return wrapWithAbort(prepared, ctx.abortSignal).then(() => {
477
+ assertCurrentLoaderRequest(routeLoaderCtx, state[id], request, ctx.abortSignal);
478
+ try {
479
+ return state[id].untrackedValue;
480
+ } catch {
481
+ throw new Error("Route loader redirect completed without data.");
482
+ }
483
+ }).finally(() => {
484
+ if (request.redirect === prepared) request.redirect = void 0;
485
+ });
357
486
  }
358
487
  if (response.e) throw response.e;
359
488
  lastFetch.raw = result.raw;
489
+ if (ctx.previous === void 0 && lastFetch.e && lastFetch.e === normalizeETag(result.eTag || "")) state[id].untrackedValue = response.d;
490
+ lastFetch.e = void 0;
360
491
  const onValue = routeLoaderCtx.onValue;
361
492
  if (onValue) Promise.resolve().then(() => state[id].promise()).then(() => onValue(REFRESH_HEAD));
362
493
  return response.d;
@@ -368,7 +499,7 @@ var createRouteLoaderSignal = (loader, routeLoaderCtx, state, requestEv3) => {
368
499
  routeLoaderCtx,
369
500
  searchFilter,
370
501
  state
371
- ]), { serializationStrategy: loader.__serializationStrategy });
502
+ ]), { serializationStrategy: loader2.__serializationStrategy });
372
503
  _markSignalAsExternallyOwned(signal);
373
504
  return signal;
374
505
  };
@@ -387,7 +518,7 @@ function getLoaderOptions(rest) {
387
518
  let id;
388
519
  let serializationStrategy = DEFAULT_LOADERS_SERIALIZATION_STRATEGY();
389
520
  let cacheControl;
390
- let eTag;
521
+ let eTag2;
391
522
  let cacheKey;
392
523
  let search;
393
524
  let blockSSR2 = true;
@@ -401,7 +532,7 @@ function getLoaderOptions(rest) {
401
532
  if (options.serializationStrategy) serializationStrategy = options.serializationStrategy;
402
533
  if (options.validation) validators2.push(...options.validation);
403
534
  if ("cacheControl" in options) cacheControl = options.cacheControl;
404
- if ("eTag" in options) eTag = options.eTag;
535
+ if ("eTag" in options) eTag2 = options.eTag;
405
536
  if ("cacheKey" in options) cacheKey = options.cacheKey;
406
537
  if (options.search) search = options.search;
407
538
  else if (globalThis.__STRICT_LOADERS__) search = [];
@@ -417,7 +548,7 @@ function getLoaderOptions(rest) {
417
548
  validators: validators2.reverse(),
418
549
  serializationStrategy,
419
550
  cacheControl,
420
- eTag,
551
+ eTag: eTag2,
421
552
  cacheKey,
422
553
  search,
423
554
  blockSSR: blockSSR2
@@ -516,7 +647,7 @@ var isImmutableLoader = (loaderId) => immutableLoaderIds.has(loaderId);
516
647
  function abortRouteLoaderNavigation(ctx) {
517
648
  for (const [signal, request] of clientRouteLoaders.get(ctx)?.current.requests ?? []) {
518
649
  if (signal.untrackedPending) request.isAborted = true;
519
- signal.abort();
650
+ if (!request.redirect) signal.abort();
520
651
  }
521
652
  }
522
653
  /** Search-filtered loaders ignore changes to unlisted params. */
@@ -537,15 +668,15 @@ function prepareRouteLoaders(mods, state, ctx, paths, pageUrl, previousUrl, navC
537
668
  };
538
669
  const loaders = ensureRouteLoaderSignals(mods, state, ctx);
539
670
  const routeLoaders = /* @__PURE__ */ new Map();
540
- for (const loader of loaders) {
541
- routeLoaders.set(loader.__id, loader);
542
- current.paths[loader.__id] ||= current.paths[loader.__qrl.getHash()] || pageUrl.pathname;
671
+ for (const loader3 of loaders) {
672
+ routeLoaders.set(loader3.__id, loader3);
673
+ current.paths[loader3.__id] ||= current.paths[loader3.__qrl.getHash()] || pageUrl.pathname;
543
674
  }
544
675
  for (const id in state) {
545
676
  const signal = state[id];
546
677
  const old = previous.requests.get(signal);
547
- const loader = routeLoaders.get(id);
548
- const hash3 = loader?.__qrl.getHash() || old?.hash;
678
+ const loader4 = routeLoaders.get(id);
679
+ const hash3 = loader4?.__qrl.getHash() || old?.hash;
549
680
  const routePath = current.paths[id] || hash3 && current.paths[hash3];
550
681
  if (!routePath) {
551
682
  if (old) current.requests.set(signal, {
@@ -555,7 +686,7 @@ function prepareRouteLoaders(mods, state, ctx, paths, pageUrl, previousUrl, navC
555
686
  signal.abort();
556
687
  continue;
557
688
  }
558
- const keepRequest = old?.active && !old.isAborted && old.routePath === routePath && (old.pageUrl === pageUrl.href ? isImmutableLoader(id) : hasSameListedSearch(new URL(old.pageUrl), pageUrl, loader?.__search));
689
+ const keepRequest = old?.active && !old.isAborted && old.routePath === routePath && (old.pageUrl === pageUrl.href ? isImmutableLoader(id) : hasSameListedSearch(new URL(old.pageUrl), pageUrl, loader4?.__search));
559
690
  current.requests.set(signal, keepRequest ? old : {
560
691
  routePath,
561
692
  pageUrl: pageUrl.href,
@@ -597,9 +728,9 @@ function restoreRouteLoaders(state, ctx, navCount) {
597
728
  pruneRouteLoaders(state, ctx);
598
729
  for (const signal of client.current.requests.keys()) signal.invalidate();
599
730
  }
600
- var ensureRouteLoaderSignal = (loader, state, routeLoaderCtx, requestEv12) => {
601
- if (loader.__cacheControl === "immutable") immutableLoaderIds.add(loader.__id);
602
- return state[loader.__id] ||= createRouteLoaderSignal(loader, routeLoaderCtx, state, requestEv12);
731
+ var ensureRouteLoaderSignal = (loader5, state, routeLoaderCtx, requestEv12) => {
732
+ if (loader5.__cacheControl === "immutable") immutableLoaderIds.add(loader5.__id);
733
+ return state[loader5.__id] ||= createRouteLoaderSignal(loader5, routeLoaderCtx, state, requestEv12);
603
734
  };
604
735
  var ensureRouteLoaderSignals = (mods, state, routeLoaderCtx, requestEv13) => {
605
736
  const loaders = getModuleRouteLoaders(mods);
@@ -617,10 +748,10 @@ var setLoaderSignalValue = (signal, value) => {
617
748
  _injectAsyncSignalValue(signal, value);
618
749
  };
619
750
  var resolveRouteLoaderByHash = (routeLoaders, loaderId) => {
620
- return routeLoaders.find((loader) => matchesRouteLoaderId(loader, loaderId));
751
+ return routeLoaders.find((loader6) => matchesRouteLoaderId(loader6, loaderId));
621
752
  };
622
- var matchesRouteLoaderId = (loader, loaderId) => {
623
- return typeof loaderId === "string" && (loader.__id === loaderId || isDev && loader.__qrl.getHash() === loaderId);
753
+ var matchesRouteLoaderId = (loader7, loaderId) => {
754
+ return typeof loaderId === "string" && (loader7.__id === loaderId || isDev && loader7.__qrl.getHash() === loaderId);
624
755
  };
625
756
  /** Run a loader and return its raw value. Errors/redirects propagate as exceptions. */
626
757
  var getRouteLoaderData = async (loaderQrl, validators3, requestEv14) => {
@@ -651,31 +782,36 @@ var loadRouteLoaderByQrl = (loaderId, loaderQrl, validators4, requestEv15) => {
651
782
  return promise;
652
783
  };
653
784
  /** @internal */
654
- var getLoaderRequestEvent = (loader, requestEv16) => {
785
+ var getLoaderRequestEvent = (loader8, requestEv16) => {
655
786
  let rootRequestEv = requestEv16.sharedMap.get(REQUEST_ROUTE_LOADER_ROOT_EVENT);
656
787
  if (!rootRequestEv) {
657
788
  rootRequestEv = requestEv16;
658
789
  requestEv16.sharedMap.set(REQUEST_ROUTE_LOADER_ROOT_EVENT, rootRequestEv);
659
790
  }
660
791
  const url = new URL(rootRequestEv.url);
661
- const pathname = globalThis.__STRICT_LOADERS__ ? getRouteLoaderCtx(rootRequestEv).loaderPaths[loader.__id] || rootRequestEv.url.pathname : rootRequestEv.url.pathname;
662
- const filteredSearch = loader.__search ? filterSearchParams(url.searchParams, loader.__search) : rootRequestEv.url.search;
663
- if (pathname === rootRequestEv.url.pathname && filteredSearch === rootRequestEv.url.search) return rootRequestEv;
664
- const params = pathname === rootRequestEv.url.pathname ? rootRequestEv.params : getRouteLoaderParams(rootRequestEv)[loader.__id] || {};
792
+ const pathname = globalThis.__STRICT_LOADERS__ ? getRouteLoaderCtx(rootRequestEv).loaderPaths[loader8.__id] || rootRequestEv.url.pathname : rootRequestEv.url.pathname;
793
+ const filteredSearch = loader8.__search ? filterSearchParams(url.searchParams, loader8.__search) : rootRequestEv.url.search;
794
+ const isSameUrl = pathname === rootRequestEv.url.pathname && filteredSearch === rootRequestEv.url.search;
795
+ const params = globalThis.__STRICT_LOADERS__ ? getRouteLoaderParams(rootRequestEv)[loader8.__id] ?? (pathname === rootRequestEv.url.pathname ? rootRequestEv.params : {}) : rootRequestEv.params;
796
+ if (isSameUrl && params === rootRequestEv.params) return rootRequestEv;
665
797
  let events = rootRequestEv.sharedMap.get(REQUEST_ROUTE_LOADER_EVENTS);
666
798
  if (!events) {
667
799
  events = /* @__PURE__ */ new Map();
668
800
  rootRequestEv.sharedMap.set(REQUEST_ROUTE_LOADER_EVENTS, events);
669
801
  }
670
- const eventKey = `${pathname}\n${filteredSearch}`;
802
+ const eventKey = `${pathname}\n${filteredSearch}\n${params === rootRequestEv.params ? "" : loader8.__id}`;
671
803
  let loaderRequestEv = events.get(eventKey);
672
804
  if (!loaderRequestEv) {
673
805
  url.pathname = pathname;
674
806
  url.search = filteredSearch;
675
- const request = new Request(url, rootRequestEv.request);
807
+ const request = new Request(url, {
808
+ method: rootRequestEv.request.method,
809
+ headers: rootRequestEv.request.headers,
810
+ signal: rootRequestEv.request.signal
811
+ });
676
812
  loaderRequestEv = Object.create(rootRequestEv, {
677
813
  originalUrl: {
678
- value: new URL(url),
814
+ value: isSameUrl ? rootRequestEv.originalUrl : new URL(url),
679
815
  enumerable: true
680
816
  },
681
817
  params: {
@@ -755,9 +891,9 @@ var detachResponseFromEvent = (requestEv17) => {
755
891
  }
756
892
  });
757
893
  };
758
- var loadRouteLoader = (loader, requestEv18) => {
759
- const loaderEv = getLoaderRequestEvent(loader, requestEv18);
760
- return loadRouteLoaderByQrl(loader.__id, loader.__qrl, loader.__validators, loader.__blockSSR ? loaderEv : detachResponseFromEvent(loaderEv));
894
+ var loadRouteLoader = (loader9, requestEv18) => {
895
+ const loaderEv = getLoaderRequestEvent(loader9, requestEv18);
896
+ return loadRouteLoaderByQrl(loader9.__id, loader9.__qrl, loader9.__validators, loader9.__blockSSR ? loaderEv : detachResponseFromEvent(loaderEv));
761
897
  };
762
898
  /** Run a loader and wrap the result in a LoaderResponse envelope. Catches redirects/errors. */
763
899
  var getRouteLoaderResponse = async (loaderQrl, validators5, requestEv19) => {
@@ -781,24 +917,24 @@ var getRouteLoaderResponse = async (loaderQrl, validators5, requestEv19) => {
781
917
  * @internal
782
918
  */
783
919
  function routeLoaderQrl(loaderQrl, ...rest) {
784
- const { id, validators: validators6, serializationStrategy, cacheControl, eTag, cacheKey, search, blockSSR: blockSSR3 } = getLoaderOptions(rest);
785
- function loader() {
786
- const signal = ensureRouteLoaderSignal(loader, _resolveContextWithoutSequentialScope(RouteStateContext), _resolveContextWithoutSequentialScope(RouteLoaderCtxContext));
920
+ const { id, validators: validators6, serializationStrategy, cacheControl, eTag: eTag3, cacheKey, search, blockSSR: blockSSR3 } = getLoaderOptions(rest);
921
+ function loader10() {
922
+ const signal = ensureRouteLoaderSignal(loader10, _resolveContextWithoutSequentialScope(RouteStateContext), _resolveContextWithoutSequentialScope(RouteLoaderCtxContext));
787
923
  signal.promise();
788
924
  return signal;
789
925
  }
790
- loader.__brand = "server_loader";
791
- loader.__qrl = loaderQrl;
792
- loader.__validators = validators6;
793
- loader.__id = id ?? loaderQrl.getHash();
794
- loader.__serializationStrategy = serializationStrategy;
795
- loader.__cacheControl = cacheControl;
796
- loader.__eTag = eTag;
797
- loader.__cacheKey = cacheKey;
798
- loader.__search = search;
799
- loader.__blockSSR = blockSSR3;
800
- Object.freeze(loader);
801
- return loader;
926
+ loader10.__brand = "server_loader";
927
+ loader10.__qrl = loaderQrl;
928
+ loader10.__validators = validators6;
929
+ loader10.__id = id ?? loaderQrl.getHash();
930
+ loader10.__serializationStrategy = serializationStrategy;
931
+ loader10.__cacheControl = cacheControl;
932
+ loader10.__eTag = eTag3;
933
+ loader10.__cacheKey = cacheKey;
934
+ loader10.__search = search;
935
+ loader10.__blockSSR = blockSSR3;
936
+ Object.freeze(loader10);
937
+ return loader10;
802
938
  }
803
939
  /**
804
940
  * Define a route loader that fetches data before the route renders.
@@ -864,6 +1000,18 @@ var deepFreeze = (obj) => {
864
1000
  var MODULE_CACHE = /*#__PURE__*/ new WeakMap();
865
1001
  var loadRoute = async (routes, cacheModules, pathname) => {
866
1002
  const { loaders, params, routeParts, notFound, routeBundleNames, loaderPathsByHash, loaderParamsByHash, menuLoader, errorLoader } = matchRouteTree(routes, pathname);
1003
+ const loaderEndpoints = /* @__PURE__ */ new Map();
1004
+ const pagePath = ensureSlash(pathname);
1005
+ for (const hash in loaderPathsByHash) {
1006
+ const loaderPath = loaderPathsByHash[hash];
1007
+ if (loaderPath === pagePath) continue;
1008
+ let endpoint = loaderEndpoints.get(loaderPath);
1009
+ if (!endpoint) {
1010
+ endpoint = matchRouteTree(routes, loaderPath);
1011
+ loaderEndpoints.set(loaderPath, endpoint);
1012
+ }
1013
+ if (!endpoint.notFound && !endpoint.loaderPathsByHash?.[hash]) loaderPathsByHash[hash] = pagePath;
1014
+ }
867
1015
  const routeName = "/" + routeParts.join("/");
868
1016
  const modules = new Array(loaders.length);
869
1017
  const pendingLoads = [];
@@ -1019,7 +1167,7 @@ function getStaticChild(node, partLower) {
1019
1167
  * Priority: exact match → _M groups (recursively) → _W wildcard → _A rest wildcard. This ensures
1020
1168
  * exact matches inside nested groups take precedence over wildcards at parent level.
1021
1169
  */
1022
- function findChild(node, part, partLower, parts, partIndex) {
1170
+ function findChild(node, part, partLower) {
1023
1171
  const exact = getStaticChild(node, partLower);
1024
1172
  if (exact) return {
1025
1173
  next: exact,
@@ -1030,21 +1178,21 @@ function findChild(node, part, partLower, parts, partIndex) {
1030
1178
  };
1031
1179
  if (node._M) for (let j = 0; j < node._M.length; j++) {
1032
1180
  const group = node._M[j];
1033
- const groupResult = findChild(group, part, partLower, parts, partIndex);
1181
+ const groupResult = findChild(group, part, partLower);
1034
1182
  if (groupResult) {
1035
1183
  groupResult.groups.unshift(group);
1036
1184
  return groupResult;
1037
1185
  }
1038
1186
  }
1039
- const wildcard = tryWildcardMatch(node, part, partLower, parts, partIndex);
1187
+ const wildcard = tryWildcardMatch(node, part, partLower);
1040
1188
  if (wildcard) return {
1041
1189
  ...wildcard,
1042
1190
  groups: []
1043
1191
  };
1044
1192
  }
1045
1193
  /** Try to match a segment against a node's wildcard children (_W, _A). */
1046
- function tryWildcardMatch(node, part, partLower, parts, partIndex) {
1047
- return matchWildcardNode(node, part, partLower) ?? matchRestNode(node, parts, partIndex);
1194
+ function tryWildcardMatch(node, part, partLower) {
1195
+ return matchWildcardNode(node, part, partLower) ?? matchRestNode(node);
1048
1196
  }
1049
1197
  /** Try to match a segment against a node's `[param]` wildcard child (`_W`). */
1050
1198
  function matchWildcardNode(node, part, partLower) {
@@ -1081,18 +1229,16 @@ function matchWildcardNode(node, part, partLower) {
1081
1229
  }
1082
1230
  }
1083
1231
  /** Try to match the remaining segments against a node's `[...param]` rest child (`_A`). */
1084
- function matchRestNode(node, parts, partIndex) {
1232
+ function matchRestNode(node) {
1085
1233
  const next = node._A;
1086
1234
  if (next) {
1087
1235
  const paramName = next._P;
1088
- const restValue = parts.slice(partIndex).join("/");
1089
1236
  return {
1090
1237
  next,
1091
1238
  routePart: `[...${paramName}]`,
1092
1239
  done: true,
1093
1240
  kind: ChildMatchKind.Rest,
1094
- paramName,
1095
- paramValue: restValue
1241
+ paramName
1096
1242
  };
1097
1243
  }
1098
1244
  }
@@ -1119,7 +1265,6 @@ function matchRestSpans(node, parts, partIndex) {
1119
1265
  done: false,
1120
1266
  kind: ChildMatchKind.Rest,
1121
1267
  paramName,
1122
- paramValue: parts.slice(partIndex, partIndex + span).join("/"),
1123
1268
  span
1124
1269
  });
1125
1270
  return spans;
@@ -1158,7 +1303,7 @@ function findChildAll(node, part, partLower, parts, partIndex) {
1158
1303
  groups: []
1159
1304
  });
1160
1305
  candidates.push(...matchRestSpans(node, parts, partIndex));
1161
- const rest = matchRestNode(node, parts, partIndex);
1306
+ const rest = matchRestNode(node);
1162
1307
  if (rest) candidates.push({
1163
1308
  ...rest,
1164
1309
  groups: []
@@ -1289,7 +1434,8 @@ function matchRouteTree(root = {}, pathname) {
1289
1434
  });
1290
1435
  let done = false;
1291
1436
  let matched = true;
1292
- const parts = pathname.split("/").filter((p) => p.length > 0).map(decodeURIComponent);
1437
+ const encodedParts = pathname.split("/").filter((p) => p.length > 0);
1438
+ const parts = encodedParts.map(decodeURIComponent);
1293
1439
  let restFallback;
1294
1440
  let i = 0;
1295
1441
  const len = parts.length;
@@ -1298,7 +1444,7 @@ function matchRouteTree(root = {}, pathname) {
1298
1444
  while (!done && i < len) {
1299
1445
  const part = parts[i];
1300
1446
  const partLower = part.toLowerCase();
1301
- const found = chain ? chain[chainIndex++] : findChild(node, part, partLower, parts, i);
1447
+ const found = chain ? chain[chainIndex++] : findChild(node, part, partLower);
1302
1448
  if (!found) {
1303
1449
  matched = false;
1304
1450
  break;
@@ -1320,12 +1466,12 @@ function matchRouteTree(root = {}, pathname) {
1320
1466
  notFoundLayouts: notFoundLoaderRef.layouts,
1321
1467
  menuLoader: menuLoaderRef.v
1322
1468
  };
1323
- if (found.paramName) params[found.paramName] = found.paramValue;
1469
+ const span = found.span ?? 1;
1470
+ if (found.paramName) params[found.paramName] = found.paramValue ?? parts.slice(i, found.done ? len : i + span).join("/");
1324
1471
  routeParts.push(found.routePart);
1325
1472
  done = found.done;
1326
1473
  node = found.next;
1327
- const span = found.span ?? 1;
1328
- const matchedParts = parts.slice(0, found.done ? len : i + span);
1474
+ const matchedParts = encodedParts.slice(0, found.done ? len : i + span);
1329
1475
  const matchedPathname = matchedParts.length ? `/${matchedParts.join("/")}/` : "/";
1330
1476
  collectNodeMeta(node, found.groups, layouts, errorLoaderRef, notFoundLoaderRef, menuLoaderRef, loaderPathsByHash, matchedPathname, loaderParamsByHash, { ...params });
1331
1477
  if (node._M) groupNodes.push({
@@ -1481,39 +1627,6 @@ function collectPageLoaders({ node, loaderPaths, loaderParams }, paths, pathPara
1481
1627
  pathParams[hash] = { ...params };
1482
1628
  }
1483
1629
  }
1484
- /** Gets an absolute url path string (url.pathname + url.search + url.hash) */
1485
- var toPath = (url) => url.pathname + url.search + url.hash;
1486
- /** Create a URL from a string and baseUrl */
1487
- var toUrl = (url, baseUrl) => new URL(url, baseUrl.href);
1488
- /** Checks only if the origins are the same. */
1489
- var isSameOrigin = (a, b) => a.origin === b.origin;
1490
- /** Checks only if the pathnames are the same for the URLs (doesn't include search and hash) */
1491
- var isSamePathname = ({ pathname: a }, { pathname: b }) => {
1492
- const lDiff = Math.abs(a.length - b.length);
1493
- return lDiff === 0 ? a === b : lDiff === 1 && ensureSlash(a) === ensureSlash(b);
1494
- };
1495
- /** Checks only if the search query strings are the same for the URLs */
1496
- var isSameSearchQuery = (a, b) => a.search === b.search;
1497
- /** Checks only if the pathname + search are the same for the URLs. */
1498
- var isSamePath = (a, b) => isSameSearchQuery(a, b) && isSamePathname(a, b);
1499
- var getClientNavPath = (props, baseUrl) => {
1500
- const href = props.href;
1501
- if (typeof href === "string" && typeof props.target !== "string" && !props.reload) try {
1502
- const linkUrl = toUrl(href.trim(), baseUrl.url);
1503
- if (isSameOrigin(linkUrl, toUrl("", baseUrl.url))) return toPath(linkUrl);
1504
- } catch (e) {
1505
- console.error(e);
1506
- }
1507
- else if (props.reload) return toPath(toUrl("", baseUrl.url));
1508
- return null;
1509
- };
1510
- var shouldPreload = (clientNavPath, currentLoc) => {
1511
- if (clientNavPath) return !isSamePathname(toUrl(clientNavPath, currentLoc.url), toUrl("", currentLoc.url));
1512
- return false;
1513
- };
1514
- var isPromise = (value) => {
1515
- return value && typeof value.then === "function";
1516
- };
1517
1630
  /**
1518
1631
  * Resolve the full route config (head + eTag + cacheKey) from all content modules. Uses the same
1519
1632
  * resolution rules as DocumentHead: objects are merged immediately, functions are queued and
@@ -1631,4 +1744,4 @@ var createDocumentHead = (defaults, manifestHash) => ({
1631
1744
  frontmatter: { ...defaults?.frontmatter },
1632
1745
  manifestHash: manifestHash || "dev"
1633
1746
  });
1634
- export { HttpStatusContext as $, loadRouteLoader as A, _setRouterConfig as B, getRequestEvent as C, getRouteLoaderValues as D, getRouteLoaderResponse as E, routeLoader$ as F, REFRESH_HEAD as G, getRouterConfig as H, routeLoaderQrl as I, preventNav as J, RUN_PENDING_ACTION as K, setLoaderSignalValue as L, prepareRouteLoaders as M, resolveRouteLoaderByHash as N, getRouteLoaders as O, restoreRouteLoaders as P, DocumentHeadContext as Q, setRouteLoaders as R, getModuleRouteLoaders as S, getRouteLoaderParams as T, getRoutes as U, getBasePathname as V, getTrailingSlash as W, ContentContext as X, registerPreventNav as Y, ContentInternalContext as Z, commitRouteLoaders as _, isPromise as a, RouteStateContext as at, getClientRouteLoaders as b, shouldPreload as c, QFN_KEY as ct, loadRoute as d, _asyncRequestStore as dt, RouteActionContext as et, FULLPATH_HEADER as f, clearRouteLoaderData as g, clearNavFetchCache as h, getClientNavPath as i, RouteNavigateContext as it, matchesRouteLoaderId as j, isImmutableLoader as k, toPath as l, Q_ROUTE as lt, abortRouteLoaderNavigation as m, resolveHead as n, RouteLoaderCtxContext as nt, isSameOrigin as o, QACTION_KEY as ot, ROUTE_PATH_HEADER as p, internalState as q, resolveRouteConfig as r, RouteLocationContext as rt, isSamePath as s, QDATA_KEY as st, createDocumentHead as t, RouteActionRunnerContext as tt, toUrl as u, RequestEvRouterConfig as ut, ensureRouteLoaderSignals as v, getRouteLoaderCtx as w, getLoaderRequestEvent as x, fetchRouteLoaderData as y, _getServiceWorkerUrl as z };
1747
+ export { ContentContext as $, routeLoaderQrl as A, toUrl as B, isImmutableLoader as C, resolveRouteLoaderByHash as D, prepareRouteLoaders as E, isSameOrigin as F, getRouterConfig as G, _setRouterConfig as H, isSamePath as I, REFRESH_HEAD as J, getRoutes as K, shouldPreload as L, setRouteLoaders as M, getClientNavPath as N, restoreRouteLoaders as O, isPromise as P, registerPreventNav as Q, toPath as R, getRouteLoaders as S, matchesRouteLoaderId as T, findRouterConfig as U, _getServiceWorkerUrl as V, getBasePathname as W, internalState as X, RUN_PENDING_ACTION as Y, preventNav as Z, getRequestEvent as _, setETagHeader as _t, matchRouteTree as a, RouteLoaderCtxContext as at, getRouteLoaderResponse as b, abortRouteLoaderNavigation as c, RouteStateContext as ct, commitRouteLoaders as d, QFN_KEY as dt, ContentInternalContext as et, ensureRouteLoaderSignals as f, Q_ROUTE as ft, getModuleRouteLoaders as g, resolvePreETag as gt, getLoaderRequestEvent as h, performETagMatch as ht, loadRoute as i, RouteActionRunnerContext as it, setLoaderSignalValue as j, routeLoader$ as k, clearNavFetchCache as l, QACTION_KEY as lt, getClientRouteLoaders as m, normalizeETag as mt, resolveHead as n, HttpStatusContext as nt, FULLPATH_HEADER as o, RouteLocationContext as ot, fetchRouteLoaderData as p, hash as pt, getTrailingSlash as q, resolveRouteConfig as r, RouteActionContext as rt, ROUTE_PATH_HEADER as s, RouteNavigateContext as st, createDocumentHead as t, DocumentHeadContext as tt, clearRouteLoaderData as u, QDATA_KEY as ut, getRouteLoaderCtx as v, RequestEvRouterConfig as vt, loadRouteLoader as w, getRouteLoaderValues as x, getRouteLoaderParams as y, _asyncRequestStore as yt, toSafeRedirectUrl as z };
@@ -1,11 +1,14 @@
1
1
  import { t as ensureSlash } from "./pathname.mjs";
2
2
  var IsQLoader = "@isQLoader";
3
3
  var IsQAction = "@isQAction";
4
+ var IsQRoute = "@isQRoute";
4
5
  var QLoaderId = "@loaderId";
5
6
  var QActionId = "@actionId";
6
7
  /** Matches the final `/q-loader-{loaderId}.{manifestHash}.json` path segment. */
7
8
  var LOADER_REGEX = /\/(q-loader-([^/.]+)\.([^/.]+)\.json)$/;
8
9
  var getLoaderName = (loaderId, manifestHash) => `q-loader-${loaderId}.${manifestHash}.json`;
10
+ /** Matches the final `/q-route.json` path segment: the client asks where a URL really routes to. */
11
+ var ROUTE_REGEX = /\/q-route\.json$/;
9
12
  /**
10
13
  * Recognize internal request types from the URL pathname.
11
14
  *
@@ -23,6 +26,11 @@ function recognizeRequest(pathname) {
23
26
  manifestHash: loaderMatch[3]
24
27
  }
25
28
  };
29
+ if (ROUTE_REGEX.test(pathname)) return {
30
+ type: IsQRoute,
31
+ trimLength: 13,
32
+ data: null
33
+ };
26
34
  return null;
27
35
  }
28
36
  /** Trim a recognized internal URL suffix from a pathname, returning the clean route pathname. */
@@ -50,4 +58,4 @@ function resolveValidInternalFullPathname(loaderPathname, fullPath) {
50
58
  return;
51
59
  }
52
60
  }
53
- export { QLoaderId as a, resolveValidInternalFullPathname as c, QActionId as i, trimInternalPathname as l, IsQLoader as n, getLoaderName as o, LOADER_REGEX as r, recognizeRequest as s, IsQAction as t, trimRecognizedInternalPathname as u };
61
+ export { QActionId as a, recognizeRequest as c, trimRecognizedInternalPathname as d, LOADER_REGEX as i, resolveValidInternalFullPathname as l, IsQLoader as n, QLoaderId as o, IsQRoute as r, getLoaderName as s, IsQAction as t, trimInternalPathname as u };