vinext 0.0.39 → 0.0.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/build/standalone.js +7 -0
  2. package/dist/build/standalone.js.map +1 -1
  3. package/dist/entries/app-rsc-entry.d.ts +2 -1
  4. package/dist/entries/app-rsc-entry.js +131 -245
  5. package/dist/entries/app-rsc-entry.js.map +1 -1
  6. package/dist/index.d.ts +32 -1
  7. package/dist/index.js +80 -6
  8. package/dist/index.js.map +1 -1
  9. package/dist/plugins/server-externals-manifest.d.ts +11 -1
  10. package/dist/plugins/server-externals-manifest.js +10 -3
  11. package/dist/plugins/server-externals-manifest.js.map +1 -1
  12. package/dist/routing/app-router.d.ts +10 -2
  13. package/dist/routing/app-router.js +37 -22
  14. package/dist/routing/app-router.js.map +1 -1
  15. package/dist/server/app-page-response.d.ts +12 -1
  16. package/dist/server/app-page-response.js +26 -7
  17. package/dist/server/app-page-response.js.map +1 -1
  18. package/dist/server/app-page-route-wiring.d.ts +79 -0
  19. package/dist/server/app-page-route-wiring.js +165 -0
  20. package/dist/server/app-page-route-wiring.js.map +1 -0
  21. package/dist/server/app-page-stream.js +3 -0
  22. package/dist/server/app-page-stream.js.map +1 -1
  23. package/dist/server/app-route-handler-response.js +4 -1
  24. package/dist/server/app-route-handler-response.js.map +1 -1
  25. package/dist/server/app-router-entry.d.ts +6 -1
  26. package/dist/server/app-router-entry.js +9 -2
  27. package/dist/server/app-router-entry.js.map +1 -1
  28. package/dist/server/prod-server.d.ts +1 -1
  29. package/dist/server/prod-server.js +37 -11
  30. package/dist/server/prod-server.js.map +1 -1
  31. package/dist/server/worker-utils.d.ts +4 -1
  32. package/dist/server/worker-utils.js +31 -1
  33. package/dist/server/worker-utils.js.map +1 -1
  34. package/dist/shims/error-boundary.d.ts +13 -4
  35. package/dist/shims/error-boundary.js +23 -3
  36. package/dist/shims/error-boundary.js.map +1 -1
  37. package/dist/shims/head.js.map +1 -1
  38. package/dist/shims/navigation.d.ts +16 -1
  39. package/dist/shims/navigation.js +18 -3
  40. package/dist/shims/navigation.js.map +1 -1
  41. package/dist/shims/router.js +127 -38
  42. package/dist/shims/router.js.map +1 -1
  43. package/dist/shims/script.js.map +1 -1
  44. package/dist/shims/server.d.ts +17 -4
  45. package/dist/shims/server.js +91 -73
  46. package/dist/shims/server.js.map +1 -1
  47. package/dist/shims/slot.d.ts +28 -0
  48. package/dist/shims/slot.js +49 -0
  49. package/dist/shims/slot.js.map +1 -0
  50. package/package.json +1 -2
@@ -200,10 +200,54 @@ function getPathnameAndQuery() {
200
200
  };
201
201
  }
202
202
  /**
203
+ * Error thrown when a navigation is superseded by a newer one.
204
+ * Matches Next.js's convention of an Error with `.cancelled = true`.
205
+ */
206
+ var NavigationCancelledError = class extends Error {
207
+ cancelled = true;
208
+ constructor(route) {
209
+ super(`Abort fetching component for route: "${route}"`);
210
+ this.name = "NavigationCancelledError";
211
+ }
212
+ };
213
+ /**
214
+ * Error thrown after queueing a hard navigation fallback for a known failure
215
+ * mode. Callers can use this to avoid scheduling the same hard navigation twice.
216
+ */
217
+ var HardNavigationScheduledError = class extends Error {
218
+ hardNavigationScheduled = true;
219
+ constructor(message) {
220
+ super(message);
221
+ this.name = "HardNavigationScheduledError";
222
+ }
223
+ };
224
+ /**
225
+ * Monotonically increasing ID for tracking the current navigation.
226
+ * Each call to navigateClient() increments this and captures the value.
227
+ * After each async boundary, the navigation checks whether it is still
228
+ * the active one. If a newer navigation has started, the stale one
229
+ * throws NavigationCancelledError so the caller can emit routeChangeError
230
+ * and skip routeChangeComplete.
231
+ *
232
+ * Replaces the old boolean `_navInProgress` guard which silently dropped
233
+ * the second navigation, causing URL/content mismatch.
234
+ */
235
+ let _navigationId = 0;
236
+ /** AbortController for the in-flight fetch, so superseded navigations abort network I/O. */
237
+ let _activeAbortController = null;
238
+ function scheduleHardNavigationAndThrow(url, message) {
239
+ if (typeof window === "undefined") throw new HardNavigationScheduledError(message);
240
+ window.location.href = url;
241
+ throw new HardNavigationScheduledError(message);
242
+ }
243
+ /**
203
244
  * Perform client-side navigation: fetch the target page's HTML,
204
245
  * extract __NEXT_DATA__, and re-render the React root.
246
+ *
247
+ * Throws NavigationCancelledError if a newer navigation supersedes this one.
248
+ * Throws on hard-navigation failures (non-OK response, missing data) so the
249
+ * caller can distinguish success from failure for event emission.
205
250
  */
206
- let _navInProgress = false;
207
251
  async function navigateClient(url) {
208
252
  if (typeof window === "undefined") return;
209
253
  const root = window.__VINEXT_ROOT__;
@@ -211,47 +255,53 @@ async function navigateClient(url) {
211
255
  window.location.href = url;
212
256
  return;
213
257
  }
214
- if (_navInProgress) return;
215
- _navInProgress = true;
258
+ _activeAbortController?.abort();
259
+ const controller = new AbortController();
260
+ _activeAbortController = controller;
261
+ const navId = ++_navigationId;
262
+ /** Check if this navigation is still the active one. If not, throw. */
263
+ function assertStillCurrent() {
264
+ if (navId !== _navigationId) throw new NavigationCancelledError(url);
265
+ }
216
266
  try {
217
- const res = await fetch(url, { headers: { Accept: "text/html" } });
218
- if (!res.ok) {
219
- window.location.href = url;
220
- return;
267
+ let res;
268
+ try {
269
+ res = await fetch(url, {
270
+ headers: { Accept: "text/html" },
271
+ signal: controller.signal
272
+ });
273
+ } catch (err) {
274
+ if (err instanceof DOMException && err.name === "AbortError") throw new NavigationCancelledError(url);
275
+ throw err;
221
276
  }
277
+ assertStillCurrent();
278
+ if (!res.ok) scheduleHardNavigationAndThrow(url, `Navigation failed: ${res.status} ${res.statusText}`);
222
279
  const html = await res.text();
280
+ assertStillCurrent();
223
281
  const match = html.match(/<script>window\.__NEXT_DATA__\s*=\s*(.*?)<\/script>/);
224
- if (!match) {
225
- window.location.href = url;
226
- return;
227
- }
282
+ if (!match) scheduleHardNavigationAndThrow(url, "Navigation failed: missing __NEXT_DATA__ in response");
228
283
  const nextData = JSON.parse(match[1]);
229
284
  const { pageProps } = nextData.props;
230
- window.__NEXT_DATA__ = nextData;
231
285
  let pageModuleUrl = nextData.__vinext?.pageModuleUrl;
232
286
  if (!pageModuleUrl) {
233
287
  const moduleMatch = html.match(/import\("([^"]+)"\);\s*\n\s*const PageComponent/);
234
288
  const altMatch = html.match(/await import\("([^"]+pages\/[^"]+)"\)/);
235
289
  pageModuleUrl = moduleMatch?.[1] ?? altMatch?.[1] ?? void 0;
236
290
  }
237
- if (!pageModuleUrl) {
238
- window.location.href = url;
239
- return;
240
- }
291
+ if (!pageModuleUrl) scheduleHardNavigationAndThrow(url, "Navigation failed: no page module URL found");
241
292
  if (!isValidModulePath(pageModuleUrl)) {
242
293
  console.error("[vinext] Blocked import of invalid page module path:", pageModuleUrl);
243
- window.location.href = url;
244
- return;
294
+ scheduleHardNavigationAndThrow(url, "Navigation failed: invalid page module path");
245
295
  }
246
- const PageComponent = (await import(
296
+ const pageModule = await import(
247
297
  /* @vite-ignore */
248
298
  pageModuleUrl
249
- )).default;
250
- if (!PageComponent) {
251
- window.location.href = url;
252
- return;
253
- }
299
+ );
300
+ assertStillCurrent();
301
+ const PageComponent = pageModule.default;
302
+ if (!PageComponent) scheduleHardNavigationAndThrow(url, "Navigation failed: page module has no default export");
254
303
  const React = (await import("react")).default;
304
+ assertStillCurrent();
255
305
  let AppComponent = window.__VINEXT_APP__;
256
306
  const appModuleUrl = nextData.__vinext?.appModuleUrl;
257
307
  if (!AppComponent && appModuleUrl) if (!isValidModulePath(appModuleUrl)) console.error("[vinext] Blocked import of invalid app module path:", appModuleUrl);
@@ -262,6 +312,7 @@ async function navigateClient(url) {
262
312
  )).default;
263
313
  window.__VINEXT_APP__ = AppComponent;
264
314
  } catch {}
315
+ assertStillCurrent();
265
316
  let element;
266
317
  if (AppComponent) element = React.createElement(AppComponent, {
267
318
  Component: PageComponent,
@@ -269,13 +320,33 @@ async function navigateClient(url) {
269
320
  });
270
321
  else element = React.createElement(PageComponent, pageProps);
271
322
  element = wrapWithRouterContext(element);
323
+ window.__NEXT_DATA__ = nextData;
272
324
  root.render(element);
273
- } catch (err) {
274
- console.error("[vinext] Client navigation failed:", err);
275
- routerEvents.emit("routeChangeError", err, url, { shallow: false });
276
- window.location.href = url;
277
325
  } finally {
278
- _navInProgress = false;
326
+ if (navId === _navigationId) _activeAbortController = null;
327
+ }
328
+ }
329
+ /**
330
+ * Run navigateClient and handle errors: emit routeChangeError on failure,
331
+ * and fall back to a hard navigation for non-cancel errors so the browser
332
+ * recovers to a consistent state.
333
+ *
334
+ * Returns:
335
+ * - "completed" — navigation finished, caller should emit routeChangeComplete
336
+ * - "cancelled" — superseded by a newer navigation, caller should return true
337
+ * without emitting routeChangeComplete (matches Next.js behaviour)
338
+ * - "failed" — genuine error, caller should return false (hard nav is already
339
+ * scheduled as recovery)
340
+ */
341
+ async function runNavigateClient(fullUrl, resolvedUrl) {
342
+ try {
343
+ await navigateClient(fullUrl);
344
+ return "completed";
345
+ } catch (err) {
346
+ routerEvents.emit("routeChangeError", err, resolvedUrl, { shallow: false });
347
+ if (err instanceof NavigationCancelledError) return "cancelled";
348
+ if (typeof window !== "undefined" && !(err instanceof HardNavigationScheduledError)) window.location.href = fullUrl;
349
+ return "failed";
279
350
  }
280
351
  }
281
352
  /**
@@ -348,7 +419,11 @@ function useRouter() {
348
419
  routerEvents.emit("beforeHistoryChange", resolved, { shallow: options?.shallow ?? false });
349
420
  window.history.pushState({}, "", full);
350
421
  _lastPathnameAndSearch = window.location.pathname + window.location.search;
351
- if (!options?.shallow) await navigateClient(full);
422
+ if (!options?.shallow) {
423
+ const result = await runNavigateClient(full, resolved);
424
+ if (result === "cancelled") return true;
425
+ if (result === "failed") return false;
426
+ }
352
427
  setState(getPathnameAndQuery());
353
428
  routerEvents.emit("routeChangeComplete", resolved, { shallow: options?.shallow ?? false });
354
429
  const hash = resolved.includes("#") ? resolved.slice(resolved.indexOf("#")) : "";
@@ -384,7 +459,11 @@ function useRouter() {
384
459
  routerEvents.emit("beforeHistoryChange", resolved, { shallow: options?.shallow ?? false });
385
460
  window.history.replaceState({}, "", full);
386
461
  _lastPathnameAndSearch = window.location.pathname + window.location.search;
387
- if (!options?.shallow) await navigateClient(full);
462
+ if (!options?.shallow) {
463
+ const result = await runNavigateClient(full, resolved);
464
+ if (result === "cancelled") return true;
465
+ if (result === "failed") return false;
466
+ }
388
467
  setState(getPathnameAndQuery());
389
468
  routerEvents.emit("routeChangeComplete", resolved, { shallow: options?.shallow ?? false });
390
469
  const hash = resolved.includes("#") ? resolved.slice(resolved.indexOf("#")) : "";
@@ -453,11 +532,13 @@ if (typeof window !== "undefined") window.addEventListener("popstate", (e) => {
453
532
  const fullAppUrl = appUrl + window.location.hash;
454
533
  routerEvents.emit("routeChangeStart", fullAppUrl, { shallow: false });
455
534
  routerEvents.emit("beforeHistoryChange", fullAppUrl, { shallow: false });
456
- navigateClient(browserUrl).then(() => {
457
- routerEvents.emit("routeChangeComplete", fullAppUrl, { shallow: false });
458
- restoreScrollPosition(e.state);
459
- window.dispatchEvent(new CustomEvent("vinext:navigate"));
460
- });
535
+ (async () => {
536
+ if (await runNavigateClient(browserUrl, fullAppUrl) === "completed") {
537
+ routerEvents.emit("routeChangeComplete", fullAppUrl, { shallow: false });
538
+ restoreScrollPosition(e.state);
539
+ window.dispatchEvent(new CustomEvent("vinext:navigate"));
540
+ }
541
+ })();
461
542
  });
462
543
  /**
463
544
  * Wrap a React element in a RouterContext.Provider so that
@@ -508,7 +589,11 @@ const Router = {
508
589
  routerEvents.emit("beforeHistoryChange", resolved, { shallow: options?.shallow ?? false });
509
590
  window.history.pushState({}, "", full);
510
591
  _lastPathnameAndSearch = window.location.pathname + window.location.search;
511
- if (!options?.shallow) await navigateClient(full);
592
+ if (!options?.shallow) {
593
+ const result = await runNavigateClient(full, resolved);
594
+ if (result === "cancelled") return true;
595
+ if (result === "failed") return false;
596
+ }
512
597
  routerEvents.emit("routeChangeComplete", resolved, { shallow: options?.shallow ?? false });
513
598
  const hash = resolved.includes("#") ? resolved.slice(resolved.indexOf("#")) : "";
514
599
  if (hash) scrollToHash(hash);
@@ -542,7 +627,11 @@ const Router = {
542
627
  routerEvents.emit("beforeHistoryChange", resolved, { shallow: options?.shallow ?? false });
543
628
  window.history.replaceState({}, "", full);
544
629
  _lastPathnameAndSearch = window.location.pathname + window.location.search;
545
- if (!options?.shallow) await navigateClient(full);
630
+ if (!options?.shallow) {
631
+ const result = await runNavigateClient(full, resolved);
632
+ if (result === "cancelled") return true;
633
+ if (result === "failed") return false;
634
+ }
546
635
  routerEvents.emit("routeChangeComplete", resolved, { shallow: options?.shallow ?? false });
547
636
  const hash = resolved.includes("#") ? resolved.slice(resolved.indexOf("#")) : "";
548
637
  if (hash) scrollToHash(hash);
@@ -1 +1 @@
1
- {"version":3,"file":"router.js","names":[],"sources":["../../src/shims/router.ts"],"sourcesContent":["/**\n * next/router shim\n *\n * Provides useRouter() hook and Router singleton for Pages Router.\n * Backed by the browser History API. Supports client-side navigation\n * by fetching new page data and re-rendering the React root.\n */\nimport { useState, useEffect, useCallback, useMemo, createElement, type ReactElement } from \"react\";\nimport { RouterContext } from \"./internal/router-context.js\";\nimport type { VinextNextData } from \"../client/vinext-next-data.js\";\nimport { isValidModulePath } from \"../client/validate-module-path.js\";\nimport { toBrowserNavigationHref, toSameOriginAppPath } from \"./url-utils.js\";\nimport { stripBasePath } from \"../utils/base-path.js\";\nimport { addLocalePrefix, getDomainLocaleUrl, type DomainLocale } from \"../utils/domain-locale.js\";\nimport {\n addQueryParam,\n appendSearchParamsToUrl,\n type UrlQuery,\n urlQueryToSearchParams,\n} from \"../utils/query.js\";\n\n/** basePath from next.config.js, injected by the plugin at build time */\nconst __basePath: string = process.env.__NEXT_ROUTER_BASEPATH ?? \"\";\n\ntype BeforePopStateCallback = (state: {\n url: string;\n as: string;\n options: { shallow: boolean };\n}) => boolean;\n\nexport type NextRouter = {\n /** Current pathname */\n pathname: string;\n /** Current route pattern (e.g., \"/posts/[id]\") */\n route: string;\n /** Query parameters */\n query: Record<string, string | string[]>;\n /** Full URL including query string */\n asPath: string;\n /** Base path */\n basePath: string;\n /** Current locale */\n locale?: string;\n /** Available locales */\n locales?: string[];\n /** Default locale */\n defaultLocale?: string;\n /** Configured domain locales */\n domainLocales?: VinextNextData[\"domainLocales\"];\n /** Whether the router is ready */\n isReady: boolean;\n /** Whether this is a preview */\n isPreview: boolean;\n /** Whether this is a fallback page */\n isFallback: boolean;\n\n /** Navigate to a new URL */\n push(url: string | UrlObject, as?: string, options?: TransitionOptions): Promise<boolean>;\n /** Replace current URL */\n replace(url: string | UrlObject, as?: string, options?: TransitionOptions): Promise<boolean>;\n /** Go back */\n back(): void;\n /** Reload the page */\n reload(): void;\n /** Prefetch a page (injects <link rel=\"prefetch\">) */\n prefetch(url: string): Promise<void>;\n /** Register a callback to run before popstate navigation */\n beforePopState(cb: BeforePopStateCallback): void;\n /** Listen for route changes */\n events: RouterEvents;\n};\n\ntype UrlObject = {\n pathname?: string;\n query?: UrlQuery;\n};\n\ntype TransitionOptions = {\n shallow?: boolean;\n scroll?: boolean;\n locale?: string;\n};\n\ntype RouterEvents = {\n on(event: string, handler: (...args: unknown[]) => void): void;\n off(event: string, handler: (...args: unknown[]) => void): void;\n emit(event: string, ...args: unknown[]): void;\n};\n\nfunction createRouterEvents(): RouterEvents {\n const listeners = new Map<string, Set<(...args: unknown[]) => void>>();\n\n return {\n on(event: string, handler: (...args: unknown[]) => void) {\n if (!listeners.has(event)) listeners.set(event, new Set());\n (listeners.get(event) as Set<(...args: unknown[]) => void>).add(handler);\n },\n off(event: string, handler: (...args: unknown[]) => void) {\n listeners.get(event)?.delete(handler);\n },\n emit(event: string, ...args: unknown[]) {\n listeners.get(event)?.forEach((handler) => handler(...args));\n },\n };\n}\n\n// Singleton events instance\nconst routerEvents = createRouterEvents();\n\nfunction resolveUrl(url: string | UrlObject): string {\n if (typeof url === \"string\") return url;\n let result = url.pathname ?? \"/\";\n if (url.query) {\n const params = urlQueryToSearchParams(url.query);\n result = appendSearchParamsToUrl(result, params);\n }\n return result;\n}\n\n/**\n * When `as` is provided, use it as the navigation target. This is a\n * simplification: Next.js keeps `url` and `as` as separate values (url for\n * data fetching, as for the browser URL). We collapse them because vinext's\n * navigateClient() fetches HTML from the target URL, so `as` must be a\n * server-resolvable path. Purely decorative `as` values are not supported.\n */\nfunction resolveNavigationTarget(\n url: string | UrlObject,\n as: string | undefined,\n locale: string | undefined,\n): string {\n return applyNavigationLocale(as ?? resolveUrl(url), locale);\n}\n\nfunction getDomainLocales(): readonly DomainLocale[] | undefined {\n return (window.__NEXT_DATA__ as VinextNextData | undefined)?.domainLocales;\n}\n\nfunction getCurrentHostname(): string | undefined {\n return window.location?.hostname;\n}\n\nfunction getDomainLocalePath(url: string, locale: string): string | undefined {\n return getDomainLocaleUrl(url, locale, {\n basePath: __basePath,\n currentHostname: getCurrentHostname(),\n domainItems: getDomainLocales(),\n });\n}\n\n/**\n * Apply locale prefix to a URL for client-side navigation.\n * Same logic as Link's applyLocaleToHref but reads from window globals.\n */\nexport function applyNavigationLocale(url: string, locale?: string): string {\n if (!locale || typeof window === \"undefined\") return url;\n // Absolute and protocol-relative URLs must not be prefixed — locale\n // only applies to local paths.\n if (url.startsWith(\"http://\") || url.startsWith(\"https://\") || url.startsWith(\"//\")) {\n return url;\n }\n\n const domainLocalePath = getDomainLocalePath(url, locale);\n if (domainLocalePath) return domainLocalePath;\n\n return addLocalePrefix(url, locale, window.__VINEXT_DEFAULT_LOCALE__ ?? \"\");\n}\n\n/** Check if a URL is external (any URL scheme per RFC 3986, or protocol-relative) */\nexport function isExternalUrl(url: string): boolean {\n return /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith(\"//\");\n}\n\n/** Resolve a hash URL to a basePath-stripped app URL for event payloads */\nfunction resolveHashUrl(url: string): string {\n if (typeof window === \"undefined\") return url;\n if (url.startsWith(\"#\"))\n return stripBasePath(window.location.pathname, __basePath) + window.location.search + url;\n // Full-path hash URL — strip basePath for consistency with other events\n try {\n const parsed = new URL(url, window.location.href);\n return stripBasePath(parsed.pathname, __basePath) + parsed.search + parsed.hash;\n } catch {\n return url;\n }\n}\n\n/** Check if a href is only a hash change relative to the current URL */\nexport function isHashOnlyChange(href: string): boolean {\n if (href.startsWith(\"#\")) return true;\n if (typeof window === \"undefined\") return false;\n try {\n const current = new URL(window.location.href);\n const next = new URL(href, window.location.href);\n return current.pathname === next.pathname && current.search === next.search && next.hash !== \"\";\n } catch {\n return false;\n }\n}\n\n/** Scroll to hash target element, or top if no hash */\nfunction scrollToHash(hash: string): void {\n if (!hash || hash === \"#\") {\n window.scrollTo(0, 0);\n return;\n }\n const el = document.getElementById(hash.slice(1));\n if (el) el.scrollIntoView({ behavior: \"auto\" });\n}\n\n/** Save current scroll position into history state for back/forward restoration */\nfunction saveScrollPosition(): void {\n const state = window.history.state ?? {};\n window.history.replaceState(\n { ...state, __vinext_scrollX: window.scrollX, __vinext_scrollY: window.scrollY },\n \"\",\n );\n}\n\n/** Restore scroll position from history state */\nfunction restoreScrollPosition(state: unknown): void {\n if (state && typeof state === \"object\" && \"__vinext_scrollY\" in state) {\n const { __vinext_scrollX: x, __vinext_scrollY: y } = state as {\n __vinext_scrollX: number;\n __vinext_scrollY: number;\n };\n requestAnimationFrame(() => window.scrollTo(x, y));\n }\n}\n\n/**\n * SSR context - set by the dev server before rendering each page.\n */\ntype SSRContext = {\n pathname: string;\n query: Record<string, string | string[]>;\n asPath: string;\n locale?: string;\n locales?: string[];\n defaultLocale?: string;\n domainLocales?: VinextNextData[\"domainLocales\"];\n};\n\n// ---------------------------------------------------------------------------\n// Server-side SSR state uses a registration pattern so this module can be\n// bundled for the browser. The ALS-backed implementation lives in\n// router-state.ts (server-only) and registers itself on import.\n// ---------------------------------------------------------------------------\n\nlet _ssrContext: SSRContext | null = null;\n\nlet _getSSRContext = (): SSRContext | null => _ssrContext;\nlet _setSSRContextImpl = (ctx: SSRContext | null): void => {\n _ssrContext = ctx;\n};\n\n/**\n * Register ALS-backed state accessors. Called by router-state.ts on import.\n * @internal\n */\nexport function _registerRouterStateAccessors(accessors: {\n getSSRContext: () => SSRContext | null;\n setSSRContext: (ctx: SSRContext | null) => void;\n}): void {\n _getSSRContext = accessors.getSSRContext;\n _setSSRContextImpl = accessors.setSSRContext;\n}\n\nexport function setSSRContext(ctx: SSRContext | null): void {\n _setSSRContextImpl(ctx);\n}\n\n/**\n * Extract param names from a Next.js route pattern.\n * E.g., \"/posts/[id]\" → [\"id\"], \"/docs/[...slug]\" → [\"slug\"],\n * \"/shop/[[...path]]\" → [\"path\"], \"/blog/[year]/[month]\" → [\"year\", \"month\"]\n * Also handles internal format: \"/posts/:id\" → [\"id\"], \"/docs/:slug+\" → [\"slug\"]\n */\nfunction extractRouteParamNames(pattern: string): string[] {\n const names: string[] = [];\n // Match Next.js bracket format: [id], [...slug], [[...slug]]\n const bracketMatches = pattern.matchAll(/\\[{1,2}(?:\\.\\.\\.)?([\\w-]+)\\]{1,2}/g);\n for (const m of bracketMatches) {\n names.push(m[1]);\n }\n if (names.length > 0) return names;\n // Fallback: match internal :param format\n const colonMatches = pattern.matchAll(/:([\\w-]+)[+*]?/g);\n for (const m of colonMatches) {\n names.push(m[1]);\n }\n return names;\n}\n\nfunction getPathnameAndQuery(): {\n pathname: string;\n query: Record<string, string | string[]>;\n asPath: string;\n} {\n if (typeof window === \"undefined\") {\n const _ssrCtx = _getSSRContext();\n if (_ssrCtx) {\n const query: Record<string, string | string[]> = {};\n for (const [key, value] of Object.entries(_ssrCtx.query)) {\n query[key] = Array.isArray(value) ? [...value] : value;\n }\n return { pathname: _ssrCtx.pathname, query, asPath: _ssrCtx.asPath };\n }\n return { pathname: \"/\", query: {}, asPath: \"/\" };\n }\n const resolvedPath = stripBasePath(window.location.pathname, __basePath);\n // In Next.js, router.pathname is the route pattern (e.g., \"/posts/[id]\"),\n // not the resolved path (\"/posts/42\"). __NEXT_DATA__.page holds the route\n // pattern and is updated by navigateClient() on every client-side navigation.\n const pathname = window.__NEXT_DATA__?.page ?? resolvedPath;\n const routeQuery: Record<string, string | string[]> = {};\n // Include dynamic route params from __NEXT_DATA__ (e.g., { id: \"42\" } from /posts/[id]).\n // Only include keys that are part of the route pattern (not stale query params).\n const nextData = window.__NEXT_DATA__;\n if (nextData && nextData.query && nextData.page) {\n const routeParamNames = extractRouteParamNames(nextData.page);\n for (const key of routeParamNames) {\n const value = nextData.query[key];\n if (typeof value === \"string\") {\n routeQuery[key] = value;\n } else if (Array.isArray(value)) {\n routeQuery[key] = [...value];\n }\n }\n }\n // URL search params always reflect the current URL\n const searchQuery: Record<string, string | string[]> = {};\n const params = new URLSearchParams(window.location.search);\n for (const [key, value] of params) {\n addQueryParam(searchQuery, key, value);\n }\n const query = { ...searchQuery, ...routeQuery };\n // asPath uses the resolved browser path, not the route pattern\n const asPath = resolvedPath + window.location.search + window.location.hash;\n return { pathname, query, asPath };\n}\n\n/**\n * Perform client-side navigation: fetch the target page's HTML,\n * extract __NEXT_DATA__, and re-render the React root.\n */\nlet _navInProgress = false;\nasync function navigateClient(url: string): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const root = window.__VINEXT_ROOT__;\n if (!root) {\n // No React root yet — fall back to hard navigation\n window.location.href = url;\n return;\n }\n\n // Prevent re-entrant navigation (e.g., double popstate events)\n if (_navInProgress) return;\n _navInProgress = true;\n\n try {\n // Fetch the target page's SSR HTML\n const res = await fetch(url, { headers: { Accept: \"text/html\" } });\n if (!res.ok) {\n window.location.href = url;\n return;\n }\n\n const html = await res.text();\n\n // Extract __NEXT_DATA__ from the HTML\n const match = html.match(/<script>window\\.__NEXT_DATA__\\s*=\\s*(.*?)<\\/script>/);\n if (!match) {\n window.location.href = url;\n return;\n }\n\n const nextData = JSON.parse(match[1]);\n const { pageProps } = nextData.props;\n window.__NEXT_DATA__ = nextData;\n\n // Get the page module URL from __NEXT_DATA__.__vinext (preferred),\n // or fall back to parsing the hydration script\n let pageModuleUrl: string | undefined = nextData.__vinext?.pageModuleUrl;\n\n if (!pageModuleUrl) {\n // Legacy fallback: try to find the module URL in the inline script\n const moduleMatch = html.match(/import\\(\"([^\"]+)\"\\);\\s*\\n\\s*const PageComponent/);\n const altMatch = html.match(/await import\\(\"([^\"]+pages\\/[^\"]+)\"\\)/);\n pageModuleUrl = moduleMatch?.[1] ?? altMatch?.[1] ?? undefined;\n }\n\n if (!pageModuleUrl) {\n window.location.href = url;\n return;\n }\n\n // Validate the module URL before importing — defense-in-depth against\n // unexpected __NEXT_DATA__ or malformed HTML responses\n if (!isValidModulePath(pageModuleUrl)) {\n console.error(\"[vinext] Blocked import of invalid page module path:\", pageModuleUrl);\n window.location.href = url;\n return;\n }\n\n // Dynamically import the new page module\n const pageModule = await import(/* @vite-ignore */ pageModuleUrl);\n const PageComponent = pageModule.default;\n\n if (!PageComponent) {\n window.location.href = url;\n return;\n }\n\n // Import React for createElement\n const React = (await import(\"react\")).default;\n\n // Re-render with the new page, loading _app if needed\n let AppComponent = window.__VINEXT_APP__;\n const appModuleUrl: string | undefined = nextData.__vinext?.appModuleUrl;\n\n if (!AppComponent && appModuleUrl) {\n if (!isValidModulePath(appModuleUrl)) {\n console.error(\"[vinext] Blocked import of invalid app module path:\", appModuleUrl);\n } else {\n try {\n const appModule = await import(/* @vite-ignore */ appModuleUrl);\n AppComponent = appModule.default;\n window.__VINEXT_APP__ = AppComponent;\n } catch {\n // _app not available — continue without it\n }\n }\n }\n\n let element;\n if (AppComponent) {\n element = React.createElement(AppComponent, {\n Component: PageComponent,\n pageProps,\n });\n } else {\n element = React.createElement(PageComponent, pageProps);\n }\n\n // Wrap with RouterContext.Provider so next/compat/router works\n element = wrapWithRouterContext(element);\n\n root.render(element);\n } catch (err) {\n console.error(\"[vinext] Client navigation failed:\", err);\n routerEvents.emit(\"routeChangeError\", err, url, { shallow: false });\n window.location.href = url;\n } finally {\n _navInProgress = false;\n }\n}\n\n/**\n * Build the full router value object from the current pathname, query, asPath,\n * and a set of navigation methods. Shared by useRouter() (which passes\n * hook-derived callbacks) and wrapWithRouterContext() (which passes the Router\n * singleton methods) so the shape stays in sync.\n */\nfunction buildRouterValue(\n pathname: string,\n query: Record<string, string | string[]>,\n asPath: string,\n methods: {\n push: NextRouter[\"push\"];\n replace: NextRouter[\"replace\"];\n back: NextRouter[\"back\"];\n reload: NextRouter[\"reload\"];\n prefetch: NextRouter[\"prefetch\"];\n beforePopState: NextRouter[\"beforePopState\"];\n },\n): NextRouter {\n const _ssrState = _getSSRContext();\n const nextData =\n typeof window !== \"undefined\"\n ? (window.__NEXT_DATA__ as VinextNextData | undefined)\n : undefined;\n const locale = typeof window === \"undefined\" ? _ssrState?.locale : window.__VINEXT_LOCALE__;\n const locales = typeof window === \"undefined\" ? _ssrState?.locales : window.__VINEXT_LOCALES__;\n const defaultLocale =\n typeof window === \"undefined\" ? _ssrState?.defaultLocale : window.__VINEXT_DEFAULT_LOCALE__;\n const domainLocales =\n typeof window === \"undefined\" ? _ssrState?.domainLocales : nextData?.domainLocales;\n\n const route = typeof window !== \"undefined\" ? (nextData?.page ?? pathname) : pathname;\n\n return {\n pathname,\n route,\n query,\n asPath,\n basePath: __basePath,\n locale,\n locales,\n defaultLocale,\n domainLocales,\n isReady: true,\n isPreview: false,\n isFallback: typeof window !== \"undefined\" && nextData?.isFallback === true,\n ...methods,\n events: routerEvents,\n };\n}\n\n/**\n * useRouter hook - Pages Router compatible.\n */\nexport function useRouter(): NextRouter {\n const [{ pathname, query, asPath }, setState] = useState(getPathnameAndQuery);\n\n // Popstate is handled by the module-level listener below so beforePopState()\n // is consistently enforced even when multiple components mount useRouter().\n useEffect(() => {\n const onNavigate = ((_e: CustomEvent) => {\n setState(getPathnameAndQuery());\n }) as EventListener;\n window.addEventListener(\"vinext:navigate\", onNavigate);\n return () => window.removeEventListener(\"vinext:navigate\", onNavigate);\n }, []);\n\n const push = useCallback(\n async (url: string | UrlObject, as?: string, options?: TransitionOptions): Promise<boolean> => {\n let resolved = resolveNavigationTarget(url, as, options?.locale);\n\n // External URLs — delegate to browser (unless same-origin)\n if (isExternalUrl(resolved)) {\n const localPath = toSameOriginAppPath(resolved, __basePath);\n if (localPath == null) {\n window.location.assign(resolved);\n return true;\n }\n resolved = localPath;\n }\n\n const full = toBrowserNavigationHref(resolved, window.location.href, __basePath);\n\n // Hash-only change — no page fetch needed\n if (isHashOnlyChange(resolved)) {\n const eventUrl = resolveHashUrl(resolved);\n routerEvents.emit(\"hashChangeStart\", eventUrl, {\n shallow: options?.shallow ?? false,\n });\n const hash = resolved.includes(\"#\") ? resolved.slice(resolved.indexOf(\"#\")) : \"\";\n window.history.pushState({}, \"\", resolved.startsWith(\"#\") ? resolved : full);\n _lastPathnameAndSearch = window.location.pathname + window.location.search;\n scrollToHash(hash);\n setState(getPathnameAndQuery());\n routerEvents.emit(\"hashChangeComplete\", eventUrl, {\n shallow: options?.shallow ?? false,\n });\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return true;\n }\n\n saveScrollPosition();\n routerEvents.emit(\"routeChangeStart\", resolved, { shallow: options?.shallow ?? false });\n routerEvents.emit(\"beforeHistoryChange\", resolved, { shallow: options?.shallow ?? false });\n window.history.pushState({}, \"\", full);\n _lastPathnameAndSearch = window.location.pathname + window.location.search;\n if (!options?.shallow) {\n await navigateClient(full);\n }\n setState(getPathnameAndQuery());\n routerEvents.emit(\"routeChangeComplete\", resolved, { shallow: options?.shallow ?? false });\n\n // Scroll: handle hash target, else scroll to top unless scroll:false\n const hash = resolved.includes(\"#\") ? resolved.slice(resolved.indexOf(\"#\")) : \"\";\n if (hash) {\n scrollToHash(hash);\n } else if (options?.scroll !== false) {\n window.scrollTo(0, 0);\n }\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return true;\n },\n [],\n );\n\n const replace = useCallback(\n async (url: string | UrlObject, as?: string, options?: TransitionOptions): Promise<boolean> => {\n let resolved = resolveNavigationTarget(url, as, options?.locale);\n\n // External URLs — delegate to browser (unless same-origin)\n if (isExternalUrl(resolved)) {\n const localPath = toSameOriginAppPath(resolved, __basePath);\n if (localPath == null) {\n window.location.replace(resolved);\n return true;\n }\n resolved = localPath;\n }\n\n const full = toBrowserNavigationHref(resolved, window.location.href, __basePath);\n\n // Hash-only change — no page fetch needed\n if (isHashOnlyChange(resolved)) {\n const eventUrl = resolveHashUrl(resolved);\n routerEvents.emit(\"hashChangeStart\", eventUrl, {\n shallow: options?.shallow ?? false,\n });\n const hash = resolved.includes(\"#\") ? resolved.slice(resolved.indexOf(\"#\")) : \"\";\n window.history.replaceState({}, \"\", resolved.startsWith(\"#\") ? resolved : full);\n _lastPathnameAndSearch = window.location.pathname + window.location.search;\n scrollToHash(hash);\n setState(getPathnameAndQuery());\n routerEvents.emit(\"hashChangeComplete\", eventUrl, {\n shallow: options?.shallow ?? false,\n });\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return true;\n }\n\n routerEvents.emit(\"routeChangeStart\", resolved, { shallow: options?.shallow ?? false });\n routerEvents.emit(\"beforeHistoryChange\", resolved, { shallow: options?.shallow ?? false });\n window.history.replaceState({}, \"\", full);\n _lastPathnameAndSearch = window.location.pathname + window.location.search;\n if (!options?.shallow) {\n await navigateClient(full);\n }\n setState(getPathnameAndQuery());\n routerEvents.emit(\"routeChangeComplete\", resolved, { shallow: options?.shallow ?? false });\n\n // Scroll: handle hash target, else scroll to top unless scroll:false\n const hash = resolved.includes(\"#\") ? resolved.slice(resolved.indexOf(\"#\")) : \"\";\n if (hash) {\n scrollToHash(hash);\n } else if (options?.scroll !== false) {\n window.scrollTo(0, 0);\n }\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return true;\n },\n [],\n );\n\n const back = useCallback(() => {\n window.history.back();\n }, []);\n\n const reload = useCallback(() => {\n window.location.reload();\n }, []);\n\n const prefetch = useCallback(async (url: string): Promise<void> => {\n // Inject a <link rel=\"prefetch\"> for the target page\n if (typeof document !== \"undefined\") {\n const link = document.createElement(\"link\");\n link.rel = \"prefetch\";\n link.href = url;\n link.as = \"document\";\n document.head.appendChild(link);\n }\n }, []);\n\n const router = useMemo(\n (): NextRouter =>\n buildRouterValue(pathname, query, asPath, {\n push,\n replace,\n back,\n reload,\n prefetch,\n beforePopState: (cb: BeforePopStateCallback) => {\n _beforePopStateCb = cb;\n },\n }),\n [pathname, query, asPath, push, replace, back, reload, prefetch],\n );\n\n return router;\n}\n\n// beforePopState callback: called before handling browser back/forward.\n// If it returns false, the navigation is cancelled.\nlet _beforePopStateCb: BeforePopStateCallback | undefined;\n\n// Track pathname+search for detecting hash-only back/forward in the popstate\n// handler. Updated after every pushState/replaceState so that popstate can\n// compare the previous value with the (already-changed) window.location.\nlet _lastPathnameAndSearch =\n typeof window !== \"undefined\" ? window.location.pathname + window.location.search : \"\";\n\n// Module-level popstate listener: handles browser back/forward by re-rendering\n// the React root with the page at the new URL. This runs regardless of whether\n// any component calls useRouter().\nif (typeof window !== \"undefined\") {\n window.addEventListener(\"popstate\", (e: PopStateEvent) => {\n const browserUrl = window.location.pathname + window.location.search;\n const appUrl = stripBasePath(window.location.pathname, __basePath) + window.location.search;\n\n // Detect hash-only back/forward: pathname+search unchanged, only hash differs.\n const isHashOnly = browserUrl === _lastPathnameAndSearch;\n\n // Check beforePopState callback\n if (_beforePopStateCb !== undefined) {\n const shouldContinue = (_beforePopStateCb as BeforePopStateCallback)({\n url: appUrl,\n as: appUrl,\n options: { shallow: false },\n });\n if (!shouldContinue) return;\n }\n\n // Update tracker only after beforePopState confirms navigation proceeds.\n // If beforePopState cancels, the tracker must retain the previous value\n // so the next popstate compares against the correct baseline.\n _lastPathnameAndSearch = browserUrl;\n\n if (isHashOnly) {\n // Hash-only back/forward — no page fetch needed\n const hashUrl = appUrl + window.location.hash;\n routerEvents.emit(\"hashChangeStart\", hashUrl, { shallow: false });\n scrollToHash(window.location.hash);\n routerEvents.emit(\"hashChangeComplete\", hashUrl, { shallow: false });\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return;\n }\n\n const fullAppUrl = appUrl + window.location.hash;\n routerEvents.emit(\"routeChangeStart\", fullAppUrl, { shallow: false });\n // Note: The browser has already updated window.location by the time popstate\n // fires, so this is not truly \"before\" the URL change. In Next.js the popstate\n // handler calls replaceState to store history metadata — beforeHistoryChange\n // precedes that call, not the URL change itself. We emit it here for API\n // compatibility.\n routerEvents.emit(\"beforeHistoryChange\", fullAppUrl, { shallow: false });\n void navigateClient(browserUrl).then(() => {\n routerEvents.emit(\"routeChangeComplete\", fullAppUrl, { shallow: false });\n restoreScrollPosition(e.state);\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n });\n });\n}\n\n/**\n * Wrap a React element in a RouterContext.Provider so that\n * next/compat/router's useRouter() returns the real Pages Router value.\n *\n * This is a plain function, NOT a React component — it builds the router\n * value object directly from the current SSR context (server) or\n * window.location + Router singleton (client), avoiding duplicate state\n * that a hook-based component would create.\n */\nexport function wrapWithRouterContext(element: ReactElement): ReactElement {\n const { pathname, query, asPath } = getPathnameAndQuery();\n\n const routerValue = buildRouterValue(pathname, query, asPath, {\n push: Router.push,\n replace: Router.replace,\n back: Router.back,\n reload: Router.reload,\n prefetch: Router.prefetch,\n beforePopState: Router.beforePopState,\n });\n\n return createElement(RouterContext.Provider, { value: routerValue }, element) as ReactElement;\n}\n\n// Also export a default Router singleton for `import Router from 'next/router'`\nconst Router = {\n push: async (url: string | UrlObject, as?: string, options?: TransitionOptions) => {\n let resolved = resolveNavigationTarget(url, as, options?.locale);\n\n // External URLs (unless same-origin)\n if (isExternalUrl(resolved)) {\n const localPath = toSameOriginAppPath(resolved, __basePath);\n if (localPath == null) {\n window.location.assign(resolved);\n return true;\n }\n resolved = localPath;\n }\n\n const full = toBrowserNavigationHref(resolved, window.location.href, __basePath);\n\n // Hash-only change\n if (isHashOnlyChange(resolved)) {\n const eventUrl = resolveHashUrl(resolved);\n routerEvents.emit(\"hashChangeStart\", eventUrl, {\n shallow: options?.shallow ?? false,\n });\n const hash = resolved.includes(\"#\") ? resolved.slice(resolved.indexOf(\"#\")) : \"\";\n window.history.pushState({}, \"\", resolved.startsWith(\"#\") ? resolved : full);\n _lastPathnameAndSearch = window.location.pathname + window.location.search;\n scrollToHash(hash);\n routerEvents.emit(\"hashChangeComplete\", eventUrl, {\n shallow: options?.shallow ?? false,\n });\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return true;\n }\n\n saveScrollPosition();\n routerEvents.emit(\"routeChangeStart\", resolved, { shallow: options?.shallow ?? false });\n routerEvents.emit(\"beforeHistoryChange\", resolved, { shallow: options?.shallow ?? false });\n window.history.pushState({}, \"\", full);\n _lastPathnameAndSearch = window.location.pathname + window.location.search;\n if (!options?.shallow) {\n await navigateClient(full);\n }\n routerEvents.emit(\"routeChangeComplete\", resolved, { shallow: options?.shallow ?? false });\n\n const hash = resolved.includes(\"#\") ? resolved.slice(resolved.indexOf(\"#\")) : \"\";\n if (hash) {\n scrollToHash(hash);\n } else if (options?.scroll !== false) {\n window.scrollTo(0, 0);\n }\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return true;\n },\n replace: async (url: string | UrlObject, as?: string, options?: TransitionOptions) => {\n let resolved = resolveNavigationTarget(url, as, options?.locale);\n\n // External URLs (unless same-origin)\n if (isExternalUrl(resolved)) {\n const localPath = toSameOriginAppPath(resolved, __basePath);\n if (localPath == null) {\n window.location.replace(resolved);\n return true;\n }\n resolved = localPath;\n }\n\n const full = toBrowserNavigationHref(resolved, window.location.href, __basePath);\n\n // Hash-only change\n if (isHashOnlyChange(resolved)) {\n const eventUrl = resolveHashUrl(resolved);\n routerEvents.emit(\"hashChangeStart\", eventUrl, {\n shallow: options?.shallow ?? false,\n });\n const hash = resolved.includes(\"#\") ? resolved.slice(resolved.indexOf(\"#\")) : \"\";\n window.history.replaceState({}, \"\", resolved.startsWith(\"#\") ? resolved : full);\n _lastPathnameAndSearch = window.location.pathname + window.location.search;\n scrollToHash(hash);\n routerEvents.emit(\"hashChangeComplete\", eventUrl, {\n shallow: options?.shallow ?? false,\n });\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return true;\n }\n\n routerEvents.emit(\"routeChangeStart\", resolved, { shallow: options?.shallow ?? false });\n routerEvents.emit(\"beforeHistoryChange\", resolved, { shallow: options?.shallow ?? false });\n window.history.replaceState({}, \"\", full);\n _lastPathnameAndSearch = window.location.pathname + window.location.search;\n if (!options?.shallow) {\n await navigateClient(full);\n }\n routerEvents.emit(\"routeChangeComplete\", resolved, { shallow: options?.shallow ?? false });\n\n const hash = resolved.includes(\"#\") ? resolved.slice(resolved.indexOf(\"#\")) : \"\";\n if (hash) {\n scrollToHash(hash);\n } else if (options?.scroll !== false) {\n window.scrollTo(0, 0);\n }\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return true;\n },\n back: () => window.history.back(),\n reload: () => window.location.reload(),\n prefetch: async (url: string) => {\n if (typeof document !== \"undefined\") {\n const link = document.createElement(\"link\");\n link.rel = \"prefetch\";\n link.href = url;\n link.as = \"document\";\n document.head.appendChild(link);\n }\n },\n beforePopState: (cb: BeforePopStateCallback) => {\n _beforePopStateCb = cb;\n },\n events: routerEvents,\n};\n\nexport default Router;\n"],"mappings":";;;;;;;;;;;;;;;;AAsBA,MAAM,aAAqB,QAAQ,IAAI,0BAA0B;AAmEjE,SAAS,qBAAmC;CAC1C,MAAM,4BAAY,IAAI,KAAgD;AAEtE,QAAO;EACL,GAAG,OAAe,SAAuC;AACvD,OAAI,CAAC,UAAU,IAAI,MAAM,CAAE,WAAU,IAAI,uBAAO,IAAI,KAAK,CAAC;AACzD,aAAU,IAAI,MAAM,CAAuC,IAAI,QAAQ;;EAE1E,IAAI,OAAe,SAAuC;AACxD,aAAU,IAAI,MAAM,EAAE,OAAO,QAAQ;;EAEvC,KAAK,OAAe,GAAG,MAAiB;AACtC,aAAU,IAAI,MAAM,EAAE,SAAS,YAAY,QAAQ,GAAG,KAAK,CAAC;;EAE/D;;AAIH,MAAM,eAAe,oBAAoB;AAEzC,SAAS,WAAW,KAAiC;AACnD,KAAI,OAAO,QAAQ,SAAU,QAAO;CACpC,IAAI,SAAS,IAAI,YAAY;AAC7B,KA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C/B,MAAI,OAAO,aAAa,aAAa;GACnC,MAAM,OAAO,SAAS,cAAc,OAAO;AAC3C,QAAK,MAAM;AACX,QAAK,OAAO;AACZ,QAAK,KAAK;AACV,YAAS,KAAK,YAAY,KAAK;;;CAGnC,iBAAiB,OAA+B;AAC9C,sBAAoB;;CAEtB,QAAQ;CACT"}
1
+ {"version":3,"file":"router.js","names":[],"sources":["../../src/shims/router.ts"],"sourcesContent":["/**\n * next/router shim\n *\n * Provides useRouter() hook and Router singleton for Pages Router.\n * Backed by the browser History API. Supports client-side navigation\n * by fetching new page data and re-rendering the React root.\n */\nimport { useState, useEffect, useCallback, useMemo, createElement, type ReactElement } from \"react\";\nimport { RouterContext } from \"./internal/router-context.js\";\nimport type { VinextNextData } from \"../client/vinext-next-data.js\";\nimport { isValidModulePath } from \"../client/validate-module-path.js\";\nimport { toBrowserNavigationHref, toSameOriginAppPath } from \"./url-utils.js\";\nimport { stripBasePath } from \"../utils/base-path.js\";\nimport { addLocalePrefix, getDomainLocaleUrl, type DomainLocale } from \"../utils/domain-locale.js\";\nimport {\n addQueryParam,\n appendSearchParamsToUrl,\n type UrlQuery,\n urlQueryToSearchParams,\n} from \"../utils/query.js\";\n\n/** basePath from next.config.js, injected by the plugin at build time */\nconst __basePath: string = process.env.__NEXT_ROUTER_BASEPATH ?? \"\";\n\ntype BeforePopStateCallback = (state: {\n url: string;\n as: string;\n options: { shallow: boolean };\n}) => boolean;\n\nexport type NextRouter = {\n /** Current pathname */\n pathname: string;\n /** Current route pattern (e.g., \"/posts/[id]\") */\n route: string;\n /** Query parameters */\n query: Record<string, string | string[]>;\n /** Full URL including query string */\n asPath: string;\n /** Base path */\n basePath: string;\n /** Current locale */\n locale?: string;\n /** Available locales */\n locales?: string[];\n /** Default locale */\n defaultLocale?: string;\n /** Configured domain locales */\n domainLocales?: VinextNextData[\"domainLocales\"];\n /** Whether the router is ready */\n isReady: boolean;\n /** Whether this is a preview */\n isPreview: boolean;\n /** Whether this is a fallback page */\n isFallback: boolean;\n\n /** Navigate to a new URL */\n push(url: string | UrlObject, as?: string, options?: TransitionOptions): Promise<boolean>;\n /** Replace current URL */\n replace(url: string | UrlObject, as?: string, options?: TransitionOptions): Promise<boolean>;\n /** Go back */\n back(): void;\n /** Reload the page */\n reload(): void;\n /** Prefetch a page (injects <link rel=\"prefetch\">) */\n prefetch(url: string): Promise<void>;\n /** Register a callback to run before popstate navigation */\n beforePopState(cb: BeforePopStateCallback): void;\n /** Listen for route changes */\n events: RouterEvents;\n};\n\ntype UrlObject = {\n pathname?: string;\n query?: UrlQuery;\n};\n\ntype TransitionOptions = {\n shallow?: boolean;\n scroll?: boolean;\n locale?: string;\n};\n\ntype RouterEvents = {\n on(event: string, handler: (...args: unknown[]) => void): void;\n off(event: string, handler: (...args: unknown[]) => void): void;\n emit(event: string, ...args: unknown[]): void;\n};\n\nfunction createRouterEvents(): RouterEvents {\n const listeners = new Map<string, Set<(...args: unknown[]) => void>>();\n\n return {\n on(event: string, handler: (...args: unknown[]) => void) {\n if (!listeners.has(event)) listeners.set(event, new Set());\n (listeners.get(event) as Set<(...args: unknown[]) => void>).add(handler);\n },\n off(event: string, handler: (...args: unknown[]) => void) {\n listeners.get(event)?.delete(handler);\n },\n emit(event: string, ...args: unknown[]) {\n listeners.get(event)?.forEach((handler) => handler(...args));\n },\n };\n}\n\n// Singleton events instance\nconst routerEvents = createRouterEvents();\n\nfunction resolveUrl(url: string | UrlObject): string {\n if (typeof url === \"string\") return url;\n let result = url.pathname ?? \"/\";\n if (url.query) {\n const params = urlQueryToSearchParams(url.query);\n result = appendSearchParamsToUrl(result, params);\n }\n return result;\n}\n\n/**\n * When `as` is provided, use it as the navigation target. This is a\n * simplification: Next.js keeps `url` and `as` as separate values (url for\n * data fetching, as for the browser URL). We collapse them because vinext's\n * navigateClient() fetches HTML from the target URL, so `as` must be a\n * server-resolvable path. Purely decorative `as` values are not supported.\n */\nfunction resolveNavigationTarget(\n url: string | UrlObject,\n as: string | undefined,\n locale: string | undefined,\n): string {\n return applyNavigationLocale(as ?? resolveUrl(url), locale);\n}\n\nfunction getDomainLocales(): readonly DomainLocale[] | undefined {\n return (window.__NEXT_DATA__ as VinextNextData | undefined)?.domainLocales;\n}\n\nfunction getCurrentHostname(): string | undefined {\n return window.location?.hostname;\n}\n\nfunction getDomainLocalePath(url: string, locale: string): string | undefined {\n return getDomainLocaleUrl(url, locale, {\n basePath: __basePath,\n currentHostname: getCurrentHostname(),\n domainItems: getDomainLocales(),\n });\n}\n\n/**\n * Apply locale prefix to a URL for client-side navigation.\n * Same logic as Link's applyLocaleToHref but reads from window globals.\n */\nexport function applyNavigationLocale(url: string, locale?: string): string {\n if (!locale || typeof window === \"undefined\") return url;\n // Absolute and protocol-relative URLs must not be prefixed — locale\n // only applies to local paths.\n if (url.startsWith(\"http://\") || url.startsWith(\"https://\") || url.startsWith(\"//\")) {\n return url;\n }\n\n const domainLocalePath = getDomainLocalePath(url, locale);\n if (domainLocalePath) return domainLocalePath;\n\n return addLocalePrefix(url, locale, window.__VINEXT_DEFAULT_LOCALE__ ?? \"\");\n}\n\n/** Check if a URL is external (any URL scheme per RFC 3986, or protocol-relative) */\nexport function isExternalUrl(url: string): boolean {\n return /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith(\"//\");\n}\n\n/** Resolve a hash URL to a basePath-stripped app URL for event payloads */\nfunction resolveHashUrl(url: string): string {\n if (typeof window === \"undefined\") return url;\n if (url.startsWith(\"#\"))\n return stripBasePath(window.location.pathname, __basePath) + window.location.search + url;\n // Full-path hash URL — strip basePath for consistency with other events\n try {\n const parsed = new URL(url, window.location.href);\n return stripBasePath(parsed.pathname, __basePath) + parsed.search + parsed.hash;\n } catch {\n return url;\n }\n}\n\n/** Check if a href is only a hash change relative to the current URL */\nexport function isHashOnlyChange(href: string): boolean {\n if (href.startsWith(\"#\")) return true;\n if (typeof window === \"undefined\") return false;\n try {\n const current = new URL(window.location.href);\n const next = new URL(href, window.location.href);\n return current.pathname === next.pathname && current.search === next.search && next.hash !== \"\";\n } catch {\n return false;\n }\n}\n\n/** Scroll to hash target element, or top if no hash */\nfunction scrollToHash(hash: string): void {\n if (!hash || hash === \"#\") {\n window.scrollTo(0, 0);\n return;\n }\n const el = document.getElementById(hash.slice(1));\n if (el) el.scrollIntoView({ behavior: \"auto\" });\n}\n\n/** Save current scroll position into history state for back/forward restoration */\nfunction saveScrollPosition(): void {\n const state = window.history.state ?? {};\n window.history.replaceState(\n { ...state, __vinext_scrollX: window.scrollX, __vinext_scrollY: window.scrollY },\n \"\",\n );\n}\n\n/** Restore scroll position from history state */\nfunction restoreScrollPosition(state: unknown): void {\n if (state && typeof state === \"object\" && \"__vinext_scrollY\" in state) {\n const { __vinext_scrollX: x, __vinext_scrollY: y } = state as {\n __vinext_scrollX: number;\n __vinext_scrollY: number;\n };\n requestAnimationFrame(() => window.scrollTo(x, y));\n }\n}\n\n/**\n * SSR context - set by the dev server before rendering each page.\n */\ntype SSRContext = {\n pathname: string;\n query: Record<string, string | string[]>;\n asPath: string;\n locale?: string;\n locales?: string[];\n defaultLocale?: string;\n domainLocales?: VinextNextData[\"domainLocales\"];\n};\n\n// ---------------------------------------------------------------------------\n// Server-side SSR state uses a registration pattern so this module can be\n// bundled for the browser. The ALS-backed implementation lives in\n// router-state.ts (server-only) and registers itself on import.\n// ---------------------------------------------------------------------------\n\nlet _ssrContext: SSRContext | null = null;\n\nlet _getSSRContext = (): SSRContext | null => _ssrContext;\nlet _setSSRContextImpl = (ctx: SSRContext | null): void => {\n _ssrContext = ctx;\n};\n\n/**\n * Register ALS-backed state accessors. Called by router-state.ts on import.\n * @internal\n */\nexport function _registerRouterStateAccessors(accessors: {\n getSSRContext: () => SSRContext | null;\n setSSRContext: (ctx: SSRContext | null) => void;\n}): void {\n _getSSRContext = accessors.getSSRContext;\n _setSSRContextImpl = accessors.setSSRContext;\n}\n\nexport function setSSRContext(ctx: SSRContext | null): void {\n _setSSRContextImpl(ctx);\n}\n\n/**\n * Extract param names from a Next.js route pattern.\n * E.g., \"/posts/[id]\" → [\"id\"], \"/docs/[...slug]\" → [\"slug\"],\n * \"/shop/[[...path]]\" → [\"path\"], \"/blog/[year]/[month]\" → [\"year\", \"month\"]\n * Also handles internal format: \"/posts/:id\" → [\"id\"], \"/docs/:slug+\" → [\"slug\"]\n */\nfunction extractRouteParamNames(pattern: string): string[] {\n const names: string[] = [];\n // Match Next.js bracket format: [id], [...slug], [[...slug]]\n const bracketMatches = pattern.matchAll(/\\[{1,2}(?:\\.\\.\\.)?([\\w-]+)\\]{1,2}/g);\n for (const m of bracketMatches) {\n names.push(m[1]);\n }\n if (names.length > 0) return names;\n // Fallback: match internal :param format\n const colonMatches = pattern.matchAll(/:([\\w-]+)[+*]?/g);\n for (const m of colonMatches) {\n names.push(m[1]);\n }\n return names;\n}\n\nfunction getPathnameAndQuery(): {\n pathname: string;\n query: Record<string, string | string[]>;\n asPath: string;\n} {\n if (typeof window === \"undefined\") {\n const _ssrCtx = _getSSRContext();\n if (_ssrCtx) {\n const query: Record<string, string | string[]> = {};\n for (const [key, value] of Object.entries(_ssrCtx.query)) {\n query[key] = Array.isArray(value) ? [...value] : value;\n }\n return { pathname: _ssrCtx.pathname, query, asPath: _ssrCtx.asPath };\n }\n return { pathname: \"/\", query: {}, asPath: \"/\" };\n }\n const resolvedPath = stripBasePath(window.location.pathname, __basePath);\n // In Next.js, router.pathname is the route pattern (e.g., \"/posts/[id]\"),\n // not the resolved path (\"/posts/42\"). __NEXT_DATA__.page holds the route\n // pattern and is updated by navigateClient() on every client-side navigation.\n const pathname = window.__NEXT_DATA__?.page ?? resolvedPath;\n const routeQuery: Record<string, string | string[]> = {};\n // Include dynamic route params from __NEXT_DATA__ (e.g., { id: \"42\" } from /posts/[id]).\n // Only include keys that are part of the route pattern (not stale query params).\n const nextData = window.__NEXT_DATA__;\n if (nextData && nextData.query && nextData.page) {\n const routeParamNames = extractRouteParamNames(nextData.page);\n for (const key of routeParamNames) {\n const value = nextData.query[key];\n if (typeof value === \"string\") {\n routeQuery[key] = value;\n } else if (Array.isArray(value)) {\n routeQuery[key] = [...value];\n }\n }\n }\n // URL search params always reflect the current URL\n const searchQuery: Record<string, string | string[]> = {};\n const params = new URLSearchParams(window.location.search);\n for (const [key, value] of params) {\n addQueryParam(searchQuery, key, value);\n }\n const query = { ...searchQuery, ...routeQuery };\n // asPath uses the resolved browser path, not the route pattern\n const asPath = resolvedPath + window.location.search + window.location.hash;\n return { pathname, query, asPath };\n}\n\n/**\n * Error thrown when a navigation is superseded by a newer one.\n * Matches Next.js's convention of an Error with `.cancelled = true`.\n */\nclass NavigationCancelledError extends Error {\n cancelled = true;\n constructor(route: string) {\n super(`Abort fetching component for route: \"${route}\"`);\n this.name = \"NavigationCancelledError\";\n }\n}\n\n/**\n * Error thrown after queueing a hard navigation fallback for a known failure\n * mode. Callers can use this to avoid scheduling the same hard navigation twice.\n */\nclass HardNavigationScheduledError extends Error {\n hardNavigationScheduled = true;\n constructor(message: string) {\n super(message);\n this.name = \"HardNavigationScheduledError\";\n }\n}\n\n/**\n * Monotonically increasing ID for tracking the current navigation.\n * Each call to navigateClient() increments this and captures the value.\n * After each async boundary, the navigation checks whether it is still\n * the active one. If a newer navigation has started, the stale one\n * throws NavigationCancelledError so the caller can emit routeChangeError\n * and skip routeChangeComplete.\n *\n * Replaces the old boolean `_navInProgress` guard which silently dropped\n * the second navigation, causing URL/content mismatch.\n */\nlet _navigationId = 0;\n\n/** AbortController for the in-flight fetch, so superseded navigations abort network I/O. */\nlet _activeAbortController: AbortController | null = null;\n\nfunction scheduleHardNavigationAndThrow(url: string, message: string): never {\n if (typeof window === \"undefined\") {\n throw new HardNavigationScheduledError(message);\n }\n window.location.href = url;\n throw new HardNavigationScheduledError(message);\n}\n\n/**\n * Perform client-side navigation: fetch the target page's HTML,\n * extract __NEXT_DATA__, and re-render the React root.\n *\n * Throws NavigationCancelledError if a newer navigation supersedes this one.\n * Throws on hard-navigation failures (non-OK response, missing data) so the\n * caller can distinguish success from failure for event emission.\n */\nasync function navigateClient(url: string): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const root = window.__VINEXT_ROOT__;\n if (!root) {\n // No React root yet — fall back to hard navigation\n window.location.href = url;\n return;\n }\n\n // Cancel any in-flight navigation (abort its fetch, mark it stale)\n _activeAbortController?.abort();\n const controller = new AbortController();\n _activeAbortController = controller;\n\n const navId = ++_navigationId;\n\n /** Check if this navigation is still the active one. If not, throw. */\n function assertStillCurrent(): void {\n if (navId !== _navigationId) {\n throw new NavigationCancelledError(url);\n }\n }\n\n try {\n // Fetch the target page's SSR HTML\n let res: Response;\n try {\n res = await fetch(url, {\n headers: { Accept: \"text/html\" },\n signal: controller.signal,\n });\n } catch (err: unknown) {\n // AbortError means a newer navigation cancelled this fetch\n if (err instanceof DOMException && err.name === \"AbortError\") {\n throw new NavigationCancelledError(url);\n }\n throw err;\n }\n assertStillCurrent();\n\n if (!res.ok) {\n // Set window.location.href first so the browser navigates to the correct\n // page even if the caller suppresses the error. The assignment schedules\n // the navigation asynchronously (as a task), so synchronous routeChangeError\n // listeners still run — and observe the error — before the page unloads.\n // Contract: routeChangeError listeners MUST be synchronous; async listeners\n // will not fire before the navigation completes. Callers (runNavigateClient)\n // must NOT schedule a second hard navigation — this assignment already queues\n // the browser fallback, and the helper-level HardNavigationScheduledError\n // makes that contract explicit to callers.\n scheduleHardNavigationAndThrow(url, `Navigation failed: ${res.status} ${res.statusText}`);\n }\n\n const html = await res.text();\n assertStillCurrent();\n\n // Extract __NEXT_DATA__ from the HTML\n const match = html.match(/<script>window\\.__NEXT_DATA__\\s*=\\s*(.*?)<\\/script>/);\n if (!match) {\n scheduleHardNavigationAndThrow(url, \"Navigation failed: missing __NEXT_DATA__ in response\");\n }\n\n const nextData = JSON.parse(match[1]);\n const { pageProps } = nextData.props;\n // Defer writing window.__NEXT_DATA__ until just before root.render() —\n // writing it here would let a stale navigation briefly pollute the global\n // between this assertStillCurrent() and the next one after await import().\n\n // Get the page module URL from __NEXT_DATA__.__vinext (preferred),\n // or fall back to parsing the hydration script\n let pageModuleUrl: string | undefined = nextData.__vinext?.pageModuleUrl;\n\n if (!pageModuleUrl) {\n // Legacy fallback: try to find the module URL in the inline script\n const moduleMatch = html.match(/import\\(\"([^\"]+)\"\\);\\s*\\n\\s*const PageComponent/);\n const altMatch = html.match(/await import\\(\"([^\"]+pages\\/[^\"]+)\"\\)/);\n pageModuleUrl = moduleMatch?.[1] ?? altMatch?.[1] ?? undefined;\n }\n\n if (!pageModuleUrl) {\n scheduleHardNavigationAndThrow(url, \"Navigation failed: no page module URL found\");\n }\n\n // Validate the module URL before importing — defense-in-depth against\n // unexpected __NEXT_DATA__ or malformed HTML responses\n if (!isValidModulePath(pageModuleUrl)) {\n console.error(\"[vinext] Blocked import of invalid page module path:\", pageModuleUrl);\n scheduleHardNavigationAndThrow(url, \"Navigation failed: invalid page module path\");\n }\n\n // Dynamically import the new page module\n const pageModule = await import(/* @vite-ignore */ pageModuleUrl);\n assertStillCurrent();\n\n const PageComponent = pageModule.default;\n\n if (!PageComponent) {\n scheduleHardNavigationAndThrow(url, \"Navigation failed: page module has no default export\");\n }\n\n // Import React for createElement\n const React = (await import(\"react\")).default;\n assertStillCurrent();\n\n // Re-render with the new page, loading _app if needed\n let AppComponent = window.__VINEXT_APP__;\n const appModuleUrl: string | undefined = nextData.__vinext?.appModuleUrl;\n\n if (!AppComponent && appModuleUrl) {\n if (!isValidModulePath(appModuleUrl)) {\n console.error(\"[vinext] Blocked import of invalid app module path:\", appModuleUrl);\n } else {\n try {\n const appModule = await import(/* @vite-ignore */ appModuleUrl);\n AppComponent = appModule.default;\n window.__VINEXT_APP__ = AppComponent;\n } catch {\n // _app not available — continue without it\n }\n }\n }\n assertStillCurrent();\n\n let element;\n if (AppComponent) {\n element = React.createElement(AppComponent, {\n Component: PageComponent,\n pageProps,\n });\n } else {\n element = React.createElement(PageComponent, pageProps);\n }\n\n // Wrap with RouterContext.Provider so next/compat/router works\n element = wrapWithRouterContext(element);\n\n // Commit __NEXT_DATA__ only after all assertStillCurrent() checks have passed,\n // so a stale navigation can never pollute the global.\n // INVARIANT: Everything after the final assertStillCurrent() above (the\n // checkpoint immediately after the optional _app import) through\n // root.render() is synchronous. If any step here ever becomes async, add\n // another assertStillCurrent() before writing __NEXT_DATA__.\n window.__NEXT_DATA__ = nextData;\n root.render(element);\n } finally {\n // Clean up the abort controller if this navigation is still the active one\n if (navId === _navigationId) {\n _activeAbortController = null;\n }\n }\n}\n\n/**\n * Run navigateClient and handle errors: emit routeChangeError on failure,\n * and fall back to a hard navigation for non-cancel errors so the browser\n * recovers to a consistent state.\n *\n * Returns:\n * - \"completed\" — navigation finished, caller should emit routeChangeComplete\n * - \"cancelled\" — superseded by a newer navigation, caller should return true\n * without emitting routeChangeComplete (matches Next.js behaviour)\n * - \"failed\" — genuine error, caller should return false (hard nav is already\n * scheduled as recovery)\n */\nasync function runNavigateClient(\n fullUrl: string,\n resolvedUrl: string,\n): Promise<\"completed\" | \"cancelled\" | \"failed\"> {\n try {\n await navigateClient(fullUrl);\n return \"completed\";\n } catch (err: unknown) {\n routerEvents.emit(\"routeChangeError\", err, resolvedUrl, { shallow: false });\n if (err instanceof NavigationCancelledError) {\n return \"cancelled\";\n }\n // Genuine error (network, parse, import failure): fall back to a hard\n // navigation so the browser lands on the correct page. Known failure modes\n // throw HardNavigationScheduledError, and this guard skips those; only\n // unexpected failures (parse, import, render) need recovery here.\n if (typeof window !== \"undefined\" && !(err instanceof HardNavigationScheduledError)) {\n window.location.href = fullUrl;\n }\n return \"failed\";\n }\n}\n\n/**\n * Build the full router value object from the current pathname, query, asPath,\n * and a set of navigation methods. Shared by useRouter() (which passes\n * hook-derived callbacks) and wrapWithRouterContext() (which passes the Router\n * singleton methods) so the shape stays in sync.\n */\nfunction buildRouterValue(\n pathname: string,\n query: Record<string, string | string[]>,\n asPath: string,\n methods: {\n push: NextRouter[\"push\"];\n replace: NextRouter[\"replace\"];\n back: NextRouter[\"back\"];\n reload: NextRouter[\"reload\"];\n prefetch: NextRouter[\"prefetch\"];\n beforePopState: NextRouter[\"beforePopState\"];\n },\n): NextRouter {\n const _ssrState = _getSSRContext();\n const nextData =\n typeof window !== \"undefined\"\n ? (window.__NEXT_DATA__ as VinextNextData | undefined)\n : undefined;\n const locale = typeof window === \"undefined\" ? _ssrState?.locale : window.__VINEXT_LOCALE__;\n const locales = typeof window === \"undefined\" ? _ssrState?.locales : window.__VINEXT_LOCALES__;\n const defaultLocale =\n typeof window === \"undefined\" ? _ssrState?.defaultLocale : window.__VINEXT_DEFAULT_LOCALE__;\n const domainLocales =\n typeof window === \"undefined\" ? _ssrState?.domainLocales : nextData?.domainLocales;\n\n const route = typeof window !== \"undefined\" ? (nextData?.page ?? pathname) : pathname;\n\n return {\n pathname,\n route,\n query,\n asPath,\n basePath: __basePath,\n locale,\n locales,\n defaultLocale,\n domainLocales,\n isReady: true,\n isPreview: false,\n isFallback: typeof window !== \"undefined\" && nextData?.isFallback === true,\n ...methods,\n events: routerEvents,\n };\n}\n\n/**\n * useRouter hook - Pages Router compatible.\n */\nexport function useRouter(): NextRouter {\n const [{ pathname, query, asPath }, setState] = useState(getPathnameAndQuery);\n\n // Popstate is handled by the module-level listener below so beforePopState()\n // is consistently enforced even when multiple components mount useRouter().\n useEffect(() => {\n const onNavigate = ((_e: CustomEvent) => {\n setState(getPathnameAndQuery());\n }) as EventListener;\n window.addEventListener(\"vinext:navigate\", onNavigate);\n return () => window.removeEventListener(\"vinext:navigate\", onNavigate);\n }, []);\n\n const push = useCallback(\n async (url: string | UrlObject, as?: string, options?: TransitionOptions): Promise<boolean> => {\n let resolved = resolveNavigationTarget(url, as, options?.locale);\n\n // External URLs — delegate to browser (unless same-origin)\n if (isExternalUrl(resolved)) {\n const localPath = toSameOriginAppPath(resolved, __basePath);\n if (localPath == null) {\n window.location.assign(resolved);\n return true;\n }\n resolved = localPath;\n }\n\n const full = toBrowserNavigationHref(resolved, window.location.href, __basePath);\n\n // Hash-only change — no page fetch needed\n if (isHashOnlyChange(resolved)) {\n const eventUrl = resolveHashUrl(resolved);\n routerEvents.emit(\"hashChangeStart\", eventUrl, {\n shallow: options?.shallow ?? false,\n });\n const hash = resolved.includes(\"#\") ? resolved.slice(resolved.indexOf(\"#\")) : \"\";\n window.history.pushState({}, \"\", resolved.startsWith(\"#\") ? resolved : full);\n _lastPathnameAndSearch = window.location.pathname + window.location.search;\n scrollToHash(hash);\n setState(getPathnameAndQuery());\n routerEvents.emit(\"hashChangeComplete\", eventUrl, {\n shallow: options?.shallow ?? false,\n });\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return true;\n }\n\n saveScrollPosition();\n routerEvents.emit(\"routeChangeStart\", resolved, { shallow: options?.shallow ?? false });\n routerEvents.emit(\"beforeHistoryChange\", resolved, { shallow: options?.shallow ?? false });\n window.history.pushState({}, \"\", full);\n _lastPathnameAndSearch = window.location.pathname + window.location.search;\n if (!options?.shallow) {\n const result = await runNavigateClient(full, resolved);\n if (result === \"cancelled\") return true;\n if (result === \"failed\") return false;\n }\n setState(getPathnameAndQuery());\n routerEvents.emit(\"routeChangeComplete\", resolved, { shallow: options?.shallow ?? false });\n\n // Scroll: handle hash target, else scroll to top unless scroll:false\n const hash = resolved.includes(\"#\") ? resolved.slice(resolved.indexOf(\"#\")) : \"\";\n if (hash) {\n scrollToHash(hash);\n } else if (options?.scroll !== false) {\n window.scrollTo(0, 0);\n }\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return true;\n },\n [],\n );\n\n const replace = useCallback(\n async (url: string | UrlObject, as?: string, options?: TransitionOptions): Promise<boolean> => {\n let resolved = resolveNavigationTarget(url, as, options?.locale);\n\n // External URLs — delegate to browser (unless same-origin)\n if (isExternalUrl(resolved)) {\n const localPath = toSameOriginAppPath(resolved, __basePath);\n if (localPath == null) {\n window.location.replace(resolved);\n return true;\n }\n resolved = localPath;\n }\n\n const full = toBrowserNavigationHref(resolved, window.location.href, __basePath);\n\n // Hash-only change — no page fetch needed\n if (isHashOnlyChange(resolved)) {\n const eventUrl = resolveHashUrl(resolved);\n routerEvents.emit(\"hashChangeStart\", eventUrl, {\n shallow: options?.shallow ?? false,\n });\n const hash = resolved.includes(\"#\") ? resolved.slice(resolved.indexOf(\"#\")) : \"\";\n window.history.replaceState({}, \"\", resolved.startsWith(\"#\") ? resolved : full);\n _lastPathnameAndSearch = window.location.pathname + window.location.search;\n scrollToHash(hash);\n setState(getPathnameAndQuery());\n routerEvents.emit(\"hashChangeComplete\", eventUrl, {\n shallow: options?.shallow ?? false,\n });\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return true;\n }\n\n routerEvents.emit(\"routeChangeStart\", resolved, { shallow: options?.shallow ?? false });\n routerEvents.emit(\"beforeHistoryChange\", resolved, { shallow: options?.shallow ?? false });\n window.history.replaceState({}, \"\", full);\n _lastPathnameAndSearch = window.location.pathname + window.location.search;\n if (!options?.shallow) {\n const result = await runNavigateClient(full, resolved);\n if (result === \"cancelled\") return true;\n if (result === \"failed\") return false;\n }\n setState(getPathnameAndQuery());\n routerEvents.emit(\"routeChangeComplete\", resolved, { shallow: options?.shallow ?? false });\n\n // Scroll: handle hash target, else scroll to top unless scroll:false\n const hash = resolved.includes(\"#\") ? resolved.slice(resolved.indexOf(\"#\")) : \"\";\n if (hash) {\n scrollToHash(hash);\n } else if (options?.scroll !== false) {\n window.scrollTo(0, 0);\n }\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return true;\n },\n [],\n );\n\n const back = useCallback(() => {\n window.history.back();\n }, []);\n\n const reload = useCallback(() => {\n window.location.reload();\n }, []);\n\n const prefetch = useCallback(async (url: string): Promise<void> => {\n // Inject a <link rel=\"prefetch\"> for the target page\n if (typeof document !== \"undefined\") {\n const link = document.createElement(\"link\");\n link.rel = \"prefetch\";\n link.href = url;\n link.as = \"document\";\n document.head.appendChild(link);\n }\n }, []);\n\n const router = useMemo(\n (): NextRouter =>\n buildRouterValue(pathname, query, asPath, {\n push,\n replace,\n back,\n reload,\n prefetch,\n beforePopState: (cb: BeforePopStateCallback) => {\n _beforePopStateCb = cb;\n },\n }),\n [pathname, query, asPath, push, replace, back, reload, prefetch],\n );\n\n return router;\n}\n\n// beforePopState callback: called before handling browser back/forward.\n// If it returns false, the navigation is cancelled.\nlet _beforePopStateCb: BeforePopStateCallback | undefined;\n\n// Track pathname+search for detecting hash-only back/forward in the popstate\n// handler. Updated after every pushState/replaceState so that popstate can\n// compare the previous value with the (already-changed) window.location.\nlet _lastPathnameAndSearch =\n typeof window !== \"undefined\" ? window.location.pathname + window.location.search : \"\";\n\n// Module-level popstate listener: handles browser back/forward by re-rendering\n// the React root with the page at the new URL. This runs regardless of whether\n// any component calls useRouter().\nif (typeof window !== \"undefined\") {\n window.addEventListener(\"popstate\", (e: PopStateEvent) => {\n const browserUrl = window.location.pathname + window.location.search;\n const appUrl = stripBasePath(window.location.pathname, __basePath) + window.location.search;\n\n // Detect hash-only back/forward: pathname+search unchanged, only hash differs.\n const isHashOnly = browserUrl === _lastPathnameAndSearch;\n\n // Check beforePopState callback\n if (_beforePopStateCb !== undefined) {\n const shouldContinue = (_beforePopStateCb as BeforePopStateCallback)({\n url: appUrl,\n as: appUrl,\n options: { shallow: false },\n });\n if (!shouldContinue) return;\n }\n\n // Update tracker only after beforePopState confirms navigation proceeds.\n // If beforePopState cancels, the tracker must retain the previous value\n // so the next popstate compares against the correct baseline.\n _lastPathnameAndSearch = browserUrl;\n\n if (isHashOnly) {\n // Hash-only back/forward — no page fetch needed\n const hashUrl = appUrl + window.location.hash;\n routerEvents.emit(\"hashChangeStart\", hashUrl, { shallow: false });\n scrollToHash(window.location.hash);\n routerEvents.emit(\"hashChangeComplete\", hashUrl, { shallow: false });\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return;\n }\n\n const fullAppUrl = appUrl + window.location.hash;\n routerEvents.emit(\"routeChangeStart\", fullAppUrl, { shallow: false });\n // Note: The browser has already updated window.location by the time popstate\n // fires, so this is not truly \"before\" the URL change. In Next.js the popstate\n // handler calls replaceState to store history metadata — beforeHistoryChange\n // precedes that call, not the URL change itself. We emit it here for API\n // compatibility.\n routerEvents.emit(\"beforeHistoryChange\", fullAppUrl, { shallow: false });\n void (async () => {\n const result = await runNavigateClient(browserUrl, fullAppUrl);\n if (result === \"completed\") {\n routerEvents.emit(\"routeChangeComplete\", fullAppUrl, { shallow: false });\n restoreScrollPosition(e.state);\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n }\n // \"cancelled\": superseded by a newer navigation, so this popstate no longer wins.\n // \"failed\": runNavigateClient already scheduled the hard-navigation fallback.\n })();\n });\n}\n\n/**\n * Wrap a React element in a RouterContext.Provider so that\n * next/compat/router's useRouter() returns the real Pages Router value.\n *\n * This is a plain function, NOT a React component — it builds the router\n * value object directly from the current SSR context (server) or\n * window.location + Router singleton (client), avoiding duplicate state\n * that a hook-based component would create.\n */\nexport function wrapWithRouterContext(element: ReactElement): ReactElement {\n const { pathname, query, asPath } = getPathnameAndQuery();\n\n const routerValue = buildRouterValue(pathname, query, asPath, {\n push: Router.push,\n replace: Router.replace,\n back: Router.back,\n reload: Router.reload,\n prefetch: Router.prefetch,\n beforePopState: Router.beforePopState,\n });\n\n return createElement(RouterContext.Provider, { value: routerValue }, element) as ReactElement;\n}\n\n// Also export a default Router singleton for `import Router from 'next/router'`\nconst Router = {\n push: async (url: string | UrlObject, as?: string, options?: TransitionOptions) => {\n let resolved = resolveNavigationTarget(url, as, options?.locale);\n\n // External URLs (unless same-origin)\n if (isExternalUrl(resolved)) {\n const localPath = toSameOriginAppPath(resolved, __basePath);\n if (localPath == null) {\n window.location.assign(resolved);\n return true;\n }\n resolved = localPath;\n }\n\n const full = toBrowserNavigationHref(resolved, window.location.href, __basePath);\n\n // Hash-only change\n if (isHashOnlyChange(resolved)) {\n const eventUrl = resolveHashUrl(resolved);\n routerEvents.emit(\"hashChangeStart\", eventUrl, {\n shallow: options?.shallow ?? false,\n });\n const hash = resolved.includes(\"#\") ? resolved.slice(resolved.indexOf(\"#\")) : \"\";\n window.history.pushState({}, \"\", resolved.startsWith(\"#\") ? resolved : full);\n _lastPathnameAndSearch = window.location.pathname + window.location.search;\n scrollToHash(hash);\n routerEvents.emit(\"hashChangeComplete\", eventUrl, {\n shallow: options?.shallow ?? false,\n });\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return true;\n }\n\n saveScrollPosition();\n routerEvents.emit(\"routeChangeStart\", resolved, { shallow: options?.shallow ?? false });\n routerEvents.emit(\"beforeHistoryChange\", resolved, { shallow: options?.shallow ?? false });\n window.history.pushState({}, \"\", full);\n _lastPathnameAndSearch = window.location.pathname + window.location.search;\n if (!options?.shallow) {\n const result = await runNavigateClient(full, resolved);\n if (result === \"cancelled\") return true;\n if (result === \"failed\") return false;\n }\n routerEvents.emit(\"routeChangeComplete\", resolved, { shallow: options?.shallow ?? false });\n\n const hash = resolved.includes(\"#\") ? resolved.slice(resolved.indexOf(\"#\")) : \"\";\n if (hash) {\n scrollToHash(hash);\n } else if (options?.scroll !== false) {\n window.scrollTo(0, 0);\n }\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return true;\n },\n replace: async (url: string | UrlObject, as?: string, options?: TransitionOptions) => {\n let resolved = resolveNavigationTarget(url, as, options?.locale);\n\n // External URLs (unless same-origin)\n if (isExternalUrl(resolved)) {\n const localPath = toSameOriginAppPath(resolved, __basePath);\n if (localPath == null) {\n window.location.replace(resolved);\n return true;\n }\n resolved = localPath;\n }\n\n const full = toBrowserNavigationHref(resolved, window.location.href, __basePath);\n\n // Hash-only change\n if (isHashOnlyChange(resolved)) {\n const eventUrl = resolveHashUrl(resolved);\n routerEvents.emit(\"hashChangeStart\", eventUrl, {\n shallow: options?.shallow ?? false,\n });\n const hash = resolved.includes(\"#\") ? resolved.slice(resolved.indexOf(\"#\")) : \"\";\n window.history.replaceState({}, \"\", resolved.startsWith(\"#\") ? resolved : full);\n _lastPathnameAndSearch = window.location.pathname + window.location.search;\n scrollToHash(hash);\n routerEvents.emit(\"hashChangeComplete\", eventUrl, {\n shallow: options?.shallow ?? false,\n });\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return true;\n }\n\n routerEvents.emit(\"routeChangeStart\", resolved, { shallow: options?.shallow ?? false });\n routerEvents.emit(\"beforeHistoryChange\", resolved, { shallow: options?.shallow ?? false });\n window.history.replaceState({}, \"\", full);\n _lastPathnameAndSearch = window.location.pathname + window.location.search;\n if (!options?.shallow) {\n const result = await runNavigateClient(full, resolved);\n if (result === \"cancelled\") return true;\n if (result === \"failed\") return false;\n }\n routerEvents.emit(\"routeChangeComplete\", resolved, { shallow: options?.shallow ?? false });\n\n const hash = resolved.includes(\"#\") ? resolved.slice(resolved.indexOf(\"#\")) : \"\";\n if (hash) {\n scrollToHash(hash);\n } else if (options?.scroll !== false) {\n window.scrollTo(0, 0);\n }\n window.dispatchEvent(new CustomEvent(\"vinext:navigate\"));\n return true;\n },\n back: () => window.history.back(),\n reload: () => window.location.reload(),\n prefetch: async (url: string) => {\n if (typeof document !== \"undefined\") {\n const link = document.createElement(\"link\");\n link.rel = \"prefetch\";\n link.href = url;\n link.as = \"document\";\n document.head.appendChild(link);\n }\n },\n beforePopState: (cb: BeforePopStateCallback) => {\n _beforePopStateCb = cb;\n },\n events: routerEvents,\n};\n\nexport default Router;\n"],"mappings":";;;;;;;;;;;;;;;;AAsBA,MAAM,aAAqB,QAAQ,IAAI,0BAA0B;AAmEjE,SAAS,qBAAmC;CAC1C,MAAM,4BAAY,IAAI,KAAgD;AAEtE,QAAO;EACL,GAAG,OAAe,SAAuC;AACvD,OAAI,CAAC,UAAU,IAAI,MAAM,CAAE,WAAU,IAAI,uBAAO,IAAI,KAAK,CAAC;AACzD,aAAU,IAAI,MAAM,CAAuC,IAAI,QAAQ;;EAE1E,IAAI,OAAe,SAAuC;AACxD,aAAU,IAAI,MAAM,EAAE,OAAO,QAAQ;;EAEvC,KAAK,OAAe,GAAG,MAAiB;AACtC,aAAU,IA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AO,CAAC;EAE1F,MAAM,OAAO,SAAS,SAAS,IAAI,GAAG,SAAS,MAAM,SAAS,QAAQ,IAAI,CAAC,GAAG;AAC9E,MAAI,KACF,cAAa,KAAK;WACT,SAAS,WAAW,MAC7B,QAAO,SAAS,GAAG,EAAE;AAEvB,SAAO,cAAc,IAAI,YAAY,kBAAkB,CAAC;AACxD,SAAO;;CAET,YAAY,OAAO,QAAQ,MAAM;CACjC,cAAc,OAAO,SAAS,QAAQ;CACtC,UAAU,OAAO,QAAgB;AAC/B,MAAI,OAAO,aAAa,aAAa;GACnC,MAAM,OAAO,SAAS,cAAc,OAAO;AAC3C,QAAK,MAAM;AACX,QAAK,OAAO;AACZ,QAAK,KAAK;AACV,YAAS,KAAK,YAAY,KAAK;;;CAGnC,iBAAiB,OAA+B;AAC9C,sBAAoB;;CAEtB,QAAQ;CACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"script.js","names":[],"sources":["../../src/shims/script.tsx"],"sourcesContent":["\"use client\";\n\n/**\n * next/script shim\n *\n * Provides the <Script> component for loading third-party scripts with\n * configurable loading strategies.\n *\n * Strategies:\n * - \"beforeInteractive\": rendered as a <script> tag in SSR output\n * - \"afterInteractive\" (default): loaded client-side after hydration\n * - \"lazyOnload\": deferred until window.load + requestIdleCallback\n * - \"worker\": sets type=\"text/partytown\" (requires Partytown setup)\n */\nimport React, { useEffect, useRef } from \"react\";\nimport { escapeInlineContent } from \"./head.js\";\n\nexport type ScriptProps = {\n /** Script source URL */\n src?: string;\n /** Loading strategy. Default: \"afterInteractive\" */\n strategy?: \"beforeInteractive\" | \"afterInteractive\" | \"lazyOnload\" | \"worker\";\n /** Unique identifier for the script */\n id?: string;\n /** Called when the script has loaded */\n onLoad?: (e: Event) => void;\n /** Called when the script is ready (after load, and on every re-render if already loaded) */\n onReady?: () => void;\n /** Called on script load error */\n onError?: (e: Event) => void;\n /** Inline script content */\n children?: React.ReactNode;\n /** Dangerous inner HTML */\n dangerouslySetInnerHTML?: { __html: string };\n /** Script type attribute */\n type?: string;\n /** Async attribute */\n async?: boolean;\n /** Defer attribute */\n defer?: boolean;\n /** Crossorigin attribute */\n crossOrigin?: string;\n /** Nonce for CSP */\n nonce?: string;\n /** Integrity hash */\n integrity?: string;\n /** Additional attributes */\n [key: string]: unknown;\n};\n\n// Track scripts that have already been loaded to avoid duplicates\nconst loadedScripts = new Set<string>();\n\n/**\n * Load a script imperatively (outside of React).\n */\nexport function handleClientScriptLoad(props: ScriptProps): void {\n const {\n src,\n id,\n onLoad,\n onError,\n strategy: _strategy,\n onReady: _onReady,\n children,\n ...rest\n } = props;\n if (typeof window === \"undefined\") return;\n\n const key = id ?? src ?? \"\";\n if (key && loadedScripts.has(key)) return;\n\n const el = document.createElement(\"script\");\n if (src) el.src = src;\n if (id) el.id = id;\n\n for (const [attr, value] of Object.entries(rest)) {\n if (attr === \"dangerouslySetInnerHTML\" || attr === \"className\") continue;\n if (typeof value === \"string\") {\n el.setAttribute(attr, value);\n } else if (typeof value === \"boolean\" && value) {\n el.setAttribute(attr, \"\");\n }\n }\n\n if (children && typeof children === \"string\") {\n el.textContent = children;\n }\n\n if (onLoad) el.addEventListener(\"load\", onLoad);\n if (onError) el.addEventListener(\"error\", onError);\n\n document.body.appendChild(el);\n if (key) loadedScripts.add(key);\n}\n\n/**\n * Initialize multiple scripts at once (called during app bootstrap).\n */\nexport function initScriptLoader(scripts: ScriptProps[]): void {\n for (const script of scripts) {\n handleClientScriptLoad(script);\n }\n}\n\nfunction Script(props: ScriptProps): React.ReactElement | null {\n const {\n src,\n id,\n strategy = \"afterInteractive\",\n onLoad,\n onReady,\n onError,\n children,\n dangerouslySetInnerHTML,\n ...rest\n } = props;\n\n const hasMounted = useRef(false);\n const key = id ?? src ?? \"\";\n\n // Client path: load scripts via useEffect based on strategy.\n // useEffect never runs during SSR, so it's safe to call unconditionally.\n useEffect(() => {\n if (hasMounted.current) return;\n hasMounted.current = true;\n\n // Already loaded — just fire onReady\n if (key && loadedScripts.has(key)) {\n onReady?.();\n return;\n }\n\n const load = () => {\n if (key && loadedScripts.has(key)) {\n onReady?.();\n return;\n }\n\n const el = document.createElement(\"script\");\n if (src) el.src = src;\n if (id) el.id = id;\n\n for (const [attr, value] of Object.entries(rest)) {\n if (attr === \"className\") {\n el.setAttribute(\"class\", String(value));\n } else if (typeof value === \"string\") {\n el.setAttribute(attr, value);\n } else if (typeof value === \"boolean\" && value) {\n el.setAttribute(attr, \"\");\n }\n }\n\n if (strategy === \"worker\") {\n el.setAttribute(\"type\", \"text/partytown\");\n }\n\n if (dangerouslySetInnerHTML?.__html) {\n el.innerHTML = dangerouslySetInnerHTML.__html as string;\n } else if (children && typeof children === \"string\") {\n el.textContent = children;\n }\n\n el.addEventListener(\"load\", (e) => {\n if (key) loadedScripts.add(key);\n onLoad?.(e);\n onReady?.();\n });\n\n if (onError) {\n el.addEventListener(\"error\", onError);\n }\n\n document.body.appendChild(el);\n };\n\n if (strategy === \"lazyOnload\") {\n // Wait for window load, then use idle callback\n if (document.readyState === \"complete\") {\n if (typeof requestIdleCallback === \"function\") {\n requestIdleCallback(load);\n } else {\n setTimeout(load, 1);\n }\n } else {\n window.addEventListener(\"load\", () => {\n if (typeof requestIdleCallback === \"function\") {\n requestIdleCallback(load);\n } else {\n setTimeout(load, 1);\n }\n });\n }\n } else {\n // \"afterInteractive\" (default), \"beforeInteractive\" (client re-mount), \"worker\"\n load();\n }\n }, [src, id, strategy, onLoad, onReady, onError, children, dangerouslySetInnerHTML, key, rest]);\n\n // SSR path: only \"beforeInteractive\" renders a <script> tag server-side\n if (typeof window === \"undefined\") {\n if (strategy === \"beforeInteractive\") {\n const scriptProps: Record<string, unknown> = { ...rest };\n if (src) scriptProps.src = src;\n if (id) scriptProps.id = id;\n if (dangerouslySetInnerHTML) {\n // Escape closing </script> sequences in inline content so the HTML\n // parser doesn't prematurely terminate the element during SSR.\n const raw = dangerouslySetInnerHTML.__html;\n scriptProps.dangerouslySetInnerHTML = {\n __html: escapeInlineContent(raw, \"script\"),\n };\n }\n return React.createElement(\"script\", scriptProps, children);\n }\n // Other strategies don't render during SSR\n return null;\n }\n\n // The component itself renders nothing — scripts are injected imperatively\n return null;\n}\n\nexport default Script;\n"],"mappings":";;;;;;;;;;;;;;;;AAmDA,MAAM,gCAAgB,IAAI,KAAa;;;;AAKvC,SAAgB,uBAAuB,OAA0B;CAC/D,MAAM,EACJ,KACA,IACA,QACA,SACA,UAAU,WACV,SAAS,UACT,UACA,GAAG,SACD;AACJ,KAAI,OAAO,WAAW,YAAa;CAEnC,MAAM,MAAM,MAAM,OAAO;AACzB,KAAI,OAAO,cAAc,IAAI,IAAI,CAAE;CAEnC,MAAM,KAAK,SAAS,cAAc,SAAS;AAC3C,KAAI,IAAK,IAAG,MAAM;AAClB,KAAI,GAAI,IAAG,KAAK;AAEhB,MAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,KAAK,EAAE;AAChD,MAAI,SAAS,6BAA6B,SAAS,YAAa;AAChE,MAAI,OAAO,UAAU,SACnB,IAAG,aAAa,MAAM,MAAM;WACnB,OAAO,UAAU,aAAa,MACvC,IAAG,aAAa,MAAM,GAAG;;AAI7B,KAAI,YAAY,OAAO,aAAa,SAClC,IAAG,cAAc;AAGnB,KAAI,OAAQ,IAAG,iBAAiB,QAAQ,OAAO;AAC/C,KAAI,QAAS,IAAG,iBAAiB,SAAS,QAAQ;AAElD,UAAS,KAAK,YAAY,GAAG;AAC7B,KAAI,IAAK,eAAc,IAAI,IAAI;;;;;AAMjC,SAAgB,iBAAiB,SAA8B;AAC7D,MAAK,MAAM,UAAU,QACnB,wBAAuB,OAAO;;AAIlC,SAAS,OAAO,OAA+C;CAC7D,MAAM,EACJ,KACA,IACA,WAAW,oBACX,QACA,SACA,SACA,UACA,yBACA,GAAG,SACD;CAEJ,MAAM,aAAa,OAAO,MAAM;CAChC,MAAM,MAAM,MAAM,OAAO;AAIzB,iBAAgB;AACd,MAAI,WAAW,QAAS;AACxB,aAAW,UAAU;AAGrB,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GAAI,aAAY,KAAK;AACzB,OAAI,yBAAyB;IAG3B,MAAM,MAAM,wBAAwB;AACpC,gBAAY,0BAA0B,EACpC,QAAQ,oBAAoB,KAAK,SAAS,EAC3C;;AAEH,UAAO,MAAM,cAAc,UAAU,aAAa,SAAS;;AAG7D,SAAO;;AAIT,QAAO"}
1
+ {"version":3,"file":"script.js","names":[],"sources":["../../src/shims/script.tsx"],"sourcesContent":["\"use client\";\n\n/**\n * next/script shim\n *\n * Provides the <Script> component for loading third-party scripts with\n * configurable loading strategies.\n *\n * Strategies:\n * - \"beforeInteractive\": rendered as a <script> tag in SSR output\n * - \"afterInteractive\" (default): loaded client-side after hydration\n * - \"lazyOnload\": deferred until window.load + requestIdleCallback\n * - \"worker\": sets type=\"text/partytown\" (requires Partytown setup)\n */\nimport React, { useEffect, useRef } from \"react\";\nimport { escapeInlineContent } from \"./head.js\";\n\nexport type ScriptProps = {\n /** Script source URL */\n src?: string;\n /** Loading strategy. Default: \"afterInteractive\" */\n strategy?: \"beforeInteractive\" | \"afterInteractive\" | \"lazyOnload\" | \"worker\";\n /** Unique identifier for the script */\n id?: string;\n /** Called when the script has loaded */\n onLoad?: (e: Event) => void;\n /** Called when the script is ready (after load, and on every re-render if already loaded) */\n onReady?: () => void;\n /** Called on script load error */\n onError?: (e: Event) => void;\n /** Inline script content */\n children?: React.ReactNode;\n /** Dangerous inner HTML */\n dangerouslySetInnerHTML?: { __html: string };\n /** Script type attribute */\n type?: string;\n /** Async attribute */\n async?: boolean;\n /** Defer attribute */\n defer?: boolean;\n /** Crossorigin attribute */\n crossOrigin?: string;\n /** Nonce for CSP */\n nonce?: string;\n /** Integrity hash */\n integrity?: string;\n /** Additional attributes */\n [key: string]: unknown;\n};\n\n// Track scripts that have already been loaded to avoid duplicates\nconst loadedScripts = new Set<string>();\n\n/**\n * Load a script imperatively (outside of React).\n */\nexport function handleClientScriptLoad(props: ScriptProps): void {\n const {\n src,\n id,\n onLoad,\n onError,\n strategy: _strategy,\n onReady: _onReady,\n children,\n ...rest\n } = props;\n if (typeof window === \"undefined\") return;\n\n const key = id ?? src ?? \"\";\n if (key && loadedScripts.has(key)) return;\n\n const el = document.createElement(\"script\");\n if (src) el.src = src;\n if (id) el.id = id;\n\n for (const [attr, value] of Object.entries(rest)) {\n if (attr === \"dangerouslySetInnerHTML\" || attr === \"className\") continue;\n if (typeof value === \"string\") {\n el.setAttribute(attr, value);\n } else if (typeof value === \"boolean\" && value) {\n el.setAttribute(attr, \"\");\n }\n }\n\n if (children && typeof children === \"string\") {\n el.textContent = children;\n }\n\n if (onLoad) el.addEventListener(\"load\", onLoad);\n if (onError) el.addEventListener(\"error\", onError);\n\n document.body.appendChild(el);\n if (key) loadedScripts.add(key);\n}\n\n/**\n * Initialize multiple scripts at once (called during app bootstrap).\n */\nexport function initScriptLoader(scripts: ScriptProps[]): void {\n for (const script of scripts) {\n handleClientScriptLoad(script);\n }\n}\n\nfunction Script(props: ScriptProps): React.ReactElement | null {\n const {\n src,\n id,\n strategy = \"afterInteractive\",\n onLoad,\n onReady,\n onError,\n children,\n dangerouslySetInnerHTML,\n ...rest\n } = props;\n\n const hasMounted = useRef(false);\n const key = id ?? src ?? \"\";\n\n // Client path: load scripts via useEffect based on strategy.\n // useEffect never runs during SSR, so it's safe to call unconditionally.\n useEffect(() => {\n if (hasMounted.current) return;\n hasMounted.current = true;\n\n // Already loaded — just fire onReady\n if (key && loadedScripts.has(key)) {\n onReady?.();\n return;\n }\n\n const load = () => {\n if (key && loadedScripts.has(key)) {\n onReady?.();\n return;\n }\n\n const el = document.createElement(\"script\");\n if (src) el.src = src;\n if (id) el.id = id;\n\n for (const [attr, value] of Object.entries(rest)) {\n if (attr === \"className\") {\n el.setAttribute(\"class\", String(value));\n } else if (typeof value === \"string\") {\n el.setAttribute(attr, value);\n } else if (typeof value === \"boolean\" && value) {\n el.setAttribute(attr, \"\");\n }\n }\n\n if (strategy === \"worker\") {\n el.setAttribute(\"type\", \"text/partytown\");\n }\n\n if (dangerouslySetInnerHTML?.__html) {\n // Intentional: mirrors the Next.js <Script> API where dangerouslySetInnerHTML\n // is developer-supplied inline script content (not user input). The prop name\n // itself signals developer awareness of the XSS risk, consistent with React's\n // design. User-supplied data must never flow into this prop.\n el.innerHTML = dangerouslySetInnerHTML.__html as string;\n } else if (children && typeof children === \"string\") {\n el.textContent = children;\n }\n\n el.addEventListener(\"load\", (e) => {\n if (key) loadedScripts.add(key);\n onLoad?.(e);\n onReady?.();\n });\n\n if (onError) {\n el.addEventListener(\"error\", onError);\n }\n\n document.body.appendChild(el);\n };\n\n if (strategy === \"lazyOnload\") {\n // Wait for window load, then use idle callback\n if (document.readyState === \"complete\") {\n if (typeof requestIdleCallback === \"function\") {\n requestIdleCallback(load);\n } else {\n setTimeout(load, 1);\n }\n } else {\n window.addEventListener(\"load\", () => {\n if (typeof requestIdleCallback === \"function\") {\n requestIdleCallback(load);\n } else {\n setTimeout(load, 1);\n }\n });\n }\n } else {\n // \"afterInteractive\" (default), \"beforeInteractive\" (client re-mount), \"worker\"\n load();\n }\n }, [src, id, strategy, onLoad, onReady, onError, children, dangerouslySetInnerHTML, key, rest]);\n\n // SSR path: only \"beforeInteractive\" renders a <script> tag server-side\n if (typeof window === \"undefined\") {\n if (strategy === \"beforeInteractive\") {\n const scriptProps: Record<string, unknown> = { ...rest };\n if (src) scriptProps.src = src;\n if (id) scriptProps.id = id;\n if (dangerouslySetInnerHTML) {\n // Escape closing </script> sequences in inline content so the HTML\n // parser doesn't prematurely terminate the element during SSR.\n const raw = dangerouslySetInnerHTML.__html;\n scriptProps.dangerouslySetInnerHTML = {\n __html: escapeInlineContent(raw, \"script\"),\n };\n }\n return React.createElement(\"script\", scriptProps, children);\n }\n // Other strategies don't render during SSR\n return null;\n }\n\n // The component itself renders nothing — scripts are injected imperatively\n return null;\n}\n\nexport default Script;\n"],"mappings":";;;;;;;;;;;;;;;;AAmDA,MAAM,gCAAgB,IAAI,KAAa;;;;AAKvC,SAAgB,uBAAuB,OAA0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@ declare class RequestCookies {
156
156
  }
157
157
  declare class ResponseCookies {
158
158
  private _headers;
159
+ /** Internal map keyed by cookie name — single source of truth. */
160
+ private _parsed;
159
161
  constructor(headers: Headers);
160
- set(name: string, value: string, options?: CookieOptions): this;
161
- get(name: string): CookieEntry | undefined;
162
+ set(...args: [name: string, value: string, options?: CookieOptions] | [options: CookieOptions & {
163
+ name: string;
164
+ value: string;
165
+ }]): this;
166
+ get(...args: [name: string] | [options: {
167
+ name: string;
168
+ }]): CookieEntry | undefined;
162
169
  has(name: string): boolean;
163
- getAll(): CookieEntry[];
164
- delete(name: string): this;
170
+ getAll(...args: [name: string] | [options: {
171
+ name: string;
172
+ }] | []): CookieEntry[];
173
+ delete(...args: [name: string] | [options: Omit<CookieOptions & {
174
+ name: string;
175
+ }, "maxAge" | "expires">]): this;
165
176
  [Symbol.iterator](): IterableIterator<[string, CookieEntry]>;
177
+ /** Delete all Set-Cookie headers and re-append from the internal map. */
178
+ private _syncHeaders;
166
179
  }
167
180
  type CookieOptions = {
168
181
  path?: string;