From 0aa15fdfe21d58004d263af0d24702eaecd60a29 Mon Sep 17 00:00:00 2001 From: nextjs-bot Date: Wed, 18 Mar 2026 18:55:15 +0000 Subject: [PATCH 01/76] setup release branch --- .github/workflows/build_and_deploy.yml | 4 ++-- .github/workflows/build_and_test.yml | 25 +++++++------------------ lerna.json | 3 ++- 3 files changed, 11 insertions(+), 21 deletions(-) diff --git a/.github/workflows/build_and_deploy.yml b/.github/workflows/build_and_deploy.yml index f02d14d90e9e..854478439d8c 100644 --- a/.github/workflows/build_and_deploy.yml +++ b/.github/workflows/build_and_deploy.yml @@ -59,7 +59,7 @@ jobs: if [[ $(node ./scripts/check-is-release.js 2> /dev/null || :) == v* ]]; then echo "value=production" >> $GITHUB_OUTPUT - elif [ '${{ github.ref }}' == 'refs/heads/canary' ] + elif [ '${{ github.ref }}' == 'refs/heads/next-16-2' ] then echo "value=staging" >> $GITHUB_OUTPUT elif [ '${{ github.event_name }}' == 'workflow_dispatch' ] @@ -618,7 +618,7 @@ jobs: publish-turbopack-npm-packages: # Matches the commit message written by turbopack/xtask/src/publish.rs:377 - if: "${{(github.ref == 'refs/heads/canary') && startsWith(github.event.head_commit.message, 'chore: release turbopack npm packages')}}" + if: "${{(github.ref == 'refs/heads/next-16-2') && startsWith(github.event.head_commit.message, 'chore: release turbopack npm packages')}}" runs-on: ubuntu-latest permissions: contents: write diff --git a/.github/workflows/build_and_test.yml b/.github/workflows/build_and_test.yml index d35202b7b315..0dfe1aeaf4d0 100644 --- a/.github/workflows/build_and_test.yml +++ b/.github/workflows/build_and_test.yml @@ -2,7 +2,7 @@ name: build-and-test on: push: - branches: ['canary'] + branches: ['next-16-2'] pull_request: types: [opened, synchronize] @@ -720,7 +720,7 @@ jobs: name: Test new and changed tests for flakes (dev) needs: ['optimize-ci', 'changes', 'build-native', 'build-next'] # test-new-tests-if - if: ${{ needs.optimize-ci.outputs.skip == 'false' && needs.changes.outputs.docs-only == 'false' }} + if: false # test-new-tests-end-if strategy: @@ -745,7 +745,7 @@ jobs: name: Test new and changed tests for flakes (prod) needs: ['optimize-ci', 'changes', 'build-native', 'build-next'] # test-new-tests-if - if: ${{ needs.optimize-ci.outputs.skip == 'false' && needs.changes.outputs.docs-only == 'false' }} + if: false # test-new-tests-end-if strategy: @@ -767,10 +767,9 @@ jobs: test-new-tests-deploy: name: Test new and changed tests when deployed - needs: - ['optimize-ci', 'test-prod', 'test-new-tests-dev', 'test-new-tests-start'] + needs: ['optimize-ci', 'test-prod', 'test-new-tests-start'] # test-new-tests-if - if: ${{ needs.optimize-ci.outputs.skip == 'false' }} + if: false # test-new-tests-end-if strategy: @@ -794,15 +793,9 @@ jobs: test-new-tests-deploy-cache-components: name: Test new and changed tests when deployed (cache components) - needs: - [ - 'optimize-ci', - 'test-cache-components-prod', - 'test-new-tests-dev', - 'test-new-tests-start', - ] + needs: ['optimize-ci', 'test-cache-components-prod'] # test-new-tests-if - if: ${{ needs.optimize-ci.outputs.skip == 'false' }} + if: false # test-new-tests-end-if strategy: @@ -1187,10 +1180,6 @@ jobs: 'test-next-swc-wasm', 'test-turbopack-dev', 'test-turbopack-integration', - 'test-new-tests-dev', - 'test-new-tests-start', - 'test-new-tests-deploy', - 'test-new-tests-deploy-cache-components', 'test-turbopack-production', 'test-unit-windows', 'test-dev-windows', diff --git a/lerna.json b/lerna.json index fd4a1b764cee..622a5a573f8b 100644 --- a/lerna.json +++ b/lerna.json @@ -10,7 +10,8 @@ "publish": { "npmClient": "npm", "allowBranch": [ - "canary" + "canary", + "next-16-2" ], "registry": "https://registry.npmjs.org/" } From e6b101ae717ba801af80f72bc6d974427edc9684 Mon Sep 17 00:00:00 2001 From: Luke Sandberg Date: Thu, 19 Mar 2026 13:58:13 -0700 Subject: [PATCH 02/76] [turbopack] Respect `{eval:true}` in worker_threads constructors (#91666) ### What? Fixed Turbopack incorrectly trying to resolve inline JavaScript code as module references when `new Worker()` is called with `{ eval: true }` option. Now we skip creating a reference when `eval:true`, and report warnings if we cannot tell what the value is ### Why? Libraries like jsPDF create Worker threads by passing inline JavaScript code as the first argument along with `{ eval: true }` as the second argument. Turbopack was incorrectly treating this inline code as a file path and attempting to resolve it as a module reference, causing build failures. ### How? Added logic to detect when the `eval: true` option is passed to the Worker constructor. When this option is present, Turbopack now skips creating a worker reference since the first argument contains executable code rather than a file path. Added comprehensive test coverage using jsPDF to verify the fix works correctly. Fixes #91642 --- .../app/api/jspdf-test/route.ts | 20 +++++++ .../node-worker-threads.test.ts | 12 +++++ .../turbopack-core/src/resolve/parse.rs | 7 ++- .../src/references/mod.rs | 54 ++++++++++++++++++- 4 files changed, 91 insertions(+), 2 deletions(-) create mode 100644 test/e2e/app-dir/node-worker-threads/app/api/jspdf-test/route.ts diff --git a/test/e2e/app-dir/node-worker-threads/app/api/jspdf-test/route.ts b/test/e2e/app-dir/node-worker-threads/app/api/jspdf-test/route.ts new file mode 100644 index 000000000000..cb2dd92be48b --- /dev/null +++ b/test/e2e/app-dir/node-worker-threads/app/api/jspdf-test/route.ts @@ -0,0 +1,20 @@ +import { NextResponse } from 'next/server' + +export async function GET() { + try { + const { jsPDF } = await import('jspdf') + const doc = new jsPDF() + doc.text('Hello world!', 10, 10) + const pdfData = doc.output('arraybuffer') + + return NextResponse.json({ + success: true, + size: pdfData.byteLength, + }) + } catch (error) { + return NextResponse.json( + { success: false, error: String(error) }, + { status: 500 } + ) + } +} diff --git a/test/e2e/app-dir/node-worker-threads/node-worker-threads.test.ts b/test/e2e/app-dir/node-worker-threads/node-worker-threads.test.ts index 574b814196f0..8f0d660b9c92 100644 --- a/test/e2e/app-dir/node-worker-threads/node-worker-threads.test.ts +++ b/test/e2e/app-dir/node-worker-threads/node-worker-threads.test.ts @@ -6,6 +6,7 @@ describe('node-worker-threads', () => { skipDeployment: true, dependencies: { pino: '9.6.0', + jspdf: '4.2.1', }, }) @@ -58,6 +59,17 @@ describe('node-worker-threads', () => { expect(data.turbopackKeys).toEqual([]) }) + it('should handle jsPDF which uses Worker with eval: true (issue #91642)', async () => { + // jsPDF internally creates Worker threads with { eval: true }, passing + // inline JS code instead of a file path. Turbopack should not try to + // resolve the first argument as a module reference in this case. + const res = await next.fetch('/api/jspdf-test') + const data = await res.json() + expect(res.status).toBe(200) + expect(data.success).toBe(true) + expect(data.size).toBeGreaterThan(0) + }) + it('should handle PNG file import in worker', async () => { // Test that static assets (like PNG images) can be imported and used in workers // The server worker returns the PNG URL, then we fetch it from the client diff --git a/turbopack/crates/turbopack-core/src/resolve/parse.rs b/turbopack/crates/turbopack-core/src/resolve/parse.rs index 15f58172c845..e8af9e865d0c 100644 --- a/turbopack/crates/turbopack-core/src/resolve/parse.rs +++ b/turbopack/crates/turbopack-core/src/resolve/parse.rs @@ -293,7 +293,12 @@ impl Request { Request::Unknown { path } => { path.push(item); } - Request::DataUri { .. } | Request::Uri { .. } | Request::Dynamic => { + Request::DataUri { .. } | Request::Uri { .. } => { + return Request::Dynamic; + } + Request::Dynamic => { + // A dynamic prefix is essentially impossible to resolve so we don't try. We + // would have to scan the entire repo for suffix matches. return Request::Dynamic; } Request::Alternatives { .. } => unreachable!(), diff --git a/turbopack/crates/turbopack-ecmascript/src/references/mod.rs b/turbopack/crates/turbopack-ecmascript/src/references/mod.rs index 6da5f4f39a2d..a6b1c3e3e2b8 100644 --- a/turbopack/crates/turbopack-ecmascript/src/references/mod.rs +++ b/turbopack/crates/turbopack-ecmascript/src/references/mod.rs @@ -2167,6 +2167,58 @@ where WellKnownFunctionKind::NodeWorkerConstructor => { let args = linked_args().await?; if !args.is_empty() { + // When `{ eval: true }` is passed as the second argument, + // the first argument is inline JS code, not a file path. + // Skip creating a worker reference in that case. + let mut dynamic_warning: Option<&str> = None; + if let Some(opts) = args.get(1) { + match opts { + JsValue::Object { parts, .. } => { + let eval_value = parts.iter().find_map(|part| match part { + ObjectPart::KeyValue( + JsValue::Constant(JsConstantValue::Str(key)), + value, + ) if key.as_str() == "eval" => Some(value), + _ => None, + }); + if let Some(eval_value) = eval_value { + match eval_value { + // eval: true — first arg is code, not a + // path + JsValue::Constant(JsConstantValue::True) => { + return Ok(()); + } + // eval: false — first arg is a path, + // continue normally + JsValue::Constant(JsConstantValue::False) => {} + // eval is set but not a literal boolean + _ => { + dynamic_warning = Some("has a dynamic `eval` option"); + } + } + } + } + // Options argument is not a static object literal — + // we can't inspect it for `eval: true` + _ => { + dynamic_warning = Some("has a dynamic options argument"); + } + } + } + if let Some(warning) = dynamic_warning { + let (args, hints) = explain_args(args); + handler.span_warn_with_code( + span, + &format!("new Worker({args}) {warning}{hints}"), + DiagnosticId::Lint( + errors::failed_to_analyze::ecmascript::NEW_WORKER.to_string(), + ), + ); + if ignore_dynamic_requests { + return Ok(()); + } + } + let pat = js_value_to_pattern(&args[0]); if !pat.has_constant_parts() { let (args, hints) = explain_args(args); @@ -2208,7 +2260,7 @@ where span, &format!("new Worker({args}) is not statically analyze-able{hints}",), DiagnosticId::Error( - errors::failed_to_analyze::ecmascript::FS_METHOD.to_string(), + errors::failed_to_analyze::ecmascript::NEW_WORKER.to_string(), ), ); // Ignore (e.g. dynamic parameter or string literal) From 6cb97d6d759307806d23e629d5081e638de29b6a Mon Sep 17 00:00:00 2001 From: Niklas Mischkulnig <4586894+mischnic@users.noreply.github.com> Date: Fri, 20 Mar 2026 16:30:32 +0100 Subject: [PATCH 03/76] Turbopack: lazy require metadata and handle TLA (#91705) A regression from #88487 1. Make metadata import lazy with `() => require()`, just like for the layout segments 2. Properly await the return value to better handle TLA modules This align with Webpack which does this: Bildschirmfoto 2026-03-20 um 11 58 00 Closes PACK-6927 Closes #91700 Closes https://github.com/vercel/next.js/issues/91676 --- crates/next-core/src/app_page_loader_tree.rs | 109 ++++++++++-------- .../next/src/lib/metadata/resolve-metadata.ts | 5 +- .../app/blog/[slug]/opengraph-image.tsx | 22 ++++ .../app/blog/[slug]/page.tsx | 14 +++ .../app/data.ts | 9 ++ .../app/layout.tsx | 8 ++ .../index.test.ts | 22 ++++ .../next.config.js | 2 + 8 files changed, 141 insertions(+), 50 deletions(-) create mode 100644 test/e2e/app-dir/metadata-dynamic-routes-async-deps/app/blog/[slug]/opengraph-image.tsx create mode 100644 test/e2e/app-dir/metadata-dynamic-routes-async-deps/app/blog/[slug]/page.tsx create mode 100644 test/e2e/app-dir/metadata-dynamic-routes-async-deps/app/data.ts create mode 100644 test/e2e/app-dir/metadata-dynamic-routes-async-deps/app/layout.tsx create mode 100644 test/e2e/app-dir/metadata-dynamic-routes-async-deps/index.test.ts create mode 100644 test/e2e/app-dir/metadata-dynamic-routes-async-deps/next.config.js diff --git a/crates/next-core/src/app_page_loader_tree.rs b/crates/next-core/src/app_page_loader_tree.rs index 77292e4ac9bd..b7781bf22605 100644 --- a/crates/next-core/src/app_page_loader_tree.rs +++ b/crates/next-core/src/app_page_loader_tree.rs @@ -189,7 +189,7 @@ impl AppPageLoaderTreeBuilder { // when mixing ESM imports and requires). self.base.imports.push( format!( - "const {identifier} = require(/*turbopackChunkingType: \ + "const {identifier} = () => require(/*turbopackChunkingType: \ shared*/\"{inner_module_id}\");" ) .into(), @@ -208,7 +208,10 @@ impl AppPageLoaderTreeBuilder { .insert(inner_module_id.into(), module); let s = " "; - writeln!(self.loader_tree_code, "{s}{identifier}.default,")?; + writeln!( + self.loader_tree_code, + "{s}async (props) => interopDefault(await {identifier}())(props)," + )?; } } Ok(()) @@ -240,7 +243,7 @@ impl AppPageLoaderTreeBuilder { // requires). self.base.imports.push( format!( - "const {identifier} = require(/*turbopackChunkingType: \ + "const {identifier} = () => require(/*turbopackChunkingType: \ shared*/\"{inner_module_id}\");" ) .into(), @@ -255,8 +258,51 @@ impl AppPageLoaderTreeBuilder { .inner_assets .insert(inner_module_id.into(), module); + let alt = if let Some(alt_path) = alt_path { + let identifier = magic_identifier::mangle(&format!("{name} alt text #{i}")); + let inner_module_id = format!("METADATA_ALT_{i}"); + + // This should use the same importing mechanism as create_module_tuple_code, so that the + // relative order of items is retained (which isn't the case when mixing ESM imports and + // requires). + self.base.imports.push( + format!( + "const {identifier} = () => require(/*turbopackChunkingType: \ + shared*/\"{inner_module_id}\");" + ) + .into(), + ); + + let module = self + .base + .process_source(Vc::upcast(TextContentFileSource::new(Vc::upcast( + FileSource::new(alt_path), + )))) + .to_resolved() + .await?; + + self.base + .inner_assets + .insert(inner_module_id.into(), module); + + Some(identifier) + } else { + None + }; + let s = " "; - writeln!(self.loader_tree_code, "{s}(async (props) => [{{")?; + writeln!(self.loader_tree_code, "{s}(async (props) => {{")?; + writeln!( + self.loader_tree_code, + "{s} const mod = interopDefault(await {identifier}());" + )?; + if let Some(alt) = &alt { + writeln!( + self.loader_tree_code, + "{s} const alt = interopDefault(await {alt}());" + )?; + } + writeln!(self.loader_tree_code, "{s} return [{{")?; let pathname_prefix = if let Some(base_path) = &self.base_path { format!("{base_path}/{app_page}") } else { @@ -265,68 +311,37 @@ impl AppPageLoaderTreeBuilder { let metadata_route = &*get_metadata_route_name(item.clone().into()).await?; writeln!( self.loader_tree_code, - "{s} url: fillMetadataSegment({}, await props.params, {}, true) + \ - `?${{{identifier}.default.src.split(\"/\").splice(-1)[0]}}`,", + "{s} url: fillMetadataSegment({}, await props.params, {}, true) + \ + `?${{mod.src.split(\"/\").splice(-1)[0]}}`,", StringifyJs(&pathname_prefix), StringifyJs(metadata_route), )?; let numeric_sizes = name == "twitter" || name == "openGraph"; if numeric_sizes { - writeln!( - self.loader_tree_code, - "{s} width: {identifier}.default.width," - )?; - writeln!( - self.loader_tree_code, - "{s} height: {identifier}.default.height," - )?; + writeln!(self.loader_tree_code, "{s} width: mod.width,")?; + writeln!(self.loader_tree_code, "{s} height: mod.height,")?; } else { // For SVGs, skip sizes and use "any" to let it scale automatically based on viewport, // For the images doesn't provide the size properly, use "any" as well. // If the size is presented, use the actual size for the image. let sizes = if path.has_extension(".svg") { - "any".to_string() + "any" } else { - format!("${{{identifier}.default.width}}x${{{identifier}.default.height}}") + "${mod.width}x${mod.height}" }; - writeln!(self.loader_tree_code, "{s} sizes: `{sizes}`,")?; + writeln!(self.loader_tree_code, "{s} sizes: `{sizes}`,")?; } let content_type = get_content_type(path).await?; - writeln!(self.loader_tree_code, "{s} type: `{content_type}`,")?; - - if let Some(alt_path) = alt_path { - let identifier = magic_identifier::mangle(&format!("{name} alt text #{i}")); - let inner_module_id = format!("METADATA_ALT_{i}"); - - // This should use the same importing mechanism as create_module_tuple_code, so that the - // relative order of items is retained (which isn't the case when mixing ESM imports and - // requires). - self.base.imports.push( - format!( - "const {identifier} = require(/*turbopackChunkingType: \ - shared*/\"{inner_module_id}\");" - ) - .into(), - ); - - let module = self - .base - .process_source(Vc::upcast(TextContentFileSource::new(Vc::upcast( - FileSource::new(alt_path), - )))) - .to_resolved() - .await?; - - self.base - .inner_assets - .insert(inner_module_id.into(), module); + writeln!(self.loader_tree_code, "{s} type: `{content_type}`,")?; - writeln!(self.loader_tree_code, "{s} alt: {identifier}.default,")?; + if alt.is_some() { + writeln!(self.loader_tree_code, "{s} alt,")?; } - writeln!(self.loader_tree_code, "{s}}}]),")?; + writeln!(self.loader_tree_code, "{s} }}];")?; + writeln!(self.loader_tree_code, "{s}}}),")?; Ok(()) } diff --git a/packages/next/src/lib/metadata/resolve-metadata.ts b/packages/next/src/lib/metadata/resolve-metadata.ts index bac8bb9e146b..1ae86da5d768 100644 --- a/packages/next/src/lib/metadata/resolve-metadata.ts +++ b/packages/next/src/lib/metadata/resolve-metadata.ts @@ -41,7 +41,6 @@ import { getComponentTypeModule, getLayoutOrPageModule, } from '../../server/lib/app-dir-module' -import { interopDefault } from '../interop-default' import { resolveAlternates, resolveAppleWebApp, @@ -572,11 +571,11 @@ async function collectStaticImagesFiles( const iconPromises = metadata[type as 'icon' | 'apple'].map( async (imageModule: (p: any) => Promise) => - await interopDefault(imageModule)(props) + await imageModule(props) ) return iconPromises?.length > 0 - ? (await Promise.all(iconPromises))?.flat() + ? (await Promise.all(iconPromises)).flat() : undefined } diff --git a/test/e2e/app-dir/metadata-dynamic-routes-async-deps/app/blog/[slug]/opengraph-image.tsx b/test/e2e/app-dir/metadata-dynamic-routes-async-deps/app/blog/[slug]/opengraph-image.tsx new file mode 100644 index 000000000000..c9132932508d --- /dev/null +++ b/test/e2e/app-dir/metadata-dynamic-routes-async-deps/app/blog/[slug]/opengraph-image.tsx @@ -0,0 +1,22 @@ +import { ImageResponse } from 'next/og' +import { getAllSlugs } from '../../data' + +export default function og() { + return new ImageResponse( + ( +
+ Posts: {getAllSlugs().join(', ')} +
+ ) + ) +} diff --git a/test/e2e/app-dir/metadata-dynamic-routes-async-deps/app/blog/[slug]/page.tsx b/test/e2e/app-dir/metadata-dynamic-routes-async-deps/app/blog/[slug]/page.tsx new file mode 100644 index 000000000000..b00f1ce0a289 --- /dev/null +++ b/test/e2e/app-dir/metadata-dynamic-routes-async-deps/app/blog/[slug]/page.tsx @@ -0,0 +1,14 @@ +import { getAllSlugs } from '../../data' + +export function generateStaticParams() { + return getAllSlugs().map((slug) => ({ slug })) +} + +export default async function Page({ + params, +}: { + params: Promise<{ slug: string }> +}) { + const { slug } = await params + return

Post: {slug}

+} diff --git a/test/e2e/app-dir/metadata-dynamic-routes-async-deps/app/data.ts b/test/e2e/app-dir/metadata-dynamic-routes-async-deps/app/data.ts new file mode 100644 index 000000000000..8226c7adf635 --- /dev/null +++ b/test/e2e/app-dir/metadata-dynamic-routes-async-deps/app/data.ts @@ -0,0 +1,9 @@ +// Async module: top-level await makes this an async module, +// which causes any transitive importer to also become async. +const data = await Promise.resolve({ + slugs: ['hello-world', 'another-post'], +}) + +export function getAllSlugs(): string[] { + return data.slugs +} diff --git a/test/e2e/app-dir/metadata-dynamic-routes-async-deps/app/layout.tsx b/test/e2e/app-dir/metadata-dynamic-routes-async-deps/app/layout.tsx new file mode 100644 index 000000000000..762515029332 --- /dev/null +++ b/test/e2e/app-dir/metadata-dynamic-routes-async-deps/app/layout.tsx @@ -0,0 +1,8 @@ +export default function Layout({ children }) { + return ( + + + {children} + + ) +} diff --git a/test/e2e/app-dir/metadata-dynamic-routes-async-deps/index.test.ts b/test/e2e/app-dir/metadata-dynamic-routes-async-deps/index.test.ts new file mode 100644 index 000000000000..69dce22f6e94 --- /dev/null +++ b/test/e2e/app-dir/metadata-dynamic-routes-async-deps/index.test.ts @@ -0,0 +1,22 @@ +import { nextTestSetup } from 'e2e-utils' + +describe('app dir - metadata dynamic routes with async deps', () => { + const { next } = nextTestSetup({ + files: __dirname, + dependencies: { + '@vercel/og': 'latest', + }, + }) + + it('should render page with og:image meta tag when opengraph-image has async dependencies', async () => { + const $ = await next.render$('/blog/hello-world') + const ogImageUrl = $('meta[property="og:image"]').attr('content') + expect(ogImageUrl).toContain('/blog/hello-world/opengraph-image') + }) + + it('should serve the opengraph-image route as a valid image', async () => { + const res = await next.fetch('/blog/hello-world/opengraph-image') + expect(res.status).toBe(200) + expect(res.headers.get('content-type')).toBe('image/png') + }) +}) diff --git a/test/e2e/app-dir/metadata-dynamic-routes-async-deps/next.config.js b/test/e2e/app-dir/metadata-dynamic-routes-async-deps/next.config.js new file mode 100644 index 000000000000..5a877d2dbfab --- /dev/null +++ b/test/e2e/app-dir/metadata-dynamic-routes-async-deps/next.config.js @@ -0,0 +1,2 @@ +/** @type {import('next').NextConfig} */ +module.exports = {} From d6195eca8cf1f89a288ccc2f8c957f66f50c8ca2 Mon Sep 17 00:00:00 2001 From: Tobias Koppers Date: Fri, 20 Mar 2026 13:00:43 +0100 Subject: [PATCH 04/76] Fix layout segment optimization: move app-page imports to server-utility transition (#91701) ## Summary - Add `'turbopack-transition': 'next-server-utility'` to all server-side imports in the `app-page.ts` template so they are properly placed in the server utility layer, rather than relying on `SharedMerged` chunk groups to handle them - Remove the now-unnecessary `next-server-utility` transition from `fillMetadataSegment` import in `app_page_loader_tree.rs` - Add `SharedMultiple` chunk group variant to support multiple shared entries without a merge tag - This avoid passing the `parent` into `SharedMerged`, which did break the layout segment optimization. - Refactor `app_module_graphs` to combine `client_shared_entries` + `has_layout_segments` into a single `Option` parameter, simplifying the API and removing the dead code path for non-page endpoints ## Test plan - [ ] Verify dev and production builds work with app pages that have layout segments - [ ] Verify route handlers still build correctly (no client runtime entries passed) - [ ] Run existing app-dir e2e tests --- crates/next-api/src/app.rs | 63 +++++++--------- crates/next-core/src/app_page_loader_tree.rs | 3 +- packages/next/src/build/templates/app-page.ts | 73 +++++++++++-------- .../src/module_graph/chunk_group_info.rs | 25 +++++++ 4 files changed, 96 insertions(+), 68 deletions(-) diff --git a/crates/next-api/src/app.rs b/crates/next-api/src/app.rs index c539f4e37aba..b2f918fbda73 100644 --- a/crates/next-api/src/app.rs +++ b/crates/next-api/src/app.rs @@ -874,8 +874,7 @@ impl AppProject { &self, endpoint: Vc, rsc_entry: ResolvedVc>, - client_shared_entries: Vc, - has_layout_segments: bool, + client_shared_entries_when_has_layout_segments: Option>, ) -> Result> { if *self.project.per_page_module_graph().await? { let next_mode = self.project.next_mode(); @@ -883,43 +882,47 @@ impl AppProject { let should_trace = next_mode_ref.is_production(); let should_read_binding_usage = next_mode_ref.is_production(); - let client_shared_entries = client_shared_entries - .await? - .into_iter() - .map(|m| ResolvedVc::upcast(*m)) - .collect(); // Implements layout segment optimization to compute a graph "chain" for each layout // segment async move { let rsc_entry_chunk_group = ChunkGroupEntry::Entry(vec![rsc_entry]); let mut graphs = vec![]; - let mut visited_modules = if has_layout_segments { + let mut visited_modules = VisitedModules::empty(); + + if let Some(client_shared_entries) = client_shared_entries_when_has_layout_segments + { let ServerEntries { - server_utils, server_component_entries, + server_utils, } = &*find_server_entries(*rsc_entry, should_trace, should_read_binding_usage) .await?; + let client_shared_entries = client_shared_entries + .await? + .into_iter() + .map(|m| ResolvedVc::upcast(*m)) + .collect(); + + // SEGMENT: client_shared_entries and server utils shared by the layout segments + // and the page let graph = SingleModuleGraph::new_with_entries_visited_intern( vec![ - ChunkGroupEntry::SharedMerged { - parent: Box::new(rsc_entry_chunk_group.clone()), - merge_tag: NEXT_SERVER_UTILITY_MERGE_TAG.clone(), - entries: server_utils + ChunkGroupEntry::Entry(client_shared_entries), + ChunkGroupEntry::SharedMultiple( + server_utils .iter() .map(async |m| Ok(ResolvedVc::upcast(m.await?.module))) .try_join() .await?, - }, - ChunkGroupEntry::Entry(client_shared_entries), + ), ], - VisitedModules::empty(), + visited_modules, should_trace, should_read_binding_usage, ); graphs.push(graph); - let mut visited_modules = VisitedModules::from_graph(graph); + visited_modules = VisitedModules::concatenate(visited_modules, graph); // Skip the last server component, which is the page itself, because that one // won't have it's visited modules added, and will be visited in the next step @@ -928,6 +931,7 @@ impl AppProject { .iter() .take(server_component_entries.len().saturating_sub(1)) { + // SEGMENT: layout segment let graph = SingleModuleGraph::new_with_entries_visited_intern( vec![ChunkGroupEntry::Shared(ResolvedVc::upcast(*module))], visited_modules, @@ -948,18 +952,9 @@ impl AppProject { VisitedModules::with_incremented_index(visited_modules) }; } - visited_modules - } else { - let graph = SingleModuleGraph::new_with_entries_visited_intern( - vec![ChunkGroupEntry::Entry(client_shared_entries)], - VisitedModules::empty(), - should_trace, - should_read_binding_usage, - ); - graphs.push(graph); - VisitedModules::from_graph(graph) - }; + } + // SEGMENT: rsc entry chunk group let graph = SingleModuleGraph::new_with_entries_visited_intern( vec![rsc_entry_chunk_group], visited_modules, @@ -1254,12 +1249,7 @@ impl AppEndpoint { self, *rsc_entry, // We only need the client runtime entries for pages not for Route Handlers - if is_app_page { - this.app_project.client_runtime_entries() - } else { - EvaluatableAssets::empty() - }, - is_app_page, + is_app_page.then(|| this.app_project.client_runtime_entries()), ) .await?; @@ -2133,13 +2123,14 @@ impl Endpoint for AppEndpoint { async fn module_graphs(self: Vc) -> Result> { let this = self.await?; let app_entry = self.app_endpoint_entry().await?; + let is_app_page = matches!(this.ty, AppEndpointType::Page { .. }); let module_graphs = this .app_project .app_module_graphs( self, *app_entry.rsc_entry, - this.app_project.client_runtime_entries(), - matches!(this.ty, AppEndpointType::Page { .. }), + // We only need the client runtime entries for pages not for Route Handlers + is_app_page.then(|| this.app_project.client_runtime_entries()), ) .await?; Ok(Vc::cell(vec![module_graphs.full])) diff --git a/crates/next-core/src/app_page_loader_tree.rs b/crates/next-core/src/app_page_loader_tree.rs index b7781bf22605..46b8c5511d17 100644 --- a/crates/next-core/src/app_page_loader_tree.rs +++ b/crates/next-core/src/app_page_loader_tree.rs @@ -230,8 +230,7 @@ impl AppPageLoaderTreeBuilder { let identifier = magic_identifier::mangle(&format!("{name} #{i}")); let inner_module_id = format!("METADATA_{i}"); let helper_import = rcstr!( - "import { fillMetadataSegment } from 'next/dist/lib/metadata/get-metadata-route' with \ - { 'turbopack-transition': 'next-server-utility' }" + "import { fillMetadataSegment } from 'next/dist/lib/metadata/get-metadata-route'" ); if !self.base.imports.contains(&helper_import) { diff --git a/packages/next/src/build/templates/app-page.ts b/packages/next/src/build/templates/app-page.ts index e738267b160e..9848c72bc7a3 100644 --- a/packages/next/src/build/templates/app-page.ts +++ b/packages/next/src/build/templates/app-page.ts @@ -9,31 +9,38 @@ import { import { RouteKind } from '../../server/route-kind' with { 'turbopack-transition': 'next-server-utility' } -import { getRevalidateReason } from '../../server/instrumentation/utils' -import { getTracer, SpanKind, type Span } from '../../server/lib/trace/tracer' +import { getRevalidateReason } from '../../server/instrumentation/utils' with { 'turbopack-transition': 'next-server-utility' } +import { + getTracer, + SpanKind, + type Span, +} from '../../server/lib/trace/tracer' with { 'turbopack-transition': 'next-server-utility' } import type { RequestMeta } from '../../server/request-meta' import { addRequestMeta, getRequestMeta, setRequestMeta, -} from '../../server/request-meta' -import { BaseServerSpan } from '../../server/lib/trace/constants' -import { interopDefault } from '../../server/app-render/interop-default' -import { stripFlightHeaders } from '../../server/app-render/strip-flight-headers' -import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node' -import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr' +} from '../../server/request-meta' with { 'turbopack-transition': 'next-server-utility' } +import { BaseServerSpan } from '../../server/lib/trace/constants' with { 'turbopack-transition': 'next-server-utility' } +import { interopDefault } from '../../server/app-render/interop-default' with { 'turbopack-transition': 'next-server-utility' } +import { stripFlightHeaders } from '../../server/app-render/strip-flight-headers' with { 'turbopack-transition': 'next-server-utility' } +import { + NodeNextRequest, + NodeNextResponse, +} from '../../server/base-http/node' with { 'turbopack-transition': 'next-server-utility' } +import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr' with { 'turbopack-transition': 'next-server-utility' } import { getFallbackRouteParams, createOpaqueFallbackRouteParams, type OpaqueFallbackRouteParams, -} from '../../server/request/fallback-params' -import { setManifestsSingleton } from '../../server/app-render/manifests-singleton' +} from '../../server/request/fallback-params' with { 'turbopack-transition': 'next-server-utility' } +import { setManifestsSingleton } from '../../server/app-render/manifests-singleton' with { 'turbopack-transition': 'next-server-utility' } import { isHtmlBotRequest, shouldServeStreamingMetadata, -} from '../../server/lib/streaming-metadata' -import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' -import { getIsPossibleServerAction } from '../../server/lib/server-action-request-meta' +} from '../../server/lib/streaming-metadata' with { 'turbopack-transition': 'next-server-utility' } +import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' with { 'turbopack-transition': 'next-server-utility' } +import { getIsPossibleServerAction } from '../../server/lib/server-action-request-meta' with { 'turbopack-transition': 'next-server-utility' } import { RSC_HEADER, NEXT_ROUTER_PREFETCH_HEADER, @@ -42,8 +49,11 @@ import { NEXT_IS_PRERENDER_HEADER, NEXT_DID_POSTPONE_HEADER, RSC_CONTENT_TYPE_HEADER, -} from '../../client/components/app-router-headers' -import { getBotType, isBot } from '../../shared/lib/router/utils/is-bot' +} from '../../client/components/app-router-headers' with { 'turbopack-transition': 'next-server-utility' } +import { + getBotType, + isBot, +} from '../../shared/lib/router/utils/is-bot' with { 'turbopack-transition': 'next-server-utility' } import { CachedRouteKind, IncrementalCacheKind, @@ -51,9 +61,12 @@ import { type CachedPageValue, type ResponseCacheEntry, type ResponseGenerator, -} from '../../server/response-cache' -import { FallbackMode, parseFallbackField } from '../../lib/fallback' -import RenderResult from '../../server/render-result' +} from '../../server/response-cache' with { 'turbopack-transition': 'next-server-utility' } +import { + FallbackMode, + parseFallbackField, +} from '../../lib/fallback' with { 'turbopack-transition': 'next-server-utility' } +import RenderResult from '../../server/render-result' with { 'turbopack-transition': 'next-server-utility' } import { CACHE_ONE_YEAR_SECONDS, HTML_CONTENT_TYPE_HEADER, @@ -61,18 +74,18 @@ import { NEXT_NAV_DEPLOYMENT_ID_HEADER, NEXT_RESUME_HEADER, NEXT_RESUME_STATE_LENGTH_HEADER, -} from '../../lib/constants' +} from '../../lib/constants' with { 'turbopack-transition': 'next-server-utility' } import type { CacheControl } from '../../server/lib/cache-control' -import { ENCODED_TAGS } from '../../server/stream-utils/encoded-tags' -import { createInstantTestScriptInsertionTransformStream } from '../../server/stream-utils/node-web-streams-helper' -import { sendRenderResult } from '../../server/send-payload' -import { NoFallbackError } from '../../shared/lib/no-fallback-error.external' -import { parseMaxPostponedStateSize } from '../../shared/lib/size-limit' +import { ENCODED_TAGS } from '../../server/stream-utils/encoded-tags' with { 'turbopack-transition': 'next-server-utility' } +import { createInstantTestScriptInsertionTransformStream } from '../../server/stream-utils/node-web-streams-helper' with { 'turbopack-transition': 'next-server-utility' } +import { sendRenderResult } from '../../server/send-payload' with { 'turbopack-transition': 'next-server-utility' } +import { NoFallbackError } from '../../shared/lib/no-fallback-error.external' with { 'turbopack-transition': 'next-server-utility' } +import { parseMaxPostponedStateSize } from '../../shared/lib/size-limit' with { 'turbopack-transition': 'next-server-utility' } import { getMaxPostponedStateSize, getPostponedStateExceededErrorMessage, readBodyWithSizeLimit, -} from '../../server/lib/postponed-request-body' +} from '../../server/lib/postponed-request-body' with { 'turbopack-transition': 'next-server-utility' } // These are injected by the loader afterwards. @@ -98,14 +111,14 @@ export const __next_app__ = { } import * as entryBase from '../../server/app-render/entry-base' with { 'turbopack-transition': 'next-server-utility' } -import { RedirectStatusCode } from '../../client/components/redirect-status-code' -import { InvariantError } from '../../shared/lib/invariant-error' -import { scheduleOnNextTick } from '../../lib/scheduler' -import { isInterceptionRouteAppPath } from '../../shared/lib/router/utils/interception-routes' +import { RedirectStatusCode } from '../../client/components/redirect-status-code' with { 'turbopack-transition': 'next-server-utility' } +import { InvariantError } from '../../shared/lib/invariant-error' with { 'turbopack-transition': 'next-server-utility' } +import { scheduleOnNextTick } from '../../lib/scheduler' with { 'turbopack-transition': 'next-server-utility' } +import { isInterceptionRouteAppPath } from '../../shared/lib/router/utils/interception-routes' with { 'turbopack-transition': 'next-server-utility' } import { getParamProperties, getSegmentParam, -} from '../../shared/lib/router/utils/get-segment-param' +} from '../../shared/lib/router/utils/get-segment-param' with { 'turbopack-transition': 'next-server-utility' } export * from '../../server/app-render/entry-base' with { 'turbopack-transition': 'next-server-utility' } diff --git a/turbopack/crates/turbopack-core/src/module_graph/chunk_group_info.rs b/turbopack/crates/turbopack-core/src/module_graph/chunk_group_info.rs index 5da760c9cc78..2de0435dd525 100644 --- a/turbopack/crates/turbopack-core/src/module_graph/chunk_group_info.rs +++ b/turbopack/crates/turbopack-core/src/module_graph/chunk_group_info.rs @@ -136,6 +136,7 @@ pub enum ChunkGroupEntry { entries: Vec>>, }, Shared(ResolvedVc>), + SharedMultiple(Vec>>), SharedMerged { parent: Box, merge_tag: RcStr, @@ -150,6 +151,7 @@ impl ChunkGroupEntry { } Self::Entry(entries) | Self::IsolatedMerged { entries, .. } + | Self::SharedMultiple(entries) | Self::SharedMerged { entries, .. } => Either::Right(entries.iter().copied()), } } @@ -175,6 +177,8 @@ pub enum ChunkGroup { /// A shared chunk group. Corresponds to an incoming [ChunkingType::Shared] reference with /// `merge_tag: None` Shared(ResolvedVc>), + /// A shared chunk group with multiple entries. + SharedMultiple(Vec>>), /// A shared chunk group. Corresponds to an incoming [ChunkingType::Shared] reference with /// `merge_tag: Some(_)` SharedMerged { @@ -205,6 +209,7 @@ impl ChunkGroup { } ChunkGroup::Entry(entries) | ChunkGroup::IsolatedMerged { entries, .. } + | ChunkGroup::SharedMultiple(entries) | ChunkGroup::SharedMerged { entries, .. } => Either::Right(entries.iter().copied()), } } @@ -214,6 +219,7 @@ impl ChunkGroup { ChunkGroup::Async(_) | ChunkGroup::Isolated(_) | ChunkGroup::Shared(_) => 1, ChunkGroup::Entry(entries) | ChunkGroup::IsolatedMerged { entries, .. } + | ChunkGroup::SharedMultiple(entries) | ChunkGroup::SharedMerged { entries, .. } => entries.len(), } } @@ -237,6 +243,14 @@ impl ChunkGroup { ChunkGroup::Shared(entry) => turbofmt!("ChunkGroup::Shared({:?})", entry.ident()) .await? .to_string(), + ChunkGroup::SharedMultiple(entries) => format!( + "ChunkGroup::SharedMultiple({:?})", + entries + .iter() + .map(|m| m.ident().to_string()) + .try_join() + .await? + ), ChunkGroup::IsolatedMerged { parent, merge_tag, @@ -286,6 +300,7 @@ pub enum ChunkGroupKey { merge_tag: RcStr, }, Shared(ResolvedVc>), + SharedMultiple(Vec>>), SharedMerged { parent: ChunkGroupId, merge_tag: RcStr, @@ -322,6 +337,14 @@ impl ChunkGroupKey { ChunkGroupKey::Shared(module) => { turbofmt!("Shared({:?})", module.ident()).await?.to_string() } + ChunkGroupKey::SharedMultiple(entries) => format!( + "SharedMultiple({:?})", + entries + .iter() + .map(|m| m.ident().to_string()) + .try_join() + .await? + ), ChunkGroupKey::SharedMerged { parent, merge_tag } => { format!( "SharedMerged {{ parent: {}, merge_tag: {:?} }}", @@ -446,6 +469,7 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraph) -> Result ChunkGroupKey::Async(entry), ChunkGroupEntry::Isolated(entry) => ChunkGroupKey::Isolated(entry), ChunkGroupEntry::Shared(entry) => ChunkGroupKey::Shared(entry), + ChunkGroupEntry::SharedMultiple(entries) => ChunkGroupKey::SharedMultiple(entries), ChunkGroupEntry::IsolatedMerged { parent, merge_tag, @@ -752,6 +776,7 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraph) -> Result ChunkGroup::Shared(module), + ChunkGroupKey::SharedMultiple(entries) => ChunkGroup::SharedMultiple(entries), ChunkGroupKey::SharedMerged { parent, merge_tag } => ChunkGroup::SharedMerged { parent: parent.0 as usize, merge_tag, From 37aed862ed7ed956666615f521f6cef166e5b47a Mon Sep 17 00:00:00 2001 From: Tobias Koppers Date: Fri, 20 Mar 2026 14:59:04 +0100 Subject: [PATCH 05/76] turbo-persistence: remove Unmergeable mmap advice (#91713) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove the `MADV_UNMERGEABLE` (Unmergeable) mmap advice from `turbo-persistence`'s `advise_mmap_for_persistence` helper in `mmap_helper.rs`. The WSL (Windows Subsystem for Linux) kernel does not support `MADV_UNMERGEABLE` and returns an error when it is applied, causing turbo-persistence to fail on WSL. See: https://x.com/von_cronen/status/2034944304712392891 Additionally, `MADV_UNMERGEABLE` is already the **default** state for memory pages — KSM (Kernel Same-page Merging) is opt-in via `MADV_MERGEABLE`. Explicitly setting `MADV_UNMERGEABLE` on pages that were never marked mergeable is a no-op on standard kernels, so the call provides no benefit while breaking WSL users. The `MADV_DONTFORK` advice is retained, as it has a clear correctness benefit (prevents mmap regions from being inherited by child processes on `fork()`). Removed the `mmap.advise(memmap2::Advice::Unmergeable)` call and its associated doc comment from `turbopack/crates/turbo-persistence/src/mmap_helper.rs`. Co-authored-by: Tobias Koppers Co-authored-by: Claude --- turbopack/crates/turbo-persistence/src/mmap_helper.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/turbopack/crates/turbo-persistence/src/mmap_helper.rs b/turbopack/crates/turbo-persistence/src/mmap_helper.rs index be6a951f0cd6..a6d5e657aeb3 100644 --- a/turbopack/crates/turbo-persistence/src/mmap_helper.rs +++ b/turbopack/crates/turbo-persistence/src/mmap_helper.rs @@ -2,12 +2,11 @@ /// /// - `DontFork`: prevents mmap regions from being copied into child processes on `fork()`, avoiding /// unnecessary memory duplication and potential SIGBUS. -/// - `Unmergeable`: opts pages out of KSM (Kernel Same-page Merging) since our data is unique -/// compressed content that won't benefit from deduplication scanning. #[cfg(target_os = "linux")] pub fn advise_mmap_for_persistence(mmap: &memmap2::Mmap) -> anyhow::Result<()> { - mmap.advise(memmap2::Advice::DontFork)?; - mmap.advise(memmap2::Advice::Unmergeable)?; + use anyhow::Context; + mmap.advise(memmap2::Advice::DontFork) + .context("Failed to advise mmap DontFork")?; Ok(()) } From 88fc4308e25076d09112b96f56941eb1fd2ff77e Mon Sep 17 00:00:00 2001 From: Hendrik Liebau Date: Fri, 20 Mar 2026 14:38:28 +0100 Subject: [PATCH 06/76] Fix server actions in standalone mode with `cacheComponents` (#91711) The `staticPathKey` condition added in #91231 inadvertently applies to server action requests on dynamic SSG routes when `cacheComponents` is enabled. Server action fetch requests from the client do not send the `RSC` header (`rsc: 1`). They only send `Accept: text/x-component` and the `Next-Action` header. This means `isRSCRequest` and `isDynamicRSCRequest` are both `false` for action requests. The new `staticPathKey` condition (`isSSG && pageIsDynamic && prerenderInfo?.fallbackRouteParams`) evaluates to `true` for dynamic PPR routes, setting `staticPathKey` even though `ssgCacheKey` is `null` for actions. With `staticPathKey` set, the request enters the fallback rendering block, which serves the cached fallback HTML shell with the action result appended to it, instead of responding with just the RSC action result. The fix excludes server action requests from the `staticPathKey` computation by adding `!isPossibleServerAction` to the condition, restoring the pre-#91231 behavior where `staticPathKey` was always `null` for server actions in production. fixes #91662 closes #91677 closes #91669 --- packages/next/src/build/templates/app-page.ts | 9 ++- .../server-actions/app/[slug]/form.tsx | 57 +++++++++++++ .../server-actions/app/[slug]/page.tsx | 22 +++++ .../server-actions/app/layout.tsx | 11 +++ .../server-actions/build-local.sh | 12 +++ .../server-actions/next.config.ts | 7 ++ .../server-actions/public/favicon.ico | Bin 0 -> 15086 bytes .../standalone-mode-server-actions.test.ts | 76 ++++++++++++++++++ 8 files changed, 193 insertions(+), 1 deletion(-) create mode 100644 test/production/standalone-mode/server-actions/app/[slug]/form.tsx create mode 100644 test/production/standalone-mode/server-actions/app/[slug]/page.tsx create mode 100644 test/production/standalone-mode/server-actions/app/layout.tsx create mode 100755 test/production/standalone-mode/server-actions/build-local.sh create mode 100644 test/production/standalone-mode/server-actions/next.config.ts create mode 100644 test/production/standalone-mode/server-actions/public/favicon.ico create mode 100644 test/production/standalone-mode/server-actions/standalone-mode-server-actions.test.ts diff --git a/packages/next/src/build/templates/app-page.ts b/packages/next/src/build/templates/app-page.ts index 9848c72bc7a3..08c9d676d7ca 100644 --- a/packages/next/src/build/templates/app-page.ts +++ b/packages/next/src/build/templates/app-page.ts @@ -620,7 +620,14 @@ export async function handler( if ( !staticPathKey && (routeModule.isDev || - (isSSG && pageIsDynamic && prerenderInfo?.fallbackRouteParams)) + (isSSG && + pageIsDynamic && + prerenderInfo?.fallbackRouteParams && + // Server action requests must not get a staticPathKey, otherwise they + // enter the fallback rendering block below and return the cached HTML + // shell with the action result appended, instead of responding with + // just the RSC action result. + !isPossibleServerAction)) ) { staticPathKey = resolvedPathname } diff --git a/test/production/standalone-mode/server-actions/app/[slug]/form.tsx b/test/production/standalone-mode/server-actions/app/[slug]/form.tsx new file mode 100644 index 000000000000..3ff97e6245ec --- /dev/null +++ b/test/production/standalone-mode/server-actions/app/[slug]/form.tsx @@ -0,0 +1,57 @@ +'use client' + +import { Component, type ReactNode } from 'react' +import { useActionState } from 'react' + +class ErrorBoundary extends Component< + { children: ReactNode }, + { error: string | null } +> { + constructor(props: { children: ReactNode }) { + super(props) + this.state = { error: null } + } + + static getDerivedStateFromError(error: Error) { + return { error: error.message } + } + + render() { + if (this.state.error) { + return ( +

+ {this.state.error} +

+ ) + } + + return this.props.children + } +} + +function Form({ action }: { action: () => Promise }) { + const [result, formAction] = useActionState(action, '') + + return ( +
+ + {result && ( +

+ {result} +

+ )} +
+ ) +} + +export function FormWithErrorBoundary({ + action, +}: { + action: () => Promise +}) { + return ( + +
+ + ) +} diff --git a/test/production/standalone-mode/server-actions/app/[slug]/page.tsx b/test/production/standalone-mode/server-actions/app/[slug]/page.tsx new file mode 100644 index 000000000000..8b02ca237848 --- /dev/null +++ b/test/production/standalone-mode/server-actions/app/[slug]/page.tsx @@ -0,0 +1,22 @@ +import { FormWithErrorBoundary } from './form' + +export function generateStaticParams() { + return [{ slug: 'world' }] +} + +export default async function Page({ + params, +}: { + params: Promise<{ slug: string }> +}) { + const { slug } = await params + + return ( + { + 'use server' + return `hello ${slug}` + }} + /> + ) +} diff --git a/test/production/standalone-mode/server-actions/app/layout.tsx b/test/production/standalone-mode/server-actions/app/layout.tsx new file mode 100644 index 000000000000..0d1755202a3d --- /dev/null +++ b/test/production/standalone-mode/server-actions/app/layout.tsx @@ -0,0 +1,11 @@ +import { Suspense } from 'react' + +export default function Layout({ children }: { children: React.ReactNode }) { + return ( + + + {children} + + + ) +} diff --git a/test/production/standalone-mode/server-actions/build-local.sh b/test/production/standalone-mode/server-actions/build-local.sh new file mode 100755 index 000000000000..822b9bb7eb37 --- /dev/null +++ b/test/production/standalone-mode/server-actions/build-local.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -e + +DIR="test/production/standalone-mode/server-actions" + +pnpm next build "$DIR" +cp -r "$DIR/public" "$DIR/.next/standalone/$DIR/" +cp -r "$DIR/.next/static" "$DIR/.next/standalone/$DIR/.next/" + +echo "" +echo "Build complete. To start the server:" +echo " node $DIR/.next/standalone/$DIR/server.js" diff --git a/test/production/standalone-mode/server-actions/next.config.ts b/test/production/standalone-mode/server-actions/next.config.ts new file mode 100644 index 000000000000..4133a3fcff06 --- /dev/null +++ b/test/production/standalone-mode/server-actions/next.config.ts @@ -0,0 +1,7 @@ +import type { NextConfig } from 'next' + +const nextConfig: NextConfig = { + output: 'standalone', +} + +export default nextConfig diff --git a/test/production/standalone-mode/server-actions/public/favicon.ico b/test/production/standalone-mode/server-actions/public/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..4965832f2c9b0605eaa189b7c7fb11124d24e48a GIT binary patch literal 15086 zcmeHOOH5Q(7(R0cc?bh2AT>N@1PWL!LLfZKyG5c!MTHoP7_p!sBz0k$?pjS;^lmgJ zU6^i~bWuZYHL)9$wuvEKm~qo~(5=Lvx5&Hv;?X#m}i|`yaGY4gX+&b>tew;gcnRQA1kp zBbm04SRuuE{Hn+&1wk%&g;?wja_Is#1gKoFlI7f`Gt}X*-nsMO30b_J@)EFNhzd1QM zdH&qFb9PVqQOx@clvc#KAu}^GrN`q5oP(8>m4UOcp`k&xwzkTio*p?kI4BPtIwX%B zJN69cGsm=x90<;Wmh-bs>43F}ro$}Of@8)4KHndLiR$nW?*{Rl72JPUqRr3ta6e#A z%DTEbi9N}+xPtd1juj8;(CJt3r9NOgb>KTuK|z7!JB_KsFW3(pBN4oh&M&}Nb$Ee2 z$-arA6a)CdsPj`M#1DS>fqj#KF%0q?w50GN4YbmMZIoF{e1yTR=4ablqXHBB2!`wM z1M1ke9+<);|AI;f=2^F1;G6Wfpql?1d5D4rMr?#f(=hkoH)U`6Gb)#xDLjoKjp)1;Js@2Iy5yk zMXUqj+gyk1i0yLjWS|3sM2-1ECc;MAz<4t0P53%7se$$+5Ex`L5TQO_MMXXi04UDIU+3*7Ez&X|mj9cFYBXqM{M;mw_ zpw>azP*qjMyNSD4hh)XZt$gqf8f?eRSFX8VQ4Y+H3jAtvyTrXr`qHAD6`m;aYmH2zOhJC~_*AuT} zvUxC38|JYN94i(05R)dVKgUQF$}#cxV7xZ4FULqFCNX*Forhgp*yr6;DsIk=ub0Hv zpk2L{9Q&|uI^b<6@i(Y+iSxeO_n**4nRLc`P!3ld5jL=nZRw6;DEJ*1z6Pvg+eW|$lnnjO zjd|8>6l{i~UxI244CGn2kK@cJ|#ecwgSyt&HKA2)z zrOO{op^o*- { + let next: NextInstance + let server: ChildProcess + let appPort: number + + beforeAll(async () => { + next = await createNext({ + files: __dirname, + skipStart: true, + }) + await next.build() + + await fs.move( + join(next.testDir, '.next/standalone'), + join(next.testDir, 'standalone') + ) + + await fs.copy( + join(next.testDir, 'public'), + join(next.testDir, 'standalone/public') + ) + + await fs.copy( + join(next.testDir, '.next/static'), + join(next.testDir, 'standalone/.next/static') + ) + + for (const file of await fs.readdir(next.testDir)) { + if (file !== 'standalone') { + await fs.remove(join(next.testDir, file)) + console.log('removed', file) + } + } + + const testServer = join(next.testDir, 'standalone/server.js') + appPort = await findPort() + server = await initNextServerScript(testServer, /- Local:/, { + ...process.env, + ...next.env, + HOSTNAME: '::', + PORT: '' + appPort, + }) + }) + + afterAll(async () => { + await next.destroy() + + if (server) { + await killApp(server) + } + }) + + it('should be able to execute server actions', async () => { + const browser = await webdriver(appPort, `/world`) + await browser.elementByCss('button').click() + + expect(await browser.elementByCss('#result').text()).toBe('hello world') + }) + + it('should be able to execute MPA server actions', async () => { + const browser = await webdriver(appPort, `/world`, { + disableJavaScript: true, + }) + + await browser.elementByCss('button').click() + + expect(await browser.elementByCss('#result').text()).toBe('hello world') + }) +}) From 27886d3cfbec395275252917d01ace90a86ddc80 Mon Sep 17 00:00:00 2001 From: Niklas Mischkulnig <4586894+mischnic@users.noreply.github.com> Date: Fri, 20 Mar 2026 19:08:15 +0100 Subject: [PATCH 07/76] Turbopack: fix webpack loader runner layer (#91727) Otherwise you get a `Dependency tracking is disabled` / infinite loop when trying to use both turbopack.rules.loader and turbopackLoader at the same time --- .../turbopack-import-assertions-use/app/page.tsx | 4 ++++ .../turbopack-import-assertions-use/data.jsonlike2 | 1 + .../turbopack-import-assertions-use/next.config.js | 11 ++++++++++- .../turbopack-import-assertions-use.test.ts | 5 +++++ turbopack/crates/turbopack/src/lib.rs | 2 +- 5 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 test/development/app-dir/turbopack-import-assertions-use/data.jsonlike2 diff --git a/test/development/app-dir/turbopack-import-assertions-use/app/page.tsx b/test/development/app-dir/turbopack-import-assertions-use/app/page.tsx index 1edb74a29a9d..40c34e9442a7 100644 --- a/test/development/app-dir/turbopack-import-assertions-use/app/page.tsx +++ b/test/development/app-dir/turbopack-import-assertions-use/app/page.tsx @@ -8,7 +8,10 @@ import replacedValue from '../data-with-placeholder.js' with { turbopackLoader: import rawTextViaModuleType from '../data2.txt' with { turbopackLoader: '../node_modules/test-raw-loader/index.js', turbopackModuleType: 'ecmascript' } // Import a non-.json file and treat it as JSON via turbopackModuleType import jsonData from '../data.jsonlike' with { turbopackLoader: 'test-identity-loader', turbopackModuleType: 'json' } +// Normal rules should still work at the same time +import jsonData2 from '../data.jsonlike2' +console.log(jsonData, jsonData2) export default function Page() { return (
@@ -16,6 +19,7 @@ export default function Page() {

{replacedValue}

{rawTextViaModuleType}

{jsonData.greeting}

+

{jsonData2.greeting}

) } diff --git a/test/development/app-dir/turbopack-import-assertions-use/data.jsonlike2 b/test/development/app-dir/turbopack-import-assertions-use/data.jsonlike2 new file mode 100644 index 000000000000..26a72604ff69 --- /dev/null +++ b/test/development/app-dir/turbopack-import-assertions-use/data.jsonlike2 @@ -0,0 +1 @@ +{"greeting": "Hello from JSON module type 2"} diff --git a/test/development/app-dir/turbopack-import-assertions-use/next.config.js b/test/development/app-dir/turbopack-import-assertions-use/next.config.js index 807126e4cf0b..97e57003ca8a 100644 --- a/test/development/app-dir/turbopack-import-assertions-use/next.config.js +++ b/test/development/app-dir/turbopack-import-assertions-use/next.config.js @@ -1,6 +1,15 @@ /** * @type {import('next').NextConfig} */ -const nextConfig = {} +const nextConfig = { + turbopack: { + rules: { + '*.jsonlike2': { + loaders: ['test-identity-loader'], + as: '*.json', + }, + }, + }, +} module.exports = nextConfig diff --git a/test/development/app-dir/turbopack-import-assertions-use/turbopack-import-assertions-use.test.ts b/test/development/app-dir/turbopack-import-assertions-use/turbopack-import-assertions-use.test.ts index 175d36ffda54..0faefdc4005c 100644 --- a/test/development/app-dir/turbopack-import-assertions-use/turbopack-import-assertions-use.test.ts +++ b/test/development/app-dir/turbopack-import-assertions-use/turbopack-import-assertions-use.test.ts @@ -31,4 +31,9 @@ describe('turbopack-import-assertions-use', () => { const $ = await next.render$('/') expect($('#json-type').text()).toBe('Hello from JSON module type') }) + + it('should apply identity with loader rules', async () => { + const $ = await next.render$('/') + expect($('#json-type-2').text()).toBe('Hello from JSON module type 2') + }) }) diff --git a/turbopack/crates/turbopack/src/lib.rs b/turbopack/crates/turbopack/src/lib.rs index 1d63bef7c6a3..08231611ae81 100644 --- a/turbopack/crates/turbopack/src/lib.rs +++ b/turbopack/crates/turbopack/src/lib.rs @@ -716,7 +716,7 @@ async fn process_default_internal( *execution_context, Some(import_map), None, - Layer::new(rcstr!("turbopack_use_loaders")), + Layer::new(rcstr!("webpack_loaders")), false, ) .to_resolved() From 600cd2fedbd78943a856ce2ddefac0baee29346c Mon Sep 17 00:00:00 2001 From: JJ Kasper Date: Fri, 20 Mar 2026 10:05:27 -0700 Subject: [PATCH 08/76] Fix adapter outputs for dynamic metadata routes (#91680) ## Summary This fixes adapter `onBuildComplete` outputs for dynamic metadata routes. ## Bug `handleBuildComplete` skipped metadata routes too aggressively via `isStaticMetadataFile(...)`, so dynamic metadata routes (for example `robots.txt` / `sitemap.xml` using `connection()`) were omitted from `outputs.appRoutes`. ## Fix Only skip metadata routes when they are actually prerendered/static (present in prerender manifests). Dynamic metadata routes are now included in adapter `outputs.appRoutes` as expected. ## Tests Added e2e coverage in `test/e2e/app-dir/adapter-dynamic-metadata`: - verifies dynamic `robots.txt`, `sitemap.xml`, and `favicon.ico` functionality - verifies adapter output classification for non-deploy runs - skips output-shape verification in deploy mode - skips the suite in dev mode --- .../next/src/build/adapter/build-complete.ts | 22 ++++++- .../adapter-dynamic-metadata.test.ts | 65 +++++++++++++++++++ .../app/favicon.ico/route.ts | 11 ++++ .../adapter-dynamic-metadata/app/layout.tsx | 8 +++ .../adapter-dynamic-metadata/app/page.tsx | 3 + .../adapter-dynamic-metadata/app/robots.ts | 14 ++++ .../adapter-dynamic-metadata/app/sitemap.ts | 12 ++++ .../adapter-dynamic-metadata/my-adapter.mjs | 14 ++++ .../adapter-dynamic-metadata/next.config.js | 10 +++ 9 files changed, 157 insertions(+), 2 deletions(-) create mode 100644 test/e2e/app-dir/adapter-dynamic-metadata/adapter-dynamic-metadata.test.ts create mode 100644 test/e2e/app-dir/adapter-dynamic-metadata/app/favicon.ico/route.ts create mode 100644 test/e2e/app-dir/adapter-dynamic-metadata/app/layout.tsx create mode 100644 test/e2e/app-dir/adapter-dynamic-metadata/app/page.tsx create mode 100644 test/e2e/app-dir/adapter-dynamic-metadata/app/robots.ts create mode 100644 test/e2e/app-dir/adapter-dynamic-metadata/app/sitemap.ts create mode 100644 test/e2e/app-dir/adapter-dynamic-metadata/my-adapter.mjs create mode 100644 test/e2e/app-dir/adapter-dynamic-metadata/next.config.js diff --git a/packages/next/src/build/adapter/build-complete.ts b/packages/next/src/build/adapter/build-complete.ts index 32cded960f5b..0a801a8a6952 100644 --- a/packages/next/src/build/adapter/build-complete.ts +++ b/packages/next/src/build/adapter/build-complete.ts @@ -1070,8 +1070,26 @@ export async function handleBuildComplete({ } const normalizedPage = normalizeAppPath(page) - // Skip static metadata routes - they will be output as static files - if (isStaticMetadataFile(normalizedPage)) { + // Skip static metadata routes only when they are prerendered. + // Dynamic metadata routes (e.g. robots/sitemap using connection()) + // should remain app routes in adapter outputs. + const isStaticMetadataRoute = isStaticMetadataFile(normalizedPage) + const isPrerenderedMetadataRoute = + prerenderManifest.routes[normalizedPage] || + prerenderManifest.dynamicRoutes[normalizedPage] || + config.i18n?.locales?.some((locale) => { + const localePathname = path.posix.join( + '/', + locale, + normalizedPage.slice(1) + ) + return ( + prerenderManifest.routes[localePathname] || + prerenderManifest.dynamicRoutes[localePathname] + ) + }) + + if (isStaticMetadataRoute && isPrerenderedMetadataRoute) { continue } const pageFile = path.join(appDistDir, `${page}.js`) diff --git a/test/e2e/app-dir/adapter-dynamic-metadata/adapter-dynamic-metadata.test.ts b/test/e2e/app-dir/adapter-dynamic-metadata/adapter-dynamic-metadata.test.ts new file mode 100644 index 000000000000..2a03a961fab9 --- /dev/null +++ b/test/e2e/app-dir/adapter-dynamic-metadata/adapter-dynamic-metadata.test.ts @@ -0,0 +1,65 @@ +import type { NextAdapter } from 'next' +import { nextTestSetup } from 'e2e-utils' + +describe('adapter-dynamic-metadata', () => { + const { next, isNextDev, isNextDeploy } = nextTestSetup({ + files: __dirname, + }) + + if (isNextDev) { + it('should skip next dev', () => {}) + return + } + + if (!isNextDeploy) { + it('should classify dynamic metadata routes as app routes in adapter outputs', async () => { + const { outputs }: Parameters[0] = + await next.readJSON('build-complete.json') + + const expectedDynamicMetadataRoutes = [ + '/robots.txt', + '/sitemap.xml', + '/favicon.ico', + ] + const staticFilePathnames = outputs.staticFiles.map( + (item) => item.pathname + ) + const prerenderPathnames = outputs.prerenders.map((item) => item.pathname) + const appRoutePathnames = outputs.appRoutes.map((item) => item.pathname) + + expect(staticFilePathnames).toEqual( + expect.not.arrayContaining(expectedDynamicMetadataRoutes) + ) + expect(prerenderPathnames).toEqual( + expect.not.arrayContaining(expectedDynamicMetadataRoutes) + ) + expect(appRoutePathnames).toEqual( + expect.arrayContaining(expectedDynamicMetadataRoutes) + ) + + for (const pathname of expectedDynamicMetadataRoutes) { + const appRoute = outputs.appRoutes.find( + (item) => item.pathname === pathname + ) + expect(appRoute?.runtime).toBe('nodejs') + } + }) + } + + it('should serve dynamic metadata routes', async () => { + const robots = await next.fetch('/robots.txt') + expect(robots.status).toBe(200) + expect(robots.headers.get('content-type')).toContain('text/plain') + expect(await robots.text()).toContain('User-Agent: *') + + const sitemap = await next.fetch('/sitemap.xml') + expect(sitemap.status).toBe(200) + expect(sitemap.headers.get('content-type')).toBe('application/xml') + expect(await sitemap.text()).toContain(' + {children} + + ) +} diff --git a/test/e2e/app-dir/adapter-dynamic-metadata/app/page.tsx b/test/e2e/app-dir/adapter-dynamic-metadata/app/page.tsx new file mode 100644 index 000000000000..ff7159d9149f --- /dev/null +++ b/test/e2e/app-dir/adapter-dynamic-metadata/app/page.tsx @@ -0,0 +1,3 @@ +export default function Page() { + return

hello world

+} diff --git a/test/e2e/app-dir/adapter-dynamic-metadata/app/robots.ts b/test/e2e/app-dir/adapter-dynamic-metadata/app/robots.ts new file mode 100644 index 000000000000..58731f5d36e8 --- /dev/null +++ b/test/e2e/app-dir/adapter-dynamic-metadata/app/robots.ts @@ -0,0 +1,14 @@ +import type { MetadataRoute } from 'next' +import { connection } from 'next/server' + +export default async function robots(): Promise { + await connection() + + return { + rules: { + userAgent: '*', + allow: '/', + }, + sitemap: 'https://example.com/sitemap.xml', + } +} diff --git a/test/e2e/app-dir/adapter-dynamic-metadata/app/sitemap.ts b/test/e2e/app-dir/adapter-dynamic-metadata/app/sitemap.ts new file mode 100644 index 000000000000..b733e98c5cfc --- /dev/null +++ b/test/e2e/app-dir/adapter-dynamic-metadata/app/sitemap.ts @@ -0,0 +1,12 @@ +import type { MetadataRoute } from 'next' +import { connection } from 'next/server' + +export default async function sitemap(): Promise { + await connection() + + return [ + { + url: 'https://example.com', + }, + ] +} diff --git a/test/e2e/app-dir/adapter-dynamic-metadata/my-adapter.mjs b/test/e2e/app-dir/adapter-dynamic-metadata/my-adapter.mjs new file mode 100644 index 000000000000..a67e21090da6 --- /dev/null +++ b/test/e2e/app-dir/adapter-dynamic-metadata/my-adapter.mjs @@ -0,0 +1,14 @@ +import fs from 'fs' + +/** @type {import('next').NextAdapter} */ +const adapter = { + name: 'adapter-dynamic-metadata', + onBuildComplete: async (ctx) => { + await fs.promises.writeFile( + 'build-complete.json', + JSON.stringify(ctx, null, 2) + ) + }, +} + +export default adapter diff --git a/test/e2e/app-dir/adapter-dynamic-metadata/next.config.js b/test/e2e/app-dir/adapter-dynamic-metadata/next.config.js new file mode 100644 index 000000000000..d0451f026871 --- /dev/null +++ b/test/e2e/app-dir/adapter-dynamic-metadata/next.config.js @@ -0,0 +1,10 @@ +/** + * @type {import('next').NextConfig} + */ +const nextConfig = {} + +if (!process.env.NEXT_ADAPTER_PATH) { + nextConfig.adapterPath = require.resolve('./my-adapter.mjs') +} + +module.exports = nextConfig From a15ec6e9707c5b3db6a818f0049e366dd31c47fc Mon Sep 17 00:00:00 2001 From: Abhishek Mardiya <97448460+abhishekmardiya@users.noreply.github.com> Date: Fri, 20 Mar 2026 14:30:54 +0530 Subject: [PATCH 09/76] docs: fix broken Activity Patterns demo link in preserving UI state guide (#91698) ## What? Fixes a broken link in the Preserving UI State guide: https://nextjs.org/docs/app/guides/preserving-ui-state#examples The "Activity Patterns demo" link currently points to a non-working URL. ## Why? The demo link returns a 404 / invalid page, which makes the example section confusing for readers. ## Changes - Updated the Activity Patterns demo link to the correct URL. ## Notes No functional changes, docs only. @icyJoseph @delbaoliveira --- docs/01-app/02-guides/preserving-ui-state.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/01-app/02-guides/preserving-ui-state.mdx b/docs/01-app/02-guides/preserving-ui-state.mdx index be97f907f407..d7026a7c098d 100644 --- a/docs/01-app/02-guides/preserving-ui-state.mdx +++ b/docs/01-app/02-guides/preserving-ui-state.mdx @@ -496,7 +496,7 @@ The ref persists across hide/show cycles (refs aren't cleaned up), so `hasMounte ## Examples -The [Activity Patterns Demo](https://react-activity-patterns.vercel.app/) ([source](https://github.com/vercel-labs/react-activity-patterns)) is a Next.js app with Cache Components enabled and three routes. Navigate between them to see state preservation in action: +The [Activity Patterns Demo](https://react-activity-patterns.labs.vercel.dev) ([source](https://github.com/vercel-labs/react-activity-patterns)) is a Next.js app with Cache Components enabled and three routes. Navigate between them to see state preservation in action: - **Data** — sortable table and selectable list that keep their state across navigations, plus a reviews section that prerenders in the background - **Forms** — filter panel with DOM state (`
`, checkboxes, text inputs) that persists, and a newsletter form that resets after submission using `useLayoutEffect` cleanup From 3e37bb42d250b02897b07fd03130e38631cdfbbd Mon Sep 17 00:00:00 2001 From: Joseph Date: Fri, 20 Mar 2026 15:47:19 +0100 Subject: [PATCH 10/76] docs: post release amends (#91715) Fixes based on feedback post release Fixes: https://github.com/vercel/next.js/pull/91715 --- .../01-getting-started/03-layouts-and-pages.mdx | 2 +- .../04-linking-and-navigating.mdx | 1 + docs/01-app/01-getting-started/09-revalidating.mdx | 4 ++-- .../01-app/01-getting-started/10-error-handling.mdx | 8 +++++++- docs/01-app/01-getting-started/11-css.mdx | 2 +- docs/01-app/02-guides/ai-agents.mdx | 13 +++++++++++++ docs/01-app/02-guides/content-security-policy.mdx | 1 - .../03-api-reference/04-functions/catchError.mdx | 4 ++-- 8 files changed, 27 insertions(+), 8 deletions(-) diff --git a/docs/01-app/01-getting-started/03-layouts-and-pages.mdx b/docs/01-app/01-getting-started/03-layouts-and-pages.mdx index 95a7f76c9451..f8472b31e294 100644 --- a/docs/01-app/01-getting-started/03-layouts-and-pages.mdx +++ b/docs/01-app/01-getting-started/03-layouts-and-pages.mdx @@ -129,7 +129,7 @@ export default async function Page() { } ``` -```jsx filename="app/blog/[slug]/page.js" switcher +```jsx filename="app/blog/page.js" switcher // Dummy imports import { getPosts } from '@/lib/posts' import { Post } from '@/ui/post' diff --git a/docs/01-app/01-getting-started/04-linking-and-navigating.mdx b/docs/01-app/01-getting-started/04-linking-and-navigating.mdx index 326fa99251f5..0e0bf63d8ea9 100644 --- a/docs/01-app/01-getting-started/04-linking-and-navigating.mdx +++ b/docs/01-app/01-getting-started/04-linking-and-navigating.mdx @@ -218,6 +218,7 @@ export async function generateStaticParams() { return posts.map((post) => ({ slug: post.slug, })) +} export default async function Page({ params }) { const { slug } = await params diff --git a/docs/01-app/01-getting-started/09-revalidating.mdx b/docs/01-app/01-getting-started/09-revalidating.mdx index c130732e294b..f636c65f32c5 100644 --- a/docs/01-app/01-getting-started/09-revalidating.mdx +++ b/docs/01-app/01-getting-started/09-revalidating.mdx @@ -119,7 +119,7 @@ See the [`revalidateTag` API reference](/docs/app/api-reference/functions/revali `updateTag` immediately expires cached data for read-your-own-writes scenarios — the user sees their change right away instead of stale content. Unlike `revalidateTag`, it can only be used in [Server Actions](/docs/app/getting-started/mutating-data). -```tsx filename="app/lib/actions.ts" highlight={1,6} switcher +```tsx filename="app/lib/actions.ts" highlight={1,12} switcher import { updateTag } from 'next/cache' import { redirect } from 'next/navigation' @@ -136,7 +136,7 @@ export async function createPost(formData: FormData) { } ``` -```jsx filename="app/lib/actions.js" highlight={1,6} switcher +```jsx filename="app/lib/actions.js" highlight={1,12} switcher import { updateTag } from 'next/cache' import { redirect } from 'next/navigation' diff --git a/docs/01-app/01-getting-started/10-error-handling.mdx b/docs/01-app/01-getting-started/10-error-handling.mdx index 1550b49f722f..a8b361633ceb 100644 --- a/docs/01-app/01-getting-started/10-error-handling.mdx +++ b/docs/01-app/01-getting-started/10-error-handling.mdx @@ -151,9 +151,14 @@ export default async function Page() { You can call the [`notFound`](/docs/app/api-reference/functions/not-found) function within a route segment and use the [`not-found.js`](/docs/app/api-reference/file-conventions/not-found) file to show a 404 UI. ```tsx filename="app/blog/[slug]/page.tsx" switcher +import { notFound } from 'next/navigation' import { getPostBySlug } from '@/lib/posts' -export default async function Page({ params }: { params: { slug: string } }) { +export default async function Page({ + params, +}: { + params: Promise<{ slug: string }> +}) { const { slug } = await params const post = getPostBySlug(slug) @@ -166,6 +171,7 @@ export default async function Page({ params }: { params: { slug: string } }) { ``` ```jsx filename="app/blog/[slug]/page.js" switcher +import { notFound } from 'next/navigation' import { getPostBySlug } from '@/lib/posts' export default async function Page({ params }) { diff --git a/docs/01-app/01-getting-started/11-css.mdx b/docs/01-app/01-getting-started/11-css.mdx index 2e33430e9301..a949e2b94864 100644 --- a/docs/01-app/01-getting-started/11-css.mdx +++ b/docs/01-app/01-getting-started/11-css.mdx @@ -210,7 +210,7 @@ export default function Page() { ```jsx filename="app/blog/page.js" switcher import styles from './blog.module.css' -export default function Layout() { +export default function Page() { return
} ``` diff --git a/docs/01-app/02-guides/ai-agents.mdx b/docs/01-app/02-guides/ai-agents.mdx index fa5bd1fefa4e..f3f429a921df 100644 --- a/docs/01-app/02-guides/ai-agents.mdx +++ b/docs/01-app/02-guides/ai-agents.mdx @@ -79,6 +79,19 @@ Before any Next.js work, find and read the relevant doc in `node_modules/next/di @AGENTS.md ``` +
+For earlier versions + +On version 16.1 and earlier, use the codemod to generate these files automatically: + +```bash +npx @next/codemod@latest agents-md +``` + +The codemod outputs the bundled docs to `.next-docs/` in the project root instead of `node_modules/next/dist/docs/`, and the generated agent files will point to that directory. + +
+ ## Understanding AGENTS.md The default `AGENTS.md` contains a single, focused instruction: **read the bundled docs before writing code**. This is intentionally minimal — the goal is to redirect agents from stale training data to the accurate, version-matched documentation in `node_modules/next/dist/docs/`. diff --git a/docs/01-app/02-guides/content-security-policy.mdx b/docs/01-app/02-guides/content-security-policy.mdx index 34793fb77d7d..1763b0c5d57b 100644 --- a/docs/01-app/02-guides/content-security-policy.mdx +++ b/docs/01-app/02-guides/content-security-policy.mdx @@ -534,7 +534,6 @@ module.exports = { ### Limitations of SRI - **Experimental**: Feature may change or be removed -- **Webpack only**: Not available with Turbopack - **App Router only**: Not supported in Pages Router - **Build-time only**: Cannot handle dynamically generated scripts diff --git a/docs/01-app/03-api-reference/04-functions/catchError.mdx b/docs/01-app/03-api-reference/04-functions/catchError.mdx index 21a1dc04db79..e7fa23ae92f6 100644 --- a/docs/01-app/03-api-reference/04-functions/catchError.mdx +++ b/docs/01-app/03-api-reference/04-functions/catchError.mdx @@ -112,7 +112,7 @@ Use `retry()` to prompt the user to recover from the error. When called, the fun In most cases, use `retry()` instead of `reset()`. The `reset()` function only clears the error state and re-renders without re-fetching, which means it won't recover from Server Component errors. -```tsx filename="app/custom-error-boundary.tsx" highlight={9,12} switcher +```tsx filename="app/custom-error-boundary.tsx" highlight={16,17} switcher 'use client' import { unstable_catchError } from 'next/error' @@ -137,7 +137,7 @@ function ErrorFallback( export default unstable_catchError(ErrorFallback) ``` -```jsx filename="app/custom-error-boundary.js" highlight={7,10} switcher +```jsx filename="app/custom-error-boundary.js" highlight={9,10} switcher 'use client' import { unstable_catchError } from 'next/error' From ed7d2cef246dcb3e2955c018fd8b2027e0ff8eed Mon Sep 17 00:00:00 2001 From: nextjs-bot Date: Fri, 20 Mar 2026 23:23:58 +0000 Subject: [PATCH 11/76] v16.2.1 --- lerna.json | 2 +- packages/create-next-app/package.json | 2 +- packages/eslint-config-next/package.json | 4 ++-- packages/eslint-plugin-internal/package.json | 2 +- packages/eslint-plugin-next/package.json | 2 +- packages/font/package.json | 2 +- packages/next-bundle-analyzer/package.json | 2 +- packages/next-codemod/package.json | 2 +- packages/next-env/package.json | 2 +- packages/next-mdx/package.json | 2 +- packages/next-playwright/package.json | 2 +- packages/next-plugin-storybook/package.json | 2 +- packages/next-polyfill-module/package.json | 2 +- packages/next-polyfill-nomodule/package.json | 2 +- packages/next-routing/package.json | 2 +- packages/next-rspack/package.json | 2 +- packages/next-swc/package.json | 2 +- packages/next/package.json | 14 +++++++------- packages/react-refresh-utils/package.json | 2 +- packages/third-parties/package.json | 4 ++-- pnpm-lock.yaml | 16 ++++++++-------- 21 files changed, 36 insertions(+), 36 deletions(-) diff --git a/lerna.json b/lerna.json index 622a5a573f8b..2c2b1189b639 100644 --- a/lerna.json +++ b/lerna.json @@ -16,5 +16,5 @@ "registry": "https://registry.npmjs.org/" } }, - "version": "16.2.0" + "version": "16.2.1" } \ No newline at end of file diff --git a/packages/create-next-app/package.json b/packages/create-next-app/package.json index be9a9d2ca7e2..51299326527f 100644 --- a/packages/create-next-app/package.json +++ b/packages/create-next-app/package.json @@ -1,6 +1,6 @@ { "name": "create-next-app", - "version": "16.2.0", + "version": "16.2.1", "keywords": [ "react", "next", diff --git a/packages/eslint-config-next/package.json b/packages/eslint-config-next/package.json index d2f61e32ec4c..26ff16bb9d71 100644 --- a/packages/eslint-config-next/package.json +++ b/packages/eslint-config-next/package.json @@ -1,6 +1,6 @@ { "name": "eslint-config-next", - "version": "16.2.0", + "version": "16.2.1", "description": "ESLint configuration used by Next.js.", "license": "MIT", "repository": { @@ -12,7 +12,7 @@ "dist" ], "dependencies": { - "@next/eslint-plugin-next": "16.2.0", + "@next/eslint-plugin-next": "16.2.1", "eslint-import-resolver-node": "^0.3.6", "eslint-import-resolver-typescript": "^3.5.2", "eslint-plugin-import": "^2.32.0", diff --git a/packages/eslint-plugin-internal/package.json b/packages/eslint-plugin-internal/package.json index 507806c42933..cd8e66fe025e 100644 --- a/packages/eslint-plugin-internal/package.json +++ b/packages/eslint-plugin-internal/package.json @@ -1,7 +1,7 @@ { "name": "@next/eslint-plugin-internal", "private": true, - "version": "16.2.0", + "version": "16.2.1", "description": "ESLint plugin for working on Next.js.", "exports": { ".": "./src/eslint-plugin-internal.js" diff --git a/packages/eslint-plugin-next/package.json b/packages/eslint-plugin-next/package.json index 5973444c4b8c..9a2da229b490 100644 --- a/packages/eslint-plugin-next/package.json +++ b/packages/eslint-plugin-next/package.json @@ -1,6 +1,6 @@ { "name": "@next/eslint-plugin-next", - "version": "16.2.0", + "version": "16.2.1", "description": "ESLint plugin for Next.js.", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/font/package.json b/packages/font/package.json index 95bed12ef435..41271e57b6f8 100644 --- a/packages/font/package.json +++ b/packages/font/package.json @@ -1,7 +1,7 @@ { "name": "@next/font", "private": true, - "version": "16.2.0", + "version": "16.2.1", "repository": { "url": "vercel/next.js", "directory": "packages/font" diff --git a/packages/next-bundle-analyzer/package.json b/packages/next-bundle-analyzer/package.json index 059bfdcaec07..1a942136438e 100644 --- a/packages/next-bundle-analyzer/package.json +++ b/packages/next-bundle-analyzer/package.json @@ -1,6 +1,6 @@ { "name": "@next/bundle-analyzer", - "version": "16.2.0", + "version": "16.2.1", "main": "index.js", "types": "index.d.ts", "license": "MIT", diff --git a/packages/next-codemod/package.json b/packages/next-codemod/package.json index 8e43e6da3f01..315f72ecd40f 100644 --- a/packages/next-codemod/package.json +++ b/packages/next-codemod/package.json @@ -1,6 +1,6 @@ { "name": "@next/codemod", - "version": "16.2.0", + "version": "16.2.1", "license": "MIT", "repository": { "type": "git", diff --git a/packages/next-env/package.json b/packages/next-env/package.json index 60fb70612adb..3d066e291cb9 100644 --- a/packages/next-env/package.json +++ b/packages/next-env/package.json @@ -1,6 +1,6 @@ { "name": "@next/env", - "version": "16.2.0", + "version": "16.2.1", "keywords": [ "react", "next", diff --git a/packages/next-mdx/package.json b/packages/next-mdx/package.json index 7dd5fa409526..6d6b01b113b4 100644 --- a/packages/next-mdx/package.json +++ b/packages/next-mdx/package.json @@ -1,6 +1,6 @@ { "name": "@next/mdx", - "version": "16.2.0", + "version": "16.2.1", "main": "index.js", "license": "MIT", "repository": { diff --git a/packages/next-playwright/package.json b/packages/next-playwright/package.json index 8e3dec1dad09..79d7913708f5 100644 --- a/packages/next-playwright/package.json +++ b/packages/next-playwright/package.json @@ -1,6 +1,6 @@ { "name": "@next/playwright", - "version": "16.2.0", + "version": "16.2.1", "repository": { "url": "vercel/next.js", "directory": "packages/next-playwright" diff --git a/packages/next-plugin-storybook/package.json b/packages/next-plugin-storybook/package.json index 412da2a8865b..bc3a3b226a41 100644 --- a/packages/next-plugin-storybook/package.json +++ b/packages/next-plugin-storybook/package.json @@ -1,6 +1,6 @@ { "name": "@next/plugin-storybook", - "version": "16.2.0", + "version": "16.2.1", "repository": { "url": "vercel/next.js", "directory": "packages/next-plugin-storybook" diff --git a/packages/next-polyfill-module/package.json b/packages/next-polyfill-module/package.json index 8fa43c3783e3..5fc4ddf8f511 100644 --- a/packages/next-polyfill-module/package.json +++ b/packages/next-polyfill-module/package.json @@ -1,6 +1,6 @@ { "name": "@next/polyfill-module", - "version": "16.2.0", + "version": "16.2.1", "description": "A standard library polyfill for ES Modules supporting browsers (Edge 16+, Firefox 60+, Chrome 61+, Safari 10.1+)", "main": "dist/polyfill-module.js", "license": "MIT", diff --git a/packages/next-polyfill-nomodule/package.json b/packages/next-polyfill-nomodule/package.json index b60904973141..08d37a7e9bb3 100644 --- a/packages/next-polyfill-nomodule/package.json +++ b/packages/next-polyfill-nomodule/package.json @@ -1,6 +1,6 @@ { "name": "@next/polyfill-nomodule", - "version": "16.2.0", + "version": "16.2.1", "description": "A polyfill for non-dead, nomodule browsers.", "main": "dist/polyfill-nomodule.js", "license": "MIT", diff --git a/packages/next-routing/package.json b/packages/next-routing/package.json index 66ea93eb1d9f..956eb2bfa665 100644 --- a/packages/next-routing/package.json +++ b/packages/next-routing/package.json @@ -1,6 +1,6 @@ { "name": "@next/routing", - "version": "16.2.0", + "version": "16.2.1", "keywords": [ "react", "next", diff --git a/packages/next-rspack/package.json b/packages/next-rspack/package.json index 55b1ebea6b91..34e8c338f4e5 100644 --- a/packages/next-rspack/package.json +++ b/packages/next-rspack/package.json @@ -1,6 +1,6 @@ { "name": "next-rspack", - "version": "16.2.0", + "version": "16.2.1", "repository": { "url": "vercel/next.js", "directory": "packages/next-rspack" diff --git a/packages/next-swc/package.json b/packages/next-swc/package.json index b9b4341d6a02..d2c7a78f995c 100644 --- a/packages/next-swc/package.json +++ b/packages/next-swc/package.json @@ -1,6 +1,6 @@ { "name": "@next/swc", - "version": "16.2.0", + "version": "16.2.1", "private": true, "files": [ "native/" diff --git a/packages/next/package.json b/packages/next/package.json index 3d4ff6c69463..f864894f1f5e 100644 --- a/packages/next/package.json +++ b/packages/next/package.json @@ -1,6 +1,6 @@ { "name": "next", - "version": "16.2.0", + "version": "16.2.1", "description": "The React Framework", "main": "./dist/server/next.js", "license": "MIT", @@ -97,7 +97,7 @@ ] }, "dependencies": { - "@next/env": "16.2.0", + "@next/env": "16.2.1", "@swc/helpers": "0.5.15", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", @@ -161,11 +161,11 @@ "@modelcontextprotocol/sdk": "1.18.1", "@mswjs/interceptors": "0.23.0", "@napi-rs/triples": "1.2.0", - "@next/font": "16.2.0", - "@next/polyfill-module": "16.2.0", - "@next/polyfill-nomodule": "16.2.0", - "@next/react-refresh-utils": "16.2.0", - "@next/swc": "16.2.0", + "@next/font": "16.2.1", + "@next/polyfill-module": "16.2.1", + "@next/polyfill-nomodule": "16.2.1", + "@next/react-refresh-utils": "16.2.1", + "@next/swc": "16.2.1", "@opentelemetry/api": "1.6.0", "@playwright/test": "1.58.2", "@rspack/core": "1.6.7", diff --git a/packages/react-refresh-utils/package.json b/packages/react-refresh-utils/package.json index dc7e16c02606..091e10b51c4b 100644 --- a/packages/react-refresh-utils/package.json +++ b/packages/react-refresh-utils/package.json @@ -1,6 +1,6 @@ { "name": "@next/react-refresh-utils", - "version": "16.2.0", + "version": "16.2.1", "description": "An experimental package providing utilities for React Refresh.", "repository": { "url": "vercel/next.js", diff --git a/packages/third-parties/package.json b/packages/third-parties/package.json index bc18386bc7c3..dbfd66a5dafe 100644 --- a/packages/third-parties/package.json +++ b/packages/third-parties/package.json @@ -1,6 +1,6 @@ { "name": "@next/third-parties", - "version": "16.2.0", + "version": "16.2.1", "repository": { "url": "vercel/next.js", "directory": "packages/third-parties" @@ -26,7 +26,7 @@ "third-party-capital": "1.0.20" }, "devDependencies": { - "next": "16.2.0", + "next": "16.2.1", "outdent": "0.8.0", "prettier": "2.5.1", "typescript": "5.9.2" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ca151170e22c..b77d960365f0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1017,7 +1017,7 @@ importers: packages/eslint-config-next: dependencies: '@next/eslint-plugin-next': - specifier: 16.2.0 + specifier: 16.2.1 version: link:../eslint-plugin-next eslint: specifier: '>=9.0.0' @@ -1094,7 +1094,7 @@ importers: packages/next: dependencies: '@next/env': - specifier: 16.2.0 + specifier: 16.2.1 version: link:../next-env '@swc/helpers': specifier: 0.5.15 @@ -1219,19 +1219,19 @@ importers: specifier: 1.2.0 version: 1.2.0 '@next/font': - specifier: 16.2.0 + specifier: 16.2.1 version: link:../font '@next/polyfill-module': - specifier: 16.2.0 + specifier: 16.2.1 version: link:../next-polyfill-module '@next/polyfill-nomodule': - specifier: 16.2.0 + specifier: 16.2.1 version: link:../next-polyfill-nomodule '@next/react-refresh-utils': - specifier: 16.2.0 + specifier: 16.2.1 version: link:../react-refresh-utils '@next/swc': - specifier: 16.2.0 + specifier: 16.2.1 version: link:../next-swc '@opentelemetry/api': specifier: 1.6.0 @@ -1955,7 +1955,7 @@ importers: version: 1.0.20 devDependencies: next: - specifier: 16.2.0 + specifier: 16.2.1 version: link:../next outdent: specifier: 0.8.0 From 6d31c3905a22b030b92e02ef317a4b95726a874f Mon Sep 17 00:00:00 2001 From: Joseph Date: Wed, 25 Mar 2026 23:41:22 -0700 Subject: [PATCH 12/76] Backport: docs - 16.2.1 (#91885) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Backporting 1. `0e598d2131` — docs: use ErrorInfo type consistently in catchError docs (#91744) 2. `70760c201b` — docs: add catchError benefits over userspace error boundaries (#91745) 3. `1f920cd057` — docs: platform portability and infrastructure documentation (#91237) 4. `5d2b57b051` — docs: add verified adapters section (#91849) --------- Co-authored-by: Jiwon Choi Co-authored-by: Jimmy Lai Co-authored-by: JJ Kasper Co-authored-by: Tim Neutkens --- .../01-getting-started/10-error-handling.mdx | 8 +- .../01-getting-started/17-deploying.mdx | 30 +++-- docs/01-app/02-guides/cdn-caching.mdx | 114 ++++++++++++++++++ .../02-guides/deploying-to-platforms.mdx | 93 ++++++++++++++ .../02-guides/how-revalidation-works.mdx | 96 +++++++++++++++ .../incremental-static-regeneration.mdx | 3 + docs/01-app/02-guides/ppr-platform-guide.mdx | 114 ++++++++++++++++++ .../01-app/02-guides/rendering-philosophy.mdx | 75 ++++++++++++ docs/01-app/02-guides/self-hosting.mdx | 30 ++++- docs/01-app/02-guides/streaming.mdx | 1 + .../03-file-conventions/error.mdx | 4 +- .../04-functions/catchError.mdx | 54 ++++----- .../01-next-config-js/adapterPath.mdx | 30 ++++- .../01-next-config-js/cacheHandlers.mdx | 88 +++++++++++++- 14 files changed, 686 insertions(+), 54 deletions(-) create mode 100644 docs/01-app/02-guides/cdn-caching.mdx create mode 100644 docs/01-app/02-guides/deploying-to-platforms.mdx create mode 100644 docs/01-app/02-guides/how-revalidation-works.mdx create mode 100644 docs/01-app/02-guides/ppr-platform-guide.mdx create mode 100644 docs/01-app/02-guides/rendering-philosophy.mdx diff --git a/docs/01-app/01-getting-started/10-error-handling.mdx b/docs/01-app/01-getting-started/10-error-handling.mdx index a8b361633ceb..7878dc24e89d 100644 --- a/docs/01-app/01-getting-started/10-error-handling.mdx +++ b/docs/01-app/01-getting-started/10-error-handling.mdx @@ -287,13 +287,13 @@ import { unstable_catchError as catchError, type ErrorInfo } from 'next/error' function ErrorFallback( props: { title: string }, - { error, unstable_retry: retry }: ErrorInfo + { error, unstable_retry }: ErrorInfo ) { return (

{props.title}

{error.message}

- +
) } @@ -306,12 +306,12 @@ export default catchError(ErrorFallback) import { unstable_catchError as catchError } from 'next/error' -function ErrorFallback(props, { error, unstable_retry: retry }) { +function ErrorFallback(props, { error, unstable_retry }) { return (

{props.title}

{error.message}

- +
) } diff --git a/docs/01-app/01-getting-started/17-deploying.mdx b/docs/01-app/01-getting-started/17-deploying.mdx index 22af3f6b7bb5..21488861e43b 100644 --- a/docs/01-app/01-getting-started/17-deploying.mdx +++ b/docs/01-app/01-getting-started/17-deploying.mdx @@ -5,12 +5,12 @@ description: Learn how to deploy your Next.js application. Next.js can be deployed as a Node.js server, Docker container, static export, or adapted to run on different platforms. -| Deployment Option | Feature Support | -| -------------------------------- | ----------------- | -| [Node.js server](#nodejs-server) | All | -| [Docker container](#docker) | All | -| [Static export](#static-export) | Limited | -| [Adapters](#adapters) | Platform-specific | +| Deployment Option | Feature Support | +| -------------------------------- | ------------------------------------------------------------------- | +| [Node.js server](#nodejs-server) | All | +| [Docker container](#docker) | All | +| [Static export](#static-export) | Limited | +| [Adapters](#adapters) | Varies ([verified](#verified-adapters) adapters run the test suite) | ## Node.js server @@ -75,9 +75,20 @@ Running as a [static export](/docs/app/guides/static-exports) **does not** suppo ## Adapters -Next.js can be adapted to run on different platforms to support their infrastructure capabilities. +Next.js can be adapted to run on different platforms to support their infrastructure capabilities. The [Deployment Adapter API](/docs/app/api-reference/config/next-config-js/adapterPath) lets platforms customize how Next.js applications are built and deployed. -Refer to each provider's documentation for information on supported Next.js features: +### Verified Adapters + +Verified adapters are open source, run the full [Next.js compatibility test suite](/docs/app/api-reference/config/next-config-js/adapterPath#testing-adapters), and are hosted under the [Next.js GitHub organization](https://github.com/nextjs). The Next.js team coordinates testing with these platforms before major releases. Publicly visible test results for each adapter are coming soon. [Learn more about verified adapters](/docs/app/guides/deploying-to-platforms#verified-adapters). + +- [Vercel](https://vercel.com/docs/frameworks/nextjs) +- [Bun](https://bun.sh/docs/frameworks/nextjs) + +Cloudflare and Netlify are working on verified adapters built on the Adapter API. In the meantime, they offer their own Next.js integrations (see below). + +### Other Platforms + +The following platforms offer their own Next.js integrations. These are not built on the public [Adapter API](/docs/app/api-reference/config/next-config-js/adapterPath) and are not verified by the Next.js team, so feature support and compatibility may vary. Refer to each provider's documentation for details: - [Appwrite Sites](https://appwrite.io/docs/products/sites/quick-start/nextjs) - [AWS Amplify Hosting](https://docs.amplify.aws/nextjs/start/quickstart/nextjs-app-router-client-components) @@ -85,6 +96,5 @@ Refer to each provider's documentation for information on supported Next.js feat - [Deno Deploy](https://docs.deno.com/examples/next_tutorial) - [Firebase App Hosting](https://firebase.google.com/docs/app-hosting/get-started) - [Netlify](https://docs.netlify.com/frameworks/next-js/overview/#next-js-support-on-netlify) -- [Vercel](https://vercel.com/docs/frameworks/nextjs) -> **Note:** We are working on a [Deployment Adapters API](https://github.com/vercel/next.js/discussions/77740) for all platforms to adopt. After completion, we will add documentation on how to write your own adapters. +For details on which Next.js features require specific platform capabilities, see [Deploying to Platforms](/docs/app/guides/deploying-to-platforms). diff --git a/docs/01-app/02-guides/cdn-caching.mdx b/docs/01-app/02-guides/cdn-caching.mdx new file mode 100644 index 000000000000..fd802ed3a56a --- /dev/null +++ b/docs/01-app/02-guides/cdn-caching.mdx @@ -0,0 +1,114 @@ +--- +title: Using a CDN with Next.js +nav_title: CDN Caching +description: Learn how CDN caching works with Next.js, including what works today, cache variability, and the direction toward pathname-based cache keying. +related: + description: Related guides and references. + links: + - app/guides/deploying-to-platforms + - app/guides/self-hosting + - app/guides/streaming + - app/api-reference/config/next-config-js/assetPrefix +--- + +Next.js sets standard `Cache-Control` headers that CDNs can use to cache responses at the edge. This page covers what works today, where CDN caching is challenging, and the direction toward eliminating custom-header dependencies. + +## What Works Today + +### Cache-Control headers + +Next.js sets `Cache-Control` headers based on the rendering strategy of each route: + +- **Static pages** (no revalidation): `s-maxage=31536000` (one year) +- **ISR pages** (time-based revalidation): `s-maxage={revalidate}, stale-while-revalidate={expire - revalidate}`. The default `expire` is one year, so `stale-while-revalidate` is included in the response header by default. You can customize this with [`cacheLife`](/docs/app/api-reference/functions/cacheLife). +- **Dynamic pages** (no caching): `private, no-cache, no-store, max-age=0, must-revalidate` + +CDNs that respect `s-maxage` and `stale-while-revalidate` can cache static and ISR pages at the edge. However, CDN-level caching alone does not support on-demand revalidation ([`revalidateTag()`](/docs/app/api-reference/functions/revalidateTag) / [`revalidatePath()`](/docs/app/api-reference/functions/revalidatePath)): those calls invalidate the Next.js server cache, but the CDN will continue serving its cached copy until the `s-maxage` TTL expires. To propagate on-demand revalidation to the CDN, trigger CDN purges alongside your revalidation call. A common pattern is: call `revalidateTag()`/`revalidatePath()` to invalidate the Next.js server cache, then call your CDN purge API for the affected keys (including both HTML and RSC variants). + +### Static assets + +Static assets (JavaScript, CSS, images, fonts) served from `/_next/static/` include content hashes in their filenames and have a 1 year `max-age` and `immutable` directive: `public,max-age=31536000,immutable` + +You can use [`assetPrefix`](/docs/app/api-reference/config/next-config-js/assetPrefix) to serve static assets from a different domain or CDN origin. + +### Static prefetches (PPR-enabled routes) + +When a route has Partial Prerendering enabled and the `next-router-prefetch` header is set (indicating a static prefetch), the response is deterministic: it returns the same prerendered content regardless of the client's router state. The `next-router-state-tree` header is not parsed for these requests, so it does not affect the response. + +For PPR-enabled routes, a CDN can cache static prefetch responses if it: + +1. Includes the `_rsc` search parameter in the cache key (to distinguish prefetch variants from HTML responses). +2. Respects the `Cache-Control` headers Next.js sets on the response. + +> **Good to know:** For routes without PPR, the `next-router-state-tree` header is read during prefetch requests to determine which segments to include, which increases cache `vary` as it passes the current router state. When Cache Components is enabled, segment-level prefetches already use pathname-based routes (for example, `/page.segments/_tree.segment.rsc`), and CDNs can cache these with standard pathname-based cache keys. + +## Where CDN Caching Is Challenging + +App Router responses can vary based on several custom request headers. Next.js sets a `Vary` header on responses to signal this to CDNs: + +- `rsc` — whether the request should return a React Server Components (RSC) payload instead of HTML +- `next-router-state-tree` — the client's current router state, used for targeted segment updates during dynamic navigations +- `next-router-prefetch` — whether this is a prefetch request +- `next-router-segment-prefetch` — the specific segment being prefetched +- `next-url` — added only for routes that use [interception routes](/docs/app/api-reference/file-conventions/intercepting-routes), carries the URL being intercepted + +Many CDNs don't support `Vary` without additional configuration. Next.js addresses this with the `_rsc` search parameter: a hash of the relevant request header values that acts as a cache-key, ensuring different response variants get different cache keys. This ensures correct responses even on CDNs that ignore `Vary`. + +## Handling Headers at the CDN + +### What you can safely ignore + +These headers can be omitted in specific cases without causing protocol errors. The server still returns a parseable response, but it may be larger or less targeted to the specific navigation: + +**`next-router-state-tree`**: when omitted on non-prefetch RSC requests, the server returns a full payload instead of a targeted segment update. + +**`next-router-segment-prefetch`**: when omitted on prefetch requests, the server falls back to a broader prefetch payload instead of a segment-specific one. + +**`next-url`**: used for [interception routes](/docs/app/api-reference/file-conventions/intercepting-routes) to vary the response based on the referring page. If omitted, interception routes are not supported as the server doesn't know what original path to match against. The response returned is for regular navigation when `next-url` is omitted: the user sees the target page instead of the intercepted target page. + +### What you must preserve + +**The `rsc` header** must be forwarded from the client to the server. This header tells the server to return an RSC payload instead of HTML. If a CDN strips it, the server returns HTML when the client-side router expects RSC data, which breaks client-side navigation, causing browser navigations instead. The `Vary` header and `_rsc` parameter exist specifically to prevent CDNs from serving a cached HTML response to an RSC request (or vice versa). + +**When `next-router-prefetch` is present, preserve both the prefetch header and the `_rsc` search parameter.** For prefetch flows, `_rsc` is a required cache-busting discriminator and should be treated as mandatory. + +**The `_rsc` search parameter** must be included in the cache key. It distinguishes response variants (HTML vs. RSC, different prefetch types). Ensure your CDN does not strip query parameters from cache keys, as some CDNs do this by default. When the `experimental.validateRSCRequestHeaders` option is enabled and a RSC request arrives without the correct `_rsc` value, the server responds with a **307 redirect** to the URL with the correct hash. CDNs should follow this redirect. Platforms that compute the hash upstream can rewrite requests to include the correct `_rsc` before forwarding to avoid an extra round trip. + +> **Good to know:** Today, `next-url` is included in the `_rsc` hash even during static prefetches. This means you cannot safely ignore it under the current scheme without potentially getting cache misses. The pathname-based direction described below resolves this gap. + +## Direction: Pathname-Based Cache Keying + +The Next.js team is working on moving all cache-affecting inputs into the URL pathname, eliminating the need for `Vary` on custom headers and removing the `_rsc` search parameter. This resolves the CDN caching challenges described above. + +### How it works + +The approach extends the routing scheme that [`output: 'export'`](/docs/app/guides/static-exports) and segment prefetches already use today. File extensions in the pathname identify the response type: + +- **Full page RSC**: `/my/page.rsc` returns the RSC payload for the entire page +- **Segment RSC**: `/my/page.segments/path/to/segment.segment.rsc` returns the RSC payload for a specific segment + +Under this model: + +- **The pathname determines the cache key.** Anything in the pathname affects which response variant is returned. +- **Search parameters can be safely dropped** without affecting returned responses. +- **Standard HTTP cache headers** (`Cache-Control`, `max-age`, etc.) are respected as usual. +- **No `Vary` support needed** from the CDN. + +A CDN would cache Next.js responses by using the pathname as the cache key, ignoring search parameters, and respecting standard `Cache-Control` headers. No need to understand `Vary`, inspect custom headers, or program edge logic. + +### What changes for interception routes + +Under the current scheme, `next-url` contributes to the `_rsc` hash, so dropping it causes cache misses. Under the pathname-based scheme, interception variability would be encoded in a search parameter (not the pathname): + +- If a CDN preserves search params, interception works correctly. +- If a CDN drops search params, interception is not supported. It would gracefully degrade to the non-intercepted page, client-side navigations won't break. + +This makes interception route support an opt-in CDN capability rather than a requirement. + +### Current status + +This direction extends patterns that are already operational in the codebase (segment prefetch paths, `output: 'export'` mode). It is in active design. + +## CDN Feature Compatibility + +For a full table showing the infrastructure primitives available on every major CDN (edge compute, key-value storage, blob storage, PPR resuming), see [Deploying to Platforms](/docs/app/guides/deploying-to-platforms#cdn-infrastructure-compatibility). diff --git a/docs/01-app/02-guides/deploying-to-platforms.mdx b/docs/01-app/02-guides/deploying-to-platforms.mdx new file mode 100644 index 000000000000..3830811628b9 --- /dev/null +++ b/docs/01-app/02-guides/deploying-to-platforms.mdx @@ -0,0 +1,93 @@ +--- +title: Deploying Next.js to different platforms +nav_title: Deploying to Platforms +description: Understand which Next.js features require specific platform capabilities and how to choose the right deployment target. +related: + description: Related guides and references. + links: + - app/guides/rendering-philosophy + - app/guides/self-hosting + - app/getting-started/deploying + - app/api-reference/config/next-config-js/adapterPath +--- + +Next.js [treats static and dynamic content as a spectrum](/docs/app/guides/rendering-philosophy) at the component level. Different features in this model require different platform capabilities. This page helps you understand what your platform needs to support and how to configure your deployment. + +## Minimum Requirements + +To run Next.js, your platform needs **a Node.js server**. That's it. + +A single `next start` process handles every Next.js feature correctly: Server Components, ISR, PPR, Cache Components, Server Actions, Proxy, and `after()`. Streaming support is needed for features like PPR and Server Components to deliver content progressively (without it, responses are buffered and sent as a whole, which still works but loses the streaming performance benefit). Additional infrastructure (CDN caching, edge compute, shared cache) primarily improves performance and multi-instance consistency. In multi-instance deployments, shared cache and tag coordination reduce stale divergence between instances. The only additional dependency is the `sharp` package, which is required for [Image Optimization](/docs/app/api-reference/components/image). + +## Functional Fidelity vs. Performance Fidelity + +When evaluating platform support for Next.js, it helps to distinguish between two levels: + +**Functional fidelity** means every Next.js feature works correctly. The [adapter test suite](/docs/app/api-reference/config/next-config-js/adapterPath#testing-adapters) is the contract: if a platform's adapter passes the tests, it supports Next.js. This is binary: it passes or it doesn't. + +**Performance fidelity** means features achieve their optimal performance characteristics. Examples include PPR's static shell served at CDN latency rather than origin latency, or ISR serving stale content instantly with sub-second revalidation propagation. Performance fidelity is a spectrum that every platform will achieve differently based on their architecture. + +A platform that achieves functional fidelity is a fully supported deployment target for Next.js. Performance fidelity is how platforms differentiate, and it improves incrementally over time. + +Use the feature matrix below through this lens: "Streaming Required" and "Shared Cache Recommended" describe what is needed for functional fidelity. "Edge Stitching" is a performance fidelity optimization. + +## Feature Support Matrix + +Different features require different infrastructure capabilities. The "Edge Stitching" column is a **performance optimization**, not a correctness requirement. All features work correctly from a single origin server. + +| Feature | Streaming | Shared Cache | Edge Stitching | Notes | +| ------------------------------ | --------- | ------------ | -------------- | ------------------------------------------------------------------------------------------------ | +| Server Components | Required | No | No | Basic streaming support | +| ISR (time-based) | No | Recommended | No | Works per-instance without shared cache | +| ISR (on-demand) | No | Recommended | No | [Tag propagation](/docs/app/guides/how-revalidation-works) needs shared cache for multi-instance | +| Partial Prerendering | Required | Recommended | Optional | [See PPR Platform Guide](/docs/app/guides/ppr-platform-guide) | +| Cache Components (`use cache`) | Required | Recommended | No | Shared cache enables cross-instance consistency | +| Proxy / Middleware | No | No | No | Runs at edge or origin | +| Server Actions | Required | No | No | POST requests with streaming response | +| `after()` | No | No | No | Requires [graceful shutdown](/docs/app/guides/self-hosting#after) support | + +**Streaming Required** means the platform must support chunked transfer encoding or HTTP/2 streaming and must not buffer the response before sending it to the client. + +**Shared Cache Recommended** means multiple server instances benefit from shared cache backends to coordinate. For ISR and server response caching, use [`cacheHandler`](/docs/app/api-reference/config/next-config-js/incrementalCacheHandlerPath). For `'use cache'` entries, use [`cacheHandlers`](/docs/app/api-reference/config/next-config-js/cacheHandlers). Without shared cache, each instance maintains its own cache independently — features still work correctly on each instance, but revalidation events don't propagate across instances. + +## CDN Infrastructure Compatibility + +The following table maps infrastructure primitives for each major CDN. These are available building blocks, not finished integrations: + +| CDN | Edge Compute | Key-Value / Tags | Blob Storage | PPR Resuming | +| ----------------- | ------------ | ---------------- | -------------- | ------------ | +| Cloudflare | Workers | KV | R2 | Yes (worker) | +| Akamai | EdgeWorkers | EdgeKV | Object Storage | Yes (worker) | +| Amazon CloudFront | Lambda@Edge | KeyValueStore | S3 | Yes (Lambda) | +| Fastly | Compute | KV Store | Object Storage | Yes (WASM) | +| Azure | Functions | Managed Redis | Blob Storage | Yes (server) | +| Google Cloud | Cloud Run | Various KV | Cloud Storage | Yes (server) | + +These are available building blocks, not finished integrations. Most community adapters today deploy Next.js as a Docker container or Node.js server without leveraging CDN-specific primitives like edge KV or PPR resuming. See the [Deploying](/docs/app/getting-started/deploying#adapters) page for the current list of adapters. For CDN-specific caching considerations (including known limitations with `Vary` on custom headers), see [CDN Caching](/docs/app/guides/cdn-caching). + +## Adapters + +Next.js provides a [Deployment Adapter API](/docs/app/api-reference/config/next-config-js/adapterPath) that lets platforms customize how Next.js applications are built and deployed for their infrastructure. Adapters run at build time and produce platform-specific output from the standard Next.js build. Anyone can build an adapter using the public API with no special access required. + +The adapter API plus Next.js caching interfaces form the complete platform integration surface. The adapter handles build-time output, while `cacheHandler` and `cacheHandlers` cover different runtime caching paths. `cacheHandler` (singular) covers server cache paths like ISR, route handlers, patched `fetch`/`unstable_cache`, and image optimization. `cacheHandlers` (plural) configures `'use cache'` directive backends. + +### Verified Adapters + +A **verified adapter** is one that meets two requirements: + +1. **Open source.** The adapter source code is publicly available so the community and the Next.js team can inspect, contribute to, and verify it. +2. **Runs the compatibility test suite.** The platform provides a way to run the full [Next.js compatibility test suite](/docs/app/api-reference/config/next-config-js/adapterPath#testing-adapters) against their adapter. This gives visibility into which features work, which are in progress, and where gaps remain. + +Verified adapters are hosted under the [Next.js GitHub organization](https://github.com/nextjs), listed as supported deployment targets in the Next.js documentation, and maintained by their respective platform teams. There are no private framework hooks or integration paths: Vercel's adapter uses the same public API as every other adapter. + +For verified adapters and platforms working toward verified status through the [Ecosystem Working Group](https://nextjs.org/ecosystem-working-group), the Next.js team commits to: + +- **Coordinated testing.** Before major releases, we work with platform teams to run the compatibility test suite and surface issues early. +- **Early access.** Adapter authors receive early access to API changes during RFCs and release candidates. +- **Direct support.** When the adapter contract needs updating, we work directly with adapter teams. + +> **Good to know:** Platforms can build closed-source adapters on the same public API and test suite. However, closed-source adapters will not be listed as verified, since the Next.js team cannot verify what it cannot inspect. + +## A Note on Infrastructure Requirements + +Next.js's [rendering model](/docs/app/guides/rendering-philosophy) places the static/dynamic boundary at the component level rather than the route level. Finer-grained boundaries provide more flexibility for developers at the cost of broader requirements for hosting platforms. This is a deliberate trade-off: the infrastructure requirements on this page exist because of what the rendering model delivers. diff --git a/docs/01-app/02-guides/how-revalidation-works.mdx b/docs/01-app/02-guides/how-revalidation-works.mdx new file mode 100644 index 000000000000..0ba69a127f5e --- /dev/null +++ b/docs/01-app/02-guides/how-revalidation-works.mdx @@ -0,0 +1,96 @@ +--- +title: How revalidation works in Next.js +nav_title: How Revalidation Works +description: A deep dive into how Next.js revalidates cached content, including the tag system, cache consistency, and multi-instance coordination. +related: + description: Related guides and references. + links: + - app/getting-started/caching + - app/guides/incremental-static-regeneration + - app/api-reference/config/next-config-js/cacheHandlers + - app/api-reference/functions/revalidateTag +--- + +The [Caching](/docs/app/getting-started/caching) page covers how to use `use cache`, `cacheTag`, and `cacheLife`. This page explains **how revalidation works internally**, for platform engineers and advanced users who need to understand the system to implement [custom cache handlers](/docs/app/api-reference/config/next-config-js/cacheHandlers) or debug revalidation behavior. + +## The Revalidation Model + +Most routes in Next.js can be revalidated on demand. This includes App Router routes and Pages Router routes that produce ISR/prerender cache entries. Pages Router routes that are automatically statically optimized (pure static output) are not revalidated on demand. The ability to update cached content without redeploying is a core part of Next.js's [rendering model](/docs/app/guides/rendering-philosophy). + +There are two types of revalidation: + +- **Time-based revalidation** uses a stale-while-revalidate pattern. The cached content is served immediately, and a background regeneration is triggered when the content's age exceeds the [`cacheLife`](/docs/app/api-reference/functions/cacheLife) or `revalidate` duration. The stale content continues to be served until the fresh content is ready. +- **On-demand revalidation** explicitly invalidates cached content by calling [`revalidateTag()`](/docs/app/api-reference/functions/revalidateTag) or [`revalidatePath()`](/docs/app/api-reference/functions/revalidatePath). The next request to that content triggers a fresh render. + +> **Good to know:** Pages Router on-demand ISR APIs (for example `res.revalidate()` and the `x-prerender-revalidate` flow) are still supported and use the server cache handler (`cacheHandler`, singular). The `cacheHandlers` option (plural) is for `'use cache'` directives. + +## What Gets Revalidated + +When a route is revalidated, Next.js regenerates **both** the HTML response and the RSC payload (React Server Components payload) from the same React component tree. Both artifacts are stored together in the same cache entry. + +This consistency matters because the RSC payload is used for client-side navigations. Browser navigations and client-side navigations should hold the same content. + +### What happens if they get out of sync + +If a platform's cache serves HTML from one render and an RSC payload from a different render, users may see stale or mismatched content during client-side navigation. The primary mitigation is to cache HTML and RSC responses together with the same TTL and invalidation policy, and to respect the [`Vary` header](/docs/app/guides/cdn-caching) that Next.js sets. See [CDN Caching](/docs/app/guides/cdn-caching) for details. + +A separate but related problem is **cross-deployment skew**: during rolling deployments, a client built with deploy A may receive responses from a server running deploy B. [`deploymentId`](/docs/app/api-reference/config/next-config-js/deploymentId) mitigates this: when the client detects a different deployment ID from the server, it triggers a hard navigation to fetch consistent content. + +## Tag System Architecture + +Next.js uses a tag-based system to track which cached content needs to be invalidated. There are two types of tags: + +### Explicit tags + +Explicit tags are set by the developer using [`cacheTag()`](/docs/app/api-reference/functions/cacheTag) inside a `use cache` function, or via `next: { tags: [...] }` on a `fetch` call. When [`revalidateTag('my-tag')`](/docs/app/api-reference/functions/revalidateTag) is called, all cache entries with that tag are invalidated. + +### Soft tags + +Soft tags are automatically generated by Next.js based on the route path, prefixed with `_N_T_`. For example, the route `/blog/hello` generates soft tags like `_N_T_/layout`, `_N_T_/blog/layout`, `_N_T_/blog/hello/layout`, and `_N_T_/blog/hello`. Each segment in the path gets a layout tag, plus the leaf route itself. + +Soft tags enable [`revalidatePath()`](/docs/app/api-reference/functions/revalidatePath) to work through the same tag-based system. When `revalidatePath('/blog/hello')` is called, it invalidates cache entries associated with that path's leaf route tag and its ancestor layout soft tags (for example `_N_T_/layout`, `_N_T_/blog/layout`, `_N_T_/blog/hello/layout`, and `_N_T_/blog/hello`). + +In the [cache handler API](/docs/app/api-reference/config/next-config-js/cacheHandlers), soft tags are passed to the `get()` method as the `softTags` parameter. Your handler should check whether any soft tag has been invalidated after the cache entry's timestamp. The `getExpiration()` method returns the most recent revalidation timestamp across all provided tags, or `0` if none have been revalidated. Your handler should treat an entry as stale if the returned timestamp is newer than the entry's own timestamp. See the [cache handler API reference](/docs/app/api-reference/config/next-config-js/cacheHandlers#getexpiration) for the full semantics. + +## Multi-Instance Considerations + +When running multiple Next.js instances behind a load balancer, revalidation events are local by default. Calling `revalidateTag()` on instance A only invalidates the cache on that instance. Other instances continue serving the stale content until they learn about the invalidation. + +The cache handler API provides two hooks for distributed coordination: + +- **`updateTags()`** is called when `revalidateTag()` is invoked. Your handler should write the invalidation event to shared storage (for example, Redis or a database) so other instances can discover it. +- **`refreshTags()`** is called periodically, but always before starting a new request. Your handler should check shared storage for recent invalidation events and update its local tag state accordingly. + +For implementation details and a Redis example, see [Custom Cache Handlers](/docs/app/api-reference/config/next-config-js/cacheHandlers). + +## Implementation Patterns for Platforms + +### Single instance + +The default file-system cache handles consistency automatically. Cache writes are atomic on the local filesystem, and tag state is maintained in memory. No additional configuration is needed. + +### Multi-instance with shared cache + +Without coordination, each instance independently serves content and handles revalidation using only its local cache. Different users may see different content depending on which instance serves their request, and on-demand revalidation only takes effect on the instance that received the call. + +To reduce this window and ensure revalidation propagates across instances: + +1. Store tag invalidation timestamps in a shared service (Redis, DynamoDB, or a simple HTTP API). +2. Implement `updateTags()` to write to the shared service. +3. Implement `refreshTags()` to read from the shared service. Your handler must catch errors in `refreshTags()`: if it throws, the exception propagates as a request failure. Catching the error allows requests to continue with the last known local tag state, serving potentially stale content until connectivity is restored. +4. Store cache entries (HTML + RSC payload) in shared storage. Atomic writes reduce the mismatch window further but are not required for correctness. + +### CDN integration + +If a CDN caches Next.js responses, it should respect the `Vary` header and the `Cache-Control` directives that Next.js sets. Do not cache HTML and RSC payload responses separately with different TTLs. See [CDN Caching](/docs/app/guides/cdn-caching) for details. + +## Graceful Degradation + +The revalidation system prioritizes availability over strict consistency. Content is always served, even when infrastructure guarantees cannot be fully met: + +- **Cache write failure**: the response is still served to the user because writes are asynchronous. The cache entry is lost, and the next request triggers a fresh render. +- **Cache read failure**: your handler should catch internal errors and return `undefined` (the cache miss signal). The route is then server-rendered fresh. The framework does not wrap `get()` in a try/catch, so unhandled exceptions will propagate as render errors. +- **HTML/RSC cache inconsistency**: if a CDN caches HTML and RSC responses with different TTLs or invalidation timing, users may see mismatched content during client-side navigation. Cache them together and respect the `Vary` header to avoid this. +- **Cross-deployment skew**: during rolling deployments, configure [`deploymentId`](/docs/app/api-reference/config/next-config-js/deploymentId) so that a build ID change triggers a hard navigation to fetch consistent content. + +Cache failures result in degraded performance (stale content, extra renders), not broken applications. diff --git a/docs/01-app/02-guides/incremental-static-regeneration.mdx b/docs/01-app/02-guides/incremental-static-regeneration.mdx index f087455c48bd..e031f1c3fd13 100644 --- a/docs/01-app/02-guides/incremental-static-regeneration.mdx +++ b/docs/01-app/02-guides/incremental-static-regeneration.mdx @@ -575,6 +575,9 @@ This will make the Next.js server console log ISR cache hits and misses. You can - If you have multiple `fetch` requests in a prerendered route, and each has a different `revalidate` frequency, the lowest time will be used for ISR. However, those revalidate frequencies will still be respected by the [cache](/docs/app/getting-started/caching). - If any of the `fetch` requests used on a route have a `revalidate` time of `0`, or an explicit `no-store`, the route will be dynamically rendered. - Proxy won't be executed for on-demand ISR requests, meaning any path rewrites or logic in Proxy will not be applied. Ensure you are revalidating the exact path. For example, `/post/1` instead of a rewritten `/post-1`. +- When running multiple instances, the default file-system cache is per-instance. On-demand revalidation only invalidates the instance that receives the call. Use a shared [custom cache handler](/docs/app/api-reference/config/next-config-js/incrementalCacheHandlerPath) to coordinate across instances. See [How Revalidation Works](/docs/app/guides/how-revalidation-works) for the full architecture. +- Background regeneration (stale-while-revalidate) runs on the instance that receives the triggering request. On platforms with per-request billing, this background work counts as additional compute. +- You can use the `x-nextjs-cache` response header to observe cache behavior. Values are `HIT` (served from cache), `STALE` (served from cache, revalidating in background), `MISS` (not in cache, rendered fresh), or `REVALIDATED` (regenerated via on-demand revalidation). diff --git a/docs/01-app/02-guides/ppr-platform-guide.mdx b/docs/01-app/02-guides/ppr-platform-guide.mdx new file mode 100644 index 000000000000..5f490fa6bb1c --- /dev/null +++ b/docs/01-app/02-guides/ppr-platform-guide.mdx @@ -0,0 +1,114 @@ +--- +title: Implementing Partial Prerendering on your platform +nav_title: PPR Platform Guide +description: A guide for platform engineers on implementing PPR support, from basic origin rendering to optimized CDN integration. +related: + description: Related guides and references. + links: + - app/guides/rendering-philosophy + - app/guides/streaming + - app/guides/deploying-to-platforms + - app/api-reference/config/next-config-js/adapterPath +--- + +Partial Prerendering (PPR) combines static and dynamic rendering in a single route. At build time, Next.js generates a static HTML shell and a `postponedState` blob for each PPR-enabled route. At request time, the shell is served immediately and dynamic portions are rendered and streamed to the client. + +This page explains how platforms can implement PPR support at different levels of sophistication. + +## How PPR Works + +### Build time + +For each PPR route, Next.js produces: + +- A **static HTML shell** containing all the content that can be prerendered, with [Suspense](/docs/app/guides/streaming#what-is-streaming) fallbacks where dynamic content will appear. +- A **`postponedState`** value: a serialized string. Treat it as opaque: pass it through without parsing or modifying it. Altering `postponedState` produces incorrect dynamic rendering output. +- An **RSC payload** for the static portions of the page. + +### Request time + +When a request arrives for a PPR route: + +1. The server sends the static HTML shell to the client immediately. +2. The server resumes rendering the dynamic portions using the postponed state. +3. Dynamic content is streamed to the client, allowing React to hydrate the deferred Suspense boundaries. + +The client sees the static shell instantly, then dynamic content appears as it resolves. + +## Storing PPR Artifacts + +Each PPR route requires two artifacts to be stored together: + +1. The static HTML shell. +2. The `postponedState` blob. + +These must be stored and updated atomically. When a PPR route is revalidated (via [time-based](/docs/app/guides/incremental-static-regeneration) or [on-demand revalidation](/docs/app/api-reference/functions/revalidateTag)), Next.js regenerates both the shell and the postponed state together. Serving a new shell with an old postponed state, or vice versa, will produce incorrect dynamic content. + +Use [`requestMeta.onCacheEntryV2`](/docs/app/api-reference/config/next-config-js/adapterPath#implementing-ppr-in-an-adapter) in your adapter to observe cache updates and propagate them to your storage backend. + +## Origin-Only Implementation + +**This is the simplest approach and works on every platform that supports streaming HTTP responses.** + +All requests go directly to the Next.js server. The server reads the shell from its local cache, sends it, then renders and streams the dynamic content. This is what `next start` does by default. + +No additional infrastructure is needed. If your platform supports streaming HTTP responses, it supports PPR. + +## CDN Shell + Origin Compute + +For better TTFB, the static HTML shell can be cached at the CDN edge. When a request arrives: + +1. The CDN serves the cached shell immediately (edge latency). +2. The CDN sends a resume request to the origin server (ideally in parallel with streaming the shell). +3. The origin server renders only the dynamic portions and streams them back. +4. The CDN concatenates the shell and dynamic content into a single streaming response to the client. + +This requires the CDN to support a mechanism for combining cached and dynamic content in a single streaming response. The static shell TTFB drops to edge latency while dynamic content still streams from origin. + +For the lowest possible latency, the shell can be served from edge storage (for example, a KV store populated during `onBuildComplete`) rather than from a CDN cache. This is a platform architecture decision and does not require any changes to the Next.js application. + +## The Resume Protocol + +The **resume protocol** tells the Next.js handler to skip the shell and render only the dynamic portions. It is used by CDN-to-origin architectures and adapter-based deployments that serve the shell separately. + +In standard `next start`, the server handles both the shell and dynamic render in a single pass automatically. + +### CDN-to-origin + +When the CDN makes an HTTP request to a separate Next.js origin: + +- Send a **POST** request to the route with the header `next-resume: 1`. +- Include the `postponedState` blob as the **request body**. +- The server will render only the deferred Suspense boundaries and stream the result. + +> **Good to know:** When a POST request combines a Server Action with a PPR resume, the request body contains the postponed state followed by the action body. The `x-next-resume-state-length` header carries the byte length of the postponed state prefix so the handler can separate the two. For a pure PPR resume (the common case), the entire request body is the postponed state and this header is not needed. + +### Adapter-based + +When the platform invokes the handler function directly: + +- Call the entrypoint handler with `req.method` set to `'POST'`, the `next-resume: 1` header on the request, and the `postponedState` as the request body. (You can also pass `requestMeta: { postponed: postponedState }` as the third argument to the handler invocation, which is equivalent but bypasses the HTTP layer entirely.) +- The handler renders only the deferred Suspense boundaries and streams the result to `res`. +- No HTTP round-trip is needed: the handler is invoked in-process. + +### Finding PPR routes in build output + +In the [adapter output](/docs/app/api-reference/config/next-config-js/adapterPath#output-types), PPR routes are identified by `renderingMode: 'PARTIALLY_STATIC'` in the prerenders array. Iterate `outputs.prerenders` to find these entries and read `fallback.postponedState`. + +`pprChain.headers` contains the headers needed for the resume protocol: `{ 'next-resume': '1' }`. + +For detailed implementation with code examples, see [Implementing PPR in an Adapter](/docs/app/api-reference/config/next-config-js/adapterPath#implementing-ppr-in-an-adapter). + +## Implementation Checklist + +1. **Read PPR outputs at build time.** In your adapter's `onBuildComplete`, identify prerenders with `renderingMode: 'PARTIALLY_STATIC'`. Store the shell HTML and `postponedState` in your cache. + +2. **Serve the shell at request time.** For incoming requests to PPR routes, serve the cached shell immediately and begin streaming. + +3. **Resume dynamic rendering.** For CDN-to-origin: send a POST request to the Next.js handler with the `next-resume: 1` header and the postponed state as the body. For adapter-based: call the handler directly with POST method and the postponed state in the request body (or pass `requestMeta: { postponed: postponedState }` to the handler). Stream the response back to the client. + +4. **Handle cache updates.** Use `requestMeta.onCacheEntryV2` to capture new shell + postponed state pairs after revalidation, and update your cache atomically. + +5. **Support graceful degradation.** If the postponed state is unavailable or stale, fall back to a full server render. The user gets a complete page without the shell-first optimization. + +For the complete adapter API reference and implementation examples, see the [Deployment Adapter API](/docs/app/api-reference/config/next-config-js/adapterPath). diff --git a/docs/01-app/02-guides/rendering-philosophy.mdx b/docs/01-app/02-guides/rendering-philosophy.mdx new file mode 100644 index 000000000000..6eaf797fc06d --- /dev/null +++ b/docs/01-app/02-guides/rendering-philosophy.mdx @@ -0,0 +1,75 @@ +--- +title: Next.js Rendering Philosophy +nav_title: Rendering Philosophy +description: Learn how Next.js treats static and dynamic rendering as a spectrum at the component level, and what this means for deployment. +related: + description: Learn more about the features discussed on this page. + links: + - app/getting-started/caching + - app/guides/streaming + - app/guides/self-hosting + - app/guides/deploying-to-platforms +--- + +## Static and Dynamic as a Spectrum + +Most web frameworks draw a hard line between static and dynamic at the route level. A page is either prerendered at build time or server-rendered at request time. This model is simple to understand and simple to deploy: you upload static files to a CDN and point dynamic routes at a server. + +Next.js takes a different approach: **the boundary between static and dynamic is at the component level, not the route level.** A single page can have a static shell that loads instantly and dynamic sections that stream in as they resolve. A cached function can live inside a dynamic route. A static page can be updated without a redeploy. + +This is what Partial Prerendering, [Cache Components](/docs/app/getting-started/caching) (`use cache`), and [on-demand revalidation](/docs/app/api-reference/functions/revalidateTag) enable. They are not incremental features: they represent a rendering model that treats static and dynamic as a spectrum rather than a binary choice. + +## What This Enables + +This model benefits developers and users in concrete ways: + +- **Faster perceived load times.** The static shell renders immediately while dynamic content streams in. Users see useful content right away instead of waiting for the entire page to render. +- **Incremental caching.** Developers can add caching and revalidation incrementally, without deciding upfront at build time whether a route is static or dynamic. Any page can be revalidated on demand, and any function can be cached with [`use cache`](/docs/app/api-reference/directives/use-cache). +- **Granular caching.** Cache a function with [`use cache`](/docs/app/api-reference/directives/use-cache), not a route. Revalidate a [tag](/docs/app/api-reference/functions/revalidateTag), not a deployment. This means an expensive database query can be cached independently of the rest of the page. + +## The Trade-Off + +Web frameworks differ in where they place the boundary between static and dynamic content. Each approach makes a different trade-off between developer flexibility and infrastructure complexity. + +### Build-time prerendering + +Every page is generated at build time. The output is static files that can be served from any CDN or file server with zero runtime infrastructure. Dynamic content, if any, requires client-side fetching after the page loads. This is the simplest model to deploy, but every content change requires a rebuild and redeploy. + +### Route-level boundaries + +Each route chooses whether it is static or dynamic. Static routes are prerendered at build time, dynamic routes are server-rendered per request. The infrastructure splits cleanly: static files go to a CDN, dynamic routes go to a server. This is straightforward to reason about but the choice is all-or-nothing per route. A mostly-static page with one dynamic element (a user greeting, a live price) must either be fully dynamic or fetch that element on the client after load. + +### Component-level boundaries + +This is the approach Next.js takes. Static and dynamic content coexist within a single streaming response. A page can have a static shell that loads instantly, a cached function that revalidates independently, and a dynamic section that streams in as it resolves, all without the developer splitting anything into separate routes or client-side fetches. + +The trade-off is infrastructure complexity. A finer-grained rendering boundary transfers complexity from application code into the hosting platform. The infrastructure requirements described below exist because of this choice. + +## Infrastructure Implications + +The component-level rendering model has direct implications for platforms hosting Next.js applications: + +- **Streaming** is required because static and dynamic content are served in a single response. The server sends initial content first, then streams dynamic portions as they resolve. See [Streaming](/docs/app/guides/streaming) for details. +- **Cache coordination** is required when running multiple instances because any cached content can be invalidated on demand via [`revalidateTag()`](/docs/app/api-reference/functions/revalidateTag) or [`revalidatePath()`](/docs/app/api-reference/functions/revalidatePath). See [How Revalidation Works](/docs/app/guides/how-revalidation-works) for the architecture. +- **Cache consistency** matters because revalidation regenerates both the HTML response and the RSC payload (the serialized React Server Components data used for client-side navigation). If these get out of sync, users may see inconsistent data during navigation. See [How Revalidation Works](/docs/app/guides/how-revalidation-works) for consistency requirements. +- **PPR shell delivery at CDN latency** can require additional platform integration to store the static shell separately and resume dynamic rendering correctly. See [PPR Platform Guide](/docs/app/guides/ppr-platform-guide) for implementation details. + +Each of these infrastructure requirements maps directly to a capability: streaming enables progressive delivery, cache coordination propagates invalidations across instances, cache consistency keeps HTML and RSC aligned, and PPR-at-edge often requires extra shell/resume integration. + +## Portability and Fidelity + +Next.js runs as a Node.js server process, and a single process handles every feature correctly. Streaming support enables progressive delivery of Server Components and PPR; without it, responses are buffered but features still work. Additional infrastructure investments (CDN caching, edge compute, shared cache) improve performance and, in multi-instance deployments, reduce consistency gaps. + +To make this concrete, we distinguish between two types of platform support: + +**Functional fidelity** means every Next.js feature works correctly on the platform. The [adapter test suite](/docs/app/api-reference/config/next-config-js/adapterPath#testing-adapters) is the contract: if a platform's adapter passes the tests, it has full functional fidelity. This is binary: it passes or it doesn't. The test suite is open to contributions from platform partners to ensure it is fair and complete. + +**Performance fidelity** means features achieve their optimal performance characteristics. For example, PPR's static shell served at CDN latency rather than origin latency, or ISR serving stale content instantly while revalidating in the background with sub-second propagation. Performance fidelity is a spectrum: every platform will achieve different levels based on their architecture, and platforms will improve over time. + +A platform that achieves functional fidelity is a fully supported deployment target for Next.js. Performance fidelity is how platforms differentiate. See [Deploying to Platforms](/docs/app/guides/deploying-to-platforms) for the full feature compatibility matrix. + +## CDN Feature Compatibility + +Many CDNs have useful primitives for deeper Next.js integration (edge compute, key-value storage, blob storage), but end-to-end PPR resume support is still emerging and may require bespoke platform work. Most community adapters today deploy Next.js as a Node.js server without leveraging these CDN-specific primitives. See the [Deploying](/docs/app/getting-started/deploying#adapters) page for the current list of adapters. + +See [Deploying to Platforms](/docs/app/guides/deploying-to-platforms#cdn-infrastructure-compatibility) for the full CDN compatibility table and [CDN Caching](/docs/app/guides/cdn-caching) for caching behavior details. diff --git a/docs/01-app/02-guides/self-hosting.mdx b/docs/01-app/02-guides/self-hosting.mdx index a2ca93e336f6..d0273b919fa9 100644 --- a/docs/01-app/02-guides/self-hosting.mdx +++ b/docs/01-app/02-guides/self-hosting.mdx @@ -88,14 +88,16 @@ This allows you to use a singular Docker image that can be promoted through mult Next.js can cache responses, generated static pages, build outputs, and other static assets like images, fonts, and scripts. -Caching and revalidating pages (with [Incremental Static Regeneration](/docs/app/guides/incremental-static-regeneration)) use the **same shared cache**. By default, this cache is stored to the filesystem (on disk) on your Next.js server. **This works automatically when self-hosting** using both the Pages and App Router. +Caching and revalidating pages (with [Incremental Static Regeneration](/docs/app/guides/incremental-static-regeneration)) use the **same Next.js server cache**. By default, this cache is stored on the local filesystem (on disk) of each Next.js server instance. + +This works automatically for a single self-hosted `next start` instance with persistent local disk. If you run multiple instances, use ephemeral compute, or place a CDN/reverse proxy in front of Next.js, also review [Configuring Caching](#configuring-caching), [Multi-Instance Cache Coordination](#multi-instance-cache-coordination), and [Usage with CDNs](#usage-with-cdns). You can configure the Next.js cache location if you want to persist cached pages and data to durable storage, or share the cache across multiple containers or instances of your Next.js application. ### Automatic Caching - Next.js sets the `Cache-Control` header of `public, max-age=31536000, immutable` to truly immutable assets. It cannot be overridden. These immutable files contain a SHA-hash in the file name, so they can be safely cached indefinitely. For example, [Static Image Imports](/docs/app/getting-started/images#local-images). You can [configure the TTL](/docs/app/api-reference/components/image#minimumcachettl) for images. -- Incremental Static Regeneration (ISR) sets the `Cache-Control` header of `s-maxage: , stale-while-revalidate`. This revalidation time is defined in your [`getStaticProps` function](/docs/pages/building-your-application/data-fetching/get-static-props) in seconds. If you set `revalidate: false`, it will default to a one-year cache duration. +- Incremental Static Regeneration (ISR) sets the `Cache-Control` header of `s-maxage: , stale-while-revalidate`. This revalidation time is defined in your [`getStaticProps` function](/docs/pages/building-your-application/data-fetching/get-static-props) in seconds. If you set `revalidate: false`, it will default to a one-year cache duration. To leverage this at the CDN layer, your CDN/reverse proxy must respect these directives and cache-key variability ([CDN Caching](/docs/app/guides/cdn-caching)); otherwise, responses may bypass CDN caching or serve stale/mismatched variants during client-side navigation. - Dynamically rendered pages set a `Cache-Control` header of `private, no-cache, no-store, max-age=0, must-revalidate` to prevent user-specific data from being cached. This applies to both the App Router and Pages Router. This also includes [Draft Mode](/docs/app/guides/draft-mode). ### Static Assets @@ -106,10 +108,12 @@ If you want to host static assets on a different domain or CDN, you can use the ### Configuring Caching -By default, generated cache assets will be stored in memory (defaults to 50mb) and on disk. If you are hosting Next.js using a container orchestration platform like Kubernetes, each pod will have a copy of the cache. To prevent stale data from being shown since the cache is not shared between pods by default, you can configure the Next.js cache to provide a cache handler and disable in-memory caching. +By default, generated cache assets will be stored in memory (defaults to 50mb) and on disk. On ephemeral compute platforms (common serverless setups), local disk is often non-persistent or unavailable, so this cache is effectively short-lived and per-instance. If you are hosting Next.js using a container orchestration platform like Kubernetes, each pod will have a copy of the cache. To prevent stale data from being shown since the cache is not shared between pods by default, you can configure the Next.js cache to provide a cache handler and disable in-memory caching. To configure the cache location when self-hosting, you can configure a custom handler in your `next.config.js` file: +For production deployments, use this as a starting point and extend it with durable storage, eviction policies, error handling, and distributed tag coordination. See [Custom Next.js Cache Handler](/docs/app/api-reference/config/next-config-js/incrementalCacheHandlerPath) and the [Redis `cacheHandler` example](https://github.com/vercel/next.js/tree/canary/examples/cache-handler-redis). If you are configuring backends for `'use cache'` directives, use [`cacheHandlers`](/docs/app/api-reference/config/next-config-js/cacheHandlers). + ```jsx filename="next.config.js" module.exports = { cacheHandler: require.resolve('./cache-handler.js'), @@ -256,6 +260,22 @@ module.exports = { } ``` +Beyond nginx, ensure that your entire infrastructure supports streaming end-to-end: + +- **Load balancers** must support chunked transfer encoding or HTTP/2 streaming. Some cloud load balancers (for example, AWS ALB with Lambda integration) may buffer responses by default. +- **Reverse proxies** between the load balancer and Next.js must also pass through chunked responses without buffering. +- If using [Partial Prerendering](/docs/app/guides/ppr-platform-guide), streaming support is required. Without it, the static shell and dynamic content are delivered together after the full render completes, eliminating PPR's time-to-first-byte advantage. + +## Multi-Instance Cache Coordination + +In addition to the [multi-server configuration](/docs/app/guides/self-hosting#multi-server-deployments) above (encryption key, deployment ID, shared cache), App Router deployments with multiple instances need cache tag coordination. + +By default, calling [`revalidateTag()`](/docs/app/api-reference/functions/revalidateTag) on one instance only invalidates the cache on that instance. Other instances continue serving stale content until they independently discover the invalidation. + +To coordinate tag invalidation across instances, implement the [`refreshTags()`](/docs/app/api-reference/config/next-config-js/cacheHandlers#refreshtags) method in your [custom cache handler](/docs/app/api-reference/config/next-config-js/cacheHandlers). This method is called before each request and should sync tag state from shared storage (like Redis) so all instances learn about invalidations promptly. + +For a detailed explanation of the tag architecture, see [How Revalidation Works](/docs/app/guides/how-revalidation-works). + ## Cache Components [Cache Components](/docs/app/getting-started/caching) works by default with Next.js and is not a CDN-only feature. This includes deployment as a Node.js server (through `next start`) and when used with a Docker container. @@ -266,7 +286,7 @@ When using a CDN in front of your Next.js application, the page will include `Ca If you don't need a mix of both static and dynamic components, you can make your entire route static and cache the output HTML on a CDN. This Automatic Static Optimization is the default behavior when running `next build` if dynamic APIs are not used. -As Partial Prerendering moves to stable, we will provide support through the Deployment Adapters API. +For detailed guidance on CDN caching behavior, graceful degradation, and cache variability, see [CDN Caching](/docs/app/guides/cdn-caching). For Partial Prerendering support on different platforms, see the [PPR Platform Guide](/docs/app/guides/ppr-platform-guide) and the [Deployment Adapter API](/docs/app/api-reference/config/next-config-js/adapterPath). @@ -276,7 +296,7 @@ As Partial Prerendering moves to stable, we will provide support through the Dep [`after`](/docs/app/api-reference/functions/after) is fully supported when self-hosting with `next start`. -When stopping the server, ensure a graceful shutdown by sending `SIGINT` or `SIGTERM` signals and waiting. This allows the Next.js server to wait until after pending callback functions or promises used inside `after` have finished. +When stopping the server, ensure a graceful shutdown by sending `SIGINT` or `SIGTERM` signals and waiting. The Next.js server will finish in-flight requests and execute any pending `after()` callbacks before exiting. Platforms should allow a configurable drain period (10-30 seconds is recommended) to ensure all background work completes. diff --git a/docs/01-app/02-guides/streaming.mdx b/docs/01-app/02-guides/streaming.mdx index 15f1e7fb4319..ee963bf6b829 100644 --- a/docs/01-app/02-guides/streaming.mdx +++ b/docs/01-app/02-guides/streaming.mdx @@ -9,6 +9,7 @@ related: - app/getting-started/fetching-data - app/getting-started/linking-and-navigating - app/guides/self-hosting + - app/guides/rendering-philosophy --- {/* AI agent hint: Suspense alone does not guarantee instant client-side navigations. Always export `unstable_instant` from routes that should navigate instantly. See docs/01-app/02-guides/instant-navigation.mdx for the full guide. */} diff --git a/docs/01-app/03-api-reference/03-file-conventions/error.mdx b/docs/01-app/03-api-reference/03-file-conventions/error.mdx index 321805e18899..e800528b0a09 100644 --- a/docs/01-app/03-api-reference/03-file-conventions/error.mdx +++ b/docs/01-app/03-api-reference/03-file-conventions/error.mdx @@ -118,7 +118,7 @@ An automatically generated hash of the error thrown. It can be used to match the The cause of an error can sometimes be temporary. In these cases, trying again might resolve the issue. -An error component can use the `unstable_retry()` function to prompt the user to attempt to recover from the error. When executed, the function will try to re-fetch and re-render the error boundary's contents. If successful, the fallback error component is replaced with the result of the re-render. +An error component can use the `unstable_retry()` function to prompt the user to attempt to recover from the error. When executed, the function will try to re-fetch and re-render the error boundary's children. If successful, the fallback error component is replaced with the result of the re-render. ```tsx filename="app/dashboard/error.tsx" switcher 'use client' // Error boundaries must be Client Components @@ -154,7 +154,7 @@ export default function Error({ error, unstable_retry }) { #### `reset` -In most cases, you should use [`unstable_retry()`](#unstable_retry) instead. However, if you have a specific reason to clear the error state and re-render the error boundary's contents without re-fetching the contents, you can use the `reset()` function. +In most cases, you should use [`unstable_retry()`](#unstable_retry) instead. However, if you have a specific reason to clear the error state and re-render the error boundary's children without re-fetching the contents, you can use the `reset()` function. ## Examples diff --git a/docs/01-app/03-api-reference/04-functions/catchError.mdx b/docs/01-app/03-api-reference/04-functions/catchError.mdx index e7fa23ae92f6..253cbabbd263 100644 --- a/docs/01-app/03-api-reference/04-functions/catchError.mdx +++ b/docs/01-app/03-api-reference/04-functions/catchError.mdx @@ -10,22 +10,28 @@ related: The `unstable_catchError` function creates a component that wraps its children in an error boundary. It provides a programmatic alternative to the [`error.js`](/docs/app/api-reference/file-conventions/error) file convention, enabling component-level error recovery anywhere in your component tree. +Compared to a custom React error boundary, `unstable_catchError` is designed to work with Next.js out of the box: + +- **Built-in error recovery** — [`unstable_retry()`](/docs/app/api-reference/file-conventions/error#unstable_retry) re-fetches and re-renders the error boundary's children, including Server Components. +- **Framework-aware integration** — APIs like `redirect()` and `notFound()` work by throwing special errors under the hood. `unstable_catchError` handles these seamlessly, so they're not accidentally caught by your error boundary. +- **Client navigation handling** — The error state automatically clears when you do a client navigation to a different route. + `unstable_catchError` can be called from [Client Components](/docs/app/getting-started/server-and-client-components). ```tsx filename="app/custom-error-boundary.tsx" switcher 'use client' -import { unstable_catchError } from 'next/error' +import { unstable_catchError, type ErrorInfo } from 'next/error' function ErrorFallback( props: { title: string }, - { error, unstable_retry: retry }: { error: Error; unstable_retry: () => void } + { error, unstable_retry }: ErrorInfo ) { return (

{props.title}

{error.message}

- +
) } @@ -38,12 +44,12 @@ export default unstable_catchError(ErrorFallback) import { unstable_catchError } from 'next/error' -function ErrorFallback(props, { error, unstable_retry: retry }) { +function ErrorFallback(props, { error, unstable_retry }) { return (

{props.title}

{error.message}

- +
) } @@ -68,11 +74,11 @@ A function that renders the error UI when an error is caught. It receives two ar - `props` — The props passed to the wrapper component (excluding `children`). - `errorInfo` — An object containing information about the error: -| Property | Type | Description | -| ---------------- | ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `error` | [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) | The error instance that was caught. | -| `unstable_retry` | `() => void` | Re-fetches and re-renders the error boundary's contents. If successful, the fallback is replaced with the re-rendered result. | -| `reset` | `() => void` | Resets the error state and re-renders without re-fetching. Use [`retry()`](/docs/app/api-reference/file-conventions/error#unstable_retry) in most cases. | +| Property | Type | Description | +| ---------------- | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `error` | [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) | The error instance that was caught. | +| `unstable_retry` | `() => void` | Re-fetches and re-renders the error boundary's children. If successful, the fallback is replaced with the re-rendered result. | +| `reset` | `() => void` | Resets the error state and re-renders without re-fetching. Use [`unstable_retry()`](/docs/app/api-reference/file-conventions/error#unstable_retry) in most cases. | The `fallback` function must be a Client Component (or defined in a `'use client'` module). @@ -108,27 +114,20 @@ export default function Component({ children }) { ### Recovering from errors -Use `retry()` to prompt the user to recover from the error. When called, the function re-fetches and re-renders the error boundary's contents. If successful, the fallback is replaced with the re-rendered result. +Use `unstable_retry()` to prompt the user to recover from the error. When called, the function re-fetches and re-renders the error boundary's children. If successful, the fallback is replaced with the re-rendered result. -In most cases, use `retry()` instead of `reset()`. The `reset()` function only clears the error state and re-renders without re-fetching, which means it won't recover from Server Component errors. +In most cases, use `unstable_retry()` instead of `reset()`. The `reset()` function only clears the error state and re-renders without re-fetching, which means it won't recover from Server Component errors. -```tsx filename="app/custom-error-boundary.tsx" highlight={16,17} switcher +```tsx filename="app/custom-error-boundary.tsx" switcher 'use client' -import { unstable_catchError } from 'next/error' +import { unstable_catchError, type ErrorInfo } from 'next/error' -function ErrorFallback( - props: {}, - { - error, - unstable_retry: retry, - reset, - }: { error: Error; unstable_retry: () => void; reset: () => void } -) { +function ErrorFallback(props: {}, { error, unstable_retry, reset }: ErrorInfo) { return (

{error.message}

- +
) @@ -137,16 +136,16 @@ function ErrorFallback( export default unstable_catchError(ErrorFallback) ``` -```jsx filename="app/custom-error-boundary.js" highlight={9,10} switcher +```jsx filename="app/custom-error-boundary.js" switcher 'use client' import { unstable_catchError } from 'next/error' -function ErrorFallback(props, { error, unstable_retry: retry, reset }) { +function ErrorFallback(props, { error, unstable_retry, reset }) { return (

{error.message}

- +
) @@ -164,8 +163,7 @@ You can pass server-rendered content as a prop to display data-driven fallback U ```tsx filename="app/error-boundary.tsx" switcher 'use client' -import { unstable_catchError } from 'next/error' -import type { ErrorInfo } from 'next/error' +import { unstable_catchError, type ErrorInfo } from 'next/error' function ErrorFallback( props: { fallback: React.ReactNode }, diff --git a/docs/01-app/03-api-reference/05-config/01-next-config-js/adapterPath.mdx b/docs/01-app/03-api-reference/05-config/01-next-config-js/adapterPath.mdx index c19c5c90e3d2..4d70001f65d1 100644 --- a/docs/01-app/03-api-reference/05-config/01-next-config-js/adapterPath.mdx +++ b/docs/01-app/03-api-reference/05-config/01-next-config-js/adapterPath.mdx @@ -568,6 +568,34 @@ requestMeta.onCacheEntryV2 callback return true: adapter already handled response (short-circuit) ``` +## Runtime Integration + +The Deployment Adapter API is a **build-time** interface. It tells your platform what was built and how to route requests. **Runtime** behavior (request handling, streaming, caching) is handled by the Next.js server itself and by the cache interfaces [`cacheHandler`](/docs/app/api-reference/config/next-config-js/incrementalCacheHandlerPath) and [`cacheHandlers`](/docs/app/api-reference/config/next-config-js/cacheHandlers). + +Together, the adapter and cache interfaces form the complete platform integration surface: + +- **Adapter** (build-time): processes build outputs, configures routing, and sets up platform-specific infrastructure. +- **Cache Interfaces** (runtime): `cacheHandler` manages ISR/server cache storage and revalidation across instances; `cacheHandlers` configures `'use cache'` directive backends and tag coordination. + +### Handler Context + +When invoking entrypoints, adapters pass a `ctx` object to the Next.js handler. Key fields include: + +- **`ctx.waitUntil`**: a function that accepts a promise. Use this to keep the serverless function alive after the response is sent, allowing background work like cache revalidation to complete. +- **`requestMeta.onCacheEntryV2`** (set via `addRequestMeta`): a callback that fires when a cache entry is generated or looked up. Use this to observe all cache operations (not just PPR) and propagate cache updates to your platform's storage backend. This callback fires on the instance that handled the request. For multi-instance deployments, your adapter should propagate updates to shared storage. See [How Revalidation Works](/docs/app/guides/how-revalidation-works) for coordination patterns. + +### PPR Chain Headers + +In the [prerenders output type](#prerenders-outputsprerenders), `pprChain.headers` contains the headers needed for the [resume protocol](#implementing-ppr-in-an-adapter). Specifically, it contains `{ 'next-resume': '1' }`. + +When your adapter detects a PPR-enabled route with a cached static shell: + +1. Set the `pprChain.headers` on the internal request to the Next.js handler. +2. Send the request as a **POST** with the `postponedState` as the request body. +3. The handler will render only the deferred Suspense boundaries and stream the result. + +> **Good to know:** In standard `next start`, the server handles both the shell and dynamic render in a single pass automatically. The resume protocol is useful for adapter-based deployments and CDN-to-origin architectures that want to serve the shell separately. See the [PPR Platform Guide](/docs/app/guides/ppr-platform-guide) for the full implementation context. + ## Invoking Entrypoints Build output entrypoints use a `handler(..., ctx)` interface, with runtime-specific request/response types. @@ -795,7 +823,7 @@ ISR-enabled routes and static prerenders: parentOutputId: string // ID of the source page/route groupId: number // Revalidation group identifier (prerenders with same groupId revalidate together) pprChain?: { - headers: Record // PPR chain headers (e.g., 'x-nextjs-resume': '1') + headers: Record // PPR chain headers (e.g., 'next-resume': '1') } parentFallbackMode?: false | null | string // false: no additional paths (fallback: false), null: blocking render, string: path to HTML fallback fallback?: { diff --git a/docs/01-app/03-api-reference/05-config/01-next-config-js/cacheHandlers.mdx b/docs/01-app/03-api-reference/05-config/01-next-config-js/cacheHandlers.mdx index ba1c572e2112..1cbb56682d2d 100644 --- a/docs/01-app/03-api-reference/05-config/01-next-config-js/cacheHandlers.mdx +++ b/docs/01-app/03-api-reference/05-config/01-next-config-js/cacheHandlers.mdx @@ -81,10 +81,10 @@ Retrieve a cache entry for the given cache key. get(cacheKey: string, softTags: string[]): Promise ``` -| Parameter | Type | Description | -| ---------- | ---------- | ------------------------------------------------------------ | -| `cacheKey` | `string` | The unique key for the cache entry. | -| `softTags` | `string[]` | Tags to check for staleness (used in some cache strategies). | +| Parameter | Type | Description | +| ---------- | ---------- | ------------------------------------------------------------------------------------------- | +| `cacheKey` | `string` | The unique key for the cache entry. | +| `softTags` | `string[]` | Implicit tags derived from the route path. See [Soft Tags](#soft-tags) for how to use them. | Returns a `CacheEntry` object if found, or `undefined` if not found or expired. @@ -413,6 +413,86 @@ module.exports = { } ``` +## Distributed Tag Coordination + +When running multiple Next.js instances, tag invalidation must be coordinated across instances. The default in-memory handler only tracks tags locally, so calling `revalidateTag()` on one instance does not affect others. + +To coordinate tags across instances: + +1. **`updateTags()`** is called when `revalidateTag()` is invoked. Your handler should write the invalidation timestamp to shared storage. +2. **`refreshTags()`** is called before each request. Your handler should read recent invalidation events from shared storage and update its local tag state. +3. **`getExpiration()`** returns the most recent revalidation timestamp across all provided tags. The default implementation returns `Math.max(...timestamps, 0)`. + +Here's an example using Redis for distributed tag coordination: + +```js filename="cache-handlers/distributed-tags.js" +const { createClient } = require('redis') + +const client = createClient({ url: process.env.REDIS_URL }) +client.connect() + +// Local cache of tag timestamps, synced via refreshTags +const localTagTimestamps = new Map() + +module.exports = { + // ... get() and set() methods ... + + async refreshTags() { + // Sync tag invalidation timestamps from Redis + // Using a dedicated set to track tag keys avoids scanning the keyspace + const tagKeys = await client.sMembers('revalidated-tags') + if (tagKeys.length > 0) { + const values = await client.mGet(tagKeys.map((k) => `tag:${k}`)) + for (let i = 0; i < tagKeys.length; i++) { + localTagTimestamps.set(tagKeys[i], Number(values[i])) + } + } + }, + + async getExpiration(tags) { + const timestamps = tags.map((tag) => localTagTimestamps.get(tag) || 0) + return Math.max(...timestamps, 0) + }, + + async updateTags(tags, durations) { + const now = Date.now() + const pipeline = client.multi() + for (const tag of tags) { + pipeline.set(`tag:${tag}`, String(now)) + pipeline.sAdd('revalidated-tags', tag) + localTagTimestamps.set(tag, now) + } + await pipeline.exec() + }, +} +``` + +For a full explanation of the tag architecture (including soft tags and multi-instance considerations), see [How Revalidation Works](/docs/app/guides/how-revalidation-works). + +## Soft Tags + +Soft tags are implicit tags that Next.js automatically generates based on the route path. For example, the route `/blog/hello` generates soft tags for `/`, `/blog`, `/blog/hello`, and their corresponding layout entries. These tags are prefixed internally with `_N_T_`. + +Soft tags enable [`revalidatePath()`](/docs/app/api-reference/functions/revalidatePath) to work through the same tag-based cache system. When `revalidatePath('/blog/hello')` is called, it invalidates all cache entries associated with that path's soft tags. + +In the cache handler API, soft tags are passed to the [`get()`](#get) method as the `softTags` parameter. Your handler should check whether any soft tag has been invalidated (via `getExpiration()` or direct timestamp comparison) after the cache entry's `timestamp`. If a soft tag was invalidated more recently than the entry was created, the entry should be treated as stale. + +## Handling Streams + +The `CacheEntry.value` is a [`ReadableStream`](https://developer.mozilla.org/docs/Web/API/ReadableStream). When implementing a cache handler that stores entries externally, keep in mind: + +- **Use `.tee()`** if you need to both store and return the stream. One branch goes to storage, the other is returned to the caller. +- **Memory implications**: large pages produce large cache entries. For S3-like storage backends, consider streaming directly to storage without buffering the entire entry in memory. +- **Partial writes**: the stream may error partway through rendering. Your handler should decide whether to keep partial entries or discard them. Discarding is safer, as partial entries can produce incomplete pages. + +## Error Handling + +Cache operations should be implemented defensively: + +- **`set()` failure**: the response is still served to the user because `set()` is called asynchronously after the response stream is already flowing. The cache entry is lost, and the next request triggers a fresh render. +- **`get()` failure**: your handler should catch internal errors and return `undefined` (the "cache miss" signal). The framework does not wrap `get()` in a try/catch, so an unhandled exception from `get()` will propagate as a render error. +- **Partial writes**: if a cache entry is partially written and then read, the behavior is undefined. Use atomic writes or a write-then-rename pattern to avoid serving partial entries. + ## Platform Support | Deployment Option | Supported | From eee3f524e9f7b322cbd82999fb0f4b90585cc7bf Mon Sep 17 00:00:00 2001 From: JJ Kasper Date: Tue, 31 Mar 2026 08:56:27 -0700 Subject: [PATCH 13/76] backport: Move expanded adapters docs to API reference (#92115) (#92129) ## Summary - move adapter implementation docs from `app/api-reference/config/next-config-js/adapters` to `app/api-reference/adapters` - keep `adapterPath` as an entry page that points to the new adapters section - add matching Pages Router pointer docs under `pages/api-reference/adapters` - update existing docs links that referenced old `adapterPath#...` anchors to the new adapters routes --- .../01-getting-started/17-deploying.mdx | 2 +- .../02-guides/deploying-to-platforms.mdx | 4 +- docs/01-app/02-guides/ppr-platform-guide.mdx | 6 +- .../01-app/02-guides/rendering-philosophy.mdx | 2 +- .../01-next-config-js/adapterPath.mdx | 918 +----------------- .../07-adapters/01-configuration.mdx | 17 + .../07-adapters/02-creating-an-adapter.mdx | 124 +++ .../07-adapters/03-api-reference.mdx | 39 + .../07-adapters/04-testing-adapters.mdx | 230 +++++ .../05-routing-with-next-routing.mdx | 50 + .../06-implementing-ppr-in-an-adapter.mdx | 113 +++ .../07-adapters/07-runtime-integration.mdx | 30 + .../07-adapters/08-invoking-entrypoints.mdx | 93 ++ .../07-adapters/09-output-types.mdx | 207 ++++ .../07-adapters/10-routing-information.mdx | 43 + .../07-adapters/11-use-cases.mdx | 13 + .../03-api-reference/07-adapters/index.mdx | 18 + .../01-next-config-js/adapterPath.mdx | 2 +- .../06-adapters/01-configuration.mdx | 7 + .../06-adapters/02-creating-an-adapter.mdx | 7 + .../06-adapters/03-api-reference.mdx | 7 + .../06-adapters/04-testing-adapters.mdx | 7 + .../05-routing-with-next-routing.mdx | 7 + .../06-implementing-ppr-in-an-adapter.mdx | 7 + .../06-adapters/07-runtime-integration.mdx | 7 + .../06-adapters/08-invoking-entrypoints.mdx | 7 + .../06-adapters/09-output-types.mdx | 7 + .../06-adapters/10-routing-information.mdx | 7 + .../06-adapters/11-use-cases.mdx | 7 + .../04-api-reference/06-adapters/index.mdx | 7 + 30 files changed, 1095 insertions(+), 900 deletions(-) create mode 100644 docs/01-app/03-api-reference/07-adapters/01-configuration.mdx create mode 100644 docs/01-app/03-api-reference/07-adapters/02-creating-an-adapter.mdx create mode 100644 docs/01-app/03-api-reference/07-adapters/03-api-reference.mdx create mode 100644 docs/01-app/03-api-reference/07-adapters/04-testing-adapters.mdx create mode 100644 docs/01-app/03-api-reference/07-adapters/05-routing-with-next-routing.mdx create mode 100644 docs/01-app/03-api-reference/07-adapters/06-implementing-ppr-in-an-adapter.mdx create mode 100644 docs/01-app/03-api-reference/07-adapters/07-runtime-integration.mdx create mode 100644 docs/01-app/03-api-reference/07-adapters/08-invoking-entrypoints.mdx create mode 100644 docs/01-app/03-api-reference/07-adapters/09-output-types.mdx create mode 100644 docs/01-app/03-api-reference/07-adapters/10-routing-information.mdx create mode 100644 docs/01-app/03-api-reference/07-adapters/11-use-cases.mdx create mode 100644 docs/01-app/03-api-reference/07-adapters/index.mdx create mode 100644 docs/02-pages/04-api-reference/06-adapters/01-configuration.mdx create mode 100644 docs/02-pages/04-api-reference/06-adapters/02-creating-an-adapter.mdx create mode 100644 docs/02-pages/04-api-reference/06-adapters/03-api-reference.mdx create mode 100644 docs/02-pages/04-api-reference/06-adapters/04-testing-adapters.mdx create mode 100644 docs/02-pages/04-api-reference/06-adapters/05-routing-with-next-routing.mdx create mode 100644 docs/02-pages/04-api-reference/06-adapters/06-implementing-ppr-in-an-adapter.mdx create mode 100644 docs/02-pages/04-api-reference/06-adapters/07-runtime-integration.mdx create mode 100644 docs/02-pages/04-api-reference/06-adapters/08-invoking-entrypoints.mdx create mode 100644 docs/02-pages/04-api-reference/06-adapters/09-output-types.mdx create mode 100644 docs/02-pages/04-api-reference/06-adapters/10-routing-information.mdx create mode 100644 docs/02-pages/04-api-reference/06-adapters/11-use-cases.mdx create mode 100644 docs/02-pages/04-api-reference/06-adapters/index.mdx diff --git a/docs/01-app/01-getting-started/17-deploying.mdx b/docs/01-app/01-getting-started/17-deploying.mdx index 21488861e43b..3df41a89880b 100644 --- a/docs/01-app/01-getting-started/17-deploying.mdx +++ b/docs/01-app/01-getting-started/17-deploying.mdx @@ -79,7 +79,7 @@ Next.js can be adapted to run on different platforms to support their infrastruc ### Verified Adapters -Verified adapters are open source, run the full [Next.js compatibility test suite](/docs/app/api-reference/config/next-config-js/adapterPath#testing-adapters), and are hosted under the [Next.js GitHub organization](https://github.com/nextjs). The Next.js team coordinates testing with these platforms before major releases. Publicly visible test results for each adapter are coming soon. [Learn more about verified adapters](/docs/app/guides/deploying-to-platforms#verified-adapters). +Verified adapters are open source, run the full [Next.js compatibility test suite](/docs/app/api-reference/adapters/testing-adapters), and are hosted under the [Next.js GitHub organization](https://github.com/nextjs). The Next.js team coordinates testing with these platforms before major releases. Publicly visible test results for each adapter are coming soon. [Learn more about verified adapters](/docs/app/guides/deploying-to-platforms#verified-adapters). - [Vercel](https://vercel.com/docs/frameworks/nextjs) - [Bun](https://bun.sh/docs/frameworks/nextjs) diff --git a/docs/01-app/02-guides/deploying-to-platforms.mdx b/docs/01-app/02-guides/deploying-to-platforms.mdx index 3830811628b9..9b646e995b9b 100644 --- a/docs/01-app/02-guides/deploying-to-platforms.mdx +++ b/docs/01-app/02-guides/deploying-to-platforms.mdx @@ -23,7 +23,7 @@ A single `next start` process handles every Next.js feature correctly: Server Co When evaluating platform support for Next.js, it helps to distinguish between two levels: -**Functional fidelity** means every Next.js feature works correctly. The [adapter test suite](/docs/app/api-reference/config/next-config-js/adapterPath#testing-adapters) is the contract: if a platform's adapter passes the tests, it supports Next.js. This is binary: it passes or it doesn't. +**Functional fidelity** means every Next.js feature works correctly. The [adapter test suite](/docs/app/api-reference/adapters/testing-adapters) is the contract: if a platform's adapter passes the tests, it supports Next.js. This is binary: it passes or it doesn't. **Performance fidelity** means features achieve their optimal performance characteristics. Examples include PPR's static shell served at CDN latency rather than origin latency, or ISR serving stale content instantly with sub-second revalidation propagation. Performance fidelity is a spectrum that every platform will achieve differently based on their architecture. @@ -76,7 +76,7 @@ The adapter API plus Next.js caching interfaces form the complete platform integ A **verified adapter** is one that meets two requirements: 1. **Open source.** The adapter source code is publicly available so the community and the Next.js team can inspect, contribute to, and verify it. -2. **Runs the compatibility test suite.** The platform provides a way to run the full [Next.js compatibility test suite](/docs/app/api-reference/config/next-config-js/adapterPath#testing-adapters) against their adapter. This gives visibility into which features work, which are in progress, and where gaps remain. +2. **Runs the compatibility test suite.** The platform provides a way to run the full [Next.js compatibility test suite](/docs/app/api-reference/adapters/testing-adapters) against their adapter. This gives visibility into which features work, which are in progress, and where gaps remain. Verified adapters are hosted under the [Next.js GitHub organization](https://github.com/nextjs), listed as supported deployment targets in the Next.js documentation, and maintained by their respective platform teams. There are no private framework hooks or integration paths: Vercel's adapter uses the same public API as every other adapter. diff --git a/docs/01-app/02-guides/ppr-platform-guide.mdx b/docs/01-app/02-guides/ppr-platform-guide.mdx index 5f490fa6bb1c..8bd084ba0dc7 100644 --- a/docs/01-app/02-guides/ppr-platform-guide.mdx +++ b/docs/01-app/02-guides/ppr-platform-guide.mdx @@ -44,7 +44,7 @@ Each PPR route requires two artifacts to be stored together: These must be stored and updated atomically. When a PPR route is revalidated (via [time-based](/docs/app/guides/incremental-static-regeneration) or [on-demand revalidation](/docs/app/api-reference/functions/revalidateTag)), Next.js regenerates both the shell and the postponed state together. Serving a new shell with an old postponed state, or vice versa, will produce incorrect dynamic content. -Use [`requestMeta.onCacheEntryV2`](/docs/app/api-reference/config/next-config-js/adapterPath#implementing-ppr-in-an-adapter) in your adapter to observe cache updates and propagate them to your storage backend. +Use [`requestMeta.onCacheEntryV2`](/docs/app/api-reference/adapters/implementing-ppr-in-an-adapter) in your adapter to observe cache updates and propagate them to your storage backend. ## Origin-Only Implementation @@ -93,11 +93,11 @@ When the platform invokes the handler function directly: ### Finding PPR routes in build output -In the [adapter output](/docs/app/api-reference/config/next-config-js/adapterPath#output-types), PPR routes are identified by `renderingMode: 'PARTIALLY_STATIC'` in the prerenders array. Iterate `outputs.prerenders` to find these entries and read `fallback.postponedState`. +In the [adapter output](/docs/app/api-reference/adapters/output-types), PPR routes are identified by `renderingMode: 'PARTIALLY_STATIC'` in the prerenders array. Iterate `outputs.prerenders` to find these entries and read `fallback.postponedState`. `pprChain.headers` contains the headers needed for the resume protocol: `{ 'next-resume': '1' }`. -For detailed implementation with code examples, see [Implementing PPR in an Adapter](/docs/app/api-reference/config/next-config-js/adapterPath#implementing-ppr-in-an-adapter). +For detailed implementation with code examples, see [Implementing PPR in an Adapter](/docs/app/api-reference/adapters/implementing-ppr-in-an-adapter). ## Implementation Checklist diff --git a/docs/01-app/02-guides/rendering-philosophy.mdx b/docs/01-app/02-guides/rendering-philosophy.mdx index 6eaf797fc06d..0ef4069ca725 100644 --- a/docs/01-app/02-guides/rendering-philosophy.mdx +++ b/docs/01-app/02-guides/rendering-philosophy.mdx @@ -62,7 +62,7 @@ Next.js runs as a Node.js server process, and a single process handles every fea To make this concrete, we distinguish between two types of platform support: -**Functional fidelity** means every Next.js feature works correctly on the platform. The [adapter test suite](/docs/app/api-reference/config/next-config-js/adapterPath#testing-adapters) is the contract: if a platform's adapter passes the tests, it has full functional fidelity. This is binary: it passes or it doesn't. The test suite is open to contributions from platform partners to ensure it is fair and complete. +**Functional fidelity** means every Next.js feature works correctly on the platform. The [adapter test suite](/docs/app/api-reference/adapters/testing-adapters) is the contract: if a platform's adapter passes the tests, it has full functional fidelity. This is binary: it passes or it doesn't. The test suite is open to contributions from platform partners to ensure it is fair and complete. **Performance fidelity** means features achieve their optimal performance characteristics. For example, PPR's static shell served at CDN latency rather than origin latency, or ISR serving stale content instantly while revalidating in the background with sub-second propagation. Performance fidelity is a spectrum: every platform will achieve different levels based on their architecture, and platforms will improve over time. diff --git a/docs/01-app/03-api-reference/05-config/01-next-config-js/adapterPath.mdx b/docs/01-app/03-api-reference/05-config/01-next-config-js/adapterPath.mdx index 4d70001f65d1..de47ac50e310 100644 --- a/docs/01-app/03-api-reference/05-config/01-next-config-js/adapterPath.mdx +++ b/docs/01-app/03-api-reference/05-config/01-next-config-js/adapterPath.mdx @@ -22,924 +22,58 @@ module.exports = nextConfig Alternatively `NEXT_ADAPTER_PATH` can be set to enable zero-config usage in deployment platforms. -## Creating an Adapter - -An adapter is a module that exports an object implementing the `NextAdapter` interface. - -The interface can be imported from the `next` package: - -```typescript -import type { NextAdapter } from 'next' -``` - -The interface is defined as follows: - -```typescript -type Route = { - source?: string - sourceRegex: string - destination?: string - headers?: Record - has?: RouteHas[] - missing?: RouteHas[] - status?: number - priority?: boolean -} - -export interface AdapterOutputs { - pages: Array - middleware?: AdapterOutput['MIDDLEWARE'] - appPages: Array - pagesApi: Array - appRoutes: Array - prerenders: Array - staticFiles: Array -} - -export interface NextAdapter { - name: string - modifyConfig?: ( - config: NextConfigComplete, - ctx: { - phase: PHASE_TYPE - nextVersion: string - } - ) => Promise | NextConfigComplete - onBuildComplete?: (ctx: { - routing: { - beforeMiddleware: Array - beforeFiles: Array - afterFiles: Array - dynamicRoutes: Array - onMatch: Array - fallback: Array - shouldNormalizeNextData: boolean - rsc: RoutesManifest['rsc'] - } - outputs: AdapterOutputs - projectDir: string - repoRoot: string - distDir: string - config: NextConfigComplete - nextVersion: string - buildId: string - }) => Promise | void -} -``` +## Adapters + +For full adapter implementation details, use the dedicated Adapters section: + +- [Configuration](/docs/app/api-reference/adapters/configuration) +- [Creating an Adapter](/docs/app/api-reference/adapters/creating-an-adapter) +- [API Reference](/docs/app/api-reference/adapters/api-reference) +- [Testing Adapters](/docs/app/api-reference/adapters/testing-adapters) +- [Routing with `@next/routing`](/docs/app/api-reference/adapters/routing-with-next-routing) +- [Implementing PPR in an Adapter](/docs/app/api-reference/adapters/implementing-ppr-in-an-adapter) +- [Runtime Integration](/docs/app/api-reference/adapters/runtime-integration) +- [Invoking Entrypoints](/docs/app/api-reference/adapters/invoking-entrypoints) +- [Output Types](/docs/app/api-reference/adapters/output-types) +- [Routing Information](/docs/app/api-reference/adapters/routing-information) +- [Use Cases](/docs/app/api-reference/adapters/use-cases) -### Basic Adapter Structure - -Here's a minimal adapter example: - -```js filename="my-adapter.js" -/** @type {import('next').NextAdapter} */ -const adapter = { - name: 'my-custom-adapter', - - async modifyConfig(config, { phase }) { - // Modify the Next.js config based on the build phase - if (phase === 'phase-production-build') { - return { - ...config, - // Add your modifications - } - } - return config - }, - - async onBuildComplete({ - routing, - outputs, - projectDir, - repoRoot, - distDir, - config, - nextVersion, - buildId, - }) { - // Process the build output - console.log('Build completed with', outputs.pages.length, 'pages') - console.log('Build ID:', buildId) - console.log('Dynamic routes:', routing.dynamicRoutes.length) - - // Access emitted output entries - for (const page of outputs.pages) { - console.log('Page:', page.pathname, 'at', page.filePath) - } - - for (const apiRoute of outputs.pagesApi) { - console.log('API Route:', apiRoute.pathname, 'at', apiRoute.filePath) - } - - for (const appPage of outputs.appPages) { - console.log('App Page:', appPage.pathname, 'at', appPage.filePath) - } - - for (const prerender of outputs.prerenders) { - console.log('Prerendered:', prerender.pathname) - } - }, -} +## Creating an Adapter -module.exports = adapter -``` +See [Creating an Adapter](/docs/app/api-reference/adapters/creating-an-adapter). ## API Reference -### `async modifyConfig(config, context)` - -Called for any CLI command that loads the `next.config.js` file to allow modification of the configuration. - -**Parameters:** - -- `config`: The complete Next.js configuration object -- `context.phase`: The current build phase (see [phases](/docs/app/api-reference/config/next-config-js#phase)) -- `context.nextVersion`: Version of Next.js being used - -**Returns:** The modified configuration object (can be async) - -### `async onBuildComplete(context)` - -Called after the build process completes with detailed information about routes and outputs. - -**Parameters:** - -- `context.routing`: Object containing Next.js routing phases and metadata - - `routing.beforeMiddleware`: Routes executed before middleware (includes header and redirect handling) - - `routing.beforeFiles`: Rewrite routes checked before filesystem route matching - - `routing.afterFiles`: Rewrite routes checked after filesystem route matching - - `routing.dynamicRoutes`: Dynamic route matching table - - `routing.onMatch`: Routes applied after a successful match (for example immutable static asset cache headers) - - `routing.fallback`: Final rewrite fallback routes - - `routing.shouldNormalizeNextData`: Whether `/_next/data//...` URLs should be normalized during matching - - `routing.rsc`: Route metadata used for React Server Components routing behavior -- `context.outputs`: Detailed information about all build outputs organized by type -- `context.projectDir`: Absolute path to the Next.js project directory -- `context.repoRoot`: Absolute path to the detected repository root -- `context.distDir`: Absolute path to the build output directory -- `context.config`: The final Next.js configuration (with `modifyConfig` applied) -- `context.nextVersion`: Version of Next.js being used -- `context.buildId`: Unique identifier for the current build +See [API Reference](/docs/app/api-reference/adapters/api-reference). ## Testing Adapters -Next.js provides a test harness for validating adapters. Running the end-to-end tests for deployment. - -Example GitHub Actions workflow: - -```yaml filename=".github/workflows/test-e2e-deploy.yml" -name: test-e2e-deploy - -on: - workflow_dispatch: - inputs: - nextjsRef: - description: 'Next.js repo ref (branch/tag/SHA)' - default: 'canary' - type: string - # schedule: - # - cron: '0 2 * * *' - -jobs: - build: - name: Build Next.js + adapter - runs-on: ubuntu-latest - timeout-minutes: 30 - steps: - - uses: actions/checkout@v4 - with: - path: adapter - - - uses: actions/checkout@v4 - with: - repository: vercel/next.js - ref: ${{ inputs.nextjsRef || 'canary' }} - path: nextjs - fetch-depth: 25 - - - uses: actions/setup-node@v4 - with: { node-version: '20' } - - - name: Setup pnpm - run: npm i -g corepack@0.31 && corepack enable - - - name: Install & build Next.js - working-directory: nextjs - run: pnpm install && pnpm build && pnpm install - - - name: Install Playwright - working-directory: nextjs - run: pnpm playwright install --with-deps chromium - - - name: Build adapter - working-directory: adapter - run: pnpm install && pnpm build - - - uses: actions/cache/save@v4 - with: - path: | - nextjs - adapter - ~/.cache/ms-playwright - key: build-${{ github.sha }}-${{ github.run_id }} - - test: - name: Tests (${{ matrix.group }}) - needs: build - runs-on: ubuntu-latest - timeout-minutes: 60 - strategy: - fail-fast: false - matrix: - group: - [ - 1/16, - 2/16, - 3/16, - 4/16, - 5/16, - 6/16, - 7/16, - 8/16, - 9/16, - 10/16, - 11/16, - 12/16, - 13/16, - 14/16, - 15/16, - 16/16, - ] - steps: - - uses: actions/cache/restore@v4 - with: - path: | - nextjs - adapter - ~/.cache/ms-playwright - key: build-${{ github.sha }}-${{ github.run_id }} - - - uses: actions/setup-node@v4 - with: { node-version: '20' } - - - name: Setup pnpm - run: npm i -g corepack@0.31 && corepack enable - - - name: Ensure Playwright browser - working-directory: nextjs - run: pnpm playwright install chromium - - - name: Make scripts executable - run: chmod +x adapter/scripts/e2e-deploy.sh - adapter/scripts/e2e-logs.sh - adapter/scripts/e2e-cleanup.sh - - - name: Run deploy tests - working-directory: nextjs - env: - NEXT_TEST_MODE: deploy - NEXT_E2E_TEST_TIMEOUT: 240000 - NEXT_EXTERNAL_TESTS_FILTERS: test/deploy-tests-manifest.json - ADAPTER_DIR: ${{ github.workspace }}/adapter - IS_TURBOPACK_TEST: 1 - NEXT_TEST_JOB: 1 - NEXT_TELEMETRY_DISABLED: 1 - - # Change these to your adapter's scripts - # Keep as-is if the scripts are in the adapter repository `scripts` directory - NEXT_TEST_DEPLOY_SCRIPT_PATH: ${{ github.workspace }}/adapter/scripts/e2e-deploy.sh - NEXT_TEST_DEPLOY_LOGS_SCRIPT_PATH: ${{ github.workspace }}/adapter/scripts/e2e-logs.sh - NEXT_TEST_CLEANUP_SCRIPT_PATH: ${{ github.workspace }}/adapter/scripts/e2e-cleanup.sh - run: node run-tests.js --timings -g ${{ matrix.group }} -c 2 --type e2e -``` - -The test harness looks for these environment variables: - -- `NEXT_TEST_DEPLOY_SCRIPT_PATH`: Path to the executable that builds and deploys the isolated test app -- `NEXT_TEST_DEPLOY_LOGS_SCRIPT_PATH`: Path to the executable that returns build and runtime logs for that deployment -- `NEXT_TEST_CLEANUP_SCRIPT_PATH`: Path to the optional executable that tears the deployment down after the test run - -### Custom deploy script contract - -The deploy script `NEXT_TEST_DEPLOY_SCRIPT_PATH` is executed with `cwd` set to the isolated temporary app created by the Next.js test harness. - -The deploy script must follow this contract: - -- Exit with a non-zero code on failure. -- Print the deployment URL to `stdout`. This will be used to verify the deployment. Avoid writing anything else to `stdout`. -- Write diagnostic output to `stderr` or to files inside the working directory. - -Because the deploy script and logs script run as separate processes, any data you want to use later, such as build IDs or server logs, should be persisted to files inside the working directory. - -Example deploy script: - -```bash filename="scripts/e2e-deploy.sh" -#!/usr/bin/env bash -set -euo pipefail - -# Install the adapter, build the app, and deploy or start it. -node -e " -const pkg=JSON.parse(require('fs').readFileSync('package.json','utf8')); -pkg.dependencies=pkg.dependencies||{}; -pkg.dependencies['adapter']='file:${ADAPTER_DIR}'; -require('fs').writeFileSync('package.json',JSON.stringify(pkg,null,2)); -" >&2 - -# Set the adapter path so that the app uses it. -export NEXT_ADAPTER_PATH="${ADAPTER_DIR}/dist/index.js" - -# Write any metadata needed later to files in the working directory. -BUILD_ID="$(cat .next/BUILD_ID)" -DEPLOYMENT_ID="my-adapter-local" -# If your adapter generates an immutable asset token, set it here. -# Otherwise use "undefined" to indicate there is none. -IMMUTABLE_ASSET_TOKEN="undefined" - -{ - echo "BUILD_ID: $BUILD_ID" - echo "DEPLOYMENT_ID: $DEPLOYMENT_ID" - echo "IMMUTABLE_ASSET_TOKEN: $IMMUTABLE_ASSET_TOKEN" -} >> .adapter-build.log - -# Build the app -pnpm build - -# Start or deploy the app. Capture the URL at this point or make the script output the URL to stdout. -provider-cli-to-deploy - -# Example URL output: -# echo "http://127.0.0.1:3000" -``` - -### Custom logs script contract - -The logs script `NEXT_TEST_DEPLOY_LOGS_SCRIPT_PATH` is executed with `cwd` set to the isolated temporary app created by the Next.js test harness. - -Additionally it receives `NEXT_TEST_DIR` and `NEXT_TEST_DEPLOY_URL` as environment variables. - -Its output must include lines starting with: - -- `BUILD_ID:` -- `DEPLOYMENT_ID:` -- `IMMUTABLE_ASSET_TOKEN:` (use the value `undefined` if your adapter does not produce one) - -After those markers, the logs script can print any additional build or server logs that would help debug failures. - -```bash filename="scripts/e2e-logs.sh" -#!/usr/bin/env bash -set -euo pipefail - -if [ -f ".adapter-build.log" ]; then - cat ".adapter-build.log" -fi - -if [ -f ".adapter-server.log" ]; then - echo "=== .adapter-server.log ===" - cat ".adapter-server.log" -fi -``` - -One pattern is to have the deploy script write `.adapter-build.log` and `.adapter-server.log`, then have the logs script replay those files so the harness can extract the required markers. This is one option, each platform has different ways to get the logs. - -### Custom cleanup script contract - -The cleanup script `NEXT_TEST_CLEANUP_SCRIPT_PATH` is executed with `cwd` set to the isolated temporary app created by the Next.js test harness. - -Additionally it receives `NEXT_TEST_DIR` and `NEXT_TEST_DEPLOY_URL` as environment variables. - -The cleanup script can be used to clean up any resources created by the deploy script. It runs after the tests have completed. +See [Testing Adapters](/docs/app/api-reference/adapters/testing-adapters). ## Routing with `@next/routing` -You can use [`@next/routing`](https://www.npmjs.com/package/@next/routing) to reproduce Next.js route matching behavior with data from `onBuildComplete`. - -> [!NOTE] -> `@next/routing` is experimental and will stabilize with the adapters API. - -```typescript -import { resolveRoutes } from '@next/routing' - -const pathnames = [ - ...outputs.pages, - ...outputs.pagesApi, - ...outputs.appPages, - ...outputs.appRoutes, - ...outputs.staticFiles, -].map((output) => output.pathname) - -const result = await resolveRoutes({ - url: requestUrl, - buildId, - basePath: config.basePath || '', - i18n: config.i18n, - headers: requestHeaders, - requestBody, - pathnames, - routes: routing, - invokeMiddleware: async (ctx) => { - // platform-specific middleware invocation - return {} - }, -}) - -if (result.resolvedPathname) { - console.log('Resolved pathname:', result.resolvedPathname) - console.log('Resolved query:', result.resolvedQuery) - console.log('Invocation target:', result.invocationTarget) -} -``` - -`resolveRoutes()` returns: - -- `resolvedPathname`: The route pathname selected by Next.js routing. For dynamic routes, this is the matched route template such as `/blog/[slug]`. -- `resolvedQuery`: The final query after rewrites or middleware have added or replaced search params. -- `invocationTarget`: The concrete pathname and query to invoke for the matched route. - -For example, if `/blog/post-1?draft=1` matches `/blog/[slug]?slug=post-1`, `resolvedPathname` is `/blog/[slug]` while `invocationTarget.pathname` is `/blog/post-1`. +See [Routing with `@next/routing`](/docs/app/api-reference/adapters/routing-with-next-routing). ## Implementing PPR in an Adapter -For partially prerendered app routes, `onBuildComplete` gives you the data needed to seed and resume PPR: - -- `outputs.prerenders[].fallback.filePath`: path to the generated fallback shell (for example HTML) -- `outputs.prerenders[].fallback.postponedState`: serialized postponed state used to resume rendering - -### 1. Seed shell + postponed state at build time - -```ts filename="my-adapter.ts" -import { readFile } from 'node:fs/promises' - -async function seedPprEntries(outputs: AdapterOutputs) { - for (const prerender of outputs.prerenders) { - const fallback = prerender.fallback - if (!fallback?.filePath || !fallback.postponedState) continue - - const shell = await readFile(fallback.filePath, 'utf8') - await platformCache.set(prerender.pathname, { - shell, - postponedState: fallback.postponedState, - initialHeaders: fallback.initialHeaders, - initialStatus: fallback.initialStatus, - initialRevalidate: fallback.initialRevalidate, - initialExpiration: fallback.initialExpiration, - }) - } -} -``` - -### 2. Runtime flow: serve cached shell and resume in background - -At request time, you can stream a single response that is the concatenation of: - -1. cached HTML shell stream -2. resumed render stream (generated after invoking `handler` with postponed state) - -```text -Client - | GET /ppr-route - v -Adapter Router - | - |-- read cached shell + postponedState ---> Platform Cache - |<------------- cache hit -----------------| - | - |-- create responseStream = concat(shellStream, resumedStream) - | - |-- start piping shellStream ------------> Client (first bytes) - | - |-- invoke handler(req, res, { requestMeta: { postponed } }) - | -------------------------------------> Entrypoint (handler) - | <------------------------------------- resumed chunks/cache entry - | - |-- append resumed chunks to resumedStream - | - '-- client receives one HTTP response: - [shell bytes........][resumed bytes........] -``` - -### 3. Update cache with `requestMeta.onCacheEntryV2` - -`requestMeta.onCacheEntryV2` is called when a response cache entry is looked up or generated. Use it to persist updated shell/postponed data. - -> [!NOTE] -> -> - `requestMeta.onCacheEntry` still works, but is deprecated. -> - Prefer `requestMeta.onCacheEntryV2`. -> - If your adapter uses an internal `onCacheCallback` abstraction, wire it to `requestMeta.onCacheEntryV2`. - -```ts filename="my-adapter.ts" -await handler(req, res, { - waitUntil, - requestMeta: { - postponed: cachedPprEntry?.postponedState, - onCacheEntryV2: async (cacheEntry, meta) => { - if (cacheEntry.value?.kind === 'APP_PAGE') { - const html = - cacheEntry.value.html && - typeof cacheEntry.value.html.toUnchunkedString === 'function' - ? cacheEntry.value.html.toUnchunkedString() - : null - - await platformCache.set(meta.url || req.url || '/', { - shell: html, - postponedState: cacheEntry.value.postponed, - headers: cacheEntry.value.headers, - status: cacheEntry.value.status, - cacheControl: cacheEntry.cacheControl, - }) - } - - // Return true only if your adapter already wrote the response itself. - return false - }, - }, -}) -``` - -```text -Entrypoint (handler) - | onCacheEntryV2(cacheEntry, { url }) - v -requestMeta.onCacheEntryV2 callback - | - |-- if APP_PAGE ---> persist html + postponedState + headers ---> Platform Cache - | - '-- return false: continue normal Next.js response flow - return true: adapter already handled response (short-circuit) -``` +See [Implementing PPR in an Adapter](/docs/app/api-reference/adapters/implementing-ppr-in-an-adapter). ## Runtime Integration -The Deployment Adapter API is a **build-time** interface. It tells your platform what was built and how to route requests. **Runtime** behavior (request handling, streaming, caching) is handled by the Next.js server itself and by the cache interfaces [`cacheHandler`](/docs/app/api-reference/config/next-config-js/incrementalCacheHandlerPath) and [`cacheHandlers`](/docs/app/api-reference/config/next-config-js/cacheHandlers). - -Together, the adapter and cache interfaces form the complete platform integration surface: - -- **Adapter** (build-time): processes build outputs, configures routing, and sets up platform-specific infrastructure. -- **Cache Interfaces** (runtime): `cacheHandler` manages ISR/server cache storage and revalidation across instances; `cacheHandlers` configures `'use cache'` directive backends and tag coordination. - -### Handler Context - -When invoking entrypoints, adapters pass a `ctx` object to the Next.js handler. Key fields include: - -- **`ctx.waitUntil`**: a function that accepts a promise. Use this to keep the serverless function alive after the response is sent, allowing background work like cache revalidation to complete. -- **`requestMeta.onCacheEntryV2`** (set via `addRequestMeta`): a callback that fires when a cache entry is generated or looked up. Use this to observe all cache operations (not just PPR) and propagate cache updates to your platform's storage backend. This callback fires on the instance that handled the request. For multi-instance deployments, your adapter should propagate updates to shared storage. See [How Revalidation Works](/docs/app/guides/how-revalidation-works) for coordination patterns. - -### PPR Chain Headers - -In the [prerenders output type](#prerenders-outputsprerenders), `pprChain.headers` contains the headers needed for the [resume protocol](#implementing-ppr-in-an-adapter). Specifically, it contains `{ 'next-resume': '1' }`. - -When your adapter detects a PPR-enabled route with a cached static shell: - -1. Set the `pprChain.headers` on the internal request to the Next.js handler. -2. Send the request as a **POST** with the `postponedState` as the request body. -3. The handler will render only the deferred Suspense boundaries and stream the result. - -> **Good to know:** In standard `next start`, the server handles both the shell and dynamic render in a single pass automatically. The resume protocol is useful for adapter-based deployments and CDN-to-origin architectures that want to serve the shell separately. See the [PPR Platform Guide](/docs/app/guides/ppr-platform-guide) for the full implementation context. +See [Runtime Integration](/docs/app/api-reference/adapters/runtime-integration). ## Invoking Entrypoints -Build output entrypoints use a `handler(..., ctx)` interface, with runtime-specific request/response types. - -### Node.js runtime (`runtime: 'nodejs'`) - -Node.js entrypoints use the following interface: - -```typescript -handler( - req: IncomingMessage, - res: ServerResponse, - ctx: { - waitUntil?: (promise: Promise) => void - requestMeta?: RequestMeta - } -): Promise -``` - -When invoking Node.js entrypoints directly, adapters can pass helpers directly on `requestMeta` instead of relying on internals. Some of the supported fields are `hostname`, -`revalidate`, and `render404`: - -```ts -await handler(req, res, { - requestMeta: { - // Relative path from process.cwd() to the Next.js project directory. - relativeProjectDir: '.', - // Optional hostname used by route handlers when constructing absolute URLs. - hostname: '127.0.0.1', - // Optional internal revalidate function to avoid revalidating over the network - revalidate: async ({ urlPath, headers, opts }) => { - // platform-specific revalidate implementation - }, - // Optional function to render the 404 page for pages router `notFound: true` - render404: async (req, res, parsedUrl, setHeaders) => { - // platform-specific 404 rendering implementation - }, - }, -}) -``` - -Relevant files in the Next.js core: - -- [`packages/next/src/build/templates/app-page.ts`](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/templates/app-page.ts) -- [`packages/next/src/build/templates/app-route.ts`](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/templates/app-route.ts) -- and [`packages/next/src/build/templates/pages-api.ts`](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/templates/pages-api.ts) - -### Edge runtime (`runtime: 'edge'`) - -Edge entrypoints use the following interface: - -```typescript -handler( - request: Request, - ctx: { - waitUntil?: (prom: Promise) => void - signal?: AbortSignal - requestMeta?: RequestMeta - } -): Promise -``` - -The shape is aligned around `handler(..., ctx)`, but Node.js and Edge runtimes use different request/response primitives. - -For outputs with `runtime: 'edge'`, Next.js also provides `output.edgeRuntime` with the canonical metadata needed to invoke the entrypoint: - -```typescript -{ - modulePath: string // Absolute path to the module registered in the edge runtime - entryKey: string // Canonical key used by the edge entry registry - handlerExport: string // Export name to invoke, currently 'handler' -} -``` - -After your edge runtime loads and evaluates the chunks for `modulePath`, use `entryKey` to read the registered entry from the global edge entry registry (`globalThis._ENTRIES`), then invoke `handlerExport` from that entry: - -```ts -const entry = await globalThis._ENTRIES[output.edgeRuntime.entryKey] -const handler = entry[output.edgeRuntime.handlerExport] -await handler(request, ctx) -``` - -Use `edgeRuntime` instead of deriving registry keys or handler names from filenames. - -Relevant files in the Next.js core: - -- [`packages/next/src/build/templates/edge-ssr.ts`](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/templates/edge-ssr.ts) -- [`packages/next/src/build/templates/edge-app-route.ts`](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/templates/edge-app-route.ts) -- [`packages/next/src/build/templates/pages-edge-api.ts`](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/templates/pages-edge-api.ts) -- and [`packages/next/src/build/templates/middleware.ts`](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/templates/middleware.ts) +See [Invoking Entrypoints](/docs/app/api-reference/adapters/invoking-entrypoints). ## Output Types -The `outputs` object contains arrays of build output types: - -- `outputs.pages`: React pages from the `pages/` directory -- `outputs.pagesApi`: API routes from `pages/api/` -- `outputs.appPages`: React pages from the `app/` directory -- `outputs.appRoutes`: API and metadata routes from `app/` -- `outputs.prerenders`: ISR-enabled routes and static prerenders -- `outputs.staticFiles`: Static assets and auto-statically optimized pages -- `outputs.middleware`: Middleware function (if present) - -> **Note:** When `config.output` is set to `'export'`, only `outputs.staticFiles` is populated. All other arrays (`pages`, `appPages`, `pagesApi`, `appRoutes`, `prerenders`) will be empty since the entire application is exported as static files. - -For any route output with `runtime: 'edge'`, `edgeRuntime` is included and contains the canonical entry metadata for invoking that output in your edge runtime. - -### Pages (`outputs.pages`) - -React pages from the `pages/` directory: - -```typescript -{ - type: 'PAGES' - id: string // Route identifier - filePath: string // Path to the built file - pathname: string // URL pathname - sourcePage: string // Original source file path in pages/ directory - runtime: 'nodejs' | 'edge' - assets: Record // Traced dependencies (key: relative path from repo root, value: absolute path) - wasmAssets?: Record // Bundled wasm files (key: name, value: absolute path) - edgeRuntime?: { - modulePath: string // Absolute path to the module registered in the edge runtime - entryKey: string // Canonical key used by the edge entry registry - handlerExport: string // Export name to invoke, currently 'handler' - } - config: { - maxDuration?: number // Maximum duration of the route in seconds - preferredRegion?: string | string[] // Preferred deployment region - env?: Record // Environment variables (edge runtime only) - } -} -``` - -### API Routes (`outputs.pagesApi`) - -API routes from `pages/api/`: - -```typescript -{ - type: 'PAGES_API' - id: string // Route identifier - filePath: string // Path to the built file - pathname: string // URL pathname - sourcePage: string // Original relative source file path - runtime: 'nodejs' | 'edge' - assets: Record // Traced dependencies (key: relative path from repo root, value: absolute path) - wasmAssets?: Record // Bundled wasm files (key: name, value: absolute path) - edgeRuntime?: { - modulePath: string // Absolute path to the module registered in the edge runtime - entryKey: string // Canonical key used by the edge entry registry - handlerExport: string // Export name to invoke, currently 'handler' - } - config: { - maxDuration?: number // Maximum duration of the route in seconds - preferredRegion?: string | string[] // Preferred deployment region - env?: Record // Environment variables (edge runtime only) - } -} -``` - -### App Pages (`outputs.appPages`) - -React pages from the `app/` directory: - -```typescript -{ - type: 'APP_PAGE' - id: string // Route identifier - filePath: string // Path to the built file - pathname: string // URL pathname.Includes .rsc suffix for RSC routes - sourcePage: string // Original relative source file path - runtime: 'nodejs' | 'edge' // Runtime the route is built for - assets: Record // Traced dependencies (key: relative path from repo root, value: absolute path) - wasmAssets?: Record // Bundled wasm files (key: name, value: absolute path) - edgeRuntime?: { - modulePath: string // Absolute path to the module registered in the edge runtime - entryKey: string // Canonical key used by the edge entry registry - handlerExport: string // Export name to invoke, currently 'handler' - } - config: { - maxDuration?: number // Maximum duration of the route in seconds - preferredRegion?: string | string[] // Preferred deployment region - env?: Record // Environment variables (edge runtime only) - } -} -``` - -### App Routes (`outputs.appRoutes`) - -API and metadata routes from the `app/` directory: - -```typescript -{ - type: 'APP_ROUTE' - id: string // Route identifier - filePath: string // Path to the built file - pathname: string // URL pathname - sourcePage: string // Original relative source file path - runtime: 'nodejs' | 'edge' // Runtime the route is built for - assets: Record // Traced dependencies (key: relative path from repo root, value: absolute path) - wasmAssets?: Record // Bundled wasm files (key: name, value: absolute path) - edgeRuntime?: { - modulePath: string // Absolute path to the module registered in the edge runtime - entryKey: string // Canonical key used by the edge entry registry - handlerExport: string // Export name to invoke, currently 'handler' - } - config: { - maxDuration?: number // Maximum duration of the route in seconds - preferredRegion?: string | string[] // Preferred deployment region - env?: Record // Environment variables (edge runtime only) - } -} -``` - -### Prerenders (`outputs.prerenders`) - -ISR-enabled routes and static prerenders: - -```typescript -{ - type: 'PRERENDER' - id: string // Route identifier - pathname: string // URL pathname - parentOutputId: string // ID of the source page/route - groupId: number // Revalidation group identifier (prerenders with same groupId revalidate together) - pprChain?: { - headers: Record // PPR chain headers (e.g., 'next-resume': '1') - } - parentFallbackMode?: false | null | string // false: no additional paths (fallback: false), null: blocking render, string: path to HTML fallback - fallback?: { - filePath: string | undefined // Path to the fallback file (HTML, JSON, or RSC) - initialStatus?: number // Initial status code - initialHeaders?: Record // Initial headers - initialExpiration?: number // Initial expiration time in seconds - initialRevalidate?: number | false // Initial revalidate time in seconds, or false for fully static - postponedState: string | undefined // Serialized PPR state used for resuming rendering - } - config: { - allowQuery?: string[] // Allowed query parameters considered for the cache key - allowHeader?: string[] // Allowed headers for ISR - bypassFor?: RouteHas[] // Cache bypass conditions - renderingMode?: 'STATIC' | 'PARTIALLY_STATIC' // STATIC: fully static, PARTIALLY_STATIC: PPR-enabled - partialFallback?: boolean // Serves a partial fallback shell that should be upgraded to a full route in the background - bypassToken?: string // Generated token that signals the prerender cache should be bypassed - } -} -``` - -### Static Files (`outputs.staticFiles`) - -Static assets and auto-statically optimized pages: - -```typescript -{ - type: 'STATIC_FILE' - id: string // Route identifier - filePath: string // Path to the built file - pathname: string // URL pathname - immutableHash: string | undefined // Content hash when the filename contains a hash, indicating the file is immutable -} -``` - -### Middleware (`outputs.middleware`) - -`middleware.ts` (`.js`/`.ts`) or `proxy.ts` (`.js`/`.ts`) function (if present): - -```typescript -{ - type: 'MIDDLEWARE' - id: string // Route identifier - filePath: string // Path to the built file - pathname: string // Always '/_middleware' - sourcePage: string // Always 'middleware' - runtime: 'nodejs' | 'edge' // Runtime the route is built for - assets: Record // Traced dependencies (key: relative path from repo root, value: absolute path) - wasmAssets?: Record // Bundled wasm files (key: name, value: absolute path) - edgeRuntime?: { - modulePath: string // Absolute path to the module registered in the edge runtime - entryKey: string // Canonical key used by the edge entry registry - handlerExport: string // Export name to invoke, currently 'handler' - } - config: { - maxDuration?: number // Maximum duration of the route in seconds - preferredRegion?: string | string[] // Preferred deployment region - env?: Record // Environment variables (edge runtime only) - matchers?: Array<{ - source: string // Source pattern - sourceRegex: string // Compiled regex for matching requests - has: RouteHas[] | undefined // Positive matching conditions - missing: RouteHas[] | undefined // Negative matching conditions - }> - } -} -``` +See [Output Types](/docs/app/api-reference/adapters/output-types). ## Routing Information -The `routing` object in `onBuildComplete` provides complete routing information with processed patterns ready for deployment: - -### `routing.beforeMiddleware` - -Routes applied before middleware execution. These include generated header and redirect behavior. - -### `routing.beforeFiles` - -Rewrite routes checked before filesystem route matching. - -### `routing.afterFiles` - -Rewrite routes checked after filesystem route matching. - -### `routing.dynamicRoutes` - -Dynamic matchers generated from route segments such as `[slug]` and catch-all routes. - -### `routing.onMatch` - -Routes that apply after a successful match, such as immutable cache headers for hashed static assets. - -### `routing.fallback` - -Final rewrite routes checked when earlier phases did not produce a match. - -### Common Route Fields - -Each route entry can include: - -- `source`: Original route pattern (optional for generated internal rules) -- `sourceRegex`: Compiled regex for matching requests -- `destination`: Internal destination or redirect destination -- `headers`: Headers to apply -- `has`: Positive matching conditions -- `missing`: Negative matching conditions -- `status`: Redirect status code -- `priority`: Internal route priority flag +See [Routing Information](/docs/app/api-reference/adapters/routing-information). ## Use Cases -Common use cases for adapters include: - -- **Deployment Platform Integration**: Automatically configure build outputs for specific hosting platforms -- **Asset Processing**: Transform or optimize build outputs -- **Monitoring Integration**: Collect build metrics and route information -- **Custom Bundling**: Package outputs in platform-specific formats -- **Build Validation**: Ensure outputs meet specific requirements -- **Route Generation**: Use processed route information to generate platform-specific routing configs +See [Use Cases](/docs/app/api-reference/adapters/use-cases). diff --git a/docs/01-app/03-api-reference/07-adapters/01-configuration.mdx b/docs/01-app/03-api-reference/07-adapters/01-configuration.mdx new file mode 100644 index 000000000000..3e02a3e10302 --- /dev/null +++ b/docs/01-app/03-api-reference/07-adapters/01-configuration.mdx @@ -0,0 +1,17 @@ +--- +title: Configuration +description: Configure `adapterPath` or `NEXT_ADAPTER_PATH` to use a custom deployment adapter. +--- + +To use an adapter, specify the path to your adapter module in `adapterPath`: + +```js filename="next.config.js" +/** @type {import('next').NextConfig} */ +const nextConfig = { + adapterPath: require.resolve('./my-adapter.js'), +} + +module.exports = nextConfig +``` + +Alternatively `NEXT_ADAPTER_PATH` can be set to enable zero-config usage in deployment platforms. diff --git a/docs/01-app/03-api-reference/07-adapters/02-creating-an-adapter.mdx b/docs/01-app/03-api-reference/07-adapters/02-creating-an-adapter.mdx new file mode 100644 index 000000000000..081b135bbbb6 --- /dev/null +++ b/docs/01-app/03-api-reference/07-adapters/02-creating-an-adapter.mdx @@ -0,0 +1,124 @@ +--- +title: Creating an Adapter +description: Create an adapter module that implements the `NextAdapter` interface. +--- + +An adapter is a module that exports an object implementing the `NextAdapter` interface. + +The interface can be imported from the `next` package: + +```typescript +import type { NextAdapter } from 'next' +``` + +The interface is defined as follows: + +```typescript +type Route = { + source?: string + sourceRegex: string + destination?: string + headers?: Record + has?: RouteHas[] + missing?: RouteHas[] + status?: number + priority?: boolean +} + +export interface AdapterOutputs { + pages: Array + middleware?: AdapterOutput['MIDDLEWARE'] + appPages: Array + pagesApi: Array + appRoutes: Array + prerenders: Array + staticFiles: Array +} + +export interface NextAdapter { + name: string + modifyConfig?: ( + config: NextConfigComplete, + ctx: { + phase: PHASE_TYPE + nextVersion: string + } + ) => Promise | NextConfigComplete + onBuildComplete?: (ctx: { + routing: { + beforeMiddleware: Array + beforeFiles: Array + afterFiles: Array + dynamicRoutes: Array + onMatch: Array + fallback: Array + shouldNormalizeNextData: boolean + rsc: RoutesManifest['rsc'] + } + outputs: AdapterOutputs + projectDir: string + repoRoot: string + distDir: string + config: NextConfigComplete + nextVersion: string + buildId: string + }) => Promise | void +} +``` + +## Basic Adapter Structure + +Here's a minimal adapter example: + +```js filename="my-adapter.js" +/** @type {import('next').NextAdapter} */ +const adapter = { + name: 'my-custom-adapter', + + async modifyConfig(config, { phase }) { + // Modify the Next.js config based on the build phase + if (phase === 'phase-production-build') { + return { + ...config, + // Add your modifications + } + } + return config + }, + + async onBuildComplete({ + routing, + outputs, + projectDir, + repoRoot, + distDir, + config, + nextVersion, + buildId, + }) { + // Process the build output + console.log('Build completed with', outputs.pages.length, 'pages') + console.log('Build ID:', buildId) + console.log('Dynamic routes:', routing.dynamicRoutes.length) + + // Access emitted output entries + for (const page of outputs.pages) { + console.log('Page:', page.pathname, 'at', page.filePath) + } + + for (const apiRoute of outputs.pagesApi) { + console.log('API Route:', apiRoute.pathname, 'at', apiRoute.filePath) + } + + for (const appPage of outputs.appPages) { + console.log('App Page:', appPage.pathname, 'at', appPage.filePath) + } + + for (const prerender of outputs.prerenders) { + console.log('Prerendered:', prerender.pathname) + } + }, +} + +module.exports = adapter +``` diff --git a/docs/01-app/03-api-reference/07-adapters/03-api-reference.mdx b/docs/01-app/03-api-reference/07-adapters/03-api-reference.mdx new file mode 100644 index 000000000000..4567c187bd4c --- /dev/null +++ b/docs/01-app/03-api-reference/07-adapters/03-api-reference.mdx @@ -0,0 +1,39 @@ +--- +title: API Reference +description: Reference for `modifyConfig` and `onBuildComplete` in the `NextAdapter` interface. +--- + +## `async modifyConfig(config, context)` + +Called for any CLI command that loads the `next.config.js` file to allow modification of the configuration. + +**Parameters:** + +- `config`: The complete Next.js configuration object +- `context.phase`: The current build phase (see [phases](/docs/app/api-reference/config/next-config-js#phase)) +- `context.nextVersion`: Version of Next.js being used + +**Returns:** The modified configuration object (can be async) + +## `async onBuildComplete(context)` + +Called after the build process completes with detailed information about routes and outputs. + +**Parameters:** + +- `context.routing`: Object containing Next.js routing phases and metadata + - `routing.beforeMiddleware`: Routes executed before middleware (includes header and redirect handling) + - `routing.beforeFiles`: Rewrite routes checked before filesystem route matching + - `routing.afterFiles`: Rewrite routes checked after filesystem route matching + - `routing.dynamicRoutes`: Dynamic route matching table + - `routing.onMatch`: Routes applied after a successful match (for example immutable static asset cache headers) + - `routing.fallback`: Final rewrite fallback routes + - `routing.shouldNormalizeNextData`: Whether `/_next/data//...` URLs should be normalized during matching + - `routing.rsc`: Route metadata used for React Server Components routing behavior +- `context.outputs`: Detailed information about all build outputs organized by type +- `context.projectDir`: Absolute path to the Next.js project directory +- `context.repoRoot`: Absolute path to the detected repository root +- `context.distDir`: Absolute path to the build output directory +- `context.config`: The final Next.js configuration (with `modifyConfig` applied) +- `context.nextVersion`: Version of Next.js being used +- `context.buildId`: Unique identifier for the current build diff --git a/docs/01-app/03-api-reference/07-adapters/04-testing-adapters.mdx b/docs/01-app/03-api-reference/07-adapters/04-testing-adapters.mdx new file mode 100644 index 000000000000..8ed97abfb79f --- /dev/null +++ b/docs/01-app/03-api-reference/07-adapters/04-testing-adapters.mdx @@ -0,0 +1,230 @@ +--- +title: Testing Adapters +description: Validate adapters with the Next.js compatibility test harness and custom lifecycle scripts. +--- + +Next.js provides a test harness for validating adapters. Running the end-to-end tests for deployment. + +Example GitHub Actions workflow: + +```yaml filename=".github/workflows/test-e2e-deploy.yml" +name: test-e2e-deploy + +on: + workflow_dispatch: + inputs: + nextjsRef: + description: 'Next.js repo ref (branch/tag/SHA)' + default: 'canary' + type: string + # schedule: + # - cron: '0 2 * * *' + +jobs: + build: + name: Build Next.js + adapter + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + with: + path: adapter + + - uses: actions/checkout@v4 + with: + repository: vercel/next.js + ref: ${{ inputs.nextjsRef || 'canary' }} + path: nextjs + fetch-depth: 25 + + - uses: actions/setup-node@v4 + with: { node-version: '20' } + + - name: Setup pnpm + run: npm i -g corepack@0.31 && corepack enable + + - name: Install & build Next.js + working-directory: nextjs + run: pnpm install && pnpm build && pnpm install + + - name: Install Playwright + working-directory: nextjs + run: pnpm playwright install --with-deps chromium + + - name: Build adapter + working-directory: adapter + run: pnpm install && pnpm build + + - uses: actions/cache/save@v4 + with: + path: | + nextjs + adapter + ~/.cache/ms-playwright + key: build-${{ github.sha }}-${{ github.run_id }} + + test: + name: Tests (${{ matrix.group }}) + needs: build + runs-on: ubuntu-latest + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + group: + [ + 1/16, + 2/16, + 3/16, + 4/16, + 5/16, + 6/16, + 7/16, + 8/16, + 9/16, + 10/16, + 11/16, + 12/16, + 13/16, + 14/16, + 15/16, + 16/16, + ] + steps: + - uses: actions/cache/restore@v4 + with: + path: | + nextjs + adapter + ~/.cache/ms-playwright + key: build-${{ github.sha }}-${{ github.run_id }} + + - uses: actions/setup-node@v4 + with: { node-version: '20' } + + - name: Setup pnpm + run: npm i -g corepack@0.31 && corepack enable + + - name: Ensure Playwright browser + working-directory: nextjs + run: pnpm playwright install chromium + + - name: Make scripts executable + run: chmod +x adapter/scripts/e2e-deploy.sh + adapter/scripts/e2e-logs.sh + adapter/scripts/e2e-cleanup.sh + + - name: Run deploy tests + working-directory: nextjs + env: + NEXT_TEST_MODE: deploy + NEXT_E2E_TEST_TIMEOUT: 240000 + NEXT_EXTERNAL_TESTS_FILTERS: test/deploy-tests-manifest.json + ADAPTER_DIR: ${{ github.workspace }}/adapter + IS_TURBOPACK_TEST: 1 + NEXT_TEST_JOB: 1 + NEXT_TELEMETRY_DISABLED: 1 + + # Change these to your adapter's scripts + # Keep as-is if the scripts are in the adapter repository `scripts` directory + NEXT_TEST_DEPLOY_SCRIPT_PATH: ${{ github.workspace }}/adapter/scripts/e2e-deploy.sh + NEXT_TEST_DEPLOY_LOGS_SCRIPT_PATH: ${{ github.workspace }}/adapter/scripts/e2e-logs.sh + NEXT_TEST_CLEANUP_SCRIPT_PATH: ${{ github.workspace }}/adapter/scripts/e2e-cleanup.sh + run: node run-tests.js --timings -g ${{ matrix.group }} -c 2 --type e2e +``` + +The test harness looks for these environment variables: + +- `NEXT_TEST_DEPLOY_SCRIPT_PATH`: Path to the executable that builds and deploys the isolated test app +- `NEXT_TEST_DEPLOY_LOGS_SCRIPT_PATH`: Path to the executable that returns build and runtime logs for that deployment +- `NEXT_TEST_CLEANUP_SCRIPT_PATH`: Path to the optional executable that tears the deployment down after the test run + +## Custom deploy script contract + +The deploy script `NEXT_TEST_DEPLOY_SCRIPT_PATH` is executed with `cwd` set to the isolated temporary app created by the Next.js test harness. + +The deploy script must follow this contract: + +- Exit with a non-zero code on failure. +- Print the deployment URL to `stdout`. This will be used to verify the deployment. Avoid writing anything else to `stdout`. +- Write diagnostic output to `stderr` or to files inside the working directory. + +Because the deploy script and logs script run as separate processes, any data you want to use later, such as build IDs or server logs, should be persisted to files inside the working directory. + +Example deploy script: + +```bash filename="scripts/e2e-deploy.sh" +#!/usr/bin/env bash +set -euo pipefail + +# Install the adapter, build the app, and deploy or start it. +node -e " +const pkg=JSON.parse(require('fs').readFileSync('package.json','utf8')); +pkg.dependencies=pkg.dependencies||{}; +pkg.dependencies['adapter']='file:${ADAPTER_DIR}'; +require('fs').writeFileSync('package.json',JSON.stringify(pkg,null,2)); +" >&2 + +# Set the adapter path so that the app uses it. +export NEXT_ADAPTER_PATH="${ADAPTER_DIR}/dist/index.js" + +# Write any metadata needed later to files in the working directory. +BUILD_ID="$(cat .next/BUILD_ID)" +DEPLOYMENT_ID="my-adapter-local" +# If your adapter generates an immutable asset token, set it here. +# Otherwise use "undefined" to indicate there is none. +IMMUTABLE_ASSET_TOKEN="undefined" + +{ + echo "BUILD_ID: $BUILD_ID" + echo "DEPLOYMENT_ID: $DEPLOYMENT_ID" + echo "IMMUTABLE_ASSET_TOKEN: $IMMUTABLE_ASSET_TOKEN" +} >> .adapter-build.log + +# Build the app +pnpm build + +# Start or deploy the app. Capture the URL at this point or make the script output the URL to stdout. +provider-cli-to-deploy + +# Example URL output: +# echo "http://127.0.0.1:3000" +``` + +## Custom logs script contract + +The logs script `NEXT_TEST_DEPLOY_LOGS_SCRIPT_PATH` is executed with `cwd` set to the isolated temporary app created by the Next.js test harness. + +Additionally it receives `NEXT_TEST_DIR` and `NEXT_TEST_DEPLOY_URL` as environment variables. + +Its output must include lines starting with: + +- `BUILD_ID:` +- `DEPLOYMENT_ID:` +- `IMMUTABLE_ASSET_TOKEN:` (use the value `undefined` if your adapter does not produce one) + +After those markers, the logs script can print any additional build or server logs that would help debug failures. + +```bash filename="scripts/e2e-logs.sh" +#!/usr/bin/env bash +set -euo pipefail + +if [ -f ".adapter-build.log" ]; then + cat ".adapter-build.log" +fi + +if [ -f ".adapter-server.log" ]; then + echo "=== .adapter-server.log ===" + cat ".adapter-server.log" +fi +``` + +One pattern is to have the deploy script write `.adapter-build.log` and `.adapter-server.log`, then have the logs script replay those files so the harness can extract the required markers. This is one option, each platform has different ways to get the logs. + +## Custom cleanup script contract + +The cleanup script `NEXT_TEST_CLEANUP_SCRIPT_PATH` is executed with `cwd` set to the isolated temporary app created by the Next.js test harness. + +Additionally it receives `NEXT_TEST_DIR` and `NEXT_TEST_DEPLOY_URL` as environment variables. + +The cleanup script can be used to clean up any resources created by the deploy script. It runs after the tests have completed. diff --git a/docs/01-app/03-api-reference/07-adapters/05-routing-with-next-routing.mdx b/docs/01-app/03-api-reference/07-adapters/05-routing-with-next-routing.mdx new file mode 100644 index 000000000000..96e722d06093 --- /dev/null +++ b/docs/01-app/03-api-reference/07-adapters/05-routing-with-next-routing.mdx @@ -0,0 +1,50 @@ +--- +title: Routing with @next/routing +description: Use `@next/routing` to apply Next.js route matching behavior in adapters. +--- + +You can use [`@next/routing`](https://www.npmjs.com/package/@next/routing) to reproduce Next.js route matching behavior with data from `onBuildComplete`. + +> [!NOTE] +> `@next/routing` is experimental and will stabilize with the adapters API. + +```typescript +import { resolveRoutes } from '@next/routing' + +const pathnames = [ + ...outputs.pages, + ...outputs.pagesApi, + ...outputs.appPages, + ...outputs.appRoutes, + ...outputs.staticFiles, +].map((output) => output.pathname) + +const result = await resolveRoutes({ + url: requestUrl, + buildId, + basePath: config.basePath || '', + i18n: config.i18n, + headers: requestHeaders, + requestBody, + pathnames, + routes: routing, + invokeMiddleware: async (ctx) => { + // platform-specific middleware invocation + return {} + }, +}) + +if (result.resolvedPathname) { + console.log('Resolved pathname:', result.resolvedPathname) + console.log('Resolved query:', result.resolvedQuery) + console.log('Invocation target:', result.invocationTarget) +} +``` + +`resolveRoutes()` returns: + +- `resolvedPathname`: The route pathname selected by Next.js routing. For dynamic routes, this is the matched route template such as `/blog/[slug]`. +- `resolvedQuery`: The final query after rewrites or middleware have added or replaced search params. +- `invocationTarget`: The concrete pathname and query to invoke for the matched route. + +For example, if `/blog/post-1?draft=1` matches `/blog/[slug]?slug=post-1`, `resolvedPathname` is `/blog/[slug]` while `invocationTarget.pathname` is `/blog/post-1`. diff --git a/docs/01-app/03-api-reference/07-adapters/06-implementing-ppr-in-an-adapter.mdx b/docs/01-app/03-api-reference/07-adapters/06-implementing-ppr-in-an-adapter.mdx new file mode 100644 index 000000000000..53d8d9ef85c3 --- /dev/null +++ b/docs/01-app/03-api-reference/07-adapters/06-implementing-ppr-in-an-adapter.mdx @@ -0,0 +1,113 @@ +--- +title: Implementing PPR in an Adapter +description: Implement Partial Prerendering support in an adapter using fallback output and cache hooks. +--- + +For partially prerendered app routes, `onBuildComplete` gives you the data needed to seed and resume PPR: + +- `outputs.prerenders[].fallback.filePath`: path to the generated fallback shell (for example HTML) +- `outputs.prerenders[].fallback.postponedState`: serialized postponed state used to resume rendering + +## 1. Seed shell + postponed state at build time + +```ts filename="my-adapter.ts" +import { readFile } from 'node:fs/promises' + +async function seedPprEntries(outputs: AdapterOutputs) { + for (const prerender of outputs.prerenders) { + const fallback = prerender.fallback + if (!fallback?.filePath || !fallback.postponedState) continue + + const shell = await readFile(fallback.filePath, 'utf8') + await platformCache.set(prerender.pathname, { + shell, + postponedState: fallback.postponedState, + initialHeaders: fallback.initialHeaders, + initialStatus: fallback.initialStatus, + initialRevalidate: fallback.initialRevalidate, + initialExpiration: fallback.initialExpiration, + }) + } +} +``` + +## 2. Runtime flow: serve cached shell and resume in background + +At request time, you can stream a single response that is the concatenation of: + +1. cached HTML shell stream +2. resumed render stream (generated after invoking `handler` with postponed state) + +```text +Client + | GET /ppr-route + v +Adapter Router + | + |-- read cached shell + postponedState ---> Platform Cache + |<------------- cache hit -----------------| + | + |-- create responseStream = concat(shellStream, resumedStream) + | + |-- start piping shellStream ------------> Client (first bytes) + | + |-- invoke handler(req, res, { requestMeta: { postponed } }) + | -------------------------------------> Entrypoint (handler) + | <------------------------------------- resumed chunks/cache entry + | + |-- append resumed chunks to resumedStream + | + '-- client receives one HTTP response: + [shell bytes........][resumed bytes........] +``` + +## 3. Update cache with `requestMeta.onCacheEntryV2` + +`requestMeta.onCacheEntryV2` is called when a response cache entry is looked up or generated. Use it to persist updated shell/postponed data. + +> [!NOTE] +> +> - `requestMeta.onCacheEntry` still works, but is deprecated. +> - Prefer `requestMeta.onCacheEntryV2`. +> - If your adapter uses an internal `onCacheCallback` abstraction, wire it to `requestMeta.onCacheEntryV2`. + +```ts filename="my-adapter.ts" +await handler(req, res, { + waitUntil, + requestMeta: { + postponed: cachedPprEntry?.postponedState, + onCacheEntryV2: async (cacheEntry, meta) => { + if (cacheEntry.value?.kind === 'APP_PAGE') { + const html = + cacheEntry.value.html && + typeof cacheEntry.value.html.toUnchunkedString === 'function' + ? cacheEntry.value.html.toUnchunkedString() + : null + + await platformCache.set(meta.url || req.url || '/', { + shell: html, + postponedState: cacheEntry.value.postponed, + headers: cacheEntry.value.headers, + status: cacheEntry.value.status, + cacheControl: cacheEntry.cacheControl, + }) + } + + // Return true only if your adapter already wrote the response itself. + return false + }, + }, +}) +``` + +```text +Entrypoint (handler) + | onCacheEntryV2(cacheEntry, { url }) + v +requestMeta.onCacheEntryV2 callback + | + |-- if APP_PAGE ---> persist html + postponedState + headers ---> Platform Cache + | + '-- return false: continue normal Next.js response flow + return true: adapter already handled response (short-circuit) +``` diff --git a/docs/01-app/03-api-reference/07-adapters/07-runtime-integration.mdx b/docs/01-app/03-api-reference/07-adapters/07-runtime-integration.mdx new file mode 100644 index 000000000000..1a02529447e5 --- /dev/null +++ b/docs/01-app/03-api-reference/07-adapters/07-runtime-integration.mdx @@ -0,0 +1,30 @@ +--- +title: Runtime Integration +description: Understand how build-time adapters and runtime cache interfaces work together. +--- + +The Deployment Adapter API is a **build-time** interface. It tells your platform what was built and how to route requests. **Runtime** behavior (request handling, streaming, caching) is handled by the Next.js server itself and by the cache interfaces [`cacheHandler`](/docs/app/api-reference/config/next-config-js/incrementalCacheHandlerPath) and [`cacheHandlers`](/docs/app/api-reference/config/next-config-js/cacheHandlers). + +Together, the adapter and cache interfaces form the complete platform integration surface: + +- **Adapter** (build-time): processes build outputs, configures routing, and sets up platform-specific infrastructure. +- **Cache Interfaces** (runtime): `cacheHandler` manages ISR/server cache storage and revalidation across instances; `cacheHandlers` configures `'use cache'` directive backends and tag coordination. + +## Handler Context + +When invoking entrypoints, adapters pass a `ctx` object to the Next.js handler. Key fields include: + +- **`ctx.waitUntil`**: a function that accepts a promise. Use this to keep the serverless function alive after the response is sent, allowing background work like cache revalidation to complete. +- **`requestMeta.onCacheEntryV2`** (set via `addRequestMeta`): a callback that fires when a cache entry is generated or looked up. Use this to observe all cache operations (not just PPR) and propagate cache updates to your platform's storage backend. This callback fires on the instance that handled the request. For multi-instance deployments, your adapter should propagate updates to shared storage. See [How Revalidation Works](/docs/app/guides/how-revalidation-works) for coordination patterns. + +## PPR Chain Headers + +In the [prerenders output type](/docs/app/api-reference/adapters/output-types#prerenders-outputsprerenders), `pprChain.headers` contains the headers needed for the [resume protocol](/docs/app/api-reference/adapters/implementing-ppr-in-an-adapter). Specifically, it contains `{ 'next-resume': '1' }`. + +When your adapter detects a PPR-enabled route with a cached static shell: + +1. Set the `pprChain.headers` on the internal request to the Next.js handler. +2. Send the request as a **POST** with the `postponedState` as the request body. +3. The handler will render only the deferred Suspense boundaries and stream the result. + +> **Good to know:** In standard `next start`, the server handles both the shell and dynamic render in a single pass automatically. The resume protocol is useful for adapter-based deployments and CDN-to-origin architectures that want to serve the shell separately. See the [PPR Platform Guide](/docs/app/guides/ppr-platform-guide) for the full implementation context. diff --git a/docs/01-app/03-api-reference/07-adapters/08-invoking-entrypoints.mdx b/docs/01-app/03-api-reference/07-adapters/08-invoking-entrypoints.mdx new file mode 100644 index 000000000000..5fd30e9f44e9 --- /dev/null +++ b/docs/01-app/03-api-reference/07-adapters/08-invoking-entrypoints.mdx @@ -0,0 +1,93 @@ +--- +title: Invoking Entrypoints +description: Invoke Node.js and Edge build entrypoints with adapter runtime context. +--- + +Build output entrypoints use a `handler(..., ctx)` interface, with runtime-specific request/response types. + +## Node.js runtime (`runtime: 'nodejs'`) + +Node.js entrypoints use the following interface: + +```typescript +handler( + req: IncomingMessage, + res: ServerResponse, + ctx: { + waitUntil?: (promise: Promise) => void + requestMeta?: RequestMeta + } +): Promise +``` + +When invoking Node.js entrypoints directly, adapters can pass helpers directly on `requestMeta` instead of relying on internals. Some of the supported fields are `hostname`, +`revalidate`, and `render404`: + +```ts +await handler(req, res, { + requestMeta: { + // Relative path from process.cwd() to the Next.js project directory. + relativeProjectDir: '.', + // Optional hostname used by route handlers when constructing absolute URLs. + hostname: '127.0.0.1', + // Optional internal revalidate function to avoid revalidating over the network + revalidate: async ({ urlPath, headers, opts }) => { + // platform-specific revalidate implementation + }, + // Optional function to render the 404 page for pages router `notFound: true` + render404: async (req, res, parsedUrl, setHeaders) => { + // platform-specific 404 rendering implementation + }, + }, +}) +``` + +Relevant files in the Next.js core: + +- [`packages/next/src/build/templates/app-page.ts`](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/templates/app-page.ts) +- [`packages/next/src/build/templates/app-route.ts`](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/templates/app-route.ts) +- and [`packages/next/src/build/templates/pages-api.ts`](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/templates/pages-api.ts) + +## Edge runtime (`runtime: 'edge'`) + +Edge entrypoints use the following interface: + +```typescript +handler( + request: Request, + ctx: { + waitUntil?: (prom: Promise) => void + signal?: AbortSignal + requestMeta?: RequestMeta + } +): Promise +``` + +The shape is aligned around `handler(..., ctx)`, but Node.js and Edge runtimes use different request/response primitives. + +For outputs with `runtime: 'edge'`, Next.js also provides `output.edgeRuntime` with the canonical metadata needed to invoke the entrypoint: + +```typescript +{ + modulePath: string // Absolute path to the module registered in the edge runtime + entryKey: string // Canonical key used by the edge entry registry + handlerExport: string // Export name to invoke, currently 'handler' +} +``` + +After your edge runtime loads and evaluates the chunks for `modulePath`, use `entryKey` to read the registered entry from the global edge entry registry (`globalThis._ENTRIES`), then invoke `handlerExport` from that entry: + +```ts +const entry = await globalThis._ENTRIES[output.edgeRuntime.entryKey] +const handler = entry[output.edgeRuntime.handlerExport] +await handler(request, ctx) +``` + +Use `edgeRuntime` instead of deriving registry keys or handler names from filenames. + +Relevant files in the Next.js core: + +- [`packages/next/src/build/templates/edge-ssr.ts`](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/templates/edge-ssr.ts) +- [`packages/next/src/build/templates/edge-app-route.ts`](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/templates/edge-app-route.ts) +- [`packages/next/src/build/templates/pages-edge-api.ts`](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/templates/pages-edge-api.ts) +- and [`packages/next/src/build/templates/middleware.ts`](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/templates/middleware.ts) diff --git a/docs/01-app/03-api-reference/07-adapters/09-output-types.mdx b/docs/01-app/03-api-reference/07-adapters/09-output-types.mdx new file mode 100644 index 000000000000..400d17e09dfe --- /dev/null +++ b/docs/01-app/03-api-reference/07-adapters/09-output-types.mdx @@ -0,0 +1,207 @@ +--- +title: Output Types +description: Reference for all build output types exposed to adapters. +--- + +The `outputs` object contains arrays of build output types: + +- `outputs.pages`: React pages from the `pages/` directory +- `outputs.pagesApi`: API routes from `pages/api/` +- `outputs.appPages`: React pages from the `app/` directory +- `outputs.appRoutes`: API and metadata routes from `app/` +- `outputs.prerenders`: ISR-enabled routes and static prerenders +- `outputs.staticFiles`: Static assets and auto-statically optimized pages +- `outputs.middleware`: Middleware function (if present) + +> **Note:** When `config.output` is set to `'export'`, only `outputs.staticFiles` is populated. All other arrays (`pages`, `appPages`, `pagesApi`, `appRoutes`, `prerenders`) will be empty since the entire application is exported as static files. + +For any route output with `runtime: 'edge'`, `edgeRuntime` is included and contains the canonical entry metadata for invoking that output in your edge runtime. + +## Pages (`outputs.pages`) + +React pages from the `pages/` directory: + +```typescript +{ + type: 'PAGES' + id: string // Route identifier + filePath: string // Path to the built file + pathname: string // URL pathname + sourcePage: string // Original source file path in pages/ directory + runtime: 'nodejs' | 'edge' + assets: Record // Traced dependencies (key: relative path from repo root, value: absolute path) + wasmAssets?: Record // Bundled wasm files (key: name, value: absolute path) + edgeRuntime?: { + modulePath: string // Absolute path to the module registered in the edge runtime + entryKey: string // Canonical key used by the edge entry registry + handlerExport: string // Export name to invoke, currently 'handler' + } + config: { + maxDuration?: number // Maximum duration of the route in seconds + preferredRegion?: string | string[] // Preferred deployment region + env?: Record // Environment variables (edge runtime only) + } +} +``` + +## API Routes (`outputs.pagesApi`) + +API routes from `pages/api/`: + +```typescript +{ + type: 'PAGES_API' + id: string // Route identifier + filePath: string // Path to the built file + pathname: string // URL pathname + sourcePage: string // Original relative source file path + runtime: 'nodejs' | 'edge' + assets: Record // Traced dependencies (key: relative path from repo root, value: absolute path) + wasmAssets?: Record // Bundled wasm files (key: name, value: absolute path) + edgeRuntime?: { + modulePath: string // Absolute path to the module registered in the edge runtime + entryKey: string // Canonical key used by the edge entry registry + handlerExport: string // Export name to invoke, currently 'handler' + } + config: { + maxDuration?: number // Maximum duration of the route in seconds + preferredRegion?: string | string[] // Preferred deployment region + env?: Record // Environment variables (edge runtime only) + } +} +``` + +## App Pages (`outputs.appPages`) + +React pages from the `app/` directory: + +```typescript +{ + type: 'APP_PAGE' + id: string // Route identifier + filePath: string // Path to the built file + pathname: string // URL pathname.Includes .rsc suffix for RSC routes + sourcePage: string // Original relative source file path + runtime: 'nodejs' | 'edge' // Runtime the route is built for + assets: Record // Traced dependencies (key: relative path from repo root, value: absolute path) + wasmAssets?: Record // Bundled wasm files (key: name, value: absolute path) + edgeRuntime?: { + modulePath: string // Absolute path to the module registered in the edge runtime + entryKey: string // Canonical key used by the edge entry registry + handlerExport: string // Export name to invoke, currently 'handler' + } + config: { + maxDuration?: number // Maximum duration of the route in seconds + preferredRegion?: string | string[] // Preferred deployment region + env?: Record // Environment variables (edge runtime only) + } +} +``` + +## App Routes (`outputs.appRoutes`) + +API and metadata routes from the `app/` directory: + +```typescript +{ + type: 'APP_ROUTE' + id: string // Route identifier + filePath: string // Path to the built file + pathname: string // URL pathname + sourcePage: string // Original relative source file path + runtime: 'nodejs' | 'edge' // Runtime the route is built for + assets: Record // Traced dependencies (key: relative path from repo root, value: absolute path) + wasmAssets?: Record // Bundled wasm files (key: name, value: absolute path) + edgeRuntime?: { + modulePath: string // Absolute path to the module registered in the edge runtime + entryKey: string // Canonical key used by the edge entry registry + handlerExport: string // Export name to invoke, currently 'handler' + } + config: { + maxDuration?: number // Maximum duration of the route in seconds + preferredRegion?: string | string[] // Preferred deployment region + env?: Record // Environment variables (edge runtime only) + } +} +``` + +## Prerenders (`outputs.prerenders`) + +ISR-enabled routes and static prerenders: + +```typescript +{ + type: 'PRERENDER' + id: string // Route identifier + pathname: string // URL pathname + parentOutputId: string // ID of the source page/route + groupId: number // Revalidation group identifier (prerenders with same groupId revalidate together) + pprChain?: { + headers: Record // PPR chain headers (e.g., 'next-resume': '1') + } + parentFallbackMode?: false | null | string // false: no additional paths (fallback: false), null: blocking render, string: path to HTML fallback + fallback?: { + filePath: string | undefined // Path to the fallback file (HTML, JSON, or RSC) + initialStatus?: number // Initial status code + initialHeaders?: Record // Initial headers + initialExpiration?: number // Initial expiration time in seconds + initialRevalidate?: number | false // Initial revalidate time in seconds, or false for fully static + postponedState: string | undefined // Serialized PPR state used for resuming rendering + } + config: { + allowQuery?: string[] // Allowed query parameters considered for the cache key + allowHeader?: string[] // Allowed headers for ISR + bypassFor?: RouteHas[] // Cache bypass conditions + renderingMode?: 'STATIC' | 'PARTIALLY_STATIC' // STATIC: fully static, PARTIALLY_STATIC: PPR-enabled + partialFallback?: boolean // Serves a partial fallback shell that should be upgraded to a full route in the background + bypassToken?: string // Generated token that signals the prerender cache should be bypassed + } +} +``` + +## Static Files (`outputs.staticFiles`) + +Static assets and auto-statically optimized pages: + +```typescript +{ + type: 'STATIC_FILE' + id: string // Route identifier + filePath: string // Path to the built file + pathname: string // URL pathname + immutableHash: string | undefined // Content hash when the filename contains a hash, indicating the file is immutable +} +``` + +## Middleware (`outputs.middleware`) + +`middleware.ts` (`.js`/`.ts`) or `proxy.ts` (`.js`/`.ts`) function (if present): + +```typescript +{ + type: 'MIDDLEWARE' + id: string // Route identifier + filePath: string // Path to the built file + pathname: string // Always '/_middleware' + sourcePage: string // Always 'middleware' + runtime: 'nodejs' | 'edge' // Runtime the route is built for + assets: Record // Traced dependencies (key: relative path from repo root, value: absolute path) + wasmAssets?: Record // Bundled wasm files (key: name, value: absolute path) + edgeRuntime?: { + modulePath: string // Absolute path to the module registered in the edge runtime + entryKey: string // Canonical key used by the edge entry registry + handlerExport: string // Export name to invoke, currently 'handler' + } + config: { + maxDuration?: number // Maximum duration of the route in seconds + preferredRegion?: string | string[] // Preferred deployment region + env?: Record // Environment variables (edge runtime only) + matchers?: Array<{ + source: string // Source pattern + sourceRegex: string // Compiled regex for matching requests + has: RouteHas[] | undefined // Positive matching conditions + missing: RouteHas[] | undefined // Negative matching conditions + }> + } +} +``` diff --git a/docs/01-app/03-api-reference/07-adapters/10-routing-information.mdx b/docs/01-app/03-api-reference/07-adapters/10-routing-information.mdx new file mode 100644 index 000000000000..e061dc153618 --- /dev/null +++ b/docs/01-app/03-api-reference/07-adapters/10-routing-information.mdx @@ -0,0 +1,43 @@ +--- +title: Routing Information +description: Reference for routing phases and route fields exposed in `onBuildComplete`. +--- + +The `routing` object in `onBuildComplete` provides complete routing information with processed patterns ready for deployment: + +## `routing.beforeMiddleware` + +Routes applied before middleware execution. These include generated header and redirect behavior. + +## `routing.beforeFiles` + +Rewrite routes checked before filesystem route matching. + +## `routing.afterFiles` + +Rewrite routes checked after filesystem route matching. + +## `routing.dynamicRoutes` + +Dynamic matchers generated from route segments such as `[slug]` and catch-all routes. + +## `routing.onMatch` + +Routes that apply after a successful match, such as immutable cache headers for hashed static assets. + +## `routing.fallback` + +Final rewrite routes checked when earlier phases did not produce a match. + +## Common Route Fields + +Each route entry can include: + +- `source`: Original route pattern (optional for generated internal rules) +- `sourceRegex`: Compiled regex for matching requests +- `destination`: Internal destination or redirect destination +- `headers`: Headers to apply +- `has`: Positive matching conditions +- `missing`: Negative matching conditions +- `status`: Redirect status code +- `priority`: Internal route priority flag diff --git a/docs/01-app/03-api-reference/07-adapters/11-use-cases.mdx b/docs/01-app/03-api-reference/07-adapters/11-use-cases.mdx new file mode 100644 index 000000000000..4dca8c46c939 --- /dev/null +++ b/docs/01-app/03-api-reference/07-adapters/11-use-cases.mdx @@ -0,0 +1,13 @@ +--- +title: Use Cases +description: Common patterns and examples for deployment adapter implementations. +--- + +Common use cases for adapters include: + +- **Deployment Platform Integration**: Automatically configure build outputs for specific hosting platforms +- **Asset Processing**: Transform or optimize build outputs +- **Monitoring Integration**: Collect build metrics and route information +- **Custom Bundling**: Package outputs in platform-specific formats +- **Build Validation**: Ensure outputs meet specific requirements +- **Route Generation**: Use processed route information to generate platform-specific routing configs diff --git a/docs/01-app/03-api-reference/07-adapters/index.mdx b/docs/01-app/03-api-reference/07-adapters/index.mdx new file mode 100644 index 000000000000..5d130498db7a --- /dev/null +++ b/docs/01-app/03-api-reference/07-adapters/index.mdx @@ -0,0 +1,18 @@ +--- +title: Adapters +description: Build deployment adapters for Next.js platforms and infrastructure. +--- + +Use this section to build and validate deployment adapters that integrate with the Next.js build and runtime model. + +- [Configuration](/docs/app/api-reference/adapters/configuration) +- [Creating an Adapter](/docs/app/api-reference/adapters/creating-an-adapter) +- [API Reference](/docs/app/api-reference/adapters/api-reference) +- [Testing Adapters](/docs/app/api-reference/adapters/testing-adapters) +- [Routing with `@next/routing`](/docs/app/api-reference/adapters/routing-with-next-routing) +- [Implementing PPR in an Adapter](/docs/app/api-reference/adapters/implementing-ppr-in-an-adapter) +- [Runtime Integration](/docs/app/api-reference/adapters/runtime-integration) +- [Invoking Entrypoints](/docs/app/api-reference/adapters/invoking-entrypoints) +- [Output Types](/docs/app/api-reference/adapters/output-types) +- [Routing Information](/docs/app/api-reference/adapters/routing-information) +- [Use Cases](/docs/app/api-reference/adapters/use-cases) diff --git a/docs/02-pages/04-api-reference/04-config/01-next-config-js/adapterPath.mdx b/docs/02-pages/04-api-reference/04-config/01-next-config-js/adapterPath.mdx index 899cdd7f0660..9143d16afed3 100644 --- a/docs/02-pages/04-api-reference/04-config/01-next-config-js/adapterPath.mdx +++ b/docs/02-pages/04-api-reference/04-config/01-next-config-js/adapterPath.mdx @@ -1,6 +1,6 @@ --- title: adapterPath -description: Configure a custom adapter for Next.js to hook into the build process with modifyConfig and buildComplete callbacks. +description: Configure a custom adapter for Next.js to hook into the build process. source: app/api-reference/config/next-config-js/adapterPath --- diff --git a/docs/02-pages/04-api-reference/06-adapters/01-configuration.mdx b/docs/02-pages/04-api-reference/06-adapters/01-configuration.mdx new file mode 100644 index 000000000000..77b888d8fbc5 --- /dev/null +++ b/docs/02-pages/04-api-reference/06-adapters/01-configuration.mdx @@ -0,0 +1,7 @@ +--- +title: Configuration +description: Configure `adapterPath` or `NEXT_ADAPTER_PATH` to use a custom deployment adapter. +source: app/api-reference/adapters/configuration +--- + +{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the Content component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/04-api-reference/06-adapters/02-creating-an-adapter.mdx b/docs/02-pages/04-api-reference/06-adapters/02-creating-an-adapter.mdx new file mode 100644 index 000000000000..de9c4a5c5ac2 --- /dev/null +++ b/docs/02-pages/04-api-reference/06-adapters/02-creating-an-adapter.mdx @@ -0,0 +1,7 @@ +--- +title: Creating an Adapter +description: Create an adapter module that implements the `NextAdapter` interface. +source: app/api-reference/adapters/creating-an-adapter +--- + +{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the Content component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/04-api-reference/06-adapters/03-api-reference.mdx b/docs/02-pages/04-api-reference/06-adapters/03-api-reference.mdx new file mode 100644 index 000000000000..05abfb3907a1 --- /dev/null +++ b/docs/02-pages/04-api-reference/06-adapters/03-api-reference.mdx @@ -0,0 +1,7 @@ +--- +title: API Reference +description: Reference for `modifyConfig` and `onBuildComplete` in the `NextAdapter` interface. +source: app/api-reference/adapters/api-reference +--- + +{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the Content component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/04-api-reference/06-adapters/04-testing-adapters.mdx b/docs/02-pages/04-api-reference/06-adapters/04-testing-adapters.mdx new file mode 100644 index 000000000000..e2f72d196385 --- /dev/null +++ b/docs/02-pages/04-api-reference/06-adapters/04-testing-adapters.mdx @@ -0,0 +1,7 @@ +--- +title: Testing Adapters +description: Validate adapters with the Next.js compatibility test harness and custom lifecycle scripts. +source: app/api-reference/adapters/testing-adapters +--- + +{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the Content component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/04-api-reference/06-adapters/05-routing-with-next-routing.mdx b/docs/02-pages/04-api-reference/06-adapters/05-routing-with-next-routing.mdx new file mode 100644 index 000000000000..750b9441fc98 --- /dev/null +++ b/docs/02-pages/04-api-reference/06-adapters/05-routing-with-next-routing.mdx @@ -0,0 +1,7 @@ +--- +title: Routing with @next/routing +description: Use `@next/routing` to apply Next.js route matching behavior in adapters. +source: app/api-reference/adapters/routing-with-next-routing +--- + +{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the Content component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/04-api-reference/06-adapters/06-implementing-ppr-in-an-adapter.mdx b/docs/02-pages/04-api-reference/06-adapters/06-implementing-ppr-in-an-adapter.mdx new file mode 100644 index 000000000000..7954166700ad --- /dev/null +++ b/docs/02-pages/04-api-reference/06-adapters/06-implementing-ppr-in-an-adapter.mdx @@ -0,0 +1,7 @@ +--- +title: Implementing PPR in an Adapter +description: Implement Partial Prerendering support in an adapter using fallback output and cache hooks. +source: app/api-reference/adapters/implementing-ppr-in-an-adapter +--- + +{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the Content component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/04-api-reference/06-adapters/07-runtime-integration.mdx b/docs/02-pages/04-api-reference/06-adapters/07-runtime-integration.mdx new file mode 100644 index 000000000000..c9da7c119c71 --- /dev/null +++ b/docs/02-pages/04-api-reference/06-adapters/07-runtime-integration.mdx @@ -0,0 +1,7 @@ +--- +title: Runtime Integration +description: Understand how build-time adapters and runtime cache interfaces work together. +source: app/api-reference/adapters/runtime-integration +--- + +{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the Content component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/04-api-reference/06-adapters/08-invoking-entrypoints.mdx b/docs/02-pages/04-api-reference/06-adapters/08-invoking-entrypoints.mdx new file mode 100644 index 000000000000..08f43958cb11 --- /dev/null +++ b/docs/02-pages/04-api-reference/06-adapters/08-invoking-entrypoints.mdx @@ -0,0 +1,7 @@ +--- +title: Invoking Entrypoints +description: Invoke Node.js and Edge build entrypoints with adapter runtime context. +source: app/api-reference/adapters/invoking-entrypoints +--- + +{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the Content component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/04-api-reference/06-adapters/09-output-types.mdx b/docs/02-pages/04-api-reference/06-adapters/09-output-types.mdx new file mode 100644 index 000000000000..30f3b56a38b1 --- /dev/null +++ b/docs/02-pages/04-api-reference/06-adapters/09-output-types.mdx @@ -0,0 +1,7 @@ +--- +title: Output Types +description: Reference for all build output types exposed to adapters. +source: app/api-reference/adapters/output-types +--- + +{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the Content component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/04-api-reference/06-adapters/10-routing-information.mdx b/docs/02-pages/04-api-reference/06-adapters/10-routing-information.mdx new file mode 100644 index 000000000000..294c143d2fdd --- /dev/null +++ b/docs/02-pages/04-api-reference/06-adapters/10-routing-information.mdx @@ -0,0 +1,7 @@ +--- +title: Routing Information +description: Reference for routing phases and route fields exposed in `onBuildComplete`. +source: app/api-reference/adapters/routing-information +--- + +{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the Content component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/04-api-reference/06-adapters/11-use-cases.mdx b/docs/02-pages/04-api-reference/06-adapters/11-use-cases.mdx new file mode 100644 index 000000000000..f26905668294 --- /dev/null +++ b/docs/02-pages/04-api-reference/06-adapters/11-use-cases.mdx @@ -0,0 +1,7 @@ +--- +title: Use Cases +description: Common patterns and examples for deployment adapter implementations. +source: app/api-reference/adapters/use-cases +--- + +{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the Content component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/04-api-reference/06-adapters/index.mdx b/docs/02-pages/04-api-reference/06-adapters/index.mdx new file mode 100644 index 000000000000..6bf6e68aa010 --- /dev/null +++ b/docs/02-pages/04-api-reference/06-adapters/index.mdx @@ -0,0 +1,7 @@ +--- +title: Adapters +description: Build deployment adapters for Next.js platforms and infrastructure. +source: app/api-reference/adapters +--- + +{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the Content component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} From edcf19ae132b5853bb9f9c41888887f7830c19ad Mon Sep 17 00:00:00 2001 From: JJ Kasper Date: Tue, 31 Mar 2026 09:38:57 -0700 Subject: [PATCH 14/76] Backport: TypeScript v6 deprecations for baseUrl and moduleResolution (#92130) backports: https://github.com/vercel/next.js/pull/91855 backports: https://github.com/vercel/next.js/pull/91847 --- packages/next/src/build/index.ts | 7 + .../typescript/getTypeScriptConfiguration.ts | 132 ++++++++++++++++++ .../writeConfigurationDefaults.test.ts | 29 +++- .../typescript/writeConfigurationDefaults.ts | 56 +++++--- .../correct-tsconfig-defaults/index.test.ts | 4 +- .../next-dist-client-esm-import/app/page.tsx | 1 - test/e2e/twoslash/index.test.ts | 2 + test/e2e/twoslash/standalone.test.ts | 2 + .../tsconfig-verifier/test/index.test.ts | 26 ++-- .../types-gen-nounuselocal.test.ts | 6 + 10 files changed, 229 insertions(+), 36 deletions(-) diff --git a/packages/next/src/build/index.ts b/packages/next/src/build/index.ts index a2362f70864a..bc24502bbef5 100644 --- a/packages/next/src/build/index.ts +++ b/packages/next/src/build/index.ts @@ -219,6 +219,7 @@ import { writeRouteTypesManifest, writeValidatorFile, } from '../server/lib/router-utils/route-types-utils' +import { writeCacheLifeTypes } from '../server/lib/router-utils/cache-life-type-utils' import { Lockfile } from './lockfile' import { buildPrefetchSegmentDataRoute, @@ -1391,6 +1392,11 @@ export default async function build( .traceAsyncFn(async () => { const routeTypesFilePath = path.join(distDir, 'types', 'routes.d.ts') const validatorFilePath = path.join(distDir, 'types', 'validator.ts') + const cacheLifeFilePath = path.join( + distDir, + 'types', + 'cache-life.d.ts' + ) await mkdir(path.dirname(routeTypesFilePath), { recursive: true }) const routeTypesManifest = await createRouteTypesManifest({ @@ -1416,6 +1422,7 @@ export default async function build( validatorFilePath, Boolean(config.experimental.strictRouteTypes) ) + writeCacheLifeTypes(config.cacheLife, cacheLifeFilePath) }) // Turbopack already handles conflicting app and page routes. diff --git a/packages/next/src/lib/typescript/getTypeScriptConfiguration.ts b/packages/next/src/lib/typescript/getTypeScriptConfiguration.ts index a775b122bce6..e225c42fed93 100644 --- a/packages/next/src/lib/typescript/getTypeScriptConfiguration.ts +++ b/packages/next/src/lib/typescript/getTypeScriptConfiguration.ts @@ -1,10 +1,80 @@ import { bold, cyan } from '../picocolors' import os from 'os' import path from 'path' +import semver from 'next/dist/compiled/semver' import { FatalError } from '../fatal-error' import isError from '../is-error' +function resolvePathAliasTarget(baseUrl: string, target: string): string { + if ( + path.isAbsolute(target) || + target.startsWith('./') || + target.startsWith('../') + ) { + return target + } + + if (baseUrl === '.' || baseUrl === './') { + return `./${target}` + } + + const resolvedTarget = path.join(baseUrl, target) + if ( + path.isAbsolute(resolvedTarget) || + resolvedTarget.startsWith('./') || + resolvedTarget.startsWith('../') + ) { + return resolvedTarget + } + + return `./${resolvedTarget}` +} + +function rewritePathAliasesWithoutBaseUrl( + baseUrl: string, + originalPaths: unknown +): Record { + const rewrittenPaths: Record = + originalPaths && typeof originalPaths === 'object' + ? Object.fromEntries( + Object.entries(originalPaths).map(([key, values]) => [ + key, + Array.isArray(values) + ? values.map((value) => + typeof value === 'string' + ? resolvePathAliasTarget(baseUrl, value) + : value + ) + : values, + ]) + ) + : { + '*': [resolvePathAliasTarget(baseUrl, '*')], + } + + if (!Object.prototype.hasOwnProperty.call(rewrittenPaths, '*')) { + rewrittenPaths['*'] = [resolvePathAliasTarget(baseUrl, '*')] + } + + return rewrittenPaths +} + +function getNormalizedBaseUrlForPaths( + baseUrl: string, + tsConfigPath: string +): string { + const tsConfigDir = path.resolve(path.dirname(tsConfigPath)) + const absoluteBaseUrl = path.isAbsolute(baseUrl) + ? baseUrl + : baseUrl.startsWith('./') || baseUrl.startsWith('../') + ? path.resolve(tsConfigDir, baseUrl) + : path.resolve(baseUrl) + const relativeBaseUrl = path.relative(tsConfigDir, absoluteBaseUrl) + + return relativeBaseUrl || '.' +} + export async function getTypeScriptConfiguration( typescript: typeof import('typescript'), tsConfigPath: string, @@ -28,6 +98,49 @@ export async function getTypeScriptConfiguration( } let configToParse: any = config + if (semver.gte(typescript.version, '6.0.0')) { + const target = configToParse.compilerOptions?.target + if ( + typeof target === 'string' && + (target.toLowerCase() === 'es3' || target.toLowerCase() === 'es5') + ) { + const { target: _target, ...restCompilerOptions } = + configToParse.compilerOptions ?? {} + + // TypeScript 6 deprecates ES3/ES5 targets. Rewrite deprecated + // targets in-memory to keep typechecking working without requiring + // `ignoreDeprecations`. + configToParse = { + ...configToParse, + compilerOptions: { + ...restCompilerOptions, + target: 'es2015', + }, + } + } + + const baseUrl = configToParse.compilerOptions?.baseUrl + const hasBaseUrl = typeof baseUrl === 'string' && baseUrl.length > 0 + + if (hasBaseUrl) { + const rewrittenPaths = rewritePathAliasesWithoutBaseUrl( + baseUrl, + configToParse.compilerOptions?.paths + ) + const { baseUrl: _baseUrl, ...restCompilerOptions } = + configToParse.compilerOptions ?? {} + + // TypeScript 6 deprecates `baseUrl`; rewrite aliases to explicit + // relative paths so path mapping still works without this option. + configToParse = { + ...configToParse, + compilerOptions: { + ...restCompilerOptions, + paths: rewrittenPaths, + }, + } + } + } const result = typescript.parseJsonConfigFileContent( configToParse, @@ -44,6 +157,25 @@ export async function getTypeScriptConfiguration( path.dirname(tsConfigPath) ) + if (semver.gte(typescript.version, '6.0.0')) { + const parsedBaseUrl = result.options.baseUrl + if (typeof parsedBaseUrl === 'string' && parsedBaseUrl.length > 0) { + const normalizedBaseUrl = getNormalizedBaseUrlForPaths( + parsedBaseUrl, + tsConfigPath + ) + + // `baseUrl` can come from extended tsconfigs. Rewrite paths from the + // fully-resolved baseUrl and remove it so TS6 deprecation checks do not + // fail type checking. + result.options.paths = rewritePathAliasesWithoutBaseUrl( + normalizedBaseUrl, + result.options.paths + ) as import('typescript').MapLike + delete (result.options as { baseUrl?: unknown }).baseUrl + } + } + if (result.errors) { result.errors = result.errors.filter( ({ code }) => diff --git a/packages/next/src/lib/typescript/writeConfigurationDefaults.test.ts b/packages/next/src/lib/typescript/writeConfigurationDefaults.test.ts index aada2aeb0c6d..af5236083d64 100644 --- a/packages/next/src/lib/typescript/writeConfigurationDefaults.test.ts +++ b/packages/next/src/lib/typescript/writeConfigurationDefaults.test.ts @@ -68,7 +68,7 @@ describe('writeConfigurationDefaults()', () => { "esnext", ], "module": "esnext", - "moduleResolution": "node", + "moduleResolution": "bundler", "noEmit": true, "plugins": [ { @@ -113,7 +113,7 @@ describe('writeConfigurationDefaults()', () => { - module was set to esnext (for dynamic import() support) - esModuleInterop was set to true (requirement for SWC / babel) - - moduleResolution was set to node (to match webpack resolution) + - moduleResolution was set to bundler (to match modern bundler resolution) - resolveJsonModule was set to true (to match webpack resolution) - isolatedModules was set to true (requirement for SWC / Babel) - jsx was set to react-jsx (next.js uses the React automatic runtime) @@ -143,6 +143,31 @@ describe('writeConfigurationDefaults()', () => { ) }) + it('uses bundler moduleResolution for TypeScript 6+', async () => { + await writeFile(tsConfigPath, JSON.stringify({ compilerOptions: {} }), { + encoding: 'utf8', + }) + + await writeConfigurationDefaults( + '6.0.0', + tsConfigPath, + isFirstTimeSetup, + hasAppDir, + distDir, + hasPagesDir, + experimentalStrictRouteTypes + ) + + const tsConfig = JSON.parse( + await readFile(tsConfigPath, { encoding: 'utf8' }) + ) + + expect(tsConfig.compilerOptions.moduleResolution).toBe('bundler') + expect(stripAnsi(consoleLogSpy.mock.calls.flat().join('\n'))).toContain( + '- moduleResolution was set to bundler (to match modern bundler resolution)' + ) + }) + describe('with tsconfig extends', () => { let tsConfigBasePath: string let nextAppTypes: string diff --git a/packages/next/src/lib/typescript/writeConfigurationDefaults.ts b/packages/next/src/lib/typescript/writeConfigurationDefaults.ts index c4dfc0e0f00d..23772c795f7a 100644 --- a/packages/next/src/lib/typescript/writeConfigurationDefaults.ts +++ b/packages/next/src/lib/typescript/writeConfigurationDefaults.ts @@ -33,9 +33,18 @@ function getDesiredCompilerOptions( // ModuleResolutionKind const moduleResolutionKindBundler = 'bundler' - const moduleResolutionKindNode10 = 'node10' + const moduleResolutionKindNode16 = 'node16' + const moduleResolutionKindNodeNext = 'nodenext' const moduleResolutionKindNode12 = 'node12' - const moduleResolutionKindNodeJs = 'node' + const moduleResolutionKindNode = 'node' + const configuredModule = + typeof userTsConfig?.compilerOptions?.module === 'string' + ? userTsConfig.compilerOptions.module.toLowerCase() + : undefined + const preferBundlerResolution = + semver.gte(typescriptVersion, '5.0.0') && + configuredModule !== moduleKindCommonJS && + configuredModule !== moduleKindAMD // Jsx const jsxEmitReactJSX = 'react-jsx' @@ -89,21 +98,29 @@ function getDesiredCompilerOptions( reason: 'requirement for SWC / babel', }, moduleResolution: { - // In TypeScript 5.0, `NodeJs` has renamed to `Node10` - parsedValue: moduleResolutionKindBundler, + parsedValue: preferBundlerResolution + ? moduleResolutionKindBundler + : moduleResolutionKindNode, // All of these values work: - parsedValues: [ - moduleResolutionKindNode10, - moduleResolutionKindNodeJs, - // only newer TypeScript versions have this field, it - // will be filtered for new versions of TypeScript - moduleResolutionKindNode12, - moduleKindNode16, - moduleKindNodeNext, - moduleResolutionKindBundler, - ].filter((val) => typeof val !== 'undefined'), - value: 'node', - reason: 'to match webpack resolution', + parsedValues: preferBundlerResolution + ? [ + moduleResolutionKindNode16, + moduleResolutionKindNodeNext, + moduleResolutionKindBundler, + ] + : [ + moduleResolutionKindNode, + // only older TypeScript versions have this field + moduleResolutionKindNode12, + moduleResolutionKindNode16, + moduleResolutionKindNodeNext, + ], + value: preferBundlerResolution + ? moduleResolutionKindBundler + : moduleResolutionKindNode, + reason: preferBundlerResolution + ? 'to match modern bundler resolution' + : 'to match webpack resolution', }, resolveJsonModule: { value: true, @@ -161,9 +178,12 @@ export function getRequiredConfiguration( import('typescript').ModuleResolutionKind > = { bundler: typescript.ModuleResolutionKind.Bundler, - node10: typescript.ModuleResolutionKind.Node10, + node16: typescript.ModuleResolutionKind.Node16, + nodenext: typescript.ModuleResolutionKind.NodeNext, node12: (typescript.ModuleResolutionKind as any).Node12, - node: typescript.ModuleResolutionKind.NodeJs, + node: + (typescript.ModuleResolutionKind as any).Node10 ?? + typescript.ModuleResolutionKind.NodeJs, } res[optionKey] = moduleResolutionMap[value.toLowerCase()] ?? value } else if (optionKey === 'jsx' && typeof value === 'string') { diff --git a/test/development/correct-tsconfig-defaults/index.test.ts b/test/development/correct-tsconfig-defaults/index.test.ts index 0c4e250fd2cb..71eeff35d35a 100644 --- a/test/development/correct-tsconfig-defaults/index.test.ts +++ b/test/development/correct-tsconfig-defaults/index.test.ts @@ -39,7 +39,7 @@ describe('correct tsconfig.json defaults', () => { expect(next.cliOutput).not.toContain('moduleResolution') expect(tsconfig.compilerOptions).toEqual( - expect.objectContaining({ moduleResolution: 'node' }) + expect.objectContaining({ moduleResolution: 'bundler' }) ) } finally { await next.stop() @@ -57,7 +57,7 @@ describe('correct tsconfig.json defaults', () => { const tsconfig = JSON.parse(await next.readFile('tsconfig.json')) expect(tsconfig.compilerOptions).toEqual( - expect.objectContaining({ moduleResolution: 'node' }) + expect.objectContaining({ moduleResolution: 'bundler' }) ) expect(next.cliOutput).not.toContain('moduleResolution') } finally { diff --git a/test/e2e/app-dir/next-dist-client-esm-import/app/page.tsx b/test/e2e/app-dir/next-dist-client-esm-import/app/page.tsx index 6beefc1a422e..836a1ee00ae2 100644 --- a/test/e2e/app-dir/next-dist-client-esm-import/app/page.tsx +++ b/test/e2e/app-dir/next-dist-client-esm-import/app/page.tsx @@ -1,4 +1,3 @@ -// @ts-expect-error no types defined import { Hello } from '@monorepo/adapter-next' export default function Page() { diff --git a/test/e2e/twoslash/index.test.ts b/test/e2e/twoslash/index.test.ts index fa1edcbd20d6..a8996b646ce4 100644 --- a/test/e2e/twoslash/index.test.ts +++ b/test/e2e/twoslash/index.test.ts @@ -5,6 +5,8 @@ describe('twoslash', () => { files: __dirname, dependencies: { twoslash: '0.3.4', + 'twoslash-protocol': '0.3.4', + typescript: '5.9.2', }, }) diff --git a/test/e2e/twoslash/standalone.test.ts b/test/e2e/twoslash/standalone.test.ts index b44826a0bd94..5f4ad33a59b1 100644 --- a/test/e2e/twoslash/standalone.test.ts +++ b/test/e2e/twoslash/standalone.test.ts @@ -17,6 +17,8 @@ if (!(globalThis as any).isNextStart) { files: __dirname, dependencies: { twoslash: '0.3.4', + 'twoslash-protocol': '0.3.4', + typescript: '5.9.2', }, skipStart: true, }) diff --git a/test/integration/tsconfig-verifier/test/index.test.ts b/test/integration/tsconfig-verifier/test/index.test.ts index e4775377232d..527e174d3b7f 100644 --- a/test/integration/tsconfig-verifier/test/index.test.ts +++ b/test/integration/tsconfig-verifier/test/index.test.ts @@ -45,7 +45,7 @@ const strictRouteTypes = "incremental": true, "module": "esnext", "esModuleInterop": true, - "moduleResolution": "node", + "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react-jsx", @@ -85,7 +85,7 @@ const strictRouteTypes = "incremental": true, "module": "esnext", "esModuleInterop": true, - "moduleResolution": "node", + "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react-jsx", @@ -144,7 +144,7 @@ const strictRouteTypes = "incremental": true, "module": "esnext", "esModuleInterop": true, - "moduleResolution": "node", + "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react-jsx", @@ -184,7 +184,7 @@ const strictRouteTypes = "incremental": true, "module": "esnext", "esModuleInterop": true, - "moduleResolution": "node", + "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react-jsx", @@ -260,7 +260,7 @@ const strictRouteTypes = "strict": false, "noEmit": true, "incremental": true, - "moduleResolution": "node", + "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react-jsx", @@ -308,7 +308,7 @@ const strictRouteTypes = "strict": false, "noEmit": true, "incremental": true, - "moduleResolution": "node", + "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react-jsx", @@ -463,7 +463,7 @@ const strictRouteTypes = "strict": false, "noEmit": true, "incremental": true, - "moduleResolution": "node", + "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react-jsx", @@ -503,7 +503,7 @@ const strictRouteTypes = "strict": false, "noEmit": true, "incremental": true, - "moduleResolution": "node", + "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react-jsx", @@ -760,7 +760,7 @@ const strictRouteTypes = "incremental": true, "module": "esnext", "esModuleInterop": true, - "moduleResolution": "node", + "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react-jsx", @@ -800,7 +800,7 @@ const strictRouteTypes = "incremental": true, "module": "esnext", "esModuleInterop": true, - "moduleResolution": "node", + "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react-jsx", @@ -961,7 +961,7 @@ const strictRouteTypes = "incremental": true, "module": "esnext", "esModuleInterop": true, - "moduleResolution": "node", + "moduleResolution": "bundler", "resolveJsonModule": true, "jsx": "react-jsx", "plugins": [ @@ -1001,7 +1001,7 @@ const strictRouteTypes = "incremental": true, "module": "esnext", "esModuleInterop": true, - "moduleResolution": "node", + "moduleResolution": "bundler", "resolveJsonModule": true, "jsx": "react-jsx", "plugins": [ @@ -1050,7 +1050,7 @@ const strictRouteTypes = "incremental": true, "module": "esnext", "esModuleInterop": true, - "moduleResolution": "node", + "moduleResolution": "bundler", "resolveJsonModule": true, "jsx": "react-jsx", "plugins": [ diff --git a/test/production/app-dir/types-gen-nounuselocal/types-gen-nounuselocal.test.ts b/test/production/app-dir/types-gen-nounuselocal/types-gen-nounuselocal.test.ts index 83daae35eb2a..e5b5a00e3a20 100644 --- a/test/production/app-dir/types-gen-nounuselocal/types-gen-nounuselocal.test.ts +++ b/test/production/app-dir/types-gen-nounuselocal/types-gen-nounuselocal.test.ts @@ -31,6 +31,12 @@ describe('types-gen-nounuselocal', () => { expect(routeTypes).not.toContain('ApiRouteConfig') if (strictRouteTypes) { + const cacheLifeTypes = await fsp.readFile( + path.join(next.testDir, '.next', 'types', 'cache-life.d.ts'), + 'utf-8' + ) + expect(cacheLifeTypes).toContain("declare module 'next/cache'") + expect(routeTypes).toMatchInlineSnapshot(` "// This file is generated automatically by Next.js with experimental.strictRouteTypes // Do not edit this file manually From c4779d1b085a563f39faea86f7b84d5d9adc4f72 Mon Sep 17 00:00:00 2001 From: Jude Gao Date: Wed, 25 Mar 2026 14:36:01 -0400 Subject: [PATCH 15/76] [create-next-app] Skip interactive prompts when CLI flags are provided (#91840) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When AI agents run `create-next-app` with explicit flags like `--typescript --tailwind --eslint --app --src-dir`, the CLI still enters interactive mode and prompts for any unspecified options: ``` ➜ npx create-next-app my-app --typescript --tailwind --eslint --app --src-dir --use-pnpm ✔ Would you like to use React Compiler? … No / Yes ✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes ? Would you like to include AGENTS.md to guide coding agents to write up-to-date Next.js code? › No / Yes ``` Agents can sometimes answer these interactive prompts correctly, but often they can't. When they fail to navigate the prompts, they fall back to scaffolding the project themselves from scratch — generating files based on stale training data. This means they might initialize an app using deprecated patterns or pin to an older version of Next.js (e.g. 15) instead of the latest. Using `create-next-app` non-interactively is the best way to ensure agents always produce up-to-date scaffolding. Previously, `hasProvidedOptions` only skipped the initial "use recommended defaults?" meta-prompt but still showed individual prompts for each missing option. Now when any config flags are provided, all remaining options use the recommended defaults without prompting. The resolved defaults are printed to stdout so the caller knows exactly what was assumed and which flags to pass to override: ``` Using defaults for unprovided options: --eslint ESLint (use --biome for Biome, --no-eslint for None) --no-react-compiler No React Compiler (use --react-compiler for React Compiler) --agents-md AGENTS.md (use --no-agents-md for No AGENTS.md) --import-alias "@/*" To customize, re-run with explicit flags. ``` The `displayConfig` array is extended with a `flags` field so this output is auto-generated from the same source of truth used for the interactive prompts. Existing behavior for `--yes`, CI mode, and fully interactive mode (no flags) is unchanged. --- packages/create-next-app/index.ts | 99 +++++++++++++++++-- .../create-next-app/examples.test.ts | 4 + .../integration/create-next-app/index.test.ts | 82 +++++++++++++++ .../create-next-app/prompts.test.ts | 31 ++---- 4 files changed, 187 insertions(+), 29 deletions(-) diff --git a/packages/create-next-app/index.ts b/packages/create-next-app/index.ts index 313086c76d90..6cdc2977103b 100644 --- a/packages/create-next-app/index.ts +++ b/packages/create-next-app/index.ts @@ -251,19 +251,45 @@ async function run(): Promise { type DisplayConfigItem = { key: keyof typeof defaults values?: Record + flags?: Record } const displayConfig: DisplayConfigItem[] = [ { key: 'typescript', values: { true: 'TypeScript', false: 'JavaScript' }, + flags: { true: '--ts', false: '--js' }, + }, + { + key: 'linter', + values: { eslint: 'ESLint', biome: 'Biome', none: 'None' }, + flags: { eslint: '--eslint', biome: '--biome', none: '--no-eslint' }, + }, + { + key: 'reactCompiler', + values: { true: 'React Compiler', false: 'No React Compiler' }, + flags: { true: '--react-compiler', false: '--no-react-compiler' }, + }, + { + key: 'tailwind', + values: { true: 'Tailwind CSS', false: 'No Tailwind CSS' }, + flags: { true: '--tailwind', false: '--no-tailwind' }, + }, + { + key: 'srcDir', + values: { true: 'src/ directory', false: 'No src/ directory' }, + flags: { true: '--src-dir', false: '--no-src-dir' }, + }, + { + key: 'app', + values: { true: 'App Router', false: 'Pages Router' }, + flags: { true: '--app', false: '--no-app' }, + }, + { + key: 'agentsMd', + values: { true: 'AGENTS.md', false: 'No AGENTS.md' }, + flags: { true: '--agents-md', false: '--no-agents-md' }, }, - { key: 'linter', values: { eslint: 'ESLint', biome: 'Biome' } }, - { key: 'reactCompiler', values: { true: 'React Compiler' } }, - { key: 'tailwind', values: { true: 'Tailwind CSS' } }, - { key: 'srcDir', values: { true: 'src/ dir' } }, - { key: 'app', values: { true: 'App Router', false: 'Pages Router' } }, - { key: 'agentsMd', values: { true: 'AGENTS.md' } }, ] // Helper to format settings for display based on displayConfig @@ -291,10 +317,17 @@ async function run(): Promise { const hasSavedPreferences = Object.keys(preferences).length > 0 // Check if user provided any configuration flags - // If they did, skip the "recommended defaults" prompt and go straight to - // individual prompts for any missing options + // If they did, skip all prompts and use recommended defaults for unspecified + // options. This is critical for AI agents, which pass flags like + // --typescript --tailwind --app and expect the rest to use sensible defaults + // without entering interactive mode. const hasProvidedOptions = process.argv.some((arg) => arg.startsWith('--')) + if (!skipPrompt && hasProvidedOptions) { + skipPrompt = true + useRecommendedDefaults = true + } + // Only show the "recommended defaults" prompt if: // - Not in CI and not using --yes flag // - User hasn't provided any custom options @@ -620,6 +653,56 @@ async function run(): Promise { preferences.agentsMd = Boolean(agentsMd) } } + + // When prompts were skipped because flags were provided, print the + // defaults that were assumed so agents and users know what to override. + if (hasProvidedOptions && useRecommendedDefaults) { + const lines: string[] = [] + + for (const config of displayConfig) { + if (!config.flags || !config.values) continue + + // Skip options the user already specified explicitly + const wasExplicit = process.argv.some((arg) => + Object.values(config.flags!).includes(arg) + ) + if (wasExplicit) continue + + const value = String(defaults[config.key]) + const flag = config.flags[value] + const label = config.values[value] + if (!flag || !label) continue + + // Show alternatives the user could pass instead + const alts: string[] = [] + for (const [k, f] of Object.entries(config.flags)) { + if (k !== value && config.values[k]) { + alts.push(`${f} for ${config.values[k]}`) + } + } + + const altText = alts.length > 0 ? ` (use ${alts.join(', ')})` : '' + lines.push(` ${flag.padEnd(24)}${label}${altText}`) + } + + // Import alias is not a boolean toggle, handle separately + const hasImportAlias = process.argv.some( + (arg) => + arg.startsWith('--import-alias') || + arg.startsWith('--no-import-alias') + ) + if (!hasImportAlias) { + lines.push(` ${'--import-alias'.padEnd(24)}"${defaults.importAlias}"`) + } + + if (lines.length > 0) { + console.log( + '\nUsing defaults for unprovided options:\n\n' + + lines.join('\n') + + '\n' + ) + } + } } const bundler: Bundler = opts.rspack ? Bundler.Rspack : Bundler.Turbopack diff --git a/test/integration/create-next-app/examples.test.ts b/test/integration/create-next-app/examples.test.ts index 03137f8e027f..f5124034d4e7 100644 --- a/test/integration/create-next-app/examples.test.ts +++ b/test/integration/create-next-app/examples.test.ts @@ -233,8 +233,12 @@ describe('create-next-app --example', () => { [ projectName, '--js', + '--no-app', '--no-tailwind', '--eslint', + '--no-src-dir', + '--no-react-compiler', + '--no-agents-md', '--example', 'default', '--import-alias=@/*', diff --git a/test/integration/create-next-app/index.test.ts b/test/integration/create-next-app/index.test.ts index 47eaaf6c0b60..f3003d1ec81b 100644 --- a/test/integration/create-next-app/index.test.ts +++ b/test/integration/create-next-app/index.test.ts @@ -164,6 +164,88 @@ describe('create-next-app', () => { }) }) + it('should print assumed defaults when flags are partially provided', async () => { + await useTempDir(async (cwd) => { + const projectName = 'partial-flags' + + const res = await run( + [ + projectName, + '--ts', + '--tailwind', + '--app', + '--skip-install', + ...(process.env.NEXT_RSPACK ? ['--rspack'] : []), + ], + nextTgzFilename, + { + cwd, + stdio: 'pipe', + } + ) + expect(res.exitCode).toBe(0) + + // Extract the defaults block from stdout + const defaultsMatch = res.stdout.match( + /Using defaults for unprovided options:\n\n([\s\S]*?)\n\nCreating/ + ) + expect(defaultsMatch).not.toBeNull() + expect(defaultsMatch[1]).toMatchInlineSnapshot(` + " --eslint ESLint (use --biome for Biome, --no-eslint for None) + --no-react-compiler No React Compiler (use --react-compiler for React Compiler) + --no-src-dir No src/ directory (use --src-dir for src/ directory) + --agents-md AGENTS.md (use --no-agents-md for No AGENTS.md) + --import-alias "@/*"" + `) + }) + }) + + it('should not print assumed defaults when all flags are provided', async () => { + await useTempDir(async (cwd) => { + const projectName = 'all-flags' + + const res = await run( + [ + projectName, + '--ts', + '--app', + '--eslint', + '--tailwind', + '--no-src-dir', + '--no-import-alias', + '--no-react-compiler', + '--no-agents-md', + '--skip-install', + ...(process.env.NEXT_RSPACK ? ['--rspack'] : []), + ], + nextTgzFilename, + { + cwd, + stdio: 'pipe', + } + ) + expect(res.exitCode).toBe(0) + expect(res.stdout).not.toContain('Using defaults for unprovided options') + }) + }) + + it('should not print assumed defaults with --yes flag', async () => { + await useTempDir(async (cwd) => { + const projectName = 'yes-flag' + + const res = await run( + [projectName, '--yes', '--skip-install'], + nextTgzFilename, + { + cwd, + stdio: 'pipe', + } + ) + expect(res.exitCode).toBe(0) + expect(res.stdout).not.toContain('Using defaults for unprovided options') + }) + }) + it('should not install dependencies if --skip-install', async () => { await useTempDir(async (cwd) => { const projectName = 'empty-dir' diff --git a/test/integration/create-next-app/prompts.test.ts b/test/integration/create-next-app/prompts.test.ts index 1f8d872f40bd..45b2dad86d93 100644 --- a/test/integration/create-next-app/prompts.test.ts +++ b/test/integration/create-next-app/prompts.test.ts @@ -57,7 +57,7 @@ describe('create-next-app prompts', () => { }) }) - it('should prompt user for choice if --js or --ts flag is absent', async () => { + it('should use default for --ts when other flags are provided', async () => { await useTempDir(async (cwd) => { const projectName = 'ts-js' const childProcess = createNextApp( @@ -77,9 +77,11 @@ describe('create-next-app prompts', () => { nextTgzFilename ) + // No stdin interaction needed - defaults are used automatically await new Promise((resolve) => { childProcess.on('exit', async (exitCode) => { expect(exitCode).toBe(0) + // Default is TypeScript projectFilesShouldExist({ cwd, projectName, @@ -87,14 +89,11 @@ describe('create-next-app prompts', () => { }) resolve() }) - - // select default choice: typescript - childProcess.stdin.write('\n') }) }) }) - it('should prompt user for choice if --tailwind is absent', async () => { + it('should use default for --tailwind when other flags are provided', async () => { await useTempDir(async (cwd) => { const projectName = 'tw' const childProcess = createNextApp( @@ -114,9 +113,11 @@ describe('create-next-app prompts', () => { nextTgzFilename ) + // No stdin interaction needed - defaults are used automatically await new Promise((resolve) => { childProcess.on('exit', async (exitCode) => { expect(exitCode).toBe(0) + // Default is Tailwind enabled projectFilesShouldExist({ cwd, projectName, @@ -124,14 +125,11 @@ describe('create-next-app prompts', () => { }) resolve() }) - - // select default choice: tailwind - childProcess.stdin.write('\n') }) }) }) - it('should prompt user for choice if --import-alias is absent', async () => { + it('should use default import alias when other flags are provided', async () => { await useTempDir(async (cwd) => { const projectName = 'import-alias' const childProcess = createNextApp( @@ -151,27 +149,18 @@ describe('create-next-app prompts', () => { nextTgzFilename ) - await new Promise(async (resolve) => { + // No stdin interaction needed - default import alias @/* is used + await new Promise((resolve) => { childProcess.on('exit', async (exitCode) => { expect(exitCode).toBe(0) resolve() }) - let output = '' - childProcess.stdout.on('data', (data) => { - output += data - process.stdout.write(data) - }) - // cursor forward, choose 'Yes' for custom import alias - childProcess.stdin.write('\u001b[C\n') - // used check here since it needs to wait for the prompt - await check(() => output, /What import alias would you like configured/) - childProcess.stdin.write('@/something/*\n') }) const tsConfig = require(join(cwd, projectName, 'tsconfig.json')) expect(tsConfig.compilerOptions.paths).toMatchInlineSnapshot(` { - "@/something/*": [ + "@/*": [ "./*", ], } From 34de2cac2918aa570a4c12c6e3ae9ed3d70d1f7a Mon Sep 17 00:00:00 2001 From: Will Binns-Smith Date: Mon, 30 Mar 2026 17:20:15 -0700 Subject: [PATCH 16/76] next.config.js: Accept an option for serverFastRefresh (#91968) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### What? Adds `experimental.serverFastRefresh` to `next.config.js` so users (and Next.js plugins) can opt out of server-side Fast Refresh without needing to pass a CLI flag. Also adds a `--server-fast-refresh` positive CLI flag (hidden) alongside the existing `--no-server-fast-refresh`, and emits a warning when the CLI flag and config value conflict. This is a necessary implementation detail for `commander` to detect when no option is provided. ### Why? Certain Next.js plugins have encountered issues with server Fast Refresh and need a way to disable it programmatically via config rather than requiring users to modify their start scripts. The CLI-only opt-out (`--no-server-fast-refresh`) was insufficient for this use case. ### How? - **`config-shared.ts` / `config-schema.ts`**: Added `experimental.serverFastRefresh?: boolean` to the `ExperimentalConfig` type and Zod schema. - **`router-server.ts`**: Resolves the effective `serverFastRefresh` value at startup by combining the CLI flag (`opts.serverFastRefresh`) and `nextConfig.experimental.serverFastRefresh`, with CLI taking precedence. Emits a `Log.warn` when both are set to conflicting values. Defaults to `true` when neither is specified. - **`bin/next.ts`**: Fixed the Commander option definition for `--no-server-fast-refresh`. Commander's `--no-X` pattern implicitly creates a positive `--server-fast-refresh` option defaulting to `true`, which meant `opts.serverFastRefresh` was never `undefined` and the config value could never take effect. Fixed by explicitly registering a hidden `--server-fast-refresh` option with `.default(undefined)`. - **Tests**: Added two new test suites in `test/development/app-dir/server-hmr/server-hmr.test.ts`: - `server-hmr config opt-out` — verifies that setting `experimental.serverFastRefresh: false` in config causes unmodified dependencies to be re-evaluated (i.e., server HMR is disabled). - `server-hmr CLI/config conflict warning` — verifies that passing `--no-server-fast-refresh` when config has `serverFastRefresh: true` logs the conflict warning. ### Test Plan - [x] Added e2e development tests (`test/development/app-dir/server-hmr/server-hmr.test.ts`) — all 8 tests pass --------- Co-authored-by: Will Binns-Smith Co-authored-by: Claude --- packages/next/src/bin/next.ts | 9 ++- packages/next/src/server/config-schema.ts | 1 + packages/next/src/server/config-shared.ts | 12 +++ packages/next/src/server/lib/router-server.ts | 23 +++++- .../app-dir/server-hmr/server-hmr.test.ts | 74 ++++++++++++++++++- 5 files changed, 116 insertions(+), 3 deletions(-) diff --git a/packages/next/src/bin/next.ts b/packages/next/src/bin/next.ts index d08775192b38..3df1cf6847a8 100755 --- a/packages/next/src/bin/next.ts +++ b/packages/next/src/bin/next.ts @@ -313,7 +313,14 @@ program '--experimental-https-ca, ', 'Path to a HTTPS certificate authority file.' ) - .option('--no-server-fast-refresh', 'Disable server-side Fast Refresh') + // `--server-fast-refresh` is hidden because it's the default behavior and + // only needs to be explicitly passed to override a + // `experimental.turbopackServerFastRefresh: false` in next.config. The + // `--no-server-fast-refresh` negation is the meaningful user-facing flag. + .addOption(new Option('--server-fast-refresh').default(undefined).hideHelp()) + .addOption( + new Option('--no-server-fast-refresh', 'Disable server-side Fast Refresh') + ) .option( '--experimental-upload-trace, ', 'Reports a subset of the debugging trace to a remote HTTP URL. Includes sensitive data.' diff --git a/packages/next/src/server/config-schema.ts b/packages/next/src/server/config-schema.ts index fcf78696eb2b..00754f2daf5f 100644 --- a/packages/next/src/server/config-schema.ts +++ b/packages/next/src/server/config-schema.ts @@ -355,6 +355,7 @@ export const experimentalSchema = { turbopackUseBuiltinSass: z.boolean().optional(), turbopackModuleIds: z.enum(['named', 'deterministic']).optional(), turbopackInferModuleSideEffects: z.boolean().optional(), + turbopackServerFastRefresh: z.boolean().optional(), optimizePackageImports: z.array(z.string()).optional(), optimizeServerReact: z.boolean().optional(), strictRouteTypes: z.boolean().optional(), diff --git a/packages/next/src/server/config-shared.ts b/packages/next/src/server/config-shared.ts index ae5ac929a4de..fdf20d88cdf0 100644 --- a/packages/next/src/server/config-shared.ts +++ b/packages/next/src/server/config-shared.ts @@ -674,6 +674,18 @@ export interface ExperimentalConfig { */ turbopackModuleIds?: 'named' | 'deterministic' + /** + * Enable server-side Fast Refresh (Hot Module Replacement) during development + * with Turbopack. When set to `false`, server-side HMR is disabled and a full + * restart is performed on server file changes. + * + * Can also be controlled via the `--no-server-fast-refresh` CLI flag. + * If both are set, the CLI flag takes precedence. + * + * @default true + */ + turbopackServerFastRefresh?: boolean + /** * For use with `@next/mdx`. Compile MDX files using the new Rust compiler. * @see https://nextjs.org/docs/app/api-reference/next-config-js/mdxRs diff --git a/packages/next/src/server/lib/router-server.ts b/packages/next/src/server/lib/router-server.ts index f866b8f46323..92ddf69eecc5 100644 --- a/packages/next/src/server/lib/router-server.ts +++ b/packages/next/src/server/lib/router-server.ts @@ -164,6 +164,27 @@ export async function initialize(opts: { // In development, it's always the complete config. let developmentConfig = config as NextConfigComplete + // Resolve the effective serverFastRefresh value. + // Both default to enabled (true). CLI takes precedence over config. + const cliServerFastRefresh = opts.serverFastRefresh + const configServerFastRefresh = + developmentConfig.experimental?.turbopackServerFastRefresh + let effectiveServerFastRefresh: boolean | undefined + if ( + cliServerFastRefresh !== undefined && + configServerFastRefresh !== undefined && + cliServerFastRefresh !== configServerFastRefresh + ) { + Log.warn( + `The CLI flag "${cliServerFastRefresh === false ? '--no-server-fast-refresh' : '--server-fast-refresh'}" conflicts with "experimental.turbopackServerFastRefresh: ${configServerFastRefresh}" in your Next.js config. The CLI flag will take precedence.` + ) + effectiveServerFastRefresh = cliServerFastRefresh + } else { + // Default to true when neither CLI nor config specifies a value. + effectiveServerFastRefresh = + cliServerFastRefresh ?? configServerFastRefresh ?? true + } + let developmentBundler = await setupDevBundlerSpan.traceAsyncFn(() => setupDevBundler({ // Passed here but the initialization of this object happens below, doing the initialization before the setupDev call breaks. @@ -179,7 +200,7 @@ export async function initialize(opts: { port: opts.port, onDevServerCleanup: opts.onDevServerCleanup, resetFetch, - serverFastRefresh: opts.serverFastRefresh, + serverFastRefresh: effectiveServerFastRefresh, }) ) diff --git a/test/development/app-dir/server-hmr/server-hmr.test.ts b/test/development/app-dir/server-hmr/server-hmr.test.ts index d3cad766240c..6c57125de8f2 100644 --- a/test/development/app-dir/server-hmr/server-hmr.test.ts +++ b/test/development/app-dir/server-hmr/server-hmr.test.ts @@ -1,5 +1,6 @@ import type { Response } from 'node-fetch' -import { nextTestSetup } from 'e2e-utils' +import { join } from 'path' +import { nextTestSetup, FileRef } from 'e2e-utils' import { retry } from 'next-test-utils' describe('server-hmr', () => { @@ -179,3 +180,74 @@ describe('server-hmr', () => { }) }) }) + +describe('server-hmr config opt-out', () => { + const { next, isTurbopack, isNextDev } = nextTestSetup({ + files: { + app: new FileRef(join(__dirname, 'app')), + }, + nextConfig: { + experimental: { + turbopackServerFastRefresh: false, + }, + }, + }) + + const itTurbopackDev = isTurbopack && isNextDev ? it : it.skip + + itTurbopackDev( + 're-evaluates unmodified dependencies when serverFastRefresh is disabled via config', + async () => { + const initial = await next + .fetch('/api/with-dep') + .then((res) => res.json()) + expect(initial.routeVersion).toBe('v1') + const initialDepEvaluatedAt = initial.depEvaluatedAt + + // Change only the route module, not the dependency + await next.patchFile('app/api/with-dep/route.ts', (content) => + content.replace("'v1'", "'v2'") + ) + + await retry(async () => { + const updated = await next + .fetch('/api/with-dep') + .then((res) => res.json()) + + expect(updated.routeVersion).toBe('v2') + + // With server HMR disabled, the dependency SHOULD be re-evaluated + // (full module graph is re-evaluated on changes) + expect(updated.depEvaluatedAt).not.toBe(initialDepEvaluatedAt) + }) + } + ) +}) + +describe('server-hmr CLI/config conflict warning', () => { + const { next, isNextDev } = nextTestSetup({ + files: { + app: new FileRef(join(__dirname, 'app')), + }, + nextConfig: { + experimental: { + turbopackServerFastRefresh: true, + }, + }, + startArgs: ['--no-server-fast-refresh'], + }) + + if (!isNextDev) { + it('should be skipped in production', () => {}) + return + } + + it('should warn when CLI flag conflicts with config', async () => { + // Trigger a page load so the server is fully started + await next.render('/') + + expect(next.cliOutput).toContain( + 'The CLI flag "--no-server-fast-refresh" conflicts with "experimental.turbopackServerFastRefresh: true" in your Next.js config. The CLI flag will take precedence.' + ) + }) +}) From d6446990d929c5560d652ce76634b450be057b4e Mon Sep 17 00:00:00 2001 From: Will Binns-Smith Date: Wed, 18 Mar 2026 20:57:41 -0700 Subject: [PATCH 17/76] Turbopack: enable server HMR for app route handlers (#91466) App router handlers are already built with the Turbopack runtime, so they can use server HMR. **We also already get subscription events for their chunks.** However, unlike app pages which use `__next_app__.require()` for dynamic devModuleCache lookup, route handlers capture userland exports statically in AppRouteRouteModule at construction time. This change makes routes behave a lot like pages, dynamically loading the user's code when requests are made. This way, we can freely invalidate and reload it when changes are made without evicting the entire require cache. Only `next dev` uses this lazy evaluation, as `next start` continues to eagerly import route handlers. This change removes the `isAppPage` restriction from `usesServerHmr`, extending server HMR coverage to all App Router entries (pages and route handlers) built with the Node.js runtime. For route handlers, we also clear the entry chunk from Node.js `require.cache` on each rebuild so the next `requirePage()` call re-executes the entry and obtains fresh module exports from `devModuleCache` (which HMR updates in-place). Test Plan: Added an additional e2e test, `with-dep` --- crates/next-api/src/project.rs | 7 ++- .../next/src/build/templates/app-route.ts | 14 ++++- .../src/server/dev/hot-reloader-turbopack.ts | 27 ++++---- .../server/route-modules/app-route/module.ts | 61 ++++++++++++++----- .../server-hmr/app/api/with-dep/dep.ts | 3 + .../server-hmr/app/api/with-dep/route.ts | 13 ++++ .../app-dir/server-hmr/server-hmr.test.ts | 28 +++++++++ 7 files changed, 118 insertions(+), 35 deletions(-) create mode 100644 test/development/app-dir/server-hmr/app/api/with-dep/dep.ts create mode 100644 test/development/app-dir/server-hmr/app/api/with-dep/route.ts diff --git a/crates/next-api/src/project.rs b/crates/next-api/src/project.rs index b01590d33ff7..815fb763eed3 100644 --- a/crates/next-api/src/project.rs +++ b/crates/next-api/src/project.rs @@ -869,7 +869,7 @@ impl ProjectContainer { self.project().entrypoints() } - /// See [Project::hmr_chunk_names]. + /// See [`Project::hmr_chunk_names`]. #[turbo_tasks::function] pub fn hmr_chunk_names(self: Vc, target: HmrTarget) -> Vc> { self.project().hmr_chunk_names(target) @@ -2318,8 +2318,9 @@ impl Project { } /// Gets a list of all HMR chunk names that can be subscribed to for the - /// specified target. This is only needed for testing purposes and isn't - /// used in real apps. + /// specified target. Used by the dev server to set up server-side HMR + /// subscriptions for all Node.js App Router entries (pages and route + /// handlers). #[turbo_tasks::function] pub async fn hmr_chunk_names(self: Vc, target: HmrTarget) -> Result>> { if let Some(map) = self.await?.versioned_content_map { diff --git a/packages/next/src/build/templates/app-route.ts b/packages/next/src/build/templates/app-route.ts index 50e8b04f5255..4817c5883e9b 100644 --- a/packages/next/src/build/templates/app-route.ts +++ b/packages/next/src/build/templates/app-route.ts @@ -2,6 +2,7 @@ import { AppRouteRouteModule, type AppRouteRouteHandlerContext, type AppRouteRouteModuleOptions, + type AppRouteUserlandModule, } from '../../server/route-modules/app-route/module.compiled' import { RouteKind } from '../../server/route-kind' import { patchFetch as _patchFetch } from '../../server/lib/patch-fetch' @@ -35,7 +36,6 @@ import { type ResponseCacheEntry, type ResponseGenerator, } from '../../server/response-cache' - import * as userland from 'VAR_USERLAND' // These are injected by the loader afterwards. This is injected as a variable @@ -59,7 +59,17 @@ const routeModule = new AppRouteRouteModule({ relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '', resolvedPagePath: 'VAR_RESOLVED_PAGE_PATH', nextConfigOutput, - userland, + // The static import is used for initialization (methods, dynamic, etc.). + userland: userland as AppRouteUserlandModule, + // In Turbopack dev mode, also provide a getter that calls require() on every + // request. This re-reads from devModuleCache so HMR updates are picked up, + // and the async wrapper unwraps async-module Promises (ESM-only + // serverExternalPackages) automatically. + ...(process.env.TURBOPACK && process.env.__NEXT_DEV_SERVER + ? { + getUserland: () => import('VAR_USERLAND'), + } + : {}), }) // Pull out the exports that we need to expose from the module. This should diff --git a/packages/next/src/server/dev/hot-reloader-turbopack.ts b/packages/next/src/server/dev/hot-reloader-turbopack.ts index f20f40bd5b70..a3194c5e880c 100644 --- a/packages/next/src/server/dev/hot-reloader-turbopack.ts +++ b/packages/next/src/server/dev/hot-reloader-turbopack.ts @@ -602,21 +602,16 @@ export async function createHotReloaderTurbopack( join(distDir, p) ) - const { type: entryType, page: entryPage } = splitEntryKey(key) - const isAppPage = - entryType === 'app' && - currentEntrypoints.app.get(entryPage)?.type === 'app-page' + const { type: entryType } = splitEntryKey(key) - // Server HMR only applies to app router pages since these use the Turbopack runtime. - // Currently, this is only app router pages. - // - // This excludes: - // - Pages Router pages - // - Edge routes - // - Middleware - // - App Router route handlers (route.ts) + // Server HMR applies to all App Router entries built with the Turbopack + // Node.js runtime: both app pages and route handlers. Edge routes, + // Pages Router pages, and middleware/instrumentation do not use the + // Turbopack Node.js dev runtime and are excluded. const usesServerHmr = - serverFastRefresh && isAppPage && writtenEndpoint.type !== 'edge' + serverFastRefresh && + entryType === 'app' && + writtenEndpoint.type !== 'edge' const filesToDelete: string[] = [] for (const file of serverPaths) { @@ -624,9 +619,9 @@ export async function createHotReloaderTurbopack( const relativePath = relative(distDir, file) if ( - // For Pages Router, edge routes, middleware, and manifest files - // (e.g., *_client-reference-manifest.js): clear the sharedCache in - // evalManifest(), Node.js require.cache, and edge runtime module contexts. + // For Pages Router, edge routes, middleware, and manifest files: + // clear the sharedCache in evalManifest(), Node.js require.cache, + // and edge runtime module contexts. force || !usesServerHmr || !serverHmrSubscriptions?.has(relativePath) diff --git a/packages/next/src/server/route-modules/app-route/module.ts b/packages/next/src/server/route-modules/app-route/module.ts index 2b985deeff80..df095e5a8a3f 100644 --- a/packages/next/src/server/route-modules/app-route/module.ts +++ b/packages/next/src/server/route-modules/app-route/module.ts @@ -176,6 +176,12 @@ export interface AppRouteRouteModuleOptions extends RouteModuleOptions { readonly resolvedPagePath: string readonly nextConfigOutput: NextConfig['output'] + /** + * Optional getter that returns the live userland module. When provided (in + * Turbopack dev mode), it is called on every request so that server HMR + * updates are picked up without re-executing the entry chunk. + */ + readonly getUserland?: () => Promise } /** @@ -212,32 +218,40 @@ export class AppRouteRouteModule extends RouteModule< public readonly resolvedPagePath: string public readonly nextConfigOutput: NextConfig['output'] | undefined - private readonly methods: Record - private readonly hasNonStaticMethods: boolean - private readonly dynamic: AppRouteUserlandModule['dynamic'] + private readonly _getUserland?: () => Promise + private methods: Record + private hasNonStaticMethods: boolean + private dynamic: AppRouteUserlandModule['dynamic'] constructor({ userland, + getUserland, definition, distDir, relativeProjectDir, resolvedPagePath, nextConfigOutput, }: AppRouteRouteModuleOptions) { - super({ userland, definition, distDir, relativeProjectDir }) + super({ + userland: userland!, + definition, + distDir, + relativeProjectDir, + }) this.resolvedPagePath = resolvedPagePath this.nextConfigOutput = nextConfigOutput + this._getUserland = getUserland // Automatically implement some methods if they aren't implemented by the // userland module. - this.methods = autoImplementMethods(userland) + this.methods = autoImplementMethods(userland!) // Get the non-static methods for this route. - this.hasNonStaticMethods = hasNonStaticMethods(userland) + this.hasNonStaticMethods = hasNonStaticMethods(userland!) // Get the dynamic property from the userland module. - this.dynamic = this.userland.dynamic + this.dynamic = userland!.dynamic if (this.nextConfigOutput === 'export') { if (this.dynamic === 'force-dynamic') { throw new Error( @@ -296,8 +310,22 @@ export class AppRouteRouteModule extends RouteModule< // Ensure that the requested method is a valid method (to prevent RCE's). if (!isHTTPMethod(method)) return () => new Response(null, { status: 400 }) - // Return the handler. - return this.methods[method] + return autoImplementMethods(this.userland as AppRouteUserlandModule)[method] + } + + /** + * Like resolve(), but re-fetches the userland module on every call via the + * async getter. Only used in Turbopack dev mode, where server HMR disposes + * modules between requests. The async wrapper also unwraps async-module + * Promises produced by ESM-only serverExternalPackages. + */ + private async resolveWithGetter( + method: string, + getUserland: () => Promise + ): Promise { + if (!isHTTPMethod(method)) return () => new Response(null, { status: 400 }) + const userland = await getUserland() + return autoImplementMethods(userland)[method] } private async do( @@ -692,8 +720,12 @@ export class AppRouteRouteModule extends RouteModule< req: NextRequest, context: AppRouteRouteHandlerContext ): Promise { - // Get the handler function for the given method. - const handler = this.resolve(req.method) + // Get the handler function for the given method. In Turbopack dev mode, + // use resolveWithGetter() to re-fetch the live userland on every request + // In all other modes, resolve() is synchronous. + const handler = this._getUserland + ? await this.resolveWithGetter(req.method, this._getUserland) + : this.resolve(req.method) // Get the context for the static generation. const staticGenerationContext: WorkStoreContext = { @@ -738,7 +770,7 @@ export class AppRouteRouteModule extends RouteModule< this.workAsyncStorage.run(workStore, async () => { // Check to see if we should bail out of static generation based on // having non-static methods. - if (this.hasNonStaticMethods) { + if (hasNonStaticMethods(this.userland)) { if (workStore.isStaticGeneration) { const err = new DynamicServerError( 'Route is configured with methods that cannot be statically generated.' @@ -754,7 +786,8 @@ export class AppRouteRouteModule extends RouteModule< let request = req // Update the static generation store based on the dynamic property. - switch (this.dynamic) { + const { dynamic } = this.userland + switch (dynamic) { case 'force-dynamic': { // Routes of generated paths should be dynamic workStore.forceDynamic = true @@ -790,7 +823,7 @@ export class AppRouteRouteModule extends RouteModule< request = proxyNextRequest(req, workStore) break default: - this.dynamic satisfies never + dynamic satisfies never } const tracer = getTracer() diff --git a/test/development/app-dir/server-hmr/app/api/with-dep/dep.ts b/test/development/app-dir/server-hmr/app/api/with-dep/dep.ts new file mode 100644 index 000000000000..dad0c6fb74d2 --- /dev/null +++ b/test/development/app-dir/server-hmr/app/api/with-dep/dep.ts @@ -0,0 +1,3 @@ +export const _hmrTrigger = 0 +export const depMessage = 'original message' +export const depEvaluatedAt = Date.now() diff --git a/test/development/app-dir/server-hmr/app/api/with-dep/route.ts b/test/development/app-dir/server-hmr/app/api/with-dep/route.ts new file mode 100644 index 000000000000..e5be89a97423 --- /dev/null +++ b/test/development/app-dir/server-hmr/app/api/with-dep/route.ts @@ -0,0 +1,13 @@ +import { depMessage, depEvaluatedAt } from './dep' + +const routeEvaluatedAt = Date.now() +const routeVersion = 'v1' + +export async function GET() { + return Response.json({ + depMessage, + depEvaluatedAt, + routeEvaluatedAt, + routeVersion, + }) +} diff --git a/test/development/app-dir/server-hmr/server-hmr.test.ts b/test/development/app-dir/server-hmr/server-hmr.test.ts index 6c57125de8f2..02691dccfc69 100644 --- a/test/development/app-dir/server-hmr/server-hmr.test.ts +++ b/test/development/app-dir/server-hmr/server-hmr.test.ts @@ -178,6 +178,34 @@ describe('server-hmr', () => { expect(updated).toBe('version: 1') }) }) + + itTurbopackDev( + 'does not re-evaluate an unmodified dependency when route changes', + async () => { + const initial = await next + .fetch('/api/with-dep') + .then((res) => res.json()) + expect(initial.routeVersion).toBe('v1') + const initialDepEvaluatedAt = initial.depEvaluatedAt + + // Change only the route module, not the dependency + await next.patchFile('app/api/with-dep/route.ts', (content) => + content.replace("'v1'", "'v2'") + ) + + await retry(async () => { + const updated = await next + .fetch('/api/with-dep') + .then((res) => res.json()) + + // The route change should be reflected in the response + expect(updated.routeVersion).toBe('v2') + + // The unmodified dependency should NOT have been re-evaluated + expect(updated.depEvaluatedAt).toBe(initialDepEvaluatedAt) + }) + } + ) }) }) From c0edad2762d309cf9125c1dee361227c0f4327d1 Mon Sep 17 00:00:00 2001 From: Will Binns-Smith Date: Mon, 30 Mar 2026 17:17:46 -0700 Subject: [PATCH 18/76] Turbopack: exclude metadata routes from server HMR (#92034) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### What? Metadata routes (`manifest.ts`, `robots.ts`, `sitemap.ts`, `icon.tsx`, `apple-icon.tsx`, etc.) were not being hot-reloaded in Turbopack dev mode — changes to those files would not be reflected on subsequent requests until a full server restart. ### Why? PR #91466 extended `usesServerHmr = true` in `clearRequireCache()` (in `hot-reloader-turbopack.ts`) from `app-page` entries only to **all** `app`-type entries (pages + route handlers). The motivation was correct: regular route handlers like `app/api/hello/route.ts` use Turbopack's in-place module update model and benefit from server HMR. However, metadata routes (`/manifest.webmanifest/route`, `/robots.txt/route`, etc.) are also `app`-type entries but they are **not** suitable for in-place server HMR. When `usesServerHmr = true` for a metadata route, `clearRequireCache()` skips two critical invalidation steps: 1. Deleting the compiled chunk from `require.cache` 2. Calling `__next__clear_chunk_cache__()` Without those steps, the old module stays in-memory and all subsequent requests to `/manifest.webmanifest` (etc.) return the stale content. ### How? Added an `!isMetadataRoute(entryPage)` guard to the `usesServerHmr` expression in `clearRequireCache()`. This restores full cache invalidation for metadata routes on every rebuild while leaving regular route handler server HMR (added in #91466) intact. ```ts // Before const usesServerHmr = serverFastRefresh && entryType === 'app' && writtenEndpoint.type !== 'edge' // After const usesServerHmr = serverFastRefresh && entryType === 'app' && writtenEndpoint.type !== 'edge' && !isMetadataRoute(entryPage) // ← metadata routes always clear the cache ``` `isMetadataRoute('/manifest.webmanifest/route')` → `true` (excluded from server HMR) `isMetadataRoute('/api/hello/route')` → `false` (keeps server HMR, no regression) Also added a regression test: `metadata route hmr > reflects manifest.ts changes on fetch/refresh` in the `server-hmr` test suite, with a `manifest.ts` fixture that starts at `name: 'Version 0'`. The test patches the file and asserts the updated JSON is returned on the next fetch. Fixes #91981 --------- Co-authored-by: Will Binns-Smith Co-authored-by: Claude --- .../src/server/dev/hot-reloader-turbopack.ts | 21 ++++++++++++------- .../app-dir/server-hmr/app/manifest.ts | 10 +++++++++ .../app-dir/server-hmr/server-hmr.test.ts | 20 ++++++++++++++++++ 3 files changed, 44 insertions(+), 7 deletions(-) create mode 100644 test/development/app-dir/server-hmr/app/manifest.ts diff --git a/packages/next/src/server/dev/hot-reloader-turbopack.ts b/packages/next/src/server/dev/hot-reloader-turbopack.ts index a3194c5e880c..271d8ab51696 100644 --- a/packages/next/src/server/dev/hot-reloader-turbopack.ts +++ b/packages/next/src/server/dev/hot-reloader-turbopack.ts @@ -82,7 +82,10 @@ import { isAppPageRouteDefinition } from '../route-definitions/app-page-route-de import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import type { ModernSourceMapPayload } from '../lib/source-maps' import { isDeferredEntry } from '../../build/entries' -import { isMetadataRouteFile } from '../../lib/metadata/is-metadata-route' +import { + isMetadataRoute, + isMetadataRouteFile, +} from '../../lib/metadata/is-metadata-route' import { setBundlerFindSourceMapImplementation } from '../patch-error-inspect' import { getNextErrorFeedbackMiddleware } from '../../next-devtools/server/get-next-error-feedback-middleware' import { @@ -602,16 +605,20 @@ export async function createHotReloaderTurbopack( join(distDir, p) ) - const { type: entryType } = splitEntryKey(key) + const { type: entryType, page: entryPage } = splitEntryKey(key) - // Server HMR applies to all App Router entries built with the Turbopack - // Node.js runtime: both app pages and route handlers. Edge routes, - // Pages Router pages, and middleware/instrumentation do not use the - // Turbopack Node.js dev runtime and are excluded. + // Server HMR applies to App Router entries built with the Turbopack Node.js + // runtime: app pages and regular route handlers. Edge routes, Pages Router + // pages, middleware/instrumentation, and metadata routes (manifest.ts, + // robots.ts, sitemap.ts, icon.tsx, etc.) are excluded. Metadata routes are + // excluded because they serve HTTP responses directly and must re-execute + // on every request to pick up file changes; the in-place module update + // model of Server HMR does not apply to them. const usesServerHmr = serverFastRefresh && entryType === 'app' && - writtenEndpoint.type !== 'edge' + writtenEndpoint.type !== 'edge' && + !isMetadataRoute(entryPage) const filesToDelete: string[] = [] for (const file of serverPaths) { diff --git a/test/development/app-dir/server-hmr/app/manifest.ts b/test/development/app-dir/server-hmr/app/manifest.ts new file mode 100644 index 000000000000..c24c6ade4365 --- /dev/null +++ b/test/development/app-dir/server-hmr/app/manifest.ts @@ -0,0 +1,10 @@ +import type { MetadataRoute } from 'next' + +export default function manifest(): MetadataRoute.Manifest { + return { + name: 'Version 0', + short_name: 'v0', + start_url: '/', + display: 'standalone', + } +} diff --git a/test/development/app-dir/server-hmr/server-hmr.test.ts b/test/development/app-dir/server-hmr/server-hmr.test.ts index 02691dccfc69..2f59d38659bc 100644 --- a/test/development/app-dir/server-hmr/server-hmr.test.ts +++ b/test/development/app-dir/server-hmr/server-hmr.test.ts @@ -156,6 +156,26 @@ describe('server-hmr', () => { ) }) + describe('metadata route hmr', () => { + it('reflects manifest.ts changes on fetch/refresh', async () => { + const initial = await next + .fetch('/manifest.webmanifest') + .then((res) => res.json()) + expect(initial.name).toBe('Version 0') + + await next.patchFile('app/manifest.ts', (content) => + content.replace('Version 0', 'Version 1') + ) + + await retry(async () => { + const updated = await next + .fetch('/manifest.webmanifest') + .then((res) => res.json()) + expect(updated.name).toBe('Version 1') + }) + }) + }) + describe('route handler hmr', () => { function getText(res: Response) { return res.ok From 1a319ea4dc564974371f9e7ff0f3693512fa018c Mon Sep 17 00:00:00 2001 From: Luke Sandberg Date: Tue, 31 Mar 2026 15:05:38 -0700 Subject: [PATCH 19/76] [backport] Fix CSS HMR on Safari (#92174) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary - Backport of #92123 to `next-16-2` release branch - Cherry-picked the CSS HMR Safari fix and regenerated turbopack-tests snapshot goldens for the release branch ## Test plan - [x] `UPDATE=1 cargo nextest r -p turbopack-tests` — all 297 tests pass - [x] `pnpm build-all` — clean build, no issues with `generated-native.d.ts` --- .github/workflows/build_and_test.yml | 15 ++++-- .../src/browser/dev/hmr-client/hmr-client.ts | 5 ++ .../browser/runtime/dom/dev-backend-dom.ts | 43 ++++++++++++----- .../runtime/dom/runtime-backend-dom.ts | 11 ++--- ...bug-ids_browser_input_index_0jat3.b.js.map | 6 +-- ...t_debug-ids_browser_input_index_0jat3.b.js | 47 +++++++++++++------ ...default_dev_runtime_input_index_0evo.uz.js | 43 ++++++++++++----- ...ult_dev_runtime_input_index_0evo.uz.js.map | 4 +- ...ansforms_preset_env_input_index_0ot90f-.js | 9 ++-- ...orms_preset_env_input_index_0ot90f-.js.map | 2 +- ...t_workers_basic_input_index_03~su6s.js.map | 4 +- ..._workers_basic_input_worker_11ydsw-.js.map | 4 +- ...pshot_workers_basic_input_index_03~su6s.js | 43 ++++++++++++----- ...shot_workers_basic_input_worker_11ydsw-.js | 43 ++++++++++++----- ..._workers_shared_input_index_00pjotx.js.map | 4 +- ...workers_shared_input_worker_0i7eipv.js.map | 4 +- ...shot_workers_shared_input_index_00pjotx.js | 43 ++++++++++++----- ...hot_workers_shared_input_worker_0i7eipv.js | 43 ++++++++++++----- 18 files changed, 252 insertions(+), 121 deletions(-) diff --git a/.github/workflows/build_and_test.yml b/.github/workflows/build_and_test.yml index 0dfe1aeaf4d0..d95b76f85040 100644 --- a/.github/workflows/build_and_test.yml +++ b/.github/workflows/build_and_test.yml @@ -1047,19 +1047,24 @@ jobs: # these all run without concurrency because they're heavier export TEST_CONCURRENCY=1 - export IS_WEBPACK_TEST=1 - - BROWSER_NAME=firefox node run-tests.js \ + export IS_TURBOPACK_TEST=1 + TURBOPACK_BUILD=1 NEXT_TEST_MODE=start BROWSER_NAME=firefox node run-tests.js \ test/production/pages-dir/production/test/index.test.ts \ test/production/chunk-load-failure/chunk-load-failure.test.ts - NEXT_TEST_MODE=start BROWSER_NAME=safari node run-tests.js \ + TURBOPACK_DEV=1 NEXT_TEST_MODE=dev BROWSER_NAME=firefox node run-tests.js \ + test/e2e/app-dir/scss/hmr-module/hmr-module.test.ts + + TURBOPACK_DEV=1 NEXT_TEST_MODE=dev BROWSER_NAME=safari node run-tests.js \ + test/e2e/app-dir/scss/hmr-module/hmr-module.test.ts + + TURBOPACK_BUILD=1 NEXT_TEST_MODE=start BROWSER_NAME=safari node run-tests.js \ test/production/pages-dir/production/test/index.test.ts \ test/production/chunk-load-failure/chunk-load-failure.test.ts \ test/e2e/basepath/basepath.test.ts \ test/e2e/basepath/error-pages.test.ts - BROWSER_NAME=safari DEVICE_NAME='iPhone XR' node run-tests.js \ + TURBOPACK_BUILD=1 NEXT_TEST_MODE=start BROWSER_NAME=safari DEVICE_NAME='iPhone XR' node run-tests.js \ test/production/prerender-prefetch/index.test.ts stepName: 'test-firefox-safari' secrets: inherit diff --git a/turbopack/crates/turbopack-ecmascript-runtime/js/src/browser/dev/hmr-client/hmr-client.ts b/turbopack/crates/turbopack-ecmascript-runtime/js/src/browser/dev/hmr-client/hmr-client.ts index 9cab5e10b0ec..fabe2cfc0557 100644 --- a/turbopack/crates/turbopack-ecmascript-runtime/js/src/browser/dev/hmr-client/hmr-client.ts +++ b/turbopack/crates/turbopack-ecmascript-runtime/js/src/browser/dev/hmr-client/hmr-client.ts @@ -237,6 +237,11 @@ function mergeChunkUpdates( return undefined } + if (updateB.type === 'total') { + // A total update replaces the entire chunk, so it supersedes any prior update. + return updateB + } + if (updateA.type === 'partial') { invariant(updateA.instruction, 'Partial updates are unsupported') } diff --git a/turbopack/crates/turbopack-ecmascript-runtime/js/src/browser/runtime/dom/dev-backend-dom.ts b/turbopack/crates/turbopack-ecmascript-runtime/js/src/browser/runtime/dom/dev-backend-dom.ts index 263c4450158a..a2bbd63600d8 100644 --- a/turbopack/crates/turbopack-ecmascript-runtime/js/src/browser/runtime/dom/dev-backend-dom.ts +++ b/turbopack/crates/turbopack-ecmascript-runtime/js/src/browser/runtime/dom/dev-backend-dom.ts @@ -18,12 +18,15 @@ let DEV_BACKEND: DevRuntimeBackend unloadChunk(chunkUrl) { deleteResolver(chunkUrl) + // Strip query string so we match links regardless of cache-busting + // params (e.g. ?ts=) that may differ between HMR updates. + const baseChunkUrl = chunkUrl.split('?')[0] // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped. - const decodedChunkUrl = decodeURI(chunkUrl) + const decodedBaseChunkUrl = decodeURI(baseChunkUrl) if (isCss(chunkUrl)) { const links = document.querySelectorAll( - `link[href="${chunkUrl}"],link[href^="${chunkUrl}?"],link[href="${decodedChunkUrl}"],link[href^="${decodedChunkUrl}?"]` + `link[href="${baseChunkUrl}"],link[href^="${baseChunkUrl}?"],link[href="${decodedBaseChunkUrl}"],link[href^="${decodedBaseChunkUrl}?"]` ) for (const link of Array.from(links)) { link.remove() @@ -34,7 +37,7 @@ let DEV_BACKEND: DevRuntimeBackend // However, we still want to remove the script tag from the DOM to keep // the HTML somewhat consistent from the user's perspective. const scripts = document.querySelectorAll( - `script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]` + `script[src="${baseChunkUrl}"],script[src^="${baseChunkUrl}?"],script[src="${decodedBaseChunkUrl}"],script[src^="${decodedBaseChunkUrl}?"]` ) for (const script of Array.from(scripts)) { script.remove() @@ -51,9 +54,12 @@ let DEV_BACKEND: DevRuntimeBackend return } - const decodedChunkUrl = decodeURI(chunkUrl) + // Strip query string so we match links regardless of cache-busting + // params (e.g. ?ts=) that may differ between HMR updates. + const baseChunkUrl = chunkUrl.split('?')[0] + const decodedBaseChunkUrl = decodeURI(baseChunkUrl) const previousLinks = document.querySelectorAll( - `link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]` + `link[rel=stylesheet][href="${baseChunkUrl}"],link[rel=stylesheet][href^="${baseChunkUrl}?"],link[rel=stylesheet][href="${decodedBaseChunkUrl}"],link[rel=stylesheet][href^="${decodedBaseChunkUrl}?"]` ) if (previousLinks.length === 0) { @@ -64,15 +70,28 @@ let DEV_BACKEND: DevRuntimeBackend const link = document.createElement('link') link.rel = 'stylesheet' - if (navigator.userAgent.includes('Firefox')) { - // Firefox won't reload CSS files that were previously loaded on the current page, - // we need to add a query param to make sure CSS is actually reloaded from the server. + if ( + navigator.userAgent.includes('Firefox') || + (navigator.userAgent.includes('Safari') && + !navigator.userAgent.includes('Chrome') && + !navigator.userAgent.includes('Chromium')) + ) { + // Firefox won't reload CSS files that were previously loaded on the + // current page: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506 // - // I believe this is this issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506 + // Safari serves cached CSS when a exists for the + // same URL: https://bugs.webkit.org/show_bug.cgi?id=187726 // - // Safari has a similar issue, but only if you have a `` tag - // pointing to the same URL as the stylesheet: https://bugs.webkit.org/show_bug.cgi?id=187726 - link.href = `${chunkUrl}?ts=${Date.now()}` + // Replace or add a fresh `ts` cache-busting param without + // discarding other query parameters that may already be present. + const url = new URL(chunkUrl, location.origin) + url.searchParams.set('ts', String(Date.now())) + // Reduced timer precision in some browers could lead to an update getting dropped + // in firefox if it happens fast enough (in firefox precision is sometimes 100ms!). + // So trust that the server is only updating us when it is important and use a + // random number to bust the cache. + url.searchParams.set('_next_rand', String(Math.random())) + link.href = url.pathname + url.search } else { link.href = chunkUrl } diff --git a/turbopack/crates/turbopack-ecmascript-runtime/js/src/browser/runtime/dom/runtime-backend-dom.ts b/turbopack/crates/turbopack-ecmascript-runtime/js/src/browser/runtime/dom/runtime-backend-dom.ts index d514565edc8b..79e620df1222 100644 --- a/turbopack/crates/turbopack-ecmascript-runtime/js/src/browser/runtime/dom/runtime-backend-dom.ts +++ b/turbopack/crates/turbopack-ecmascript-runtime/js/src/browser/runtime/dom/runtime-backend-dom.ts @@ -11,13 +11,10 @@ function getAssetSuffixFromScriptSrc() { // TURBOPACK_ASSET_SUFFIX is set in web workers - return ( - (self.TURBOPACK_ASSET_SUFFIX ?? - document?.currentScript - ?.getAttribute?.('src') - ?.replace(/^(.*(?=\?)|^.*$)/, '')) || - '' - ) + if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX + const src = document?.currentScript?.getAttribute?.('src') ?? '' + const qi = src.indexOf('?') + return qi >= 0 ? src.slice(qi) : '' } type ChunkResolver = { diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/output/0teu_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0jat3.b.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/output/0teu_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0jat3.b.js.map index 1c5331fb3763..6a225612f9f4 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/output/0teu_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0jat3.b.js.map +++ b/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/output/0teu_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0jat3.b.js.map @@ -1,12 +1,12 @@ { "version": 3, "sources": [], - "debugId": "c7d0d6f1-2fed-24f2-514f-5f447a850612", + "debugId": "154fe60a-f286-b7e0-80b6-f5300e0e86a1", "sections": [ {"offset": {"line": 15, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared/runtime/runtime-utils.ts"],"sourcesContent":["/**\n * This file contains runtime types and functions that are shared between all\n * TurboPack ECMAScript runtimes.\n *\n * It will be prepended to the runtime code of each runtime.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n\ntype EsmNamespaceObject = Record\n\n/**\n * Describes why a module was instantiated.\n * Shared between browser and Node.js runtimes.\n */\nenum SourceType {\n /**\n * The module was instantiated because it was included in an evaluated chunk's\n * runtime.\n * SourceData is a ChunkPath.\n */\n Runtime = 0,\n /**\n * The module was instantiated because a parent module imported it.\n * SourceData is a ModuleId.\n */\n Parent = 1,\n /**\n * The module was instantiated because it was included in a chunk's hot module\n * update.\n * SourceData is an array of ModuleIds or undefined.\n */\n Update = 2,\n}\n\ntype SourceData = ChunkPath | ModuleId | ModuleId[] | undefined\n\n// @ts-ignore Defined in `dev-base.ts`\ndeclare function getOrInstantiateModuleFromParent(\n id: ModuleId,\n sourceModule: M\n): M\n\n// @ts-ignore Defined in `hmr-runtime.ts` (dev mode only)\ndeclare let devModuleCache: Record | undefined\n\n/**\n * Flag indicating which module object type to create when a module is merged. Set to `true`\n * by each runtime that uses ModuleWithDirection (browser dev-base.ts, nodejs dev-base.ts,\n * nodejs build-base.ts). Browser production (build-base.ts) leaves it as `false` since it\n * uses plain Module objects.\n */\nlet createModuleWithDirectionFlag = false\n\nconst REEXPORTED_OBJECTS = new WeakMap()\n\n/**\n * Constructs the `__turbopack_context__` object for a module.\n */\nfunction Context(\n this: TurbopackBaseContext,\n module: Module,\n exports: Exports\n) {\n this.m = module\n // We need to store this here instead of accessing it from the module object to:\n // 1. Make it available to factories directly, since we rewrite `this` to\n // `__turbopack_context__.e` in CJS modules.\n // 2. Support async modules which rewrite `module.exports` to a promise, so we\n // can still access the original exports object from functions like\n // `esmExport`\n // Ideally we could find a new approach for async modules and drop this property altogether.\n this.e = exports\n}\nconst contextPrototype = Context.prototype as TurbopackBaseContext\n\ntype ModuleContextMap = Record\n\ninterface ModuleContextEntry {\n id: () => ModuleId\n module: () => any\n}\n\ninterface ModuleContext {\n // require call\n (moduleId: string): Exports | EsmNamespaceObject\n\n // async import call\n import(moduleId: string): Promise\n\n keys(): ModuleId[]\n\n resolve(moduleId: string): ModuleId\n}\n\ntype GetOrInstantiateModuleFromParent = (\n moduleId: M['id'],\n parentModule: M\n) => M\n\ndeclare function getOrInstantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): Module\n\nconst hasOwnProperty = Object.prototype.hasOwnProperty\nconst toStringTag = typeof Symbol !== 'undefined' && Symbol.toStringTag\n\nfunction defineProp(\n obj: any,\n name: PropertyKey,\n options: PropertyDescriptor & ThisType\n) {\n if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options)\n}\n\nfunction getOverwrittenModule(\n moduleCache: ModuleCache,\n id: ModuleId\n): Module {\n let module = moduleCache[id]\n if (!module) {\n if (createModuleWithDirectionFlag) {\n // set in development modes for hmr support\n module = createModuleWithDirection(id)\n } else {\n module = createModuleObject(id)\n }\n moduleCache[id] = module\n }\n return module\n}\n\n/**\n * Creates the module object. Only done here to ensure all module objects have the same shape.\n */\nfunction createModuleObject(id: ModuleId): Module {\n return {\n exports: {},\n error: undefined,\n id,\n namespaceObject: undefined,\n }\n}\n\nfunction createModuleWithDirection(id: ModuleId): ModuleWithDirection {\n return {\n exports: {},\n error: undefined,\n id,\n namespaceObject: undefined,\n parents: [],\n children: [],\n }\n}\n\ntype BindingTag = 0\nconst BindingTag_Value = 0 as BindingTag\n\n// an arbitrary sequence of bindings as\n// - a prop name\n// - BindingTag_Value, a value to be bound directly, or\n// - 1 or 2 functions to bind as getters and sdetters\ntype EsmBindings = Array<\n string | BindingTag | (() => unknown) | ((v: unknown) => void) | unknown\n>\n\n/**\n * Adds the getters to the exports object.\n */\nfunction esm(exports: Exports, bindings: EsmBindings) {\n defineProp(exports, '__esModule', { value: true })\n if (toStringTag) defineProp(exports, toStringTag, { value: 'Module' })\n let i = 0\n while (i < bindings.length) {\n const propName = bindings[i++] as string\n const tagOrFunction = bindings[i++]\n if (typeof tagOrFunction === 'number') {\n if (tagOrFunction === BindingTag_Value) {\n defineProp(exports, propName, {\n value: bindings[i++],\n enumerable: true,\n writable: false,\n })\n } else {\n throw new Error(`unexpected tag: ${tagOrFunction}`)\n }\n } else {\n const getterFn = tagOrFunction as () => unknown\n if (typeof bindings[i] === 'function') {\n const setterFn = bindings[i++] as (v: unknown) => void\n defineProp(exports, propName, {\n get: getterFn,\n set: setterFn,\n enumerable: true,\n })\n } else {\n defineProp(exports, propName, {\n get: getterFn,\n enumerable: true,\n })\n }\n }\n }\n Object.seal(exports)\n}\n\n/**\n * Makes the module an ESM with exports\n */\nfunction esmExport(\n this: TurbopackBaseContext,\n bindings: EsmBindings,\n id: ModuleId | undefined\n) {\n let module: Module\n let exports: Module['exports']\n if (id != null) {\n module = getOverwrittenModule(this.c, id)\n exports = module.exports\n } else {\n module = this.m\n exports = this.e\n }\n module.namespaceObject = exports\n esm(exports, bindings)\n}\ncontextPrototype.s = esmExport\n\ntype ReexportedObjects = Record[]\nfunction ensureDynamicExports(\n module: Module,\n exports: Exports\n): ReexportedObjects {\n let reexportedObjects: ReexportedObjects | undefined =\n REEXPORTED_OBJECTS.get(module)\n\n if (!reexportedObjects) {\n REEXPORTED_OBJECTS.set(module, (reexportedObjects = []))\n module.exports = module.namespaceObject = new Proxy(exports, {\n get(target, prop) {\n if (\n hasOwnProperty.call(target, prop) ||\n prop === 'default' ||\n prop === '__esModule'\n ) {\n return Reflect.get(target, prop)\n }\n for (const obj of reexportedObjects!) {\n const value = Reflect.get(obj, prop)\n if (value !== undefined) return value\n }\n return undefined\n },\n ownKeys(target) {\n const keys = Reflect.ownKeys(target)\n for (const obj of reexportedObjects!) {\n for (const key of Reflect.ownKeys(obj)) {\n if (key !== 'default' && !keys.includes(key)) keys.push(key)\n }\n }\n return keys\n },\n })\n }\n return reexportedObjects\n}\n\n/**\n * Dynamically exports properties from an object\n */\nfunction dynamicExport(\n this: TurbopackBaseContext,\n object: Record,\n id: ModuleId | undefined\n) {\n let module: Module\n let exports: Exports\n if (id != null) {\n module = getOverwrittenModule(this.c, id)\n exports = module.exports\n } else {\n module = this.m\n exports = this.e\n }\n const reexportedObjects = ensureDynamicExports(module, exports)\n\n if (typeof object === 'object' && object !== null) {\n reexportedObjects.push(object)\n }\n}\ncontextPrototype.j = dynamicExport\n\nfunction exportValue(\n this: TurbopackBaseContext,\n value: any,\n id: ModuleId | undefined\n) {\n let module: Module\n if (id != null) {\n module = getOverwrittenModule(this.c, id)\n } else {\n module = this.m\n }\n module.exports = value\n}\ncontextPrototype.v = exportValue\n\nfunction exportNamespace(\n this: TurbopackBaseContext,\n namespace: any,\n id: ModuleId | undefined\n) {\n let module: Module\n if (id != null) {\n module = getOverwrittenModule(this.c, id)\n } else {\n module = this.m\n }\n module.exports = module.namespaceObject = namespace\n}\ncontextPrototype.n = exportNamespace\n\nfunction createGetter(obj: Record, key: string | symbol) {\n return () => obj[key]\n}\n\n/**\n * @returns prototype of the object\n */\nconst getProto: (obj: any) => any = Object.getPrototypeOf\n ? (obj) => Object.getPrototypeOf(obj)\n : (obj) => obj.__proto__\n\n/** Prototypes that are not expanded for exports */\nconst LEAF_PROTOTYPES = [null, getProto({}), getProto([]), getProto(getProto)]\n\n/**\n * @param raw\n * @param ns\n * @param allowExportDefault\n * * `false`: will have the raw module as default export\n * * `true`: will have the default property as default export\n */\nfunction interopEsm(\n raw: Exports,\n ns: EsmNamespaceObject,\n allowExportDefault?: boolean\n) {\n const bindings: EsmBindings = []\n let defaultLocation = -1\n for (\n let current = raw;\n (typeof current === 'object' || typeof current === 'function') &&\n !LEAF_PROTOTYPES.includes(current);\n current = getProto(current)\n ) {\n for (const key of Object.getOwnPropertyNames(current)) {\n bindings.push(key, createGetter(raw, key))\n if (defaultLocation === -1 && key === 'default') {\n defaultLocation = bindings.length - 1\n }\n }\n }\n\n // this is not really correct\n // we should set the `default` getter if the imported module is a `.cjs file`\n if (!(allowExportDefault && defaultLocation >= 0)) {\n // Replace the binding with one for the namespace itself in order to preserve iteration order.\n if (defaultLocation >= 0) {\n // Replace the getter with the value\n bindings.splice(defaultLocation, 1, BindingTag_Value, raw)\n } else {\n bindings.push('default', BindingTag_Value, raw)\n }\n }\n\n esm(ns, bindings)\n return ns\n}\n\nfunction createNS(raw: Module['exports']): EsmNamespaceObject {\n if (typeof raw === 'function') {\n return function (this: any, ...args: any[]) {\n return raw.apply(this, args)\n }\n } else {\n return Object.create(null)\n }\n}\n\nfunction esmImport(\n this: TurbopackBaseContext,\n id: ModuleId\n): Exclude {\n const module = getOrInstantiateModuleFromParent(id, this.m)\n\n // any ES module has to have `module.namespaceObject` defined.\n if (module.namespaceObject) return module.namespaceObject\n\n // only ESM can be an async module, so we don't need to worry about exports being a promise here.\n const raw = module.exports\n return (module.namespaceObject = interopEsm(\n raw,\n createNS(raw),\n raw && (raw as any).__esModule\n ))\n}\ncontextPrototype.i = esmImport\n\nfunction asyncLoader(\n this: TurbopackBaseContext,\n moduleId: ModuleId\n): Promise {\n const loader = this.r(moduleId) as (\n importFunction: EsmImport\n ) => Promise\n return loader(esmImport.bind(this))\n}\ncontextPrototype.A = asyncLoader\n\n// Add a simple runtime require so that environments without one can still pass\n// `typeof require` CommonJS checks so that exports are correctly registered.\nconst runtimeRequire =\n // @ts-ignore\n typeof require === 'function'\n ? // @ts-ignore\n require\n : function require() {\n throw new Error('Unexpected use of runtime require')\n }\ncontextPrototype.t = runtimeRequire\n\nfunction commonJsRequire(\n this: TurbopackBaseContext,\n id: ModuleId\n): Exports {\n return getOrInstantiateModuleFromParent(id, this.m).exports\n}\ncontextPrototype.r = commonJsRequire\n\n/**\n * Remove fragments and query parameters since they are never part of the context map keys\n *\n * This matches how we parse patterns at resolving time. Arguably we should only do this for\n * strings passed to `import` but the resolve does it for `import` and `require` and so we do\n * here as well.\n */\nfunction parseRequest(request: string): string {\n // Per the URI spec fragments can contain `?` characters, so we should trim it off first\n // https://datatracker.ietf.org/doc/html/rfc3986#section-3.5\n const hashIndex = request.indexOf('#')\n if (hashIndex !== -1) {\n request = request.substring(0, hashIndex)\n }\n\n const queryIndex = request.indexOf('?')\n if (queryIndex !== -1) {\n request = request.substring(0, queryIndex)\n }\n\n return request\n}\n/**\n * `require.context` and require/import expression runtime.\n */\nfunction moduleContext(map: ModuleContextMap): ModuleContext {\n function moduleContext(id: string): Exports {\n id = parseRequest(id)\n if (hasOwnProperty.call(map, id)) {\n return map[id].module()\n }\n\n const e = new Error(`Cannot find module '${id}'`)\n ;(e as any).code = 'MODULE_NOT_FOUND'\n throw e\n }\n\n moduleContext.keys = (): string[] => {\n return Object.keys(map)\n }\n\n moduleContext.resolve = (id: string): ModuleId => {\n id = parseRequest(id)\n if (hasOwnProperty.call(map, id)) {\n return map[id].id()\n }\n\n const e = new Error(`Cannot find module '${id}'`)\n ;(e as any).code = 'MODULE_NOT_FOUND'\n throw e\n }\n\n moduleContext.import = async (id: string) => {\n return await (moduleContext(id) as Promise)\n }\n\n return moduleContext\n}\ncontextPrototype.f = moduleContext\n\n/**\n * Returns the path of a chunk defined by its data.\n */\nfunction getChunkPath(chunkData: ChunkData): ChunkPath {\n return typeof chunkData === 'string' ? chunkData : chunkData.path\n}\n\nfunction isPromise(maybePromise: any): maybePromise is Promise {\n return (\n maybePromise != null &&\n typeof maybePromise === 'object' &&\n 'then' in maybePromise &&\n typeof maybePromise.then === 'function'\n )\n}\n\nfunction isAsyncModuleExt(obj: T): obj is AsyncModuleExt & T {\n return turbopackQueues in obj\n}\n\nfunction createPromise() {\n let resolve: (value: T | PromiseLike) => void\n let reject: (reason?: any) => void\n\n const promise = new Promise((res, rej) => {\n reject = rej\n resolve = res\n })\n\n return {\n promise,\n resolve: resolve!,\n reject: reject!,\n }\n}\n\n// Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map.\n// The CompressedModuleFactories format is\n// - 1 or more module ids\n// - a module factory function\n// So walking this is a little complex but the flat structure is also fast to\n// traverse, we can use `typeof` operators to distinguish the two cases.\nfunction installCompressedModuleFactories(\n chunkModules: CompressedModuleFactories,\n offset: number,\n moduleFactories: ModuleFactories,\n newModuleId?: (id: ModuleId) => void\n) {\n let i = offset\n while (i < chunkModules.length) {\n let end = i + 1\n // Find our factory function\n while (\n end < chunkModules.length &&\n typeof chunkModules[end] !== 'function'\n ) {\n end++\n }\n if (end === chunkModules.length) {\n throw new Error('malformed chunk format, expected a factory function')\n }\n\n // Install the factory for each module ID that doesn't already have one.\n // When some IDs in this group already have a factory, reuse that existing\n // group factory for the missing IDs to keep all IDs in the group consistent.\n // Otherwise, install the factory from this chunk.\n const moduleFactoryFn = chunkModules[end] as Function\n let existingGroupFactory: Function | undefined = undefined\n for (let j = i; j < end; j++) {\n const id = chunkModules[j] as ModuleId\n const existingFactory = moduleFactories.get(id)\n if (existingFactory) {\n existingGroupFactory = existingFactory\n break\n }\n }\n const factoryToInstall = existingGroupFactory ?? moduleFactoryFn\n\n let didInstallFactory = false\n for (let j = i; j < end; j++) {\n const id = chunkModules[j] as ModuleId\n if (!moduleFactories.has(id)) {\n if (!didInstallFactory) {\n if (factoryToInstall === moduleFactoryFn) {\n applyModuleFactoryName(moduleFactoryFn)\n }\n didInstallFactory = true\n }\n moduleFactories.set(id, factoryToInstall)\n newModuleId?.(id)\n }\n }\n i = end + 1 // end is pointing at the last factory advance to the next id or the end of the array.\n }\n}\n\n// everything below is adapted from webpack\n// https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13\n\nconst turbopackQueues = Symbol('turbopack queues')\nconst turbopackExports = Symbol('turbopack exports')\nconst turbopackError = Symbol('turbopack error')\n\nconst enum QueueStatus {\n Unknown = -1,\n Unresolved = 0,\n Resolved = 1,\n}\n\ntype AsyncQueueFn = (() => void) & { queueCount: number }\ntype AsyncQueue = AsyncQueueFn[] & {\n status: QueueStatus\n}\n\nfunction resolveQueue(queue?: AsyncQueue) {\n if (queue && queue.status !== QueueStatus.Resolved) {\n queue.status = QueueStatus.Resolved\n queue.forEach((fn) => fn.queueCount--)\n queue.forEach((fn) => (fn.queueCount-- ? fn.queueCount++ : fn()))\n }\n}\n\ntype Dep = Exports | AsyncModulePromise | Promise\n\ntype AsyncModuleExt = {\n [turbopackQueues]: (fn: (queue: AsyncQueue) => void) => void\n [turbopackExports]: Exports\n [turbopackError]?: any\n}\n\ntype AsyncModulePromise = Promise & AsyncModuleExt\n\nfunction wrapDeps(deps: Dep[]): AsyncModuleExt[] {\n return deps.map((dep): AsyncModuleExt => {\n if (dep !== null && typeof dep === 'object') {\n if (isAsyncModuleExt(dep)) return dep\n if (isPromise(dep)) {\n const queue: AsyncQueue = Object.assign([], {\n status: QueueStatus.Unresolved,\n })\n\n const obj: AsyncModuleExt = {\n [turbopackExports]: {},\n [turbopackQueues]: (fn: (queue: AsyncQueue) => void) => fn(queue),\n }\n\n dep.then(\n (res) => {\n obj[turbopackExports] = res\n resolveQueue(queue)\n },\n (err) => {\n obj[turbopackError] = err\n resolveQueue(queue)\n }\n )\n\n return obj\n }\n }\n\n return {\n [turbopackExports]: dep,\n [turbopackQueues]: () => {},\n }\n })\n}\n\nfunction asyncModule(\n this: TurbopackBaseContext,\n body: (\n handleAsyncDependencies: (\n deps: Dep[]\n ) => Exports[] | Promise<() => Exports[]>,\n asyncResult: (err?: any) => void\n ) => void,\n hasAwait: boolean\n) {\n const module = this.m\n const queue: AsyncQueue | undefined = hasAwait\n ? Object.assign([], { status: QueueStatus.Unknown })\n : undefined\n\n const depQueues: Set = new Set()\n\n const { resolve, reject, promise: rawPromise } = createPromise()\n\n const promise: AsyncModulePromise = Object.assign(rawPromise, {\n [turbopackExports]: module.exports,\n [turbopackQueues]: (fn) => {\n queue && fn(queue)\n depQueues.forEach(fn)\n promise['catch'](() => {})\n },\n } satisfies AsyncModuleExt)\n\n const attributes: PropertyDescriptor = {\n get(): any {\n return promise\n },\n set(v: any) {\n // Calling `esmExport` leads to this.\n if (v !== promise) {\n promise[turbopackExports] = v\n }\n },\n }\n\n Object.defineProperty(module, 'exports', attributes)\n Object.defineProperty(module, 'namespaceObject', attributes)\n\n function handleAsyncDependencies(deps: Dep[]) {\n const currentDeps = wrapDeps(deps)\n\n const getResult = () =>\n currentDeps.map((d) => {\n if (d[turbopackError]) throw d[turbopackError]\n return d[turbopackExports]\n })\n\n const { promise, resolve } = createPromise<() => Exports[]>()\n\n const fn: AsyncQueueFn = Object.assign(() => resolve(getResult), {\n queueCount: 0,\n })\n\n function fnQueue(q: AsyncQueue) {\n if (q !== queue && !depQueues.has(q)) {\n depQueues.add(q)\n if (q && q.status === QueueStatus.Unresolved) {\n fn.queueCount++\n q.push(fn)\n }\n }\n }\n\n currentDeps.map((dep) => dep[turbopackQueues](fnQueue))\n\n return fn.queueCount ? promise : getResult()\n }\n\n function asyncResult(err?: any) {\n if (err) {\n reject((promise[turbopackError] = err))\n } else {\n resolve(promise[turbopackExports])\n }\n\n resolveQueue(queue)\n }\n\n body(handleAsyncDependencies, asyncResult)\n\n if (queue && queue.status === QueueStatus.Unknown) {\n queue.status = QueueStatus.Unresolved\n }\n}\ncontextPrototype.a = asyncModule\n\n/**\n * A pseudo \"fake\" URL object to resolve to its relative path.\n *\n * When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this\n * runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid\n * hydration mismatch.\n *\n * This is based on webpack's existing implementation:\n * https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js\n */\nconst relativeURL = function relativeURL(this: any, inputUrl: string) {\n const realUrl = new URL(inputUrl, 'x:/')\n const values: Record = {}\n for (const key in realUrl) values[key] = (realUrl as any)[key]\n values.href = inputUrl\n values.pathname = inputUrl.replace(/[?#].*/, '')\n values.origin = values.protocol = ''\n values.toString = values.toJSON = (..._args: Array) => inputUrl\n for (const key in values)\n Object.defineProperty(this, key, {\n enumerable: true,\n configurable: true,\n value: values[key],\n })\n}\nrelativeURL.prototype = URL.prototype\ncontextPrototype.U = relativeURL\n\n/**\n * Utility function to ensure all variants of an enum are handled.\n */\nfunction invariant(never: never, computeMessage: (arg: any) => string): never {\n throw new Error(`Invariant: ${computeMessage(never)}`)\n}\n\n/**\n * Constructs an error message for when a module factory is not available.\n */\nfunction factoryNotAvailableMessage(\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): string {\n let instantiationReason: string\n switch (sourceType) {\n case SourceType.Runtime:\n instantiationReason = `as a runtime entry of chunk ${sourceData}`\n break\n case SourceType.Parent:\n instantiationReason = `because it was required from module ${sourceData}`\n break\n case SourceType.Update:\n instantiationReason = 'because of an HMR update'\n break\n default:\n invariant(\n sourceType,\n (sourceType) => `Unknown source type: ${sourceType}`\n )\n }\n return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`\n}\n\n/**\n * A stub function to make `require` available but non-functional in ESM.\n */\nfunction requireStub(_moduleId: ModuleId): never {\n throw new Error('dynamic usage of require is not supported')\n}\ncontextPrototype.z = requireStub\n\n// Make `globalThis` available to the module in a way that cannot be shadowed by a local variable.\ncontextPrototype.g = globalThis\n\ntype ContextConstructor = {\n new (module: Module, exports: Exports): TurbopackBaseContext\n}\n\nfunction applyModuleFactoryName(factory: Function) {\n // Give the module factory a nice name to improve stack traces.\n Object.defineProperty(factory, 'name', {\n value: 'module evaluation',\n })\n}\n"],"names":["SourceType","createModuleWithDirectionFlag","REEXPORTED_OBJECTS","WeakMap","Context","module","exports","m","e","contextPrototype","prototype","hasOwnProperty","Object","toStringTag","Symbol","defineProp","obj","name","options","call","defineProperty","getOverwrittenModule","moduleCache","id","createModuleWithDirection","createModuleObject","error","undefined","namespaceObject","parents","children","BindingTag_Value","esm","bindings","value","i","length","propName","tagOrFunction","enumerable","writable","Error","getterFn","setterFn","get","set","seal","esmExport","c","s","ensureDynamicExports","reexportedObjects","Proxy","target","prop","Reflect","ownKeys","keys","key","includes","push","dynamicExport","object","j","exportValue","v","exportNamespace","namespace","n","createGetter","getProto","getPrototypeOf","__proto__","LEAF_PROTOTYPES","interopEsm","raw","ns","allowExportDefault","defaultLocation","current","getOwnPropertyNames","splice","createNS","args","apply","create","esmImport","getOrInstantiateModuleFromParent","__esModule","asyncLoader","moduleId","loader","r","bind","A","runtimeRequire","require","require1","t","commonJsRequire","parseRequest","request","hashIndex","indexOf","substring","queryIndex","moduleContext","map","code","resolve","import","f","getChunkPath","chunkData","path","isPromise","maybePromise","then","isAsyncModuleExt","turbopackQueues","createPromise","reject","promise","Promise","res","rej","installCompressedModuleFactories","chunkModules","offset","moduleFactories","newModuleId","end","moduleFactoryFn","existingGroupFactory","existingFactory","factoryToInstall","didInstallFactory","has","applyModuleFactoryName","turbopackExports","turbopackError","resolveQueue","queue","status","forEach","fn","queueCount","wrapDeps","deps","dep","assign","err","asyncModule","body","hasAwait","depQueues","Set","rawPromise","attributes","handleAsyncDependencies","currentDeps","getResult","d","fnQueue","q","add","asyncResult","a","relativeURL","inputUrl","realUrl","URL","values","href","pathname","replace","origin","protocol","toString","toJSON","_args","configurable","U","invariant","never","computeMessage","factoryNotAvailableMessage","sourceType","sourceData","instantiationReason","requireStub","_moduleId","z","g","globalThis","factory"],"mappings":"AAAA;;;;;CAKC,GAED,oDAAoD,GAEpD,6CAA6C;AAI7C;;;CAGC,GACD,IAAA,AAAKA,oCAAAA;IACH;;;;GAIC;IAED;;;GAGC;IAED;;;;GAIC;WAhBEA;EAAAA;AA+BL;;;;;CAKC,GACD,IAAIC,gCAAgC;AAEpC,MAAMC,qBAAqB,IAAIC;AAE/B;;CAEC,GACD,SAASC,QAEPC,MAAc,EACdC,OAAgB;IAEhB,IAAI,CAACC,CAAC,GAAGF;IACT,gFAAgF;IAChF,yEAAyE;IACzE,+CAA+C;IAC/C,8EAA8E;IAC9E,sEAAsE;IACtE,iBAAiB;IACjB,4FAA4F;IAC5F,IAAI,CAACG,CAAC,GAAGF;AACX;AACA,MAAMG,mBAAmBL,QAAQM,SAAS;AA+B1C,MAAMC,iBAAiBC,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tB,IAAIC;IACJ,OAAQF;QACN;YACEE,sBAAsB,CAAC,4BAA4B,EAAED,YAAY;YACjE;QACF;YACEC,sBAAsB,CAAC,oCAAoC,EAAED,YAAY;YACzE;QACF;YACEC,sBAAsB;YACtB;QACF;YACEN,UACEI,YACA,CAACA,aAAe,CAAC,qBAAqB,EAAEA,YAAY;IAE1D;IACA,OAAO,CAAC,OAAO,EAAEjG,SAAS,kBAAkB,EAAEmG,oBAAoB,0CAA0C,CAAC;AAC/G;AAEA;;CAEC,GACD,SAASC,YAAYC,SAAmB;IACtC,MAAM,IAAItJ,MAAM;AAClB;AACAhC,iBAAiBuL,CAAC,GAAGF;AAErB,kGAAkG;AAClGrL,iBAAiBwL,CAAC,GAAGC;AAMrB,SAASxD,uBAAuByD,OAAiB;IAC/C,+DAA+D;IAC/DvL,OAAOQ,cAAc,CAAC+K,SAAS,QAAQ;QACrCjK,OAAO;IACT;AACF","ignoreList":[0]}}, {"offset": {"line": 591, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/runtime-base.ts"],"sourcesContent":["/**\n * This file contains runtime types and functions that are shared between all\n * Turbopack *browser* ECMAScript runtimes.\n *\n * It will be appended to the runtime code of each runtime right after the\n * shared runtime utils.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\n// Used in WebWorkers to tell the runtime about the chunk suffix\ndeclare var TURBOPACK_ASSET_SUFFIX: string\n// Used in WebWorkers to tell the runtime about the current chunk url since it\n// can't be detected via `document.currentScript`. Note it's stored in reversed\n// order to use `push` and `pop`\ndeclare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined\n\n// Injected by rust code\ndeclare var CHUNK_BASE_PATH: string\ndeclare var ASSET_SUFFIX: string\ndeclare var WORKER_FORWARDED_GLOBALS: string[]\n\ninterface TurbopackBrowserBaseContext extends TurbopackBaseContext {\n R: ResolvePathFromModule\n}\n\nconst browserContextPrototype =\n Context.prototype as TurbopackBrowserBaseContext\n\n// Provided by build or dev base\ndeclare function instantiateModule(\n id: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): Module\n\ntype RuntimeParams = {\n otherChunks: ChunkData[]\n runtimeModuleIds: ModuleId[]\n}\n\ntype ChunkRegistrationChunk =\n | ChunkPath\n | { getAttribute: (name: string) => string | null }\n | undefined\n\ntype ChunkRegistration = [\n chunkPath: ChunkRegistrationChunk,\n ...([RuntimeParams] | CompressedModuleFactories),\n]\n\ntype ChunkList = {\n script: ChunkRegistrationChunk\n chunks: ChunkData[]\n source: 'entry' | 'dynamic'\n}\n\ninterface RuntimeBackend {\n registerChunk: (\n chunkPath: ChunkPath | ChunkScript,\n params?: RuntimeParams\n ) => void\n /**\n * Returns the same Promise for the same chunk URL.\n */\n loadChunkCached: (sourceType: SourceType, chunkUrl: ChunkUrl) => Promise\n loadWebAssembly: (\n sourceType: SourceType,\n sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ) => Promise\n loadWebAssemblyModule: (\n sourceType: SourceType,\n sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module\n ) => Promise\n}\n\ninterface DevRuntimeBackend {\n reloadChunk?: (chunkUrl: ChunkUrl) => Promise\n unloadChunk?: (chunkUrl: ChunkUrl) => void\n restart: () => void\n}\n\nconst moduleFactories: ModuleFactories = new Map()\ncontextPrototype.M = moduleFactories\n\nconst availableModules: Map | true> = new Map()\n\nconst availableModuleChunks: Map | true> = new Map()\n\nfunction loadChunk(\n this: TurbopackBrowserBaseContext,\n chunkData: ChunkData\n): Promise {\n return loadChunkInternal(SourceType.Parent, this.m.id, chunkData)\n}\nbrowserContextPrototype.l = loadChunk\n\nfunction loadInitialChunk(chunkPath: ChunkPath, chunkData: ChunkData) {\n return loadChunkInternal(SourceType.Runtime, chunkPath, chunkData)\n}\n\nasync function loadChunkInternal(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkData: ChunkData\n): Promise {\n if (typeof chunkData === 'string') {\n return loadChunkPath(sourceType, sourceData, chunkData)\n }\n\n const includedList = chunkData.included || []\n const modulesPromises = includedList.map((included) => {\n if (moduleFactories.has(included)) return true\n return availableModules.get(included)\n })\n if (modulesPromises.length > 0 && modulesPromises.every((p) => p)) {\n // When all included items are already loaded or loading, we can skip loading ourselves\n await Promise.all(modulesPromises)\n return\n }\n\n const includedModuleChunksList = chunkData.moduleChunks || []\n const moduleChunksPromises = includedModuleChunksList\n .map((included) => {\n // TODO(alexkirsz) Do we need this check?\n // if (moduleFactories[included]) return true;\n return availableModuleChunks.get(included)\n })\n .filter((p) => p)\n\n let promise: Promise\n if (moduleChunksPromises.length > 0) {\n // Some module chunks are already loaded or loading.\n\n if (moduleChunksPromises.length === includedModuleChunksList.length) {\n // When all included module chunks are already loaded or loading, we can skip loading ourselves\n await Promise.all(moduleChunksPromises)\n return\n }\n\n const moduleChunksToLoad: Set = new Set()\n for (const moduleChunk of includedModuleChunksList) {\n if (!availableModuleChunks.has(moduleChunk)) {\n moduleChunksToLoad.add(moduleChunk)\n }\n }\n\n for (const moduleChunkToLoad of moduleChunksToLoad) {\n const promise = loadChunkPath(sourceType, sourceData, moduleChunkToLoad)\n\n availableModuleChunks.set(moduleChunkToLoad, promise)\n\n moduleChunksPromises.push(promise)\n }\n\n promise = Promise.all(moduleChunksPromises)\n } else {\n promise = loadChunkPath(sourceType, sourceData, chunkData.path)\n\n // Mark all included module chunks as loading if they are not already loaded or loading.\n for (const includedModuleChunk of includedModuleChunksList) {\n if (!availableModuleChunks.has(includedModuleChunk)) {\n availableModuleChunks.set(includedModuleChunk, promise)\n }\n }\n }\n\n for (const included of includedList) {\n if (!availableModules.has(included)) {\n // It might be better to race old and new promises, but it's rare that the new promise will be faster than a request started earlier.\n // In production it's even more rare, because the chunk optimization tries to deduplicate modules anyway.\n availableModules.set(included, promise)\n }\n }\n\n await promise\n}\n\nconst loadedChunk = Promise.resolve(undefined)\nconst instrumentedBackendLoadChunks = new WeakMap<\n Promise,\n Promise | typeof loadedChunk\n>()\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkByUrl(\n this: TurbopackBrowserBaseContext,\n chunkUrl: ChunkUrl\n) {\n return loadChunkByUrlInternal(SourceType.Parent, this.m.id, chunkUrl)\n}\nbrowserContextPrototype.L = loadChunkByUrl\n\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkByUrlInternal(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkUrl: ChunkUrl\n): Promise {\n const thenable = BACKEND.loadChunkCached(sourceType, chunkUrl)\n let entry = instrumentedBackendLoadChunks.get(thenable)\n if (entry === undefined) {\n const resolve = instrumentedBackendLoadChunks.set.bind(\n instrumentedBackendLoadChunks,\n thenable,\n loadedChunk\n )\n entry = thenable.then(resolve).catch((cause) => {\n let loadReason: string\n switch (sourceType) {\n case SourceType.Runtime:\n loadReason = `as a runtime dependency of chunk ${sourceData}`\n break\n case SourceType.Parent:\n loadReason = `from module ${sourceData}`\n break\n case SourceType.Update:\n loadReason = 'from an HMR update'\n break\n default:\n invariant(\n sourceType,\n (sourceType) => `Unknown source type: ${sourceType}`\n )\n }\n let error = new Error(\n `Failed to load chunk ${chunkUrl} ${loadReason}${\n cause ? `: ${cause}` : ''\n }`,\n cause ? { cause } : undefined\n )\n error.name = 'ChunkLoadError'\n throw error\n })\n instrumentedBackendLoadChunks.set(thenable, entry)\n }\n\n return entry\n}\n\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkPath(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkPath: ChunkPath\n): Promise {\n const url = getChunkRelativeUrl(chunkPath)\n return loadChunkByUrlInternal(sourceType, sourceData, url)\n}\n\n/**\n * Returns an absolute url to an asset.\n */\nfunction resolvePathFromModule(\n this: TurbopackBaseContext,\n moduleId: string\n): string {\n const exported = this.r(moduleId)\n return exported?.default ?? exported\n}\nbrowserContextPrototype.R = resolvePathFromModule\n\n/**\n * no-op for browser\n * @param modulePath\n */\nfunction resolveAbsolutePath(modulePath?: string): string {\n return `/ROOT/${modulePath ?? ''}`\n}\nbrowserContextPrototype.P = resolveAbsolutePath\n\n/**\n * Exports a URL with the static suffix appended.\n */\nfunction exportUrl(\n this: TurbopackBrowserBaseContext,\n url: string,\n id: ModuleId | undefined\n) {\n exportValue.call(this, `${url}${ASSET_SUFFIX}`, id)\n}\nbrowserContextPrototype.q = exportUrl\n\n/**\n * Creates a worker by instantiating the given WorkerConstructor with the\n * appropriate URL and options.\n *\n * The entrypoint is a pre-compiled worker runtime file. The params configure\n * which module chunks to load and which module to run as the entry point.\n *\n * The params are a JSON array of the following structure:\n * `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`\n *\n * @param WorkerConstructor The Worker or SharedWorker constructor\n * @param entrypoint URL path to the worker entrypoint chunk\n * @param moduleChunks list of module chunk paths to load\n * @param workerOptions options to pass to the Worker constructor (optional)\n */\nfunction createWorker(\n WorkerConstructor: { new (url: URL, options?: object): Worker },\n entrypoint: ChunkPath,\n moduleChunks: ChunkPath[],\n workerOptions?: object\n): Worker {\n const isSharedWorker = WorkerConstructor.name === 'SharedWorker'\n\n const chunkUrls = moduleChunks\n .map((chunk) => getChunkRelativeUrl(chunk))\n .reverse()\n const params: unknown[] = [chunkUrls, ASSET_SUFFIX]\n for (const globalName of WORKER_FORWARDED_GLOBALS) {\n params.push((globalThis as Record)[globalName])\n }\n\n const url = new URL(getChunkRelativeUrl(entrypoint), location.origin)\n const paramsJson = JSON.stringify(params)\n if (isSharedWorker) {\n url.searchParams.set('params', paramsJson)\n } else {\n url.hash = '#params=' + encodeURIComponent(paramsJson)\n }\n\n // Remove type: \"module\" from options since our worker entrypoint is not a module\n const options = workerOptions\n ? { ...workerOptions, type: undefined }\n : undefined\n return new WorkerConstructor(url, options)\n}\nbrowserContextPrototype.b = createWorker\n\n/**\n * Instantiates a runtime module.\n */\nfunction instantiateRuntimeModule(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): Module {\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n/**\n * Returns the URL relative to the origin where a chunk can be fetched from.\n */\nfunction getChunkRelativeUrl(chunkPath: ChunkPath | ChunkListPath): ChunkUrl {\n return `${CHUNK_BASE_PATH}${chunkPath\n .split('/')\n .map((p) => encodeURIComponent(p))\n .join('/')}${ASSET_SUFFIX}` as ChunkUrl\n}\n\n/**\n * Return the ChunkPath from a ChunkScript.\n */\nfunction getPathFromScript(chunkScript: ChunkPath | ChunkScript): ChunkPath\nfunction getPathFromScript(\n chunkScript: ChunkListPath | ChunkListScript\n): ChunkListPath\nfunction getPathFromScript(\n chunkScript: ChunkPath | ChunkListPath | ChunkScript | ChunkListScript\n): ChunkPath | ChunkListPath {\n if (typeof chunkScript === 'string') {\n return chunkScript as ChunkPath | ChunkListPath\n }\n const chunkUrl = chunkScript.src!\n const src = decodeURIComponent(chunkUrl.replace(/[?#].*$/, ''))\n const path = src.startsWith(CHUNK_BASE_PATH)\n ? src.slice(CHUNK_BASE_PATH.length)\n : src\n return path as ChunkPath | ChunkListPath\n}\n\n/**\n * Return the ChunkUrl from a ChunkScript.\n */\nfunction getUrlFromScript(chunk: ChunkPath | ChunkScript): ChunkUrl {\n if (typeof chunk === 'string') {\n return getChunkRelativeUrl(chunk)\n } else {\n // This is already exactly what we want\n return chunk.src! as ChunkUrl\n }\n}\n\n/**\n * Determine the chunk to register. Note that this function has side-effects!\n */\nfunction getChunkFromRegistration(\n chunk: ChunkRegistrationChunk\n): ChunkPath | CurrentScript {\n if (typeof chunk === 'string') {\n return chunk\n } else if (!chunk) {\n if (typeof TURBOPACK_NEXT_CHUNK_URLS !== 'undefined') {\n return { src: TURBOPACK_NEXT_CHUNK_URLS.pop()! } as CurrentScript\n } else {\n throw new Error('chunk path empty but not in a worker')\n }\n } else {\n return { src: chunk.getAttribute('src')! } as CurrentScript\n }\n}\n\nconst regexJsUrl = /\\.js(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.\n */\nfunction isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {\n return regexJsUrl.test(chunkUrlOrPath)\n}\n\nconst regexCssUrl = /\\.css(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .css, optionally followed by ?query or #fragment.\n */\nfunction isCss(chunkUrl: ChunkUrl): boolean {\n return regexCssUrl.test(chunkUrl)\n}\n\nfunction loadWebAssembly(\n this: TurbopackBaseContext,\n chunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n): Promise {\n return BACKEND.loadWebAssembly(\n SourceType.Parent,\n this.m.id,\n chunkPath,\n edgeModule,\n importsObj\n )\n}\ncontextPrototype.w = loadWebAssembly\n\nfunction loadWebAssemblyModule(\n this: TurbopackBaseContext,\n chunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module\n): Promise {\n return BACKEND.loadWebAssemblyModule(\n SourceType.Parent,\n this.m.id,\n chunkPath,\n edgeModule\n )\n}\ncontextPrototype.u = loadWebAssemblyModule\n"],"names":["browserContextPrototype","Context","prototype","moduleFactories","Map","contextPrototype","M","availableModules","availableModuleChunks","loadChunk","chunkData","loadChunkInternal","SourceType","Parent","m","id","l","loadInitialChunk","chunkPath","Runtime","sourceType","sourceData","loadChunkPath","includedList","included","modulesPromises","map","has","get","length","every","p","Promise","all","includedModuleChunksList","moduleChunks","moduleChunksPromises","filter","promise","moduleChunksToLoad","Set","moduleChunk","add","moduleChunkToLoad","set","push","path","includedModuleChunk","loadedChunk","resolve","undefined","instrumentedBackendLoadChunks","WeakMap","loadChunkByUrl","chunkUrl","loadChunkByUrlInternal","L","thenable","BACKEND","loadChunkCached","entry","bind","then","catch","cause","loadReason","Update","invariant","error","Error","name","url","getChunkRelativeUrl","resolvePathFromModule","moduleId","exported","r","default","R","resolveAbsolutePath","modulePath","P","exportUrl","exportValue","call","ASSET_SUFFIX","q","createWorker","WorkerConstructor","entrypoint","workerOptions","isSharedWorker","chunkUrls","chunk","reverse","params","globalName","WORKER_FORWARDED_GLOBALS","globalThis","URL","location","origin","paramsJson","JSON","stringify","searchParams","hash","encodeURIComponent","options","type","b","instantiateRuntimeModule","instantiateModule","CHUNK_BASE_PATH","split","join","getPathFromScript","chunkScript","src","decodeURIComponent","replace","startsWith","slice","getUrlFromScript","getChunkFromRegistration","TURBOPACK_NEXT_CHUNK_URLS","pop","getAttribute","regexJsUrl","isJs","chunkUrlOrPath","test","regexCssUrl","isCss","loadWebAssembly","edgeModule","importsObj","w","loadWebAssemblyModule","u"],"mappings":"AAAA;;;;;;CAMC,GAED,oDAAoD,GAEpD,6CAA6C;AAC7C,iEAAiE;AAEjE,gEAAgE;AAgBhE,MAAMA,0BACJC,QAAQC,SAAS;AA4DnB,MAAMC,kBAAmC,IAAIC;AAC7CC,iBAAiBC,CAAC,GAAGH;AAErB,MAAMI,mBAAuD,IAAIH;AAEjE,MAAMI,wBAA6D,IAAIJ;AAEvE,SAASK,UAEPC,SAAoB;IAEpB,OAAOC,kBAAkBC,WAAWC,MAAM,EAAE,IAAI,CAACC,CAAC,CAACC,EAAE,EAAEL;AACzD;AACAV,wBAAwBgB,CAAC,GAAGP;AAE5B,SAASQ,iBAAiBC,SAAoB,EAAER,SAAoB;IAClE,OAAOC,kBAAkBC,WAAWO,OAAO,EAAED,WAAWR;AAC1D;AAEA,eAAeC,kBACbS,UAAsB,EACtBC,UAAsB,EACtBX,SAAoB;IAEpB,IAAI,OAAOA,cAAc,UAAU;QACjC,OAAOY,cAAcF,YAAYC,YAAYX;IAC/C;IAEA,MAAMa,eAAeb,UAAUc,QAAQ,IAAI,EAAE;IAC7C,MAAMC,kBAAkBF,aAAaG,GAAG,CAAC,CAACF;QACxC,IAAIrB,gBAAgBwB,GAAG,CAACH,WAAW,OAAO;QAC1C,OAAOjB,iBAAiBqB,GAAG,CAACJ;IAC9B;IACA,IAA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I,CAACD;AACzB;AAEA,MAAME,cAAc;AACpB;;CAEC,GACD,SAASC,MAAM/E,QAAkB;IAC/B,OAAO8E,YAAYD,IAAI,CAAC7E;AAC1B;AAEA,SAASgF,gBAEPpH,SAAoB,EACpBqH,UAAoC,EACpCC,UAA+B;IAE/B,OAAO9E,QAAQ4E,eAAe,CAC5B1H,WAAWC,MAAM,EACjB,IAAI,CAACC,CAAC,CAACC,EAAE,EACTG,WACAqH,YACAC;AAEJ;AACAnI,iBAAiBoI,CAAC,GAAGH;AAErB,SAASI,sBAEPxH,SAAoB,EACpBqH,UAAoC;IAEpC,OAAO7E,QAAQgF,qBAAqB,CAClC9H,WAAWC,MAAM,EACjB,IAAI,CAACC,CAAC,CAACC,EAAE,EACTG,WACAqH;AAEJ;AACAlI,iBAAiBsI,CAAC,GAAGD","ignoreList":[0]}}, {"offset": {"line": 840, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared/runtime/hmr-runtime.ts"],"sourcesContent":["/// \n/// \n/// \n/// \n\ntype HotModuleFactoryFunction = ModuleFactoryFunction<\n HotModule,\n TurbopackBaseContext\n>\n\n/**\n * Shared HMR (Hot Module Replacement) implementation.\n *\n * This file contains the complete HMR implementation that's shared between\n * browser and Node.js runtimes. It manages module hot state, dependency\n * tracking, the module.hot API, and the full HMR update flow.\n */\n\n/**\n * The development module cache shared across the runtime.\n * Browser runtime declares this directly.\n * Node.js runtime assigns globalThis.__turbopack_module_cache__ to this.\n */\nlet devModuleCache: Record\n\n/**\n * Module IDs that are instantiated as part of the runtime of a chunk.\n */\nlet runtimeModules: Set\n\n/**\n * Maps module IDs to persisted data between executions of their hot module\n * implementation (`hot.data`).\n */\nconst moduleHotData: Map = new Map()\n\n/**\n * Maps module instances to their hot module state.\n * Uses WeakMap so it works with both HotModule and ModuleWithDirection.\n */\nconst moduleHotState: WeakMap = new WeakMap()\n\n/**\n * Modules that call `module.hot.invalidate()` (while being updated).\n */\nconst queuedInvalidatedModules: Set = new Set()\n\nclass UpdateApplyError extends Error {\n name = 'UpdateApplyError'\n\n dependencyChain: ModuleId[]\n\n constructor(message: string, dependencyChain: ModuleId[]) {\n super(message)\n this.dependencyChain = dependencyChain\n }\n}\n\ntype ModuleEffect =\n | {\n type: 'unaccepted'\n dependencyChain: ModuleId[]\n }\n | {\n type: 'self-declined'\n dependencyChain: ModuleId[]\n moduleId: ModuleId\n }\n | {\n type: 'declined'\n dependencyChain: ModuleId[]\n moduleId: ModuleId\n parentId: ModuleId\n }\n | {\n type: 'accepted'\n moduleId: ModuleId\n outdatedModules: Set\n outdatedDependencies: Map>\n }\n\n/**\n * Records parent-child relationship when a module imports another.\n * Should be called during module instantiation.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction trackModuleImport(\n parentModule: ModuleWithDirection,\n childModuleId: ModuleId,\n childModule: ModuleWithDirection | undefined\n): void {\n // Record that parent imports child\n if (parentModule.children.indexOf(childModuleId) === -1) {\n parentModule.children.push(childModuleId)\n }\n\n // Record that child is imported by parent\n if (childModule && childModule.parents.indexOf(parentModule.id) === -1) {\n childModule.parents.push(parentModule.id)\n }\n}\n\nfunction formatDependencyChain(dependencyChain: ModuleId[]): string {\n return `Dependency chain: ${dependencyChain.join(' -> ')}`\n}\n\n/**\n * Walks the dependency tree to find all modules affected by a change.\n * Returns information about whether the update can be accepted and which\n * modules need to be invalidated.\n *\n * @param moduleId - The module that changed\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept().\n * This is used for server-side HMR where pages auto-accept at the top level.\n */\nfunction getAffectedModuleEffects(\n moduleId: ModuleId,\n autoAcceptRootModules: boolean\n): ModuleEffect {\n const outdatedModules: Set = new Set()\n const outdatedDependencies: Map> = new Map()\n\n type QueueItem = { moduleId?: ModuleId; dependencyChain: ModuleId[] }\n\n const queue: QueueItem[] = [\n {\n moduleId,\n dependencyChain: [],\n },\n ]\n\n let nextItem\n while ((nextItem = queue.shift())) {\n const { moduleId, dependencyChain } = nextItem\n\n if (moduleId != null) {\n if (outdatedModules.has(moduleId)) {\n // Avoid infinite loops caused by cycles between modules in the dependency chain.\n continue\n }\n\n outdatedModules.add(moduleId)\n }\n\n // We've arrived at the runtime of the chunk, which means that nothing\n // else above can accept this update.\n if (moduleId === undefined) {\n if (autoAcceptRootModules) {\n return {\n type: 'accepted',\n moduleId,\n outdatedModules,\n outdatedDependencies,\n }\n }\n return {\n type: 'unaccepted',\n dependencyChain,\n }\n }\n\n const module = devModuleCache[moduleId]\n const hotState = moduleHotState.get(module)!\n\n if (\n // The module is not in the cache. Since this is a \"modified\" update,\n // it means that the module was never instantiated before.\n !module || // The module accepted itself without invalidating globalThis.\n // TODO is that right?\n (hotState.selfAccepted && !hotState.selfInvalidated)\n ) {\n continue\n }\n\n if (hotState.selfDeclined) {\n return {\n type: 'self-declined',\n dependencyChain,\n moduleId,\n }\n }\n\n if (runtimeModules.has(moduleId)) {\n if (autoAcceptRootModules) {\n continue\n }\n queue.push({\n moduleId: undefined,\n dependencyChain: [...dependencyChain, moduleId],\n })\n continue\n }\n\n for (const parentId of module.parents) {\n const parent = devModuleCache[parentId]\n\n if (!parent) {\n continue\n }\n\n const parentHotState = moduleHotState.get(parent)\n\n // Check if parent declined this dependency\n if (parentHotState?.declinedDependencies[moduleId]) {\n return {\n type: 'declined',\n dependencyChain: [...dependencyChain, moduleId],\n moduleId,\n parentId,\n }\n }\n\n // Skip if parent is already outdated\n if (outdatedModules.has(parentId)) {\n continue\n }\n\n // Check if parent accepts this dependency\n if (parentHotState?.acceptedDependencies[moduleId]) {\n if (!outdatedDependencies.has(parentId)) {\n outdatedDependencies.set(parentId, new Set())\n }\n outdatedDependencies.get(parentId)!.add(moduleId)\n continue\n }\n\n // Neither accepted nor declined — propagate to parent\n queue.push({\n moduleId: parentId,\n dependencyChain: [...dependencyChain, moduleId],\n })\n }\n\n // If no parents and we're at a root module, auto-accept if configured\n if (module.parents.length === 0 && autoAcceptRootModules) {\n continue\n }\n }\n\n return {\n type: 'accepted',\n moduleId,\n outdatedModules,\n outdatedDependencies,\n }\n}\n\n/**\n * Merges source dependency map into target dependency map.\n */\nfunction mergeDependencies(\n target: Map>,\n source: Map>\n): void {\n for (const [parentId, deps] of source) {\n const existing = target.get(parentId)\n if (existing) {\n for (const dep of deps) {\n existing.add(dep)\n }\n } else {\n target.set(parentId, new Set(deps))\n }\n }\n}\n\n/**\n * Computes all modules that need to be invalidated based on which modules changed.\n *\n * @param invalidated - The modules that have been invalidated\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction computedInvalidatedModules(\n invalidated: Iterable,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n} {\n const outdatedModules = new Set()\n const outdatedDependencies = new Map>()\n\n for (const moduleId of invalidated) {\n const effect = getAffectedModuleEffects(moduleId, autoAcceptRootModules)\n\n switch (effect.type) {\n case 'unaccepted':\n throw new UpdateApplyError(\n `cannot apply update: unaccepted module. ${formatDependencyChain(\n effect.dependencyChain\n )}.`,\n effect.dependencyChain\n )\n case 'self-declined':\n throw new UpdateApplyError(\n `cannot apply update: self-declined module. ${formatDependencyChain(\n effect.dependencyChain\n )}.`,\n effect.dependencyChain\n )\n case 'declined':\n throw new UpdateApplyError(\n `cannot apply update: declined dependency. ${formatDependencyChain(\n effect.dependencyChain\n )}. Declined by ${effect.parentId}.`,\n effect.dependencyChain\n )\n case 'accepted':\n for (const outdatedModuleId of effect.outdatedModules) {\n outdatedModules.add(outdatedModuleId)\n }\n mergeDependencies(outdatedDependencies, effect.outdatedDependencies)\n break\n default:\n invariant(effect, (effect) => `Unknown effect type: ${effect?.type}`)\n }\n }\n\n return { outdatedModules, outdatedDependencies }\n}\n\n/**\n * Creates the module.hot API object and its internal state.\n * This provides the HMR API that user code calls (module.hot.accept(), etc.)\n */\n\nfunction createModuleHot(\n moduleId: ModuleId,\n hotData: HotData\n): { hot: Hot; hotState: HotState } {\n const hotState: HotState = {\n selfAccepted: false,\n selfDeclined: false,\n selfInvalidated: false,\n disposeHandlers: [],\n acceptedDependencies: {},\n acceptedErrorHandlers: {},\n declinedDependencies: {},\n }\n\n const hot: Hot = {\n // TODO(alexkirsz) This is not defined in the HMR API. It was used to\n // decide whether to warn whenever an HMR-disposed module required other\n // modules. We might want to remove it.\n active: true,\n\n data: hotData ?? {},\n\n accept: (\n modules?: string | string[] | AcceptErrorHandler,\n callback?: AcceptCallback,\n errorHandler?: AcceptErrorHandler\n ) => {\n if (modules === undefined) {\n hotState.selfAccepted = true\n } else if (typeof modules === 'function') {\n hotState.selfAccepted = modules\n } else if (typeof modules === 'object' && modules !== null) {\n for (let i = 0; i < modules.length; i++) {\n hotState.acceptedDependencies[modules[i]] = callback || function () {}\n hotState.acceptedErrorHandlers[modules[i]] = errorHandler\n }\n } else {\n hotState.acceptedDependencies[modules] = callback || function () {}\n hotState.acceptedErrorHandlers[modules] = errorHandler\n }\n },\n\n decline: (dep?: string | string[]) => {\n if (dep === undefined) {\n hotState.selfDeclined = true\n } else if (typeof dep === 'object' && dep !== null) {\n for (let i = 0; i < dep.length; i++) {\n hotState.declinedDependencies[dep[i]] = true\n }\n } else {\n hotState.declinedDependencies[dep] = true\n }\n },\n\n dispose: (callback) => {\n hotState.disposeHandlers.push(callback)\n },\n\n addDisposeHandler: (callback) => {\n hotState.disposeHandlers.push(callback)\n },\n\n removeDisposeHandler: (callback) => {\n const idx = hotState.disposeHandlers.indexOf(callback)\n if (idx >= 0) {\n hotState.disposeHandlers.splice(idx, 1)\n }\n },\n\n invalidate: () => {\n hotState.selfInvalidated = true\n queuedInvalidatedModules.add(moduleId)\n },\n\n // NOTE(alexkirsz) This is part of the management API, which we don't\n // implement, but the Next.js React Refresh runtime uses this to decide\n // whether to schedule an update.\n status: () => 'idle',\n\n // NOTE(alexkirsz) Since we always return \"idle\" for now, these are no-ops.\n addStatusHandler: (_handler) => {},\n removeStatusHandler: (_handler) => {},\n\n // NOTE(jridgewell) Check returns the list of updated modules, but we don't\n // want the webpack code paths to ever update (the turbopack paths handle\n // this already).\n check: () => Promise.resolve(null),\n }\n\n return { hot, hotState }\n}\n\n/**\n * Processes queued invalidated modules and adds them to the outdated modules set.\n * Modules that call module.hot.invalidate() are queued and processed here.\n *\n * @param outdatedModules - The current set of outdated modules\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction applyInvalidatedModules(\n outdatedModules: Set,\n outdatedDependencies: Map>,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n} {\n if (queuedInvalidatedModules.size > 0) {\n const result = computedInvalidatedModules(\n queuedInvalidatedModules,\n autoAcceptRootModules\n )\n for (const moduleId of result.outdatedModules) {\n outdatedModules.add(moduleId)\n }\n mergeDependencies(outdatedDependencies, result.outdatedDependencies)\n\n queuedInvalidatedModules.clear()\n }\n\n return { outdatedModules, outdatedDependencies }\n}\n\n/**\n * Computes which outdated modules have self-accepted and can be hot reloaded.\n */\n\nfunction computeOutdatedSelfAcceptedModules(\n outdatedModules: Iterable\n): { moduleId: ModuleId; errorHandler: true | Function }[] {\n const outdatedSelfAcceptedModules: {\n moduleId: ModuleId\n errorHandler: true | Function\n }[] = []\n for (const moduleId of outdatedModules) {\n const module = devModuleCache[moduleId]\n const hotState = moduleHotState.get(module)\n if (module && hotState?.selfAccepted && !hotState.selfInvalidated) {\n outdatedSelfAcceptedModules.push({\n moduleId,\n errorHandler: hotState.selfAccepted,\n })\n }\n }\n return outdatedSelfAcceptedModules\n}\n\n/**\n * Disposes of an instance of a module.\n * Runs hot.dispose handlers and manages persistent hot data.\n *\n * NOTE: mode = \"replace\" will not remove modules from devModuleCache.\n * This must be done in a separate step afterwards.\n */\nfunction disposeModule(moduleId: ModuleId, mode: 'clear' | 'replace') {\n const module = devModuleCache[moduleId]\n if (!module) {\n return\n }\n\n const hotState = moduleHotState.get(module)\n if (!hotState) {\n return\n }\n\n const data: HotData = {}\n\n // Run the `hot.dispose` handler, if any, passing in the persistent\n // `hot.data` object.\n for (const disposeHandler of hotState.disposeHandlers) {\n disposeHandler(data)\n }\n\n // This used to warn in `getOrInstantiateModuleFromParent` when a disposed\n // module is still importing other modules.\n if (module.hot) {\n module.hot.active = false\n }\n\n moduleHotState.delete(module)\n\n // Remove the disposed module from its children's parent list.\n // It will be added back once the module re-instantiates and imports its\n // children again.\n for (const childId of module.children) {\n const child = devModuleCache[childId]\n if (!child) {\n continue\n }\n\n const idx = child.parents.indexOf(module.id)\n if (idx >= 0) {\n child.parents.splice(idx, 1)\n }\n }\n\n switch (mode) {\n case 'clear':\n delete devModuleCache[module.id]\n moduleHotData.delete(module.id)\n break\n case 'replace':\n moduleHotData.set(module.id, data)\n break\n default:\n invariant(mode, (mode) => `invalid mode: ${mode}`)\n }\n}\n\n/**\n * Dispose phase: runs dispose handlers and cleans up outdated/disposed modules.\n * Returns the parent modules of outdated modules for use in the apply phase.\n */\n\nfunction disposePhase(\n outdatedModules: Iterable,\n disposedModules: Iterable,\n outdatedDependencies: Map>\n): { outdatedModuleParents: Map> } {\n for (const moduleId of outdatedModules) {\n disposeModule(moduleId, 'replace')\n }\n\n for (const moduleId of disposedModules) {\n disposeModule(moduleId, 'clear')\n }\n\n // Removing modules from the module cache is a separate step.\n // We also want to keep track of previous parents of the outdated modules.\n const outdatedModuleParents = new Map>()\n for (const moduleId of outdatedModules) {\n const oldModule = devModuleCache[moduleId]\n outdatedModuleParents.set(moduleId, oldModule?.parents)\n delete devModuleCache[moduleId]\n }\n\n // Remove outdated dependencies from parent module's children list.\n // When a parent accepts a child's update, the child is re-instantiated\n // but the parent stays alive. We remove the old child reference so it\n // gets re-added when the child re-imports.\n for (const [parentId, deps] of outdatedDependencies) {\n const module = devModuleCache[parentId]\n if (module) {\n for (const dep of deps) {\n const idx = module.children.indexOf(dep)\n if (idx >= 0) {\n module.children.splice(idx, 1)\n }\n }\n }\n }\n\n return { outdatedModuleParents }\n}\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/**\n * Shared module instantiation logic.\n * This handles the full module instantiation flow for both browser and Node.js.\n * Only React Refresh hooks differ between platforms (passed as callback).\n */\nfunction instantiateModuleShared(\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n runtimeModules: Set,\n createModuleObjectFn: (id: ModuleId) => HotModule,\n createContextFn: (module: HotModule, exports: Exports, refresh?: any) => any,\n runModuleExecutionHooksFn: (\n module: HotModule,\n exec: (refresh: any) => void\n ) => void\n): HotModule {\n // 1. Factory validation (same in both browser and Node.js)\n const id = moduleId\n const moduleFactory = moduleFactories.get(id)\n if (typeof moduleFactory !== 'function') {\n throw new Error(\n factoryNotAvailableMessage(moduleId, sourceType, sourceData) +\n `\\nThis is often caused by a stale browser cache, misconfigured Cache-Control headers, or a service worker serving outdated responses.` +\n `\\nTo fix this, make sure your Cache-Control headers allow revalidation of chunks and review your service worker configuration. ` +\n `As an immediate workaround, try hard-reloading the page, clearing the browser cache, or unregistering any service workers.`\n )\n }\n\n // 2. Hot API setup (same in both - works for browser, included for Node.js)\n const hotData = moduleHotData.get(id)!\n const { hot, hotState } = createModuleHot(id, hotData)\n\n // 3. Parent assignment logic (same in both)\n let parents: ModuleId[]\n switch (sourceType) {\n case SourceType.Runtime:\n runtimeModules.add(id)\n parents = []\n break\n case SourceType.Parent:\n parents = [sourceData as ModuleId]\n break\n case SourceType.Update:\n parents = (sourceData as ModuleId[]) || []\n break\n default:\n throw new Error(`Unknown source type: ${sourceType}`)\n }\n\n // 4. Module creation (platform creates base module object)\n const module = createModuleObjectFn(id)\n const exports = module.exports\n module.parents = parents\n module.children = []\n module.hot = hot\n\n devModuleCache[id] = module\n moduleHotState.set(module, hotState)\n\n // 5. Module execution (React Refresh hooks are platform-specific)\n try {\n runModuleExecutionHooksFn(module, (refresh) => {\n const context = createContextFn(module, exports, refresh)\n moduleFactory.call(exports, context, module, exports)\n })\n } catch (error) {\n module.error = error as any\n throw error\n }\n\n // 6. ESM interop (same in both)\n if (module.namespaceObject && module.exports !== module.namespaceObject) {\n // in case of a circular dependency: cjs1 -> esm2 -> cjs1\n interopEsm(module.exports, module.namespaceObject)\n }\n\n return module\n}\n\n/**\n * Analyzes update entries and chunks to determine which modules were added, modified, or deleted.\n * This is pure logic that doesn't depend on the runtime environment.\n */\nfunction computeChangedModules(\n entries: Record,\n updates: Record,\n chunkModulesMap?: Map>\n): {\n added: Map\n modified: Map\n deleted: Set\n chunksAdded: Map>\n chunksDeleted: Map>\n} {\n const chunksAdded = new Map()\n const chunksDeleted = new Map()\n const added: Map = new Map()\n const modified = new Map()\n const deleted: Set = new Set()\n\n for (const [chunkPath, mergedChunkUpdate] of Object.entries(updates) as Array<\n [ChunkPath, EcmascriptMergedChunkUpdate]\n >) {\n switch (mergedChunkUpdate.type) {\n case 'added': {\n const updateAdded = new Set(mergedChunkUpdate.modules)\n for (const moduleId of updateAdded) {\n added.set(moduleId, entries[moduleId])\n }\n chunksAdded.set(chunkPath, updateAdded)\n break\n }\n case 'deleted': {\n const updateDeleted = chunkModulesMap\n ? new Set(chunkModulesMap.get(chunkPath))\n : new Set()\n for (const moduleId of updateDeleted) {\n deleted.add(moduleId)\n }\n chunksDeleted.set(chunkPath, updateDeleted)\n break\n }\n case 'partial': {\n const updateAdded = new Set(mergedChunkUpdate.added)\n const updateDeleted = new Set(mergedChunkUpdate.deleted)\n for (const moduleId of updateAdded) {\n added.set(moduleId, entries[moduleId])\n }\n for (const moduleId of updateDeleted) {\n deleted.add(moduleId)\n }\n chunksAdded.set(chunkPath, updateAdded)\n chunksDeleted.set(chunkPath, updateDeleted)\n break\n }\n default:\n throw new Error('Unknown merged chunk update type')\n }\n }\n\n // If a module was added from one chunk and deleted from another in the same update,\n // consider it to be modified, as it means the module was moved from one chunk to another\n // AND has new code in a single update.\n for (const moduleId of added.keys()) {\n if (deleted.has(moduleId)) {\n added.delete(moduleId)\n deleted.delete(moduleId)\n }\n }\n\n for (const [moduleId, entry] of Object.entries(entries)) {\n // Modules that haven't been added to any chunk but have new code are considered\n // to be modified.\n // This needs to be under the previous loop, as we need it to get rid of modules\n // that were added and deleted in the same update.\n if (!added.has(moduleId)) {\n modified.set(moduleId, entry)\n }\n }\n\n return { added, deleted, modified, chunksAdded, chunksDeleted }\n}\n\n/**\n * Compiles new module code and walks the dependency tree to find all outdated modules.\n * Uses the evalModuleEntry function to compile code (platform-specific).\n *\n * @param added - Map of added modules\n * @param modified - Map of modified modules\n * @param evalModuleEntry - Function to compile module code\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction computeOutdatedModules(\n added: Map,\n modified: Map,\n evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n newModuleFactories: Map\n} {\n const newModuleFactories = new Map()\n\n // Compile added modules\n for (const [moduleId, entry] of added) {\n if (entry != null) {\n newModuleFactories.set(moduleId, evalModuleEntry(entry))\n }\n }\n\n // Walk dependency tree to find all modules affected by modifications\n const { outdatedModules, outdatedDependencies } = computedInvalidatedModules(\n modified.keys(),\n autoAcceptRootModules\n )\n\n // Compile modified modules\n for (const [moduleId, entry] of modified) {\n newModuleFactories.set(moduleId, evalModuleEntry(entry))\n }\n\n return { outdatedModules, outdatedDependencies, newModuleFactories }\n}\n\n/**\n * Updates module factories and re-instantiates self-accepted modules.\n * Uses the instantiateModule function (platform-specific via callback).\n */\nfunction applyPhase(\n outdatedSelfAcceptedModules: {\n moduleId: ModuleId\n errorHandler: true | Function\n }[],\n newModuleFactories: Map,\n outdatedModuleParents: Map>,\n outdatedDependencies: Map>,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n instantiateModuleFn: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule,\n applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void,\n reportError: (err: any) => void\n) {\n // Update module factories\n for (const [moduleId, factory] of newModuleFactories.entries()) {\n applyModuleFactoryNameFn(factory)\n moduleFactories.set(moduleId, factory)\n }\n\n // TODO(alexkirsz) Run new runtime entries here.\n\n // Call accept handlers for outdated dependencies.\n // This runs BEFORE re-instantiating self-accepted modules, matching\n // webpack's behavior.\n for (const [parentId, deps] of outdatedDependencies) {\n const module = devModuleCache[parentId]\n if (!module) continue\n\n const hotState = moduleHotState.get(module)\n if (!hotState) continue\n\n // Group deps by callback, deduplicating callbacks that handle multiple deps.\n // Each callback receives only the deps it was registered for.\n const callbackDeps = new Map void), ModuleId[]>()\n const callbackErrorHandlers = new Map<\n AcceptCallback | (() => void),\n AcceptErrorHandler | undefined\n >()\n\n for (const dep of deps) {\n const acceptCallback = hotState.acceptedDependencies[dep]\n if (acceptCallback) {\n let depList = callbackDeps.get(acceptCallback)\n if (!depList) {\n depList = []\n callbackDeps.set(acceptCallback, depList)\n callbackErrorHandlers.set(\n acceptCallback,\n hotState.acceptedErrorHandlers[dep]\n )\n }\n depList.push(dep)\n }\n }\n\n for (const [callback, cbDeps] of callbackDeps) {\n try {\n callback.call(null, cbDeps)\n } catch (err: any) {\n const errorHandler = callbackErrorHandlers.get(callback)\n if (typeof errorHandler === 'function') {\n try {\n errorHandler(err, {\n moduleId: parentId,\n dependencyId: cbDeps[0],\n })\n } catch (err2) {\n reportError(err2)\n reportError(err)\n }\n } else {\n reportError(err)\n }\n }\n }\n }\n\n // Re-instantiate all outdated self-accepted modules\n for (const { moduleId, errorHandler } of outdatedSelfAcceptedModules) {\n try {\n instantiateModuleFn(\n moduleId,\n SourceType.Update,\n outdatedModuleParents.get(moduleId)\n )\n } catch (err) {\n if (typeof errorHandler === 'function') {\n try {\n errorHandler(err, { moduleId, module: devModuleCache[moduleId] })\n } catch (err2) {\n reportError(err2)\n reportError(err)\n }\n } else {\n reportError(err)\n }\n }\n }\n}\n\n/**\n * Internal implementation that orchestrates the full HMR update flow:\n * invalidation, disposal, and application of new modules.\n *\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction applyInternal(\n outdatedModules: Set,\n outdatedDependencies: Map>,\n disposedModules: Iterable,\n newModuleFactories: Map,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n instantiateModuleFn: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule,\n applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void,\n autoAcceptRootModules: boolean\n) {\n ;({ outdatedModules, outdatedDependencies } = applyInvalidatedModules(\n outdatedModules,\n outdatedDependencies,\n autoAcceptRootModules\n ))\n\n // Find self-accepted modules to re-instantiate\n const outdatedSelfAcceptedModules =\n computeOutdatedSelfAcceptedModules(outdatedModules)\n\n // Run dispose handlers, save hot.data, clear caches\n const { outdatedModuleParents } = disposePhase(\n outdatedModules,\n disposedModules,\n outdatedDependencies\n )\n\n let error: any\n\n function reportError(err: any) {\n if (!error) error = err // Keep first error\n }\n\n applyPhase(\n outdatedSelfAcceptedModules,\n newModuleFactories,\n outdatedModuleParents,\n outdatedDependencies,\n moduleFactories,\n devModuleCache,\n instantiateModuleFn,\n applyModuleFactoryNameFn,\n reportError\n )\n\n if (error) {\n throw error\n }\n\n // Recursively apply any queued invalidations from new module execution\n if (queuedInvalidatedModules.size > 0) {\n applyInternal(\n new Set(),\n new Map(),\n [],\n new Map(),\n moduleFactories,\n devModuleCache,\n instantiateModuleFn,\n applyModuleFactoryNameFn,\n autoAcceptRootModules\n )\n }\n}\n\n/**\n * Main entry point for applying an ECMAScript merged update.\n * This is called by both browser and Node.js runtimes with platform-specific callbacks.\n *\n * @param options.autoAcceptRootModules - If true, root modules auto-accept updates without explicit\n * module.hot.accept(). Used for server-side HMR where pages\n * auto-accept at the top level.\n */\nfunction applyEcmascriptMergedUpdateShared(options: {\n added: Map\n modified: Map\n disposedModules: Iterable\n evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction\n instantiateModule: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule\n applyModuleFactoryName: (factory: HotModuleFactoryFunction) => void\n moduleFactories: ModuleFactories\n devModuleCache: ModuleCache\n autoAcceptRootModules: boolean\n}) {\n const {\n added,\n modified,\n disposedModules,\n evalModuleEntry,\n instantiateModule,\n applyModuleFactoryName,\n moduleFactories,\n devModuleCache,\n autoAcceptRootModules,\n } = options\n\n const { outdatedModules, outdatedDependencies, newModuleFactories } =\n computeOutdatedModules(\n added,\n modified,\n evalModuleEntry,\n autoAcceptRootModules\n )\n\n applyInternal(\n outdatedModules,\n outdatedDependencies,\n disposedModules,\n newModuleFactories,\n moduleFactories,\n devModuleCache,\n instantiateModule,\n applyModuleFactoryName,\n autoAcceptRootModules\n )\n}\n"],"names":["devModuleCache","runtimeModules","moduleHotData","Map","moduleHotState","WeakMap","queuedInvalidatedModules","Set","UpdateApplyError","Error","name","dependencyChain","message","trackModuleImport","parentModule","childModuleId","childModule","children","indexOf","push","parents","id","formatDependencyChain","join","getAffectedModuleEffects","moduleId","autoAcceptRootModules","outdatedModules","outdatedDependencies","queue","nextItem","shift","has","add","undefined","type","module","hotState","get","selfAccepted","selfInvalidated","selfDeclined","parentId","parent","parentHotState","declinedDependencies","acceptedDependencies","set","length","mergeDependencies","target","source","deps","existing","dep","computedInvalidatedModules","invalidated","effect","outdatedModuleId","invariant","createModuleHot","hotData","disposeHandlers","acceptedErrorHandlers","hot","active","data","accept","modules","callback","errorHandler","i","decline","dispose","addDisposeHandler","removeDisposeHandler","idx","splice","invalidate","status","addStatusHandler","_handler","removeStatusHandler","check","Promise","resolve","applyInvalidatedModules","size","result","clear","computeOutdatedSelfAcceptedModules","outdatedSelfAcceptedModules","disposeModule","mode","disposeHandler","delete","childId","child","disposePhase","disposedModules","outdatedModuleParents","oldModule","instantiateModuleShared","sourceType","sourceData","moduleFactories","createModuleObjectFn","createContextFn","runModuleExecutionHooksFn","moduleFactory","factoryNotAvailableMessage","SourceType","Runtime","Parent","Update","exports","refresh","context","call","error","namespaceObject","interopEsm","computeChangedModules","entries","updates","chunkModulesMap","chunksAdded","chunksDeleted","added","modified","deleted","chunkPath","mergedChunkUpdate","Object","updateAdded","updateDeleted","keys","entry","computeOutdatedModules","evalModuleEntry","newModuleFactories","applyPhase","instantiateModuleFn","applyModuleFactoryNameFn","reportError","factory","callbackDeps","callbackErrorHandlers","acceptCallback","depList","cbDeps","err","dependencyId","err2","applyInternal","applyEcmascriptMergedUpdateShared","options","instantiateModule","applyModuleFactoryName"],"mappings":"AAAA,2CAA2C;AAC3C,6CAA6C;AAC7C,4CAA4C;AAC5C,4CAA4C;AAO5C;;;;;;CAMC,GAED;;;;CAIC,GACD,IAAIA;AAEJ;;CAEC,GACD,IAAIC;AAEJ;;;CAGC,GACD,MAAMC,gBAAwC,IAAIC;AAElD;;;CAGC,GACD,MAAMC,iBAAyC,IAAIC;AAEnD;;CAEC,GACD,MAAMC,2BAA0C,IAAIC;AAEpD,MAAMC,yBAAyBC;IAC7BC,OAAO,mBAAkB;IAEzBC,gBAA2B;IAE3BH,YAAYI,OAAe,EAAED,eAA2B,CAAE;QACxD,KAAK,CAACC;QACN,IAAI,CAACD,eAAe,GAAGA;IACzB;AACF;AAyBA;;;CAGC,GACD,6DAA6D;AAC7D,SAASE,kBACPC,YAAiC,EACjCC,aAAuB,EACvBC,WAA4C;IAE5C,mCAAmC;IACnC,IAAIF,aAAaG,QAAQ,CAACC,OAAO,CAACH,mBAAmB,CAAC,GAAG;QACvDD,aAAaG,QAAQ,CAACE,IAAI,CAACJ;IAC7B;IAEA,0CAA0C;IAC1C,IAAIC,eAAeA,YAAYI,OAAO,CAACF,OAAO,CAACJ,aAAaO,EAAE,MAAM,CAAC,GAAG;QACtEL,YAAYI,OAAO,CAACD,IAAI,CAACL,aAAaO,EAAE;IAC1C;AACF;AAEA,SAASC,sBAAsBX,eAA2B;IACxD,OAAO,CAAC,kBAAkB,EAAEA,gBAAgBY,IAAI,CAAC,SAAS;AAC5D;AAEA;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;IAED,+CAA+C;IAC/C,MAAMiE,8BACJD,mCAAmC/D;IAErC,oDAAoD;IACpD,MAAM,EAAEyE,qBAAqB,EAAE,GAAGF,aAChCvE,iBACAwE,iBACAvE;IAGF,IAAI2F;IAEJ,SAASyB,YAAYO,GAAQ;QAC3B,IAAI,CAAChC,OAAOA,QAAQgC,KAAI,mBAAmB;IAC7C;IAEAV,WACElD,6BACAiD,oBACAxC,uBACAxE,sBACA6E,iBACAzG,gBACA8I,qBACAC,0BACAC;IAGF,IAAIzB,OAAO;QACT,MAAMA;IACR;IAEA,uEAAuE;IACvE,IAAIjH,yBAAyBiF,IAAI,GAAG,GAAG;QACrCmE,cACE,IAAInJ,OACJ,IAAIJ,OACJ,EAAE,EACF,IAAIA,OACJsG,iBACAzG,gBACA8I,qBACAC,0BACArH;IAEJ;AACF;AAEA;;;;;;;CAOC,GACD,SAASiI,kCAAkCC,OAc1C;IACC,MAAM,EACJ5B,KAAK,EACLC,QAAQ,EACR9B,eAAe,EACfwC,eAAe,EACfkB,iBAAiB,EACjBC,sBAAsB,EACtBrD,eAAe,EACfzG,cAAc,EACd0B,qBAAqB,EACtB,GAAGkI;IAEJ,MAAM,EAAEjI,eAAe,EAAEC,oBAAoB,EAAEgH,kBAAkB,EAAE,GACjEF,uBACEV,OACAC,UACAU,iBACAjH;IAGJgI,cACE/H,iBACAC,sBACAuE,iBACAyC,oBACAnC,iBACAzG,gBACA6J,mBACAC,wBACApI;AAEJ","ignoreList":[0]}}, {"offset": {"line": 1534, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/dev-base.ts"],"sourcesContent":["/// \n/// \n\ninterface TurbopackDevContext extends TurbopackBrowserBaseContext {\n k: RefreshContext\n}\n\nconst devContextPrototype = Context.prototype as TurbopackDevContext\n\n/**\n * This file contains runtime types and functions that are shared between all\n * Turbopack *development* ECMAScript runtimes.\n *\n * It will be appended to the runtime code of each runtime right after the\n * shared runtime utils.\n */\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n// Assign browser's module cache and runtime modules to shared HMR state\ndevModuleCache = Object.create(null)\ndevContextPrototype.c = devModuleCache\nruntimeModules = new Set()\n\n// Set flag to indicate we use ModuleWithDirection\ncreateModuleWithDirectionFlag = true\n\n// This file must not use `import` and `export` statements. Otherwise, it\n// becomes impossible to augment interfaces declared in ``d files\n// (e.g. `Module`). Hence, the need for `import()` here.\ntype RefreshRuntimeGlobals =\n import('@next/react-refresh-utils/dist/runtime').RefreshRuntimeGlobals\n\ndeclare var $RefreshHelpers$: RefreshRuntimeGlobals['$RefreshHelpers$']\ndeclare var $RefreshReg$: RefreshRuntimeGlobals['$RefreshReg$']\ndeclare var $RefreshSig$: RefreshRuntimeGlobals['$RefreshSig$']\ndeclare var $RefreshInterceptModuleExecution$: RefreshRuntimeGlobals['$RefreshInterceptModuleExecution$']\n\ntype RefreshContext = {\n register: RefreshRuntimeGlobals['$RefreshReg$']\n signature: RefreshRuntimeGlobals['$RefreshSig$']\n registerExports: typeof registerExportsAndSetupBoundaryForReactRefresh\n}\n\ntype RefreshHelpers = RefreshRuntimeGlobals['$RefreshHelpers$']\n\ntype ModuleFactory = (\n this: Module['exports'],\n context: TurbopackDevContext\n) => unknown\n\ninterface DevRuntimeBackend {\n reloadChunk?: (chunkUrl: ChunkUrl) => Promise\n unloadChunk?: (chunkUrl: ChunkUrl) => void\n restart: () => void\n}\n\n/**\n * Map from module ID to the chunks that contain this module.\n *\n * In HMR, we need to keep track of which modules are contained in which so\n * chunks. This is so we don't eagerly dispose of a module when it is removed\n * from chunk A, but still exists in chunk B.\n */\nconst moduleChunksMap: Map> = new Map()\n/**\n * Map from a chunk path to all modules it contains.\n */\nconst chunkModulesMap: Map> = new Map()\n/**\n * Chunk lists that contain a runtime. When these chunk lists receive an update\n * that can't be reconciled with the current state of the page, we need to\n * reload the runtime entirely.\n */\nconst runtimeChunkLists: Set = new Set()\n/**\n * Map from a chunk list to the chunk paths it contains.\n */\nconst chunkListChunksMap: Map> = new Map()\n/**\n * Map from a chunk path to the chunk lists it belongs to.\n */\nconst chunkChunkListsMap: Map> = new Map()\n\n/**\n * Gets or instantiates a runtime module.\n */\n// @ts-ignore\nfunction getOrInstantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): Module {\n const module = devModuleCache[moduleId]\n if (module) {\n if (module.error) {\n throw module.error\n }\n return module\n }\n\n // @ts-ignore\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it if it is not cached.\n */\n// @ts-ignore Defined in `runtime-utils.ts`\nconst getOrInstantiateModuleFromParent: GetOrInstantiateModuleFromParent<\n HotModule\n> = (id, sourceModule) => {\n if (!sourceModule.hot.active) {\n console.warn(\n `Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`\n )\n }\n\n const module = devModuleCache[id]\n\n if (sourceModule.children.indexOf(id) === -1) {\n sourceModule.children.push(id)\n }\n\n if (module) {\n if (module.error) {\n throw module.error\n }\n\n if (module.parents.indexOf(sourceModule.id) === -1) {\n module.parents.push(sourceModule.id)\n }\n\n return module\n }\n\n return instantiateModule(id, SourceType.Parent, sourceModule.id)\n}\n\nfunction DevContext(\n this: TurbopackDevContext,\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n) {\n Context.call(this, module, exports)\n this.k = refresh\n}\nDevContext.prototype = Context.prototype\n\ntype DevContextConstructor = {\n new (\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n ): TurbopackDevContext\n}\n\nfunction instantiateModule(\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): Module {\n // Browser: creates base HotModule object (hot API added by shared code)\n const createModuleObjectFn = (id: ModuleId) => {\n return createModuleObject(id) as HotModule\n }\n\n // Browser: creates DevContext with refresh\n const createContext = (\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n ) => {\n return new (DevContext as any as DevContextConstructor)(\n module,\n exports,\n refresh\n )\n }\n\n // Use shared instantiation logic (includes hot API setup)\n return instantiateModuleShared(\n moduleId,\n sourceType,\n sourceData,\n moduleFactories,\n devModuleCache,\n runtimeModules,\n createModuleObjectFn,\n createContext,\n runModuleExecutionHooks\n )\n}\n\nconst DUMMY_REFRESH_CONTEXT = {\n register: (_type: unknown, _id: unknown) => {},\n signature: () => (_type: unknown) => {},\n registerExports: (_module: unknown, _helpers: unknown) => {},\n}\n\n/**\n * NOTE(alexkirsz) Webpack has a \"module execution\" interception hook that\n * Next.js' React Refresh runtime hooks into to add module context to the\n * refresh registry.\n */\nfunction runModuleExecutionHooks(\n module: HotModule,\n executeModule: (ctx: RefreshContext) => void\n) {\n if (typeof globalThis.$RefreshInterceptModuleExecution$ === 'function') {\n const cleanupReactRefreshIntercept =\n globalThis.$RefreshInterceptModuleExecution$(module.id)\n try {\n executeModule({\n register: globalThis.$RefreshReg$,\n signature: globalThis.$RefreshSig$,\n registerExports: registerExportsAndSetupBoundaryForReactRefresh,\n })\n } finally {\n // Always cleanup the intercept, even if module execution failed.\n cleanupReactRefreshIntercept()\n }\n } else {\n // If the react refresh hooks are not installed we need to bind dummy functions.\n // This is expected when running in a Web Worker. It is also common in some of\n // our test environments.\n executeModule(DUMMY_REFRESH_CONTEXT)\n }\n}\n\n/**\n * This is adapted from https://github.com/vercel/next.js/blob/3466862d9dc9c8bb3131712134d38757b918d1c0/packages/react-refresh-utils/internal/ReactRefreshModule.runtime.ts\n */\nfunction registerExportsAndSetupBoundaryForReactRefresh(\n module: HotModule,\n helpers: RefreshHelpers\n) {\n const currentExports = module.exports\n const prevExports = module.hot.data.prevExports ?? null\n\n helpers.registerExportsForReactRefresh(currentExports, module.id)\n\n // A module can be accepted automatically based on its exports, e.g. when\n // it is a Refresh Boundary.\n if (helpers.isReactRefreshBoundary(currentExports)) {\n // Save the previous exports on update, so we can compare the boundary\n // signatures.\n module.hot.dispose((data) => {\n data.prevExports = currentExports\n })\n // Unconditionally accept an update to this module, we'll check if it's\n // still a Refresh Boundary later.\n module.hot.accept()\n\n // This field is set when the previous version of this module was a\n // Refresh Boundary, letting us know we need to check for invalidation or\n // enqueue an update.\n if (prevExports !== null) {\n // A boundary can become ineligible if its exports are incompatible\n // with the previous exports.\n //\n // For example, if you add/remove/change exports, we'll want to\n // re-execute the importing modules, and force those components to\n // re-render. Similarly, if you convert a class component to a\n // function, we want to invalidate the boundary.\n if (\n helpers.shouldInvalidateReactRefreshBoundary(\n helpers.getRefreshBoundarySignature(prevExports),\n helpers.getRefreshBoundarySignature(currentExports)\n )\n ) {\n module.hot.invalidate()\n } else {\n helpers.scheduleUpdate()\n }\n }\n } else {\n // Since we just executed the code for the module, it's possible that the\n // new exports made it ineligible for being a boundary.\n // We only care about the case when we were _previously_ a boundary,\n // because we already accepted this update (accidental side effect).\n const isNoLongerABoundary = prevExports !== null\n if (isNoLongerABoundary) {\n module.hot.invalidate()\n }\n }\n}\n\n/**\n * Adds, deletes, and moves modules between chunks. This must happen before the\n * dispose phase as it needs to know which modules were removed from all chunks,\n * which we can only compute *after* taking care of added and moved modules.\n */\nfunction updateChunksPhase(\n chunksAddedModules: Map>,\n chunksDeletedModules: Map>\n): { disposedModules: Set } {\n for (const [chunkPath, addedModuleIds] of chunksAddedModules) {\n for (const moduleId of addedModuleIds) {\n addModuleToChunk(moduleId, chunkPath)\n }\n }\n\n const disposedModules: Set = new Set()\n for (const [chunkPath, addedModuleIds] of chunksDeletedModules) {\n for (const moduleId of addedModuleIds) {\n if (removeModuleFromChunk(moduleId, chunkPath)) {\n disposedModules.add(moduleId)\n }\n }\n }\n\n return { disposedModules }\n}\n\nfunction applyUpdate(update: PartialUpdate) {\n switch (update.type) {\n case 'ChunkListUpdate':\n applyChunkListUpdate(update)\n break\n default:\n invariant(update, (update) => `Unknown update type: ${update.type}`)\n }\n}\n\nfunction applyChunkListUpdate(update: ChunkListUpdate) {\n if (update.merged != null) {\n for (const merged of update.merged) {\n switch (merged.type) {\n case 'EcmascriptMergedUpdate':\n applyEcmascriptMergedUpdate(merged)\n break\n default:\n invariant(merged, (merged) => `Unknown merged type: ${merged.type}`)\n }\n }\n }\n\n if (update.chunks != null) {\n for (const [chunkPath, chunkUpdate] of Object.entries(\n update.chunks\n ) as Array<[ChunkPath, ChunkUpdate]>) {\n const chunkUrl = getChunkRelativeUrl(chunkPath)\n\n switch (chunkUpdate.type) {\n case 'added':\n BACKEND.loadChunkCached(SourceType.Update, chunkUrl)\n break\n case 'total':\n DEV_BACKEND.reloadChunk?.(chunkUrl)\n break\n case 'deleted':\n DEV_BACKEND.unloadChunk?.(chunkUrl)\n break\n case 'partial':\n invariant(\n chunkUpdate.instruction,\n (instruction) =>\n `Unknown partial instruction: ${JSON.stringify(instruction)}.`\n )\n break\n default:\n invariant(\n chunkUpdate,\n (chunkUpdate) => `Unknown chunk update type: ${chunkUpdate.type}`\n )\n }\n }\n }\n}\n\nfunction applyEcmascriptMergedUpdate(update: EcmascriptMergedUpdate) {\n // Browser-specific chunk management phase\n const { entries = {}, chunks = {} } = update\n const { added, modified, chunksAdded, chunksDeleted } = computeChangedModules(\n entries,\n chunks,\n chunkModulesMap\n )\n const { disposedModules } = updateChunksPhase(chunksAdded, chunksDeleted)\n\n // Use shared HMR update implementation\n applyEcmascriptMergedUpdateShared({\n added,\n modified,\n disposedModules,\n evalModuleEntry: _eval, // browser's eval with source maps\n instantiateModule, // now wraps shared logic\n applyModuleFactoryName,\n moduleFactories,\n devModuleCache,\n autoAcceptRootModules: false,\n })\n}\n\nfunction handleApply(chunkListPath: ChunkListPath, update: ServerMessage) {\n switch (update.type) {\n case 'partial': {\n // This indicates that the update is can be applied to the current state of the application.\n applyUpdate(update.instruction)\n break\n }\n case 'restart': {\n // This indicates that there is no way to apply the update to the\n // current state of the application, and that the application must be\n // restarted.\n DEV_BACKEND.restart()\n break\n }\n case 'notFound': {\n // This indicates that the chunk list no longer exists: either the dynamic import which created it was removed,\n // or the page itself was deleted.\n // If it is a dynamic import, we simply discard all modules that the chunk has exclusive access to.\n // If it is a runtime chunk list, we restart the application.\n if (runtimeChunkLists.has(chunkListPath)) {\n DEV_BACKEND.restart()\n } else {\n disposeChunkList(chunkListPath)\n }\n break\n }\n default:\n throw new Error(`Unknown update type: ${update.type}`)\n }\n}\n\n/**\n * Removes a module from a chunk.\n * Returns `true` if there are no remaining chunks including this module.\n */\nfunction removeModuleFromChunk(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): boolean {\n const moduleChunks = moduleChunksMap.get(moduleId)!\n moduleChunks.delete(chunkPath)\n\n const chunkModules = chunkModulesMap.get(chunkPath)!\n chunkModules.delete(moduleId)\n\n const noRemainingModules = chunkModules.size === 0\n if (noRemainingModules) {\n chunkModulesMap.delete(chunkPath)\n }\n\n const noRemainingChunks = moduleChunks.size === 0\n if (noRemainingChunks) {\n moduleChunksMap.delete(moduleId)\n }\n\n return noRemainingChunks\n}\n\n/**\n * Disposes of a chunk list and its corresponding exclusive chunks.\n */\nfunction disposeChunkList(chunkListPath: ChunkListPath): boolean {\n const chunkPaths = chunkListChunksMap.get(chunkListPath)\n if (chunkPaths == null) {\n return false\n }\n chunkListChunksMap.delete(chunkListPath)\n\n for (const chunkPath of chunkPaths) {\n const chunkChunkLists = chunkChunkListsMap.get(chunkPath)!\n chunkChunkLists.delete(chunkListPath)\n\n if (chunkChunkLists.size === 0) {\n chunkChunkListsMap.delete(chunkPath)\n disposeChunk(chunkPath)\n }\n }\n\n // We must also dispose of the chunk list's chunk itself to ensure it may\n // be reloaded properly in the future.\n const chunkListUrl = getChunkRelativeUrl(chunkListPath)\n\n DEV_BACKEND.unloadChunk?.(chunkListUrl)\n\n return true\n}\n\n/**\n * Disposes of a chunk and its corresponding exclusive modules.\n *\n * @returns Whether the chunk was disposed of.\n */\nfunction disposeChunk(chunkPath: ChunkPath): boolean {\n const chunkUrl = getChunkRelativeUrl(chunkPath)\n // This should happen whether the chunk has any modules in it or not.\n // For instance, CSS chunks have no modules in them, but they still need to be unloaded.\n DEV_BACKEND.unloadChunk?.(chunkUrl)\n\n const chunkModules = chunkModulesMap.get(chunkPath)\n if (chunkModules == null) {\n return false\n }\n chunkModules.delete(chunkPath)\n\n for (const moduleId of chunkModules) {\n const moduleChunks = moduleChunksMap.get(moduleId)!\n moduleChunks.delete(chunkPath)\n\n const noRemainingChunks = moduleChunks.size === 0\n if (noRemainingChunks) {\n moduleChunksMap.delete(moduleId)\n disposeModule(moduleId, 'clear')\n availableModules.delete(moduleId)\n }\n }\n\n return true\n}\n\n/**\n * Adds a module to a chunk.\n */\nfunction addModuleToChunk(moduleId: ModuleId, chunkPath: ChunkPath) {\n let moduleChunks = moduleChunksMap.get(moduleId)\n if (!moduleChunks) {\n moduleChunks = new Set([chunkPath])\n moduleChunksMap.set(moduleId, moduleChunks)\n } else {\n moduleChunks.add(chunkPath)\n }\n\n let chunkModules = chunkModulesMap.get(chunkPath)\n if (!chunkModules) {\n chunkModules = new Set([moduleId])\n chunkModulesMap.set(chunkPath, chunkModules)\n } else {\n chunkModules.add(moduleId)\n }\n}\n\n/**\n * Marks a chunk list as a runtime chunk list. There can be more than one\n * runtime chunk list. For instance, integration tests can have multiple chunk\n * groups loaded at runtime, each with its own chunk list.\n */\nfunction markChunkListAsRuntime(chunkListPath: ChunkListPath) {\n runtimeChunkLists.add(chunkListPath)\n}\n\nfunction registerChunk(registration: ChunkRegistration) {\n const chunk = getChunkFromRegistration(registration[0]) as\n | ChunkPath\n | ChunkScript\n let runtimeParams: RuntimeParams | undefined\n // When bootstrapping we are passed a single runtimeParams object so we can distinguish purely based on length\n if (registration.length === 2) {\n runtimeParams = registration[1] as RuntimeParams\n } else {\n let chunkPath = getPathFromScript(chunk)\n runtimeParams = undefined\n installCompressedModuleFactories(\n registration as CompressedModuleFactories,\n /* offset= */ 1,\n moduleFactories,\n (id: ModuleId) => addModuleToChunk(id, chunkPath)\n )\n }\n return BACKEND.registerChunk(chunk, runtimeParams)\n}\n\n/**\n * Subscribes to chunk list updates from the update server and applies them.\n */\nfunction registerChunkList(chunkList: ChunkList) {\n const chunkListScript = getChunkFromRegistration(chunkList.script) as\n | ChunkListPath\n | ChunkListScript\n const chunkListPath = getPathFromScript(chunkListScript)\n // The \"chunk\" is also registered to finish the loading in the backend\n BACKEND.registerChunk(chunkListPath as string as ChunkPath)\n globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS!.push([\n chunkListPath,\n handleApply.bind(null, chunkListPath),\n ])\n\n // Adding chunks to chunk lists and vice versa.\n const chunkPaths = new Set(chunkList.chunks.map(getChunkPath))\n chunkListChunksMap.set(chunkListPath, chunkPaths)\n for (const chunkPath of chunkPaths) {\n let chunkChunkLists = chunkChunkListsMap.get(chunkPath)\n if (!chunkChunkLists) {\n chunkChunkLists = new Set([chunkListPath])\n chunkChunkListsMap.set(chunkPath, chunkChunkLists)\n } else {\n chunkChunkLists.add(chunkListPath)\n }\n }\n\n if (chunkList.source === 'entry') {\n markChunkListAsRuntime(chunkListPath)\n }\n}\n\nglobalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= []\n"],"names":["devContextPrototype","Context","prototype","devModuleCache","Object","create","c","runtimeModules","Set","createModuleWithDirectionFlag","moduleChunksMap","Map","chunkModulesMap","runtimeChunkLists","chunkListChunksMap","chunkChunkListsMap","getOrInstantiateRuntimeModule","chunkPath","moduleId","module","error","instantiateModule","SourceType","Runtime","getOrInstantiateModuleFromParent","id","sourceModule","hot","active","console","warn","children","indexOf","push","parents","Parent","DevContext","exports","refresh","call","k","sourceType","sourceData","createModuleObjectFn","createModuleObject","createContext","instantiateModuleShared","moduleFactories","runModuleExecutionHooks","DUMMY_REFRESH_CONTEXT","register","_type","_id","signature","registerExports","_module","_helpers","executeModule","globalThis","$RefreshInterceptModuleExecution$","cleanupReactRefreshIntercept","$RefreshReg$","$RefreshSig$","registerExportsAndSetupBoundaryForReactRefresh","helpers","currentExports","prevExports","data","registerExportsForReactRefresh","isReactRefreshBoundary","dispose","accept","shouldInvalidateReactRefreshBoundary","getRefreshBoundarySignature","invalidate","scheduleUpdate","isNoLongerABoundary","updateChunksPhase","chunksAddedModules","chunksDeletedModules","addedModuleIds","addModuleToChunk","disposedModules","removeModuleFromChunk","add","applyUpdate","update","type","applyChunkListUpdate","invariant","merged","applyEcmascriptMergedUpdate","chunks","chunkUpdate","entries","chunkUrl","getChunkRelativeUrl","BACKEND","loadChunkCached","Update","DEV_BACKEND","reloadChunk","unloadChunk","instruction","JSON","stringify","added","modified","chunksAdded","chunksDeleted","computeChangedModules","applyEcmascriptMergedUpdateShared","evalModuleEntry","_eval","applyModuleFactoryName","autoAcceptRootModules","handleApply","chunkListPath","restart","has","disposeChunkList","Error","moduleChunks","get","delete","chunkModules","noRemainingModules","size","noRemainingChunks","chunkPaths","chunkChunkLists","disposeChunk","chunkListUrl","disposeModule","availableModules","set","markChunkListAsRuntime","registerChunk","registration","chunk","getChunkFromRegistration","runtimeParams","length","getPathFromScript","undefined","installCompressedModuleFactories","registerChunkList","chunkList","chunkListScript","script","TURBOPACK_CHUNK_UPDATE_LISTENERS","bind","map","getChunkPath","source"],"mappings":"AAAA,iEAAiE;AACjE,kEAAkE;AAMlE,MAAMA,sBAAsBC,QAAQC,SAAS;AAE7C;;;;;;CAMC,GACD,oDAAoD,GAEpD,wEAAwE;AACxEC,iBAAiBC,OAAOC,MAAM,CAAC;AAC/BL,oBAAoBM,CAAC,GAAGH;AACxBI,iBAAiB,IAAIC;AAErB,kDAAkD;AAClDC,gCAAgC;AAgChC;;;;;;CAMC,GACD,MAAMC,kBAAiD,IAAIC;AAC3D;;CAEC,GACD,MAAMC,kBAAiD,IAAID;AAC3D;;;;CAIC,GACD,MAAME,oBAAwC,IAAIL;AAClD;;CAEC,GACD,MAAMM,qBAAyD,IAAIH;AACnE;;CAEC,GACD,MAAMI,qBAAyD,IAAIJ;AAEnE;;CAEC,GACD,aAAa;AACb,SAASK,8BACPC,SAAoB,EACpBC,QAAkB;IAElB,MAAMC,SAAShB,cAAc,CAACe,SAAS;IACvC,IAAIC,QAAQ;QACV,IAAIA,OAAOC,KAAK,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G;QAC7BD,gBAAgBH,YAAY,CAAC,EAAE;IACjC,OAAO;QACL,IAAIzH,YAAY8H,kBAAkBJ;QAClCE,gBAAgBG;QAChBC,iCACEP,cACA,WAAW,GAAG,GACd3F,iBACA,CAACtB,KAAiBwD,iBAAiBxD,IAAIR;IAE3C;IACA,OAAOgF,QAAQwC,aAAa,CAACE,OAAOE;AACtC;AAEA;;CAEC,GACD,SAASK,kBAAkBC,SAAoB;IAC7C,MAAMC,kBAAkBR,yBAAyBO,UAAUE,MAAM;IAGjE,MAAMhC,gBAAgB0B,kBAAkBK;IACxC,sEAAsE;IACtEnD,QAAQwC,aAAa,CAACpB;IACtB3D,WAAW4F,gCAAgC,CAAErH,IAAI,CAAC;QAChDoF;QACAD,YAAYmC,IAAI,CAAC,MAAMlC;KACxB;IAED,+CAA+C;IAC/C,MAAMY,aAAa,IAAIzH,IAAI2I,UAAUvD,MAAM,CAAC4D,GAAG,CAACC;IAChD3I,mBAAmByH,GAAG,CAAClB,eAAeY;IACtC,KAAK,MAAMhH,aAAagH,WAAY;QAClC,IAAIC,kBAAkBnH,mBAAmB4G,GAAG,CAAC1G;QAC7C,IAAI,CAACiH,iBAAiB;YACpBA,kBAAkB,IAAI1H,IAAI;gBAAC6G;aAAc;YACzCtG,mBAAmBwH,GAAG,CAACtH,WAAWiH;QACpC,OAAO;YACLA,gBAAgB9C,GAAG,CAACiC;QACtB;IACF;IAEA,IAAI8B,UAAUO,MAAM,KAAK,SAAS;QAChClB,uBAAuBnB;IACzB;AACF;AAEA3D,WAAW4F,gCAAgC,KAAK,EAAE","ignoreList":[0]}}, - {"offset": {"line": 1951, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/runtime-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack ECMAScript DOM runtime.\n *\n * It will be appended to the base runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\nfunction getAssetSuffixFromScriptSrc() {\n // TURBOPACK_ASSET_SUFFIX is set in web workers\n return (\n (self.TURBOPACK_ASSET_SUFFIX ??\n document?.currentScript\n ?.getAttribute?.('src')\n ?.replace(/^(.*(?=\\?)|^.*$)/, '')) ||\n ''\n )\n}\n\ntype ChunkResolver = {\n resolved: boolean\n loadingStarted: boolean\n resolve: () => void\n reject: (error?: Error) => void\n promise: Promise\n}\n\nlet BACKEND: RuntimeBackend\n\n/**\n * Maps chunk paths to the corresponding resolver.\n */\nconst chunkResolvers: Map = new Map()\n\n;(() => {\n BACKEND = {\n async registerChunk(chunk, params) {\n let chunkPath = getPathFromScript(chunk)\n let chunkUrl = getUrlFromScript(chunk)\n\n const resolver = getOrCreateResolver(chunkUrl)\n resolver.resolve()\n\n if (params == null) {\n return\n }\n\n for (const otherChunkData of params.otherChunks) {\n const otherChunkPath = getChunkPath(otherChunkData)\n const otherChunkUrl = getChunkRelativeUrl(otherChunkPath)\n\n // Chunk might have started loading, so we want to avoid triggering another load.\n getOrCreateResolver(otherChunkUrl)\n }\n\n // This waits for chunks to be loaded, but also marks included items as available.\n await Promise.all(\n params.otherChunks.map((otherChunkData) =>\n loadInitialChunk(chunkPath, otherChunkData)\n )\n )\n\n if (params.runtimeModuleIds.length > 0) {\n for (const moduleId of params.runtimeModuleIds) {\n getOrInstantiateRuntimeModule(chunkPath, moduleId)\n }\n }\n },\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n loadChunkCached(sourceType: SourceType, chunkUrl: ChunkUrl) {\n return doLoadChunk(sourceType, chunkUrl)\n },\n\n async loadWebAssembly(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n const { instance } = await WebAssembly.instantiateStreaming(\n req,\n importsObj\n )\n\n return instance.exports\n },\n\n async loadWebAssemblyModule(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n return await WebAssembly.compileStreaming(req)\n },\n }\n\n function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {\n let resolver = chunkResolvers.get(chunkUrl)\n if (!resolver) {\n let resolve: () => void\n let reject: (error?: Error) => void\n const promise = new Promise((innerResolve, innerReject) => {\n resolve = innerResolve\n reject = innerReject\n })\n resolver = {\n resolved: false,\n loadingStarted: false,\n promise,\n resolve: () => {\n resolver!.resolved = true\n resolve()\n },\n reject: reject!,\n }\n chunkResolvers.set(chunkUrl, resolver)\n }\n return resolver\n }\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n function doLoadChunk(sourceType: SourceType, chunkUrl: ChunkUrl) {\n const resolver = getOrCreateResolver(chunkUrl)\n if (resolver.loadingStarted) {\n return resolver.promise\n }\n\n if (sourceType === SourceType.Runtime) {\n // We don't need to load chunks references from runtime code, as they're already\n // present in the DOM.\n resolver.loadingStarted = true\n\n if (isCss(chunkUrl)) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n\n // We need to wait for JS chunks to register themselves within `registerChunk`\n // before we can start instantiating runtime modules, hence the absence of\n // `resolver.resolve()` in this branch.\n\n return resolver.promise\n }\n\n if (typeof importScripts === 'function') {\n // We're in a web worker\n if (isCss(chunkUrl)) {\n // ignore\n } else if (isJs(chunkUrl)) {\n self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl)\n importScripts(chunkUrl)\n } else {\n throw new Error(\n `can't infer type of chunk from URL ${chunkUrl} in worker`\n )\n }\n } else {\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n if (previousLinks.length > 0) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n } else {\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n link.href = chunkUrl\n link.onerror = () => {\n resolver.reject()\n }\n link.onload = () => {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(link)\n }\n } else if (isJs(chunkUrl)) {\n const previousScripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n if (previousScripts.length > 0) {\n // There is this edge where the script already failed loading, but we\n // can't detect that. The Promise will never resolve in this case.\n for (const script of Array.from(previousScripts)) {\n script.addEventListener('error', () => {\n resolver.reject()\n })\n }\n } else {\n const script = document.createElement('script')\n script.src = chunkUrl\n // We'll only mark the chunk as loaded once the script has been executed,\n // which happens in `registerChunk`. Hence the absence of `resolve()` in\n // this branch.\n script.onerror = () => {\n resolver.reject()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(script)\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n }\n\n resolver.loadingStarted = true\n return resolver.promise\n }\n\n function fetchWebAssembly(wasmChunkPath: ChunkPath) {\n return fetch(getChunkRelativeUrl(wasmChunkPath))\n }\n})()\n"],"names":["getAssetSuffixFromScriptSrc","self","TURBOPACK_ASSET_SUFFIX","document","currentScript","getAttribute","replace","BACKEND","chunkResolvers","Map","registerChunk","chunk","params","chunkPath","getPathFromScript","chunkUrl","getUrlFromScript","resolver","getOrCreateResolver","resolve","otherChunkData","otherChunks","otherChunkPath","getChunkPath","otherChunkUrl","getChunkRelativeUrl","Promise","all","map","loadInitialChunk","runtimeModuleIds","length","moduleId","getOrInstantiateRuntimeModule","loadChunkCached","sourceType","doLoadChunk","loadWebAssembly","_sourceType","_sourceData","wasmChunkPath","_edgeModule","importsObj","req","fetchWebAssembly","instance","WebAssembly","instantiateStreaming","exports","loadWebAssemblyModule","compileStreaming","get","reject","promise","innerResolve","innerReject","resolved","loadingStarted","set","SourceType","Runtime","isCss","importScripts","isJs","TURBOPACK_NEXT_CHUNK_URLS","push","Error","decodedChunkUrl","decodeURI","previousLinks","querySelectorAll","link","createElement","rel","href","onerror","onload","head","appendChild","previousScripts","script","Array","from","addEventListener","src","fetch"],"mappings":"AAAA;;;;CAIC,GAED,oDAAoD,GAEpD,sEAAsE;AACtE,mEAAmE;AAEnE,SAASA;IACP,+CAA+C;IAC/C,OACE,CAACC,KAAKC,sBAAsB,IAC1BC,UAAUC,eACNC,eAAe,QACfC,QAAQ,oBAAoB,GAAG,KACrC;AAEJ;AAUA,IAAIC;AAEJ;;CAEC,GACD,MAAMC,iBAA+C,IAAIC;AAExD,CAAC;IACAF,UAAU;QACR,MAAMG,eAAcC,KAAK,EAAEC,MAAM;YAC/B,IAAIC,YAAYC,kBAAkBH;YAClC,IAAII,WAAWC,iBAAiBL;YAEhC,MAAMM,WAAWC,oBAAoBH;YACrCE,SAASE,OAAO;YAEhB,IAAIP,UAAU,MAAM;gBAClB;YACF;YAEA,KAAK,MAAMQ,kBAAkBR,OAAOS,WAAW,CAAE;gBAC/C,MAAMC,iBAAiBC,aAAaH;gBACpC,MAAMI,gBAAgBC,oBAAoBH;gBAE1C,iFAAiF;gBACjFJ,oBAAoBM;YACtB;YAEA,kFAAkF;YAClF,MAAME,QAAQC,GAAG,CACff,OAAOS,WAAW,CAACO,GAAG,CAAC,CAACR,iBACtBS,iBAAiBhB,WAAWO;YAIhC,IAAIR,OAAOkB,gBAAgB,CAACC,MAAM,GAAG,GAAG;gBACtC,KAAK,MAAMC,YAAYpB,OAAOkB,gBAAgB,CAAE;oBAC9CG,8BAA8BpB,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MAAM,GAAG,GAAG;oBAC9B,qEAAqE;oBACrE,kEAAkE;oBAClE,KAAK,MAAMiD,UAAUC,MAAMC,IAAI,CAACH,iBAAkB;wBAChDC,OAAOG,gBAAgB,CAAC,SAAS;4BAC/BlE,SAASmC,MAAM;wBACjB;oBACF;gBACF,OAAO;oBACL,MAAM4B,SAAS7E,SAASqE,aAAa,CAAC;oBACtCQ,OAAOI,GAAG,GAAGrE;oBACb,yEAAyE;oBACzE,wEAAwE;oBACxE,eAAe;oBACfiE,OAAOL,OAAO,GAAG;wBACf1D,SAASmC,MAAM;oBACjB;oBACA,kDAAkD;oBAClDjD,SAAS0E,IAAI,CAACC,WAAW,CAACE;gBAC5B;YACF,OAAO;gBACL,MAAM,IAAId,MAAM,CAAC,mCAAmC,EAAEnD,UAAU;YAClE;QACF;QAEAE,SAASwC,cAAc,GAAG;QAC1B,OAAOxC,SAASoC,OAAO;IACzB;IAEA,SAAST,iBAAiBJ,aAAwB;QAChD,OAAO6C,MAAM5D,oBAAoBe;IACnC;AACF,CAAC","ignoreList":[0]}}, - {"offset": {"line": 2117, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/dev-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack development\n * ECMAScript DOM runtime.\n *\n * It will be appended to the base development runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n/// \n/// \n\nlet DEV_BACKEND: DevRuntimeBackend\n;(() => {\n DEV_BACKEND = {\n unloadChunk(chunkUrl) {\n deleteResolver(chunkUrl)\n\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const links = document.querySelectorAll(\n `link[href=\"${chunkUrl}\"],link[href^=\"${chunkUrl}?\"],link[href=\"${decodedChunkUrl}\"],link[href^=\"${decodedChunkUrl}?\"]`\n )\n for (const link of Array.from(links)) {\n link.remove()\n }\n } else if (isJs(chunkUrl)) {\n // Unloading a JS chunk would have no effect, as it lives in the JS\n // runtime once evaluated.\n // However, we still want to remove the script tag from the DOM to keep\n // the HTML somewhat consistent from the user's perspective.\n const scripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n for (const script of Array.from(scripts)) {\n script.remove()\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n },\n\n reloadChunk(chunkUrl) {\n return new Promise((resolve, reject) => {\n if (!isCss(chunkUrl)) {\n reject(new Error('The DOM backend can only reload CSS chunks'))\n return\n }\n\n const decodedChunkUrl = decodeURI(chunkUrl)\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n\n if (previousLinks.length === 0) {\n reject(new Error(`No link element found for chunk ${chunkUrl}`))\n return\n }\n\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n\n if (navigator.userAgent.includes('Firefox')) {\n // Firefox won't reload CSS files that were previously loaded on the current page,\n // we need to add a query param to make sure CSS is actually reloaded from the server.\n //\n // I believe this is this issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506\n //\n // Safari has a similar issue, but only if you have a `` tag\n // pointing to the same URL as the stylesheet: https://bugs.webkit.org/show_bug.cgi?id=187726\n link.href = `${chunkUrl}?ts=${Date.now()}`\n } else {\n link.href = chunkUrl\n }\n\n link.onerror = () => {\n reject()\n }\n link.onload = () => {\n // First load the new CSS, then remove the old ones. This prevents visible\n // flickering that would happen in-between removing the previous CSS and\n // loading the new one.\n for (const previousLink of Array.from(previousLinks))\n previousLink.remove()\n\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolve()\n }\n\n // Make sure to insert the new CSS right after the previous one, so that\n // its precedence is higher.\n previousLinks[0].parentElement!.insertBefore(\n link,\n previousLinks[0].nextSibling\n )\n })\n },\n\n restart: () => self.location.reload(),\n }\n\n function deleteResolver(chunkUrl: ChunkUrl) {\n chunkResolvers.delete(chunkUrl)\n }\n})()\n\nfunction _eval({ code, url, map }: EcmascriptModuleEntry): ModuleFactory {\n code += `\\n\\n//# sourceURL=${encodeURI(\n location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX\n )}`\n if (map) {\n code += `\\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(\n // btoa doesn't handle nonlatin characters, so escape them as \\x sequences\n // See https://stackoverflow.com/a/26603875\n unescape(encodeURIComponent(map))\n )}`\n }\n\n // eslint-disable-next-line no-eval\n return eval(code)\n}\n"],"names":["DEV_BACKEND","unloadChunk","chunkUrl","deleteResolver","decodedChunkUrl","decodeURI","isCss","links","document","querySelectorAll","link","Array","from","remove","isJs","scripts","script","Error","reloadChunk","Promise","resolve","reject","previousLinks","length","createElement","rel","navigator","userAgent","includes","href","Date","now","onerror","onload","previousLink","parentElement","insertBefore","nextSibling","restart","self","location","reload","chunkResolvers","delete","_eval","code","url","map","encodeURI","origin","CHUNK_BASE_PATH","ASSET_SUFFIX","btoa","unescape","encodeURIComponent","eval"],"mappings":"AAAA;;;;;CAKC,GAED,oDAAoD,GAEpD,gDAAgD;AAChD,4CAA4C;AAC5C,iDAAiD;AACjD,0DAA0D;AAE1D,IAAIA;AACH,CAAC;IACAA,cAAc;QACZC,aAAYC,QAAQ;YAClBC,eAAeD;YAEf,gFAAgF;YAChF,MAAME,kBAAkBC,UAAUH;YAElC,IAAII,MAAMJ,WAAW;gBACnB,MAAMK,QAAQC,SAASC,gBAAgB,CACrC,CAAC,WAAW,EAAEP,SAAS,eAAe,EAAEA,SAAS,eAAe,EAAEE,gBAAgB,eAAe,EAAEA,gBAAgB,GAAG,CAAC;gBAEzH,KAAK,MAAMM,QAAQC,MAAMC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I,GAAG3B;gBACd;gBAEAQ,KAAKsB,OAAO,GAAG;oBACbX;gBACF;gBACAX,KAAKuB,MAAM,GAAG;oBACZ,0EAA0E;oBAC1E,wEAAwE;oBACxE,uBAAuB;oBACvB,KAAK,MAAMC,gBAAgBvB,MAAMC,IAAI,CAACU,eACpCY,aAAarB,MAAM;oBAErB,uEAAuE;oBACvE,oBAAoB;oBACpBO;gBACF;gBAEA,wEAAwE;gBACxE,4BAA4B;gBAC5BE,aAAa,CAAC,EAAE,CAACa,aAAa,CAAEC,YAAY,CAC1C1B,MACAY,aAAa,CAAC,EAAE,CAACe,WAAW;YAEhC;QACF;QAEAC,SAAS,IAAMC,KAAKC,QAAQ,CAACC,MAAM;IACrC;IAEA,SAAStC,eAAeD,QAAkB;QACxCwC,eAAeC,MAAM,CAACzC;IACxB;AACF,CAAC;AAED,SAAS0C,MAAM,EAAEC,IAAI,EAAEC,GAAG,EAAEC,GAAG,EAAyB;IACtDF,QAAQ,CAAC,kBAAkB,EAAEG,UAC3BR,SAASS,MAAM,GAAGC,kBAAkBJ,MAAMK,eACzC;IACH,IAAIJ,KAAK;QACPF,QAAQ,CAAC,kEAAkE,EAAEO,KAC3E,0EAA0E;QAC1E,2CAA2C;QAC3CC,SAASC,mBAAmBP,QAC3B;IACL;IAEA,mCAAmC;IACnC,OAAOQ,KAAKV;AACd","ignoreList":[0]}}] + {"offset": {"line": 1951, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/runtime-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack ECMAScript DOM runtime.\n *\n * It will be appended to the base runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\nfunction getAssetSuffixFromScriptSrc() {\n // TURBOPACK_ASSET_SUFFIX is set in web workers\n if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX\n const src = document?.currentScript?.getAttribute?.('src') ?? ''\n const qi = src.indexOf('?')\n return qi >= 0 ? src.slice(qi) : ''\n}\n\ntype ChunkResolver = {\n resolved: boolean\n loadingStarted: boolean\n resolve: () => void\n reject: (error?: Error) => void\n promise: Promise\n}\n\nlet BACKEND: RuntimeBackend\n\n/**\n * Maps chunk paths to the corresponding resolver.\n */\nconst chunkResolvers: Map = new Map()\n\n;(() => {\n BACKEND = {\n async registerChunk(chunk, params) {\n let chunkPath = getPathFromScript(chunk)\n let chunkUrl = getUrlFromScript(chunk)\n\n const resolver = getOrCreateResolver(chunkUrl)\n resolver.resolve()\n\n if (params == null) {\n return\n }\n\n for (const otherChunkData of params.otherChunks) {\n const otherChunkPath = getChunkPath(otherChunkData)\n const otherChunkUrl = getChunkRelativeUrl(otherChunkPath)\n\n // Chunk might have started loading, so we want to avoid triggering another load.\n getOrCreateResolver(otherChunkUrl)\n }\n\n // This waits for chunks to be loaded, but also marks included items as available.\n await Promise.all(\n params.otherChunks.map((otherChunkData) =>\n loadInitialChunk(chunkPath, otherChunkData)\n )\n )\n\n if (params.runtimeModuleIds.length > 0) {\n for (const moduleId of params.runtimeModuleIds) {\n getOrInstantiateRuntimeModule(chunkPath, moduleId)\n }\n }\n },\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n loadChunkCached(sourceType: SourceType, chunkUrl: ChunkUrl) {\n return doLoadChunk(sourceType, chunkUrl)\n },\n\n async loadWebAssembly(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n const { instance } = await WebAssembly.instantiateStreaming(\n req,\n importsObj\n )\n\n return instance.exports\n },\n\n async loadWebAssemblyModule(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n return await WebAssembly.compileStreaming(req)\n },\n }\n\n function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {\n let resolver = chunkResolvers.get(chunkUrl)\n if (!resolver) {\n let resolve: () => void\n let reject: (error?: Error) => void\n const promise = new Promise((innerResolve, innerReject) => {\n resolve = innerResolve\n reject = innerReject\n })\n resolver = {\n resolved: false,\n loadingStarted: false,\n promise,\n resolve: () => {\n resolver!.resolved = true\n resolve()\n },\n reject: reject!,\n }\n chunkResolvers.set(chunkUrl, resolver)\n }\n return resolver\n }\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n function doLoadChunk(sourceType: SourceType, chunkUrl: ChunkUrl) {\n const resolver = getOrCreateResolver(chunkUrl)\n if (resolver.loadingStarted) {\n return resolver.promise\n }\n\n if (sourceType === SourceType.Runtime) {\n // We don't need to load chunks references from runtime code, as they're already\n // present in the DOM.\n resolver.loadingStarted = true\n\n if (isCss(chunkUrl)) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n\n // We need to wait for JS chunks to register themselves within `registerChunk`\n // before we can start instantiating runtime modules, hence the absence of\n // `resolver.resolve()` in this branch.\n\n return resolver.promise\n }\n\n if (typeof importScripts === 'function') {\n // We're in a web worker\n if (isCss(chunkUrl)) {\n // ignore\n } else if (isJs(chunkUrl)) {\n self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl)\n importScripts(chunkUrl)\n } else {\n throw new Error(\n `can't infer type of chunk from URL ${chunkUrl} in worker`\n )\n }\n } else {\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n if (previousLinks.length > 0) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n } else {\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n link.href = chunkUrl\n link.onerror = () => {\n resolver.reject()\n }\n link.onload = () => {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(link)\n }\n } else if (isJs(chunkUrl)) {\n const previousScripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n if (previousScripts.length > 0) {\n // There is this edge where the script already failed loading, but we\n // can't detect that. The Promise will never resolve in this case.\n for (const script of Array.from(previousScripts)) {\n script.addEventListener('error', () => {\n resolver.reject()\n })\n }\n } else {\n const script = document.createElement('script')\n script.src = chunkUrl\n // We'll only mark the chunk as loaded once the script has been executed,\n // which happens in `registerChunk`. Hence the absence of `resolve()` in\n // this branch.\n script.onerror = () => {\n resolver.reject()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(script)\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n }\n\n resolver.loadingStarted = true\n return resolver.promise\n }\n\n function fetchWebAssembly(wasmChunkPath: ChunkPath) {\n return fetch(getChunkRelativeUrl(wasmChunkPath))\n }\n})()\n"],"names":["getAssetSuffixFromScriptSrc","self","TURBOPACK_ASSET_SUFFIX","src","document","currentScript","getAttribute","qi","indexOf","slice","BACKEND","chunkResolvers","Map","registerChunk","chunk","params","chunkPath","getPathFromScript","chunkUrl","getUrlFromScript","resolver","getOrCreateResolver","resolve","otherChunkData","otherChunks","otherChunkPath","getChunkPath","otherChunkUrl","getChunkRelativeUrl","Promise","all","map","loadInitialChunk","runtimeModuleIds","length","moduleId","getOrInstantiateRuntimeModule","loadChunkCached","sourceType","doLoadChunk","loadWebAssembly","_sourceType","_sourceData","wasmChunkPath","_edgeModule","importsObj","req","fetchWebAssembly","instance","WebAssembly","instantiateStreaming","exports","loadWebAssemblyModule","compileStreaming","get","reject","promise","innerResolve","innerReject","resolved","loadingStarted","set","SourceType","Runtime","isCss","importScripts","isJs","TURBOPACK_NEXT_CHUNK_URLS","push","Error","decodedChunkUrl","decodeURI","previousLinks","querySelectorAll","link","createElement","rel","href","onerror","onload","head","appendChild","previousScripts","script","Array","from","addEventListener","fetch"],"mappings":"AAAA;;;;CAIC,GAED,oDAAoD,GAEpD,sEAAsE;AACtE,mEAAmE;AAEnE,SAASA;IACP,+CAA+C;IAC/C,IAAIC,KAAKC,sBAAsB,IAAI,MAAM,OAAOD,KAAKC,sBAAsB;IAC3E,MAAMC,MAAMC,UAAUC,eAAeC,eAAe,UAAU;IAC9D,MAAMC,KAAKJ,IAAIK,OAAO,CAAC;IACvB,OAAOD,MAAM,IAAIJ,IAAIM,KAAK,CAACF,MAAM;AACnC;AAUA,IAAIG;AAEJ;;CAEC,GACD,MAAMC,iBAA+C,IAAIC;AAExD,CAAC;IACAF,UAAU;QACR,MAAMG,eAAcC,KAAK,EAAEC,MAAM;YAC/B,IAAIC,YAAYC,kBAAkBH;YAClC,IAAII,WAAWC,iBAAiBL;YAEhC,MAAMM,WAAWC,oBAAoBH;YACrCE,SAASE,OAAO;YAEhB,IAAIP,UAAU,MAAM;gBAClB;YACF;YAEA,KAAK,MAAMQ,kBAAkBR,OAAOS,WAAW,CAAE;gBAC/C,MAAMC,iBAAiBC,aAAaH;gBACpC,MAAMI,gBAAgBC,oBAAoBH;gBAE1C,iFAAiF;gBACjFJ,oBAAoBM;YACtB;YAEA,kFAAkF;YAClF,MAAME,QAAQC,GAAG,CACff,OAAOS,WAAW,CAACO,GAAG,CAAC,CAACR,iBACtBS,iBAAiBhB,WAAWO;YAIhC,IAAIR,OAAOkB,gBAAgB,CAACC,MAAM,GAAG,GAAG;gBACtC,KAAK,MAAMC,YAAYpB,OAAOkB,gBAAgB,CAAE;oBAC9CG,8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gBAAgBhD,MAAM,GAAG,GAAG;oBAC9B,qEAAqE;oBACrE,kEAAkE;oBAClE,KAAK,MAAMiD,UAAUC,MAAMC,IAAI,CAACH,iBAAkB;wBAChDC,OAAOG,gBAAgB,CAAC,SAAS;4BAC/BlE,SAASmC,MAAM;wBACjB;oBACF;gBACF,OAAO;oBACL,MAAM4B,SAAS/E,SAASuE,aAAa,CAAC;oBACtCQ,OAAOhF,GAAG,GAAGe;oBACb,yEAAyE;oBACzE,wEAAwE;oBACxE,eAAe;oBACfiE,OAAOL,OAAO,GAAG;wBACf1D,SAASmC,MAAM;oBACjB;oBACA,kDAAkD;oBAClDnD,SAAS4E,IAAI,CAACC,WAAW,CAACE;gBAC5B;YACF,OAAO;gBACL,MAAM,IAAId,MAAM,CAAC,mCAAmC,EAAEnD,UAAU;YAClE;QACF;QAEAE,SAASwC,cAAc,GAAG;QAC1B,OAAOxC,SAASoC,OAAO;IACzB;IAEA,SAAST,iBAAiBJ,aAAwB;QAChD,OAAO4C,MAAM3D,oBAAoBe;IACnC;AACF,CAAC","ignoreList":[0]}}, + {"offset": {"line": 2120, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/dev-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack development\n * ECMAScript DOM runtime.\n *\n * It will be appended to the base development runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n/// \n/// \n\nlet DEV_BACKEND: DevRuntimeBackend\n;(() => {\n DEV_BACKEND = {\n unloadChunk(chunkUrl) {\n deleteResolver(chunkUrl)\n\n // Strip query string so we match links regardless of cache-busting\n // params (e.g. ?ts=) that may differ between HMR updates.\n const baseChunkUrl = chunkUrl.split('?')[0]\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedBaseChunkUrl = decodeURI(baseChunkUrl)\n\n if (isCss(chunkUrl)) {\n const links = document.querySelectorAll(\n `link[href=\"${baseChunkUrl}\"],link[href^=\"${baseChunkUrl}?\"],link[href=\"${decodedBaseChunkUrl}\"],link[href^=\"${decodedBaseChunkUrl}?\"]`\n )\n for (const link of Array.from(links)) {\n link.remove()\n }\n } else if (isJs(chunkUrl)) {\n // Unloading a JS chunk would have no effect, as it lives in the JS\n // runtime once evaluated.\n // However, we still want to remove the script tag from the DOM to keep\n // the HTML somewhat consistent from the user's perspective.\n const scripts = document.querySelectorAll(\n `script[src=\"${baseChunkUrl}\"],script[src^=\"${baseChunkUrl}?\"],script[src=\"${decodedBaseChunkUrl}\"],script[src^=\"${decodedBaseChunkUrl}?\"]`\n )\n for (const script of Array.from(scripts)) {\n script.remove()\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n },\n\n reloadChunk(chunkUrl) {\n return new Promise((resolve, reject) => {\n if (!isCss(chunkUrl)) {\n reject(new Error('The DOM backend can only reload CSS chunks'))\n return\n }\n\n // Strip query string so we match links regardless of cache-busting\n // params (e.g. ?ts=) that may differ between HMR updates.\n const baseChunkUrl = chunkUrl.split('?')[0]\n const decodedBaseChunkUrl = decodeURI(baseChunkUrl)\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${baseChunkUrl}\"],link[rel=stylesheet][href^=\"${baseChunkUrl}?\"],link[rel=stylesheet][href=\"${decodedBaseChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedBaseChunkUrl}?\"]`\n )\n\n if (previousLinks.length === 0) {\n reject(new Error(`No link element found for chunk ${chunkUrl}`))\n return\n }\n\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n\n if (\n navigator.userAgent.includes('Firefox') ||\n (navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome') &&\n !navigator.userAgent.includes('Chromium'))\n ) {\n // Firefox won't reload CSS files that were previously loaded on the\n // current page: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506\n //\n // Safari serves cached CSS when a exists for the\n // same URL: https://bugs.webkit.org/show_bug.cgi?id=187726\n //\n // Replace or add a fresh `ts` cache-busting param without\n // discarding other query parameters that may already be present.\n const url = new URL(chunkUrl, location.origin)\n url.searchParams.set('ts', String(Date.now()))\n // Reduced timer precision in some browers could lead to an update getting dropped\n // in firefox if it happens fast enough (in firefox precision is sometimes 100ms!).\n // So trust that the server is only updating us when it is important and use a\n // random number to bust the cache.\n url.searchParams.set('_next_rand', String(Math.random()))\n link.href = url.pathname + url.search\n } else {\n link.href = chunkUrl\n }\n\n link.onerror = () => {\n reject()\n }\n link.onload = () => {\n // First load the new CSS, then remove the old ones. This prevents visible\n // flickering that would happen in-between removing the previous CSS and\n // loading the new one.\n for (const previousLink of Array.from(previousLinks))\n previousLink.remove()\n\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolve()\n }\n\n // Make sure to insert the new CSS right after the previous one, so that\n // its precedence is higher.\n previousLinks[0].parentElement!.insertBefore(\n link,\n previousLinks[0].nextSibling\n )\n })\n },\n\n restart: () => self.location.reload(),\n }\n\n function deleteResolver(chunkUrl: ChunkUrl) {\n chunkResolvers.delete(chunkUrl)\n }\n})()\n\nfunction _eval({ code, url, map }: EcmascriptModuleEntry): ModuleFactory {\n code += `\\n\\n//# sourceURL=${encodeURI(\n location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX\n )}`\n if (map) {\n code += `\\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(\n // btoa doesn't handle nonlatin characters, so escape them as \\x sequences\n // See https://stackoverflow.com/a/26603875\n unescape(encodeURIComponent(map))\n )}`\n }\n\n // eslint-disable-next-line no-eval\n return eval(code)\n}\n"],"names":["DEV_BACKEND","unloadChunk","chunkUrl","deleteResolver","baseChunkUrl","split","decodedBaseChunkUrl","decodeURI","isCss","links","document","querySelectorAll","link","Array","from","remove","isJs","scripts","script","Error","reloadChunk","Promise","resolve","reject","previousLinks","length","createElement","rel","navigator","userAgent","includes","url","URL","location","origin","searchParams","set","String","Date","now","Math","random","href","pathname","search","onerror","onload","previousLink","parentElement","insertBefore","nextSibling","restart","self","reload","chunkResolvers","delete","_eval","code","map","encodeURI","CHUNK_BASE_PATH","ASSET_SUFFIX","btoa","unescape","encodeURIComponent","eval"],"mappings":"AAAA;;;;;CAKC,GAED,oDAAoD,GAEpD,gDAAgD;AAChD,4CAA4C;AAC5C,iDAAiD;AACjD,0DAA0D;AAE1D,IAAIA;AACH,CAAC;IACAA,cAAc;QACZC,aAAYC,QAAQ;YAClBC,eAAeD;YAEf,mEAAmE;YACnE,0DAA0D;YAC1D,MAAME,eAAeF,SAASG,KAAK,CAAC,IAAI,CAAC,EAAE;YAC3C,gFAAgF;YAChF,MAAMC,sBAAsBC,UAAUH;YAEtC,IAAII,MAAMN,WAAW;gBACnB,MAAMO,QAAQC,SAASC,gBAAgB,CACrC,CAAC,WAAW,EAAEP,aAAa,eAAe,EAAEA,aAAa,eAAe,EAAEE,oBAAoB,eAAe,EAAEA,oBAAoB,GAAG,CAAC;gBAEzI,KAAK,MAAMM,QAAQC,MAAMC,IAAI,CAACL,OAAQ;oBACpCG,KAAKG,MAAM;gBACb;YACF,OAAO,IAAIC,KAAKd,WAAW;gBACzB,mEAAmE;gBACnE,0BAA0B;gBAC1B,uEAAuE;gBACvE,4DAA4D;gBAC5D,MAAMe,UAAUP,SAASC,gBAAgB,CACvC,CAAC,YAAY,EAAEP,aAAa,gBAAgB,EAAEA,aAAa,gBAAgB,EAAEE,oBAAoB,gBAAgB,EAAEA,oBAAoB,GAAG,CAAC;gBAE7I,KAAK,MAAMY,UAAUL,MAAMC,IAAI,CAACG,SAAU;oBACxCC,OAAOH,MAAM;gBACf;YACF,OAAO;gBACL,MAAM,IAAII,MAAM,CAAC,mCAAmC,EAAEjB,UAAU;YAClE;QACF;QAEAkB,aAAYlB,QAAQ;YAClB,OAAO,IAAImB,QAAc,CAACC,SAASC;gBACjC,IAAI,CAACf,MAAMN,WAAW;oBACpBqB,OAAO,IAAIJ,MAAM;oBACjB;gBACF;gBAEA,mEAAmE;gBACnE,0DAA0D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vB,KAAK,MAAMC,gBAAgBlC,MAAMC,IAAI,CAACU,eACpCuB,aAAahC,MAAM;oBAErB,uEAAuE;oBACvE,oBAAoB;oBACpBO;gBACF;gBAEA,wEAAwE;gBACxE,4BAA4B;gBAC5BE,aAAa,CAAC,EAAE,CAACwB,aAAa,CAAEC,YAAY,CAC1CrC,MACAY,aAAa,CAAC,EAAE,CAAC0B,WAAW;YAEhC;QACF;QAEAC,SAAS,IAAMC,KAAKnB,QAAQ,CAACoB,MAAM;IACrC;IAEA,SAASlD,eAAeD,QAAkB;QACxCoD,eAAeC,MAAM,CAACrD;IACxB;AACF,CAAC;AAED,SAASsD,MAAM,EAAEC,IAAI,EAAE1B,GAAG,EAAE2B,GAAG,EAAyB;IACtDD,QAAQ,CAAC,kBAAkB,EAAEE,UAC3B1B,SAASC,MAAM,GAAG0B,kBAAkB7B,MAAM8B,eACzC;IACH,IAAIH,KAAK;QACPD,QAAQ,CAAC,kEAAkE,EAAEK,KAC3E,0EAA0E;QAC1E,2CAA2C;QAC3CC,SAASC,mBAAmBN,QAC3B;IACL;IAEA,mCAAmC;IACnC,OAAOO,KAAKR;AACd","ignoreList":[0]}}] } \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/output/0v.~_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0jat3.b.js b/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/output/0v.~_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0jat3.b.js index 7d321060bbbe..d5688a1a34f2 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/output/0v.~_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0jat3.b.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/output/0v.~_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0jat3.b.js @@ -1,4 +1,4 @@ -;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="c7d0d6f1-2fed-24f2-514f-5f447a850612")}catch(e){}}(); +;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="154fe60a-f286-b7e0-80b6-f5300e0e86a1")}catch(e){}}(); (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([ "output/0v.~_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0jat3.b.js", {"otherChunks":["output/0teu_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_01.8xqj.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]} @@ -1957,7 +1957,10 @@ globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= []; /// function getAssetSuffixFromScriptSrc() { // TURBOPACK_ASSET_SUFFIX is set in web workers - return (self.TURBOPACK_ASSET_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || ''; + if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX; + const src = document?.currentScript?.getAttribute?.('src') ?? ''; + const qi = src.indexOf('?'); + return qi >= 0 ? src.slice(qi) : ''; } let BACKEND; /** @@ -2129,10 +2132,13 @@ let DEV_BACKEND; DEV_BACKEND = { unloadChunk (chunkUrl) { deleteResolver(chunkUrl); + // Strip query string so we match links regardless of cache-busting + // params (e.g. ?ts=) that may differ between HMR updates. + const baseChunkUrl = chunkUrl.split('?')[0]; // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped. - const decodedChunkUrl = decodeURI(chunkUrl); + const decodedBaseChunkUrl = decodeURI(baseChunkUrl); if (isCss(chunkUrl)) { - const links = document.querySelectorAll(`link[href="${chunkUrl}"],link[href^="${chunkUrl}?"],link[href="${decodedChunkUrl}"],link[href^="${decodedChunkUrl}?"]`); + const links = document.querySelectorAll(`link[href="${baseChunkUrl}"],link[href^="${baseChunkUrl}?"],link[href="${decodedBaseChunkUrl}"],link[href^="${decodedBaseChunkUrl}?"]`); for (const link of Array.from(links)){ link.remove(); } @@ -2141,7 +2147,7 @@ let DEV_BACKEND; // runtime once evaluated. // However, we still want to remove the script tag from the DOM to keep // the HTML somewhat consistent from the user's perspective. - const scripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); + const scripts = document.querySelectorAll(`script[src="${baseChunkUrl}"],script[src^="${baseChunkUrl}?"],script[src="${decodedBaseChunkUrl}"],script[src^="${decodedBaseChunkUrl}?"]`); for (const script of Array.from(scripts)){ script.remove(); } @@ -2155,23 +2161,34 @@ let DEV_BACKEND; reject(new Error('The DOM backend can only reload CSS chunks')); return; } - const decodedChunkUrl = decodeURI(chunkUrl); - const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`); + // Strip query string so we match links regardless of cache-busting + // params (e.g. ?ts=) that may differ between HMR updates. + const baseChunkUrl = chunkUrl.split('?')[0]; + const decodedBaseChunkUrl = decodeURI(baseChunkUrl); + const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${baseChunkUrl}"],link[rel=stylesheet][href^="${baseChunkUrl}?"],link[rel=stylesheet][href="${decodedBaseChunkUrl}"],link[rel=stylesheet][href^="${decodedBaseChunkUrl}?"]`); if (previousLinks.length === 0) { reject(new Error(`No link element found for chunk ${chunkUrl}`)); return; } const link = document.createElement('link'); link.rel = 'stylesheet'; - if (navigator.userAgent.includes('Firefox')) { - // Firefox won't reload CSS files that were previously loaded on the current page, - // we need to add a query param to make sure CSS is actually reloaded from the server. + if (navigator.userAgent.includes('Firefox') || navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome') && !navigator.userAgent.includes('Chromium')) { + // Firefox won't reload CSS files that were previously loaded on the + // current page: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506 // - // I believe this is this issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506 + // Safari serves cached CSS when a exists for the + // same URL: https://bugs.webkit.org/show_bug.cgi?id=187726 // - // Safari has a similar issue, but only if you have a `` tag - // pointing to the same URL as the stylesheet: https://bugs.webkit.org/show_bug.cgi?id=187726 - link.href = `${chunkUrl}?ts=${Date.now()}`; + // Replace or add a fresh `ts` cache-busting param without + // discarding other query parameters that may already be present. + const url = new URL(chunkUrl, location.origin); + url.searchParams.set('ts', String(Date.now())); + // Reduced timer precision in some browers could lead to an update getting dropped + // in firefox if it happens fast enough (in firefox precision is sometimes 100ms!). + // So trust that the server is only updating us when it is important and use a + // random number to bust the cache. + url.searchParams.set('_next_rand', String(Math.random())); + link.href = url.pathname + url.search; } else { link.href = chunkUrl; } @@ -2217,5 +2234,5 @@ chunkListsToRegister.forEach(registerChunkList); })(); -//# debugId=c7d0d6f1-2fed-24f2-514f-5f447a850612 +//# debugId=154fe60a-f286-b7e0-80b6-f5300e0e86a1 //# sourceMappingURL=0teu_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0jat3.b.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/0fw._turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_0evo.uz.js b/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/0fw._turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_0evo.uz.js index d7baa9ffdc23..500efae5c16b 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/0fw._turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_0evo.uz.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/0fw._turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_0evo.uz.js @@ -1956,7 +1956,10 @@ globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= []; /// function getAssetSuffixFromScriptSrc() { // TURBOPACK_ASSET_SUFFIX is set in web workers - return (self.TURBOPACK_ASSET_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || ''; + if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX; + const src = document?.currentScript?.getAttribute?.('src') ?? ''; + const qi = src.indexOf('?'); + return qi >= 0 ? src.slice(qi) : ''; } let BACKEND; /** @@ -2128,10 +2131,13 @@ let DEV_BACKEND; DEV_BACKEND = { unloadChunk (chunkUrl) { deleteResolver(chunkUrl); + // Strip query string so we match links regardless of cache-busting + // params (e.g. ?ts=) that may differ between HMR updates. + const baseChunkUrl = chunkUrl.split('?')[0]; // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped. - const decodedChunkUrl = decodeURI(chunkUrl); + const decodedBaseChunkUrl = decodeURI(baseChunkUrl); if (isCss(chunkUrl)) { - const links = document.querySelectorAll(`link[href="${chunkUrl}"],link[href^="${chunkUrl}?"],link[href="${decodedChunkUrl}"],link[href^="${decodedChunkUrl}?"]`); + const links = document.querySelectorAll(`link[href="${baseChunkUrl}"],link[href^="${baseChunkUrl}?"],link[href="${decodedBaseChunkUrl}"],link[href^="${decodedBaseChunkUrl}?"]`); for (const link of Array.from(links)){ link.remove(); } @@ -2140,7 +2146,7 @@ let DEV_BACKEND; // runtime once evaluated. // However, we still want to remove the script tag from the DOM to keep // the HTML somewhat consistent from the user's perspective. - const scripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); + const scripts = document.querySelectorAll(`script[src="${baseChunkUrl}"],script[src^="${baseChunkUrl}?"],script[src="${decodedBaseChunkUrl}"],script[src^="${decodedBaseChunkUrl}?"]`); for (const script of Array.from(scripts)){ script.remove(); } @@ -2154,23 +2160,34 @@ let DEV_BACKEND; reject(new Error('The DOM backend can only reload CSS chunks')); return; } - const decodedChunkUrl = decodeURI(chunkUrl); - const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`); + // Strip query string so we match links regardless of cache-busting + // params (e.g. ?ts=) that may differ between HMR updates. + const baseChunkUrl = chunkUrl.split('?')[0]; + const decodedBaseChunkUrl = decodeURI(baseChunkUrl); + const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${baseChunkUrl}"],link[rel=stylesheet][href^="${baseChunkUrl}?"],link[rel=stylesheet][href="${decodedBaseChunkUrl}"],link[rel=stylesheet][href^="${decodedBaseChunkUrl}?"]`); if (previousLinks.length === 0) { reject(new Error(`No link element found for chunk ${chunkUrl}`)); return; } const link = document.createElement('link'); link.rel = 'stylesheet'; - if (navigator.userAgent.includes('Firefox')) { - // Firefox won't reload CSS files that were previously loaded on the current page, - // we need to add a query param to make sure CSS is actually reloaded from the server. + if (navigator.userAgent.includes('Firefox') || navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome') && !navigator.userAgent.includes('Chromium')) { + // Firefox won't reload CSS files that were previously loaded on the + // current page: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506 // - // I believe this is this issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506 + // Safari serves cached CSS when a exists for the + // same URL: https://bugs.webkit.org/show_bug.cgi?id=187726 // - // Safari has a similar issue, but only if you have a `` tag - // pointing to the same URL as the stylesheet: https://bugs.webkit.org/show_bug.cgi?id=187726 - link.href = `${chunkUrl}?ts=${Date.now()}`; + // Replace or add a fresh `ts` cache-busting param without + // discarding other query parameters that may already be present. + const url = new URL(chunkUrl, location.origin); + url.searchParams.set('ts', String(Date.now())); + // Reduced timer precision in some browers could lead to an update getting dropped + // in firefox if it happens fast enough (in firefox precision is sometimes 100ms!). + // So trust that the server is only updating us when it is important and use a + // random number to bust the cache. + url.searchParams.set('_next_rand', String(Math.random())); + link.href = url.pathname + url.search; } else { link.href = chunkUrl; } diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/0ko._turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_0evo.uz.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/0ko._turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_0evo.uz.js.map index 8d17818c396f..e9d426222813 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/0ko._turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_0evo.uz.js.map +++ b/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/0ko._turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_0evo.uz.js.map @@ -6,6 +6,6 @@ {"offset": {"line": 590, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/runtime-base.ts"],"sourcesContent":["/**\n * This file contains runtime types and functions that are shared between all\n * Turbopack *browser* ECMAScript runtimes.\n *\n * It will be appended to the runtime code of each runtime right after the\n * shared runtime utils.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\n// Used in WebWorkers to tell the runtime about the chunk suffix\ndeclare var TURBOPACK_ASSET_SUFFIX: string\n// Used in WebWorkers to tell the runtime about the current chunk url since it\n// can't be detected via `document.currentScript`. Note it's stored in reversed\n// order to use `push` and `pop`\ndeclare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined\n\n// Injected by rust code\ndeclare var CHUNK_BASE_PATH: string\ndeclare var ASSET_SUFFIX: string\ndeclare var WORKER_FORWARDED_GLOBALS: string[]\n\ninterface TurbopackBrowserBaseContext extends TurbopackBaseContext {\n R: ResolvePathFromModule\n}\n\nconst browserContextPrototype =\n Context.prototype as TurbopackBrowserBaseContext\n\n// Provided by build or dev base\ndeclare function instantiateModule(\n id: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): Module\n\ntype RuntimeParams = {\n otherChunks: ChunkData[]\n runtimeModuleIds: ModuleId[]\n}\n\ntype ChunkRegistrationChunk =\n | ChunkPath\n | { getAttribute: (name: string) => string | null }\n | undefined\n\ntype ChunkRegistration = [\n chunkPath: ChunkRegistrationChunk,\n ...([RuntimeParams] | CompressedModuleFactories),\n]\n\ntype ChunkList = {\n script: ChunkRegistrationChunk\n chunks: ChunkData[]\n source: 'entry' | 'dynamic'\n}\n\ninterface RuntimeBackend {\n registerChunk: (\n chunkPath: ChunkPath | ChunkScript,\n params?: RuntimeParams\n ) => void\n /**\n * Returns the same Promise for the same chunk URL.\n */\n loadChunkCached: (sourceType: SourceType, chunkUrl: ChunkUrl) => Promise\n loadWebAssembly: (\n sourceType: SourceType,\n sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ) => Promise\n loadWebAssemblyModule: (\n sourceType: SourceType,\n sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module\n ) => Promise\n}\n\ninterface DevRuntimeBackend {\n reloadChunk?: (chunkUrl: ChunkUrl) => Promise\n unloadChunk?: (chunkUrl: ChunkUrl) => void\n restart: () => void\n}\n\nconst moduleFactories: ModuleFactories = new Map()\ncontextPrototype.M = moduleFactories\n\nconst availableModules: Map | true> = new Map()\n\nconst availableModuleChunks: Map | true> = new Map()\n\nfunction loadChunk(\n this: TurbopackBrowserBaseContext,\n chunkData: ChunkData\n): Promise {\n return loadChunkInternal(SourceType.Parent, this.m.id, chunkData)\n}\nbrowserContextPrototype.l = loadChunk\n\nfunction loadInitialChunk(chunkPath: ChunkPath, chunkData: ChunkData) {\n return loadChunkInternal(SourceType.Runtime, chunkPath, chunkData)\n}\n\nasync function loadChunkInternal(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkData: ChunkData\n): Promise {\n if (typeof chunkData === 'string') {\n return loadChunkPath(sourceType, sourceData, chunkData)\n }\n\n const includedList = chunkData.included || []\n const modulesPromises = includedList.map((included) => {\n if (moduleFactories.has(included)) return true\n return availableModules.get(included)\n })\n if (modulesPromises.length > 0 && modulesPromises.every((p) => p)) {\n // When all included items are already loaded or loading, we can skip loading ourselves\n await Promise.all(modulesPromises)\n return\n }\n\n const includedModuleChunksList = chunkData.moduleChunks || []\n const moduleChunksPromises = includedModuleChunksList\n .map((included) => {\n // TODO(alexkirsz) Do we need this check?\n // if (moduleFactories[included]) return true;\n return availableModuleChunks.get(included)\n })\n .filter((p) => p)\n\n let promise: Promise\n if (moduleChunksPromises.length > 0) {\n // Some module chunks are already loaded or loading.\n\n if (moduleChunksPromises.length === includedModuleChunksList.length) {\n // When all included module chunks are already loaded or loading, we can skip loading ourselves\n await Promise.all(moduleChunksPromises)\n return\n }\n\n const moduleChunksToLoad: Set = new Set()\n for (const moduleChunk of includedModuleChunksList) {\n if (!availableModuleChunks.has(moduleChunk)) {\n moduleChunksToLoad.add(moduleChunk)\n }\n }\n\n for (const moduleChunkToLoad of moduleChunksToLoad) {\n const promise = loadChunkPath(sourceType, sourceData, moduleChunkToLoad)\n\n availableModuleChunks.set(moduleChunkToLoad, promise)\n\n moduleChunksPromises.push(promise)\n }\n\n promise = Promise.all(moduleChunksPromises)\n } else {\n promise = loadChunkPath(sourceType, sourceData, chunkData.path)\n\n // Mark all included module chunks as loading if they are not already loaded or loading.\n for (const includedModuleChunk of includedModuleChunksList) {\n if (!availableModuleChunks.has(includedModuleChunk)) {\n availableModuleChunks.set(includedModuleChunk, promise)\n }\n }\n }\n\n for (const included of includedList) {\n if (!availableModules.has(included)) {\n // It might be better to race old and new promises, but it's rare that the new promise will be faster than a request started earlier.\n // In production it's even more rare, because the chunk optimization tries to deduplicate modules anyway.\n availableModules.set(included, promise)\n }\n }\n\n await promise\n}\n\nconst loadedChunk = Promise.resolve(undefined)\nconst instrumentedBackendLoadChunks = new WeakMap<\n Promise,\n Promise | typeof loadedChunk\n>()\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkByUrl(\n this: TurbopackBrowserBaseContext,\n chunkUrl: ChunkUrl\n) {\n return loadChunkByUrlInternal(SourceType.Parent, this.m.id, chunkUrl)\n}\nbrowserContextPrototype.L = loadChunkByUrl\n\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkByUrlInternal(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkUrl: ChunkUrl\n): Promise {\n const thenable = BACKEND.loadChunkCached(sourceType, chunkUrl)\n let entry = instrumentedBackendLoadChunks.get(thenable)\n if (entry === undefined) {\n const resolve = instrumentedBackendLoadChunks.set.bind(\n instrumentedBackendLoadChunks,\n thenable,\n loadedChunk\n )\n entry = thenable.then(resolve).catch((cause) => {\n let loadReason: string\n switch (sourceType) {\n case SourceType.Runtime:\n loadReason = `as a runtime dependency of chunk ${sourceData}`\n break\n case SourceType.Parent:\n loadReason = `from module ${sourceData}`\n break\n case SourceType.Update:\n loadReason = 'from an HMR update'\n break\n default:\n invariant(\n sourceType,\n (sourceType) => `Unknown source type: ${sourceType}`\n )\n }\n let error = new Error(\n `Failed to load chunk ${chunkUrl} ${loadReason}${\n cause ? `: ${cause}` : ''\n }`,\n cause ? { cause } : undefined\n )\n error.name = 'ChunkLoadError'\n throw error\n })\n instrumentedBackendLoadChunks.set(thenable, entry)\n }\n\n return entry\n}\n\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkPath(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkPath: ChunkPath\n): Promise {\n const url = getChunkRelativeUrl(chunkPath)\n return loadChunkByUrlInternal(sourceType, sourceData, url)\n}\n\n/**\n * Returns an absolute url to an asset.\n */\nfunction resolvePathFromModule(\n this: TurbopackBaseContext,\n moduleId: string\n): string {\n const exported = this.r(moduleId)\n return exported?.default ?? exported\n}\nbrowserContextPrototype.R = resolvePathFromModule\n\n/**\n * no-op for browser\n * @param modulePath\n */\nfunction resolveAbsolutePath(modulePath?: string): string {\n return `/ROOT/${modulePath ?? ''}`\n}\nbrowserContextPrototype.P = resolveAbsolutePath\n\n/**\n * Exports a URL with the static suffix appended.\n */\nfunction exportUrl(\n this: TurbopackBrowserBaseContext,\n url: string,\n id: ModuleId | undefined\n) {\n exportValue.call(this, `${url}${ASSET_SUFFIX}`, id)\n}\nbrowserContextPrototype.q = exportUrl\n\n/**\n * Creates a worker by instantiating the given WorkerConstructor with the\n * appropriate URL and options.\n *\n * The entrypoint is a pre-compiled worker runtime file. The params configure\n * which module chunks to load and which module to run as the entry point.\n *\n * The params are a JSON array of the following structure:\n * `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`\n *\n * @param WorkerConstructor The Worker or SharedWorker constructor\n * @param entrypoint URL path to the worker entrypoint chunk\n * @param moduleChunks list of module chunk paths to load\n * @param workerOptions options to pass to the Worker constructor (optional)\n */\nfunction createWorker(\n WorkerConstructor: { new (url: URL, options?: object): Worker },\n entrypoint: ChunkPath,\n moduleChunks: ChunkPath[],\n workerOptions?: object\n): Worker {\n const isSharedWorker = WorkerConstructor.name === 'SharedWorker'\n\n const chunkUrls = moduleChunks\n .map((chunk) => getChunkRelativeUrl(chunk))\n .reverse()\n const params: unknown[] = [chunkUrls, ASSET_SUFFIX]\n for (const globalName of WORKER_FORWARDED_GLOBALS) {\n params.push((globalThis as Record)[globalName])\n }\n\n const url = new URL(getChunkRelativeUrl(entrypoint), location.origin)\n const paramsJson = JSON.stringify(params)\n if (isSharedWorker) {\n url.searchParams.set('params', paramsJson)\n } else {\n url.hash = '#params=' + encodeURIComponent(paramsJson)\n }\n\n // Remove type: \"module\" from options since our worker entrypoint is not a module\n const options = workerOptions\n ? { ...workerOptions, type: undefined }\n : undefined\n return new WorkerConstructor(url, options)\n}\nbrowserContextPrototype.b = createWorker\n\n/**\n * Instantiates a runtime module.\n */\nfunction instantiateRuntimeModule(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): Module {\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n/**\n * Returns the URL relative to the origin where a chunk can be fetched from.\n */\nfunction getChunkRelativeUrl(chunkPath: ChunkPath | ChunkListPath): ChunkUrl {\n return `${CHUNK_BASE_PATH}${chunkPath\n .split('/')\n .map((p) => encodeURIComponent(p))\n .join('/')}${ASSET_SUFFIX}` as ChunkUrl\n}\n\n/**\n * Return the ChunkPath from a ChunkScript.\n */\nfunction getPathFromScript(chunkScript: ChunkPath | ChunkScript): ChunkPath\nfunction getPathFromScript(\n chunkScript: ChunkListPath | ChunkListScript\n): ChunkListPath\nfunction getPathFromScript(\n chunkScript: ChunkPath | ChunkListPath | ChunkScript | ChunkListScript\n): ChunkPath | ChunkListPath {\n if (typeof chunkScript === 'string') {\n return chunkScript as ChunkPath | ChunkListPath\n }\n const chunkUrl = chunkScript.src!\n const src = decodeURIComponent(chunkUrl.replace(/[?#].*$/, ''))\n const path = src.startsWith(CHUNK_BASE_PATH)\n ? src.slice(CHUNK_BASE_PATH.length)\n : src\n return path as ChunkPath | ChunkListPath\n}\n\n/**\n * Return the ChunkUrl from a ChunkScript.\n */\nfunction getUrlFromScript(chunk: ChunkPath | ChunkScript): ChunkUrl {\n if (typeof chunk === 'string') {\n return getChunkRelativeUrl(chunk)\n } else {\n // This is already exactly what we want\n return chunk.src! as ChunkUrl\n }\n}\n\n/**\n * Determine the chunk to register. Note that this function has side-effects!\n */\nfunction getChunkFromRegistration(\n chunk: ChunkRegistrationChunk\n): ChunkPath | CurrentScript {\n if (typeof chunk === 'string') {\n return chunk\n } else if (!chunk) {\n if (typeof TURBOPACK_NEXT_CHUNK_URLS !== 'undefined') {\n return { src: TURBOPACK_NEXT_CHUNK_URLS.pop()! } as CurrentScript\n } else {\n throw new Error('chunk path empty but not in a worker')\n }\n } else {\n return { src: chunk.getAttribute('src')! } as CurrentScript\n }\n}\n\nconst regexJsUrl = /\\.js(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.\n */\nfunction isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {\n return regexJsUrl.test(chunkUrlOrPath)\n}\n\nconst regexCssUrl = /\\.css(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .css, optionally followed by ?query or #fragment.\n */\nfunction isCss(chunkUrl: ChunkUrl): boolean {\n return regexCssUrl.test(chunkUrl)\n}\n\nfunction loadWebAssembly(\n this: TurbopackBaseContext,\n chunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n): Promise {\n return BACKEND.loadWebAssembly(\n SourceType.Parent,\n this.m.id,\n chunkPath,\n edgeModule,\n importsObj\n )\n}\ncontextPrototype.w = loadWebAssembly\n\nfunction loadWebAssemblyModule(\n this: TurbopackBaseContext,\n chunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module\n): Promise {\n return BACKEND.loadWebAssemblyModule(\n SourceType.Parent,\n this.m.id,\n chunkPath,\n edgeModule\n )\n}\ncontextPrototype.u = loadWebAssemblyModule\n"],"names":["browserContextPrototype","Context","prototype","moduleFactories","Map","contextPrototype","M","availableModules","availableModuleChunks","loadChunk","chunkData","loadChunkInternal","SourceType","Parent","m","id","l","loadInitialChunk","chunkPath","Runtime","sourceType","sourceData","loadChunkPath","includedList","included","modulesPromises","map","has","get","length","every","p","Promise","all","includedModuleChunksList","moduleChunks","moduleChunksPromises","filter","promise","moduleChunksToLoad","Set","moduleChunk","add","moduleChunkToLoad","set","push","path","includedModuleChunk","loadedChunk","resolve","undefined","instrumentedBackendLoadChunks","WeakMap","loadChunkByUrl","chunkUrl","loadChunkByUrlInternal","L","thenable","BACKEND","loadChunkCached","entry","bind","then","catch","cause","loadReason","Update","invariant","error","Error","name","url","getChunkRelativeUrl","resolvePathFromModule","moduleId","exported","r","default","R","resolveAbsolutePath","modulePath","P","exportUrl","exportValue","call","ASSET_SUFFIX","q","createWorker","WorkerConstructor","entrypoint","workerOptions","isSharedWorker","chunkUrls","chunk","reverse","params","globalName","WORKER_FORWARDED_GLOBALS","globalThis","URL","location","origin","paramsJson","JSON","stringify","searchParams","hash","encodeURIComponent","options","type","b","instantiateRuntimeModule","instantiateModule","CHUNK_BASE_PATH","split","join","getPathFromScript","chunkScript","src","decodeURIComponent","replace","startsWith","slice","getUrlFromScript","getChunkFromRegistration","TURBOPACK_NEXT_CHUNK_URLS","pop","getAttribute","regexJsUrl","isJs","chunkUrlOrPath","test","regexCssUrl","isCss","loadWebAssembly","edgeModule","importsObj","w","loadWebAssemblyModule","u"],"mappings":"AAAA;;;;;;CAMC,GAED,oDAAoD,GAEpD,6CAA6C;AAC7C,iEAAiE;AAEjE,gEAAgE;AAgBhE,MAAMA,0BACJC,QAAQC,SAAS;AA4DnB,MAAMC,kBAAmC,IAAIC;AAC7CC,iBAAiBC,CAAC,GAAGH;AAErB,MAAMI,mBAAuD,IAAIH;AAEjE,MAAMI,wBAA6D,IAAIJ;AAEvE,SAASK,UAEPC,SAAoB;IAEpB,OAAOC,kBAAkBC,WAAWC,MAAM,EAAE,IAAI,CAACC,CAAC,CAACC,EAAE,EAAEL;AACzD;AACAV,wBAAwBgB,CAAC,GAAGP;AAE5B,SAASQ,iBAAiBC,SAAoB,EAAER,SAAoB;IAClE,OAAOC,kBAAkBC,WAAWO,OAAO,EAAED,WAAWR;AAC1D;AAEA,eAAeC,kBACbS,UAAsB,EACtBC,UAAsB,EACtBX,SAAoB;IAEpB,IAAI,OAAOA,cAAc,UAAU;QACjC,OAAOY,cAAcF,YAAYC,YAAYX;IAC/C;IAEA,MAAMa,eAAeb,UAAUc,QAAQ,IAAI,EAAE;IAC7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QACL,OAAO;YAAEiD,KAAKzB,MAAMkC,YAAY,CAAC;QAAQ;IAC3C;AACF;AAEA,MAAMC,aAAa;AACnB;;CAEC,GACD,SAASC,KAAKC,cAAoC;IAChD,OAAOF,WAAWG,IAAI,CAACD;AACzB;AAEA,MAAME,cAAc;AACpB;;CAEC,GACD,SAASC,MAAM/E,QAAkB;IAC/B,OAAO8E,YAAYD,IAAI,CAAC7E;AAC1B;AAEA,SAASgF,gBAEPpH,SAAoB,EACpBqH,UAAoC,EACpCC,UAA+B;IAE/B,OAAO9E,QAAQ4E,eAAe,CAC5B1H,WAAWC,MAAM,EACjB,IAAI,CAACC,CAAC,CAACC,EAAE,EACTG,WACAqH,YACAC;AAEJ;AACAnI,iBAAiBoI,CAAC,GAAGH;AAErB,SAASI,sBAEPxH,SAAoB,EACpBqH,UAAoC;IAEpC,OAAO7E,QAAQgF,qBAAqB,CAClC9H,WAAWC,MAAM,EACjB,IAAI,CAACC,CAAC,CAACC,EAAE,EACTG,WACAqH;AAEJ;AACAlI,iBAAiBsI,CAAC,GAAGD","ignoreList":[0]}}, {"offset": {"line": 839, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared/runtime/hmr-runtime.ts"],"sourcesContent":["/// \n/// \n/// \n/// \n\ntype HotModuleFactoryFunction = ModuleFactoryFunction<\n HotModule,\n TurbopackBaseContext\n>\n\n/**\n * Shared HMR (Hot Module Replacement) implementation.\n *\n * This file contains the complete HMR implementation that's shared between\n * browser and Node.js runtimes. It manages module hot state, dependency\n * tracking, the module.hot API, and the full HMR update flow.\n */\n\n/**\n * The development module cache shared across the runtime.\n * Browser runtime declares this directly.\n * Node.js runtime assigns globalThis.__turbopack_module_cache__ to this.\n */\nlet devModuleCache: Record\n\n/**\n * Module IDs that are instantiated as part of the runtime of a chunk.\n */\nlet runtimeModules: Set\n\n/**\n * Maps module IDs to persisted data between executions of their hot module\n * implementation (`hot.data`).\n */\nconst moduleHotData: Map = new Map()\n\n/**\n * Maps module instances to their hot module state.\n * Uses WeakMap so it works with both HotModule and ModuleWithDirection.\n */\nconst moduleHotState: WeakMap = new WeakMap()\n\n/**\n * Modules that call `module.hot.invalidate()` (while being updated).\n */\nconst queuedInvalidatedModules: Set = new Set()\n\nclass UpdateApplyError extends Error {\n name = 'UpdateApplyError'\n\n dependencyChain: ModuleId[]\n\n constructor(message: string, dependencyChain: ModuleId[]) {\n super(message)\n this.dependencyChain = dependencyChain\n }\n}\n\ntype ModuleEffect =\n | {\n type: 'unaccepted'\n dependencyChain: ModuleId[]\n }\n | {\n type: 'self-declined'\n dependencyChain: ModuleId[]\n moduleId: ModuleId\n }\n | {\n type: 'declined'\n dependencyChain: ModuleId[]\n moduleId: ModuleId\n parentId: ModuleId\n }\n | {\n type: 'accepted'\n moduleId: ModuleId\n outdatedModules: Set\n outdatedDependencies: Map>\n }\n\n/**\n * Records parent-child relationship when a module imports another.\n * Should be called during module instantiation.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction trackModuleImport(\n parentModule: ModuleWithDirection,\n childModuleId: ModuleId,\n childModule: ModuleWithDirection | undefined\n): void {\n // Record that parent imports child\n if (parentModule.children.indexOf(childModuleId) === -1) {\n parentModule.children.push(childModuleId)\n }\n\n // Record that child is imported by parent\n if (childModule && childModule.parents.indexOf(parentModule.id) === -1) {\n childModule.parents.push(parentModule.id)\n }\n}\n\nfunction formatDependencyChain(dependencyChain: ModuleId[]): string {\n return `Dependency chain: ${dependencyChain.join(' -> ')}`\n}\n\n/**\n * Walks the dependency tree to find all modules affected by a change.\n * Returns information about whether the update can be accepted and which\n * modules need to be invalidated.\n *\n * @param moduleId - The module that changed\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept().\n * This is used for server-side HMR where pages auto-accept at the top level.\n */\nfunction getAffectedModuleEffects(\n moduleId: ModuleId,\n autoAcceptRootModules: boolean\n): ModuleEffect {\n const outdatedModules: Set = new Set()\n const outdatedDependencies: Map> = new Map()\n\n type QueueItem = { moduleId?: ModuleId; dependencyChain: ModuleId[] }\n\n const queue: QueueItem[] = [\n {\n moduleId,\n dependencyChain: [],\n },\n ]\n\n let nextItem\n while ((nextItem = queue.shift())) {\n const { moduleId, dependencyChain } = nextItem\n\n if (moduleId != null) {\n if (outdatedModules.has(moduleId)) {\n // Avoid infinite loops caused by cycles between modules in the dependency chain.\n continue\n }\n\n outdatedModules.add(moduleId)\n }\n\n // We've arrived at the runtime of the chunk, which means that nothing\n // else above can accept this update.\n if (moduleId === undefined) {\n if (autoAcceptRootModules) {\n return {\n type: 'accepted',\n moduleId,\n outdatedModules,\n outdatedDependencies,\n }\n }\n return {\n type: 'unaccepted',\n dependencyChain,\n }\n }\n\n const module = devModuleCache[moduleId]\n const hotState = moduleHotState.get(module)!\n\n if (\n // The module is not in the cache. Since this is a \"modified\" update,\n // it means that the module was never instantiated before.\n !module || // The module accepted itself without invalidating globalThis.\n // TODO is that right?\n (hotState.selfAccepted && !hotState.selfInvalidated)\n ) {\n continue\n }\n\n if (hotState.selfDeclined) {\n return {\n type: 'self-declined',\n dependencyChain,\n moduleId,\n }\n }\n\n if (runtimeModules.has(moduleId)) {\n if (autoAcceptRootModules) {\n continue\n }\n queue.push({\n moduleId: undefined,\n dependencyChain: [...dependencyChain, moduleId],\n })\n continue\n }\n\n for (const parentId of module.parents) {\n const parent = devModuleCache[parentId]\n\n if (!parent) {\n continue\n }\n\n const parentHotState = moduleHotState.get(parent)\n\n // Check if parent declined this dependency\n if (parentHotState?.declinedDependencies[moduleId]) {\n return {\n type: 'declined',\n dependencyChain: [...dependencyChain, moduleId],\n moduleId,\n parentId,\n }\n }\n\n // Skip if parent is already outdated\n if (outdatedModules.has(parentId)) {\n continue\n }\n\n // Check if parent accepts this dependency\n if (parentHotState?.acceptedDependencies[moduleId]) {\n if (!outdatedDependencies.has(parentId)) {\n outdatedDependencies.set(parentId, new Set())\n }\n outdatedDependencies.get(parentId)!.add(moduleId)\n continue\n }\n\n // Neither accepted nor declined — propagate to parent\n queue.push({\n moduleId: parentId,\n dependencyChain: [...dependencyChain, moduleId],\n })\n }\n\n // If no parents and we're at a root module, auto-accept if configured\n if (module.parents.length === 0 && autoAcceptRootModules) {\n continue\n }\n }\n\n return {\n type: 'accepted',\n moduleId,\n outdatedModules,\n outdatedDependencies,\n }\n}\n\n/**\n * Merges source dependency map into target dependency map.\n */\nfunction mergeDependencies(\n target: Map>,\n source: Map>\n): void {\n for (const [parentId, deps] of source) {\n const existing = target.get(parentId)\n if (existing) {\n for (const dep of deps) {\n existing.add(dep)\n }\n } else {\n target.set(parentId, new Set(deps))\n }\n }\n}\n\n/**\n * Computes all modules that need to be invalidated based on which modules changed.\n *\n * @param invalidated - The modules that have been invalidated\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction computedInvalidatedModules(\n invalidated: Iterable,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n} {\n const outdatedModules = new Set()\n const outdatedDependencies = new Map>()\n\n for (const moduleId of invalidated) {\n const effect = getAffectedModuleEffects(moduleId, autoAcceptRootModules)\n\n switch (effect.type) {\n case 'unaccepted':\n throw new UpdateApplyError(\n `cannot apply update: unaccepted module. ${formatDependencyChain(\n effect.dependencyChain\n )}.`,\n effect.dependencyChain\n )\n case 'self-declined':\n throw new UpdateApplyError(\n `cannot apply update: self-declined module. ${formatDependencyChain(\n effect.dependencyChain\n )}.`,\n effect.dependencyChain\n )\n case 'declined':\n throw new UpdateApplyError(\n `cannot apply update: declined dependency. ${formatDependencyChain(\n effect.dependencyChain\n )}. Declined by ${effect.parentId}.`,\n effect.dependencyChain\n )\n case 'accepted':\n for (const outdatedModuleId of effect.outdatedModules) {\n outdatedModules.add(outdatedModuleId)\n }\n mergeDependencies(outdatedDependencies, effect.outdatedDependencies)\n break\n default:\n invariant(effect, (effect) => `Unknown effect type: ${effect?.type}`)\n }\n }\n\n return { outdatedModules, outdatedDependencies }\n}\n\n/**\n * Creates the module.hot API object and its internal state.\n * This provides the HMR API that user code calls (module.hot.accept(), etc.)\n */\n\nfunction createModuleHot(\n moduleId: ModuleId,\n hotData: HotData\n): { hot: Hot; hotState: HotState } {\n const hotState: HotState = {\n selfAccepted: false,\n selfDeclined: false,\n selfInvalidated: false,\n disposeHandlers: [],\n acceptedDependencies: {},\n acceptedErrorHandlers: {},\n declinedDependencies: {},\n }\n\n const hot: Hot = {\n // TODO(alexkirsz) This is not defined in the HMR API. It was used to\n // decide whether to warn whenever an HMR-disposed module required other\n // modules. We might want to remove it.\n active: true,\n\n data: hotData ?? {},\n\n accept: (\n modules?: string | string[] | AcceptErrorHandler,\n callback?: AcceptCallback,\n errorHandler?: AcceptErrorHandler\n ) => {\n if (modules === undefined) {\n hotState.selfAccepted = true\n } else if (typeof modules === 'function') {\n hotState.selfAccepted = modules\n } else if (typeof modules === 'object' && modules !== null) {\n for (let i = 0; i < modules.length; i++) {\n hotState.acceptedDependencies[modules[i]] = callback || function () {}\n hotState.acceptedErrorHandlers[modules[i]] = errorHandler\n }\n } else {\n hotState.acceptedDependencies[modules] = callback || function () {}\n hotState.acceptedErrorHandlers[modules] = errorHandler\n }\n },\n\n decline: (dep?: string | string[]) => {\n if (dep === undefined) {\n hotState.selfDeclined = true\n } else if (typeof dep === 'object' && dep !== null) {\n for (let i = 0; i < dep.length; i++) {\n hotState.declinedDependencies[dep[i]] = true\n }\n } else {\n hotState.declinedDependencies[dep] = true\n }\n },\n\n dispose: (callback) => {\n hotState.disposeHandlers.push(callback)\n },\n\n addDisposeHandler: (callback) => {\n hotState.disposeHandlers.push(callback)\n },\n\n removeDisposeHandler: (callback) => {\n const idx = hotState.disposeHandlers.indexOf(callback)\n if (idx >= 0) {\n hotState.disposeHandlers.splice(idx, 1)\n }\n },\n\n invalidate: () => {\n hotState.selfInvalidated = true\n queuedInvalidatedModules.add(moduleId)\n },\n\n // NOTE(alexkirsz) This is part of the management API, which we don't\n // implement, but the Next.js React Refresh runtime uses this to decide\n // whether to schedule an update.\n status: () => 'idle',\n\n // NOTE(alexkirsz) Since we always return \"idle\" for now, these are no-ops.\n addStatusHandler: (_handler) => {},\n removeStatusHandler: (_handler) => {},\n\n // NOTE(jridgewell) Check returns the list of updated modules, but we don't\n // want the webpack code paths to ever update (the turbopack paths handle\n // this already).\n check: () => Promise.resolve(null),\n }\n\n return { hot, hotState }\n}\n\n/**\n * Processes queued invalidated modules and adds them to the outdated modules set.\n * Modules that call module.hot.invalidate() are queued and processed here.\n *\n * @param outdatedModules - The current set of outdated modules\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction applyInvalidatedModules(\n outdatedModules: Set,\n outdatedDependencies: Map>,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n} {\n if (queuedInvalidatedModules.size > 0) {\n const result = computedInvalidatedModules(\n queuedInvalidatedModules,\n autoAcceptRootModules\n )\n for (const moduleId of result.outdatedModules) {\n outdatedModules.add(moduleId)\n }\n mergeDependencies(outdatedDependencies, result.outdatedDependencies)\n\n queuedInvalidatedModules.clear()\n }\n\n return { outdatedModules, outdatedDependencies }\n}\n\n/**\n * Computes which outdated modules have self-accepted and can be hot reloaded.\n */\n\nfunction computeOutdatedSelfAcceptedModules(\n outdatedModules: Iterable\n): { moduleId: ModuleId; errorHandler: true | Function }[] {\n const outdatedSelfAcceptedModules: {\n moduleId: ModuleId\n errorHandler: true | Function\n }[] = []\n for (const moduleId of outdatedModules) {\n const module = devModuleCache[moduleId]\n const hotState = moduleHotState.get(module)\n if (module && hotState?.selfAccepted && !hotState.selfInvalidated) {\n outdatedSelfAcceptedModules.push({\n moduleId,\n errorHandler: hotState.selfAccepted,\n })\n }\n }\n return outdatedSelfAcceptedModules\n}\n\n/**\n * Disposes of an instance of a module.\n * Runs hot.dispose handlers and manages persistent hot data.\n *\n * NOTE: mode = \"replace\" will not remove modules from devModuleCache.\n * This must be done in a separate step afterwards.\n */\nfunction disposeModule(moduleId: ModuleId, mode: 'clear' | 'replace') {\n const module = devModuleCache[moduleId]\n if (!module) {\n return\n }\n\n const hotState = moduleHotState.get(module)\n if (!hotState) {\n return\n }\n\n const data: HotData = {}\n\n // Run the `hot.dispose` handler, if any, passing in the persistent\n // `hot.data` object.\n for (const disposeHandler of hotState.disposeHandlers) {\n disposeHandler(data)\n }\n\n // This used to warn in `getOrInstantiateModuleFromParent` when a disposed\n // module is still importing other modules.\n if (module.hot) {\n module.hot.active = false\n }\n\n moduleHotState.delete(module)\n\n // Remove the disposed module from its children's parent list.\n // It will be added back once the module re-instantiates and imports its\n // children again.\n for (const childId of module.children) {\n const child = devModuleCache[childId]\n if (!child) {\n continue\n }\n\n const idx = child.parents.indexOf(module.id)\n if (idx >= 0) {\n child.parents.splice(idx, 1)\n }\n }\n\n switch (mode) {\n case 'clear':\n delete devModuleCache[module.id]\n moduleHotData.delete(module.id)\n break\n case 'replace':\n moduleHotData.set(module.id, data)\n break\n default:\n invariant(mode, (mode) => `invalid mode: ${mode}`)\n }\n}\n\n/**\n * Dispose phase: runs dispose handlers and cleans up outdated/disposed modules.\n * Returns the parent modules of outdated modules for use in the apply phase.\n */\n\nfunction disposePhase(\n outdatedModules: Iterable,\n disposedModules: Iterable,\n outdatedDependencies: Map>\n): { outdatedModuleParents: Map> } {\n for (const moduleId of outdatedModules) {\n disposeModule(moduleId, 'replace')\n }\n\n for (const moduleId of disposedModules) {\n disposeModule(moduleId, 'clear')\n }\n\n // Removing modules from the module cache is a separate step.\n // We also want to keep track of previous parents of the outdated modules.\n const outdatedModuleParents = new Map>()\n for (const moduleId of outdatedModules) {\n const oldModule = devModuleCache[moduleId]\n outdatedModuleParents.set(moduleId, oldModule?.parents)\n delete devModuleCache[moduleId]\n }\n\n // Remove outdated dependencies from parent module's children list.\n // When a parent accepts a child's update, the child is re-instantiated\n // but the parent stays alive. We remove the old child reference so it\n // gets re-added when the child re-imports.\n for (const [parentId, deps] of outdatedDependencies) {\n const module = devModuleCache[parentId]\n if (module) {\n for (const dep of deps) {\n const idx = module.children.indexOf(dep)\n if (idx >= 0) {\n module.children.splice(idx, 1)\n }\n }\n }\n }\n\n return { outdatedModuleParents }\n}\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/**\n * Shared module instantiation logic.\n * This handles the full module instantiation flow for both browser and Node.js.\n * Only React Refresh hooks differ between platforms (passed as callback).\n */\nfunction instantiateModuleShared(\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n runtimeModules: Set,\n createModuleObjectFn: (id: ModuleId) => HotModule,\n createContextFn: (module: HotModule, exports: Exports, refresh?: any) => any,\n runModuleExecutionHooksFn: (\n module: HotModule,\n exec: (refresh: any) => void\n ) => void\n): HotModule {\n // 1. Factory validation (same in both browser and Node.js)\n const id = moduleId\n const moduleFactory = moduleFactories.get(id)\n if (typeof moduleFactory !== 'function') {\n throw new Error(\n factoryNotAvailableMessage(moduleId, sourceType, sourceData) +\n `\\nThis is often caused by a stale browser cache, misconfigured Cache-Control headers, or a service worker serving outdated responses.` +\n `\\nTo fix this, make sure your Cache-Control headers allow revalidation of chunks and review your service worker configuration. ` +\n `As an immediate workaround, try hard-reloading the page, clearing the browser cache, or unregistering any service workers.`\n )\n }\n\n // 2. Hot API setup (same in both - works for browser, included for Node.js)\n const hotData = moduleHotData.get(id)!\n const { hot, hotState } = createModuleHot(id, hotData)\n\n // 3. Parent assignment logic (same in both)\n let parents: ModuleId[]\n switch (sourceType) {\n case SourceType.Runtime:\n runtimeModules.add(id)\n parents = []\n break\n case SourceType.Parent:\n parents = [sourceData as ModuleId]\n break\n case SourceType.Update:\n parents = (sourceData as ModuleId[]) || []\n break\n default:\n throw new Error(`Unknown source type: ${sourceType}`)\n }\n\n // 4. Module creation (platform creates base module object)\n const module = createModuleObjectFn(id)\n const exports = module.exports\n module.parents = parents\n module.children = []\n module.hot = hot\n\n devModuleCache[id] = module\n moduleHotState.set(module, hotState)\n\n // 5. Module execution (React Refresh hooks are platform-specific)\n try {\n runModuleExecutionHooksFn(module, (refresh) => {\n const context = createContextFn(module, exports, refresh)\n moduleFactory.call(exports, context, module, exports)\n })\n } catch (error) {\n module.error = error as any\n throw error\n }\n\n // 6. ESM interop (same in both)\n if (module.namespaceObject && module.exports !== module.namespaceObject) {\n // in case of a circular dependency: cjs1 -> esm2 -> cjs1\n interopEsm(module.exports, module.namespaceObject)\n }\n\n return module\n}\n\n/**\n * Analyzes update entries and chunks to determine which modules were added, modified, or deleted.\n * This is pure logic that doesn't depend on the runtime environment.\n */\nfunction computeChangedModules(\n entries: Record,\n updates: Record,\n chunkModulesMap?: Map>\n): {\n added: Map\n modified: Map\n deleted: Set\n chunksAdded: Map>\n chunksDeleted: Map>\n} {\n const chunksAdded = new Map()\n const chunksDeleted = new Map()\n const added: Map = new Map()\n const modified = new Map()\n const deleted: Set = new Set()\n\n for (const [chunkPath, mergedChunkUpdate] of Object.entries(updates) as Array<\n [ChunkPath, EcmascriptMergedChunkUpdate]\n >) {\n switch (mergedChunkUpdate.type) {\n case 'added': {\n const updateAdded = new Set(mergedChunkUpdate.modules)\n for (const moduleId of updateAdded) {\n added.set(moduleId, entries[moduleId])\n }\n chunksAdded.set(chunkPath, updateAdded)\n break\n }\n case 'deleted': {\n const updateDeleted = chunkModulesMap\n ? new Set(chunkModulesMap.get(chunkPath))\n : new Set()\n for (const moduleId of updateDeleted) {\n deleted.add(moduleId)\n }\n chunksDeleted.set(chunkPath, updateDeleted)\n break\n }\n case 'partial': {\n const updateAdded = new Set(mergedChunkUpdate.added)\n const updateDeleted = new Set(mergedChunkUpdate.deleted)\n for (const moduleId of updateAdded) {\n added.set(moduleId, entries[moduleId])\n }\n for (const moduleId of updateDeleted) {\n deleted.add(moduleId)\n }\n chunksAdded.set(chunkPath, updateAdded)\n chunksDeleted.set(chunkPath, updateDeleted)\n break\n }\n default:\n throw new Error('Unknown merged chunk update type')\n }\n }\n\n // If a module was added from one chunk and deleted from another in the same update,\n // consider it to be modified, as it means the module was moved from one chunk to another\n // AND has new code in a single update.\n for (const moduleId of added.keys()) {\n if (deleted.has(moduleId)) {\n added.delete(moduleId)\n deleted.delete(moduleId)\n }\n }\n\n for (const [moduleId, entry] of Object.entries(entries)) {\n // Modules that haven't been added to any chunk but have new code are considered\n // to be modified.\n // This needs to be under the previous loop, as we need it to get rid of modules\n // that were added and deleted in the same update.\n if (!added.has(moduleId)) {\n modified.set(moduleId, entry)\n }\n }\n\n return { added, deleted, modified, chunksAdded, chunksDeleted }\n}\n\n/**\n * Compiles new module code and walks the dependency tree to find all outdated modules.\n * Uses the evalModuleEntry function to compile code (platform-specific).\n *\n * @param added - Map of added modules\n * @param modified - Map of modified modules\n * @param evalModuleEntry - Function to compile module code\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction computeOutdatedModules(\n added: Map,\n modified: Map,\n evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n newModuleFactories: Map\n} {\n const newModuleFactories = new Map()\n\n // Compile added modules\n for (const [moduleId, entry] of added) {\n if (entry != null) {\n newModuleFactories.set(moduleId, evalModuleEntry(entry))\n }\n }\n\n // Walk dependency tree to find all modules affected by modifications\n const { outdatedModules, outdatedDependencies } = computedInvalidatedModules(\n modified.keys(),\n autoAcceptRootModules\n )\n\n // Compile modified modules\n for (const [moduleId, entry] of modified) {\n newModuleFactories.set(moduleId, evalModuleEntry(entry))\n }\n\n return { outdatedModules, outdatedDependencies, newModuleFactories }\n}\n\n/**\n * Updates module factories and re-instantiates self-accepted modules.\n * Uses the instantiateModule function (platform-specific via callback).\n */\nfunction applyPhase(\n outdatedSelfAcceptedModules: {\n moduleId: ModuleId\n errorHandler: true | Function\n }[],\n newModuleFactories: Map,\n outdatedModuleParents: Map>,\n outdatedDependencies: Map>,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n instantiateModuleFn: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule,\n applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void,\n reportError: (err: any) => void\n) {\n // Update module factories\n for (const [moduleId, factory] of newModuleFactories.entries()) {\n applyModuleFactoryNameFn(factory)\n moduleFactories.set(moduleId, factory)\n }\n\n // TODO(alexkirsz) Run new runtime entries here.\n\n // Call accept handlers for outdated dependencies.\n // This runs BEFORE re-instantiating self-accepted modules, matching\n // webpack's behavior.\n for (const [parentId, deps] of outdatedDependencies) {\n const module = devModuleCache[parentId]\n if (!module) continue\n\n const hotState = moduleHotState.get(module)\n if (!hotState) continue\n\n // Group deps by callback, deduplicating callbacks that handle multiple deps.\n // Each callback receives only the deps it was registered for.\n const callbackDeps = new Map void), ModuleId[]>()\n const callbackErrorHandlers = new Map<\n AcceptCallback | (() => void),\n AcceptErrorHandler | undefined\n >()\n\n for (const dep of deps) {\n const acceptCallback = hotState.acceptedDependencies[dep]\n if (acceptCallback) {\n let depList = callbackDeps.get(acceptCallback)\n if (!depList) {\n depList = []\n callbackDeps.set(acceptCallback, depList)\n callbackErrorHandlers.set(\n acceptCallback,\n hotState.acceptedErrorHandlers[dep]\n )\n }\n depList.push(dep)\n }\n }\n\n for (const [callback, cbDeps] of callbackDeps) {\n try {\n callback.call(null, cbDeps)\n } catch (err: any) {\n const errorHandler = callbackErrorHandlers.get(callback)\n if (typeof errorHandler === 'function') {\n try {\n errorHandler(err, {\n moduleId: parentId,\n dependencyId: cbDeps[0],\n })\n } catch (err2) {\n reportError(err2)\n reportError(err)\n }\n } else {\n reportError(err)\n }\n }\n }\n }\n\n // Re-instantiate all outdated self-accepted modules\n for (const { moduleId, errorHandler } of outdatedSelfAcceptedModules) {\n try {\n instantiateModuleFn(\n moduleId,\n SourceType.Update,\n outdatedModuleParents.get(moduleId)\n )\n } catch (err) {\n if (typeof errorHandler === 'function') {\n try {\n errorHandler(err, { moduleId, module: devModuleCache[moduleId] })\n } catch (err2) {\n reportError(err2)\n reportError(err)\n }\n } else {\n reportError(err)\n }\n }\n }\n}\n\n/**\n * Internal implementation that orchestrates the full HMR update flow:\n * invalidation, disposal, and application of new modules.\n *\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction applyInternal(\n outdatedModules: Set,\n outdatedDependencies: Map>,\n disposedModules: Iterable,\n newModuleFactories: Map,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n instantiateModuleFn: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule,\n applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void,\n autoAcceptRootModules: boolean\n) {\n ;({ outdatedModules, outdatedDependencies } = applyInvalidatedModules(\n outdatedModules,\n outdatedDependencies,\n autoAcceptRootModules\n ))\n\n // Find self-accepted modules to re-instantiate\n const outdatedSelfAcceptedModules =\n computeOutdatedSelfAcceptedModules(outdatedModules)\n\n // Run dispose handlers, save hot.data, clear caches\n const { outdatedModuleParents } = disposePhase(\n outdatedModules,\n disposedModules,\n outdatedDependencies\n )\n\n let error: any\n\n function reportError(err: any) {\n if (!error) error = err // Keep first error\n }\n\n applyPhase(\n outdatedSelfAcceptedModules,\n newModuleFactories,\n outdatedModuleParents,\n outdatedDependencies,\n moduleFactories,\n devModuleCache,\n instantiateModuleFn,\n applyModuleFactoryNameFn,\n reportError\n )\n\n if (error) {\n throw error\n }\n\n // Recursively apply any queued invalidations from new module execution\n if (queuedInvalidatedModules.size > 0) {\n applyInternal(\n new Set(),\n new Map(),\n [],\n new Map(),\n moduleFactories,\n devModuleCache,\n instantiateModuleFn,\n applyModuleFactoryNameFn,\n autoAcceptRootModules\n )\n }\n}\n\n/**\n * Main entry point for applying an ECMAScript merged update.\n * This is called by both browser and Node.js runtimes with platform-specific callbacks.\n *\n * @param options.autoAcceptRootModules - If true, root modules auto-accept updates without explicit\n * module.hot.accept(). Used for server-side HMR where pages\n * auto-accept at the top level.\n */\nfunction applyEcmascriptMergedUpdateShared(options: {\n added: Map\n modified: Map\n disposedModules: Iterable\n evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction\n instantiateModule: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule\n applyModuleFactoryName: (factory: HotModuleFactoryFunction) => void\n moduleFactories: ModuleFactories\n devModuleCache: ModuleCache\n autoAcceptRootModules: boolean\n}) {\n const {\n added,\n modified,\n disposedModules,\n evalModuleEntry,\n instantiateModule,\n applyModuleFactoryName,\n moduleFactories,\n devModuleCache,\n autoAcceptRootModules,\n } = options\n\n const { outdatedModules, outdatedDependencies, newModuleFactories } =\n computeOutdatedModules(\n added,\n modified,\n evalModuleEntry,\n autoAcceptRootModules\n )\n\n applyInternal(\n outdatedModules,\n outdatedDependencies,\n disposedModules,\n newModuleFactories,\n moduleFactories,\n devModuleCache,\n instantiateModule,\n applyModuleFactoryName,\n autoAcceptRootModules\n )\n}\n"],"names":["devModuleCache","runtimeModules","moduleHotData","Map","moduleHotState","WeakMap","queuedInvalidatedModules","Set","UpdateApplyError","Error","name","dependencyChain","message","trackModuleImport","parentModule","childModuleId","childModule","children","indexOf","push","parents","id","formatDependencyChain","join","getAffectedModuleEffects","moduleId","autoAcceptRootModules","outdatedModules","outdatedDependencies","queue","nextItem","shift","has","add","undefined","type","module","hotState","get","selfAccepted","selfInvalidated","selfDeclined","parentId","parent","parentHotState","declinedDependencies","acceptedDependencies","set","length","mergeDependencies","target","source","deps","existing","dep","computedInvalidatedModules","invalidated","effect","outdatedModuleId","invariant","createModuleHot","hotData","disposeHandlers","acceptedErrorHandlers","hot","active","data","accept","modules","callback","errorHandler","i","decline","dispose","addDisposeHandler","removeDisposeHandler","idx","splice","invalidate","status","addStatusHandler","_handler","removeStatusHandler","check","Promise","resolve","applyInvalidatedModules","size","result","clear","computeOutdatedSelfAcceptedModules","outdatedSelfAcceptedModules","disposeModule","mode","disposeHandler","delete","childId","child","disposePhase","disposedModules","outdatedModuleParents","oldModule","instantiateModuleShared","sourceType","sourceData","moduleFactories","createModuleObjectFn","createContextFn","runModuleExecutionHooksFn","moduleFactory","factoryNotAvailableMessage","SourceType","Runtime","Parent","Update","exports","refresh","context","call","error","namespaceObject","interopEsm","computeChangedModules","entries","updates","chunkModulesMap","chunksAdded","chunksDeleted","added","modified","deleted","chunkPath","mergedChunkUpdate","Object","updateAdded","updateDeleted","keys","entry","computeOutdatedModules","evalModuleEntry","newModuleFactories","applyPhase","instantiateModuleFn","applyModuleFactoryNameFn","reportError","factory","callbackDeps","callbackErrorHandlers","acceptCallback","depList","cbDeps","err","dependencyId","err2","applyInternal","applyEcmascriptMergedUpdateShared","options","instantiateModule","applyModuleFactoryName"],"mappings":"AAAA,2CAA2C;AAC3C,6CAA6C;AAC7C,4CAA4C;AAC5C,4CAA4C;AAO5C;;;;;;CAMC,GAED;;;;CAIC,GACD,IAAIA;AAEJ;;CAEC,GACD,IAAIC;AAEJ;;;CAGC,GACD,MAAMC,gBAAwC,IAAIC;AAElD;;;CAGC,GACD,MAAMC,iBAAyC,IAAIC;AAEnD;;CAEC,GACD,MAAMC,2BAA0C,IAAIC;AAEpD,MAAMC,yBAAyBC;IAC7BC,OAAO,mBAAkB;IAEzBC,gBAA2B;IAE3BH,YAAYI,OAAe,EAAED,eAA2B,CAAE;QACxD,KAAK,CAACC;QACN,IAAI,CAACD,eAAe,GAAGA;IACzB;AACF;AAyBA;;;CAGC,GACD,6DAA6D;AAC7D,SAASE,kBACPC,YAAiC,EACjCC,aAAuB,EACvBC,WAA4C;IAE5C,mCAAmC;IACnC,IAAIF,aAAaG,QAAQ,CAACC,OAAO,CAACH,mBAAmB,CAAC,GAAG;QACvDD,aAAaG,QAAQ,CAACE,IAAI,CAACJ;IAC7B;IAEA,0CAA0C;IAC1C,IAAIC,eAAeA,YAAYI,OAAO,CAACF,OAAO,CAACJ,aAAaO,EAAE,MAAM,CAAC,GAAG;QACtEL,YAAYI,OAA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EAChCzG,cAAsC,EACtC8I,mBAIc,EACdC,wBAAqE,EACrErH,qBAA8B;;IAE7B,CAAC,EAAEC,eAAe,EAAEC,oBAAoB,EAAE,GAAG0D,wBAC5C3D,iBACAC,sBACAF,sBACD;IAED,+CAA+C;IAC/C,MAAMiE,8BACJD,mCAAmC/D;IAErC,oDAAoD;IACpD,MAAM,EAAEyE,qBAAqB,EAAE,GAAGF,aAChCvE,iBACAwE,iBACAvE;IAGF,IAAI2F;IAEJ,SAASyB,YAAYO,GAAQ;QAC3B,IAAI,CAAChC,OAAOA,QAAQgC,KAAI,mBAAmB;IAC7C;IAEAV,WACElD,6BACAiD,oBACAxC,uBACAxE,sBACA6E,iBACAzG,gBACA8I,qBACAC,0BACAC;IAGF,IAAIzB,OAAO;QACT,MAAMA;IACR;IAEA,uEAAuE;IACvE,IAAIjH,yBAAyBiF,IAAI,GAAG,GAAG;QACrCmE,cACE,IAAInJ,OACJ,IAAIJ,OACJ,EAAE,EACF,IAAIA,OACJsG,iBACAzG,gBACA8I,qBACAC,0BACArH;IAEJ;AACF;AAEA;;;;;;;CAOC,GACD,SAASiI,kCAAkCC,OAc1C;IACC,MAAM,EACJ5B,KAAK,EACLC,QAAQ,EACR9B,eAAe,EACfwC,eAAe,EACfkB,iBAAiB,EACjBC,sBAAsB,EACtBrD,eAAe,EACfzG,cAAc,EACd0B,qBAAqB,EACtB,GAAGkI;IAEJ,MAAM,EAAEjI,eAAe,EAAEC,oBAAoB,EAAEgH,kBAAkB,EAAE,GACjEF,uBACEV,OACAC,UACAU,iBACAjH;IAGJgI,cACE/H,iBACAC,sBACAuE,iBACAyC,oBACAnC,iBACAzG,gBACA6J,mBACAC,wBACApI;AAEJ","ignoreList":[0]}}, {"offset": {"line": 1533, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/dev-base.ts"],"sourcesContent":["/// \n/// \n\ninterface TurbopackDevContext extends TurbopackBrowserBaseContext {\n k: RefreshContext\n}\n\nconst devContextPrototype = Context.prototype as TurbopackDevContext\n\n/**\n * This file contains runtime types and functions that are shared between all\n * Turbopack *development* ECMAScript runtimes.\n *\n * It will be appended to the runtime code of each runtime right after the\n * shared runtime utils.\n */\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n// Assign browser's module cache and runtime modules to shared HMR state\ndevModuleCache = Object.create(null)\ndevContextPrototype.c = devModuleCache\nruntimeModules = new Set()\n\n// Set flag to indicate we use ModuleWithDirection\ncreateModuleWithDirectionFlag = true\n\n// This file must not use `import` and `export` statements. Otherwise, it\n// becomes impossible to augment interfaces declared in ``d files\n// (e.g. `Module`). Hence, the need for `import()` here.\ntype RefreshRuntimeGlobals =\n import('@next/react-refresh-utils/dist/runtime').RefreshRuntimeGlobals\n\ndeclare var $RefreshHelpers$: RefreshRuntimeGlobals['$RefreshHelpers$']\ndeclare var $RefreshReg$: RefreshRuntimeGlobals['$RefreshReg$']\ndeclare var $RefreshSig$: RefreshRuntimeGlobals['$RefreshSig$']\ndeclare var $RefreshInterceptModuleExecution$: RefreshRuntimeGlobals['$RefreshInterceptModuleExecution$']\n\ntype RefreshContext = {\n register: RefreshRuntimeGlobals['$RefreshReg$']\n signature: RefreshRuntimeGlobals['$RefreshSig$']\n registerExports: typeof registerExportsAndSetupBoundaryForReactRefresh\n}\n\ntype RefreshHelpers = RefreshRuntimeGlobals['$RefreshHelpers$']\n\ntype ModuleFactory = (\n this: Module['exports'],\n context: TurbopackDevContext\n) => unknown\n\ninterface DevRuntimeBackend {\n reloadChunk?: (chunkUrl: ChunkUrl) => Promise\n unloadChunk?: (chunkUrl: ChunkUrl) => void\n restart: () => void\n}\n\n/**\n * Map from module ID to the chunks that contain this module.\n *\n * In HMR, we need to keep track of which modules are contained in which so\n * chunks. This is so we don't eagerly dispose of a module when it is removed\n * from chunk A, but still exists in chunk B.\n */\nconst moduleChunksMap: Map> = new Map()\n/**\n * Map from a chunk path to all modules it contains.\n */\nconst chunkModulesMap: Map> = new Map()\n/**\n * Chunk lists that contain a runtime. When these chunk lists receive an update\n * that can't be reconciled with the current state of the page, we need to\n * reload the runtime entirely.\n */\nconst runtimeChunkLists: Set = new Set()\n/**\n * Map from a chunk list to the chunk paths it contains.\n */\nconst chunkListChunksMap: Map> = new Map()\n/**\n * Map from a chunk path to the chunk lists it belongs to.\n */\nconst chunkChunkListsMap: Map> = new Map()\n\n/**\n * Gets or instantiates a runtime module.\n */\n// @ts-ignore\nfunction getOrInstantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): Module {\n const module = devModuleCache[moduleId]\n if (module) {\n if (module.error) {\n throw module.error\n }\n return module\n }\n\n // @ts-ignore\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it if it is not cached.\n */\n// @ts-ignore Defined in `runtime-utils.ts`\nconst getOrInstantiateModuleFromParent: GetOrInstantiateModuleFromParent<\n HotModule\n> = (id, sourceModule) => {\n if (!sourceModule.hot.active) {\n console.warn(\n `Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`\n )\n }\n\n const module = devModuleCache[id]\n\n if (sourceModule.children.indexOf(id) === -1) {\n sourceModule.children.push(id)\n }\n\n if (module) {\n if (module.error) {\n throw module.error\n }\n\n if (module.parents.indexOf(sourceModule.id) === -1) {\n module.parents.push(sourceModule.id)\n }\n\n return module\n }\n\n return instantiateModule(id, SourceType.Parent, sourceModule.id)\n}\n\nfunction DevContext(\n this: TurbopackDevContext,\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n) {\n Context.call(this, module, exports)\n this.k = refresh\n}\nDevContext.prototype = Context.prototype\n\ntype DevContextConstructor = {\n new (\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n ): TurbopackDevContext\n}\n\nfunction instantiateModule(\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): Module {\n // Browser: creates base HotModule object (hot API added by shared code)\n const createModuleObjectFn = (id: ModuleId) => {\n return createModuleObject(id) as HotModule\n }\n\n // Browser: creates DevContext with refresh\n const createContext = (\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n ) => {\n return new (DevContext as any as DevContextConstructor)(\n module,\n exports,\n refresh\n )\n }\n\n // Use shared instantiation logic (includes hot API setup)\n return instantiateModuleShared(\n moduleId,\n sourceType,\n sourceData,\n moduleFactories,\n devModuleCache,\n runtimeModules,\n createModuleObjectFn,\n createContext,\n runModuleExecutionHooks\n )\n}\n\nconst DUMMY_REFRESH_CONTEXT = {\n register: (_type: unknown, _id: unknown) => {},\n signature: () => (_type: unknown) => {},\n registerExports: (_module: unknown, _helpers: unknown) => {},\n}\n\n/**\n * NOTE(alexkirsz) Webpack has a \"module execution\" interception hook that\n * Next.js' React Refresh runtime hooks into to add module context to the\n * refresh registry.\n */\nfunction runModuleExecutionHooks(\n module: HotModule,\n executeModule: (ctx: RefreshContext) => void\n) {\n if (typeof globalThis.$RefreshInterceptModuleExecution$ === 'function') {\n const cleanupReactRefreshIntercept =\n globalThis.$RefreshInterceptModuleExecution$(module.id)\n try {\n executeModule({\n register: globalThis.$RefreshReg$,\n signature: globalThis.$RefreshSig$,\n registerExports: registerExportsAndSetupBoundaryForReactRefresh,\n })\n } finally {\n // Always cleanup the intercept, even if module execution failed.\n cleanupReactRefreshIntercept()\n }\n } else {\n // If the react refresh hooks are not installed we need to bind dummy functions.\n // This is expected when running in a Web Worker. It is also common in some of\n // our test environments.\n executeModule(DUMMY_REFRESH_CONTEXT)\n }\n}\n\n/**\n * This is adapted from https://github.com/vercel/next.js/blob/3466862d9dc9c8bb3131712134d38757b918d1c0/packages/react-refresh-utils/internal/ReactRefreshModule.runtime.ts\n */\nfunction registerExportsAndSetupBoundaryForReactRefresh(\n module: HotModule,\n helpers: RefreshHelpers\n) {\n const currentExports = module.exports\n const prevExports = module.hot.data.prevExports ?? null\n\n helpers.registerExportsForReactRefresh(currentExports, module.id)\n\n // A module can be accepted automatically based on its exports, e.g. when\n // it is a Refresh Boundary.\n if (helpers.isReactRefreshBoundary(currentExports)) {\n // Save the previous exports on update, so we can compare the boundary\n // signatures.\n module.hot.dispose((data) => {\n data.prevExports = currentExports\n })\n // Unconditionally accept an update to this module, we'll check if it's\n // still a Refresh Boundary later.\n module.hot.accept()\n\n // This field is set when the previous version of this module was a\n // Refresh Boundary, letting us know we need to check for invalidation or\n // enqueue an update.\n if (prevExports !== null) {\n // A boundary can become ineligible if its exports are incompatible\n // with the previous exports.\n //\n // For example, if you add/remove/change exports, we'll want to\n // re-execute the importing modules, and force those components to\n // re-render. Similarly, if you convert a class component to a\n // function, we want to invalidate the boundary.\n if (\n helpers.shouldInvalidateReactRefreshBoundary(\n helpers.getRefreshBoundarySignature(prevExports),\n helpers.getRefreshBoundarySignature(currentExports)\n )\n ) {\n module.hot.invalidate()\n } else {\n helpers.scheduleUpdate()\n }\n }\n } else {\n // Since we just executed the code for the module, it's possible that the\n // new exports made it ineligible for being a boundary.\n // We only care about the case when we were _previously_ a boundary,\n // because we already accepted this update (accidental side effect).\n const isNoLongerABoundary = prevExports !== null\n if (isNoLongerABoundary) {\n module.hot.invalidate()\n }\n }\n}\n\n/**\n * Adds, deletes, and moves modules between chunks. This must happen before the\n * dispose phase as it needs to know which modules were removed from all chunks,\n * which we can only compute *after* taking care of added and moved modules.\n */\nfunction updateChunksPhase(\n chunksAddedModules: Map>,\n chunksDeletedModules: Map>\n): { disposedModules: Set } {\n for (const [chunkPath, addedModuleIds] of chunksAddedModules) {\n for (const moduleId of addedModuleIds) {\n addModuleToChunk(moduleId, chunkPath)\n }\n }\n\n const disposedModules: Set = new Set()\n for (const [chunkPath, addedModuleIds] of chunksDeletedModules) {\n for (const moduleId of addedModuleIds) {\n if (removeModuleFromChunk(moduleId, chunkPath)) {\n disposedModules.add(moduleId)\n }\n }\n }\n\n return { disposedModules }\n}\n\nfunction applyUpdate(update: PartialUpdate) {\n switch (update.type) {\n case 'ChunkListUpdate':\n applyChunkListUpdate(update)\n break\n default:\n invariant(update, (update) => `Unknown update type: ${update.type}`)\n }\n}\n\nfunction applyChunkListUpdate(update: ChunkListUpdate) {\n if (update.merged != null) {\n for (const merged of update.merged) {\n switch (merged.type) {\n case 'EcmascriptMergedUpdate':\n applyEcmascriptMergedUpdate(merged)\n break\n default:\n invariant(merged, (merged) => `Unknown merged type: ${merged.type}`)\n }\n }\n }\n\n if (update.chunks != null) {\n for (const [chunkPath, chunkUpdate] of Object.entries(\n update.chunks\n ) as Array<[ChunkPath, ChunkUpdate]>) {\n const chunkUrl = getChunkRelativeUrl(chunkPath)\n\n switch (chunkUpdate.type) {\n case 'added':\n BACKEND.loadChunkCached(SourceType.Update, chunkUrl)\n break\n case 'total':\n DEV_BACKEND.reloadChunk?.(chunkUrl)\n break\n case 'deleted':\n DEV_BACKEND.unloadChunk?.(chunkUrl)\n break\n case 'partial':\n invariant(\n chunkUpdate.instruction,\n (instruction) =>\n `Unknown partial instruction: ${JSON.stringify(instruction)}.`\n )\n break\n default:\n invariant(\n chunkUpdate,\n (chunkUpdate) => `Unknown chunk update type: ${chunkUpdate.type}`\n )\n }\n }\n }\n}\n\nfunction applyEcmascriptMergedUpdate(update: EcmascriptMergedUpdate) {\n // Browser-specific chunk management phase\n const { entries = {}, chunks = {} } = update\n const { added, modified, chunksAdded, chunksDeleted } = computeChangedModules(\n entries,\n chunks,\n chunkModulesMap\n )\n const { disposedModules } = updateChunksPhase(chunksAdded, chunksDeleted)\n\n // Use shared HMR update implementation\n applyEcmascriptMergedUpdateShared({\n added,\n modified,\n disposedModules,\n evalModuleEntry: _eval, // browser's eval with source maps\n instantiateModule, // now wraps shared logic\n applyModuleFactoryName,\n moduleFactories,\n devModuleCache,\n autoAcceptRootModules: false,\n })\n}\n\nfunction handleApply(chunkListPath: ChunkListPath, update: ServerMessage) {\n switch (update.type) {\n case 'partial': {\n // This indicates that the update is can be applied to the current state of the application.\n applyUpdate(update.instruction)\n break\n }\n case 'restart': {\n // This indicates that there is no way to apply the update to the\n // current state of the application, and that the application must be\n // restarted.\n DEV_BACKEND.restart()\n break\n }\n case 'notFound': {\n // This indicates that the chunk list no longer exists: either the dynamic import which created it was removed,\n // or the page itself was deleted.\n // If it is a dynamic import, we simply discard all modules that the chunk has exclusive access to.\n // If it is a runtime chunk list, we restart the application.\n if (runtimeChunkLists.has(chunkListPath)) {\n DEV_BACKEND.restart()\n } else {\n disposeChunkList(chunkListPath)\n }\n break\n }\n default:\n throw new Error(`Unknown update type: ${update.type}`)\n }\n}\n\n/**\n * Removes a module from a chunk.\n * Returns `true` if there are no remaining chunks including this module.\n */\nfunction removeModuleFromChunk(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): boolean {\n const moduleChunks = moduleChunksMap.get(moduleId)!\n moduleChunks.delete(chunkPath)\n\n const chunkModules = chunkModulesMap.get(chunkPath)!\n chunkModules.delete(moduleId)\n\n const noRemainingModules = chunkModules.size === 0\n if (noRemainingModules) {\n chunkModulesMap.delete(chunkPath)\n }\n\n const noRemainingChunks = moduleChunks.size === 0\n if (noRemainingChunks) {\n moduleChunksMap.delete(moduleId)\n }\n\n return noRemainingChunks\n}\n\n/**\n * Disposes of a chunk list and its corresponding exclusive chunks.\n */\nfunction disposeChunkList(chunkListPath: ChunkListPath): boolean {\n const chunkPaths = chunkListChunksMap.get(chunkListPath)\n if (chunkPaths == null) {\n return false\n }\n chunkListChunksMap.delete(chunkListPath)\n\n for (const chunkPath of chunkPaths) {\n const chunkChunkLists = chunkChunkListsMap.get(chunkPath)!\n chunkChunkLists.delete(chunkListPath)\n\n if (chunkChunkLists.size === 0) {\n chunkChunkListsMap.delete(chunkPath)\n disposeChunk(chunkPath)\n }\n }\n\n // We must also dispose of the chunk list's chunk itself to ensure it may\n // be reloaded properly in the future.\n const chunkListUrl = getChunkRelativeUrl(chunkListPath)\n\n DEV_BACKEND.unloadChunk?.(chunkListUrl)\n\n return true\n}\n\n/**\n * Disposes of a chunk and its corresponding exclusive modules.\n *\n * @returns Whether the chunk was disposed of.\n */\nfunction disposeChunk(chunkPath: ChunkPath): boolean {\n const chunkUrl = getChunkRelativeUrl(chunkPath)\n // This should happen whether the chunk has any modules in it or not.\n // For instance, CSS chunks have no modules in them, but they still need to be unloaded.\n DEV_BACKEND.unloadChunk?.(chunkUrl)\n\n const chunkModules = chunkModulesMap.get(chunkPath)\n if (chunkModules == null) {\n return false\n }\n chunkModules.delete(chunkPath)\n\n for (const moduleId of chunkModules) {\n const moduleChunks = moduleChunksMap.get(moduleId)!\n moduleChunks.delete(chunkPath)\n\n const noRemainingChunks = moduleChunks.size === 0\n if (noRemainingChunks) {\n moduleChunksMap.delete(moduleId)\n disposeModule(moduleId, 'clear')\n availableModules.delete(moduleId)\n }\n }\n\n return true\n}\n\n/**\n * Adds a module to a chunk.\n */\nfunction addModuleToChunk(moduleId: ModuleId, chunkPath: ChunkPath) {\n let moduleChunks = moduleChunksMap.get(moduleId)\n if (!moduleChunks) {\n moduleChunks = new Set([chunkPath])\n moduleChunksMap.set(moduleId, moduleChunks)\n } else {\n moduleChunks.add(chunkPath)\n }\n\n let chunkModules = chunkModulesMap.get(chunkPath)\n if (!chunkModules) {\n chunkModules = new Set([moduleId])\n chunkModulesMap.set(chunkPath, chunkModules)\n } else {\n chunkModules.add(moduleId)\n }\n}\n\n/**\n * Marks a chunk list as a runtime chunk list. There can be more than one\n * runtime chunk list. For instance, integration tests can have multiple chunk\n * groups loaded at runtime, each with its own chunk list.\n */\nfunction markChunkListAsRuntime(chunkListPath: ChunkListPath) {\n runtimeChunkLists.add(chunkListPath)\n}\n\nfunction registerChunk(registration: ChunkRegistration) {\n const chunk = getChunkFromRegistration(registration[0]) as\n | ChunkPath\n | ChunkScript\n let runtimeParams: RuntimeParams | undefined\n // When bootstrapping we are passed a single runtimeParams object so we can distinguish purely based on length\n if (registration.length === 2) {\n runtimeParams = registration[1] as RuntimeParams\n } else {\n let chunkPath = getPathFromScript(chunk)\n runtimeParams = undefined\n installCompressedModuleFactories(\n registration as CompressedModuleFactories,\n /* offset= */ 1,\n moduleFactories,\n (id: ModuleId) => addModuleToChunk(id, chunkPath)\n )\n }\n return BACKEND.registerChunk(chunk, runtimeParams)\n}\n\n/**\n * Subscribes to chunk list updates from the update server and applies them.\n */\nfunction registerChunkList(chunkList: ChunkList) {\n const chunkListScript = getChunkFromRegistration(chunkList.script) as\n | ChunkListPath\n | ChunkListScript\n const chunkListPath = getPathFromScript(chunkListScript)\n // The \"chunk\" is also registered to finish the loading in the backend\n BACKEND.registerChunk(chunkListPath as string as ChunkPath)\n globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS!.push([\n chunkListPath,\n handleApply.bind(null, chunkListPath),\n ])\n\n // Adding chunks to chunk lists and vice versa.\n const chunkPaths = new Set(chunkList.chunks.map(getChunkPath))\n chunkListChunksMap.set(chunkListPath, chunkPaths)\n for (const chunkPath of chunkPaths) {\n let chunkChunkLists = chunkChunkListsMap.get(chunkPath)\n if (!chunkChunkLists) {\n chunkChunkLists = new Set([chunkListPath])\n chunkChunkListsMap.set(chunkPath, chunkChunkLists)\n } else {\n chunkChunkLists.add(chunkListPath)\n }\n }\n\n if (chunkList.source === 'entry') {\n markChunkListAsRuntime(chunkListPath)\n }\n}\n\nglobalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= []\n"],"names":["devContextPrototype","Context","prototype","devModuleCache","Object","create","c","runtimeModules","Set","createModuleWithDirectionFlag","moduleChunksMap","Map","chunkModulesMap","runtimeChunkLists","chunkListChunksMap","chunkChunkListsMap","getOrInstantiateRuntimeModule","chunkPath","moduleId","module","error","instantiateModule","SourceType","Runtime","getOrInstantiateModuleFromParent","id","sourceModule","hot","active","console","warn","children","indexOf","push","parents","Parent","DevContext","exports","refresh","call","k","sourceType","sourceData","createModuleObjectFn","createModuleObject","createContext","instantiateModuleShared","moduleFactories","runModuleExecutionHooks","DUMMY_REFRESH_CONTEXT","register","_type","_id","signature","registerExports","_module","_helpers","executeModule","globalThis","$RefreshInterceptModuleExecution$","cleanupReactRefreshIntercept","$RefreshReg$","$RefreshSig$","registerExportsAndSetupBoundaryForReactRefresh","helpers","currentExports","prevExports","data","registerExportsForReactRefresh","isReactRefreshBoundary","dispose","accept","shouldInvalidateReactRefreshBoundary","getRefreshBoundarySignature","invalidate","scheduleUpdate","isNoLongerABoundary","updateChunksPhase","chunksAddedModules","chunksDeletedModules","addedModuleIds","addModuleToChunk","disposedModules","removeModuleFromChunk","add","applyUpdate","update","type","applyChunkListUpdate","invariant","merged","applyEcmascriptMergedUpdate","chunks","chunkUpdate","entries","chunkUrl","getChunkRelativeUrl","BACKEND","loadChunkCached","Update","DEV_BACKEND","reloadChunk","unloadChunk","instruction","JSON","stringify","added","modified","chunksAdded","chunksDeleted","computeChangedModules","applyEcmascriptMergedUpdateShared","evalModuleEntry","_eval","applyModuleFactoryName","autoAcceptRootModules","handleApply","chunkListPath","restart","has","disposeChunkList","Error","moduleChunks","get","delete","chunkModules","noRemainingModules","size","noRemainingChunks","chunkPaths","chunkChunkLists","disposeChunk","chunkListUrl","disposeModule","availableModules","set","markChunkListAsRuntime","registerChunk","registration","chunk","getChunkFromRegistration","runtimeParams","length","getPathFromScript","undefined","installCompressedModuleFactories","registerChunkList","chunkList","chunkListScript","script","TURBOPACK_CHUNK_UPDATE_LISTENERS","bind","map","getChunkPath","source"],"mappings":"AAAA,iEAAiE;AACjE,kEAAkE;AAMlE,MAAMA,sBAAsBC,QAAQC,SAAS;AAE7C;;;;;;CAMC,GACD,oDAAoD,GAEpD,wEAAwE;AACxEC,iBAAiBC,OAAOC,MAAM,CAAC;AAC/BL,oBAAoBM,CAAC,GAAGH;AACxBI,iBAAiB,IAAIC;AAErB,kDAAkD;AAClDC,gCAAgC;AAgChC;;;;;;CAMC,GACD,MAAMC,kBAAiD,IAAIC;AAC3D;;CAEC,GACD,MAAMC,kBAAiD,IAAID;AAC3D;;;;CAIC,GACD,MAAME,oBAAwC,IAAIL;AAClD;;CAEC,GACD,MAAMM,qBAAyD,IAAIH;AACnE;;CAEC,GACD,MAAMI,qBAAyD,IAAIJ;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;AACxB;AAEA,SAASoB,cAAcC,YAA+B;IACpD,MAAMC,QAAQC,yBAAyBF,YAAY,CAAC,EAAE;IAGtD,IAAIG;IACJ,8GAA8G;IAC9G,IAAIH,aAAaI,MAAM,KAAK,GAAG;QAC7BD,gBAAgBH,YAAY,CAAC,EAAE;IACjC,OAAO;QACL,IAAIzH,YAAY8H,kBAAkBJ;QAClCE,gBAAgBG;QAChBC,iCACEP,cACA,WAAW,GAAG,GACd3F,iBACA,CAACtB,KAAiBwD,iBAAiBxD,IAAIR;IAE3C;IACA,OAAOgF,QAAQwC,aAAa,CAACE,OAAOE;AACtC;AAEA;;CAEC,GACD,SAASK,kBAAkBC,SAAoB;IAC7C,MAAMC,kBAAkBR,yBAAyBO,UAAUE,MAAM;IAGjE,MAAMhC,gBAAgB0B,kBAAkBK;IACxC,sEAAsE;IACtEnD,QAAQwC,aAAa,CAACpB;IACtB3D,WAAW4F,gCAAgC,CAAErH,IAAI,CAAC;QAChDoF;QACAD,YAAYmC,IAAI,CAAC,MAAMlC;KACxB;IAED,+CAA+C;IAC/C,MAAMY,aAAa,IAAIzH,IAAI2I,UAAUvD,MAAM,CAAC4D,GAAG,CAACC;IAChD3I,mBAAmByH,GAAG,CAAClB,eAAeY;IACtC,KAAK,MAAMhH,aAAagH,WAAY;QAClC,IAAIC,kBAAkBnH,mBAAmB4G,GAAG,CAAC1G;QAC7C,IAAI,CAACiH,iBAAiB;YACpBA,kBAAkB,IAAI1H,IAAI;gBAAC6G;aAAc;YACzCtG,mBAAmBwH,GAAG,CAACtH,WAAWiH;QACpC,OAAO;YACLA,gBAAgB9C,GAAG,CAACiC;QACtB;IACF;IAEA,IAAI8B,UAAUO,MAAM,KAAK,SAAS;QAChClB,uBAAuBnB;IACzB;AACF;AAEA3D,WAAW4F,gCAAgC,KAAK,EAAE","ignoreList":[0]}}, - {"offset": {"line": 1950, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/runtime-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack ECMAScript DOM runtime.\n *\n * It will be appended to the base runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\nfunction getAssetSuffixFromScriptSrc() {\n // TURBOPACK_ASSET_SUFFIX is set in web workers\n return (\n (self.TURBOPACK_ASSET_SUFFIX ??\n document?.currentScript\n ?.getAttribute?.('src')\n ?.replace(/^(.*(?=\\?)|^.*$)/, '')) ||\n ''\n )\n}\n\ntype ChunkResolver = {\n resolved: boolean\n loadingStarted: boolean\n resolve: () => void\n reject: (error?: Error) => void\n promise: Promise\n}\n\nlet BACKEND: RuntimeBackend\n\n/**\n * Maps chunk paths to the corresponding resolver.\n */\nconst chunkResolvers: Map = new Map()\n\n;(() => {\n BACKEND = {\n async registerChunk(chunk, params) {\n let chunkPath = getPathFromScript(chunk)\n let chunkUrl = getUrlFromScript(chunk)\n\n const resolver = getOrCreateResolver(chunkUrl)\n resolver.resolve()\n\n if (params == null) {\n return\n }\n\n for (const otherChunkData of params.otherChunks) {\n const otherChunkPath = getChunkPath(otherChunkData)\n const otherChunkUrl = getChunkRelativeUrl(otherChunkPath)\n\n // Chunk might have started loading, so we want to avoid triggering another load.\n getOrCreateResolver(otherChunkUrl)\n }\n\n // This waits for chunks to be loaded, but also marks included items as available.\n await Promise.all(\n params.otherChunks.map((otherChunkData) =>\n loadInitialChunk(chunkPath, otherChunkData)\n )\n )\n\n if (params.runtimeModuleIds.length > 0) {\n for (const moduleId of params.runtimeModuleIds) {\n getOrInstantiateRuntimeModule(chunkPath, moduleId)\n }\n }\n },\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n loadChunkCached(sourceType: SourceType, chunkUrl: ChunkUrl) {\n return doLoadChunk(sourceType, chunkUrl)\n },\n\n async loadWebAssembly(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n const { instance } = await WebAssembly.instantiateStreaming(\n req,\n importsObj\n )\n\n return instance.exports\n },\n\n async loadWebAssemblyModule(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n return await WebAssembly.compileStreaming(req)\n },\n }\n\n function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {\n let resolver = chunkResolvers.get(chunkUrl)\n if (!resolver) {\n let resolve: () => void\n let reject: (error?: Error) => void\n const promise = new Promise((innerResolve, innerReject) => {\n resolve = innerResolve\n reject = innerReject\n })\n resolver = {\n resolved: false,\n loadingStarted: false,\n promise,\n resolve: () => {\n resolver!.resolved = true\n resolve()\n },\n reject: reject!,\n }\n chunkResolvers.set(chunkUrl, resolver)\n }\n return resolver\n }\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n function doLoadChunk(sourceType: SourceType, chunkUrl: ChunkUrl) {\n const resolver = getOrCreateResolver(chunkUrl)\n if (resolver.loadingStarted) {\n return resolver.promise\n }\n\n if (sourceType === SourceType.Runtime) {\n // We don't need to load chunks references from runtime code, as they're already\n // present in the DOM.\n resolver.loadingStarted = true\n\n if (isCss(chunkUrl)) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n\n // We need to wait for JS chunks to register themselves within `registerChunk`\n // before we can start instantiating runtime modules, hence the absence of\n // `resolver.resolve()` in this branch.\n\n return resolver.promise\n }\n\n if (typeof importScripts === 'function') {\n // We're in a web worker\n if (isCss(chunkUrl)) {\n // ignore\n } else if (isJs(chunkUrl)) {\n self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl)\n importScripts(chunkUrl)\n } else {\n throw new Error(\n `can't infer type of chunk from URL ${chunkUrl} in worker`\n )\n }\n } else {\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n if (previousLinks.length > 0) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n } else {\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n link.href = chunkUrl\n link.onerror = () => {\n resolver.reject()\n }\n link.onload = () => {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(link)\n }\n } else if (isJs(chunkUrl)) {\n const previousScripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n if (previousScripts.length > 0) {\n // There is this edge where the script already failed loading, but we\n // can't detect that. The Promise will never resolve in this case.\n for (const script of Array.from(previousScripts)) {\n script.addEventListener('error', () => {\n resolver.reject()\n })\n }\n } else {\n const script = document.createElement('script')\n script.src = chunkUrl\n // We'll only mark the chunk as loaded once the script has been executed,\n // which happens in `registerChunk`. Hence the absence of `resolve()` in\n // this branch.\n script.onerror = () => {\n resolver.reject()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(script)\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n }\n\n resolver.loadingStarted = true\n return resolver.promise\n }\n\n function fetchWebAssembly(wasmChunkPath: ChunkPath) {\n return fetch(getChunkRelativeUrl(wasmChunkPath))\n }\n})()\n"],"names":["getAssetSuffixFromScriptSrc","self","TURBOPACK_ASSET_SUFFIX","document","currentScript","getAttribute","replace","BACKEND","chunkResolvers","Map","registerChunk","chunk","params","chunkPath","getPathFromScript","chunkUrl","getUrlFromScript","resolver","getOrCreateResolver","resolve","otherChunkData","otherChunks","otherChunkPath","getChunkPath","otherChunkUrl","getChunkRelativeUrl","Promise","all","map","loadInitialChunk","runtimeModuleIds","length","moduleId","getOrInstantiateRuntimeModule","loadChunkCached","sourceType","doLoadChunk","loadWebAssembly","_sourceType","_sourceData","wasmChunkPath","_edgeModule","importsObj","req","fetchWebAssembly","instance","WebAssembly","instantiateStreaming","exports","loadWebAssemblyModule","compileStreaming","get","reject","promise","innerResolve","innerReject","resolved","loadingStarted","set","SourceType","Runtime","isCss","importScripts","isJs","TURBOPACK_NEXT_CHUNK_URLS","push","Error","decodedChunkUrl","decodeURI","previousLinks","querySelectorAll","link","createElement","rel","href","onerror","onload","head","appendChild","previousScripts","script","Array","from","addEventListener","src","fetch"],"mappings":"AAAA;;;;CAIC,GAED,oDAAoD,GAEpD,sEAAsE;AACtE,mEAAmE;AAEnE,SAASA;IACP,+CAA+C;IAC/C,OACE,CAACC,KAAKC,sBAAsB,IAC1BC,UAAUC,eACNC,eAAe,QACfC,QAAQ,oBAAoB,GAAG,KACrC;AAEJ;AAUA,IAAIC;AAEJ;;CAEC,GACD,MAAMC,iBAA+C,IAAIC;AAExD,CAAC;IACAF,UAAU;QACR,MAAMG,eAAcC,KAAK,EAAEC,MAAM;YAC/B,IAAIC,YAAYC,kBAAkBH;YAClC,IAAII,WAAWC,iBAAiBL;YAEhC,MAAMM,WAAWC,oBAAoBH;YACrCE,SAASE,OAAO;YAEhB,IAAIP,UAAU,MAAM;gBAClB;YACF;YAEA,KAAK,MAAMQ,kBAAkBR,OAAOS,WAAW,CAAE;gBAC/C,MAAMC,iBAAiBC,aAAaH;gBACpC,MAAMI,gBAAgBC,oBAAoBH;gBAE1C,iFAAiF;gBACjFJ,oBAAoBM;YACtB;YAEA,kFAAkF;YAClF,MAAME,QAAQC,GAAG,CACff,OAAOS,WAAW,CAACO,GAAG,CAAC,CAACR,iBACt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AAgB,CAC/C,CAAC,YAAY,EAAEvD,SAAS,gBAAgB,EAAEA,SAAS,gBAAgB,EAAEoD,gBAAgB,gBAAgB,EAAEA,gBAAgB,GAAG,CAAC;gBAE7H,IAAIY,gBAAgBhD,MAAM,GAAG,GAAG;oBAC9B,qEAAqE;oBACrE,kEAAkE;oBAClE,KAAK,MAAMiD,UAAUC,MAAMC,IAAI,CAACH,iBAAkB;wBAChDC,OAAOG,gBAAgB,CAAC,SAAS;4BAC/BlE,SAASmC,MAAM;wBACjB;oBACF;gBACF,OAAO;oBACL,MAAM4B,SAAS7E,SAASqE,aAAa,CAAC;oBACtCQ,OAAOI,GAAG,GAAGrE;oBACb,yEAAyE;oBACzE,wEAAwE;oBACxE,eAAe;oBACfiE,OAAOL,OAAO,GAAG;wBACf1D,SAASmC,MAAM;oBACjB;oBACA,kDAAkD;oBAClDjD,SAAS0E,IAAI,CAACC,WAAW,CAACE;gBAC5B;YACF,OAAO;gBACL,MAAM,IAAId,MAAM,CAAC,mCAAmC,EAAEnD,UAAU;YAClE;QACF;QAEAE,SAASwC,cAAc,GAAG;QAC1B,OAAOxC,SAASoC,OAAO;IACzB;IAEA,SAAST,iBAAiBJ,aAAwB;QAChD,OAAO6C,MAAM5D,oBAAoBe;IACnC;AACF,CAAC","ignoreList":[0]}}, - {"offset": {"line": 2116, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/dev-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack development\n * ECMAScript DOM runtime.\n *\n * It will be appended to the base development runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n/// \n/// \n\nlet DEV_BACKEND: DevRuntimeBackend\n;(() => {\n DEV_BACKEND = {\n unloadChunk(chunkUrl) {\n deleteResolver(chunkUrl)\n\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const links = document.querySelectorAll(\n `link[href=\"${chunkUrl}\"],link[href^=\"${chunkUrl}?\"],link[href=\"${decodedChunkUrl}\"],link[href^=\"${decodedChunkUrl}?\"]`\n )\n for (const link of Array.from(links)) {\n link.remove()\n }\n } else if (isJs(chunkUrl)) {\n // Unloading a JS chunk would have no effect, as it lives in the JS\n // runtime once evaluated.\n // However, we still want to remove the script tag from the DOM to keep\n // the HTML somewhat consistent from the user's perspective.\n const scripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n for (const script of Array.from(scripts)) {\n script.remove()\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n },\n\n reloadChunk(chunkUrl) {\n return new Promise((resolve, reject) => {\n if (!isCss(chunkUrl)) {\n reject(new Error('The DOM backend can only reload CSS chunks'))\n return\n }\n\n const decodedChunkUrl = decodeURI(chunkUrl)\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n\n if (previousLinks.length === 0) {\n reject(new Error(`No link element found for chunk ${chunkUrl}`))\n return\n }\n\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n\n if (navigator.userAgent.includes('Firefox')) {\n // Firefox won't reload CSS files that were previously loaded on the current page,\n // we need to add a query param to make sure CSS is actually reloaded from the server.\n //\n // I believe this is this issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506\n //\n // Safari has a similar issue, but only if you have a `` tag\n // pointing to the same URL as the stylesheet: https://bugs.webkit.org/show_bug.cgi?id=187726\n link.href = `${chunkUrl}?ts=${Date.now()}`\n } else {\n link.href = chunkUrl\n }\n\n link.onerror = () => {\n reject()\n }\n link.onload = () => {\n // First load the new CSS, then remove the old ones. This prevents visible\n // flickering that would happen in-between removing the previous CSS and\n // loading the new one.\n for (const previousLink of Array.from(previousLinks))\n previousLink.remove()\n\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolve()\n }\n\n // Make sure to insert the new CSS right after the previous one, so that\n // its precedence is higher.\n previousLinks[0].parentElement!.insertBefore(\n link,\n previousLinks[0].nextSibling\n )\n })\n },\n\n restart: () => self.location.reload(),\n }\n\n function deleteResolver(chunkUrl: ChunkUrl) {\n chunkResolvers.delete(chunkUrl)\n }\n})()\n\nfunction _eval({ code, url, map }: EcmascriptModuleEntry): ModuleFactory {\n code += `\\n\\n//# sourceURL=${encodeURI(\n location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX\n )}`\n if (map) {\n code += `\\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(\n // btoa doesn't handle nonlatin characters, so escape them as \\x sequences\n // See https://stackoverflow.com/a/26603875\n unescape(encodeURIComponent(map))\n )}`\n }\n\n // eslint-disable-next-line no-eval\n return eval(code)\n}\n"],"names":["DEV_BACKEND","unloadChunk","chunkUrl","deleteResolver","decodedChunkUrl","decodeURI","isCss","links","document","querySelectorAll","link","Array","from","remove","isJs","scripts","script","Error","reloadChunk","Promise","resolve","reject","previousLinks","length","createElement","rel","navigator","userAgent","includes","href","Date","now","onerror","onload","previousLink","parentElement","insertBefore","nextSibling","restart","self","location","reload","chunkResolvers","delete","_eval","code","url","map","encodeURI","origin","CHUNK_BASE_PATH","ASSET_SUFFIX","btoa","unescape","encodeURIComponent","eval"],"mappings":"AAAA;;;;;CAKC,GAED,oDAAoD,GAEpD,gDAAgD;AAChD,4CAA4C;AAC5C,iDAAiD;AACjD,0DAA0D;AAE1D,IAAIA;AACH,CAAC;IACAA,cAAc;QACZC,aAAYC,QAAQ;YAClBC,eAAeD;YAEf,gFAAgF;YAChF,MAAME,kBAAkBC,UAAUH;YAElC,IAAII,MAAMJ,WAAW;gBACnB,MAAMK,QAAQC,SAASC,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AAE;oBACF,oFAAoF;oBACpF,6FAA6F;oBAC7FlB,KAAKmB,IAAI,GAAG,GAAG3B,SAAS,IAAI,EAAE4B,KAAKC,GAAG,IAAI;gBAC5C,OAAO;oBACLrB,KAAKmB,IAAI,GAAG3B;gBACd;gBAEAQ,KAAKsB,OAAO,GAAG;oBACbX;gBACF;gBACAX,KAAKuB,MAAM,GAAG;oBACZ,0EAA0E;oBAC1E,wEAAwE;oBACxE,uBAAuB;oBACvB,KAAK,MAAMC,gBAAgBvB,MAAMC,IAAI,CAACU,eACpCY,aAAarB,MAAM;oBAErB,uEAAuE;oBACvE,oBAAoB;oBACpBO;gBACF;gBAEA,wEAAwE;gBACxE,4BAA4B;gBAC5BE,aAAa,CAAC,EAAE,CAACa,aAAa,CAAEC,YAAY,CAC1C1B,MACAY,aAAa,CAAC,EAAE,CAACe,WAAW;YAEhC;QACF;QAEAC,SAAS,IAAMC,KAAKC,QAAQ,CAACC,MAAM;IACrC;IAEA,SAAStC,eAAeD,QAAkB;QACxCwC,eAAeC,MAAM,CAACzC;IACxB;AACF,CAAC;AAED,SAAS0C,MAAM,EAAEC,IAAI,EAAEC,GAAG,EAAEC,GAAG,EAAyB;IACtDF,QAAQ,CAAC,kBAAkB,EAAEG,UAC3BR,SAASS,MAAM,GAAGC,kBAAkBJ,MAAMK,eACzC;IACH,IAAIJ,KAAK;QACPF,QAAQ,CAAC,kEAAkE,EAAEO,KAC3E,0EAA0E;QAC1E,2CAA2C;QAC3CC,SAASC,mBAAmBP,QAC3B;IACL;IAEA,mCAAmC;IACnC,OAAOQ,KAAKV;AACd","ignoreList":[0]}}] + {"offset": {"line": 1950, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/runtime-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack ECMAScript DOM runtime.\n *\n * It will be appended to the base runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\nfunction getAssetSuffixFromScriptSrc() {\n // TURBOPACK_ASSET_SUFFIX is set in web workers\n if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX\n const src = document?.currentScript?.getAttribute?.('src') ?? ''\n const qi = src.indexOf('?')\n return qi >= 0 ? src.slice(qi) : ''\n}\n\ntype ChunkResolver = {\n resolved: boolean\n loadingStarted: boolean\n resolve: () => void\n reject: (error?: Error) => void\n promise: Promise\n}\n\nlet BACKEND: RuntimeBackend\n\n/**\n * Maps chunk paths to the corresponding resolver.\n */\nconst chunkResolvers: Map = new Map()\n\n;(() => {\n BACKEND = {\n async registerChunk(chunk, params) {\n let chunkPath = getPathFromScript(chunk)\n let chunkUrl = getUrlFromScript(chunk)\n\n const resolver = getOrCreateResolver(chunkUrl)\n resolver.resolve()\n\n if (params == null) {\n return\n }\n\n for (const otherChunkData of params.otherChunks) {\n const otherChunkPath = getChunkPath(otherChunkData)\n const otherChunkUrl = getChunkRelativeUrl(otherChunkPath)\n\n // Chunk might have started loading, so we want to avoid triggering another load.\n getOrCreateResolver(otherChunkUrl)\n }\n\n // This waits for chunks to be loaded, but also marks included items as available.\n await Promise.all(\n params.otherChunks.map((otherChunkData) =>\n loadInitialChunk(chunkPath, otherChunkData)\n )\n )\n\n if (params.runtimeModuleIds.length > 0) {\n for (const moduleId of params.runtimeModuleIds) {\n getOrInstantiateRuntimeModule(chunkPath, moduleId)\n }\n }\n },\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n loadChunkCached(sourceType: SourceType, chunkUrl: ChunkUrl) {\n return doLoadChunk(sourceType, chunkUrl)\n },\n\n async loadWebAssembly(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n const { instance } = await WebAssembly.instantiateStreaming(\n req,\n importsObj\n )\n\n return instance.exports\n },\n\n async loadWebAssemblyModule(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n return await WebAssembly.compileStreaming(req)\n },\n }\n\n function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {\n let resolver = chunkResolvers.get(chunkUrl)\n if (!resolver) {\n let resolve: () => void\n let reject: (error?: Error) => void\n const promise = new Promise((innerResolve, innerReject) => {\n resolve = innerResolve\n reject = innerReject\n })\n resolver = {\n resolved: false,\n loadingStarted: false,\n promise,\n resolve: () => {\n resolver!.resolved = true\n resolve()\n },\n reject: reject!,\n }\n chunkResolvers.set(chunkUrl, resolver)\n }\n return resolver\n }\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n function doLoadChunk(sourceType: SourceType, chunkUrl: ChunkUrl) {\n const resolver = getOrCreateResolver(chunkUrl)\n if (resolver.loadingStarted) {\n return resolver.promise\n }\n\n if (sourceType === SourceType.Runtime) {\n // We don't need to load chunks references from runtime code, as they're already\n // present in the DOM.\n resolver.loadingStarted = true\n\n if (isCss(chunkUrl)) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n\n // We need to wait for JS chunks to register themselves within `registerChunk`\n // before we can start instantiating runtime modules, hence the absence of\n // `resolver.resolve()` in this branch.\n\n return resolver.promise\n }\n\n if (typeof importScripts === 'function') {\n // We're in a web worker\n if (isCss(chunkUrl)) {\n // ignore\n } else if (isJs(chunkUrl)) {\n self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl)\n importScripts(chunkUrl)\n } else {\n throw new Error(\n `can't infer type of chunk from URL ${chunkUrl} in worker`\n )\n }\n } else {\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n if (previousLinks.length > 0) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n } else {\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n link.href = chunkUrl\n link.onerror = () => {\n resolver.reject()\n }\n link.onload = () => {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(link)\n }\n } else if (isJs(chunkUrl)) {\n const previousScripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n if (previousScripts.length > 0) {\n // There is this edge where the script already failed loading, but we\n // can't detect that. The Promise will never resolve in this case.\n for (const script of Array.from(previousScripts)) {\n script.addEventListener('error', () => {\n resolver.reject()\n })\n }\n } else {\n const script = document.createElement('script')\n script.src = chunkUrl\n // We'll only mark the chunk as loaded once the script has been executed,\n // which happens in `registerChunk`. Hence the absence of `resolve()` in\n // this branch.\n script.onerror = () => {\n resolver.reject()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(script)\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n }\n\n resolver.loadingStarted = true\n return resolver.promise\n }\n\n function fetchWebAssembly(wasmChunkPath: ChunkPath) {\n return fetch(getChunkRelativeUrl(wasmChunkPath))\n }\n})()\n"],"names":["getAssetSuffixFromScriptSrc","self","TURBOPACK_ASSET_SUFFIX","src","document","currentScript","getAttribute","qi","indexOf","slice","BACKEND","chunkResolvers","Map","registerChunk","chunk","params","chunkPath","getPathFromScript","chunkUrl","getUrlFromScript","resolver","getOrCreateResolver","resolve","otherChunkData","otherChunks","otherChunkPath","getChunkPath","otherChunkUrl","getChunkRelativeUrl","Promise","all","map","loadInitialChunk","runtimeModuleIds","length","moduleId","getOrInstantiateRuntimeModule","loadChunkCached","sourceType","doLoadChunk","loadWebAssembly","_sourceType","_sourceData","wasmChunkPath","_edgeModule","importsObj","req","fetchWebAssembly","instance","WebAssembly","instantiateStreaming","exports","loadWebAssemblyModule","compileStreaming","get","reject","promise","innerResolve","innerReject","resolved","loadingStarted","set","SourceType","Runtime","isCss","importScripts","isJs","TURBOPACK_NEXT_CHUNK_URLS","push","Error","decodedChunkUrl","decodeURI","previousLinks","querySelectorAll","link","createElement","rel","href","onerror","onload","head","appendChild","previousScripts","script","Array","from","addEventListener","fetch"],"mappings":"AAAA;;;;CAIC,GAED,oDAAoD,GAEpD,sEAAsE;AACtE,mEAAmE;AAEnE,SAASA;IACP,+CAA+C;IAC/C,IAAIC,KAAKC,sBAAsB,IAAI,MAAM,OAAOD,KAAKC,sBAAsB;IAC3E,MAAMC,MAAMC,UAAUC,eAAeC,eAAe,UAAU;IAC9D,MAAMC,KAAKJ,IAAIK,OAAO,CAAC;IACvB,OAAOD,MAAM,IAAIJ,IAAIM,KAAK,CAACF,MAAM;AACnC;AAUA,IAAIG;AAEJ;;CAEC,GACD,MAAMC,iBAA+C,IAAIC;AAExD,CAAC;IACAF,UAAU;QACR,MAAMG,eAAcC,KAAK,EAAEC,MAAM;YAC/B,IAAIC,YAAYC,kBAAkBH;YAClC,IAAII,WAAWC,iBAAiBL;YAEhC,MAAMM,WAAWC,oBAAoBH;YACrCE,SAASE,OAAO;YAEhB,IAAIP,UAAU,MAAM;gBAClB;YACF;YAEA,KAAK,MAAMQ,kBAAkBR,OAAOS,WAAW,CAAE;gBAC/C,MAAMC,iBAAiBC,aAAaH;gBACpC,MAAMI,gBAAgBC,oBAAoBH;gBAE1C,iFAAiF;gBACjFJ,oBAAoBM;YACtB;YAEA,kFAAkF;YAClF,MAAME,QAAQC,GAAG,CACff,OAAOS,WAAW,CAACO,GAAG,CAAC,C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,SAASqE,gBAAgB,CAC/C,CAAC,YAAY,EAAEvD,SAAS,gBAAgB,EAAEA,SAAS,gBAAgB,EAAEoD,gBAAgB,gBAAgB,EAAEA,gBAAgB,GAAG,CAAC;gBAE7H,IAAIY,gBAAgBhD,MAAM,GAAG,GAAG;oBAC9B,qEAAqE;oBACrE,kEAAkE;oBAClE,KAAK,MAAMiD,UAAUC,MAAMC,IAAI,CAACH,iBAAkB;wBAChDC,OAAOG,gBAAgB,CAAC,SAAS;4BAC/BlE,SAASmC,MAAM;wBACjB;oBACF;gBACF,OAAO;oBACL,MAAM4B,SAAS/E,SAASuE,aAAa,CAAC;oBACtCQ,OAAOhF,GAAG,GAAGe;oBACb,yEAAyE;oBACzE,wEAAwE;oBACxE,eAAe;oBACfiE,OAAOL,OAAO,GAAG;wBACf1D,SAASmC,MAAM;oBACjB;oBACA,kDAAkD;oBAClDnD,SAAS4E,IAAI,CAACC,WAAW,CAACE;gBAC5B;YACF,OAAO;gBACL,MAAM,IAAId,MAAM,CAAC,mCAAmC,EAAEnD,UAAU;YAClE;QACF;QAEAE,SAASwC,cAAc,GAAG;QAC1B,OAAOxC,SAASoC,OAAO;IACzB;IAEA,SAAST,iBAAiBJ,aAAwB;QAChD,OAAO4C,MAAM3D,oBAAoBe;IACnC;AACF,CAAC","ignoreList":[0]}}, + {"offset": {"line": 2119, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/dev-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack development\n * ECMAScript DOM runtime.\n *\n * It will be appended to the base development runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n/// \n/// \n\nlet DEV_BACKEND: DevRuntimeBackend\n;(() => {\n DEV_BACKEND = {\n unloadChunk(chunkUrl) {\n deleteResolver(chunkUrl)\n\n // Strip query string so we match links regardless of cache-busting\n // params (e.g. ?ts=) that may differ between HMR updates.\n const baseChunkUrl = chunkUrl.split('?')[0]\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedBaseChunkUrl = decodeURI(baseChunkUrl)\n\n if (isCss(chunkUrl)) {\n const links = document.querySelectorAll(\n `link[href=\"${baseChunkUrl}\"],link[href^=\"${baseChunkUrl}?\"],link[href=\"${decodedBaseChunkUrl}\"],link[href^=\"${decodedBaseChunkUrl}?\"]`\n )\n for (const link of Array.from(links)) {\n link.remove()\n }\n } else if (isJs(chunkUrl)) {\n // Unloading a JS chunk would have no effect, as it lives in the JS\n // runtime once evaluated.\n // However, we still want to remove the script tag from the DOM to keep\n // the HTML somewhat consistent from the user's perspective.\n const scripts = document.querySelectorAll(\n `script[src=\"${baseChunkUrl}\"],script[src^=\"${baseChunkUrl}?\"],script[src=\"${decodedBaseChunkUrl}\"],script[src^=\"${decodedBaseChunkUrl}?\"]`\n )\n for (const script of Array.from(scripts)) {\n script.remove()\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n },\n\n reloadChunk(chunkUrl) {\n return new Promise((resolve, reject) => {\n if (!isCss(chunkUrl)) {\n reject(new Error('The DOM backend can only reload CSS chunks'))\n return\n }\n\n // Strip query string so we match links regardless of cache-busting\n // params (e.g. ?ts=) that may differ between HMR updates.\n const baseChunkUrl = chunkUrl.split('?')[0]\n const decodedBaseChunkUrl = decodeURI(baseChunkUrl)\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${baseChunkUrl}\"],link[rel=stylesheet][href^=\"${baseChunkUrl}?\"],link[rel=stylesheet][href=\"${decodedBaseChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedBaseChunkUrl}?\"]`\n )\n\n if (previousLinks.length === 0) {\n reject(new Error(`No link element found for chunk ${chunkUrl}`))\n return\n }\n\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n\n if (\n navigator.userAgent.includes('Firefox') ||\n (navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome') &&\n !navigator.userAgent.includes('Chromium'))\n ) {\n // Firefox won't reload CSS files that were previously loaded on the\n // current page: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506\n //\n // Safari serves cached CSS when a exists for the\n // same URL: https://bugs.webkit.org/show_bug.cgi?id=187726\n //\n // Replace or add a fresh `ts` cache-busting param without\n // discarding other query parameters that may already be present.\n const url = new URL(chunkUrl, location.origin)\n url.searchParams.set('ts', String(Date.now()))\n // Reduced timer precision in some browers could lead to an update getting dropped\n // in firefox if it happens fast enough (in firefox precision is sometimes 100ms!).\n // So trust that the server is only updating us when it is important and use a\n // random number to bust the cache.\n url.searchParams.set('_next_rand', String(Math.random()))\n link.href = url.pathname + url.search\n } else {\n link.href = chunkUrl\n }\n\n link.onerror = () => {\n reject()\n }\n link.onload = () => {\n // First load the new CSS, then remove the old ones. This prevents visible\n // flickering that would happen in-between removing the previous CSS and\n // loading the new one.\n for (const previousLink of Array.from(previousLinks))\n previousLink.remove()\n\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolve()\n }\n\n // Make sure to insert the new CSS right after the previous one, so that\n // its precedence is higher.\n previousLinks[0].parentElement!.insertBefore(\n link,\n previousLinks[0].nextSibling\n )\n })\n },\n\n restart: () => self.location.reload(),\n }\n\n function deleteResolver(chunkUrl: ChunkUrl) {\n chunkResolvers.delete(chunkUrl)\n }\n})()\n\nfunction _eval({ code, url, map }: EcmascriptModuleEntry): ModuleFactory {\n code += `\\n\\n//# sourceURL=${encodeURI(\n location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX\n )}`\n if (map) {\n code += `\\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(\n // btoa doesn't handle nonlatin characters, so escape them as \\x sequences\n // See https://stackoverflow.com/a/26603875\n unescape(encodeURIComponent(map))\n )}`\n }\n\n // eslint-disable-next-line no-eval\n return eval(code)\n}\n"],"names":["DEV_BACKEND","unloadChunk","chunkUrl","deleteResolver","baseChunkUrl","split","decodedBaseChunkUrl","decodeURI","isCss","links","document","querySelectorAll","link","Array","from","remove","isJs","scripts","script","Error","reloadChunk","Promise","resolve","reject","previousLinks","length","createElement","rel","navigator","userAgent","includes","url","URL","location","origin","searchParams","set","String","Date","now","Math","random","href","pathname","search","onerror","onload","previousLink","parentElement","insertBefore","nextSibling","restart","self","reload","chunkResolvers","delete","_eval","code","map","encodeURI","CHUNK_BASE_PATH","ASSET_SUFFIX","btoa","unescape","encodeURIComponent","eval"],"mappings":"AAAA;;;;;CAKC,GAED,oDAAoD,GAEpD,gDAAgD;AAChD,4CAA4C;AAC5C,iDAAiD;AACjD,0DAA0D;AAE1D,IAAIA;AACH,CAAC;IACAA,cAAc;QACZC,aAAYC,QAAQ;YAClBC,eAAeD;YAEf,mEAAmE;YACnE,0DAA0D;YAC1D,MAAME,eAAeF,SAASG,KAAK,CAAC,IAAI,CAAC,EAAE;YAC3C,gFAAgF;YAChF,MAAMC,sBAAsBC,UAAUH;YAEtC,IAAII,MAAMN,WAAW;gBACnB,MAAMO,QAAQC,SAASC,gBAAgB,CACrC,CAAC,WAAW,EAAEP,aAAa,eAAe,EAAEA,aAAa,eAAe,EAAEE,oBAAoB,eAAe,EAAEA,oBAAoB,GAAG,CAAC;gBAEzI,KAAK,MAAMM,QAAQC,MAAMC,IAAI,CAACL,OAAQ;oBACpCG,KAAKG,MAAM;gBACb;YACF,OAAO,IAAIC,KAAKd,WAAW;gBACzB,mEAAmE;gBACnE,0BAA0B;gBAC1B,uEAAuE;gBACvE,4DAA4D;gBAC5D,MAAMe,UAAUP,SAASC,gBAAgB,CACvC,CAAC,YAAY,EAAEP,aAAa,gBAAgB,EAAEA,aAAa,gBAAgB,EAAEE,oBAAoB,gBAAgB,EAAEA,oBAAoB,GAAG,CAAC;gBAE7I,KAAK,MAAMY,UAAUL,MAAMC,IAAI,CAACG,SAAU;oBACxCC,OAAOH,MAAM;gBACf;YACF,OAAO;gBACL,MAAM,IAAII,MAAM,CAAC,mCAAmC,EAAEjB,UAAU;YAClE;QACF;QAEAkB,aAAYlB,Q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AK8B,IAAI,GAAGxC;gBACd;gBAEAU,KAAKiC,OAAO,GAAG;oBACbtB;gBACF;gBACAX,KAAKkC,MAAM,GAAG;oBACZ,0EAA0E;oBAC1E,wEAAwE;oBACxE,uBAAuB;oBACvB,KAAK,MAAMC,gBAAgBlC,MAAMC,IAAI,CAACU,eACpCuB,aAAahC,MAAM;oBAErB,uEAAuE;oBACvE,oBAAoB;oBACpBO;gBACF;gBAEA,wEAAwE;gBACxE,4BAA4B;gBAC5BE,aAAa,CAAC,EAAE,CAACwB,aAAa,CAAEC,YAAY,CAC1CrC,MACAY,aAAa,CAAC,EAAE,CAAC0B,WAAW;YAEhC;QACF;QAEAC,SAAS,IAAMC,KAAKnB,QAAQ,CAACoB,MAAM;IACrC;IAEA,SAASlD,eAAeD,QAAkB;QACxCoD,eAAeC,MAAM,CAACrD;IACxB;AACF,CAAC;AAED,SAASsD,MAAM,EAAEC,IAAI,EAAE1B,GAAG,EAAE2B,GAAG,EAAyB;IACtDD,QAAQ,CAAC,kBAAkB,EAAEE,UAC3B1B,SAASC,MAAM,GAAG0B,kBAAkB7B,MAAM8B,eACzC;IACH,IAAIH,KAAK;QACPD,QAAQ,CAAC,kEAAkE,EAAEK,KAC3E,0EAA0E;QAC1E,2CAA2C;QAC3CC,SAASC,mBAAmBN,QAC3B;IACL;IAEA,mCAAmC;IACnC,OAAOO,KAAKR;AACd","ignoreList":[0]}}] } \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/swc_transforms/preset_env/output/0fw._turbopack-tests_tests_snapshot_swc_transforms_preset_env_input_index_0ot90f-.js b/turbopack/crates/turbopack-tests/tests/snapshot/swc_transforms/preset_env/output/0fw._turbopack-tests_tests_snapshot_swc_transforms_preset_env_input_index_0ot90f-.js index d0446b63164c..d423017e5e17 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/swc_transforms/preset_env/output/0fw._turbopack-tests_tests_snapshot_swc_transforms_preset_env_input_index_0ot90f-.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/swc_transforms/preset_env/output/0fw._turbopack-tests_tests_snapshot_swc_transforms_preset_env_input_index_0ot90f-.js @@ -1613,10 +1613,13 @@ function _ts_generator(thisArg, body) { */ /* eslint-disable @typescript-eslint/no-unused-vars */ /// /// function getAssetSuffixFromScriptSrc() { - var _self_TURBOPACK_ASSET_SUFFIX; - var _document_currentScript_getAttribute, _document_currentScript_getAttribute1, _document_currentScript, _document; + var _ref; + var _document_currentScript_getAttribute, _document_currentScript, _document; // TURBOPACK_ASSET_SUFFIX is set in web workers - return ((_self_TURBOPACK_ASSET_SUFFIX = self.TURBOPACK_ASSET_SUFFIX) !== null && _self_TURBOPACK_ASSET_SUFFIX !== void 0 ? _self_TURBOPACK_ASSET_SUFFIX : (_document = document) === null || _document === void 0 ? void 0 : (_document_currentScript = _document.currentScript) === null || _document_currentScript === void 0 ? void 0 : (_document_currentScript_getAttribute1 = _document_currentScript.getAttribute) === null || _document_currentScript_getAttribute1 === void 0 ? void 0 : (_document_currentScript_getAttribute = _document_currentScript_getAttribute1.call(_document_currentScript, 'src')) === null || _document_currentScript_getAttribute === void 0 ? void 0 : _document_currentScript_getAttribute.replace(/^(.*(?=\?)|^.*$)/, '')) || ''; + if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX; + var src = (_ref = (_document = document) === null || _document === void 0 ? void 0 : (_document_currentScript = _document.currentScript) === null || _document_currentScript === void 0 ? void 0 : (_document_currentScript_getAttribute = _document_currentScript.getAttribute) === null || _document_currentScript_getAttribute === void 0 ? void 0 : _document_currentScript_getAttribute.call(_document_currentScript, 'src')) !== null && _ref !== void 0 ? _ref : ''; + var qi = src.indexOf('?'); + return qi >= 0 ? src.slice(qi) : ''; } var BACKEND; /** diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/swc_transforms/preset_env/output/0ko._turbopack-tests_tests_snapshot_swc_transforms_preset_env_input_index_0ot90f-.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/swc_transforms/preset_env/output/0ko._turbopack-tests_tests_snapshot_swc_transforms_preset_env_input_index_0ot90f-.js.map index 02b2c07427d1..1e647f7d3cb7 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/swc_transforms/preset_env/output/0ko._turbopack-tests_tests_snapshot_swc_transforms_preset_env_input_index_0ot90f-.js.map +++ b/turbopack/crates/turbopack-tests/tests/snapshot/swc_transforms/preset_env/output/0ko._turbopack-tests_tests_snapshot_swc_transforms_preset_env_input_index_0ot90f-.js.map @@ -5,5 +5,5 @@ {"offset": {"line": 14, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared/runtime/runtime-utils.ts"],"sourcesContent":["/**\n * This file contains runtime types and functions that are shared between all\n * TurboPack ECMAScript runtimes.\n *\n * It will be prepended to the runtime code of each runtime.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n\ntype EsmNamespaceObject = Record\n\n/**\n * Describes why a module was instantiated.\n * Shared between browser and Node.js runtimes.\n */\nenum SourceType {\n /**\n * The module was instantiated because it was included in an evaluated chunk's\n * runtime.\n * SourceData is a ChunkPath.\n */\n Runtime = 0,\n /**\n * The module was instantiated because a parent module imported it.\n * SourceData is a ModuleId.\n */\n Parent = 1,\n /**\n * The module was instantiated because it was included in a chunk's hot module\n * update.\n * SourceData is an array of ModuleIds or undefined.\n */\n Update = 2,\n}\n\ntype SourceData = ChunkPath | ModuleId | ModuleId[] | undefined\n\n// @ts-ignore Defined in `dev-base.ts`\ndeclare function getOrInstantiateModuleFromParent(\n id: ModuleId,\n sourceModule: M\n): M\n\n// @ts-ignore Defined in `hmr-runtime.ts` (dev mode only)\ndeclare let devModuleCache: Record | undefined\n\n/**\n * Flag indicating which module object type to create when a module is merged. Set to `true`\n * by each runtime that uses ModuleWithDirection (browser dev-base.ts, nodejs dev-base.ts,\n * nodejs build-base.ts). Browser production (build-base.ts) leaves it as `false` since it\n * uses plain Module objects.\n */\nlet createModuleWithDirectionFlag = false\n\nconst REEXPORTED_OBJECTS = new WeakMap()\n\n/**\n * Constructs the `__turbopack_context__` object for a module.\n */\nfunction Context(\n this: TurbopackBaseContext,\n module: Module,\n exports: Exports\n) {\n this.m = module\n // We need to store this here instead of accessing it from the module object to:\n // 1. Make it available to factories directly, since we rewrite `this` to\n // `__turbopack_context__.e` in CJS modules.\n // 2. Support async modules which rewrite `module.exports` to a promise, so we\n // can still access the original exports object from functions like\n // `esmExport`\n // Ideally we could find a new approach for async modules and drop this property altogether.\n this.e = exports\n}\nconst contextPrototype = Context.prototype as TurbopackBaseContext\n\ntype ModuleContextMap = Record\n\ninterface ModuleContextEntry {\n id: () => ModuleId\n module: () => any\n}\n\ninterface ModuleContext {\n // require call\n (moduleId: string): Exports | EsmNamespaceObject\n\n // async import call\n import(moduleId: string): Promise\n\n keys(): ModuleId[]\n\n resolve(moduleId: string): ModuleId\n}\n\ntype GetOrInstantiateModuleFromParent = (\n moduleId: M['id'],\n parentModule: M\n) => M\n\ndeclare function getOrInstantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): Module\n\nconst hasOwnProperty = Object.prototype.hasOwnProperty\nconst toStringTag = typeof Symbol !== 'undefined' && Symbol.toStringTag\n\nfunction defineProp(\n obj: any,\n name: PropertyKey,\n options: PropertyDescriptor & ThisType\n) {\n if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options)\n}\n\nfunction getOverwrittenModule(\n moduleCache: ModuleCache,\n id: ModuleId\n): Module {\n let module = moduleCache[id]\n if (!module) {\n if (createModuleWithDirectionFlag) {\n // set in development modes for hmr support\n module = createModuleWithDirection(id)\n } else {\n module = createModuleObject(id)\n }\n moduleCache[id] = module\n }\n return module\n}\n\n/**\n * Creates the module object. Only done here to ensure all module objects have the same shape.\n */\nfunction createModuleObject(id: ModuleId): Module {\n return {\n exports: {},\n error: undefined,\n id,\n namespaceObject: undefined,\n }\n}\n\nfunction createModuleWithDirection(id: ModuleId): ModuleWithDirection {\n return {\n exports: {},\n error: undefined,\n id,\n namespaceObject: undefined,\n parents: [],\n children: [],\n }\n}\n\ntype BindingTag = 0\nconst BindingTag_Value = 0 as BindingTag\n\n// an arbitrary sequence of bindings as\n// - a prop name\n// - BindingTag_Value, a value to be bound directly, or\n// - 1 or 2 functions to bind as getters and sdetters\ntype EsmBindings = Array<\n string | BindingTag | (() => unknown) | ((v: unknown) => void) | unknown\n>\n\n/**\n * Adds the getters to the exports object.\n */\nfunction esm(exports: Exports, bindings: EsmBindings) {\n defineProp(exports, '__esModule', { value: true })\n if (toStringTag) defineProp(exports, toStringTag, { value: 'Module' })\n let i = 0\n while (i < bindings.length) {\n const propName = bindings[i++] as string\n const tagOrFunction = bindings[i++]\n if (typeof tagOrFunction === 'number') {\n if (tagOrFunction === BindingTag_Value) {\n defineProp(exports, propName, {\n value: bindings[i++],\n enumerable: true,\n writable: false,\n })\n } else {\n throw new Error(`unexpected tag: ${tagOrFunction}`)\n }\n } else {\n const getterFn = tagOrFunction as () => unknown\n if (typeof bindings[i] === 'function') {\n const setterFn = bindings[i++] as (v: unknown) => void\n defineProp(exports, propName, {\n get: getterFn,\n set: setterFn,\n enumerable: true,\n })\n } else {\n defineProp(exports, propName, {\n get: getterFn,\n enumerable: true,\n })\n }\n }\n }\n Object.seal(exports)\n}\n\n/**\n * Makes the module an ESM with exports\n */\nfunction esmExport(\n this: TurbopackBaseContext,\n bindings: EsmBindings,\n id: ModuleId | undefined\n) {\n let module: Module\n let exports: Module['exports']\n if (id != null) {\n module = getOverwrittenModule(this.c, id)\n exports = module.exports\n } else {\n module = this.m\n exports = this.e\n }\n module.namespaceObject = exports\n esm(exports, bindings)\n}\ncontextPrototype.s = esmExport\n\ntype ReexportedObjects = Record[]\nfunction ensureDynamicExports(\n module: Module,\n exports: Exports\n): ReexportedObjects {\n let reexportedObjects: ReexportedObjects | undefined =\n REEXPORTED_OBJECTS.get(module)\n\n if (!reexportedObjects) {\n REEXPORTED_OBJECTS.set(module, (reexportedObjects = []))\n module.exports = module.namespaceObject = new Proxy(exports, {\n get(target, prop) {\n if (\n hasOwnProperty.call(target, prop) ||\n prop === 'default' ||\n prop === '__esModule'\n ) {\n return Reflect.get(target, prop)\n }\n for (const obj of reexportedObjects!) {\n const value = Reflect.get(obj, prop)\n if (value !== undefined) return value\n }\n return undefined\n },\n ownKeys(target) {\n const keys = Reflect.ownKeys(target)\n for (const obj of reexportedObjects!) {\n for (const key of Reflect.ownKeys(obj)) {\n if (key !== 'default' && !keys.includes(key)) keys.push(key)\n }\n }\n return keys\n },\n })\n }\n return reexportedObjects\n}\n\n/**\n * Dynamically exports properties from an object\n */\nfunction dynamicExport(\n this: TurbopackBaseContext,\n object: Record,\n id: ModuleId | undefined\n) {\n let module: Module\n let exports: Exports\n if (id != null) {\n module = getOverwrittenModule(this.c, id)\n exports = module.exports\n } else {\n module = this.m\n exports = this.e\n }\n const reexportedObjects = ensureDynamicExports(module, exports)\n\n if (typeof object === 'object' && object !== null) {\n reexportedObjects.push(object)\n }\n}\ncontextPrototype.j = dynamicExport\n\nfunction exportValue(\n this: TurbopackBaseContext,\n value: any,\n id: ModuleId | undefined\n) {\n let module: Module\n if (id != null) {\n module = getOverwrittenModule(this.c, id)\n } else {\n module = this.m\n }\n module.exports = value\n}\ncontextPrototype.v = exportValue\n\nfunction exportNamespace(\n this: TurbopackBaseContext,\n namespace: any,\n id: ModuleId | undefined\n) {\n let module: Module\n if (id != null) {\n module = getOverwrittenModule(this.c, id)\n } else {\n module = this.m\n }\n module.exports = module.namespaceObject = namespace\n}\ncontextPrototype.n = exportNamespace\n\nfunction createGetter(obj: Record, key: string | symbol) {\n return () => obj[key]\n}\n\n/**\n * @returns prototype of the object\n */\nconst getProto: (obj: any) => any = Object.getPrototypeOf\n ? (obj) => Object.getPrototypeOf(obj)\n : (obj) => obj.__proto__\n\n/** Prototypes that are not expanded for exports */\nconst LEAF_PROTOTYPES = [null, getProto({}), getProto([]), getProto(getProto)]\n\n/**\n * @param raw\n * @param ns\n * @param allowExportDefault\n * * `false`: will have the raw module as default export\n * * `true`: will have the default property as default export\n */\nfunction interopEsm(\n raw: Exports,\n ns: EsmNamespaceObject,\n allowExportDefault?: boolean\n) {\n const bindings: EsmBindings = []\n let defaultLocation = -1\n for (\n let current = raw;\n (typeof current === 'object' || typeof current === 'function') &&\n !LEAF_PROTOTYPES.includes(current);\n current = getProto(current)\n ) {\n for (const key of Object.getOwnPropertyNames(current)) {\n bindings.push(key, createGetter(raw, key))\n if (defaultLocation === -1 && key === 'default') {\n defaultLocation = bindings.length - 1\n }\n }\n }\n\n // this is not really correct\n // we should set the `default` getter if the imported module is a `.cjs file`\n if (!(allowExportDefault && defaultLocation >= 0)) {\n // Replace the binding with one for the namespace itself in order to preserve iteration order.\n if (defaultLocation >= 0) {\n // Replace the getter with the value\n bindings.splice(defaultLocation, 1, BindingTag_Value, raw)\n } else {\n bindings.push('default', BindingTag_Value, raw)\n }\n }\n\n esm(ns, bindings)\n return ns\n}\n\nfunction createNS(raw: Module['exports']): EsmNamespaceObject {\n if (typeof raw === 'function') {\n return function (this: any, ...args: any[]) {\n return raw.apply(this, args)\n }\n } else {\n return Object.create(null)\n }\n}\n\nfunction esmImport(\n this: TurbopackBaseContext,\n id: ModuleId\n): Exclude {\n const module = getOrInstantiateModuleFromParent(id, this.m)\n\n // any ES module has to have `module.namespaceObject` defined.\n if (module.namespaceObject) return module.namespaceObject\n\n // only ESM can be an async module, so we don't need to worry about exports being a promise here.\n const raw = module.exports\n return (module.namespaceObject = interopEsm(\n raw,\n createNS(raw),\n raw && (raw as any).__esModule\n ))\n}\ncontextPrototype.i = esmImport\n\nfunction asyncLoader(\n this: TurbopackBaseContext,\n moduleId: ModuleId\n): Promise {\n const loader = this.r(moduleId) as (\n importFunction: EsmImport\n ) => Promise\n return loader(esmImport.bind(this))\n}\ncontextPrototype.A = asyncLoader\n\n// Add a simple runtime require so that environments without one can still pass\n// `typeof require` CommonJS checks so that exports are correctly registered.\nconst runtimeRequire =\n // @ts-ignore\n typeof require === 'function'\n ? // @ts-ignore\n require\n : function require() {\n throw new Error('Unexpected use of runtime require')\n }\ncontextPrototype.t = runtimeRequire\n\nfunction commonJsRequire(\n this: TurbopackBaseContext,\n id: ModuleId\n): Exports {\n return getOrInstantiateModuleFromParent(id, this.m).exports\n}\ncontextPrototype.r = commonJsRequire\n\n/**\n * Remove fragments and query parameters since they are never part of the context map keys\n *\n * This matches how we parse patterns at resolving time. Arguably we should only do this for\n * strings passed to `import` but the resolve does it for `import` and `require` and so we do\n * here as well.\n */\nfunction parseRequest(request: string): string {\n // Per the URI spec fragments can contain `?` characters, so we should trim it off first\n // https://datatracker.ietf.org/doc/html/rfc3986#section-3.5\n const hashIndex = request.indexOf('#')\n if (hashIndex !== -1) {\n request = request.substring(0, hashIndex)\n }\n\n const queryIndex = request.indexOf('?')\n if (queryIndex !== -1) {\n request = request.substring(0, queryIndex)\n }\n\n return request\n}\n/**\n * `require.context` and require/import expression runtime.\n */\nfunction moduleContext(map: ModuleContextMap): ModuleContext {\n function moduleContext(id: string): Exports {\n id = parseRequest(id)\n if (hasOwnProperty.call(map, id)) {\n return map[id].module()\n }\n\n const e = new Error(`Cannot find module '${id}'`)\n ;(e as any).code = 'MODULE_NOT_FOUND'\n throw e\n }\n\n moduleContext.keys = (): string[] => {\n return Object.keys(map)\n }\n\n moduleContext.resolve = (id: string): ModuleId => {\n id = parseRequest(id)\n if (hasOwnProperty.call(map, id)) {\n return map[id].id()\n }\n\n const e = new Error(`Cannot find module '${id}'`)\n ;(e as any).code = 'MODULE_NOT_FOUND'\n throw e\n }\n\n moduleContext.import = async (id: string) => {\n return await (moduleContext(id) as Promise)\n }\n\n return moduleContext\n}\ncontextPrototype.f = moduleContext\n\n/**\n * Returns the path of a chunk defined by its data.\n */\nfunction getChunkPath(chunkData: ChunkData): ChunkPath {\n return typeof chunkData === 'string' ? chunkData : chunkData.path\n}\n\nfunction isPromise(maybePromise: any): maybePromise is Promise {\n return (\n maybePromise != null &&\n typeof maybePromise === 'object' &&\n 'then' in maybePromise &&\n typeof maybePromise.then === 'function'\n )\n}\n\nfunction isAsyncModuleExt(obj: T): obj is AsyncModuleExt & T {\n return turbopackQueues in obj\n}\n\nfunction createPromise() {\n let resolve: (value: T | PromiseLike) => void\n let reject: (reason?: any) => void\n\n const promise = new Promise((res, rej) => {\n reject = rej\n resolve = res\n })\n\n return {\n promise,\n resolve: resolve!,\n reject: reject!,\n }\n}\n\n// Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map.\n// The CompressedModuleFactories format is\n// - 1 or more module ids\n// - a module factory function\n// So walking this is a little complex but the flat structure is also fast to\n// traverse, we can use `typeof` operators to distinguish the two cases.\nfunction installCompressedModuleFactories(\n chunkModules: CompressedModuleFactories,\n offset: number,\n moduleFactories: ModuleFactories,\n newModuleId?: (id: ModuleId) => void\n) {\n let i = offset\n while (i < chunkModules.length) {\n let end = i + 1\n // Find our factory function\n while (\n end < chunkModules.length &&\n typeof chunkModules[end] !== 'function'\n ) {\n end++\n }\n if (end === chunkModules.length) {\n throw new Error('malformed chunk format, expected a factory function')\n }\n\n // Install the factory for each module ID that doesn't already have one.\n // When some IDs in this group already have a factory, reuse that existing\n // group factory for the missing IDs to keep all IDs in the group consistent.\n // Otherwise, install the factory from this chunk.\n const moduleFactoryFn = chunkModules[end] as Function\n let existingGroupFactory: Function | undefined = undefined\n for (let j = i; j < end; j++) {\n const id = chunkModules[j] as ModuleId\n const existingFactory = moduleFactories.get(id)\n if (existingFactory) {\n existingGroupFactory = existingFactory\n break\n }\n }\n const factoryToInstall = existingGroupFactory ?? moduleFactoryFn\n\n let didInstallFactory = false\n for (let j = i; j < end; j++) {\n const id = chunkModules[j] as ModuleId\n if (!moduleFactories.has(id)) {\n if (!didInstallFactory) {\n if (factoryToInstall === moduleFactoryFn) {\n applyModuleFactoryName(moduleFactoryFn)\n }\n didInstallFactory = true\n }\n moduleFactories.set(id, factoryToInstall)\n newModuleId?.(id)\n }\n }\n i = end + 1 // end is pointing at the last factory advance to the next id or the end of the array.\n }\n}\n\n// everything below is adapted from webpack\n// https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13\n\nconst turbopackQueues = Symbol('turbopack queues')\nconst turbopackExports = Symbol('turbopack exports')\nconst turbopackError = Symbol('turbopack error')\n\nconst enum QueueStatus {\n Unknown = -1,\n Unresolved = 0,\n Resolved = 1,\n}\n\ntype AsyncQueueFn = (() => void) & { queueCount: number }\ntype AsyncQueue = AsyncQueueFn[] & {\n status: QueueStatus\n}\n\nfunction resolveQueue(queue?: AsyncQueue) {\n if (queue && queue.status !== QueueStatus.Resolved) {\n queue.status = QueueStatus.Resolved\n queue.forEach((fn) => fn.queueCount--)\n queue.forEach((fn) => (fn.queueCount-- ? fn.queueCount++ : fn()))\n }\n}\n\ntype Dep = Exports | AsyncModulePromise | Promise\n\ntype AsyncModuleExt = {\n [turbopackQueues]: (fn: (queue: AsyncQueue) => void) => void\n [turbopackExports]: Exports\n [turbopackError]?: any\n}\n\ntype AsyncModulePromise = Promise & AsyncModuleExt\n\nfunction wrapDeps(deps: Dep[]): AsyncModuleExt[] {\n return deps.map((dep): AsyncModuleExt => {\n if (dep !== null && typeof dep === 'object') {\n if (isAsyncModuleExt(dep)) return dep\n if (isPromise(dep)) {\n const queue: AsyncQueue = Object.assign([], {\n status: QueueStatus.Unresolved,\n })\n\n const obj: AsyncModuleExt = {\n [turbopackExports]: {},\n [turbopackQueues]: (fn: (queue: AsyncQueue) => void) => fn(queue),\n }\n\n dep.then(\n (res) => {\n obj[turbopackExports] = res\n resolveQueue(queue)\n },\n (err) => {\n obj[turbopackError] = err\n resolveQueue(queue)\n }\n )\n\n return obj\n }\n }\n\n return {\n [turbopackExports]: dep,\n [turbopackQueues]: () => {},\n }\n })\n}\n\nfunction asyncModule(\n this: TurbopackBaseContext,\n body: (\n handleAsyncDependencies: (\n deps: Dep[]\n ) => Exports[] | Promise<() => Exports[]>,\n asyncResult: (err?: any) => void\n ) => void,\n hasAwait: boolean\n) {\n const module = this.m\n const queue: AsyncQueue | undefined = hasAwait\n ? Object.assign([], { status: QueueStatus.Unknown })\n : undefined\n\n const depQueues: Set = new Set()\n\n const { resolve, reject, promise: rawPromise } = createPromise()\n\n const promise: AsyncModulePromise = Object.assign(rawPromise, {\n [turbopackExports]: module.exports,\n [turbopackQueues]: (fn) => {\n queue && fn(queue)\n depQueues.forEach(fn)\n promise['catch'](() => {})\n },\n } satisfies AsyncModuleExt)\n\n const attributes: PropertyDescriptor = {\n get(): any {\n return promise\n },\n set(v: any) {\n // Calling `esmExport` leads to this.\n if (v !== promise) {\n promise[turbopackExports] = v\n }\n },\n }\n\n Object.defineProperty(module, 'exports', attributes)\n Object.defineProperty(module, 'namespaceObject', attributes)\n\n function handleAsyncDependencies(deps: Dep[]) {\n const currentDeps = wrapDeps(deps)\n\n const getResult = () =>\n currentDeps.map((d) => {\n if (d[turbopackError]) throw d[turbopackError]\n return d[turbopackExports]\n })\n\n const { promise, resolve } = createPromise<() => Exports[]>()\n\n const fn: AsyncQueueFn = Object.assign(() => resolve(getResult), {\n queueCount: 0,\n })\n\n function fnQueue(q: AsyncQueue) {\n if (q !== queue && !depQueues.has(q)) {\n depQueues.add(q)\n if (q && q.status === QueueStatus.Unresolved) {\n fn.queueCount++\n q.push(fn)\n }\n }\n }\n\n currentDeps.map((dep) => dep[turbopackQueues](fnQueue))\n\n return fn.queueCount ? promise : getResult()\n }\n\n function asyncResult(err?: any) {\n if (err) {\n reject((promise[turbopackError] = err))\n } else {\n resolve(promise[turbopackExports])\n }\n\n resolveQueue(queue)\n }\n\n body(handleAsyncDependencies, asyncResult)\n\n if (queue && queue.status === QueueStatus.Unknown) {\n queue.status = QueueStatus.Unresolved\n }\n}\ncontextPrototype.a = asyncModule\n\n/**\n * A pseudo \"fake\" URL object to resolve to its relative path.\n *\n * When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this\n * runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid\n * hydration mismatch.\n *\n * This is based on webpack's existing implementation:\n * https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js\n */\nconst relativeURL = function relativeURL(this: any, inputUrl: string) {\n const realUrl = new URL(inputUrl, 'x:/')\n const values: Record = {}\n for (const key in realUrl) values[key] = (realUrl as any)[key]\n values.href = inputUrl\n values.pathname = inputUrl.replace(/[?#].*/, '')\n values.origin = values.protocol = ''\n values.toString = values.toJSON = (..._args: Array) => inputUrl\n for (const key in values)\n Object.defineProperty(this, key, {\n enumerable: true,\n configurable: true,\n value: values[key],\n })\n}\nrelativeURL.prototype = URL.prototype\ncontextPrototype.U = relativeURL\n\n/**\n * Utility function to ensure all variants of an enum are handled.\n */\nfunction invariant(never: never, computeMessage: (arg: any) => string): never {\n throw new Error(`Invariant: ${computeMessage(never)}`)\n}\n\n/**\n * Constructs an error message for when a module factory is not available.\n */\nfunction factoryNotAvailableMessage(\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): string {\n let instantiationReason: string\n switch (sourceType) {\n case SourceType.Runtime:\n instantiationReason = `as a runtime entry of chunk ${sourceData}`\n break\n case SourceType.Parent:\n instantiationReason = `because it was required from module ${sourceData}`\n break\n case SourceType.Update:\n instantiationReason = 'because of an HMR update'\n break\n default:\n invariant(\n sourceType,\n (sourceType) => `Unknown source type: ${sourceType}`\n )\n }\n return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`\n}\n\n/**\n * A stub function to make `require` available but non-functional in ESM.\n */\nfunction requireStub(_moduleId: ModuleId): never {\n throw new Error('dynamic usage of require is not supported')\n}\ncontextPrototype.z = requireStub\n\n// Make `globalThis` available to the module in a way that cannot be shadowed by a local variable.\ncontextPrototype.g = globalThis\n\ntype ContextConstructor = {\n new (module: Module, exports: Exports): TurbopackBaseContext\n}\n\nfunction applyModuleFactoryName(factory: Function) {\n // Give the module factory a nice name to improve stack traces.\n Object.defineProperty(factory, 'name', {\n value: 'module evaluation',\n })\n}\n"],"names":["SourceType","createModuleWithDirectionFlag","REEXPORTED_OBJECTS","WeakMap","Context","module","exports","m","e","contextPrototype","prototype","hasOwnProperty","Object","toStringTag","Symbol","defineProp","obj","name","options","call","defineProperty","getOverwrittenModule","moduleCache","id","createModuleWithDirection","createModuleObject","error","undefined","namespaceObject","parents","children","BindingTag_Value","esm","bindings","value","i","length","propName","tagOrFunction","enumerable","writable","Error","getterFn","setterFn","get","set","seal","esmExport","c","s","ensureDynamicExports","reexportedObjects","Proxy","target","prop","Reflect","_iteratorError","ownKeys","keys","_iteratorError1","key","includes","push","dynamicExport","object","_type_of","j","exportValue","v","exportNamespace","namespace","n","createGetter","getProto","getPrototypeOf","__proto__","LEAF_PROTOTYPES","interopEsm","raw","ns","allowExportDefault","defaultLocation","current","getOwnPropertyNames","splice","createNS","_key","args","apply","create","esmImport","getOrInstantiateModuleFromParent","__esModule","asyncLoader","moduleId","loader","r","bind","A","runtimeRequire","require","require1","t","commonJsRequire","parseRequest","request","hashIndex","indexOf","substring","queryIndex","moduleContext","map","code","resolve","import","f","getChunkPath","chunkData","path","isPromise","maybePromise","then","isAsyncModuleExt","turbopackQueues","createPromise","reject","promise","Promise","res","rej","installCompressedModuleFactories","chunkModules","offset","moduleFactories","newModuleId","end","moduleFactoryFn","existingGroupFactory","existingFactory","factoryToInstall","didInstallFactory","j1","id1","has","applyModuleFactoryName","turbopackExports","turbopackError","resolveQueue","queue","status","forEach","fn","queueCount","wrapDeps","deps","dep","assign","_obj","err","_obj1","asyncModule","body","hasAwait","depQueues","Set","_createPromise","rawPromise","attributes","handleAsyncDependencies","currentDeps","getResult","d","fnQueue","q","add","asyncResult","a","relativeURL","inputUrl","realUrl","URL","values","href","pathname","replace","origin","protocol","toString","toJSON","_args","key1","configurable","U","invariant","never","computeMessage","factoryNotAvailableMessage","sourceType","sourceData","instantiationReason","requireStub","_moduleId","z","g","globalThis","factory"],"mappings":"AAA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bopack]/browser/runtime/base/runtime-base.ts"],"sourcesContent":["/**\n * This file contains runtime types and functions that are shared between all\n * Turbopack *browser* ECMAScript runtimes.\n *\n * It will be appended to the runtime code of each runtime right after the\n * shared runtime utils.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\n// Used in WebWorkers to tell the runtime about the chunk suffix\ndeclare var TURBOPACK_ASSET_SUFFIX: string\n// Used in WebWorkers to tell the runtime about the current chunk url since it\n// can't be detected via `document.currentScript`. Note it's stored in reversed\n// order to use `push` and `pop`\ndeclare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined\n\n// Injected by rust code\ndeclare var CHUNK_BASE_PATH: string\ndeclare var ASSET_SUFFIX: string\ndeclare var WORKER_FORWARDED_GLOBALS: string[]\n\ninterface TurbopackBrowserBaseContext extends TurbopackBaseContext {\n R: ResolvePathFromModule\n}\n\nconst browserContextPrototype =\n Context.prototype as TurbopackBrowserBaseContext\n\n// Provided by build or dev base\ndeclare function instantiateModule(\n id: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): Module\n\ntype RuntimeParams = {\n otherChunks: ChunkData[]\n runtimeModuleIds: ModuleId[]\n}\n\ntype ChunkRegistrationChunk =\n | ChunkPath\n | { getAttribute: (name: string) => string | null }\n | undefined\n\ntype ChunkRegistration = [\n chunkPath: ChunkRegistrationChunk,\n ...([RuntimeParams] | CompressedModuleFactories),\n]\n\ntype ChunkList = {\n script: ChunkRegistrationChunk\n chunks: ChunkData[]\n source: 'entry' | 'dynamic'\n}\n\ninterface RuntimeBackend {\n registerChunk: (\n chunkPath: ChunkPath | ChunkScript,\n params?: RuntimeParams\n ) => void\n /**\n * Returns the same Promise for the same chunk URL.\n */\n loadChunkCached: (sourceType: SourceType, chunkUrl: ChunkUrl) => Promise\n loadWebAssembly: (\n sourceType: SourceType,\n sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ) => Promise\n loadWebAssemblyModule: (\n sourceType: SourceType,\n sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module\n ) => Promise\n}\n\ninterface DevRuntimeBackend {\n reloadChunk?: (chunkUrl: ChunkUrl) => Promise\n unloadChunk?: (chunkUrl: ChunkUrl) => void\n restart: () => void\n}\n\nconst moduleFactories: ModuleFactories = new Map()\ncontextPrototype.M = moduleFactories\n\nconst availableModules: Map | true> = new Map()\n\nconst availableModuleChunks: Map | true> = new Map()\n\nfunction loadChunk(\n this: TurbopackBrowserBaseContext,\n chunkData: ChunkData\n): Promise {\n return loadChunkInternal(SourceType.Parent, this.m.id, chunkData)\n}\nbrowserContextPrototype.l = loadChunk\n\nfunction loadInitialChunk(chunkPath: ChunkPath, chunkData: ChunkData) {\n return loadChunkInternal(SourceType.Runtime, chunkPath, chunkData)\n}\n\nasync function loadChunkInternal(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkData: ChunkData\n): Promise {\n if (typeof chunkData === 'string') {\n return loadChunkPath(sourceType, sourceData, chunkData)\n }\n\n const includedList = chunkData.included || []\n const modulesPromises = includedList.map((included) => {\n if (moduleFactories.has(included)) return true\n return availableModules.get(included)\n })\n if (modulesPromises.length > 0 && modulesPromises.every((p) => p)) {\n // When all included items are already loaded or loading, we can skip loading ourselves\n await Promise.all(modulesPromises)\n return\n }\n\n const includedModuleChunksList = chunkData.moduleChunks || []\n const moduleChunksPromises = includedModuleChunksList\n .map((included) => {\n // TODO(alexkirsz) Do we need this check?\n // if (moduleFactories[included]) return true;\n return availableModuleChunks.get(included)\n })\n .filter((p) => p)\n\n let promise: Promise\n if (moduleChunksPromises.length > 0) {\n // Some module chunks are already loaded or loading.\n\n if (moduleChunksPromises.length === includedModuleChunksList.length) {\n // When all included module chunks are already loaded or loading, we can skip loading ourselves\n await Promise.all(moduleChunksPromises)\n return\n }\n\n const moduleChunksToLoad: Set = new Set()\n for (const moduleChunk of includedModuleChunksList) {\n if (!availableModuleChunks.has(moduleChunk)) {\n moduleChunksToLoad.add(moduleChunk)\n }\n }\n\n for (const moduleChunkToLoad of moduleChunksToLoad) {\n const promise = loadChunkPath(sourceType, sourceData, moduleChunkToLoad)\n\n availableModuleChunks.set(moduleChunkToLoad, promise)\n\n moduleChunksPromises.push(promise)\n }\n\n promise = Promise.all(moduleChunksPromises)\n } else {\n promise = loadChunkPath(sourceType, sourceData, chunkData.path)\n\n // Mark all included module chunks as loading if they are not already loaded or loading.\n for (const includedModuleChunk of includedModuleChunksList) {\n if (!availableModuleChunks.has(includedModuleChunk)) {\n availableModuleChunks.set(includedModuleChunk, promise)\n }\n }\n }\n\n for (const included of includedList) {\n if (!availableModules.has(included)) {\n // It might be better to race old and new promises, but it's rare that the new promise will be faster than a request started earlier.\n // In production it's even more rare, because the chunk optimization tries to deduplicate modules anyway.\n availableModules.set(included, promise)\n }\n }\n\n await promise\n}\n\nconst loadedChunk = Promise.resolve(undefined)\nconst instrumentedBackendLoadChunks = new WeakMap<\n Promise,\n Promise | typeof loadedChunk\n>()\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkByUrl(\n this: TurbopackBrowserBaseContext,\n chunkUrl: ChunkUrl\n) {\n return loadChunkByUrlInternal(SourceType.Parent, this.m.id, chunkUrl)\n}\nbrowserContextPrototype.L = loadChunkByUrl\n\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkByUrlInternal(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkUrl: ChunkUrl\n): Promise {\n const thenable = BACKEND.loadChunkCached(sourceType, chunkUrl)\n let entry = instrumentedBackendLoadChunks.get(thenable)\n if (entry === undefined) {\n const resolve = instrumentedBackendLoadChunks.set.bind(\n instrumentedBackendLoadChunks,\n thenable,\n loadedChunk\n )\n entry = thenable.then(resolve).catch((cause) => {\n let loadReason: string\n switch (sourceType) {\n case SourceType.Runtime:\n loadReason = `as a runtime dependency of chunk ${sourceData}`\n break\n case SourceType.Parent:\n loadReason = `from module ${sourceData}`\n break\n case SourceType.Update:\n loadReason = 'from an HMR update'\n break\n default:\n invariant(\n sourceType,\n (sourceType) => `Unknown source type: ${sourceType}`\n )\n }\n let error = new Error(\n `Failed to load chunk ${chunkUrl} ${loadReason}${\n cause ? `: ${cause}` : ''\n }`,\n cause ? { cause } : undefined\n )\n error.name = 'ChunkLoadError'\n throw error\n })\n instrumentedBackendLoadChunks.set(thenable, entry)\n }\n\n return entry\n}\n\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkPath(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkPath: ChunkPath\n): Promise {\n const url = getChunkRelativeUrl(chunkPath)\n return loadChunkByUrlInternal(sourceType, sourceData, url)\n}\n\n/**\n * Returns an absolute url to an asset.\n */\nfunction resolvePathFromModule(\n this: TurbopackBaseContext,\n moduleId: string\n): string {\n const exported = this.r(moduleId)\n return exported?.default ?? exported\n}\nbrowserContextPrototype.R = resolvePathFromModule\n\n/**\n * no-op for browser\n * @param modulePath\n */\nfunction resolveAbsolutePath(modulePath?: string): string {\n return `/ROOT/${modulePath ?? ''}`\n}\nbrowserContextPrototype.P = resolveAbsolutePath\n\n/**\n * Exports a URL with the static suffix appended.\n */\nfunction exportUrl(\n this: TurbopackBrowserBaseContext,\n url: string,\n id: ModuleId | undefined\n) {\n exportValue.call(this, `${url}${ASSET_SUFFIX}`, id)\n}\nbrowserContextPrototype.q = exportUrl\n\n/**\n * Creates a worker by instantiating the given WorkerConstructor with the\n * appropriate URL and options.\n *\n * The entrypoint is a pre-compiled worker runtime file. The params configure\n * which module chunks to load and which module to run as the entry point.\n *\n * The params are a JSON array of the following structure:\n * `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`\n *\n * @param WorkerConstructor The Worker or SharedWorker constructor\n * @param entrypoint URL path to the worker entrypoint chunk\n * @param moduleChunks list of module chunk paths to load\n * @param workerOptions options to pass to the Worker constructor (optional)\n */\nfunction createWorker(\n WorkerConstructor: { new (url: URL, options?: object): Worker },\n entrypoint: ChunkPath,\n moduleChunks: ChunkPath[],\n workerOptions?: object\n): Worker {\n const isSharedWorker = WorkerConstructor.name === 'SharedWorker'\n\n const chunkUrls = moduleChunks\n .map((chunk) => getChunkRelativeUrl(chunk))\n .reverse()\n const params: unknown[] = [chunkUrls, ASSET_SUFFIX]\n for (const globalName of WORKER_FORWARDED_GLOBALS) {\n params.push((globalThis as Record)[globalName])\n }\n\n const url = new URL(getChunkRelativeUrl(entrypoint), location.origin)\n const paramsJson = JSON.stringify(params)\n if (isSharedWorker) {\n url.searchParams.set('params', paramsJson)\n } else {\n url.hash = '#params=' + encodeURIComponent(paramsJson)\n }\n\n // Remove type: \"module\" from options since our worker entrypoint is not a module\n const options = workerOptions\n ? { ...workerOptions, type: undefined }\n : undefined\n return new WorkerConstructor(url, options)\n}\nbrowserContextPrototype.b = createWorker\n\n/**\n * Instantiates a runtime module.\n */\nfunction instantiateRuntimeModule(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): Module {\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n/**\n * Returns the URL relative to the origin where a chunk can be fetched from.\n */\nfunction getChunkRelativeUrl(chunkPath: ChunkPath | ChunkListPath): ChunkUrl {\n return `${CHUNK_BASE_PATH}${chunkPath\n .split('/')\n .map((p) => encodeURIComponent(p))\n .join('/')}${ASSET_SUFFIX}` as ChunkUrl\n}\n\n/**\n * Return the ChunkPath from a ChunkScript.\n */\nfunction getPathFromScript(chunkScript: ChunkPath | ChunkScript): ChunkPath\nfunction getPathFromScript(\n chunkScript: ChunkListPath | ChunkListScript\n): ChunkListPath\nfunction getPathFromScript(\n chunkScript: ChunkPath | ChunkListPath | ChunkScript | ChunkListScript\n): ChunkPath | ChunkListPath {\n if (typeof chunkScript === 'string') {\n return chunkScript as ChunkPath | ChunkListPath\n }\n const chunkUrl = chunkScript.src!\n const src = decodeURIComponent(chunkUrl.replace(/[?#].*$/, ''))\n const path = src.startsWith(CHUNK_BASE_PATH)\n ? src.slice(CHUNK_BASE_PATH.length)\n : src\n return path as ChunkPath | ChunkListPath\n}\n\n/**\n * Return the ChunkUrl from a ChunkScript.\n */\nfunction getUrlFromScript(chunk: ChunkPath | ChunkScript): ChunkUrl {\n if (typeof chunk === 'string') {\n return getChunkRelativeUrl(chunk)\n } else {\n // This is already exactly what we want\n return chunk.src! as ChunkUrl\n }\n}\n\n/**\n * Determine the chunk to register. Note that this function has side-effects!\n */\nfunction getChunkFromRegistration(\n chunk: ChunkRegistrationChunk\n): ChunkPath | CurrentScript {\n if (typeof chunk === 'string') {\n return chunk\n } else if (!chunk) {\n if (typeof TURBOPACK_NEXT_CHUNK_URLS !== 'undefined') {\n return { src: TURBOPACK_NEXT_CHUNK_URLS.pop()! } as CurrentScript\n } else {\n throw new Error('chunk path empty but not in a worker')\n }\n } else {\n return { src: chunk.getAttribute('src')! } as CurrentScript\n }\n}\n\nconst regexJsUrl = /\\.js(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.\n */\nfunction isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {\n return regexJsUrl.test(chunkUrlOrPath)\n}\n\nconst regexCssUrl = /\\.css(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .css, optionally followed by ?query or #fragment.\n */\nfunction isCss(chunkUrl: ChunkUrl): boolean {\n return regexCssUrl.test(chunkUrl)\n}\n\nfunction loadWebAssembly(\n this: TurbopackBaseContext,\n chunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n): Promise {\n return BACKEND.loadWebAssembly(\n SourceType.Parent,\n this.m.id,\n chunkPath,\n edgeModule,\n importsObj\n )\n}\ncontextPrototype.w = loadWebAssembly\n\nfunction loadWebAssemblyModule(\n this: TurbopackBaseContext,\n chunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module\n): Promise {\n return BACKEND.loadWebAssemblyModule(\n SourceType.Parent,\n this.m.id,\n chunkPath,\n edgeModule\n )\n}\ncontextPrototype.u = loadWebAssemblyModule\n"],"names":["browserContextPrototype","Context","prototype","moduleFactories","Map","contextPrototype","M","availableModules","availableModuleChunks","loadChunk","chunkData","loadChunkInternal","SourceType","Parent","m","id","l","loadInitialChunk","chunkPath","Runtime","sourceType","sourceData","includedList","modulesPromises","includedModuleChunksList","moduleChunksPromises","promise","moduleChunksToLoad","_iteratorError","moduleChunk","_iteratorError1","moduleChunkToLoad","promise1","_iteratorError2","includedModuleChunk","_iteratorError3","included","loadChunkPath","map","has","get","length","every","p","Promise","all","moduleChunks","filter","Set","add","set","push","path","loadedChunk","resolve","undefined","instrumentedBackendLoadChunks","WeakMap","loadChunkByUrl","chunkUrl","loadChunkByUrlInternal","L","thenable","BACKEND","loadChunkCached","entry","bind","then","catch","cause","loadReason","Update","invariant","error","Error","name","url","getChunkRelativeUrl","resolvePathFromModule","moduleId","exported","r","default","R","resolveAbsolutePath","modulePath","P","exportUrl","exportValue","call","ASSET_SUFFIX","q","createWorker","WorkerConstructor","entrypoint","workerOptions","isSharedWorker","chunkUrls","chunk","reverse","params","WORKER_FORWARDED_GLOBALS","globalName","globalThis","URL","location","origin","paramsJson","JSON","stringify","searchParams","hash","encodeURIComponent","options","type","b","instantiateRuntimeModule","instantiateModule","CHUNK_BASE_PATH","split","join","getPathFromScript","chunkScript","src","decodeURIComponent","replace","startsWith","slice","getUrlFromScript","getChunkFromRegistration","TURBOPACK_NEXT_CHUNK_URLS","pop","getAttribute","regexJsUrl","isJs","chunkUrlOrPath","test","regexCssUrl","isCss","loadWebAssembly","edgeModule","importsObj","w","loadWebAssemblyModule","u"],"mappings":"AAAA;;;;;;CAMC,GAED,oDAAoD,GAEpD,6CAA6C;AAC7C,iEAAiE;AAEjE,gEAAgE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/build-base.ts"],"sourcesContent":["/// \n/// \n\nconst moduleCache: ModuleCache = {}\ncontextPrototype.c = moduleCache\n\n/**\n * Gets or instantiates a runtime module.\n */\n// @ts-ignore\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction getOrInstantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): Module {\n const module = moduleCache[moduleId]\n if (module) {\n if (module.error) {\n throw module.error\n }\n return module\n }\n\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it if it is not cached.\n */\n// Used by the backend\n// @ts-ignore\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst getOrInstantiateModuleFromParent: GetOrInstantiateModuleFromParent<\n Module\n> = (id, sourceModule) => {\n const module = moduleCache[id]\n\n if (module) {\n if (module.error) {\n throw module.error\n }\n return module\n }\n\n return instantiateModule(id, SourceType.Parent, sourceModule.id)\n}\n\nfunction instantiateModule(\n id: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): Module {\n const moduleFactory = moduleFactories.get(id)\n if (typeof moduleFactory !== 'function') {\n // This can happen if modules incorrectly handle HMR disposes/updates,\n // e.g. when they keep a `setTimeout` around which still executes old code\n // and contains e.g. a `require(\"something\")` call.\n throw new Error(factoryNotAvailableMessage(id, sourceType, sourceData))\n }\n\n const module: Module = createModuleObject(id)\n const exports = module.exports\n\n moduleCache[id] = module\n\n // NOTE(alexkirsz) This can fail when the module encounters a runtime error.\n const context = new (Context as any as ContextConstructor)(\n module,\n exports\n )\n try {\n moduleFactory(context, module, exports)\n } catch (error) {\n module.error = error as any\n throw error\n }\n\n if (module.namespaceObject && module.exports !== module.namespaceObject) {\n // in case of a circular dependency: cjs1 -> esm2 -> cjs1\n interopEsm(module.exports, module.namespaceObject)\n }\n\n return module\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction registerChunk(registration: ChunkRegistration) {\n const chunk = getChunkFromRegistration(registration[0]) as\n | ChunkScript\n | ChunkPath\n let runtimeParams: RuntimeParams | undefined\n // When bootstrapping we are passed a single runtimeParams object so we can distinguish purely based on length\n if (registration.length === 2) {\n runtimeParams = registration[1] as RuntimeParams\n } else {\n runtimeParams = undefined\n installCompressedModuleFactories(\n registration as CompressedModuleFactories,\n /* offset= */ 1,\n moduleFactories\n )\n }\n\n return BACKEND.registerChunk(chunk, runtimeParams)\n}\n"],"names":["moduleCache","contextPrototype","c","getOrInstantiateRuntimeModule","chunkPath","moduleId","module","error","instantiateModule","SourceType","Runtime","getOrInstantiateModuleFromParent","id","sourceModule","Parent","sourceType","sourceData","moduleFactory","moduleFactories","get","Error","factoryNotAvailableMessage","createModuleObject","exports","context","Context","namespaceObject","interopEsm","registerChunk","registration","chunk","getChunkFromRegistration","runtimeParams","length","undefined","installCompressedModuleFactories","BACKEND"],"mappings":"AAAA,0CAA0C;AAC1C,mCAAmC;AAEnC,IAAMA,cAAmC,CAAC;AAC1CC,iBAAiBC,CAAC,GAAGF;AAErB;;CAEC,GACD,aAAa;AACb,6DAA6D;AAC7D,SAASG,8BACPC,SAAoB,EACpBC,QAAkB;IAElB,IAAMC,SAASN,WAAW,CAACK,SAAS;IACpC,IAAIC,QAAQ;QACV,IAAIA,OAAOC,KAAK,EAAE;YAChB,MAAMD,OAAOC,KAAK;QACpB;QACA,OAAOD;IACT;IAEA,OAAOE,kBAAkBH,UAAUI,WAAWC,OAAO,EAAEN;AACzD;AAEA;;CAEC,GACD,sBAAsB;AACtB,aAAa;AACb,6DAA6D;AAC7D,IAAMO,mCAEF,0CAACC,IAAIC;IACP,IAAMP,SAASN,WAAW,CAACY,GAAG;IAE9B,IAAIN,QAAQ;QACV,IAAIA,OAAOC,KAAK,EAAE;YAChB,MAAMD,OAAOC,KAAK;QACpB;QACA,OAAOD;IACT;IAEA,OAAOE,kBAAkBI,IAAIH,WAAWK,MAAM,EAAED,aAAaD,EAAE;AACjE;AAEA,SAASJ,kBACPI,EAAY,EACZG,UAAsB,EACtBC,UAAsB;IAEtB,IAAMC,gBAAgBC,gBAAgBC,GAAG,CAACP;IAC1C,IAAI,OAAOK,kBAAkB,YAAY;QACvC,sEAAsE;QACtE,0EAA0E;QAC1E,mDAAmD;QACnD,MAAM,IAAIG,MAAMC,2BAA2BT,IAAIG,YAAYC;IAC7D;IAEA,IAAMV,SAAiBgB,mBAAmBV;IAC1C,IAAMW,UAAUjB,OAAOiB,OAAO;IAE9BvB,WAAW,CAACY,GAAG,GAAGN;IAElB,4EAA4E;IAC5E,IAAMkB,UAAU,IAAKC,QACnBnB,QACAiB;IAEF,IAAI;QACFN,cAAcO,SAASlB,QAAQiB;IACjC,EAAE,OAAOhB,OAAO;QACdD,OAAOC,KAAK,GAAGA;QACf,MAAMA;IACR;IAEA,IAAID,OAAOoB,eAAe,IAAIpB,OAAOiB,OAAO,KAAKjB,OAAOoB,eAAe,EAAE;QACvE,yDAAyD;QACzDC,WAAWrB,OAAOiB,OAAO,EAAEjB,OAAOoB,eAAe;IACnD;IAEA,OAAOpB;AACT;AAEA,6DAA6D;AAC7D,SAASsB,cAAcC,YAA+B;IACpD,IAAMC,QAAQC,yBAAyBF,YAAY,CAAC,EAAE;IAGtD,IAAIG;IACJ,8GAA8G;IAC9G,IAAIH,aAAaI,MAAM,KAAK,GAAG;QAC7BD,gBAAgBH,YAAY,CAAC,EAAE;IACjC,OAAO;QACLG,gBAAgBE;QAChBC,iCACEN,cACA,WAAW,GAAG,GACdX;IAEJ;IAEA,OAAOkB,QAAQR,aAAa,CAACE,OAAOE;AACtC","ignoreList":[0]}}, - {"offset": {"line": 1480, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/runtime-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack ECMAScript DOM runtime.\n *\n * It will be appended to the base runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\nfunction getAssetSuffixFromScriptSrc() {\n // TURBOPACK_ASSET_SUFFIX is set in web workers\n return (\n (self.TURBOPACK_ASSET_SUFFIX ??\n document?.currentScript\n ?.getAttribute?.('src')\n ?.replace(/^(.*(?=\\?)|^.*$)/, '')) ||\n ''\n )\n}\n\ntype ChunkResolver = {\n resolved: boolean\n loadingStarted: boolean\n resolve: () => void\n reject: (error?: Error) => void\n promise: Promise\n}\n\nlet BACKEND: RuntimeBackend\n\n/**\n * Maps chunk paths to the corresponding resolver.\n */\nconst chunkResolvers: Map = new Map()\n\n;(() => {\n BACKEND = {\n async registerChunk(chunk, params) {\n let chunkPath = getPathFromScript(chunk)\n let chunkUrl = getUrlFromScript(chunk)\n\n const resolver = getOrCreateResolver(chunkUrl)\n resolver.resolve()\n\n if (params == null) {\n return\n }\n\n for (const otherChunkData of params.otherChunks) {\n const otherChunkPath = getChunkPath(otherChunkData)\n const otherChunkUrl = getChunkRelativeUrl(otherChunkPath)\n\n // Chunk might have started loading, so we want to avoid triggering another load.\n getOrCreateResolver(otherChunkUrl)\n }\n\n // This waits for chunks to be loaded, but also marks included items as available.\n await Promise.all(\n params.otherChunks.map((otherChunkData) =>\n loadInitialChunk(chunkPath, otherChunkData)\n )\n )\n\n if (params.runtimeModuleIds.length > 0) {\n for (const moduleId of params.runtimeModuleIds) {\n getOrInstantiateRuntimeModule(chunkPath, moduleId)\n }\n }\n },\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n loadChunkCached(sourceType: SourceType, chunkUrl: ChunkUrl) {\n return doLoadChunk(sourceType, chunkUrl)\n },\n\n async loadWebAssembly(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n const { instance } = await WebAssembly.instantiateStreaming(\n req,\n importsObj\n )\n\n return instance.exports\n },\n\n async loadWebAssemblyModule(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n return await WebAssembly.compileStreaming(req)\n },\n }\n\n function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {\n let resolver = chunkResolvers.get(chunkUrl)\n if (!resolver) {\n let resolve: () => void\n let reject: (error?: Error) => void\n const promise = new Promise((innerResolve, innerReject) => {\n resolve = innerResolve\n reject = innerReject\n })\n resolver = {\n resolved: false,\n loadingStarted: false,\n promise,\n resolve: () => {\n resolver!.resolved = true\n resolve()\n },\n reject: reject!,\n }\n chunkResolvers.set(chunkUrl, resolver)\n }\n return resolver\n }\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n function doLoadChunk(sourceType: SourceType, chunkUrl: ChunkUrl) {\n const resolver = getOrCreateResolver(chunkUrl)\n if (resolver.loadingStarted) {\n return resolver.promise\n }\n\n if (sourceType === SourceType.Runtime) {\n // We don't need to load chunks references from runtime code, as they're already\n // present in the DOM.\n resolver.loadingStarted = true\n\n if (isCss(chunkUrl)) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n\n // We need to wait for JS chunks to register themselves within `registerChunk`\n // before we can start instantiating runtime modules, hence the absence of\n // `resolver.resolve()` in this branch.\n\n return resolver.promise\n }\n\n if (typeof importScripts === 'function') {\n // We're in a web worker\n if (isCss(chunkUrl)) {\n // ignore\n } else if (isJs(chunkUrl)) {\n self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl)\n importScripts(chunkUrl)\n } else {\n throw new Error(\n `can't infer type of chunk from URL ${chunkUrl} in worker`\n )\n }\n } else {\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n if (previousLinks.length > 0) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n } else {\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n link.href = chunkUrl\n link.onerror = () => {\n resolver.reject()\n }\n link.onload = () => {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(link)\n }\n } else if (isJs(chunkUrl)) {\n const previousScripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n if (previousScripts.length > 0) {\n // There is this edge where the script already failed loading, but we\n // can't detect that. The Promise will never resolve in this case.\n for (const script of Array.from(previousScripts)) {\n script.addEventListener('error', () => {\n resolver.reject()\n })\n }\n } else {\n const script = document.createElement('script')\n script.src = chunkUrl\n // We'll only mark the chunk as loaded once the script has been executed,\n // which happens in `registerChunk`. Hence the absence of `resolve()` in\n // this branch.\n script.onerror = () => {\n resolver.reject()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(script)\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n }\n\n resolver.loadingStarted = true\n return resolver.promise\n }\n\n function fetchWebAssembly(wasmChunkPath: ChunkPath) {\n return fetch(getChunkRelativeUrl(wasmChunkPath))\n }\n})()\n"],"names":["getAssetSuffixFromScriptSrc","_self_TURBOPACK_ASSET_SUFFIX","_document_currentScript_getAttribute","TURBOPACK_ASSET_SUFFIX","currentScript","getAttribute","replace","BACKEND","chunkResolvers","Map","registerChunk","chunk","params","chunkPath","chunkUrl","resolver","_iteratorError","otherChunkData","otherChunkPath","otherChunkUrl","_iteratorError1","moduleId","getPathFromScript","getUrlFromScript","getOrCreateResolver","resolve","otherChunks","getChunkPath","getChunkRelativeUrl","Promise","all","map","loadInitialChunk","runtimeModuleIds","length","getOrInstantiateRuntimeModule","loadChunkCached","sourceType","doLoadChunk","loadWebAssembly","_sourceType","_sourceData","wasmChunkPath","_edgeModule","importsObj","req","instance","fetchWebAssembly","WebAssembly","instantiateStreaming","exports","loadWebAssemblyModule","compileStreaming","get","reject","promise","innerResolve","innerReject","resolved","loadingStarted","resolve1","set","SourceType","Runtime","isCss","importScripts","isJs","self","TURBOPACK_NEXT_CHUNK_URLS","push","Error","decodedChunkUrl","decodeURI","previousLinks","document","querySelectorAll","link","createElement","rel","href","onerror","onload","head","appendChild","previousScripts","Array","from","script","addEventListener","script1","src","fetch"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;CAIC,GAED,oDAAoD,GAEpD,sEAAsE;AACtE,mEAAmE;AAEnE,SAASA;QAGJC;QACCC,sCAAAA,uCAAAA,yBAAAA;IAHJ,+CAA+C;IAC/C,OACE,CAAA,CAACD,+BAAAA,KAAKE,sBAAsB,AAGS,cAHpCF,0CAAAA,gCACCC,YAAAA,sBAAAA,iCAAAA,0BAAAA,UAAUE,aAAa,cAAvBF,+CAAAA,wCAAAA,wBACIG,YAAY,cADhBH,6DAAAA,uCAAAA,2CAAAA,yBACmB,oBADnBA,2DAAAA,qCAEII,OAAO,CAAC,oBAAoB,QAClC;AAEJ;AAUA,IAAIC;AAEJ;;CAEC,GACD,IAAMC,iBAA+C,IAAIC;AAExD,CAAC;IACAF,UAAU;QACFG,eAAN,SAAMA,cAAcC,KAAK,EAAEC,MAAM;;oBAC3BC,WACAC,UAEEC,UAODC,2BAAAA,mBAAAA,gBAAAA,WAAAA,OAAMC,gBACHC,gBACAC,e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ACjB;wBACF;;wBAJKtC;wBAAAA;;;iCAAAA,6BAAAA;gCAAAA;;;gCAAAA;sCAAAA;;;;gBAKP,OAAO;oBACL,IAAMyE,UAASf,SAASG,aAAa,CAAC;oBACtCY,QAAOC,GAAG,GAAG5E;oBACb,yEAAyE;oBACzE,wEAAwE;oBACxE,eAAe;oBACf2E,QAAOT,OAAO,GAAG;wBACfjE,SAASuC,MAAM;oBACjB;oBACA,kDAAkD;oBAClDoB,SAASQ,IAAI,CAACC,WAAW,CAACM;gBAC5B;YACF,OAAO;gBACL,MAAM,IAAInB,MAAM,CAAC,mCAAmC,EAAExD,UAAU;YAClE;QACF;QAEAC,SAAS4C,cAAc,GAAG;QAC1B,OAAO5C,SAASwC,OAAO;IACzB;IAEA,SAASR,iBAAiBL,aAAwB;QAChD,OAAOiD,MAAM/D,oBAAoBc;IACnC;AACF,CAAC","ignoreList":[0]}}] + {"offset": {"line": 1480, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/runtime-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack ECMAScript DOM runtime.\n *\n * It will be appended to the base runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\nfunction getAssetSuffixFromScriptSrc() {\n // TURBOPACK_ASSET_SUFFIX is set in web workers\n if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX\n const src = document?.currentScript?.getAttribute?.('src') ?? ''\n const qi = src.indexOf('?')\n return qi >= 0 ? src.slice(qi) : ''\n}\n\ntype ChunkResolver = {\n resolved: boolean\n loadingStarted: boolean\n resolve: () => void\n reject: (error?: Error) => void\n promise: Promise\n}\n\nlet BACKEND: RuntimeBackend\n\n/**\n * Maps chunk paths to the corresponding resolver.\n */\nconst chunkResolvers: Map = new Map()\n\n;(() => {\n BACKEND = {\n async registerChunk(chunk, params) {\n let chunkPath = getPathFromScript(chunk)\n let chunkUrl = getUrlFromScript(chunk)\n\n const resolver = getOrCreateResolver(chunkUrl)\n resolver.resolve()\n\n if (params == null) {\n return\n }\n\n for (const otherChunkData of params.otherChunks) {\n const otherChunkPath = getChunkPath(otherChunkData)\n const otherChunkUrl = getChunkRelativeUrl(otherChunkPath)\n\n // Chunk might have started loading, so we want to avoid triggering another load.\n getOrCreateResolver(otherChunkUrl)\n }\n\n // This waits for chunks to be loaded, but also marks included items as available.\n await Promise.all(\n params.otherChunks.map((otherChunkData) =>\n loadInitialChunk(chunkPath, otherChunkData)\n )\n )\n\n if (params.runtimeModuleIds.length > 0) {\n for (const moduleId of params.runtimeModuleIds) {\n getOrInstantiateRuntimeModule(chunkPath, moduleId)\n }\n }\n },\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n loadChunkCached(sourceType: SourceType, chunkUrl: ChunkUrl) {\n return doLoadChunk(sourceType, chunkUrl)\n },\n\n async loadWebAssembly(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n const { instance } = await WebAssembly.instantiateStreaming(\n req,\n importsObj\n )\n\n return instance.exports\n },\n\n async loadWebAssemblyModule(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n return await WebAssembly.compileStreaming(req)\n },\n }\n\n function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {\n let resolver = chunkResolvers.get(chunkUrl)\n if (!resolver) {\n let resolve: () => void\n let reject: (error?: Error) => void\n const promise = new Promise((innerResolve, innerReject) => {\n resolve = innerResolve\n reject = innerReject\n })\n resolver = {\n resolved: false,\n loadingStarted: false,\n promise,\n resolve: () => {\n resolver!.resolved = true\n resolve()\n },\n reject: reject!,\n }\n chunkResolvers.set(chunkUrl, resolver)\n }\n return resolver\n }\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n function doLoadChunk(sourceType: SourceType, chunkUrl: ChunkUrl) {\n const resolver = getOrCreateResolver(chunkUrl)\n if (resolver.loadingStarted) {\n return resolver.promise\n }\n\n if (sourceType === SourceType.Runtime) {\n // We don't need to load chunks references from runtime code, as they're already\n // present in the DOM.\n resolver.loadingStarted = true\n\n if (isCss(chunkUrl)) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n\n // We need to wait for JS chunks to register themselves within `registerChunk`\n // before we can start instantiating runtime modules, hence the absence of\n // `resolver.resolve()` in this branch.\n\n return resolver.promise\n }\n\n if (typeof importScripts === 'function') {\n // We're in a web worker\n if (isCss(chunkUrl)) {\n // ignore\n } else if (isJs(chunkUrl)) {\n self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl)\n importScripts(chunkUrl)\n } else {\n throw new Error(\n `can't infer type of chunk from URL ${chunkUrl} in worker`\n )\n }\n } else {\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n if (previousLinks.length > 0) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n } else {\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n link.href = chunkUrl\n link.onerror = () => {\n resolver.reject()\n }\n link.onload = () => {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(link)\n }\n } else if (isJs(chunkUrl)) {\n const previousScripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n if (previousScripts.length > 0) {\n // There is this edge where the script already failed loading, but we\n // can't detect that. The Promise will never resolve in this case.\n for (const script of Array.from(previousScripts)) {\n script.addEventListener('error', () => {\n resolver.reject()\n })\n }\n } else {\n const script = document.createElement('script')\n script.src = chunkUrl\n // We'll only mark the chunk as loaded once the script has been executed,\n // which happens in `registerChunk`. Hence the absence of `resolve()` in\n // this branch.\n script.onerror = () => {\n resolver.reject()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(script)\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n }\n\n resolver.loadingStarted = true\n return resolver.promise\n }\n\n function fetchWebAssembly(wasmChunkPath: ChunkPath) {\n return fetch(getChunkRelativeUrl(wasmChunkPath))\n }\n})()\n"],"names":["getAssetSuffixFromScriptSrc","_document_currentScript","self","TURBOPACK_ASSET_SUFFIX","src","currentScript","getAttribute","qi","indexOf","slice","BACKEND","chunkResolvers","Map","registerChunk","chunk","params","chunkPath","chunkUrl","resolver","_iteratorError","otherChunkData","otherChunkPath","otherChunkUrl","_iteratorError1","moduleId","getPathFromScript","getUrlFromScript","getOrCreateResolver","resolve","otherChunks","getChunkPath","getChunkRelativeUrl","Promise","all","map","loadInitialChunk","runtimeModuleIds","length","getOrInstantiateRuntimeModule","loadChunkCached","sourceType","doLoadChunk","loadWebAssembly","_sourceType","_sourceData","wasmChunkPath","_edgeModule","importsObj","req","instance","fetchWebAssembly","WebAssembly","instantiateStreaming","exports","loadWebAssemblyModule","compileStreaming","get","reject","promise","innerResolve","innerReject","resolved","loadingStarted","resolve1","set","SourceType","Runtime","isCss","importScripts","isJs","TURBOPACK_NEXT_CHUNK_URLS","push","Error","decodedChunkUrl","decodeURI","previousLinks","document","querySelectorAll","link","createElement","rel","href","onerror","onload","head","appendChild","previousScripts","Array","from","script","add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,GAAG;QAC1B,OAAO5C,SAASwC,OAAO;IACzB;IAEA,SAASR,iBAAiBL,aAAwB;QAChD,OAAO+C,MAAM7D,oBAAoBc;IACnC;AACF,CAAC","ignoreList":[0]}}] } \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/output/0teu_crates_turbopack-tests_tests_snapshot_workers_basic_input_index_03~su6s.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/output/0teu_crates_turbopack-tests_tests_snapshot_workers_basic_input_index_03~su6s.js.map index 8d17818c396f..e9d426222813 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/output/0teu_crates_turbopack-tests_tests_snapshot_workers_basic_input_index_03~su6s.js.map +++ b/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/output/0teu_crates_turbopack-tests_tests_snapshot_workers_basic_input_index_03~su6s.js.map @@ -6,6 +6,6 @@ {"offset": {"line": 590, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/runtime-base.ts"],"sourcesContent":["/**\n * This file contains runtime types and functions that are shared between all\n * Turbopack *browser* ECMAScript runtimes.\n *\n * It will be appended to the runtime code of each runtime right after the\n * shared runtime utils.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\n// Used in WebWorkers to tell the runtime about the chunk suffix\ndeclare var TURBOPACK_ASSET_SUFFIX: string\n// Used in WebWorkers to tell the runtime about the current chunk url since it\n// can't be detected via `document.currentScript`. Note it's stored in reversed\n// order to use `push` and `pop`\ndeclare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined\n\n// Injected by rust code\ndeclare var CHUNK_BASE_PATH: string\ndeclare var ASSET_SUFFIX: string\ndeclare var WORKER_FORWARDED_GLOBALS: string[]\n\ninterface TurbopackBrowserBaseContext extends TurbopackBaseContext {\n R: ResolvePathFromModule\n}\n\nconst browserContextPrototype =\n Context.prototype as TurbopackBrowserBaseContext\n\n// Provided by build or dev base\ndeclare function instantiateModule(\n id: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): Module\n\ntype RuntimeParams = {\n otherChunks: ChunkData[]\n runtimeModuleIds: ModuleId[]\n}\n\ntype ChunkRegistrationChunk =\n | ChunkPath\n | { getAttribute: (name: string) => string | null }\n | undefined\n\ntype ChunkRegistration = [\n chunkPath: ChunkRegistrationChunk,\n ...([RuntimeParams] | CompressedModuleFactories),\n]\n\ntype ChunkList = {\n script: ChunkRegistrationChunk\n chunks: ChunkData[]\n source: 'entry' | 'dynamic'\n}\n\ninterface RuntimeBackend {\n registerChunk: (\n chunkPath: ChunkPath | ChunkScript,\n params?: RuntimeParams\n ) => void\n /**\n * Returns the same Promise for the same chunk URL.\n */\n loadChunkCached: (sourceType: SourceType, chunkUrl: ChunkUrl) => Promise\n loadWebAssembly: (\n sourceType: SourceType,\n sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ) => Promise\n loadWebAssemblyModule: (\n sourceType: SourceType,\n sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module\n ) => Promise\n}\n\ninterface DevRuntimeBackend {\n reloadChunk?: (chunkUrl: ChunkUrl) => Promise\n unloadChunk?: (chunkUrl: ChunkUrl) => void\n restart: () => void\n}\n\nconst moduleFactories: ModuleFactories = new Map()\ncontextPrototype.M = moduleFactories\n\nconst availableModules: Map | true> = new Map()\n\nconst availableModuleChunks: Map | true> = new Map()\n\nfunction loadChunk(\n this: TurbopackBrowserBaseContext,\n chunkData: ChunkData\n): Promise {\n return loadChunkInternal(SourceType.Parent, this.m.id, chunkData)\n}\nbrowserContextPrototype.l = loadChunk\n\nfunction loadInitialChunk(chunkPath: ChunkPath, chunkData: ChunkData) {\n return loadChunkInternal(SourceType.Runtime, chunkPath, chunkData)\n}\n\nasync function loadChunkInternal(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkData: ChunkData\n): Promise {\n if (typeof chunkData === 'string') {\n return loadChunkPath(sourceType, sourceData, chunkData)\n }\n\n const includedList = chunkData.included || []\n const modulesPromises = includedList.map((included) => {\n if (moduleFactories.has(included)) return true\n return availableModules.get(included)\n })\n if (modulesPromises.length > 0 && modulesPromises.every((p) => p)) {\n // When all included items are already loaded or loading, we can skip loading ourselves\n await Promise.all(modulesPromises)\n return\n }\n\n const includedModuleChunksList = chunkData.moduleChunks || []\n const moduleChunksPromises = includedModuleChunksList\n .map((included) => {\n // TODO(alexkirsz) Do we need this check?\n // if (moduleFactories[included]) return true;\n return availableModuleChunks.get(included)\n })\n .filter((p) => p)\n\n let promise: Promise\n if (moduleChunksPromises.length > 0) {\n // Some module chunks are already loaded or loading.\n\n if (moduleChunksPromises.length === includedModuleChunksList.length) {\n // When all included module chunks are already loaded or loading, we can skip loading ourselves\n await Promise.all(moduleChunksPromises)\n return\n }\n\n const moduleChunksToLoad: Set = new Set()\n for (const moduleChunk of includedModuleChunksList) {\n if (!availableModuleChunks.has(moduleChunk)) {\n moduleChunksToLoad.add(moduleChunk)\n }\n }\n\n for (const moduleChunkToLoad of moduleChunksToLoad) {\n const promise = loadChunkPath(sourceType, sourceData, moduleChunkToLoad)\n\n availableModuleChunks.set(moduleChunkToLoad, promise)\n\n moduleChunksPromises.push(promise)\n }\n\n promise = Promise.all(moduleChunksPromises)\n } else {\n promise = loadChunkPath(sourceType, sourceData, chunkData.path)\n\n // Mark all included module chunks as loading if they are not already loaded or loading.\n for (const includedModuleChunk of includedModuleChunksList) {\n if (!availableModuleChunks.has(includedModuleChunk)) {\n availableModuleChunks.set(includedModuleChunk, promise)\n }\n }\n }\n\n for (const included of includedList) {\n if (!availableModules.has(included)) {\n // It might be better to race old and new promises, but it's rare that the new promise will be faster than a request started earlier.\n // In production it's even more rare, because the chunk optimization tries to deduplicate modules anyway.\n availableModules.set(included, promise)\n }\n }\n\n await promise\n}\n\nconst loadedChunk = Promise.resolve(undefined)\nconst instrumentedBackendLoadChunks = new WeakMap<\n Promise,\n Promise | typeof loadedChunk\n>()\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkByUrl(\n this: TurbopackBrowserBaseContext,\n chunkUrl: ChunkUrl\n) {\n return loadChunkByUrlInternal(SourceType.Parent, this.m.id, chunkUrl)\n}\nbrowserContextPrototype.L = loadChunkByUrl\n\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkByUrlInternal(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkUrl: ChunkUrl\n): Promise {\n const thenable = BACKEND.loadChunkCached(sourceType, chunkUrl)\n let entry = instrumentedBackendLoadChunks.get(thenable)\n if (entry === undefined) {\n const resolve = instrumentedBackendLoadChunks.set.bind(\n instrumentedBackendLoadChunks,\n thenable,\n loadedChunk\n )\n entry = thenable.then(resolve).catch((cause) => {\n let loadReason: string\n switch (sourceType) {\n case SourceType.Runtime:\n loadReason = `as a runtime dependency of chunk ${sourceData}`\n break\n case SourceType.Parent:\n loadReason = `from module ${sourceData}`\n break\n case SourceType.Update:\n loadReason = 'from an HMR update'\n break\n default:\n invariant(\n sourceType,\n (sourceType) => `Unknown source type: ${sourceType}`\n )\n }\n let error = new Error(\n `Failed to load chunk ${chunkUrl} ${loadReason}${\n cause ? `: ${cause}` : ''\n }`,\n cause ? { cause } : undefined\n )\n error.name = 'ChunkLoadError'\n throw error\n })\n instrumentedBackendLoadChunks.set(thenable, entry)\n }\n\n return entry\n}\n\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkPath(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkPath: ChunkPath\n): Promise {\n const url = getChunkRelativeUrl(chunkPath)\n return loadChunkByUrlInternal(sourceType, sourceData, url)\n}\n\n/**\n * Returns an absolute url to an asset.\n */\nfunction resolvePathFromModule(\n this: TurbopackBaseContext,\n moduleId: string\n): string {\n const exported = this.r(moduleId)\n return exported?.default ?? exported\n}\nbrowserContextPrototype.R = resolvePathFromModule\n\n/**\n * no-op for browser\n * @param modulePath\n */\nfunction resolveAbsolutePath(modulePath?: string): string {\n return `/ROOT/${modulePath ?? ''}`\n}\nbrowserContextPrototype.P = resolveAbsolutePath\n\n/**\n * Exports a URL with the static suffix appended.\n */\nfunction exportUrl(\n this: TurbopackBrowserBaseContext,\n url: string,\n id: ModuleId | undefined\n) {\n exportValue.call(this, `${url}${ASSET_SUFFIX}`, id)\n}\nbrowserContextPrototype.q = exportUrl\n\n/**\n * Creates a worker by instantiating the given WorkerConstructor with the\n * appropriate URL and options.\n *\n * The entrypoint is a pre-compiled worker runtime file. The params configure\n * which module chunks to load and which module to run as the entry point.\n *\n * The params are a JSON array of the following structure:\n * `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`\n *\n * @param WorkerConstructor The Worker or SharedWorker constructor\n * @param entrypoint URL path to the worker entrypoint chunk\n * @param moduleChunks list of module chunk paths to load\n * @param workerOptions options to pass to the Worker constructor (optional)\n */\nfunction createWorker(\n WorkerConstructor: { new (url: URL, options?: object): Worker },\n entrypoint: ChunkPath,\n moduleChunks: ChunkPath[],\n workerOptions?: object\n): Worker {\n const isSharedWorker = WorkerConstructor.name === 'SharedWorker'\n\n const chunkUrls = moduleChunks\n .map((chunk) => getChunkRelativeUrl(chunk))\n .reverse()\n const params: unknown[] = [chunkUrls, ASSET_SUFFIX]\n for (const globalName of WORKER_FORWARDED_GLOBALS) {\n params.push((globalThis as Record)[globalName])\n }\n\n const url = new URL(getChunkRelativeUrl(entrypoint), location.origin)\n const paramsJson = JSON.stringify(params)\n if (isSharedWorker) {\n url.searchParams.set('params', paramsJson)\n } else {\n url.hash = '#params=' + encodeURIComponent(paramsJson)\n }\n\n // Remove type: \"module\" from options since our worker entrypoint is not a module\n const options = workerOptions\n ? { ...workerOptions, type: undefined }\n : undefined\n return new WorkerConstructor(url, options)\n}\nbrowserContextPrototype.b = createWorker\n\n/**\n * Instantiates a runtime module.\n */\nfunction instantiateRuntimeModule(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): Module {\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n/**\n * Returns the URL relative to the origin where a chunk can be fetched from.\n */\nfunction getChunkRelativeUrl(chunkPath: ChunkPath | ChunkListPath): ChunkUrl {\n return `${CHUNK_BASE_PATH}${chunkPath\n .split('/')\n .map((p) => encodeURIComponent(p))\n .join('/')}${ASSET_SUFFIX}` as ChunkUrl\n}\n\n/**\n * Return the ChunkPath from a ChunkScript.\n */\nfunction getPathFromScript(chunkScript: ChunkPath | ChunkScript): ChunkPath\nfunction getPathFromScript(\n chunkScript: ChunkListPath | ChunkListScript\n): ChunkListPath\nfunction getPathFromScript(\n chunkScript: ChunkPath | ChunkListPath | ChunkScript | ChunkListScript\n): ChunkPath | ChunkListPath {\n if (typeof chunkScript === 'string') {\n return chunkScript as ChunkPath | ChunkListPath\n }\n const chunkUrl = chunkScript.src!\n const src = decodeURIComponent(chunkUrl.replace(/[?#].*$/, ''))\n const path = src.startsWith(CHUNK_BASE_PATH)\n ? src.slice(CHUNK_BASE_PATH.length)\n : src\n return path as ChunkPath | ChunkListPath\n}\n\n/**\n * Return the ChunkUrl from a ChunkScript.\n */\nfunction getUrlFromScript(chunk: ChunkPath | ChunkScript): ChunkUrl {\n if (typeof chunk === 'string') {\n return getChunkRelativeUrl(chunk)\n } else {\n // This is already exactly what we want\n return chunk.src! as ChunkUrl\n }\n}\n\n/**\n * Determine the chunk to register. Note that this function has side-effects!\n */\nfunction getChunkFromRegistration(\n chunk: ChunkRegistrationChunk\n): ChunkPath | CurrentScript {\n if (typeof chunk === 'string') {\n return chunk\n } else if (!chunk) {\n if (typeof TURBOPACK_NEXT_CHUNK_URLS !== 'undefined') {\n return { src: TURBOPACK_NEXT_CHUNK_URLS.pop()! } as CurrentScript\n } else {\n throw new Error('chunk path empty but not in a worker')\n }\n } else {\n return { src: chunk.getAttribute('src')! } as CurrentScript\n }\n}\n\nconst regexJsUrl = /\\.js(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.\n */\nfunction isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {\n return regexJsUrl.test(chunkUrlOrPath)\n}\n\nconst regexCssUrl = /\\.css(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .css, optionally followed by ?query or #fragment.\n */\nfunction isCss(chunkUrl: ChunkUrl): boolean {\n return regexCssUrl.test(chunkUrl)\n}\n\nfunction loadWebAssembly(\n this: TurbopackBaseContext,\n chunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n): Promise {\n return BACKEND.loadWebAssembly(\n SourceType.Parent,\n this.m.id,\n chunkPath,\n edgeModule,\n importsObj\n )\n}\ncontextPrototype.w = loadWebAssembly\n\nfunction loadWebAssemblyModule(\n this: TurbopackBaseContext,\n chunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module\n): Promise {\n return BACKEND.loadWebAssemblyModule(\n SourceType.Parent,\n this.m.id,\n chunkPath,\n edgeModule\n )\n}\ncontextPrototype.u = loadWebAssemblyModule\n"],"names":["browserContextPrototype","Context","prototype","moduleFactories","Map","contextPrototype","M","availableModules","availableModuleChunks","loadChunk","chunkData","loadChunkInternal","SourceType","Parent","m","id","l","loadInitialChunk","chunkPath","Runtime","sourceType","sourceData","loadChunkPath","includedList","included","modulesPromises","map","has","get","length","every","p","Promise","all","includedModuleChunksList","moduleChunks","moduleChunksPromises","filter","promise","moduleChunksToLoad","Set","moduleChunk","add","moduleChunkToLoad","set","push","path","includedModuleChunk","loadedChunk","resolve","undefined","instrumentedBackendLoadChunks","WeakMap","loadChunkByUrl","chunkUrl","loadChunkByUrlInternal","L","thenable","BACKEND","loadChunkCached","entry","bind","then","catch","cause","loadReason","Update","invariant","error","Error","name","url","getChunkRelativeUrl","resolvePathFromModule","moduleId","exported","r","default","R","resolveAbsolutePath","modulePath","P","exportUrl","exportValue","call","ASSET_SUFFIX","q","createWorker","WorkerConstructor","entrypoint","workerOptions","isSharedWorker","chunkUrls","chunk","reverse","params","globalName","WORKER_FORWARDED_GLOBALS","globalThis","URL","location","origin","paramsJson","JSON","stringify","searchParams","hash","encodeURIComponent","options","type","b","instantiateRuntimeModule","instantiateModule","CHUNK_BASE_PATH","split","join","getPathFromScript","chunkScript","src","decodeURIComponent","replace","startsWith","slice","getUrlFromScript","getChunkFromRegistration","TURBOPACK_NEXT_CHUNK_URLS","pop","getAttribute","regexJsUrl","isJs","chunkUrlOrPath","test","regexCssUrl","isCss","loadWebAssembly","edgeModule","importsObj","w","loadWebAssemblyModule","u"],"mappings":"AAAA;;;;;;CAMC,GAED,oDAAoD,GAEpD,6CAA6C;AAC7C,iEAAiE;AAEjE,gEAAgE;AAgBhE,MAAMA,0BACJC,QAAQC,SAAS;AA4DnB,MAAMC,kBAAmC,IAAIC;AAC7CC,iBAAiBC,CAAC,GAAGH;AAErB,MAAMI,mBAAuD,IAAIH;AAEjE,MAAMI,wBAA6D,IAAIJ;AAEvE,SAASK,UAEPC,SAAoB;IAEpB,OAAOC,kBAAkBC,WAAWC,MAAM,EAAE,IAAI,CAACC,CAAC,CAACC,EAAE,EAAEL;AACzD;AACAV,wBAAwBgB,CAAC,GAAGP;AAE5B,SAASQ,iBAAiBC,SAAoB,EAAER,SAAoB;IAClE,OAAOC,kBAAkBC,WAAWO,OAAO,EAAED,WAAWR;AAC1D;AAEA,eAAeC,kBACbS,UAAsB,EACtBC,UAAsB,EACtBX,SAAoB;IAEpB,IAAI,OAAOA,cAAc,UAAU;QACjC,OAAOY,cAAcF,YAAYC,YAAYX;IAC/C;IAEA,MAAMa,eAAeb,UAAUc,QAAQ,IAAI,EAAE;IAC7C,MAAMC,kBAAkBF,aAAaG,GAAG,CAAC,CAACF;QACxC,IAAIrB,gBAAgBwB,GAAG,CAACH,WAAW,OAAO;QAC1C,OAAOjB,iBAAiBqB,GAAG,CAACJ;IAC9B;IACA,IAAIC,gBAAgBI,MAAM,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,MAAME,cAAc;AACpB;;CAEC,GACD,SAASC,MAAM/E,QAAkB;IAC/B,OAAO8E,YAAYD,IAAI,CAAC7E;AAC1B;AAEA,SAASgF,gBAEPpH,SAAoB,EACpBqH,UAAoC,EACpCC,UAA+B;IAE/B,OAAO9E,QAAQ4E,eAAe,CAC5B1H,WAAWC,MAAM,EACjB,IAAI,CAACC,CAAC,CAACC,EAAE,EACTG,WACAqH,YACAC;AAEJ;AACAnI,iBAAiBoI,CAAC,GAAGH;AAErB,SAASI,sBAEPxH,SAAoB,EACpBqH,UAAoC;IAEpC,OAAO7E,QAAQgF,qBAAqB,CAClC9H,WAAWC,MAAM,EACjB,IAAI,CAACC,CAAC,CAACC,EAAE,EACTG,WACAqH;AAEJ;AACAlI,iBAAiBsI,CAAC,GAAGD","ignoreList":[0]}}, {"offset": {"line": 839, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared/runtime/hmr-runtime.ts"],"sourcesContent":["/// \n/// \n/// \n/// \n\ntype HotModuleFactoryFunction = ModuleFactoryFunction<\n HotModule,\n TurbopackBaseContext\n>\n\n/**\n * Shared HMR (Hot Module Replacement) implementation.\n *\n * This file contains the complete HMR implementation that's shared between\n * browser and Node.js runtimes. It manages module hot state, dependency\n * tracking, the module.hot API, and the full HMR update flow.\n */\n\n/**\n * The development module cache shared across the runtime.\n * Browser runtime declares this directly.\n * Node.js runtime assigns globalThis.__turbopack_module_cache__ to this.\n */\nlet devModuleCache: Record\n\n/**\n * Module IDs that are instantiated as part of the runtime of a chunk.\n */\nlet runtimeModules: Set\n\n/**\n * Maps module IDs to persisted data between executions of their hot module\n * implementation (`hot.data`).\n */\nconst moduleHotData: Map = new Map()\n\n/**\n * Maps module instances to their hot module state.\n * Uses WeakMap so it works with both HotModule and ModuleWithDirection.\n */\nconst moduleHotState: WeakMap = new WeakMap()\n\n/**\n * Modules that call `module.hot.invalidate()` (while being updated).\n */\nconst queuedInvalidatedModules: Set = new Set()\n\nclass UpdateApplyError extends Error {\n name = 'UpdateApplyError'\n\n dependencyChain: ModuleId[]\n\n constructor(message: string, dependencyChain: ModuleId[]) {\n super(message)\n this.dependencyChain = dependencyChain\n }\n}\n\ntype ModuleEffect =\n | {\n type: 'unaccepted'\n dependencyChain: ModuleId[]\n }\n | {\n type: 'self-declined'\n dependencyChain: ModuleId[]\n moduleId: ModuleId\n }\n | {\n type: 'declined'\n dependencyChain: ModuleId[]\n moduleId: ModuleId\n parentId: ModuleId\n }\n | {\n type: 'accepted'\n moduleId: ModuleId\n outdatedModules: Set\n outdatedDependencies: Map>\n }\n\n/**\n * Records parent-child relationship when a module imports another.\n * Should be called during module instantiation.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction trackModuleImport(\n parentModule: ModuleWithDirection,\n childModuleId: ModuleId,\n childModule: ModuleWithDirection | undefined\n): void {\n // Record that parent imports child\n if (parentModule.children.indexOf(childModuleId) === -1) {\n parentModule.children.push(childModuleId)\n }\n\n // Record that child is imported by parent\n if (childModule && childModule.parents.indexOf(parentModule.id) === -1) {\n childModule.parents.push(parentModule.id)\n }\n}\n\nfunction formatDependencyChain(dependencyChain: ModuleId[]): string {\n return `Dependency chain: ${dependencyChain.join(' -> ')}`\n}\n\n/**\n * Walks the dependency tree to find all modules affected by a change.\n * Returns information about whether the update can be accepted and which\n * modules need to be invalidated.\n *\n * @param moduleId - The module that changed\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept().\n * This is used for server-side HMR where pages auto-accept at the top level.\n */\nfunction getAffectedModuleEffects(\n moduleId: ModuleId,\n autoAcceptRootModules: boolean\n): ModuleEffect {\n const outdatedModules: Set = new Set()\n const outdatedDependencies: Map> = new Map()\n\n type QueueItem = { moduleId?: ModuleId; dependencyChain: ModuleId[] }\n\n const queue: QueueItem[] = [\n {\n moduleId,\n dependencyChain: [],\n },\n ]\n\n let nextItem\n while ((nextItem = queue.shift())) {\n const { moduleId, dependencyChain } = nextItem\n\n if (moduleId != null) {\n if (outdatedModules.has(moduleId)) {\n // Avoid infinite loops caused by cycles between modules in the dependency chain.\n continue\n }\n\n outdatedModules.add(moduleId)\n }\n\n // We've arrived at the runtime of the chunk, which means that nothing\n // else above can accept this update.\n if (moduleId === undefined) {\n if (autoAcceptRootModules) {\n return {\n type: 'accepted',\n moduleId,\n outdatedModules,\n outdatedDependencies,\n }\n }\n return {\n type: 'unaccepted',\n dependencyChain,\n }\n }\n\n const module = devModuleCache[moduleId]\n const hotState = moduleHotState.get(module)!\n\n if (\n // The module is not in the cache. Since this is a \"modified\" update,\n // it means that the module was never instantiated before.\n !module || // The module accepted itself without invalidating globalThis.\n // TODO is that right?\n (hotState.selfAccepted && !hotState.selfInvalidated)\n ) {\n continue\n }\n\n if (hotState.selfDeclined) {\n return {\n type: 'self-declined',\n dependencyChain,\n moduleId,\n }\n }\n\n if (runtimeModules.has(moduleId)) {\n if (autoAcceptRootModules) {\n continue\n }\n queue.push({\n moduleId: undefined,\n dependencyChain: [...dependencyChain, moduleId],\n })\n continue\n }\n\n for (const parentId of module.parents) {\n const parent = devModuleCache[parentId]\n\n if (!parent) {\n continue\n }\n\n const parentHotState = moduleHotState.get(parent)\n\n // Check if parent declined this dependency\n if (parentHotState?.declinedDependencies[moduleId]) {\n return {\n type: 'declined',\n dependencyChain: [...dependencyChain, moduleId],\n moduleId,\n parentId,\n }\n }\n\n // Skip if parent is already outdated\n if (outdatedModules.has(parentId)) {\n continue\n }\n\n // Check if parent accepts this dependency\n if (parentHotState?.acceptedDependencies[moduleId]) {\n if (!outdatedDependencies.has(parentId)) {\n outdatedDependencies.set(parentId, new Set())\n }\n outdatedDependencies.get(parentId)!.add(moduleId)\n continue\n }\n\n // Neither accepted nor declined — propagate to parent\n queue.push({\n moduleId: parentId,\n dependencyChain: [...dependencyChain, moduleId],\n })\n }\n\n // If no parents and we're at a root module, auto-accept if configured\n if (module.parents.length === 0 && autoAcceptRootModules) {\n continue\n }\n }\n\n return {\n type: 'accepted',\n moduleId,\n outdatedModules,\n outdatedDependencies,\n }\n}\n\n/**\n * Merges source dependency map into target dependency map.\n */\nfunction mergeDependencies(\n target: Map>,\n source: Map>\n): void {\n for (const [parentId, deps] of source) {\n const existing = target.get(parentId)\n if (existing) {\n for (const dep of deps) {\n existing.add(dep)\n }\n } else {\n target.set(parentId, new Set(deps))\n }\n }\n}\n\n/**\n * Computes all modules that need to be invalidated based on which modules changed.\n *\n * @param invalidated - The modules that have been invalidated\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction computedInvalidatedModules(\n invalidated: Iterable,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n} {\n const outdatedModules = new Set()\n const outdatedDependencies = new Map>()\n\n for (const moduleId of invalidated) {\n const effect = getAffectedModuleEffects(moduleId, autoAcceptRootModules)\n\n switch (effect.type) {\n case 'unaccepted':\n throw new UpdateApplyError(\n `cannot apply update: unaccepted module. ${formatDependencyChain(\n effect.dependencyChain\n )}.`,\n effect.dependencyChain\n )\n case 'self-declined':\n throw new UpdateApplyError(\n `cannot apply update: self-declined module. ${formatDependencyChain(\n effect.dependencyChain\n )}.`,\n effect.dependencyChain\n )\n case 'declined':\n throw new UpdateApplyError(\n `cannot apply update: declined dependency. ${formatDependencyChain(\n effect.dependencyChain\n )}. Declined by ${effect.parentId}.`,\n effect.dependencyChain\n )\n case 'accepted':\n for (const outdatedModuleId of effect.outdatedModules) {\n outdatedModules.add(outdatedModuleId)\n }\n mergeDependencies(outdatedDependencies, effect.outdatedDependencies)\n break\n default:\n invariant(effect, (effect) => `Unknown effect type: ${effect?.type}`)\n }\n }\n\n return { outdatedModules, outdatedDependencies }\n}\n\n/**\n * Creates the module.hot API object and its internal state.\n * This provides the HMR API that user code calls (module.hot.accept(), etc.)\n */\n\nfunction createModuleHot(\n moduleId: ModuleId,\n hotData: HotData\n): { hot: Hot; hotState: HotState } {\n const hotState: HotState = {\n selfAccepted: false,\n selfDeclined: false,\n selfInvalidated: false,\n disposeHandlers: [],\n acceptedDependencies: {},\n acceptedErrorHandlers: {},\n declinedDependencies: {},\n }\n\n const hot: Hot = {\n // TODO(alexkirsz) This is not defined in the HMR API. It was used to\n // decide whether to warn whenever an HMR-disposed module required other\n // modules. We might want to remove it.\n active: true,\n\n data: hotData ?? {},\n\n accept: (\n modules?: string | string[] | AcceptErrorHandler,\n callback?: AcceptCallback,\n errorHandler?: AcceptErrorHandler\n ) => {\n if (modules === undefined) {\n hotState.selfAccepted = true\n } else if (typeof modules === 'function') {\n hotState.selfAccepted = modules\n } else if (typeof modules === 'object' && modules !== null) {\n for (let i = 0; i < modules.length; i++) {\n hotState.acceptedDependencies[modules[i]] = callback || function () {}\n hotState.acceptedErrorHandlers[modules[i]] = errorHandler\n }\n } else {\n hotState.acceptedDependencies[modules] = callback || function () {}\n hotState.acceptedErrorHandlers[modules] = errorHandler\n }\n },\n\n decline: (dep?: string | string[]) => {\n if (dep === undefined) {\n hotState.selfDeclined = true\n } else if (typeof dep === 'object' && dep !== null) {\n for (let i = 0; i < dep.length; i++) {\n hotState.declinedDependencies[dep[i]] = true\n }\n } else {\n hotState.declinedDependencies[dep] = true\n }\n },\n\n dispose: (callback) => {\n hotState.disposeHandlers.push(callback)\n },\n\n addDisposeHandler: (callback) => {\n hotState.disposeHandlers.push(callback)\n },\n\n removeDisposeHandler: (callback) => {\n const idx = hotState.disposeHandlers.indexOf(callback)\n if (idx >= 0) {\n hotState.disposeHandlers.splice(idx, 1)\n }\n },\n\n invalidate: () => {\n hotState.selfInvalidated = true\n queuedInvalidatedModules.add(moduleId)\n },\n\n // NOTE(alexkirsz) This is part of the management API, which we don't\n // implement, but the Next.js React Refresh runtime uses this to decide\n // whether to schedule an update.\n status: () => 'idle',\n\n // NOTE(alexkirsz) Since we always return \"idle\" for now, these are no-ops.\n addStatusHandler: (_handler) => {},\n removeStatusHandler: (_handler) => {},\n\n // NOTE(jridgewell) Check returns the list of updated modules, but we don't\n // want the webpack code paths to ever update (the turbopack paths handle\n // this already).\n check: () => Promise.resolve(null),\n }\n\n return { hot, hotState }\n}\n\n/**\n * Processes queued invalidated modules and adds them to the outdated modules set.\n * Modules that call module.hot.invalidate() are queued and processed here.\n *\n * @param outdatedModules - The current set of outdated modules\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction applyInvalidatedModules(\n outdatedModules: Set,\n outdatedDependencies: Map>,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n} {\n if (queuedInvalidatedModules.size > 0) {\n const result = computedInvalidatedModules(\n queuedInvalidatedModules,\n autoAcceptRootModules\n )\n for (const moduleId of result.outdatedModules) {\n outdatedModules.add(moduleId)\n }\n mergeDependencies(outdatedDependencies, result.outdatedDependencies)\n\n queuedInvalidatedModules.clear()\n }\n\n return { outdatedModules, outdatedDependencies }\n}\n\n/**\n * Computes which outdated modules have self-accepted and can be hot reloaded.\n */\n\nfunction computeOutdatedSelfAcceptedModules(\n outdatedModules: Iterable\n): { moduleId: ModuleId; errorHandler: true | Function }[] {\n const outdatedSelfAcceptedModules: {\n moduleId: ModuleId\n errorHandler: true | Function\n }[] = []\n for (const moduleId of outdatedModules) {\n const module = devModuleCache[moduleId]\n const hotState = moduleHotState.get(module)\n if (module && hotState?.selfAccepted && !hotState.selfInvalidated) {\n outdatedSelfAcceptedModules.push({\n moduleId,\n errorHandler: hotState.selfAccepted,\n })\n }\n }\n return outdatedSelfAcceptedModules\n}\n\n/**\n * Disposes of an instance of a module.\n * Runs hot.dispose handlers and manages persistent hot data.\n *\n * NOTE: mode = \"replace\" will not remove modules from devModuleCache.\n * This must be done in a separate step afterwards.\n */\nfunction disposeModule(moduleId: ModuleId, mode: 'clear' | 'replace') {\n const module = devModuleCache[moduleId]\n if (!module) {\n return\n }\n\n const hotState = moduleHotState.get(module)\n if (!hotState) {\n return\n }\n\n const data: HotData = {}\n\n // Run the `hot.dispose` handler, if any, passing in the persistent\n // `hot.data` object.\n for (const disposeHandler of hotState.disposeHandlers) {\n disposeHandler(data)\n }\n\n // This used to warn in `getOrInstantiateModuleFromParent` when a disposed\n // module is still importing other modules.\n if (module.hot) {\n module.hot.active = false\n }\n\n moduleHotState.delete(module)\n\n // Remove the disposed module from its children's parent list.\n // It will be added back once the module re-instantiates and imports its\n // children again.\n for (const childId of module.children) {\n const child = devModuleCache[childId]\n if (!child) {\n continue\n }\n\n const idx = child.parents.indexOf(module.id)\n if (idx >= 0) {\n child.parents.splice(idx, 1)\n }\n }\n\n switch (mode) {\n case 'clear':\n delete devModuleCache[module.id]\n moduleHotData.delete(module.id)\n break\n case 'replace':\n moduleHotData.set(module.id, data)\n break\n default:\n invariant(mode, (mode) => `invalid mode: ${mode}`)\n }\n}\n\n/**\n * Dispose phase: runs dispose handlers and cleans up outdated/disposed modules.\n * Returns the parent modules of outdated modules for use in the apply phase.\n */\n\nfunction disposePhase(\n outdatedModules: Iterable,\n disposedModules: Iterable,\n outdatedDependencies: Map>\n): { outdatedModuleParents: Map> } {\n for (const moduleId of outdatedModules) {\n disposeModule(moduleId, 'replace')\n }\n\n for (const moduleId of disposedModules) {\n disposeModule(moduleId, 'clear')\n }\n\n // Removing modules from the module cache is a separate step.\n // We also want to keep track of previous parents of the outdated modules.\n const outdatedModuleParents = new Map>()\n for (const moduleId of outdatedModules) {\n const oldModule = devModuleCache[moduleId]\n outdatedModuleParents.set(moduleId, oldModule?.parents)\n delete devModuleCache[moduleId]\n }\n\n // Remove outdated dependencies from parent module's children list.\n // When a parent accepts a child's update, the child is re-instantiated\n // but the parent stays alive. We remove the old child reference so it\n // gets re-added when the child re-imports.\n for (const [parentId, deps] of outdatedDependencies) {\n const module = devModuleCache[parentId]\n if (module) {\n for (const dep of deps) {\n const idx = module.children.indexOf(dep)\n if (idx >= 0) {\n module.children.splice(idx, 1)\n }\n }\n }\n }\n\n return { outdatedModuleParents }\n}\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/**\n * Shared module instantiation logic.\n * This handles the full module instantiation flow for both browser and Node.js.\n * Only React Refresh hooks differ between platforms (passed as callback).\n */\nfunction instantiateModuleShared(\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n runtimeModules: Set,\n createModuleObjectFn: (id: ModuleId) => HotModule,\n createContextFn: (module: HotModule, exports: Exports, refresh?: any) => any,\n runModuleExecutionHooksFn: (\n module: HotModule,\n exec: (refresh: any) => void\n ) => void\n): HotModule {\n // 1. Factory validation (same in both browser and Node.js)\n const id = moduleId\n const moduleFactory = moduleFactories.get(id)\n if (typeof moduleFactory !== 'function') {\n throw new Error(\n factoryNotAvailableMessage(moduleId, sourceType, sourceData) +\n `\\nThis is often caused by a stale browser cache, misconfigured Cache-Control headers, or a service worker serving outdated responses.` +\n `\\nTo fix this, make sure your Cache-Control headers allow revalidation of chunks and review your service worker configuration. ` +\n `As an immediate workaround, try hard-reloading the page, clearing the browser cache, or unregistering any service workers.`\n )\n }\n\n // 2. Hot API setup (same in both - works for browser, included for Node.js)\n const hotData = moduleHotData.get(id)!\n const { hot, hotState } = createModuleHot(id, hotData)\n\n // 3. Parent assignment logic (same in both)\n let parents: ModuleId[]\n switch (sourceType) {\n case SourceType.Runtime:\n runtimeModules.add(id)\n parents = []\n break\n case SourceType.Parent:\n parents = [sourceData as ModuleId]\n break\n case SourceType.Update:\n parents = (sourceData as ModuleId[]) || []\n break\n default:\n throw new Error(`Unknown source type: ${sourceType}`)\n }\n\n // 4. Module creation (platform creates base module object)\n const module = createModuleObjectFn(id)\n const exports = module.exports\n module.parents = parents\n module.children = []\n module.hot = hot\n\n devModuleCache[id] = module\n moduleHotState.set(module, hotState)\n\n // 5. Module execution (React Refresh hooks are platform-specific)\n try {\n runModuleExecutionHooksFn(module, (refresh) => {\n const context = createContextFn(module, exports, refresh)\n moduleFactory.call(exports, context, module, exports)\n })\n } catch (error) {\n module.error = error as any\n throw error\n }\n\n // 6. ESM interop (same in both)\n if (module.namespaceObject && module.exports !== module.namespaceObject) {\n // in case of a circular dependency: cjs1 -> esm2 -> cjs1\n interopEsm(module.exports, module.namespaceObject)\n }\n\n return module\n}\n\n/**\n * Analyzes update entries and chunks to determine which modules were added, modified, or deleted.\n * This is pure logic that doesn't depend on the runtime environment.\n */\nfunction computeChangedModules(\n entries: Record,\n updates: Record,\n chunkModulesMap?: Map>\n): {\n added: Map\n modified: Map\n deleted: Set\n chunksAdded: Map>\n chunksDeleted: Map>\n} {\n const chunksAdded = new Map()\n const chunksDeleted = new Map()\n const added: Map = new Map()\n const modified = new Map()\n const deleted: Set = new Set()\n\n for (const [chunkPath, mergedChunkUpdate] of Object.entries(updates) as Array<\n [ChunkPath, EcmascriptMergedChunkUpdate]\n >) {\n switch (mergedChunkUpdate.type) {\n case 'added': {\n const updateAdded = new Set(mergedChunkUpdate.modules)\n for (const moduleId of updateAdded) {\n added.set(moduleId, entries[moduleId])\n }\n chunksAdded.set(chunkPath, updateAdded)\n break\n }\n case 'deleted': {\n const updateDeleted = chunkModulesMap\n ? new Set(chunkModulesMap.get(chunkPath))\n : new Set()\n for (const moduleId of updateDeleted) {\n deleted.add(moduleId)\n }\n chunksDeleted.set(chunkPath, updateDeleted)\n break\n }\n case 'partial': {\n const updateAdded = new Set(mergedChunkUpdate.added)\n const updateDeleted = new Set(mergedChunkUpdate.deleted)\n for (const moduleId of updateAdded) {\n added.set(moduleId, entries[moduleId])\n }\n for (const moduleId of updateDeleted) {\n deleted.add(moduleId)\n }\n chunksAdded.set(chunkPath, updateAdded)\n chunksDeleted.set(chunkPath, updateDeleted)\n break\n }\n default:\n throw new Error('Unknown merged chunk update type')\n }\n }\n\n // If a module was added from one chunk and deleted from another in the same update,\n // consider it to be modified, as it means the module was moved from one chunk to another\n // AND has new code in a single update.\n for (const moduleId of added.keys()) {\n if (deleted.has(moduleId)) {\n added.delete(moduleId)\n deleted.delete(moduleId)\n }\n }\n\n for (const [moduleId, entry] of Object.entries(entries)) {\n // Modules that haven't been added to any chunk but have new code are considered\n // to be modified.\n // This needs to be under the previous loop, as we need it to get rid of modules\n // that were added and deleted in the same update.\n if (!added.has(moduleId)) {\n modified.set(moduleId, entry)\n }\n }\n\n return { added, deleted, modified, chunksAdded, chunksDeleted }\n}\n\n/**\n * Compiles new module code and walks the dependency tree to find all outdated modules.\n * Uses the evalModuleEntry function to compile code (platform-specific).\n *\n * @param added - Map of added modules\n * @param modified - Map of modified modules\n * @param evalModuleEntry - Function to compile module code\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction computeOutdatedModules(\n added: Map,\n modified: Map,\n evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n newModuleFactories: Map\n} {\n const newModuleFactories = new Map()\n\n // Compile added modules\n for (const [moduleId, entry] of added) {\n if (entry != null) {\n newModuleFactories.set(moduleId, evalModuleEntry(entry))\n }\n }\n\n // Walk dependency tree to find all modules affected by modifications\n const { outdatedModules, outdatedDependencies } = computedInvalidatedModules(\n modified.keys(),\n autoAcceptRootModules\n )\n\n // Compile modified modules\n for (const [moduleId, entry] of modified) {\n newModuleFactories.set(moduleId, evalModuleEntry(entry))\n }\n\n return { outdatedModules, outdatedDependencies, newModuleFactories }\n}\n\n/**\n * Updates module factories and re-instantiates self-accepted modules.\n * Uses the instantiateModule function (platform-specific via callback).\n */\nfunction applyPhase(\n outdatedSelfAcceptedModules: {\n moduleId: ModuleId\n errorHandler: true | Function\n }[],\n newModuleFactories: Map,\n outdatedModuleParents: Map>,\n outdatedDependencies: Map>,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n instantiateModuleFn: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule,\n applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void,\n reportError: (err: any) => void\n) {\n // Update module factories\n for (const [moduleId, factory] of newModuleFactories.entries()) {\n applyModuleFactoryNameFn(factory)\n moduleFactories.set(moduleId, factory)\n }\n\n // TODO(alexkirsz) Run new runtime entries here.\n\n // Call accept handlers for outdated dependencies.\n // This runs BEFORE re-instantiating self-accepted modules, matching\n // webpack's behavior.\n for (const [parentId, deps] of outdatedDependencies) {\n const module = devModuleCache[parentId]\n if (!module) continue\n\n const hotState = moduleHotState.get(module)\n if (!hotState) continue\n\n // Group deps by callback, deduplicating callbacks that handle multiple deps.\n // Each callback receives only the deps it was registered for.\n const callbackDeps = new Map void), ModuleId[]>()\n const callbackErrorHandlers = new Map<\n AcceptCallback | (() => void),\n AcceptErrorHandler | undefined\n >()\n\n for (const dep of deps) {\n const acceptCallback = hotState.acceptedDependencies[dep]\n if (acceptCallback) {\n let depList = callbackDeps.get(acceptCallback)\n if (!depList) {\n depList = []\n callbackDeps.set(acceptCallback, depList)\n callbackErrorHandlers.set(\n acceptCallback,\n hotState.acceptedErrorHandlers[dep]\n )\n }\n depList.push(dep)\n }\n }\n\n for (const [callback, cbDeps] of callbackDeps) {\n try {\n callback.call(null, cbDeps)\n } catch (err: any) {\n const errorHandler = callbackErrorHandlers.get(callback)\n if (typeof errorHandler === 'function') {\n try {\n errorHandler(err, {\n moduleId: parentId,\n dependencyId: cbDeps[0],\n })\n } catch (err2) {\n reportError(err2)\n reportError(err)\n }\n } else {\n reportError(err)\n }\n }\n }\n }\n\n // Re-instantiate all outdated self-accepted modules\n for (const { moduleId, errorHandler } of outdatedSelfAcceptedModules) {\n try {\n instantiateModuleFn(\n moduleId,\n SourceType.Update,\n outdatedModuleParents.get(moduleId)\n )\n } catch (err) {\n if (typeof errorHandler === 'function') {\n try {\n errorHandler(err, { moduleId, module: devModuleCache[moduleId] })\n } catch (err2) {\n reportError(err2)\n reportError(err)\n }\n } else {\n reportError(err)\n }\n }\n }\n}\n\n/**\n * Internal implementation that orchestrates the full HMR update flow:\n * invalidation, disposal, and application of new modules.\n *\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction applyInternal(\n outdatedModules: Set,\n outdatedDependencies: Map>,\n disposedModules: Iterable,\n newModuleFactories: Map,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n instantiateModuleFn: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule,\n applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void,\n autoAcceptRootModules: boolean\n) {\n ;({ outdatedModules, outdatedDependencies } = applyInvalidatedModules(\n outdatedModules,\n outdatedDependencies,\n autoAcceptRootModules\n ))\n\n // Find self-accepted modules to re-instantiate\n const outdatedSelfAcceptedModules =\n computeOutdatedSelfAcceptedModules(outdatedModules)\n\n // Run dispose handlers, save hot.data, clear caches\n const { outdatedModuleParents } = disposePhase(\n outdatedModules,\n disposedModules,\n outdatedDependencies\n )\n\n let error: any\n\n function reportError(err: any) {\n if (!error) error = err // Keep first error\n }\n\n applyPhase(\n outdatedSelfAcceptedModules,\n newModuleFactories,\n outdatedModuleParents,\n outdatedDependencies,\n moduleFactories,\n devModuleCache,\n instantiateModuleFn,\n applyModuleFactoryNameFn,\n reportError\n )\n\n if (error) {\n throw error\n }\n\n // Recursively apply any queued invalidations from new module execution\n if (queuedInvalidatedModules.size > 0) {\n applyInternal(\n new Set(),\n new Map(),\n [],\n new Map(),\n moduleFactories,\n devModuleCache,\n instantiateModuleFn,\n applyModuleFactoryNameFn,\n autoAcceptRootModules\n )\n }\n}\n\n/**\n * Main entry point for applying an ECMAScript merged update.\n * This is called by both browser and Node.js runtimes with platform-specific callbacks.\n *\n * @param options.autoAcceptRootModules - If true, root modules auto-accept updates without explicit\n * module.hot.accept(). Used for server-side HMR where pages\n * auto-accept at the top level.\n */\nfunction applyEcmascriptMergedUpdateShared(options: {\n added: Map\n modified: Map\n disposedModules: Iterable\n evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction\n instantiateModule: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule\n applyModuleFactoryName: (factory: HotModuleFactoryFunction) => void\n moduleFactories: ModuleFactories\n devModuleCache: ModuleCache\n autoAcceptRootModules: boolean\n}) {\n const {\n added,\n modified,\n disposedModules,\n evalModuleEntry,\n instantiateModule,\n applyModuleFactoryName,\n moduleFactories,\n devModuleCache,\n autoAcceptRootModules,\n } = options\n\n const { outdatedModules, outdatedDependencies, newModuleFactories } =\n computeOutdatedModules(\n added,\n modified,\n evalModuleEntry,\n autoAcceptRootModules\n )\n\n applyInternal(\n outdatedModules,\n outdatedDependencies,\n disposedModules,\n newModuleFactories,\n moduleFactories,\n devModuleCache,\n instantiateModule,\n applyModuleFactoryName,\n autoAcceptRootModules\n )\n}\n"],"names":["devModuleCache","runtimeModules","moduleHotData","Map","moduleHotState","WeakMap","queuedInvalidatedModules","Set","UpdateApplyError","Error","name","dependencyChain","message","trackModuleImport","parentModule","childModuleId","childModule","children","indexOf","push","parents","id","formatDependencyChain","join","getAffectedModuleEffects","moduleId","autoAcceptRootModules","outdatedModules","outdatedDependencies","queue","nextItem","shift","has","add","undefined","type","module","hotState","get","selfAccepted","selfInvalidated","selfDeclined","parentId","parent","parentHotState","declinedDependencies","acceptedDependencies","set","length","mergeDependencies","target","source","deps","existing","dep","computedInvalidatedModules","invalidated","effect","outdatedModuleId","invariant","createModuleHot","hotData","disposeHandlers","acceptedErrorHandlers","hot","active","data","accept","modules","callback","errorHandler","i","decline","dispose","addDisposeHandler","removeDisposeHandler","idx","splice","invalidate","status","addStatusHandler","_handler","removeStatusHandler","check","Promise","resolve","applyInvalidatedModules","size","result","clear","computeOutdatedSelfAcceptedModules","outdatedSelfAcceptedModules","disposeModule","mode","disposeHandler","delete","childId","child","disposePhase","disposedModules","outdatedModuleParents","oldModule","instantiateModuleShared","sourceType","sourceData","moduleFactories","createModuleObjectFn","createContextFn","runModuleExecutionHooksFn","moduleFactory","factoryNotAvailableMessage","SourceType","Runtime","Parent","Update","exports","refresh","context","call","error","namespaceObject","interopEsm","computeChangedModules","entries","updates","chunkModulesMap","chunksAdded","chunksDeleted","added","modified","deleted","chunkPath","mergedChunkUpdate","Object","updateAdded","updateDeleted","keys","entry","computeOutdatedModules","evalModuleEntry","newModuleFactories","applyPhase","instantiateModuleFn","applyModuleFactoryNameFn","reportError","factory","callbackDeps","callbackErrorHandlers","acceptCallback","depList","cbDeps","err","dependencyId","err2","applyInternal","applyEcmascriptMergedUpdateShared","options","instantiateModule","applyModuleFactoryName"],"mappings":"AAAA,2CAA2C;AAC3C,6CAA6C;AAC7C,4CAA4C;AAC5C,4CAA4C;AAO5C;;;;;;CAMC,GAED;;;;CAIC,GACD,IAAIA;AAEJ;;CAEC,GACD,IAAIC;AAEJ;;;CAGC,GACD,MAAMC,gBAAwC,IAAIC;AAElD;;;CAGC,GACD,MAAMC,iBAAyC,IAAIC;AAEnD;;CAEC,GACD,MAAMC,2BAA0C,IAAIC;AAEpD,MAAMC,yBAAyBC;IAC7BC,OAAO,mBAAkB;IAEzBC,gBAA2B;IAE3BH,YAAYI,OAAe,EAAED,eAA2B,CAAE;QACxD,KAAK,CAACC;QACN,IAAI,CAACD,eAAe,GAAGA;IACzB;AACF;AAyBA;;;CAGC,GACD,6DAA6D;AAC7D,SAASE,kBACPC,YAAiC,EACjCC,aAAuB,EACvBC,WAA4C;IAE5C,mCAAmC;IACnC,IAAIF,aAAaG,QAAQ,CAACC,OAAO,CAACH,mBAAmB,CAAC,GAAG;QACvDD,aAAaG,QAAQ,CAACE,IAAI,CAACJ;IAC7B;IAEA,0CAA0C;IAC1C,IAAIC,eAAeA,YAAYI,OAAO,CAACF,OAAO,CAACJ,aAAaO,EAAE,MAAM,CAAC,GAAG;QACtEL,YAAYI,OAAO,CAACD,IAAI,CAACL,aAAaO,EAAE;IAC1C;AACF;AAEA,SAASC,sBAAsBX,eAA2B;IACxD,OAAO,CAAC,kBAAkB,EAAEA,gBAAgBY,IAAI,CAAC,SAAS;AAC5D;AAEA;;;;;;;;CAQC,GACD,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C,MAAMiE,8BACJD,mCAAmC/D;IAErC,oDAAoD;IACpD,MAAM,EAAEyE,qBAAqB,EAAE,GAAGF,aAChCvE,iBACAwE,iBACAvE;IAGF,IAAI2F;IAEJ,SAASyB,YAAYO,GAAQ;QAC3B,IAAI,CAAChC,OAAOA,QAAQgC,KAAI,mBAAmB;IAC7C;IAEAV,WACElD,6BACAiD,oBACAxC,uBACAxE,sBACA6E,iBACAzG,gBACA8I,qBACAC,0BACAC;IAGF,IAAIzB,OAAO;QACT,MAAMA;IACR;IAEA,uEAAuE;IACvE,IAAIjH,yBAAyBiF,IAAI,GAAG,GAAG;QACrCmE,cACE,IAAInJ,OACJ,IAAIJ,OACJ,EAAE,EACF,IAAIA,OACJsG,iBACAzG,gBACA8I,qBACAC,0BACArH;IAEJ;AACF;AAEA;;;;;;;CAOC,GACD,SAASiI,kCAAkCC,OAc1C;IACC,MAAM,EACJ5B,KAAK,EACLC,QAAQ,EACR9B,eAAe,EACfwC,eAAe,EACfkB,iBAAiB,EACjBC,sBAAsB,EACtBrD,eAAe,EACfzG,cAAc,EACd0B,qBAAqB,EACtB,GAAGkI;IAEJ,MAAM,EAAEjI,eAAe,EAAEC,oBAAoB,EAAEgH,kBAAkB,EAAE,GACjEF,uBACEV,OACAC,UACAU,iBACAjH;IAGJgI,cACE/H,iBACAC,sBACAuE,iBACAyC,oBACAnC,iBACAzG,gBACA6J,mBACAC,wBACApI;AAEJ","ignoreList":[0]}}, {"offset": {"line": 1533, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/dev-base.ts"],"sourcesContent":["/// \n/// \n\ninterface TurbopackDevContext extends TurbopackBrowserBaseContext {\n k: RefreshContext\n}\n\nconst devContextPrototype = Context.prototype as TurbopackDevContext\n\n/**\n * This file contains runtime types and functions that are shared between all\n * Turbopack *development* ECMAScript runtimes.\n *\n * It will be appended to the runtime code of each runtime right after the\n * shared runtime utils.\n */\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n// Assign browser's module cache and runtime modules to shared HMR state\ndevModuleCache = Object.create(null)\ndevContextPrototype.c = devModuleCache\nruntimeModules = new Set()\n\n// Set flag to indicate we use ModuleWithDirection\ncreateModuleWithDirectionFlag = true\n\n// This file must not use `import` and `export` statements. Otherwise, it\n// becomes impossible to augment interfaces declared in ``d files\n// (e.g. `Module`). Hence, the need for `import()` here.\ntype RefreshRuntimeGlobals =\n import('@next/react-refresh-utils/dist/runtime').RefreshRuntimeGlobals\n\ndeclare var $RefreshHelpers$: RefreshRuntimeGlobals['$RefreshHelpers$']\ndeclare var $RefreshReg$: RefreshRuntimeGlobals['$RefreshReg$']\ndeclare var $RefreshSig$: RefreshRuntimeGlobals['$RefreshSig$']\ndeclare var $RefreshInterceptModuleExecution$: RefreshRuntimeGlobals['$RefreshInterceptModuleExecution$']\n\ntype RefreshContext = {\n register: RefreshRuntimeGlobals['$RefreshReg$']\n signature: RefreshRuntimeGlobals['$RefreshSig$']\n registerExports: typeof registerExportsAndSetupBoundaryForReactRefresh\n}\n\ntype RefreshHelpers = RefreshRuntimeGlobals['$RefreshHelpers$']\n\ntype ModuleFactory = (\n this: Module['exports'],\n context: TurbopackDevContext\n) => unknown\n\ninterface DevRuntimeBackend {\n reloadChunk?: (chunkUrl: ChunkUrl) => Promise\n unloadChunk?: (chunkUrl: ChunkUrl) => void\n restart: () => void\n}\n\n/**\n * Map from module ID to the chunks that contain this module.\n *\n * In HMR, we need to keep track of which modules are contained in which so\n * chunks. This is so we don't eagerly dispose of a module when it is removed\n * from chunk A, but still exists in chunk B.\n */\nconst moduleChunksMap: Map> = new Map()\n/**\n * Map from a chunk path to all modules it contains.\n */\nconst chunkModulesMap: Map> = new Map()\n/**\n * Chunk lists that contain a runtime. When these chunk lists receive an update\n * that can't be reconciled with the current state of the page, we need to\n * reload the runtime entirely.\n */\nconst runtimeChunkLists: Set = new Set()\n/**\n * Map from a chunk list to the chunk paths it contains.\n */\nconst chunkListChunksMap: Map> = new Map()\n/**\n * Map from a chunk path to the chunk lists it belongs to.\n */\nconst chunkChunkListsMap: Map> = new Map()\n\n/**\n * Gets or instantiates a runtime module.\n */\n// @ts-ignore\nfunction getOrInstantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): Module {\n const module = devModuleCache[moduleId]\n if (module) {\n if (module.error) {\n throw module.error\n }\n return module\n }\n\n // @ts-ignore\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it if it is not cached.\n */\n// @ts-ignore Defined in `runtime-utils.ts`\nconst getOrInstantiateModuleFromParent: GetOrInstantiateModuleFromParent<\n HotModule\n> = (id, sourceModule) => {\n if (!sourceModule.hot.active) {\n console.warn(\n `Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`\n )\n }\n\n const module = devModuleCache[id]\n\n if (sourceModule.children.indexOf(id) === -1) {\n sourceModule.children.push(id)\n }\n\n if (module) {\n if (module.error) {\n throw module.error\n }\n\n if (module.parents.indexOf(sourceModule.id) === -1) {\n module.parents.push(sourceModule.id)\n }\n\n return module\n }\n\n return instantiateModule(id, SourceType.Parent, sourceModule.id)\n}\n\nfunction DevContext(\n this: TurbopackDevContext,\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n) {\n Context.call(this, module, exports)\n this.k = refresh\n}\nDevContext.prototype = Context.prototype\n\ntype DevContextConstructor = {\n new (\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n ): TurbopackDevContext\n}\n\nfunction instantiateModule(\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): Module {\n // Browser: creates base HotModule object (hot API added by shared code)\n const createModuleObjectFn = (id: ModuleId) => {\n return createModuleObject(id) as HotModule\n }\n\n // Browser: creates DevContext with refresh\n const createContext = (\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n ) => {\n return new (DevContext as any as DevContextConstructor)(\n module,\n exports,\n refresh\n )\n }\n\n // Use shared instantiation logic (includes hot API setup)\n return instantiateModuleShared(\n moduleId,\n sourceType,\n sourceData,\n moduleFactories,\n devModuleCache,\n runtimeModules,\n createModuleObjectFn,\n createContext,\n runModuleExecutionHooks\n )\n}\n\nconst DUMMY_REFRESH_CONTEXT = {\n register: (_type: unknown, _id: unknown) => {},\n signature: () => (_type: unknown) => {},\n registerExports: (_module: unknown, _helpers: unknown) => {},\n}\n\n/**\n * NOTE(alexkirsz) Webpack has a \"module execution\" interception hook that\n * Next.js' React Refresh runtime hooks into to add module context to the\n * refresh registry.\n */\nfunction runModuleExecutionHooks(\n module: HotModule,\n executeModule: (ctx: RefreshContext) => void\n) {\n if (typeof globalThis.$RefreshInterceptModuleExecution$ === 'function') {\n const cleanupReactRefreshIntercept =\n globalThis.$RefreshInterceptModuleExecution$(module.id)\n try {\n executeModule({\n register: globalThis.$RefreshReg$,\n signature: globalThis.$RefreshSig$,\n registerExports: registerExportsAndSetupBoundaryForReactRefresh,\n })\n } finally {\n // Always cleanup the intercept, even if module execution failed.\n cleanupReactRefreshIntercept()\n }\n } else {\n // If the react refresh hooks are not installed we need to bind dummy functions.\n // This is expected when running in a Web Worker. It is also common in some of\n // our test environments.\n executeModule(DUMMY_REFRESH_CONTEXT)\n }\n}\n\n/**\n * This is adapted from https://github.com/vercel/next.js/blob/3466862d9dc9c8bb3131712134d38757b918d1c0/packages/react-refresh-utils/internal/ReactRefreshModule.runtime.ts\n */\nfunction registerExportsAndSetupBoundaryForReactRefresh(\n module: HotModule,\n helpers: RefreshHelpers\n) {\n const currentExports = module.exports\n const prevExports = module.hot.data.prevExports ?? null\n\n helpers.registerExportsForReactRefresh(currentExports, module.id)\n\n // A module can be accepted automatically based on its exports, e.g. when\n // it is a Refresh Boundary.\n if (helpers.isReactRefreshBoundary(currentExports)) {\n // Save the previous exports on update, so we can compare the boundary\n // signatures.\n module.hot.dispose((data) => {\n data.prevExports = currentExports\n })\n // Unconditionally accept an update to this module, we'll check if it's\n // still a Refresh Boundary later.\n module.hot.accept()\n\n // This field is set when the previous version of this module was a\n // Refresh Boundary, letting us know we need to check for invalidation or\n // enqueue an update.\n if (prevExports !== null) {\n // A boundary can become ineligible if its exports are incompatible\n // with the previous exports.\n //\n // For example, if you add/remove/change exports, we'll want to\n // re-execute the importing modules, and force those components to\n // re-render. Similarly, if you convert a class component to a\n // function, we want to invalidate the boundary.\n if (\n helpers.shouldInvalidateReactRefreshBoundary(\n helpers.getRefreshBoundarySignature(prevExports),\n helpers.getRefreshBoundarySignature(currentExports)\n )\n ) {\n module.hot.invalidate()\n } else {\n helpers.scheduleUpdate()\n }\n }\n } else {\n // Since we just executed the code for the module, it's possible that the\n // new exports made it ineligible for being a boundary.\n // We only care about the case when we were _previously_ a boundary,\n // because we already accepted this update (accidental side effect).\n const isNoLongerABoundary = prevExports !== null\n if (isNoLongerABoundary) {\n module.hot.invalidate()\n }\n }\n}\n\n/**\n * Adds, deletes, and moves modules between chunks. This must happen before the\n * dispose phase as it needs to know which modules were removed from all chunks,\n * which we can only compute *after* taking care of added and moved modules.\n */\nfunction updateChunksPhase(\n chunksAddedModules: Map>,\n chunksDeletedModules: Map>\n): { disposedModules: Set } {\n for (const [chunkPath, addedModuleIds] of chunksAddedModules) {\n for (const moduleId of addedModuleIds) {\n addModuleToChunk(moduleId, chunkPath)\n }\n }\n\n const disposedModules: Set = new Set()\n for (const [chunkPath, addedModuleIds] of chunksDeletedModules) {\n for (const moduleId of addedModuleIds) {\n if (removeModuleFromChunk(moduleId, chunkPath)) {\n disposedModules.add(moduleId)\n }\n }\n }\n\n return { disposedModules }\n}\n\nfunction applyUpdate(update: PartialUpdate) {\n switch (update.type) {\n case 'ChunkListUpdate':\n applyChunkListUpdate(update)\n break\n default:\n invariant(update, (update) => `Unknown update type: ${update.type}`)\n }\n}\n\nfunction applyChunkListUpdate(update: ChunkListUpdate) {\n if (update.merged != null) {\n for (const merged of update.merged) {\n switch (merged.type) {\n case 'EcmascriptMergedUpdate':\n applyEcmascriptMergedUpdate(merged)\n break\n default:\n invariant(merged, (merged) => `Unknown merged type: ${merged.type}`)\n }\n }\n }\n\n if (update.chunks != null) {\n for (const [chunkPath, chunkUpdate] of Object.entries(\n update.chunks\n ) as Array<[ChunkPath, ChunkUpdate]>) {\n const chunkUrl = getChunkRelativeUrl(chunkPath)\n\n switch (chunkUpdate.type) {\n case 'added':\n BACKEND.loadChunkCached(SourceType.Update, chunkUrl)\n break\n case 'total':\n DEV_BACKEND.reloadChunk?.(chunkUrl)\n break\n case 'deleted':\n DEV_BACKEND.unloadChunk?.(chunkUrl)\n break\n case 'partial':\n invariant(\n chunkUpdate.instruction,\n (instruction) =>\n `Unknown partial instruction: ${JSON.stringify(instruction)}.`\n )\n break\n default:\n invariant(\n chunkUpdate,\n (chunkUpdate) => `Unknown chunk update type: ${chunkUpdate.type}`\n )\n }\n }\n }\n}\n\nfunction applyEcmascriptMergedUpdate(update: EcmascriptMergedUpdate) {\n // Browser-specific chunk management phase\n const { entries = {}, chunks = {} } = update\n const { added, modified, chunksAdded, chunksDeleted } = computeChangedModules(\n entries,\n chunks,\n chunkModulesMap\n )\n const { disposedModules } = updateChunksPhase(chunksAdded, chunksDeleted)\n\n // Use shared HMR update implementation\n applyEcmascriptMergedUpdateShared({\n added,\n modified,\n disposedModules,\n evalModuleEntry: _eval, // browser's eval with source maps\n instantiateModule, // now wraps shared logic\n applyModuleFactoryName,\n moduleFactories,\n devModuleCache,\n autoAcceptRootModules: false,\n })\n}\n\nfunction handleApply(chunkListPath: ChunkListPath, update: ServerMessage) {\n switch (update.type) {\n case 'partial': {\n // This indicates that the update is can be applied to the current state of the application.\n applyUpdate(update.instruction)\n break\n }\n case 'restart': {\n // This indicates that there is no way to apply the update to the\n // current state of the application, and that the application must be\n // restarted.\n DEV_BACKEND.restart()\n break\n }\n case 'notFound': {\n // This indicates that the chunk list no longer exists: either the dynamic import which created it was removed,\n // or the page itself was deleted.\n // If it is a dynamic import, we simply discard all modules that the chunk has exclusive access to.\n // If it is a runtime chunk list, we restart the application.\n if (runtimeChunkLists.has(chunkListPath)) {\n DEV_BACKEND.restart()\n } else {\n disposeChunkList(chunkListPath)\n }\n break\n }\n default:\n throw new Error(`Unknown update type: ${update.type}`)\n }\n}\n\n/**\n * Removes a module from a chunk.\n * Returns `true` if there are no remaining chunks including this module.\n */\nfunction removeModuleFromChunk(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): boolean {\n const moduleChunks = moduleChunksMap.get(moduleId)!\n moduleChunks.delete(chunkPath)\n\n const chunkModules = chunkModulesMap.get(chunkPath)!\n chunkModules.delete(moduleId)\n\n const noRemainingModules = chunkModules.size === 0\n if (noRemainingModules) {\n chunkModulesMap.delete(chunkPath)\n }\n\n const noRemainingChunks = moduleChunks.size === 0\n if (noRemainingChunks) {\n moduleChunksMap.delete(moduleId)\n }\n\n return noRemainingChunks\n}\n\n/**\n * Disposes of a chunk list and its corresponding exclusive chunks.\n */\nfunction disposeChunkList(chunkListPath: ChunkListPath): boolean {\n const chunkPaths = chunkListChunksMap.get(chunkListPath)\n if (chunkPaths == null) {\n return false\n }\n chunkListChunksMap.delete(chunkListPath)\n\n for (const chunkPath of chunkPaths) {\n const chunkChunkLists = chunkChunkListsMap.get(chunkPath)!\n chunkChunkLists.delete(chunkListPath)\n\n if (chunkChunkLists.size === 0) {\n chunkChunkListsMap.delete(chunkPath)\n disposeChunk(chunkPath)\n }\n }\n\n // We must also dispose of the chunk list's chunk itself to ensure it may\n // be reloaded properly in the future.\n const chunkListUrl = getChunkRelativeUrl(chunkListPath)\n\n DEV_BACKEND.unloadChunk?.(chunkListUrl)\n\n return true\n}\n\n/**\n * Disposes of a chunk and its corresponding exclusive modules.\n *\n * @returns Whether the chunk was disposed of.\n */\nfunction disposeChunk(chunkPath: ChunkPath): boolean {\n const chunkUrl = getChunkRelativeUrl(chunkPath)\n // This should happen whether the chunk has any modules in it or not.\n // For instance, CSS chunks have no modules in them, but they still need to be unloaded.\n DEV_BACKEND.unloadChunk?.(chunkUrl)\n\n const chunkModules = chunkModulesMap.get(chunkPath)\n if (chunkModules == null) {\n return false\n }\n chunkModules.delete(chunkPath)\n\n for (const moduleId of chunkModules) {\n const moduleChunks = moduleChunksMap.get(moduleId)!\n moduleChunks.delete(chunkPath)\n\n const noRemainingChunks = moduleChunks.size === 0\n if (noRemainingChunks) {\n moduleChunksMap.delete(moduleId)\n disposeModule(moduleId, 'clear')\n availableModules.delete(moduleId)\n }\n }\n\n return true\n}\n\n/**\n * Adds a module to a chunk.\n */\nfunction addModuleToChunk(moduleId: ModuleId, chunkPath: ChunkPath) {\n let moduleChunks = moduleChunksMap.get(moduleId)\n if (!moduleChunks) {\n moduleChunks = new Set([chunkPath])\n moduleChunksMap.set(moduleId, moduleChunks)\n } else {\n moduleChunks.add(chunkPath)\n }\n\n let chunkModules = chunkModulesMap.get(chunkPath)\n if (!chunkModules) {\n chunkModules = new Set([moduleId])\n chunkModulesMap.set(chunkPath, chunkModules)\n } else {\n chunkModules.add(moduleId)\n }\n}\n\n/**\n * Marks a chunk list as a runtime chunk list. There can be more than one\n * runtime chunk list. For instance, integration tests can have multiple chunk\n * groups loaded at runtime, each with its own chunk list.\n */\nfunction markChunkListAsRuntime(chunkListPath: ChunkListPath) {\n runtimeChunkLists.add(chunkListPath)\n}\n\nfunction registerChunk(registration: ChunkRegistration) {\n const chunk = getChunkFromRegistration(registration[0]) as\n | ChunkPath\n | ChunkScript\n let runtimeParams: RuntimeParams | undefined\n // When bootstrapping we are passed a single runtimeParams object so we can distinguish purely based on length\n if (registration.length === 2) {\n runtimeParams = registration[1] as RuntimeParams\n } else {\n let chunkPath = getPathFromScript(chunk)\n runtimeParams = undefined\n installCompressedModuleFactories(\n registration as CompressedModuleFactories,\n /* offset= */ 1,\n moduleFactories,\n (id: ModuleId) => addModuleToChunk(id, chunkPath)\n )\n }\n return BACKEND.registerChunk(chunk, runtimeParams)\n}\n\n/**\n * Subscribes to chunk list updates from the update server and applies them.\n */\nfunction registerChunkList(chunkList: ChunkList) {\n const chunkListScript = getChunkFromRegistration(chunkList.script) as\n | ChunkListPath\n | ChunkListScript\n const chunkListPath = getPathFromScript(chunkListScript)\n // The \"chunk\" is also registered to finish the loading in the backend\n BACKEND.registerChunk(chunkListPath as string as ChunkPath)\n globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS!.push([\n chunkListPath,\n handleApply.bind(null, chunkListPath),\n ])\n\n // Adding chunks to chunk lists and vice versa.\n const chunkPaths = new Set(chunkList.chunks.map(getChunkPath))\n chunkListChunksMap.set(chunkListPath, chunkPaths)\n for (const chunkPath of chunkPaths) {\n let chunkChunkLists = chunkChunkListsMap.get(chunkPath)\n if (!chunkChunkLists) {\n chunkChunkLists = new Set([chunkListPath])\n chunkChunkListsMap.set(chunkPath, chunkChunkLists)\n } else {\n chunkChunkLists.add(chunkListPath)\n }\n }\n\n if (chunkList.source === 'entry') {\n markChunkListAsRuntime(chunkListPath)\n }\n}\n\nglobalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= []\n"],"names":["devContextPrototype","Context","prototype","devModuleCache","Object","create","c","runtimeModules","Set","createModuleWithDirectionFlag","moduleChunksMap","Map","chunkModulesMap","runtimeChunkLists","chunkListChunksMap","chunkChunkListsMap","getOrInstantiateRuntimeModule","chunkPath","moduleId","module","error","instantiateModule","SourceType","Runtime","getOrInstantiateModuleFromParent","id","sourceModule","hot","active","console","warn","children","indexOf","push","parents","Parent","DevContext","exports","refresh","call","k","sourceType","sourceData","createModuleObjectFn","createModuleObject","createContext","instantiateModuleShared","moduleFactories","runModuleExecutionHooks","DUMMY_REFRESH_CONTEXT","register","_type","_id","signature","registerExports","_module","_helpers","executeModule","globalThis","$RefreshInterceptModuleExecution$","cleanupReactRefreshIntercept","$RefreshReg$","$RefreshSig$","registerExportsAndSetupBoundaryForReactRefresh","helpers","currentExports","prevExports","data","registerExportsForReactRefresh","isReactRefreshBoundary","dispose","accept","shouldInvalidateReactRefreshBoundary","getRefreshBoundarySignature","invalidate","scheduleUpdate","isNoLongerABoundary","updateChunksPhase","chunksAddedModules","chunksDeletedModules","addedModuleIds","addModuleToChunk","disposedModules","removeModuleFromChunk","add","applyUpdate","update","type","applyChunkListUpdate","invariant","merged","applyEcmascriptMergedUpdate","chunks","chunkUpdate","entries","chunkUrl","getChunkRelativeUrl","BACKEND","loadChunkCached","Update","DEV_BACKEND","reloadChunk","unloadChunk","instruction","JSON","stringify","added","modified","chunksAdded","chunksDeleted","computeChangedModules","applyEcmascriptMergedUpdateShared","evalModuleEntry","_eval","applyModuleFactoryName","autoAcceptRootModules","handleApply","chunkListPath","restart","has","disposeChunkList","Error","moduleChunks","get","delete","chunkModules","noRemainingModules","size","noRemainingChunks","chunkPaths","chunkChunkLists","disposeChunk","chunkListUrl","disposeModule","availableModules","set","markChunkListAsRuntime","registerChunk","registration","chunk","getChunkFromRegistration","runtimeParams","length","getPathFromScript","undefined","installCompressedModuleFactories","registerChunkList","chunkList","chunkListScript","script","TURBOPACK_CHUNK_UPDATE_LISTENERS","bind","map","getChunkPath","source"],"mappings":"AAAA,iEAAiE;AACjE,kEAAkE;AAMlE,MAAMA,sBAAsBC,QAAQC,SAAS;AAE7C;;;;;;CAMC,GACD,oDAAoD,GAEpD,wEAAwE;AACxEC,iBAAiBC,OAAOC,MAAM,CAAC;AAC/BL,oBAAoBM,CAAC,GAAGH;AACxBI,iBAAiB,IAAIC;AAErB,kDAAkD;AAClDC,gCAAgC;AAgChC;;;;;;CAMC,GACD,MAAMC,kBAAiD,IAAIC;AAC3D;;CAEC,GACD,MAAMC,kBAAiD,IAAID;AAC3D;;;;CAIC,GACD,MAAME,oBAAwC,IAAIL;AAClD;;CAEC,GACD,MAAMM,qBAAyD,IAAIH;AACnE;;CAEC,GACD,MAAMI,qBAAyD,IAAIJ;AAEnE;;CAEC,GACD,aAAa;AACb,SAASK,8BACPC,SAAoB,EACpBC,QAAkB;IAElB,MAAMC,SAAShB,cAAc,CAACe,SAAS;IACvC,IAAIC,QAAQ;QACV,IAAIA,OAAOC,KAAK,EAAE;YAChB,MAAMD,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,YAAY,CAAC,EAAE;IACjC,OAAO;QACL,IAAIzH,YAAY8H,kBAAkBJ;QAClCE,gBAAgBG;QAChBC,iCACEP,cACA,WAAW,GAAG,GACd3F,iBACA,CAACtB,KAAiBwD,iBAAiBxD,IAAIR;IAE3C;IACA,OAAOgF,QAAQwC,aAAa,CAACE,OAAOE;AACtC;AAEA;;CAEC,GACD,SAASK,kBAAkBC,SAAoB;IAC7C,MAAMC,kBAAkBR,yBAAyBO,UAAUE,MAAM;IAGjE,MAAMhC,gBAAgB0B,kBAAkBK;IACxC,sEAAsE;IACtEnD,QAAQwC,aAAa,CAACpB;IACtB3D,WAAW4F,gCAAgC,CAAErH,IAAI,CAAC;QAChDoF;QACAD,YAAYmC,IAAI,CAAC,MAAMlC;KACxB;IAED,+CAA+C;IAC/C,MAAMY,aAAa,IAAIzH,IAAI2I,UAAUvD,MAAM,CAAC4D,GAAG,CAACC;IAChD3I,mBAAmByH,GAAG,CAAClB,eAAeY;IACtC,KAAK,MAAMhH,aAAagH,WAAY;QAClC,IAAIC,kBAAkBnH,mBAAmB4G,GAAG,CAAC1G;QAC7C,IAAI,CAACiH,iBAAiB;YACpBA,kBAAkB,IAAI1H,IAAI;gBAAC6G;aAAc;YACzCtG,mBAAmBwH,GAAG,CAACtH,WAAWiH;QACpC,OAAO;YACLA,gBAAgB9C,GAAG,CAACiC;QACtB;IACF;IAEA,IAAI8B,UAAUO,MAAM,KAAK,SAAS;QAChClB,uBAAuBnB;IACzB;AACF;AAEA3D,WAAW4F,gCAAgC,KAAK,EAAE","ignoreList":[0]}}, - {"offset": {"line": 1950, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/runtime-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack ECMAScript DOM runtime.\n *\n * It will be appended to the base runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\nfunction getAssetSuffixFromScriptSrc() {\n // TURBOPACK_ASSET_SUFFIX is set in web workers\n return (\n (self.TURBOPACK_ASSET_SUFFIX ??\n document?.currentScript\n ?.getAttribute?.('src')\n ?.replace(/^(.*(?=\\?)|^.*$)/, '')) ||\n ''\n )\n}\n\ntype ChunkResolver = {\n resolved: boolean\n loadingStarted: boolean\n resolve: () => void\n reject: (error?: Error) => void\n promise: Promise\n}\n\nlet BACKEND: RuntimeBackend\n\n/**\n * Maps chunk paths to the corresponding resolver.\n */\nconst chunkResolvers: Map = new Map()\n\n;(() => {\n BACKEND = {\n async registerChunk(chunk, params) {\n let chunkPath = getPathFromScript(chunk)\n let chunkUrl = getUrlFromScript(chunk)\n\n const resolver = getOrCreateResolver(chunkUrl)\n resolver.resolve()\n\n if (params == null) {\n return\n }\n\n for (const otherChunkData of params.otherChunks) {\n const otherChunkPath = getChunkPath(otherChunkData)\n const otherChunkUrl = getChunkRelativeUrl(otherChunkPath)\n\n // Chunk might have started loading, so we want to avoid triggering another load.\n getOrCreateResolver(otherChunkUrl)\n }\n\n // This waits for chunks to be loaded, but also marks included items as available.\n await Promise.all(\n params.otherChunks.map((otherChunkData) =>\n loadInitialChunk(chunkPath, otherChunkData)\n )\n )\n\n if (params.runtimeModuleIds.length > 0) {\n for (const moduleId of params.runtimeModuleIds) {\n getOrInstantiateRuntimeModule(chunkPath, moduleId)\n }\n }\n },\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n loadChunkCached(sourceType: SourceType, chunkUrl: ChunkUrl) {\n return doLoadChunk(sourceType, chunkUrl)\n },\n\n async loadWebAssembly(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n const { instance } = await WebAssembly.instantiateStreaming(\n req,\n importsObj\n )\n\n return instance.exports\n },\n\n async loadWebAssemblyModule(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n return await WebAssembly.compileStreaming(req)\n },\n }\n\n function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {\n let resolver = chunkResolvers.get(chunkUrl)\n if (!resolver) {\n let resolve: () => void\n let reject: (error?: Error) => void\n const promise = new Promise((innerResolve, innerReject) => {\n resolve = innerResolve\n reject = innerReject\n })\n resolver = {\n resolved: false,\n loadingStarted: false,\n promise,\n resolve: () => {\n resolver!.resolved = true\n resolve()\n },\n reject: reject!,\n }\n chunkResolvers.set(chunkUrl, resolver)\n }\n return resolver\n }\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n function doLoadChunk(sourceType: SourceType, chunkUrl: ChunkUrl) {\n const resolver = getOrCreateResolver(chunkUrl)\n if (resolver.loadingStarted) {\n return resolver.promise\n }\n\n if (sourceType === SourceType.Runtime) {\n // We don't need to load chunks references from runtime code, as they're already\n // present in the DOM.\n resolver.loadingStarted = true\n\n if (isCss(chunkUrl)) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n\n // We need to wait for JS chunks to register themselves within `registerChunk`\n // before we can start instantiating runtime modules, hence the absence of\n // `resolver.resolve()` in this branch.\n\n return resolver.promise\n }\n\n if (typeof importScripts === 'function') {\n // We're in a web worker\n if (isCss(chunkUrl)) {\n // ignore\n } else if (isJs(chunkUrl)) {\n self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl)\n importScripts(chunkUrl)\n } else {\n throw new Error(\n `can't infer type of chunk from URL ${chunkUrl} in worker`\n )\n }\n } else {\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n if (previousLinks.length > 0) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n } else {\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n link.href = chunkUrl\n link.onerror = () => {\n resolver.reject()\n }\n link.onload = () => {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(link)\n }\n } else if (isJs(chunkUrl)) {\n const previousScripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n if (previousScripts.length > 0) {\n // There is this edge where the script already failed loading, but we\n // can't detect that. The Promise will never resolve in this case.\n for (const script of Array.from(previousScripts)) {\n script.addEventListener('error', () => {\n resolver.reject()\n })\n }\n } else {\n const script = document.createElement('script')\n script.src = chunkUrl\n // We'll only mark the chunk as loaded once the script has been executed,\n // which happens in `registerChunk`. Hence the absence of `resolve()` in\n // this branch.\n script.onerror = () => {\n resolver.reject()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(script)\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n }\n\n resolver.loadingStarted = true\n return resolver.promise\n }\n\n function fetchWebAssembly(wasmChunkPath: ChunkPath) {\n return fetch(getChunkRelativeUrl(wasmChunkPath))\n }\n})()\n"],"names":["getAssetSuffixFromScriptSrc","self","TURBOPACK_ASSET_SUFFIX","document","currentScript","getAttribute","replace","BACKEND","chunkResolvers","Map","registerChunk","chunk","params","chunkPath","getPathFromScript","chunkUrl","getUrlFromScript","resolver","getOrCreateResolver","resolve","otherChunkData","otherChunks","otherChunkPath","getChunkPath","otherChunkUrl","getChunkRelativeUrl","Promise","all","map","loadInitialChunk","runtimeModuleIds","length","moduleId","getOrInstantiateRuntimeModule","loadChunkCached","sourceType","doLoadChunk","loadWebAssembly","_sourceType","_sourceData","wasmChunkPath","_edgeModule","importsObj","req","fetchWebAssembly","instance","WebAssembly","instantiateStreaming","exports","loadWebAssemblyModule","compileStreaming","get","reject","promise","innerResolve","innerReject","resolved","loadingStarted","set","SourceType","Runtime","isCss","importScripts","isJs","TURBOPACK_NEXT_CHUNK_URLS","push","Error","decodedChunkUrl","decodeURI","previousLinks","querySelectorAll","link","createElement","rel","href","onerror","onload","head","appendChild","previousScripts","script","Array","from","addEventListener","src","fetch"],"mappings":"AAAA;;;;CAIC,GAED,oDAAoD,GAEpD,sEAAsE;AACtE,mEAAmE;AAEnE,SAASA;IACP,+CAA+C;IAC/C,OACE,CAACC,KAAKC,sBAAsB,IAC1BC,UAAUC,eACNC,eAAe,QACfC,QAAQ,oBAAoB,GAAG,KACrC;AAEJ;AAUA,IAAIC;AAEJ;;CAEC,GACD,MAAMC,iBAA+C,IAAIC;AAExD,CAAC;IACAF,UAAU;QACR,MAAMG,eAAcC,KAAK,EAAEC,MAAM;YAC/B,IAAIC,YAAYC,kBAAkBH;YAClC,IAAII,WAAWC,iBAAiBL;YAEhC,MAAMM,WAAWC,oBAAoBH;YACrCE,SAASE,OAAO;YAEhB,IAAIP,UAAU,MAAM;gBAClB;YACF;YAEA,KAAK,MAAMQ,kBAAkBR,OAAOS,WAAW,CAAE;gBAC/C,MAAMC,iBAAiBC,aAAaH;gBACpC,MAAMI,gBAAgBC,oBAAoBH;gBAE1C,iFAAiF;gBACjFJ,oBAAoBM;YACtB;YAEA,kFAAkF;YAClF,MAAME,QAAQC,GAAG,CACff,OAAOS,WAAW,CAACO,GAAG,CAAC,CAACR,iBACtBS,iBAAiBhB,WAAWO;YAIhC,IAAIR,OAAOkB,gBAAgB,CAACC,MAAM,GAAG,GAAG;gBACtC,KAAK,MAAMC,YAAYpB,OAAOkB,gBAAgB,CAAE;oBAC9CG,8BAA8BpB,WAAWmB;gBAC3C;YAC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BAC9B,qEAAqE;oBACrE,kEAAkE;oBAClE,KAAK,MAAMiD,UAAUC,MAAMC,IAAI,CAACH,iBAAkB;wBAChDC,OAAOG,gBAAgB,CAAC,SAAS;4BAC/BlE,SAASmC,MAAM;wBACjB;oBACF;gBACF,OAAO;oBACL,MAAM4B,SAAS7E,SAASqE,aAAa,CAAC;oBACtCQ,OAAOI,GAAG,GAAGrE;oBACb,yEAAyE;oBACzE,wEAAwE;oBACxE,eAAe;oBACfiE,OAAOL,OAAO,GAAG;wBACf1D,SAASmC,MAAM;oBACjB;oBACA,kDAAkD;oBAClDjD,SAAS0E,IAAI,CAACC,WAAW,CAACE;gBAC5B;YACF,OAAO;gBACL,MAAM,IAAId,MAAM,CAAC,mCAAmC,EAAEnD,UAAU;YAClE;QACF;QAEAE,SAASwC,cAAc,GAAG;QAC1B,OAAOxC,SAASoC,OAAO;IACzB;IAEA,SAAST,iBAAiBJ,aAAwB;QAChD,OAAO6C,MAAM5D,oBAAoBe;IACnC;AACF,CAAC","ignoreList":[0]}}, - {"offset": {"line": 2116, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/dev-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack development\n * ECMAScript DOM runtime.\n *\n * It will be appended to the base development runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n/// \n/// \n\nlet DEV_BACKEND: DevRuntimeBackend\n;(() => {\n DEV_BACKEND = {\n unloadChunk(chunkUrl) {\n deleteResolver(chunkUrl)\n\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const links = document.querySelectorAll(\n `link[href=\"${chunkUrl}\"],link[href^=\"${chunkUrl}?\"],link[href=\"${decodedChunkUrl}\"],link[href^=\"${decodedChunkUrl}?\"]`\n )\n for (const link of Array.from(links)) {\n link.remove()\n }\n } else if (isJs(chunkUrl)) {\n // Unloading a JS chunk would have no effect, as it lives in the JS\n // runtime once evaluated.\n // However, we still want to remove the script tag from the DOM to keep\n // the HTML somewhat consistent from the user's perspective.\n const scripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n for (const script of Array.from(scripts)) {\n script.remove()\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n },\n\n reloadChunk(chunkUrl) {\n return new Promise((resolve, reject) => {\n if (!isCss(chunkUrl)) {\n reject(new Error('The DOM backend can only reload CSS chunks'))\n return\n }\n\n const decodedChunkUrl = decodeURI(chunkUrl)\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n\n if (previousLinks.length === 0) {\n reject(new Error(`No link element found for chunk ${chunkUrl}`))\n return\n }\n\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n\n if (navigator.userAgent.includes('Firefox')) {\n // Firefox won't reload CSS files that were previously loaded on the current page,\n // we need to add a query param to make sure CSS is actually reloaded from the server.\n //\n // I believe this is this issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506\n //\n // Safari has a similar issue, but only if you have a `` tag\n // pointing to the same URL as the stylesheet: https://bugs.webkit.org/show_bug.cgi?id=187726\n link.href = `${chunkUrl}?ts=${Date.now()}`\n } else {\n link.href = chunkUrl\n }\n\n link.onerror = () => {\n reject()\n }\n link.onload = () => {\n // First load the new CSS, then remove the old ones. This prevents visible\n // flickering that would happen in-between removing the previous CSS and\n // loading the new one.\n for (const previousLink of Array.from(previousLinks))\n previousLink.remove()\n\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolve()\n }\n\n // Make sure to insert the new CSS right after the previous one, so that\n // its precedence is higher.\n previousLinks[0].parentElement!.insertBefore(\n link,\n previousLinks[0].nextSibling\n )\n })\n },\n\n restart: () => self.location.reload(),\n }\n\n function deleteResolver(chunkUrl: ChunkUrl) {\n chunkResolvers.delete(chunkUrl)\n }\n})()\n\nfunction _eval({ code, url, map }: EcmascriptModuleEntry): ModuleFactory {\n code += `\\n\\n//# sourceURL=${encodeURI(\n location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX\n )}`\n if (map) {\n code += `\\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(\n // btoa doesn't handle nonlatin characters, so escape them as \\x sequences\n // See https://stackoverflow.com/a/26603875\n unescape(encodeURIComponent(map))\n )}`\n }\n\n // eslint-disable-next-line no-eval\n return eval(code)\n}\n"],"names":["DEV_BACKEND","unloadChunk","chunkUrl","deleteResolver","decodedChunkUrl","decodeURI","isCss","links","document","querySelectorAll","link","Array","from","remove","isJs","scripts","script","Error","reloadChunk","Promise","resolve","reject","previousLinks","length","createElement","rel","navigator","userAgent","includes","href","Date","now","onerror","onload","previousLink","parentElement","insertBefore","nextSibling","restart","self","location","reload","chunkResolvers","delete","_eval","code","url","map","encodeURI","origin","CHUNK_BASE_PATH","ASSET_SUFFIX","btoa","unescape","encodeURIComponent","eval"],"mappings":"AAAA;;;;;CAKC,GAED,oDAAoD,GAEpD,gDAAgD;AAChD,4CAA4C;AAC5C,iDAAiD;AACjD,0DAA0D;AAE1D,IAAIA;AACH,CAAC;IACAA,cAAc;QACZC,aAAYC,QAAQ;YAClBC,eAAeD;YAEf,gFAAgF;YAChF,MAAME,kBAAkBC,UAAUH;YAElC,IAAII,MAAMJ,WAAW;gBACnB,MAAMK,QAAQC,SAASC,gBAAgB,CACrC,CAAC,WAAW,EAAEP,SAAS,eAAe,EAAEA,SAAS,eAAe,EAAEE,gBAAgB,eAAe,EAAEA,gBAAgB,GAAG,CAAC;gBAEzH,KAAK,MAAMM,QAAQC,MAAMC,IAAI,CAACL,OAAQ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AEAQ,KAAKsB,OAAO,GAAG;oBACbX;gBACF;gBACAX,KAAKuB,MAAM,GAAG;oBACZ,0EAA0E;oBAC1E,wEAAwE;oBACxE,uBAAuB;oBACvB,KAAK,MAAMC,gBAAgBvB,MAAMC,IAAI,CAACU,eACpCY,aAAarB,MAAM;oBAErB,uEAAuE;oBACvE,oBAAoB;oBACpBO;gBACF;gBAEA,wEAAwE;gBACxE,4BAA4B;gBAC5BE,aAAa,CAAC,EAAE,CAACa,aAAa,CAAEC,YAAY,CAC1C1B,MACAY,aAAa,CAAC,EAAE,CAACe,WAAW;YAEhC;QACF;QAEAC,SAAS,IAAMC,KAAKC,QAAQ,CAACC,MAAM;IACrC;IAEA,SAAStC,eAAeD,QAAkB;QACxCwC,eAAeC,MAAM,CAACzC;IACxB;AACF,CAAC;AAED,SAAS0C,MAAM,EAAEC,IAAI,EAAEC,GAAG,EAAEC,GAAG,EAAyB;IACtDF,QAAQ,CAAC,kBAAkB,EAAEG,UAC3BR,SAASS,MAAM,GAAGC,kBAAkBJ,MAAMK,eACzC;IACH,IAAIJ,KAAK;QACPF,QAAQ,CAAC,kEAAkE,EAAEO,KAC3E,0EAA0E;QAC1E,2CAA2C;QAC3CC,SAASC,mBAAmBP,QAC3B;IACL;IAEA,mCAAmC;IACnC,OAAOQ,KAAKV;AACd","ignoreList":[0]}}] + {"offset": {"line": 1950, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/runtime-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack ECMAScript DOM runtime.\n *\n * It will be appended to the base runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\nfunction getAssetSuffixFromScriptSrc() {\n // TURBOPACK_ASSET_SUFFIX is set in web workers\n if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX\n const src = document?.currentScript?.getAttribute?.('src') ?? ''\n const qi = src.indexOf('?')\n return qi >= 0 ? src.slice(qi) : ''\n}\n\ntype ChunkResolver = {\n resolved: boolean\n loadingStarted: boolean\n resolve: () => void\n reject: (error?: Error) => void\n promise: Promise\n}\n\nlet BACKEND: RuntimeBackend\n\n/**\n * Maps chunk paths to the corresponding resolver.\n */\nconst chunkResolvers: Map = new Map()\n\n;(() => {\n BACKEND = {\n async registerChunk(chunk, params) {\n let chunkPath = getPathFromScript(chunk)\n let chunkUrl = getUrlFromScript(chunk)\n\n const resolver = getOrCreateResolver(chunkUrl)\n resolver.resolve()\n\n if (params == null) {\n return\n }\n\n for (const otherChunkData of params.otherChunks) {\n const otherChunkPath = getChunkPath(otherChunkData)\n const otherChunkUrl = getChunkRelativeUrl(otherChunkPath)\n\n // Chunk might have started loading, so we want to avoid triggering another load.\n getOrCreateResolver(otherChunkUrl)\n }\n\n // This waits for chunks to be loaded, but also marks included items as available.\n await Promise.all(\n params.otherChunks.map((otherChunkData) =>\n loadInitialChunk(chunkPath, otherChunkData)\n )\n )\n\n if (params.runtimeModuleIds.length > 0) {\n for (const moduleId of params.runtimeModuleIds) {\n getOrInstantiateRuntimeModule(chunkPath, moduleId)\n }\n }\n },\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n loadChunkCached(sourceType: SourceType, chunkUrl: ChunkUrl) {\n return doLoadChunk(sourceType, chunkUrl)\n },\n\n async loadWebAssembly(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n const { instance } = await WebAssembly.instantiateStreaming(\n req,\n importsObj\n )\n\n return instance.exports\n },\n\n async loadWebAssemblyModule(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n return await WebAssembly.compileStreaming(req)\n },\n }\n\n function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {\n let resolver = chunkResolvers.get(chunkUrl)\n if (!resolver) {\n let resolve: () => void\n let reject: (error?: Error) => void\n const promise = new Promise((innerResolve, innerReject) => {\n resolve = innerResolve\n reject = innerReject\n })\n resolver = {\n resolved: false,\n loadingStarted: false,\n promise,\n resolve: () => {\n resolver!.resolved = true\n resolve()\n },\n reject: reject!,\n }\n chunkResolvers.set(chunkUrl, resolver)\n }\n return resolver\n }\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n function doLoadChunk(sourceType: SourceType, chunkUrl: ChunkUrl) {\n const resolver = getOrCreateResolver(chunkUrl)\n if (resolver.loadingStarted) {\n return resolver.promise\n }\n\n if (sourceType === SourceType.Runtime) {\n // We don't need to load chunks references from runtime code, as they're already\n // present in the DOM.\n resolver.loadingStarted = true\n\n if (isCss(chunkUrl)) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n\n // We need to wait for JS chunks to register themselves within `registerChunk`\n // before we can start instantiating runtime modules, hence the absence of\n // `resolver.resolve()` in this branch.\n\n return resolver.promise\n }\n\n if (typeof importScripts === 'function') {\n // We're in a web worker\n if (isCss(chunkUrl)) {\n // ignore\n } else if (isJs(chunkUrl)) {\n self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl)\n importScripts(chunkUrl)\n } else {\n throw new Error(\n `can't infer type of chunk from URL ${chunkUrl} in worker`\n )\n }\n } else {\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n if (previousLinks.length > 0) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n } else {\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n link.href = chunkUrl\n link.onerror = () => {\n resolver.reject()\n }\n link.onload = () => {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(link)\n }\n } else if (isJs(chunkUrl)) {\n const previousScripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n if (previousScripts.length > 0) {\n // There is this edge where the script already failed loading, but we\n // can't detect that. The Promise will never resolve in this case.\n for (const script of Array.from(previousScripts)) {\n script.addEventListener('error', () => {\n resolver.reject()\n })\n }\n } else {\n const script = document.createElement('script')\n script.src = chunkUrl\n // We'll only mark the chunk as loaded once the script has been executed,\n // which happens in `registerChunk`. Hence the absence of `resolve()` in\n // this branch.\n script.onerror = () => {\n resolver.reject()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(script)\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n }\n\n resolver.loadingStarted = true\n return resolver.promise\n }\n\n function fetchWebAssembly(wasmChunkPath: ChunkPath) {\n return fetch(getChunkRelativeUrl(wasmChunkPath))\n }\n})()\n"],"names":["getAssetSuffixFromScriptSrc","self","TURBOPACK_ASSET_SUFFIX","src","document","currentScript","getAttribute","qi","indexOf","slice","BACKEND","chunkResolvers","Map","registerChunk","chunk","params","chunkPath","getPathFromScript","chunkUrl","getUrlFromScript","resolver","getOrCreateResolver","resolve","otherChunkData","otherChunks","otherChunkPath","getChunkPath","otherChunkUrl","getChunkRelativeUrl","Promise","all","map","loadInitialChunk","runtimeModuleIds","length","moduleId","getOrInstantiateRuntimeModule","loadChunkCached","sourceType","doLoadChunk","loadWebAssembly","_sourceType","_sourceData","wasmChunkPath","_edgeModule","importsObj","req","fetchWebAssembly","instance","WebAssembly","instantiateStreaming","exports","loadWebAssemblyModule","compileStreaming","get","reject","promise","innerResolve","innerReject","resolved","loadingStarted","set","SourceType","Runtime","isCss","importScripts","isJs","TURBOPACK_NEXT_CHUNK_URLS","push","Error","decodedChunkUrl","decodeURI","previousLinks","querySelectorAll","link","createElement","rel","href","onerror","onload","head","appendChild","previousScripts","script","Array","from","addEventListener","fetch"],"mappings":"AAAA;;;;CAIC,GAED,oDAAoD,GAEpD,sEAAsE;AACtE,mEAAmE;AAEnE,SAASA;IACP,+CAA+C;IAC/C,IAAIC,KAAKC,sBAAsB,IAAI,MAAM,OAAOD,KAAKC,sBAAsB;IAC3E,MAAMC,MAAMC,UAAUC,eAAeC,eAAe,UAAU;IAC9D,MAAMC,KAAKJ,IAAIK,OAAO,CAAC;IACvB,OAAOD,MAAM,IAAIJ,IAAIM,KAAK,CAACF,MAAM;AACnC;AAUA,IAAIG;AAEJ;;CAEC,GACD,MAAMC,iBAA+C,IAAIC;AAExD,CAAC;IACAF,UAAU;QACR,MAAMG,eAAcC,KAAK,EAAEC,MAAM;YAC/B,IAAIC,YAAYC,kBAAkBH;YAClC,IAAII,WAAWC,iBAAiBL;YAEhC,MAAMM,WAAWC,oBAAoBH;YACrCE,SAASE,OAAO;YAEhB,IAAIP,UAAU,MAAM;gBAClB;YACF;YAEA,KAAK,MAAMQ,kBAAkBR,OAAOS,WAAW,CAAE;gBAC/C,MAAMC,iBAAiBC,aAAaH;gBACpC,MAAMI,gBAAgBC,oBAAoBH;gBAE1C,iFAAiF;gBACjFJ,oBAAoBM;YACtB;YAEA,kFAAkF;YAClF,MAAME,QAAQC,GAAG,CACff,OAAOS,WAAW,CAACO,GAAG,CAAC,CAACR,iBACtBS,iBAAiBhB,WAAWO;YAIhC,IAAIR,OAAOkB,gBAAgB,CAACC,MAAM,GAAG,GAAG;gBACtC,KAAK,MAAMC,YAAYpB,OAAOkB,gBAAgB,CAAE;oBAC9CG,8BAA8BpB,WAAWmB;g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AG,GAAG;oBAC9B,qEAAqE;oBACrE,kEAAkE;oBAClE,KAAK,MAAMiD,UAAUC,MAAMC,IAAI,CAACH,iBAAkB;wBAChDC,OAAOG,gBAAgB,CAAC,SAAS;4BAC/BlE,SAASmC,MAAM;wBACjB;oBACF;gBACF,OAAO;oBACL,MAAM4B,SAAS/E,SAASuE,aAAa,CAAC;oBACtCQ,OAAOhF,GAAG,GAAGe;oBACb,yEAAyE;oBACzE,wEAAwE;oBACxE,eAAe;oBACfiE,OAAOL,OAAO,GAAG;wBACf1D,SAASmC,MAAM;oBACjB;oBACA,kDAAkD;oBAClDnD,SAAS4E,IAAI,CAACC,WAAW,CAACE;gBAC5B;YACF,OAAO;gBACL,MAAM,IAAId,MAAM,CAAC,mCAAmC,EAAEnD,UAAU;YAClE;QACF;QAEAE,SAASwC,cAAc,GAAG;QAC1B,OAAOxC,SAASoC,OAAO;IACzB;IAEA,SAAST,iBAAiBJ,aAAwB;QAChD,OAAO4C,MAAM3D,oBAAoBe;IACnC;AACF,CAAC","ignoreList":[0]}}, + {"offset": {"line": 2119, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/dev-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack development\n * ECMAScript DOM runtime.\n *\n * It will be appended to the base development runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n/// \n/// \n\nlet DEV_BACKEND: DevRuntimeBackend\n;(() => {\n DEV_BACKEND = {\n unloadChunk(chunkUrl) {\n deleteResolver(chunkUrl)\n\n // Strip query string so we match links regardless of cache-busting\n // params (e.g. ?ts=) that may differ between HMR updates.\n const baseChunkUrl = chunkUrl.split('?')[0]\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedBaseChunkUrl = decodeURI(baseChunkUrl)\n\n if (isCss(chunkUrl)) {\n const links = document.querySelectorAll(\n `link[href=\"${baseChunkUrl}\"],link[href^=\"${baseChunkUrl}?\"],link[href=\"${decodedBaseChunkUrl}\"],link[href^=\"${decodedBaseChunkUrl}?\"]`\n )\n for (const link of Array.from(links)) {\n link.remove()\n }\n } else if (isJs(chunkUrl)) {\n // Unloading a JS chunk would have no effect, as it lives in the JS\n // runtime once evaluated.\n // However, we still want to remove the script tag from the DOM to keep\n // the HTML somewhat consistent from the user's perspective.\n const scripts = document.querySelectorAll(\n `script[src=\"${baseChunkUrl}\"],script[src^=\"${baseChunkUrl}?\"],script[src=\"${decodedBaseChunkUrl}\"],script[src^=\"${decodedBaseChunkUrl}?\"]`\n )\n for (const script of Array.from(scripts)) {\n script.remove()\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n },\n\n reloadChunk(chunkUrl) {\n return new Promise((resolve, reject) => {\n if (!isCss(chunkUrl)) {\n reject(new Error('The DOM backend can only reload CSS chunks'))\n return\n }\n\n // Strip query string so we match links regardless of cache-busting\n // params (e.g. ?ts=) that may differ between HMR updates.\n const baseChunkUrl = chunkUrl.split('?')[0]\n const decodedBaseChunkUrl = decodeURI(baseChunkUrl)\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${baseChunkUrl}\"],link[rel=stylesheet][href^=\"${baseChunkUrl}?\"],link[rel=stylesheet][href=\"${decodedBaseChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedBaseChunkUrl}?\"]`\n )\n\n if (previousLinks.length === 0) {\n reject(new Error(`No link element found for chunk ${chunkUrl}`))\n return\n }\n\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n\n if (\n navigator.userAgent.includes('Firefox') ||\n (navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome') &&\n !navigator.userAgent.includes('Chromium'))\n ) {\n // Firefox won't reload CSS files that were previously loaded on the\n // current page: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506\n //\n // Safari serves cached CSS when a exists for the\n // same URL: https://bugs.webkit.org/show_bug.cgi?id=187726\n //\n // Replace or add a fresh `ts` cache-busting param without\n // discarding other query parameters that may already be present.\n const url = new URL(chunkUrl, location.origin)\n url.searchParams.set('ts', String(Date.now()))\n // Reduced timer precision in some browers could lead to an update getting dropped\n // in firefox if it happens fast enough (in firefox precision is sometimes 100ms!).\n // So trust that the server is only updating us when it is important and use a\n // random number to bust the cache.\n url.searchParams.set('_next_rand', String(Math.random()))\n link.href = url.pathname + url.search\n } else {\n link.href = chunkUrl\n }\n\n link.onerror = () => {\n reject()\n }\n link.onload = () => {\n // First load the new CSS, then remove the old ones. This prevents visible\n // flickering that would happen in-between removing the previous CSS and\n // loading the new one.\n for (const previousLink of Array.from(previousLinks))\n previousLink.remove()\n\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolve()\n }\n\n // Make sure to insert the new CSS right after the previous one, so that\n // its precedence is higher.\n previousLinks[0].parentElement!.insertBefore(\n link,\n previousLinks[0].nextSibling\n )\n })\n },\n\n restart: () => self.location.reload(),\n }\n\n function deleteResolver(chunkUrl: ChunkUrl) {\n chunkResolvers.delete(chunkUrl)\n }\n})()\n\nfunction _eval({ code, url, map }: EcmascriptModuleEntry): ModuleFactory {\n code += `\\n\\n//# sourceURL=${encodeURI(\n location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX\n )}`\n if (map) {\n code += `\\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(\n // btoa doesn't handle nonlatin characters, so escape them as \\x sequences\n // See https://stackoverflow.com/a/26603875\n unescape(encodeURIComponent(map))\n )}`\n }\n\n // eslint-disable-next-line no-eval\n return eval(code)\n}\n"],"names":["DEV_BACKEND","unloadChunk","chunkUrl","deleteResolver","baseChunkUrl","split","decodedBaseChunkUrl","decodeURI","isCss","links","document","querySelectorAll","link","Array","from","remove","isJs","scripts","script","Error","reloadChunk","Promise","resolve","reject","previousLinks","length","createElement","rel","navigator","userAgent","includes","url","URL","location","origin","searchParams","set","String","Date","now","Math","random","href","pathname","search","onerror","onload","previousLink","parentElement","insertBefore","nextSibling","restart","self","reload","chunkResolvers","delete","_eval","code","map","encodeURI","CHUNK_BASE_PATH","ASSET_SUFFIX","btoa","unescape","encodeURIComponent","eval"],"mappings":"AAAA;;;;;CAKC,GAED,oDAAoD,GAEpD,gDAAgD;AAChD,4CAA4C;AAC5C,iDAAiD;AACjD,0DAA0D;AAE1D,IAAIA;AACH,CAAC;IACAA,cAAc;QACZC,aAAYC,QAAQ;YAClBC,eAAeD;YAEf,mEAAmE;YACnE,0DAA0D;YAC1D,MAAME,eAAeF,SAASG,KAAK,CAAC,IAAI,CAAC,EAAE;YAC3C,gFAAgF;YAChF,MAAMC,sBAAsBC,UAAUH;YAEtC,IAAII,MAAMN,WAAW;gBACnB,MAAMO,QAAQC,SAASC,gBAAgB,CACrC,CAAC,WAAW,EAAEP,aAAa,eAAe,EAAEA,aAAa,eAAe,EAAEE,oBAAoB,eAAe,EAAEA,oBAAoB,GAAG,CAAC;gBAEzI,KAAK,MAAMM,QAAQC,MAAMC,IAAI,CAACL,OAAQ;oBACpCG,KAAKG,MAAM;gBACb;YACF,OAAO,IAAIC,KAAKd,WAAW;gBACzB,mEAAmE;gBACnE,0BAA0B;gBAC1B,uEAAuE;gBACvE,4DAA4D;gBAC5D,MAAMe,UAAUP,SAASC,gBAAgB,CACvC,CAAC,YAAY,EAAEP,aAAa,gBAAgB,EAAEA,aAAa,gBAAgB,EAAEE,oBAAoB,gBAAgB,EAAEA,oBAAoB,GAAG,CAAC;gBAE7I,KAAK,MAAMY,UAAUL,MAAMC,IAAI,CAACG,SAAU;oBACxCC,OAAOH,MAAM;gBACf;YACF,OAAO;gBACL,MAAM,IAAII,MAAM,CAAC,mCAAmC,EAAEjB,UAAU;YAClE;QACF;QAEAkB,aAAYlB,QAAQ;YAClB,OAAO,IAAImB,QAAc,CAACC,SAASC;gBACjC,IAAI,CAACf,MAAMN,WAAW;oBACpBqB,OAAO,IAAIJ,MAAM;oBACjB;gBACF;gBAEA,mEAAmE;gBACnE,0DAA0D;gBAC1D,MAAMf,eA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AAgBlC,MAAMC,IAAI,CAACU,eACpCuB,aAAahC,MAAM;oBAErB,uEAAuE;oBACvE,oBAAoB;oBACpBO;gBACF;gBAEA,wEAAwE;gBACxE,4BAA4B;gBAC5BE,aAAa,CAAC,EAAE,CAACwB,aAAa,CAAEC,YAAY,CAC1CrC,MACAY,aAAa,CAAC,EAAE,CAAC0B,WAAW;YAEhC;QACF;QAEAC,SAAS,IAAMC,KAAKnB,QAAQ,CAACoB,MAAM;IACrC;IAEA,SAASlD,eAAeD,QAAkB;QACxCoD,eAAeC,MAAM,CAACrD;IACxB;AACF,CAAC;AAED,SAASsD,MAAM,EAAEC,IAAI,EAAE1B,GAAG,EAAE2B,GAAG,EAAyB;IACtDD,QAAQ,CAAC,kBAAkB,EAAEE,UAC3B1B,SAASC,MAAM,GAAG0B,kBAAkB7B,MAAM8B,eACzC;IACH,IAAIH,KAAK;QACPD,QAAQ,CAAC,kEAAkE,EAAEK,KAC3E,0EAA0E;QAC1E,2CAA2C;QAC3CC,SAASC,mBAAmBN,QAC3B;IACL;IAEA,mCAAmC;IACnC,OAAOO,KAAKR;AACd","ignoreList":[0]}}] } \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/output/0teu_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_11ydsw-.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/output/0teu_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_11ydsw-.js.map index 8d17818c396f..e9d426222813 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/output/0teu_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_11ydsw-.js.map +++ b/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/output/0teu_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_11ydsw-.js.map @@ -6,6 +6,6 @@ {"offset": {"line": 590, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/runtime-base.ts"],"sourcesContent":["/**\n * This file contains runtime types and functions that are shared between all\n * Turbopack *browser* ECMAScript runtimes.\n *\n * It will be appended to the runtime code of each runtime right after the\n * shared runtime utils.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\n// Used in WebWorkers to tell the runtime about the chunk suffix\ndeclare var TURBOPACK_ASSET_SUFFIX: string\n// Used in WebWorkers to tell the runtime about the current chunk url since it\n// can't be detected via `document.currentScript`. Note it's stored in reversed\n// order to use `push` and `pop`\ndeclare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined\n\n// Injected by rust code\ndeclare var CHUNK_BASE_PATH: string\ndeclare var ASSET_SUFFIX: string\ndeclare var WORKER_FORWARDED_GLOBALS: string[]\n\ninterface TurbopackBrowserBaseContext extends TurbopackBaseContext {\n R: ResolvePathFromModule\n}\n\nconst browserContextPrototype =\n Context.prototype as TurbopackBrowserBaseContext\n\n// Provided by build or dev base\ndeclare function instantiateModule(\n id: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): Module\n\ntype RuntimeParams = {\n otherChunks: ChunkData[]\n runtimeModuleIds: ModuleId[]\n}\n\ntype ChunkRegistrationChunk =\n | ChunkPath\n | { getAttribute: (name: string) => string | null }\n | undefined\n\ntype ChunkRegistration = [\n chunkPath: ChunkRegistrationChunk,\n ...([RuntimeParams] | CompressedModuleFactories),\n]\n\ntype ChunkList = {\n script: ChunkRegistrationChunk\n chunks: ChunkData[]\n source: 'entry' | 'dynamic'\n}\n\ninterface RuntimeBackend {\n registerChunk: (\n chunkPath: ChunkPath | ChunkScript,\n params?: RuntimeParams\n ) => void\n /**\n * Returns the same Promise for the same chunk URL.\n */\n loadChunkCached: (sourceType: SourceType, chunkUrl: ChunkUrl) => Promise\n loadWebAssembly: (\n sourceType: SourceType,\n sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ) => Promise\n loadWebAssemblyModule: (\n sourceType: SourceType,\n sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module\n ) => Promise\n}\n\ninterface DevRuntimeBackend {\n reloadChunk?: (chunkUrl: ChunkUrl) => Promise\n unloadChunk?: (chunkUrl: ChunkUrl) => void\n restart: () => void\n}\n\nconst moduleFactories: ModuleFactories = new Map()\ncontextPrototype.M = moduleFactories\n\nconst availableModules: Map | true> = new Map()\n\nconst availableModuleChunks: Map | true> = new Map()\n\nfunction loadChunk(\n this: TurbopackBrowserBaseContext,\n chunkData: ChunkData\n): Promise {\n return loadChunkInternal(SourceType.Parent, this.m.id, chunkData)\n}\nbrowserContextPrototype.l = loadChunk\n\nfunction loadInitialChunk(chunkPath: ChunkPath, chunkData: ChunkData) {\n return loadChunkInternal(SourceType.Runtime, chunkPath, chunkData)\n}\n\nasync function loadChunkInternal(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkData: ChunkData\n): Promise {\n if (typeof chunkData === 'string') {\n return loadChunkPath(sourceType, sourceData, chunkData)\n }\n\n const includedList = chunkData.included || []\n const modulesPromises = includedList.map((included) => {\n if (moduleFactories.has(included)) return true\n return availableModules.get(included)\n })\n if (modulesPromises.length > 0 && modulesPromises.every((p) => p)) {\n // When all included items are already loaded or loading, we can skip loading ourselves\n await Promise.all(modulesPromises)\n return\n }\n\n const includedModuleChunksList = chunkData.moduleChunks || []\n const moduleChunksPromises = includedModuleChunksList\n .map((included) => {\n // TODO(alexkirsz) Do we need this check?\n // if (moduleFactories[included]) return true;\n return availableModuleChunks.get(included)\n })\n .filter((p) => p)\n\n let promise: Promise\n if (moduleChunksPromises.length > 0) {\n // Some module chunks are already loaded or loading.\n\n if (moduleChunksPromises.length === includedModuleChunksList.length) {\n // When all included module chunks are already loaded or loading, we can skip loading ourselves\n await Promise.all(moduleChunksPromises)\n return\n }\n\n const moduleChunksToLoad: Set = new Set()\n for (const moduleChunk of includedModuleChunksList) {\n if (!availableModuleChunks.has(moduleChunk)) {\n moduleChunksToLoad.add(moduleChunk)\n }\n }\n\n for (const moduleChunkToLoad of moduleChunksToLoad) {\n const promise = loadChunkPath(sourceType, sourceData, moduleChunkToLoad)\n\n availableModuleChunks.set(moduleChunkToLoad, promise)\n\n moduleChunksPromises.push(promise)\n }\n\n promise = Promise.all(moduleChunksPromises)\n } else {\n promise = loadChunkPath(sourceType, sourceData, chunkData.path)\n\n // Mark all included module chunks as loading if they are not already loaded or loading.\n for (const includedModuleChunk of includedModuleChunksList) {\n if (!availableModuleChunks.has(includedModuleChunk)) {\n availableModuleChunks.set(includedModuleChunk, promise)\n }\n }\n }\n\n for (const included of includedList) {\n if (!availableModules.has(included)) {\n // It might be better to race old and new promises, but it's rare that the new promise will be faster than a request started earlier.\n // In production it's even more rare, because the chunk optimization tries to deduplicate modules anyway.\n availableModules.set(included, promise)\n }\n }\n\n await promise\n}\n\nconst loadedChunk = Promise.resolve(undefined)\nconst instrumentedBackendLoadChunks = new WeakMap<\n Promise,\n Promise | typeof loadedChunk\n>()\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkByUrl(\n this: TurbopackBrowserBaseContext,\n chunkUrl: ChunkUrl\n) {\n return loadChunkByUrlInternal(SourceType.Parent, this.m.id, chunkUrl)\n}\nbrowserContextPrototype.L = loadChunkByUrl\n\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkByUrlInternal(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkUrl: ChunkUrl\n): Promise {\n const thenable = BACKEND.loadChunkCached(sourceType, chunkUrl)\n let entry = instrumentedBackendLoadChunks.get(thenable)\n if (entry === undefined) {\n const resolve = instrumentedBackendLoadChunks.set.bind(\n instrumentedBackendLoadChunks,\n thenable,\n loadedChunk\n )\n entry = thenable.then(resolve).catch((cause) => {\n let loadReason: string\n switch (sourceType) {\n case SourceType.Runtime:\n loadReason = `as a runtime dependency of chunk ${sourceData}`\n break\n case SourceType.Parent:\n loadReason = `from module ${sourceData}`\n break\n case SourceType.Update:\n loadReason = 'from an HMR update'\n break\n default:\n invariant(\n sourceType,\n (sourceType) => `Unknown source type: ${sourceType}`\n )\n }\n let error = new Error(\n `Failed to load chunk ${chunkUrl} ${loadReason}${\n cause ? `: ${cause}` : ''\n }`,\n cause ? { cause } : undefined\n )\n error.name = 'ChunkLoadError'\n throw error\n })\n instrumentedBackendLoadChunks.set(thenable, entry)\n }\n\n return entry\n}\n\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkPath(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkPath: ChunkPath\n): Promise {\n const url = getChunkRelativeUrl(chunkPath)\n return loadChunkByUrlInternal(sourceType, sourceData, url)\n}\n\n/**\n * Returns an absolute url to an asset.\n */\nfunction resolvePathFromModule(\n this: TurbopackBaseContext,\n moduleId: string\n): string {\n const exported = this.r(moduleId)\n return exported?.default ?? exported\n}\nbrowserContextPrototype.R = resolvePathFromModule\n\n/**\n * no-op for browser\n * @param modulePath\n */\nfunction resolveAbsolutePath(modulePath?: string): string {\n return `/ROOT/${modulePath ?? ''}`\n}\nbrowserContextPrototype.P = resolveAbsolutePath\n\n/**\n * Exports a URL with the static suffix appended.\n */\nfunction exportUrl(\n this: TurbopackBrowserBaseContext,\n url: string,\n id: ModuleId | undefined\n) {\n exportValue.call(this, `${url}${ASSET_SUFFIX}`, id)\n}\nbrowserContextPrototype.q = exportUrl\n\n/**\n * Creates a worker by instantiating the given WorkerConstructor with the\n * appropriate URL and options.\n *\n * The entrypoint is a pre-compiled worker runtime file. The params configure\n * which module chunks to load and which module to run as the entry point.\n *\n * The params are a JSON array of the following structure:\n * `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`\n *\n * @param WorkerConstructor The Worker or SharedWorker constructor\n * @param entrypoint URL path to the worker entrypoint chunk\n * @param moduleChunks list of module chunk paths to load\n * @param workerOptions options to pass to the Worker constructor (optional)\n */\nfunction createWorker(\n WorkerConstructor: { new (url: URL, options?: object): Worker },\n entrypoint: ChunkPath,\n moduleChunks: ChunkPath[],\n workerOptions?: object\n): Worker {\n const isSharedWorker = WorkerConstructor.name === 'SharedWorker'\n\n const chunkUrls = moduleChunks\n .map((chunk) => getChunkRelativeUrl(chunk))\n .reverse()\n const params: unknown[] = [chunkUrls, ASSET_SUFFIX]\n for (const globalName of WORKER_FORWARDED_GLOBALS) {\n params.push((globalThis as Record)[globalName])\n }\n\n const url = new URL(getChunkRelativeUrl(entrypoint), location.origin)\n const paramsJson = JSON.stringify(params)\n if (isSharedWorker) {\n url.searchParams.set('params', paramsJson)\n } else {\n url.hash = '#params=' + encodeURIComponent(paramsJson)\n }\n\n // Remove type: \"module\" from options since our worker entrypoint is not a module\n const options = workerOptions\n ? { ...workerOptions, type: undefined }\n : undefined\n return new WorkerConstructor(url, options)\n}\nbrowserContextPrototype.b = createWorker\n\n/**\n * Instantiates a runtime module.\n */\nfunction instantiateRuntimeModule(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): Module {\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n/**\n * Returns the URL relative to the origin where a chunk can be fetched from.\n */\nfunction getChunkRelativeUrl(chunkPath: ChunkPath | ChunkListPath): ChunkUrl {\n return `${CHUNK_BASE_PATH}${chunkPath\n .split('/')\n .map((p) => encodeURIComponent(p))\n .join('/')}${ASSET_SUFFIX}` as ChunkUrl\n}\n\n/**\n * Return the ChunkPath from a ChunkScript.\n */\nfunction getPathFromScript(chunkScript: ChunkPath | ChunkScript): ChunkPath\nfunction getPathFromScript(\n chunkScript: ChunkListPath | ChunkListScript\n): ChunkListPath\nfunction getPathFromScript(\n chunkScript: ChunkPath | ChunkListPath | ChunkScript | ChunkListScript\n): ChunkPath | ChunkListPath {\n if (typeof chunkScript === 'string') {\n return chunkScript as ChunkPath | ChunkListPath\n }\n const chunkUrl = chunkScript.src!\n const src = decodeURIComponent(chunkUrl.replace(/[?#].*$/, ''))\n const path = src.startsWith(CHUNK_BASE_PATH)\n ? src.slice(CHUNK_BASE_PATH.length)\n : src\n return path as ChunkPath | ChunkListPath\n}\n\n/**\n * Return the ChunkUrl from a ChunkScript.\n */\nfunction getUrlFromScript(chunk: ChunkPath | ChunkScript): ChunkUrl {\n if (typeof chunk === 'string') {\n return getChunkRelativeUrl(chunk)\n } else {\n // This is already exactly what we want\n return chunk.src! as ChunkUrl\n }\n}\n\n/**\n * Determine the chunk to register. Note that this function has side-effects!\n */\nfunction getChunkFromRegistration(\n chunk: ChunkRegistrationChunk\n): ChunkPath | CurrentScript {\n if (typeof chunk === 'string') {\n return chunk\n } else if (!chunk) {\n if (typeof TURBOPACK_NEXT_CHUNK_URLS !== 'undefined') {\n return { src: TURBOPACK_NEXT_CHUNK_URLS.pop()! } as CurrentScript\n } else {\n throw new Error('chunk path empty but not in a worker')\n }\n } else {\n return { src: chunk.getAttribute('src')! } as CurrentScript\n }\n}\n\nconst regexJsUrl = /\\.js(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.\n */\nfunction isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {\n return regexJsUrl.test(chunkUrlOrPath)\n}\n\nconst regexCssUrl = /\\.css(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .css, optionally followed by ?query or #fragment.\n */\nfunction isCss(chunkUrl: ChunkUrl): boolean {\n return regexCssUrl.test(chunkUrl)\n}\n\nfunction loadWebAssembly(\n this: TurbopackBaseContext,\n chunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n): Promise {\n return BACKEND.loadWebAssembly(\n SourceType.Parent,\n this.m.id,\n chunkPath,\n edgeModule,\n importsObj\n )\n}\ncontextPrototype.w = loadWebAssembly\n\nfunction loadWebAssemblyModule(\n this: TurbopackBaseContext,\n chunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module\n): Promise {\n return BACKEND.loadWebAssemblyModule(\n SourceType.Parent,\n this.m.id,\n chunkPath,\n edgeModule\n )\n}\ncontextPrototype.u = loadWebAssemblyModule\n"],"names":["browserContextPrototype","Context","prototype","moduleFactories","Map","contextPrototype","M","availableModules","availableModuleChunks","loadChunk","chunkData","loadChunkInternal","SourceType","Parent","m","id","l","loadInitialChunk","chunkPath","Runtime","sourceType","sourceData","loadChunkPath","includedList","included","modulesPromises","map","has","get","length","every","p","Promise","all","includedModuleChunksList","moduleChunks","moduleChunksPromises","filter","promise","moduleChunksToLoad","Set","moduleChunk","add","moduleChunkToLoad","set","push","path","includedModuleChunk","loadedChunk","resolve","undefined","instrumentedBackendLoadChunks","WeakMap","loadChunkByUrl","chunkUrl","loadChunkByUrlInternal","L","thenable","BACKEND","loadChunkCached","entry","bind","then","catch","cause","loadReason","Update","invariant","error","Error","name","url","getChunkRelativeUrl","resolvePathFromModule","moduleId","exported","r","default","R","resolveAbsolutePath","modulePath","P","exportUrl","exportValue","call","ASSET_SUFFIX","q","createWorker","WorkerConstructor","entrypoint","workerOptions","isSharedWorker","chunkUrls","chunk","reverse","params","globalName","WORKER_FORWARDED_GLOBALS","globalThis","URL","location","origin","paramsJson","JSON","stringify","searchParams","hash","encodeURIComponent","options","type","b","instantiateRuntimeModule","instantiateModule","CHUNK_BASE_PATH","split","join","getPathFromScript","chunkScript","src","decodeURIComponent","replace","startsWith","slice","getUrlFromScript","getChunkFromRegistration","TURBOPACK_NEXT_CHUNK_URLS","pop","getAttribute","regexJsUrl","isJs","chunkUrlOrPath","test","regexCssUrl","isCss","loadWebAssembly","edgeModule","importsObj","w","loadWebAssemblyModule","u"],"mappings":"AAAA;;;;;;CAMC,GAED,oDAAoD,GAEpD,6CAA6C;AAC7C,iEAAiE;AAEjE,gEAAgE;AAgBhE,MAAMA,0BACJC,QAAQC,SAAS;AA4DnB,MAAMC,kBAAmC,IAAIC;AAC7CC,iBAAiBC,CAAC,GAAGH;AAErB,MAAMI,mBAAuD,IAAIH;AAEjE,MAAMI,wBAA6D,IAAIJ;AAEvE,SAASK,UAEPC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,GACD,SAAS6E,iBAAiB9B,KAA8B;IACtD,IAAI,OAAOA,UAAU,UAAU;QAC7B,OAAOrB,oBAAoBqB;IAC7B,OAAO;QACL,uCAAuC;QACvC,OAAOA,MAAMyB,GAAG;IAClB;AACF;AAEA;;CAEC,GACD,SAASM,yBACP/B,KAA6B;IAE7B,IAAI,OAAOA,UAAU,UAAU;QAC7B,OAAOA;IACT,OAAO,IAAI,CAACA,OAAO;QACjB,IAAI,OAAOgC,8BAA8B,aAAa;YACpD,OAAO;gBAAEP,KAAKO,0BAA0BC,GAAG;YAAI;QACjD,OAAO;YACL,MAAM,IAAIzD,MAAM;QAClB;IACF,OAAO;QACL,OAAO;YAAEiD,KAAKzB,MAAMkC,YAAY,CAAC;QAAQ;IAC3C;AACF;AAEA,MAAMC,aAAa;AACnB;;CAEC,GACD,SAASC,KAAKC,cAAoC;IAChD,OAAOF,WAAWG,IAAI,CAACD;AACzB;AAEA,MAAME,cAAc;AACpB;;CAEC,GACD,SAASC,MAAM/E,QAAkB;IAC/B,OAAO8E,YAAYD,IAAI,CAAC7E;AAC1B;AAEA,SAASgF,gBAEPpH,SAAoB,EACpBqH,UAAoC,EACpCC,UAA+B;IAE/B,OAAO9E,QAAQ4E,eAAe,CAC5B1H,WAAWC,MAAM,EACjB,IAAI,CAACC,CAAC,CAACC,EAAE,EACTG,WACAqH,YACAC;AAEJ;AACAnI,iBAAiBoI,CAAC,GAAGH;AAErB,SAASI,sBAEPxH,SAAoB,EACpBqH,UAAoC;IAEpC,OAAO7E,QAAQgF,qBAAqB,CAClC9H,WAAWC,MAAM,EACjB,IAAI,CAACC,CAAC,CAACC,EAAE,EACTG,WACAqH;AAEJ;AACAlI,iBAAiBsI,CAAC,GAAGD","ignoreList":[0]}}, {"offset": {"line": 839, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared/runtime/hmr-runtime.ts"],"sourcesContent":["/// \n/// \n/// \n/// \n\ntype HotModuleFactoryFunction = ModuleFactoryFunction<\n HotModule,\n TurbopackBaseContext\n>\n\n/**\n * Shared HMR (Hot Module Replacement) implementation.\n *\n * This file contains the complete HMR implementation that's shared between\n * browser and Node.js runtimes. It manages module hot state, dependency\n * tracking, the module.hot API, and the full HMR update flow.\n */\n\n/**\n * The development module cache shared across the runtime.\n * Browser runtime declares this directly.\n * Node.js runtime assigns globalThis.__turbopack_module_cache__ to this.\n */\nlet devModuleCache: Record\n\n/**\n * Module IDs that are instantiated as part of the runtime of a chunk.\n */\nlet runtimeModules: Set\n\n/**\n * Maps module IDs to persisted data between executions of their hot module\n * implementation (`hot.data`).\n */\nconst moduleHotData: Map = new Map()\n\n/**\n * Maps module instances to their hot module state.\n * Uses WeakMap so it works with both HotModule and ModuleWithDirection.\n */\nconst moduleHotState: WeakMap = new WeakMap()\n\n/**\n * Modules that call `module.hot.invalidate()` (while being updated).\n */\nconst queuedInvalidatedModules: Set = new Set()\n\nclass UpdateApplyError extends Error {\n name = 'UpdateApplyError'\n\n dependencyChain: ModuleId[]\n\n constructor(message: string, dependencyChain: ModuleId[]) {\n super(message)\n this.dependencyChain = dependencyChain\n }\n}\n\ntype ModuleEffect =\n | {\n type: 'unaccepted'\n dependencyChain: ModuleId[]\n }\n | {\n type: 'self-declined'\n dependencyChain: ModuleId[]\n moduleId: ModuleId\n }\n | {\n type: 'declined'\n dependencyChain: ModuleId[]\n moduleId: ModuleId\n parentId: ModuleId\n }\n | {\n type: 'accepted'\n moduleId: ModuleId\n outdatedModules: Set\n outdatedDependencies: Map>\n }\n\n/**\n * Records parent-child relationship when a module imports another.\n * Should be called during module instantiation.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction trackModuleImport(\n parentModule: ModuleWithDirection,\n childModuleId: ModuleId,\n childModule: ModuleWithDirection | undefined\n): void {\n // Record that parent imports child\n if (parentModule.children.indexOf(childModuleId) === -1) {\n parentModule.children.push(childModuleId)\n }\n\n // Record that child is imported by parent\n if (childModule && childModule.parents.indexOf(parentModule.id) === -1) {\n childModule.parents.push(parentModule.id)\n }\n}\n\nfunction formatDependencyChain(dependencyChain: ModuleId[]): string {\n return `Dependency chain: ${dependencyChain.join(' -> ')}`\n}\n\n/**\n * Walks the dependency tree to find all modules affected by a change.\n * Returns information about whether the update can be accepted and which\n * modules need to be invalidated.\n *\n * @param moduleId - The module that changed\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept().\n * This is used for server-side HMR where pages auto-accept at the top level.\n */\nfunction getAffectedModuleEffects(\n moduleId: ModuleId,\n autoAcceptRootModules: boolean\n): ModuleEffect {\n const outdatedModules: Set = new Set()\n const outdatedDependencies: Map> = new Map()\n\n type QueueItem = { moduleId?: ModuleId; dependencyChain: ModuleId[] }\n\n const queue: QueueItem[] = [\n {\n moduleId,\n dependencyChain: [],\n },\n ]\n\n let nextItem\n while ((nextItem = queue.shift())) {\n const { moduleId, dependencyChain } = nextItem\n\n if (moduleId != null) {\n if (outdatedModules.has(moduleId)) {\n // Avoid infinite loops caused by cycles between modules in the dependency chain.\n continue\n }\n\n outdatedModules.add(moduleId)\n }\n\n // We've arrived at the runtime of the chunk, which means that nothing\n // else above can accept this update.\n if (moduleId === undefined) {\n if (autoAcceptRootModules) {\n return {\n type: 'accepted',\n moduleId,\n outdatedModules,\n outdatedDependencies,\n }\n }\n return {\n type: 'unaccepted',\n dependencyChain,\n }\n }\n\n const module = devModuleCache[moduleId]\n const hotState = moduleHotState.get(module)!\n\n if (\n // The module is not in the cache. Since this is a \"modified\" update,\n // it means that the module was never instantiated before.\n !module || // The module accepted itself without invalidating globalThis.\n // TODO is that right?\n (hotState.selfAccepted && !hotState.selfInvalidated)\n ) {\n continue\n }\n\n if (hotState.selfDeclined) {\n return {\n type: 'self-declined',\n dependencyChain,\n moduleId,\n }\n }\n\n if (runtimeModules.has(moduleId)) {\n if (autoAcceptRootModules) {\n continue\n }\n queue.push({\n moduleId: undefined,\n dependencyChain: [...dependencyChain, moduleId],\n })\n continue\n }\n\n for (const parentId of module.parents) {\n const parent = devModuleCache[parentId]\n\n if (!parent) {\n continue\n }\n\n const parentHotState = moduleHotState.get(parent)\n\n // Check if parent declined this dependency\n if (parentHotState?.declinedDependencies[moduleId]) {\n return {\n type: 'declined',\n dependencyChain: [...dependencyChain, moduleId],\n moduleId,\n parentId,\n }\n }\n\n // Skip if parent is already outdated\n if (outdatedModules.has(parentId)) {\n continue\n }\n\n // Check if parent accepts this dependency\n if (parentHotState?.acceptedDependencies[moduleId]) {\n if (!outdatedDependencies.has(parentId)) {\n outdatedDependencies.set(parentId, new Set())\n }\n outdatedDependencies.get(parentId)!.add(moduleId)\n continue\n }\n\n // Neither accepted nor declined — propagate to parent\n queue.push({\n moduleId: parentId,\n dependencyChain: [...dependencyChain, moduleId],\n })\n }\n\n // If no parents and we're at a root module, auto-accept if configured\n if (module.parents.length === 0 && autoAcceptRootModules) {\n continue\n }\n }\n\n return {\n type: 'accepted',\n moduleId,\n outdatedModules,\n outdatedDependencies,\n }\n}\n\n/**\n * Merges source dependency map into target dependency map.\n */\nfunction mergeDependencies(\n target: Map>,\n source: Map>\n): void {\n for (const [parentId, deps] of source) {\n const existing = target.get(parentId)\n if (existing) {\n for (const dep of deps) {\n existing.add(dep)\n }\n } else {\n target.set(parentId, new Set(deps))\n }\n }\n}\n\n/**\n * Computes all modules that need to be invalidated based on which modules changed.\n *\n * @param invalidated - The modules that have been invalidated\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction computedInvalidatedModules(\n invalidated: Iterable,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n} {\n const outdatedModules = new Set()\n const outdatedDependencies = new Map>()\n\n for (const moduleId of invalidated) {\n const effect = getAffectedModuleEffects(moduleId, autoAcceptRootModules)\n\n switch (effect.type) {\n case 'unaccepted':\n throw new UpdateApplyError(\n `cannot apply update: unaccepted module. ${formatDependencyChain(\n effect.dependencyChain\n )}.`,\n effect.dependencyChain\n )\n case 'self-declined':\n throw new UpdateApplyError(\n `cannot apply update: self-declined module. ${formatDependencyChain(\n effect.dependencyChain\n )}.`,\n effect.dependencyChain\n )\n case 'declined':\n throw new UpdateApplyError(\n `cannot apply update: declined dependency. ${formatDependencyChain(\n effect.dependencyChain\n )}. Declined by ${effect.parentId}.`,\n effect.dependencyChain\n )\n case 'accepted':\n for (const outdatedModuleId of effect.outdatedModules) {\n outdatedModules.add(outdatedModuleId)\n }\n mergeDependencies(outdatedDependencies, effect.outdatedDependencies)\n break\n default:\n invariant(effect, (effect) => `Unknown effect type: ${effect?.type}`)\n }\n }\n\n return { outdatedModules, outdatedDependencies }\n}\n\n/**\n * Creates the module.hot API object and its internal state.\n * This provides the HMR API that user code calls (module.hot.accept(), etc.)\n */\n\nfunction createModuleHot(\n moduleId: ModuleId,\n hotData: HotData\n): { hot: Hot; hotState: HotState } {\n const hotState: HotState = {\n selfAccepted: false,\n selfDeclined: false,\n selfInvalidated: false,\n disposeHandlers: [],\n acceptedDependencies: {},\n acceptedErrorHandlers: {},\n declinedDependencies: {},\n }\n\n const hot: Hot = {\n // TODO(alexkirsz) This is not defined in the HMR API. It was used to\n // decide whether to warn whenever an HMR-disposed module required other\n // modules. We might want to remove it.\n active: true,\n\n data: hotData ?? {},\n\n accept: (\n modules?: string | string[] | AcceptErrorHandler,\n callback?: AcceptCallback,\n errorHandler?: AcceptErrorHandler\n ) => {\n if (modules === undefined) {\n hotState.selfAccepted = true\n } else if (typeof modules === 'function') {\n hotState.selfAccepted = modules\n } else if (typeof modules === 'object' && modules !== null) {\n for (let i = 0; i < modules.length; i++) {\n hotState.acceptedDependencies[modules[i]] = callback || function () {}\n hotState.acceptedErrorHandlers[modules[i]] = errorHandler\n }\n } else {\n hotState.acceptedDependencies[modules] = callback || function () {}\n hotState.acceptedErrorHandlers[modules] = errorHandler\n }\n },\n\n decline: (dep?: string | string[]) => {\n if (dep === undefined) {\n hotState.selfDeclined = true\n } else if (typeof dep === 'object' && dep !== null) {\n for (let i = 0; i < dep.length; i++) {\n hotState.declinedDependencies[dep[i]] = true\n }\n } else {\n hotState.declinedDependencies[dep] = true\n }\n },\n\n dispose: (callback) => {\n hotState.disposeHandlers.push(callback)\n },\n\n addDisposeHandler: (callback) => {\n hotState.disposeHandlers.push(callback)\n },\n\n removeDisposeHandler: (callback) => {\n const idx = hotState.disposeHandlers.indexOf(callback)\n if (idx >= 0) {\n hotState.disposeHandlers.splice(idx, 1)\n }\n },\n\n invalidate: () => {\n hotState.selfInvalidated = true\n queuedInvalidatedModules.add(moduleId)\n },\n\n // NOTE(alexkirsz) This is part of the management API, which we don't\n // implement, but the Next.js React Refresh runtime uses this to decide\n // whether to schedule an update.\n status: () => 'idle',\n\n // NOTE(alexkirsz) Since we always return \"idle\" for now, these are no-ops.\n addStatusHandler: (_handler) => {},\n removeStatusHandler: (_handler) => {},\n\n // NOTE(jridgewell) Check returns the list of updated modules, but we don't\n // want the webpack code paths to ever update (the turbopack paths handle\n // this already).\n check: () => Promise.resolve(null),\n }\n\n return { hot, hotState }\n}\n\n/**\n * Processes queued invalidated modules and adds them to the outdated modules set.\n * Modules that call module.hot.invalidate() are queued and processed here.\n *\n * @param outdatedModules - The current set of outdated modules\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction applyInvalidatedModules(\n outdatedModules: Set,\n outdatedDependencies: Map>,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n} {\n if (queuedInvalidatedModules.size > 0) {\n const result = computedInvalidatedModules(\n queuedInvalidatedModules,\n autoAcceptRootModules\n )\n for (const moduleId of result.outdatedModules) {\n outdatedModules.add(moduleId)\n }\n mergeDependencies(outdatedDependencies, result.outdatedDependencies)\n\n queuedInvalidatedModules.clear()\n }\n\n return { outdatedModules, outdatedDependencies }\n}\n\n/**\n * Computes which outdated modules have self-accepted and can be hot reloaded.\n */\n\nfunction computeOutdatedSelfAcceptedModules(\n outdatedModules: Iterable\n): { moduleId: ModuleId; errorHandler: true | Function }[] {\n const outdatedSelfAcceptedModules: {\n moduleId: ModuleId\n errorHandler: true | Function\n }[] = []\n for (const moduleId of outdatedModules) {\n const module = devModuleCache[moduleId]\n const hotState = moduleHotState.get(module)\n if (module && hotState?.selfAccepted && !hotState.selfInvalidated) {\n outdatedSelfAcceptedModules.push({\n moduleId,\n errorHandler: hotState.selfAccepted,\n })\n }\n }\n return outdatedSelfAcceptedModules\n}\n\n/**\n * Disposes of an instance of a module.\n * Runs hot.dispose handlers and manages persistent hot data.\n *\n * NOTE: mode = \"replace\" will not remove modules from devModuleCache.\n * This must be done in a separate step afterwards.\n */\nfunction disposeModule(moduleId: ModuleId, mode: 'clear' | 'replace') {\n const module = devModuleCache[moduleId]\n if (!module) {\n return\n }\n\n const hotState = moduleHotState.get(module)\n if (!hotState) {\n return\n }\n\n const data: HotData = {}\n\n // Run the `hot.dispose` handler, if any, passing in the persistent\n // `hot.data` object.\n for (const disposeHandler of hotState.disposeHandlers) {\n disposeHandler(data)\n }\n\n // This used to warn in `getOrInstantiateModuleFromParent` when a disposed\n // module is still importing other modules.\n if (module.hot) {\n module.hot.active = false\n }\n\n moduleHotState.delete(module)\n\n // Remove the disposed module from its children's parent list.\n // It will be added back once the module re-instantiates and imports its\n // children again.\n for (const childId of module.children) {\n const child = devModuleCache[childId]\n if (!child) {\n continue\n }\n\n const idx = child.parents.indexOf(module.id)\n if (idx >= 0) {\n child.parents.splice(idx, 1)\n }\n }\n\n switch (mode) {\n case 'clear':\n delete devModuleCache[module.id]\n moduleHotData.delete(module.id)\n break\n case 'replace':\n moduleHotData.set(module.id, data)\n break\n default:\n invariant(mode, (mode) => `invalid mode: ${mode}`)\n }\n}\n\n/**\n * Dispose phase: runs dispose handlers and cleans up outdated/disposed modules.\n * Returns the parent modules of outdated modules for use in the apply phase.\n */\n\nfunction disposePhase(\n outdatedModules: Iterable,\n disposedModules: Iterable,\n outdatedDependencies: Map>\n): { outdatedModuleParents: Map> } {\n for (const moduleId of outdatedModules) {\n disposeModule(moduleId, 'replace')\n }\n\n for (const moduleId of disposedModules) {\n disposeModule(moduleId, 'clear')\n }\n\n // Removing modules from the module cache is a separate step.\n // We also want to keep track of previous parents of the outdated modules.\n const outdatedModuleParents = new Map>()\n for (const moduleId of outdatedModules) {\n const oldModule = devModuleCache[moduleId]\n outdatedModuleParents.set(moduleId, oldModule?.parents)\n delete devModuleCache[moduleId]\n }\n\n // Remove outdated dependencies from parent module's children list.\n // When a parent accepts a child's update, the child is re-instantiated\n // but the parent stays alive. We remove the old child reference so it\n // gets re-added when the child re-imports.\n for (const [parentId, deps] of outdatedDependencies) {\n const module = devModuleCache[parentId]\n if (module) {\n for (const dep of deps) {\n const idx = module.children.indexOf(dep)\n if (idx >= 0) {\n module.children.splice(idx, 1)\n }\n }\n }\n }\n\n return { outdatedModuleParents }\n}\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/**\n * Shared module instantiation logic.\n * This handles the full module instantiation flow for both browser and Node.js.\n * Only React Refresh hooks differ between platforms (passed as callback).\n */\nfunction instantiateModuleShared(\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n runtimeModules: Set,\n createModuleObjectFn: (id: ModuleId) => HotModule,\n createContextFn: (module: HotModule, exports: Exports, refresh?: any) => any,\n runModuleExecutionHooksFn: (\n module: HotModule,\n exec: (refresh: any) => void\n ) => void\n): HotModule {\n // 1. Factory validation (same in both browser and Node.js)\n const id = moduleId\n const moduleFactory = moduleFactories.get(id)\n if (typeof moduleFactory !== 'function') {\n throw new Error(\n factoryNotAvailableMessage(moduleId, sourceType, sourceData) +\n `\\nThis is often caused by a stale browser cache, misconfigured Cache-Control headers, or a service worker serving outdated responses.` +\n `\\nTo fix this, make sure your Cache-Control headers allow revalidation of chunks and review your service worker configuration. ` +\n `As an immediate workaround, try hard-reloading the page, clearing the browser cache, or unregistering any service workers.`\n )\n }\n\n // 2. Hot API setup (same in both - works for browser, included for Node.js)\n const hotData = moduleHotData.get(id)!\n const { hot, hotState } = createModuleHot(id, hotData)\n\n // 3. Parent assignment logic (same in both)\n let parents: ModuleId[]\n switch (sourceType) {\n case SourceType.Runtime:\n runtimeModules.add(id)\n parents = []\n break\n case SourceType.Parent:\n parents = [sourceData as ModuleId]\n break\n case SourceType.Update:\n parents = (sourceData as ModuleId[]) || []\n break\n default:\n throw new Error(`Unknown source type: ${sourceType}`)\n }\n\n // 4. Module creation (platform creates base module object)\n const module = createModuleObjectFn(id)\n const exports = module.exports\n module.parents = parents\n module.children = []\n module.hot = hot\n\n devModuleCache[id] = module\n moduleHotState.set(module, hotState)\n\n // 5. Module execution (React Refresh hooks are platform-specific)\n try {\n runModuleExecutionHooksFn(module, (refresh) => {\n const context = createContextFn(module, exports, refresh)\n moduleFactory.call(exports, context, module, exports)\n })\n } catch (error) {\n module.error = error as any\n throw error\n }\n\n // 6. ESM interop (same in both)\n if (module.namespaceObject && module.exports !== module.namespaceObject) {\n // in case of a circular dependency: cjs1 -> esm2 -> cjs1\n interopEsm(module.exports, module.namespaceObject)\n }\n\n return module\n}\n\n/**\n * Analyzes update entries and chunks to determine which modules were added, modified, or deleted.\n * This is pure logic that doesn't depend on the runtime environment.\n */\nfunction computeChangedModules(\n entries: Record,\n updates: Record,\n chunkModulesMap?: Map>\n): {\n added: Map\n modified: Map\n deleted: Set\n chunksAdded: Map>\n chunksDeleted: Map>\n} {\n const chunksAdded = new Map()\n const chunksDeleted = new Map()\n const added: Map = new Map()\n const modified = new Map()\n const deleted: Set = new Set()\n\n for (const [chunkPath, mergedChunkUpdate] of Object.entries(updates) as Array<\n [ChunkPath, EcmascriptMergedChunkUpdate]\n >) {\n switch (mergedChunkUpdate.type) {\n case 'added': {\n const updateAdded = new Set(mergedChunkUpdate.modules)\n for (const moduleId of updateAdded) {\n added.set(moduleId, entries[moduleId])\n }\n chunksAdded.set(chunkPath, updateAdded)\n break\n }\n case 'deleted': {\n const updateDeleted = chunkModulesMap\n ? new Set(chunkModulesMap.get(chunkPath))\n : new Set()\n for (const moduleId of updateDeleted) {\n deleted.add(moduleId)\n }\n chunksDeleted.set(chunkPath, updateDeleted)\n break\n }\n case 'partial': {\n const updateAdded = new Set(mergedChunkUpdate.added)\n const updateDeleted = new Set(mergedChunkUpdate.deleted)\n for (const moduleId of updateAdded) {\n added.set(moduleId, entries[moduleId])\n }\n for (const moduleId of updateDeleted) {\n deleted.add(moduleId)\n }\n chunksAdded.set(chunkPath, updateAdded)\n chunksDeleted.set(chunkPath, updateDeleted)\n break\n }\n default:\n throw new Error('Unknown merged chunk update type')\n }\n }\n\n // If a module was added from one chunk and deleted from another in the same update,\n // consider it to be modified, as it means the module was moved from one chunk to another\n // AND has new code in a single update.\n for (const moduleId of added.keys()) {\n if (deleted.has(moduleId)) {\n added.delete(moduleId)\n deleted.delete(moduleId)\n }\n }\n\n for (const [moduleId, entry] of Object.entries(entries)) {\n // Modules that haven't been added to any chunk but have new code are considered\n // to be modified.\n // This needs to be under the previous loop, as we need it to get rid of modules\n // that were added and deleted in the same update.\n if (!added.has(moduleId)) {\n modified.set(moduleId, entry)\n }\n }\n\n return { added, deleted, modified, chunksAdded, chunksDeleted }\n}\n\n/**\n * Compiles new module code and walks the dependency tree to find all outdated modules.\n * Uses the evalModuleEntry function to compile code (platform-specific).\n *\n * @param added - Map of added modules\n * @param modified - Map of modified modules\n * @param evalModuleEntry - Function to compile module code\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction computeOutdatedModules(\n added: Map,\n modified: Map,\n evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n newModuleFactories: Map\n} {\n const newModuleFactories = new Map()\n\n // Compile added modules\n for (const [moduleId, entry] of added) {\n if (entry != null) {\n newModuleFactories.set(moduleId, evalModuleEntry(entry))\n }\n }\n\n // Walk dependency tree to find all modules affected by modifications\n const { outdatedModules, outdatedDependencies } = computedInvalidatedModules(\n modified.keys(),\n autoAcceptRootModules\n )\n\n // Compile modified modules\n for (const [moduleId, entry] of modified) {\n newModuleFactories.set(moduleId, evalModuleEntry(entry))\n }\n\n return { outdatedModules, outdatedDependencies, newModuleFactories }\n}\n\n/**\n * Updates module factories and re-instantiates self-accepted modules.\n * Uses the instantiateModule function (platform-specific via callback).\n */\nfunction applyPhase(\n outdatedSelfAcceptedModules: {\n moduleId: ModuleId\n errorHandler: true | Function\n }[],\n newModuleFactories: Map,\n outdatedModuleParents: Map>,\n outdatedDependencies: Map>,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n instantiateModuleFn: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule,\n applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void,\n reportError: (err: any) => void\n) {\n // Update module factories\n for (const [moduleId, factory] of newModuleFactories.entries()) {\n applyModuleFactoryNameFn(factory)\n moduleFactories.set(moduleId, factory)\n }\n\n // TODO(alexkirsz) Run new runtime entries here.\n\n // Call accept handlers for outdated dependencies.\n // This runs BEFORE re-instantiating self-accepted modules, matching\n // webpack's behavior.\n for (const [parentId, deps] of outdatedDependencies) {\n const module = devModuleCache[parentId]\n if (!module) continue\n\n const hotState = moduleHotState.get(module)\n if (!hotState) continue\n\n // Group deps by callback, deduplicating callbacks that handle multiple deps.\n // Each callback receives only the deps it was registered for.\n const callbackDeps = new Map void), ModuleId[]>()\n const callbackErrorHandlers = new Map<\n AcceptCallback | (() => void),\n AcceptErrorHandler | undefined\n >()\n\n for (const dep of deps) {\n const acceptCallback = hotState.acceptedDependencies[dep]\n if (acceptCallback) {\n let depList = callbackDeps.get(acceptCallback)\n if (!depList) {\n depList = []\n callbackDeps.set(acceptCallback, depList)\n callbackErrorHandlers.set(\n acceptCallback,\n hotState.acceptedErrorHandlers[dep]\n )\n }\n depList.push(dep)\n }\n }\n\n for (const [callback, cbDeps] of callbackDeps) {\n try {\n callback.call(null, cbDeps)\n } catch (err: any) {\n const errorHandler = callbackErrorHandlers.get(callback)\n if (typeof errorHandler === 'function') {\n try {\n errorHandler(err, {\n moduleId: parentId,\n dependencyId: cbDeps[0],\n })\n } catch (err2) {\n reportError(err2)\n reportError(err)\n }\n } else {\n reportError(err)\n }\n }\n }\n }\n\n // Re-instantiate all outdated self-accepted modules\n for (const { moduleId, errorHandler } of outdatedSelfAcceptedModules) {\n try {\n instantiateModuleFn(\n moduleId,\n SourceType.Update,\n outdatedModuleParents.get(moduleId)\n )\n } catch (err) {\n if (typeof errorHandler === 'function') {\n try {\n errorHandler(err, { moduleId, module: devModuleCache[moduleId] })\n } catch (err2) {\n reportError(err2)\n reportError(err)\n }\n } else {\n reportError(err)\n }\n }\n }\n}\n\n/**\n * Internal implementation that orchestrates the full HMR update flow:\n * invalidation, disposal, and application of new modules.\n *\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction applyInternal(\n outdatedModules: Set,\n outdatedDependencies: Map>,\n disposedModules: Iterable,\n newModuleFactories: Map,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n instantiateModuleFn: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule,\n applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void,\n autoAcceptRootModules: boolean\n) {\n ;({ outdatedModules, outdatedDependencies } = applyInvalidatedModules(\n outdatedModules,\n outdatedDependencies,\n autoAcceptRootModules\n ))\n\n // Find self-accepted modules to re-instantiate\n const outdatedSelfAcceptedModules =\n computeOutdatedSelfAcceptedModules(outdatedModules)\n\n // Run dispose handlers, save hot.data, clear caches\n const { outdatedModuleParents } = disposePhase(\n outdatedModules,\n disposedModules,\n outdatedDependencies\n )\n\n let error: any\n\n function reportError(err: any) {\n if (!error) error = err // Keep first error\n }\n\n applyPhase(\n outdatedSelfAcceptedModules,\n newModuleFactories,\n outdatedModuleParents,\n outdatedDependencies,\n moduleFactories,\n devModuleCache,\n instantiateModuleFn,\n applyModuleFactoryNameFn,\n reportError\n )\n\n if (error) {\n throw error\n }\n\n // Recursively apply any queued invalidations from new module execution\n if (queuedInvalidatedModules.size > 0) {\n applyInternal(\n new Set(),\n new Map(),\n [],\n new Map(),\n moduleFactories,\n devModuleCache,\n instantiateModuleFn,\n applyModuleFactoryNameFn,\n autoAcceptRootModules\n )\n }\n}\n\n/**\n * Main entry point for applying an ECMAScript merged update.\n * This is called by both browser and Node.js runtimes with platform-specific callbacks.\n *\n * @param options.autoAcceptRootModules - If true, root modules auto-accept updates without explicit\n * module.hot.accept(). Used for server-side HMR where pages\n * auto-accept at the top level.\n */\nfunction applyEcmascriptMergedUpdateShared(options: {\n added: Map\n modified: Map\n disposedModules: Iterable\n evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction\n instantiateModule: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule\n applyModuleFactoryName: (factory: HotModuleFactoryFunction) => void\n moduleFactories: ModuleFactories\n devModuleCache: ModuleCache\n autoAcceptRootModules: boolean\n}) {\n const {\n added,\n modified,\n disposedModules,\n evalModuleEntry,\n instantiateModule,\n applyModuleFactoryName,\n moduleFactories,\n devModuleCache,\n autoAcceptRootModules,\n } = options\n\n const { outdatedModules, outdatedDependencies, newModuleFactories } =\n computeOutdatedModules(\n added,\n modified,\n evalModuleEntry,\n autoAcceptRootModules\n )\n\n applyInternal(\n outdatedModules,\n outdatedDependencies,\n disposedModules,\n newModuleFactories,\n moduleFactories,\n devModuleCache,\n instantiateModule,\n applyModuleFactoryName,\n autoAcceptRootModules\n )\n}\n"],"names":["devModuleCache","runtimeModules","moduleHotData","Map","moduleHotState","WeakMap","queuedInvalidatedModules","Set","UpdateApplyError","Error","name","dependencyChain","message","trackModuleImport","parentModule","childModuleId","childModule","children","indexOf","push","parents","id","formatDependencyChain","join","getAffectedModuleEffects","moduleId","autoAcceptRootModules","outdatedModules","outdatedDependencies","queue","nextItem","shift","has","add","undefined","type","module","hotState","get","selfAccepted","selfInvalidated","selfDeclined","parentId","parent","parentHotState","declinedDependencies","acceptedDependencies","set","length","mergeDependencies","target","source","deps","existing","dep","computedInvalidatedModules","invalidated","effect","outdatedModuleId","invariant","createModuleHot","hotData","disposeHandlers","acceptedErrorHandlers","hot","active","data","accept","modules","callback","errorHandler","i","decline","dispose","addDisposeHandler","removeDisposeHandler","idx","splice","invalidate","status","addStatusHandler","_handler","removeStatusHandler","check","Promise","resolve","applyInvalidatedModules","size","result","clear","computeOutdatedSelfAcceptedModules","outdatedSelfAcceptedModules","disposeModule","mode","disposeHandler","delete","childId","child","disposePhase","disposedModules","outdatedModuleParents","oldModule","instantiateModuleShared","sourceType","sourceData","moduleFactories","createModuleObjectFn","createContextFn","runModuleExecutionHooksFn","moduleFactory","factoryNotAvailableMessage","SourceType","Runtime","Parent","Update","exports","refresh","context","call","error","namespaceObject","interopEsm","computeChangedModules","entries","updates","chunkModulesMap","chunksAdded","chunksDeleted","added","modified","deleted","chunkPath","mergedChunkUpdate","Object","updateAdded","updateDeleted","keys","entry","computeOutdatedModules","evalModuleEntry","newModuleFactories","applyPhase","instantiateModuleFn","applyModuleFactoryNameFn","reportError","factory","callbackDeps","callbackErrorHandlers","acceptCallback","depList","cbDeps","err","dependencyId","err2","applyInternal","applyEcmascriptMergedUpdateShared","options","instantiateModule","applyModuleFactoryName"],"mappings":"AAAA,2CAA2C;AAC3C,6CAA6C;AAC7C,4CAA4C;AAC5C,4CAA4C;AAO5C;;;;;;CAMC,GAED;;;;CAIC,GACD,IAAIA;AAEJ;;CAEC,GACD,IAAIC;AAEJ;;;CAGC,GACD,MAAMC,gBAAwC,IAAIC;AAElD;;;CAGC,GACD,MAAMC,iBAAyC,IAAIC;AAEnD;;CAEC,GACD,MAAMC,2BAA0C,IAAIC;AAEpD,MAAMC,yBAAyBC;IAC7BC,OAAO,mBAAkB;IAEzBC,gBAA2B;IAE3BH,YAAYI,OAAe,EA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EACfzG,cAAc,EACd0B,qBAAqB,EACtB,GAAGkI;IAEJ,MAAM,EAAEjI,eAAe,EAAEC,oBAAoB,EAAEgH,kBAAkB,EAAE,GACjEF,uBACEV,OACAC,UACAU,iBACAjH;IAGJgI,cACE/H,iBACAC,sBACAuE,iBACAyC,oBACAnC,iBACAzG,gBACA6J,mBACAC,wBACApI;AAEJ","ignoreList":[0]}}, {"offset": {"line": 1533, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/dev-base.ts"],"sourcesContent":["/// \n/// \n\ninterface TurbopackDevContext extends TurbopackBrowserBaseContext {\n k: RefreshContext\n}\n\nconst devContextPrototype = Context.prototype as TurbopackDevContext\n\n/**\n * This file contains runtime types and functions that are shared between all\n * Turbopack *development* ECMAScript runtimes.\n *\n * It will be appended to the runtime code of each runtime right after the\n * shared runtime utils.\n */\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n// Assign browser's module cache and runtime modules to shared HMR state\ndevModuleCache = Object.create(null)\ndevContextPrototype.c = devModuleCache\nruntimeModules = new Set()\n\n// Set flag to indicate we use ModuleWithDirection\ncreateModuleWithDirectionFlag = true\n\n// This file must not use `import` and `export` statements. Otherwise, it\n// becomes impossible to augment interfaces declared in ``d files\n// (e.g. `Module`). Hence, the need for `import()` here.\ntype RefreshRuntimeGlobals =\n import('@next/react-refresh-utils/dist/runtime').RefreshRuntimeGlobals\n\ndeclare var $RefreshHelpers$: RefreshRuntimeGlobals['$RefreshHelpers$']\ndeclare var $RefreshReg$: RefreshRuntimeGlobals['$RefreshReg$']\ndeclare var $RefreshSig$: RefreshRuntimeGlobals['$RefreshSig$']\ndeclare var $RefreshInterceptModuleExecution$: RefreshRuntimeGlobals['$RefreshInterceptModuleExecution$']\n\ntype RefreshContext = {\n register: RefreshRuntimeGlobals['$RefreshReg$']\n signature: RefreshRuntimeGlobals['$RefreshSig$']\n registerExports: typeof registerExportsAndSetupBoundaryForReactRefresh\n}\n\ntype RefreshHelpers = RefreshRuntimeGlobals['$RefreshHelpers$']\n\ntype ModuleFactory = (\n this: Module['exports'],\n context: TurbopackDevContext\n) => unknown\n\ninterface DevRuntimeBackend {\n reloadChunk?: (chunkUrl: ChunkUrl) => Promise\n unloadChunk?: (chunkUrl: ChunkUrl) => void\n restart: () => void\n}\n\n/**\n * Map from module ID to the chunks that contain this module.\n *\n * In HMR, we need to keep track of which modules are contained in which so\n * chunks. This is so we don't eagerly dispose of a module when it is removed\n * from chunk A, but still exists in chunk B.\n */\nconst moduleChunksMap: Map> = new Map()\n/**\n * Map from a chunk path to all modules it contains.\n */\nconst chunkModulesMap: Map> = new Map()\n/**\n * Chunk lists that contain a runtime. When these chunk lists receive an update\n * that can't be reconciled with the current state of the page, we need to\n * reload the runtime entirely.\n */\nconst runtimeChunkLists: Set = new Set()\n/**\n * Map from a chunk list to the chunk paths it contains.\n */\nconst chunkListChunksMap: Map> = new Map()\n/**\n * Map from a chunk path to the chunk lists it belongs to.\n */\nconst chunkChunkListsMap: Map> = new Map()\n\n/**\n * Gets or instantiates a runtime module.\n */\n// @ts-ignore\nfunction getOrInstantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): Module {\n const module = devModuleCache[moduleId]\n if (module) {\n if (module.error) {\n throw module.error\n }\n return module\n }\n\n // @ts-ignore\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it if it is not cached.\n */\n// @ts-ignore Defined in `runtime-utils.ts`\nconst getOrInstantiateModuleFromParent: GetOrInstantiateModuleFromParent<\n HotModule\n> = (id, sourceModule) => {\n if (!sourceModule.hot.active) {\n console.warn(\n `Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`\n )\n }\n\n const module = devModuleCache[id]\n\n if (sourceModule.children.indexOf(id) === -1) {\n sourceModule.children.push(id)\n }\n\n if (module) {\n if (module.error) {\n throw module.error\n }\n\n if (module.parents.indexOf(sourceModule.id) === -1) {\n module.parents.push(sourceModule.id)\n }\n\n return module\n }\n\n return instantiateModule(id, SourceType.Parent, sourceModule.id)\n}\n\nfunction DevContext(\n this: TurbopackDevContext,\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n) {\n Context.call(this, module, exports)\n this.k = refresh\n}\nDevContext.prototype = Context.prototype\n\ntype DevContextConstructor = {\n new (\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n ): TurbopackDevContext\n}\n\nfunction instantiateModule(\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): Module {\n // Browser: creates base HotModule object (hot API added by shared code)\n const createModuleObjectFn = (id: ModuleId) => {\n return createModuleObject(id) as HotModule\n }\n\n // Browser: creates DevContext with refresh\n const createContext = (\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n ) => {\n return new (DevContext as any as DevContextConstructor)(\n module,\n exports,\n refresh\n )\n }\n\n // Use shared instantiation logic (includes hot API setup)\n return instantiateModuleShared(\n moduleId,\n sourceType,\n sourceData,\n moduleFactories,\n devModuleCache,\n runtimeModules,\n createModuleObjectFn,\n createContext,\n runModuleExecutionHooks\n )\n}\n\nconst DUMMY_REFRESH_CONTEXT = {\n register: (_type: unknown, _id: unknown) => {},\n signature: () => (_type: unknown) => {},\n registerExports: (_module: unknown, _helpers: unknown) => {},\n}\n\n/**\n * NOTE(alexkirsz) Webpack has a \"module execution\" interception hook that\n * Next.js' React Refresh runtime hooks into to add module context to the\n * refresh registry.\n */\nfunction runModuleExecutionHooks(\n module: HotModule,\n executeModule: (ctx: RefreshContext) => void\n) {\n if (typeof globalThis.$RefreshInterceptModuleExecution$ === 'function') {\n const cleanupReactRefreshIntercept =\n globalThis.$RefreshInterceptModuleExecution$(module.id)\n try {\n executeModule({\n register: globalThis.$RefreshReg$,\n signature: globalThis.$RefreshSig$,\n registerExports: registerExportsAndSetupBoundaryForReactRefresh,\n })\n } finally {\n // Always cleanup the intercept, even if module execution failed.\n cleanupReactRefreshIntercept()\n }\n } else {\n // If the react refresh hooks are not installed we need to bind dummy functions.\n // This is expected when running in a Web Worker. It is also common in some of\n // our test environments.\n executeModule(DUMMY_REFRESH_CONTEXT)\n }\n}\n\n/**\n * This is adapted from https://github.com/vercel/next.js/blob/3466862d9dc9c8bb3131712134d38757b918d1c0/packages/react-refresh-utils/internal/ReactRefreshModule.runtime.ts\n */\nfunction registerExportsAndSetupBoundaryForReactRefresh(\n module: HotModule,\n helpers: RefreshHelpers\n) {\n const currentExports = module.exports\n const prevExports = module.hot.data.prevExports ?? null\n\n helpers.registerExportsForReactRefresh(currentExports, module.id)\n\n // A module can be accepted automatically based on its exports, e.g. when\n // it is a Refresh Boundary.\n if (helpers.isReactRefreshBoundary(currentExports)) {\n // Save the previous exports on update, so we can compare the boundary\n // signatures.\n module.hot.dispose((data) => {\n data.prevExports = currentExports\n })\n // Unconditionally accept an update to this module, we'll check if it's\n // still a Refresh Boundary later.\n module.hot.accept()\n\n // This field is set when the previous version of this module was a\n // Refresh Boundary, letting us know we need to check for invalidation or\n // enqueue an update.\n if (prevExports !== null) {\n // A boundary can become ineligible if its exports are incompatible\n // with the previous exports.\n //\n // For example, if you add/remove/change exports, we'll want to\n // re-execute the importing modules, and force those components to\n // re-render. Similarly, if you convert a class component to a\n // function, we want to invalidate the boundary.\n if (\n helpers.shouldInvalidateReactRefreshBoundary(\n helpers.getRefreshBoundarySignature(prevExports),\n helpers.getRefreshBoundarySignature(currentExports)\n )\n ) {\n module.hot.invalidate()\n } else {\n helpers.scheduleUpdate()\n }\n }\n } else {\n // Since we just executed the code for the module, it's possible that the\n // new exports made it ineligible for being a boundary.\n // We only care about the case when we were _previously_ a boundary,\n // because we already accepted this update (accidental side effect).\n const isNoLongerABoundary = prevExports !== null\n if (isNoLongerABoundary) {\n module.hot.invalidate()\n }\n }\n}\n\n/**\n * Adds, deletes, and moves modules between chunks. This must happen before the\n * dispose phase as it needs to know which modules were removed from all chunks,\n * which we can only compute *after* taking care of added and moved modules.\n */\nfunction updateChunksPhase(\n chunksAddedModules: Map>,\n chunksDeletedModules: Map>\n): { disposedModules: Set } {\n for (const [chunkPath, addedModuleIds] of chunksAddedModules) {\n for (const moduleId of addedModuleIds) {\n addModuleToChunk(moduleId, chunkPath)\n }\n }\n\n const disposedModules: Set = new Set()\n for (const [chunkPath, addedModuleIds] of chunksDeletedModules) {\n for (const moduleId of addedModuleIds) {\n if (removeModuleFromChunk(moduleId, chunkPath)) {\n disposedModules.add(moduleId)\n }\n }\n }\n\n return { disposedModules }\n}\n\nfunction applyUpdate(update: PartialUpdate) {\n switch (update.type) {\n case 'ChunkListUpdate':\n applyChunkListUpdate(update)\n break\n default:\n invariant(update, (update) => `Unknown update type: ${update.type}`)\n }\n}\n\nfunction applyChunkListUpdate(update: ChunkListUpdate) {\n if (update.merged != null) {\n for (const merged of update.merged) {\n switch (merged.type) {\n case 'EcmascriptMergedUpdate':\n applyEcmascriptMergedUpdate(merged)\n break\n default:\n invariant(merged, (merged) => `Unknown merged type: ${merged.type}`)\n }\n }\n }\n\n if (update.chunks != null) {\n for (const [chunkPath, chunkUpdate] of Object.entries(\n update.chunks\n ) as Array<[ChunkPath, ChunkUpdate]>) {\n const chunkUrl = getChunkRelativeUrl(chunkPath)\n\n switch (chunkUpdate.type) {\n case 'added':\n BACKEND.loadChunkCached(SourceType.Update, chunkUrl)\n break\n case 'total':\n DEV_BACKEND.reloadChunk?.(chunkUrl)\n break\n case 'deleted':\n DEV_BACKEND.unloadChunk?.(chunkUrl)\n break\n case 'partial':\n invariant(\n chunkUpdate.instruction,\n (instruction) =>\n `Unknown partial instruction: ${JSON.stringify(instruction)}.`\n )\n break\n default:\n invariant(\n chunkUpdate,\n (chunkUpdate) => `Unknown chunk update type: ${chunkUpdate.type}`\n )\n }\n }\n }\n}\n\nfunction applyEcmascriptMergedUpdate(update: EcmascriptMergedUpdate) {\n // Browser-specific chunk management phase\n const { entries = {}, chunks = {} } = update\n const { added, modified, chunksAdded, chunksDeleted } = computeChangedModules(\n entries,\n chunks,\n chunkModulesMap\n )\n const { disposedModules } = updateChunksPhase(chunksAdded, chunksDeleted)\n\n // Use shared HMR update implementation\n applyEcmascriptMergedUpdateShared({\n added,\n modified,\n disposedModules,\n evalModuleEntry: _eval, // browser's eval with source maps\n instantiateModule, // now wraps shared logic\n applyModuleFactoryName,\n moduleFactories,\n devModuleCache,\n autoAcceptRootModules: false,\n })\n}\n\nfunction handleApply(chunkListPath: ChunkListPath, update: ServerMessage) {\n switch (update.type) {\n case 'partial': {\n // This indicates that the update is can be applied to the current state of the application.\n applyUpdate(update.instruction)\n break\n }\n case 'restart': {\n // This indicates that there is no way to apply the update to the\n // current state of the application, and that the application must be\n // restarted.\n DEV_BACKEND.restart()\n break\n }\n case 'notFound': {\n // This indicates that the chunk list no longer exists: either the dynamic import which created it was removed,\n // or the page itself was deleted.\n // If it is a dynamic import, we simply discard all modules that the chunk has exclusive access to.\n // If it is a runtime chunk list, we restart the application.\n if (runtimeChunkLists.has(chunkListPath)) {\n DEV_BACKEND.restart()\n } else {\n disposeChunkList(chunkListPath)\n }\n break\n }\n default:\n throw new Error(`Unknown update type: ${update.type}`)\n }\n}\n\n/**\n * Removes a module from a chunk.\n * Returns `true` if there are no remaining chunks including this module.\n */\nfunction removeModuleFromChunk(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): boolean {\n const moduleChunks = moduleChunksMap.get(moduleId)!\n moduleChunks.delete(chunkPath)\n\n const chunkModules = chunkModulesMap.get(chunkPath)!\n chunkModules.delete(moduleId)\n\n const noRemainingModules = chunkModules.size === 0\n if (noRemainingModules) {\n chunkModulesMap.delete(chunkPath)\n }\n\n const noRemainingChunks = moduleChunks.size === 0\n if (noRemainingChunks) {\n moduleChunksMap.delete(moduleId)\n }\n\n return noRemainingChunks\n}\n\n/**\n * Disposes of a chunk list and its corresponding exclusive chunks.\n */\nfunction disposeChunkList(chunkListPath: ChunkListPath): boolean {\n const chunkPaths = chunkListChunksMap.get(chunkListPath)\n if (chunkPaths == null) {\n return false\n }\n chunkListChunksMap.delete(chunkListPath)\n\n for (const chunkPath of chunkPaths) {\n const chunkChunkLists = chunkChunkListsMap.get(chunkPath)!\n chunkChunkLists.delete(chunkListPath)\n\n if (chunkChunkLists.size === 0) {\n chunkChunkListsMap.delete(chunkPath)\n disposeChunk(chunkPath)\n }\n }\n\n // We must also dispose of the chunk list's chunk itself to ensure it may\n // be reloaded properly in the future.\n const chunkListUrl = getChunkRelativeUrl(chunkListPath)\n\n DEV_BACKEND.unloadChunk?.(chunkListUrl)\n\n return true\n}\n\n/**\n * Disposes of a chunk and its corresponding exclusive modules.\n *\n * @returns Whether the chunk was disposed of.\n */\nfunction disposeChunk(chunkPath: ChunkPath): boolean {\n const chunkUrl = getChunkRelativeUrl(chunkPath)\n // This should happen whether the chunk has any modules in it or not.\n // For instance, CSS chunks have no modules in them, but they still need to be unloaded.\n DEV_BACKEND.unloadChunk?.(chunkUrl)\n\n const chunkModules = chunkModulesMap.get(chunkPath)\n if (chunkModules == null) {\n return false\n }\n chunkModules.delete(chunkPath)\n\n for (const moduleId of chunkModules) {\n const moduleChunks = moduleChunksMap.get(moduleId)!\n moduleChunks.delete(chunkPath)\n\n const noRemainingChunks = moduleChunks.size === 0\n if (noRemainingChunks) {\n moduleChunksMap.delete(moduleId)\n disposeModule(moduleId, 'clear')\n availableModules.delete(moduleId)\n }\n }\n\n return true\n}\n\n/**\n * Adds a module to a chunk.\n */\nfunction addModuleToChunk(moduleId: ModuleId, chunkPath: ChunkPath) {\n let moduleChunks = moduleChunksMap.get(moduleId)\n if (!moduleChunks) {\n moduleChunks = new Set([chunkPath])\n moduleChunksMap.set(moduleId, moduleChunks)\n } else {\n moduleChunks.add(chunkPath)\n }\n\n let chunkModules = chunkModulesMap.get(chunkPath)\n if (!chunkModules) {\n chunkModules = new Set([moduleId])\n chunkModulesMap.set(chunkPath, chunkModules)\n } else {\n chunkModules.add(moduleId)\n }\n}\n\n/**\n * Marks a chunk list as a runtime chunk list. There can be more than one\n * runtime chunk list. For instance, integration tests can have multiple chunk\n * groups loaded at runtime, each with its own chunk list.\n */\nfunction markChunkListAsRuntime(chunkListPath: ChunkListPath) {\n runtimeChunkLists.add(chunkListPath)\n}\n\nfunction registerChunk(registration: ChunkRegistration) {\n const chunk = getChunkFromRegistration(registration[0]) as\n | ChunkPath\n | ChunkScript\n let runtimeParams: RuntimeParams | undefined\n // When bootstrapping we are passed a single runtimeParams object so we can distinguish purely based on length\n if (registration.length === 2) {\n runtimeParams = registration[1] as RuntimeParams\n } else {\n let chunkPath = getPathFromScript(chunk)\n runtimeParams = undefined\n installCompressedModuleFactories(\n registration as CompressedModuleFactories,\n /* offset= */ 1,\n moduleFactories,\n (id: ModuleId) => addModuleToChunk(id, chunkPath)\n )\n }\n return BACKEND.registerChunk(chunk, runtimeParams)\n}\n\n/**\n * Subscribes to chunk list updates from the update server and applies them.\n */\nfunction registerChunkList(chunkList: ChunkList) {\n const chunkListScript = getChunkFromRegistration(chunkList.script) as\n | ChunkListPath\n | ChunkListScript\n const chunkListPath = getPathFromScript(chunkListScript)\n // The \"chunk\" is also registered to finish the loading in the backend\n BACKEND.registerChunk(chunkListPath as string as ChunkPath)\n globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS!.push([\n chunkListPath,\n handleApply.bind(null, chunkListPath),\n ])\n\n // Adding chunks to chunk lists and vice versa.\n const chunkPaths = new Set(chunkList.chunks.map(getChunkPath))\n chunkListChunksMap.set(chunkListPath, chunkPaths)\n for (const chunkPath of chunkPaths) {\n let chunkChunkLists = chunkChunkListsMap.get(chunkPath)\n if (!chunkChunkLists) {\n chunkChunkLists = new Set([chunkListPath])\n chunkChunkListsMap.set(chunkPath, chunkChunkLists)\n } else {\n chunkChunkLists.add(chunkListPath)\n }\n }\n\n if (chunkList.source === 'entry') {\n markChunkListAsRuntime(chunkListPath)\n }\n}\n\nglobalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= []\n"],"names":["devContextPrototype","Context","prototype","devModuleCache","Object","create","c","runtimeModules","Set","createModuleWithDirectionFlag","moduleChunksMap","Map","chunkModulesMap","runtimeChunkLists","chunkListChunksMap","chunkChunkListsMap","getOrInstantiateRuntimeModule","chunkPath","moduleId","module","error","instantiateModule","SourceType","Runtime","getOrInstantiateModuleFromParent","id","sourceModule","hot","active","console","warn","children","indexOf","push","parents","Parent","DevContext","exports","refresh","call","k","sourceType","sourceData","createModuleObjectFn","createModuleObject","createContext","instantiateModuleShared","moduleFactories","runModuleExecutionHooks","DUMMY_REFRESH_CONTEXT","register","_type","_id","signature","registerExports","_module","_helpers","executeModule","globalThis","$RefreshInterceptModuleExecution$","cleanupReactRefreshIntercept","$RefreshReg$","$RefreshSig$","registerExportsAndSetupBoundaryForReactRefresh","helpers","currentExports","prevExports","data","registerExportsForReactRefresh","isReactRefreshBoundary","dispose","accept","shouldInvalidateReactRefreshBoundary","getRefreshBoundarySignature","invalidate","scheduleUpdate","isNoLongerABoundary","updateChunksPhase","chunksAddedModules","chunksDeletedModules","addedModuleIds","addModuleToChunk","disposedModules","removeModuleFromChunk","add","applyUpdate","update","type","applyChunkListUpdate","invariant","merged","applyEcmascriptMergedUpdate","chunks","chunkUpdate","entries","chunkUrl","getChunkRelativeUrl","BACKEND","loadChunkCached","Update","DEV_BACKEND","reloadChunk","unloadChunk","instruction","JSON","stringify","added","modified","chunksAdded","chunksDeleted","computeChangedModules","applyEcmascriptMergedUpdateShared","evalModuleEntry","_eval","applyModuleFactoryName","autoAcceptRootModules","handleApply","chunkListPath","restart","has","disposeChunkList","Error","moduleChunks","get","delete","chunkModules","noRemainingModules","size","noRemainingChunks","chunkPaths","chunkChunkLists","disposeChunk","chunkListUrl","disposeModule","availableModules","set","markChunkListAsRuntime","registerChunk","registration","chunk","getChunkFromRegistration","runtimeParams","length","getPathFromScript","undefined","installCompressedModuleFactories","registerChunkList","chunkList","chunkListScript","script","TURBOPACK_CHUNK_UPDATE_LISTENERS","bind","map","getChunkPath","source"],"mappings":"AAAA,iEAAiE;AACjE,kEAAkE;AAMlE,MAA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nH,mBAAmB4G,GAAG,CAAC1G;QAC7C,IAAI,CAACiH,iBAAiB;YACpBA,kBAAkB,IAAI1H,IAAI;gBAAC6G;aAAc;YACzCtG,mBAAmBwH,GAAG,CAACtH,WAAWiH;QACpC,OAAO;YACLA,gBAAgB9C,GAAG,CAACiC;QACtB;IACF;IAEA,IAAI8B,UAAUO,MAAM,KAAK,SAAS;QAChClB,uBAAuBnB;IACzB;AACF;AAEA3D,WAAW4F,gCAAgC,KAAK,EAAE","ignoreList":[0]}}, - {"offset": {"line": 1950, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/runtime-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack ECMAScript DOM runtime.\n *\n * It will be appended to the base runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\nfunction getAssetSuffixFromScriptSrc() {\n // TURBOPACK_ASSET_SUFFIX is set in web workers\n return (\n (self.TURBOPACK_ASSET_SUFFIX ??\n document?.currentScript\n ?.getAttribute?.('src')\n ?.replace(/^(.*(?=\\?)|^.*$)/, '')) ||\n ''\n )\n}\n\ntype ChunkResolver = {\n resolved: boolean\n loadingStarted: boolean\n resolve: () => void\n reject: (error?: Error) => void\n promise: Promise\n}\n\nlet BACKEND: RuntimeBackend\n\n/**\n * Maps chunk paths to the corresponding resolver.\n */\nconst chunkResolvers: Map = new Map()\n\n;(() => {\n BACKEND = {\n async registerChunk(chunk, params) {\n let chunkPath = getPathFromScript(chunk)\n let chunkUrl = getUrlFromScript(chunk)\n\n const resolver = getOrCreateResolver(chunkUrl)\n resolver.resolve()\n\n if (params == null) {\n return\n }\n\n for (const otherChunkData of params.otherChunks) {\n const otherChunkPath = getChunkPath(otherChunkData)\n const otherChunkUrl = getChunkRelativeUrl(otherChunkPath)\n\n // Chunk might have started loading, so we want to avoid triggering another load.\n getOrCreateResolver(otherChunkUrl)\n }\n\n // This waits for chunks to be loaded, but also marks included items as available.\n await Promise.all(\n params.otherChunks.map((otherChunkData) =>\n loadInitialChunk(chunkPath, otherChunkData)\n )\n )\n\n if (params.runtimeModuleIds.length > 0) {\n for (const moduleId of params.runtimeModuleIds) {\n getOrInstantiateRuntimeModule(chunkPath, moduleId)\n }\n }\n },\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n loadChunkCached(sourceType: SourceType, chunkUrl: ChunkUrl) {\n return doLoadChunk(sourceType, chunkUrl)\n },\n\n async loadWebAssembly(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n const { instance } = await WebAssembly.instantiateStreaming(\n req,\n importsObj\n )\n\n return instance.exports\n },\n\n async loadWebAssemblyModule(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n return await WebAssembly.compileStreaming(req)\n },\n }\n\n function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {\n let resolver = chunkResolvers.get(chunkUrl)\n if (!resolver) {\n let resolve: () => void\n let reject: (error?: Error) => void\n const promise = new Promise((innerResolve, innerReject) => {\n resolve = innerResolve\n reject = innerReject\n })\n resolver = {\n resolved: false,\n loadingStarted: false,\n promise,\n resolve: () => {\n resolver!.resolved = true\n resolve()\n },\n reject: reject!,\n }\n chunkResolvers.set(chunkUrl, resolver)\n }\n return resolver\n }\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n function doLoadChunk(sourceType: SourceType, chunkUrl: ChunkUrl) {\n const resolver = getOrCreateResolver(chunkUrl)\n if (resolver.loadingStarted) {\n return resolver.promise\n }\n\n if (sourceType === SourceType.Runtime) {\n // We don't need to load chunks references from runtime code, as they're already\n // present in the DOM.\n resolver.loadingStarted = true\n\n if (isCss(chunkUrl)) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n\n // We need to wait for JS chunks to register themselves within `registerChunk`\n // before we can start instantiating runtime modules, hence the absence of\n // `resolver.resolve()` in this branch.\n\n return resolver.promise\n }\n\n if (typeof importScripts === 'function') {\n // We're in a web worker\n if (isCss(chunkUrl)) {\n // ignore\n } else if (isJs(chunkUrl)) {\n self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl)\n importScripts(chunkUrl)\n } else {\n throw new Error(\n `can't infer type of chunk from URL ${chunkUrl} in worker`\n )\n }\n } else {\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n if (previousLinks.length > 0) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n } else {\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n link.href = chunkUrl\n link.onerror = () => {\n resolver.reject()\n }\n link.onload = () => {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(link)\n }\n } else if (isJs(chunkUrl)) {\n const previousScripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n if (previousScripts.length > 0) {\n // There is this edge where the script already failed loading, but we\n // can't detect that. The Promise will never resolve in this case.\n for (const script of Array.from(previousScripts)) {\n script.addEventListener('error', () => {\n resolver.reject()\n })\n }\n } else {\n const script = document.createElement('script')\n script.src = chunkUrl\n // We'll only mark the chunk as loaded once the script has been executed,\n // which happens in `registerChunk`. Hence the absence of `resolve()` in\n // this branch.\n script.onerror = () => {\n resolver.reject()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(script)\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n }\n\n resolver.loadingStarted = true\n return resolver.promise\n }\n\n function fetchWebAssembly(wasmChunkPath: ChunkPath) {\n return fetch(getChunkRelativeUrl(wasmChunkPath))\n }\n})()\n"],"names":["getAssetSuffixFromScriptSrc","self","TURBOPACK_ASSET_SUFFIX","document","currentScript","getAttribute","replace","BACKEND","chunkResolvers","Map","registerChunk","chunk","params","chunkPath","getPathFromScript","chunkUrl","getUrlFromScript","resolver","getOrCreateResolver","resolve","otherChunkData","otherChunks","otherChunkPath","getChunkPath","otherChunkUrl","getChunkRelativeUrl","Promise","all","map","loadInitialChunk","runtimeModuleIds","length","moduleId","getOrInstantiateRuntimeModule","loadChunkCached","sourceType","doLoadChunk","loadWebAssembly","_sourceType","_sourceData","wasmChunkPath","_edgeModule","importsObj","req","fetchWebAssembly","instance","WebAssembly","instantiateStreaming","exports","loadWebAssemblyModule","compileStreaming","get","reject","promise","innerResolve","innerReject","resolved","loadingStarted","set","SourceType","Runtime","isCss","importScripts","isJs","TURBOPACK_NEXT_CHUNK_URLS","push","Error","decodedChunkUrl","decodeURI","previousLinks","querySelectorAll","link","createElement","rel","href","onerror","onload","head","appendChild","previousScripts","script","Array","from","addEventListener","src","fetch"],"mappings":"AAAA;;;;CAIC,GAED,oDAAoD,GAEpD,sEAAsE;AACtE,mEAAmE;AAEnE,SAASA;IACP,+CAA+C;IAC/C,OACE,CAACC,KAAKC,sBAAsB,IAC1BC,UAAUC,eACNC,eAAe,QACfC,QAAQ,oBAAoB,GAAG,KACrC;AAEJ;AAUA,IAAIC;AAEJ;;CAEC,GACD,MAAMC,iBAA+C,IAAIC;AAExD,CAAC;IACAF,UAAU;QACR,MAAMG,eAAcC,KAA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2116, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/dev-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack development\n * ECMAScript DOM runtime.\n *\n * It will be appended to the base development runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n/// \n/// \n\nlet DEV_BACKEND: DevRuntimeBackend\n;(() => {\n DEV_BACKEND = {\n unloadChunk(chunkUrl) {\n deleteResolver(chunkUrl)\n\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const links = document.querySelectorAll(\n `link[href=\"${chunkUrl}\"],link[href^=\"${chunkUrl}?\"],link[href=\"${decodedChunkUrl}\"],link[href^=\"${decodedChunkUrl}?\"]`\n )\n for (const link of Array.from(links)) {\n link.remove()\n }\n } else if (isJs(chunkUrl)) {\n // Unloading a JS chunk would have no effect, as it lives in the JS\n // runtime once evaluated.\n // However, we still want to remove the script tag from the DOM to keep\n // the HTML somewhat consistent from the user's perspective.\n const scripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n for (const script of Array.from(scripts)) {\n script.remove()\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n },\n\n reloadChunk(chunkUrl) {\n return new Promise((resolve, reject) => {\n if (!isCss(chunkUrl)) {\n reject(new Error('The DOM backend can only reload CSS chunks'))\n return\n }\n\n const decodedChunkUrl = decodeURI(chunkUrl)\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n\n if (previousLinks.length === 0) {\n reject(new Error(`No link element found for chunk ${chunkUrl}`))\n return\n }\n\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n\n if (navigator.userAgent.includes('Firefox')) {\n // Firefox won't reload CSS files that were previously loaded on the current page,\n // we need to add a query param to make sure CSS is actually reloaded from the server.\n //\n // I believe this is this issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506\n //\n // Safari has a similar issue, but only if you have a `` tag\n // pointing to the same URL as the stylesheet: https://bugs.webkit.org/show_bug.cgi?id=187726\n link.href = `${chunkUrl}?ts=${Date.now()}`\n } else {\n link.href = chunkUrl\n }\n\n link.onerror = () => {\n reject()\n }\n link.onload = () => {\n // First load the new CSS, then remove the old ones. This prevents visible\n // flickering that would happen in-between removing the previous CSS and\n // loading the new one.\n for (const previousLink of Array.from(previousLinks))\n previousLink.remove()\n\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolve()\n }\n\n // Make sure to insert the new CSS right after the previous one, so that\n // its precedence is higher.\n previousLinks[0].parentElement!.insertBefore(\n link,\n previousLinks[0].nextSibling\n )\n })\n },\n\n restart: () => self.location.reload(),\n }\n\n function deleteResolver(chunkUrl: ChunkUrl) {\n chunkResolvers.delete(chunkUrl)\n }\n})()\n\nfunction _eval({ code, url, map }: EcmascriptModuleEntry): ModuleFactory {\n code += `\\n\\n//# sourceURL=${encodeURI(\n location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX\n )}`\n if (map) {\n code += `\\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(\n // btoa doesn't handle nonlatin characters, so escape them as \\x sequences\n // See https://stackoverflow.com/a/26603875\n unescape(encodeURIComponent(map))\n )}`\n }\n\n // eslint-disable-next-line no-eval\n return eval(code)\n}\n"],"names":["DEV_BACKEND","unloadChunk","chunkUrl","deleteResolver","decodedChunkUrl","decodeURI","isCss","links","document","querySelectorAll","link","Array","from","remove","isJs","scripts","script","Error","reloadChunk","Promise","resolve","reject","previousLinks","length","createElement","rel","navigator","userAgent","includes","href","Date","now","onerror","onload","previousLink","parentElement","insertBefore","nextSibling","restart","self","location","reload","chunkResolvers","delete","_eval","code","url","map","encodeURI","origin","CHUNK_BASE_PATH","ASSET_SUFFIX","btoa","unescape","encodeURIComponent","eval"],"mappings":"AAAA;;;;;CAKC,GAED,oDAAoD,GAEpD,gDAAgD;AAChD,4CAA4C;AAC5C,iDAAiD;AACjD,0DAA0D;AAE1D,IAAIA;AACH,CAAC;IACAA,cAAc;QACZC,aAAYC,QAAQ;YAClBC,eAAeD;YAEf,gFAAgF;YAChF,MAAME,kBAAkBC,UAAUH;YAElC,IAAII,MAAMJ,WAAW;gBACnB,MAAMK,QAAQC,SAASC,gBAAgB,CACrC,CAAC,WAAW,EAAEP,SAAS,eAAe,EAAEA,SAAS,eAAe,EAAEE,gBAAgB,eAAe,EAAEA,gBAAgB,GAAG,CAAC;gBAEzH,KAAK,MAAMM,QAAQC,MAAMC,IAAI,CAACL,OAAQ;oBACpCG,KAAKG,MAAM;gBACb;YACF,OAAO,IAAIC,KAAKZ,WAAW;gBACzB,mEAAmE;gBACnE,0BAA0B;gBAC1B,uEAAuE;gBACvE,4DAA4D;gBAC5D,MAAMa,UAAUP,SAASC,gBAAgB,CACvC,CAAC,YAAY,EAAEP,SAAS,gBAAgB,EAAEA,SAAS,gBAAgB,EAAEE,gBAAgB,gBAAgB,EAAEA,gBAAgB,GAAG,CAAC;gBAE7H,KAAK,MAAMY,UAAUL,MAAMC,IAAI,CAACG,SAAU;oBACxCC,OAAOH,MAAM;gBACf;YACF,OAAO;gBACL,MAAM,IAAII,MAAM,CAAC,mCAAmC,EAAEf,UAAU;YAClE;QACF;QAEAgB,aAAYhB,QAAQ;YAClB,OAAO,IAAIiB,QAAc,CAACC,SAASC;gBACjC,IAAI,CAACf,MAAMJ,WAAW;oBACpBmB,OAAO,IAAIJ,MAAM;oBACjB;gBACF;gBAEA,MAAMb,kBAAkBC,UAAUH;gBAClC,MAAMoB,gBAAgBd,SAASC,gBAAgB,CAC7C,CAAC,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;IACH,IAAIJ,KAAK;QACPF,QAAQ,CAAC,kEAAkE,EAAEO,KAC3E,0EAA0E;QAC1E,2CAA2C;QAC3CC,SAASC,mBAAmBP,QAC3B;IACL;IAEA,mCAAmC;IACnC,OAAOQ,KAAKV;AACd","ignoreList":[0]}}] + {"offset": {"line": 1950, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/runtime-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack ECMAScript DOM runtime.\n *\n * It will be appended to the base runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\nfunction getAssetSuffixFromScriptSrc() {\n // TURBOPACK_ASSET_SUFFIX is set in web workers\n if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX\n const src = document?.currentScript?.getAttribute?.('src') ?? ''\n const qi = src.indexOf('?')\n return qi >= 0 ? src.slice(qi) : ''\n}\n\ntype ChunkResolver = {\n resolved: boolean\n loadingStarted: boolean\n resolve: () => void\n reject: (error?: Error) => void\n promise: Promise\n}\n\nlet BACKEND: RuntimeBackend\n\n/**\n * Maps chunk paths to the corresponding resolver.\n */\nconst chunkResolvers: Map = new Map()\n\n;(() => {\n BACKEND = {\n async registerChunk(chunk, params) {\n let chunkPath = getPathFromScript(chunk)\n let chunkUrl = getUrlFromScript(chunk)\n\n const resolver = getOrCreateResolver(chunkUrl)\n resolver.resolve()\n\n if (params == null) {\n return\n }\n\n for (const otherChunkData of params.otherChunks) {\n const otherChunkPath = getChunkPath(otherChunkData)\n const otherChunkUrl = getChunkRelativeUrl(otherChunkPath)\n\n // Chunk might have started loading, so we want to avoid triggering another load.\n getOrCreateResolver(otherChunkUrl)\n }\n\n // This waits for chunks to be loaded, but also marks included items as available.\n await Promise.all(\n params.otherChunks.map((otherChunkData) =>\n loadInitialChunk(chunkPath, otherChunkData)\n )\n )\n\n if (params.runtimeModuleIds.length > 0) {\n for (const moduleId of params.runtimeModuleIds) {\n getOrInstantiateRuntimeModule(chunkPath, moduleId)\n }\n }\n },\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n loadChunkCached(sourceType: SourceType, chunkUrl: ChunkUrl) {\n return doLoadChunk(sourceType, chunkUrl)\n },\n\n async loadWebAssembly(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n const { instance } = await WebAssembly.instantiateStreaming(\n req,\n importsObj\n )\n\n return instance.exports\n },\n\n async loadWebAssemblyModule(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n return await WebAssembly.compileStreaming(req)\n },\n }\n\n function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {\n let resolver = chunkResolvers.get(chunkUrl)\n if (!resolver) {\n let resolve: () => void\n let reject: (error?: Error) => void\n const promise = new Promise((innerResolve, innerReject) => {\n resolve = innerResolve\n reject = innerReject\n })\n resolver = {\n resolved: false,\n loadingStarted: false,\n promise,\n resolve: () => {\n resolver!.resolved = true\n resolve()\n },\n reject: reject!,\n }\n chunkResolvers.set(chunkUrl, resolver)\n }\n return resolver\n }\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n function doLoadChunk(sourceType: SourceType, chunkUrl: ChunkUrl) {\n const resolver = getOrCreateResolver(chunkUrl)\n if (resolver.loadingStarted) {\n return resolver.promise\n }\n\n if (sourceType === SourceType.Runtime) {\n // We don't need to load chunks references from runtime code, as they're already\n // present in the DOM.\n resolver.loadingStarted = true\n\n if (isCss(chunkUrl)) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n\n // We need to wait for JS chunks to register themselves within `registerChunk`\n // before we can start instantiating runtime modules, hence the absence of\n // `resolver.resolve()` in this branch.\n\n return resolver.promise\n }\n\n if (typeof importScripts === 'function') {\n // We're in a web worker\n if (isCss(chunkUrl)) {\n // ignore\n } else if (isJs(chunkUrl)) {\n self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl)\n importScripts(chunkUrl)\n } else {\n throw new Error(\n `can't infer type of chunk from URL ${chunkUrl} in worker`\n )\n }\n } else {\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n if (previousLinks.length > 0) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n } else {\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n link.href = chunkUrl\n link.onerror = () => {\n resolver.reject()\n }\n link.onload = () => {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(link)\n }\n } else if (isJs(chunkUrl)) {\n const previousScripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n if (previousScripts.length > 0) {\n // There is this edge where the script already failed loading, but we\n // can't detect that. The Promise will never resolve in this case.\n for (const script of Array.from(previousScripts)) {\n script.addEventListener('error', () => {\n resolver.reject()\n })\n }\n } else {\n const script = document.createElement('script')\n script.src = chunkUrl\n // We'll only mark the chunk as loaded once the script has been executed,\n // which happens in `registerChunk`. Hence the absence of `resolve()` in\n // this branch.\n script.onerror = () => {\n resolver.reject()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(script)\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n }\n\n resolver.loadingStarted = true\n return resolver.promise\n }\n\n function fetchWebAssembly(wasmChunkPath: ChunkPath) {\n return fetch(getChunkRelativeUrl(wasmChunkPath))\n }\n})()\n"],"names":["getAssetSuffixFromScriptSrc","self","TURBOPACK_ASSET_SUFFIX","src","document","currentScript","getAttribute","qi","indexOf","slice","BACKEND","chunkResolvers","Map","registerChunk","chunk","params","chunkPath","getPathFromScript","chunkUrl","getUrlFromScript","resolver","getOrCreateResolver","resolve","otherChunkData","otherChunks","otherChunkPath","getChunkPath","otherChunkUrl","getChunkRelativeUrl","Promise","all","map","loadInitialChunk","runtimeModuleIds","length","moduleId","getOrInstantiateRuntimeModule","loadChunkCached","sourceType","doLoadChunk","loadWebAssembly","_sourceType","_sourceData","wasmChunkPath","_edgeModule","importsObj","req","fetchWebAssembly","instance","WebAssembly","instantiateStreaming","exports","loadWebAssemblyModule","compileStreaming","get","reject","promise","innerResolve","innerReject","resolved","loadingStarted","set","SourceType","Runtime","isCss","importScripts","isJs","TURBOPACK_NEXT_CHUNK_URLS","push","Error","decodedChunkUrl","decodeURI","previousLinks","querySelectorAll","link","createElement","rel","href","onerror","onload","head","appendChild","previousScripts","script","Array","from","addEventListener","fetch"],"mappings":"AAAA;;;;CAIC,GAED,oDAAoD,GAEpD,sEAAsE;AACtE,mEAAmE;AAEnE,SAASA;IACP,+CAA+C;IAC/C,IAAIC,KAAKC,sBAAsB,IAAI,MAAM,OAAOD,KAAKC,sBAAsB;IAC3E,MAAMC,MAAMC,UAAUC,eAAeC,eAAe,UAAU;IAC9D,MAAMC,KAAKJ,IAAIK,OAAO,CAAC;IACvB,OAAOD,MAAM,IAAIJ,IAAIM,KAAK,CAACF,MAAM;AACnC;AAUA,IAAIG;AAEJ;;CAEC,GACD,MAAMC,iBAA+C,IAAIC;AAExD,CAAC;IACAF,UAAU;QACR,MAAMG,e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"offset": {"line": 2119, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/dev-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack development\n * ECMAScript DOM runtime.\n *\n * It will be appended to the base development runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n/// \n/// \n\nlet DEV_BACKEND: DevRuntimeBackend\n;(() => {\n DEV_BACKEND = {\n unloadChunk(chunkUrl) {\n deleteResolver(chunkUrl)\n\n // Strip query string so we match links regardless of cache-busting\n // params (e.g. ?ts=) that may differ between HMR updates.\n const baseChunkUrl = chunkUrl.split('?')[0]\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedBaseChunkUrl = decodeURI(baseChunkUrl)\n\n if (isCss(chunkUrl)) {\n const links = document.querySelectorAll(\n `link[href=\"${baseChunkUrl}\"],link[href^=\"${baseChunkUrl}?\"],link[href=\"${decodedBaseChunkUrl}\"],link[href^=\"${decodedBaseChunkUrl}?\"]`\n )\n for (const link of Array.from(links)) {\n link.remove()\n }\n } else if (isJs(chunkUrl)) {\n // Unloading a JS chunk would have no effect, as it lives in the JS\n // runtime once evaluated.\n // However, we still want to remove the script tag from the DOM to keep\n // the HTML somewhat consistent from the user's perspective.\n const scripts = document.querySelectorAll(\n `script[src=\"${baseChunkUrl}\"],script[src^=\"${baseChunkUrl}?\"],script[src=\"${decodedBaseChunkUrl}\"],script[src^=\"${decodedBaseChunkUrl}?\"]`\n )\n for (const script of Array.from(scripts)) {\n script.remove()\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n },\n\n reloadChunk(chunkUrl) {\n return new Promise((resolve, reject) => {\n if (!isCss(chunkUrl)) {\n reject(new Error('The DOM backend can only reload CSS chunks'))\n return\n }\n\n // Strip query string so we match links regardless of cache-busting\n // params (e.g. ?ts=) that may differ between HMR updates.\n const baseChunkUrl = chunkUrl.split('?')[0]\n const decodedBaseChunkUrl = decodeURI(baseChunkUrl)\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${baseChunkUrl}\"],link[rel=stylesheet][href^=\"${baseChunkUrl}?\"],link[rel=stylesheet][href=\"${decodedBaseChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedBaseChunkUrl}?\"]`\n )\n\n if (previousLinks.length === 0) {\n reject(new Error(`No link element found for chunk ${chunkUrl}`))\n return\n }\n\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n\n if (\n navigator.userAgent.includes('Firefox') ||\n (navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome') &&\n !navigator.userAgent.includes('Chromium'))\n ) {\n // Firefox won't reload CSS files that were previously loaded on the\n // current page: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506\n //\n // Safari serves cached CSS when a exists for the\n // same URL: https://bugs.webkit.org/show_bug.cgi?id=187726\n //\n // Replace or add a fresh `ts` cache-busting param without\n // discarding other query parameters that may already be present.\n const url = new URL(chunkUrl, location.origin)\n url.searchParams.set('ts', String(Date.now()))\n // Reduced timer precision in some browers could lead to an update getting dropped\n // in firefox if it happens fast enough (in firefox precision is sometimes 100ms!).\n // So trust that the server is only updating us when it is important and use a\n // random number to bust the cache.\n url.searchParams.set('_next_rand', String(Math.random()))\n link.href = url.pathname + url.search\n } else {\n link.href = chunkUrl\n }\n\n link.onerror = () => {\n reject()\n }\n link.onload = () => {\n // First load the new CSS, then remove the old ones. This prevents visible\n // flickering that would happen in-between removing the previous CSS and\n // loading the new one.\n for (const previousLink of Array.from(previousLinks))\n previousLink.remove()\n\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolve()\n }\n\n // Make sure to insert the new CSS right after the previous one, so that\n // its precedence is higher.\n previousLinks[0].parentElement!.insertBefore(\n link,\n previousLinks[0].nextSibling\n )\n })\n },\n\n restart: () => self.location.reload(),\n }\n\n function deleteResolver(chunkUrl: ChunkUrl) {\n chunkResolvers.delete(chunkUrl)\n }\n})()\n\nfunction _eval({ code, url, map }: EcmascriptModuleEntry): ModuleFactory {\n code += `\\n\\n//# sourceURL=${encodeURI(\n location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX\n )}`\n if (map) {\n code += `\\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(\n // btoa doesn't handle nonlatin characters, so escape them as \\x sequences\n // See https://stackoverflow.com/a/26603875\n unescape(encodeURIComponent(map))\n )}`\n }\n\n // eslint-disable-next-line no-eval\n return eval(code)\n}\n"],"names":["DEV_BACKEND","unloadChunk","chunkUrl","deleteResolver","baseChunkUrl","split","decodedBaseChunkUrl","decodeURI","isCss","links","document","querySelectorAll","link","Array","from","remove","isJs","scripts","script","Error","reloadChunk","Promise","resolve","reject","previousLinks","length","createElement","rel","navigator","userAgent","includes","url","URL","location","origin","searchParams","set","String","Date","now","Math","random","href","pathname","search","onerror","onload","previousLink","parentElement","insertBefore","nextSibling","restart","self","reload","chunkResolvers","delete","_eval","code","map","encodeURI","CHUNK_BASE_PATH","ASSET_SUFFIX","btoa","unescape","encodeURIComponent","eval"],"mappings":"AAAA;;;;;CAKC,GAED,oDAAoD,GAEpD,gDAAgD;AAChD,4CAA4C;AAC5C,iDAAiD;AACjD,0DAA0D;AAE1D,IAAIA;AACH,CAAC;IACAA,cAAc;QACZC,aAAYC,QAAQ;YAClBC,eAAeD;YAEf,mEAAmE;YACnE,0DAA0D;YAC1D,MAAME,eAAeF,SAASG,KAAK,CAAC,IAAI,CAAC,EAAE;YAC3C,gFAAgF;YAChF,MAAMC,sBAAsBC,UAAUH;YAEtC,IAAII,MAAMN,WAAW;gBACnB,MAAMO,QAAQC,SAASC,gBAAgB,CACrC,CAAC,WAAW,EAAEP,aAAa,eAAe,EAAEA,aAAa,eAAe,EAAEE,oBAAoB,eAAe,EAAEA,oBAAoB,GAAG,CAAC;gBAEzI,KAAK,MAAMM,QAAQC,MAAMC,IAAI,CAACL,OAAQ;oBACpCG,KAAKG,MAAM;gBACb;YACF,OAAO,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mCAAmC;IACnC,OAAOO,KAAKR;AACd","ignoreList":[0]}}] } \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/output/0v.~_crates_turbopack-tests_tests_snapshot_workers_basic_input_index_03~su6s.js b/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/output/0v.~_crates_turbopack-tests_tests_snapshot_workers_basic_input_index_03~su6s.js index 83ae2090dc13..a7b4968af59a 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/output/0v.~_crates_turbopack-tests_tests_snapshot_workers_basic_input_index_03~su6s.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/output/0v.~_crates_turbopack-tests_tests_snapshot_workers_basic_input_index_03~su6s.js @@ -1956,7 +1956,10 @@ globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= []; /// function getAssetSuffixFromScriptSrc() { // TURBOPACK_ASSET_SUFFIX is set in web workers - return (self.TURBOPACK_ASSET_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || ''; + if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX; + const src = document?.currentScript?.getAttribute?.('src') ?? ''; + const qi = src.indexOf('?'); + return qi >= 0 ? src.slice(qi) : ''; } let BACKEND; /** @@ -2128,10 +2131,13 @@ let DEV_BACKEND; DEV_BACKEND = { unloadChunk (chunkUrl) { deleteResolver(chunkUrl); + // Strip query string so we match links regardless of cache-busting + // params (e.g. ?ts=) that may differ between HMR updates. + const baseChunkUrl = chunkUrl.split('?')[0]; // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped. - const decodedChunkUrl = decodeURI(chunkUrl); + const decodedBaseChunkUrl = decodeURI(baseChunkUrl); if (isCss(chunkUrl)) { - const links = document.querySelectorAll(`link[href="${chunkUrl}"],link[href^="${chunkUrl}?"],link[href="${decodedChunkUrl}"],link[href^="${decodedChunkUrl}?"]`); + const links = document.querySelectorAll(`link[href="${baseChunkUrl}"],link[href^="${baseChunkUrl}?"],link[href="${decodedBaseChunkUrl}"],link[href^="${decodedBaseChunkUrl}?"]`); for (const link of Array.from(links)){ link.remove(); } @@ -2140,7 +2146,7 @@ let DEV_BACKEND; // runtime once evaluated. // However, we still want to remove the script tag from the DOM to keep // the HTML somewhat consistent from the user's perspective. - const scripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); + const scripts = document.querySelectorAll(`script[src="${baseChunkUrl}"],script[src^="${baseChunkUrl}?"],script[src="${decodedBaseChunkUrl}"],script[src^="${decodedBaseChunkUrl}?"]`); for (const script of Array.from(scripts)){ script.remove(); } @@ -2154,23 +2160,34 @@ let DEV_BACKEND; reject(new Error('The DOM backend can only reload CSS chunks')); return; } - const decodedChunkUrl = decodeURI(chunkUrl); - const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`); + // Strip query string so we match links regardless of cache-busting + // params (e.g. ?ts=) that may differ between HMR updates. + const baseChunkUrl = chunkUrl.split('?')[0]; + const decodedBaseChunkUrl = decodeURI(baseChunkUrl); + const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${baseChunkUrl}"],link[rel=stylesheet][href^="${baseChunkUrl}?"],link[rel=stylesheet][href="${decodedBaseChunkUrl}"],link[rel=stylesheet][href^="${decodedBaseChunkUrl}?"]`); if (previousLinks.length === 0) { reject(new Error(`No link element found for chunk ${chunkUrl}`)); return; } const link = document.createElement('link'); link.rel = 'stylesheet'; - if (navigator.userAgent.includes('Firefox')) { - // Firefox won't reload CSS files that were previously loaded on the current page, - // we need to add a query param to make sure CSS is actually reloaded from the server. + if (navigator.userAgent.includes('Firefox') || navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome') && !navigator.userAgent.includes('Chromium')) { + // Firefox won't reload CSS files that were previously loaded on the + // current page: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506 // - // I believe this is this issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506 + // Safari serves cached CSS when a exists for the + // same URL: https://bugs.webkit.org/show_bug.cgi?id=187726 // - // Safari has a similar issue, but only if you have a `` tag - // pointing to the same URL as the stylesheet: https://bugs.webkit.org/show_bug.cgi?id=187726 - link.href = `${chunkUrl}?ts=${Date.now()}`; + // Replace or add a fresh `ts` cache-busting param without + // discarding other query parameters that may already be present. + const url = new URL(chunkUrl, location.origin); + url.searchParams.set('ts', String(Date.now())); + // Reduced timer precision in some browers could lead to an update getting dropped + // in firefox if it happens fast enough (in firefox precision is sometimes 100ms!). + // So trust that the server is only updating us when it is important and use a + // random number to bust the cache. + url.searchParams.set('_next_rand', String(Math.random())); + link.href = url.pathname + url.search; } else { link.href = chunkUrl; } diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/output/0v.~_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_11ydsw-.js b/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/output/0v.~_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_11ydsw-.js index 2ab9532a80f5..da009fe7ab87 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/output/0v.~_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_11ydsw-.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/output/0v.~_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_11ydsw-.js @@ -1956,7 +1956,10 @@ globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= []; /// function getAssetSuffixFromScriptSrc() { // TURBOPACK_ASSET_SUFFIX is set in web workers - return (self.TURBOPACK_ASSET_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || ''; + if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX; + const src = document?.currentScript?.getAttribute?.('src') ?? ''; + const qi = src.indexOf('?'); + return qi >= 0 ? src.slice(qi) : ''; } let BACKEND; /** @@ -2128,10 +2131,13 @@ let DEV_BACKEND; DEV_BACKEND = { unloadChunk (chunkUrl) { deleteResolver(chunkUrl); + // Strip query string so we match links regardless of cache-busting + // params (e.g. ?ts=) that may differ between HMR updates. + const baseChunkUrl = chunkUrl.split('?')[0]; // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped. - const decodedChunkUrl = decodeURI(chunkUrl); + const decodedBaseChunkUrl = decodeURI(baseChunkUrl); if (isCss(chunkUrl)) { - const links = document.querySelectorAll(`link[href="${chunkUrl}"],link[href^="${chunkUrl}?"],link[href="${decodedChunkUrl}"],link[href^="${decodedChunkUrl}?"]`); + const links = document.querySelectorAll(`link[href="${baseChunkUrl}"],link[href^="${baseChunkUrl}?"],link[href="${decodedBaseChunkUrl}"],link[href^="${decodedBaseChunkUrl}?"]`); for (const link of Array.from(links)){ link.remove(); } @@ -2140,7 +2146,7 @@ let DEV_BACKEND; // runtime once evaluated. // However, we still want to remove the script tag from the DOM to keep // the HTML somewhat consistent from the user's perspective. - const scripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); + const scripts = document.querySelectorAll(`script[src="${baseChunkUrl}"],script[src^="${baseChunkUrl}?"],script[src="${decodedBaseChunkUrl}"],script[src^="${decodedBaseChunkUrl}?"]`); for (const script of Array.from(scripts)){ script.remove(); } @@ -2154,23 +2160,34 @@ let DEV_BACKEND; reject(new Error('The DOM backend can only reload CSS chunks')); return; } - const decodedChunkUrl = decodeURI(chunkUrl); - const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`); + // Strip query string so we match links regardless of cache-busting + // params (e.g. ?ts=) that may differ between HMR updates. + const baseChunkUrl = chunkUrl.split('?')[0]; + const decodedBaseChunkUrl = decodeURI(baseChunkUrl); + const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${baseChunkUrl}"],link[rel=stylesheet][href^="${baseChunkUrl}?"],link[rel=stylesheet][href="${decodedBaseChunkUrl}"],link[rel=stylesheet][href^="${decodedBaseChunkUrl}?"]`); if (previousLinks.length === 0) { reject(new Error(`No link element found for chunk ${chunkUrl}`)); return; } const link = document.createElement('link'); link.rel = 'stylesheet'; - if (navigator.userAgent.includes('Firefox')) { - // Firefox won't reload CSS files that were previously loaded on the current page, - // we need to add a query param to make sure CSS is actually reloaded from the server. + if (navigator.userAgent.includes('Firefox') || navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome') && !navigator.userAgent.includes('Chromium')) { + // Firefox won't reload CSS files that were previously loaded on the + // current page: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506 // - // I believe this is this issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506 + // Safari serves cached CSS when a exists for the + // same URL: https://bugs.webkit.org/show_bug.cgi?id=187726 // - // Safari has a similar issue, but only if you have a `` tag - // pointing to the same URL as the stylesheet: https://bugs.webkit.org/show_bug.cgi?id=187726 - link.href = `${chunkUrl}?ts=${Date.now()}`; + // Replace or add a fresh `ts` cache-busting param without + // discarding other query parameters that may already be present. + const url = new URL(chunkUrl, location.origin); + url.searchParams.set('ts', String(Date.now())); + // Reduced timer precision in some browers could lead to an update getting dropped + // in firefox if it happens fast enough (in firefox precision is sometimes 100ms!). + // So trust that the server is only updating us when it is important and use a + // random number to bust the cache. + url.searchParams.set('_next_rand', String(Math.random())); + link.href = url.pathname + url.search; } else { link.href = chunkUrl; } diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/output/0teu_crates_turbopack-tests_tests_snapshot_workers_shared_input_index_00pjotx.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/output/0teu_crates_turbopack-tests_tests_snapshot_workers_shared_input_index_00pjotx.js.map index 8d17818c396f..e9d426222813 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/output/0teu_crates_turbopack-tests_tests_snapshot_workers_shared_input_index_00pjotx.js.map +++ b/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/output/0teu_crates_turbopack-tests_tests_snapshot_workers_shared_input_index_00pjotx.js.map @@ -6,6 +6,6 @@ {"offset": {"line": 590, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/runtime-base.ts"],"sourcesContent":["/**\n * This file contains runtime types and functions that are shared between all\n * Turbopack *browser* ECMAScript runtimes.\n *\n * It will be appended to the runtime code of each runtime right after the\n * shared runtime utils.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\n// Used in WebWorkers to tell the runtime about the chunk suffix\ndeclare var TURBOPACK_ASSET_SUFFIX: string\n// Used in WebWorkers to tell the runtime about the current chunk url since it\n// can't be detected via `document.currentScript`. Note it's stored in reversed\n// order to use `push` and `pop`\ndeclare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined\n\n// Injected by rust code\ndeclare var CHUNK_BASE_PATH: string\ndeclare var ASSET_SUFFIX: string\ndeclare var WORKER_FORWARDED_GLOBALS: string[]\n\ninterface TurbopackBrowserBaseContext extends TurbopackBaseContext {\n R: ResolvePathFromModule\n}\n\nconst browserContextPrototype =\n Context.prototype as TurbopackBrowserBaseContext\n\n// Provided by build or dev base\ndeclare function instantiateModule(\n id: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): Module\n\ntype RuntimeParams = {\n otherChunks: ChunkData[]\n runtimeModuleIds: ModuleId[]\n}\n\ntype ChunkRegistrationChunk =\n | ChunkPath\n | { getAttribute: (name: string) => string | null }\n | undefined\n\ntype ChunkRegistration = [\n chunkPath: ChunkRegistrationChunk,\n ...([RuntimeParams] | CompressedModuleFactories),\n]\n\ntype ChunkList = {\n script: ChunkRegistrationChunk\n chunks: ChunkData[]\n source: 'entry' | 'dynamic'\n}\n\ninterface RuntimeBackend {\n registerChunk: (\n chunkPath: ChunkPath | ChunkScript,\n params?: RuntimeParams\n ) => void\n /**\n * Returns the same Promise for the same chunk URL.\n */\n loadChunkCached: (sourceType: SourceType, chunkUrl: ChunkUrl) => Promise\n loadWebAssembly: (\n sourceType: SourceType,\n sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ) => Promise\n loadWebAssemblyModule: (\n sourceType: SourceType,\n sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module\n ) => Promise\n}\n\ninterface DevRuntimeBackend {\n reloadChunk?: (chunkUrl: ChunkUrl) => Promise\n unloadChunk?: (chunkUrl: ChunkUrl) => void\n restart: () => void\n}\n\nconst moduleFactories: ModuleFactories = new Map()\ncontextPrototype.M = moduleFactories\n\nconst availableModules: Map | true> = new Map()\n\nconst availableModuleChunks: Map | true> = new Map()\n\nfunction loadChunk(\n this: TurbopackBrowserBaseContext,\n chunkData: ChunkData\n): Promise {\n return loadChunkInternal(SourceType.Parent, this.m.id, chunkData)\n}\nbrowserContextPrototype.l = loadChunk\n\nfunction loadInitialChunk(chunkPath: ChunkPath, chunkData: ChunkData) {\n return loadChunkInternal(SourceType.Runtime, chunkPath, chunkData)\n}\n\nasync function loadChunkInternal(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkData: ChunkData\n): Promise {\n if (typeof chunkData === 'string') {\n return loadChunkPath(sourceType, sourceData, chunkData)\n }\n\n const includedList = chunkData.included || []\n const modulesPromises = includedList.map((included) => {\n if (moduleFactories.has(included)) return true\n return availableModules.get(included)\n })\n if (modulesPromises.length > 0 && modulesPromises.every((p) => p)) {\n // When all included items are already loaded or loading, we can skip loading ourselves\n await Promise.all(modulesPromises)\n return\n }\n\n const includedModuleChunksList = chunkData.moduleChunks || []\n const moduleChunksPromises = includedModuleChunksList\n .map((included) => {\n // TODO(alexkirsz) Do we need this check?\n // if (moduleFactories[included]) return true;\n return availableModuleChunks.get(included)\n })\n .filter((p) => p)\n\n let promise: Promise\n if (moduleChunksPromises.length > 0) {\n // Some module chunks are already loaded or loading.\n\n if (moduleChunksPromises.length === includedModuleChunksList.length) {\n // When all included module chunks are already loaded or loading, we can skip loading ourselves\n await Promise.all(moduleChunksPromises)\n return\n }\n\n const moduleChunksToLoad: Set = new Set()\n for (const moduleChunk of includedModuleChunksList) {\n if (!availableModuleChunks.has(moduleChunk)) {\n moduleChunksToLoad.add(moduleChunk)\n }\n }\n\n for (const moduleChunkToLoad of moduleChunksToLoad) {\n const promise = loadChunkPath(sourceType, sourceData, moduleChunkToLoad)\n\n availableModuleChunks.set(moduleChunkToLoad, promise)\n\n moduleChunksPromises.push(promise)\n }\n\n promise = Promise.all(moduleChunksPromises)\n } else {\n promise = loadChunkPath(sourceType, sourceData, chunkData.path)\n\n // Mark all included module chunks as loading if they are not already loaded or loading.\n for (const includedModuleChunk of includedModuleChunksList) {\n if (!availableModuleChunks.has(includedModuleChunk)) {\n availableModuleChunks.set(includedModuleChunk, promise)\n }\n }\n }\n\n for (const included of includedList) {\n if (!availableModules.has(included)) {\n // It might be better to race old and new promises, but it's rare that the new promise will be faster than a request started earlier.\n // In production it's even more rare, because the chunk optimization tries to deduplicate modules anyway.\n availableModules.set(included, promise)\n }\n }\n\n await promise\n}\n\nconst loadedChunk = Promise.resolve(undefined)\nconst instrumentedBackendLoadChunks = new WeakMap<\n Promise,\n Promise | typeof loadedChunk\n>()\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkByUrl(\n this: TurbopackBrowserBaseContext,\n chunkUrl: ChunkUrl\n) {\n return loadChunkByUrlInternal(SourceType.Parent, this.m.id, chunkUrl)\n}\nbrowserContextPrototype.L = loadChunkByUrl\n\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkByUrlInternal(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkUrl: ChunkUrl\n): Promise {\n const thenable = BACKEND.loadChunkCached(sourceType, chunkUrl)\n let entry = instrumentedBackendLoadChunks.get(thenable)\n if (entry === undefined) {\n const resolve = instrumentedBackendLoadChunks.set.bind(\n instrumentedBackendLoadChunks,\n thenable,\n loadedChunk\n )\n entry = thenable.then(resolve).catch((cause) => {\n let loadReason: string\n switch (sourceType) {\n case SourceType.Runtime:\n loadReason = `as a runtime dependency of chunk ${sourceData}`\n break\n case SourceType.Parent:\n loadReason = `from module ${sourceData}`\n break\n case SourceType.Update:\n loadReason = 'from an HMR update'\n break\n default:\n invariant(\n sourceType,\n (sourceType) => `Unknown source type: ${sourceType}`\n )\n }\n let error = new Error(\n `Failed to load chunk ${chunkUrl} ${loadReason}${\n cause ? `: ${cause}` : ''\n }`,\n cause ? { cause } : undefined\n )\n error.name = 'ChunkLoadError'\n throw error\n })\n instrumentedBackendLoadChunks.set(thenable, entry)\n }\n\n return entry\n}\n\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkPath(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkPath: ChunkPath\n): Promise {\n const url = getChunkRelativeUrl(chunkPath)\n return loadChunkByUrlInternal(sourceType, sourceData, url)\n}\n\n/**\n * Returns an absolute url to an asset.\n */\nfunction resolvePathFromModule(\n this: TurbopackBaseContext,\n moduleId: string\n): string {\n const exported = this.r(moduleId)\n return exported?.default ?? exported\n}\nbrowserContextPrototype.R = resolvePathFromModule\n\n/**\n * no-op for browser\n * @param modulePath\n */\nfunction resolveAbsolutePath(modulePath?: string): string {\n return `/ROOT/${modulePath ?? ''}`\n}\nbrowserContextPrototype.P = resolveAbsolutePath\n\n/**\n * Exports a URL with the static suffix appended.\n */\nfunction exportUrl(\n this: TurbopackBrowserBaseContext,\n url: string,\n id: ModuleId | undefined\n) {\n exportValue.call(this, `${url}${ASSET_SUFFIX}`, id)\n}\nbrowserContextPrototype.q = exportUrl\n\n/**\n * Creates a worker by instantiating the given WorkerConstructor with the\n * appropriate URL and options.\n *\n * The entrypoint is a pre-compiled worker runtime file. The params configure\n * which module chunks to load and which module to run as the entry point.\n *\n * The params are a JSON array of the following structure:\n * `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`\n *\n * @param WorkerConstructor The Worker or SharedWorker constructor\n * @param entrypoint URL path to the worker entrypoint chunk\n * @param moduleChunks list of module chunk paths to load\n * @param workerOptions options to pass to the Worker constructor (optional)\n */\nfunction createWorker(\n WorkerConstructor: { new (url: URL, options?: object): Worker },\n entrypoint: ChunkPath,\n moduleChunks: ChunkPath[],\n workerOptions?: object\n): Worker {\n const isSharedWorker = WorkerConstructor.name === 'SharedWorker'\n\n const chunkUrls = moduleChunks\n .map((chunk) => getChunkRelativeUrl(chunk))\n .reverse()\n const params: unknown[] = [chunkUrls, ASSET_SUFFIX]\n for (const globalName of WORKER_FORWARDED_GLOBALS) {\n params.push((globalThis as Record)[globalName])\n }\n\n const url = new URL(getChunkRelativeUrl(entrypoint), location.origin)\n const paramsJson = JSON.stringify(params)\n if (isSharedWorker) {\n url.searchParams.set('params', paramsJson)\n } else {\n url.hash = '#params=' + encodeURIComponent(paramsJson)\n }\n\n // Remove type: \"module\" from options since our worker entrypoint is not a module\n const options = workerOptions\n ? { ...workerOptions, type: undefined }\n : undefined\n return new WorkerConstructor(url, options)\n}\nbrowserContextPrototype.b = createWorker\n\n/**\n * Instantiates a runtime module.\n */\nfunction instantiateRuntimeModule(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): Module {\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n/**\n * Returns the URL relative to the origin where a chunk can be fetched from.\n */\nfunction getChunkRelativeUrl(chunkPath: ChunkPath | ChunkListPath): ChunkUrl {\n return `${CHUNK_BASE_PATH}${chunkPath\n .split('/')\n .map((p) => encodeURIComponent(p))\n .join('/')}${ASSET_SUFFIX}` as ChunkUrl\n}\n\n/**\n * Return the ChunkPath from a ChunkScript.\n */\nfunction getPathFromScript(chunkScript: ChunkPath | ChunkScript): ChunkPath\nfunction getPathFromScript(\n chunkScript: ChunkListPath | ChunkListScript\n): ChunkListPath\nfunction getPathFromScript(\n chunkScript: ChunkPath | ChunkListPath | ChunkScript | ChunkListScript\n): ChunkPath | ChunkListPath {\n if (typeof chunkScript === 'string') {\n return chunkScript as ChunkPath | ChunkListPath\n }\n const chunkUrl = chunkScript.src!\n const src = decodeURIComponent(chunkUrl.replace(/[?#].*$/, ''))\n const path = src.startsWith(CHUNK_BASE_PATH)\n ? src.slice(CHUNK_BASE_PATH.length)\n : src\n return path as ChunkPath | ChunkListPath\n}\n\n/**\n * Return the ChunkUrl from a ChunkScript.\n */\nfunction getUrlFromScript(chunk: ChunkPath | ChunkScript): ChunkUrl {\n if (typeof chunk === 'string') {\n return getChunkRelativeUrl(chunk)\n } else {\n // This is already exactly what we want\n return chunk.src! as ChunkUrl\n }\n}\n\n/**\n * Determine the chunk to register. Note that this function has side-effects!\n */\nfunction getChunkFromRegistration(\n chunk: ChunkRegistrationChunk\n): ChunkPath | CurrentScript {\n if (typeof chunk === 'string') {\n return chunk\n } else if (!chunk) {\n if (typeof TURBOPACK_NEXT_CHUNK_URLS !== 'undefined') {\n return { src: TURBOPACK_NEXT_CHUNK_URLS.pop()! } as CurrentScript\n } else {\n throw new Error('chunk path empty but not in a worker')\n }\n } else {\n return { src: chunk.getAttribute('src')! } as CurrentScript\n }\n}\n\nconst regexJsUrl = /\\.js(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.\n */\nfunction isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {\n return regexJsUrl.test(chunkUrlOrPath)\n}\n\nconst regexCssUrl = /\\.css(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .css, optionally followed by ?query or #fragment.\n */\nfunction isCss(chunkUrl: ChunkUrl): boolean {\n return regexCssUrl.test(chunkUrl)\n}\n\nfunction loadWebAssembly(\n this: TurbopackBaseContext,\n chunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n): Promise {\n return BACKEND.loadWebAssembly(\n SourceType.Parent,\n this.m.id,\n chunkPath,\n edgeModule,\n importsObj\n )\n}\ncontextPrototype.w = loadWebAssembly\n\nfunction loadWebAssemblyModule(\n this: TurbopackBaseContext,\n chunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module\n): Promise {\n return BACKEND.loadWebAssemblyModule(\n SourceType.Parent,\n this.m.id,\n chunkPath,\n edgeModule\n )\n}\ncontextPrototype.u = loadWebAssemblyModule\n"],"names":["browserContextPrototype","Context","prototype","moduleFactories","Map","contextPrototype","M","availableModules","availableModuleChunks","loadChunk","chunkData","loadChunkInternal","SourceType","Parent","m","id","l","loadInitialChunk","chunkPath","Runtime","sourceType","sourceData","loadChunkPath","includedList","included","modulesPromises","map","has","get","length","every","p","Promise","all","includedModuleChunksList","moduleChunks","moduleChunksPromises","filter","promise","moduleChunksToLoad","Set","moduleChunk","add","moduleChunkToLoad","set","push","path","includedModuleChunk","loadedChunk","resolve","undefined","instrumentedBackendLoadChunks","WeakMap","loadChunkByUrl","chunkUrl","loadChunkByUrlInternal","L","thenable","BACKEND","loadChunkCached","entry","bind","then","catch","cause","loadReason","Update","invariant","error","Error","name","url","getChunkRelativeUrl","resolvePathFromModule","moduleId","exported","r","default","R","resolveAbsolutePath","modulePath","P","exportUrl","exportValue","call","ASSET_SUFFIX","q","createWorker","WorkerConstructor","entrypoint","workerOptions","isSharedWorker","chunkUrls","chunk","reverse","params","globalName","WORKER_FORWARDED_GLOBALS","globalThis","URL","location","origin","paramsJson","JSON","stringify","searchParams","hash","encodeURIComponent","options","type","b","instantiateRuntimeModule","instantiateModule","CHUNK_BASE_PATH","split","join","getPathFromScript","chunkScript","src","decodeURIComponent","replace","startsWith","slice","getUrlFromScript","getChunkFromRegistration","TURBOPACK_NEXT_CHUNK_URLS","pop","getAttribute","regexJsUrl","isJs","chunkUrlOrPath","test","regexCssUrl","isCss","loadWebAssembly","edgeModule","importsObj","w","loadWebAssemblyModule","u"],"mappings":"AAAA;;;;;;CAMC,GAED,oDAAoD,GAEpD,6CAA6C;AAC7C,iEAAiE;AAEjE,gEAAgE;AAgBhE,MAAMA,0BACJC,QAAQC,SAAS;AA4DnB,MAAMC,kBAAmC,IAAIC;AAC7CC,iBAAiBC,CAAC,GAAGH;AAErB,MAAMI,mBAAuD,IAAIH;AAEjE,MAAMI,wBAA6D,IAAIJ;AAEvE,SAASK,UAEPC,SAAoB;IAEpB,OAAOC,kBAAkBC,WAAWC,MAAM,EAAE,IAAI,CAACC,CAAC,CAACC,EAAE,EAAEL;AACzD;AACAV,wBAAwBgB,CAAC,GAAGP;AAE5B,SAASQ,iBAAiBC,SAAoB,EAAER,SAAoB;IAClE,OAAOC,kBAAkBC,WAAWO,OAAO,EAAED,WAAWR;AAC1D;AAEA,eAAeC,kBACbS,UAAsB,EACtBC,UAAsB,EACtBX,SAAoB;IAEpB,IAAI,OAAOA,cAAc,UAAU;QACjC,OAAOY,cAAcF,YAAYC,YAAYX;IAC/C;IAEA,MAAMa,eAAeb,UAAUc,QAAQ,IAAI,EAAE;IAC7C,MAAMC,kBAAkBF,aAAaG,GAAG,CAAC,CAACF;QACxC,IAAIrB,gBAAgBwB,GAAG,CAACH,WAAW,OAAO;QAC1C,OAAOjB,iBAAiBqB,GAAG,CAACJ;IAC9B;IACA,IAAIC,gBAAgBI,MAAM,GAAG,KAAKJ,gBAAgBK,KAAK,CAAC,CAACC,IAAMA,IAAI;QACjE,uFAAuF;QACvF,MAAMC,QAAQC,GAAG,CAACR;QAClB;IACF;IAEA,MAAMS,2BAA2BxB,UAAUyB,YAAY,IAAI,EAAE;IAC7D,MAAMC,uBAAuBF,yBAC1BR,GAAG,CAAC,CAACF;QACJ,yCAAyC;QACzC,8CAA8C;QAC9C,OA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WACAqH,YACAC;AAEJ;AACAnI,iBAAiBoI,CAAC,GAAGH;AAErB,SAASI,sBAEPxH,SAAoB,EACpBqH,UAAoC;IAEpC,OAAO7E,QAAQgF,qBAAqB,CAClC9H,WAAWC,MAAM,EACjB,IAAI,CAACC,CAAC,CAACC,EAAE,EACTG,WACAqH;AAEJ;AACAlI,iBAAiBsI,CAAC,GAAGD","ignoreList":[0]}}, {"offset": {"line": 839, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared/runtime/hmr-runtime.ts"],"sourcesContent":["/// \n/// \n/// \n/// \n\ntype HotModuleFactoryFunction = ModuleFactoryFunction<\n HotModule,\n TurbopackBaseContext\n>\n\n/**\n * Shared HMR (Hot Module Replacement) implementation.\n *\n * This file contains the complete HMR implementation that's shared between\n * browser and Node.js runtimes. It manages module hot state, dependency\n * tracking, the module.hot API, and the full HMR update flow.\n */\n\n/**\n * The development module cache shared across the runtime.\n * Browser runtime declares this directly.\n * Node.js runtime assigns globalThis.__turbopack_module_cache__ to this.\n */\nlet devModuleCache: Record\n\n/**\n * Module IDs that are instantiated as part of the runtime of a chunk.\n */\nlet runtimeModules: Set\n\n/**\n * Maps module IDs to persisted data between executions of their hot module\n * implementation (`hot.data`).\n */\nconst moduleHotData: Map = new Map()\n\n/**\n * Maps module instances to their hot module state.\n * Uses WeakMap so it works with both HotModule and ModuleWithDirection.\n */\nconst moduleHotState: WeakMap = new WeakMap()\n\n/**\n * Modules that call `module.hot.invalidate()` (while being updated).\n */\nconst queuedInvalidatedModules: Set = new Set()\n\nclass UpdateApplyError extends Error {\n name = 'UpdateApplyError'\n\n dependencyChain: ModuleId[]\n\n constructor(message: string, dependencyChain: ModuleId[]) {\n super(message)\n this.dependencyChain = dependencyChain\n }\n}\n\ntype ModuleEffect =\n | {\n type: 'unaccepted'\n dependencyChain: ModuleId[]\n }\n | {\n type: 'self-declined'\n dependencyChain: ModuleId[]\n moduleId: ModuleId\n }\n | {\n type: 'declined'\n dependencyChain: ModuleId[]\n moduleId: ModuleId\n parentId: ModuleId\n }\n | {\n type: 'accepted'\n moduleId: ModuleId\n outdatedModules: Set\n outdatedDependencies: Map>\n }\n\n/**\n * Records parent-child relationship when a module imports another.\n * Should be called during module instantiation.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction trackModuleImport(\n parentModule: ModuleWithDirection,\n childModuleId: ModuleId,\n childModule: ModuleWithDirection | undefined\n): void {\n // Record that parent imports child\n if (parentModule.children.indexOf(childModuleId) === -1) {\n parentModule.children.push(childModuleId)\n }\n\n // Record that child is imported by parent\n if (childModule && childModule.parents.indexOf(parentModule.id) === -1) {\n childModule.parents.push(parentModule.id)\n }\n}\n\nfunction formatDependencyChain(dependencyChain: ModuleId[]): string {\n return `Dependency chain: ${dependencyChain.join(' -> ')}`\n}\n\n/**\n * Walks the dependency tree to find all modules affected by a change.\n * Returns information about whether the update can be accepted and which\n * modules need to be invalidated.\n *\n * @param moduleId - The module that changed\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept().\n * This is used for server-side HMR where pages auto-accept at the top level.\n */\nfunction getAffectedModuleEffects(\n moduleId: ModuleId,\n autoAcceptRootModules: boolean\n): ModuleEffect {\n const outdatedModules: Set = new Set()\n const outdatedDependencies: Map> = new Map()\n\n type QueueItem = { moduleId?: ModuleId; dependencyChain: ModuleId[] }\n\n const queue: QueueItem[] = [\n {\n moduleId,\n dependencyChain: [],\n },\n ]\n\n let nextItem\n while ((nextItem = queue.shift())) {\n const { moduleId, dependencyChain } = nextItem\n\n if (moduleId != null) {\n if (outdatedModules.has(moduleId)) {\n // Avoid infinite loops caused by cycles between modules in the dependency chain.\n continue\n }\n\n outdatedModules.add(moduleId)\n }\n\n // We've arrived at the runtime of the chunk, which means that nothing\n // else above can accept this update.\n if (moduleId === undefined) {\n if (autoAcceptRootModules) {\n return {\n type: 'accepted',\n moduleId,\n outdatedModules,\n outdatedDependencies,\n }\n }\n return {\n type: 'unaccepted',\n dependencyChain,\n }\n }\n\n const module = devModuleCache[moduleId]\n const hotState = moduleHotState.get(module)!\n\n if (\n // The module is not in the cache. Since this is a \"modified\" update,\n // it means that the module was never instantiated before.\n !module || // The module accepted itself without invalidating globalThis.\n // TODO is that right?\n (hotState.selfAccepted && !hotState.selfInvalidated)\n ) {\n continue\n }\n\n if (hotState.selfDeclined) {\n return {\n type: 'self-declined',\n dependencyChain,\n moduleId,\n }\n }\n\n if (runtimeModules.has(moduleId)) {\n if (autoAcceptRootModules) {\n continue\n }\n queue.push({\n moduleId: undefined,\n dependencyChain: [...dependencyChain, moduleId],\n })\n continue\n }\n\n for (const parentId of module.parents) {\n const parent = devModuleCache[parentId]\n\n if (!parent) {\n continue\n }\n\n const parentHotState = moduleHotState.get(parent)\n\n // Check if parent declined this dependency\n if (parentHotState?.declinedDependencies[moduleId]) {\n return {\n type: 'declined',\n dependencyChain: [...dependencyChain, moduleId],\n moduleId,\n parentId,\n }\n }\n\n // Skip if parent is already outdated\n if (outdatedModules.has(parentId)) {\n continue\n }\n\n // Check if parent accepts this dependency\n if (parentHotState?.acceptedDependencies[moduleId]) {\n if (!outdatedDependencies.has(parentId)) {\n outdatedDependencies.set(parentId, new Set())\n }\n outdatedDependencies.get(parentId)!.add(moduleId)\n continue\n }\n\n // Neither accepted nor declined — propagate to parent\n queue.push({\n moduleId: parentId,\n dependencyChain: [...dependencyChain, moduleId],\n })\n }\n\n // If no parents and we're at a root module, auto-accept if configured\n if (module.parents.length === 0 && autoAcceptRootModules) {\n continue\n }\n }\n\n return {\n type: 'accepted',\n moduleId,\n outdatedModules,\n outdatedDependencies,\n }\n}\n\n/**\n * Merges source dependency map into target dependency map.\n */\nfunction mergeDependencies(\n target: Map>,\n source: Map>\n): void {\n for (const [parentId, deps] of source) {\n const existing = target.get(parentId)\n if (existing) {\n for (const dep of deps) {\n existing.add(dep)\n }\n } else {\n target.set(parentId, new Set(deps))\n }\n }\n}\n\n/**\n * Computes all modules that need to be invalidated based on which modules changed.\n *\n * @param invalidated - The modules that have been invalidated\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction computedInvalidatedModules(\n invalidated: Iterable,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n} {\n const outdatedModules = new Set()\n const outdatedDependencies = new Map>()\n\n for (const moduleId of invalidated) {\n const effect = getAffectedModuleEffects(moduleId, autoAcceptRootModules)\n\n switch (effect.type) {\n case 'unaccepted':\n throw new UpdateApplyError(\n `cannot apply update: unaccepted module. ${formatDependencyChain(\n effect.dependencyChain\n )}.`,\n effect.dependencyChain\n )\n case 'self-declined':\n throw new UpdateApplyError(\n `cannot apply update: self-declined module. ${formatDependencyChain(\n effect.dependencyChain\n )}.`,\n effect.dependencyChain\n )\n case 'declined':\n throw new UpdateApplyError(\n `cannot apply update: declined dependency. ${formatDependencyChain(\n effect.dependencyChain\n )}. Declined by ${effect.parentId}.`,\n effect.dependencyChain\n )\n case 'accepted':\n for (const outdatedModuleId of effect.outdatedModules) {\n outdatedModules.add(outdatedModuleId)\n }\n mergeDependencies(outdatedDependencies, effect.outdatedDependencies)\n break\n default:\n invariant(effect, (effect) => `Unknown effect type: ${effect?.type}`)\n }\n }\n\n return { outdatedModules, outdatedDependencies }\n}\n\n/**\n * Creates the module.hot API object and its internal state.\n * This provides the HMR API that user code calls (module.hot.accept(), etc.)\n */\n\nfunction createModuleHot(\n moduleId: ModuleId,\n hotData: HotData\n): { hot: Hot; hotState: HotState } {\n const hotState: HotState = {\n selfAccepted: false,\n selfDeclined: false,\n selfInvalidated: false,\n disposeHandlers: [],\n acceptedDependencies: {},\n acceptedErrorHandlers: {},\n declinedDependencies: {},\n }\n\n const hot: Hot = {\n // TODO(alexkirsz) This is not defined in the HMR API. It was used to\n // decide whether to warn whenever an HMR-disposed module required other\n // modules. We might want to remove it.\n active: true,\n\n data: hotData ?? {},\n\n accept: (\n modules?: string | string[] | AcceptErrorHandler,\n callback?: AcceptCallback,\n errorHandler?: AcceptErrorHandler\n ) => {\n if (modules === undefined) {\n hotState.selfAccepted = true\n } else if (typeof modules === 'function') {\n hotState.selfAccepted = modules\n } else if (typeof modules === 'object' && modules !== null) {\n for (let i = 0; i < modules.length; i++) {\n hotState.acceptedDependencies[modules[i]] = callback || function () {}\n hotState.acceptedErrorHandlers[modules[i]] = errorHandler\n }\n } else {\n hotState.acceptedDependencies[modules] = callback || function () {}\n hotState.acceptedErrorHandlers[modules] = errorHandler\n }\n },\n\n decline: (dep?: string | string[]) => {\n if (dep === undefined) {\n hotState.selfDeclined = true\n } else if (typeof dep === 'object' && dep !== null) {\n for (let i = 0; i < dep.length; i++) {\n hotState.declinedDependencies[dep[i]] = true\n }\n } else {\n hotState.declinedDependencies[dep] = true\n }\n },\n\n dispose: (callback) => {\n hotState.disposeHandlers.push(callback)\n },\n\n addDisposeHandler: (callback) => {\n hotState.disposeHandlers.push(callback)\n },\n\n removeDisposeHandler: (callback) => {\n const idx = hotState.disposeHandlers.indexOf(callback)\n if (idx >= 0) {\n hotState.disposeHandlers.splice(idx, 1)\n }\n },\n\n invalidate: () => {\n hotState.selfInvalidated = true\n queuedInvalidatedModules.add(moduleId)\n },\n\n // NOTE(alexkirsz) This is part of the management API, which we don't\n // implement, but the Next.js React Refresh runtime uses this to decide\n // whether to schedule an update.\n status: () => 'idle',\n\n // NOTE(alexkirsz) Since we always return \"idle\" for now, these are no-ops.\n addStatusHandler: (_handler) => {},\n removeStatusHandler: (_handler) => {},\n\n // NOTE(jridgewell) Check returns the list of updated modules, but we don't\n // want the webpack code paths to ever update (the turbopack paths handle\n // this already).\n check: () => Promise.resolve(null),\n }\n\n return { hot, hotState }\n}\n\n/**\n * Processes queued invalidated modules and adds them to the outdated modules set.\n * Modules that call module.hot.invalidate() are queued and processed here.\n *\n * @param outdatedModules - The current set of outdated modules\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction applyInvalidatedModules(\n outdatedModules: Set,\n outdatedDependencies: Map>,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n} {\n if (queuedInvalidatedModules.size > 0) {\n const result = computedInvalidatedModules(\n queuedInvalidatedModules,\n autoAcceptRootModules\n )\n for (const moduleId of result.outdatedModules) {\n outdatedModules.add(moduleId)\n }\n mergeDependencies(outdatedDependencies, result.outdatedDependencies)\n\n queuedInvalidatedModules.clear()\n }\n\n return { outdatedModules, outdatedDependencies }\n}\n\n/**\n * Computes which outdated modules have self-accepted and can be hot reloaded.\n */\n\nfunction computeOutdatedSelfAcceptedModules(\n outdatedModules: Iterable\n): { moduleId: ModuleId; errorHandler: true | Function }[] {\n const outdatedSelfAcceptedModules: {\n moduleId: ModuleId\n errorHandler: true | Function\n }[] = []\n for (const moduleId of outdatedModules) {\n const module = devModuleCache[moduleId]\n const hotState = moduleHotState.get(module)\n if (module && hotState?.selfAccepted && !hotState.selfInvalidated) {\n outdatedSelfAcceptedModules.push({\n moduleId,\n errorHandler: hotState.selfAccepted,\n })\n }\n }\n return outdatedSelfAcceptedModules\n}\n\n/**\n * Disposes of an instance of a module.\n * Runs hot.dispose handlers and manages persistent hot data.\n *\n * NOTE: mode = \"replace\" will not remove modules from devModuleCache.\n * This must be done in a separate step afterwards.\n */\nfunction disposeModule(moduleId: ModuleId, mode: 'clear' | 'replace') {\n const module = devModuleCache[moduleId]\n if (!module) {\n return\n }\n\n const hotState = moduleHotState.get(module)\n if (!hotState) {\n return\n }\n\n const data: HotData = {}\n\n // Run the `hot.dispose` handler, if any, passing in the persistent\n // `hot.data` object.\n for (const disposeHandler of hotState.disposeHandlers) {\n disposeHandler(data)\n }\n\n // This used to warn in `getOrInstantiateModuleFromParent` when a disposed\n // module is still importing other modules.\n if (module.hot) {\n module.hot.active = false\n }\n\n moduleHotState.delete(module)\n\n // Remove the disposed module from its children's parent list.\n // It will be added back once the module re-instantiates and imports its\n // children again.\n for (const childId of module.children) {\n const child = devModuleCache[childId]\n if (!child) {\n continue\n }\n\n const idx = child.parents.indexOf(module.id)\n if (idx >= 0) {\n child.parents.splice(idx, 1)\n }\n }\n\n switch (mode) {\n case 'clear':\n delete devModuleCache[module.id]\n moduleHotData.delete(module.id)\n break\n case 'replace':\n moduleHotData.set(module.id, data)\n break\n default:\n invariant(mode, (mode) => `invalid mode: ${mode}`)\n }\n}\n\n/**\n * Dispose phase: runs dispose handlers and cleans up outdated/disposed modules.\n * Returns the parent modules of outdated modules for use in the apply phase.\n */\n\nfunction disposePhase(\n outdatedModules: Iterable,\n disposedModules: Iterable,\n outdatedDependencies: Map>\n): { outdatedModuleParents: Map> } {\n for (const moduleId of outdatedModules) {\n disposeModule(moduleId, 'replace')\n }\n\n for (const moduleId of disposedModules) {\n disposeModule(moduleId, 'clear')\n }\n\n // Removing modules from the module cache is a separate step.\n // We also want to keep track of previous parents of the outdated modules.\n const outdatedModuleParents = new Map>()\n for (const moduleId of outdatedModules) {\n const oldModule = devModuleCache[moduleId]\n outdatedModuleParents.set(moduleId, oldModule?.parents)\n delete devModuleCache[moduleId]\n }\n\n // Remove outdated dependencies from parent module's children list.\n // When a parent accepts a child's update, the child is re-instantiated\n // but the parent stays alive. We remove the old child reference so it\n // gets re-added when the child re-imports.\n for (const [parentId, deps] of outdatedDependencies) {\n const module = devModuleCache[parentId]\n if (module) {\n for (const dep of deps) {\n const idx = module.children.indexOf(dep)\n if (idx >= 0) {\n module.children.splice(idx, 1)\n }\n }\n }\n }\n\n return { outdatedModuleParents }\n}\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/**\n * Shared module instantiation logic.\n * This handles the full module instantiation flow for both browser and Node.js.\n * Only React Refresh hooks differ between platforms (passed as callback).\n */\nfunction instantiateModuleShared(\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n runtimeModules: Set,\n createModuleObjectFn: (id: ModuleId) => HotModule,\n createContextFn: (module: HotModule, exports: Exports, refresh?: any) => any,\n runModuleExecutionHooksFn: (\n module: HotModule,\n exec: (refresh: any) => void\n ) => void\n): HotModule {\n // 1. Factory validation (same in both browser and Node.js)\n const id = moduleId\n const moduleFactory = moduleFactories.get(id)\n if (typeof moduleFactory !== 'function') {\n throw new Error(\n factoryNotAvailableMessage(moduleId, sourceType, sourceData) +\n `\\nThis is often caused by a stale browser cache, misconfigured Cache-Control headers, or a service worker serving outdated responses.` +\n `\\nTo fix this, make sure your Cache-Control headers allow revalidation of chunks and review your service worker configuration. ` +\n `As an immediate workaround, try hard-reloading the page, clearing the browser cache, or unregistering any service workers.`\n )\n }\n\n // 2. Hot API setup (same in both - works for browser, included for Node.js)\n const hotData = moduleHotData.get(id)!\n const { hot, hotState } = createModuleHot(id, hotData)\n\n // 3. Parent assignment logic (same in both)\n let parents: ModuleId[]\n switch (sourceType) {\n case SourceType.Runtime:\n runtimeModules.add(id)\n parents = []\n break\n case SourceType.Parent:\n parents = [sourceData as ModuleId]\n break\n case SourceType.Update:\n parents = (sourceData as ModuleId[]) || []\n break\n default:\n throw new Error(`Unknown source type: ${sourceType}`)\n }\n\n // 4. Module creation (platform creates base module object)\n const module = createModuleObjectFn(id)\n const exports = module.exports\n module.parents = parents\n module.children = []\n module.hot = hot\n\n devModuleCache[id] = module\n moduleHotState.set(module, hotState)\n\n // 5. Module execution (React Refresh hooks are platform-specific)\n try {\n runModuleExecutionHooksFn(module, (refresh) => {\n const context = createContextFn(module, exports, refresh)\n moduleFactory.call(exports, context, module, exports)\n })\n } catch (error) {\n module.error = error as any\n throw error\n }\n\n // 6. ESM interop (same in both)\n if (module.namespaceObject && module.exports !== module.namespaceObject) {\n // in case of a circular dependency: cjs1 -> esm2 -> cjs1\n interopEsm(module.exports, module.namespaceObject)\n }\n\n return module\n}\n\n/**\n * Analyzes update entries and chunks to determine which modules were added, modified, or deleted.\n * This is pure logic that doesn't depend on the runtime environment.\n */\nfunction computeChangedModules(\n entries: Record,\n updates: Record,\n chunkModulesMap?: Map>\n): {\n added: Map\n modified: Map\n deleted: Set\n chunksAdded: Map>\n chunksDeleted: Map>\n} {\n const chunksAdded = new Map()\n const chunksDeleted = new Map()\n const added: Map = new Map()\n const modified = new Map()\n const deleted: Set = new Set()\n\n for (const [chunkPath, mergedChunkUpdate] of Object.entries(updates) as Array<\n [ChunkPath, EcmascriptMergedChunkUpdate]\n >) {\n switch (mergedChunkUpdate.type) {\n case 'added': {\n const updateAdded = new Set(mergedChunkUpdate.modules)\n for (const moduleId of updateAdded) {\n added.set(moduleId, entries[moduleId])\n }\n chunksAdded.set(chunkPath, updateAdded)\n break\n }\n case 'deleted': {\n const updateDeleted = chunkModulesMap\n ? new Set(chunkModulesMap.get(chunkPath))\n : new Set()\n for (const moduleId of updateDeleted) {\n deleted.add(moduleId)\n }\n chunksDeleted.set(chunkPath, updateDeleted)\n break\n }\n case 'partial': {\n const updateAdded = new Set(mergedChunkUpdate.added)\n const updateDeleted = new Set(mergedChunkUpdate.deleted)\n for (const moduleId of updateAdded) {\n added.set(moduleId, entries[moduleId])\n }\n for (const moduleId of updateDeleted) {\n deleted.add(moduleId)\n }\n chunksAdded.set(chunkPath, updateAdded)\n chunksDeleted.set(chunkPath, updateDeleted)\n break\n }\n default:\n throw new Error('Unknown merged chunk update type')\n }\n }\n\n // If a module was added from one chunk and deleted from another in the same update,\n // consider it to be modified, as it means the module was moved from one chunk to another\n // AND has new code in a single update.\n for (const moduleId of added.keys()) {\n if (deleted.has(moduleId)) {\n added.delete(moduleId)\n deleted.delete(moduleId)\n }\n }\n\n for (const [moduleId, entry] of Object.entries(entries)) {\n // Modules that haven't been added to any chunk but have new code are considered\n // to be modified.\n // This needs to be under the previous loop, as we need it to get rid of modules\n // that were added and deleted in the same update.\n if (!added.has(moduleId)) {\n modified.set(moduleId, entry)\n }\n }\n\n return { added, deleted, modified, chunksAdded, chunksDeleted }\n}\n\n/**\n * Compiles new module code and walks the dependency tree to find all outdated modules.\n * Uses the evalModuleEntry function to compile code (platform-specific).\n *\n * @param added - Map of added modules\n * @param modified - Map of modified modules\n * @param evalModuleEntry - Function to compile module code\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction computeOutdatedModules(\n added: Map,\n modified: Map,\n evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n newModuleFactories: Map\n} {\n const newModuleFactories = new Map()\n\n // Compile added modules\n for (const [moduleId, entry] of added) {\n if (entry != null) {\n newModuleFactories.set(moduleId, evalModuleEntry(entry))\n }\n }\n\n // Walk dependency tree to find all modules affected by modifications\n const { outdatedModules, outdatedDependencies } = computedInvalidatedModules(\n modified.keys(),\n autoAcceptRootModules\n )\n\n // Compile modified modules\n for (const [moduleId, entry] of modified) {\n newModuleFactories.set(moduleId, evalModuleEntry(entry))\n }\n\n return { outdatedModules, outdatedDependencies, newModuleFactories }\n}\n\n/**\n * Updates module factories and re-instantiates self-accepted modules.\n * Uses the instantiateModule function (platform-specific via callback).\n */\nfunction applyPhase(\n outdatedSelfAcceptedModules: {\n moduleId: ModuleId\n errorHandler: true | Function\n }[],\n newModuleFactories: Map,\n outdatedModuleParents: Map>,\n outdatedDependencies: Map>,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n instantiateModuleFn: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule,\n applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void,\n reportError: (err: any) => void\n) {\n // Update module factories\n for (const [moduleId, factory] of newModuleFactories.entries()) {\n applyModuleFactoryNameFn(factory)\n moduleFactories.set(moduleId, factory)\n }\n\n // TODO(alexkirsz) Run new runtime entries here.\n\n // Call accept handlers for outdated dependencies.\n // This runs BEFORE re-instantiating self-accepted modules, matching\n // webpack's behavior.\n for (const [parentId, deps] of outdatedDependencies) {\n const module = devModuleCache[parentId]\n if (!module) continue\n\n const hotState = moduleHotState.get(module)\n if (!hotState) continue\n\n // Group deps by callback, deduplicating callbacks that handle multiple deps.\n // Each callback receives only the deps it was registered for.\n const callbackDeps = new Map void), ModuleId[]>()\n const callbackErrorHandlers = new Map<\n AcceptCallback | (() => void),\n AcceptErrorHandler | undefined\n >()\n\n for (const dep of deps) {\n const acceptCallback = hotState.acceptedDependencies[dep]\n if (acceptCallback) {\n let depList = callbackDeps.get(acceptCallback)\n if (!depList) {\n depList = []\n callbackDeps.set(acceptCallback, depList)\n callbackErrorHandlers.set(\n acceptCallback,\n hotState.acceptedErrorHandlers[dep]\n )\n }\n depList.push(dep)\n }\n }\n\n for (const [callback, cbDeps] of callbackDeps) {\n try {\n callback.call(null, cbDeps)\n } catch (err: any) {\n const errorHandler = callbackErrorHandlers.get(callback)\n if (typeof errorHandler === 'function') {\n try {\n errorHandler(err, {\n moduleId: parentId,\n dependencyId: cbDeps[0],\n })\n } catch (err2) {\n reportError(err2)\n reportError(err)\n }\n } else {\n reportError(err)\n }\n }\n }\n }\n\n // Re-instantiate all outdated self-accepted modules\n for (const { moduleId, errorHandler } of outdatedSelfAcceptedModules) {\n try {\n instantiateModuleFn(\n moduleId,\n SourceType.Update,\n outdatedModuleParents.get(moduleId)\n )\n } catch (err) {\n if (typeof errorHandler === 'function') {\n try {\n errorHandler(err, { moduleId, module: devModuleCache[moduleId] })\n } catch (err2) {\n reportError(err2)\n reportError(err)\n }\n } else {\n reportError(err)\n }\n }\n }\n}\n\n/**\n * Internal implementation that orchestrates the full HMR update flow:\n * invalidation, disposal, and application of new modules.\n *\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction applyInternal(\n outdatedModules: Set,\n outdatedDependencies: Map>,\n disposedModules: Iterable,\n newModuleFactories: Map,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n instantiateModuleFn: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule,\n applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void,\n autoAcceptRootModules: boolean\n) {\n ;({ outdatedModules, outdatedDependencies } = applyInvalidatedModules(\n outdatedModules,\n outdatedDependencies,\n autoAcceptRootModules\n ))\n\n // Find self-accepted modules to re-instantiate\n const outdatedSelfAcceptedModules =\n computeOutdatedSelfAcceptedModules(outdatedModules)\n\n // Run dispose handlers, save hot.data, clear caches\n const { outdatedModuleParents } = disposePhase(\n outdatedModules,\n disposedModules,\n outdatedDependencies\n )\n\n let error: any\n\n function reportError(err: any) {\n if (!error) error = err // Keep first error\n }\n\n applyPhase(\n outdatedSelfAcceptedModules,\n newModuleFactories,\n outdatedModuleParents,\n outdatedDependencies,\n moduleFactories,\n devModuleCache,\n instantiateModuleFn,\n applyModuleFactoryNameFn,\n reportError\n )\n\n if (error) {\n throw error\n }\n\n // Recursively apply any queued invalidations from new module execution\n if (queuedInvalidatedModules.size > 0) {\n applyInternal(\n new Set(),\n new Map(),\n [],\n new Map(),\n moduleFactories,\n devModuleCache,\n instantiateModuleFn,\n applyModuleFactoryNameFn,\n autoAcceptRootModules\n )\n }\n}\n\n/**\n * Main entry point for applying an ECMAScript merged update.\n * This is called by both browser and Node.js runtimes with platform-specific callbacks.\n *\n * @param options.autoAcceptRootModules - If true, root modules auto-accept updates without explicit\n * module.hot.accept(). Used for server-side HMR where pages\n * auto-accept at the top level.\n */\nfunction applyEcmascriptMergedUpdateShared(options: {\n added: Map\n modified: Map\n disposedModules: Iterable\n evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction\n instantiateModule: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule\n applyModuleFactoryName: (factory: HotModuleFactoryFunction) => void\n moduleFactories: ModuleFactories\n devModuleCache: ModuleCache\n autoAcceptRootModules: boolean\n}) {\n const {\n added,\n modified,\n disposedModules,\n evalModuleEntry,\n instantiateModule,\n applyModuleFactoryName,\n moduleFactories,\n devModuleCache,\n autoAcceptRootModules,\n } = options\n\n const { outdatedModules, outdatedDependencies, newModuleFactories } =\n computeOutdatedModules(\n added,\n modified,\n evalModuleEntry,\n autoAcceptRootModules\n )\n\n applyInternal(\n outdatedModules,\n outdatedDependencies,\n disposedModules,\n newModuleFactories,\n moduleFactories,\n devModuleCache,\n instantiateModule,\n applyModuleFactoryName,\n autoAcceptRootModules\n )\n}\n"],"names":["devModuleCache","runtimeModules","moduleHotData","Map","moduleHotState","WeakMap","queuedInvalidatedModules","Set","UpdateApplyError","Error","name","dependencyChain","message","trackModuleImport","parentModule","childModuleId","childModule","children","indexOf","push","parents","id","formatDependencyChain","join","getAffectedModuleEffects","moduleId","autoAcceptRootModules","outdatedModules","outdatedDependencies","queue","nextItem","shift","has","add","undefined","type","module","hotState","get","selfAccepted","selfInvalidated","selfDeclined","parentId","parent","parentHotState","declinedDependencies","acceptedDependencies","set","length","mergeDependencies","target","source","deps","existing","dep","computedInvalidatedModules","invalidated","effect","outdatedModuleId","invariant","createModuleHot","hotData","disposeHandlers","acceptedErrorHandlers","hot","active","data","accept","modules","callback","errorHandler","i","decline","dispose","addDisposeHandler","removeDisposeHandler","idx","splice","invalidate","status","addStatusHandler","_handler","removeStatusHandler","check","Promise","resolve","applyInvalidatedModules","size","result","clear","computeOutdatedSelfAcceptedModules","outdatedSelfAcceptedModules","disposeModule","mode","disposeHandler","delete","childId","child","disposePhase","disposedModules","outdatedModuleParents","oldModule","instantiateModuleShared","sourceType","sourceData","moduleFactories","createModuleObjectFn","createContextFn","runModuleExecutionHooksFn","moduleFactory","factoryNotAvailableMessage","SourceType","Runtime","Parent","Update","exports","refresh","context","call","error","namespaceObject","interopEsm","computeChangedModules","entries","updates","chunkModulesMap","chunksAdded","chunksDeleted","added","modified","deleted","chunkPath","mergedChunkUpdate","Object","updateAdded","updateDeleted","keys","entry","computeOutdatedModules","evalModuleEntry","newModuleFactories","applyPhase","instantiateModuleFn","applyModuleFactoryNameFn","reportError","factory","callbackDeps","callbackErrorHandlers","acceptCallback","depList","cbDeps","err","dependencyId","err2","applyInternal","apply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A6E,iBACAzG,gBACA8I,qBACAC,0BACAC;IAGF,IAAIzB,OAAO;QACT,MAAMA;IACR;IAEA,uEAAuE;IACvE,IAAIjH,yBAAyBiF,IAAI,GAAG,GAAG;QACrCmE,cACE,IAAInJ,OACJ,IAAIJ,OACJ,EAAE,EACF,IAAIA,OACJsG,iBACAzG,gBACA8I,qBACAC,0BACArH;IAEJ;AACF;AAEA;;;;;;;CAOC,GACD,SAASiI,kCAAkCC,OAc1C;IACC,MAAM,EACJ5B,KAAK,EACLC,QAAQ,EACR9B,eAAe,EACfwC,eAAe,EACfkB,iBAAiB,EACjBC,sBAAsB,EACtBrD,eAAe,EACfzG,cAAc,EACd0B,qBAAqB,EACtB,GAAGkI;IAEJ,MAAM,EAAEjI,eAAe,EAAEC,oBAAoB,EAAEgH,kBAAkB,EAAE,GACjEF,uBACEV,OACAC,UACAU,iBACAjH;IAGJgI,cACE/H,iBACAC,sBACAuE,iBACAyC,oBACAnC,iBACAzG,gBACA6J,mBACAC,wBACApI;AAEJ","ignoreList":[0]}}, {"offset": {"line": 1533, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/dev-base.ts"],"sourcesContent":["/// \n/// \n\ninterface TurbopackDevContext extends TurbopackBrowserBaseContext {\n k: RefreshContext\n}\n\nconst devContextPrototype = Context.prototype as TurbopackDevContext\n\n/**\n * This file contains runtime types and functions that are shared between all\n * Turbopack *development* ECMAScript runtimes.\n *\n * It will be appended to the runtime code of each runtime right after the\n * shared runtime utils.\n */\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n// Assign browser's module cache and runtime modules to shared HMR state\ndevModuleCache = Object.create(null)\ndevContextPrototype.c = devModuleCache\nruntimeModules = new Set()\n\n// Set flag to indicate we use ModuleWithDirection\ncreateModuleWithDirectionFlag = true\n\n// This file must not use `import` and `export` statements. Otherwise, it\n// becomes impossible to augment interfaces declared in ``d files\n// (e.g. `Module`). Hence, the need for `import()` here.\ntype RefreshRuntimeGlobals =\n import('@next/react-refresh-utils/dist/runtime').RefreshRuntimeGlobals\n\ndeclare var $RefreshHelpers$: RefreshRuntimeGlobals['$RefreshHelpers$']\ndeclare var $RefreshReg$: RefreshRuntimeGlobals['$RefreshReg$']\ndeclare var $RefreshSig$: RefreshRuntimeGlobals['$RefreshSig$']\ndeclare var $RefreshInterceptModuleExecution$: RefreshRuntimeGlobals['$RefreshInterceptModuleExecution$']\n\ntype RefreshContext = {\n register: RefreshRuntimeGlobals['$RefreshReg$']\n signature: RefreshRuntimeGlobals['$RefreshSig$']\n registerExports: typeof registerExportsAndSetupBoundaryForReactRefresh\n}\n\ntype RefreshHelpers = RefreshRuntimeGlobals['$RefreshHelpers$']\n\ntype ModuleFactory = (\n this: Module['exports'],\n context: TurbopackDevContext\n) => unknown\n\ninterface DevRuntimeBackend {\n reloadChunk?: (chunkUrl: ChunkUrl) => Promise\n unloadChunk?: (chunkUrl: ChunkUrl) => void\n restart: () => void\n}\n\n/**\n * Map from module ID to the chunks that contain this module.\n *\n * In HMR, we need to keep track of which modules are contained in which so\n * chunks. This is so we don't eagerly dispose of a module when it is removed\n * from chunk A, but still exists in chunk B.\n */\nconst moduleChunksMap: Map> = new Map()\n/**\n * Map from a chunk path to all modules it contains.\n */\nconst chunkModulesMap: Map> = new Map()\n/**\n * Chunk lists that contain a runtime. When these chunk lists receive an update\n * that can't be reconciled with the current state of the page, we need to\n * reload the runtime entirely.\n */\nconst runtimeChunkLists: Set = new Set()\n/**\n * Map from a chunk list to the chunk paths it contains.\n */\nconst chunkListChunksMap: Map> = new Map()\n/**\n * Map from a chunk path to the chunk lists it belongs to.\n */\nconst chunkChunkListsMap: Map> = new Map()\n\n/**\n * Gets or instantiates a runtime module.\n */\n// @ts-ignore\nfunction getOrInstantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): Module {\n const module = devModuleCache[moduleId]\n if (module) {\n if (module.error) {\n throw module.error\n }\n return module\n }\n\n // @ts-ignore\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it if it is not cached.\n */\n// @ts-ignore Defined in `runtime-utils.ts`\nconst getOrInstantiateModuleFromParent: GetOrInstantiateModuleFromParent<\n HotModule\n> = (id, sourceModule) => {\n if (!sourceModule.hot.active) {\n console.warn(\n `Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`\n )\n }\n\n const module = devModuleCache[id]\n\n if (sourceModule.children.indexOf(id) === -1) {\n sourceModule.children.push(id)\n }\n\n if (module) {\n if (module.error) {\n throw module.error\n }\n\n if (module.parents.indexOf(sourceModule.id) === -1) {\n module.parents.push(sourceModule.id)\n }\n\n return module\n }\n\n return instantiateModule(id, SourceType.Parent, sourceModule.id)\n}\n\nfunction DevContext(\n this: TurbopackDevContext,\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n) {\n Context.call(this, module, exports)\n this.k = refresh\n}\nDevContext.prototype = Context.prototype\n\ntype DevContextConstructor = {\n new (\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n ): TurbopackDevContext\n}\n\nfunction instantiateModule(\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): Module {\n // Browser: creates base HotModule object (hot API added by shared code)\n const createModuleObjectFn = (id: ModuleId) => {\n return createModuleObject(id) as HotModule\n }\n\n // Browser: creates DevContext with refresh\n const createContext = (\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n ) => {\n return new (DevContext as any as DevContextConstructor)(\n module,\n exports,\n refresh\n )\n }\n\n // Use shared instantiation logic (includes hot API setup)\n return instantiateModuleShared(\n moduleId,\n sourceType,\n sourceData,\n moduleFactories,\n devModuleCache,\n runtimeModules,\n createModuleObjectFn,\n createContext,\n runModuleExecutionHooks\n )\n}\n\nconst DUMMY_REFRESH_CONTEXT = {\n register: (_type: unknown, _id: unknown) => {},\n signature: () => (_type: unknown) => {},\n registerExports: (_module: unknown, _helpers: unknown) => {},\n}\n\n/**\n * NOTE(alexkirsz) Webpack has a \"module execution\" interception hook that\n * Next.js' React Refresh runtime hooks into to add module context to the\n * refresh registry.\n */\nfunction runModuleExecutionHooks(\n module: HotModule,\n executeModule: (ctx: RefreshContext) => void\n) {\n if (typeof globalThis.$RefreshInterceptModuleExecution$ === 'function') {\n const cleanupReactRefreshIntercept =\n globalThis.$RefreshInterceptModuleExecution$(module.id)\n try {\n executeModule({\n register: globalThis.$RefreshReg$,\n signature: globalThis.$RefreshSig$,\n registerExports: registerExportsAndSetupBoundaryForReactRefresh,\n })\n } finally {\n // Always cleanup the intercept, even if module execution failed.\n cleanupReactRefreshIntercept()\n }\n } else {\n // If the react refresh hooks are not installed we need to bind dummy functions.\n // This is expected when running in a Web Worker. It is also common in some of\n // our test environments.\n executeModule(DUMMY_REFRESH_CONTEXT)\n }\n}\n\n/**\n * This is adapted from https://github.com/vercel/next.js/blob/3466862d9dc9c8bb3131712134d38757b918d1c0/packages/react-refresh-utils/internal/ReactRefreshModule.runtime.ts\n */\nfunction registerExportsAndSetupBoundaryForReactRefresh(\n module: HotModule,\n helpers: RefreshHelpers\n) {\n const currentExports = module.exports\n const prevExports = module.hot.data.prevExports ?? null\n\n helpers.registerExportsForReactRefresh(currentExports, module.id)\n\n // A module can be accepted automatically based on its exports, e.g. when\n // it is a Refresh Boundary.\n if (helpers.isReactRefreshBoundary(currentExports)) {\n // Save the previous exports on update, so we can compare the boundary\n // signatures.\n module.hot.dispose((data) => {\n data.prevExports = currentExports\n })\n // Unconditionally accept an update to this module, we'll check if it's\n // still a Refresh Boundary later.\n module.hot.accept()\n\n // This field is set when the previous version of this module was a\n // Refresh Boundary, letting us know we need to check for invalidation or\n // enqueue an update.\n if (prevExports !== null) {\n // A boundary can become ineligible if its exports are incompatible\n // with the previous exports.\n //\n // For example, if you add/remove/change exports, we'll want to\n // re-execute the importing modules, and force those components to\n // re-render. Similarly, if you convert a class component to a\n // function, we want to invalidate the boundary.\n if (\n helpers.shouldInvalidateReactRefreshBoundary(\n helpers.getRefreshBoundarySignature(prevExports),\n helpers.getRefreshBoundarySignature(currentExports)\n )\n ) {\n module.hot.invalidate()\n } else {\n helpers.scheduleUpdate()\n }\n }\n } else {\n // Since we just executed the code for the module, it's possible that the\n // new exports made it ineligible for being a boundary.\n // We only care about the case when we were _previously_ a boundary,\n // because we already accepted this update (accidental side effect).\n const isNoLongerABoundary = prevExports !== null\n if (isNoLongerABoundary) {\n module.hot.invalidate()\n }\n }\n}\n\n/**\n * Adds, deletes, and moves modules between chunks. This must happen before the\n * dispose phase as it needs to know which modules were removed from all chunks,\n * which we can only compute *after* taking care of added and moved modules.\n */\nfunction updateChunksPhase(\n chunksAddedModules: Map>,\n chunksDeletedModules: Map>\n): { disposedModules: Set } {\n for (const [chunkPath, addedModuleIds] of chunksAddedModules) {\n for (const moduleId of addedModuleIds) {\n addModuleToChunk(moduleId, chunkPath)\n }\n }\n\n const disposedModules: Set = new Set()\n for (const [chunkPath, addedModuleIds] of chunksDeletedModules) {\n for (const moduleId of addedModuleIds) {\n if (removeModuleFromChunk(moduleId, chunkPath)) {\n disposedModules.add(moduleId)\n }\n }\n }\n\n return { disposedModules }\n}\n\nfunction applyUpdate(update: PartialUpdate) {\n switch (update.type) {\n case 'ChunkListUpdate':\n applyChunkListUpdate(update)\n break\n default:\n invariant(update, (update) => `Unknown update type: ${update.type}`)\n }\n}\n\nfunction applyChunkListUpdate(update: ChunkListUpdate) {\n if (update.merged != null) {\n for (const merged of update.merged) {\n switch (merged.type) {\n case 'EcmascriptMergedUpdate':\n applyEcmascriptMergedUpdate(merged)\n break\n default:\n invariant(merged, (merged) => `Unknown merged type: ${merged.type}`)\n }\n }\n }\n\n if (update.chunks != null) {\n for (const [chunkPath, chunkUpdate] of Object.entries(\n update.chunks\n ) as Array<[ChunkPath, ChunkUpdate]>) {\n const chunkUrl = getChunkRelativeUrl(chunkPath)\n\n switch (chunkUpdate.type) {\n case 'added':\n BACKEND.loadChunkCached(SourceType.Update, chunkUrl)\n break\n case 'total':\n DEV_BACKEND.reloadChunk?.(chunkUrl)\n break\n case 'deleted':\n DEV_BACKEND.unloadChunk?.(chunkUrl)\n break\n case 'partial':\n invariant(\n chunkUpdate.instruction,\n (instruction) =>\n `Unknown partial instruction: ${JSON.stringify(instruction)}.`\n )\n break\n default:\n invariant(\n chunkUpdate,\n (chunkUpdate) => `Unknown chunk update type: ${chunkUpdate.type}`\n )\n }\n }\n }\n}\n\nfunction applyEcmascriptMergedUpdate(update: EcmascriptMergedUpdate) {\n // Browser-specific chunk management phase\n const { entries = {}, chunks = {} } = update\n const { added, modified, chunksAdded, chunksDeleted } = computeChangedModules(\n entries,\n chunks,\n chunkModulesMap\n )\n const { disposedModules } = updateChunksPhase(chunksAdded, chunksDeleted)\n\n // Use shared HMR update implementation\n applyEcmascriptMergedUpdateShared({\n added,\n modified,\n disposedModules,\n evalModuleEntry: _eval, // browser's eval with source maps\n instantiateModule, // now wraps shared logic\n applyModuleFactoryName,\n moduleFactories,\n devModuleCache,\n autoAcceptRootModules: false,\n })\n}\n\nfunction handleApply(chunkListPath: ChunkListPath, update: ServerMessage) {\n switch (update.type) {\n case 'partial': {\n // This indicates that the update is can be applied to the current state of the application.\n applyUpdate(update.instruction)\n break\n }\n case 'restart': {\n // This indicates that there is no way to apply the update to the\n // current state of the application, and that the application must be\n // restarted.\n DEV_BACKEND.restart()\n break\n }\n case 'notFound': {\n // This indicates that the chunk list no longer exists: either the dynamic import which created it was removed,\n // or the page itself was deleted.\n // If it is a dynamic import, we simply discard all modules that the chunk has exclusive access to.\n // If it is a runtime chunk list, we restart the application.\n if (runtimeChunkLists.has(chunkListPath)) {\n DEV_BACKEND.restart()\n } else {\n disposeChunkList(chunkListPath)\n }\n break\n }\n default:\n throw new Error(`Unknown update type: ${update.type}`)\n }\n}\n\n/**\n * Removes a module from a chunk.\n * Returns `true` if there are no remaining chunks including this module.\n */\nfunction removeModuleFromChunk(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): boolean {\n const moduleChunks = moduleChunksMap.get(moduleId)!\n moduleChunks.delete(chunkPath)\n\n const chunkModules = chunkModulesMap.get(chunkPath)!\n chunkModules.delete(moduleId)\n\n const noRemainingModules = chunkModules.size === 0\n if (noRemainingModules) {\n chunkModulesMap.delete(chunkPath)\n }\n\n const noRemainingChunks = moduleChunks.size === 0\n if (noRemainingChunks) {\n moduleChunksMap.delete(moduleId)\n }\n\n return noRemainingChunks\n}\n\n/**\n * Disposes of a chunk list and its corresponding exclusive chunks.\n */\nfunction disposeChunkList(chunkListPath: ChunkListPath): boolean {\n const chunkPaths = chunkListChunksMap.get(chunkListPath)\n if (chunkPaths == null) {\n return false\n }\n chunkListChunksMap.delete(chunkListPath)\n\n for (const chunkPath of chunkPaths) {\n const chunkChunkLists = chunkChunkListsMap.get(chunkPath)!\n chunkChunkLists.delete(chunkListPath)\n\n if (chunkChunkLists.size === 0) {\n chunkChunkListsMap.delete(chunkPath)\n disposeChunk(chunkPath)\n }\n }\n\n // We must also dispose of the chunk list's chunk itself to ensure it may\n // be reloaded properly in the future.\n const chunkListUrl = getChunkRelativeUrl(chunkListPath)\n\n DEV_BACKEND.unloadChunk?.(chunkListUrl)\n\n return true\n}\n\n/**\n * Disposes of a chunk and its corresponding exclusive modules.\n *\n * @returns Whether the chunk was disposed of.\n */\nfunction disposeChunk(chunkPath: ChunkPath): boolean {\n const chunkUrl = getChunkRelativeUrl(chunkPath)\n // This should happen whether the chunk has any modules in it or not.\n // For instance, CSS chunks have no modules in them, but they still need to be unloaded.\n DEV_BACKEND.unloadChunk?.(chunkUrl)\n\n const chunkModules = chunkModulesMap.get(chunkPath)\n if (chunkModules == null) {\n return false\n }\n chunkModules.delete(chunkPath)\n\n for (const moduleId of chunkModules) {\n const moduleChunks = moduleChunksMap.get(moduleId)!\n moduleChunks.delete(chunkPath)\n\n const noRemainingChunks = moduleChunks.size === 0\n if (noRemainingChunks) {\n moduleChunksMap.delete(moduleId)\n disposeModule(moduleId, 'clear')\n availableModules.delete(moduleId)\n }\n }\n\n return true\n}\n\n/**\n * Adds a module to a chunk.\n */\nfunction addModuleToChunk(moduleId: ModuleId, chunkPath: ChunkPath) {\n let moduleChunks = moduleChunksMap.get(moduleId)\n if (!moduleChunks) {\n moduleChunks = new Set([chunkPath])\n moduleChunksMap.set(moduleId, moduleChunks)\n } else {\n moduleChunks.add(chunkPath)\n }\n\n let chunkModules = chunkModulesMap.get(chunkPath)\n if (!chunkModules) {\n chunkModules = new Set([moduleId])\n chunkModulesMap.set(chunkPath, chunkModules)\n } else {\n chunkModules.add(moduleId)\n }\n}\n\n/**\n * Marks a chunk list as a runtime chunk list. There can be more than one\n * runtime chunk list. For instance, integration tests can have multiple chunk\n * groups loaded at runtime, each with its own chunk list.\n */\nfunction markChunkListAsRuntime(chunkListPath: ChunkListPath) {\n runtimeChunkLists.add(chunkListPath)\n}\n\nfunction registerChunk(registration: ChunkRegistration) {\n const chunk = getChunkFromRegistration(registration[0]) as\n | ChunkPath\n | ChunkScript\n let runtimeParams: RuntimeParams | undefined\n // When bootstrapping we are passed a single runtimeParams object so we can distinguish purely based on length\n if (registration.length === 2) {\n runtimeParams = registration[1] as RuntimeParams\n } else {\n let chunkPath = getPathFromScript(chunk)\n runtimeParams = undefined\n installCompressedModuleFactories(\n registration as CompressedModuleFactories,\n /* offset= */ 1,\n moduleFactories,\n (id: ModuleId) => addModuleToChunk(id, chunkPath)\n )\n }\n return BACKEND.registerChunk(chunk, runtimeParams)\n}\n\n/**\n * Subscribes to chunk list updates from the update server and applies them.\n */\nfunction registerChunkList(chunkList: ChunkList) {\n const chunkListScript = getChunkFromRegistration(chunkList.script) as\n | ChunkListPath\n | ChunkListScript\n const chunkListPath = getPathFromScript(chunkListScript)\n // The \"chunk\" is also registered to finish the loading in the backend\n BACKEND.registerChunk(chunkListPath as string as ChunkPath)\n globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS!.push([\n chunkListPath,\n handleApply.bind(null, chunkListPath),\n ])\n\n // Adding chunks to chunk lists and vice versa.\n const chunkPaths = new Set(chunkList.chunks.map(getChunkPath))\n chunkListChunksMap.set(chunkListPath, chunkPaths)\n for (const chunkPath of chunkPaths) {\n let chunkChunkLists = chunkChunkListsMap.get(chunkPath)\n if (!chunkChunkLists) {\n chunkChunkLists = new Set([chunkListPath])\n chunkChunkListsMap.set(chunkPath, chunkChunkLists)\n } else {\n chunkChunkLists.add(chunkListPath)\n }\n }\n\n if (chunkList.source === 'entry') {\n markChunkListAsRuntime(chunkListPath)\n }\n}\n\nglobalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= []\n"],"names":["devContextPrototype","Context","prototype","devModuleCache","Object","create","c","runtimeModules","Set","createModuleWithDirectionFlag","moduleChunksMap","Map","chunkModulesMap","runtimeChunkLists","chunkListChunksMap","chunkChunkListsMap","getOrInstantiateRuntimeModule","chunkPath","moduleId","module","error","instantiateModule","SourceType","Runtime","getOrInstantiateModuleFromParent","id","sourceModule","hot","active","console","warn","children","indexOf","push","parents","Parent","DevContext","exports","refresh","call","k","sourceType","sourceData","createModuleObjectFn","createModuleObject","createContext","instantiateModuleShared","moduleFactories","runModuleExecutionHooks","DUMMY_REFRESH_CONTEXT","register","_type","_id","signature","registerExports","_module","_helpers","executeModule","globalThis","$RefreshInterceptModuleExecution$","cleanupReactRefreshIntercept","$RefreshReg$","$RefreshSig$","registerExportsAndSetupBoundaryForReactRefresh","helpers","currentExports","prevExports","data","registerExportsForReactRefresh","isReactRefreshBoundary","dispose","accept","shouldInvalidateReactRefreshBoundary","getRefreshBoundarySignature","invalidate","scheduleUpdate","isNoLongerABoundary","updateChunksPhase","chunksAddedModules","chunksDeletedModules","addedModuleIds","addModuleToChunk","disposedModules","removeModuleFromChunk","add","applyUpdate","update","type","applyChunkListUpdate","invariant","merged","applyEcmascriptMergedUpdate","chunks","chunkUpdate","entries","chunkUrl","getChunkRelativeUrl","BACKEND","loadChunkCached","Update","DEV_BACKEND","reloadChunk","unloadChunk","instruction","JSON","stringify","added","modified","chunksAdded","chunksDeleted","computeChangedModules","applyEcmascriptMergedUpdateShared","evalModuleEntry","_eval","applyModuleFactoryName","autoAcceptRootModules","handleApply","chunkListPath","restart","has","disposeChunkList","Error","moduleChunks","get","delete","chunkModules","noRemainingModules","size","noRemainingChunks","chunkPaths","chunkChunkLists","disposeChunk","chunkListUrl","disposeModule","availableModules","set","markChunkListAsRuntime","registerChunk","registration","chunk","getChunkFromRegistration","runtimeParams","length","getPathFromScript","undefined","installCompressedModuleFactories","registerChunkList","chunkList","chunkListScript","script","TURBOPACK_CHUNK_UPDATE_LISTENERS","bind","map","getChunkPath","source"],"mappings":"AAAA,iEAAiE;AACjE,kEAAkE;AAMlE,MAAMA,sBAAsBC,QAAQC,SAAS;AAE7C;;;;;;CAMC,GACD,oDAAoD,GAEpD,wEAAwE;AACxEC,iBAAiBC,OAAOC,MAAM,CAAC;AAC/BL,oBAAoBM,CAAC,GAAGH;AACxBI,iBAAiB,IAAIC;AAErB,kDAAkD;AAClDC,gCAAgC;AAgChC;;;;;;CAMC,GACD,MAAMC,kBAAiD,IAAIC;AAC3D;;CAEC,GACD,MAAMC,kBAAiD,IAAID;AAC3D;;;;CAIC,GACD,MAAME,oBAAwC,IAAIL;AAClD;;CAEC,GACD,MAAMM,qBAAyD,IAAIH;AACnE;;CAEC,GACD,MAAMI,qBAAyD,IAAIJ;AAEnE;;CAEC,GACD,aAAa;AACb,SAASK,8BACPC,SAAoB,EACpBC,QAAkB;IAElB,MAAMC,SAAShB,cAAc,CAACe,SAAS;IACvC,IAAIC,QAAQ;QACV,IAAIA,OAAOC,KAAK,EAAE;YAChB,MAAMD,OAAOC,KAAK;QACpB;QACA,OAAOD;IACT;IAEA,aAAa;IACb,OAAOE,kBAAkBH,UAAUI,WAAWC,OAAO,EAAEN;AACzD;AAEA;;CAEC,GACD,2CAA2C;AAC3C,MAAMO,mCAEF,CAACC,IAAIC;IACP,IAAI,CAACA,aAAaC,GAAG,CAACC,MAAM,EAAE;QAC5BC,QAAQC,IAAI,CACV,CAAC,4BAA4B,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;IAC7C,MAAMC,kBAAkBR,yBAAyBO,UAAUE,MAAM;IAGjE,MAAMhC,gBAAgB0B,kBAAkBK;IACxC,sEAAsE;IACtEnD,QAAQwC,aAAa,CAACpB;IACtB3D,WAAW4F,gCAAgC,CAAErH,IAAI,CAAC;QAChDoF;QACAD,YAAYmC,IAAI,CAAC,MAAMlC;KACxB;IAED,+CAA+C;IAC/C,MAAMY,aAAa,IAAIzH,IAAI2I,UAAUvD,MAAM,CAAC4D,GAAG,CAACC;IAChD3I,mBAAmByH,GAAG,CAAClB,eAAeY;IACtC,KAAK,MAAMhH,aAAagH,WAAY;QAClC,IAAIC,kBAAkBnH,mBAAmB4G,GAAG,CAAC1G;QAC7C,IAAI,CAACiH,iBAAiB;YACpBA,kBAAkB,IAAI1H,IAAI;gBAAC6G;aAAc;YACzCtG,mBAAmBwH,GAAG,CAACtH,WAAWiH;QACpC,OAAO;YACLA,gBAAgB9C,GAAG,CAACiC;QACtB;IACF;IAEA,IAAI8B,UAAUO,MAAM,KAAK,SAAS;QAChClB,uBAAuBnB;IACzB;AACF;AAEA3D,WAAW4F,gCAAgC,KAAK,EAAE","ignoreList":[0]}}, - {"offset": {"line": 1950, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/runtime-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack ECMAScript DOM runtime.\n *\n * It will be appended to the base runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\nfunction getAssetSuffixFromScriptSrc() {\n // TURBOPACK_ASSET_SUFFIX is set in web workers\n return (\n (self.TURBOPACK_ASSET_SUFFIX ??\n document?.currentScript\n ?.getAttribute?.('src')\n ?.replace(/^(.*(?=\\?)|^.*$)/, '')) ||\n ''\n )\n}\n\ntype ChunkResolver = {\n resolved: boolean\n loadingStarted: boolean\n resolve: () => void\n reject: (error?: Error) => void\n promise: Promise\n}\n\nlet BACKEND: RuntimeBackend\n\n/**\n * Maps chunk paths to the corresponding resolver.\n */\nconst chunkResolvers: Map = new Map()\n\n;(() => {\n BACKEND = {\n async registerChunk(chunk, params) {\n let chunkPath = getPathFromScript(chunk)\n let chunkUrl = getUrlFromScript(chunk)\n\n const resolver = getOrCreateResolver(chunkUrl)\n resolver.resolve()\n\n if (params == null) {\n return\n }\n\n for (const otherChunkData of params.otherChunks) {\n const otherChunkPath = getChunkPath(otherChunkData)\n const otherChunkUrl = getChunkRelativeUrl(otherChunkPath)\n\n // Chunk might have started loading, so we want to avoid triggering another load.\n getOrCreateResolver(otherChunkUrl)\n }\n\n // This waits for chunks to be loaded, but also marks included items as available.\n await Promise.all(\n params.otherChunks.map((otherChunkData) =>\n loadInitialChunk(chunkPath, otherChunkData)\n )\n )\n\n if (params.runtimeModuleIds.length > 0) {\n for (const moduleId of params.runtimeModuleIds) {\n getOrInstantiateRuntimeModule(chunkPath, moduleId)\n }\n }\n },\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n loadChunkCached(sourceType: SourceType, chunkUrl: ChunkUrl) {\n return doLoadChunk(sourceType, chunkUrl)\n },\n\n async loadWebAssembly(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n const { instance } = await WebAssembly.instantiateStreaming(\n req,\n importsObj\n )\n\n return instance.exports\n },\n\n async loadWebAssemblyModule(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n return await WebAssembly.compileStreaming(req)\n },\n }\n\n function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {\n let resolver = chunkResolvers.get(chunkUrl)\n if (!resolver) {\n let resolve: () => void\n let reject: (error?: Error) => void\n const promise = new Promise((innerResolve, innerReject) => {\n resolve = innerResolve\n reject = innerReject\n })\n resolver = {\n resolved: false,\n loadingStarted: false,\n promise,\n resolve: () => {\n resolver!.resolved = true\n resolve()\n },\n reject: reject!,\n }\n chunkResolvers.set(chunkUrl, resolver)\n }\n return resolver\n }\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n function doLoadChunk(sourceType: SourceType, chunkUrl: ChunkUrl) {\n const resolver = getOrCreateResolver(chunkUrl)\n if (resolver.loadingStarted) {\n return resolver.promise\n }\n\n if (sourceType === SourceType.Runtime) {\n // We don't need to load chunks references from runtime code, as they're already\n // present in the DOM.\n resolver.loadingStarted = true\n\n if (isCss(chunkUrl)) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n\n // We need to wait for JS chunks to register themselves within `registerChunk`\n // before we can start instantiating runtime modules, hence the absence of\n // `resolver.resolve()` in this branch.\n\n return resolver.promise\n }\n\n if (typeof importScripts === 'function') {\n // We're in a web worker\n if (isCss(chunkUrl)) {\n // ignore\n } else if (isJs(chunkUrl)) {\n self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl)\n importScripts(chunkUrl)\n } else {\n throw new Error(\n `can't infer type of chunk from URL ${chunkUrl} in worker`\n )\n }\n } else {\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n if (previousLinks.length > 0) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n } else {\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n link.href = chunkUrl\n link.onerror = () => {\n resolver.reject()\n }\n link.onload = () => {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(link)\n }\n } else if (isJs(chunkUrl)) {\n const previousScripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n if (previousScripts.length > 0) {\n // There is this edge where the script already failed loading, but we\n // can't detect that. The Promise will never resolve in this case.\n for (const script of Array.from(previousScripts)) {\n script.addEventListener('error', () => {\n resolver.reject()\n })\n }\n } else {\n const script = document.createElement('script')\n script.src = chunkUrl\n // We'll only mark the chunk as loaded once the script has been executed,\n // which happens in `registerChunk`. Hence the absence of `resolve()` in\n // this branch.\n script.onerror = () => {\n resolver.reject()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(script)\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n }\n\n resolver.loadingStarted = true\n return resolver.promise\n }\n\n function fetchWebAssembly(wasmChunkPath: ChunkPath) {\n return fetch(getChunkRelativeUrl(wasmChunkPath))\n }\n})()\n"],"names":["getAssetSuffixFromScriptSrc","self","TURBOPACK_ASSET_SUFFIX","document","currentScript","getAttribute","replace","BACKEND","chunkResolvers","Map","registerChunk","chunk","params","chunkPath","getPathFromScript","chunkUrl","getUrlFromScript","resolver","getOrCreateResolver","resolve","otherChunkData","otherChunks","otherChunkPath","getChunkPath","otherChunkUrl","getChunkRelativeUrl","Promise","all","map","loadInitialChunk","runtimeModuleIds","length","moduleId","getOrInstantiateRuntimeModule","loadChunkCached","sourceType","doLoadChunk","loadWebAssembly","_sourceType","_sourceData","wasmChunkPath","_edgeModule","importsObj","req","fetchWebAssembly","instance","WebAssembly","instantiateStreaming","exports","loadWebAssemblyModule","compileStreaming","get","reject","promise","innerResolve","innerReject","resolved","loadingStarted","set","SourceType","Runtime","isCss","importScripts","isJs","TURBOPACK_NEXT_CHUNK_URLS","push","Error","decodedChunkUrl","decodeURI","previousLinks","querySelectorAll","link","createElement","rel","href","onerror","onload","head","appendChild","previousScripts","script","Array","from","addEventListener","src","fetch"],"mappings":"AAAA;;;;CAIC,GAED,oDAAoD,GAEpD,sEAAsE;AACtE,mEAAmE;AAEnE,SAASA;IACP,+CAA+C;IAC/C,OACE,CAACC,KAAKC,sBAAsB,IAC1BC,UAAUC,eACNC,eAAe,QACfC,QAAQ,oBAAoB,GAAG,KACrC;AAEJ;AAUA,IAAIC;AAEJ;;CAEC,GACD,MAAMC,iBAA+C,IAAIC;AAExD,CAAC;IACAF,UAAU;QACR,MAAMG,eAAcC,KAAK,EAAEC,MAAM;YAC/B,IAAIC,YAAYC,kBAAkBH;YAClC,IAAII,WAAWC,iBAAiBL;YAEhC,MAAMM,WAAWC,oBAAoBH;YACrCE,SAASE,OAAO;YAEhB,IAAIP,UAAU,MAAM;gBAClB;YACF;YAEA,KAAK,MAAMQ,kBAAkBR,OAAOS,WAAW,CAAE;gBAC/C,MAAMC,iBAAiBC,aAAaH;gBACpC,MAAMI,gBAAgBC,oBAAoBH;gBAE1C,iFAAiF;gBACjFJ,oBAAoBM;YACtB;YAEA,kFAAkF;YAClF,MAAME,QAAQC,GAAG,CACff,OAAOS,WAAW,CAACO,GAAG,CAAC,CAACR,iBACtBS,iBAAiBhB,WAAWO;YAIhC,IAAIR,OAAOkB,gBAAgB,CAACC,MAAM,GAAG,GAAG;gBACtC,KAAK,MAAMC,YAAYpB,OAAOkB,gBAAgB,CAAE;oBAC9CG,8BAA8BpB,WAAWmB;gBAC3C;YACF;QACF;QAEA;;;KAGC,GACDE,iBAAgBC,UAAsB,EAAEpB,QAAkB;YACxD,OAAOqB,YAAYD,YAAYpB;QACjC;QAEA,MAAMsB,iBACJC,WAAuB,EACvBC,WAAuB,EACvBC,aAAwB,EACxBC,WAAqC,EACrCC,UAA+B;YAE/B,MAAMC,MAAMC,iBAAiBJ;YAE7B,MAAM,EAAEK,QAAQ,EAAE,GAAG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EAAyE;oBACzE,wEAAwE;oBACxE,eAAe;oBACfiE,OAAOL,OAAO,GAAG;wBACf1D,SAASmC,MAAM;oBACjB;oBACA,kDAAkD;oBAClDjD,SAAS0E,IAAI,CAACC,WAAW,CAACE;gBAC5B;YACF,OAAO;gBACL,MAAM,IAAId,MAAM,CAAC,mCAAmC,EAAEnD,UAAU;YAClE;QACF;QAEAE,SAASwC,cAAc,GAAG;QAC1B,OAAOxC,SAASoC,OAAO;IACzB;IAEA,SAAST,iBAAiBJ,aAAwB;QAChD,OAAO6C,MAAM5D,oBAAoBe;IACnC;AACF,CAAC","ignoreList":[0]}}, - {"offset": {"line": 2116, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/dev-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack development\n * ECMAScript DOM runtime.\n *\n * It will be appended to the base development runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n/// \n/// \n\nlet DEV_BACKEND: DevRuntimeBackend\n;(() => {\n DEV_BACKEND = {\n unloadChunk(chunkUrl) {\n deleteResolver(chunkUrl)\n\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const links = document.querySelectorAll(\n `link[href=\"${chunkUrl}\"],link[href^=\"${chunkUrl}?\"],link[href=\"${decodedChunkUrl}\"],link[href^=\"${decodedChunkUrl}?\"]`\n )\n for (const link of Array.from(links)) {\n link.remove()\n }\n } else if (isJs(chunkUrl)) {\n // Unloading a JS chunk would have no effect, as it lives in the JS\n // runtime once evaluated.\n // However, we still want to remove the script tag from the DOM to keep\n // the HTML somewhat consistent from the user's perspective.\n const scripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n for (const script of Array.from(scripts)) {\n script.remove()\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n },\n\n reloadChunk(chunkUrl) {\n return new Promise((resolve, reject) => {\n if (!isCss(chunkUrl)) {\n reject(new Error('The DOM backend can only reload CSS chunks'))\n return\n }\n\n const decodedChunkUrl = decodeURI(chunkUrl)\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n\n if (previousLinks.length === 0) {\n reject(new Error(`No link element found for chunk ${chunkUrl}`))\n return\n }\n\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n\n if (navigator.userAgent.includes('Firefox')) {\n // Firefox won't reload CSS files that were previously loaded on the current page,\n // we need to add a query param to make sure CSS is actually reloaded from the server.\n //\n // I believe this is this issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506\n //\n // Safari has a similar issue, but only if you have a `` tag\n // pointing to the same URL as the stylesheet: https://bugs.webkit.org/show_bug.cgi?id=187726\n link.href = `${chunkUrl}?ts=${Date.now()}`\n } else {\n link.href = chunkUrl\n }\n\n link.onerror = () => {\n reject()\n }\n link.onload = () => {\n // First load the new CSS, then remove the old ones. This prevents visible\n // flickering that would happen in-between removing the previous CSS and\n // loading the new one.\n for (const previousLink of Array.from(previousLinks))\n previousLink.remove()\n\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolve()\n }\n\n // Make sure to insert the new CSS right after the previous one, so that\n // its precedence is higher.\n previousLinks[0].parentElement!.insertBefore(\n link,\n previousLinks[0].nextSibling\n )\n })\n },\n\n restart: () => self.location.reload(),\n }\n\n function deleteResolver(chunkUrl: ChunkUrl) {\n chunkResolvers.delete(chunkUrl)\n }\n})()\n\nfunction _eval({ code, url, map }: EcmascriptModuleEntry): ModuleFactory {\n code += `\\n\\n//# sourceURL=${encodeURI(\n location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX\n )}`\n if (map) {\n code += `\\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(\n // btoa doesn't handle nonlatin characters, so escape them as \\x sequences\n // See https://stackoverflow.com/a/26603875\n unescape(encodeURIComponent(map))\n )}`\n }\n\n // eslint-disable-next-line no-eval\n return eval(code)\n}\n"],"names":["DEV_BACKEND","unloadChunk","chunkUrl","deleteResolver","decodedChunkUrl","decodeURI","isCss","links","document","querySelectorAll","link","Array","from","remove","isJs","scripts","script","Error","reloadChunk","Promise","resolve","reject","previousLinks","length","createElement","rel","navigator","userAgent","includes","href","Date","now","onerror","onload","previousLink","parentElement","insertBefore","nextSibling","restart","self","location","reload","chunkResolvers","delete","_eval","code","url","map","encodeURI","origin","CHUNK_BASE_PATH","ASSET_SUFFIX","btoa","unescape","encodeURIComponent","eval"],"mappings":"AAAA;;;;;CAKC,GAED,oDAAoD,GAEpD,gDAAgD;AAChD,4CAA4C;AAC5C,iDAAiD;AACjD,0DAA0D;AAE1D,IAAIA;AACH,CAAC;IACAA,cAAc;QACZC,aAAYC,QAAQ;YAClBC,eAAeD;YAEf,gFAAgF;YAChF,MAAME,kBAAkBC,UAAUH;YAElC,IAAII,MAAMJ,WAAW;gBACnB,MAAMK,QAAQC,SAASC,gBAAgB,CACrC,CAAC,WAAW,EAAEP,SAAS,eAAe,EAAEA,SAAS,eAAe,EAAEE,gBAAgB,eAAe,EAAEA,gBAAgB,GAAG,CAAC;gBAEzH,KAAK,MAAMM,QAAQC,MAAMC,IAAI,CAACL,OAAQ;oBACpCG,KAAKG,MAAM;gBACb;YACF,OAAO,IAAIC,KAAKZ,WAAW;gBACzB,mEAAmE;gBACnE,0BAA0B;gBAC1B,uEAAuE;gBACvE,4DAA4D;gBAC5D,MAAMa,UAAUP,SAASC,gBAAgB,CACvC,CAAC,YAAY,EAAEP,SAAS,gBAAgB,EAAEA,SAAS,gBAAgB,EAAEE,gBAAgB,gBAAgB,EAAEA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E,4BAA4B;gBAC5BE,aAAa,CAAC,EAAE,CAACa,aAAa,CAAEC,YAAY,CAC1C1B,MACAY,aAAa,CAAC,EAAE,CAACe,WAAW;YAEhC;QACF;QAEAC,SAAS,IAAMC,KAAKC,QAAQ,CAACC,MAAM;IACrC;IAEA,SAAStC,eAAeD,QAAkB;QACxCwC,eAAeC,MAAM,CAACzC;IACxB;AACF,CAAC;AAED,SAAS0C,MAAM,EAAEC,IAAI,EAAEC,GAAG,EAAEC,GAAG,EAAyB;IACtDF,QAAQ,CAAC,kBAAkB,EAAEG,UAC3BR,SAASS,MAAM,GAAGC,kBAAkBJ,MAAMK,eACzC;IACH,IAAIJ,KAAK;QACPF,QAAQ,CAAC,kEAAkE,EAAEO,KAC3E,0EAA0E;QAC1E,2CAA2C;QAC3CC,SAASC,mBAAmBP,QAC3B;IACL;IAEA,mCAAmC;IACnC,OAAOQ,KAAKV;AACd","ignoreList":[0]}}] + {"offset": {"line": 1950, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/runtime-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack ECMAScript DOM runtime.\n *\n * It will be appended to the base runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\nfunction getAssetSuffixFromScriptSrc() {\n // TURBOPACK_ASSET_SUFFIX is set in web workers\n if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX\n const src = document?.currentScript?.getAttribute?.('src') ?? ''\n const qi = src.indexOf('?')\n return qi >= 0 ? src.slice(qi) : ''\n}\n\ntype ChunkResolver = {\n resolved: boolean\n loadingStarted: boolean\n resolve: () => void\n reject: (error?: Error) => void\n promise: Promise\n}\n\nlet BACKEND: RuntimeBackend\n\n/**\n * Maps chunk paths to the corresponding resolver.\n */\nconst chunkResolvers: Map = new Map()\n\n;(() => {\n BACKEND = {\n async registerChunk(chunk, params) {\n let chunkPath = getPathFromScript(chunk)\n let chunkUrl = getUrlFromScript(chunk)\n\n const resolver = getOrCreateResolver(chunkUrl)\n resolver.resolve()\n\n if (params == null) {\n return\n }\n\n for (const otherChunkData of params.otherChunks) {\n const otherChunkPath = getChunkPath(otherChunkData)\n const otherChunkUrl = getChunkRelativeUrl(otherChunkPath)\n\n // Chunk might have started loading, so we want to avoid triggering another load.\n getOrCreateResolver(otherChunkUrl)\n }\n\n // This waits for chunks to be loaded, but also marks included items as available.\n await Promise.all(\n params.otherChunks.map((otherChunkData) =>\n loadInitialChunk(chunkPath, otherChunkData)\n )\n )\n\n if (params.runtimeModuleIds.length > 0) {\n for (const moduleId of params.runtimeModuleIds) {\n getOrInstantiateRuntimeModule(chunkPath, moduleId)\n }\n }\n },\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n loadChunkCached(sourceType: SourceType, chunkUrl: ChunkUrl) {\n return doLoadChunk(sourceType, chunkUrl)\n },\n\n async loadWebAssembly(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n const { instance } = await WebAssembly.instantiateStreaming(\n req,\n importsObj\n )\n\n return instance.exports\n },\n\n async loadWebAssemblyModule(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n return await WebAssembly.compileStreaming(req)\n },\n }\n\n function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {\n let resolver = chunkResolvers.get(chunkUrl)\n if (!resolver) {\n let resolve: () => void\n let reject: (error?: Error) => void\n const promise = new Promise((innerResolve, innerReject) => {\n resolve = innerResolve\n reject = innerReject\n })\n resolver = {\n resolved: false,\n loadingStarted: false,\n promise,\n resolve: () => {\n resolver!.resolved = true\n resolve()\n },\n reject: reject!,\n }\n chunkResolvers.set(chunkUrl, resolver)\n }\n return resolver\n }\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n function doLoadChunk(sourceType: SourceType, chunkUrl: ChunkUrl) {\n const resolver = getOrCreateResolver(chunkUrl)\n if (resolver.loadingStarted) {\n return resolver.promise\n }\n\n if (sourceType === SourceType.Runtime) {\n // We don't need to load chunks references from runtime code, as they're already\n // present in the DOM.\n resolver.loadingStarted = true\n\n if (isCss(chunkUrl)) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n\n // We need to wait for JS chunks to register themselves within `registerChunk`\n // before we can start instantiating runtime modules, hence the absence of\n // `resolver.resolve()` in this branch.\n\n return resolver.promise\n }\n\n if (typeof importScripts === 'function') {\n // We're in a web worker\n if (isCss(chunkUrl)) {\n // ignore\n } else if (isJs(chunkUrl)) {\n self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl)\n importScripts(chunkUrl)\n } else {\n throw new Error(\n `can't infer type of chunk from URL ${chunkUrl} in worker`\n )\n }\n } else {\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n if (previousLinks.length > 0) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n } else {\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n link.href = chunkUrl\n link.onerror = () => {\n resolver.reject()\n }\n link.onload = () => {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(link)\n }\n } else if (isJs(chunkUrl)) {\n const previousScripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n if (previousScripts.length > 0) {\n // There is this edge where the script already failed loading, but we\n // can't detect that. The Promise will never resolve in this case.\n for (const script of Array.from(previousScripts)) {\n script.addEventListener('error', () => {\n resolver.reject()\n })\n }\n } else {\n const script = document.createElement('script')\n script.src = chunkUrl\n // We'll only mark the chunk as loaded once the script has been executed,\n // which happens in `registerChunk`. Hence the absence of `resolve()` in\n // this branch.\n script.onerror = () => {\n resolver.reject()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(script)\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n }\n\n resolver.loadingStarted = true\n return resolver.promise\n }\n\n function fetchWebAssembly(wasmChunkPath: ChunkPath) {\n return fetch(getChunkRelativeUrl(wasmChunkPath))\n }\n})()\n"],"names":["getAssetSuffixFromScriptSrc","self","TURBOPACK_ASSET_SUFFIX","src","document","currentScript","getAttribute","qi","indexOf","slice","BACKEND","chunkResolvers","Map","registerChunk","chunk","params","chunkPath","getPathFromScript","chunkUrl","getUrlFromScript","resolver","getOrCreateResolver","resolve","otherChunkData","otherChunks","otherChunkPath","getChunkPath","otherChunkUrl","getChunkRelativeUrl","Promise","all","map","loadInitialChunk","runtimeModuleIds","length","moduleId","getOrInstantiateRuntimeModule","loadChunkCached","sourceType","doLoadChunk","loadWebAssembly","_sourceType","_sourceData","wasmChunkPath","_edgeModule","importsObj","req","fetchWebAssembly","instance","WebAssembly","instantiateStreaming","exports","loadWebAssemblyModule","compileStreaming","get","reject","promise","innerResolve","innerReject","resolved","loadingStarted","set","SourceType","Runtime","isCss","importScripts","isJs","TURBOPACK_NEXT_CHUNK_URLS","push","Error","decodedChunkUrl","decodeURI","previousLinks","querySelectorAll","link","createElement","rel","href","onerror","onload","head","appendChild","previousScripts","script","Array","from","addEventListener","fetch"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Ge;oBACb,yEAAyE;oBACzE,wEAAwE;oBACxE,eAAe;oBACfiE,OAAOL,OAAO,GAAG;wBACf1D,SAASmC,MAAM;oBACjB;oBACA,kDAAkD;oBAClDnD,SAAS4E,IAAI,CAACC,WAAW,CAACE;gBAC5B;YACF,OAAO;gBACL,MAAM,IAAId,MAAM,CAAC,mCAAmC,EAAEnD,UAAU;YAClE;QACF;QAEAE,SAASwC,cAAc,GAAG;QAC1B,OAAOxC,SAASoC,OAAO;IACzB;IAEA,SAAST,iBAAiBJ,aAAwB;QAChD,OAAO4C,MAAM3D,oBAAoBe;IACnC;AACF,CAAC","ignoreList":[0]}}, + {"offset": {"line": 2119, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/dev-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack development\n * ECMAScript DOM runtime.\n *\n * It will be appended to the base development runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n/// \n/// \n\nlet DEV_BACKEND: DevRuntimeBackend\n;(() => {\n DEV_BACKEND = {\n unloadChunk(chunkUrl) {\n deleteResolver(chunkUrl)\n\n // Strip query string so we match links regardless of cache-busting\n // params (e.g. ?ts=) that may differ between HMR updates.\n const baseChunkUrl = chunkUrl.split('?')[0]\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedBaseChunkUrl = decodeURI(baseChunkUrl)\n\n if (isCss(chunkUrl)) {\n const links = document.querySelectorAll(\n `link[href=\"${baseChunkUrl}\"],link[href^=\"${baseChunkUrl}?\"],link[href=\"${decodedBaseChunkUrl}\"],link[href^=\"${decodedBaseChunkUrl}?\"]`\n )\n for (const link of Array.from(links)) {\n link.remove()\n }\n } else if (isJs(chunkUrl)) {\n // Unloading a JS chunk would have no effect, as it lives in the JS\n // runtime once evaluated.\n // However, we still want to remove the script tag from the DOM to keep\n // the HTML somewhat consistent from the user's perspective.\n const scripts = document.querySelectorAll(\n `script[src=\"${baseChunkUrl}\"],script[src^=\"${baseChunkUrl}?\"],script[src=\"${decodedBaseChunkUrl}\"],script[src^=\"${decodedBaseChunkUrl}?\"]`\n )\n for (const script of Array.from(scripts)) {\n script.remove()\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n },\n\n reloadChunk(chunkUrl) {\n return new Promise((resolve, reject) => {\n if (!isCss(chunkUrl)) {\n reject(new Error('The DOM backend can only reload CSS chunks'))\n return\n }\n\n // Strip query string so we match links regardless of cache-busting\n // params (e.g. ?ts=) that may differ between HMR updates.\n const baseChunkUrl = chunkUrl.split('?')[0]\n const decodedBaseChunkUrl = decodeURI(baseChunkUrl)\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${baseChunkUrl}\"],link[rel=stylesheet][href^=\"${baseChunkUrl}?\"],link[rel=stylesheet][href=\"${decodedBaseChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedBaseChunkUrl}?\"]`\n )\n\n if (previousLinks.length === 0) {\n reject(new Error(`No link element found for chunk ${chunkUrl}`))\n return\n }\n\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n\n if (\n navigator.userAgent.includes('Firefox') ||\n (navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome') &&\n !navigator.userAgent.includes('Chromium'))\n ) {\n // Firefox won't reload CSS files that were previously loaded on the\n // current page: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506\n //\n // Safari serves cached CSS when a exists for the\n // same URL: https://bugs.webkit.org/show_bug.cgi?id=187726\n //\n // Replace or add a fresh `ts` cache-busting param without\n // discarding other query parameters that may already be present.\n const url = new URL(chunkUrl, location.origin)\n url.searchParams.set('ts', String(Date.now()))\n // Reduced timer precision in some browers could lead to an update getting dropped\n // in firefox if it happens fast enough (in firefox precision is sometimes 100ms!).\n // So trust that the server is only updating us when it is important and use a\n // random number to bust the cache.\n url.searchParams.set('_next_rand', String(Math.random()))\n link.href = url.pathname + url.search\n } else {\n link.href = chunkUrl\n }\n\n link.onerror = () => {\n reject()\n }\n link.onload = () => {\n // First load the new CSS, then remove the old ones. This prevents visible\n // flickering that would happen in-between removing the previous CSS and\n // loading the new one.\n for (const previousLink of Array.from(previousLinks))\n previousLink.remove()\n\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolve()\n }\n\n // Make sure to insert the new CSS right after the previous one, so that\n // its precedence is higher.\n previousLinks[0].parentElement!.insertBefore(\n link,\n previousLinks[0].nextSibling\n )\n })\n },\n\n restart: () => self.location.reload(),\n }\n\n function deleteResolver(chunkUrl: ChunkUrl) {\n chunkResolvers.delete(chunkUrl)\n }\n})()\n\nfunction _eval({ code, url, map }: EcmascriptModuleEntry): ModuleFactory {\n code += `\\n\\n//# sourceURL=${encodeURI(\n location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX\n )}`\n if (map) {\n code += `\\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(\n // btoa doesn't handle nonlatin characters, so escape them as \\x sequences\n // See https://stackoverflow.com/a/26603875\n unescape(encodeURIComponent(map))\n )}`\n }\n\n // eslint-disable-next-line no-eval\n return eval(code)\n}\n"],"names":["DEV_BACKEND","unloadChunk","chunkUrl","deleteResolver","baseChunkUrl","split","decodedBaseChunkUrl","decodeURI","isCss","links","document","querySelectorAll","link","Array","from","remove","isJs","scripts","script","Error","reloadChunk","Promise","resolve","reject","previousLinks","length","createElement","rel","navigator","userAgent","includes","url","URL","location","origin","searchParams","set","String","Date","now","Math","random","href","pathname","search","onerror","onload","previousLink","parentElement","insertBefore","nextSibling","restart","self","reload","chunkResolvers","delete","_eval","code","map","encodeURI","CHUNK_BASE_PATH","ASSET_SUFFIX","btoa","unescape","encodeURIComponent","eval"],"mappings":"AAAA;;;;;CAKC,GAED,oDAAoD,GAEpD,gDAAgD;AAChD,4CAA4C;AAC5C,iDAAiD;AACjD,0DAA0D;AAE1D,IAAIA;AACH,CAAC;IACAA,cAAc;QACZC,aAAYC,QAAQ;YAClBC,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IAAMC,KAAKnB,QAAQ,CAACoB,MAAM;IACrC;IAEA,SAASlD,eAAeD,QAAkB;QACxCoD,eAAeC,MAAM,CAACrD;IACxB;AACF,CAAC;AAED,SAASsD,MAAM,EAAEC,IAAI,EAAE1B,GAAG,EAAE2B,GAAG,EAAyB;IACtDD,QAAQ,CAAC,kBAAkB,EAAEE,UAC3B1B,SAASC,MAAM,GAAG0B,kBAAkB7B,MAAM8B,eACzC;IACH,IAAIH,KAAK;QACPD,QAAQ,CAAC,kEAAkE,EAAEK,KAC3E,0EAA0E;QAC1E,2CAA2C;QAC3CC,SAASC,mBAAmBN,QAC3B;IACL;IAEA,mCAAmC;IACnC,OAAOO,KAAKR;AACd","ignoreList":[0]}}] } \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/output/0teu_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_0i7eipv.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/output/0teu_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_0i7eipv.js.map index 8d17818c396f..e9d426222813 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/output/0teu_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_0i7eipv.js.map +++ b/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/output/0teu_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_0i7eipv.js.map @@ -6,6 +6,6 @@ {"offset": {"line": 590, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/runtime-base.ts"],"sourcesContent":["/**\n * This file contains runtime types and functions that are shared between all\n * Turbopack *browser* ECMAScript runtimes.\n *\n * It will be appended to the runtime code of each runtime right after the\n * shared runtime utils.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\n// Used in WebWorkers to tell the runtime about the chunk suffix\ndeclare var TURBOPACK_ASSET_SUFFIX: string\n// Used in WebWorkers to tell the runtime about the current chunk url since it\n// can't be detected via `document.currentScript`. Note it's stored in reversed\n// order to use `push` and `pop`\ndeclare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined\n\n// Injected by rust code\ndeclare var CHUNK_BASE_PATH: string\ndeclare var ASSET_SUFFIX: string\ndeclare var WORKER_FORWARDED_GLOBALS: string[]\n\ninterface TurbopackBrowserBaseContext extends TurbopackBaseContext {\n R: ResolvePathFromModule\n}\n\nconst browserContextPrototype =\n Context.prototype as TurbopackBrowserBaseContext\n\n// Provided by build or dev base\ndeclare function instantiateModule(\n id: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): Module\n\ntype RuntimeParams = {\n otherChunks: ChunkData[]\n runtimeModuleIds: ModuleId[]\n}\n\ntype ChunkRegistrationChunk =\n | ChunkPath\n | { getAttribute: (name: string) => string | null }\n | undefined\n\ntype ChunkRegistration = [\n chunkPath: ChunkRegistrationChunk,\n ...([RuntimeParams] | CompressedModuleFactories),\n]\n\ntype ChunkList = {\n script: ChunkRegistrationChunk\n chunks: ChunkData[]\n source: 'entry' | 'dynamic'\n}\n\ninterface RuntimeBackend {\n registerChunk: (\n chunkPath: ChunkPath | ChunkScript,\n params?: RuntimeParams\n ) => void\n /**\n * Returns the same Promise for the same chunk URL.\n */\n loadChunkCached: (sourceType: SourceType, chunkUrl: ChunkUrl) => Promise\n loadWebAssembly: (\n sourceType: SourceType,\n sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ) => Promise\n loadWebAssemblyModule: (\n sourceType: SourceType,\n sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module\n ) => Promise\n}\n\ninterface DevRuntimeBackend {\n reloadChunk?: (chunkUrl: ChunkUrl) => Promise\n unloadChunk?: (chunkUrl: ChunkUrl) => void\n restart: () => void\n}\n\nconst moduleFactories: ModuleFactories = new Map()\ncontextPrototype.M = moduleFactories\n\nconst availableModules: Map | true> = new Map()\n\nconst availableModuleChunks: Map | true> = new Map()\n\nfunction loadChunk(\n this: TurbopackBrowserBaseContext,\n chunkData: ChunkData\n): Promise {\n return loadChunkInternal(SourceType.Parent, this.m.id, chunkData)\n}\nbrowserContextPrototype.l = loadChunk\n\nfunction loadInitialChunk(chunkPath: ChunkPath, chunkData: ChunkData) {\n return loadChunkInternal(SourceType.Runtime, chunkPath, chunkData)\n}\n\nasync function loadChunkInternal(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkData: ChunkData\n): Promise {\n if (typeof chunkData === 'string') {\n return loadChunkPath(sourceType, sourceData, chunkData)\n }\n\n const includedList = chunkData.included || []\n const modulesPromises = includedList.map((included) => {\n if (moduleFactories.has(included)) return true\n return availableModules.get(included)\n })\n if (modulesPromises.length > 0 && modulesPromises.every((p) => p)) {\n // When all included items are already loaded or loading, we can skip loading ourselves\n await Promise.all(modulesPromises)\n return\n }\n\n const includedModuleChunksList = chunkData.moduleChunks || []\n const moduleChunksPromises = includedModuleChunksList\n .map((included) => {\n // TODO(alexkirsz) Do we need this check?\n // if (moduleFactories[included]) return true;\n return availableModuleChunks.get(included)\n })\n .filter((p) => p)\n\n let promise: Promise\n if (moduleChunksPromises.length > 0) {\n // Some module chunks are already loaded or loading.\n\n if (moduleChunksPromises.length === includedModuleChunksList.length) {\n // When all included module chunks are already loaded or loading, we can skip loading ourselves\n await Promise.all(moduleChunksPromises)\n return\n }\n\n const moduleChunksToLoad: Set = new Set()\n for (const moduleChunk of includedModuleChunksList) {\n if (!availableModuleChunks.has(moduleChunk)) {\n moduleChunksToLoad.add(moduleChunk)\n }\n }\n\n for (const moduleChunkToLoad of moduleChunksToLoad) {\n const promise = loadChunkPath(sourceType, sourceData, moduleChunkToLoad)\n\n availableModuleChunks.set(moduleChunkToLoad, promise)\n\n moduleChunksPromises.push(promise)\n }\n\n promise = Promise.all(moduleChunksPromises)\n } else {\n promise = loadChunkPath(sourceType, sourceData, chunkData.path)\n\n // Mark all included module chunks as loading if they are not already loaded or loading.\n for (const includedModuleChunk of includedModuleChunksList) {\n if (!availableModuleChunks.has(includedModuleChunk)) {\n availableModuleChunks.set(includedModuleChunk, promise)\n }\n }\n }\n\n for (const included of includedList) {\n if (!availableModules.has(included)) {\n // It might be better to race old and new promises, but it's rare that the new promise will be faster than a request started earlier.\n // In production it's even more rare, because the chunk optimization tries to deduplicate modules anyway.\n availableModules.set(included, promise)\n }\n }\n\n await promise\n}\n\nconst loadedChunk = Promise.resolve(undefined)\nconst instrumentedBackendLoadChunks = new WeakMap<\n Promise,\n Promise | typeof loadedChunk\n>()\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkByUrl(\n this: TurbopackBrowserBaseContext,\n chunkUrl: ChunkUrl\n) {\n return loadChunkByUrlInternal(SourceType.Parent, this.m.id, chunkUrl)\n}\nbrowserContextPrototype.L = loadChunkByUrl\n\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkByUrlInternal(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkUrl: ChunkUrl\n): Promise {\n const thenable = BACKEND.loadChunkCached(sourceType, chunkUrl)\n let entry = instrumentedBackendLoadChunks.get(thenable)\n if (entry === undefined) {\n const resolve = instrumentedBackendLoadChunks.set.bind(\n instrumentedBackendLoadChunks,\n thenable,\n loadedChunk\n )\n entry = thenable.then(resolve).catch((cause) => {\n let loadReason: string\n switch (sourceType) {\n case SourceType.Runtime:\n loadReason = `as a runtime dependency of chunk ${sourceData}`\n break\n case SourceType.Parent:\n loadReason = `from module ${sourceData}`\n break\n case SourceType.Update:\n loadReason = 'from an HMR update'\n break\n default:\n invariant(\n sourceType,\n (sourceType) => `Unknown source type: ${sourceType}`\n )\n }\n let error = new Error(\n `Failed to load chunk ${chunkUrl} ${loadReason}${\n cause ? `: ${cause}` : ''\n }`,\n cause ? { cause } : undefined\n )\n error.name = 'ChunkLoadError'\n throw error\n })\n instrumentedBackendLoadChunks.set(thenable, entry)\n }\n\n return entry\n}\n\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkPath(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkPath: ChunkPath\n): Promise {\n const url = getChunkRelativeUrl(chunkPath)\n return loadChunkByUrlInternal(sourceType, sourceData, url)\n}\n\n/**\n * Returns an absolute url to an asset.\n */\nfunction resolvePathFromModule(\n this: TurbopackBaseContext,\n moduleId: string\n): string {\n const exported = this.r(moduleId)\n return exported?.default ?? exported\n}\nbrowserContextPrototype.R = resolvePathFromModule\n\n/**\n * no-op for browser\n * @param modulePath\n */\nfunction resolveAbsolutePath(modulePath?: string): string {\n return `/ROOT/${modulePath ?? ''}`\n}\nbrowserContextPrototype.P = resolveAbsolutePath\n\n/**\n * Exports a URL with the static suffix appended.\n */\nfunction exportUrl(\n this: TurbopackBrowserBaseContext,\n url: string,\n id: ModuleId | undefined\n) {\n exportValue.call(this, `${url}${ASSET_SUFFIX}`, id)\n}\nbrowserContextPrototype.q = exportUrl\n\n/**\n * Creates a worker by instantiating the given WorkerConstructor with the\n * appropriate URL and options.\n *\n * The entrypoint is a pre-compiled worker runtime file. The params configure\n * which module chunks to load and which module to run as the entry point.\n *\n * The params are a JSON array of the following structure:\n * `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`\n *\n * @param WorkerConstructor The Worker or SharedWorker constructor\n * @param entrypoint URL path to the worker entrypoint chunk\n * @param moduleChunks list of module chunk paths to load\n * @param workerOptions options to pass to the Worker constructor (optional)\n */\nfunction createWorker(\n WorkerConstructor: { new (url: URL, options?: object): Worker },\n entrypoint: ChunkPath,\n moduleChunks: ChunkPath[],\n workerOptions?: object\n): Worker {\n const isSharedWorker = WorkerConstructor.name === 'SharedWorker'\n\n const chunkUrls = moduleChunks\n .map((chunk) => getChunkRelativeUrl(chunk))\n .reverse()\n const params: unknown[] = [chunkUrls, ASSET_SUFFIX]\n for (const globalName of WORKER_FORWARDED_GLOBALS) {\n params.push((globalThis as Record)[globalName])\n }\n\n const url = new URL(getChunkRelativeUrl(entrypoint), location.origin)\n const paramsJson = JSON.stringify(params)\n if (isSharedWorker) {\n url.searchParams.set('params', paramsJson)\n } else {\n url.hash = '#params=' + encodeURIComponent(paramsJson)\n }\n\n // Remove type: \"module\" from options since our worker entrypoint is not a module\n const options = workerOptions\n ? { ...workerOptions, type: undefined }\n : undefined\n return new WorkerConstructor(url, options)\n}\nbrowserContextPrototype.b = createWorker\n\n/**\n * Instantiates a runtime module.\n */\nfunction instantiateRuntimeModule(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): Module {\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n/**\n * Returns the URL relative to the origin where a chunk can be fetched from.\n */\nfunction getChunkRelativeUrl(chunkPath: ChunkPath | ChunkListPath): ChunkUrl {\n return `${CHUNK_BASE_PATH}${chunkPath\n .split('/')\n .map((p) => encodeURIComponent(p))\n .join('/')}${ASSET_SUFFIX}` as ChunkUrl\n}\n\n/**\n * Return the ChunkPath from a ChunkScript.\n */\nfunction getPathFromScript(chunkScript: ChunkPath | ChunkScript): ChunkPath\nfunction getPathFromScript(\n chunkScript: ChunkListPath | ChunkListScript\n): ChunkListPath\nfunction getPathFromScript(\n chunkScript: ChunkPath | ChunkListPath | ChunkScript | ChunkListScript\n): ChunkPath | ChunkListPath {\n if (typeof chunkScript === 'string') {\n return chunkScript as ChunkPath | ChunkListPath\n }\n const chunkUrl = chunkScript.src!\n const src = decodeURIComponent(chunkUrl.replace(/[?#].*$/, ''))\n const path = src.startsWith(CHUNK_BASE_PATH)\n ? src.slice(CHUNK_BASE_PATH.length)\n : src\n return path as ChunkPath | ChunkListPath\n}\n\n/**\n * Return the ChunkUrl from a ChunkScript.\n */\nfunction getUrlFromScript(chunk: ChunkPath | ChunkScript): ChunkUrl {\n if (typeof chunk === 'string') {\n return getChunkRelativeUrl(chunk)\n } else {\n // This is already exactly what we want\n return chunk.src! as ChunkUrl\n }\n}\n\n/**\n * Determine the chunk to register. Note that this function has side-effects!\n */\nfunction getChunkFromRegistration(\n chunk: ChunkRegistrationChunk\n): ChunkPath | CurrentScript {\n if (typeof chunk === 'string') {\n return chunk\n } else if (!chunk) {\n if (typeof TURBOPACK_NEXT_CHUNK_URLS !== 'undefined') {\n return { src: TURBOPACK_NEXT_CHUNK_URLS.pop()! } as CurrentScript\n } else {\n throw new Error('chunk path empty but not in a worker')\n }\n } else {\n return { src: chunk.getAttribute('src')! } as CurrentScript\n }\n}\n\nconst regexJsUrl = /\\.js(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.\n */\nfunction isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {\n return regexJsUrl.test(chunkUrlOrPath)\n}\n\nconst regexCssUrl = /\\.css(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .css, optionally followed by ?query or #fragment.\n */\nfunction isCss(chunkUrl: ChunkUrl): boolean {\n return regexCssUrl.test(chunkUrl)\n}\n\nfunction loadWebAssembly(\n this: TurbopackBaseContext,\n chunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n): Promise {\n return BACKEND.loadWebAssembly(\n SourceType.Parent,\n this.m.id,\n chunkPath,\n edgeModule,\n importsObj\n )\n}\ncontextPrototype.w = loadWebAssembly\n\nfunction loadWebAssemblyModule(\n this: TurbopackBaseContext,\n chunkPath: ChunkPath,\n edgeModule: () => WebAssembly.Module\n): Promise {\n return BACKEND.loadWebAssemblyModule(\n SourceType.Parent,\n this.m.id,\n chunkPath,\n edgeModule\n )\n}\ncontextPrototype.u = loadWebAssemblyModule\n"],"names":["browserContextPrototype","Context","prototype","moduleFactories","Map","contextPrototype","M","availableModules","availableModuleChunks","loadChunk","chunkData","loadChunkInternal","SourceType","Parent","m","id","l","loadInitialChunk","chunkPath","Runtime","sourceType","sourceData","loadChunkPath","includedList","included","modulesPromises","map","has","get","length","every","p","Promise","all","includedModuleChunksList","moduleChunks","moduleChunksPromises","filter","promise","moduleChunksToLoad","Set","moduleChunk","add","moduleChunkToLoad","set","push","path","includedModuleChunk","loadedChunk","resolve","undefined","instrumentedBackendLoadChunks","WeakMap","loadChunkByUrl","chunkUrl","loadChunkByUrlInternal","L","thenable","BACKEND","loadChunkCached","entry","bind","then","catch","cause","loadReason","Update","invariant","error","Error","name","url","getChunkRelativeUrl","resolvePathFromModule","moduleId","exported","r","default","R","resolveAbsolutePath","modulePath","P","exportUrl","exportValue","call","ASSET_SUFFIX","q","createWorker","WorkerConstructor","entrypoint","workerOptions","isSharedWorker","chunkUrls","chunk","reverse","params","globalName","WORKER_FORWARDED_GLOBALS","globalThis","URL","location","origin","paramsJson","JSON","stringify","searchParams","hash","encodeURIComponent","options","type","b","instantiateRuntimeModule","instantiateModule","CHUNK_BASE_PATH","split","join","getPathFromScript","chunkScript","src","decodeURIComponent","replace","startsWith","slice","getUrlFromScript","getChunkFromRegistration","TURBOPACK_NEXT_CHUNK_URLS","pop","getAttribute","regexJsUrl","isJs","chunkUrlOrPath","test","regexCssUrl","isCss","loadWebAssembly","edgeModule","importsObj","w","loadWebAssemblyModule","u"],"mappings":"AAAA;;;;;;CAMC,GAED,oDAAoD,GAEpD,6CAA6C;AAC7C,iEAAiE;AAEjE,gEAAgE;AAgBhE,MAAMA,0BACJC,QAAQC,SAAS;AA4DnB,MAAMC,kBAAmC,IAAIC;AAC7CC,iBAAiBC,CAAC,GAAGH;AAErB,MAAMI,mBAAuD,IAAIH;AAEjE,MAAMI,wBAA6D,IAAIJ;AAEvE,SAASK,UAEPC,SAAoB;IAEpB,OAAOC,kBAAkBC,WAAWC,MAAM,EAAE,IAAI,CAACC,CAAC,CAACC,EAAE,EAAEL;AACzD;AACAV,wBAAwBgB,CAAC,GAAGP;AAE5B,SAASQ,iBAAiBC,SAAoB,EAAER,SAAoB;IAClE,OAAOC,kBAAkBC,WAAWO,OAAO,EAAED,WAAWR;AAC1D;AAEA,eAAeC,kBACbS,UAAsB,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AAI,CAACA,OAAO;QACjB,IAAI,OAAOgC,8BAA8B,aAAa;YACpD,OAAO;gBAAEP,KAAKO,0BAA0BC,GAAG;YAAI;QACjD,OAAO;YACL,MAAM,IAAIzD,MAAM;QAClB;IACF,OAAO;QACL,OAAO;YAAEiD,KAAKzB,MAAMkC,YAAY,CAAC;QAAQ;IAC3C;AACF;AAEA,MAAMC,aAAa;AACnB;;CAEC,GACD,SAASC,KAAKC,cAAoC;IAChD,OAAOF,WAAWG,IAAI,CAACD;AACzB;AAEA,MAAME,cAAc;AACpB;;CAEC,GACD,SAASC,MAAM/E,QAAkB;IAC/B,OAAO8E,YAAYD,IAAI,CAAC7E;AAC1B;AAEA,SAASgF,gBAEPpH,SAAoB,EACpBqH,UAAoC,EACpCC,UAA+B;IAE/B,OAAO9E,QAAQ4E,eAAe,CAC5B1H,WAAWC,MAAM,EACjB,IAAI,CAACC,CAAC,CAACC,EAAE,EACTG,WACAqH,YACAC;AAEJ;AACAnI,iBAAiBoI,CAAC,GAAGH;AAErB,SAASI,sBAEPxH,SAAoB,EACpBqH,UAAoC;IAEpC,OAAO7E,QAAQgF,qBAAqB,CAClC9H,WAAWC,MAAM,EACjB,IAAI,CAACC,CAAC,CAACC,EAAE,EACTG,WACAqH;AAEJ;AACAlI,iBAAiBsI,CAAC,GAAGD","ignoreList":[0]}}, {"offset": {"line": 839, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared/runtime/hmr-runtime.ts"],"sourcesContent":["/// \n/// \n/// \n/// \n\ntype HotModuleFactoryFunction = ModuleFactoryFunction<\n HotModule,\n TurbopackBaseContext\n>\n\n/**\n * Shared HMR (Hot Module Replacement) implementation.\n *\n * This file contains the complete HMR implementation that's shared between\n * browser and Node.js runtimes. It manages module hot state, dependency\n * tracking, the module.hot API, and the full HMR update flow.\n */\n\n/**\n * The development module cache shared across the runtime.\n * Browser runtime declares this directly.\n * Node.js runtime assigns globalThis.__turbopack_module_cache__ to this.\n */\nlet devModuleCache: Record\n\n/**\n * Module IDs that are instantiated as part of the runtime of a chunk.\n */\nlet runtimeModules: Set\n\n/**\n * Maps module IDs to persisted data between executions of their hot module\n * implementation (`hot.data`).\n */\nconst moduleHotData: Map = new Map()\n\n/**\n * Maps module instances to their hot module state.\n * Uses WeakMap so it works with both HotModule and ModuleWithDirection.\n */\nconst moduleHotState: WeakMap = new WeakMap()\n\n/**\n * Modules that call `module.hot.invalidate()` (while being updated).\n */\nconst queuedInvalidatedModules: Set = new Set()\n\nclass UpdateApplyError extends Error {\n name = 'UpdateApplyError'\n\n dependencyChain: ModuleId[]\n\n constructor(message: string, dependencyChain: ModuleId[]) {\n super(message)\n this.dependencyChain = dependencyChain\n }\n}\n\ntype ModuleEffect =\n | {\n type: 'unaccepted'\n dependencyChain: ModuleId[]\n }\n | {\n type: 'self-declined'\n dependencyChain: ModuleId[]\n moduleId: ModuleId\n }\n | {\n type: 'declined'\n dependencyChain: ModuleId[]\n moduleId: ModuleId\n parentId: ModuleId\n }\n | {\n type: 'accepted'\n moduleId: ModuleId\n outdatedModules: Set\n outdatedDependencies: Map>\n }\n\n/**\n * Records parent-child relationship when a module imports another.\n * Should be called during module instantiation.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction trackModuleImport(\n parentModule: ModuleWithDirection,\n childModuleId: ModuleId,\n childModule: ModuleWithDirection | undefined\n): void {\n // Record that parent imports child\n if (parentModule.children.indexOf(childModuleId) === -1) {\n parentModule.children.push(childModuleId)\n }\n\n // Record that child is imported by parent\n if (childModule && childModule.parents.indexOf(parentModule.id) === -1) {\n childModule.parents.push(parentModule.id)\n }\n}\n\nfunction formatDependencyChain(dependencyChain: ModuleId[]): string {\n return `Dependency chain: ${dependencyChain.join(' -> ')}`\n}\n\n/**\n * Walks the dependency tree to find all modules affected by a change.\n * Returns information about whether the update can be accepted and which\n * modules need to be invalidated.\n *\n * @param moduleId - The module that changed\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept().\n * This is used for server-side HMR where pages auto-accept at the top level.\n */\nfunction getAffectedModuleEffects(\n moduleId: ModuleId,\n autoAcceptRootModules: boolean\n): ModuleEffect {\n const outdatedModules: Set = new Set()\n const outdatedDependencies: Map> = new Map()\n\n type QueueItem = { moduleId?: ModuleId; dependencyChain: ModuleId[] }\n\n const queue: QueueItem[] = [\n {\n moduleId,\n dependencyChain: [],\n },\n ]\n\n let nextItem\n while ((nextItem = queue.shift())) {\n const { moduleId, dependencyChain } = nextItem\n\n if (moduleId != null) {\n if (outdatedModules.has(moduleId)) {\n // Avoid infinite loops caused by cycles between modules in the dependency chain.\n continue\n }\n\n outdatedModules.add(moduleId)\n }\n\n // We've arrived at the runtime of the chunk, which means that nothing\n // else above can accept this update.\n if (moduleId === undefined) {\n if (autoAcceptRootModules) {\n return {\n type: 'accepted',\n moduleId,\n outdatedModules,\n outdatedDependencies,\n }\n }\n return {\n type: 'unaccepted',\n dependencyChain,\n }\n }\n\n const module = devModuleCache[moduleId]\n const hotState = moduleHotState.get(module)!\n\n if (\n // The module is not in the cache. Since this is a \"modified\" update,\n // it means that the module was never instantiated before.\n !module || // The module accepted itself without invalidating globalThis.\n // TODO is that right?\n (hotState.selfAccepted && !hotState.selfInvalidated)\n ) {\n continue\n }\n\n if (hotState.selfDeclined) {\n return {\n type: 'self-declined',\n dependencyChain,\n moduleId,\n }\n }\n\n if (runtimeModules.has(moduleId)) {\n if (autoAcceptRootModules) {\n continue\n }\n queue.push({\n moduleId: undefined,\n dependencyChain: [...dependencyChain, moduleId],\n })\n continue\n }\n\n for (const parentId of module.parents) {\n const parent = devModuleCache[parentId]\n\n if (!parent) {\n continue\n }\n\n const parentHotState = moduleHotState.get(parent)\n\n // Check if parent declined this dependency\n if (parentHotState?.declinedDependencies[moduleId]) {\n return {\n type: 'declined',\n dependencyChain: [...dependencyChain, moduleId],\n moduleId,\n parentId,\n }\n }\n\n // Skip if parent is already outdated\n if (outdatedModules.has(parentId)) {\n continue\n }\n\n // Check if parent accepts this dependency\n if (parentHotState?.acceptedDependencies[moduleId]) {\n if (!outdatedDependencies.has(parentId)) {\n outdatedDependencies.set(parentId, new Set())\n }\n outdatedDependencies.get(parentId)!.add(moduleId)\n continue\n }\n\n // Neither accepted nor declined — propagate to parent\n queue.push({\n moduleId: parentId,\n dependencyChain: [...dependencyChain, moduleId],\n })\n }\n\n // If no parents and we're at a root module, auto-accept if configured\n if (module.parents.length === 0 && autoAcceptRootModules) {\n continue\n }\n }\n\n return {\n type: 'accepted',\n moduleId,\n outdatedModules,\n outdatedDependencies,\n }\n}\n\n/**\n * Merges source dependency map into target dependency map.\n */\nfunction mergeDependencies(\n target: Map>,\n source: Map>\n): void {\n for (const [parentId, deps] of source) {\n const existing = target.get(parentId)\n if (existing) {\n for (const dep of deps) {\n existing.add(dep)\n }\n } else {\n target.set(parentId, new Set(deps))\n }\n }\n}\n\n/**\n * Computes all modules that need to be invalidated based on which modules changed.\n *\n * @param invalidated - The modules that have been invalidated\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction computedInvalidatedModules(\n invalidated: Iterable,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n} {\n const outdatedModules = new Set()\n const outdatedDependencies = new Map>()\n\n for (const moduleId of invalidated) {\n const effect = getAffectedModuleEffects(moduleId, autoAcceptRootModules)\n\n switch (effect.type) {\n case 'unaccepted':\n throw new UpdateApplyError(\n `cannot apply update: unaccepted module. ${formatDependencyChain(\n effect.dependencyChain\n )}.`,\n effect.dependencyChain\n )\n case 'self-declined':\n throw new UpdateApplyError(\n `cannot apply update: self-declined module. ${formatDependencyChain(\n effect.dependencyChain\n )}.`,\n effect.dependencyChain\n )\n case 'declined':\n throw new UpdateApplyError(\n `cannot apply update: declined dependency. ${formatDependencyChain(\n effect.dependencyChain\n )}. Declined by ${effect.parentId}.`,\n effect.dependencyChain\n )\n case 'accepted':\n for (const outdatedModuleId of effect.outdatedModules) {\n outdatedModules.add(outdatedModuleId)\n }\n mergeDependencies(outdatedDependencies, effect.outdatedDependencies)\n break\n default:\n invariant(effect, (effect) => `Unknown effect type: ${effect?.type}`)\n }\n }\n\n return { outdatedModules, outdatedDependencies }\n}\n\n/**\n * Creates the module.hot API object and its internal state.\n * This provides the HMR API that user code calls (module.hot.accept(), etc.)\n */\n\nfunction createModuleHot(\n moduleId: ModuleId,\n hotData: HotData\n): { hot: Hot; hotState: HotState } {\n const hotState: HotState = {\n selfAccepted: false,\n selfDeclined: false,\n selfInvalidated: false,\n disposeHandlers: [],\n acceptedDependencies: {},\n acceptedErrorHandlers: {},\n declinedDependencies: {},\n }\n\n const hot: Hot = {\n // TODO(alexkirsz) This is not defined in the HMR API. It was used to\n // decide whether to warn whenever an HMR-disposed module required other\n // modules. We might want to remove it.\n active: true,\n\n data: hotData ?? {},\n\n accept: (\n modules?: string | string[] | AcceptErrorHandler,\n callback?: AcceptCallback,\n errorHandler?: AcceptErrorHandler\n ) => {\n if (modules === undefined) {\n hotState.selfAccepted = true\n } else if (typeof modules === 'function') {\n hotState.selfAccepted = modules\n } else if (typeof modules === 'object' && modules !== null) {\n for (let i = 0; i < modules.length; i++) {\n hotState.acceptedDependencies[modules[i]] = callback || function () {}\n hotState.acceptedErrorHandlers[modules[i]] = errorHandler\n }\n } else {\n hotState.acceptedDependencies[modules] = callback || function () {}\n hotState.acceptedErrorHandlers[modules] = errorHandler\n }\n },\n\n decline: (dep?: string | string[]) => {\n if (dep === undefined) {\n hotState.selfDeclined = true\n } else if (typeof dep === 'object' && dep !== null) {\n for (let i = 0; i < dep.length; i++) {\n hotState.declinedDependencies[dep[i]] = true\n }\n } else {\n hotState.declinedDependencies[dep] = true\n }\n },\n\n dispose: (callback) => {\n hotState.disposeHandlers.push(callback)\n },\n\n addDisposeHandler: (callback) => {\n hotState.disposeHandlers.push(callback)\n },\n\n removeDisposeHandler: (callback) => {\n const idx = hotState.disposeHandlers.indexOf(callback)\n if (idx >= 0) {\n hotState.disposeHandlers.splice(idx, 1)\n }\n },\n\n invalidate: () => {\n hotState.selfInvalidated = true\n queuedInvalidatedModules.add(moduleId)\n },\n\n // NOTE(alexkirsz) This is part of the management API, which we don't\n // implement, but the Next.js React Refresh runtime uses this to decide\n // whether to schedule an update.\n status: () => 'idle',\n\n // NOTE(alexkirsz) Since we always return \"idle\" for now, these are no-ops.\n addStatusHandler: (_handler) => {},\n removeStatusHandler: (_handler) => {},\n\n // NOTE(jridgewell) Check returns the list of updated modules, but we don't\n // want the webpack code paths to ever update (the turbopack paths handle\n // this already).\n check: () => Promise.resolve(null),\n }\n\n return { hot, hotState }\n}\n\n/**\n * Processes queued invalidated modules and adds them to the outdated modules set.\n * Modules that call module.hot.invalidate() are queued and processed here.\n *\n * @param outdatedModules - The current set of outdated modules\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction applyInvalidatedModules(\n outdatedModules: Set,\n outdatedDependencies: Map>,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n} {\n if (queuedInvalidatedModules.size > 0) {\n const result = computedInvalidatedModules(\n queuedInvalidatedModules,\n autoAcceptRootModules\n )\n for (const moduleId of result.outdatedModules) {\n outdatedModules.add(moduleId)\n }\n mergeDependencies(outdatedDependencies, result.outdatedDependencies)\n\n queuedInvalidatedModules.clear()\n }\n\n return { outdatedModules, outdatedDependencies }\n}\n\n/**\n * Computes which outdated modules have self-accepted and can be hot reloaded.\n */\n\nfunction computeOutdatedSelfAcceptedModules(\n outdatedModules: Iterable\n): { moduleId: ModuleId; errorHandler: true | Function }[] {\n const outdatedSelfAcceptedModules: {\n moduleId: ModuleId\n errorHandler: true | Function\n }[] = []\n for (const moduleId of outdatedModules) {\n const module = devModuleCache[moduleId]\n const hotState = moduleHotState.get(module)\n if (module && hotState?.selfAccepted && !hotState.selfInvalidated) {\n outdatedSelfAcceptedModules.push({\n moduleId,\n errorHandler: hotState.selfAccepted,\n })\n }\n }\n return outdatedSelfAcceptedModules\n}\n\n/**\n * Disposes of an instance of a module.\n * Runs hot.dispose handlers and manages persistent hot data.\n *\n * NOTE: mode = \"replace\" will not remove modules from devModuleCache.\n * This must be done in a separate step afterwards.\n */\nfunction disposeModule(moduleId: ModuleId, mode: 'clear' | 'replace') {\n const module = devModuleCache[moduleId]\n if (!module) {\n return\n }\n\n const hotState = moduleHotState.get(module)\n if (!hotState) {\n return\n }\n\n const data: HotData = {}\n\n // Run the `hot.dispose` handler, if any, passing in the persistent\n // `hot.data` object.\n for (const disposeHandler of hotState.disposeHandlers) {\n disposeHandler(data)\n }\n\n // This used to warn in `getOrInstantiateModuleFromParent` when a disposed\n // module is still importing other modules.\n if (module.hot) {\n module.hot.active = false\n }\n\n moduleHotState.delete(module)\n\n // Remove the disposed module from its children's parent list.\n // It will be added back once the module re-instantiates and imports its\n // children again.\n for (const childId of module.children) {\n const child = devModuleCache[childId]\n if (!child) {\n continue\n }\n\n const idx = child.parents.indexOf(module.id)\n if (idx >= 0) {\n child.parents.splice(idx, 1)\n }\n }\n\n switch (mode) {\n case 'clear':\n delete devModuleCache[module.id]\n moduleHotData.delete(module.id)\n break\n case 'replace':\n moduleHotData.set(module.id, data)\n break\n default:\n invariant(mode, (mode) => `invalid mode: ${mode}`)\n }\n}\n\n/**\n * Dispose phase: runs dispose handlers and cleans up outdated/disposed modules.\n * Returns the parent modules of outdated modules for use in the apply phase.\n */\n\nfunction disposePhase(\n outdatedModules: Iterable,\n disposedModules: Iterable,\n outdatedDependencies: Map>\n): { outdatedModuleParents: Map> } {\n for (const moduleId of outdatedModules) {\n disposeModule(moduleId, 'replace')\n }\n\n for (const moduleId of disposedModules) {\n disposeModule(moduleId, 'clear')\n }\n\n // Removing modules from the module cache is a separate step.\n // We also want to keep track of previous parents of the outdated modules.\n const outdatedModuleParents = new Map>()\n for (const moduleId of outdatedModules) {\n const oldModule = devModuleCache[moduleId]\n outdatedModuleParents.set(moduleId, oldModule?.parents)\n delete devModuleCache[moduleId]\n }\n\n // Remove outdated dependencies from parent module's children list.\n // When a parent accepts a child's update, the child is re-instantiated\n // but the parent stays alive. We remove the old child reference so it\n // gets re-added when the child re-imports.\n for (const [parentId, deps] of outdatedDependencies) {\n const module = devModuleCache[parentId]\n if (module) {\n for (const dep of deps) {\n const idx = module.children.indexOf(dep)\n if (idx >= 0) {\n module.children.splice(idx, 1)\n }\n }\n }\n }\n\n return { outdatedModuleParents }\n}\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/**\n * Shared module instantiation logic.\n * This handles the full module instantiation flow for both browser and Node.js.\n * Only React Refresh hooks differ between platforms (passed as callback).\n */\nfunction instantiateModuleShared(\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n runtimeModules: Set,\n createModuleObjectFn: (id: ModuleId) => HotModule,\n createContextFn: (module: HotModule, exports: Exports, refresh?: any) => any,\n runModuleExecutionHooksFn: (\n module: HotModule,\n exec: (refresh: any) => void\n ) => void\n): HotModule {\n // 1. Factory validation (same in both browser and Node.js)\n const id = moduleId\n const moduleFactory = moduleFactories.get(id)\n if (typeof moduleFactory !== 'function') {\n throw new Error(\n factoryNotAvailableMessage(moduleId, sourceType, sourceData) +\n `\\nThis is often caused by a stale browser cache, misconfigured Cache-Control headers, or a service worker serving outdated responses.` +\n `\\nTo fix this, make sure your Cache-Control headers allow revalidation of chunks and review your service worker configuration. ` +\n `As an immediate workaround, try hard-reloading the page, clearing the browser cache, or unregistering any service workers.`\n )\n }\n\n // 2. Hot API setup (same in both - works for browser, included for Node.js)\n const hotData = moduleHotData.get(id)!\n const { hot, hotState } = createModuleHot(id, hotData)\n\n // 3. Parent assignment logic (same in both)\n let parents: ModuleId[]\n switch (sourceType) {\n case SourceType.Runtime:\n runtimeModules.add(id)\n parents = []\n break\n case SourceType.Parent:\n parents = [sourceData as ModuleId]\n break\n case SourceType.Update:\n parents = (sourceData as ModuleId[]) || []\n break\n default:\n throw new Error(`Unknown source type: ${sourceType}`)\n }\n\n // 4. Module creation (platform creates base module object)\n const module = createModuleObjectFn(id)\n const exports = module.exports\n module.parents = parents\n module.children = []\n module.hot = hot\n\n devModuleCache[id] = module\n moduleHotState.set(module, hotState)\n\n // 5. Module execution (React Refresh hooks are platform-specific)\n try {\n runModuleExecutionHooksFn(module, (refresh) => {\n const context = createContextFn(module, exports, refresh)\n moduleFactory.call(exports, context, module, exports)\n })\n } catch (error) {\n module.error = error as any\n throw error\n }\n\n // 6. ESM interop (same in both)\n if (module.namespaceObject && module.exports !== module.namespaceObject) {\n // in case of a circular dependency: cjs1 -> esm2 -> cjs1\n interopEsm(module.exports, module.namespaceObject)\n }\n\n return module\n}\n\n/**\n * Analyzes update entries and chunks to determine which modules were added, modified, or deleted.\n * This is pure logic that doesn't depend on the runtime environment.\n */\nfunction computeChangedModules(\n entries: Record,\n updates: Record,\n chunkModulesMap?: Map>\n): {\n added: Map\n modified: Map\n deleted: Set\n chunksAdded: Map>\n chunksDeleted: Map>\n} {\n const chunksAdded = new Map()\n const chunksDeleted = new Map()\n const added: Map = new Map()\n const modified = new Map()\n const deleted: Set = new Set()\n\n for (const [chunkPath, mergedChunkUpdate] of Object.entries(updates) as Array<\n [ChunkPath, EcmascriptMergedChunkUpdate]\n >) {\n switch (mergedChunkUpdate.type) {\n case 'added': {\n const updateAdded = new Set(mergedChunkUpdate.modules)\n for (const moduleId of updateAdded) {\n added.set(moduleId, entries[moduleId])\n }\n chunksAdded.set(chunkPath, updateAdded)\n break\n }\n case 'deleted': {\n const updateDeleted = chunkModulesMap\n ? new Set(chunkModulesMap.get(chunkPath))\n : new Set()\n for (const moduleId of updateDeleted) {\n deleted.add(moduleId)\n }\n chunksDeleted.set(chunkPath, updateDeleted)\n break\n }\n case 'partial': {\n const updateAdded = new Set(mergedChunkUpdate.added)\n const updateDeleted = new Set(mergedChunkUpdate.deleted)\n for (const moduleId of updateAdded) {\n added.set(moduleId, entries[moduleId])\n }\n for (const moduleId of updateDeleted) {\n deleted.add(moduleId)\n }\n chunksAdded.set(chunkPath, updateAdded)\n chunksDeleted.set(chunkPath, updateDeleted)\n break\n }\n default:\n throw new Error('Unknown merged chunk update type')\n }\n }\n\n // If a module was added from one chunk and deleted from another in the same update,\n // consider it to be modified, as it means the module was moved from one chunk to another\n // AND has new code in a single update.\n for (const moduleId of added.keys()) {\n if (deleted.has(moduleId)) {\n added.delete(moduleId)\n deleted.delete(moduleId)\n }\n }\n\n for (const [moduleId, entry] of Object.entries(entries)) {\n // Modules that haven't been added to any chunk but have new code are considered\n // to be modified.\n // This needs to be under the previous loop, as we need it to get rid of modules\n // that were added and deleted in the same update.\n if (!added.has(moduleId)) {\n modified.set(moduleId, entry)\n }\n }\n\n return { added, deleted, modified, chunksAdded, chunksDeleted }\n}\n\n/**\n * Compiles new module code and walks the dependency tree to find all outdated modules.\n * Uses the evalModuleEntry function to compile code (platform-specific).\n *\n * @param added - Map of added modules\n * @param modified - Map of modified modules\n * @param evalModuleEntry - Function to compile module code\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction computeOutdatedModules(\n added: Map,\n modified: Map,\n evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction,\n autoAcceptRootModules: boolean\n): {\n outdatedModules: Set\n outdatedDependencies: Map>\n newModuleFactories: Map\n} {\n const newModuleFactories = new Map()\n\n // Compile added modules\n for (const [moduleId, entry] of added) {\n if (entry != null) {\n newModuleFactories.set(moduleId, evalModuleEntry(entry))\n }\n }\n\n // Walk dependency tree to find all modules affected by modifications\n const { outdatedModules, outdatedDependencies } = computedInvalidatedModules(\n modified.keys(),\n autoAcceptRootModules\n )\n\n // Compile modified modules\n for (const [moduleId, entry] of modified) {\n newModuleFactories.set(moduleId, evalModuleEntry(entry))\n }\n\n return { outdatedModules, outdatedDependencies, newModuleFactories }\n}\n\n/**\n * Updates module factories and re-instantiates self-accepted modules.\n * Uses the instantiateModule function (platform-specific via callback).\n */\nfunction applyPhase(\n outdatedSelfAcceptedModules: {\n moduleId: ModuleId\n errorHandler: true | Function\n }[],\n newModuleFactories: Map,\n outdatedModuleParents: Map>,\n outdatedDependencies: Map>,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n instantiateModuleFn: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule,\n applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void,\n reportError: (err: any) => void\n) {\n // Update module factories\n for (const [moduleId, factory] of newModuleFactories.entries()) {\n applyModuleFactoryNameFn(factory)\n moduleFactories.set(moduleId, factory)\n }\n\n // TODO(alexkirsz) Run new runtime entries here.\n\n // Call accept handlers for outdated dependencies.\n // This runs BEFORE re-instantiating self-accepted modules, matching\n // webpack's behavior.\n for (const [parentId, deps] of outdatedDependencies) {\n const module = devModuleCache[parentId]\n if (!module) continue\n\n const hotState = moduleHotState.get(module)\n if (!hotState) continue\n\n // Group deps by callback, deduplicating callbacks that handle multiple deps.\n // Each callback receives only the deps it was registered for.\n const callbackDeps = new Map void), ModuleId[]>()\n const callbackErrorHandlers = new Map<\n AcceptCallback | (() => void),\n AcceptErrorHandler | undefined\n >()\n\n for (const dep of deps) {\n const acceptCallback = hotState.acceptedDependencies[dep]\n if (acceptCallback) {\n let depList = callbackDeps.get(acceptCallback)\n if (!depList) {\n depList = []\n callbackDeps.set(acceptCallback, depList)\n callbackErrorHandlers.set(\n acceptCallback,\n hotState.acceptedErrorHandlers[dep]\n )\n }\n depList.push(dep)\n }\n }\n\n for (const [callback, cbDeps] of callbackDeps) {\n try {\n callback.call(null, cbDeps)\n } catch (err: any) {\n const errorHandler = callbackErrorHandlers.get(callback)\n if (typeof errorHandler === 'function') {\n try {\n errorHandler(err, {\n moduleId: parentId,\n dependencyId: cbDeps[0],\n })\n } catch (err2) {\n reportError(err2)\n reportError(err)\n }\n } else {\n reportError(err)\n }\n }\n }\n }\n\n // Re-instantiate all outdated self-accepted modules\n for (const { moduleId, errorHandler } of outdatedSelfAcceptedModules) {\n try {\n instantiateModuleFn(\n moduleId,\n SourceType.Update,\n outdatedModuleParents.get(moduleId)\n )\n } catch (err) {\n if (typeof errorHandler === 'function') {\n try {\n errorHandler(err, { moduleId, module: devModuleCache[moduleId] })\n } catch (err2) {\n reportError(err2)\n reportError(err)\n }\n } else {\n reportError(err)\n }\n }\n }\n}\n\n/**\n * Internal implementation that orchestrates the full HMR update flow:\n * invalidation, disposal, and application of new modules.\n *\n * @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction applyInternal(\n outdatedModules: Set,\n outdatedDependencies: Map>,\n disposedModules: Iterable,\n newModuleFactories: Map,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache,\n instantiateModuleFn: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule,\n applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void,\n autoAcceptRootModules: boolean\n) {\n ;({ outdatedModules, outdatedDependencies } = applyInvalidatedModules(\n outdatedModules,\n outdatedDependencies,\n autoAcceptRootModules\n ))\n\n // Find self-accepted modules to re-instantiate\n const outdatedSelfAcceptedModules =\n computeOutdatedSelfAcceptedModules(outdatedModules)\n\n // Run dispose handlers, save hot.data, clear caches\n const { outdatedModuleParents } = disposePhase(\n outdatedModules,\n disposedModules,\n outdatedDependencies\n )\n\n let error: any\n\n function reportError(err: any) {\n if (!error) error = err // Keep first error\n }\n\n applyPhase(\n outdatedSelfAcceptedModules,\n newModuleFactories,\n outdatedModuleParents,\n outdatedDependencies,\n moduleFactories,\n devModuleCache,\n instantiateModuleFn,\n applyModuleFactoryNameFn,\n reportError\n )\n\n if (error) {\n throw error\n }\n\n // Recursively apply any queued invalidations from new module execution\n if (queuedInvalidatedModules.size > 0) {\n applyInternal(\n new Set(),\n new Map(),\n [],\n new Map(),\n moduleFactories,\n devModuleCache,\n instantiateModuleFn,\n applyModuleFactoryNameFn,\n autoAcceptRootModules\n )\n }\n}\n\n/**\n * Main entry point for applying an ECMAScript merged update.\n * This is called by both browser and Node.js runtimes with platform-specific callbacks.\n *\n * @param options.autoAcceptRootModules - If true, root modules auto-accept updates without explicit\n * module.hot.accept(). Used for server-side HMR where pages\n * auto-accept at the top level.\n */\nfunction applyEcmascriptMergedUpdateShared(options: {\n added: Map\n modified: Map\n disposedModules: Iterable\n evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction\n instantiateModule: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule\n applyModuleFactoryName: (factory: HotModuleFactoryFunction) => void\n moduleFactories: ModuleFactories\n devModuleCache: ModuleCache\n autoAcceptRootModules: boolean\n}) {\n const {\n added,\n modified,\n disposedModules,\n evalModuleEntry,\n instantiateModule,\n applyModuleFactoryName,\n moduleFactories,\n devModuleCache,\n autoAcceptRootModules,\n } = options\n\n const { outdatedModules, outdatedDependencies, newModuleFactories } =\n computeOutdatedModules(\n added,\n modified,\n evalModuleEntry,\n autoAcceptRootModules\n )\n\n applyInternal(\n outdatedModules,\n outdatedDependencies,\n disposedModules,\n newModuleFactories,\n moduleFactories,\n devModuleCache,\n instantiateModule,\n applyModuleFactoryName,\n autoAcceptRootModules\n )\n}\n"],"names":["devModuleCache","runtimeModules","moduleHotData","Map","moduleHotState","WeakMap","queuedInvalidatedModules","Set","UpdateApplyError","Error","name","dependencyChain","message","trackModuleImport","parentModule","childModuleId","childModule","children","indexOf","push","parents","id","formatDependencyChain","join","getAffectedModuleEffects","moduleId","autoAcceptRootModules","outdatedModules","outdatedDependencies","queue","nextItem","shift","has","add","undefined","type","module","hotState","get","selfAccepted","selfInvalidated","selfDeclined","parentId","parent","parentHotState","declinedDependencies","acceptedDependencies","set","length","mergeDependencies","target","source","deps","existing","dep","computedInvalidatedModules","invalidated","effect","outdatedModuleId","invariant","createModuleHot","hotData","disposeHandlers","acceptedErrorHandlers","hot","active","data","accept","modules","callback","errorHandler","i","decline","dispose","addDisposeHandler","removeDisposeHandler","idx","splice","invalidate","status","addStatusHandler","_handler","removeStatusHandler","check","Promise","resolve","applyInvalidatedModules","size","result","clear","computeOutdatedSelfAcceptedModules","outdatedSelfAcceptedModules","disposeModule","mode","disposeHandler","delete","childId","child","disposePhase","disposedModules","outdatedModuleParents","oldModule","instantiateModuleShared","sourceType","sourceData","moduleFactories","createModuleObjectFn","createContextFn","runModuleExecutionHooksFn","moduleFactory","factoryNotAvailableMessage","SourceType","Runtime","Parent","Update","exports","refresh","context","call","error","namespaceObject","interopEsm","computeChangedModules","entries","updates","chunkModulesMap","chunksAdded","chunksDeleted","added","modified","deleted","chunkPath","mergedChunkUpdate","Object","updateAdded","updateDeleted","keys","entry","computeOutdatedModules","evalModuleEntry","newModuleFactories","applyPhase","instantiateModuleFn","applyModuleFactoryNameFn","reportError","factory","callbackDeps","callbackErrorHandlers","acceptCallback","depList","cbDeps","err","dependencyId","err2","applyInternal","applyEcmascriptMergedUpdateShared","options","instantiateModule","applyModuleFactoryName"],"mappings":"AAAA,2CAA2C;AAC3C,6CAA6C;AAC7C,4CAA4C;AAC5C,4CAA4C;AAO5C;;;;;;CAMC,GAED;;;;CAIC,GACD,IAAIA;AAEJ;;CAEC,GACD,IAAIC;AAEJ;;;CAGC,GACD,MAAMC,gBAAwC,IAAIC;AAElD;;;CAGC,GACD,MAAMC,iBAAyC,IAAIC;AAEnD;;CAEC,GACD,MAAMC,2BAA0C,IAAIC;AAEpD,MAAMC,yBAAyBC;IAC7BC,OAAO,mBAAkB;IAEzBC,gBAA2B;IAE3BH,YAAYI,OAAe,EAAED,eAA2B,CAAE;QACxD,KAAK,CAACC;QACN,IAAI,CAACD,eAAe,GAAGA;IACzB;AACF;AAyBA;;;CAGC,GACD,6DAA6D;AAC7D,SAASE,kBACPC,YAAiC,EACjCC,aAAuB,EACvBC,WAA4C;IAE5C,mCAAmC;IACnC,IAAIF,aAAaG,QAAQ,CAACC,OAAO,CAACH,mBAAmB,CAAC,GAAG;QACvDD,aAA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line": 1533, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/dev-base.ts"],"sourcesContent":["/// \n/// \n\ninterface TurbopackDevContext extends TurbopackBrowserBaseContext {\n k: RefreshContext\n}\n\nconst devContextPrototype = Context.prototype as TurbopackDevContext\n\n/**\n * This file contains runtime types and functions that are shared between all\n * Turbopack *development* ECMAScript runtimes.\n *\n * It will be appended to the runtime code of each runtime right after the\n * shared runtime utils.\n */\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n// Assign browser's module cache and runtime modules to shared HMR state\ndevModuleCache = Object.create(null)\ndevContextPrototype.c = devModuleCache\nruntimeModules = new Set()\n\n// Set flag to indicate we use ModuleWithDirection\ncreateModuleWithDirectionFlag = true\n\n// This file must not use `import` and `export` statements. Otherwise, it\n// becomes impossible to augment interfaces declared in ``d files\n// (e.g. `Module`). Hence, the need for `import()` here.\ntype RefreshRuntimeGlobals =\n import('@next/react-refresh-utils/dist/runtime').RefreshRuntimeGlobals\n\ndeclare var $RefreshHelpers$: RefreshRuntimeGlobals['$RefreshHelpers$']\ndeclare var $RefreshReg$: RefreshRuntimeGlobals['$RefreshReg$']\ndeclare var $RefreshSig$: RefreshRuntimeGlobals['$RefreshSig$']\ndeclare var $RefreshInterceptModuleExecution$: RefreshRuntimeGlobals['$RefreshInterceptModuleExecution$']\n\ntype RefreshContext = {\n register: RefreshRuntimeGlobals['$RefreshReg$']\n signature: RefreshRuntimeGlobals['$RefreshSig$']\n registerExports: typeof registerExportsAndSetupBoundaryForReactRefresh\n}\n\ntype RefreshHelpers = RefreshRuntimeGlobals['$RefreshHelpers$']\n\ntype ModuleFactory = (\n this: Module['exports'],\n context: TurbopackDevContext\n) => unknown\n\ninterface DevRuntimeBackend {\n reloadChunk?: (chunkUrl: ChunkUrl) => Promise\n unloadChunk?: (chunkUrl: ChunkUrl) => void\n restart: () => void\n}\n\n/**\n * Map from module ID to the chunks that contain this module.\n *\n * In HMR, we need to keep track of which modules are contained in which so\n * chunks. This is so we don't eagerly dispose of a module when it is removed\n * from chunk A, but still exists in chunk B.\n */\nconst moduleChunksMap: Map> = new Map()\n/**\n * Map from a chunk path to all modules it contains.\n */\nconst chunkModulesMap: Map> = new Map()\n/**\n * Chunk lists that contain a runtime. When these chunk lists receive an update\n * that can't be reconciled with the current state of the page, we need to\n * reload the runtime entirely.\n */\nconst runtimeChunkLists: Set = new Set()\n/**\n * Map from a chunk list to the chunk paths it contains.\n */\nconst chunkListChunksMap: Map> = new Map()\n/**\n * Map from a chunk path to the chunk lists it belongs to.\n */\nconst chunkChunkListsMap: Map> = new Map()\n\n/**\n * Gets or instantiates a runtime module.\n */\n// @ts-ignore\nfunction getOrInstantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): Module {\n const module = devModuleCache[moduleId]\n if (module) {\n if (module.error) {\n throw module.error\n }\n return module\n }\n\n // @ts-ignore\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it if it is not cached.\n */\n// @ts-ignore Defined in `runtime-utils.ts`\nconst getOrInstantiateModuleFromParent: GetOrInstantiateModuleFromParent<\n HotModule\n> = (id, sourceModule) => {\n if (!sourceModule.hot.active) {\n console.warn(\n `Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`\n )\n }\n\n const module = devModuleCache[id]\n\n if (sourceModule.children.indexOf(id) === -1) {\n sourceModule.children.push(id)\n }\n\n if (module) {\n if (module.error) {\n throw module.error\n }\n\n if (module.parents.indexOf(sourceModule.id) === -1) {\n module.parents.push(sourceModule.id)\n }\n\n return module\n }\n\n return instantiateModule(id, SourceType.Parent, sourceModule.id)\n}\n\nfunction DevContext(\n this: TurbopackDevContext,\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n) {\n Context.call(this, module, exports)\n this.k = refresh\n}\nDevContext.prototype = Context.prototype\n\ntype DevContextConstructor = {\n new (\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n ): TurbopackDevContext\n}\n\nfunction instantiateModule(\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): Module {\n // Browser: creates base HotModule object (hot API added by shared code)\n const createModuleObjectFn = (id: ModuleId) => {\n return createModuleObject(id) as HotModule\n }\n\n // Browser: creates DevContext with refresh\n const createContext = (\n module: HotModule,\n exports: Exports,\n refresh: RefreshContext\n ) => {\n return new (DevContext as any as DevContextConstructor)(\n module,\n exports,\n refresh\n )\n }\n\n // Use shared instantiation logic (includes hot API setup)\n return instantiateModuleShared(\n moduleId,\n sourceType,\n sourceData,\n moduleFactories,\n devModuleCache,\n runtimeModules,\n createModuleObjectFn,\n createContext,\n runModuleExecutionHooks\n )\n}\n\nconst DUMMY_REFRESH_CONTEXT = {\n register: (_type: unknown, _id: unknown) => {},\n signature: () => (_type: unknown) => {},\n registerExports: (_module: unknown, _helpers: unknown) => {},\n}\n\n/**\n * NOTE(alexkirsz) Webpack has a \"module execution\" interception hook that\n * Next.js' React Refresh runtime hooks into to add module context to the\n * refresh registry.\n */\nfunction runModuleExecutionHooks(\n module: HotModule,\n executeModule: (ctx: RefreshContext) => void\n) {\n if (typeof globalThis.$RefreshInterceptModuleExecution$ === 'function') {\n const cleanupReactRefreshIntercept =\n globalThis.$RefreshInterceptModuleExecution$(module.id)\n try {\n executeModule({\n register: globalThis.$RefreshReg$,\n signature: globalThis.$RefreshSig$,\n registerExports: registerExportsAndSetupBoundaryForReactRefresh,\n })\n } finally {\n // Always cleanup the intercept, even if module execution failed.\n cleanupReactRefreshIntercept()\n }\n } else {\n // If the react refresh hooks are not installed we need to bind dummy functions.\n // This is expected when running in a Web Worker. It is also common in some of\n // our test environments.\n executeModule(DUMMY_REFRESH_CONTEXT)\n }\n}\n\n/**\n * This is adapted from https://github.com/vercel/next.js/blob/3466862d9dc9c8bb3131712134d38757b918d1c0/packages/react-refresh-utils/internal/ReactRefreshModule.runtime.ts\n */\nfunction registerExportsAndSetupBoundaryForReactRefresh(\n module: HotModule,\n helpers: RefreshHelpers\n) {\n const currentExports = module.exports\n const prevExports = module.hot.data.prevExports ?? null\n\n helpers.registerExportsForReactRefresh(currentExports, module.id)\n\n // A module can be accepted automatically based on its exports, e.g. when\n // it is a Refresh Boundary.\n if (helpers.isReactRefreshBoundary(currentExports)) {\n // Save the previous exports on update, so we can compare the boundary\n // signatures.\n module.hot.dispose((data) => {\n data.prevExports = currentExports\n })\n // Unconditionally accept an update to this module, we'll check if it's\n // still a Refresh Boundary later.\n module.hot.accept()\n\n // This field is set when the previous version of this module was a\n // Refresh Boundary, letting us know we need to check for invalidation or\n // enqueue an update.\n if (prevExports !== null) {\n // A boundary can become ineligible if its exports are incompatible\n // with the previous exports.\n //\n // For example, if you add/remove/change exports, we'll want to\n // re-execute the importing modules, and force those components to\n // re-render. Similarly, if you convert a class component to a\n // function, we want to invalidate the boundary.\n if (\n helpers.shouldInvalidateReactRefreshBoundary(\n helpers.getRefreshBoundarySignature(prevExports),\n helpers.getRefreshBoundarySignature(currentExports)\n )\n ) {\n module.hot.invalidate()\n } else {\n helpers.scheduleUpdate()\n }\n }\n } else {\n // Since we just executed the code for the module, it's possible that the\n // new exports made it ineligible for being a boundary.\n // We only care about the case when we were _previously_ a boundary,\n // because we already accepted this update (accidental side effect).\n const isNoLongerABoundary = prevExports !== null\n if (isNoLongerABoundary) {\n module.hot.invalidate()\n }\n }\n}\n\n/**\n * Adds, deletes, and moves modules between chunks. This must happen before the\n * dispose phase as it needs to know which modules were removed from all chunks,\n * which we can only compute *after* taking care of added and moved modules.\n */\nfunction updateChunksPhase(\n chunksAddedModules: Map>,\n chunksDeletedModules: Map>\n): { disposedModules: Set } {\n for (const [chunkPath, addedModuleIds] of chunksAddedModules) {\n for (const moduleId of addedModuleIds) {\n addModuleToChunk(moduleId, chunkPath)\n }\n }\n\n const disposedModules: Set = new Set()\n for (const [chunkPath, addedModuleIds] of chunksDeletedModules) {\n for (const moduleId of addedModuleIds) {\n if (removeModuleFromChunk(moduleId, chunkPath)) {\n disposedModules.add(moduleId)\n }\n }\n }\n\n return { disposedModules }\n}\n\nfunction applyUpdate(update: PartialUpdate) {\n switch (update.type) {\n case 'ChunkListUpdate':\n applyChunkListUpdate(update)\n break\n default:\n invariant(update, (update) => `Unknown update type: ${update.type}`)\n }\n}\n\nfunction applyChunkListUpdate(update: ChunkListUpdate) {\n if (update.merged != null) {\n for (const merged of update.merged) {\n switch (merged.type) {\n case 'EcmascriptMergedUpdate':\n applyEcmascriptMergedUpdate(merged)\n break\n default:\n invariant(merged, (merged) => `Unknown merged type: ${merged.type}`)\n }\n }\n }\n\n if (update.chunks != null) {\n for (const [chunkPath, chunkUpdate] of Object.entries(\n update.chunks\n ) as Array<[ChunkPath, ChunkUpdate]>) {\n const chunkUrl = getChunkRelativeUrl(chunkPath)\n\n switch (chunkUpdate.type) {\n case 'added':\n BACKEND.loadChunkCached(SourceType.Update, chunkUrl)\n break\n case 'total':\n DEV_BACKEND.reloadChunk?.(chunkUrl)\n break\n case 'deleted':\n DEV_BACKEND.unloadChunk?.(chunkUrl)\n break\n case 'partial':\n invariant(\n chunkUpdate.instruction,\n (instruction) =>\n `Unknown partial instruction: ${JSON.stringify(instruction)}.`\n )\n break\n default:\n invariant(\n chunkUpdate,\n (chunkUpdate) => `Unknown chunk update type: ${chunkUpdate.type}`\n )\n }\n }\n }\n}\n\nfunction applyEcmascriptMergedUpdate(update: EcmascriptMergedUpdate) {\n // Browser-specific chunk management phase\n const { entries = {}, chunks = {} } = update\n const { added, modified, chunksAdded, chunksDeleted } = computeChangedModules(\n entries,\n chunks,\n chunkModulesMap\n )\n const { disposedModules } = updateChunksPhase(chunksAdded, chunksDeleted)\n\n // Use shared HMR update implementation\n applyEcmascriptMergedUpdateShared({\n added,\n modified,\n disposedModules,\n evalModuleEntry: _eval, // browser's eval with source maps\n instantiateModule, // now wraps shared logic\n applyModuleFactoryName,\n moduleFactories,\n devModuleCache,\n autoAcceptRootModules: false,\n })\n}\n\nfunction handleApply(chunkListPath: ChunkListPath, update: ServerMessage) {\n switch (update.type) {\n case 'partial': {\n // This indicates that the update is can be applied to the current state of the application.\n applyUpdate(update.instruction)\n break\n }\n case 'restart': {\n // This indicates that there is no way to apply the update to the\n // current state of the application, and that the application must be\n // restarted.\n DEV_BACKEND.restart()\n break\n }\n case 'notFound': {\n // This indicates that the chunk list no longer exists: either the dynamic import which created it was removed,\n // or the page itself was deleted.\n // If it is a dynamic import, we simply discard all modules that the chunk has exclusive access to.\n // If it is a runtime chunk list, we restart the application.\n if (runtimeChunkLists.has(chunkListPath)) {\n DEV_BACKEND.restart()\n } else {\n disposeChunkList(chunkListPath)\n }\n break\n }\n default:\n throw new Error(`Unknown update type: ${update.type}`)\n }\n}\n\n/**\n * Removes a module from a chunk.\n * Returns `true` if there are no remaining chunks including this module.\n */\nfunction removeModuleFromChunk(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): boolean {\n const moduleChunks = moduleChunksMap.get(moduleId)!\n moduleChunks.delete(chunkPath)\n\n const chunkModules = chunkModulesMap.get(chunkPath)!\n chunkModules.delete(moduleId)\n\n const noRemainingModules = chunkModules.size === 0\n if (noRemainingModules) {\n chunkModulesMap.delete(chunkPath)\n }\n\n const noRemainingChunks = moduleChunks.size === 0\n if (noRemainingChunks) {\n moduleChunksMap.delete(moduleId)\n }\n\n return noRemainingChunks\n}\n\n/**\n * Disposes of a chunk list and its corresponding exclusive chunks.\n */\nfunction disposeChunkList(chunkListPath: ChunkListPath): boolean {\n const chunkPaths = chunkListChunksMap.get(chunkListPath)\n if (chunkPaths == null) {\n return false\n }\n chunkListChunksMap.delete(chunkListPath)\n\n for (const chunkPath of chunkPaths) {\n const chunkChunkLists = chunkChunkListsMap.get(chunkPath)!\n chunkChunkLists.delete(chunkListPath)\n\n if (chunkChunkLists.size === 0) {\n chunkChunkListsMap.delete(chunkPath)\n disposeChunk(chunkPath)\n }\n }\n\n // We must also dispose of the chunk list's chunk itself to ensure it may\n // be reloaded properly in the future.\n const chunkListUrl = getChunkRelativeUrl(chunkListPath)\n\n DEV_BACKEND.unloadChunk?.(chunkListUrl)\n\n return true\n}\n\n/**\n * Disposes of a chunk and its corresponding exclusive modules.\n *\n * @returns Whether the chunk was disposed of.\n */\nfunction disposeChunk(chunkPath: ChunkPath): boolean {\n const chunkUrl = getChunkRelativeUrl(chunkPath)\n // This should happen whether the chunk has any modules in it or not.\n // For instance, CSS chunks have no modules in them, but they still need to be unloaded.\n DEV_BACKEND.unloadChunk?.(chunkUrl)\n\n const chunkModules = chunkModulesMap.get(chunkPath)\n if (chunkModules == null) {\n return false\n }\n chunkModules.delete(chunkPath)\n\n for (const moduleId of chunkModules) {\n const moduleChunks = moduleChunksMap.get(moduleId)!\n moduleChunks.delete(chunkPath)\n\n const noRemainingChunks = moduleChunks.size === 0\n if (noRemainingChunks) {\n moduleChunksMap.delete(moduleId)\n disposeModule(moduleId, 'clear')\n availableModules.delete(moduleId)\n }\n }\n\n return true\n}\n\n/**\n * Adds a module to a chunk.\n */\nfunction addModuleToChunk(moduleId: ModuleId, chunkPath: ChunkPath) {\n let moduleChunks = moduleChunksMap.get(moduleId)\n if (!moduleChunks) {\n moduleChunks = new Set([chunkPath])\n moduleChunksMap.set(moduleId, moduleChunks)\n } else {\n moduleChunks.add(chunkPath)\n }\n\n let chunkModules = chunkModulesMap.get(chunkPath)\n if (!chunkModules) {\n chunkModules = new Set([moduleId])\n chunkModulesMap.set(chunkPath, chunkModules)\n } else {\n chunkModules.add(moduleId)\n }\n}\n\n/**\n * Marks a chunk list as a runtime chunk list. There can be more than one\n * runtime chunk list. For instance, integration tests can have multiple chunk\n * groups loaded at runtime, each with its own chunk list.\n */\nfunction markChunkListAsRuntime(chunkListPath: ChunkListPath) {\n runtimeChunkLists.add(chunkListPath)\n}\n\nfunction registerChunk(registration: ChunkRegistration) {\n const chunk = getChunkFromRegistration(registration[0]) as\n | ChunkPath\n | ChunkScript\n let runtimeParams: RuntimeParams | undefined\n // When bootstrapping we are passed a single runtimeParams object so we can distinguish purely based on length\n if (registration.length === 2) {\n runtimeParams = registration[1] as RuntimeParams\n } else {\n let chunkPath = getPathFromScript(chunk)\n runtimeParams = undefined\n installCompressedModuleFactories(\n registration as CompressedModuleFactories,\n /* offset= */ 1,\n moduleFactories,\n (id: ModuleId) => addModuleToChunk(id, chunkPath)\n )\n }\n return BACKEND.registerChunk(chunk, runtimeParams)\n}\n\n/**\n * Subscribes to chunk list updates from the update server and applies them.\n */\nfunction registerChunkList(chunkList: ChunkList) {\n const chunkListScript = getChunkFromRegistration(chunkList.script) as\n | ChunkListPath\n | ChunkListScript\n const chunkListPath = getPathFromScript(chunkListScript)\n // The \"chunk\" is also registered to finish the loading in the backend\n BACKEND.registerChunk(chunkListPath as string as ChunkPath)\n globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS!.push([\n chunkListPath,\n handleApply.bind(null, chunkListPath),\n ])\n\n // Adding chunks to chunk lists and vice versa.\n const chunkPaths = new Set(chunkList.chunks.map(getChunkPath))\n chunkListChunksMap.set(chunkListPath, chunkPaths)\n for (const chunkPath of chunkPaths) {\n let chunkChunkLists = chunkChunkListsMap.get(chunkPath)\n if (!chunkChunkLists) {\n chunkChunkLists = new Set([chunkListPath])\n chunkChunkListsMap.set(chunkPath, chunkChunkLists)\n } else {\n chunkChunkLists.add(chunkListPath)\n }\n }\n\n if (chunkList.source === 'entry') {\n markChunkListAsRuntime(chunkListPath)\n }\n}\n\nglobalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= []\n"],"names":["devContextPrototype","Context","prototype","devModuleCache","Object","create","c","runtimeModules","Set","createModuleWithDirectionFlag","moduleChunksMap","Map","chunkModulesMap","runtimeChunkLists","chunkListChunksMap","chunkChunkListsMap","getOrInstantiateRuntimeModule","chunkPath","moduleId","module","error","instantiateModule","SourceType","Runtime","getOrInstantiateModuleFromParent","id","sourceModule","hot","active","console","warn","children","indexOf","push","parents","Parent","DevContext","exports","refresh","call","k","sourceType","sourceData","createModuleObjectFn","createModuleObject","createContext","instantiateModuleShared","moduleFactories","runModuleExecutionHooks","DUMMY_REFRESH_CONTEXT","register","_type","_id","signature","registerExports","_module","_helpers","executeModule","globalThis","$RefreshInterceptModuleExecution$","cleanupReactRefreshIntercept","$RefreshReg$","$RefreshSig$","registerExportsAndSetupBoundaryForReactRefresh","helpers","currentExports","prevExports","data","registerExportsForReactRefresh","isReactRefreshBoundary","dispose","accept","shouldInvalidateReactRefreshBoundary","getRefreshBoundarySignature","invalidate","scheduleUpdate","isNoLongerABoundary","updateChunksPhase","chunksAddedModules","chunksDeletedModules","addedModuleIds","addModuleToChunk","disposedModules","removeModuleFromChunk","add","applyUpdate","update","type","applyChunkListUpdate","invariant","merged","applyEcmascriptMergedUpdate","chunks","chunkUpdate","entries","chunkUrl","getChunkRelativeUrl","BACKEND","loadChunkCached","Update","DEV_BACKEND","reloadChunk","unloadChunk","instruction","JSON","stringify","added","modified","chunksAdded","chunksDeleted","computeChangedModules","applyEcmascriptMergedUpdateShared","evalModuleEntry","_eval","applyModuleFactoryName","autoAcceptRootModules","handleApply","chunkListPath","restart","has","disposeChunkList","Error","moduleChunks","get","delete","chunkModules","noRemainingModules","size","noRemainingChunks","chunkPaths","chunkChunkLists","disposeChunk","chunkListUrl","disposeModule","availableModules","set","markChunkListAsRuntime","registerChunk","registration","chunk","getChunkFromRegistration","runtimeParams","length","getPathFromScript","undefined","installCompressedModuleFactories","registerChunkList","chunkList","chunkListScript","script","TURBOPACK_CHUNK_UPDATE_LISTENERS","bind","map","getChunkPath","source"],"mappings":"AAAA,iEAAiE;AACjE,kEAAkE;AAMlE,MAAMA,sBAAsBC,QAAQC,SAAS;AAE7C;;;;;;CAMC,GACD,oDAAoD,GAEpD,wEAAwE;AACxEC,iBAAiBC,OAAOC,MAAM,CAAC;AAC/BL,oBAAoBM,CAAC,GAAGH;AACxBI,iBAAiB,IAAIC;AAErB,kDAAkD;AAClDC,gCAAgC;AAgChC;;;;;;CAMC,GACD,MAAMC,kBAAiD,IAAIC;AAC3D;;CAE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;IACzB;AACF;AAEA3D,WAAW4F,gCAAgC,KAAK,EAAE","ignoreList":[0]}}, - {"offset": {"line": 1950, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/runtime-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack ECMAScript DOM runtime.\n *\n * It will be appended to the base runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\nfunction getAssetSuffixFromScriptSrc() {\n // TURBOPACK_ASSET_SUFFIX is set in web workers\n return (\n (self.TURBOPACK_ASSET_SUFFIX ??\n document?.currentScript\n ?.getAttribute?.('src')\n ?.replace(/^(.*(?=\\?)|^.*$)/, '')) ||\n ''\n )\n}\n\ntype ChunkResolver = {\n resolved: boolean\n loadingStarted: boolean\n resolve: () => void\n reject: (error?: Error) => void\n promise: Promise\n}\n\nlet BACKEND: RuntimeBackend\n\n/**\n * Maps chunk paths to the corresponding resolver.\n */\nconst chunkResolvers: Map = new Map()\n\n;(() => {\n BACKEND = {\n async registerChunk(chunk, params) {\n let chunkPath = getPathFromScript(chunk)\n let chunkUrl = getUrlFromScript(chunk)\n\n const resolver = getOrCreateResolver(chunkUrl)\n resolver.resolve()\n\n if (params == null) {\n return\n }\n\n for (const otherChunkData of params.otherChunks) {\n const otherChunkPath = getChunkPath(otherChunkData)\n const otherChunkUrl = getChunkRelativeUrl(otherChunkPath)\n\n // Chunk might have started loading, so we want to avoid triggering another load.\n getOrCreateResolver(otherChunkUrl)\n }\n\n // This waits for chunks to be loaded, but also marks included items as available.\n await Promise.all(\n params.otherChunks.map((otherChunkData) =>\n loadInitialChunk(chunkPath, otherChunkData)\n )\n )\n\n if (params.runtimeModuleIds.length > 0) {\n for (const moduleId of params.runtimeModuleIds) {\n getOrInstantiateRuntimeModule(chunkPath, moduleId)\n }\n }\n },\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n loadChunkCached(sourceType: SourceType, chunkUrl: ChunkUrl) {\n return doLoadChunk(sourceType, chunkUrl)\n },\n\n async loadWebAssembly(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n const { instance } = await WebAssembly.instantiateStreaming(\n req,\n importsObj\n )\n\n return instance.exports\n },\n\n async loadWebAssemblyModule(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n return await WebAssembly.compileStreaming(req)\n },\n }\n\n function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {\n let resolver = chunkResolvers.get(chunkUrl)\n if (!resolver) {\n let resolve: () => void\n let reject: (error?: Error) => void\n const promise = new Promise((innerResolve, innerReject) => {\n resolve = innerResolve\n reject = innerReject\n })\n resolver = {\n resolved: false,\n loadingStarted: false,\n promise,\n resolve: () => {\n resolver!.resolved = true\n resolve()\n },\n reject: reject!,\n }\n chunkResolvers.set(chunkUrl, resolver)\n }\n return resolver\n }\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n function doLoadChunk(sourceType: SourceType, chunkUrl: ChunkUrl) {\n const resolver = getOrCreateResolver(chunkUrl)\n if (resolver.loadingStarted) {\n return resolver.promise\n }\n\n if (sourceType === SourceType.Runtime) {\n // We don't need to load chunks references from runtime code, as they're already\n // present in the DOM.\n resolver.loadingStarted = true\n\n if (isCss(chunkUrl)) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n\n // We need to wait for JS chunks to register themselves within `registerChunk`\n // before we can start instantiating runtime modules, hence the absence of\n // `resolver.resolve()` in this branch.\n\n return resolver.promise\n }\n\n if (typeof importScripts === 'function') {\n // We're in a web worker\n if (isCss(chunkUrl)) {\n // ignore\n } else if (isJs(chunkUrl)) {\n self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl)\n importScripts(chunkUrl)\n } else {\n throw new Error(\n `can't infer type of chunk from URL ${chunkUrl} in worker`\n )\n }\n } else {\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n if (previousLinks.length > 0) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n } else {\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n link.href = chunkUrl\n link.onerror = () => {\n resolver.reject()\n }\n link.onload = () => {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(link)\n }\n } else if (isJs(chunkUrl)) {\n const previousScripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n if (previousScripts.length > 0) {\n // There is this edge where the script already failed loading, but we\n // can't detect that. The Promise will never resolve in this case.\n for (const script of Array.from(previousScripts)) {\n script.addEventListener('error', () => {\n resolver.reject()\n })\n }\n } else {\n const script = document.createElement('script')\n script.src = chunkUrl\n // We'll only mark the chunk as loaded once the script has been executed,\n // which happens in `registerChunk`. Hence the absence of `resolve()` in\n // this branch.\n script.onerror = () => {\n resolver.reject()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(script)\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n }\n\n resolver.loadingStarted = true\n return resolver.promise\n }\n\n function fetchWebAssembly(wasmChunkPath: ChunkPath) {\n return fetch(getChunkRelativeUrl(wasmChunkPath))\n }\n})()\n"],"names":["getAssetSuffixFromScriptSrc","self","TURBOPACK_ASSET_SUFFIX","document","currentScript","getAttribute","replace","BACKEND","chunkResolvers","Map","registerChunk","chunk","params","chunkPath","getPathFromScript","chunkUrl","getUrlFromScript","resolver","getOrCreateResolver","resolve","otherChunkData","otherChunks","otherChunkPath","getChunkPath","otherChunkUrl","getChunkRelativeUrl","Promise","all","map","loadInitialChunk","runtimeModuleIds","length","moduleId","getOrInstantiateRuntimeModule","loadChunkCached","sourceType","doLoadChunk","loadWebAssembly","_sourceType","_sourceData","wasmChunkPath","_edgeModule","importsObj","req","fetchWebAssembly","instance","WebAssembly","instantiateStreaming","exports","loadWebAssemblyModule","compileStreaming","get","reject","promise","innerResolve","innerReject","resolved","loadingStarted","set","SourceType","Runtime","isCss","importScripts","isJs","TURBOPACK_NEXT_CHUNK_URLS","push","Error","decodedChunkUrl","decodeURI","previousLinks","querySelectorAll","link","createElement","rel","href","onerror","onload","head","appendChild","previousScripts","script","Array","from","addEventListener","src","fetch"],"mappings":"AAAA;;;;CAIC,GAED,oDAAoD,GAEpD,sEAAsE;AACtE,mEAAmE;AAEnE,SAASA;IACP,+CAA+C;IAC/C,OACE,CAACC,KAAKC,sBAAsB,IAC1BC,UAAUC,eACNC,eAAe,QACfC,QAAQ,oBAAoB,GAAG,KACrC;AAEJ;AAUA,IAAIC;AAEJ;;CAEC,GACD,MAAMC,iBAA+C,IAAIC;AAExD,CAAC;IACAF,UAAU;QACR,MAAMG,eAAcC,KAAK,EAAEC,MAAM;YAC/B,IAAIC,YAAYC,kBAAkBH;YAClC,IAAII,WAAWC,iBAAiBL;YAEhC,MAAMM,WAAWC,oBAAoBH;YACrCE,SAASE,OAAO;YAEhB,IAAIP,UAAU,MAAM;gBAClB;YACF;YAEA,KAAK,MAAMQ,kBAAkBR,OAAOS,WAAW,CAAE;gBAC/C,MAAMC,iBAAiBC,aAAaH;gBACpC,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D,SAASE,OAAO;oBAClB;oBACA,kDAAkD;oBAClDhB,SAAS0E,IAAI,CAACC,WAAW,CAACP;gBAC5B;YACF,OAAO,IAAIR,KAAKhD,WAAW;gBACzB,MAAMgE,kBAAkB5E,SAASmE,gBAAgB,CAC/C,CAAC,YAAY,EAAEvD,SAAS,gBAAgB,EAAEA,SAAS,gBAAgB,EAAEoD,gBAAgB,gBAAgB,EAAEA,gBAAgB,GAAG,CAAC;gBAE7H,IAAIY,gBAAgBhD,MAAM,GAAG,GAAG;oBAC9B,qEAAqE;oBACrE,kEAAkE;oBAClE,KAAK,MAAMiD,UAAUC,MAAMC,IAAI,CAACH,iBAAkB;wBAChDC,OAAOG,gBAAgB,CAAC,SAAS;4BAC/BlE,SAASmC,MAAM;wBACjB;oBACF;gBACF,OAAO;oBACL,MAAM4B,SAAS7E,SAASqE,aAAa,CAAC;oBACtCQ,OAAOI,GAAG,GAAGrE;oBACb,yEAAyE;oBACzE,wEAAwE;oBACxE,eAAe;oBACfiE,OAAOL,OAAO,GAAG;wBACf1D,SAASmC,MAAM;oBACjB;oBACA,kDAAkD;oBAClDjD,SAAS0E,IAAI,CAACC,WAAW,CAACE;gBAC5B;YACF,OAAO;gBACL,MAAM,IAAId,MAAM,CAAC,mCAAmC,EAAEnD,UAAU;YAClE;QACF;QAEAE,SAASwC,cAAc,GAAG;QAC1B,OAAOxC,SAASoC,OAAO;IACzB;IAEA,SAAST,iBAAiBJ,aAAwB;QAChD,OAAO6C,MAAM5D,oBAAoBe;IACnC;AACF,CAAC","ignoreList":[0]}}, - {"offset": {"line": 2116, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/dev-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack development\n * ECMAScript DOM runtime.\n *\n * It will be appended to the base development runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n/// \n/// \n\nlet DEV_BACKEND: DevRuntimeBackend\n;(() => {\n DEV_BACKEND = {\n unloadChunk(chunkUrl) {\n deleteResolver(chunkUrl)\n\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const links = document.querySelectorAll(\n `link[href=\"${chunkUrl}\"],link[href^=\"${chunkUrl}?\"],link[href=\"${decodedChunkUrl}\"],link[href^=\"${decodedChunkUrl}?\"]`\n )\n for (const link of Array.from(links)) {\n link.remove()\n }\n } else if (isJs(chunkUrl)) {\n // Unloading a JS chunk would have no effect, as it lives in the JS\n // runtime once evaluated.\n // However, we still want to remove the script tag from the DOM to keep\n // the HTML somewhat consistent from the user's perspective.\n const scripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n for (const script of Array.from(scripts)) {\n script.remove()\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n },\n\n reloadChunk(chunkUrl) {\n return new Promise((resolve, reject) => {\n if (!isCss(chunkUrl)) {\n reject(new Error('The DOM backend can only reload CSS chunks'))\n return\n }\n\n const decodedChunkUrl = decodeURI(chunkUrl)\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n\n if (previousLinks.length === 0) {\n reject(new Error(`No link element found for chunk ${chunkUrl}`))\n return\n }\n\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n\n if (navigator.userAgent.includes('Firefox')) {\n // Firefox won't reload CSS files that were previously loaded on the current page,\n // we need to add a query param to make sure CSS is actually reloaded from the server.\n //\n // I believe this is this issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506\n //\n // Safari has a similar issue, but only if you have a `` tag\n // pointing to the same URL as the stylesheet: https://bugs.webkit.org/show_bug.cgi?id=187726\n link.href = `${chunkUrl}?ts=${Date.now()}`\n } else {\n link.href = chunkUrl\n }\n\n link.onerror = () => {\n reject()\n }\n link.onload = () => {\n // First load the new CSS, then remove the old ones. This prevents visible\n // flickering that would happen in-between removing the previous CSS and\n // loading the new one.\n for (const previousLink of Array.from(previousLinks))\n previousLink.remove()\n\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolve()\n }\n\n // Make sure to insert the new CSS right after the previous one, so that\n // its precedence is higher.\n previousLinks[0].parentElement!.insertBefore(\n link,\n previousLinks[0].nextSibling\n )\n })\n },\n\n restart: () => self.location.reload(),\n }\n\n function deleteResolver(chunkUrl: ChunkUrl) {\n chunkResolvers.delete(chunkUrl)\n }\n})()\n\nfunction _eval({ code, url, map }: EcmascriptModuleEntry): ModuleFactory {\n code += `\\n\\n//# sourceURL=${encodeURI(\n location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX\n )}`\n if (map) {\n code += `\\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(\n // btoa doesn't handle nonlatin characters, so escape them as \\x sequences\n // See https://stackoverflow.com/a/26603875\n unescape(encodeURIComponent(map))\n )}`\n }\n\n // eslint-disable-next-line no-eval\n return eval(code)\n}\n"],"names":["DEV_BACKEND","unloadChunk","chunkUrl","deleteResolver","decodedChunkUrl","decodeURI","isCss","links","document","querySelectorAll","link","Array","from","remove","isJs","scripts","script","Error","reloadChunk","Promise","resolve","reject","previousLinks","length","createElement","rel","navigator","userAgent","includes","href","Date","now","onerror","onload","previousLink","parentElement","insertBefore","nextSibling","restart","self","location","reload","chunkResolvers","delete","_eval","code","url","map","encodeURI","origin","CHUNK_BASE_PATH","ASSET_SUFFIX","btoa","unescape","encodeURIComponent","eval"],"mappings":"AAAA;;;;;CAKC,GAED,oDAAoD,GAEpD,gDAAgD;AAChD,4CAA4C;AAC5C,iDAAiD;AACjD,0DAA0D;AAE1D,IAAIA;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CAAC;gBACpCd,KAAKe,GAAG,GAAG;gBAEX,IAAIC,UAAUC,SAAS,CAACC,QAAQ,CAAC,YAAY;oBAC3C,kFAAkF;oBAClF,sFAAsF;oBACtF,EAAE;oBACF,qFAAqF;oBACrF,EAAE;oBACF,oFAAoF;oBACpF,6FAA6F;oBAC7FlB,KAAKmB,IAAI,GAAG,GAAG3B,SAAS,IAAI,EAAE4B,KAAKC,GAAG,IAAI;gBAC5C,OAAO;oBACLrB,KAAKmB,IAAI,GAAG3B;gBACd;gBAEAQ,KAAKsB,OAAO,GAAG;oBACbX;gBACF;gBACAX,KAAKuB,MAAM,GAAG;oBACZ,0EAA0E;oBAC1E,wEAAwE;oBACxE,uBAAuB;oBACvB,KAAK,MAAMC,gBAAgBvB,MAAMC,IAAI,CAACU,eACpCY,aAAarB,MAAM;oBAErB,uEAAuE;oBACvE,oBAAoB;oBACpBO;gBACF;gBAEA,wEAAwE;gBACxE,4BAA4B;gBAC5BE,aAAa,CAAC,EAAE,CAACa,aAAa,CAAEC,YAAY,CAC1C1B,MACAY,aAAa,CAAC,EAAE,CAACe,WAAW;YAEhC;QACF;QAEAC,SAAS,IAAMC,KAAKC,QAAQ,CAACC,MAAM;IACrC;IAEA,SAAStC,eAAeD,QAAkB;QACxCwC,eAAeC,MAAM,CAACzC;IACxB;AACF,CAAC;AAED,SAAS0C,MAAM,EAAEC,IAAI,EAAEC,GAAG,EAAEC,GAAG,EAAyB;IACtDF,QAAQ,CAAC,kBAAkB,EAAEG,UAC3BR,SAASS,MAAM,GAAGC,kBAAkBJ,MAAMK,eACzC;IACH,IAAIJ,KAAK;QACPF,QAAQ,CAAC,kEAAkE,EAAEO,KAC3E,0EAA0E;QAC1E,2CAA2C;QAC3CC,SAASC,mBAAmBP,QAC3B;IACL;IAEA,mCAAmC;IACnC,OAAOQ,KAAKV;AACd","ignoreList":[0]}}] + {"offset": {"line": 1950, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/runtime-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack ECMAScript DOM runtime.\n *\n * It will be appended to the base runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\nfunction getAssetSuffixFromScriptSrc() {\n // TURBOPACK_ASSET_SUFFIX is set in web workers\n if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX\n const src = document?.currentScript?.getAttribute?.('src') ?? ''\n const qi = src.indexOf('?')\n return qi >= 0 ? src.slice(qi) : ''\n}\n\ntype ChunkResolver = {\n resolved: boolean\n loadingStarted: boolean\n resolve: () => void\n reject: (error?: Error) => void\n promise: Promise\n}\n\nlet BACKEND: RuntimeBackend\n\n/**\n * Maps chunk paths to the corresponding resolver.\n */\nconst chunkResolvers: Map = new Map()\n\n;(() => {\n BACKEND = {\n async registerChunk(chunk, params) {\n let chunkPath = getPathFromScript(chunk)\n let chunkUrl = getUrlFromScript(chunk)\n\n const resolver = getOrCreateResolver(chunkUrl)\n resolver.resolve()\n\n if (params == null) {\n return\n }\n\n for (const otherChunkData of params.otherChunks) {\n const otherChunkPath = getChunkPath(otherChunkData)\n const otherChunkUrl = getChunkRelativeUrl(otherChunkPath)\n\n // Chunk might have started loading, so we want to avoid triggering another load.\n getOrCreateResolver(otherChunkUrl)\n }\n\n // This waits for chunks to be loaded, but also marks included items as available.\n await Promise.all(\n params.otherChunks.map((otherChunkData) =>\n loadInitialChunk(chunkPath, otherChunkData)\n )\n )\n\n if (params.runtimeModuleIds.length > 0) {\n for (const moduleId of params.runtimeModuleIds) {\n getOrInstantiateRuntimeModule(chunkPath, moduleId)\n }\n }\n },\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n loadChunkCached(sourceType: SourceType, chunkUrl: ChunkUrl) {\n return doLoadChunk(sourceType, chunkUrl)\n },\n\n async loadWebAssembly(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n importsObj: WebAssembly.Imports\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n const { instance } = await WebAssembly.instantiateStreaming(\n req,\n importsObj\n )\n\n return instance.exports\n },\n\n async loadWebAssemblyModule(\n _sourceType: SourceType,\n _sourceData: SourceData,\n wasmChunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n ): Promise {\n const req = fetchWebAssembly(wasmChunkPath)\n\n return await WebAssembly.compileStreaming(req)\n },\n }\n\n function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {\n let resolver = chunkResolvers.get(chunkUrl)\n if (!resolver) {\n let resolve: () => void\n let reject: (error?: Error) => void\n const promise = new Promise((innerResolve, innerReject) => {\n resolve = innerResolve\n reject = innerReject\n })\n resolver = {\n resolved: false,\n loadingStarted: false,\n promise,\n resolve: () => {\n resolver!.resolved = true\n resolve()\n },\n reject: reject!,\n }\n chunkResolvers.set(chunkUrl, resolver)\n }\n return resolver\n }\n\n /**\n * Loads the given chunk, and returns a promise that resolves once the chunk\n * has been loaded.\n */\n function doLoadChunk(sourceType: SourceType, chunkUrl: ChunkUrl) {\n const resolver = getOrCreateResolver(chunkUrl)\n if (resolver.loadingStarted) {\n return resolver.promise\n }\n\n if (sourceType === SourceType.Runtime) {\n // We don't need to load chunks references from runtime code, as they're already\n // present in the DOM.\n resolver.loadingStarted = true\n\n if (isCss(chunkUrl)) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n\n // We need to wait for JS chunks to register themselves within `registerChunk`\n // before we can start instantiating runtime modules, hence the absence of\n // `resolver.resolve()` in this branch.\n\n return resolver.promise\n }\n\n if (typeof importScripts === 'function') {\n // We're in a web worker\n if (isCss(chunkUrl)) {\n // ignore\n } else if (isJs(chunkUrl)) {\n self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl)\n importScripts(chunkUrl)\n } else {\n throw new Error(\n `can't infer type of chunk from URL ${chunkUrl} in worker`\n )\n }\n } else {\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedChunkUrl = decodeURI(chunkUrl)\n\n if (isCss(chunkUrl)) {\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${chunkUrl}\"],link[rel=stylesheet][href^=\"${chunkUrl}?\"],link[rel=stylesheet][href=\"${decodedChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedChunkUrl}?\"]`\n )\n if (previousLinks.length > 0) {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n } else {\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n link.href = chunkUrl\n link.onerror = () => {\n resolver.reject()\n }\n link.onload = () => {\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolver.resolve()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(link)\n }\n } else if (isJs(chunkUrl)) {\n const previousScripts = document.querySelectorAll(\n `script[src=\"${chunkUrl}\"],script[src^=\"${chunkUrl}?\"],script[src=\"${decodedChunkUrl}\"],script[src^=\"${decodedChunkUrl}?\"]`\n )\n if (previousScripts.length > 0) {\n // There is this edge where the script already failed loading, but we\n // can't detect that. The Promise will never resolve in this case.\n for (const script of Array.from(previousScripts)) {\n script.addEventListener('error', () => {\n resolver.reject()\n })\n }\n } else {\n const script = document.createElement('script')\n script.src = chunkUrl\n // We'll only mark the chunk as loaded once the script has been executed,\n // which happens in `registerChunk`. Hence the absence of `resolve()` in\n // this branch.\n script.onerror = () => {\n resolver.reject()\n }\n // Append to the `head` for webpack compatibility.\n document.head.appendChild(script)\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n }\n\n resolver.loadingStarted = true\n return resolver.promise\n }\n\n function fetchWebAssembly(wasmChunkPath: ChunkPath) {\n return fetch(getChunkRelativeUrl(wasmChunkPath))\n }\n})()\n"],"names":["getAssetSuffixFromScriptSrc","self","TURBOPACK_ASSET_SUFFIX","src","document","currentScript","getAttribute","qi","indexOf","slice","BACKEND","chunkResolvers","Map","registerChunk","chunk","params","chunkPath","getPathFromScript","chunkUrl","getUrlFromScript","resolver","getOrCreateResolver","resolve","otherChunkData","otherChunks","otherChunkPath","getChunkPath","otherChunkUrl","getChunkRelativeUrl","Promise","all","map","loadInitialChunk","runtimeModuleIds","length","moduleId","getOrInstantiateRuntimeModule","loadChunkCached","sourceType","doLoadChunk","loadWebAssembly","_sourceType","_sourceData","wasmChunkPath","_edgeModule","importsObj","req","fetchWebAssembly","instance","WebAssembly","instantiateStreaming","exports","loadWebAssemblyModule","compileStreaming","get","reject","promise","innerResolve","innerReject","resolved","loadingStarted","set","SourceType","Runtime","isCss","importScripts","isJs","TURBOPACK_NEXT_CHUNK_URLS","push","Error","decodedChunkUrl","decodeURI","previousLinks","querySelectorAll","link","createElement","rel","href","onerror","onload","head","appendChild","previousScripts","script","Array","from","addEventListener","fetch"],"mappings":"AAAA;;;;CAIC,GAED,oDAAoD,GAEpD,sEAAsE;AACtE,mEAAmE;AAEnE,SAASA;IACP,+CAA+C;IAC/C,IAAIC,KAAKC,sBAAsB,IAAI,MAAM,OAAOD,KAAKC,sBAAsB;IAC3E,MAAMC,MAAMC,UAAUC,eAAeC,eAAe,UAAU;IAC9D,MAAMC,KAAKJ,IAAIK,OAAO,CAAC;IACvB,OAAOD,MAAM,IAAIJ,IAAIM,KAAK,CAACF,MAAM;AACnC;AAUA,IAAIG;AAEJ;;CAEC,GACD,MAAMC,iBAA+C,IAAIC;AAExD,CAAC;IACAF,UAAU;QACR,MAAMG,eAAcC,KAAK,EAAEC,MAAM;YAC/B,IAAIC,YAAYC,kBAAkBH;YAClC,IAAII,WAAWC,iBAAiBL;YAEhC,MAAMM,WAAWC,oBAAoBH;YACrCE,SAASE,OAAO;YAEhB,IAAIP,UAAU,MAAM;gBAClB;YACF;YAEA,KAAK,MAAMQ,kBAAkBR,OAAOS,WAAW,CAAE;gBAC/C,MAAMC,iBAAiBC,aAAa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oB;wBACpB3D,SAASE,OAAO;oBAClB;oBACA,kDAAkD;oBAClDlB,SAAS4E,IAAI,CAACC,WAAW,CAACP;gBAC5B;YACF,OAAO,IAAIR,KAAKhD,WAAW;gBACzB,MAAMgE,kBAAkB9E,SAASqE,gBAAgB,CAC/C,CAAC,YAAY,EAAEvD,SAAS,gBAAgB,EAAEA,SAAS,gBAAgB,EAAEoD,gBAAgB,gBAAgB,EAAEA,gBAAgB,GAAG,CAAC;gBAE7H,IAAIY,gBAAgBhD,MAAM,GAAG,GAAG;oBAC9B,qEAAqE;oBACrE,kEAAkE;oBAClE,KAAK,MAAMiD,UAAUC,MAAMC,IAAI,CAACH,iBAAkB;wBAChDC,OAAOG,gBAAgB,CAAC,SAAS;4BAC/BlE,SAASmC,MAAM;wBACjB;oBACF;gBACF,OAAO;oBACL,MAAM4B,SAAS/E,SAASuE,aAAa,CAAC;oBACtCQ,OAAOhF,GAAG,GAAGe;oBACb,yEAAyE;oBACzE,wEAAwE;oBACxE,eAAe;oBACfiE,OAAOL,OAAO,GAAG;wBACf1D,SAASmC,MAAM;oBACjB;oBACA,kDAAkD;oBAClDnD,SAAS4E,IAAI,CAACC,WAAW,CAACE;gBAC5B;YACF,OAAO;gBACL,MAAM,IAAId,MAAM,CAAC,mCAAmC,EAAEnD,UAAU;YAClE;QACF;QAEAE,SAASwC,cAAc,GAAG;QAC1B,OAAOxC,SAASoC,OAAO;IACzB;IAEA,SAAST,iBAAiBJ,aAAwB;QAChD,OAAO4C,MAAM3D,oBAAoBe;IACnC;AACF,CAAC","ignoreList":[0]}}, + {"offset": {"line": 2119, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/dom/dev-backend-dom.ts"],"sourcesContent":["/**\n * This file contains the runtime code specific to the Turbopack development\n * ECMAScript DOM runtime.\n *\n * It will be appended to the base development runtime code.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n/// \n/// \n\nlet DEV_BACKEND: DevRuntimeBackend\n;(() => {\n DEV_BACKEND = {\n unloadChunk(chunkUrl) {\n deleteResolver(chunkUrl)\n\n // Strip query string so we match links regardless of cache-busting\n // params (e.g. ?ts=) that may differ between HMR updates.\n const baseChunkUrl = chunkUrl.split('?')[0]\n // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.\n const decodedBaseChunkUrl = decodeURI(baseChunkUrl)\n\n if (isCss(chunkUrl)) {\n const links = document.querySelectorAll(\n `link[href=\"${baseChunkUrl}\"],link[href^=\"${baseChunkUrl}?\"],link[href=\"${decodedBaseChunkUrl}\"],link[href^=\"${decodedBaseChunkUrl}?\"]`\n )\n for (const link of Array.from(links)) {\n link.remove()\n }\n } else if (isJs(chunkUrl)) {\n // Unloading a JS chunk would have no effect, as it lives in the JS\n // runtime once evaluated.\n // However, we still want to remove the script tag from the DOM to keep\n // the HTML somewhat consistent from the user's perspective.\n const scripts = document.querySelectorAll(\n `script[src=\"${baseChunkUrl}\"],script[src^=\"${baseChunkUrl}?\"],script[src=\"${decodedBaseChunkUrl}\"],script[src^=\"${decodedBaseChunkUrl}?\"]`\n )\n for (const script of Array.from(scripts)) {\n script.remove()\n }\n } else {\n throw new Error(`can't infer type of chunk from URL ${chunkUrl}`)\n }\n },\n\n reloadChunk(chunkUrl) {\n return new Promise((resolve, reject) => {\n if (!isCss(chunkUrl)) {\n reject(new Error('The DOM backend can only reload CSS chunks'))\n return\n }\n\n // Strip query string so we match links regardless of cache-busting\n // params (e.g. ?ts=) that may differ between HMR updates.\n const baseChunkUrl = chunkUrl.split('?')[0]\n const decodedBaseChunkUrl = decodeURI(baseChunkUrl)\n const previousLinks = document.querySelectorAll(\n `link[rel=stylesheet][href=\"${baseChunkUrl}\"],link[rel=stylesheet][href^=\"${baseChunkUrl}?\"],link[rel=stylesheet][href=\"${decodedBaseChunkUrl}\"],link[rel=stylesheet][href^=\"${decodedBaseChunkUrl}?\"]`\n )\n\n if (previousLinks.length === 0) {\n reject(new Error(`No link element found for chunk ${chunkUrl}`))\n return\n }\n\n const link = document.createElement('link')\n link.rel = 'stylesheet'\n\n if (\n navigator.userAgent.includes('Firefox') ||\n (navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome') &&\n !navigator.userAgent.includes('Chromium'))\n ) {\n // Firefox won't reload CSS files that were previously loaded on the\n // current page: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506\n //\n // Safari serves cached CSS when a exists for the\n // same URL: https://bugs.webkit.org/show_bug.cgi?id=187726\n //\n // Replace or add a fresh `ts` cache-busting param without\n // discarding other query parameters that may already be present.\n const url = new URL(chunkUrl, location.origin)\n url.searchParams.set('ts', String(Date.now()))\n // Reduced timer precision in some browers could lead to an update getting dropped\n // in firefox if it happens fast enough (in firefox precision is sometimes 100ms!).\n // So trust that the server is only updating us when it is important and use a\n // random number to bust the cache.\n url.searchParams.set('_next_rand', String(Math.random()))\n link.href = url.pathname + url.search\n } else {\n link.href = chunkUrl\n }\n\n link.onerror = () => {\n reject()\n }\n link.onload = () => {\n // First load the new CSS, then remove the old ones. This prevents visible\n // flickering that would happen in-between removing the previous CSS and\n // loading the new one.\n for (const previousLink of Array.from(previousLinks))\n previousLink.remove()\n\n // CSS chunks do not register themselves, and as such must be marked as\n // loaded instantly.\n resolve()\n }\n\n // Make sure to insert the new CSS right after the previous one, so that\n // its precedence is higher.\n previousLinks[0].parentElement!.insertBefore(\n link,\n previousLinks[0].nextSibling\n )\n })\n },\n\n restart: () => self.location.reload(),\n }\n\n function deleteResolver(chunkUrl: ChunkUrl) {\n chunkResolvers.delete(chunkUrl)\n }\n})()\n\nfunction _eval({ code, url, map }: EcmascriptModuleEntry): ModuleFactory {\n code += `\\n\\n//# sourceURL=${encodeURI(\n location.origin + CHUNK_BASE_PATH + url + ASSET_SUFFIX\n )}`\n if (map) {\n code += `\\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(\n // btoa doesn't handle nonlatin characters, so escape them as \\x sequences\n // See https://stackoverflow.com/a/26603875\n unescape(encodeURIComponent(map))\n )}`\n }\n\n // eslint-disable-next-line no-eval\n return eval(code)\n}\n"],"names":["DEV_BACKEND","unloadChunk","chunkUrl","deleteResolver","baseChunkUrl","split","decodedBaseChunkUrl","decodeURI","isCss","links","document","querySelectorAll","link","Array","from","remove","isJs","scripts","script","Error","reloadChunk","Promise","resolve","reject","previousLinks","length","createElement","rel","navigator","userAgent","includes","url","URL","location","origin","searchParams","set","String","Date","now","Math","random","href","pathname","search","onerror","onload","previousLink","parentElement","insertBefore","nextSibling","restart","self","reload","chunkResolvers","delete","_eval","code","map","encodeURI","CHUNK_BASE_PATH","ASSET_SUFFIX","btoa","unescape","encodeURIComponent","eval"],"mappings":"AAAA;;;;;CAKC,GAED,oDAAoD,GAEpD,gDAAgD;AAChD,4CAA4C;AAC5C,iDAAiD;AACjD,0DAA0D;AAE1D,IAAIA;AACH,CAAC;IACAA,cAAc;QACZC,aAAYC,QAAQ;YAClBC,eAAeD;YAEf,mEAAmE;YACnE,0DAA0D;YAC1D,MAAME,eAAeF,SAASG,KAAK,CAAC,IAAI,CAAC,EAAE;YAC3C,gFAAgF;YAChF,MAAMC,sBAAsBC,UAAUH;YAEtC,IAAII,MAAMN,WAAW;gBACnB,MAAMO,QAAQC,SAASC,gBAAgB,CACrC,CAAC,WAAW,EAAEP,aAAa,eAAe,EAAEA,aAAa,eAAe,EAAEE,oBAAoB,eAAe,EAAEA,oBAAoB,GAAG,CAAC;gBAEzI,KAAK,MAAMM,QAAQC,MAAMC,IAAI,CAACL,OAAQ;oBACpCG,KAAKG,MAAM;gBACb;YACF,OAAO,IAAIC,KAAKd,WAAW;gBACzB,mEAAmE;gBACnE,0BAA0B;gBAC1B,uEAAuE;gBACvE,4DAA4D;gBAC5D,MAAMe,UAAUP,SAASC,gBAAgB,CACvC,CAAC,YAAY,EAAEP,aAAa,gBAAgB,EAAEA,aAAa,gBAAgB,EAAEE,oBAAoB,gBAAgB,EAAEA,oBAAoB,GAAG,CAAC;gBAE7I,KAAK,MAAM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ACnCR,IAAII,YAAY,CAACC,GAAG,CAAC,cAAcC,OAAOG,KAAKC,MAAM;oBACrD7B,KAAK8B,IAAI,GAAGX,IAAIY,QAAQ,GAAGZ,IAAIa,MAAM;gBACvC,OAAO;oBACLhC,KAAK8B,IAAI,GAAGxC;gBACd;gBAEAU,KAAKiC,OAAO,GAAG;oBACbtB;gBACF;gBACAX,KAAKkC,MAAM,GAAG;oBACZ,0EAA0E;oBAC1E,wEAAwE;oBACxE,uBAAuB;oBACvB,KAAK,MAAMC,gBAAgBlC,MAAMC,IAAI,CAACU,eACpCuB,aAAahC,MAAM;oBAErB,uEAAuE;oBACvE,oBAAoB;oBACpBO;gBACF;gBAEA,wEAAwE;gBACxE,4BAA4B;gBAC5BE,aAAa,CAAC,EAAE,CAACwB,aAAa,CAAEC,YAAY,CAC1CrC,MACAY,aAAa,CAAC,EAAE,CAAC0B,WAAW;YAEhC;QACF;QAEAC,SAAS,IAAMC,KAAKnB,QAAQ,CAACoB,MAAM;IACrC;IAEA,SAASlD,eAAeD,QAAkB;QACxCoD,eAAeC,MAAM,CAACrD;IACxB;AACF,CAAC;AAED,SAASsD,MAAM,EAAEC,IAAI,EAAE1B,GAAG,EAAE2B,GAAG,EAAyB;IACtDD,QAAQ,CAAC,kBAAkB,EAAEE,UAC3B1B,SAASC,MAAM,GAAG0B,kBAAkB7B,MAAM8B,eACzC;IACH,IAAIH,KAAK;QACPD,QAAQ,CAAC,kEAAkE,EAAEK,KAC3E,0EAA0E;QAC1E,2CAA2C;QAC3CC,SAASC,mBAAmBN,QAC3B;IACL;IAEA,mCAAmC;IACnC,OAAOO,KAAKR;AACd","ignoreList":[0]}}] } \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/output/0v.~_crates_turbopack-tests_tests_snapshot_workers_shared_input_index_00pjotx.js b/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/output/0v.~_crates_turbopack-tests_tests_snapshot_workers_shared_input_index_00pjotx.js index 4940c8c50c87..9a8623cff1b4 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/output/0v.~_crates_turbopack-tests_tests_snapshot_workers_shared_input_index_00pjotx.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/output/0v.~_crates_turbopack-tests_tests_snapshot_workers_shared_input_index_00pjotx.js @@ -1956,7 +1956,10 @@ globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= []; /// function getAssetSuffixFromScriptSrc() { // TURBOPACK_ASSET_SUFFIX is set in web workers - return (self.TURBOPACK_ASSET_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || ''; + if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX; + const src = document?.currentScript?.getAttribute?.('src') ?? ''; + const qi = src.indexOf('?'); + return qi >= 0 ? src.slice(qi) : ''; } let BACKEND; /** @@ -2128,10 +2131,13 @@ let DEV_BACKEND; DEV_BACKEND = { unloadChunk (chunkUrl) { deleteResolver(chunkUrl); + // Strip query string so we match links regardless of cache-busting + // params (e.g. ?ts=) that may differ between HMR updates. + const baseChunkUrl = chunkUrl.split('?')[0]; // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped. - const decodedChunkUrl = decodeURI(chunkUrl); + const decodedBaseChunkUrl = decodeURI(baseChunkUrl); if (isCss(chunkUrl)) { - const links = document.querySelectorAll(`link[href="${chunkUrl}"],link[href^="${chunkUrl}?"],link[href="${decodedChunkUrl}"],link[href^="${decodedChunkUrl}?"]`); + const links = document.querySelectorAll(`link[href="${baseChunkUrl}"],link[href^="${baseChunkUrl}?"],link[href="${decodedBaseChunkUrl}"],link[href^="${decodedBaseChunkUrl}?"]`); for (const link of Array.from(links)){ link.remove(); } @@ -2140,7 +2146,7 @@ let DEV_BACKEND; // runtime once evaluated. // However, we still want to remove the script tag from the DOM to keep // the HTML somewhat consistent from the user's perspective. - const scripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); + const scripts = document.querySelectorAll(`script[src="${baseChunkUrl}"],script[src^="${baseChunkUrl}?"],script[src="${decodedBaseChunkUrl}"],script[src^="${decodedBaseChunkUrl}?"]`); for (const script of Array.from(scripts)){ script.remove(); } @@ -2154,23 +2160,34 @@ let DEV_BACKEND; reject(new Error('The DOM backend can only reload CSS chunks')); return; } - const decodedChunkUrl = decodeURI(chunkUrl); - const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`); + // Strip query string so we match links regardless of cache-busting + // params (e.g. ?ts=) that may differ between HMR updates. + const baseChunkUrl = chunkUrl.split('?')[0]; + const decodedBaseChunkUrl = decodeURI(baseChunkUrl); + const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${baseChunkUrl}"],link[rel=stylesheet][href^="${baseChunkUrl}?"],link[rel=stylesheet][href="${decodedBaseChunkUrl}"],link[rel=stylesheet][href^="${decodedBaseChunkUrl}?"]`); if (previousLinks.length === 0) { reject(new Error(`No link element found for chunk ${chunkUrl}`)); return; } const link = document.createElement('link'); link.rel = 'stylesheet'; - if (navigator.userAgent.includes('Firefox')) { - // Firefox won't reload CSS files that were previously loaded on the current page, - // we need to add a query param to make sure CSS is actually reloaded from the server. + if (navigator.userAgent.includes('Firefox') || navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome') && !navigator.userAgent.includes('Chromium')) { + // Firefox won't reload CSS files that were previously loaded on the + // current page: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506 // - // I believe this is this issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506 + // Safari serves cached CSS when a exists for the + // same URL: https://bugs.webkit.org/show_bug.cgi?id=187726 // - // Safari has a similar issue, but only if you have a `` tag - // pointing to the same URL as the stylesheet: https://bugs.webkit.org/show_bug.cgi?id=187726 - link.href = `${chunkUrl}?ts=${Date.now()}`; + // Replace or add a fresh `ts` cache-busting param without + // discarding other query parameters that may already be present. + const url = new URL(chunkUrl, location.origin); + url.searchParams.set('ts', String(Date.now())); + // Reduced timer precision in some browers could lead to an update getting dropped + // in firefox if it happens fast enough (in firefox precision is sometimes 100ms!). + // So trust that the server is only updating us when it is important and use a + // random number to bust the cache. + url.searchParams.set('_next_rand', String(Math.random())); + link.href = url.pathname + url.search; } else { link.href = chunkUrl; } diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/output/0v.~_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_0i7eipv.js b/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/output/0v.~_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_0i7eipv.js index e85713639c1e..6d877069b828 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/output/0v.~_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_0i7eipv.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/output/0v.~_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_0i7eipv.js @@ -1956,7 +1956,10 @@ globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= []; /// function getAssetSuffixFromScriptSrc() { // TURBOPACK_ASSET_SUFFIX is set in web workers - return (self.TURBOPACK_ASSET_SUFFIX ?? document?.currentScript?.getAttribute?.('src')?.replace(/^(.*(?=\?)|^.*$)/, '')) || ''; + if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX; + const src = document?.currentScript?.getAttribute?.('src') ?? ''; + const qi = src.indexOf('?'); + return qi >= 0 ? src.slice(qi) : ''; } let BACKEND; /** @@ -2128,10 +2131,13 @@ let DEV_BACKEND; DEV_BACKEND = { unloadChunk (chunkUrl) { deleteResolver(chunkUrl); + // Strip query string so we match links regardless of cache-busting + // params (e.g. ?ts=) that may differ between HMR updates. + const baseChunkUrl = chunkUrl.split('?')[0]; // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped. - const decodedChunkUrl = decodeURI(chunkUrl); + const decodedBaseChunkUrl = decodeURI(baseChunkUrl); if (isCss(chunkUrl)) { - const links = document.querySelectorAll(`link[href="${chunkUrl}"],link[href^="${chunkUrl}?"],link[href="${decodedChunkUrl}"],link[href^="${decodedChunkUrl}?"]`); + const links = document.querySelectorAll(`link[href="${baseChunkUrl}"],link[href^="${baseChunkUrl}?"],link[href="${decodedBaseChunkUrl}"],link[href^="${decodedBaseChunkUrl}?"]`); for (const link of Array.from(links)){ link.remove(); } @@ -2140,7 +2146,7 @@ let DEV_BACKEND; // runtime once evaluated. // However, we still want to remove the script tag from the DOM to keep // the HTML somewhat consistent from the user's perspective. - const scripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); + const scripts = document.querySelectorAll(`script[src="${baseChunkUrl}"],script[src^="${baseChunkUrl}?"],script[src="${decodedBaseChunkUrl}"],script[src^="${decodedBaseChunkUrl}?"]`); for (const script of Array.from(scripts)){ script.remove(); } @@ -2154,23 +2160,34 @@ let DEV_BACKEND; reject(new Error('The DOM backend can only reload CSS chunks')); return; } - const decodedChunkUrl = decodeURI(chunkUrl); - const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`); + // Strip query string so we match links regardless of cache-busting + // params (e.g. ?ts=) that may differ between HMR updates. + const baseChunkUrl = chunkUrl.split('?')[0]; + const decodedBaseChunkUrl = decodeURI(baseChunkUrl); + const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${baseChunkUrl}"],link[rel=stylesheet][href^="${baseChunkUrl}?"],link[rel=stylesheet][href="${decodedBaseChunkUrl}"],link[rel=stylesheet][href^="${decodedBaseChunkUrl}?"]`); if (previousLinks.length === 0) { reject(new Error(`No link element found for chunk ${chunkUrl}`)); return; } const link = document.createElement('link'); link.rel = 'stylesheet'; - if (navigator.userAgent.includes('Firefox')) { - // Firefox won't reload CSS files that were previously loaded on the current page, - // we need to add a query param to make sure CSS is actually reloaded from the server. + if (navigator.userAgent.includes('Firefox') || navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome') && !navigator.userAgent.includes('Chromium')) { + // Firefox won't reload CSS files that were previously loaded on the + // current page: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506 // - // I believe this is this issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506 + // Safari serves cached CSS when a exists for the + // same URL: https://bugs.webkit.org/show_bug.cgi?id=187726 // - // Safari has a similar issue, but only if you have a `` tag - // pointing to the same URL as the stylesheet: https://bugs.webkit.org/show_bug.cgi?id=187726 - link.href = `${chunkUrl}?ts=${Date.now()}`; + // Replace or add a fresh `ts` cache-busting param without + // discarding other query parameters that may already be present. + const url = new URL(chunkUrl, location.origin); + url.searchParams.set('ts', String(Date.now())); + // Reduced timer precision in some browers could lead to an update getting dropped + // in firefox if it happens fast enough (in firefox precision is sometimes 100ms!). + // So trust that the server is only updating us when it is important and use a + // random number to bust the cache. + url.searchParams.set('_next_rand', String(Math.random())); + link.href = url.pathname + url.search; } else { link.href = chunkUrl; } From e151e5f84285ac569cf2ec311873200511eea8b3 Mon Sep 17 00:00:00 2001 From: Benjamin Woodruff Date: Tue, 31 Mar 2026 16:06:42 -0700 Subject: [PATCH 20/76] Fix CI for glibc linux builds --- .github/workflows/build_and_deploy.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/workflows/build_and_deploy.yml b/.github/workflows/build_and_deploy.yml index 854478439d8c..a451d3a631a7 100644 --- a/.github/workflows/build_and_deploy.yml +++ b/.github/workflows/build_and_deploy.yml @@ -226,6 +226,10 @@ jobs: # environment. docker: ghcr.io/napi-rs/napi-rs/nodejs-rust:stable-2023-09-17-x64 build: | + rm /usr/share/keyrings/nodesource.gpg + curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key \ + | gpg --dearmor -o /usr/share/keyrings/nodesource.gpg + sed -i 's/jammy/nodistro/g' /etc/apt/sources.list.d/nodesource.list apt update apt install -y pkg-config xz-utils dav1d libdav1d-dev rustup show @@ -267,6 +271,10 @@ jobs: target: 'aarch64-unknown-linux-gnu' docker: ghcr.io/napi-rs/napi-rs/nodejs-rust:stable-2023-09-17-aarch64 build: | + rm /usr/share/keyrings/nodesource.gpg + curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key \ + | gpg --dearmor -o /usr/share/keyrings/nodesource.gpg + sed -i 's/jammy/nodistro/g' /etc/apt/sources.list.d/nodesource.list apt update apt install -y pkg-config xz-utils dav1d libdav1d-dev export JEMALLOC_SYS_WITH_LG_PAGE=16 From 8d0f77bfa210691875c264fdf83cfee4e9ae418f Mon Sep 17 00:00:00 2001 From: Luke Sandberg Date: Tue, 31 Mar 2026 16:17:14 -0700 Subject: [PATCH 21/76] Backport: #92177 Fixes #91708 set the legacy_x86_64_support feature on qfilter to support older intel cpus --- turbopack/crates/turbo-persistence/Cargo.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/turbopack/crates/turbo-persistence/Cargo.toml b/turbopack/crates/turbo-persistence/Cargo.toml index 4f5121b554b8..93fcbd35f90a 100644 --- a/turbopack/crates/turbo-persistence/Cargo.toml +++ b/turbopack/crates/turbo-persistence/Cargo.toml @@ -26,7 +26,8 @@ memmap2 = "0.9.5" nohash-hasher = { workspace = true } parking_lot = { workspace = true } pot = "3.0.0" -qfilter = { version = "0.3.0-alpha.2", features = ["serde"] } +# See https://github.com/vercel/next.js/issues/91708 for why we need the legacy_x86_64_support feature +qfilter = { version = "0.3.0-alpha.2", features = ["serde", "legacy_x86_64_support"] } quick_cache = { workspace = true } rustc-hash = { workspace = true } smallvec = { workspace = true } From 52faae3d94641584e13691238df5be158d0f00fb Mon Sep 17 00:00:00 2001 From: nextjs-bot Date: Tue, 31 Mar 2026 23:39:18 +0000 Subject: [PATCH 22/76] v16.2.2 --- lerna.json | 2 +- packages/create-next-app/package.json | 2 +- packages/eslint-config-next/package.json | 4 ++-- packages/eslint-plugin-internal/package.json | 2 +- packages/eslint-plugin-next/package.json | 2 +- packages/font/package.json | 2 +- packages/next-bundle-analyzer/package.json | 2 +- packages/next-codemod/package.json | 2 +- packages/next-env/package.json | 2 +- packages/next-mdx/package.json | 2 +- packages/next-playwright/package.json | 2 +- packages/next-plugin-storybook/package.json | 2 +- packages/next-polyfill-module/package.json | 2 +- packages/next-polyfill-nomodule/package.json | 2 +- packages/next-routing/package.json | 2 +- packages/next-rspack/package.json | 2 +- packages/next-swc/package.json | 2 +- packages/next/package.json | 14 +++++++------- packages/react-refresh-utils/package.json | 2 +- packages/third-parties/package.json | 4 ++-- pnpm-lock.yaml | 16 ++++++++-------- 21 files changed, 36 insertions(+), 36 deletions(-) diff --git a/lerna.json b/lerna.json index 2c2b1189b639..3373831fff5c 100644 --- a/lerna.json +++ b/lerna.json @@ -16,5 +16,5 @@ "registry": "https://registry.npmjs.org/" } }, - "version": "16.2.1" + "version": "16.2.2" } \ No newline at end of file diff --git a/packages/create-next-app/package.json b/packages/create-next-app/package.json index 51299326527f..dcde720a6b9e 100644 --- a/packages/create-next-app/package.json +++ b/packages/create-next-app/package.json @@ -1,6 +1,6 @@ { "name": "create-next-app", - "version": "16.2.1", + "version": "16.2.2", "keywords": [ "react", "next", diff --git a/packages/eslint-config-next/package.json b/packages/eslint-config-next/package.json index 26ff16bb9d71..d439e8468aa2 100644 --- a/packages/eslint-config-next/package.json +++ b/packages/eslint-config-next/package.json @@ -1,6 +1,6 @@ { "name": "eslint-config-next", - "version": "16.2.1", + "version": "16.2.2", "description": "ESLint configuration used by Next.js.", "license": "MIT", "repository": { @@ -12,7 +12,7 @@ "dist" ], "dependencies": { - "@next/eslint-plugin-next": "16.2.1", + "@next/eslint-plugin-next": "16.2.2", "eslint-import-resolver-node": "^0.3.6", "eslint-import-resolver-typescript": "^3.5.2", "eslint-plugin-import": "^2.32.0", diff --git a/packages/eslint-plugin-internal/package.json b/packages/eslint-plugin-internal/package.json index cd8e66fe025e..38e6f4d1ea30 100644 --- a/packages/eslint-plugin-internal/package.json +++ b/packages/eslint-plugin-internal/package.json @@ -1,7 +1,7 @@ { "name": "@next/eslint-plugin-internal", "private": true, - "version": "16.2.1", + "version": "16.2.2", "description": "ESLint plugin for working on Next.js.", "exports": { ".": "./src/eslint-plugin-internal.js" diff --git a/packages/eslint-plugin-next/package.json b/packages/eslint-plugin-next/package.json index 9a2da229b490..b07260c7068f 100644 --- a/packages/eslint-plugin-next/package.json +++ b/packages/eslint-plugin-next/package.json @@ -1,6 +1,6 @@ { "name": "@next/eslint-plugin-next", - "version": "16.2.1", + "version": "16.2.2", "description": "ESLint plugin for Next.js.", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/font/package.json b/packages/font/package.json index 41271e57b6f8..6dfb3f4cb428 100644 --- a/packages/font/package.json +++ b/packages/font/package.json @@ -1,7 +1,7 @@ { "name": "@next/font", "private": true, - "version": "16.2.1", + "version": "16.2.2", "repository": { "url": "vercel/next.js", "directory": "packages/font" diff --git a/packages/next-bundle-analyzer/package.json b/packages/next-bundle-analyzer/package.json index 1a942136438e..689210f9c2c6 100644 --- a/packages/next-bundle-analyzer/package.json +++ b/packages/next-bundle-analyzer/package.json @@ -1,6 +1,6 @@ { "name": "@next/bundle-analyzer", - "version": "16.2.1", + "version": "16.2.2", "main": "index.js", "types": "index.d.ts", "license": "MIT", diff --git a/packages/next-codemod/package.json b/packages/next-codemod/package.json index 315f72ecd40f..d4622a54af6c 100644 --- a/packages/next-codemod/package.json +++ b/packages/next-codemod/package.json @@ -1,6 +1,6 @@ { "name": "@next/codemod", - "version": "16.2.1", + "version": "16.2.2", "license": "MIT", "repository": { "type": "git", diff --git a/packages/next-env/package.json b/packages/next-env/package.json index 3d066e291cb9..94663fce204e 100644 --- a/packages/next-env/package.json +++ b/packages/next-env/package.json @@ -1,6 +1,6 @@ { "name": "@next/env", - "version": "16.2.1", + "version": "16.2.2", "keywords": [ "react", "next", diff --git a/packages/next-mdx/package.json b/packages/next-mdx/package.json index 6d6b01b113b4..07af088bda2f 100644 --- a/packages/next-mdx/package.json +++ b/packages/next-mdx/package.json @@ -1,6 +1,6 @@ { "name": "@next/mdx", - "version": "16.2.1", + "version": "16.2.2", "main": "index.js", "license": "MIT", "repository": { diff --git a/packages/next-playwright/package.json b/packages/next-playwright/package.json index 79d7913708f5..b700c44fc235 100644 --- a/packages/next-playwright/package.json +++ b/packages/next-playwright/package.json @@ -1,6 +1,6 @@ { "name": "@next/playwright", - "version": "16.2.1", + "version": "16.2.2", "repository": { "url": "vercel/next.js", "directory": "packages/next-playwright" diff --git a/packages/next-plugin-storybook/package.json b/packages/next-plugin-storybook/package.json index bc3a3b226a41..d4fa85fad02e 100644 --- a/packages/next-plugin-storybook/package.json +++ b/packages/next-plugin-storybook/package.json @@ -1,6 +1,6 @@ { "name": "@next/plugin-storybook", - "version": "16.2.1", + "version": "16.2.2", "repository": { "url": "vercel/next.js", "directory": "packages/next-plugin-storybook" diff --git a/packages/next-polyfill-module/package.json b/packages/next-polyfill-module/package.json index 5fc4ddf8f511..2ab97973a243 100644 --- a/packages/next-polyfill-module/package.json +++ b/packages/next-polyfill-module/package.json @@ -1,6 +1,6 @@ { "name": "@next/polyfill-module", - "version": "16.2.1", + "version": "16.2.2", "description": "A standard library polyfill for ES Modules supporting browsers (Edge 16+, Firefox 60+, Chrome 61+, Safari 10.1+)", "main": "dist/polyfill-module.js", "license": "MIT", diff --git a/packages/next-polyfill-nomodule/package.json b/packages/next-polyfill-nomodule/package.json index 08d37a7e9bb3..61f5312e940c 100644 --- a/packages/next-polyfill-nomodule/package.json +++ b/packages/next-polyfill-nomodule/package.json @@ -1,6 +1,6 @@ { "name": "@next/polyfill-nomodule", - "version": "16.2.1", + "version": "16.2.2", "description": "A polyfill for non-dead, nomodule browsers.", "main": "dist/polyfill-nomodule.js", "license": "MIT", diff --git a/packages/next-routing/package.json b/packages/next-routing/package.json index 956eb2bfa665..d2271b269df6 100644 --- a/packages/next-routing/package.json +++ b/packages/next-routing/package.json @@ -1,6 +1,6 @@ { "name": "@next/routing", - "version": "16.2.1", + "version": "16.2.2", "keywords": [ "react", "next", diff --git a/packages/next-rspack/package.json b/packages/next-rspack/package.json index 34e8c338f4e5..392d9efdd55d 100644 --- a/packages/next-rspack/package.json +++ b/packages/next-rspack/package.json @@ -1,6 +1,6 @@ { "name": "next-rspack", - "version": "16.2.1", + "version": "16.2.2", "repository": { "url": "vercel/next.js", "directory": "packages/next-rspack" diff --git a/packages/next-swc/package.json b/packages/next-swc/package.json index d2c7a78f995c..8b6944a801e9 100644 --- a/packages/next-swc/package.json +++ b/packages/next-swc/package.json @@ -1,6 +1,6 @@ { "name": "@next/swc", - "version": "16.2.1", + "version": "16.2.2", "private": true, "files": [ "native/" diff --git a/packages/next/package.json b/packages/next/package.json index f864894f1f5e..6a58f4f9d595 100644 --- a/packages/next/package.json +++ b/packages/next/package.json @@ -1,6 +1,6 @@ { "name": "next", - "version": "16.2.1", + "version": "16.2.2", "description": "The React Framework", "main": "./dist/server/next.js", "license": "MIT", @@ -97,7 +97,7 @@ ] }, "dependencies": { - "@next/env": "16.2.1", + "@next/env": "16.2.2", "@swc/helpers": "0.5.15", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", @@ -161,11 +161,11 @@ "@modelcontextprotocol/sdk": "1.18.1", "@mswjs/interceptors": "0.23.0", "@napi-rs/triples": "1.2.0", - "@next/font": "16.2.1", - "@next/polyfill-module": "16.2.1", - "@next/polyfill-nomodule": "16.2.1", - "@next/react-refresh-utils": "16.2.1", - "@next/swc": "16.2.1", + "@next/font": "16.2.2", + "@next/polyfill-module": "16.2.2", + "@next/polyfill-nomodule": "16.2.2", + "@next/react-refresh-utils": "16.2.2", + "@next/swc": "16.2.2", "@opentelemetry/api": "1.6.0", "@playwright/test": "1.58.2", "@rspack/core": "1.6.7", diff --git a/packages/react-refresh-utils/package.json b/packages/react-refresh-utils/package.json index 091e10b51c4b..4d6f63b919a4 100644 --- a/packages/react-refresh-utils/package.json +++ b/packages/react-refresh-utils/package.json @@ -1,6 +1,6 @@ { "name": "@next/react-refresh-utils", - "version": "16.2.1", + "version": "16.2.2", "description": "An experimental package providing utilities for React Refresh.", "repository": { "url": "vercel/next.js", diff --git a/packages/third-parties/package.json b/packages/third-parties/package.json index dbfd66a5dafe..d04b30776939 100644 --- a/packages/third-parties/package.json +++ b/packages/third-parties/package.json @@ -1,6 +1,6 @@ { "name": "@next/third-parties", - "version": "16.2.1", + "version": "16.2.2", "repository": { "url": "vercel/next.js", "directory": "packages/third-parties" @@ -26,7 +26,7 @@ "third-party-capital": "1.0.20" }, "devDependencies": { - "next": "16.2.1", + "next": "16.2.2", "outdent": "0.8.0", "prettier": "2.5.1", "typescript": "5.9.2" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b77d960365f0..ae4bc0a83bd5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1017,7 +1017,7 @@ importers: packages/eslint-config-next: dependencies: '@next/eslint-plugin-next': - specifier: 16.2.1 + specifier: 16.2.2 version: link:../eslint-plugin-next eslint: specifier: '>=9.0.0' @@ -1094,7 +1094,7 @@ importers: packages/next: dependencies: '@next/env': - specifier: 16.2.1 + specifier: 16.2.2 version: link:../next-env '@swc/helpers': specifier: 0.5.15 @@ -1219,19 +1219,19 @@ importers: specifier: 1.2.0 version: 1.2.0 '@next/font': - specifier: 16.2.1 + specifier: 16.2.2 version: link:../font '@next/polyfill-module': - specifier: 16.2.1 + specifier: 16.2.2 version: link:../next-polyfill-module '@next/polyfill-nomodule': - specifier: 16.2.1 + specifier: 16.2.2 version: link:../next-polyfill-nomodule '@next/react-refresh-utils': - specifier: 16.2.1 + specifier: 16.2.2 version: link:../react-refresh-utils '@next/swc': - specifier: 16.2.1 + specifier: 16.2.2 version: link:../next-swc '@opentelemetry/api': specifier: 1.6.0 @@ -1955,7 +1955,7 @@ importers: version: 1.0.20 devDependencies: next: - specifier: 16.2.1 + specifier: 16.2.2 version: link:../next outdent: specifier: 0.8.0 From b2f208ae98645d119a7e3388ab8a407005619dd8 Mon Sep 17 00:00:00 2001 From: Joseph Date: Thu, 2 Apr 2026 17:46:50 +0200 Subject: [PATCH 23/76] Backport: new view-transitions guide, update and fixes (#92264) Publishing: 1. `6a2045936f` - docs: add middleware bypass note to CDN caching guide (#92132) 2. `495d50f187` - docs: document revalidateTag's required second argument in upgrade guide (#92134) 3. `faa4b99296` - docs: local images referenced by remote source (#92178) 4. `0167a02695` - Docs/adapters review (#92223) 5. `2622a53942` - docs: vt demo guide (#92249) --------- Co-authored-by: JJ Kasper Co-authored-by: Aurora Scharff <66901228+aurorascharff@users.noreply.github.com> --- docs/01-app/01-getting-started/12-images.mdx | 44 ++ docs/01-app/02-guides/cdn-caching.mdx | 2 + .../01-app/02-guides/upgrading/version-16.mdx | 12 +- docs/01-app/02-guides/view-transitions.mdx | 393 ++++++++++++++++++ .../01-next-config-js/viewTransition.mdx | 13 +- .../07-adapters/04-testing-adapters.mdx | 6 +- .../05-routing-with-next-routing.mdx | 12 +- .../07-adapters/09-output-types.mdx | 2 +- 8 files changed, 470 insertions(+), 14 deletions(-) create mode 100644 docs/01-app/02-guides/view-transitions.mdx diff --git a/docs/01-app/01-getting-started/12-images.mdx b/docs/01-app/01-getting-started/12-images.mdx index 0059d00e8e0f..764c22241ac8 100644 --- a/docs/01-app/01-getting-started/12-images.mdx +++ b/docs/01-app/01-getting-started/12-images.mdx @@ -117,6 +117,50 @@ export default function Page() { } ``` +### Images without static imports + +If you can't use a static `import` for your images, you can use a dynamic `import()` in a Server Component to still get automatic `width`, `height`, and `blurDataURL`: + +```tsx filename="app/blog/[slug]/page.tsx" switcher +import Image from 'next/image' + +async function PostImage({ + imageFilename, + alt, +}: { + imageFilename: string + alt: string +}) { + const { default: image } = await import( + `../content/blog/images/${imageFilename}` + ) + // image contains width, height, and blurDataURL + return {alt} +} +``` + +```jsx filename="app/blog/[slug]/page.js" switcher +import Image from 'next/image' + +async function PostImage({ imageFilename, alt }) { + const { default: image } = await import( + `../content/blog/images/${imageFilename}` + ) + // image contains width, height, and blurDataURL + return {alt} +} +``` + +If you have a [path alias](https://www.typescriptlang.org/tsconfig/#paths) configured (e.g. `@/`), you can use it instead of a relative path: + +```tsx +const { default: image } = await import( + `@/content/blog/images/${imageFilename}` +) +``` + +The path must include a static prefix (like `../content/blog/images/`). Be as specific as possible, since **all** files matching that prefix are bundled. Only files in your specified directory are included, so external input cannot reach outside of it. + ## Remote images To use a remote image, you can provide a URL string for the `src` property. diff --git a/docs/01-app/02-guides/cdn-caching.mdx b/docs/01-app/02-guides/cdn-caching.mdx index fd802ed3a56a..2b274f5f853c 100644 --- a/docs/01-app/02-guides/cdn-caching.mdx +++ b/docs/01-app/02-guides/cdn-caching.mdx @@ -52,6 +52,8 @@ App Router responses can vary based on several custom request headers. Next.js s - `next-router-segment-prefetch` — the specific segment being prefetched - `next-url` — added only for routes that use [interception routes](/docs/app/api-reference/file-conventions/intercepting-routes), carries the URL being intercepted +> **Good to know:** [`proxy.js`](/docs/app/api-reference/file-conventions/proxy) (previously Middleware) should run before the CDN cache so it remains the source of truth for auth, redirects, and rewrites. If your deployment places `proxy.js` behind the CDN, configure the cache layer to bypass caching for routes that depend on `proxy.js` decisions. + Many CDNs don't support `Vary` without additional configuration. Next.js addresses this with the `_rsc` search parameter: a hash of the relevant request header values that acts as a cache-key, ensuring different response variants get different cache keys. This ensures correct responses even on CDNs that ignore `Vary`. ## Handling Headers at the CDN diff --git a/docs/01-app/02-guides/upgrading/version-16.mdx b/docs/01-app/02-guides/upgrading/version-16.mdx index cf7c2d64c0bb..0b60187a82b7 100644 --- a/docs/01-app/02-guides/upgrading/version-16.mdx +++ b/docs/01-app/02-guides/upgrading/version-16.mdx @@ -454,7 +454,17 @@ bun add -D babel-plugin-react-compiler ### revalidateTag -[`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) has a new function signature. You can pass a [`cacheLife`](/docs/app/api-reference/functions/cacheLife#reference) profile as the second argument. +[`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) now requires a second argument specifying a [`cacheLife`](/docs/app/api-reference/functions/cacheLife#reference) profile. The single-argument form is deprecated and will produce a TypeScript error. + +```ts +// Before +revalidateTag('posts') + +// After +revalidateTag('posts', 'max') +``` + +If you need immediate expiration rather than stale-while-revalidate, use [`updateTag`](/docs/app/api-reference/functions/updateTag) in Server Actions instead. ```ts filename="app/actions.ts" switcher 'use server' diff --git a/docs/01-app/02-guides/view-transitions.mdx b/docs/01-app/02-guides/view-transitions.mdx new file mode 100644 index 000000000000..01e151b823f3 --- /dev/null +++ b/docs/01-app/02-guides/view-transitions.mdx @@ -0,0 +1,393 @@ +--- +title: Designing view transitions +description: Learn how to use view transitions to communicate meaning during navigation, loading, and content changes in a Next.js app. +nav_title: View transitions +--- + +In web apps, route changes replace the entire page at once. One set of elements disappears, another appears, with no visual connection between them. A user selects a photo thumbnail to view it in detail on another page. They are the same image, but nothing on screen communicates that. + +Apps that need these transitions typically rely on complex animation libraries that manage mount/unmount lifecycles, track element positions across routes, and coordinate timing manually, to animate how elements enter, exit, and move between states. + +React's `` component integrates with the browser's [View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API) to handle this declaratively. You name the elements that should persist, and the browser animates between their old and new positions. + +This guide walks through four patterns that cover the most common cases: morphing shared elements, animating loading states, adding directional navigation, and crossfading content within the same route. + +## Example + +As an example, we'll build a photography gallery called _Frames_. + +We'll start by morphing a thumbnail into a hero image (shared elements), then animate the loading skeleton into real content (Suspense reveals), add directional slides for forward and back navigation (route transitions), and finish with crossfades for switching between photographer tabs (same-route transitions). + +You can find the resources used in this example here: + +- [Demo](https://react-view-transitions-demo.labs.vercel.dev) +- [Code](https://github.com/vercel-labs/react-view-transitions-demo) + +Before starting, enable view transitions in your Next.js config: + +```ts filename="next.config.ts" +import type { NextConfig } from 'next' + +const nextConfig: NextConfig = { + experimental: { + viewTransition: true, + }, +} + +export default nextConfig +``` + +> [!NOTE] +> The View Transitions API is supported in all major browsers, though some animations may behave differently in Safari. Without browser support, your application works normally, the transitions simply do not animate. + +Then import the `ViewTransition` component from React: + +```tsx +import { ViewTransition } from 'react' +``` + +`` animations are activated by [Transitions](https://react.dev/reference/react/useTransition), [``](https://react.dev/reference/react/Suspense), and [`useDeferredValue`](https://react.dev/reference/react/useDeferredValue). Regular `setState` calls do not trigger them. In Next.js, route navigations are transitions, so `` animations activate automatically during navigation. + +### Step 1: Morph a thumbnail into a hero image + +The gallery displays photos in a grid. Clicking a photo opens a detail page with a larger version of the same image. Without transitions, the thumbnail disappears and the hero appears. Nothing connects them visually. The user has to scan the detail page to confirm they clicked the right photo. + +In motion design, when an object persists across a cut, it communicates continuity. The viewer understands they are looking at the same thing, not a replacement. This is the most important transition pattern: **shared element morphing**. + +Wrap both the grid thumbnail and the detail hero in `` with the same `name`: + +```tsx filename="components/photo-grid.tsx" +import { ViewTransition } from 'react' +import Image from 'next/image' +import Link from 'next/link' + +function PhotoGrid({ photos }) { + return ( +
+ {photos.map((photo) => ( + + + {photo.title} + + + ))} +
+ ) +} +``` + +```tsx filename="app/photo/[id]/photo-content.tsx" +import { ViewTransition } from 'react' +import Image from 'next/image' + +async function PhotoContent({ id }) { + const photo = await getPhoto(id) + + return ( + + {photo.title} + + ) +} +``` + +The `name` prop creates identity. React finds elements with the same name on the old and new pages, then animates between their size and position automatically. No additional props are needed for the morph to work. + +If we click a thumbnail now, the image scales and repositions from its grid cell to the hero slot. Navigating back reverses the morph. The user sees one object moving, not two objects swapping. + +#### Customizing the morph animation + +To control the morph CSS, add `share="morph"`. This assigns the `morph` class to the view transition, which you can target with CSS pseudo-elements. For example, to soften the morph mid-flight with a [`blur`](https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/blur) keyframe: + +```tsx + + {photo.title} + +``` + +```css filename="app/globals.css" +::view-transition-group(.morph) { + animation-duration: 400ms; +} +::view-transition-image-pair(.morph) { + animation-name: via-blur; +} +@keyframes via-blur { + 30% { + filter: blur(3px); + } +} +``` + +The blur hides pixel-level interpolation artifacts during the transition. At 400ms, the morph is slow enough to register but fast enough to feel direct. + +### Step 2: Animate loading states with Suspense reveals + +The photo detail page loads its content asynchronously. While data is in flight, a Suspense boundary shows a skeleton. When the data resolves, the skeleton is replaced by the real content. + +Without a transition, the swap is instant. The skeleton vanishes and the content pops in. + +In motion design, vertical direction encodes hierarchy. Content sliding up communicates arrival. Content sliding down communicates departure. The pair together creates a handoff: the placeholder yields to the real thing. + +Wrap the Suspense fallback in a `ViewTransition` with an exit animation, and the content in a `ViewTransition` with an enter animation: + +```tsx filename="app/photo/[id]/page.tsx" +import { Suspense, ViewTransition } from 'react' + +export default async function PhotoPage({ params }) { + const { id } = await params + + return ( + + +
+ } + > + + + +
+ ) +} +``` + +The `default="none"` prop prevents this `ViewTransition` from animating during unrelated transitions, like the shared element morph from Step 1. Without it, every transition on the page would trigger every `ViewTransition`'s animation. + +The CSS animations use asymmetric timing. The exit is fast (150ms). The enter is slower (210ms) and delayed until the exit completes: + +```css filename="app/globals.css" +:root { + --duration-exit: 150ms; + --duration-enter: 210ms; +} + +::view-transition-old(.slide-down) { + animation: + var(--duration-exit) ease-out both fade reverse, + var(--duration-exit) ease-out both slide-y reverse; +} +::view-transition-new(.slide-up) { + animation: + var(--duration-enter) ease-in var(--duration-exit) both fade, + 400ms ease-in both slide-y; +} + +@keyframes fade { + from { + filter: blur(3px); + opacity: 0; + } + to { + filter: blur(0); + opacity: 1; + } +} +@keyframes slide-y { + from { + transform: translateY(10px); + } + to { + transform: translateY(0); + } +} +``` + +The asymmetry is deliberate. Old content should leave quickly so it does not compete for attention. New content should arrive more gently so the user has time to register it. The `var(--duration-exit)` delay on the enter animation means the new content waits for the old content to finish leaving before it appears. + +If we refresh the page, the skeleton slides down and fades out, and a moment later the real content slides up and fades in. + +### Step 3: Add directional motion for navigation + +The gallery now has morphing images and animated loading states. But navigating between pages still has no directional signal. Forward and back navigations look identical. The user cannot tell from the animation whether they moved deeper into the app or returned to a previous page. + +In film and animation, horizontal direction encodes spatial position. Moving left means progressing forward (like turning a page in a left-to-right language). Moving right means going back. This convention is so ingrained that violating it feels disorienting. + +Use the `transitionTypes` prop on `` to tag forward navigations: + +```tsx filename="components/photo-grid.tsx" + + {/* photo thumbnail */} + +``` + +The same pattern works for any navigation within the app. For example, previous/next arrows on a photo detail page can use `nav-back` and `nav-forward` to animate in the corresponding direction. + +For links that return the user to a previous page, use `nav-back`: + +```tsx filename="app/photo/[id]/page.tsx" + + ← Gallery + +``` + +The transition type is not automatic. You decide which links are "forward" and which are "back" based on your app's navigation hierarchy. + +Then wrap page content in a `ViewTransition` that maps transition types to directional animations: + +```tsx filename="app/photo/[id]/page.tsx" + + {/* page content */} + +``` + +The `enter` and `exit` props accept an object keyed by transition type. When a navigation carries the `nav-forward` type, the exit animation slides old content left and the enter animation slides new content in from the right. The `default: "none"` ensures that transitions without a type (like initial page loads) produce no animation. + +The CSS for directional slides: + +```css filename="app/globals.css" +::view-transition-old(.nav-forward) { + --slide-offset: -60px; + animation: + 150ms ease-in both fade reverse, + 400ms ease-in-out both slide reverse; +} +::view-transition-new(.nav-forward) { + --slide-offset: 60px; + animation: + 210ms ease-out 150ms both fade, + 400ms ease-in-out both slide; +} + +::view-transition-old(.nav-back) { + --slide-offset: 60px; + animation: + 150ms ease-in both fade reverse, + 400ms ease-in-out both slide reverse; +} +::view-transition-new(.nav-back) { + --slide-offset: -60px; + animation: + 210ms ease-out 150ms both fade, + 400ms ease-in-out both slide; +} + +@keyframes slide { + from { + translate: var(--slide-offset); + } + to { + translate: 0; + } +} +``` + +The 60px offset is enough to communicate direction without making the user track a fast-moving element across the screen. + +#### Anchoring the header + +During directional slides, the header should not move. A sliding header breaks the user's spatial anchor. They need one fixed reference point to understand that the _content_ moved, not the entire viewport. + +Assign the header a `viewTransitionName` and suppress its animation in CSS: + +```tsx filename="components/header.tsx" +
+ {/* navigation links */} +
+``` + +```css filename="app/globals.css" +::view-transition-group(site-header) { + animation: none; + z-index: 100; +} +::view-transition-old(site-header) { + display: none; +} +::view-transition-new(site-header) { + animation: none; +} +``` + +The `display: none` on the old snapshot prevents a flash where both old and new headers are briefly visible. The `z-index: 100` ensures the header renders above the sliding content. + +If we navigate forward to a photo, content slides left. If we click the "← Gallery" link (tagged with `nav-back`), content slides right. The header stays fixed throughout both transitions. + +Browser-initiated back navigations (the back button or swipe gestures) do not carry a transition type, so the directional slide does not play. The shared element morph from Step 1 still applies if both pages have matching `name` props. + +#### Respecting reduced motion + +Directional slides simulate physical movement across the viewport. This is the most common trigger for motion sensitivity. Morphs, reveals, and crossfades carry less risk since they affect smaller areas or rely on opacity rather than position. + +The simplest approach is to disable all animation durations: + +```css filename="app/globals.css" +@media (prefers-reduced-motion: reduce) { + ::view-transition-old(*), + ::view-transition-new(*), + ::view-transition-group(*) { + animation-duration: 0s !important; + animation-delay: 0s !important; + } +} +``` + +Without animation, content swaps instantly, which is the browser's default behavior. A more refined approach would preserve crossfades and opacity transitions while removing positional movement. See ["No Motion Isn't Always prefers-reduced-motion"](https://css-tricks.com/nuking-motion-with-prefers-reduced-motion/) for more on this. + +### Step 4: Crossfade content within the same route + +The gallery has a photographer section with tabs. Each tab shows a different photographer's photos, but the route structure is the same: `/collection/[slug]`. Clicking between tabs does not feel like navigating to a new page. It feels like switching content within the same container. + +A directional slide would be wrong here. Slides communicate "going to a new place." A crossfade communicates "same place, different content." The container persists (continuity), only the grid inside changes (swap). + +Use a `ViewTransition` with `key` set to the current slug. When the key changes, React triggers a transition between the old and new content: + +```tsx filename="app/collection/[slug]/page.tsx" +import { Suspense, ViewTransition } from 'react' + +export default async function CollectionPage({ params }) { + const { slug } = await params + + return ( + }> + + + + + ) +} +``` + +The `share="auto"` and `enter="auto"` props tell React to use its default crossfade animation. The `name` prop gives the container an identity so React knows what to animate. The `key={slug}` change is what triggers the transition. + +If we click between photographer tabs, the grid crossfades. The tab bar and surrounding layout do not move. Only the photo grid transitions between states. + +## Next steps + +You now know how to use view transitions to communicate meaning during navigation. Shared elements communicate continuity across routes. Suspense reveals animate loading handoffs. Directional slides encode navigation history. Crossfades signal content changes within the same location. + +Each pattern answers a different question for the user: + +| Pattern | What it communicates | +| ---------------------- | ------------------------------- | +| Shared element (morph) | "Same thing, going deeper" | +| Suspense reveal | "Data loaded" | +| Directional slide | "Going forward / coming back" | +| Same-route crossfade | "Same place, different content" | + +For API details and more patterns: + +- [View transition configuration](/docs/app/api-reference/config/next-config-js/viewTransition) +- [Link `transitionTypes` prop](/docs/app/api-reference/components/link#transitiontypes) +- [`useRouter`](/docs/app/api-reference/functions/use-router) — also supports `transitionTypes` in `push()` and `replace()` +- [React `ViewTransition` component](https://react.dev/reference/react/ViewTransition) +- [Complete CSS from this guide](https://github.com/vercel-labs/react-view-transitions-demo/blob/main/src/app/globals.css) — all keyframes and view transition rules in one file diff --git a/docs/01-app/03-api-reference/05-config/01-next-config-js/viewTransition.mdx b/docs/01-app/03-api-reference/05-config/01-next-config-js/viewTransition.mdx index ccbea80d46ee..4f0e1022fddd 100644 --- a/docs/01-app/03-api-reference/05-config/01-next-config-js/viewTransition.mdx +++ b/docs/01-app/03-api-reference/05-config/01-next-config-js/viewTransition.mdx @@ -4,7 +4,7 @@ description: Enable ViewTransition API from React in App Router version: experimental --- -`viewTransition` is an experimental flag that enables the new [View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API) in React. This API allows you to leverage the native View Transitions browser API to create seamless transitions between UI states. +`viewTransition` enables React's [View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API) integration in Next.js. This lets you animate navigations, loading states, and content changes using the native browser View Transitions API. To enable this feature, you need to set the `viewTransition` property to `true` in your `next.config.js` file. @@ -19,9 +19,10 @@ const nextConfig = { module.exports = nextConfig ``` -> Important Notice: The `` Component is already available in React's Canary release channel. -> `experimental.viewTransition` is only required to enable deeper integration with Next.js features e.g. automatically -> [adding Transition types](https://react.dev/reference/react/addTransitionType) for navigations. Next.js specific transition types are not implemented yet. +> [!NOTE] +> The [``](https://react.dev/reference/react/ViewTransition) component is provided by React. +> The `experimental.viewTransition` flag enables Next.js integration, such as triggering +> transitions during route navigations. ## Usage @@ -33,6 +34,6 @@ import { ViewTransition } from 'react' ### Live Demo -Check out our [Next.js View Transition Demo](https://view-transition-example.vercel.app) to see this feature in action. +Check out the [View Transitions Demo](https://react-view-transitions-demo.labs.vercel.dev) to see this feature in action, or read the [designing view transitions guide](/docs/app/guides/view-transitions) for a step-by-step walkthrough. -As this API evolves, we will update our documentation and share more examples. However, for now, we strongly advise against using this feature in production. +The View Transitions API is a baseline web standard, and browser support continues to expand. As React's [``](https://react.dev/reference/react/ViewTransition) component evolves, more transition patterns and use cases will become available. diff --git a/docs/01-app/03-api-reference/07-adapters/04-testing-adapters.mdx b/docs/01-app/03-api-reference/07-adapters/04-testing-adapters.mdx index 8ed97abfb79f..61e2223f4432 100644 --- a/docs/01-app/03-api-reference/07-adapters/04-testing-adapters.mdx +++ b/docs/01-app/03-api-reference/07-adapters/04-testing-adapters.mdx @@ -168,6 +168,9 @@ require('fs').writeFileSync('package.json',JSON.stringify(pkg,null,2)); # Set the adapter path so that the app uses it. export NEXT_ADAPTER_PATH="${ADAPTER_DIR}/dist/index.js" +# Build the app +pnpm build + # Write any metadata needed later to files in the working directory. BUILD_ID="$(cat .next/BUILD_ID)" DEPLOYMENT_ID="my-adapter-local" @@ -181,9 +184,6 @@ IMMUTABLE_ASSET_TOKEN="undefined" echo "IMMUTABLE_ASSET_TOKEN: $IMMUTABLE_ASSET_TOKEN" } >> .adapter-build.log -# Build the app -pnpm build - # Start or deploy the app. Capture the URL at this point or make the script output the URL to stdout. provider-cli-to-deploy diff --git a/docs/01-app/03-api-reference/07-adapters/05-routing-with-next-routing.mdx b/docs/01-app/03-api-reference/07-adapters/05-routing-with-next-routing.mdx index 96e722d06093..dc6dd8ff49a9 100644 --- a/docs/01-app/03-api-reference/07-adapters/05-routing-with-next-routing.mdx +++ b/docs/01-app/03-api-reference/07-adapters/05-routing-with-next-routing.mdx @@ -20,12 +20,12 @@ const pathnames = [ ].map((output) => output.pathname) const result = await resolveRoutes({ - url: requestUrl, + url: new URL(requestUrl), buildId, basePath: config.basePath || '', i18n: config.i18n, - headers: requestHeaders, - requestBody, + headers: new Headers(requestHeaders), + requestBody, // ReadableStream pathnames, routes: routing, invokeMiddleware: async (ctx) => { @@ -43,8 +43,14 @@ if (result.resolvedPathname) { `resolveRoutes()` returns: +- `middlewareResponded`: `true` when middleware already sent a response (the adapter should not invoke an entrypoint). +- `externalRewrite`: A `URL` when routing resolved to an external rewrite destination. +- `redirect`: An object with `url` (`URL`) and `status` when the request should be redirected. - `resolvedPathname`: The route pathname selected by Next.js routing. For dynamic routes, this is the matched route template such as `/blog/[slug]`. - `resolvedQuery`: The final query after rewrites or middleware have added or replaced search params. - `invocationTarget`: The concrete pathname and query to invoke for the matched route. +- `resolvedHeaders`: A `Headers` object containing any headers added or modified during routing. +- `status`: An HTTP status code set by routing (for example from a redirect or rewrite rule). +- `routeMatches`: A record of named matches extracted from dynamic route segments. For example, if `/blog/post-1?draft=1` matches `/blog/[slug]?slug=post-1`, `resolvedPathname` is `/blog/[slug]` while `invocationTarget.pathname` is `/blog/post-1`. diff --git a/docs/01-app/03-api-reference/07-adapters/09-output-types.mdx b/docs/01-app/03-api-reference/07-adapters/09-output-types.mdx index 400d17e09dfe..a463d9bed404 100644 --- a/docs/01-app/03-api-reference/07-adapters/09-output-types.mdx +++ b/docs/01-app/03-api-reference/07-adapters/09-output-types.mdx @@ -80,7 +80,7 @@ React pages from the `app/` directory: type: 'APP_PAGE' id: string // Route identifier filePath: string // Path to the built file - pathname: string // URL pathname.Includes .rsc suffix for RSC routes + pathname: string // URL pathname. Includes .rsc suffix for RSC routes sourcePage: string // Original relative source file path runtime: 'nodejs' | 'edge' // Runtime the route is built for assets: Record // Traced dependencies (key: relative path from repo root, value: absolute path) From 3b77a6e2670ce81d686111b8e466eec612fa1867 Mon Sep 17 00:00:00 2001 From: Tobias Koppers Date: Wed, 1 Apr 2026 22:25:03 +0200 Subject: [PATCH 24/76] Fix DashMap read-write self-deadlock in task_cache causing hangs (#92210) --- .../crates/turbo-tasks-backend/src/backend/mod.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs b/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs index 122e3e68b53d..c3ba1827cba3 100644 --- a/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs +++ b/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs @@ -1474,8 +1474,9 @@ impl TurboTasksBackendInner { let is_root = task_type.native_fn.is_root; // First check if the task exists in the cache which only uses a read lock - if let Some(task_id) = self.task_cache.get(&task_type) { - let task_id = *task_id; + // .map(|r| *r) copies the TaskId and drops the DashMap Ref (releasing the read lock) + // before ConnectChildOperation::run, which may re-enter task_cache with a write lock. + if let Some(task_id) = self.task_cache.get(&task_type).map(|r| *r) { self.track_cache_hit(&task_type); self.connect_child( parent_task, @@ -1564,9 +1565,10 @@ impl TurboTasksBackendInner { /* cell_id */ None, ); } - // First check if the task exists in the cache which only uses a read lock - if let Some(task_id) = self.task_cache.get(&task_type) { - let task_id = *task_id; + // First check if the task exists in the cache which only uses a read lock. + // .map(|r| *r) copies the TaskId and drops the DashMap Ref (releasing the read lock) + // before ConnectChildOperation::run, which may re-enter task_cache with a write lock. + if let Some(task_id) = self.task_cache.get(&task_type).map(|r| *r) { self.track_cache_hit(&task_type); self.connect_child( parent_task, From 356d605b5831ffbe12ce9c9641e5e2e55d203523 Mon Sep 17 00:00:00 2001 From: Tobias Koppers Date: Fri, 3 Apr 2026 10:05:17 +0200 Subject: [PATCH 25/76] turbo-tasks-backend: stability fixes for task cancellation and error handling (#92254) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bug fixes and a refactoring in `turbo-tasks-backend` targeting stability issues that surface when filesystem caching is enabled: 1. **Preserve `cell_type_max_index` on task error** — when a task fails partway through execution, `cell_counters` only reflects the partially-executed state. Previously, `cell_type_max_index` was updated from these incomplete counters, which removed entries for cell types not yet encountered. This caused `"Cell no longer exists"` hard errors for tasks that still held dependencies on those cells. The fix skips the `cell_type_max_index` update on error, keeping it consistent with the preserved cell data (which already wasn't cleared on error). This bug manifested specifically with `serialization = "hash"` cell types (e.g. `FileContent`), where cell data is transient and readers fall back to `cell_type_max_index` to decide whether to schedule recomputation. 2. **Fix shutdown hang and cache poisoning for cancelled tasks** — three related fixes for tasks cancelled during shutdown: - `task_execution_canceled` now drains and notifies all `InProgressCellState` events, preventing `stop_and_wait` from hanging on foreground jobs waiting on cells that will never be filled. - `try_read_task_cell` bails early (before calling `listen_to_cell`) when a task is in `Canceled` state, avoiding pointless listener registrations that would never resolve. - Cancelled tasks are marked as session-dependent dirty, preventing cache poisoning where `"was canceled"` errors get persisted as task output and break subsequent builds. The session-dependent dirty flag causes the task to re-execute in the next session, invalidating stale dependents. 3. **Extract `update_dirty_state` helper on `TaskGuard`** — the "read old dirty state → apply new state → propagate via `ComputeDirtyAndCleanUpdate`" pattern was duplicated between `task_execution_canceled` and `task_execution_completed_finish`. The new `update_dirty_state` default method on `TaskGuard` handles both transitions (to `SessionDependent` or to `None`) and returns the aggregation job + `ComputeDirtyAndCleanUpdateResult` for callers that need post-processing (e.g. firing the `all_clean_event`). These bugs caused observable failures when using Turbopack with filesystem caching (`--cache` / persistent cache): - `"Cell no longer exists"` panics/errors on incremental rebuilds after a task error. - Hangs on `stop_and_wait` during dev server shutdown. - Stale `"was canceled"` errors persisted in the cache breaking subsequent builds until the cache is cleared. Changes are in `turbopack/crates/turbo-tasks-backend/src/backend/`: **`mod.rs`:** - Guard the `cell_type_max_index` update block inside `if result.is_ok()` to skip it on error, with a cross-reference comment to `task_execution_completed_cleanup` (which similarly skips cell data removal on error — the two must stay in sync). - Move the `is_cancelled` bail in `try_read_task_cell` before the `listen_to_cell` call to avoid inserting phantom `InProgressCellState` events that would never be notified. - In `task_execution_canceled`: switch to `TaskDataCategory::All` (needed for dirty state metadata access), notify all pending in-progress cell events, and mark the task as `SessionDependent` dirty via the new helper. - In `task_execution_completed_finish`: replace ~77 lines of inline dirty state logic with a call to `task.update_dirty_state(new_dirtyness)`, preserving the `all_clean_event` post-processing and the `dirty_changed` variable under `#[cfg(feature = "verify_determinism")]`. **`operation/mod.rs`:** - Add `update_dirty_state` default method on `TaskGuard` trait (~60 lines), co-located with the existing `dirty_state()` reader. Takes `Option`, applies the transition, builds `ComputeDirtyAndCleanUpdate`, and returns `(Option, ComputeDirtyAndCleanUpdateResult)`. - Add `ComputeDirtyAndCleanUpdateResult` to the public re-exports. --------- Co-authored-by: Tobias Koppers Co-authored-by: Claude --- .../turbo-tasks-backend/src/backend/mod.rs | 169 ++++++++---------- .../src/backend/operation/mod.rs | 76 +++++++- 2 files changed, 145 insertions(+), 100 deletions(-) diff --git a/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs b/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs index c3ba1827cba3..edc082ffcede 100644 --- a/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs +++ b/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs @@ -55,10 +55,10 @@ use crate::{ backend::{ operation::{ AggregationUpdateJob, AggregationUpdateQueue, ChildExecuteContext, - CleanupOldEdgesOperation, ComputeDirtyAndCleanUpdate, ConnectChildOperation, - ExecuteContext, ExecuteContextImpl, LeafDistanceUpdateQueue, Operation, OutdatedEdge, - TaskGuard, TaskType, connect_children, get_aggregation_number, get_uppers, - is_root_node, make_task_dirty_internal, prepare_new_children, + CleanupOldEdgesOperation, ConnectChildOperation, ExecuteContext, ExecuteContextImpl, + LeafDistanceUpdateQueue, Operation, OutdatedEdge, TaskGuard, TaskType, + connect_children, get_aggregation_number, get_uppers, is_root_node, + make_task_dirty_internal, prepare_new_children, }, storage::Storage, storage_schema::{TaskStorage, TaskStorageAccessors}, @@ -939,7 +939,13 @@ impl TurboTasksBackendInner { } // Cell should exist, but data was dropped or is not serializable. We need to recompute the - // task the get the cell content. + // task to get the cell content. + + // Bail early if the task was cancelled — no point in registering a listener + // on a task that won't execute again. + if is_cancelled { + bail!("{} was canceled", task.get_task_description()); + } // Listen to the cell and potentially schedule the task let (listener, new_listener) = self.listen_to_cell(&mut task, task_id, &reader_task, cell); @@ -955,11 +961,6 @@ impl TurboTasksBackendInner { ) .entered(); - // Schedule the task, if not already scheduled - if is_cancelled { - bail!("{} was canceled", task.get_task_description()); - } - let _ = task.add_scheduled( TaskExecutionReason::CellNotAvailable, EventDescription::new(|| task.get_task_desc_fn()), @@ -1812,7 +1813,7 @@ impl TurboTasksBackendInner { turbo_tasks: &dyn TurboTasksBackendApi>, ) { let mut ctx = self.execute_context(turbo_tasks); - let mut task = ctx.task(task_id, TaskDataCategory::Data); + let mut task = ctx.task(task_id, TaskDataCategory::All); if let Some(in_progress) = task.take_in_progress() { match in_progress { InProgressState::Scheduled { @@ -1825,8 +1826,35 @@ impl TurboTasksBackendInner { InProgressState::Canceled => {} } } + // Notify any readers waiting on in-progress cells so their listeners + // resolve and foreground jobs can finish (prevents stop_and_wait hang). + let in_progress_cells = task.take_in_progress_cells(); + if let Some(ref cells) = in_progress_cells { + for state in cells.values() { + state.event.notify(usize::MAX); + } + } + + // Mark the cancelled task as session-dependent dirty so it will be re-executed + // in the next session. Without this, any reader that encounters the cancelled task + // records an error in its output. That error is persisted and would poison + // subsequent builds. By marking the task session-dependent dirty, the next build + // re-executes it, which invalidates dependents and corrects the stale errors. + let data_update = if self.should_track_dependencies() && !task_id.is_transient() { + task.update_dirty_state(Some(Dirtyness::SessionDependent)) + } else { + None + }; + let old = task.set_in_progress(InProgressState::Canceled); debug_assert!(old.is_none(), "InProgress already exists"); + drop(task); + + if let Some(data_update) = data_update { + AggregationUpdateQueue::run(data_update, &mut ctx); + } + + drop(in_progress_cells); } fn try_start_task_execution( @@ -2145,23 +2173,33 @@ impl TurboTasksBackendInner { } // handle cell counters: update max index and remove cells that are no longer used - let old_counters: FxHashMap<_, _> = task - .iter_cell_type_max_index() - .map(|(&k, &v)| (k, v)) - .collect(); - let mut counters_to_remove = old_counters.clone(); - - for (&cell_type, &max_index) in cell_counters.iter() { - if let Some(old_max_index) = counters_to_remove.remove(&cell_type) { - if old_max_index != max_index { + // On error, skip this update: the task may have failed before creating all cells it + // normally creates, so cell_counters is incomplete. Clearing cell_type_max_index entries + // based on partial counters would cause "cell no longer exists" errors for tasks that + // still hold dependencies on those cells. The old cell data is preserved on error + // (see task_execution_completed_cleanup), so keeping cell_type_max_index consistent with + // that data is correct. + // NOTE: This must stay in sync with task_execution_completed_cleanup, which similarly + // skips cell data removal on error. + if result.is_ok() { + let old_counters: FxHashMap<_, _> = task + .iter_cell_type_max_index() + .map(|(&k, &v)| (k, v)) + .collect(); + let mut counters_to_remove = old_counters.clone(); + + for (&cell_type, &max_index) in cell_counters.iter() { + if let Some(old_max_index) = counters_to_remove.remove(&cell_type) { + if old_max_index != max_index { + task.insert_cell_type_max_index(cell_type, max_index); + } + } else { task.insert_cell_type_max_index(cell_type, max_index); } - } else { - task.insert_cell_type_max_index(cell_type, max_index); } - } - for (cell_type, _) in counters_to_remove { - task.remove_cell_type_max_index(&cell_type); + for (cell_type, _) in counters_to_remove { + task.remove_cell_type_max_index(&cell_type); + } } let mut queue = AggregationUpdateQueue::new(); @@ -2563,82 +2601,15 @@ impl TurboTasksBackendInner { } } - // Grab the old dirty state - let old_dirtyness = task.get_dirty().cloned(); - let (old_self_dirty, old_current_session_self_clean) = match old_dirtyness { - None => (false, false), - Some(Dirtyness::Dirty(_)) => (true, false), - Some(Dirtyness::SessionDependent) => { - let clean_in_current_session = task.current_session_clean(); - (true, clean_in_current_session) - } - }; - - // Compute the new dirty state - let (new_dirtyness, new_self_dirty, new_current_session_self_clean) = if session_dependent { - (Some(Dirtyness::SessionDependent), true, true) - } else { - (None, false, false) - }; - - // Update the dirty state - let dirty_changed = old_dirtyness != new_dirtyness; - if dirty_changed { - if let Some(value) = new_dirtyness { - task.set_dirty(value); - } else if old_dirtyness.is_some() { - task.take_dirty(); - } - } - if old_current_session_self_clean != new_current_session_self_clean { - if new_current_session_self_clean { - task.set_current_session_clean(true); - } else if old_current_session_self_clean { - task.set_current_session_clean(false); - } - } - - // Propagate dirtyness changes - let data_update = if old_self_dirty != new_self_dirty - || old_current_session_self_clean != new_current_session_self_clean - { - let dirty_container_count = task - .get_aggregated_dirty_container_count() - .cloned() - .unwrap_or_default(); - let current_session_clean_container_count = task - .get_aggregated_current_session_clean_container_count() - .copied() - .unwrap_or_default(); - let result = ComputeDirtyAndCleanUpdate { - old_dirty_container_count: dirty_container_count, - new_dirty_container_count: dirty_container_count, - old_current_session_clean_container_count: current_session_clean_container_count, - new_current_session_clean_container_count: current_session_clean_container_count, - old_self_dirty, - new_self_dirty, - old_current_session_self_clean, - new_current_session_self_clean, - } - .compute(); - if result.dirty_count_update - result.current_session_clean_update < 0 { - // The task is clean now - if let Some(activeness_state) = task.get_activeness_mut() { - activeness_state.all_clean_event.notify(usize::MAX); - activeness_state.unset_active_until_clean(); - if activeness_state.is_empty() { - task.take_activeness(); - } - } - } - result - .aggregated_update(task_id) - .and_then(|aggregated_update| { - AggregationUpdateJob::data_update(&mut task, aggregated_update) - }) + // Compute and apply the new dirty state, propagating to aggregating ancestors + let new_dirtyness = if session_dependent { + Some(Dirtyness::SessionDependent) } else { None }; + #[cfg(feature = "verify_determinism")] + let dirty_changed = task.get_dirty().cloned() != new_dirtyness; + let data_update = task.update_dirty_state(new_dirtyness); #[cfg(feature = "verify_determinism")] let reschedule = @@ -2681,6 +2652,8 @@ impl TurboTasksBackendInner { // An error is potentially caused by a eventual consistency, so we avoid updating cells // after an error as it is likely transient and we want to keep the dependent tasks // clean to avoid re-executions. + // NOTE: This must stay in sync with task_execution_completed_prepare, which similarly + // skips cell_type_max_index updates on error. if !is_error { // Remove no longer existing cells and // find all outdated data items (removed cells, outdated edges) diff --git a/turbopack/crates/turbo-tasks-backend/src/backend/operation/mod.rs b/turbopack/crates/turbo-tasks-backend/src/backend/operation/mod.rs index 52d836ce21d9..7d58be4d773d 100644 --- a/turbopack/crates/turbo-tasks-backend/src/backend/operation/mod.rs +++ b/turbopack/crates/turbo-tasks-backend/src/backend/operation/mod.rs @@ -18,6 +18,7 @@ use turbo_tasks::{ TurboTasksCallApi, TypedSharedReference, backend::CachedTaskType, }; +use self::aggregation_update::ComputeDirtyAndCleanUpdate; use crate::{ backend::{ EventDescription, OperationGuard, TaskDataCategory, TurboTasksBackend, @@ -764,6 +765,77 @@ pub trait TaskGuard: Debug + TaskStorageAccessors { Some(Dirtyness::SessionDependent) => (true, self.current_session_clean()), } } + /// Update the task's dirty state to `new_dirtyness`, applying the change to stored fields, + /// computing the aggregated propagation update, and firing the `all_clean_event` if the task + /// transitioned to clean. + /// + /// Returns an optional `AggregationUpdateJob` that the caller must run via + /// `AggregationUpdateQueue::run` to propagate the change to aggregating ancestors. + fn update_dirty_state( + &mut self, + new_dirtyness: Option, + ) -> Option + where + Self: Sized, + { + let task_id = self.id(); + let old_dirtyness = self.get_dirty().cloned(); + let (old_self_dirty, old_current_session_self_clean) = self.dirty_state(); + let (new_self_dirty, new_current_session_self_clean) = match new_dirtyness { + None => (false, false), + Some(Dirtyness::Dirty(_)) => (true, false), + Some(Dirtyness::SessionDependent) => (true, true), + }; + if old_dirtyness != new_dirtyness { + if let Some(value) = new_dirtyness { + self.set_dirty(value); + } else { + self.take_dirty(); + } + } + if old_current_session_self_clean != new_current_session_self_clean { + self.set_current_session_clean(new_current_session_self_clean); + } + if old_self_dirty == new_self_dirty + && old_current_session_self_clean == new_current_session_self_clean + { + return None; + } + let dirty_container_count = self + .get_aggregated_dirty_container_count() + .cloned() + .unwrap_or_default(); + let current_session_clean_container_count = self + .get_aggregated_current_session_clean_container_count() + .copied() + .unwrap_or_default(); + let result = ComputeDirtyAndCleanUpdate { + old_dirty_container_count: dirty_container_count, + new_dirty_container_count: dirty_container_count, + old_current_session_clean_container_count: current_session_clean_container_count, + new_current_session_clean_container_count: current_session_clean_container_count, + old_self_dirty, + new_self_dirty, + old_current_session_self_clean, + new_current_session_self_clean, + } + .compute(); + // Fire the all_clean_event if the task transitioned to clean + if result.dirty_count_update - result.current_session_clean_update < 0 + && let Some(activeness_state) = self.get_activeness_mut() + { + activeness_state.all_clean_event.notify(usize::MAX); + activeness_state.unset_active_until_clean(); + if activeness_state.is_empty() { + self.take_activeness(); + } + } + result + .aggregated_update(task_id) + .and_then(|aggregated_update| { + AggregationUpdateJob::data_update(self, aggregated_update) + }) + } fn dirty_containers(&self) -> impl Iterator { self.dirty_containers_with_count() .map(|(task_id, _)| task_id) @@ -1106,8 +1178,8 @@ impl_operation!(LeafDistanceUpdate leaf_distance_update::LeafDistanceUpdateQueue pub use self::invalidate::TaskDirtyCause; pub use self::{ aggregation_update::{ - AggregatedDataUpdate, AggregationUpdateJob, ComputeDirtyAndCleanUpdate, - get_aggregation_number, get_uppers, is_aggregating_node, is_root_node, + AggregatedDataUpdate, AggregationUpdateJob, get_aggregation_number, get_uppers, + is_aggregating_node, is_root_node, }, cleanup_old_edges::OutdatedEdge, connect_children::connect_children, From f158df18bd926d0c2165ad309bbb561d7e73e74a Mon Sep 17 00:00:00 2001 From: Tobias Koppers Date: Tue, 7 Apr 2026 17:02:37 +0200 Subject: [PATCH 26/76] Fix styled-jsx race condition: styles lost due to concurrent rendering (#92459) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### What? Fix a race condition in the Pages Router SSR path where styled-jsx styles were dropped from the rendered HTML. ### Why? `styledJsxInsertedHTML()` reads and flushes the styled-jsx style registry. Previously it was called concurrently with the page render via `Promise.all`: ```js const [rawStyledJsxInsertedHTML, content] = await Promise.all([ renderToString(styledJsxInsertedHTML()), (async () => { /* render the page */ })(), ]) ``` Because both ran at the same time, `styledJsxInsertedHTML()` could (and in practice did) execute and flush the registry **before** the page render had finished populating it. The result was that dynamic styled-jsx styles — those with interpolated expressions that compute their class names at runtime via DJB2 hashing — were silently dropped from the SSR output, causing a flash of unstyled content on first load. This is particularly visible in production deployments where all components use dynamic styled-jsx (numeric `jsx-*` class names), since those styles only exist in the registry after rendering completes. ### How? Serialize the two operations: render the page first, then call `styledJsxInsertedHTML()`. Since the registry is fully populated by the time it is read, all styles are captured correctly. A new e2e test (`test/e2e/styled-jsx-dynamic`) exercises this scenario with multiple nested components that all use dynamic styled-jsx with interpolated props, covering the exact FOUC pattern seen in production. Co-authored-by: Tobias Koppers Co-authored-by: Claude --- packages/next/src/server/render.tsx | 46 ++++++++++--------- .../components/DynamicStyled.js | 12 +++++ .../styled-jsx-dynamic/components/Footer.js | 13 ++++++ .../styled-jsx-dynamic/components/Header.js | 14 ++++++ test/e2e/styled-jsx-dynamic/index.test.ts | 27 +++++++++++ test/e2e/styled-jsx-dynamic/pages/index.js | 28 +++++++++++ 6 files changed, 119 insertions(+), 21 deletions(-) create mode 100644 test/e2e/styled-jsx-dynamic/components/DynamicStyled.js create mode 100644 test/e2e/styled-jsx-dynamic/components/Footer.js create mode 100644 test/e2e/styled-jsx-dynamic/components/Header.js create mode 100644 test/e2e/styled-jsx-dynamic/index.test.ts create mode 100644 test/e2e/styled-jsx-dynamic/pages/index.js diff --git a/packages/next/src/server/render.tsx b/packages/next/src/server/render.tsx index 872927b8d787..fdff082e4374 100644 --- a/packages/next/src/server/render.tsx +++ b/packages/next/src/server/render.tsx @@ -1385,29 +1385,22 @@ export async function renderToHTMLImpl( | {} | Awaited> - const [rawStyledJsxInsertedHTML, content] = await Promise.all([ - renderToString(styledJsxInsertedHTML()), - (async () => { - if (hasDocumentGetInitialProps) { - documentInitialPropsRes = await loadDocumentInitialProps(renderShell) - if (documentInitialPropsRes === null) return null - const { docProps } = documentInitialPropsRes as any - return docProps.html - } else { - documentInitialPropsRes = {} - const stream = await renderShell(App, Component) - await stream.allReady - return streamToString(stream) - } - })(), - ]) - - if (content === null) { - return null + let content: string | null + if (hasDocumentGetInitialProps) { + documentInitialPropsRes = await loadDocumentInitialProps(renderShell) + if (documentInitialPropsRes === null) { + content = null + } else { + const { docProps } = documentInitialPropsRes as any + content = docProps.html + } + } else { + documentInitialPropsRes = {} + const stream = await renderShell(App, Component) + await stream.allReady + content = await streamToString(stream) } - const contentHTML = rawStyledJsxInsertedHTML + content - // @ts-ignore: documentInitialPropsRes is set const { docProps } = (documentInitialPropsRes as any) || {} const documentElement = (htmlProps: any) => { @@ -1427,6 +1420,17 @@ export async function renderToHTMLImpl( jsxStyleRegistry.flush() } + // Registry is now flushed; rawStyledJsxInsertedHTML will be empty. + const rawStyledJsxInsertedHTML = await renderToString( + styledJsxInsertedHTML() + ) + + if (content === null) { + return null + } + + const contentHTML = rawStyledJsxInsertedHTML + content + return { contentHTML, documentElement, diff --git a/test/e2e/styled-jsx-dynamic/components/DynamicStyled.js b/test/e2e/styled-jsx-dynamic/components/DynamicStyled.js new file mode 100644 index 000000000000..60756a0b9e16 --- /dev/null +++ b/test/e2e/styled-jsx-dynamic/components/DynamicStyled.js @@ -0,0 +1,12 @@ +export default function DynamicStyled({ color }) { + return ( +
+ +

dynamic styled

+
+ ) +} diff --git a/test/e2e/styled-jsx-dynamic/components/Footer.js b/test/e2e/styled-jsx-dynamic/components/Footer.js new file mode 100644 index 000000000000..037de0a33603 --- /dev/null +++ b/test/e2e/styled-jsx-dynamic/components/Footer.js @@ -0,0 +1,13 @@ +export default function Footer({ color }) { + return ( +
+ + Footer +
+ ) +} diff --git a/test/e2e/styled-jsx-dynamic/components/Header.js b/test/e2e/styled-jsx-dynamic/components/Header.js new file mode 100644 index 000000000000..48e90ecc0ae2 --- /dev/null +++ b/test/e2e/styled-jsx-dynamic/components/Header.js @@ -0,0 +1,14 @@ +export default function Header({ bg, fg }) { + return ( +
+ + Header +
+ ) +} diff --git a/test/e2e/styled-jsx-dynamic/index.test.ts b/test/e2e/styled-jsx-dynamic/index.test.ts new file mode 100644 index 000000000000..adbd235b296a --- /dev/null +++ b/test/e2e/styled-jsx-dynamic/index.test.ts @@ -0,0 +1,27 @@ +import { nextTestSetup } from 'e2e-utils' + +describe('styled-jsx dynamic styles SSR', () => { + const { next } = nextTestSetup({ + files: __dirname, + skipDeployment: true, + }) + + // Dynamic styled-jsx (with interpolated expressions) produces numeric class + // names at runtime via the DJB2 hash in styled-jsx's computeId function. + // This pattern matches production deployments where all jsx class names + // are numeric (e.g. jsx-2267428885) rather than hex (jsx-f36313d9f07883b7). + it('should contain dynamic styled-jsx styles during SSR', async () => { + const html = await next.render('/') + + // Dynamic styled-jsx produces numeric class names at runtime + const numericClasses = html.match(/\bjsx-\d+\b/g) || [] + console.log('Numeric jsx classes:', [...new Set(numericClasses)]) + expect(numericClasses.length).toBeGreaterThan(0) + + // All dynamic styles should be present as inline +
+
+ +
+