vinext 0.0.37 → 0.0.38
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.
- package/dist/cache.d.ts +2 -0
- package/dist/cache.js +2 -0
- package/dist/cli.js +6 -22
- package/dist/cli.js.map +1 -1
- package/dist/client/empty-module.d.ts +1 -0
- package/dist/client/empty-module.js +1 -0
- package/dist/client/entry.js +2 -0
- package/dist/client/entry.js.map +1 -1
- package/dist/client/instrumentation-client-state.d.ts +10 -0
- package/dist/client/instrumentation-client-state.js +19 -0
- package/dist/client/instrumentation-client-state.js.map +1 -0
- package/dist/client/instrumentation-client.d.ts +8 -0
- package/dist/client/instrumentation-client.js +8 -0
- package/dist/client/instrumentation-client.js.map +1 -0
- package/dist/cloudflare/tpr.js +1 -3
- package/dist/cloudflare/tpr.js.map +1 -1
- package/dist/deploy.js +9 -3
- package/dist/deploy.js.map +1 -1
- package/dist/entries/app-rsc-entry.js +27 -22
- package/dist/entries/app-rsc-entry.js.map +1 -1
- package/dist/entries/pages-client-entry.js +2 -0
- package/dist/entries/pages-client-entry.js.map +1 -1
- package/dist/entries/pages-server-entry.js +41 -260
- package/dist/entries/pages-server-entry.js.map +1 -1
- package/dist/entries/runtime-entry-module.d.ts +13 -1
- package/dist/entries/runtime-entry-module.js +18 -4
- package/dist/entries/runtime-entry-module.js.map +1 -1
- package/dist/index.d.ts +13 -11
- package/dist/index.js +101 -696
- package/dist/index.js.map +1 -1
- package/dist/plugins/fix-use-server-closure-collision.d.ts +29 -0
- package/dist/plugins/fix-use-server-closure-collision.js +204 -0
- package/dist/plugins/fix-use-server-closure-collision.js.map +1 -0
- package/dist/plugins/fonts.d.ts +39 -0
- package/dist/plugins/fonts.js +432 -0
- package/dist/plugins/fonts.js.map +1 -0
- package/dist/plugins/instrumentation-client.d.ts +7 -0
- package/dist/plugins/instrumentation-client.js +29 -0
- package/dist/plugins/instrumentation-client.js.map +1 -0
- package/dist/plugins/og-assets.d.ts +26 -0
- package/dist/plugins/og-assets.js +118 -0
- package/dist/plugins/og-assets.js.map +1 -0
- package/dist/server/api-handler.js +6 -23
- package/dist/server/api-handler.js.map +1 -1
- package/dist/server/app-browser-entry.js +4 -0
- package/dist/server/app-browser-entry.js.map +1 -1
- package/dist/server/dev-server.js +3 -1
- package/dist/server/dev-server.js.map +1 -1
- package/dist/server/instrumentation.d.ts +5 -1
- package/dist/server/instrumentation.js +15 -6
- package/dist/server/instrumentation.js.map +1 -1
- package/dist/server/middleware.d.ts +2 -0
- package/dist/server/middleware.js +14 -7
- package/dist/server/middleware.js.map +1 -1
- package/dist/server/pages-api-route.d.ts +23 -0
- package/dist/server/pages-api-route.js +40 -0
- package/dist/server/pages-api-route.js.map +1 -0
- package/dist/server/pages-media-type.d.ts +16 -0
- package/dist/server/pages-media-type.js +25 -0
- package/dist/server/pages-media-type.js.map +1 -0
- package/dist/server/pages-node-compat.d.ts +45 -0
- package/dist/server/pages-node-compat.js +148 -0
- package/dist/server/pages-node-compat.js.map +1 -0
- package/dist/server/prod-server.js +1 -0
- package/dist/server/prod-server.js.map +1 -1
- package/dist/shims/cache-for-request.d.ts +58 -0
- package/dist/shims/cache-for-request.js +74 -0
- package/dist/shims/cache-for-request.js.map +1 -0
- package/dist/shims/dynamic.js +25 -10
- package/dist/shims/dynamic.js.map +1 -1
- package/dist/shims/headers.js +1 -1
- package/dist/shims/image.js +24 -8
- package/dist/shims/image.js.map +1 -1
- package/dist/shims/layout-segment-context.js +9 -3
- package/dist/shims/layout-segment-context.js.map +1 -1
- package/dist/shims/link.js +2 -0
- package/dist/shims/link.js.map +1 -1
- package/dist/shims/navigation.js +2 -0
- package/dist/shims/navigation.js.map +1 -1
- package/dist/shims/server.d.ts +1 -0
- package/dist/shims/server.js +3 -0
- package/dist/shims/server.js.map +1 -1
- package/dist/shims/unified-request-context.d.ts +2 -0
- package/dist/shims/unified-request-context.js +1 -0
- package/dist/shims/unified-request-context.js.map +1 -1
- package/package.json +8 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamic.js","names":[],"sources":["../../src/shims/dynamic.ts"],"sourcesContent":["\"use client\";\n/**\n * next/dynamic shim\n *\n * SSR-safe dynamic imports. On the server, uses React.lazy + Suspense so that\n * renderToReadableStream suspends until the dynamically-imported component is\n * available. On the client, also uses React.lazy for code splitting.\n *\n * Supports:\n * - dynamic(() => import('./Component'))\n * - dynamic(() => import('./Component'), { loading: () => <Spinner /> })\n * - dynamic(() => import('./Component'), { ssr: false })\n */\nimport React, { lazy, Suspense, type ComponentType, useState, useEffect } from \"react\";\n\ninterface DynamicOptions {\n loading?: ComponentType<{ error?: Error | null; isLoading?: boolean; pastDelay?: boolean }>;\n ssr?: boolean;\n}\n\ntype Loader<P> = () => Promise<{ default: ComponentType<P> } | ComponentType<P>>;\n\n/**\n * Lightweight error boundary that renders the loading component with the error\n * when a dynamic() loader rejects. Without this, loader failures would propagate\n * uncaught through React's rendering — this preserves the Next.js behavior where\n * the `loading` component can display errors.\n *\n * Lazily created because React.Component is not available in the RSC environment\n * (server components use a slimmed-down React that doesn't include class components).\n */\nlet DynamicErrorBoundary: any;\nfunction getDynamicErrorBoundary() {\n if (DynamicErrorBoundary) return DynamicErrorBoundary;\n if (!React.Component) return null;\n DynamicErrorBoundary = class extends (\n React.Component<\n {\n fallback: ComponentType<{ error?: Error | null; isLoading?: boolean; pastDelay?: boolean }>;\n children: React.ReactNode;\n },\n { error: Error | null }\n >\n ) {\n constructor(props: any) {\n super(props);\n this.state = { error: null };\n }\n static getDerivedStateFromError(error: unknown) {\n return { error: error instanceof Error ? error : new Error(String(error)) };\n }\n render() {\n if (this.state.error) {\n return React.createElement(this.props.fallback, {\n isLoading: false,\n pastDelay: true,\n error: this.state.error,\n });\n }\n return this.props.children;\n }\n };\n return DynamicErrorBoundary;\n}\n\n// Detect server vs client\nconst isServer = typeof window === \"undefined\";\n\n// Legacy preload queue — kept for backward compatibility with Pages Router\n// which calls flushPreloads() before rendering. The App Router uses React.lazy\n// + Suspense instead, so this queue is no longer populated.\nconst preloadQueue: Promise<void>[] = [];\n\n/**\n * Wait for all pending dynamic() preloads to resolve, then clear the queue.\n * Called by the Pages Router SSR handler before rendering.\n * No-op for the App Router path which uses React.lazy + Suspense.\n */\nexport function flushPreloads(): Promise<void[]> {\n const pending = preloadQueue.splice(0);\n return Promise.all(pending);\n}\n\nfunction dynamic<P extends object = object>(\n loader: Loader<P>,\n options?: DynamicOptions,\n): ComponentType<P> {\n const { loading: LoadingComponent, ssr = true } = options ?? {};\n\n // ssr: false — render nothing on the server, lazy-load on client\n if (!ssr) {\n if (isServer) {\n // On the server, just render the loading state or nothing\n const SSRFalse = (_props: P) => {\n return LoadingComponent\n ? React.createElement(LoadingComponent, { isLoading: true, pastDelay: true, error: null })\n : null;\n };\n SSRFalse.displayName = \"DynamicSSRFalse\";\n return SSRFalse;\n }\n\n // Client: use lazy with Suspense\n const LazyComponent = lazy(async () => {\n const mod = await loader();\n if (\"default\" in mod) return mod as { default: ComponentType<P> };\n return { default: mod as ComponentType<P> };\n });\n\n const ClientSSRFalse = (props: P) => {\n const [mounted, setMounted] = useState(false);\n useEffect(() => setMounted(true), []);\n\n if (!mounted) {\n return LoadingComponent\n ? React.createElement(LoadingComponent, { isLoading: true, pastDelay: true, error: null })\n : null;\n }\n\n const fallback = LoadingComponent\n ? React.createElement(LoadingComponent, { isLoading: true, pastDelay: true, error: null })\n : null;\n return React.createElement(Suspense, { fallback }, React.createElement(LazyComponent, props));\n };\n\n ClientSSRFalse.displayName = \"DynamicClientSSRFalse\";\n return ClientSSRFalse;\n }\n\n // SSR-enabled path\n if (isServer) {\n // Use React.lazy so that renderToReadableStream can suspend until the\n // dynamically-imported component is available. The previous eager-load\n // pattern relied on flushPreloads() being called before rendering, which\n // works for the Pages Router but not the App Router where client modules\n // are loaded lazily during RSC stream deserialization (issue #75).\n const LazyServer = lazy(async () => {\n const mod = await loader();\n if (\"default\" in mod) return mod as { default: ComponentType<P> };\n return { default: mod as ComponentType<P> };\n });\n\n const ServerDynamic = (props: P) => {\n const fallback = LoadingComponent\n ? React.createElement(LoadingComponent, { isLoading: true, pastDelay: true, error: null })\n : null;\n const lazyElement = React.createElement(LazyServer, props);\n // Wrap with error boundary so loader rejections render the loading\n // component with the error instead of propagating uncaught.\n const ErrorBoundary = LoadingComponent ? getDynamicErrorBoundary() : null;\n const content = ErrorBoundary\n ? React.createElement(ErrorBoundary, { fallback: LoadingComponent }, lazyElement)\n : lazyElement;\n return React.createElement(Suspense, { fallback }, content);\n };\n\n ServerDynamic.displayName = \"DynamicServer\";\n return ServerDynamic;\n }\n\n // Client path: standard React.lazy with Suspense\n const LazyComponent = lazy(async () => {\n const mod = await loader();\n if (\"default\" in mod) return mod as { default: ComponentType<P> };\n return { default: mod as ComponentType<P> };\n });\n\n const ClientDynamic = (props: P) => {\n const fallback = LoadingComponent\n ? React.createElement(LoadingComponent, { isLoading: true, pastDelay: true, error: null })\n : null;\n return React.createElement(Suspense, { fallback }, React.createElement(LazyComponent, props));\n };\n\n ClientDynamic.displayName = \"DynamicClient\";\n return ClientDynamic;\n}\n\nexport default dynamic;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAI;AACJ,SAAS,0BAA0B;AACjC,KAAI,qBAAsB,QAAO;AACjC,KAAI,CAAC,MAAM,UAAW,QAAO;AAC7B,wBAAuB,cACrB,MAAM,UAON;EACA,YAAY,OAAY;AACtB,SAAM,MAAM;AACZ,QAAK,QAAQ,EAAE,OAAO,MAAM;;EAE9B,OAAO,yBAAyB,OAAgB;AAC9C,UAAO,EAAE,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,MAAM,CAAC,EAAE;;EAE7E,SAAS;AACP,OAAI,KAAK,MAAM,MACb,QAAO,MAAM,cAAc,KAAK,MAAM,UAAU;IAC9C,WAAW;IACX,WAAW;IACX,OAAO,KAAK,MAAM;IACnB,CAAC;AAEJ,UAAO,KAAK,MAAM;;;AAGtB,QAAO;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AAE,WAAW;IAAM,WAAW;IAAM,OAAO;IAAM,CAAC,GACxF;GACJ,MAAM,cAAc,MAAM,cAAc,YAAY,MAAM;GAG1D,MAAM,gBAAgB,mBAAmB,yBAAyB,GAAG;GACrE,MAAM,UAAU,gBACZ,MAAM,cAAc,eAAe,EAAE,UAAU,kBAAkB,EAAE,YAAY,GAC/E;AACJ,UAAO,MAAM,cAAc,UAAU,EAAE,UAAU,EAAE,QAAQ;;AAG7D,gBAAc,cAAc;AAC5B,SAAO;;CAIT,MAAM,gBAAgB,KAAK,YAAY;EACrC,MAAM,MAAM,MAAM,QAAQ;AAC1B,MAAI,aAAa,IAAK,QAAO;AAC7B,SAAO,EAAE,SAAS,KAAyB;GAC3C;CAEF,MAAM,iBAAiB,UAAa;EAClC,MAAM,WAAW,mBACb,MAAM,cAAc,kBAAkB;GAAE,WAAW;GAAM,WAAW;GAAM,OAAO;GAAM,CAAC,GACxF;AACJ,SAAO,MAAM,cAAc,UAAU,EAAE,UAAU,EAAE,MAAM,cAAc,eAAe,MAAM,CAAC;;AAG/F,eAAc,cAAc;AAC5B,QAAO"}
|
|
1
|
+
{"version":3,"file":"dynamic.js","names":[],"sources":["../../src/shims/dynamic.ts"],"sourcesContent":["/**\n * next/dynamic shim\n *\n * SSR-safe dynamic imports. On the server, uses React.lazy + Suspense so that\n * renderToReadableStream suspends until the dynamically-imported component is\n * available. On the client, also uses React.lazy for code splitting.\n *\n * Works in RSC, SSR, and client environments:\n * - RSC: Uses React.lazy + Suspense (available in React 19.x react-server).\n * Falls back to async component pattern if a future React version\n * strips lazy from react-server.\n * - SSR: React.lazy + Suspense (renderToReadableStream suspends)\n * - Client: React.lazy + Suspense (standard code splitting)\n *\n * Supports:\n * - dynamic(() => import('./Component'))\n * - dynamic(() => import('./Component'), { loading: () => <Spinner /> })\n * - dynamic(() => import('./Component'), { ssr: false })\n */\nimport React, { type ComponentType } from \"react\";\n\ninterface DynamicOptions {\n loading?: ComponentType<{ error?: Error | null; isLoading?: boolean; pastDelay?: boolean }>;\n ssr?: boolean;\n}\n\ntype Loader<P> = () => Promise<{ default: ComponentType<P> } | ComponentType<P>>;\n\n/**\n * Lightweight error boundary that renders the loading component with the error\n * when a dynamic() loader rejects. Without this, loader failures would propagate\n * uncaught through React's rendering — this preserves the Next.js behavior where\n * the `loading` component can display errors.\n *\n * Lazily created because React.Component is not available in the RSC environment\n * (server components use a slimmed-down React that doesn't include class components).\n */\nlet DynamicErrorBoundary: any;\nfunction getDynamicErrorBoundary() {\n if (DynamicErrorBoundary) return DynamicErrorBoundary;\n if (!React.Component) return null;\n DynamicErrorBoundary = class extends (\n React.Component<\n {\n fallback: ComponentType<{ error?: Error | null; isLoading?: boolean; pastDelay?: boolean }>;\n children: React.ReactNode;\n },\n { error: Error | null }\n >\n ) {\n constructor(props: any) {\n super(props);\n this.state = { error: null };\n }\n static getDerivedStateFromError(error: unknown) {\n return { error: error instanceof Error ? error : new Error(String(error)) };\n }\n render() {\n if (this.state.error) {\n return React.createElement(this.props.fallback, {\n isLoading: false,\n pastDelay: true,\n error: this.state.error,\n });\n }\n return this.props.children;\n }\n };\n return DynamicErrorBoundary;\n}\n\n// Detect server vs client\nconst isServer = typeof window === \"undefined\";\n\n// Legacy preload queue — kept for backward compatibility with Pages Router\n// which calls flushPreloads() before rendering. The App Router uses React.lazy\n// + Suspense instead, so this queue is no longer populated.\nconst preloadQueue: Promise<void>[] = [];\n\n/**\n * Wait for all pending dynamic() preloads to resolve, then clear the queue.\n * Called by the Pages Router SSR handler before rendering.\n * No-op for the App Router path which uses React.lazy + Suspense.\n */\nexport function flushPreloads(): Promise<void[]> {\n const pending = preloadQueue.splice(0);\n return Promise.all(pending);\n}\n\nfunction dynamic<P extends object = object>(\n loader: Loader<P>,\n options?: DynamicOptions,\n): ComponentType<P> {\n const { loading: LoadingComponent, ssr = true } = options ?? {};\n\n // ssr: false — render nothing on the server, lazy-load on client\n if (!ssr) {\n if (isServer) {\n // On the server (SSR or RSC), just render the loading state or nothing\n const SSRFalse = (_props: P) => {\n return LoadingComponent\n ? React.createElement(LoadingComponent, { isLoading: true, pastDelay: true, error: null })\n : null;\n };\n SSRFalse.displayName = \"DynamicSSRFalse\";\n return SSRFalse;\n }\n\n // Client: use lazy with Suspense\n const LazyComponent = React.lazy(async () => {\n const mod = await loader();\n if (\"default\" in mod) return mod as { default: ComponentType<P> };\n return { default: mod as ComponentType<P> };\n });\n\n const ClientSSRFalse = (props: P) => {\n const [mounted, setMounted] = React.useState(false);\n React.useEffect(() => setMounted(true), []);\n\n if (!mounted) {\n return LoadingComponent\n ? React.createElement(LoadingComponent, { isLoading: true, pastDelay: true, error: null })\n : null;\n }\n\n const fallback = LoadingComponent\n ? React.createElement(LoadingComponent, { isLoading: true, pastDelay: true, error: null })\n : null;\n return React.createElement(\n React.Suspense,\n { fallback },\n React.createElement(LazyComponent, props),\n );\n };\n\n ClientSSRFalse.displayName = \"DynamicClientSSRFalse\";\n return ClientSSRFalse;\n }\n\n // SSR-enabled path\n if (isServer) {\n // Defensive fallback: if a future React version strips React.lazy from the\n // react-server condition, fall back to an async component pattern.\n // In React 19.x, React.lazy IS available in react-server, so this branch\n // does not execute — it exists for forward compatibility only.\n if (typeof React.lazy !== \"function\") {\n const AsyncServerDynamic = async (props: P) => {\n // Note: LoadingComponent is not used here — in the RSC environment,\n // async components suspend natively and parent <Suspense> boundaries\n // provide loading states. Error handling also defers to the nearest\n // error boundary in the component tree.\n const mod = await loader();\n const Component =\n \"default\" in mod\n ? (mod as { default: ComponentType<P> }).default\n : (mod as ComponentType<P>);\n return React.createElement(Component, props);\n };\n AsyncServerDynamic.displayName = \"DynamicAsyncServer\";\n // Cast is safe: async components are natively supported by the RSC renderer,\n // but TypeScript's ComponentType<P> doesn't account for async return types.\n return AsyncServerDynamic as unknown as ComponentType<P>;\n }\n\n // SSR path: Use React.lazy so that renderToReadableStream can suspend\n // until the dynamically-imported component is available.\n const LazyServer = React.lazy(async () => {\n const mod = await loader();\n if (\"default\" in mod) return mod as { default: ComponentType<P> };\n return { default: mod as ComponentType<P> };\n });\n\n const ServerDynamic = (props: P) => {\n const fallback = LoadingComponent\n ? React.createElement(LoadingComponent, { isLoading: true, pastDelay: true, error: null })\n : null;\n const lazyElement = React.createElement(LazyServer, props);\n // Wrap with error boundary so loader rejections render the loading\n // component with the error instead of propagating uncaught.\n const ErrorBoundary = LoadingComponent ? getDynamicErrorBoundary() : null;\n const content = ErrorBoundary\n ? React.createElement(ErrorBoundary, { fallback: LoadingComponent }, lazyElement)\n : lazyElement;\n return React.createElement(React.Suspense, { fallback }, content);\n };\n\n ServerDynamic.displayName = \"DynamicServer\";\n return ServerDynamic;\n }\n\n // Client path: standard React.lazy with Suspense\n const LazyComponent = React.lazy(async () => {\n const mod = await loader();\n if (\"default\" in mod) return mod as { default: ComponentType<P> };\n return { default: mod as ComponentType<P> };\n });\n\n const ClientDynamic = (props: P) => {\n const fallback = LoadingComponent\n ? React.createElement(LoadingComponent, { isLoading: true, pastDelay: true, error: null })\n : null;\n return React.createElement(\n React.Suspense,\n { fallback },\n React.createElement(LazyComponent, props),\n );\n };\n\n ClientDynamic.displayName = \"DynamicClient\";\n return ClientDynamic;\n}\n\nexport default dynamic;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,IAAI;AACJ,SAAS,0BAA0B;AACjC,KAAI,qBAAsB,QAAO;AACjC,KAAI,CAAC,MAAM,UAAW,QAAO;AAC7B,wBAAuB,cACrB,MAAM,UAON;EACA,YAAY,OAAY;AACtB,SAAM,MAAM;AACZ,QAAK,QAAQ,EAAE,OAAO,MAAM;;EAE9B,OAAO,yBAAyB,OAAgB;AAC9C,UAAO,EAAE,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,MAAM,CAAC,EAAE;;EAE7E,SAAS;AACP,OAAI,KAAK,MAAM,MACb,QAAO,MAAM,cAAc,KAAK,MAAM,UAAU;IAC9C,WAAW;IACX,WAAW;IACX,OAAO,KAAK,MAAM;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R,IAAsC,UACtC;AACP,WAAO,MAAM,cAAc,WAAW,MAAM;;AAE9C,sBAAmB,cAAc;AAGjC,UAAO;;EAKT,MAAM,aAAa,MAAM,KAAK,YAAY;GACxC,MAAM,MAAM,MAAM,QAAQ;AAC1B,OAAI,aAAa,IAAK,QAAO;AAC7B,UAAO,EAAE,SAAS,KAAyB;IAC3C;EAEF,MAAM,iBAAiB,UAAa;GAClC,MAAM,WAAW,mBACb,MAAM,cAAc,kBAAkB;IAAE,WAAW;IAAM,WAAW;IAAM,OAAO;IAAM,CAAC,GACxF;GACJ,MAAM,cAAc,MAAM,cAAc,YAAY,MAAM;GAG1D,MAAM,gBAAgB,mBAAmB,yBAAyB,GAAG;GACrE,MAAM,UAAU,gBACZ,MAAM,cAAc,eAAe,EAAE,UAAU,kBAAkB,EAAE,YAAY,GAC/E;AACJ,UAAO,MAAM,cAAc,MAAM,UAAU,EAAE,UAAU,EAAE,QAAQ;;AAGnE,gBAAc,cAAc;AAC5B,SAAO;;CAIT,MAAM,gBAAgB,MAAM,KAAK,YAAY;EAC3C,MAAM,MAAM,MAAM,QAAQ;AAC1B,MAAI,aAAa,IAAK,QAAO;AAC7B,SAAO,EAAE,SAAS,KAAyB;GAC3C;CAEF,MAAM,iBAAiB,UAAa;EAClC,MAAM,WAAW,mBACb,MAAM,cAAc,kBAAkB;GAAE,WAAW;GAAM,WAAW;GAAM,OAAO;GAAM,CAAC,GACxF;AACJ,SAAO,MAAM,cACX,MAAM,UACN,EAAE,UAAU,EACZ,MAAM,cAAc,eAAe,MAAM,CAC1C;;AAGH,eAAc,cAAc;AAC5B,QAAO"}
|
package/dist/shims/headers.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { getRequestContext, isInsideUnifiedScope, runWithUnifiedStateMutation } from "./unified-request-context.js";
|
|
1
2
|
import { buildRequestHeadersFromMiddlewareResponse } from "../server/middleware-request-headers.js";
|
|
2
3
|
import { parseCookieHeader } from "./internal/parse-cookie-header.js";
|
|
3
|
-
import { getRequestContext, isInsideUnifiedScope, runWithUnifiedStateMutation } from "./unified-request-context.js";
|
|
4
4
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
5
5
|
//#region src/shims/headers.ts
|
|
6
6
|
/**
|
package/dist/shims/image.js
CHANGED
|
@@ -113,6 +113,18 @@ function isRemoteUrl(src) {
|
|
|
113
113
|
return src.startsWith("http://") || src.startsWith("https://") || src.startsWith("//");
|
|
114
114
|
}
|
|
115
115
|
/**
|
|
116
|
+
* Resolve src, width, height, blurDataURL from Image props (string or StaticImageData).
|
|
117
|
+
* Shared by the Image component and getImageProps to keep behavior in sync.
|
|
118
|
+
*/
|
|
119
|
+
function resolveImageSource(v) {
|
|
120
|
+
return {
|
|
121
|
+
src: typeof v.src === "string" ? v.src : v.src.src,
|
|
122
|
+
width: v.width ?? (typeof v.src === "object" ? v.src.width : void 0),
|
|
123
|
+
height: v.height ?? (typeof v.src === "object" ? v.src.height : void 0),
|
|
124
|
+
blurDataURL: v.blurDataURL ?? (typeof v.src === "object" ? v.src.blurDataURL : void 0)
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
116
128
|
* Responsive image widths matching Next.js's device sizes config.
|
|
117
129
|
* These are the breakpoints used for srcSet generation.
|
|
118
130
|
* Configurable via `images.deviceSizes` in next.config.js.
|
|
@@ -145,10 +157,12 @@ const Image = forwardRef(function Image({ src: srcProp, alt, width, height, fill
|
|
|
145
157
|
onLoad?.(e);
|
|
146
158
|
onLoadingComplete(e.currentTarget);
|
|
147
159
|
} : onLoad;
|
|
148
|
-
const src
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
160
|
+
const { src, width: imgWidth, height: imgHeight, blurDataURL: imgBlurDataURL } = resolveImageSource({
|
|
161
|
+
src: srcProp,
|
|
162
|
+
width,
|
|
163
|
+
height,
|
|
164
|
+
blurDataURL
|
|
165
|
+
});
|
|
152
166
|
if (loader) return /* @__PURE__ */ jsx("img", {
|
|
153
167
|
ref,
|
|
154
168
|
src: loader({
|
|
@@ -255,10 +269,12 @@ const Image = forwardRef(function Image({ src: srcProp, alt, width, height, fill
|
|
|
255
269
|
*/
|
|
256
270
|
function getImageProps(props) {
|
|
257
271
|
const { src: srcProp, alt, width, height, fill, priority, quality: _quality, placeholder, blurDataURL: blurDataURLProp, loader, sizes, className, style, onLoad: _onLoad, onLoadingComplete: _onLoadingComplete, unoptimized: _unoptimized, overrideSrc: _overrideSrc, loading, ...rest } = props;
|
|
258
|
-
const src
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
272
|
+
const { src, width: imgWidth, height: imgHeight, blurDataURL: imgBlurDataURL } = resolveImageSource({
|
|
273
|
+
src: srcProp,
|
|
274
|
+
width,
|
|
275
|
+
height,
|
|
276
|
+
blurDataURL: blurDataURLProp
|
|
277
|
+
});
|
|
262
278
|
let blockedInProd = false;
|
|
263
279
|
if (isRemoteUrl(src)) {
|
|
264
280
|
const validation = validateRemoteUrl(src);
|
package/dist/shims/image.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"image.js","names":["UnpicImage"],"sources":["../../src/shims/image.tsx"],"sourcesContent":["/**\n * next/image shim\n *\n * Translates Next.js Image props to @unpic/react Image component.\n * @unpic/react auto-detects CDN from URL and uses native transforms.\n * For local images (relative paths), routes through `/_vinext/image`\n * for server-side optimization (resize, format negotiation, quality).\n *\n * Remote images are validated against `images.remotePatterns` and\n * `images.domains` from next.config.js. Unmatched URLs are blocked\n * in production and warn in development, matching Next.js behavior.\n */\nimport React, { forwardRef } from \"react\";\nimport { Image as UnpicImage } from \"@unpic/react\";\nimport { hasRemoteMatch, type RemotePattern } from \"./image-config.js\";\n\nexport interface StaticImageData {\n src: string;\n height: number;\n width: number;\n blurDataURL?: string;\n}\n\n/**\n * Image config injected at build time via Vite define.\n * Serialized as JSON — parsed once at module level.\n */\nconst __imageRemotePatterns: RemotePattern[] = (() => {\n try {\n return JSON.parse(process.env.__VINEXT_IMAGE_REMOTE_PATTERNS ?? \"[]\");\n } catch {\n return [];\n }\n})();\nconst __imageDomains: string[] = (() => {\n try {\n return JSON.parse(process.env.__VINEXT_IMAGE_DOMAINS ?? \"[]\");\n } catch {\n return [];\n }\n})();\nconst __hasImageConfig = __imageRemotePatterns.length > 0 || __imageDomains.length > 0;\nconst __isDev = process.env.NODE_ENV !== \"production\";\nconst __imageDeviceSizes: number[] = (() => {\n try {\n return JSON.parse(\n process.env.__VINEXT_IMAGE_DEVICE_SIZES ?? \"[640,750,828,1080,1200,1920,2048,3840]\",\n );\n } catch {\n return [640, 750, 828, 1080, 1200, 1920, 2048, 3840];\n }\n})();\n/**\n * Whether dangerouslyAllowSVG is enabled in next.config.js.\n * When false (default), .svg sources auto-skip the optimization endpoint\n * and are served directly, matching Next.js behavior.\n * When true, .svg sources are routed through the optimizer (served as-is\n * with security headers).\n */\nconst __dangerouslyAllowSVG = process.env.__VINEXT_IMAGE_DANGEROUSLY_ALLOW_SVG === \"true\";\n/**\n * Validate that a remote URL is allowed by the configured remote patterns.\n * Returns true if the URL is allowed, false otherwise.\n *\n * When no remotePatterns/domains are configured, all remote URLs are allowed\n * (backwards-compatible — user hasn't opted into restriction).\n *\n * When patterns ARE configured, only matching URLs are allowed.\n * In development, non-matching URLs produce a console warning.\n * In production, non-matching URLs are blocked (src replaced with empty string).\n */\nfunction validateRemoteUrl(src: string): { allowed: boolean; reason?: string } {\n if (!__hasImageConfig) {\n // No image config — allow everything (backwards-compatible)\n return { allowed: true };\n }\n\n let url: URL;\n try {\n url = new URL(src, \"http://n\");\n } catch {\n return { allowed: false, reason: `Invalid URL: ${src}` };\n }\n\n if (hasRemoteMatch(__imageDomains, __imageRemotePatterns, url)) {\n return { allowed: true };\n }\n\n return {\n allowed: false,\n reason: `Image URL \"${src}\" is not configured in images.remotePatterns or images.domains in next.config.js. See: https://nextjs.org/docs/messages/next-image-unconfigured-host`,\n };\n}\n\ninterface ImageProps {\n src: string | StaticImageData;\n alt: string;\n width?: number;\n height?: number;\n fill?: boolean;\n priority?: boolean;\n quality?: number;\n placeholder?: \"blur\" | \"empty\";\n blurDataURL?: string;\n loader?: (params: { src: string; width: number; quality?: number }) => string;\n sizes?: string;\n className?: string;\n style?: React.CSSProperties;\n onLoad?: React.ReactEventHandler<HTMLImageElement>;\n /** @deprecated Use onLoad instead. Still supported for migration compat. */\n onLoadingComplete?: (img: HTMLImageElement) => void;\n onError?: React.ReactEventHandler<HTMLImageElement>;\n onClick?: React.MouseEventHandler<HTMLImageElement>;\n id?: string;\n // Accept and ignore Next.js-specific props that don't apply\n unoptimized?: boolean;\n overrideSrc?: string;\n loading?: \"lazy\" | \"eager\";\n}\n\n/**\n * Sanitize a blurDataURL to prevent CSS injection.\n *\n * A crafted data URL containing `)` can break out of the `url()` CSS function,\n * allowing injection of arbitrary CSS properties or rules. Characters like `{`,\n * `}`, and `\\` can also assist in crafting injection payloads.\n *\n * This validates the URL starts with `data:image/` and rejects characters that\n * could escape the `url()` context. Semicolons are allowed since they're part\n * of valid data URLs (`data:image/png;base64,...`) and harmless inside `url()`.\n *\n * Returns undefined for invalid URLs, which causes the blur placeholder to be\n * skipped gracefully.\n */\nfunction sanitizeBlurDataURL(url: string): string | undefined {\n // Must be a data: image URL\n if (!url.startsWith(\"data:image/\")) return undefined;\n // Reject characters that can break out of CSS url():\n // ) - closes url()\n // ( - could open nested functions\n // { } - CSS rule boundaries\n // \\ - CSS escape sequences\n // newlines - break CSS parsing\n if (/[)(}{\\\\'\"\\n\\r]/.test(url)) return undefined;\n return url;\n}\n\n/**\n * Determine if a src is a remote URL (CDN-optimizable) or local.\n */\nfunction isRemoteUrl(src: string): boolean {\n return src.startsWith(\"http://\") || src.startsWith(\"https://\") || src.startsWith(\"//\");\n}\n\n/**\n * Responsive image widths matching Next.js's device sizes config.\n * These are the breakpoints used for srcSet generation.\n * Configurable via `images.deviceSizes` in next.config.js.\n */\nconst RESPONSIVE_WIDTHS = __imageDeviceSizes;\n\n/**\n * Build a `/_vinext/image` optimization URL.\n *\n * In production (Cloudflare Workers), the worker intercepts this path and uses\n * the Images binding to resize/transcode on the fly. In dev, the Vite dev\n * server handles it as a passthrough (serves the original file).\n */\nexport function imageOptimizationUrl(src: string, width: number, quality: number = 75): string {\n return `/_vinext/image?url=${encodeURIComponent(src)}&w=${width}&q=${quality}`;\n}\n\n/**\n * Generate a srcSet string for responsive images.\n *\n * Each width points to the `/_vinext/image` optimization endpoint so the\n * server can resize and transcode the image. Only includes widths that are\n * <= 2x the original image width to avoid pointless upscaling.\n */\nfunction generateSrcSet(src: string, originalWidth: number, quality: number = 75): string {\n const widths = RESPONSIVE_WIDTHS.filter((w) => w <= originalWidth * 2);\n if (widths.length === 0)\n return `${imageOptimizationUrl(src, originalWidth, quality)} ${originalWidth}w`;\n return widths.map((w) => `${imageOptimizationUrl(src, w, quality)} ${w}w`).join(\", \");\n}\n\nconst Image = forwardRef<HTMLImageElement, ImageProps>(function Image(\n {\n src: srcProp,\n alt,\n width,\n height,\n fill,\n priority,\n quality,\n placeholder,\n blurDataURL,\n loader,\n sizes,\n className,\n style,\n onLoad,\n onLoadingComplete,\n unoptimized: _unoptimized,\n overrideSrc: _overrideSrc,\n loading,\n ...rest\n },\n ref,\n) {\n // Wire onLoadingComplete (deprecated) into onLoad — matches Next.js behavior.\n // onLoad fires first, then onLoadingComplete receives the HTMLImageElement.\n const handleLoad = onLoadingComplete\n ? (e: React.SyntheticEvent<HTMLImageElement>) => {\n onLoad?.(e);\n onLoadingComplete(e.currentTarget);\n }\n : onLoad;\n\n // Handle StaticImageData (import result)\n const src = typeof srcProp === \"string\" ? srcProp : srcProp.src;\n const imgWidth = width ?? (typeof srcProp === \"object\" ? srcProp.width : undefined);\n const imgHeight = height ?? (typeof srcProp === \"object\" ? srcProp.height : undefined);\n const imgBlurDataURL =\n blurDataURL ?? (typeof srcProp === \"object\" ? srcProp.blurDataURL : undefined);\n\n // If a custom loader is provided, use basic img with loader URL\n if (loader) {\n const resolvedSrc = loader({ src, width: imgWidth ?? 0, quality: quality ?? 75 });\n return (\n <img\n ref={ref}\n src={resolvedSrc}\n alt={alt}\n width={fill ? undefined : imgWidth}\n height={fill ? undefined : imgHeight}\n loading={priority ? \"eager\" : (loading ?? \"lazy\")}\n decoding=\"async\"\n sizes={sizes}\n className={className}\n onLoad={handleLoad}\n style={\n fill\n ? {\n position: \"absolute\",\n inset: 0,\n width: \"100%\",\n height: \"100%\",\n objectFit: \"cover\",\n ...style,\n }\n : style\n }\n {...rest}\n />\n );\n }\n\n // For remote URLs, validate against remotePatterns then use @unpic/react\n if (isRemoteUrl(src)) {\n const validation = validateRemoteUrl(src);\n if (!validation.allowed) {\n if (__isDev) {\n console.warn(`[next/image] ${validation.reason}`);\n // In dev, render the image but with a warning — matches Next.js dev behavior\n } else {\n // In production, block the image entirely\n console.error(`[next/image] ${validation.reason}`);\n return null;\n }\n }\n\n const sanitizedBlur = imgBlurDataURL ? sanitizeBlurDataURL(imgBlurDataURL) : undefined;\n const bg = placeholder === \"blur\" && sanitizedBlur ? `url(${sanitizedBlur})` : undefined;\n\n if (fill) {\n return (\n <UnpicImage\n src={src}\n alt={alt}\n layout=\"fullWidth\"\n // `priority` is a Next.js concept — translate it to HTML attributes so\n // it is never forwarded to the DOM as a non-boolean attribute, which\n // would trigger React's \"Received `true` for a non-boolean attribute\"\n // warning.\n loading={priority ? \"eager\" : (loading ?? \"lazy\")}\n fetchPriority={priority ? \"high\" : undefined}\n sizes={sizes}\n className={className}\n background={bg}\n onLoad={handleLoad}\n />\n );\n }\n // constrained layout requires width+height or aspectRatio\n if (imgWidth && imgHeight) {\n return (\n <UnpicImage\n src={src}\n alt={alt}\n width={imgWidth}\n height={imgHeight}\n layout=\"constrained\"\n // Same translation as above — never pass `priority` to the DOM.\n loading={priority ? \"eager\" : (loading ?? \"lazy\")}\n fetchPriority={priority ? \"high\" : undefined}\n sizes={sizes}\n className={className}\n background={bg}\n onLoad={handleLoad}\n />\n );\n }\n // Fall through to basic <img> if dimensions not provided\n // (unpic requires them for constrained layout)\n }\n\n // Route local images through the /_vinext/image optimization endpoint.\n // In production on Cloudflare Workers, this resizes and transcodes via\n // the Images binding. In dev, it serves the original file as a passthrough.\n // When `unoptimized` is true, bypass the endpoint entirely (Next.js compat).\n // SVG sources auto-skip unless dangerouslyAllowSVG is enabled, matching\n // Next.js behavior where .svg triggers unoptimized=true by default.\n const imgQuality = quality ?? 75;\n const isSvg = src.endsWith(\".svg\");\n const skipOptimization = _unoptimized === true || (isSvg && !__dangerouslyAllowSVG);\n\n // Build srcSet for responsive local images (common breakpoints).\n // Each entry points to /_vinext/image with the appropriate width.\n const srcSet =\n imgWidth && !fill && !skipOptimization\n ? generateSrcSet(src, imgWidth, imgQuality)\n : imgWidth && !fill\n ? RESPONSIVE_WIDTHS.filter((w) => w <= imgWidth * 2)\n .map((w) => `${src} ${w}w`)\n .join(\", \") || `${src} ${imgWidth}w`\n : undefined;\n\n // The main `src` also goes through the optimization endpoint. Use the\n // declared width (or the first responsive width as fallback).\n const optimizedSrc = skipOptimization\n ? src\n : imgWidth\n ? imageOptimizationUrl(src, imgWidth, imgQuality)\n : imageOptimizationUrl(src, RESPONSIVE_WIDTHS[0], imgQuality);\n\n // Blur placeholder: show a low-quality background while the image loads.\n // Sanitize blurDataURL to prevent CSS injection via crafted data URLs.\n const sanitizedLocalBlur = imgBlurDataURL ? sanitizeBlurDataURL(imgBlurDataURL) : undefined;\n const blurStyle =\n placeholder === \"blur\" && sanitizedLocalBlur\n ? {\n backgroundImage: `url(${sanitizedLocalBlur})`,\n backgroundSize: \"cover\",\n backgroundRepeat: \"no-repeat\",\n backgroundPosition: \"center\",\n }\n : undefined;\n\n // For local images, render a standard <img> tag with srcSet and blur support.\n // The src and srcSet point to the /_vinext/image optimization endpoint.\n return (\n <img\n ref={ref}\n src={optimizedSrc}\n alt={alt}\n width={fill ? undefined : imgWidth}\n height={fill ? undefined : imgHeight}\n loading={priority ? \"eager\" : (loading ?? \"lazy\")}\n fetchPriority={priority ? \"high\" : undefined}\n decoding=\"async\"\n srcSet={srcSet}\n sizes={sizes ?? (fill ? \"100vw\" : undefined)}\n className={className}\n data-nimg={fill ? \"fill\" : \"1\"}\n onLoad={handleLoad}\n style={\n fill\n ? {\n position: \"absolute\",\n inset: 0,\n width: \"100%\",\n height: \"100%\",\n objectFit: \"cover\",\n ...blurStyle,\n ...style,\n }\n : { ...blurStyle, ...style }\n }\n {...rest}\n />\n );\n});\n\n/**\n * getImageProps — for advanced use cases (picture elements, background images).\n * Returns the props that would be passed to the underlying <img> element.\n */\nexport function getImageProps(props: ImageProps): {\n props: React.ImgHTMLAttributes<HTMLImageElement>;\n} {\n const {\n src: srcProp,\n alt,\n width,\n height,\n fill,\n priority,\n quality: _quality,\n placeholder,\n blurDataURL: blurDataURLProp,\n loader,\n sizes,\n className,\n style,\n onLoad: _onLoad,\n onLoadingComplete: _onLoadingComplete,\n unoptimized: _unoptimized,\n overrideSrc: _overrideSrc,\n loading,\n ...rest\n } = props;\n\n const src = typeof srcProp === \"string\" ? srcProp : srcProp.src;\n const imgWidth = width ?? (typeof srcProp === \"object\" ? srcProp.width : undefined);\n const imgHeight = height ?? (typeof srcProp === \"object\" ? srcProp.height : undefined);\n const imgBlurDataURL =\n blurDataURLProp ?? (typeof srcProp === \"object\" ? srcProp.blurDataURL : undefined);\n\n // Validate remote URLs against configured patterns\n let blockedInProd = false;\n if (isRemoteUrl(src)) {\n const validation = validateRemoteUrl(src);\n if (!validation.allowed) {\n if (__isDev) {\n console.warn(`[next/image] ${validation.reason}`);\n } else {\n console.error(`[next/image] ${validation.reason}`);\n blockedInProd = true;\n }\n }\n }\n\n // Resolve src through custom loader if provided\n const imgQuality = _quality ?? 75;\n const resolvedSrc = blockedInProd\n ? \"\"\n : loader\n ? loader({ src, width: imgWidth ?? 0, quality: imgQuality })\n : src;\n\n // For local images (no loader, not remote), route through optimization endpoint.\n // When `unoptimized` is true, bypass the endpoint entirely (Next.js compat).\n // SVG sources auto-skip unless dangerouslyAllowSVG is enabled.\n const isSvg = resolvedSrc.endsWith(\".svg\");\n const skipOpt =\n _unoptimized === true ||\n (isSvg && !__dangerouslyAllowSVG) ||\n blockedInProd ||\n !!loader ||\n isRemoteUrl(resolvedSrc);\n const optimizedSrc = skipOpt\n ? resolvedSrc\n : imgWidth\n ? imageOptimizationUrl(resolvedSrc, imgWidth, imgQuality)\n : imageOptimizationUrl(resolvedSrc, RESPONSIVE_WIDTHS[0], imgQuality);\n\n // Build srcSet for local images — each width points to /_vinext/image\n const srcSet =\n imgWidth && !fill && !isRemoteUrl(resolvedSrc) && !loader && !skipOpt\n ? generateSrcSet(resolvedSrc, imgWidth, imgQuality)\n : undefined;\n\n // Blur placeholder styles — sanitize to prevent CSS injection\n const sanitizedBlurURL = imgBlurDataURL ? sanitizeBlurDataURL(imgBlurDataURL) : undefined;\n const blurStyle =\n placeholder === \"blur\" && sanitizedBlurURL\n ? {\n backgroundImage: `url(${sanitizedBlurURL})`,\n backgroundSize: \"cover\",\n backgroundRepeat: \"no-repeat\" as const,\n backgroundPosition: \"center\" as const,\n }\n : undefined;\n\n return {\n props: {\n src: optimizedSrc,\n alt,\n width: fill ? undefined : imgWidth,\n height: fill ? undefined : imgHeight,\n loading: priority ? \"eager\" : (loading ?? \"lazy\"),\n fetchPriority: priority ? (\"high\" as const) : undefined,\n decoding: \"async\" as const,\n srcSet,\n sizes: sizes ?? (fill ? \"100vw\" : undefined),\n className,\n \"data-nimg\": fill ? \"fill\" : \"1\",\n style: fill\n ? {\n position: \"absolute\" as const,\n inset: 0,\n width: \"100%\",\n height: \"100%\",\n objectFit: \"cover\" as const,\n ...blurStyle,\n ...style,\n }\n : { ...blurStyle, ...style },\n ...rest,\n } as React.ImgHTMLAttributes<HTMLImageElement>,\n };\n}\n\nexport default Image;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA2BA,MAAM,+BAAgD;AACpD,KAAI;AACF,SAAO,KAAK,MAAM,QAAQ,IAAI,kCAAkC,KAAK;SAC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,SAAS,OAAO;CAC1C,MAAM,UACJ,iBAAiB,QAChB,SAAS,CAAC,yBACX,iBACA,CAAC,CAAC,UACF,YAAY,YAAY;CAC1B,MAAM,eAAe,UACjB,cACA,WACE,qBAAqB,aAAa,UAAU,WAAW,GACvD,qBAAqB,aAAa,kBAAkB,IAAI,WAAW;CAGzE,MAAM,SACJ,YAAY,CAAC,QAAQ,CAAC,YAAY,YAAY,IAAI,CAAC,UAAU,CAAC,UAC1D,eAAe,aAAa,UAAU,WAAW,GACjD,KAAA;CAGN,MAAM,mBAAmB,iBAAiB,oBAAoB,eAAe,GAAG,KAAA;CAChF,MAAM,YACJ,gBAAgB,UAAU,mBACtB;EACE,iBAAiB,OAAO,iBAAiB;EACzC,gBAAgB;EAChB,kBAAkB;EAClB,oBAAoB;EACrB,GACD,KAAA;AAEN,QAAO,EACL,OAAO;EACL,KAAK;EACL;EACA,OAAO,OAAO,KAAA,IAAY;EAC1B,QAAQ,OAAO,KAAA,IAAY;EAC3B,SAAS,WAAW,UAAW,WAAW;EAC1C,eAAe,WAAY,SAAmB,KAAA;EAC9C,UAAU;EACV;EACA,OAAO,UAAU,OAAO,UAAU,KAAA;EAClC;EACA,aAAa,OAAO,SAAS;EAC7B,OAAO,OACH;GACE,UAAU;GACV,OAAO;GACP,OAAO;GACP,QAAQ;GACR,WAAW;GACX,GAAG;GACH,GAAG;GACJ,GACD;GAAE,GAAG;GAAW,GAAG;GAAO;EAC9B,GAAG;EACJ,EACF"}
|
|
1
|
+
{"version":3,"file":"image.js","names":["UnpicImage"],"sources":["../../src/shims/image.tsx"],"sourcesContent":["/**\n * next/image shim\n *\n * Translates Next.js Image props to @unpic/react Image component.\n * @unpic/react auto-detects CDN from URL and uses native transforms.\n * For local images (relative paths), routes through `/_vinext/image`\n * for server-side optimization (resize, format negotiation, quality).\n *\n * Remote images are validated against `images.remotePatterns` and\n * `images.domains` from next.config.js. Unmatched URLs are blocked\n * in production and warn in development, matching Next.js behavior.\n */\nimport React, { forwardRef } from \"react\";\nimport { Image as UnpicImage } from \"@unpic/react\";\nimport { hasRemoteMatch, type RemotePattern } from \"./image-config.js\";\n\nexport interface StaticImageData {\n src: string;\n height: number;\n width: number;\n blurDataURL?: string;\n}\n\n/**\n * Image config injected at build time via Vite define.\n * Serialized as JSON — parsed once at module level.\n */\nconst __imageRemotePatterns: RemotePattern[] = (() => {\n try {\n return JSON.parse(process.env.__VINEXT_IMAGE_REMOTE_PATTERNS ?? \"[]\");\n } catch {\n return [];\n }\n})();\nconst __imageDomains: string[] = (() => {\n try {\n return JSON.parse(process.env.__VINEXT_IMAGE_DOMAINS ?? \"[]\");\n } catch {\n return [];\n }\n})();\nconst __hasImageConfig = __imageRemotePatterns.length > 0 || __imageDomains.length > 0;\nconst __isDev = process.env.NODE_ENV !== \"production\";\nconst __imageDeviceSizes: number[] = (() => {\n try {\n return JSON.parse(\n process.env.__VINEXT_IMAGE_DEVICE_SIZES ?? \"[640,750,828,1080,1200,1920,2048,3840]\",\n );\n } catch {\n return [640, 750, 828, 1080, 1200, 1920, 2048, 3840];\n }\n})();\n/**\n * Whether dangerouslyAllowSVG is enabled in next.config.js.\n * When false (default), .svg sources auto-skip the optimization endpoint\n * and are served directly, matching Next.js behavior.\n * When true, .svg sources are routed through the optimizer (served as-is\n * with security headers).\n */\nconst __dangerouslyAllowSVG = process.env.__VINEXT_IMAGE_DANGEROUSLY_ALLOW_SVG === \"true\";\n/**\n * Validate that a remote URL is allowed by the configured remote patterns.\n * Returns true if the URL is allowed, false otherwise.\n *\n * When no remotePatterns/domains are configured, all remote URLs are allowed\n * (backwards-compatible — user hasn't opted into restriction).\n *\n * When patterns ARE configured, only matching URLs are allowed.\n * In development, non-matching URLs produce a console warning.\n * In production, non-matching URLs are blocked (src replaced with empty string).\n */\nfunction validateRemoteUrl(src: string): { allowed: boolean; reason?: string } {\n if (!__hasImageConfig) {\n // No image config — allow everything (backwards-compatible)\n return { allowed: true };\n }\n\n let url: URL;\n try {\n url = new URL(src, \"http://n\");\n } catch {\n return { allowed: false, reason: `Invalid URL: ${src}` };\n }\n\n if (hasRemoteMatch(__imageDomains, __imageRemotePatterns, url)) {\n return { allowed: true };\n }\n\n return {\n allowed: false,\n reason: `Image URL \"${src}\" is not configured in images.remotePatterns or images.domains in next.config.js. See: https://nextjs.org/docs/messages/next-image-unconfigured-host`,\n };\n}\n\ninterface ImageProps {\n src: string | StaticImageData;\n alt: string;\n width?: number;\n height?: number;\n fill?: boolean;\n priority?: boolean;\n quality?: number;\n placeholder?: \"blur\" | \"empty\";\n blurDataURL?: string;\n loader?: (params: { src: string; width: number; quality?: number }) => string;\n sizes?: string;\n className?: string;\n style?: React.CSSProperties;\n onLoad?: React.ReactEventHandler<HTMLImageElement>;\n /** @deprecated Use onLoad instead. Still supported for migration compat. */\n onLoadingComplete?: (img: HTMLImageElement) => void;\n onError?: React.ReactEventHandler<HTMLImageElement>;\n onClick?: React.MouseEventHandler<HTMLImageElement>;\n id?: string;\n // Accept and ignore Next.js-specific props that don't apply\n unoptimized?: boolean;\n overrideSrc?: string;\n loading?: \"lazy\" | \"eager\";\n}\n\n/**\n * Sanitize a blurDataURL to prevent CSS injection.\n *\n * A crafted data URL containing `)` can break out of the `url()` CSS function,\n * allowing injection of arbitrary CSS properties or rules. Characters like `{`,\n * `}`, and `\\` can also assist in crafting injection payloads.\n *\n * This validates the URL starts with `data:image/` and rejects characters that\n * could escape the `url()` context. Semicolons are allowed since they're part\n * of valid data URLs (`data:image/png;base64,...`) and harmless inside `url()`.\n *\n * Returns undefined for invalid URLs, which causes the blur placeholder to be\n * skipped gracefully.\n */\nfunction sanitizeBlurDataURL(url: string): string | undefined {\n // Must be a data: image URL\n if (!url.startsWith(\"data:image/\")) return undefined;\n // Reject characters that can break out of CSS url():\n // ) - closes url()\n // ( - could open nested functions\n // { } - CSS rule boundaries\n // \\ - CSS escape sequences\n // newlines - break CSS parsing\n if (/[)(}{\\\\'\"\\n\\r]/.test(url)) return undefined;\n return url;\n}\n\n/**\n * Determine if a src is a remote URL (CDN-optimizable) or local.\n */\nfunction isRemoteUrl(src: string): boolean {\n return src.startsWith(\"http://\") || src.startsWith(\"https://\") || src.startsWith(\"//\");\n}\n\n/**\n * Resolve src, width, height, blurDataURL from Image props (string or StaticImageData).\n * Shared by the Image component and getImageProps to keep behavior in sync.\n */\nfunction resolveImageSource(v: {\n src: string | StaticImageData;\n width?: number;\n height?: number;\n blurDataURL?: string;\n}): { src: string; width?: number; height?: number; blurDataURL?: string } {\n const src = typeof v.src === \"string\" ? v.src : v.src.src;\n const imgWidth = v.width ?? (typeof v.src === \"object\" ? v.src.width : undefined);\n const imgHeight = v.height ?? (typeof v.src === \"object\" ? v.src.height : undefined);\n const imgBlurDataURL =\n v.blurDataURL ?? (typeof v.src === \"object\" ? v.src.blurDataURL : undefined);\n return { src, width: imgWidth, height: imgHeight, blurDataURL: imgBlurDataURL };\n}\n\n/**\n * Responsive image widths matching Next.js's device sizes config.\n * These are the breakpoints used for srcSet generation.\n * Configurable via `images.deviceSizes` in next.config.js.\n */\nconst RESPONSIVE_WIDTHS = __imageDeviceSizes;\n\n/**\n * Build a `/_vinext/image` optimization URL.\n *\n * In production (Cloudflare Workers), the worker intercepts this path and uses\n * the Images binding to resize/transcode on the fly. In dev, the Vite dev\n * server handles it as a passthrough (serves the original file).\n */\nexport function imageOptimizationUrl(src: string, width: number, quality: number = 75): string {\n return `/_vinext/image?url=${encodeURIComponent(src)}&w=${width}&q=${quality}`;\n}\n\n/**\n * Generate a srcSet string for responsive images.\n *\n * Each width points to the `/_vinext/image` optimization endpoint so the\n * server can resize and transcode the image. Only includes widths that are\n * <= 2x the original image width to avoid pointless upscaling.\n */\nfunction generateSrcSet(src: string, originalWidth: number, quality: number = 75): string {\n const widths = RESPONSIVE_WIDTHS.filter((w) => w <= originalWidth * 2);\n if (widths.length === 0)\n return `${imageOptimizationUrl(src, originalWidth, quality)} ${originalWidth}w`;\n return widths.map((w) => `${imageOptimizationUrl(src, w, quality)} ${w}w`).join(\", \");\n}\n\nconst Image = forwardRef<HTMLImageElement, ImageProps>(function Image(\n {\n src: srcProp,\n alt,\n width,\n height,\n fill,\n priority,\n quality,\n placeholder,\n blurDataURL,\n loader,\n sizes,\n className,\n style,\n onLoad,\n onLoadingComplete,\n unoptimized: _unoptimized,\n overrideSrc: _overrideSrc,\n loading,\n ...rest\n },\n ref,\n) {\n // Wire onLoadingComplete (deprecated) into onLoad — matches Next.js behavior.\n // onLoad fires first, then onLoadingComplete receives the HTMLImageElement.\n const handleLoad = onLoadingComplete\n ? (e: React.SyntheticEvent<HTMLImageElement>) => {\n onLoad?.(e);\n onLoadingComplete(e.currentTarget);\n }\n : onLoad;\n\n const {\n src,\n width: imgWidth,\n height: imgHeight,\n blurDataURL: imgBlurDataURL,\n } = resolveImageSource({ src: srcProp, width, height, blurDataURL });\n\n // If a custom loader is provided, use basic img with loader URL\n if (loader) {\n const resolvedSrc = loader({ src, width: imgWidth ?? 0, quality: quality ?? 75 });\n return (\n <img\n ref={ref}\n src={resolvedSrc}\n alt={alt}\n width={fill ? undefined : imgWidth}\n height={fill ? undefined : imgHeight}\n loading={priority ? \"eager\" : (loading ?? \"lazy\")}\n decoding=\"async\"\n sizes={sizes}\n className={className}\n onLoad={handleLoad}\n style={\n fill\n ? {\n position: \"absolute\",\n inset: 0,\n width: \"100%\",\n height: \"100%\",\n objectFit: \"cover\",\n ...style,\n }\n : style\n }\n {...rest}\n />\n );\n }\n\n // For remote URLs, validate against remotePatterns then use @unpic/react\n if (isRemoteUrl(src)) {\n const validation = validateRemoteUrl(src);\n if (!validation.allowed) {\n if (__isDev) {\n console.warn(`[next/image] ${validation.reason}`);\n // In dev, render the image but with a warning — matches Next.js dev behavior\n } else {\n // In production, block the image entirely\n console.error(`[next/image] ${validation.reason}`);\n return null;\n }\n }\n\n const sanitizedBlur = imgBlurDataURL ? sanitizeBlurDataURL(imgBlurDataURL) : undefined;\n const bg = placeholder === \"blur\" && sanitizedBlur ? `url(${sanitizedBlur})` : undefined;\n\n if (fill) {\n return (\n <UnpicImage\n src={src}\n alt={alt}\n layout=\"fullWidth\"\n // `priority` is a Next.js concept — translate it to HTML attributes so\n // it is never forwarded to the DOM as a non-boolean attribute, which\n // would trigger React's \"Received `true` for a non-boolean attribute\"\n // warning.\n loading={priority ? \"eager\" : (loading ?? \"lazy\")}\n fetchPriority={priority ? \"high\" : undefined}\n sizes={sizes}\n className={className}\n background={bg}\n onLoad={handleLoad}\n />\n );\n }\n // constrained layout requires width+height or aspectRatio\n if (imgWidth && imgHeight) {\n return (\n <UnpicImage\n src={src}\n alt={alt}\n width={imgWidth}\n height={imgHeight}\n layout=\"constrained\"\n // Same translation as above — never pass `priority` to the DOM.\n loading={priority ? \"eager\" : (loading ?? \"lazy\")}\n fetchPriority={priority ? \"high\" : undefined}\n sizes={sizes}\n className={className}\n background={bg}\n onLoad={handleLoad}\n />\n );\n }\n // Fall through to basic <img> if dimensions not provided\n // (unpic requires them for constrained layout)\n }\n\n // Route local images through the /_vinext/image optimization endpoint.\n // In production on Cloudflare Workers, this resizes and transcodes via\n // the Images binding. In dev, it serves the original file as a passthrough.\n // When `unoptimized` is true, bypass the endpoint entirely (Next.js compat).\n // SVG sources auto-skip unless dangerouslyAllowSVG is enabled, matching\n // Next.js behavior where .svg triggers unoptimized=true by default.\n const imgQuality = quality ?? 75;\n const isSvg = src.endsWith(\".svg\");\n const skipOptimization = _unoptimized === true || (isSvg && !__dangerouslyAllowSVG);\n\n // Build srcSet for responsive local images (common breakpoints).\n // Each entry points to /_vinext/image with the appropriate width.\n const srcSet =\n imgWidth && !fill && !skipOptimization\n ? generateSrcSet(src, imgWidth, imgQuality)\n : imgWidth && !fill\n ? RESPONSIVE_WIDTHS.filter((w) => w <= imgWidth * 2)\n .map((w) => `${src} ${w}w`)\n .join(\", \") || `${src} ${imgWidth}w`\n : undefined;\n\n // The main `src` also goes through the optimization endpoint. Use the\n // declared width (or the first responsive width as fallback).\n const optimizedSrc = skipOptimization\n ? src\n : imgWidth\n ? imageOptimizationUrl(src, imgWidth, imgQuality)\n : imageOptimizationUrl(src, RESPONSIVE_WIDTHS[0], imgQuality);\n\n // Blur placeholder: show a low-quality background while the image loads.\n // Sanitize blurDataURL to prevent CSS injection via crafted data URLs.\n const sanitizedLocalBlur = imgBlurDataURL ? sanitizeBlurDataURL(imgBlurDataURL) : undefined;\n const blurStyle =\n placeholder === \"blur\" && sanitizedLocalBlur\n ? {\n backgroundImage: `url(${sanitizedLocalBlur})`,\n backgroundSize: \"cover\",\n backgroundRepeat: \"no-repeat\",\n backgroundPosition: \"center\",\n }\n : undefined;\n\n // For local images, render a standard <img> tag with srcSet and blur support.\n // The src and srcSet point to the /_vinext/image optimization endpoint.\n return (\n <img\n ref={ref}\n src={optimizedSrc}\n alt={alt}\n width={fill ? undefined : imgWidth}\n height={fill ? undefined : imgHeight}\n loading={priority ? \"eager\" : (loading ?? \"lazy\")}\n fetchPriority={priority ? \"high\" : undefined}\n decoding=\"async\"\n srcSet={srcSet}\n sizes={sizes ?? (fill ? \"100vw\" : undefined)}\n className={className}\n data-nimg={fill ? \"fill\" : \"1\"}\n onLoad={handleLoad}\n style={\n fill\n ? {\n position: \"absolute\",\n inset: 0,\n width: \"100%\",\n height: \"100%\",\n objectFit: \"cover\",\n ...blurStyle,\n ...style,\n }\n : { ...blurStyle, ...style }\n }\n {...rest}\n />\n );\n});\n\n/**\n * getImageProps — for advanced use cases (picture elements, background images).\n * Returns the props that would be passed to the underlying <img> element.\n */\nexport function getImageProps(props: ImageProps): {\n props: React.ImgHTMLAttributes<HTMLImageElement>;\n} {\n const {\n src: srcProp,\n alt,\n width,\n height,\n fill,\n priority,\n quality: _quality,\n placeholder,\n blurDataURL: blurDataURLProp,\n loader,\n sizes,\n className,\n style,\n onLoad: _onLoad,\n onLoadingComplete: _onLoadingComplete,\n unoptimized: _unoptimized,\n overrideSrc: _overrideSrc,\n loading,\n ...rest\n } = props;\n\n const {\n src,\n width: imgWidth,\n height: imgHeight,\n blurDataURL: imgBlurDataURL,\n } = resolveImageSource({ src: srcProp, width, height, blurDataURL: blurDataURLProp });\n\n // Validate remote URLs against configured patterns\n let blockedInProd = false;\n if (isRemoteUrl(src)) {\n const validation = validateRemoteUrl(src);\n if (!validation.allowed) {\n if (__isDev) {\n console.warn(`[next/image] ${validation.reason}`);\n } else {\n console.error(`[next/image] ${validation.reason}`);\n blockedInProd = true;\n }\n }\n }\n\n // Resolve src through custom loader if provided\n const imgQuality = _quality ?? 75;\n const resolvedSrc = blockedInProd\n ? \"\"\n : loader\n ? loader({ src, width: imgWidth ?? 0, quality: imgQuality })\n : src;\n\n // For local images (no loader, not remote), route through optimization endpoint.\n // When `unoptimized` is true, bypass the endpoint entirely (Next.js compat).\n // SVG sources auto-skip unless dangerouslyAllowSVG is enabled.\n const isSvg = resolvedSrc.endsWith(\".svg\");\n const skipOpt =\n _unoptimized === true ||\n (isSvg && !__dangerouslyAllowSVG) ||\n blockedInProd ||\n !!loader ||\n isRemoteUrl(resolvedSrc);\n const optimizedSrc = skipOpt\n ? resolvedSrc\n : imgWidth\n ? imageOptimizationUrl(resolvedSrc, imgWidth, imgQuality)\n : imageOptimizationUrl(resolvedSrc, RESPONSIVE_WIDTHS[0], imgQuality);\n\n // Build srcSet for local images — each width points to /_vinext/image\n const srcSet =\n imgWidth && !fill && !isRemoteUrl(resolvedSrc) && !loader && !skipOpt\n ? generateSrcSet(resolvedSrc, imgWidth, imgQuality)\n : undefined;\n\n // Blur placeholder styles — sanitize to prevent CSS injection\n const sanitizedBlurURL = imgBlurDataURL ? sanitizeBlurDataURL(imgBlurDataURL) : undefined;\n const blurStyle =\n placeholder === \"blur\" && sanitizedBlurURL\n ? {\n backgroundImage: `url(${sanitizedBlurURL})`,\n backgroundSize: \"cover\",\n backgroundRepeat: \"no-repeat\" as const,\n backgroundPosition: \"center\" as const,\n }\n : undefined;\n\n return {\n props: {\n src: optimizedSrc,\n alt,\n width: fill ? undefined : imgWidth,\n height: fill ? undefined : imgHeight,\n loading: priority ? \"eager\" : (loading ?? \"lazy\"),\n fetchPriority: priority ? (\"high\" as const) : undefined,\n decoding: \"async\" as const,\n srcSet,\n sizes: sizes ?? (fill ? \"100vw\" : undefined),\n className,\n \"data-nimg\": fill ? \"fill\" : \"1\",\n style: fill\n ? {\n position: \"absolute\" as const,\n inset: 0,\n width: \"100%\",\n height: \"100%\",\n objectFit: \"cover\" as const,\n ...blurStyle,\n ...style,\n }\n : { ...blurStyle, ...style },\n ...rest,\n } as React.ImgHTMLAttributes<HTMLImageElement>,\n };\n}\n\nexport default Image;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA2BA,MAAM,+BAAgD;AACpD,KAAI;AACF,SAAO,KAAK,MAAM,QAAQ,IAAI,kCAAkC,KAAK;SAC/D;AACN,SAAO,EAAE;;IAET;AACJ,MAAM,wBAAkC;AACtC,KAAI;AACF,SAAO,KAAK,MAAM,QAAQ,IAAI,0BAA0B,KAAK;SACvD;AACN,SAAO,EAAE;;IAET;AACJ,MAAM,mBAAmB,sBAAsB,SAAS,KAAK,eAAe,SAAS;AACrF,MAAM,UAAU,QAAQ,IAAI,aAAa;AACzC,MAAM,4BAAsC;AAC1C,KAAI;AACF,SAAO,KAAK,MACV,QAAQ,IAAI,+BAA+B,yCAC5C;SACK;AACN,SAAO;GAAC;GAAK;GAAK;GAAK;GAAM;GAAM;GAAM;GAAM;GAAK;;IAEpD;;;;;;;;AAQJ,MAAM,wBAAwB,QAAQ,IAAI,yCAAyC;;;;;;;;;;;;AAYnF,SAAS,kBAAkB,KAAoD;AAC7E,KAAI,CAAC,iBAEH,QAAO,EAAE,SAAS,MAAM;CAG1B,IAAI;AACJ,KAAI;AACF,QAAM,IAAI,IAAI,KAAK,WAAW;SACxB;AACN,SAAO;GAAE,SAAS;GAAO,QAAQ,gBAAgB;GAAO;;AAG1D,KAAI,eAAe,gBAAgB,uBAAuB,IAAI,CAC5D,QAAO,EAAE,SAAS,MAAM;AAG1B,QAAO;EACL,SAAS;EACT,QA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AC9C,UAAU;EACV;EACA,OAAO,UAAU,OAAO,UAAU,KAAA;EAClC;EACA,aAAa,OAAO,SAAS;EAC7B,OAAO,OACH;GACE,UAAU;GACV,OAAO;GACP,OAAO;GACP,QAAQ;GACR,WAAW;GACX,GAAG;GACH,GAAG;GACJ,GACD;GAAE,GAAG;GAAW,GAAG;GAAO;EAC9B,GAAG;EACJ,EACF"}
|
|
@@ -5,9 +5,15 @@ import { createElement } from "react";
|
|
|
5
5
|
/**
|
|
6
6
|
* Layout segment context provider.
|
|
7
7
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
8
|
+
* Must be "use client" so that Vite's RSC bundler renders this component in
|
|
9
|
+
* the SSR/browser environment where React.createContext is available. The RSC
|
|
10
|
+
* entry imports and renders LayoutSegmentProvider directly, but because of the
|
|
11
|
+
* "use client" boundary the actual execution happens on the SSR/client side
|
|
12
|
+
* where the context can be created and consumed by useSelectedLayoutSegment(s).
|
|
13
|
+
*
|
|
14
|
+
* Without "use client", this runs in the RSC environment where
|
|
15
|
+
* React.createContext is undefined, getLayoutSegmentContext() returns null,
|
|
16
|
+
* the provider becomes a no-op, and useSelectedLayoutSegments always returns [].
|
|
11
17
|
*
|
|
12
18
|
* The context is shared with navigation.ts via getLayoutSegmentContext()
|
|
13
19
|
* to avoid creating separate contexts in different modules.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"layout-segment-context.js","names":[],"sources":["../../src/shims/layout-segment-context.tsx"],"sourcesContent":["\"use client\";\n\n/**\n * Layout segment context provider.\n *\n *
|
|
1
|
+
{"version":3,"file":"layout-segment-context.js","names":[],"sources":["../../src/shims/layout-segment-context.tsx"],"sourcesContent":["\"use client\";\n\n/**\n * Layout segment context provider.\n *\n * Must be \"use client\" so that Vite's RSC bundler renders this component in\n * the SSR/browser environment where React.createContext is available. The RSC\n * entry imports and renders LayoutSegmentProvider directly, but because of the\n * \"use client\" boundary the actual execution happens on the SSR/client side\n * where the context can be created and consumed by useSelectedLayoutSegment(s).\n *\n * Without \"use client\", this runs in the RSC environment where\n * React.createContext is undefined, getLayoutSegmentContext() returns null,\n * the provider becomes a no-op, and useSelectedLayoutSegments always returns [].\n *\n * The context is shared with navigation.ts via getLayoutSegmentContext()\n * to avoid creating separate contexts in different modules.\n */\nimport { createElement, type ReactNode } from \"react\";\nimport { getLayoutSegmentContext } from \"./navigation.js\";\n\n/**\n * Wraps children with the layout segment context.\n * Each layout in the App Router tree wraps its children with this provider,\n * passing the remaining route tree segments below that layout level.\n * Segments include route groups and resolved dynamic param values.\n */\nexport function LayoutSegmentProvider({\n childSegments,\n children,\n}: {\n childSegments: string[];\n children: ReactNode;\n}) {\n const ctx = getLayoutSegmentContext();\n if (!ctx) {\n // Fallback: no context available (shouldn't happen in SSR/Browser)\n return children as any;\n }\n return createElement(ctx.Provider, { value: childSegments }, children);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,sBAAsB,EACpC,eACA,YAIC;CACD,MAAM,MAAM,yBAAyB;AACrC,KAAI,CAAC,IAEH,QAAO;AAET,QAAO,cAAc,IAAI,UAAU,EAAE,OAAO,eAAe,EAAE,SAAS"}
|
package/dist/shims/link.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { resolveRelativeHref, toBrowserNavigationHref, toSameOriginAppPath, withBasePath } from "./url-utils.js";
|
|
3
3
|
import { addLocalePrefix, getDomainLocaleUrl } from "../utils/domain-locale.js";
|
|
4
4
|
import { appendSearchParamsToUrl, urlQueryToSearchParams } from "../utils/query.js";
|
|
5
|
+
import { notifyAppRouterTransitionStart } from "../client/instrumentation-client-state.js";
|
|
5
6
|
import { getPrefetchedUrls, storePrefetchResponse, toRscUrl } from "./navigation.js";
|
|
6
7
|
import { isDangerousScheme } from "./url-safety.js";
|
|
7
8
|
import { getI18nContext } from "./i18n-context.js";
|
|
@@ -246,6 +247,7 @@ const Link = forwardRef(function Link({ href, as, replace = false, prefetch: pre
|
|
|
246
247
|
const hashIdx = absoluteFullHref.indexOf("#");
|
|
247
248
|
const hash = hashIdx !== -1 ? absoluteFullHref.slice(hashIdx) : "";
|
|
248
249
|
if (typeof window.__VINEXT_RSC_NAVIGATE__ === "function") {
|
|
250
|
+
notifyAppRouterTransitionStart(absoluteFullHref, replace ? "replace" : "push");
|
|
249
251
|
if (replace) window.history.replaceState(null, "", absoluteFullHref);
|
|
250
252
|
else window.history.pushState(null, "", absoluteFullHref);
|
|
251
253
|
setPending(true);
|
package/dist/shims/link.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"link.js","names":[],"sources":["../../src/shims/link.tsx"],"sourcesContent":["\"use client\";\n\n/**\n * next/link shim\n *\n * Renders an <a> tag with client-side navigation support.\n * On click, prevents full page reload and triggers client-side\n * page swap via the router's navigation system.\n */\nimport React, {\n forwardRef,\n useRef,\n useEffect,\n useCallback,\n useContext,\n createContext,\n useState,\n type AnchorHTMLAttributes,\n type MouseEvent,\n} from \"react\";\n// Import shared RSC prefetch utilities from navigation shim (relative path\n// so this resolves both via the Vite plugin and in direct vitest imports)\nimport { toRscUrl, getPrefetchedUrls, storePrefetchResponse } from \"./navigation.js\";\nimport { isDangerousScheme } from \"./url-safety.js\";\nimport {\n resolveRelativeHref,\n toBrowserNavigationHref,\n toSameOriginAppPath,\n withBasePath,\n} from \"./url-utils.js\";\nimport { appendSearchParamsToUrl, type UrlQuery, urlQueryToSearchParams } from \"../utils/query.js\";\nimport { addLocalePrefix, getDomainLocaleUrl, type DomainLocale } from \"../utils/domain-locale.js\";\nimport { getI18nContext } from \"./i18n-context.js\";\nimport type { VinextNextData } from \"../client/vinext-next-data.js\";\n\ninterface NavigateEvent {\n url: URL;\n /** Call to prevent the Link's default navigation (e.g. for View Transitions). */\n preventDefault(): void;\n /** Whether preventDefault() has been called. */\n defaultPrevented: boolean;\n}\n\ninterface LinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> {\n href: string | { pathname?: string; query?: UrlQuery };\n /** URL displayed in the browser (when href is a route pattern like /user/[id]) */\n as?: string;\n /** Replace the current history entry instead of pushing */\n replace?: boolean;\n /** Prefetch the page in the background (default: true, uses IntersectionObserver) */\n prefetch?: boolean;\n /** Whether to pass the href to the child element */\n passHref?: boolean;\n /** Scroll to top on navigation (default: true) */\n scroll?: boolean;\n /** Locale for i18n (used for locale-prefixed URLs) */\n locale?: string | false;\n /** Called before navigation happens (Next.js 16). Return value is ignored. */\n onNavigate?: (event: NavigateEvent) => void;\n children?: React.ReactNode;\n}\n\n// ---------------------------------------------------------------------------\n// useLinkStatus — reports the pending state of a parent <Link> navigation\n// ---------------------------------------------------------------------------\n\ninterface LinkStatusContextValue {\n pending: boolean;\n}\n\nconst LinkStatusContext = createContext<LinkStatusContextValue>({ pending: false });\n\n/**\n * useLinkStatus returns the pending state of the enclosing <Link>.\n * In Next.js, this is used to show loading indicators while a\n * prefetch-triggered navigation is in progress.\n */\nexport function useLinkStatus(): LinkStatusContextValue {\n return useContext(LinkStatusContext);\n}\n\n/** basePath from next.config.js, injected by the plugin at build time */\nconst __basePath: string = process.env.__NEXT_ROUTER_BASEPATH ?? \"\";\n\nfunction resolveHref(href: LinkProps[\"href\"]): string {\n if (typeof href === \"string\") return href;\n let url = href.pathname ?? \"/\";\n if (href.query) {\n const params = urlQueryToSearchParams(href.query);\n url = appendSearchParamsToUrl(url, params);\n }\n return url;\n}\n\n/**\n * Check if a href is only a hash change (same pathname, different/added hash).\n * Handles relative hashes like \"#foo\" and \"?query#foo\".\n */\nfunction isHashOnlyChange(href: string): boolean {\n if (href.startsWith(\"#\")) return true;\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/**\n * Scroll to a hash target element, or to the top if no hash.\n */\nfunction scrollToHash(hash: string): void {\n if (!hash || hash === \"#\") {\n window.scrollTo(0, 0);\n return;\n }\n const id = hash.slice(1); // Remove leading #\n const element = document.getElementById(id);\n if (element) {\n element.scrollIntoView({ behavior: \"auto\" });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Prefetching infrastructure\n// ---------------------------------------------------------------------------\n\n/**\n * Prefetch a URL for faster navigation.\n *\n * For App Router (RSC): fetches the .rsc payload in the background and\n * stores it in an in-memory cache for instant use during navigation.\n * For Pages Router: injects a <link rel=\"prefetch\"> for the page module.\n *\n * Uses `requestIdleCallback` (or `setTimeout` fallback) to avoid blocking\n * the main thread during initial page load.\n */\nfunction prefetchUrl(href: string): void {\n if (typeof window === \"undefined\") return;\n\n // Normalize same-origin absolute URLs to local paths before prefetching\n let prefetchHref = href;\n if (href.startsWith(\"http://\") || href.startsWith(\"https://\") || href.startsWith(\"//\")) {\n const localPath = toSameOriginAppPath(href, __basePath);\n if (localPath == null) return; // truly external — don't prefetch\n prefetchHref = localPath;\n }\n\n const fullHref = toBrowserNavigationHref(prefetchHref, window.location.href, __basePath);\n\n // Don't prefetch the same URL twice (keyed by rscUrl so the browser\n // entry can clear the key when a cache entry is consumed)\n const rscUrl = toRscUrl(fullHref);\n const prefetched = getPrefetchedUrls();\n if (prefetched.has(rscUrl)) return;\n prefetched.add(rscUrl);\n\n const schedule = (window as any).requestIdleCallback ?? ((fn: () => void) => setTimeout(fn, 100));\n\n schedule(() => {\n if (typeof window.__VINEXT_RSC_NAVIGATE__ === \"function\") {\n // App Router: prefetch the RSC payload and store in cache\n fetch(rscUrl, {\n headers: { Accept: \"text/x-component\" },\n credentials: \"include\",\n priority: \"low\" as any,\n // @ts-expect-error — purpose is a valid fetch option in some browsers\n purpose: \"prefetch\",\n })\n .then((response) => {\n if (response.ok) {\n storePrefetchResponse(rscUrl, response);\n } else {\n // Non-ok response: allow retry on next viewport intersection\n prefetched.delete(rscUrl);\n }\n })\n .catch(() => {\n // Network error: allow retry on next viewport intersection\n prefetched.delete(rscUrl);\n });\n } else if ((window.__NEXT_DATA__ as VinextNextData | undefined)?.__vinext?.pageModuleUrl) {\n // Pages Router: inject a prefetch link for the target page module\n // We can't easily resolve the target page's module URL from the Link,\n // so we create a <link rel=\"prefetch\"> for the HTML page which helps\n // the browser's preload scanner.\n const link = document.createElement(\"link\");\n link.rel = \"prefetch\";\n link.href = fullHref;\n link.as = \"document\";\n document.head.appendChild(link);\n }\n });\n}\n\n/**\n * Shared IntersectionObserver for viewport-based prefetching.\n * All Link elements use the same observer to minimize resource usage.\n */\nlet sharedObserver: IntersectionObserver | null = null;\nconst observerCallbacks = new WeakMap<Element, () => void>();\n\nfunction getSharedObserver(): IntersectionObserver | null {\n if (typeof window === \"undefined\" || typeof IntersectionObserver === \"undefined\") return null;\n if (sharedObserver) return sharedObserver;\n\n sharedObserver = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n const callback = observerCallbacks.get(entry.target);\n if (callback) {\n callback();\n // Unobserve after prefetching — only prefetch once\n sharedObserver?.unobserve(entry.target);\n observerCallbacks.delete(entry.target);\n }\n }\n }\n },\n {\n // Start prefetching when the link is within 250px of the viewport.\n // This gives the browser a head start before the user scrolls to it.\n rootMargin: \"250px\",\n },\n );\n\n return sharedObserver;\n}\n\nfunction getDefaultLocale(): string | undefined {\n if (typeof window !== \"undefined\") {\n return window.__VINEXT_DEFAULT_LOCALE__;\n }\n return getI18nContext()?.defaultLocale;\n}\n\nfunction getDomainLocales(): readonly DomainLocale[] | undefined {\n if (typeof window !== \"undefined\") {\n return (window.__NEXT_DATA__ as VinextNextData | undefined)?.domainLocales;\n }\n return getI18nContext()?.domainLocales;\n}\n\nfunction getCurrentHostname(): string | undefined {\n if (typeof window !== \"undefined\") return window.location.hostname;\n return getI18nContext()?.hostname;\n}\n\nfunction getDomainLocaleHref(href: string, locale: string): string | undefined {\n // Only cross-domain locale switches need a special absolute URL here.\n // Same-domain cases fall back to the standard locale-prefix logic below.\n return getDomainLocaleUrl(href, locale, {\n basePath: __basePath,\n currentHostname: getCurrentHostname(),\n domainItems: getDomainLocales(),\n });\n}\n\n/**\n * Apply locale prefix to a URL path based on the locale prop.\n * - locale=\"fr\" → prepend /fr (unless it already has a locale prefix)\n * - locale={false} → use the href as-is (no locale prefix, link to default)\n * - locale=undefined → use current locale (href as-is in most cases)\n */\nfunction applyLocaleToHref(href: string, locale: string | false | undefined): string {\n if (locale === false) {\n // Explicit false: no locale prefix\n return href;\n }\n\n if (locale === undefined) {\n // No locale prop: keep current behavior (href as-is)\n return href;\n }\n\n // Absolute and protocol-relative URLs must not be prefixed — locale\n // only applies to local paths.\n if (href.startsWith(\"http://\") || href.startsWith(\"https://\") || href.startsWith(\"//\")) {\n return href;\n }\n\n const domainLocaleHref = getDomainLocaleHref(href, locale);\n if (domainLocaleHref) {\n return domainLocaleHref;\n }\n\n return addLocalePrefix(href, locale, getDefaultLocale() ?? \"\");\n}\n\nconst Link = forwardRef<HTMLAnchorElement, LinkProps>(function Link(\n {\n href,\n as,\n replace = false,\n prefetch: prefetchProp,\n scroll = true,\n children,\n onClick,\n onNavigate,\n ...rest\n },\n forwardedRef,\n) {\n // Extract locale from rest props\n const { locale, ...restWithoutLocale } = rest as any;\n\n // If `as` is provided, use it as the actual URL (legacy Next.js pattern\n // where href is a route pattern like \"/user/[id]\" and as is \"/user/1\")\n const resolvedHref = as ?? resolveHref(href);\n\n const isDangerous = typeof resolvedHref === \"string\" && isDangerousScheme(resolvedHref);\n\n // Apply locale prefix if specified (safe even for dangerous hrefs since we\n // won't use the result when isDangerous is true)\n const localizedHref = applyLocaleToHref(isDangerous ? \"/\" : resolvedHref, locale);\n // Full href with basePath for browser URLs and fetches\n const fullHref = withBasePath(localizedHref, __basePath);\n\n // Track pending state for useLinkStatus()\n const [pending, setPending] = useState(false);\n const mountedRef = useRef(true);\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Prefetching: observe the element when it enters the viewport.\n // prefetch={false} disables, prefetch={true} or undefined/null (default) enables.\n const internalRef = useRef<HTMLAnchorElement | null>(null);\n const shouldPrefetch = prefetchProp !== false && !isDangerous;\n\n const setRefs = useCallback(\n (node: HTMLAnchorElement | null) => {\n internalRef.current = node;\n if (typeof forwardedRef === \"function\") forwardedRef(node);\n else if (forwardedRef)\n (forwardedRef as React.MutableRefObject<HTMLAnchorElement | null>).current = node;\n },\n [forwardedRef],\n );\n\n useEffect(() => {\n if (!shouldPrefetch || typeof window === \"undefined\") return;\n const node = internalRef.current;\n if (!node) return;\n\n // Normalize same-origin absolute URLs; skip truly external ones\n let hrefToPrefetch = localizedHref;\n if (\n localizedHref.startsWith(\"http://\") ||\n localizedHref.startsWith(\"https://\") ||\n localizedHref.startsWith(\"//\")\n ) {\n const localPath = toSameOriginAppPath(localizedHref, __basePath);\n if (localPath == null) return; // truly external\n hrefToPrefetch = localPath;\n }\n\n const observer = getSharedObserver();\n if (!observer) return;\n\n observerCallbacks.set(node, () => prefetchUrl(hrefToPrefetch));\n observer.observe(node);\n\n return () => {\n observer.unobserve(node);\n observerCallbacks.delete(node);\n };\n }, [shouldPrefetch, localizedHref]);\n\n const handleClick = async (e: MouseEvent<HTMLAnchorElement>) => {\n if (onClick) onClick(e);\n if (e.defaultPrevented) return;\n\n // Only intercept left clicks without modifiers (standard link behavior)\n if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {\n return;\n }\n\n // Don't intercept links with target (e.g. target=\"_blank\")\n if (e.currentTarget.target && e.currentTarget.target !== \"_self\") {\n return;\n }\n\n // External links: let the browser handle it.\n // Same-origin absolute URLs (e.g. http://localhost:3000/about) are\n // normalized to local paths so they get client-side navigation.\n let navigateHref = localizedHref;\n if (\n resolvedHref.startsWith(\"http://\") ||\n resolvedHref.startsWith(\"https://\") ||\n resolvedHref.startsWith(\"//\")\n ) {\n const localPath = toSameOriginAppPath(resolvedHref, __basePath);\n if (localPath == null) return; // truly external\n navigateHref = localPath;\n }\n\n e.preventDefault();\n\n // Resolve relative hrefs (#hash, ?query) against the current URL once so\n // onNavigate and the actual navigation target stay in sync.\n const absoluteHref = resolveRelativeHref(navigateHref, window.location.href, __basePath);\n const absoluteFullHref = toBrowserNavigationHref(\n navigateHref,\n window.location.href,\n __basePath,\n );\n\n // Call onNavigate callback if provided (Next.js 16 View Transitions support)\n if (onNavigate) {\n try {\n const navUrl = new URL(absoluteFullHref, window.location.origin);\n let prevented = false;\n const navEvent: NavigateEvent = {\n url: navUrl,\n preventDefault() {\n prevented = true;\n },\n get defaultPrevented() {\n return prevented;\n },\n };\n onNavigate(navEvent);\n // If the callback called preventDefault(), skip Link's default navigation.\n // The callback is responsible for its own navigation (e.g. via View Transitions API).\n if (navEvent.defaultPrevented) {\n return;\n }\n } catch {\n // Ignore URL parsing errors for relative/hash hrefs\n }\n }\n\n // Save scroll position for back/forward restoration\n if (!replace) {\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 // Hash-only change: update URL and scroll to target, skip RSC fetch\n if (typeof window !== \"undefined\" && isHashOnlyChange(absoluteFullHref)) {\n const hash = absoluteFullHref.includes(\"#\")\n ? absoluteFullHref.slice(absoluteFullHref.indexOf(\"#\"))\n : \"\";\n if (replace) {\n window.history.replaceState(null, \"\", absoluteFullHref);\n } else {\n window.history.pushState(null, \"\", absoluteFullHref);\n }\n if (scroll) {\n scrollToHash(hash);\n }\n return;\n }\n\n // Extract hash for scroll-after-navigation\n const hashIdx = absoluteFullHref.indexOf(\"#\");\n const hash = hashIdx !== -1 ? absoluteFullHref.slice(hashIdx) : \"\";\n\n // Try RSC navigation first (App Router), then Pages Router\n if (typeof window.__VINEXT_RSC_NAVIGATE__ === \"function\") {\n // App Router: push/replace history state, then fetch RSC stream.\n // Await the RSC navigate so scroll-to-top happens after the new\n // content is committed to the DOM (prevents flash of old page at top).\n if (replace) {\n window.history.replaceState(null, \"\", absoluteFullHref);\n } else {\n window.history.pushState(null, \"\", absoluteFullHref);\n }\n setPending(true);\n try {\n await window.__VINEXT_RSC_NAVIGATE__(absoluteFullHref);\n } finally {\n if (mountedRef.current) setPending(false);\n }\n } else {\n // Pages Router: use the Router singleton\n try {\n const routerModule = await import(\"next/router\");\n // eslint-disable-next-line -- vinext's Router shim accepts (url, as, options)\n const Router = routerModule.default as any;\n if (replace) {\n await Router.replace(absoluteHref, undefined, { scroll });\n } else {\n await Router.push(absoluteHref, undefined, { scroll });\n }\n } catch {\n // Fallback to hard navigation if router fails\n if (replace) {\n window.history.replaceState({}, \"\", absoluteFullHref);\n } else {\n window.history.pushState({}, \"\", absoluteFullHref);\n }\n window.dispatchEvent(new PopStateEvent(\"popstate\"));\n }\n }\n\n if (scroll) {\n if (hash) {\n scrollToHash(hash);\n } else {\n window.scrollTo(0, 0);\n }\n }\n };\n\n // Remove props that shouldn't be on <a>\n const { passHref: _p, ...anchorProps } = restWithoutLocale;\n\n const linkStatusValue = React.useMemo(() => ({ pending }), [pending]);\n\n // Block dangerous URI schemes (javascript:, data:, vbscript:).\n // Render an inert <a> without href to prevent XSS while preserving\n // styling and attributes like className, id, aria-*.\n // This check is placed after all hooks to satisfy the Rules of Hooks.\n if (isDangerous) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(`<Link> blocked dangerous href: ${resolvedHref}`);\n }\n return <a {...anchorProps}>{children}</a>;\n }\n\n return (\n <LinkStatusContext.Provider value={linkStatusValue}>\n <a ref={setRefs} href={fullHref} onClick={handleClick} {...anchorProps}>\n {children}\n </a>\n </LinkStatusContext.Provider>\n );\n});\n\nexport default Link;\n"],"mappings":";;;;;;;;;;;;;;;;;AAsEA,MAAM,oBAAoB,cAAsC,EAAE,SAAS,OAAO,CAAC;;;;;;AAOnF,SAAgB,gBAAwC;AACtD,QAAO,WAAW,kBAAkB;;;AAItC,MAAM,aAAqB,QAAQ,IAAI,0BAA0B;AAEjE,SAAS,YAAY,MAAiC;AACpD,KAAI,OAAO,SAAS,SAAU,QAAO;CACrC,IAAI,MAAM,KAAK,YAA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SAAO,oBAAC,KAAD;GAAG,GAAI;GAAc;GAAa,CAAA;;AAG3C,QACE,oBAAC,kBAAkB,UAAnB;EAA4B,OAAO;YACjC,oBAAC,KAAD;GAAG,KAAK;GAAS,MAAM;GAAU,SAAS;GAAa,GAAI;GACxD;GACC,CAAA;EACuB,CAAA;EAE/B"}
|
|
1
|
+
{"version":3,"file":"link.js","names":[],"sources":["../../src/shims/link.tsx"],"sourcesContent":["\"use client\";\n\n/**\n * next/link shim\n *\n * Renders an <a> tag with client-side navigation support.\n * On click, prevents full page reload and triggers client-side\n * page swap via the router's navigation system.\n */\nimport React, {\n forwardRef,\n useRef,\n useEffect,\n useCallback,\n useContext,\n createContext,\n useState,\n type AnchorHTMLAttributes,\n type MouseEvent,\n} from \"react\";\n// Import shared RSC prefetch utilities from navigation shim (relative path\n// so this resolves both via the Vite plugin and in direct vitest imports)\nimport { toRscUrl, getPrefetchedUrls, storePrefetchResponse } from \"./navigation.js\";\nimport { notifyAppRouterTransitionStart } from \"../client/instrumentation-client-state.js\";\nimport { isDangerousScheme } from \"./url-safety.js\";\nimport {\n resolveRelativeHref,\n toBrowserNavigationHref,\n toSameOriginAppPath,\n withBasePath,\n} from \"./url-utils.js\";\nimport { appendSearchParamsToUrl, type UrlQuery, urlQueryToSearchParams } from \"../utils/query.js\";\nimport { addLocalePrefix, getDomainLocaleUrl, type DomainLocale } from \"../utils/domain-locale.js\";\nimport { getI18nContext } from \"./i18n-context.js\";\nimport type { VinextNextData } from \"../client/vinext-next-data.js\";\n\ninterface NavigateEvent {\n url: URL;\n /** Call to prevent the Link's default navigation (e.g. for View Transitions). */\n preventDefault(): void;\n /** Whether preventDefault() has been called. */\n defaultPrevented: boolean;\n}\n\ninterface LinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> {\n href: string | { pathname?: string; query?: UrlQuery };\n /** URL displayed in the browser (when href is a route pattern like /user/[id]) */\n as?: string;\n /** Replace the current history entry instead of pushing */\n replace?: boolean;\n /** Prefetch the page in the background (default: true, uses IntersectionObserver) */\n prefetch?: boolean;\n /** Whether to pass the href to the child element */\n passHref?: boolean;\n /** Scroll to top on navigation (default: true) */\n scroll?: boolean;\n /** Locale for i18n (used for locale-prefixed URLs) */\n locale?: string | false;\n /** Called before navigation happens (Next.js 16). Return value is ignored. */\n onNavigate?: (event: NavigateEvent) => void;\n children?: React.ReactNode;\n}\n\n// ---------------------------------------------------------------------------\n// useLinkStatus — reports the pending state of a parent <Link> navigation\n// ---------------------------------------------------------------------------\n\ninterface LinkStatusContextValue {\n pending: boolean;\n}\n\nconst LinkStatusContext = createContext<LinkStatusContextValue>({ pending: false });\n\n/**\n * useLinkStatus returns the pending state of the enclosing <Link>.\n * In Next.js, this is used to show loading indicators while a\n * prefetch-triggered navigation is in progress.\n */\nexport function useLinkStatus(): LinkStatusContextValue {\n return useContext(LinkStatusContext);\n}\n\n/** basePath from next.config.js, injected by the plugin at build time */\nconst __basePath: string = process.env.__NEXT_ROUTER_BASEPATH ?? \"\";\n\nfunction resolveHref(href: LinkProps[\"href\"]): string {\n if (typeof href === \"string\") return href;\n let url = href.pathname ?? \"/\";\n if (href.query) {\n const params = urlQueryToSearchParams(href.query);\n url = appendSearchParamsToUrl(url, params);\n }\n return url;\n}\n\n/**\n * Check if a href is only a hash change (same pathname, different/added hash).\n * Handles relative hashes like \"#foo\" and \"?query#foo\".\n */\nfunction isHashOnlyChange(href: string): boolean {\n if (href.startsWith(\"#\")) return true;\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/**\n * Scroll to a hash target element, or to the top if no hash.\n */\nfunction scrollToHash(hash: string): void {\n if (!hash || hash === \"#\") {\n window.scrollTo(0, 0);\n return;\n }\n const id = hash.slice(1); // Remove leading #\n const element = document.getElementById(id);\n if (element) {\n element.scrollIntoView({ behavior: \"auto\" });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Prefetching infrastructure\n// ---------------------------------------------------------------------------\n\n/**\n * Prefetch a URL for faster navigation.\n *\n * For App Router (RSC): fetches the .rsc payload in the background and\n * stores it in an in-memory cache for instant use during navigation.\n * For Pages Router: injects a <link rel=\"prefetch\"> for the page module.\n *\n * Uses `requestIdleCallback` (or `setTimeout` fallback) to avoid blocking\n * the main thread during initial page load.\n */\nfunction prefetchUrl(href: string): void {\n if (typeof window === \"undefined\") return;\n\n // Normalize same-origin absolute URLs to local paths before prefetching\n let prefetchHref = href;\n if (href.startsWith(\"http://\") || href.startsWith(\"https://\") || href.startsWith(\"//\")) {\n const localPath = toSameOriginAppPath(href, __basePath);\n if (localPath == null) return; // truly external — don't prefetch\n prefetchHref = localPath;\n }\n\n const fullHref = toBrowserNavigationHref(prefetchHref, window.location.href, __basePath);\n\n // Don't prefetch the same URL twice (keyed by rscUrl so the browser\n // entry can clear the key when a cache entry is consumed)\n const rscUrl = toRscUrl(fullHref);\n const prefetched = getPrefetchedUrls();\n if (prefetched.has(rscUrl)) return;\n prefetched.add(rscUrl);\n\n const schedule = (window as any).requestIdleCallback ?? ((fn: () => void) => setTimeout(fn, 100));\n\n schedule(() => {\n if (typeof window.__VINEXT_RSC_NAVIGATE__ === \"function\") {\n // App Router: prefetch the RSC payload and store in cache\n fetch(rscUrl, {\n headers: { Accept: \"text/x-component\" },\n credentials: \"include\",\n priority: \"low\" as any,\n // @ts-expect-error — purpose is a valid fetch option in some browsers\n purpose: \"prefetch\",\n })\n .then((response) => {\n if (response.ok) {\n storePrefetchResponse(rscUrl, response);\n } else {\n // Non-ok response: allow retry on next viewport intersection\n prefetched.delete(rscUrl);\n }\n })\n .catch(() => {\n // Network error: allow retry on next viewport intersection\n prefetched.delete(rscUrl);\n });\n } else if ((window.__NEXT_DATA__ as VinextNextData | undefined)?.__vinext?.pageModuleUrl) {\n // Pages Router: inject a prefetch link for the target page module\n // We can't easily resolve the target page's module URL from the Link,\n // so we create a <link rel=\"prefetch\"> for the HTML page which helps\n // the browser's preload scanner.\n const link = document.createElement(\"link\");\n link.rel = \"prefetch\";\n link.href = fullHref;\n link.as = \"document\";\n document.head.appendChild(link);\n }\n });\n}\n\n/**\n * Shared IntersectionObserver for viewport-based prefetching.\n * All Link elements use the same observer to minimize resource usage.\n */\nlet sharedObserver: IntersectionObserver | null = null;\nconst observerCallbacks = new WeakMap<Element, () => void>();\n\nfunction getSharedObserver(): IntersectionObserver | null {\n if (typeof window === \"undefined\" || typeof IntersectionObserver === \"undefined\") return null;\n if (sharedObserver) return sharedObserver;\n\n sharedObserver = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n const callback = observerCallbacks.get(entry.target);\n if (callback) {\n callback();\n // Unobserve after prefetching — only prefetch once\n sharedObserver?.unobserve(entry.target);\n observerCallbacks.delete(entry.target);\n }\n }\n }\n },\n {\n // Start prefetching when the link is within 250px of the viewport.\n // This gives the browser a head start before the user scrolls to it.\n rootMargin: \"250px\",\n },\n );\n\n return sharedObserver;\n}\n\nfunction getDefaultLocale(): string | undefined {\n if (typeof window !== \"undefined\") {\n return window.__VINEXT_DEFAULT_LOCALE__;\n }\n return getI18nContext()?.defaultLocale;\n}\n\nfunction getDomainLocales(): readonly DomainLocale[] | undefined {\n if (typeof window !== \"undefined\") {\n return (window.__NEXT_DATA__ as VinextNextData | undefined)?.domainLocales;\n }\n return getI18nContext()?.domainLocales;\n}\n\nfunction getCurrentHostname(): string | undefined {\n if (typeof window !== \"undefined\") return window.location.hostname;\n return getI18nContext()?.hostname;\n}\n\nfunction getDomainLocaleHref(href: string, locale: string): string | undefined {\n // Only cross-domain locale switches need a special absolute URL here.\n // Same-domain cases fall back to the standard locale-prefix logic below.\n return getDomainLocaleUrl(href, locale, {\n basePath: __basePath,\n currentHostname: getCurrentHostname(),\n domainItems: getDomainLocales(),\n });\n}\n\n/**\n * Apply locale prefix to a URL path based on the locale prop.\n * - locale=\"fr\" → prepend /fr (unless it already has a locale prefix)\n * - locale={false} → use the href as-is (no locale prefix, link to default)\n * - locale=undefined → use current locale (href as-is in most cases)\n */\nfunction applyLocaleToHref(href: string, locale: string | false | undefined): string {\n if (locale === false) {\n // Explicit false: no locale prefix\n return href;\n }\n\n if (locale === undefined) {\n // No locale prop: keep current behavior (href as-is)\n return href;\n }\n\n // Absolute and protocol-relative URLs must not be prefixed — locale\n // only applies to local paths.\n if (href.startsWith(\"http://\") || href.startsWith(\"https://\") || href.startsWith(\"//\")) {\n return href;\n }\n\n const domainLocaleHref = getDomainLocaleHref(href, locale);\n if (domainLocaleHref) {\n return domainLocaleHref;\n }\n\n return addLocalePrefix(href, locale, getDefaultLocale() ?? \"\");\n}\n\nconst Link = forwardRef<HTMLAnchorElement, LinkProps>(function Link(\n {\n href,\n as,\n replace = false,\n prefetch: prefetchProp,\n scroll = true,\n children,\n onClick,\n onNavigate,\n ...rest\n },\n forwardedRef,\n) {\n // Extract locale from rest props\n const { locale, ...restWithoutLocale } = rest as any;\n\n // If `as` is provided, use it as the actual URL (legacy Next.js pattern\n // where href is a route pattern like \"/user/[id]\" and as is \"/user/1\")\n const resolvedHref = as ?? resolveHref(href);\n\n const isDangerous = typeof resolvedHref === \"string\" && isDangerousScheme(resolvedHref);\n\n // Apply locale prefix if specified (safe even for dangerous hrefs since we\n // won't use the result when isDangerous is true)\n const localizedHref = applyLocaleToHref(isDangerous ? \"/\" : resolvedHref, locale);\n // Full href with basePath for browser URLs and fetches\n const fullHref = withBasePath(localizedHref, __basePath);\n\n // Track pending state for useLinkStatus()\n const [pending, setPending] = useState(false);\n const mountedRef = useRef(true);\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Prefetching: observe the element when it enters the viewport.\n // prefetch={false} disables, prefetch={true} or undefined/null (default) enables.\n const internalRef = useRef<HTMLAnchorElement | null>(null);\n const shouldPrefetch = prefetchProp !== false && !isDangerous;\n\n const setRefs = useCallback(\n (node: HTMLAnchorElement | null) => {\n internalRef.current = node;\n if (typeof forwardedRef === \"function\") forwardedRef(node);\n else if (forwardedRef)\n (forwardedRef as React.MutableRefObject<HTMLAnchorElement | null>).current = node;\n },\n [forwardedRef],\n );\n\n useEffect(() => {\n if (!shouldPrefetch || typeof window === \"undefined\") return;\n const node = internalRef.current;\n if (!node) return;\n\n // Normalize same-origin absolute URLs; skip truly external ones\n let hrefToPrefetch = localizedHref;\n if (\n localizedHref.startsWith(\"http://\") ||\n localizedHref.startsWith(\"https://\") ||\n localizedHref.startsWith(\"//\")\n ) {\n const localPath = toSameOriginAppPath(localizedHref, __basePath);\n if (localPath == null) return; // truly external\n hrefToPrefetch = localPath;\n }\n\n const observer = getSharedObserver();\n if (!observer) return;\n\n observerCallbacks.set(node, () => prefetchUrl(hrefToPrefetch));\n observer.observe(node);\n\n return () => {\n observer.unobserve(node);\n observerCallbacks.delete(node);\n };\n }, [shouldPrefetch, localizedHref]);\n\n const handleClick = async (e: MouseEvent<HTMLAnchorElement>) => {\n if (onClick) onClick(e);\n if (e.defaultPrevented) return;\n\n // Only intercept left clicks without modifiers (standard link behavior)\n if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {\n return;\n }\n\n // Don't intercept links with target (e.g. target=\"_blank\")\n if (e.currentTarget.target && e.currentTarget.target !== \"_self\") {\n return;\n }\n\n // External links: let the browser handle it.\n // Same-origin absolute URLs (e.g. http://localhost:3000/about) are\n // normalized to local paths so they get client-side navigation.\n let navigateHref = localizedHref;\n if (\n resolvedHref.startsWith(\"http://\") ||\n resolvedHref.startsWith(\"https://\") ||\n resolvedHref.startsWith(\"//\")\n ) {\n const localPath = toSameOriginAppPath(resolvedHref, __basePath);\n if (localPath == null) return; // truly external\n navigateHref = localPath;\n }\n\n e.preventDefault();\n\n // Resolve relative hrefs (#hash, ?query) against the current URL once so\n // onNavigate and the actual navigation target stay in sync.\n const absoluteHref = resolveRelativeHref(navigateHref, window.location.href, __basePath);\n const absoluteFullHref = toBrowserNavigationHref(\n navigateHref,\n window.location.href,\n __basePath,\n );\n\n // Call onNavigate callback if provided (Next.js 16 View Transitions support)\n if (onNavigate) {\n try {\n const navUrl = new URL(absoluteFullHref, window.location.origin);\n let prevented = false;\n const navEvent: NavigateEvent = {\n url: navUrl,\n preventDefault() {\n prevented = true;\n },\n get defaultPrevented() {\n return prevented;\n },\n };\n onNavigate(navEvent);\n // If the callback called preventDefault(), skip Link's default navigation.\n // The callback is responsible for its own navigation (e.g. via View Transitions API).\n if (navEvent.defaultPrevented) {\n return;\n }\n } catch {\n // Ignore URL parsing errors for relative/hash hrefs\n }\n }\n\n // Save scroll position for back/forward restoration\n if (!replace) {\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 // Hash-only change: update URL and scroll to target, skip RSC fetch\n if (typeof window !== \"undefined\" && isHashOnlyChange(absoluteFullHref)) {\n const hash = absoluteFullHref.includes(\"#\")\n ? absoluteFullHref.slice(absoluteFullHref.indexOf(\"#\"))\n : \"\";\n if (replace) {\n window.history.replaceState(null, \"\", absoluteFullHref);\n } else {\n window.history.pushState(null, \"\", absoluteFullHref);\n }\n if (scroll) {\n scrollToHash(hash);\n }\n return;\n }\n\n // Extract hash for scroll-after-navigation\n const hashIdx = absoluteFullHref.indexOf(\"#\");\n const hash = hashIdx !== -1 ? absoluteFullHref.slice(hashIdx) : \"\";\n\n // Try RSC navigation first (App Router), then Pages Router\n if (typeof window.__VINEXT_RSC_NAVIGATE__ === \"function\") {\n // App Router: push/replace history state, then fetch RSC stream.\n // Await the RSC navigate so scroll-to-top happens after the new\n // content is committed to the DOM (prevents flash of old page at top).\n notifyAppRouterTransitionStart(absoluteFullHref, replace ? \"replace\" : \"push\");\n if (replace) {\n window.history.replaceState(null, \"\", absoluteFullHref);\n } else {\n window.history.pushState(null, \"\", absoluteFullHref);\n }\n setPending(true);\n try {\n await window.__VINEXT_RSC_NAVIGATE__(absoluteFullHref);\n } finally {\n if (mountedRef.current) setPending(false);\n }\n } else {\n // Next.js only consumes onRouterTransitionStart in the App Router.\n // Pages Router still executes instrumentation-client side effects\n // during startup, but it does not invoke the named export on navigation.\n // Pages Router: use the Router singleton\n try {\n const routerModule = await import(\"next/router\");\n // eslint-disable-next-line -- vinext's Router shim accepts (url, as, options)\n const Router = routerModule.default as any;\n if (replace) {\n await Router.replace(absoluteHref, undefined, { scroll });\n } else {\n await Router.push(absoluteHref, undefined, { scroll });\n }\n } catch {\n // Fallback to hard navigation if router fails\n if (replace) {\n window.history.replaceState({}, \"\", absoluteFullHref);\n } else {\n window.history.pushState({}, \"\", absoluteFullHref);\n }\n window.dispatchEvent(new PopStateEvent(\"popstate\"));\n }\n }\n\n if (scroll) {\n if (hash) {\n scrollToHash(hash);\n } else {\n window.scrollTo(0, 0);\n }\n }\n };\n\n // Remove props that shouldn't be on <a>\n const { passHref: _p, ...anchorProps } = restWithoutLocale;\n\n const linkStatusValue = React.useMemo(() => ({ pending }), [pending]);\n\n // Block dangerous URI schemes (javascript:, data:, vbscript:).\n // Render an inert <a> without href to prevent XSS while preserving\n // styling and attributes like className, id, aria-*.\n // This check is placed after all hooks to satisfy the Rules of Hooks.\n if (isDangerous) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(`<Link> blocked dangerous href: ${resolvedHref}`);\n }\n return <a {...anchorProps}>{children}</a>;\n }\n\n return (\n <LinkStatusContext.Provider value={linkStatusValue}>\n <a ref={setRefs} href={fullHref} onClick={handleClick} {...anchorProps}>\n {children}\n </a>\n </LinkStatusContext.Provider>\n );\n});\n\nexport default Link;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuEA,MAAM,oBAAoB,cAAsC,EAAE,SAAS,OAAO,CAAC;;;;;;AAOnF,SAAgB,gBAAwC;AACtD,QAAO,WAAW,kBAAkB;;;AAItC,MAAM,aAAqB,QAAQ,IAAI,0BAA0B;AAEjE,SAAS,YAAY,MAAiC;AACpD,KAAI,OAAO,SAAS,SAAU,QAAO;CAC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MAAI,QAAQ,IAAI,aAAa,aAC3B,SAAQ,KAAK,kCAAkC,eAAe;AAEhE,SAAO,oBAAC,KAAD;GAAG,GAAI;GAAc;GAAa,CAAA;;AAG3C,QACE,oBAAC,kBAAkB,UAAnB;EAA4B,OAAO;YACjC,oBAAC,KAAD;GAAG,KAAK;GAAS,MAAM;GAAU,SAAS;GAAa,GAAI;GACxD;GACC,CAAA;EACuB,CAAA;EAE/B"}
|
package/dist/shims/navigation.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { stripBasePath } from "../utils/base-path.js";
|
|
2
2
|
import { toBrowserNavigationHref, toSameOriginAppPath } from "./url-utils.js";
|
|
3
|
+
import { notifyAppRouterTransitionStart } from "../client/instrumentation-client-state.js";
|
|
3
4
|
import { ReadonlyURLSearchParams } from "./readonly-url-search-params.js";
|
|
4
5
|
import * as React$1 from "react";
|
|
5
6
|
//#region src/shims/navigation.ts
|
|
@@ -338,6 +339,7 @@ async function navigateImpl(href, mode, scroll) {
|
|
|
338
339
|
normalizedHref = localPath;
|
|
339
340
|
}
|
|
340
341
|
const fullHref = toBrowserNavigationHref(normalizedHref, window.location.href, __basePath);
|
|
342
|
+
notifyAppRouterTransitionStart(fullHref, mode);
|
|
341
343
|
if (mode === "push") saveScrollPosition();
|
|
342
344
|
if (isHashOnlyChange(fullHref)) {
|
|
343
345
|
const hash = fullHref.includes("#") ? fullHref.slice(fullHref.indexOf("#")) : "";
|