diff --git a/.cargo/config.toml b/.cargo/config.toml index fd2e766d5e4c9..48a22abd2166d 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -35,8 +35,4 @@ rustflags = [ "-Zshare-generics=y", "-Csymbol-mangling-version=v0", "-Aclippy::too_many_arguments", - # Clippy's needless mut lint is buggy: https://github.com/rust-lang/rust-clippy/issues/11299 - "-Aclippy::needless_pass_by_ref_mut", - # Clippy's partial_eq lint is buggy: https://github.com/rust-lang/rust-clippy/issues/11178 - "-Aclippy::non_canonical_partial_ord_impl", ] diff --git a/.eslintrc.json b/.eslintrc.json index feb49b2ecbbff..4dfa939d385d4 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -213,6 +213,18 @@ ], "eslint-plugin/require-meta-docs-url": "error" } + }, + { + "files": ["packages/**/*.tsx", "packages/**/*.ts"], + "rules": { + "@typescript-eslint/consistent-type-imports": [ + "error", + { + "disallowTypeAnnotations": false + } + ], + "@typescript-eslint/no-import-type-side-effects": "error" + } } ], "rules": { diff --git a/.github/actions/next-stats-action/src/prepare/repo-setup.js b/.github/actions/next-stats-action/src/prepare/repo-setup.js index 660a6f4a0b012..74fd6ea1fc925 100644 --- a/.github/actions/next-stats-action/src/prepare/repo-setup.js +++ b/.github/actions/next-stats-action/src/prepare/repo-setup.js @@ -1,5 +1,7 @@ const path = require('path') -const fs = require('fs-extra') +const fse = require('fs-extra') +const fs = require('fs') +const fsp = require('fs/promises') const exec = require('../util/exec') const { remove } = require('fs-extra') const logger = require('../util/logger') @@ -54,11 +56,23 @@ module.exports = (actionInfo) => { }, async linkPackages({ repoDir, nextSwcVersion }) { const pkgPaths = new Map() + + /** + * @typedef {Object} PkgData + * @property {string} pkgDataPath Where the package.json file is located + * @property {string} pkg The folder name of the package + * @property {string} pkgPath The path to the package folder + * @property {any} pkgData The content of package.json + * @property {string} packedPkgPath The npm pack output .tgz file path + */ + + /** @type {Map} */ const pkgDatas = new Map() + let pkgs try { - pkgs = await fs.readdir(path.join(repoDir, 'packages')) + pkgs = await fsp.readdir(path.join(repoDir, 'packages')) } catch (err) { if (err.code === 'ENOENT') { require('console').log('no packages to link') @@ -67,69 +81,81 @@ module.exports = (actionInfo) => { throw err } - for (const pkg of pkgs) { - const pkgPath = path.join(repoDir, 'packages', pkg) - const packedPkgPath = path.join(pkgPath, `${pkg}-packed.tgz`) - - const pkgDataPath = path.join(pkgPath, 'package.json') - if (!fs.existsSync(pkgDataPath)) { - require('console').log(`Skipping ${pkgDataPath}`) - continue - } - const pkgData = require(pkgDataPath) - const { name } = pkgData - - pkgDatas.set(name, { - pkgDataPath, - pkg, - pkgPath, - pkgData, - packedPkgPath, + await Promise.all( + pkgs.map(async (pkg) => { + const pkgPath = path.join(repoDir, 'packages', pkg) + const packedPkgPath = path.join(pkgPath, `${pkg}-packed.tgz`) + + const pkgDataPath = path.join(pkgPath, 'package.json') + if (fs.existsSync(pkgDataPath)) { + const pkgData = JSON.parse(await fsp.readFile(pkgDataPath)) + const { name } = pkgData + + pkgDatas.set(name, { + pkgDataPath, + pkg, + pkgPath, + pkgData, + packedPkgPath, + }) + pkgPaths.set(name, packedPkgPath) + } else { + require('console').log(`Skipping ${pkgDataPath}`) + } }) - pkgPaths.set(name, packedPkgPath) - } - - for (const pkg of pkgDatas.keys()) { - const { pkgDataPath, pkgData } = pkgDatas.get(pkg) + ) - for (const pkg of pkgDatas.keys()) { - const { packedPkgPath } = pkgDatas.get(pkg) + for (const [ + pkg, + { pkgDataPath, pkgData, pkgPath }, + ] of pkgDatas.entries()) { + // update the current package dependencies to point to packed tgz path + for (const [pkg, { packedPkgPath }] of pkgDatas.entries()) { if (!pkgData.dependencies || !pkgData.dependencies[pkg]) continue pkgData.dependencies[pkg] = packedPkgPath } // make sure native binaries are included in local linking if (pkg === '@next/swc') { - if (!pkgData.files) { - pkgData.files = [] - } + pkgData.files ||= [] + pkgData.files.push('native') - require('console').log( - 'using swc binaries: ', - await exec(`ls ${path.join(path.dirname(pkgDataPath), 'native')}`) - ) - } - if (pkg === 'next') { + try { + const swcBinariesDirContents = await fsp.readdir( + path.join(pkgPath, 'native') + ) + require('console').log( + 'using swc binaries: ', + swcBinariesDirContents.join(', ') + ) + } catch (err) { + if (err.code === 'ENOENT') { + require('console').log('swc binaries dir is missing!') + } + throw err + } + } else if (pkg === 'next') { + const nextSwcPkg = pkgDatas.get('@next/swc') + console.log('using swc dep', { nextSwcVersion, - nextSwcPkg: pkgDatas.get('@next/swc'), + nextSwcPkg, }) if (nextSwcVersion) { Object.assign(pkgData.dependencies, { '@next/swc-linux-x64-gnu': nextSwcVersion, }) } else { - if (pkgDatas.get('@next/swc')) { - pkgData.dependencies['@next/swc'] = - pkgDatas.get('@next/swc').packedPkgPath + if (nextSwcPkg) { + pkgData.dependencies['@next/swc'] = nextSwcPkg.packedPkgPath } else { pkgData.files.push('native') } } } - await fs.writeFile( + await fsp.writeFile( pkgDataPath, JSON.stringify(pkgData, null, 2), 'utf8' @@ -139,41 +165,47 @@ module.exports = (actionInfo) => { // wait to pack packages until after dependency paths have been updated // to the correct versions await Promise.all( - Array.from(pkgDatas.keys()).map(async (pkgName) => { - const { pkgPath, packedPkgPath } = pkgDatas.get(pkgName) - - let cleanup = null - - if (pkgName === '@next/swc') { - // next-swc uses a gitignore to prevent the committing of native builds but it doesn't - // use files in package.json because it publishes to individual packages based on architecture. - // When we used yarn to pack these packages the gitignore was ignored so the native builds were packed - // however npm does respect gitignore when packing so we need to remove it in this specific case - // to ensure the native builds are packed for use in gh actions and related scripts - await fs.rename( - path.join(pkgPath, 'native/.gitignore'), - path.join(pkgPath, 'disabled-native-gitignore') - ) - cleanup = async () => { - await fs.rename( - path.join(pkgPath, 'disabled-native-gitignore'), - path.join(pkgPath, 'native/.gitignore') + Array.from(pkgDatas.entries()).map( + async ([pkgName, { pkgPath, packedPkgPath }]) => { + /** @type {null | () => Promise} */ + let cleanup = null + + if (pkgName === '@next/swc') { + // next-swc uses a gitignore to prevent the committing of native builds but it doesn't + // use files in package.json because it publishes to individual packages based on architecture. + // When we used yarn to pack these packages the gitignore was ignored so the native builds were packed + // however npm does respect gitignore when packing so we need to remove it in this specific case + // to ensure the native builds are packed for use in gh actions and related scripts + + const nativeGitignorePath = path.join( + pkgPath, + 'native/.gitignore' + ) + const renamedGitignorePath = path.join( + pkgPath, + 'disabled-native-gitignore' ) + + await fsp.rename(nativeGitignorePath, renamedGitignorePath) + cleanup = async () => { + await fsp.rename(renamedGitignorePath, nativeGitignorePath) + } } - } - const { stdout } = await execa('npm', ['pack'], { - cwd: pkgPath, - env: { - ...process.env, - COREPACK_ENABLE_STRICT: '0', - }, - }) - await fs.rename(path.resolve(pkgPath, stdout.trim()), packedPkgPath) - if (cleanup) { - await cleanup() + const { stdout } = await execa('pnpm', ['pack'], { + cwd: pkgPath, + env: { + ...process.env, + COREPACK_ENABLE_STRICT: '0', + }, + }) + + return Promise.all([ + fsp.rename(path.resolve(pkgPath, stdout.trim()), packedPkgPath), + cleanup?.(), + ]) } - }) + ) ) return pkgPaths }, diff --git a/.github/workflows/build_and_deploy.yml b/.github/workflows/build_and_deploy.yml index 44798960f3a69..93648a7ae05c5 100644 --- a/.github/workflows/build_and_deploy.yml +++ b/.github/workflows/build_and_deploy.yml @@ -254,6 +254,7 @@ jobs: with: node-version: ${{ env.NODE_LTS_VERSION }} check-latest: true + - run: corepack enable - name: Install Rust uses: ./.github/actions/setup-rust diff --git a/.github/workflows/build_and_test.yml b/.github/workflows/build_and_test.yml index 9b18c42aa0ec8..1f4d50d639ed3 100644 --- a/.github/workflows/build_and_test.yml +++ b/.github/workflows/build_and_test.yml @@ -58,6 +58,7 @@ jobs: - uses: actions/setup-node@v3 with: node-version: 18 + - run: corepack enable - name: 'Run link checker' run: node ./.github/actions/validate-docs-links/lib env: diff --git a/.github/workflows/code_freeze.yml b/.github/workflows/code_freeze.yml index 513390827cc88..3c4c8b23f6bf4 100644 --- a/.github/workflows/code_freeze.yml +++ b/.github/workflows/code_freeze.yml @@ -32,6 +32,7 @@ jobs: with: node-version: 18 check-latest: true + - run: corepack enable - run: git clone https://github.com/vercel/next.js.git --depth=1 . diff --git a/.github/workflows/pull_request_approved.yml b/.github/workflows/pull_request_approved.yml index 4dec0271a80d6..77519be02f1a6 100644 --- a/.github/workflows/pull_request_approved.yml +++ b/.github/workflows/pull_request_approved.yml @@ -14,6 +14,7 @@ jobs: - uses: actions/setup-node@v3 with: node-version: 18 + - run: corepack enable - name: 'Send notification to Slack' run: node ./.github/actions/pr-approved-open/index.mjs env: diff --git a/Cargo.lock b/Cargo.lock index 9691bd3826777..4bfb6d1d07ea9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -289,9 +289,9 @@ dependencies = [ [[package]] name = "async-trait" -version = "0.1.68" +version = "0.1.73" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ccdd8f2a161be9bd5c023df56f1b2a0bd1d83872ae53b71a84a12c9bf6e842" +checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" dependencies = [ "proc-macro2", "quote", @@ -321,7 +321,7 @@ dependencies = [ [[package]] name = "auto-hash-map" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "serde", "smallvec", @@ -3515,7 +3515,7 @@ dependencies = [ [[package]] name = "node-file-trace" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "serde", @@ -7368,7 +7368,7 @@ dependencies = [ [[package]] name = "turbo-tasks" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "async-trait", @@ -7400,7 +7400,7 @@ dependencies = [ [[package]] name = "turbo-tasks-build" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "cargo-lock", @@ -7412,7 +7412,7 @@ dependencies = [ [[package]] name = "turbo-tasks-bytes" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "bytes", @@ -7427,7 +7427,7 @@ dependencies = [ [[package]] name = "turbo-tasks-env" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "dotenvs", @@ -7441,7 +7441,7 @@ dependencies = [ [[package]] name = "turbo-tasks-fetch" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "indexmap 1.9.3", @@ -7458,7 +7458,7 @@ dependencies = [ [[package]] name = "turbo-tasks-fs" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "auto-hash-map", @@ -7488,7 +7488,7 @@ dependencies = [ [[package]] name = "turbo-tasks-hash" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "base16", "hex", @@ -7500,7 +7500,7 @@ dependencies = [ [[package]] name = "turbo-tasks-macros" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -7514,7 +7514,7 @@ dependencies = [ [[package]] name = "turbo-tasks-macros-shared" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "proc-macro2", "quote", @@ -7524,7 +7524,7 @@ dependencies = [ [[package]] name = "turbo-tasks-malloc" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "mimalloc", ] @@ -7532,7 +7532,7 @@ dependencies = [ [[package]] name = "turbo-tasks-memory" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "auto-hash-map", @@ -7557,7 +7557,7 @@ dependencies = [ [[package]] name = "turbopack" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "async-recursion", @@ -7588,7 +7588,7 @@ dependencies = [ [[package]] name = "turbopack-binding" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "auto-hash-map", "mdxjs", @@ -7628,7 +7628,7 @@ dependencies = [ [[package]] name = "turbopack-build" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "indexmap 1.9.3", @@ -7650,7 +7650,7 @@ dependencies = [ [[package]] name = "turbopack-cli-utils" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "clap 4.4.2", @@ -7674,7 +7674,7 @@ dependencies = [ [[package]] name = "turbopack-core" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "async-recursion", @@ -7703,7 +7703,7 @@ dependencies = [ [[package]] name = "turbopack-css" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "async-trait", @@ -7725,7 +7725,7 @@ dependencies = [ [[package]] name = "turbopack-dev" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "indexmap 1.9.3", @@ -7749,7 +7749,7 @@ dependencies = [ [[package]] name = "turbopack-dev-server" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "async-compression", @@ -7786,7 +7786,7 @@ dependencies = [ [[package]] name = "turbopack-ecmascript" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "async-trait", @@ -7820,7 +7820,7 @@ dependencies = [ [[package]] name = "turbopack-ecmascript-hmr-protocol" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "serde", "serde_json", @@ -7831,7 +7831,7 @@ dependencies = [ [[package]] name = "turbopack-ecmascript-plugins" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "async-trait", @@ -7854,7 +7854,7 @@ dependencies = [ [[package]] name = "turbopack-ecmascript-runtime" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "indoc", @@ -7871,7 +7871,7 @@ dependencies = [ [[package]] name = "turbopack-env" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "indexmap 1.9.3", @@ -7887,7 +7887,7 @@ dependencies = [ [[package]] name = "turbopack-image" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "base64 0.21.4", @@ -7907,7 +7907,7 @@ dependencies = [ [[package]] name = "turbopack-json" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "serde", @@ -7922,7 +7922,7 @@ dependencies = [ [[package]] name = "turbopack-mdx" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "mdxjs", @@ -7937,7 +7937,7 @@ dependencies = [ [[package]] name = "turbopack-node" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "async-stream", @@ -7972,7 +7972,7 @@ dependencies = [ [[package]] name = "turbopack-static" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "serde", @@ -7988,7 +7988,7 @@ dependencies = [ [[package]] name = "turbopack-swc-utils" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "swc_core", "turbo-tasks", @@ -7999,7 +7999,7 @@ dependencies = [ [[package]] name = "turbopack-wasm" version = "0.1.0" -source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231005.2#2207c3eb716b81c719385e43d25d7399f673fc11" +source = "git+https://github.com/vercel/turbo.git?tag=turbopack-231006.4#8439948663a049728a48386cf4791693e264260e" dependencies = [ "anyhow", "indexmap 1.9.3", diff --git a/Cargo.toml b/Cargo.toml index 6bd1c3e771296..173a6453b4167 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,11 +40,11 @@ swc_core = { version = "0.83.28", features = [ testing = { version = "0.34.1" } # Turbo crates -turbopack-binding = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-231005.2" } +turbopack-binding = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-231006.4" } # [TODO]: need to refactor embed_directory! macro usages, as well as resolving turbo_tasks::function, macros.. -turbo-tasks = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-231005.2" } +turbo-tasks = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-231006.4" } # [TODO]: need to refactor embed_directory! macro usage in next-core -turbo-tasks-fs = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-231005.2" } +turbo-tasks-fs = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-231006.4" } # General Deps diff --git a/docs/02-app/01-building-your-application/02-data-fetching/01-fetching-caching-and-revalidating.mdx b/docs/02-app/01-building-your-application/02-data-fetching/01-fetching-caching-and-revalidating.mdx index e364b27828158..f73228c63590a 100644 --- a/docs/02-app/01-building-your-application/02-data-fetching/01-fetching-caching-and-revalidating.mdx +++ b/docs/02-app/01-building-your-application/02-data-fetching/01-fetching-caching-and-revalidating.mdx @@ -310,7 +310,7 @@ export const getItem = cache(async (id) => { Although the `getItem` function is called twice, only one query will be made to the database. -```tsx filename="app/item/layout.tsx" switcher +```tsx filename="app/item/[id]/layout.tsx" switcher import { getItem } from '@/utils/get-item' export default async function Layout({ @@ -323,7 +323,7 @@ export default async function Layout({ } ``` -```jsx filename="app/item/layout.js" switcher +```jsx filename="app/item/[id]/layout.js" switcher import { getItem } from '@/utils/get-item' export default async function Layout({ params: { id } }) { diff --git a/docs/02-app/01-building-your-application/03-rendering/02-client-components.mdx b/docs/02-app/01-building-your-application/03-rendering/02-client-components.mdx index 08312aef99492..1cc7fc2a15761 100644 --- a/docs/02-app/01-building-your-application/03-rendering/02-client-components.mdx +++ b/docs/02-app/01-building-your-application/03-rendering/02-client-components.mdx @@ -91,7 +91,7 @@ Then, on the client: > **What is hydration?** > -> Hydration is process of attaching event listeners to the DOM, to make the static HTML interactive. Behind the scenes, hydration is done with the [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot) React API. +> Hydration is the process of attaching event listeners to the DOM, to make the static HTML interactive. Behind the scenes, hydration is done with the [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot) React API. ### Subsequent Navigations diff --git a/lerna.json b/lerna.json index b4ff2eda07dcf..ad3fab982201e 100644 --- a/lerna.json +++ b/lerna.json @@ -16,5 +16,5 @@ "registry": "https://registry.npmjs.org/" } }, - "version": "13.5.5-canary.2" + "version": "13.5.5-canary.4" } diff --git a/package.json b/package.json index 6cd4a3dac6c6f..b0c41f67309df 100644 --- a/package.json +++ b/package.json @@ -199,7 +199,7 @@ "react-dom-experimental-builtin": "npm:react-dom@0.0.0-experimental-d900fadbf-20230929", "react-experimental-builtin": "npm:react@0.0.0-experimental-d900fadbf-20230929", "react-server-dom-turbopack": "18.3.0-canary-d900fadbf-20230929", - "react-server-dom-turbopack-experimental": "npm:react-server-dom-webpack@0.0.0-experimental-d900fadbf-20230929", + "react-server-dom-turbopack-experimental": "npm:react-server-dom-turbopack@0.0.0-experimental-d900fadbf-20230929", "react-server-dom-webpack": "18.3.0-canary-d900fadbf-20230929", "react-server-dom-webpack-experimental": "npm:react-server-dom-webpack@0.0.0-experimental-d900fadbf-20230929", "react-ssr-prepass": "1.0.8", diff --git a/packages/create-next-app/create-app.ts b/packages/create-next-app/create-app.ts index 23d0c1419edfb..89719e48ad473 100644 --- a/packages/create-next-app/create-app.ts +++ b/packages/create-next-app/create-app.ts @@ -3,13 +3,13 @@ import retry from 'async-retry' import { red, green, cyan } from 'picocolors' import fs from 'fs' import path from 'path' +import type { RepoInfo } from './helpers/examples' import { downloadAndExtractExample, downloadAndExtractRepo, getRepoInfo, existsInRepo, hasRepo, - RepoInfo, } from './helpers/examples' import { makeDir } from './helpers/make-dir' import { tryGitInit } from './helpers/git' @@ -19,12 +19,8 @@ import { getOnline } from './helpers/is-online' import { isWriteable } from './helpers/is-writeable' import type { PackageManager } from './helpers/get-pkg-manager' -import { - getTemplateFile, - installTemplate, - TemplateMode, - TemplateType, -} from './templates' +import type { TemplateMode, TemplateType } from './templates' +import { getTemplateFile, installTemplate } from './templates' export class DownloadError extends Error {} diff --git a/packages/create-next-app/package.json b/packages/create-next-app/package.json index 1ca01794a8ee1..4badb4015965f 100644 --- a/packages/create-next-app/package.json +++ b/packages/create-next-app/package.json @@ -1,6 +1,6 @@ { "name": "create-next-app", - "version": "13.5.5-canary.2", + "version": "13.5.5-canary.4", "keywords": [ "react", "next", diff --git a/packages/eslint-config-next/package.json b/packages/eslint-config-next/package.json index ab5cafb81e28c..d349a1c12e24f 100644 --- a/packages/eslint-config-next/package.json +++ b/packages/eslint-config-next/package.json @@ -1,6 +1,6 @@ { "name": "eslint-config-next", - "version": "13.5.5-canary.2", + "version": "13.5.5-canary.4", "description": "ESLint configuration used by Next.js.", "main": "index.js", "license": "MIT", @@ -10,7 +10,7 @@ }, "homepage": "https://nextjs.org/docs/app/building-your-application/configuring/eslint#eslint-config", "dependencies": { - "@next/eslint-plugin-next": "13.5.5-canary.2", + "@next/eslint-plugin-next": "13.5.5-canary.4", "@rushstack/eslint-patch": "^1.3.3", "@typescript-eslint/parser": "^5.4.2 || ^6.0.0", "eslint-import-resolver-node": "^0.3.6", diff --git a/packages/eslint-plugin-next/package.json b/packages/eslint-plugin-next/package.json index d37cf3822c4f9..b92d5a8596f42 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": "13.5.5-canary.2", + "version": "13.5.5-canary.4", "description": "ESLint plugin for Next.js.", "main": "dist/index.js", "license": "MIT", diff --git a/packages/font/package.json b/packages/font/package.json index e8dac1caf89d8..856f0a79da3eb 100644 --- a/packages/font/package.json +++ b/packages/font/package.json @@ -1,6 +1,6 @@ { "name": "@next/font", - "version": "13.5.5-canary.2", + "version": "13.5.5-canary.4", "repository": { "url": "vercel/next.js", "directory": "packages/font" diff --git a/packages/font/src/google/get-proxy-agent.ts b/packages/font/src/google/get-proxy-agent.ts index 9095a6f5a12f8..eb2db1b21fa34 100644 --- a/packages/font/src/google/get-proxy-agent.ts +++ b/packages/font/src/google/get-proxy-agent.ts @@ -2,7 +2,7 @@ import HttpsProxyAgent from 'next/dist/compiled/https-proxy-agent' // @ts-ignore import HttpProxyAgent from 'next/dist/compiled/http-proxy-agent' -import { Agent } from 'https' +import type { Agent } from 'https' /** * If the http(s)_proxy environment variables is set, return a proxy agent. diff --git a/packages/next-bundle-analyzer/package.json b/packages/next-bundle-analyzer/package.json index 44ac0d40b40ac..8a557e3557a4f 100644 --- a/packages/next-bundle-analyzer/package.json +++ b/packages/next-bundle-analyzer/package.json @@ -1,6 +1,6 @@ { "name": "@next/bundle-analyzer", - "version": "13.5.5-canary.2", + "version": "13.5.5-canary.4", "main": "index.js", "types": "index.d.ts", "license": "MIT", diff --git a/packages/next-codemod/lib/cra-to-next/global-css-transform.ts b/packages/next-codemod/lib/cra-to-next/global-css-transform.ts index 6687194e64d57..46b539b1ff9e8 100644 --- a/packages/next-codemod/lib/cra-to-next/global-css-transform.ts +++ b/packages/next-codemod/lib/cra-to-next/global-css-transform.ts @@ -1,5 +1,5 @@ import nodePath from 'path' -import { API, FileInfo, Options } from 'jscodeshift' +import type { API, FileInfo, Options } from 'jscodeshift' export const globalCssContext = { cssImports: new Set(), diff --git a/packages/next-codemod/lib/cra-to-next/index-to-component.ts b/packages/next-codemod/lib/cra-to-next/index-to-component.ts index cb66d61f873be..bcb15b2941d4d 100644 --- a/packages/next-codemod/lib/cra-to-next/index-to-component.ts +++ b/packages/next-codemod/lib/cra-to-next/index-to-component.ts @@ -1,4 +1,4 @@ -import { API, FileInfo, JSXElement, Options } from 'jscodeshift' +import type { API, FileInfo, JSXElement, Options } from 'jscodeshift' export const indexContext = { multipleRenderRoots: false, diff --git a/packages/next-codemod/package.json b/packages/next-codemod/package.json index 81b150a3b928c..f910d70927782 100644 --- a/packages/next-codemod/package.json +++ b/packages/next-codemod/package.json @@ -1,6 +1,6 @@ { "name": "@next/codemod", - "version": "13.5.5-canary.2", + "version": "13.5.5-canary.4", "license": "MIT", "repository": { "type": "git", diff --git a/packages/next-codemod/transforms/add-missing-react-import.ts b/packages/next-codemod/transforms/add-missing-react-import.ts index da966ab8094ba..5e6267ed736c1 100644 --- a/packages/next-codemod/transforms/add-missing-react-import.ts +++ b/packages/next-codemod/transforms/add-missing-react-import.ts @@ -1,4 +1,10 @@ -import { API, Collection, FileInfo, JSCodeshift, Options } from 'jscodeshift' +import type { + API, + Collection, + FileInfo, + JSCodeshift, + Options, +} from 'jscodeshift' function addReactImport(j: JSCodeshift, root: Collection) { // We create an import specifier, this is the value of an import, eg: diff --git a/packages/next-codemod/transforms/name-default-component.ts b/packages/next-codemod/transforms/name-default-component.ts index 8a7d4169ff1da..6e02b73adfdc7 100644 --- a/packages/next-codemod/transforms/name-default-component.ts +++ b/packages/next-codemod/transforms/name-default-component.ts @@ -1,4 +1,4 @@ -import { +import type { API, ArrowFunctionExpression, ASTPath, diff --git a/packages/next-codemod/transforms/new-link.ts b/packages/next-codemod/transforms/new-link.ts index 1214db85c06ef..fce40964cc074 100644 --- a/packages/next-codemod/transforms/new-link.ts +++ b/packages/next-codemod/transforms/new-link.ts @@ -1,4 +1,4 @@ -import { API, FileInfo } from 'jscodeshift' +import type { API, FileInfo } from 'jscodeshift' export default function transformer(file: FileInfo, api: API) { const j = api.jscodeshift.withParser('tsx') diff --git a/packages/next-env/package.json b/packages/next-env/package.json index e3c5a99ea5487..78eb4c0d87be7 100644 --- a/packages/next-env/package.json +++ b/packages/next-env/package.json @@ -1,6 +1,6 @@ { "name": "@next/env", - "version": "13.5.5-canary.2", + "version": "13.5.5-canary.4", "keywords": [ "react", "next", diff --git a/packages/next-mdx/package.json b/packages/next-mdx/package.json index 102a8ed4d33ef..4c754fba02b7d 100644 --- a/packages/next-mdx/package.json +++ b/packages/next-mdx/package.json @@ -1,6 +1,6 @@ { "name": "@next/mdx", - "version": "13.5.5-canary.2", + "version": "13.5.5-canary.4", "main": "index.js", "license": "MIT", "repository": { diff --git a/packages/next-plugin-storybook/package.json b/packages/next-plugin-storybook/package.json index cd3dca272564e..b89fde2bf621d 100644 --- a/packages/next-plugin-storybook/package.json +++ b/packages/next-plugin-storybook/package.json @@ -1,6 +1,6 @@ { "name": "@next/plugin-storybook", - "version": "13.5.5-canary.2", + "version": "13.5.5-canary.4", "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 d498743e0287b..5c77a0c4e9bc5 100644 --- a/packages/next-polyfill-module/package.json +++ b/packages/next-polyfill-module/package.json @@ -1,6 +1,6 @@ { "name": "@next/polyfill-module", - "version": "13.5.5-canary.2", + "version": "13.5.5-canary.4", "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 c715e5a210921..3e6adee4c8318 100644 --- a/packages/next-polyfill-nomodule/package.json +++ b/packages/next-polyfill-nomodule/package.json @@ -1,6 +1,6 @@ { "name": "@next/polyfill-nomodule", - "version": "13.5.5-canary.2", + "version": "13.5.5-canary.4", "description": "A polyfill for non-dead, nomodule browsers.", "main": "dist/polyfill-nomodule.js", "license": "MIT", diff --git a/packages/next-swc/crates/core/src/react_server_components.rs b/packages/next-swc/crates/core/src/react_server_components.rs index 8dd923dc61c74..8d136e78b09d8 100644 --- a/packages/next-swc/crates/core/src/react_server_components.rs +++ b/packages/next-swc/crates/core/src/react_server_components.rs @@ -344,6 +344,10 @@ impl ReactServerComponents { } fn assert_server_graph(&self, imports: &[ModuleImports], module: &Module) { + // If the + if self.is_from_node_modules(&self.filepath) { + return; + } for import in imports { let source = import.source.0.clone(); if self.invalid_server_imports.contains(&source) { @@ -391,6 +395,9 @@ impl ReactServerComponents { } fn assert_server_filename(&self, module: &Module) { + if self.is_from_node_modules(&self.filepath) { + return; + } let is_error_file = Regex::new(r"[\\/]error\.(ts|js)x?$") .unwrap() .is_match(&self.filepath); @@ -416,6 +423,9 @@ impl ReactServerComponents { } fn assert_client_graph(&self, imports: &[ModuleImports]) { + if self.is_from_node_modules(&self.filepath) { + return; + } for import in imports { let source = import.source.0.clone(); if self.invalid_client_imports.contains(&source) { @@ -432,6 +442,9 @@ impl ReactServerComponents { } fn assert_invalid_api(&self, module: &Module, is_client_entry: bool) { + if self.is_from_node_modules(&self.filepath) { + return; + } let is_layout_or_page = Regex::new(r"[\\/](page|layout)\.(ts|js)x?$") .unwrap() .is_match(&self.filepath); @@ -562,6 +575,12 @@ impl ReactServerComponents { }, ); } + + fn is_from_node_modules(&self, filepath: &str) -> bool { + Regex::new(r"[\\/]node_modules[\\/]") + .unwrap() + .is_match(filepath) + } } pub fn server_components( diff --git a/packages/next-swc/crates/next-api/src/app.rs b/packages/next-swc/crates/next-api/src/app.rs index 05d7a0008e33b..1b0684d6746d2 100644 --- a/packages/next-swc/crates/next-api/src/app.rs +++ b/packages/next-swc/crates/next-api/src/app.rs @@ -39,8 +39,9 @@ use turbopack_binding::{ turbopack::{ core::{ asset::{Asset, AssetContent}, - chunk::{ChunkableModuleExt, ChunkingContext, EvaluatableAssets}, + chunk::{ChunkingContext, EvaluatableAssets}, file_source::FileSource, + module::Module, output::{OutputAsset, OutputAssets}, virtual_output::VirtualOutputAsset, }, @@ -507,7 +508,13 @@ impl AppEndpoint { let mut server_assets = vec![]; let mut client_assets = vec![]; + let app_entry = app_entry.await?; + let client_shared_chunks = get_app_client_shared_chunks( + app_entry + .rsc_entry + .ident() + .with_modifier(Vc::cell("client_shared_chunks".to_string())), this.app_project.client_runtime_entries(), this.app_project.project().client_chunking_context(), ); @@ -524,7 +531,6 @@ impl AppEndpoint { } } - let app_entry = app_entry.await?; let rsc_entry = app_entry.rsc_entry; let rsc_entry_asset = Vc::upcast(rsc_entry); @@ -707,9 +713,7 @@ impl AppEndpoint { } let files = chunking_context.evaluated_chunk_group( - app_entry - .rsc_entry - .as_root_chunk(Vc::upcast(chunking_context)), + app_entry.rsc_entry.ident(), Vc::cell(evaluatable_assets), ); server_assets.extend(files.await?.iter().copied()); diff --git a/packages/next-swc/crates/next-api/src/middleware.rs b/packages/next-swc/crates/next-api/src/middleware.rs index b7fedd56befb0..ba5f17524f777 100644 --- a/packages/next-swc/crates/next-api/src/middleware.rs +++ b/packages/next-swc/crates/next-api/src/middleware.rs @@ -13,7 +13,7 @@ use turbopack_binding::{ turbopack::{ core::{ asset::AssetContent, - chunk::{ChunkableModuleExt, ChunkingContext}, + chunk::ChunkingContext, context::AssetContext, module::Module, output::{OutputAsset, OutputAssets}, @@ -88,10 +88,8 @@ impl MiddlewareEndpoint { let edge_chunking_context = self.project.edge_middleware_chunking_context(); - let edge_files = edge_chunking_context.evaluated_chunk_group( - module.as_root_chunk(Vc::upcast(edge_chunking_context)), - Vc::cell(evaluatable_assets), - ); + let edge_files = edge_chunking_context + .evaluated_chunk_group(module.ident(), Vc::cell(evaluatable_assets)); Ok(edge_files) } diff --git a/packages/next-swc/crates/next-api/src/pages.rs b/packages/next-swc/crates/next-api/src/pages.rs index e198e346a3e05..8d8f6705e8b15 100644 --- a/packages/next-swc/crates/next-api/src/pages.rs +++ b/packages/next-swc/crates/next-api/src/pages.rs @@ -37,10 +37,11 @@ use turbopack_binding::{ build::BuildChunkingContext, core::{ asset::AssetContent, - chunk::{ChunkableModuleExt, ChunkingContext, EvaluatableAssets}, + chunk::{ChunkingContext, EvaluatableAssets}, context::AssetContext, file_source::FileSource, issue::{IssueSeverity, OptionIssueSource}, + module::Module, output::{OutputAsset, OutputAssets}, reference_type::{ EcmaScriptModulesReferenceSubType, EntryReferenceSubType, ReferenceType, @@ -549,11 +550,9 @@ impl PageEndpoint { let client_chunking_context = this.pages_project.project().client_chunking_context(); - let client_entry_chunk = client_module.as_root_chunk(Vc::upcast(client_chunking_context)); - let mut client_chunks = client_chunking_context .evaluated_chunk_group( - client_entry_chunk, + client_module.ident(), this.pages_project .client_runtime_entries() .with_entry(Vc::upcast(client_main_module)) @@ -611,10 +610,8 @@ impl PageEndpoint { }; evaluatable_assets.push(evaluatable); - let edge_files = edge_chunking_context.evaluated_chunk_group( - ssr_module.as_root_chunk(Vc::upcast(edge_chunking_context)), - Vc::cell(evaluatable_assets), - ); + let edge_files = edge_chunking_context + .evaluated_chunk_group(ssr_module.ident(), Vc::cell(evaluatable_assets)); Ok(SsrChunk::Edge { files: edge_files }.cell()) } else { diff --git a/packages/next-swc/crates/next-build/src/next_app/app_entries.rs b/packages/next-swc/crates/next-build/src/next_app/app_entries.rs index 57c5143babb9c..e8a05d1a86260 100644 --- a/packages/next-swc/crates/next-build/src/next_app/app_entries.rs +++ b/packages/next-swc/crates/next-build/src/next_app/app_entries.rs @@ -27,7 +27,10 @@ use turbopack_binding::{ turbopack::{ build::BuildChunkingContext, core::{ - chunk::EvaluatableAssets, compile_time_info::CompileTimeInfo, file_source::FileSource, + chunk::{ChunkingContext, EvaluatableAssets}, + compile_time_info::CompileTimeInfo, + file_source::FileSource, + ident::AssetIdent, output::OutputAsset, }, ecmascript::chunk::EcmascriptChunkingContext, @@ -256,8 +259,15 @@ pub async fn compute_app_entries_chunks( ) -> Result<()> { let client_relative_path_ref = client_relative_path.await?; - let app_client_shared_chunks = - get_app_client_shared_chunks(app_entries.client_runtime_entries, client_chunking_context); + let app_client_shared_chunks = get_app_client_shared_chunks( + AssetIdent::from_path( + client_chunking_context + .context_path() + .join("client shared chunk group".to_string()), + ), + app_entries.client_runtime_entries, + client_chunking_context, + ); let mut app_shared_client_chunks_paths = vec![]; for chunk in app_client_shared_chunks.await?.iter().copied() { diff --git a/packages/next-swc/crates/next-build/src/next_pages/page_entries.rs b/packages/next-swc/crates/next-build/src/next_pages/page_entries.rs index 1f024e90e1c64..0b183f7e535ef 100644 --- a/packages/next-swc/crates/next-build/src/next_pages/page_entries.rs +++ b/packages/next-swc/crates/next-build/src/next_pages/page_entries.rs @@ -27,10 +27,11 @@ use turbopack_binding::{ turbopack::{ build::BuildChunkingContext, core::{ - chunk::{ChunkableModuleExt, ChunkingContext, EvaluatableAssets}, + chunk::{ChunkingContext, EvaluatableAssets}, compile_time_info::CompileTimeInfo, context::AssetContext, file_source::FileSource, + module::Module, output::OutputAsset, reference_type::{EntryReferenceSubType, ReferenceType}, source::Source, @@ -400,12 +401,8 @@ pub async fn compute_page_entries_chunks( .insert(pathname.clone_value(), asset_path.to_string()); } - let client_entry_chunk = page_entry - .client_module - .as_root_chunk(Vc::upcast(client_chunking_context)); - let client_chunks = client_chunking_context.evaluated_chunk_group( - client_entry_chunk, + page_entry.client_module.ident(), page_entries .client_runtime_entries .with_entry(Vc::upcast(page_entry.client_module)), diff --git a/packages/next-swc/crates/next-core/src/next_app/app_client_references_chunks.rs b/packages/next-swc/crates/next-core/src/next_app/app_client_references_chunks.rs index ea67efab3a447..83ba23239b68c 100644 --- a/packages/next-swc/crates/next-core/src/next_app/app_client_references_chunks.rs +++ b/packages/next-swc/crates/next-core/src/next_app/app_client_references_chunks.rs @@ -4,10 +4,7 @@ use serde::{Deserialize, Serialize}; use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, TryJoinIterExt, Vc}; use turbopack_binding::turbopack::{ build::BuildChunkingContext, - core::{ - chunk::{ChunkableModuleExt, ChunkingContext}, - output::OutputAssets, - }, + core::{chunk::ChunkingContextExt, output::OutputAssets}, ecmascript::chunk::EcmascriptChunkingContext, }; @@ -46,24 +43,21 @@ pub async fn get_app_client_references_chunks( match client_reference_ty { ClientReferenceType::EcmascriptClientReference(ecmascript_client_reference) => { let ecmascript_client_reference_ref = ecmascript_client_reference.await?; - let client_entry_chunk = ecmascript_client_reference_ref - .client_module - .as_root_chunk(Vc::upcast(client_chunking_context)); - let ssr_entry_chunk = ecmascript_client_reference_ref - .ssr_module - .as_root_chunk(Vc::upcast(ssr_chunking_context)); ClientReferenceChunks { - client_chunks: client_chunking_context.chunk_group(client_entry_chunk), - ssr_chunks: ssr_chunking_context.chunk_group(ssr_entry_chunk), + client_chunks: client_chunking_context.root_chunk_group(Vc::upcast( + ecmascript_client_reference_ref.client_module, + )), + ssr_chunks: ssr_chunking_context.root_chunk_group(Vc::upcast( + ecmascript_client_reference_ref.ssr_module, + )), } } ClientReferenceType::CssClientReference(css_client_reference) => { let css_client_reference_ref = css_client_reference.await?; - let client_entry_chunk = css_client_reference_ref - .client_module - .as_root_chunk(Vc::upcast(client_chunking_context)); ClientReferenceChunks { - client_chunks: client_chunking_context.chunk_group(client_entry_chunk), + client_chunks: client_chunking_context.root_chunk_group(Vc::upcast( + css_client_reference_ref.client_module, + )), ssr_chunks: OutputAssets::empty(), } } diff --git a/packages/next-swc/crates/next-core/src/next_app/app_client_shared_chunks.rs b/packages/next-swc/crates/next-core/src/next_app/app_client_shared_chunks.rs index cedcd7a506a6d..e7e2881816905 100644 --- a/packages/next-swc/crates/next-core/src/next_app/app_client_shared_chunks.rs +++ b/packages/next-swc/crates/next-core/src/next_app/app_client_shared_chunks.rs @@ -1,41 +1,17 @@ use anyhow::Result; -use turbo_tasks::{TryJoinIterExt, Value, Vc}; +use turbo_tasks::Vc; use turbopack_binding::turbopack::{ core::{ - chunk::{availability_info::AvailabilityInfo, ChunkingContext, EvaluatableAssets}, + chunk::{ChunkingContext, EvaluatableAssets}, + ident::AssetIdent, output::OutputAssets, }, - ecmascript::chunk::{EcmascriptChunk, EcmascriptChunkPlaceable, EcmascriptChunkingContext}, + ecmascript::chunk::EcmascriptChunkingContext, }; -#[turbo_tasks::function] -pub async fn get_app_shared_client_chunk( - app_client_runtime_entries: Vc, - client_chunking_context: Vc>, -) -> Result> { - let client_runtime_entries: Vec<_> = app_client_runtime_entries - .await? - .iter() - .map(|entry| async move { - Ok(Vc::try_resolve_sidecast::>(*entry).await?) - }) - .try_join() - .await? - .into_iter() - .flatten() - .collect(); - - Ok(EcmascriptChunk::new_normalized( - client_chunking_context, - // TODO(alexkirsz) Should this accept Evaluatable instead? - Vc::cell(client_runtime_entries), - None, - Value::new(AvailabilityInfo::Untracked), - )) -} - #[turbo_tasks::function] pub async fn get_app_client_shared_chunks( + ident: Vc, app_client_runtime_entries: Vc, client_chunking_context: Vc>, ) -> Result> { @@ -43,13 +19,8 @@ pub async fn get_app_client_shared_chunks( return Ok(OutputAssets::empty()); } - let app_client_shared_chunk = - get_app_shared_client_chunk(app_client_runtime_entries, client_chunking_context); - - let app_client_shared_chunks = client_chunking_context.evaluated_chunk_group( - Vc::upcast(app_client_shared_chunk), - app_client_runtime_entries, - ); + let app_client_shared_chunks = + client_chunking_context.evaluated_chunk_group(ident, app_client_runtime_entries); Ok(app_client_shared_chunks) } diff --git a/packages/next-swc/crates/next-core/src/next_client/context.rs b/packages/next-swc/crates/next-core/src/next_client/context.rs index fe3b43aaf1564..08069da234d60 100644 --- a/packages/next-swc/crates/next-core/src/next_client/context.rs +++ b/packages/next-swc/crates/next-core/src/next_client/context.rs @@ -19,7 +19,6 @@ use turbopack_binding::{ }, dev::{react_refresh::assert_can_resolve_react_refresh, DevChunkingContext}, ecmascript::chunk::EcmascriptChunkingContext, - ecmascript_plugin::transform::directives::server::ServerDirectiveTransformer, node::execution_context::ExecutionContext, turbopack::{ condition::ContextCondition, @@ -232,11 +231,6 @@ pub async fn get_client_module_options_context( *get_emotion_transform_plugin(next_config).await?, *get_styled_components_transform_plugin(next_config).await?, *get_styled_jsx_transform_plugin().await?, - Some(Vc::cell(Box::new(ServerDirectiveTransformer::new( - // ServerDirective is not implemented yet and always reports an issue. - // We don't have to pass a valid transition name yet, but the API is prepared. - &Vc::cell("TODO".to_string()), - )) as _)), ] .into_iter() .flatten() diff --git a/packages/next-swc/crates/next-core/src/next_client_component/with_client_chunks.rs b/packages/next-swc/crates/next-core/src/next_client_component/with_client_chunks.rs index d5499cc0de811..84ea9db26b1f6 100644 --- a/packages/next-swc/crates/next-core/src/next_client_component/with_client_chunks.rs +++ b/packages/next-swc/crates/next-core/src/next_client_component/with_client_chunks.rs @@ -1,15 +1,15 @@ use anyhow::{Context, Result}; use indoc::formatdoc; -use turbo_tasks::{TryJoinIterExt, Value, ValueToString, Vc}; +use turbo_tasks::{TryJoinIterExt, ValueToString, Vc}; use turbopack_binding::{ turbo::tasks_fs::FileSystemPath, turbopack::{ core::{ asset::{Asset, AssetContent}, chunk::{ - availability_info::AvailabilityInfo, Chunk, ChunkData, ChunkItem, ChunkItemExt, - ChunkableModule, ChunkableModuleExt, ChunkableModuleReference, ChunkingContext, - ChunkingType, ChunkingTypeOption, ChunksData, + ChunkData, ChunkItem, ChunkItemExt, ChunkType, ChunkableModule, + ChunkableModuleReference, ChunkingContext, ChunkingContextExt, ChunkingType, + ChunkingTypeOption, ChunksData, }, ident::AssetIdent, module::Module, @@ -18,11 +18,11 @@ use turbopack_binding::{ reference::{ModuleReference, ModuleReferences, SingleOutputAssetReference}, resolve::ModuleResolveResult, }, - ecmascript::chunk::EcmascriptChunkData, + ecmascript::chunk::{EcmascriptChunkData, EcmascriptChunkType}, turbopack::ecmascript::{ chunk::{ - EcmascriptChunk, EcmascriptChunkItem, EcmascriptChunkItemContent, - EcmascriptChunkPlaceable, EcmascriptChunkingContext, EcmascriptExports, + EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkPlaceable, + EcmascriptChunkingContext, EcmascriptExports, }, utils::StringifyJs, }, @@ -111,9 +111,7 @@ impl WithClientChunksChunkItem { async fn chunks(self: Vc) -> Result> { let this = self.await?; let inner = this.inner.await?; - Ok(this - .context - .chunk_group(inner.asset.as_root_chunk(Vc::upcast(this.context)))) + Ok(this.context.root_chunk_group(Vc::upcast(inner.asset))) } #[turbo_tasks::function] @@ -241,12 +239,13 @@ impl ChunkItem for WithClientChunksChunkItem { } #[turbo_tasks::function] - fn as_chunk(&self, availability_info: Value) -> Vc> { - Vc::upcast(EcmascriptChunk::new( - Vc::upcast(self.context.with_layer("rsc".to_string())), - Vc::upcast(self.inner), - availability_info, - )) + fn ty(&self) -> Vc> { + Vc::upcast(Vc::::default()) + } + + #[turbo_tasks::function] + fn module(&self) -> Vc> { + Vc::upcast(self.inner) } } diff --git a/packages/next-swc/crates/next-core/src/next_client_reference/ecmascript_client_reference/ecmascript_client_reference_proxy_module.rs b/packages/next-swc/crates/next-core/src/next_client_reference/ecmascript_client_reference/ecmascript_client_reference_proxy_module.rs index fe3c06999ff39..48eb66dfe84ad 100644 --- a/packages/next-swc/crates/next-core/src/next_client_reference/ecmascript_client_reference/ecmascript_client_reference_proxy_module.rs +++ b/packages/next-swc/crates/next-core/src/next_client_reference/ecmascript_client_reference/ecmascript_client_reference_proxy_module.rs @@ -8,7 +8,8 @@ use turbopack_binding::turbopack::{ core::{ asset::{Asset, AssetContent}, chunk::{ - availability_info::AvailabilityInfo, Chunk, ChunkItem, ChunkableModule, ChunkingContext, + availability_info::AvailabilityInfo, ChunkItem, ChunkType, ChunkableModule, + ChunkingContext, }, code_builder::CodeBuilder, context::AssetContext, @@ -20,8 +21,8 @@ use turbopack_binding::turbopack::{ }, ecmascript::{ chunk::{ - EcmascriptChunk, EcmascriptChunkItem, EcmascriptChunkItemContent, - EcmascriptChunkPlaceable, EcmascriptChunkingContext, EcmascriptExports, + EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkPlaceable, + EcmascriptChunkType, EcmascriptChunkingContext, EcmascriptExports, }, utils::StringifyJs, EcmascriptModuleAsset, @@ -238,12 +239,13 @@ impl ChunkItem for ProxyModuleChunkItem { } #[turbo_tasks::function] - fn as_chunk(&self, availability_info: Value) -> Vc> { - Vc::upcast(EcmascriptChunk::new( - Vc::upcast(self.chunking_context), - Vc::upcast(self.client_proxy_asset), - availability_info, - )) + fn ty(&self) -> Vc> { + Vc::upcast(Vc::::default()) + } + + #[turbo_tasks::function] + fn module(&self) -> Vc> { + Vc::upcast(self.client_proxy_asset) } } diff --git a/packages/next-swc/crates/next-core/src/next_dynamic/dynamic_module.rs b/packages/next-swc/crates/next-core/src/next_dynamic/dynamic_module.rs index b5cd908992b66..8e20f4c4dabf6 100644 --- a/packages/next-swc/crates/next-core/src/next_dynamic/dynamic_module.rs +++ b/packages/next-swc/crates/next-core/src/next_dynamic/dynamic_module.rs @@ -2,7 +2,7 @@ use anyhow::{bail, Result}; use turbo_tasks::Vc; use turbopack_binding::turbopack::core::{ asset::{Asset, AssetContent}, - chunk::{ChunkableModule, ChunkableModuleExt, ChunkingContext}, + chunk::{ChunkableModule, ChunkingContext, ChunkingContextExt}, ident::AssetIdent, module::Module, output::OutputAssets, @@ -41,8 +41,7 @@ impl NextDynamicEntryModule { bail!("dynamic client asset must be chunkable"); }; - let client_entry_chunk = client_entry_module.as_root_chunk(client_chunking_context); - Ok(client_chunking_context.chunk_group(client_entry_chunk)) + Ok(client_chunking_context.root_chunk_group(client_entry_module)) } } diff --git a/packages/next-swc/crates/next-core/src/next_import_map.rs b/packages/next-swc/crates/next-core/src/next_import_map.rs index cec5657980867..3d0f2b788b67b 100644 --- a/packages/next-swc/crates/next-core/src/next_import_map.rs +++ b/packages/next-swc/crates/next-core/src/next_import_map.rs @@ -280,6 +280,20 @@ pub async fn get_next_server_import_map( "next/dist/build/webpack/loaders/next-flight-loader/action-proxy", ), ); + import_map.insert_exact_alias( + "private-next-rsc-action-client-wrapper", + request_to_import_mapping( + project_path, + "next/dist/build/webpack/loaders/next-flight-loader/action-client-wrapper", + ), + ); + import_map.insert_exact_alias( + "private-next-rsc-action-validate", + request_to_import_mapping( + project_path, + "next/dist/build/webpack/loaders/next-flight-loader/action-validate", + ), + ); import_map.insert_exact_alias( "next/head", request_to_import_mapping(project_path, "next/dist/client/components/noop-head"), diff --git a/packages/next-swc/crates/next-core/src/next_server/context.rs b/packages/next-swc/crates/next-core/src/next_server/context.rs index d789721362c58..dd2e3da1b3acc 100644 --- a/packages/next-swc/crates/next-core/src/next_server/context.rs +++ b/packages/next-swc/crates/next-core/src/next_server/context.rs @@ -19,9 +19,7 @@ use turbopack_binding::{ resolve::{parse::Request, pattern::Pattern}, }, ecmascript::TransformPlugin, - ecmascript_plugin::transform::directives::{ - client::ClientDirectiveTransformer, server::ServerDirectiveTransformer, - }, + ecmascript_plugin::transform::directives::client::ClientDirectiveTransformer, node::execution_context::ExecutionContext, turbopack::{ condition::ContextCondition, @@ -66,7 +64,7 @@ use crate::{ get_decorators_transform_options, get_jsx_transform_options, get_typescript_transform_options, }, - util::foreign_code_context_condition, + util::{foreign_code_context_condition, load_next_js_templateon}, }; #[turbo_tasks::value(serialization = "auto_for_input")] @@ -107,10 +105,25 @@ pub async fn get_server_resolve_options_context( let root_dir = project_path.root().resolve().await?; let module_feature_report_resolve_plugin = ModuleFeatureReportResolvePlugin::new(project_path); let unsupported_modules_resolve_plugin = UnsupportedModulesResolvePlugin::new(project_path); + + // Always load these predefined packages as external. + let mut external_packages: Vec = load_next_js_templateon( + project_path, + "dist/lib/server-external-packages.json".to_string(), + ) + .await?; + + // Add the config's own list of external packages. + external_packages.extend( + (*next_config.server_component_externals().await?) + .iter() + .cloned(), + ); + let server_component_externals_plugin = ExternalCjsModulesResolvePlugin::new( project_path, project_path.root(), - ExternalPredicate::Only(next_config.server_component_externals()).cell(), + ExternalPredicate::Only(Vc::cell(external_packages)).cell(), ); let ty = ty.into_value(); @@ -276,12 +289,6 @@ pub async fn get_server_module_options_context( let styled_components_transform_plugin = *get_styled_components_transform_plugin(next_config).await?; let styled_jsx_transform_plugin = *get_styled_jsx_transform_plugin().await?; - let server_directive_transform_plugin = - Some(Vc::cell(Box::new(ServerDirectiveTransformer::new( - // ServerDirective is not implemented yet and always reports an issue. - // We don't have to pass a valid transition name yet, but the API is prepared. - &Vc::cell("TODO".to_string()), - )) as _)); // ModuleOptionsContext related options let tsconfig = get_typescript_transform_options(project_path); @@ -374,7 +381,6 @@ pub async fn get_server_module_options_context( let mut base_source_transforms: Vec> = vec![ styled_components_transform_plugin, styled_jsx_transform_plugin, - server_directive_transform_plugin, ] .into_iter() .flatten() @@ -433,13 +439,11 @@ pub async fn get_server_module_options_context( ecmascript_client_reference_transition_name, .. } => { - let mut base_source_transforms: Vec> = vec![ - styled_components_transform_plugin, - server_directive_transform_plugin, - ] - .into_iter() - .flatten() - .collect(); + let mut base_source_transforms: Vec> = + vec![styled_components_transform_plugin] + .into_iter() + .flatten() + .collect(); if let Some(ecmascript_client_reference_transition_name) = ecmascript_client_reference_transition_name diff --git a/packages/next-swc/crates/next-core/src/next_server_component/server_component_module.rs b/packages/next-swc/crates/next-core/src/next_server_component/server_component_module.rs index bd89ee6081954..b70659a88fcac 100644 --- a/packages/next-swc/crates/next-core/src/next_server_component/server_component_module.rs +++ b/packages/next-swc/crates/next-core/src/next_server_component/server_component_module.rs @@ -1,22 +1,20 @@ use anyhow::{bail, Context, Result}; use indoc::formatdoc; -use turbo_tasks::{Value, Vc}; +use turbo_tasks::Vc; use turbo_tasks_fs::FileSystemPath; use turbopack_binding::turbopack::{ core::{ asset::{Asset, AssetContent}, - chunk::{ - availability_info::AvailabilityInfo, Chunk, ChunkItem, ChunkItemExt, ChunkableModule, - ChunkingContext, - }, + chunk::{ChunkItem, ChunkItemExt, ChunkType, ChunkableModule, ChunkingContext}, ident::AssetIdent, module::Module, reference::ModuleReferences, }, + ecmascript::chunk::EcmascriptChunkType, turbopack::ecmascript::{ chunk::{ - EcmascriptChunk, EcmascriptChunkItem, EcmascriptChunkItemContent, - EcmascriptChunkPlaceable, EcmascriptChunkingContext, EcmascriptExports, + EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkPlaceable, + EcmascriptChunkingContext, EcmascriptExports, }, utils::StringifyJs, }, @@ -161,11 +159,12 @@ impl ChunkItem for BuildServerComponentChunkItem { } #[turbo_tasks::function] - fn as_chunk(&self, availability_info: Value) -> Vc> { - Vc::upcast(EcmascriptChunk::new( - Vc::upcast(self.context), - Vc::upcast(self.inner), - availability_info, - )) + fn ty(&self) -> Vc> { + Vc::upcast(Vc::::default()) + } + + #[turbo_tasks::function] + fn module(&self) -> Vc> { + Vc::upcast(self.inner) } } diff --git a/packages/next-swc/crates/next-core/src/page_loader.rs b/packages/next-swc/crates/next-core/src/page_loader.rs index 56d240b1a476b..7ac15c7b65a93 100644 --- a/packages/next-swc/crates/next-core/src/page_loader.rs +++ b/packages/next-swc/crates/next-core/src/page_loader.rs @@ -9,10 +9,7 @@ use turbopack_binding::{ turbopack::{ core::{ asset::{Asset, AssetContent}, - chunk::{ - ChunkData, ChunkableModuleExt, ChunkingContext, ChunksData, EvaluatableAsset, - EvaluatableAssets, - }, + chunk::{ChunkData, ChunkingContext, ChunksData, EvaluatableAsset, EvaluatableAssets}, context::AssetContext, ident::AssetIdent, module::Module, @@ -138,10 +135,9 @@ impl PageLoaderAsset { bail!("internal module must be evaluatable"); }; - Ok(this.client_chunking_context.evaluated_chunk_group( - module.as_root_chunk(this.client_chunking_context), - EvaluatableAssets::one(module), - )) + Ok(this + .client_chunking_context + .evaluated_chunk_group(module.ident(), EvaluatableAssets::one(module))) } #[turbo_tasks::function] diff --git a/packages/next-swc/crates/next-core/src/util.rs b/packages/next-swc/crates/next-core/src/util.rs index 6b1479255a090..144012cd2a175 100644 --- a/packages/next-swc/crates/next-core/src/util.rs +++ b/packages/next-swc/crates/next-core/src/util.rs @@ -568,12 +568,12 @@ pub async fn load_next_js_templateon( project_path: Vc, path: String, ) -> Result { - let file_path = get_next_package(project_path).join(path); + let file_path = get_next_package(project_path).join(path.clone()); let content = &*file_path.read().await?; let FileContent::Content(file) = content else { - bail!("Expected file content for metrics data"); + bail!("Expected file content at {}", path); }; let result: T = parse_json_rope_with_source_context(file.content())?; diff --git a/packages/next-swc/package.json b/packages/next-swc/package.json index eb13e7a3d6d43..08e9191210978 100644 --- a/packages/next-swc/package.json +++ b/packages/next-swc/package.json @@ -1,6 +1,6 @@ { "name": "@next/swc", - "version": "13.5.5-canary.2", + "version": "13.5.5-canary.4", "private": true, "scripts": { "clean": "node ../../scripts/rm.mjs native", diff --git a/packages/next/package.json b/packages/next/package.json index 85d14ea8518d8..c5e0808ee5a28 100644 --- a/packages/next/package.json +++ b/packages/next/package.json @@ -1,6 +1,6 @@ { "name": "next", - "version": "13.5.5-canary.2", + "version": "13.5.5-canary.4", "description": "The React Framework", "main": "./dist/server/next.js", "license": "MIT", @@ -90,7 +90,7 @@ ] }, "dependencies": { - "@next/env": "13.5.5-canary.2", + "@next/env": "13.5.5-canary.4", "@swc/helpers": "0.5.2", "busboy": "1.6.0", "caniuse-lite": "^1.0.30001406", @@ -144,11 +144,11 @@ "@mswjs/interceptors": "0.23.0", "@napi-rs/cli": "2.16.2", "@napi-rs/triples": "1.1.0", - "@next/polyfill-module": "13.5.5-canary.2", - "@next/polyfill-nomodule": "13.5.5-canary.2", - "@next/react-dev-overlay": "13.5.5-canary.2", - "@next/react-refresh-utils": "13.5.5-canary.2", - "@next/swc": "13.5.5-canary.2", + "@next/polyfill-module": "13.5.5-canary.4", + "@next/polyfill-nomodule": "13.5.5-canary.4", + "@next/react-dev-overlay": "13.5.5-canary.4", + "@next/react-refresh-utils": "13.5.5-canary.4", + "@next/swc": "13.5.5-canary.4", "@opentelemetry/api": "1.4.1", "@playwright/test": "^1.35.1", "@taskr/clear": "1.1.0", @@ -191,7 +191,7 @@ "@types/ws": "8.2.0", "@vercel/ncc": "0.34.0", "@vercel/nft": "0.22.6", - "@vercel/turbopack-ecmascript-runtime": "https://gitpkg-fork.vercel.sh/vercel/turbo/crates/turbopack-ecmascript-runtime/js?turbopack-231005.2", + "@vercel/turbopack-ecmascript-runtime": "https://gitpkg-fork.vercel.sh/vercel/turbo/crates/turbopack-ecmascript-runtime/js?turbopack-231006.4", "acorn": "8.5.0", "amphtml-validator": "1.0.35", "anser": "1.4.9", diff --git a/packages/next/src/bin/next.ts b/packages/next/src/bin/next.ts index 80d6a0fe6fde4..2bde7eb71a911 100755 --- a/packages/next/src/bin/next.ts +++ b/packages/next/src/bin/next.ts @@ -1,4 +1,5 @@ #!/usr/bin/env node +performance.mark('next-start') import '../server/require-hook' import * as log from '../build/output/log' import arg from 'next/dist/compiled/arg/index.js' diff --git a/packages/next/src/build/analysis/get-page-static-info.ts b/packages/next/src/build/analysis/get-page-static-info.ts index 37440dfe8065c..45e99e28e9933 100644 --- a/packages/next/src/build/analysis/get-page-static-info.ts +++ b/packages/next/src/build/analysis/get-page-static-info.ts @@ -4,7 +4,7 @@ import type { Middleware, RouteHas } from '../../lib/load-custom-routes' import { promises as fs } from 'fs' import LRUCache from 'next/dist/compiled/lru-cache' import { matcher } from 'next/dist/compiled/micromatch' -import { ServerRuntime } from 'next/types' +import type { ServerRuntime } from 'next/types' import { extractExportedConstValue, UnsupportedValueError, diff --git a/packages/next/src/build/babel/loader/get-config.ts b/packages/next/src/build/babel/loader/get-config.ts index 3aaa549176ebf..6fd0d56663df0 100644 --- a/packages/next/src/build/babel/loader/get-config.ts +++ b/packages/next/src/build/babel/loader/get-config.ts @@ -4,7 +4,7 @@ import JSON5 from 'next/dist/compiled/json5' import { createConfigItem, loadOptions } from 'next/dist/compiled/babel/core' import loadConfig from 'next/dist/compiled/babel/core-lib-config' -import { NextBabelLoaderOptions, NextJsLoaderContext } from './types' +import type { NextBabelLoaderOptions, NextJsLoaderContext } from './types' import { consumeIterator } from './util' import * as Log from '../../output/log' diff --git a/packages/next/src/build/babel/loader/index.ts b/packages/next/src/build/babel/loader/index.ts index e7c77416d54fc..b8da35142ca5a 100644 --- a/packages/next/src/build/babel/loader/index.ts +++ b/packages/next/src/build/babel/loader/index.ts @@ -1,6 +1,6 @@ -import { Span } from '../../../trace' +import type { Span } from '../../../trace' import transform from './transform' -import { NextJsLoaderContext } from './types' +import type { NextJsLoaderContext } from './types' async function nextBabelLoader( this: NextJsLoaderContext, diff --git a/packages/next/src/build/babel/loader/transform.ts b/packages/next/src/build/babel/loader/transform.ts index 57dd2985ec419..8357313bb943c 100644 --- a/packages/next/src/build/babel/loader/transform.ts +++ b/packages/next/src/build/babel/loader/transform.ts @@ -11,8 +11,8 @@ import PluginPass from 'next/dist/compiled/babel/core-lib-plugin-pass' import getConfig from './get-config' import { consumeIterator } from './util' -import { Span } from '../../../trace' -import { NextJsLoaderContext } from './types' +import type { Span } from '../../../trace' +import type { NextJsLoaderContext } from './types' function getTraversalParams(file: any, pluginPairs: any[]) { const passPairs = [] diff --git a/packages/next/src/build/babel/loader/types.d.ts b/packages/next/src/build/babel/loader/types.d.ts index 896d2bf55e835..49dedf35776ec 100644 --- a/packages/next/src/build/babel/loader/types.d.ts +++ b/packages/next/src/build/babel/loader/types.d.ts @@ -1,5 +1,5 @@ -import { webpack } from 'next/dist/compiled/webpack/webpack' -import { Span } from '../../../trace' +import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { Span } from '../../../trace' export interface NextJsLoaderContext extends webpack.LoaderContext<{}> { currentTraceSpan: Span diff --git a/packages/next/src/build/babel/plugins/amp-attributes.ts b/packages/next/src/build/babel/plugins/amp-attributes.ts index b19b7f9184ef3..b76d00ebabc06 100644 --- a/packages/next/src/build/babel/plugins/amp-attributes.ts +++ b/packages/next/src/build/babel/plugins/amp-attributes.ts @@ -1,4 +1,4 @@ -import { NodePath, PluginObj, types } from 'next/dist/compiled/babel/core' +import type { NodePath, types, PluginObj } from 'next/dist/compiled/babel/core' export default function AmpAttributePatcher(): PluginObj { return { diff --git a/packages/next/src/build/babel/plugins/commonjs.ts b/packages/next/src/build/babel/plugins/commonjs.ts index 766153450221b..01573619015ca 100644 --- a/packages/next/src/build/babel/plugins/commonjs.ts +++ b/packages/next/src/build/babel/plugins/commonjs.ts @@ -1,4 +1,5 @@ -import { NodePath, PluginObj, types } from 'next/dist/compiled/babel/core' +import type { NodePath, types } from 'next/dist/compiled/babel/core' +import type { PluginObj } from 'next/dist/compiled/babel/core' import commonjsPlugin from 'next/dist/compiled/babel/plugin-transform-modules-commonjs' // Handle module.exports in user code diff --git a/packages/next/src/build/babel/plugins/jsx-pragma.ts b/packages/next/src/build/babel/plugins/jsx-pragma.ts index e992088b2435e..8413ddac3fc25 100644 --- a/packages/next/src/build/babel/plugins/jsx-pragma.ts +++ b/packages/next/src/build/babel/plugins/jsx-pragma.ts @@ -1,8 +1,8 @@ -import { +import type { NodePath, - PluginObj, types as BabelTypes, } from 'next/dist/compiled/babel/core' +import type { PluginObj } from 'next/dist/compiled/babel/core' import jsx from 'next/dist/compiled/babel/plugin-syntax-jsx' export default function ({ diff --git a/packages/next/src/build/babel/plugins/next-font-unsupported.ts b/packages/next/src/build/babel/plugins/next-font-unsupported.ts index 49dc853ea3e64..c29dd8e3cd81c 100644 --- a/packages/next/src/build/babel/plugins/next-font-unsupported.ts +++ b/packages/next/src/build/babel/plugins/next-font-unsupported.ts @@ -1,4 +1,5 @@ -import { NodePath, PluginObj, types } from 'next/dist/compiled/babel/core' +import type { NodePath, types } from 'next/dist/compiled/babel/core' +import type { PluginObj } from 'next/dist/compiled/babel/core' export default function NextPageDisallowReExportAllExports(): PluginObj { return { diff --git a/packages/next/src/build/babel/plugins/next-page-config.ts b/packages/next/src/build/babel/plugins/next-page-config.ts index 3126ba6ccf533..ceae6f8dd952d 100644 --- a/packages/next/src/build/babel/plugins/next-page-config.ts +++ b/packages/next/src/build/babel/plugins/next-page-config.ts @@ -1,11 +1,11 @@ -import { - NodePath, +import { types as BabelTypes } from 'next/dist/compiled/babel/core' +import type { PluginObj, PluginPass, - types as BabelTypes, Visitor, + NodePath, } from 'next/dist/compiled/babel/core' -import { PageConfig } from 'next/types' +import type { PageConfig } from 'next/types' import { STRING_LITERAL_DROP_BUNDLE } from '../../../shared/lib/constants' const CONFIG_KEY = 'config' diff --git a/packages/next/src/build/babel/plugins/next-page-disallow-re-export-all-exports.ts b/packages/next/src/build/babel/plugins/next-page-disallow-re-export-all-exports.ts index 93ffe83ea838b..7814fbecd995a 100644 --- a/packages/next/src/build/babel/plugins/next-page-disallow-re-export-all-exports.ts +++ b/packages/next/src/build/babel/plugins/next-page-disallow-re-export-all-exports.ts @@ -1,4 +1,5 @@ -import { NodePath, PluginObj, types } from 'next/dist/compiled/babel/core' +import type { NodePath, types } from 'next/dist/compiled/babel/core' +import type { PluginObj } from 'next/dist/compiled/babel/core' export default function NextPageDisallowReExportAllExports(): PluginObj { return { diff --git a/packages/next/src/build/babel/plugins/next-ssg-transform.ts b/packages/next/src/build/babel/plugins/next-ssg-transform.ts index eb741358a1ce5..db6be10944b94 100644 --- a/packages/next/src/build/babel/plugins/next-ssg-transform.ts +++ b/packages/next/src/build/babel/plugins/next-ssg-transform.ts @@ -1,8 +1,8 @@ -import { +import type { NodePath, - PluginObj, types as BabelTypes, } from 'next/dist/compiled/babel/core' +import type { PluginObj } from 'next/dist/compiled/babel/core' import { SERVER_PROPS_SSG_CONFLICT } from '../../../lib/constants' import { SERVER_PROPS_ID, STATIC_PROPS_ID } from '../../../shared/lib/constants' diff --git a/packages/next/src/build/babel/plugins/optimize-hook-destructuring.ts b/packages/next/src/build/babel/plugins/optimize-hook-destructuring.ts index a951ae376b6b2..63e9ccd7abe11 100644 --- a/packages/next/src/build/babel/plugins/optimize-hook-destructuring.ts +++ b/packages/next/src/build/babel/plugins/optimize-hook-destructuring.ts @@ -1,9 +1,8 @@ -import { +import type { NodePath, - PluginObj, types as BabelTypes, } from 'next/dist/compiled/babel/core' - +import type { PluginObj } from 'next/dist/compiled/babel/core' // matches any hook-like (the default) const isHook = /^use[A-Z]/ diff --git a/packages/next/src/build/babel/plugins/react-loadable-plugin.ts b/packages/next/src/build/babel/plugins/react-loadable-plugin.ts index 045f29271a673..884e6f3b1ed26 100644 --- a/packages/next/src/build/babel/plugins/react-loadable-plugin.ts +++ b/packages/next/src/build/babel/plugins/react-loadable-plugin.ts @@ -23,11 +23,11 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWAR // Modified to put `webpack` and `modules` under `loadableGenerated` to be backwards compatible with next/dynamic which has a `modules` key // Modified to support `dynamic(import('something'))` and `dynamic(import('something'), options) -import { +import type { NodePath, - PluginObj, types as BabelTypes, } from 'next/dist/compiled/babel/core' +import type { PluginObj } from 'next/dist/compiled/babel/core' import { relative as relativePath } from 'path' diff --git a/packages/next/src/build/babel/preset.ts b/packages/next/src/build/babel/preset.ts index 5ea2a647a5e9b..4a2f34fb825f4 100644 --- a/packages/next/src/build/babel/preset.ts +++ b/packages/next/src/build/babel/preset.ts @@ -1,4 +1,4 @@ -import { PluginItem } from 'next/dist/compiled/babel/core' +import type { PluginItem } from 'next/dist/compiled/babel/core' import { dirname } from 'path' const isLoadIntentTest = process.env.NODE_ENV === 'test' diff --git a/packages/next/src/build/collect-build-traces.ts b/packages/next/src/build/collect-build-traces.ts index e64fd17834698..54f72c254a91a 100644 --- a/packages/next/src/build/collect-build-traces.ts +++ b/packages/next/src/build/collect-build-traces.ts @@ -14,7 +14,7 @@ import { import path from 'path' import fs from 'fs/promises' -import { PageInfo } from './utils' +import type { PageInfo } from './utils' import { loadBindings } from './swc' import { nonNullable } from '../lib/non-nullable' import * as ciEnvironment from '../telemetry/ci-info' diff --git a/packages/next/src/build/compiler.ts b/packages/next/src/build/compiler.ts index 8af624eae1dc0..5206a4d7813ad 100644 --- a/packages/next/src/build/compiler.ts +++ b/packages/next/src/build/compiler.ts @@ -1,5 +1,5 @@ import { webpack } from 'next/dist/compiled/webpack/webpack' -import { Span } from '../trace' +import type { Span } from '../trace' export type CompilerResult = { errors: webpack.StatsError[] diff --git a/packages/next/src/build/entries.ts b/packages/next/src/build/entries.ts index 551f2a5e960b0..828eb49bda84e 100644 --- a/packages/next/src/build/entries.ts +++ b/packages/next/src/build/entries.ts @@ -32,11 +32,11 @@ import { CLIENT_STATIC_FILES_RUNTIME_MAIN_APP, CLIENT_STATIC_FILES_RUNTIME_POLYFILLS, CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH, - CompilerNameValues, COMPILER_NAMES, EDGE_RUNTIME_WEBPACK, } from '../shared/lib/constants' -import { __ApiPreviewProps } from '../server/api-utils' +import type { CompilerNameValues } from '../shared/lib/constants' +import type { __ApiPreviewProps } from '../server/api-utils' import { warn } from './output/log' import { isMiddlewareFile, @@ -46,10 +46,10 @@ import { import { getPageStaticInfo } from './analysis/get-page-static-info' import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' -import { ServerRuntime } from '../../types' +import type { ServerRuntime } from '../../types' import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import { encodeMatchers } from './webpack/loaders/next-middleware-loader' -import { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader' +import type { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader' import { isAppRouteRoute } from '../lib/is-app-route-route' import { normalizeMetadataRoute } from '../lib/metadata/get-metadata-route' import { getRouteLoaderEntry } from './webpack/loaders/next-route-loader' diff --git a/packages/next/src/build/handle-externals.ts b/packages/next/src/build/handle-externals.ts index a52f9dea1a021..2e0eb816b1495 100644 --- a/packages/next/src/build/handle-externals.ts +++ b/packages/next/src/build/handle-externals.ts @@ -1,4 +1,5 @@ -import { WebpackLayerName, WEBPACK_LAYERS } from '../lib/constants' +import { WEBPACK_LAYERS } from '../lib/constants' +import type { WebpackLayerName } from '../lib/constants' import { defaultOverrides } from '../server/require-hook' import { BARREL_OPTIMIZATION_PREFIX } from '../shared/lib/constants' import path from '../shared/lib/isomorphic/path' @@ -9,7 +10,7 @@ import { NODE_RESOLVE_OPTIONS, } from './webpack-config' import { isWebpackAppLayer, isWebpackServerLayer } from './worker' -import { NextConfigComplete } from '../server/config-shared' +import type { NextConfigComplete } from '../server/config-shared' const reactPackagesRegex = /^(react|react-dom|react-server-dom-webpack)($|\/)/ const pathSeparators = '[/\\\\]' diff --git a/packages/next/src/build/index.ts b/packages/next/src/build/index.ts index a226078d05853..4b6654d25349c 100644 --- a/packages/next/src/build/index.ts +++ b/packages/next/src/build/index.ts @@ -31,9 +31,11 @@ import { import { FileType, fileExists } from '../lib/file-exists' import { findPagesDir } from '../lib/find-pages-dir' import loadCustomRoutes, { + normalizeRouteRegex, +} from '../lib/load-custom-routes' +import type { CustomRoutes, Header, - normalizeRouteRegex, Redirect, Rewrite, RouteHas, @@ -72,9 +74,9 @@ import { FUNCTIONS_CONFIG_MANIFEST, } from '../shared/lib/constants' import { getSortedRoutes, isDynamicRoute } from '../shared/lib/router/utils' -import { __ApiPreviewProps } from '../server/api-utils' +import type { __ApiPreviewProps } from '../server/api-utils' import loadConfig from '../server/config' -import { BuildManifest } from '../server/get-page-files' +import type { BuildManifest } from '../server/get-page-files' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { getPagePath } from '../server/require' import * as ciEnvironment from '../telemetry/ci-info' @@ -84,10 +86,10 @@ import { eventBuildFeatureUsage, eventNextPlugins, EVENT_BUILD_FEATURE_USAGE, - EventBuildFeatureUsage, eventPackageUsedInGetServerSideProps, eventBuildCompleted, } from '../telemetry/events' +import type { EventBuildFeatureUsage } from '../telemetry/events' import { Telemetry } from '../telemetry/storage' import { isDynamicMetadataRoute, @@ -103,17 +105,17 @@ import { detectConflictingPaths, computeFromManifest, getJsPageSizeInKb, - PageInfo, printCustomRoutes, printTreeView, copyTracedFiles, isReservedPage, - AppConfig, isAppBuiltinNotFoundPage, } from './utils' +import type { PageInfo, AppConfig } from './utils' import { writeBuildId } from './write-build-id' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' -import isError, { NextError } from '../lib/is-error' +import isError from '../lib/is-error' +import type { NextError } from '../lib/is-error' import { isEdgeRuntime } from '../lib/is-edge-runtime' import { recursiveCopy } from '../lib/recursive-copy' import { recursiveReadDir } from '../lib/recursive-readdir' @@ -149,7 +151,7 @@ import { buildDataRoute } from '../server/lib/router-utils/build-data-route' import { initialize as initializeIncrementalCache } from '../server/lib/incremental-cache-server' import { nodeFs } from '../server/lib/node-fs-methods' import { collectBuildTraces } from './collect-build-traces' -import { BuildTraceContext } from './webpack/plugins/next-trace-entrypoints-plugin' +import type { BuildTraceContext } from './webpack/plugins/next-trace-entrypoints-plugin' import { formatManifest } from './manifests/formatter/format-manifest' interface ExperimentalBypassForInfo { diff --git a/packages/next/src/build/load-jsconfig.ts b/packages/next/src/build/load-jsconfig.ts index aaca3d52f7061..28f37dc6ce7d3 100644 --- a/packages/next/src/build/load-jsconfig.ts +++ b/packages/next/src/build/load-jsconfig.ts @@ -1,6 +1,6 @@ import path from 'path' import fs from 'fs' -import { NextConfigComplete } from '../server/config-shared' +import type { NextConfigComplete } from '../server/config-shared' import * as Log from './output/log' import { getTypeScriptConfiguration } from '../lib/typescript/getTypeScriptConfiguration' import { readFileSync } from 'fs' diff --git a/packages/next/src/build/output/index.ts b/packages/next/src/build/output/index.ts index 60932a079c11e..1519fe64387e8 100644 --- a/packages/next/src/build/output/index.ts +++ b/packages/next/src/build/output/index.ts @@ -3,9 +3,11 @@ import stripAnsi from 'next/dist/compiled/strip-ansi' import textTable from 'next/dist/compiled/text-table' import createStore from 'next/dist/compiled/unistore' import formatWebpackMessages from '../../client/dev/error-overlay/format-webpack-messages' -import { OutputState, store as consoleStore } from './store' +import { store as consoleStore } from './store' +import type { OutputState } from './store' import type { webpack } from 'next/dist/compiled/webpack/webpack' -import { CompilerNameValues, COMPILER_NAMES } from '../../shared/lib/constants' +import { COMPILER_NAMES } from '../../shared/lib/constants' +import type { CompilerNameValues } from '../../shared/lib/constants' export function startedDevelopmentServer(appUrl: string, bindAddr: string) { consoleStore.setState({ appUrl, bindAddr }) diff --git a/packages/next/src/build/swc/index.ts b/packages/next/src/build/swc/index.ts index 6accfadab603c..7d7f2ea107d49 100644 --- a/packages/next/src/build/swc/index.ts +++ b/packages/next/src/build/swc/index.ts @@ -8,12 +8,10 @@ import { getParserOptions } from './options' import { eventSwcLoadFailure } from '../../telemetry/events/swc-load-failure' import { patchIncorrectLockfile } from '../../lib/patch-incorrect-lockfile' import { downloadWasmSwc, downloadNativeNextSwc } from '../../lib/download-swc' -import { NextConfigComplete, TurboRule } from '../../server/config-shared' +import type { NextConfigComplete, TurboRule } from '../../server/config-shared' import { isDeepStrictEqual } from 'util' -import { - DefineEnvPluginOptions, - getDefineEnv, -} from '../webpack/plugins/define-env-plugin' +import { getDefineEnv } from '../webpack/plugins/define-env-plugin' +import type { DefineEnvPluginOptions } from '../webpack/plugins/define-env-plugin' const nextVersion = process.env.__NEXT_VERSION as string diff --git a/packages/next/src/build/swc/options.ts b/packages/next/src/build/swc/options.ts index 66fc96dc66573..f92bd3c99fd6f 100644 --- a/packages/next/src/build/swc/options.ts +++ b/packages/next/src/build/swc/options.ts @@ -321,7 +321,6 @@ export function getLoaderSWCOptions({ hasServerComponents, isServerLayer, isServerActionsEnabled, - optimizeBarrelExports, bundleTarget, }: // This is not passed yet as "paths" resolving is handled by webpack currently. // resolvedBaseUrl, @@ -348,9 +347,6 @@ export function getLoaderSWCOptions({ hasServerComponents?: boolean isServerLayer: boolean isServerActionsEnabled?: boolean - optimizeBarrelExports?: { - wildcard: boolean - } }) { let baseOptions: any = getBaseSWCOptions({ filename, @@ -405,9 +401,6 @@ export function getLoaderSWCOptions({ packages: optimizePackageImports, } } - if (optimizeBarrelExports) { - baseOptions.optimizeBarrelExports = optimizeBarrelExports - } const isNextDist = nextDistPath.test(filename) diff --git a/packages/next/src/build/type-check.ts b/packages/next/src/build/type-check.ts index b52cfb6d9743d..c8c18352311da 100644 --- a/packages/next/src/build/type-check.ts +++ b/packages/next/src/build/type-check.ts @@ -11,12 +11,12 @@ import { eventTypeCheckCompleted } from '../telemetry/events' import isError from '../lib/is-error' /** - * typescript will be loaded in "next/lib/verifyTypeScriptSetup" and + * typescript will be loaded in "next/lib/verify-typescript-setup" and * then passed to "next/lib/typescript/runTypeCheck" as a parameter. * * Since it is impossible to pass a function from main thread to a worker, * instead of running "next/lib/typescript/runTypeCheck" in a worker, - * we will run entire "next/lib/verifyTypeScriptSetup" in a worker instead. + * we will run entire "next/lib/verify-typescript-setup" in a worker instead. */ function verifyTypeScriptSetup( dir: string, @@ -31,14 +31,14 @@ function verifyTypeScriptSetup( hasPagesDir: boolean ) { const typeCheckWorker = new JestWorker( - require.resolve('../lib/verifyTypeScriptSetup'), + require.resolve('../lib/verify-typescript-setup'), { numWorkers: 1, enableWorkerThreads, maxRetries: 0, } ) as JestWorker & { - verifyTypeScriptSetup: typeof import('../lib/verifyTypeScriptSetup').verifyTypeScriptSetup + verifyTypeScriptSetup: typeof import('../lib/verify-typescript-setup').verifyTypeScriptSetup } typeCheckWorker.getStdout().pipe(process.stdout) diff --git a/packages/next/src/build/utils.ts b/packages/next/src/build/utils.ts index 824d86b9845eb..beb14976125d3 100644 --- a/packages/next/src/build/utils.ts +++ b/packages/next/src/build/utils.ts @@ -50,10 +50,8 @@ import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing- import { isEdgeRuntime } from '../lib/is-edge-runtime' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import * as Log from './output/log' -import { - loadComponents, - LoadComponentsReturnType, -} from '../server/load-components' +import { loadComponents } from '../server/load-components' +import type { LoadComponentsReturnType } from '../server/load-components' import { trace } from '../trace' import { setHttpClientAndAgentOptions } from '../server/setup-http-agent-env' import { Sema } from 'next/dist/compiled/async-sema' @@ -1927,7 +1925,8 @@ export async function copyTracedFiles( serverOutputPath, `${ moduleType - ? `import path from 'path' + ? `performance.mark('next-start'); +import path from 'path' import { fileURLToPath } from 'url' import module from 'module' const require = module.createRequire(import.meta.url) diff --git a/packages/next/src/build/webpack-build/impl.ts b/packages/next/src/build/webpack-build/impl.ts index d0c686c2c3d74..d64f0eaca9d03 100644 --- a/packages/next/src/build/webpack-build/impl.ts +++ b/packages/next/src/build/webpack-build/impl.ts @@ -1,18 +1,18 @@ -import { type webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/compiled/webpack/webpack' import { red } from '../../lib/picocolors' import formatWebpackMessages from '../../client/dev/error-overlay/format-webpack-messages' import { nonNullable } from '../../lib/non-nullable' +import type { COMPILER_INDEXES } from '../../shared/lib/constants' import { COMPILER_NAMES, CLIENT_STATIC_FILES_RUNTIME_MAIN_APP, APP_CLIENT_INTERNALS, PHASE_PRODUCTION_BUILD, - COMPILER_INDEXES, } from '../../shared/lib/constants' import { runCompiler } from '../compiler' import * as Log from '../output/log' import getBaseWebpackConfig, { loadProjectInfo } from '../webpack-config' -import { NextError } from '../../lib/is-error' +import type { NextError } from '../../lib/is-error' import { TelemetryPlugin } from '../webpack/plugins/telemetry-plugin' import { NextBuildContext, @@ -23,11 +23,9 @@ import { createEntrypoints } from '../entries' import loadConfig from '../../server/config' import { trace } from '../../trace' import { WEBPACK_LAYERS } from '../../lib/constants' -import { - BuildTraceContext, - TraceEntryPointsPlugin, -} from '../webpack/plugins/next-trace-entrypoints-plugin' -import { UnwrapPromise } from '../../lib/coalesced-function' +import { TraceEntryPointsPlugin } from '../webpack/plugins/next-trace-entrypoints-plugin' +import type { BuildTraceContext } from '../webpack/plugins/next-trace-entrypoints-plugin' +import type { UnwrapPromise } from '../../lib/coalesced-function' import origDebug from 'next/dist/compiled/debug' diff --git a/packages/next/src/build/webpack-build/index.ts b/packages/next/src/build/webpack-build/index.ts index 9d5855f8c5072..6d55342f1ebce 100644 --- a/packages/next/src/build/webpack-build/index.ts +++ b/packages/next/src/build/webpack-build/index.ts @@ -1,10 +1,10 @@ -import { COMPILER_INDEXES } from '../../shared/lib/constants' +import type { COMPILER_INDEXES } from '../../shared/lib/constants' import * as Log from '../output/log' import { NextBuildContext } from '../build-context' import type { BuildTraceContext } from '../webpack/plugins/next-trace-entrypoints-plugin' import { Worker } from 'next/dist/compiled/jest-worker' import origDebug from 'next/dist/compiled/debug' -import { ChildProcess } from 'child_process' +import type { ChildProcess } from 'child_process' import path from 'path' const debug = origDebug('next:build:webpack-build') diff --git a/packages/next/src/build/webpack-config.ts b/packages/next/src/build/webpack-config.ts index de5d19591b091..1a3344be3a1d7 100644 --- a/packages/next/src/build/webpack-config.ts +++ b/packages/next/src/build/webpack-config.ts @@ -17,10 +17,10 @@ import { RSC_ACTION_CLIENT_WRAPPER_ALIAS, RSC_ACTION_VALIDATE_ALIAS, WEBPACK_RESOURCE_QUERIES, - WebpackLayerName, } from '../lib/constants' +import type { WebpackLayerName } from '../lib/constants' import { isWebpackDefaultLayer, isWebpackServerLayer } from './utils' -import { CustomRoutes } from '../lib/load-custom-routes.js' +import type { CustomRoutes } from '../lib/load-custom-routes.js' import { CLIENT_STATIC_FILES_RUNTIME_AMP, CLIENT_STATIC_FILES_RUNTIME_MAIN, @@ -32,10 +32,10 @@ import { REACT_LOADABLE_MANIFEST, SERVER_DIRECTORY, COMPILER_NAMES, - CompilerNameValues, } from '../shared/lib/constants' +import type { CompilerNameValues } from '../shared/lib/constants' import { execOnce } from '../shared/lib/utils' -import { NextConfigComplete } from '../server/config-shared' +import type { NextConfigComplete } from '../server/config-shared' import { finalizeEntrypoint } from './entries' import * as Log from './output/log' import { buildConfiguration } from './webpack/config' @@ -72,7 +72,7 @@ import { getBabelConfigFile } from './get-babel-config-file' import { defaultOverrides } from '../server/require-hook' import { needsExperimentalReact } from '../lib/needs-experimental-react' import { getDefineEnvPlugin } from './webpack/plugins/define-env-plugin' -import { SWCLoaderOptions } from './webpack/loaders/next-swc-loader' +import type { SWCLoaderOptions } from './webpack/loaders/next-swc-loader' import { isResourceInPackages, makeExternalHandler } from './handle-externals' type ExcludesFalse = (x: T | false) => x is T @@ -1412,27 +1412,6 @@ export default async function getBaseWebpackConfig( }, module: { rules: [ - { - // This loader rule passes the resource to the SWC loader with - // `optimizeBarrelExports` enabled. This option makes the SWC to - // transform the original code to be a JSON of its export map, so - // the barrel loader can analyze it and only keep the needed ones. - test: /__barrel_transform__/, - use: ({ resourceQuery }: { resourceQuery: string }) => { - const isFromWildcardExport = /[&?]wildcard/.test(resourceQuery) - - return [ - getSwcLoader({ - isServerLayer: false, - bundleTarget: 'client', - hasServerComponents: false, - optimizeBarrelExports: { - wildcard: isFromWildcardExport, - }, - }), - ] - }, - }, { // This loader rule works like a bridge between user's import and // the target module behind a package's barrel file. It reads SWC's @@ -1443,14 +1422,18 @@ export default async function getBaseWebpackConfig( const names = ( resourceQuery.match(/\?names=([^&]+)/)?.[1] || '' ).split(',') - const isFromWildcardExport = /[&?]wildcard/.test(resourceQuery) return [ { loader: 'next-barrel-loader', options: { names, - wildcard: isFromWildcardExport, + swcCacheDir: path.join( + dir, + config?.distDir ?? '.next', + 'cache', + 'swc' + ), }, // This is part of the request value to serve as the module key. // The barrel loader are no-op re-exported modules keyed by diff --git a/packages/next/src/build/webpack/config/blocks/base.ts b/packages/next/src/build/webpack/config/blocks/base.ts index c580c056faaef..2fc42f11bcb80 100644 --- a/packages/next/src/build/webpack/config/blocks/base.ts +++ b/packages/next/src/build/webpack/config/blocks/base.ts @@ -1,7 +1,7 @@ import curry from 'next/dist/compiled/lodash.curry' -import { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/compiled/webpack/webpack' import { COMPILER_NAMES } from '../../../../shared/lib/constants' -import { ConfigurationContext } from '../utils' +import type { ConfigurationContext } from '../utils' export const base = curry(function base( ctx: ConfigurationContext, diff --git a/packages/next/src/build/webpack/config/blocks/css/index.ts b/packages/next/src/build/webpack/config/blocks/css/index.ts index 632c5fa959993..4cd621d937f5c 100644 --- a/packages/next/src/build/webpack/config/blocks/css/index.ts +++ b/packages/next/src/build/webpack/config/blocks/css/index.ts @@ -1,7 +1,8 @@ import curry from 'next/dist/compiled/lodash.curry' -import { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/compiled/webpack/webpack' import { loader, plugin } from '../../helpers' -import { ConfigurationContext, ConfigurationFn, pipe } from '../../utils' +import { pipe } from '../../utils' +import type { ConfigurationContext, ConfigurationFn } from '../../utils' import { getCssModuleLoader, getGlobalCssLoader } from './loaders' import { getNextFontLoader } from './loaders/next-font' import { diff --git a/packages/next/src/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent.ts b/packages/next/src/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent.ts index 567329efb404f..2291a07484e4d 100644 --- a/packages/next/src/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent.ts +++ b/packages/next/src/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent.ts @@ -1,6 +1,6 @@ import loaderUtils from 'next/dist/compiled/loader-utils3' import path from 'path' -import { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/compiled/webpack/webpack' const regexLikeIndexModule = /(?() + +async function getBarrelMapping( + resourcePath: string, + swcCacheDir: string, + resolve: (context: string, request: string) => Promise, + fs: { + readFile: ( + path: string, + callback: (err: any, data: string | Buffer | undefined) => void + ) => void + } +) { + if (barrelTransformMappingCache.has(resourcePath)) { + return barrelTransformMappingCache.get(resourcePath)! + } + + // This is a SWC transform specifically for `optimizeBarrelExports`. We don't + // care about other things but the export map only. + async function transpileSource( + filename: string, + source: string, + isWildcard: boolean + ) { + const isTypeScript = filename.endsWith('.ts') || filename.endsWith('.tsx') + return new Promise((res) => + transform(source, { + filename, + inputSourceMap: undefined, + sourceFileName: filename, + optimizeBarrelExports: { + wildcard: isWildcard, + }, + jsc: { + parser: { + syntax: isTypeScript ? 'typescript' : 'ecmascript', + [isTypeScript ? 'tsx' : 'jsx']: true, + }, + experimental: { + cacheRoot: swcCacheDir, + }, + }, + }).then((output) => { + res(output.code) + }) + ) + } + + // Avoid circular `export *` dependencies + const visited = new Set() + async function getMatches(file: string, isWildcard: boolean) { + if (visited.has(file)) { + return null + } + visited.add(file) + + const source = await new Promise((res, rej) => { + fs.readFile(file, (err, data) => { + if (err || data === undefined) { + rej(err) + } else { + res(data.toString()) + } + }) + }) + + const output = await transpileSource(file, source, isWildcard) + + const matches = output.match( + /^([^]*)export (const|var) __next_private_export_map__ = ('[^']+'|"[^"]+")/ + ) + if (!matches) { + return null + } + + const prefix = matches[1] + let exportList = JSON.parse(matches[3].slice(1, -1)) as [ + string, + string, + string + ][] + const wildcardExports = [ + ...output.matchAll(/export \* from "([^"]+)"/g), + ].map((match) => match[1]) + + // In the wildcard case, if the value is exported from another file, we + // redirect to that file (decl[0]). Otherwise, export from the current + // file itself. + if (isWildcard) { + for (const decl of exportList) { + decl[1] = file + decl[2] = decl[0] + } + } + + // This recursively handles the wildcard exports (e.g. `export * from './a'`) + if (wildcardExports.length) { + await Promise.all( + wildcardExports.map(async (req) => { + const targetPath = await resolve( + path.dirname(file), + req.replace('__barrel_optimize__?names=__PLACEHOLDER__!=!', '') + ) + + const targetMatches = await getMatches(targetPath, true) + if (targetMatches) { + // Merge the export list + exportList = exportList.concat(targetMatches.exportList) + } + }) + ) + } + + return { + prefix, + exportList, + wildcardExports, + } + } + + const res = await getMatches(resourcePath, false) + barrelTransformMappingCache.set(resourcePath, res) + + return res +} + const NextBarrelLoader = async function ( this: webpack.LoaderContext<{ names: string[] - wildcard: boolean + swcCacheDir: string }> ) { this.async() - const { names, wildcard } = this.getOptions() - - const source = await new Promise((resolve, reject) => { - this.loadModule( - `__barrel_transform__${wildcard ? '?wildcard' : ''}!=!${ - this.resourcePath - }`, - (err, src) => { - if (err) { - reject(err) - } else { - resolve(src) - } - } - ) + this.cacheable(true) + + const { names, swcCacheDir } = this.getOptions() + + // For barrel optimizations, we always prefer the "module" field over the + // "main" field because ESM handling is more robust with better tree-shaking. + const resolve = this.getResolve({ + mainFields: ['module', 'main'], }) - const matches = source.match( - /^([^]*)export const __next_private_export_map__ = ('[^']+'|"[^"]+")/ + const mapping = await getBarrelMapping( + this.resourcePath, + swcCacheDir, + resolve, + this.fs ) - if (!matches) { + // `resolve` adds all sub-paths to the dependency graph. However, we already + // cached the mapping and we assume them to not change. So, we can safely + // clear the dependencies here to avoid unnecessary watchers which turned out + // to be very expensive. + this.clearDependencies() + + if (!mapping) { // This file isn't a barrel and we can't apply any optimizations. Let's re-export everything. // Since this loader accepts `names` and the request is keyed with `names`, we can't simply // return the original source here. That will create these imports with different names as @@ -123,19 +265,12 @@ const NextBarrelLoader = async function ( return } - const wildcardExports = [...source.matchAll(/export \* from "([^"]+)"/g)] - // It needs to keep the prefix for comments and directives like "use client". - const prefix = matches[1] - - const exportList = JSON.parse(matches[2].slice(1, -1)) as [ - string, - string, - string - ][] + const prefix = mapping.prefix + const exportList = mapping.exportList const exportMap = new Map() - for (const [name, path, orig] of exportList) { - exportMap.set(name, [path, orig]) + for (const [name, filePath, orig] of exportList) { + exportMap.set(name, [filePath, orig]) } let output = prefix @@ -145,15 +280,6 @@ const NextBarrelLoader = async function ( if (exportMap.has(name)) { const decl = exportMap.get(name)! - // In the wildcard case, if the value is exported from another file, we - // redirect to that file (decl[0]). Otherwise, export from the current - // file itself (this.resourcePath). - if (wildcard && !decl[0]) { - // E.g. the file contains `export const a = 1` - decl[0] = this.resourcePath - decl[1] = name - } - if (decl[1] === '*') { output += `\nexport * as ${name} from ${JSON.stringify(decl[0])}` } else if (decl[1] === 'default') { @@ -174,11 +300,9 @@ const NextBarrelLoader = async function ( // These are from wildcard exports. if (missedNames.length > 0) { - for (const match of wildcardExports) { - const path = match[1] - + for (const req of mapping.wildcardExports) { output += `\nexport * from ${JSON.stringify( - path.replace('__PLACEHOLDER__', missedNames.join(',') + '&wildcard') + req.replace('__PLACEHOLDER__', missedNames.join(',') + '&wildcard') )}` } } diff --git a/packages/next/src/build/webpack/loaders/next-edge-app-route-loader/index.ts b/packages/next/src/build/webpack/loaders/next-edge-app-route-loader/index.ts index e14db1b3b21b1..8b9b8d244a81e 100644 --- a/packages/next/src/build/webpack/loaders/next-edge-app-route-loader/index.ts +++ b/packages/next/src/build/webpack/loaders/next-edge-app-route-loader/index.ts @@ -1,9 +1,9 @@ import { getModuleBuildInfo } from '../get-module-build-info' import { stringifyRequest } from '../../stringify-request' -import { NextConfig } from '../../../../server/config-shared' -import { webpack } from 'next/dist/compiled/webpack/webpack' +import type { NextConfig } from '../../../../server/config-shared' +import type { webpack } from 'next/dist/compiled/webpack/webpack' import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants' -import { MiddlewareConfig } from '../../../analysis/get-page-static-info' +import type { MiddlewareConfig } from '../../../analysis/get-page-static-info' import { loadEntrypoint } from '../../../load-entrypoint' export type EdgeAppRouteLoaderQuery = { diff --git a/packages/next/src/build/webpack/loaders/next-edge-function-loader.ts b/packages/next/src/build/webpack/loaders/next-edge-function-loader.ts index c2149799d45c9..d147a340e1127 100644 --- a/packages/next/src/build/webpack/loaders/next-edge-function-loader.ts +++ b/packages/next/src/build/webpack/loaders/next-edge-function-loader.ts @@ -1,7 +1,7 @@ import type webpack from 'webpack' import { getModuleBuildInfo } from './get-module-build-info' import { stringifyRequest } from '../stringify-request' -import { MiddlewareConfig } from '../../analysis/get-page-static-info' +import type { MiddlewareConfig } from '../../analysis/get-page-static-info' export type EdgeFunctionLoaderOptions = { absolutePagePath: string diff --git a/packages/next/src/build/webpack/loaders/next-edge-ssr-loader/render.ts b/packages/next/src/build/webpack/loaders/next-edge-ssr-loader/render.ts index d4c4aa11138b0..dea29c64be74d 100644 --- a/packages/next/src/build/webpack/loaders/next-edge-ssr-loader/render.ts +++ b/packages/next/src/build/webpack/loaders/next-edge-ssr-loader/render.ts @@ -13,9 +13,9 @@ import { WebNextResponse, } from '../../../../server/base-http/web' import { SERVER_RUNTIME } from '../../../../lib/constants' -import { PrerenderManifest } from '../../..' +import type { PrerenderManifest } from '../../..' import { normalizeAppPath } from '../../../../shared/lib/router/utils/app-paths' -import { SizeLimit } from '../../../../../types' +import type { SizeLimit } from '../../../../../types' const NEXT_PRIVATE_GLOBAL_WAIT_UNTIL = Symbol.for( '__next_private_global_wait_until__' diff --git a/packages/next/src/build/webpack/loaders/next-font-loader/postcss-next-font.ts b/packages/next/src/build/webpack/loaders/next-font-loader/postcss-next-font.ts index e8a0cde20377d..cc2cc5e0aad3c 100644 --- a/packages/next/src/build/webpack/loaders/next-font-loader/postcss-next-font.ts +++ b/packages/next/src/build/webpack/loaders/next-font-loader/postcss-next-font.ts @@ -1,5 +1,6 @@ import type { AdjustFontFallback } from '../../../../../font' -import postcss, { Declaration } from 'postcss' +import type { Declaration } from 'postcss' +import postcss from 'postcss' /** * The next/font postcss plugin recieves the @font-face declarations returned from the next/font loaders. diff --git a/packages/next/src/build/webpack/loaders/next-swc-loader.ts b/packages/next/src/build/webpack/loaders/next-swc-loader.ts index 253ef9e39035a..6a18b06d9bd2b 100644 --- a/packages/next/src/build/webpack/loaders/next-swc-loader.ts +++ b/packages/next/src/build/webpack/loaders/next-swc-loader.ts @@ -45,9 +45,6 @@ export interface SWCLoaderOptions { bundleTarget: BundleType hasServerComponents?: boolean isServerLayer: boolean - optimizeBarrelExports?: { - wildcard: boolean - } } async function loaderTransform( @@ -73,19 +70,11 @@ async function loaderTransform( swcCacheDir, hasServerComponents, isServerLayer, - optimizeBarrelExports, bundleTarget, } = loaderOptions const isPageFile = filename.startsWith(pagesDir) const relativeFilePathFromRoot = path.relative(rootDir, filename) - // For testing purposes - if (process.env.NEXT_TEST_MODE) { - if (loaderOptions.optimizeBarrelExports) { - console.log('optimizeBarrelExports:', filename) - } - } - const swcOptions = getLoaderSWCOptions({ pagesDir, appDir, @@ -106,7 +95,6 @@ async function loaderTransform( hasServerComponents, isServerActionsEnabled: nextConfig?.experimental?.serverActions, isServerLayer, - optimizeBarrelExports, bundleTarget, }) diff --git a/packages/next/src/build/webpack/loaders/noop-loader.ts b/packages/next/src/build/webpack/loaders/noop-loader.ts index debcaebcdcdef..0d24991b45520 100644 --- a/packages/next/src/build/webpack/loaders/noop-loader.ts +++ b/packages/next/src/build/webpack/loaders/noop-loader.ts @@ -1,4 +1,4 @@ -import { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/compiled/webpack/webpack' const NoopLoader: webpack.LoaderDefinitionFunction = (source) => source export default NoopLoader diff --git a/packages/next/src/build/webpack/plugins/build-manifest-plugin.ts b/packages/next/src/build/webpack/plugins/build-manifest-plugin.ts index f67dbf9f688e3..015dd08426bfd 100644 --- a/packages/next/src/build/webpack/plugins/build-manifest-plugin.ts +++ b/packages/next/src/build/webpack/plugins/build-manifest-plugin.ts @@ -12,7 +12,7 @@ import { CLIENT_STATIC_FILES_RUNTIME_AMP, SYSTEM_ENTRYPOINTS, } from '../../../shared/lib/constants' -import { BuildManifest } from '../../../server/get-page-files' +import type { BuildManifest } from '../../../server/get-page-files' import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint' import { ampFirstEntryNamesMap } from './next-drop-client-page-plugin' import { getSortedRoutes } from '../../../shared/lib/router/utils' diff --git a/packages/next/src/build/webpack/plugins/css-minimizer-plugin.ts b/packages/next/src/build/webpack/plugins/css-minimizer-plugin.ts index 7d2a328a94add..d79ad14b71b4e 100644 --- a/packages/next/src/build/webpack/plugins/css-minimizer-plugin.ts +++ b/packages/next/src/build/webpack/plugins/css-minimizer-plugin.ts @@ -1,6 +1,7 @@ import cssnanoSimple from 'next/dist/compiled/cssnano-simple' import postcssScss from 'next/dist/compiled/postcss-scss' -import postcss, { Parser } from 'postcss' +import postcss from 'postcss' +import type { Parser } from 'postcss' import { webpack, sources } from 'next/dist/compiled/webpack/webpack' import { spans } from './profiling-plugin' diff --git a/packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts b/packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts index 0c2e964c7439e..c62935a243a84 100644 --- a/packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts +++ b/packages/next/src/build/webpack/plugins/flight-client-entry-plugin.ts @@ -32,7 +32,7 @@ import { import { traverseModules, forEachEntryModule } from '../utils' import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep' import { getProxiedPluginState } from '../../build-context' -import { SizeLimit } from '../../../../types' +import type { SizeLimit } from '../../../../types' interface Options { dev: boolean diff --git a/packages/next/src/build/webpack/plugins/font-stylesheet-gathering-plugin.ts b/packages/next/src/build/webpack/plugins/font-stylesheet-gathering-plugin.ts index ea5eedfb28fd9..399bc60aa7d48 100644 --- a/packages/next/src/build/webpack/plugins/font-stylesheet-gathering-plugin.ts +++ b/packages/next/src/build/webpack/plugins/font-stylesheet-gathering-plugin.ts @@ -6,8 +6,8 @@ import { import { getFontDefinitionFromNetwork, getFontOverrideCss, - FontManifest, } from '../../../server/font-utils' +import type { FontManifest } from '../../../server/font-utils' import postcss from 'postcss' import minifier from 'next/dist/compiled/cssnano-simple' import { diff --git a/packages/next/src/build/webpack/plugins/jsconfig-paths-plugin.ts b/packages/next/src/build/webpack/plugins/jsconfig-paths-plugin.ts index 25b73740cdd4c..2e65e9e74ed33 100644 --- a/packages/next/src/build/webpack/plugins/jsconfig-paths-plugin.ts +++ b/packages/next/src/build/webpack/plugins/jsconfig-paths-plugin.ts @@ -4,7 +4,7 @@ * https://github.com/microsoft/TypeScript/blob/214df64e287804577afa1fea0184c18c40f7d1ca/LICENSE.txt */ import path from 'path' -import { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/compiled/webpack/webpack' import { debug } from 'next/dist/compiled/debug' const log = debug('next:jsconfig-paths-plugin') diff --git a/packages/next/src/build/webpack/plugins/memory-with-gc-cache-plugin.ts b/packages/next/src/build/webpack/plugins/memory-with-gc-cache-plugin.ts index 8a0f6b480c2c3..65c734378270d 100644 --- a/packages/next/src/build/webpack/plugins/memory-with-gc-cache-plugin.ts +++ b/packages/next/src/build/webpack/plugins/memory-with-gc-cache-plugin.ts @@ -32,7 +32,8 @@ The default for max generations is 5, so 1/5th of the modules would be marked fo This plugin instead always checks the cache and decreases the time to live of all entries. That way memory is cleaned up earlier. */ -import { type Compiler, webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/compiled/webpack/webpack' +import type { Compiler } from 'next/dist/compiled/webpack/webpack' // Webpack doesn't expose Etag as a type so get it this way instead. type Etag = Parameters[1] diff --git a/packages/next/src/build/webpack/plugins/middleware-plugin.ts b/packages/next/src/build/webpack/plugins/middleware-plugin.ts index 07536f36831b2..17fe1c6cb6754 100644 --- a/packages/next/src/build/webpack/plugins/middleware-plugin.ts +++ b/packages/next/src/build/webpack/plugins/middleware-plugin.ts @@ -22,8 +22,8 @@ import { SERVER_REFERENCE_MANIFEST, PRERENDER_MANIFEST, } from '../../../shared/lib/constants' -import { MiddlewareConfig } from '../../analysis/get-page-static-info' -import { Telemetry } from '../../../telemetry/storage' +import type { MiddlewareConfig } from '../../analysis/get-page-static-info' +import type { Telemetry } from '../../../telemetry/storage' import { traceGlobals } from '../../../trace/shared' import { EVENT_BUILD_FEATURE_USAGE } from '../../../telemetry/events' import { normalizeAppPath } from '../../../shared/lib/router/utils/app-paths' diff --git a/packages/next/src/build/webpack/plugins/next-drop-client-page-plugin.ts b/packages/next/src/build/webpack/plugins/next-drop-client-page-plugin.ts index 0706a8515afd3..b03428e7c32cb 100644 --- a/packages/next/src/build/webpack/plugins/next-drop-client-page-plugin.ts +++ b/packages/next/src/build/webpack/plugins/next-drop-client-page-plugin.ts @@ -1,4 +1,4 @@ -import { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/compiled/webpack/webpack' import { STRING_LITERAL_DROP_BUNDLE } from '../../../shared/lib/constants' export const ampFirstEntryNamesMap: WeakMap = diff --git a/packages/next/src/build/webpack/plugins/next-trace-entrypoints-plugin.ts b/packages/next/src/build/webpack/plugins/next-trace-entrypoints-plugin.ts index 7ce133dbb774d..1f61d3520d29d 100644 --- a/packages/next/src/build/webpack/plugins/next-trace-entrypoints-plugin.ts +++ b/packages/next/src/build/webpack/plugins/next-trace-entrypoints-plugin.ts @@ -1,11 +1,9 @@ import nodePath from 'path' -import { Span } from '../../../trace' +import type { Span } from '../../../trace' import { spans } from './profiling-plugin' import isError from '../../../lib/is-error' -import { - nodeFileTrace, - NodeFileTraceReasons, -} from 'next/dist/compiled/@vercel/nft' +import { nodeFileTrace } from 'next/dist/compiled/@vercel/nft' +import type { NodeFileTraceReasons } from 'next/dist/compiled/@vercel/nft' import { CLIENT_REFERENCE_MANIFEST, TRACE_OUTPUT_VERSION, @@ -15,7 +13,7 @@ import { NODE_ESM_RESOLVE_OPTIONS, NODE_RESOLVE_OPTIONS, } from '../../webpack-config' -import { NextConfigComplete } from '../../../server/config-shared' +import type { NextConfigComplete } from '../../../server/config-shared' import { loadBindings } from '../../swc' import { isMatch } from 'next/dist/compiled/micromatch' import { getModuleBuildInfo } from '../loaders/get-module-build-info' diff --git a/packages/next/src/build/webpack/plugins/profiling-plugin.ts b/packages/next/src/build/webpack/plugins/profiling-plugin.ts index 1534368c298c7..c2c48b3de2d08 100644 --- a/packages/next/src/build/webpack/plugins/profiling-plugin.ts +++ b/packages/next/src/build/webpack/plugins/profiling-plugin.ts @@ -1,5 +1,5 @@ import { NormalModule } from 'next/dist/compiled/webpack/webpack' -import { Span } from '../../../trace' +import type { Span } from '../../../trace' import type { webpack } from 'next/dist/compiled/webpack/webpack' const pluginName = 'ProfilingPlugin' diff --git a/packages/next/src/build/webpack/plugins/telemetry-plugin.ts b/packages/next/src/build/webpack/plugins/telemetry-plugin.ts index 156ef5802d24d..9299dd78206cb 100644 --- a/packages/next/src/build/webpack/plugins/telemetry-plugin.ts +++ b/packages/next/src/build/webpack/plugins/telemetry-plugin.ts @@ -1,4 +1,5 @@ -import { NormalModule, webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/compiled/webpack/webpack' +import { NormalModule } from 'next/dist/compiled/webpack/webpack' /** * List of target triples next-swc native binary supports. diff --git a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/webpackModuleError.ts b/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/webpackModuleError.ts index 6862511ea0de6..4281344e71ed2 100644 --- a/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/webpackModuleError.ts +++ b/packages/next/src/build/webpack/plugins/wellknown-errors-plugin/webpackModuleError.ts @@ -6,7 +6,7 @@ import { getBabelError } from './parseBabel' import { getCssError } from './parseCss' import { getScssError } from './parseScss' import { getNotFoundError, getImageError } from './parseNotFoundError' -import { SimpleWebpackError } from './simpleWebpackError' +import type { SimpleWebpackError } from './simpleWebpackError' import isError from '../../../../lib/is-error' import { getRscError } from './parseRSC' import { getNextFontError } from './parseNextFontError' diff --git a/packages/next/src/build/webpack/utils.ts b/packages/next/src/build/webpack/utils.ts index 8470a323642e1..95aa01b18bc23 100644 --- a/packages/next/src/build/webpack/utils.ts +++ b/packages/next/src/build/webpack/utils.ts @@ -1,4 +1,4 @@ -import { webpack } from 'next/dist/compiled/webpack/webpack' +import type { webpack } from 'next/dist/compiled/webpack/webpack' import { isAppRouteRoute } from '../../lib/is-app-route-route' export function traverseModules( diff --git a/packages/next/src/cli/next-build-args.ts b/packages/next/src/cli/next-build-args.ts index 814ac16df8396..7d328bc68935a 100755 --- a/packages/next/src/cli/next-build-args.ts +++ b/packages/next/src/cli/next-build-args.ts @@ -1,4 +1,4 @@ -import arg from 'next/dist/compiled/arg/index.js' +import type arg from 'next/dist/compiled/arg/index.js' export const validArgs: arg.Spec = { // Types diff --git a/packages/next/src/cli/next-build.ts b/packages/next/src/cli/next-build.ts index d0b3334e55454..634bbc0fc5a59 100755 --- a/packages/next/src/cli/next-build.ts +++ b/packages/next/src/cli/next-build.ts @@ -3,7 +3,7 @@ import '../server/lib/cpu-profile' import { existsSync } from 'fs' import * as Log from '../build/output/log' -import { CliCommand } from '../lib/commands' +import type { CliCommand } from '../lib/commands' import build from '../build' import { printAndExit } from '../server/lib/utils' import isError from '../lib/is-error' diff --git a/packages/next/src/cli/next-dev-args.ts b/packages/next/src/cli/next-dev-args.ts index 7d89d04b41940..a1ce6258936d7 100644 --- a/packages/next/src/cli/next-dev-args.ts +++ b/packages/next/src/cli/next-dev-args.ts @@ -1,4 +1,4 @@ -import arg from 'next/dist/compiled/arg/index.js' +import type arg from 'next/dist/compiled/arg/index.js' export const validArgs: arg.Spec = { // Types diff --git a/packages/next/src/cli/next-dev.ts b/packages/next/src/cli/next-dev.ts index 70546ea42f008..9805f183f2dd0 100644 --- a/packages/next/src/cli/next-dev.ts +++ b/packages/next/src/cli/next-dev.ts @@ -4,21 +4,19 @@ import '../server/lib/cpu-profile' import type { StartServerOptions } from '../server/lib/start-server' import { RESTART_EXIT_CODE, getPort, printAndExit } from '../server/lib/utils' import * as Log from '../build/output/log' -import { CliCommand } from '../lib/commands' +import type { CliCommand } from '../lib/commands' import { getProjectDir } from '../lib/get-project-dir' import { PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants' import path from 'path' -import { NextConfigComplete } from '../server/config-shared' +import type { NextConfigComplete } from '../server/config-shared' import { setGlobal, traceGlobals } from '../trace/shared' import { Telemetry } from '../telemetry/storage' import loadConfig, { getEnabledExperimentalFeatures } from '../server/config' import { findPagesDir } from '../lib/find-pages-dir' import { fileExists, FileType } from '../lib/file-exists' import { getNpxCommand } from '../lib/helpers/get-npx-command' -import { - SelfSignedCertificate, - createSelfSignedCertificate, -} from '../lib/mkcert' +import { createSelfSignedCertificate } from '../lib/mkcert' +import type { SelfSignedCertificate } from '../lib/mkcert' import uploadTrace from '../trace/upload-trace' import { initialEnv, loadEnvConfig } from '@next/env' import { trace } from '../trace' diff --git a/packages/next/src/cli/next-export-args.ts b/packages/next/src/cli/next-export-args.ts index e6c66da77dd30..f573274be7a1b 100755 --- a/packages/next/src/cli/next-export-args.ts +++ b/packages/next/src/cli/next-export-args.ts @@ -1,4 +1,4 @@ -import arg from 'next/dist/compiled/arg/index.js' +import type arg from 'next/dist/compiled/arg/index.js' export const validArgs: arg.Spec = { // Types diff --git a/packages/next/src/cli/next-export.ts b/packages/next/src/cli/next-export.ts index a53d05dce0c01..1791ced809b16 100755 --- a/packages/next/src/cli/next-export.ts +++ b/packages/next/src/cli/next-export.ts @@ -7,7 +7,7 @@ import { cyan } from '../lib/picocolors' import exportApp, { ExportError } from '../export' import * as Log from '../build/output/log' import { printAndExit } from '../server/lib/utils' -import { CliCommand } from '../lib/commands' +import type { CliCommand } from '../lib/commands' import { trace } from '../trace' import { getProjectDir } from '../lib/get-project-dir' diff --git a/packages/next/src/cli/next-info-args.ts b/packages/next/src/cli/next-info-args.ts index dafea92660d84..53cdbc4b92da9 100755 --- a/packages/next/src/cli/next-info-args.ts +++ b/packages/next/src/cli/next-info-args.ts @@ -1,4 +1,4 @@ -import arg from 'next/dist/compiled/arg/index.js' +import type arg from 'next/dist/compiled/arg/index.js' /** * Supported CLI arguments. diff --git a/packages/next/src/cli/next-info.ts b/packages/next/src/cli/next-info.ts index 46d2f4efb41c0..282f742368f79 100755 --- a/packages/next/src/cli/next-info.ts +++ b/packages/next/src/cli/next-info.ts @@ -7,7 +7,7 @@ import { bold, cyan, yellow } from '../lib/picocolors' const { fetch } = require('next/dist/compiled/undici') as { fetch: typeof global.fetch } -import { CliCommand } from '../lib/commands' +import type { CliCommand } from '../lib/commands' import { PHASE_INFO } from '../shared/lib/constants' import loadConfig from '../server/config' diff --git a/packages/next/src/cli/next-lint-args.ts b/packages/next/src/cli/next-lint-args.ts index 854af64be303f..5e1fbfe3c49aa 100755 --- a/packages/next/src/cli/next-lint-args.ts +++ b/packages/next/src/cli/next-lint-args.ts @@ -1,4 +1,4 @@ -import arg from 'next/dist/compiled/arg/index.js' +import type arg from 'next/dist/compiled/arg/index.js' const validEslintArgs: arg.Spec = { // Types diff --git a/packages/next/src/cli/next-lint.ts b/packages/next/src/cli/next-lint.ts index 93984a473d658..170826fb071c4 100755 --- a/packages/next/src/cli/next-lint.ts +++ b/packages/next/src/cli/next-lint.ts @@ -4,7 +4,7 @@ import { existsSync } from 'fs' import { join } from 'path' import { green } from '../lib/picocolors' -import { CliCommand } from '../lib/commands' +import type { CliCommand } from '../lib/commands' import { ESLINT_DEFAULT_DIRS } from '../lib/constants' import { runLintCheck } from '../lib/eslint/runLintCheck' import { printAndExit } from '../server/lib/utils' @@ -15,7 +15,7 @@ import { eventLintCheckCompleted } from '../telemetry/events' import { CompileError } from '../lib/compile-error' import { getProjectDir } from '../lib/get-project-dir' import { findPagesDir } from '../lib/find-pages-dir' -import { verifyTypeScriptSetup } from '../lib/verifyTypeScriptSetup' +import { verifyTypeScriptSetup } from '../lib/verify-typescript-setup' const eslintOptions = (args: arg.Spec, defaultCacheLocation: string) => ({ overrideConfigFile: args['--config'] || null, diff --git a/packages/next/src/cli/next-start-args.ts b/packages/next/src/cli/next-start-args.ts index 1c95bafd0bc71..151d1cd33bc4d 100755 --- a/packages/next/src/cli/next-start-args.ts +++ b/packages/next/src/cli/next-start-args.ts @@ -1,4 +1,4 @@ -import arg from 'next/dist/compiled/arg/index.js' +import type arg from 'next/dist/compiled/arg/index.js' export const validArgs: arg.Spec = { // Types diff --git a/packages/next/src/cli/next-start.ts b/packages/next/src/cli/next-start.ts index 06cddaed5a86f..9b072ba99edb9 100755 --- a/packages/next/src/cli/next-start.ts +++ b/packages/next/src/cli/next-start.ts @@ -1,10 +1,9 @@ #!/usr/bin/env node - import '../server/lib/cpu-profile' import { startServer } from '../server/lib/start-server' import { getPort, printAndExit } from '../server/lib/utils' import { getProjectDir } from '../lib/get-project-dir' -import { CliCommand } from '../lib/commands' +import type { CliCommand } from '../lib/commands' import { getReservedPortExplanation, isPortIsReserved, diff --git a/packages/next/src/cli/next-telemetry-args.ts b/packages/next/src/cli/next-telemetry-args.ts index 91b07af36d4fe..bdb5a7375076c 100755 --- a/packages/next/src/cli/next-telemetry-args.ts +++ b/packages/next/src/cli/next-telemetry-args.ts @@ -1,4 +1,4 @@ -import arg from 'next/dist/compiled/arg/index.js' +import type arg from 'next/dist/compiled/arg/index.js' export const validArgs: arg.Spec = { // Types diff --git a/packages/next/src/cli/next-telemetry.ts b/packages/next/src/cli/next-telemetry.ts index 7a61b92bbfb82..e1039873131b4 100755 --- a/packages/next/src/cli/next-telemetry.ts +++ b/packages/next/src/cli/next-telemetry.ts @@ -1,6 +1,6 @@ #!/usr/bin/env node import { bold, cyan, green, red, yellow } from '../lib/picocolors' -import { CliCommand } from '../lib/commands' +import type { CliCommand } from '../lib/commands' import { Telemetry } from '../telemetry/storage' const nextTelemetry: CliCommand = (args) => { diff --git a/packages/next/src/client/compat/router.ts b/packages/next/src/client/compat/router.ts index e9143c4117bd7..ec5752e7627f9 100644 --- a/packages/next/src/client/compat/router.ts +++ b/packages/next/src/client/compat/router.ts @@ -1,6 +1,6 @@ import { useContext } from 'react' import { RouterContext } from '../../shared/lib/router-context.shared-runtime' -import { NextRouter } from '../router' +import type { NextRouter } from '../router' /** * useRouter from `next/compat/router` is designed to assist developers diff --git a/packages/next/src/client/components/app-router.tsx b/packages/next/src/client/components/app-router.tsx index 51c749f002b3a..5f2d106e67d1f 100644 --- a/packages/next/src/client/components/app-router.tsx +++ b/packages/next/src/client/components/app-router.tsx @@ -33,8 +33,10 @@ import { ACTION_RESTORE, ACTION_SERVER_ACTION, ACTION_SERVER_PATCH, - Mutable, PrefetchKind, +} from './router-reducer/router-reducer-types' +import type { + Mutable, ReducerActions, RouterChangeByServerResponse, RouterNavigate, @@ -47,10 +49,8 @@ import { } from '../../shared/lib/hooks-client-context.shared-runtime' import { useReducerWithReduxDevtools } from './use-reducer-with-devtools' import { ErrorBoundary } from './error-boundary' -import { - createInitialRouterState, - InitialRouterStateParameters, -} from './router-reducer/create-initial-router-state' +import { createInitialRouterState } from './router-reducer/create-initial-router-state' +import type { InitialRouterStateParameters } from './router-reducer/create-initial-router-state' import { isBot } from '../../shared/lib/router/utils/is-bot' import { addBasePath } from '../add-base-path' import { AppRouterAnnouncer } from './app-router-announcer' diff --git a/packages/next/src/client/components/react-dev-overlay/hot-reloader-client.tsx b/packages/next/src/client/components/react-dev-overlay/hot-reloader-client.tsx index d4a2da56d3acc..6c4240d780a91 100644 --- a/packages/next/src/client/components/react-dev-overlay/hot-reloader-client.tsx +++ b/packages/next/src/client/components/react-dev-overlay/hot-reloader-client.tsx @@ -1,4 +1,4 @@ -import { ReactNode } from 'react' +import type { ReactNode } from 'react' import React, { useCallback, useEffect, @@ -36,10 +36,8 @@ import { } from './internal/helpers/use-websocket' import { parseComponentStack } from './internal/helpers/parse-component-stack' import type { VersionInfo } from '../../../server/dev/parse-version-info' -import { - HMR_ACTIONS_SENT_TO_BROWSER, - HMR_ACTION_TYPES, -} from '../../../server/dev/hot-reloader-types' +import { HMR_ACTIONS_SENT_TO_BROWSER } from '../../../server/dev/hot-reloader-types' +import type { HMR_ACTION_TYPES } from '../../../server/dev/hot-reloader-types' interface Dispatcher { onBuildOk(): void diff --git a/packages/next/src/client/components/react-dev-overlay/internal/ReactDevOverlay.tsx b/packages/next/src/client/components/react-dev-overlay/internal/ReactDevOverlay.tsx index 715e3fd1b9571..7d3c49cd0b670 100644 --- a/packages/next/src/client/components/react-dev-overlay/internal/ReactDevOverlay.tsx +++ b/packages/next/src/client/components/react-dev-overlay/internal/ReactDevOverlay.tsx @@ -1,13 +1,14 @@ import * as React from 'react' -import { - ACTION_UNHANDLED_ERROR, +import { ACTION_UNHANDLED_ERROR } from './error-overlay-reducer' +import type { OverlayState, UnhandledErrorAction, } from './error-overlay-reducer' import { ShadowPortal } from './components/ShadowPortal' import { BuildError } from './container/BuildError' -import { Errors, SupportedErrorEvent } from './container/Errors' +import { Errors } from './container/Errors' +import type { SupportedErrorEvent } from './container/Errors' import { RootLayoutError } from './container/RootLayoutError' import { parseStack } from './helpers/parseStack' import { Base } from './styles/Base' diff --git a/packages/next/src/client/components/react-dev-overlay/internal/components/CodeFrame/CodeFrame.tsx b/packages/next/src/client/components/react-dev-overlay/internal/components/CodeFrame/CodeFrame.tsx index eb8b8172b2880..3f879291291bf 100644 --- a/packages/next/src/client/components/react-dev-overlay/internal/components/CodeFrame/CodeFrame.tsx +++ b/packages/next/src/client/components/react-dev-overlay/internal/components/CodeFrame/CodeFrame.tsx @@ -1,6 +1,6 @@ import Anser from 'next/dist/compiled/anser' import * as React from 'react' -import { StackFrame } from 'next/dist/compiled/stacktrace-parser' +import type { StackFrame } from 'next/dist/compiled/stacktrace-parser' import stripAnsi from 'next/dist/compiled/strip-ansi' import { getFrameSource } from '../../helpers/stack-frame' import { useOpenInEditor } from '../../helpers/use-open-in-editor' diff --git a/packages/next/src/client/components/react-dev-overlay/internal/container/Errors.tsx b/packages/next/src/client/components/react-dev-overlay/internal/container/Errors.tsx index ab6d9df6652e7..3a799356d28e1 100644 --- a/packages/next/src/client/components/react-dev-overlay/internal/container/Errors.tsx +++ b/packages/next/src/client/components/react-dev-overlay/internal/container/Errors.tsx @@ -2,6 +2,8 @@ import * as React from 'react' import { ACTION_UNHANDLED_ERROR, ACTION_UNHANDLED_REJECTION, +} from '../error-overlay-reducer' +import type { UnhandledErrorAction, UnhandledRejectionAction, } from '../error-overlay-reducer' @@ -14,7 +16,8 @@ import { import { LeftRightDialogHeader } from '../components/LeftRightDialogHeader' import { Overlay } from '../components/Overlay' import { Toast } from '../components/Toast' -import { getErrorByType, ReadyRuntimeError } from '../helpers/getErrorByType' +import { getErrorByType } from '../helpers/getErrorByType' +import type { ReadyRuntimeError } from '../helpers/getErrorByType' import { getErrorSource } from '../helpers/nodeStackFrames' import { noop as css } from '../helpers/noop-template' import { CloseIcon } from '../icons/CloseIcon' diff --git a/packages/next/src/client/components/react-dev-overlay/internal/container/RuntimeError/index.tsx b/packages/next/src/client/components/react-dev-overlay/internal/container/RuntimeError/index.tsx index 6efe28bdffb90..bc348bbb4e7d4 100644 --- a/packages/next/src/client/components/react-dev-overlay/internal/container/RuntimeError/index.tsx +++ b/packages/next/src/client/components/react-dev-overlay/internal/container/RuntimeError/index.tsx @@ -1,8 +1,8 @@ import * as React from 'react' import { CodeFrame } from '../../components/CodeFrame' -import { ReadyRuntimeError } from '../../helpers/getErrorByType' +import type { ReadyRuntimeError } from '../../helpers/getErrorByType' import { noop as css } from '../../helpers/noop-template' -import { OriginalStackFrame } from '../../helpers/stack-frame' +import type { OriginalStackFrame } from '../../helpers/stack-frame' import { groupStackFramesByFramework } from '../../helpers/group-stack-frames-by-framework' import { CallStackFrame } from './CallStackFrame' import { GroupedStackFrames } from './GroupedStackFrames' diff --git a/packages/next/src/client/components/react-dev-overlay/internal/error-overlay-reducer.ts b/packages/next/src/client/components/react-dev-overlay/internal/error-overlay-reducer.ts index 44cb2470db7a4..4536a263277e4 100644 --- a/packages/next/src/client/components/react-dev-overlay/internal/error-overlay-reducer.ts +++ b/packages/next/src/client/components/react-dev-overlay/internal/error-overlay-reducer.ts @@ -1,7 +1,7 @@ import type { StackFrame } from 'next/dist/compiled/stacktrace-parser' import type { VersionInfo } from '../../../../server/dev/parse-version-info' import type { SupportedErrorEvent } from './container/Errors' -import { ComponentStackFrame } from './helpers/parse-component-stack' +import type { ComponentStackFrame } from './helpers/parse-component-stack' export const ACTION_BUILD_OK = 'build-ok' export const ACTION_BUILD_ERROR = 'build-error' diff --git a/packages/next/src/client/components/react-dev-overlay/internal/helpers/getErrorByType.ts b/packages/next/src/client/components/react-dev-overlay/internal/helpers/getErrorByType.ts index 9819e90555692..cd0b866e31127 100644 --- a/packages/next/src/client/components/react-dev-overlay/internal/helpers/getErrorByType.ts +++ b/packages/next/src/client/components/react-dev-overlay/internal/helpers/getErrorByType.ts @@ -2,10 +2,11 @@ import { ACTION_UNHANDLED_ERROR, ACTION_UNHANDLED_REJECTION, } from '../error-overlay-reducer' -import { SupportedErrorEvent } from '../container/Errors' +import type { SupportedErrorEvent } from '../container/Errors' import { getErrorSource } from './nodeStackFrames' -import { getOriginalStackFrames, OriginalStackFrame } from './stack-frame' -import { ComponentStackFrame } from './parse-component-stack' +import { getOriginalStackFrames } from './stack-frame' +import type { OriginalStackFrame } from './stack-frame' +import type { ComponentStackFrame } from './parse-component-stack' export type ReadyRuntimeError = { id: number diff --git a/packages/next/src/client/components/react-dev-overlay/internal/helpers/getRawSourceMap.ts b/packages/next/src/client/components/react-dev-overlay/internal/helpers/getRawSourceMap.ts index 504fa2c93bf85..0670daa0a8610 100644 --- a/packages/next/src/client/components/react-dev-overlay/internal/helpers/getRawSourceMap.ts +++ b/packages/next/src/client/components/react-dev-overlay/internal/helpers/getRawSourceMap.ts @@ -1,6 +1,5 @@ -import dataUriToBuffer, { - MimeBuffer, -} from 'next/dist/compiled/data-uri-to-buffer' +import dataUriToBuffer from 'next/dist/compiled/data-uri-to-buffer' +import type { MimeBuffer } from 'next/dist/compiled/data-uri-to-buffer' import type { RawSourceMap } from 'source-map' import { getSourceMapUrl } from './getSourceMapUrl' diff --git a/packages/next/src/client/components/react-dev-overlay/internal/helpers/nodeStackFrames.ts b/packages/next/src/client/components/react-dev-overlay/internal/helpers/nodeStackFrames.ts index cb3f9db12a072..d3691fe629654 100644 --- a/packages/next/src/client/components/react-dev-overlay/internal/helpers/nodeStackFrames.ts +++ b/packages/next/src/client/components/react-dev-overlay/internal/helpers/nodeStackFrames.ts @@ -1,4 +1,5 @@ -import { parse, StackFrame } from 'next/dist/compiled/stacktrace-parser' +import { parse } from 'next/dist/compiled/stacktrace-parser' +import type { StackFrame } from 'next/dist/compiled/stacktrace-parser' export function getFilesystemFrame(frame: StackFrame): StackFrame { const f: StackFrame = { ...frame } diff --git a/packages/next/src/client/components/react-dev-overlay/internal/helpers/parseStack.ts b/packages/next/src/client/components/react-dev-overlay/internal/helpers/parseStack.ts index ed95a92a82182..fbd509339945c 100644 --- a/packages/next/src/client/components/react-dev-overlay/internal/helpers/parseStack.ts +++ b/packages/next/src/client/components/react-dev-overlay/internal/helpers/parseStack.ts @@ -1,4 +1,5 @@ -import { parse, StackFrame } from 'next/dist/compiled/stacktrace-parser' +import { parse } from 'next/dist/compiled/stacktrace-parser' +import type { StackFrame } from 'next/dist/compiled/stacktrace-parser' const regexNextStatic = /\/_next(\/static\/.+)/g diff --git a/packages/next/src/client/components/react-dev-overlay/internal/helpers/stack-frame.ts b/packages/next/src/client/components/react-dev-overlay/internal/helpers/stack-frame.ts index c02e961aeeca6..a213da0579787 100644 --- a/packages/next/src/client/components/react-dev-overlay/internal/helpers/stack-frame.ts +++ b/packages/next/src/client/components/react-dev-overlay/internal/helpers/stack-frame.ts @@ -1,4 +1,4 @@ -import { StackFrame } from 'next/dist/compiled/stacktrace-parser' +import type { StackFrame } from 'next/dist/compiled/stacktrace-parser' // import type { OriginalStackFrameResponse } from '../../middleware' export type OriginalStackFrame = diff --git a/packages/next/src/client/components/redirect-boundary.tsx b/packages/next/src/client/components/redirect-boundary.tsx index 8d407fd6e9d6e..f0ee6fad318c4 100644 --- a/packages/next/src/client/components/redirect-boundary.tsx +++ b/packages/next/src/client/components/redirect-boundary.tsx @@ -1,6 +1,6 @@ 'use client' import React, { useEffect } from 'react' -import { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime' +import type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime' import { useRouter } from './navigation' import { RedirectType, diff --git a/packages/next/src/client/components/router-reducer/apply-flight-data.ts b/packages/next/src/client/components/router-reducer/apply-flight-data.ts index 003d0a5cde9e4..f30a8df3bc8ba 100644 --- a/packages/next/src/client/components/router-reducer/apply-flight-data.ts +++ b/packages/next/src/client/components/router-reducer/apply-flight-data.ts @@ -1,8 +1,6 @@ -import { - CacheNode, - CacheStates, -} from '../../../shared/lib/app-router-context.shared-runtime' -import { FlightDataPath } from '../../../server/app-render/types' +import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime' +import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime' +import type { FlightDataPath } from '../../../server/app-render/types' import { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-head' import { fillCacheWithNewSubTreeData } from './fill-cache-with-new-subtree-data' diff --git a/packages/next/src/client/components/router-reducer/compute-changed-path.ts b/packages/next/src/client/components/router-reducer/compute-changed-path.ts index 3a80a5a051b8a..fc3c751595c26 100644 --- a/packages/next/src/client/components/router-reducer/compute-changed-path.ts +++ b/packages/next/src/client/components/router-reducer/compute-changed-path.ts @@ -1,4 +1,7 @@ -import { FlightRouterState, Segment } from '../../../server/app-render/types' +import type { + FlightRouterState, + Segment, +} from '../../../server/app-render/types' import { INTERCEPTION_ROUTE_MARKERS } from '../../../server/future/helpers/interception-routes' import { isGroupSegment } from '../../../shared/lib/segment' import { matchSegment } from '../match-segments' diff --git a/packages/next/src/client/components/router-reducer/create-initial-router-state.test.tsx b/packages/next/src/client/components/router-reducer/create-initial-router-state.test.tsx index 414b553c63249..036944640cadf 100644 --- a/packages/next/src/client/components/router-reducer/create-initial-router-state.test.tsx +++ b/packages/next/src/client/components/router-reducer/create-initial-router-state.test.tsx @@ -1,9 +1,7 @@ import React from 'react' import type { FlightRouterState } from '../../../server/app-render/types' -import { - CacheNode, - CacheStates, -} from '../../../shared/lib/app-router-context.shared-runtime' +import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime' +import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime' import { createInitialRouterState } from './create-initial-router-state' const buildId = 'development' diff --git a/packages/next/src/client/components/router-reducer/create-record-from-thenable.ts b/packages/next/src/client/components/router-reducer/create-record-from-thenable.ts index 2976bc8decf71..ae63ff16ef564 100644 --- a/packages/next/src/client/components/router-reducer/create-record-from-thenable.ts +++ b/packages/next/src/client/components/router-reducer/create-record-from-thenable.ts @@ -1,4 +1,4 @@ -import { ThenableRecord } from './router-reducer-types' +import type { ThenableRecord } from './router-reducer-types' /** * Create data fetching record for Promise. diff --git a/packages/next/src/client/components/router-reducer/create-router-cache-key.ts b/packages/next/src/client/components/router-reducer/create-router-cache-key.ts index 3e9d739a717d7..dcf334d06ef48 100644 --- a/packages/next/src/client/components/router-reducer/create-router-cache-key.ts +++ b/packages/next/src/client/components/router-reducer/create-router-cache-key.ts @@ -1,4 +1,4 @@ -import { Segment } from '../../../server/app-render/types' +import type { Segment } from '../../../server/app-render/types' export function createRouterCacheKey( segment: Segment, diff --git a/packages/next/src/client/components/router-reducer/fetch-server-response.ts b/packages/next/src/client/components/router-reducer/fetch-server-response.ts index 691f1be2f16c8..28e8e8e65b52d 100644 --- a/packages/next/src/client/components/router-reducer/fetch-server-response.ts +++ b/packages/next/src/client/components/router-reducer/fetch-server-response.ts @@ -145,7 +145,7 @@ export async function fetchServerResponse( return [flightData, canonicalUrl] } catch (err) { console.error( - 'Failed to fetch RSC payload. Falling back to browser navigation.', + `Failed to fetch RSC payload for ${url}. Falling back to browser navigation.`, err ) // If fetch fails handle it like a mpa navigation diff --git a/packages/next/src/client/components/router-reducer/fill-cache-with-data-property.test.tsx b/packages/next/src/client/components/router-reducer/fill-cache-with-data-property.test.tsx index f64fd86b2af90..5aacf327c2270 100644 --- a/packages/next/src/client/components/router-reducer/fill-cache-with-data-property.test.tsx +++ b/packages/next/src/client/components/router-reducer/fill-cache-with-data-property.test.tsx @@ -1,12 +1,10 @@ import React from 'react' import type { FetchServerResponseResult } from './fetch-server-response' import { fillCacheWithDataProperty } from './fill-cache-with-data-property' -import { - CacheStates, - CacheNode, -} from '../../../shared/lib/app-router-context.shared-runtime' +import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime' +import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime' import { createRecordFromThenable } from './create-record-from-thenable' -import { ThenableRecord } from './router-reducer-types' +import type { ThenableRecord } from './router-reducer-types' describe('fillCacheWithDataProperty', () => { it('should add data property', () => { const fetchServerResponseMock: jest.Mock< diff --git a/packages/next/src/client/components/router-reducer/fill-cache-with-data-property.ts b/packages/next/src/client/components/router-reducer/fill-cache-with-data-property.ts index 274b9070f0c19..5584747ef06d6 100644 --- a/packages/next/src/client/components/router-reducer/fill-cache-with-data-property.ts +++ b/packages/next/src/client/components/router-reducer/fill-cache-with-data-property.ts @@ -1,10 +1,8 @@ import type { FetchServerResponseResult } from './fetch-server-response' import type { ThenableRecord } from './router-reducer-types' -import { FlightSegmentPath } from '../../../server/app-render/types' -import { - CacheNode, - CacheStates, -} from '../../../shared/lib/app-router-context.shared-runtime' +import type { FlightSegmentPath } from '../../../server/app-render/types' +import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime' +import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime' import { createRouterCacheKey } from './create-router-cache-key' /** diff --git a/packages/next/src/client/components/router-reducer/fill-cache-with-new-subtree-data.test.tsx b/packages/next/src/client/components/router-reducer/fill-cache-with-new-subtree-data.test.tsx index ac888a3ede0ff..d81ee63e12817 100644 --- a/packages/next/src/client/components/router-reducer/fill-cache-with-new-subtree-data.test.tsx +++ b/packages/next/src/client/components/router-reducer/fill-cache-with-new-subtree-data.test.tsx @@ -1,9 +1,7 @@ import React from 'react' import { fillCacheWithNewSubTreeData } from './fill-cache-with-new-subtree-data' -import { - CacheStates, - CacheNode, -} from '../../../shared/lib/app-router-context.shared-runtime' +import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime' +import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime' import type { FlightData } from '../../../server/app-render/types' const getFlightData = (): FlightData => { diff --git a/packages/next/src/client/components/router-reducer/fill-cache-with-new-subtree-data.ts b/packages/next/src/client/components/router-reducer/fill-cache-with-new-subtree-data.ts index 7e9a93699fb65..694f24b0b0e93 100644 --- a/packages/next/src/client/components/router-reducer/fill-cache-with-new-subtree-data.ts +++ b/packages/next/src/client/components/router-reducer/fill-cache-with-new-subtree-data.ts @@ -1,7 +1,5 @@ -import { - CacheNode, - CacheStates, -} from '../../../shared/lib/app-router-context.shared-runtime' +import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime' +import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime' import type { FlightDataPath } from '../../../server/app-render/types' import { invalidateCacheByRouterState } from './invalidate-cache-by-router-state' import { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-head' diff --git a/packages/next/src/client/components/router-reducer/fill-lazy-items-till-leaf-with-head.test.tsx b/packages/next/src/client/components/router-reducer/fill-lazy-items-till-leaf-with-head.test.tsx index 1edbeffd7b3e9..ba0d5fbc602b2 100644 --- a/packages/next/src/client/components/router-reducer/fill-lazy-items-till-leaf-with-head.test.tsx +++ b/packages/next/src/client/components/router-reducer/fill-lazy-items-till-leaf-with-head.test.tsx @@ -1,9 +1,7 @@ import React from 'react' import { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-head' -import { - CacheStates, - CacheNode, -} from '../../../shared/lib/app-router-context.shared-runtime' +import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime' +import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime' import type { FlightData } from '../../../server/app-render/types' const getFlightData = (): FlightData => { diff --git a/packages/next/src/client/components/router-reducer/fill-lazy-items-till-leaf-with-head.ts b/packages/next/src/client/components/router-reducer/fill-lazy-items-till-leaf-with-head.ts index f558edfab2f1e..4292b7f4607a0 100644 --- a/packages/next/src/client/components/router-reducer/fill-lazy-items-till-leaf-with-head.ts +++ b/packages/next/src/client/components/router-reducer/fill-lazy-items-till-leaf-with-head.ts @@ -1,7 +1,5 @@ -import { - CacheNode, - CacheStates, -} from '../../../shared/lib/app-router-context.shared-runtime' +import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime' +import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime' import type { FlightRouterState } from '../../../server/app-render/types' import { createRouterCacheKey } from './create-router-cache-key' diff --git a/packages/next/src/client/components/router-reducer/get-prefetch-cache-entry-status.ts b/packages/next/src/client/components/router-reducer/get-prefetch-cache-entry-status.ts index f2a6cedb134b0..efc899716b63a 100644 --- a/packages/next/src/client/components/router-reducer/get-prefetch-cache-entry-status.ts +++ b/packages/next/src/client/components/router-reducer/get-prefetch-cache-entry-status.ts @@ -1,4 +1,4 @@ -import { PrefetchCacheEntry } from './router-reducer-types' +import type { PrefetchCacheEntry } from './router-reducer-types' const FIVE_MINUTES = 5 * 60 * 1000 const THIRTY_SECONDS = 30 * 1000 diff --git a/packages/next/src/client/components/router-reducer/handle-mutable.ts b/packages/next/src/client/components/router-reducer/handle-mutable.ts index d5f48235bbde6..37b7f23066177 100644 --- a/packages/next/src/client/components/router-reducer/handle-mutable.ts +++ b/packages/next/src/client/components/router-reducer/handle-mutable.ts @@ -1,5 +1,5 @@ import { computeChangedPath } from './compute-changed-path' -import { +import type { Mutable, ReadonlyReducerState, ReducerState, diff --git a/packages/next/src/client/components/router-reducer/invalidate-cache-below-flight-segmentpath.test.tsx b/packages/next/src/client/components/router-reducer/invalidate-cache-below-flight-segmentpath.test.tsx index 8c23c47d42d74..9f062babb0f75 100644 --- a/packages/next/src/client/components/router-reducer/invalidate-cache-below-flight-segmentpath.test.tsx +++ b/packages/next/src/client/components/router-reducer/invalidate-cache-below-flight-segmentpath.test.tsx @@ -1,10 +1,8 @@ import React from 'react' import type { FlightData } from '../../../server/app-render/types' import { invalidateCacheBelowFlightSegmentPath } from './invalidate-cache-below-flight-segmentpath' -import { - CacheStates, - CacheNode, -} from '../../../shared/lib/app-router-context.shared-runtime' +import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime' +import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime' import { fillCacheWithNewSubTreeData } from './fill-cache-with-new-subtree-data' const getFlightData = (): FlightData => { diff --git a/packages/next/src/client/components/router-reducer/invalidate-cache-by-router-state.test.tsx b/packages/next/src/client/components/router-reducer/invalidate-cache-by-router-state.test.tsx index bdd819b0614d9..c365d6ae9765e 100644 --- a/packages/next/src/client/components/router-reducer/invalidate-cache-by-router-state.test.tsx +++ b/packages/next/src/client/components/router-reducer/invalidate-cache-by-router-state.test.tsx @@ -1,9 +1,7 @@ import React from 'react' import { invalidateCacheByRouterState } from './invalidate-cache-by-router-state' -import { - CacheStates, - CacheNode, -} from '../../../shared/lib/app-router-context.shared-runtime' +import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime' +import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime' import type { FlightRouterState } from '../../../server/app-render/types' describe('invalidateCacheByRouterState', () => { diff --git a/packages/next/src/client/components/router-reducer/reducers/fast-refresh-reducer.ts b/packages/next/src/client/components/router-reducer/reducers/fast-refresh-reducer.ts index dcf618118fb11..09acc94b4a9a8 100644 --- a/packages/next/src/client/components/router-reducer/reducers/fast-refresh-reducer.ts +++ b/packages/next/src/client/components/router-reducer/reducers/fast-refresh-reducer.ts @@ -4,7 +4,7 @@ import { readRecordValue } from '../read-record-value' import { createHrefFromUrl } from '../create-href-from-url' import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree' import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout' -import { +import type { ReadonlyReducerState, ReducerState, FastRefreshAction, diff --git a/packages/next/src/client/components/router-reducer/reducers/find-head-in-cache.test.tsx b/packages/next/src/client/components/router-reducer/reducers/find-head-in-cache.test.tsx index 2d4cdef348b1e..f3eaaad8a5c64 100644 --- a/packages/next/src/client/components/router-reducer/reducers/find-head-in-cache.test.tsx +++ b/packages/next/src/client/components/router-reducer/reducers/find-head-in-cache.test.tsx @@ -1,9 +1,7 @@ import React from 'react' import type { FlightRouterState } from '../../../../server/app-render/types' -import { - CacheNode, - CacheStates, -} from '../../../../shared/lib/app-router-context.shared-runtime' +import { CacheStates } from '../../../../shared/lib/app-router-context.shared-runtime' +import type { CacheNode } from '../../../../shared/lib/app-router-context.shared-runtime' import { findHeadInCache } from './find-head-in-cache' describe('findHeadInCache', () => { diff --git a/packages/next/src/client/components/router-reducer/reducers/get-segment-value.ts b/packages/next/src/client/components/router-reducer/reducers/get-segment-value.ts index 52000f5578bda..2ec8269583afa 100644 --- a/packages/next/src/client/components/router-reducer/reducers/get-segment-value.ts +++ b/packages/next/src/client/components/router-reducer/reducers/get-segment-value.ts @@ -1,4 +1,4 @@ -import { Segment } from '../../../../server/app-render/types' +import type { Segment } from '../../../../server/app-render/types' export function getSegmentValue(segment: Segment) { return Array.isArray(segment) ? segment[1] : segment diff --git a/packages/next/src/client/components/router-reducer/reducers/navigate-reducer.test.tsx b/packages/next/src/client/components/router-reducer/reducers/navigate-reducer.test.tsx index fcde9b963e9fd..6b2e9f0d343db 100644 --- a/packages/next/src/client/components/router-reducer/reducers/navigate-reducer.test.tsx +++ b/packages/next/src/client/components/router-reducer/reducers/navigate-reducer.test.tsx @@ -1,6 +1,18 @@ import React from 'react' import type { fetchServerResponse as fetchServerResponseType } from '../fetch-server-response' import type { FlightData } from '../../../../server/app-render/types' +import type { FlightRouterState } from '../../../../server/app-render/types' +import { CacheStates } from '../../../../shared/lib/app-router-context.shared-runtime' +import type { CacheNode } from '../../../../shared/lib/app-router-context.shared-runtime' +import { createInitialRouterState } from '../create-initial-router-state' +import { + ACTION_NAVIGATE, + ACTION_PREFETCH, + PrefetchKind, +} from '../router-reducer-types' +import type { NavigateAction, PrefetchAction } from '../router-reducer-types' +import { navigateReducer } from './navigate-reducer' +import { prefetchReducer } from './prefetch-reducer' const buildId = 'development' @@ -75,22 +87,6 @@ jest.mock('../fetch-server-response', () => { } }) -import { FlightRouterState } from '../../../../server/app-render/types' -import { - CacheNode, - CacheStates, -} from '../../../../shared/lib/app-router-context.shared-runtime' -import { createInitialRouterState } from '../create-initial-router-state' -import { - NavigateAction, - ACTION_NAVIGATE, - ACTION_PREFETCH, - PrefetchAction, - PrefetchKind, -} from '../router-reducer-types' -import { navigateReducer } from './navigate-reducer' -import { prefetchReducer } from './prefetch-reducer' - const getInitialRouterStateTree = (): FlightRouterState => [ '', { diff --git a/packages/next/src/client/components/router-reducer/reducers/navigate-reducer.ts b/packages/next/src/client/components/router-reducer/reducers/navigate-reducer.ts index 2436a15aca527..6ffefb5076d7c 100644 --- a/packages/next/src/client/components/router-reducer/reducers/navigate-reducer.ts +++ b/packages/next/src/client/components/router-reducer/reducers/navigate-reducer.ts @@ -1,15 +1,11 @@ -import { - CacheNode, - CacheStates, -} from '../../../../shared/lib/app-router-context.shared-runtime' +import { CacheStates } from '../../../../shared/lib/app-router-context.shared-runtime' +import type { CacheNode } from '../../../../shared/lib/app-router-context.shared-runtime' import type { FlightRouterState, FlightSegmentPath, } from '../../../../server/app-render/types' -import { - FetchServerResponseResult, - fetchServerResponse, -} from '../fetch-server-response' +import { fetchServerResponse } from '../fetch-server-response' +import type { FetchServerResponseResult } from '../fetch-server-response' import { createRecordFromThenable } from '../create-record-from-thenable' import { readRecordValue } from '../read-record-value' import { createHrefFromUrl } from '../create-href-from-url' @@ -19,14 +15,14 @@ import { createOptimisticTree } from '../create-optimistic-tree' import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree' import { shouldHardNavigate } from '../should-hard-navigate' import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout' -import { +import type { Mutable, NavigateAction, - PrefetchKind, ReadonlyReducerState, ReducerState, ThenableRecord, } from '../router-reducer-types' +import { PrefetchKind } from '../router-reducer-types' import { handleMutable } from '../handle-mutable' import { applyFlightData } from '../apply-flight-data' import { diff --git a/packages/next/src/client/components/router-reducer/reducers/prefetch-reducer.test.tsx b/packages/next/src/client/components/router-reducer/reducers/prefetch-reducer.test.tsx index bbbee6ff5f2a4..c5eca08342ead 100644 --- a/packages/next/src/client/components/router-reducer/reducers/prefetch-reducer.test.tsx +++ b/packages/next/src/client/components/router-reducer/reducers/prefetch-reducer.test.tsx @@ -1,6 +1,16 @@ import React from 'react' import type { fetchServerResponse as fetchServerResponseType } from '../fetch-server-response' import type { FlightData } from '../../../../server/app-render/types' +import type { FlightRouterState } from '../../../../server/app-render/types' +import { CacheStates } from '../../../../shared/lib/app-router-context.shared-runtime' +import type { CacheNode } from '../../../../shared/lib/app-router-context.shared-runtime' +import { createInitialRouterState } from '../create-initial-router-state' +import { ACTION_PREFETCH, PrefetchKind } from '../router-reducer-types' +import type { PrefetchAction } from '../router-reducer-types' +import { prefetchReducer } from './prefetch-reducer' +import { fetchServerResponse } from '../fetch-server-response' +import { createRecordFromThenable } from '../create-record-from-thenable' + jest.mock('../fetch-server-response', () => { const flightData: FlightData = [ [ @@ -32,20 +42,6 @@ jest.mock('../fetch-server-response', () => { }, } }) -import { FlightRouterState } from '../../../../server/app-render/types' -import { - CacheNode, - CacheStates, -} from '../../../../shared/lib/app-router-context.shared-runtime' -import { createInitialRouterState } from '../create-initial-router-state' -import { - PrefetchAction, - ACTION_PREFETCH, - PrefetchKind, -} from '../router-reducer-types' -import { prefetchReducer } from './prefetch-reducer' -import { fetchServerResponse } from '../fetch-server-response' -import { createRecordFromThenable } from '../create-record-from-thenable' const getInitialRouterStateTree = (): FlightRouterState => [ '', diff --git a/packages/next/src/client/components/router-reducer/reducers/prefetch-reducer.ts b/packages/next/src/client/components/router-reducer/reducers/prefetch-reducer.ts index 9344223de3c8d..9c9e87785b437 100644 --- a/packages/next/src/client/components/router-reducer/reducers/prefetch-reducer.ts +++ b/packages/next/src/client/components/router-reducer/reducers/prefetch-reducer.ts @@ -1,11 +1,11 @@ import { createHrefFromUrl } from '../create-href-from-url' import { fetchServerResponse } from '../fetch-server-response' -import { +import type { PrefetchAction, ReducerState, ReadonlyReducerState, - PrefetchKind, } from '../router-reducer-types' +import { PrefetchKind } from '../router-reducer-types' import { createRecordFromThenable } from '../create-record-from-thenable' import { prunePrefetchCache } from './prune-prefetch-cache' import { NEXT_RSC_UNION_QUERY } from '../../app-router-headers' diff --git a/packages/next/src/client/components/router-reducer/reducers/refresh-reducer.test.tsx b/packages/next/src/client/components/router-reducer/reducers/refresh-reducer.test.tsx index bbf36b1ec538c..dec910480ee19 100644 --- a/packages/next/src/client/components/router-reducer/reducers/refresh-reducer.test.tsx +++ b/packages/next/src/client/components/router-reducer/reducers/refresh-reducer.test.tsx @@ -1,7 +1,13 @@ import React from 'react' import type { fetchServerResponse } from '../fetch-server-response' import type { FlightData } from '../../../../server/app-render/types' - +import type { FlightRouterState } from '../../../../server/app-render/types' +import { CacheStates } from '../../../../shared/lib/app-router-context.shared-runtime' +import type { CacheNode } from '../../../../shared/lib/app-router-context.shared-runtime' +import { createInitialRouterState } from '../create-initial-router-state' +import { ACTION_REFRESH } from '../router-reducer-types' +import type { RefreshAction } from '../router-reducer-types' +import { refreshReducer } from './refresh-reducer' const buildId = 'development' jest.mock('../fetch-server-response', () => { @@ -42,14 +48,6 @@ jest.mock('../fetch-server-response', () => { }, } }) -import { FlightRouterState } from '../../../../server/app-render/types' -import { - CacheNode, - CacheStates, -} from '../../../../shared/lib/app-router-context.shared-runtime' -import { createInitialRouterState } from '../create-initial-router-state' -import { RefreshAction, ACTION_REFRESH } from '../router-reducer-types' -import { refreshReducer } from './refresh-reducer' const getInitialRouterStateTree = (): FlightRouterState => [ '', diff --git a/packages/next/src/client/components/router-reducer/reducers/refresh-reducer.ts b/packages/next/src/client/components/router-reducer/reducers/refresh-reducer.ts index bd6dfc4ef9047..804f3d619427d 100644 --- a/packages/next/src/client/components/router-reducer/reducers/refresh-reducer.ts +++ b/packages/next/src/client/components/router-reducer/reducers/refresh-reducer.ts @@ -4,7 +4,7 @@ import { readRecordValue } from '../read-record-value' import { createHrefFromUrl } from '../create-href-from-url' import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree' import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout' -import { +import type { ReadonlyReducerState, ReducerState, RefreshAction, diff --git a/packages/next/src/client/components/router-reducer/reducers/restore-reducer.test.tsx b/packages/next/src/client/components/router-reducer/reducers/restore-reducer.test.tsx index 36c978926517f..8cca3d7a9701c 100644 --- a/packages/next/src/client/components/router-reducer/reducers/restore-reducer.test.tsx +++ b/packages/next/src/client/components/router-reducer/reducers/restore-reducer.test.tsx @@ -1,11 +1,10 @@ import React from 'react' import type { FlightRouterState } from '../../../../server/app-render/types' -import { - CacheNode, - CacheStates, -} from '../../../../shared/lib/app-router-context.shared-runtime' +import { CacheStates } from '../../../../shared/lib/app-router-context.shared-runtime' +import type { CacheNode } from '../../../../shared/lib/app-router-context.shared-runtime' import { createInitialRouterState } from '../create-initial-router-state' -import { RestoreAction, ACTION_RESTORE } from '../router-reducer-types' +import { ACTION_RESTORE } from '../router-reducer-types' +import type { RestoreAction } from '../router-reducer-types' import { restoreReducer } from './restore-reducer' const buildId = 'development' diff --git a/packages/next/src/client/components/router-reducer/reducers/restore-reducer.ts b/packages/next/src/client/components/router-reducer/reducers/restore-reducer.ts index 675ae5e64ef4a..9b0ff103c94a6 100644 --- a/packages/next/src/client/components/router-reducer/reducers/restore-reducer.ts +++ b/packages/next/src/client/components/router-reducer/reducers/restore-reducer.ts @@ -1,5 +1,5 @@ import { createHrefFromUrl } from '../create-href-from-url' -import { +import type { ReadonlyReducerState, ReducerState, RestoreAction, diff --git a/packages/next/src/client/components/router-reducer/reducers/server-action-reducer.ts b/packages/next/src/client/components/router-reducer/reducers/server-action-reducer.ts index d8c67e507cc95..9ccaddafa066e 100644 --- a/packages/next/src/client/components/router-reducer/reducers/server-action-reducer.ts +++ b/packages/next/src/client/components/router-reducer/reducers/server-action-reducer.ts @@ -1,4 +1,4 @@ -import { +import type { ActionFlightResponse, ActionResult, FlightData, @@ -24,7 +24,7 @@ const { createFromFetch, encodeReply } = ( require('react-server-dom-webpack/client') ) as typeof import('react-server-dom-webpack/client') -import { +import type { ReadonlyReducerState, ReducerState, ServerActionAction, diff --git a/packages/next/src/client/components/router-reducer/reducers/server-patch-reducer.test.tsx b/packages/next/src/client/components/router-reducer/reducers/server-patch-reducer.test.tsx index 9e7035dc7e819..c1349a2740afc 100644 --- a/packages/next/src/client/components/router-reducer/reducers/server-patch-reducer.test.tsx +++ b/packages/next/src/client/components/router-reducer/reducers/server-patch-reducer.test.tsx @@ -4,7 +4,13 @@ import type { FlightData, FlightRouterState, } from '../../../../server/app-render/types' - +import { CacheStates } from '../../../../shared/lib/app-router-context.shared-runtime' +import type { CacheNode } from '../../../../shared/lib/app-router-context.shared-runtime' +import { createInitialRouterState } from '../create-initial-router-state' +import { ACTION_SERVER_PATCH, ACTION_NAVIGATE } from '../router-reducer-types' +import type { ServerPatchAction, NavigateAction } from '../router-reducer-types' +import { navigateReducer } from './navigate-reducer' +import { serverPatchReducer } from './server-patch-reducer' const buildId = 'development' const globalMutable = { @@ -42,19 +48,6 @@ jest.mock('../fetch-server-response', () => { }, } }) -import { - CacheNode, - CacheStates, -} from '../../../../shared/lib/app-router-context.shared-runtime' -import { createInitialRouterState } from '../create-initial-router-state' -import { - ServerPatchAction, - ACTION_SERVER_PATCH, - NavigateAction, - ACTION_NAVIGATE, -} from '../router-reducer-types' -import { navigateReducer } from './navigate-reducer' -import { serverPatchReducer } from './server-patch-reducer' const flightDataForPatch: FlightData = [ [ diff --git a/packages/next/src/client/components/router-reducer/reducers/server-patch-reducer.ts b/packages/next/src/client/components/router-reducer/reducers/server-patch-reducer.ts index 980f3b39827f6..d0697ea16084c 100644 --- a/packages/next/src/client/components/router-reducer/reducers/server-patch-reducer.ts +++ b/packages/next/src/client/components/router-reducer/reducers/server-patch-reducer.ts @@ -1,7 +1,7 @@ import { createHrefFromUrl } from '../create-href-from-url' import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree' import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout' -import { +import type { ServerPatchAction, ReducerState, ReadonlyReducerState, diff --git a/packages/next/src/client/components/router-reducer/router-reducer.ts b/packages/next/src/client/components/router-reducer/router-reducer.ts index d7832711aec20..ec48a3c9a8635 100644 --- a/packages/next/src/client/components/router-reducer/router-reducer.ts +++ b/packages/next/src/client/components/router-reducer/router-reducer.ts @@ -4,11 +4,13 @@ import { ACTION_RESTORE, ACTION_REFRESH, ACTION_PREFETCH, + ACTION_FAST_REFRESH, + ACTION_SERVER_ACTION, +} from './router-reducer-types' +import type { ReducerActions, ReducerState, ReadonlyReducerState, - ACTION_FAST_REFRESH, - ACTION_SERVER_ACTION, } from './router-reducer-types' import { navigateReducer } from './reducers/navigate-reducer' import { serverPatchReducer } from './reducers/server-patch-reducer' diff --git a/packages/next/src/client/dev/dev-build-watcher.ts b/packages/next/src/client/dev/dev-build-watcher.ts index ef9c008603c4a..231c3536cfbe9 100644 --- a/packages/next/src/client/dev/dev-build-watcher.ts +++ b/packages/next/src/client/dev/dev-build-watcher.ts @@ -1,8 +1,6 @@ /* eslint-disable @typescript-eslint/no-use-before-define */ -import { - HMR_ACTIONS_SENT_TO_BROWSER, - HMR_ACTION_TYPES, -} from '../../server/dev/hot-reloader-types' +import { HMR_ACTIONS_SENT_TO_BROWSER } from '../../server/dev/hot-reloader-types' +import type { HMR_ACTION_TYPES } from '../../server/dev/hot-reloader-types' import { addMessageListener } from './error-overlay/websocket' type VerticalPosition = 'top' | 'bottom' diff --git a/packages/next/src/client/dev/error-overlay/hot-dev-client.ts b/packages/next/src/client/dev/error-overlay/hot-dev-client.ts index 04992a011bb54..5fb470ea358e0 100644 --- a/packages/next/src/client/dev/error-overlay/hot-dev-client.ts +++ b/packages/next/src/client/dev/error-overlay/hot-dev-client.ts @@ -38,11 +38,8 @@ import { import stripAnsi from 'next/dist/compiled/strip-ansi' import { addMessageListener, sendMessage } from './websocket' import formatWebpackMessages from './format-webpack-messages' -import { - HMR_ACTIONS_SENT_TO_BROWSER, - HMR_ACTION_TYPES, -} from '../../../server/dev/hot-reloader-types' - +import { HMR_ACTIONS_SENT_TO_BROWSER } from '../../../server/dev/hot-reloader-types' +import type { HMR_ACTION_TYPES } from '../../../server/dev/hot-reloader-types' // This alternative WebpackDevServer combines the functionality of: // https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js // https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js diff --git a/packages/next/src/client/dev/error-overlay/websocket.ts b/packages/next/src/client/dev/error-overlay/websocket.ts index 7273c9482f111..5a90b045d186c 100644 --- a/packages/next/src/client/dev/error-overlay/websocket.ts +++ b/packages/next/src/client/dev/error-overlay/websocket.ts @@ -1,4 +1,4 @@ -import { HMR_ACTION_TYPES } from '../../../server/dev/hot-reloader-types' +import type { HMR_ACTION_TYPES } from '../../../server/dev/hot-reloader-types' let source: WebSocket diff --git a/packages/next/src/client/index.tsx b/packages/next/src/client/index.tsx index 0bce4c663e899..f8904d1308977 100644 --- a/packages/next/src/client/index.tsx +++ b/packages/next/src/client/index.tsx @@ -11,7 +11,8 @@ import type { import React from 'react' import ReactDOM from 'react-dom/client' import { HeadManagerContext } from '../shared/lib/head-manager-context.shared-runtime' -import mitt, { MittEmitter } from '../shared/lib/mitt' +import mitt from '../shared/lib/mitt' +import type { MittEmitter } from '../shared/lib/mitt' import { RouterContext } from '../shared/lib/router-context.shared-runtime' import { handleSmoothScroll } from '../shared/lib/router/utils/handle-smooth-scroll' import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic' @@ -20,22 +21,18 @@ import { assign, } from '../shared/lib/router/utils/querystring' import { setConfig } from '../shared/lib/runtime-config.external' -import { - getURL, - loadGetInitialProps, - NextWebVitalsMetric, - NEXT_DATA, - ST, -} from '../shared/lib/utils' +import { getURL, loadGetInitialProps, ST } from '../shared/lib/utils' +import type { NextWebVitalsMetric, NEXT_DATA } from '../shared/lib/utils' import { Portal } from './portal' import initHeadManager from './head-manager' -import PageLoader, { StyleSheetTuple } from './page-loader' +import PageLoader from './page-loader' +import type { StyleSheetTuple } from './page-loader' import measureWebVitals from './performance-relayer' import { RouteAnnouncer } from './route-announcer' import { createRouter, makePublicRouterInstance } from './router' import { getProperError } from '../lib/is-error' import { ImageConfigContext } from '../shared/lib/image-config-context.shared-runtime' -import { ImageConfigComplete } from '../shared/lib/image-config' +import type { ImageConfigComplete } from '../shared/lib/image-config' import { removeBasePath } from './remove-base-path' import { hasBasePath } from './has-base-path' import { AppRouterContext } from '../shared/lib/app-router-context.shared-runtime' diff --git a/packages/next/src/client/legacy/image.tsx b/packages/next/src/client/legacy/image.tsx index 0ef397d4320df..d982e9fa8a330 100644 --- a/packages/next/src/client/legacy/image.tsx +++ b/packages/next/src/client/legacy/image.tsx @@ -10,11 +10,13 @@ import React, { } from 'react' import Head from '../../shared/lib/head' import { - ImageConfigComplete, imageConfigDefault, - LoaderValue, VALID_LOADERS, } from '../../shared/lib/image-config' +import type { + ImageConfigComplete, + LoaderValue, +} from '../../shared/lib/image-config' import { useIntersection } from '../use-intersection' import { ImageConfigContext } from '../../shared/lib/image-config-context.shared-runtime' import { warnOnce } from '../../shared/lib/utils/warn-once' diff --git a/packages/next/src/client/link.tsx b/packages/next/src/client/link.tsx index 7a15dee249e26..92d6646f0ebac 100644 --- a/packages/next/src/client/link.tsx +++ b/packages/next/src/client/link.tsx @@ -6,15 +6,15 @@ import type { } from '../shared/lib/router/router' import React from 'react' -import { UrlObject } from 'url' +import type { UrlObject } from 'url' import { resolveHref } from './resolve-href' import { isLocalURL } from '../shared/lib/router/utils/is-local-url' import { formatUrl } from '../shared/lib/router/utils/format-url' import { isAbsoluteUrl } from '../shared/lib/utils' import { addLocale } from './add-locale' import { RouterContext } from '../shared/lib/router-context.shared-runtime' -import { - AppRouterContext, +import { AppRouterContext } from '../shared/lib/app-router-context.shared-runtime' +import type { AppRouterInstance, PrefetchOptions as AppRouterPrefetchOptions, } from '../shared/lib/app-router-context.shared-runtime' diff --git a/packages/next/src/client/next-dev-turbopack.ts b/packages/next/src/client/next-dev-turbopack.ts index 3381761de0b1b..54778e0c38277 100644 --- a/packages/next/src/client/next-dev-turbopack.ts +++ b/packages/next/src/client/next-dev-turbopack.ts @@ -7,7 +7,7 @@ import { pageBootrap } from './page-bootstrap' import { addMessageListener, sendMessage } from './dev/error-overlay/websocket' //@ts-expect-error requires "moduleResolution": "node16" in tsconfig.json and not .ts extension import { connect } from '@vercel/turbopack-ecmascript-runtime/dev/client/hmr-client.ts' -import { HMR_ACTION_TYPES } from '../server/dev/hot-reloader-types' +import type { HMR_ACTION_TYPES } from '../server/dev/hot-reloader-types' window.next = { version: `${version}-turbo`, diff --git a/packages/next/src/client/page-bootstrap.ts b/packages/next/src/client/page-bootstrap.ts index 1d57584ae5d75..a998607b3ac57 100644 --- a/packages/next/src/client/page-bootstrap.ts +++ b/packages/next/src/client/page-bootstrap.ts @@ -1,8 +1,7 @@ import { hydrate, router } from './' import initOnDemandEntries from './dev/on-demand-entries-client' -import initializeBuildWatcher, { - ShowHideHandler, -} from './dev/dev-build-watcher' +import initializeBuildWatcher from './dev/dev-build-watcher' +import type { ShowHideHandler } from './dev/dev-build-watcher' import { displayContent } from './dev/fouc' import { connectHMR, addMessageListener } from './dev/error-overlay/websocket' import { diff --git a/packages/next/src/client/script.tsx b/packages/next/src/client/script.tsx index f695e691c482d..9fe128aba41e1 100644 --- a/packages/next/src/client/script.tsx +++ b/packages/next/src/client/script.tsx @@ -2,7 +2,7 @@ import ReactDOM from 'react-dom' import React, { useEffect, useContext, useRef } from 'react' -import { ScriptHTMLAttributes } from 'react' +import type { ScriptHTMLAttributes } from 'react' import { HeadManagerContext } from '../shared/lib/head-manager-context.shared-runtime' import { DOMAttributeNames } from './head-manager' import { requestIdleCallback } from './request-idle-callback' diff --git a/packages/next/src/client/tracing/report-to-socket.ts b/packages/next/src/client/tracing/report-to-socket.ts index 74c87703e9997..493bd3aa98831 100644 --- a/packages/next/src/client/tracing/report-to-socket.ts +++ b/packages/next/src/client/tracing/report-to-socket.ts @@ -1,5 +1,5 @@ import { sendMessage } from '../dev/error-overlay/websocket' -import { Span } from './tracer' +import type { Span } from './tracer' export default function reportToSocket(span: Span) { if (span.state.state !== 'ended') { diff --git a/packages/next/src/client/tracing/tracer.ts b/packages/next/src/client/tracing/tracer.ts index f93b5f7219c7a..8694615980caa 100644 --- a/packages/next/src/client/tracing/tracer.ts +++ b/packages/next/src/client/tracing/tracer.ts @@ -1,4 +1,5 @@ -import mitt, { MittEmitter } from '../../shared/lib/mitt' +import mitt from '../../shared/lib/mitt' +import type { MittEmitter } from '../../shared/lib/mitt' export type SpanOptions = { startTime?: number @@ -73,5 +74,5 @@ class Tracer { } } -export { ISpan as Span } +export type { ISpan as Span } export default new Tracer() diff --git a/packages/next/src/client/web-vitals.ts b/packages/next/src/client/web-vitals.ts index 4194cf90f5666..36c532553bcf2 100644 --- a/packages/next/src/client/web-vitals.ts +++ b/packages/next/src/client/web-vitals.ts @@ -6,8 +6,8 @@ import { onINP, onFCP, onTTFB, - Metric, } from 'next/dist/compiled/web-vitals' +import type { Metric } from 'next/dist/compiled/web-vitals' export function useReportWebVitals( reportWebVitalsFn: (metric: Metric) => void diff --git a/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-client.browser.development.js b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-client.browser.development.js new file mode 100644 index 0000000000000..30862f737b0eb --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-client.browser.development.js @@ -0,0 +1,2223 @@ +/** + * @license React + * react-server-dom-turbopack-client.browser.development.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +if (process.env.NODE_ENV !== "production") { + (function() { +'use strict'; + +var ReactDOM = require('react-dom'); +var React = require('react'); + +function createStringDecoder() { + return new TextDecoder(); +} +var decoderOptions = { + stream: true +}; +function readPartialStringChunk(decoder, buffer) { + return decoder.decode(buffer, decoderOptions); +} +function readFinalStringChunk(decoder, buffer) { + return decoder.decode(buffer); +} + +// This is the parsed shape of the wire format which is why it is +// condensed to only the essentialy information +var ID = 0; +var CHUNKS = 1; +var NAME = 2; // export const ASYNC = 3; +// This logic is correct because currently only include the 4th tuple member +// when the module is async. If that changes we will need to actually assert +// the value is true. We don't index into the 4th slot because flow does not +// like the potential out of bounds access + +function isAsyncImport(metadata) { + return metadata.length === 4; +} + +function resolveClientReference(bundlerConfig, metadata) { + if (bundlerConfig) { + var moduleExports = bundlerConfig[metadata[ID]]; + var resolvedModuleData = moduleExports[metadata[NAME]]; + var name; + + if (resolvedModuleData) { + // The potentially aliased name. + name = resolvedModuleData.name; + } else { + // If we don't have this specific name, we might have the full module. + resolvedModuleData = moduleExports['*']; + + if (!resolvedModuleData) { + throw new Error('Could not find the module "' + metadata[ID] + '" in the React SSR Manifest. ' + 'This is probably a bug in the React Server Components bundler.'); + } + + name = metadata[NAME]; + } + + if (isAsyncImport(metadata)) { + return [resolvedModuleData.id, resolvedModuleData.chunks, name, 1 + /* async */ + ]; + } else { + return [resolvedModuleData.id, resolvedModuleData.chunks, name]; + } + } + + return metadata; +} +// If they're still pending they're a thenable. This map also exists +// in Turbopack but unfortunately it's not exposed so we have to +// replicate it in user space. null means that it has already loaded. + +var chunkCache = new Map(); + +function requireAsyncModule(id) { + // We've already loaded all the chunks. We can require the module. + var promise = __turbopack_require__(id); + + if (typeof promise.then !== 'function') { + // This wasn't a promise after all. + return null; + } else if (promise.status === 'fulfilled') { + // This module was already resolved earlier. + return null; + } else { + // Instrument the Promise to stash the result. + promise.then(function (value) { + var fulfilledThenable = promise; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = value; + }, function (reason) { + var rejectedThenable = promise; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = reason; + }); + return promise; + } +} + +function ignoreReject() {// We rely on rejected promises to be handled by another listener. +} // Start preloading the modules since we might need them soon. +// This function doesn't suspend. + + +function preloadModule(metadata) { + var chunks = metadata[CHUNKS]; + var promises = []; + + for (var i = 0; i < chunks.length; i++) { + var chunkFilename = chunks[i]; + var entry = chunkCache.get(chunkFilename); + + if (entry === undefined) { + var thenable = loadChunk(chunkFilename); + promises.push(thenable); // $FlowFixMe[method-unbinding] + + var resolve = chunkCache.set.bind(chunkCache, chunkFilename, null); + thenable.then(resolve, ignoreReject); + chunkCache.set(chunkFilename, thenable); + } else if (entry !== null) { + promises.push(entry); + } + } + + if (isAsyncImport(metadata)) { + if (promises.length === 0) { + return requireAsyncModule(metadata[ID]); + } else { + return Promise.all(promises).then(function () { + return requireAsyncModule(metadata[ID]); + }); + } + } else if (promises.length > 0) { + return Promise.all(promises); + } else { + return null; + } +} // Actually require the module or suspend if it's not yet ready. +// Increase priority if necessary. + +function requireModule(metadata) { + var moduleExports = __turbopack_require__(metadata[ID]); + + if (isAsyncImport(metadata)) { + if (typeof moduleExports.then !== 'function') ; else if (moduleExports.status === 'fulfilled') { + // This Promise should've been instrumented by preloadModule. + moduleExports = moduleExports.value; + } else { + throw moduleExports.reason; + } + } + + if (metadata[NAME] === '*') { + // This is a placeholder value that represents that the caller imported this + // as a CommonJS module as is. + return moduleExports; + } + + if (metadata[NAME] === '') { + // This is a placeholder value that represents that the caller accessed the + // default property of this if it was an ESM interop module. + return moduleExports.__esModule ? moduleExports.default : moduleExports; + } + + return moduleExports[metadata[NAME]]; +} + +function loadChunk(filename) { + return __turbopack_load__(filename); +} + +var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +// This client file is in the shared folder because it applies to both SSR and browser contexts. +var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher; +function dispatchHint(code, model) { + var dispatcher = ReactDOMCurrentDispatcher.current; + + if (dispatcher) { + switch (code) { + case 'D': + { + var refined = refineModel(code, model); + var href = refined; + dispatcher.prefetchDNS(href); + return; + } + + case 'C': + { + var _refined = refineModel(code, model); + + if (typeof _refined === 'string') { + var _href = _refined; + dispatcher.preconnect(_href); + } else { + var _href2 = _refined[0]; + var crossOrigin = _refined[1]; + dispatcher.preconnect(_href2, crossOrigin); + } + + return; + } + + case 'L': + { + var _refined2 = refineModel(code, model); + + var _href3 = _refined2[0]; + var as = _refined2[1]; + + if (_refined2.length === 3) { + var options = _refined2[2]; + dispatcher.preload(_href3, as, options); + } else { + dispatcher.preload(_href3, as); + } + + return; + } + + case 'm': + { + var _refined3 = refineModel(code, model); + + if (typeof _refined3 === 'string') { + var _href4 = _refined3; + dispatcher.preloadModule(_href4); + } else { + var _href5 = _refined3[0]; + var _options = _refined3[1]; + dispatcher.preloadModule(_href5, _options); + } + + return; + } + + case 'S': + { + var _refined4 = refineModel(code, model); + + if (typeof _refined4 === 'string') { + var _href6 = _refined4; + dispatcher.preinitStyle(_href6); + } else { + var _href7 = _refined4[0]; + var precedence = _refined4[1] === 0 ? undefined : _refined4[1]; + + var _options2 = _refined4.length === 3 ? _refined4[2] : undefined; + + dispatcher.preinitStyle(_href7, precedence, _options2); + } + + return; + } + + case 'X': + { + var _refined5 = refineModel(code, model); + + if (typeof _refined5 === 'string') { + var _href8 = _refined5; + dispatcher.preinitScript(_href8); + } else { + var _href9 = _refined5[0]; + var _options3 = _refined5[1]; + dispatcher.preinitScript(_href9, _options3); + } + + return; + } + + case 'M': + { + var _refined6 = refineModel(code, model); + + if (typeof _refined6 === 'string') { + var _href10 = _refined6; + dispatcher.preinitModuleScript(_href10); + } else { + var _href11 = _refined6[0]; + var _options4 = _refined6[1]; + dispatcher.preinitModuleScript(_href11, _options4); + } + + return; + } + } + } +} // Flow is having troulbe refining the HintModels so we help it a bit. +// This should be compiled out in the production build. + +function refineModel(code, model) { + return model; +} + +var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); +var REACT_POSTPONE_TYPE = Symbol.for('react.postpone'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +// in case they error. + +var jsxPropsParents = new WeakMap(); +var jsxChildrenParents = new WeakMap(); + +function isObjectPrototype(object) { + if (!object) { + return false; + } + + var ObjectPrototype = Object.prototype; + + if (object === ObjectPrototype) { + return true; + } // It might be an object from a different Realm which is + // still just a plain simple object. + + + if (Object.getPrototypeOf(object)) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + if (!(names[i] in ObjectPrototype)) { + return false; + } + } + + return true; +} + +function isSimpleObject(object) { + if (!isObjectPrototype(Object.getPrototypeOf(object))) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + var descriptor = Object.getOwnPropertyDescriptor(object, names[i]); + + if (!descriptor) { + return false; + } + + if (!descriptor.enumerable) { + if ((names[i] === 'key' || names[i] === 'ref') && typeof descriptor.get === 'function') { + // React adds key and ref getters to props objects to issue warnings. + // Those getters will not be transferred to the client, but that's ok, + // so we'll special case them. + continue; + } + + return false; + } + } + + return true; +} +function objectName(object) { + // $FlowFixMe[method-unbinding] + var name = Object.prototype.toString.call(object); + return name.replace(/^\[object (.*)\]$/, function (m, p0) { + return p0; + }); +} + +function describeKeyForErrorMessage(key) { + var encodedKey = JSON.stringify(key); + return '"' + key + '"' === encodedKey ? key : encodedKey; +} + +function describeValueForErrorMessage(value) { + switch (typeof value) { + case 'string': + { + return JSON.stringify(value.length <= 10 ? value : value.slice(0, 10) + '...'); + } + + case 'object': + { + if (isArray(value)) { + return '[...]'; + } + + var name = objectName(value); + + if (name === 'Object') { + return '{...}'; + } + + return name; + } + + case 'function': + return 'function'; + + default: + // eslint-disable-next-line react-internal/safe-string-coercion + return String(value); + } +} + +function describeElementType(type) { + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeElementType(type.render); + + case REACT_MEMO_TYPE: + return describeElementType(type.type); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeElementType(init(payload)); + } catch (x) {} + } + } + } + + return ''; +} + +function describeObjectForErrorMessage(objectOrArray, expandedName) { + var objKind = objectName(objectOrArray); + + if (objKind !== 'Object' && objKind !== 'Array') { + return objKind; + } + + var str = ''; + var start = -1; + var length = 0; + + if (isArray(objectOrArray)) { + if (jsxChildrenParents.has(objectOrArray)) { + // Print JSX Children + var type = jsxChildrenParents.get(objectOrArray); + str = '<' + describeElementType(type) + '>'; + var array = objectOrArray; + + for (var i = 0; i < array.length; i++) { + var value = array[i]; + var substr = void 0; + + if (typeof value === 'string') { + substr = value; + } else if (typeof value === 'object' && value !== null) { + substr = '{' + describeObjectForErrorMessage(value) + '}'; + } else { + substr = '{' + describeValueForErrorMessage(value) + '}'; + } + + if ('' + i === expandedName) { + start = str.length; + length = substr.length; + str += substr; + } else if (substr.length < 15 && str.length + substr.length < 40) { + str += substr; + } else { + str += '{...}'; + } + } + + str += ''; + } else { + // Print Array + str = '['; + var _array = objectOrArray; + + for (var _i = 0; _i < _array.length; _i++) { + if (_i > 0) { + str += ', '; + } + + var _value = _array[_i]; + + var _substr = void 0; + + if (typeof _value === 'object' && _value !== null) { + _substr = describeObjectForErrorMessage(_value); + } else { + _substr = describeValueForErrorMessage(_value); + } + + if ('' + _i === expandedName) { + start = str.length; + length = _substr.length; + str += _substr; + } else if (_substr.length < 10 && str.length + _substr.length < 40) { + str += _substr; + } else { + str += '...'; + } + } + + str += ']'; + } + } else { + if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) { + str = '<' + describeElementType(objectOrArray.type) + '/>'; + } else if (jsxPropsParents.has(objectOrArray)) { + // Print JSX + var _type = jsxPropsParents.get(objectOrArray); + + str = '<' + (describeElementType(_type) || '...'); + var object = objectOrArray; + var names = Object.keys(object); + + for (var _i2 = 0; _i2 < names.length; _i2++) { + str += ' '; + var name = names[_i2]; + str += describeKeyForErrorMessage(name) + '='; + var _value2 = object[name]; + + var _substr2 = void 0; + + if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) { + _substr2 = describeObjectForErrorMessage(_value2); + } else { + _substr2 = describeValueForErrorMessage(_value2); + } + + if (typeof _value2 !== 'string') { + _substr2 = '{' + _substr2 + '}'; + } + + if (name === expandedName) { + start = str.length; + length = _substr2.length; + str += _substr2; + } else if (_substr2.length < 10 && str.length + _substr2.length < 40) { + str += _substr2; + } else { + str += '...'; + } + } + + str += '>'; + } else { + // Print Object + str = '{'; + var _object = objectOrArray; + + var _names = Object.keys(_object); + + for (var _i3 = 0; _i3 < _names.length; _i3++) { + if (_i3 > 0) { + str += ', '; + } + + var _name = _names[_i3]; + str += describeKeyForErrorMessage(_name) + ': '; + var _value3 = _object[_name]; + + var _substr3 = void 0; + + if (typeof _value3 === 'object' && _value3 !== null) { + _substr3 = describeObjectForErrorMessage(_value3); + } else { + _substr3 = describeValueForErrorMessage(_value3); + } + + if (_name === expandedName) { + start = str.length; + length = _substr3.length; + str += _substr3; + } else if (_substr3.length < 10 && str.length + _substr3.length < 40) { + str += _substr3; + } else { + str += '...'; + } + } + + str += '}'; + } + } + + if (expandedName === undefined) { + return str; + } + + if (start > -1 && length > 0) { + var highlight = ' '.repeat(start) + '^'.repeat(length); + return '\n ' + str + '\n ' + highlight; + } + + return '\n ' + str; +} + +var knownServerReferences = new WeakMap(); // Serializable values +// Thenable +// function serializeByValueID(id: number): string { +// return '$' + id.toString(16); +// } + +function serializePromiseID(id) { + return '$@' + id.toString(16); +} + +function serializeServerReferenceID(id) { + return '$F' + id.toString(16); +} + +function serializeSymbolReference(name) { + return '$S' + name; +} + +function serializeFormDataReference(id) { + // Why K? F is "Function". D is "Date". What else? + return '$K' + id.toString(16); +} + +function serializeNumber(number) { + if (Number.isFinite(number)) { + if (number === 0 && 1 / number === -Infinity) { + return '$-0'; + } else { + return number; + } + } else { + if (number === Infinity) { + return '$Infinity'; + } else if (number === -Infinity) { + return '$-Infinity'; + } else { + return '$NaN'; + } + } +} + +function serializeUndefined() { + return '$undefined'; +} + +function serializeDateFromDateJSON(dateJSON) { + // JSON.stringify automatically calls Date.prototype.toJSON which calls toISOString. + // We need only tack on a $D prefix. + return '$D' + dateJSON; +} + +function serializeBigInt(n) { + return '$n' + n.toString(10); +} + +function serializeMapID(id) { + return '$Q' + id.toString(16); +} + +function serializeSetID(id) { + return '$W' + id.toString(16); +} + +function escapeStringValue(value) { + if (value[0] === '$') { + // We need to escape $ prefixed strings since we use those to encode + // references to IDs and as special symbol values. + return '$' + value; + } else { + return value; + } +} + +function processReply(root, formFieldPrefix, resolve, reject) { + var nextPartId = 1; + var pendingParts = 0; + var formData = null; + + function resolveToJSON(key, value) { + var parent = this; // Make sure that `parent[key]` wasn't JSONified before `value` was passed to us + + { + // $FlowFixMe[incompatible-use] + var originalValue = parent[key]; + + if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) { + if (objectName(originalValue) !== 'Object') { + error('Only plain objects can be passed to Server Functions from the Client. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } else { + error('Only plain objects can be passed to Server Functions from the Client. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props.%s', describeObjectForErrorMessage(parent, key)); + } + } + } + + if (value === null) { + return null; + } + + if (typeof value === 'object') { + // $FlowFixMe[method-unbinding] + if (typeof value.then === 'function') { + // We assume that any object with a .then property is a "Thenable" type, + // or a Promise type. Either of which can be represented by a Promise. + if (formData === null) { + // Upgrade to use FormData to allow us to stream this value. + formData = new FormData(); + } + + pendingParts++; + var promiseId = nextPartId++; + var thenable = value; + thenable.then(function (partValue) { + var partJSON = JSON.stringify(partValue, resolveToJSON); // $FlowFixMe[incompatible-type] We know it's not null because we assigned it above. + + var data = formData; // eslint-disable-next-line react-internal/safe-string-coercion + + data.append(formFieldPrefix + promiseId, partJSON); + pendingParts--; + + if (pendingParts === 0) { + resolve(data); + } + }, function (reason) { + // In the future we could consider serializing this as an error + // that throws on the server instead. + reject(reason); + }); + return serializePromiseID(promiseId); + } // TODO: Should we the Object.prototype.toString.call() to test for cross-realm objects? + + + if (value instanceof FormData) { + if (formData === null) { + // Upgrade to use FormData to allow us to use rich objects as its values. + formData = new FormData(); + } + + var data = formData; + var refId = nextPartId++; // Copy all the form fields with a prefix for this reference. + // These must come first in the form order because we assume that all the + // fields are available before this is referenced. + + var prefix = formFieldPrefix + refId + '_'; // $FlowFixMe[prop-missing]: FormData has forEach. + + value.forEach(function (originalValue, originalKey) { + data.append(prefix + originalKey, originalValue); + }); + return serializeFormDataReference(refId); + } + + if (value instanceof Map) { + var partJSON = JSON.stringify(Array.from(value), resolveToJSON); + + if (formData === null) { + formData = new FormData(); + } + + var mapId = nextPartId++; + formData.append(formFieldPrefix + mapId, partJSON); + return serializeMapID(mapId); + } + + if (value instanceof Set) { + var _partJSON = JSON.stringify(Array.from(value), resolveToJSON); + + if (formData === null) { + formData = new FormData(); + } + + var setId = nextPartId++; + formData.append(formFieldPrefix + setId, _partJSON); + return serializeSetID(setId); + } + + if (!isArray(value)) { + var iteratorFn = getIteratorFn(value); + + if (iteratorFn) { + return Array.from(value); + } + } + + { + if (value !== null && !isArray(value)) { + // Verify that this is a simple plain object. + if (value.$$typeof === REACT_ELEMENT_TYPE) { + error('React Element cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key)); + } else if (value.$$typeof === REACT_LAZY_TYPE) { + error('React Lazy cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key)); + } else if (value.$$typeof === REACT_PROVIDER_TYPE) { + error('React Context Providers cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key)); + } else if (objectName(value) !== 'Object') { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, key)); + } else if (!isSimpleObject(value)) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Classes or other objects with methods are not supported.%s', describeObjectForErrorMessage(parent, key)); + } else if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(value); + + if (symbols.length > 0) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with symbol properties like %s are not supported.%s', symbols[0].description, describeObjectForErrorMessage(parent, key)); + } + } + } + } // $FlowFixMe[incompatible-return] + + + return value; + } + + if (typeof value === 'string') { + // TODO: Maybe too clever. If we support URL there's no similar trick. + if (value[value.length - 1] === 'Z') { + // Possibly a Date, whose toJSON automatically calls toISOString + // $FlowFixMe[incompatible-use] + var _originalValue = parent[key]; + + if (_originalValue instanceof Date) { + return serializeDateFromDateJSON(value); + } + } + + return escapeStringValue(value); + } + + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return serializeNumber(value); + } + + if (typeof value === 'undefined') { + return serializeUndefined(); + } + + if (typeof value === 'function') { + var metaData = knownServerReferences.get(value); + + if (metaData !== undefined) { + var metaDataJSON = JSON.stringify(metaData, resolveToJSON); + + if (formData === null) { + // Upgrade to use FormData to allow us to stream this value. + formData = new FormData(); + } // The reference to this function came from the same client so we can pass it back. + + + var _refId = nextPartId++; // eslint-disable-next-line react-internal/safe-string-coercion + + + formData.set(formFieldPrefix + _refId, metaDataJSON); + return serializeServerReferenceID(_refId); + } + + throw new Error('Client Functions cannot be passed directly to Server Functions. ' + 'Only Functions passed from the Server can be passed back again.'); + } + + if (typeof value === 'symbol') { + // $FlowFixMe[incompatible-type] `description` might be undefined + var name = value.description; + + if (Symbol.for(name) !== value) { + throw new Error('Only global symbols received from Symbol.for(...) can be passed to Server Functions. ' + ("The symbol Symbol.for(" + // $FlowFixMe[incompatible-type] `description` might be undefined + value.description + ") cannot be found among global symbols.")); + } + + return serializeSymbolReference(name); + } + + if (typeof value === 'bigint') { + return serializeBigInt(value); + } + + throw new Error("Type " + typeof value + " is not supported as an argument to a Server Function."); + } // $FlowFixMe[incompatible-type] it's not going to be undefined because we'll encode it. + + + var json = JSON.stringify(root, resolveToJSON); + + if (formData === null) { + // If it's a simple data structure, we just use plain JSON. + resolve(json); + } else { + // Otherwise, we use FormData to let us stream in the result. + formData.set(formFieldPrefix + '0', json); + + if (pendingParts === 0) { + // $FlowFixMe[incompatible-call] this has already been refined. + resolve(formData); + } + } +} + +function registerServerReference(proxy, reference) { + + knownServerReferences.set(proxy, reference); +} // $FlowFixMe[method-unbinding] + +function createServerReference(id, callServer) { + var proxy = function () { + // $FlowFixMe[method-unbinding] + var args = Array.prototype.slice.call(arguments); + return callServer(id, args); + }; + + registerServerReference(proxy, { + id: id, + bound: null + }); + return proxy; +} + +var ContextRegistry = ReactSharedInternals.ContextRegistry; +function getOrCreateServerContext(globalName) { + if (!ContextRegistry[globalName]) { + var context = { + $$typeof: REACT_SERVER_CONTEXT_TYPE, + // As a workaround to support multiple concurrent renderers, we categorize + // some renderers as primary and others as secondary. We only expect + // there to be two concurrent renderers at most: React Native (primary) and + // Fabric (secondary); React DOM (primary) and React ART (secondary). + // Secondary renderers store their context values on separate fields. + _currentValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + _currentValue2: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + _defaultValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + // Used to track how many concurrent renderers this context currently + // supports within in a single renderer. Such as parallel server rendering. + _threadCount: 0, + // These are circular + Provider: null, + Consumer: null, + _globalName: globalName + }; + context.Provider = { + $$typeof: REACT_PROVIDER_TYPE, + _context: context + }; + + { + var hasWarnedAboutUsingConsumer; + context._currentRenderer = null; + context._currentRenderer2 = null; + Object.defineProperties(context, { + Consumer: { + get: function () { + if (!hasWarnedAboutUsingConsumer) { + error('Consumer pattern is not supported by ReactServerContext'); + + hasWarnedAboutUsingConsumer = true; + } + + return null; + } + } + }); + } + + ContextRegistry[globalName] = context; + } + + return ContextRegistry[globalName]; +} + +var ROW_ID = 0; +var ROW_TAG = 1; +var ROW_LENGTH = 2; +var ROW_CHUNK_BY_NEWLINE = 3; +var ROW_CHUNK_BY_LENGTH = 4; +var PENDING = 'pending'; +var BLOCKED = 'blocked'; +var RESOLVED_MODEL = 'resolved_model'; +var RESOLVED_MODULE = 'resolved_module'; +var INITIALIZED = 'fulfilled'; +var ERRORED = 'rejected'; // $FlowFixMe[missing-this-annot] + +function Chunk(status, value, reason, response) { + this.status = status; + this.value = value; + this.reason = reason; + this._response = response; +} // We subclass Promise.prototype so that we get other methods like .catch + + +Chunk.prototype = Object.create(Promise.prototype); // TODO: This doesn't return a new Promise chain unlike the real .then + +Chunk.prototype.then = function (resolve, reject) { + var chunk = this; // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + resolve(chunk.value); + break; + + case PENDING: + case BLOCKED: + if (resolve) { + if (chunk.value === null) { + chunk.value = []; + } + + chunk.value.push(resolve); + } + + if (reject) { + if (chunk.reason === null) { + chunk.reason = []; + } + + chunk.reason.push(reject); + } + + break; + + default: + reject(chunk.reason); + break; + } +}; + +function readChunk(chunk) { + // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + return chunk.value; + + case PENDING: + case BLOCKED: + // eslint-disable-next-line no-throw-literal + throw chunk; + + default: + throw chunk.reason; + } +} + +function getRoot(response) { + var chunk = getChunk(response, 0); + return chunk; +} + +function createPendingChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(PENDING, null, null, response); +} + +function createBlockedChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(BLOCKED, null, null, response); +} + +function createErrorChunk(response, error) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(ERRORED, null, error, response); +} + +function wakeChunk(listeners, value) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + listener(value); + } +} + +function wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners) { + switch (chunk.status) { + case INITIALIZED: + wakeChunk(resolveListeners, chunk.value); + break; + + case PENDING: + case BLOCKED: + chunk.value = resolveListeners; + chunk.reason = rejectListeners; + break; + + case ERRORED: + if (rejectListeners) { + wakeChunk(rejectListeners, chunk.reason); + } + + break; + } +} + +function triggerErrorOnChunk(chunk, error) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var listeners = chunk.reason; + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + + if (listeners !== null) { + wakeChunk(listeners, error); + } +} + +function createResolvedModelChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODEL, value, null, response); +} + +function createResolvedModuleChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODULE, value, null, response); +} + +function createInitializedTextChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(INITIALIZED, value, null, response); +} + +function createInitializedBufferChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(INITIALIZED, value, null, response); +} + +function resolveModelChunk(chunk, value) { + if (chunk.status !== PENDING) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODEL; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + // This is unfortunate that we're reading this eagerly if + // we already have listeners attached since they might no + // longer be rendered or might not be the highest pri. + initializeModelChunk(resolvedChunk); // The status might have changed after initialization. + + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +function resolveModuleChunk(chunk, value) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODULE; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + initializeModuleChunk(resolvedChunk); + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +var initializingChunk = null; +var initializingChunkBlockedModel = null; + +function initializeModelChunk(chunk) { + var prevChunk = initializingChunk; + var prevBlocked = initializingChunkBlockedModel; + initializingChunk = chunk; + initializingChunkBlockedModel = null; + + try { + var value = parseModel(chunk._response, chunk.value); + + if (initializingChunkBlockedModel !== null && initializingChunkBlockedModel.deps > 0) { + initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved. + // We have to go the BLOCKED state until they're resolved. + + var blockedChunk = chunk; + blockedChunk.status = BLOCKED; + blockedChunk.value = null; + blockedChunk.reason = null; + } else { + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } finally { + initializingChunk = prevChunk; + initializingChunkBlockedModel = prevBlocked; + } +} + +function initializeModuleChunk(chunk) { + try { + var value = requireModule(chunk.value); + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } +} // Report that any missing chunks in the model is now going to throw this +// error upon read. Also notify any pending promises. + + +function reportGlobalError(response, error) { + response._chunks.forEach(function (chunk) { + // If this chunk was already resolved or errored, it won't + // trigger an error but if it wasn't then we need to + // because we won't be getting any new data to resolve it. + if (chunk.status === PENDING) { + triggerErrorOnChunk(chunk, error); + } + }); +} + +function createElement(type, key, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: null, + props: props, + // Record the component responsible for creating this element. + _owner: null + }; + + { + // We don't really need to add any of these but keeping them for good measure. + // Unfortunately, _store is enumerable in jest matchers so for equality to + // work, I need to keep it or make _store non-enumerable in the other file. + element._store = {}; + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: true // This element has already been validated on the server. + + }); + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: null + }); + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: null + }); + } + + return element; +} + +function createLazyChunkWrapper(chunk) { + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: chunk, + _init: readChunk + }; + return lazyType; +} + +function getChunk(response, id) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunk = createPendingChunk(response); + chunks.set(id, chunk); + } + + return chunk; +} + +function createModelResolver(chunk, parentObject, key) { + var blocked; + + if (initializingChunkBlockedModel) { + blocked = initializingChunkBlockedModel; + blocked.deps++; + } else { + blocked = initializingChunkBlockedModel = { + deps: 1, + value: null + }; + } + + return function (value) { + parentObject[key] = value; + blocked.deps--; + + if (blocked.deps === 0) { + if (chunk.status !== BLOCKED) { + return; + } + + var resolveListeners = chunk.value; + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = blocked.value; + + if (resolveListeners !== null) { + wakeChunk(resolveListeners, blocked.value); + } + } + }; +} + +function createModelReject(chunk) { + return function (error) { + return triggerErrorOnChunk(chunk, error); + }; +} + +function createServerReferenceProxy(response, metaData) { + var callServer = response._callServer; + + var proxy = function () { + // $FlowFixMe[method-unbinding] + var args = Array.prototype.slice.call(arguments); + var p = metaData.bound; + + if (!p) { + return callServer(metaData.id, args); + } + + if (p.status === INITIALIZED) { + var bound = p.value; + return callServer(metaData.id, bound.concat(args)); + } // Since this is a fake Promise whose .then doesn't chain, we have to wrap it. + // TODO: Remove the wrapper once that's fixed. + + + return Promise.resolve(p).then(function (bound) { + return callServer(metaData.id, bound.concat(args)); + }); + }; + + registerServerReference(proxy, metaData); + return proxy; +} + +function getOutlinedModel(response, id) { + var chunk = getChunk(response, id); + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + { + return chunk.value; + } + // We always encode it first in the stream so it won't be pending. + + default: + throw chunk.reason; + } +} + +function parseModelString(response, parentObject, key, value) { + if (value[0] === '$') { + if (value === '$') { + // A very common symbol. + return REACT_ELEMENT_TYPE; + } + + switch (value[1]) { + case '$': + { + // This was an escaped string value. + return value.slice(1); + } + + case 'L': + { + // Lazy node + var id = parseInt(value.slice(2), 16); + var chunk = getChunk(response, id); // We create a React.lazy wrapper around any lazy values. + // When passed into React, we'll know how to suspend on this. + + return createLazyChunkWrapper(chunk); + } + + case '@': + { + // Promise + var _id = parseInt(value.slice(2), 16); + + var _chunk = getChunk(response, _id); + + return _chunk; + } + + case 'S': + { + // Symbol + return Symbol.for(value.slice(2)); + } + + case 'P': + { + // Server Context Provider + return getOrCreateServerContext(value.slice(2)).Provider; + } + + case 'F': + { + // Server Reference + var _id2 = parseInt(value.slice(2), 16); + + var metadata = getOutlinedModel(response, _id2); + return createServerReferenceProxy(response, metadata); + } + + case 'Q': + { + // Map + var _id3 = parseInt(value.slice(2), 16); + + var data = getOutlinedModel(response, _id3); + return new Map(data); + } + + case 'W': + { + // Set + var _id4 = parseInt(value.slice(2), 16); + + var _data = getOutlinedModel(response, _id4); + + return new Set(_data); + } + + case 'I': + { + // $Infinity + return Infinity; + } + + case '-': + { + // $-0 or $-Infinity + if (value === '$-0') { + return -0; + } else { + return -Infinity; + } + } + + case 'N': + { + // $NaN + return NaN; + } + + case 'u': + { + // matches "$undefined" + // Special encoding for `undefined` which can't be serialized as JSON otherwise. + return undefined; + } + + case 'D': + { + // Date + return new Date(Date.parse(value.slice(2))); + } + + case 'n': + { + // BigInt + return BigInt(value.slice(2)); + } + + default: + { + // We assume that anything else is a reference ID. + var _id5 = parseInt(value.slice(1), 16); + + var _chunk2 = getChunk(response, _id5); + + switch (_chunk2.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk2); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(_chunk2); + break; + } // The status might have changed after initialization. + + + switch (_chunk2.status) { + case INITIALIZED: + return _chunk2.value; + + case PENDING: + case BLOCKED: + var parentChunk = initializingChunk; + + _chunk2.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); + + return null; + + default: + throw _chunk2.reason; + } + } + } + } + + return value; +} + +function parseModelTuple(response, value) { + var tuple = value; + + if (tuple[0] === REACT_ELEMENT_TYPE) { + // TODO: Consider having React just directly accept these arrays as elements. + // Or even change the ReactElement type to be an array. + return createElement(tuple[1], tuple[2], tuple[3]); + } + + return value; +} + +function missingCall() { + throw new Error('Trying to call a function from "use server" but the callServer option ' + 'was not implemented in your router runtime.'); +} + +function createResponse(bundlerConfig, moduleLoading, callServer, nonce) { + var chunks = new Map(); + var response = { + _bundlerConfig: bundlerConfig, + _moduleLoading: moduleLoading, + _callServer: callServer !== undefined ? callServer : missingCall, + _nonce: nonce, + _chunks: chunks, + _stringDecoder: createStringDecoder(), + _fromJSON: null, + _rowState: 0, + _rowID: 0, + _rowTag: 0, + _rowLength: 0, + _buffer: [] + }; // Don't inline this call because it causes closure to outline the call above. + + response._fromJSON = createFromJSONCallback(response); + return response; +} + +function resolveModel(response, id, model) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createResolvedModelChunk(response, model)); + } else { + resolveModelChunk(chunk, model); + } +} + +function resolveText(response, id, text) { + var chunks = response._chunks; // We assume that we always reference large strings after they've been + // emitted. + + chunks.set(id, createInitializedTextChunk(response, text)); +} + +function resolveBuffer(response, id, buffer) { + var chunks = response._chunks; // We assume that we always reference buffers after they've been emitted. + + chunks.set(id, createInitializedBufferChunk(response, buffer)); +} + +function resolveModule(response, id, model) { + var chunks = response._chunks; + var chunk = chunks.get(id); + var clientReferenceMetadata = parseModel(response, model); + var clientReference = resolveClientReference(response._bundlerConfig, clientReferenceMetadata); + // For now we preload all modules as early as possible since it's likely + // that we'll need them. + + var promise = preloadModule(clientReference); + + if (promise) { + var blockedChunk; + + if (!chunk) { + // Technically, we should just treat promise as the chunk in this + // case. Because it'll just behave as any other promise. + blockedChunk = createBlockedChunk(response); + chunks.set(id, blockedChunk); + } else { + // This can't actually happen because we don't have any forward + // references to modules. + blockedChunk = chunk; + blockedChunk.status = BLOCKED; + } + + promise.then(function () { + return resolveModuleChunk(blockedChunk, clientReference); + }, function (error) { + return triggerErrorOnChunk(blockedChunk, error); + }); + } else { + if (!chunk) { + chunks.set(id, createResolvedModuleChunk(response, clientReference)); + } else { + // This can't actually happen because we don't have any forward + // references to modules. + resolveModuleChunk(chunk, clientReference); + } + } +} + +function resolveErrorDev(response, id, digest, message, stack) { + + + var error = new Error(message || 'An error occurred in the Server Components render but no message was provided'); + error.stack = stack; + error.digest = digest; + var errorWithDigest = error; + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createErrorChunk(response, errorWithDigest)); + } else { + triggerErrorOnChunk(chunk, errorWithDigest); + } +} + +function resolvePostponeDev(response, id, reason, stack) { + + + var error = new Error(reason || ''); + var postponeInstance = error; + postponeInstance.$$typeof = REACT_POSTPONE_TYPE; + postponeInstance.stack = stack; + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createErrorChunk(response, postponeInstance)); + } else { + triggerErrorOnChunk(chunk, postponeInstance); + } +} + +function resolveHint(response, code, model) { + var hintModel = parseModel(response, model); + dispatchHint(code, hintModel); +} + +function mergeBuffer(buffer, lastChunk) { + var l = buffer.length; // Count the bytes we'll need + + var byteLength = lastChunk.length; + + for (var i = 0; i < l; i++) { + byteLength += buffer[i].byteLength; + } // Allocate enough contiguous space + + + var result = new Uint8Array(byteLength); + var offset = 0; // Copy all the buffers into it. + + for (var _i = 0; _i < l; _i++) { + var chunk = buffer[_i]; + result.set(chunk, offset); + offset += chunk.byteLength; + } + + result.set(lastChunk, offset); + return result; +} + +function resolveTypedArray(response, id, buffer, lastChunk, constructor, bytesPerElement) { + // If the view fits into one original buffer, we just reuse that buffer instead of + // copying it out to a separate copy. This means that it's not always possible to + // transfer these values to other threads without copying first since they may + // share array buffer. For this to work, it must also have bytes aligned to a + // multiple of a size of the type. + var chunk = buffer.length === 0 && lastChunk.byteOffset % bytesPerElement === 0 ? lastChunk : mergeBuffer(buffer, lastChunk); // TODO: The transfer protocol of RSC is little-endian. If the client isn't little-endian + // we should convert it instead. In practice big endian isn't really Web compatible so it's + // somewhat safe to assume that browsers aren't going to run it, but maybe there's some SSR + // server that's affected. + + var view = new constructor(chunk.buffer, chunk.byteOffset, chunk.byteLength / bytesPerElement); + resolveBuffer(response, id, view); +} + +function processFullRow(response, id, tag, buffer, chunk) { + { + switch (tag) { + case 65 + /* "A" */ + : + // We must always clone to extract it into a separate buffer instead of just a view. + resolveBuffer(response, id, mergeBuffer(buffer, chunk).buffer); + return; + + case 67 + /* "C" */ + : + resolveTypedArray(response, id, buffer, chunk, Int8Array, 1); + return; + + case 99 + /* "c" */ + : + resolveBuffer(response, id, buffer.length === 0 ? chunk : mergeBuffer(buffer, chunk)); + return; + + case 85 + /* "U" */ + : + resolveTypedArray(response, id, buffer, chunk, Uint8ClampedArray, 1); + return; + + case 83 + /* "S" */ + : + resolveTypedArray(response, id, buffer, chunk, Int16Array, 2); + return; + + case 115 + /* "s" */ + : + resolveTypedArray(response, id, buffer, chunk, Uint16Array, 2); + return; + + case 76 + /* "L" */ + : + resolveTypedArray(response, id, buffer, chunk, Int32Array, 4); + return; + + case 108 + /* "l" */ + : + resolveTypedArray(response, id, buffer, chunk, Uint32Array, 4); + return; + + case 70 + /* "F" */ + : + resolveTypedArray(response, id, buffer, chunk, Float32Array, 4); + return; + + case 68 + /* "D" */ + : + resolveTypedArray(response, id, buffer, chunk, Float64Array, 8); + return; + + case 78 + /* "N" */ + : + resolveTypedArray(response, id, buffer, chunk, BigInt64Array, 8); + return; + + case 109 + /* "m" */ + : + resolveTypedArray(response, id, buffer, chunk, BigUint64Array, 8); + return; + + case 86 + /* "V" */ + : + resolveTypedArray(response, id, buffer, chunk, DataView, 1); + return; + } + } + + var stringDecoder = response._stringDecoder; + var row = ''; + + for (var i = 0; i < buffer.length; i++) { + row += readPartialStringChunk(stringDecoder, buffer[i]); + } + + row += readFinalStringChunk(stringDecoder, chunk); + + switch (tag) { + case 73 + /* "I" */ + : + { + resolveModule(response, id, row); + return; + } + + case 72 + /* "H" */ + : + { + var code = row[0]; + resolveHint(response, code, row.slice(1)); + return; + } + + case 69 + /* "E" */ + : + { + var errorInfo = JSON.parse(row); + + { + resolveErrorDev(response, id, errorInfo.digest, errorInfo.message, errorInfo.stack); + } + + return; + } + + case 84 + /* "T" */ + : + { + resolveText(response, id, row); + return; + } + + case 80 + /* "P" */ + : + { + { + { + var postponeInfo = JSON.parse(row); + resolvePostponeDev(response, id, postponeInfo.reason, postponeInfo.stack); + } + + return; + } + } + // Fallthrough + + default: + /* """ "{" "[" "t" "f" "n" "0" - "9" */ + { + // We assume anything else is JSON. + resolveModel(response, id, row); + return; + } + } +} + +function processBinaryChunk(response, chunk) { + var i = 0; + var rowState = response._rowState; + var rowID = response._rowID; + var rowTag = response._rowTag; + var rowLength = response._rowLength; + var buffer = response._buffer; + var chunkLength = chunk.length; + + while (i < chunkLength) { + var lastIdx = -1; + + switch (rowState) { + case ROW_ID: + { + var byte = chunk[i++]; + + if (byte === 58 + /* ":" */ + ) { + // Finished the rowID, next we'll parse the tag. + rowState = ROW_TAG; + } else { + rowID = rowID << 4 | (byte > 96 ? byte - 87 : byte - 48); + } + + continue; + } + + case ROW_TAG: + { + var resolvedRowTag = chunk[i]; + + if (resolvedRowTag === 84 + /* "T" */ + || (resolvedRowTag === 65 + /* "A" */ + || resolvedRowTag === 67 + /* "C" */ + || resolvedRowTag === 99 + /* "c" */ + || resolvedRowTag === 85 + /* "U" */ + || resolvedRowTag === 83 + /* "S" */ + || resolvedRowTag === 115 + /* "s" */ + || resolvedRowTag === 76 + /* "L" */ + || resolvedRowTag === 108 + /* "l" */ + || resolvedRowTag === 70 + /* "F" */ + || resolvedRowTag === 68 + /* "D" */ + || resolvedRowTag === 78 + /* "N" */ + || resolvedRowTag === 109 + /* "m" */ + || resolvedRowTag === 86) + /* "V" */ + ) { + rowTag = resolvedRowTag; + rowState = ROW_LENGTH; + i++; + } else if (resolvedRowTag > 64 && resolvedRowTag < 91 + /* "A"-"Z" */ + ) { + rowTag = resolvedRowTag; + rowState = ROW_CHUNK_BY_NEWLINE; + i++; + } else { + rowTag = 0; + rowState = ROW_CHUNK_BY_NEWLINE; // This was an unknown tag so it was probably part of the data. + } + + continue; + } + + case ROW_LENGTH: + { + var _byte = chunk[i++]; + + if (_byte === 44 + /* "," */ + ) { + // Finished the rowLength, next we'll buffer up to that length. + rowState = ROW_CHUNK_BY_LENGTH; + } else { + rowLength = rowLength << 4 | (_byte > 96 ? _byte - 87 : _byte - 48); + } + + continue; + } + + case ROW_CHUNK_BY_NEWLINE: + { + // We're looking for a newline + lastIdx = chunk.indexOf(10 + /* "\n" */ + , i); + break; + } + + case ROW_CHUNK_BY_LENGTH: + { + // We're looking for the remaining byte length + lastIdx = i + rowLength; + + if (lastIdx > chunk.length) { + lastIdx = -1; + } + + break; + } + } + + var offset = chunk.byteOffset + i; + + if (lastIdx > -1) { + // We found the last chunk of the row + var length = lastIdx - i; + var lastChunk = new Uint8Array(chunk.buffer, offset, length); + processFullRow(response, rowID, rowTag, buffer, lastChunk); // Reset state machine for a new row + + i = lastIdx; + + if (rowState === ROW_CHUNK_BY_NEWLINE) { + // If we're trailing by a newline we need to skip it. + i++; + } + + rowState = ROW_ID; + rowTag = 0; + rowID = 0; + rowLength = 0; + buffer.length = 0; + } else { + // The rest of this row is in a future chunk. We stash the rest of the + // current chunk until we can process the full row. + var _length = chunk.byteLength - i; + + var remainingSlice = new Uint8Array(chunk.buffer, offset, _length); + buffer.push(remainingSlice); // Update how many bytes we're still waiting for. If we're looking for + // a newline, this doesn't hurt since we'll just ignore it. + + rowLength -= remainingSlice.byteLength; + break; + } + } + + response._rowState = rowState; + response._rowID = rowID; + response._rowTag = rowTag; + response._rowLength = rowLength; +} + +function parseModel(response, json) { + return JSON.parse(json, response._fromJSON); +} + +function createFromJSONCallback(response) { + // $FlowFixMe[missing-this-annot] + return function (key, value) { + if (typeof value === 'string') { + // We can't use .bind here because we need the "this" value. + return parseModelString(response, this, key, value); + } + + if (typeof value === 'object' && value !== null) { + return parseModelTuple(response, value); + } + + return value; + }; +} + +function close(response) { + // In case there are any remaining unresolved chunks, they won't + // be resolved now. So we need to issue an error to those. + // Ideally we should be able to early bail out if we kept a + // ref count of pending chunks. + reportGlobalError(response, new Error('Connection closed.')); +} + +function createResponseFromOptions(options) { + return createResponse(null, null, options && options.callServer ? options.callServer : undefined, undefined // nonce + ); +} + +function startReadingFromStream(response, stream) { + var reader = stream.getReader(); + + function progress(_ref) { + var done = _ref.done, + value = _ref.value; + + if (done) { + close(response); + return; + } + + var buffer = value; + processBinaryChunk(response, buffer); + return reader.read().then(progress).catch(error); + } + + function error(e) { + reportGlobalError(response, e); + } + + reader.read().then(progress).catch(error); +} + +function createFromReadableStream(stream, options) { + var response = createResponseFromOptions(options); + startReadingFromStream(response, stream); + return getRoot(response); +} + +function createFromFetch(promiseForResponse, options) { + var response = createResponseFromOptions(options); + promiseForResponse.then(function (r) { + startReadingFromStream(response, r.body); + }, function (e) { + reportGlobalError(response, e); + }); + return getRoot(response); +} + +function encodeReply(value) +/* We don't use URLSearchParams yet but maybe */ +{ + return new Promise(function (resolve, reject) { + processReply(value, '', resolve, reject); + }); +} + +exports.createFromFetch = createFromFetch; +exports.createFromReadableStream = createFromReadableStream; +exports.createServerReference = createServerReference; +exports.encodeReply = encodeReply; + })(); +} diff --git a/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-client.browser.production.min.js b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-client.browser.production.min.js new file mode 100644 index 0000000000000..33d2aea8708fb --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-client.browser.production.min.js @@ -0,0 +1,39 @@ +/** + * @license React + * react-server-dom-turbopack-client.browser.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var p=require("react-dom"),q=require("react"),r={stream:!0};function u(a,b){if(a){var c=a[b[0]];if(a=c[b[2]])c=a.name;else{a=c["*"];if(!a)throw Error('Could not find the module "'+b[0]+'" in the React SSR Manifest. This is probably a bug in the React Server Components bundler.');c=b[2]}return 4===b.length?[a.id,a.chunks,c,1]:[a.id,a.chunks,c]}return b}var w=new Map; +function x(a){var b=__turbopack_require__(a);if("function"!==typeof b.then||"fulfilled"===b.status)return null;b.then(function(c){b.status="fulfilled";b.value=c},function(c){b.status="rejected";b.reason=c});return b}function y(){} +function z(a){for(var b=a[1],c=[],d=0;dh?(g=h,h=3,l++):(g=0,h=3);continue;case 2:m=e[l++];44===m?h=4:n=n<<4|(96e.length&&(m=-1)}var t=e.byteOffset+l;if(-1 0) { + return Promise.all(promises); + } else { + return null; + } +} // Actually require the module or suspend if it's not yet ready. +// Increase priority if necessary. + +function requireModule(metadata) { + var moduleExports = globalThis.__next_require__(metadata[ID]); + + if (isAsyncImport(metadata)) { + if (typeof moduleExports.then !== 'function') ; else if (moduleExports.status === 'fulfilled') { + // This Promise should've been instrumented by preloadModule. + moduleExports = moduleExports.value; + } else { + throw moduleExports.reason; + } + } + + if (metadata[NAME] === '*') { + // This is a placeholder value that represents that the caller imported this + // as a CommonJS module as is. + return moduleExports; + } + + if (metadata[NAME] === '') { + // This is a placeholder value that represents that the caller accessed the + // default property of this if it was an ESM interop module. + return moduleExports.__esModule ? moduleExports.default : moduleExports; + } + + return moduleExports[metadata[NAME]]; +} + +function loadChunk(filename) { + return globalThis.__next_chunk_load__(filename); +} + +function prepareDestinationWithChunks(moduleLoading, // Chunks are single-indexed filenames +chunks, nonce) { + if (moduleLoading !== null) { + for (var i = 0; i < chunks.length; i++) { + preinitScriptForSSR(moduleLoading.prefix + chunks[i], nonce, moduleLoading.crossOrigin); + } + } +} + +var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +function getCrossOriginString(input) { + if (typeof input === 'string') { + return input === 'use-credentials' ? input : ''; + } + + return undefined; +} + +// This client file is in the shared folder because it applies to both SSR and browser contexts. +var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher; +function dispatchHint(code, model) { + var dispatcher = ReactDOMCurrentDispatcher.current; + + if (dispatcher) { + switch (code) { + case 'D': + { + var refined = refineModel(code, model); + var href = refined; + dispatcher.prefetchDNS(href); + return; + } + + case 'C': + { + var _refined = refineModel(code, model); + + if (typeof _refined === 'string') { + var _href = _refined; + dispatcher.preconnect(_href); + } else { + var _href2 = _refined[0]; + var crossOrigin = _refined[1]; + dispatcher.preconnect(_href2, crossOrigin); + } + + return; + } + + case 'L': + { + var _refined2 = refineModel(code, model); + + var _href3 = _refined2[0]; + var as = _refined2[1]; + + if (_refined2.length === 3) { + var options = _refined2[2]; + dispatcher.preload(_href3, as, options); + } else { + dispatcher.preload(_href3, as); + } + + return; + } + + case 'm': + { + var _refined3 = refineModel(code, model); + + if (typeof _refined3 === 'string') { + var _href4 = _refined3; + dispatcher.preloadModule(_href4); + } else { + var _href5 = _refined3[0]; + var _options = _refined3[1]; + dispatcher.preloadModule(_href5, _options); + } + + return; + } + + case 'S': + { + var _refined4 = refineModel(code, model); + + if (typeof _refined4 === 'string') { + var _href6 = _refined4; + dispatcher.preinitStyle(_href6); + } else { + var _href7 = _refined4[0]; + var precedence = _refined4[1] === 0 ? undefined : _refined4[1]; + + var _options2 = _refined4.length === 3 ? _refined4[2] : undefined; + + dispatcher.preinitStyle(_href7, precedence, _options2); + } + + return; + } + + case 'X': + { + var _refined5 = refineModel(code, model); + + if (typeof _refined5 === 'string') { + var _href8 = _refined5; + dispatcher.preinitScript(_href8); + } else { + var _href9 = _refined5[0]; + var _options3 = _refined5[1]; + dispatcher.preinitScript(_href9, _options3); + } + + return; + } + + case 'M': + { + var _refined6 = refineModel(code, model); + + if (typeof _refined6 === 'string') { + var _href10 = _refined6; + dispatcher.preinitModuleScript(_href10); + } else { + var _href11 = _refined6[0]; + var _options4 = _refined6[1]; + dispatcher.preinitModuleScript(_href11, _options4); + } + + return; + } + } + } +} // Flow is having troulbe refining the HintModels so we help it a bit. +// This should be compiled out in the production build. + +function refineModel(code, model) { + return model; +} +function preinitScriptForSSR(href, nonce, crossOrigin) { + var dispatcher = ReactDOMCurrentDispatcher.current; + + if (dispatcher) { + dispatcher.preinitScript(href, { + crossOrigin: getCrossOriginString(crossOrigin), + nonce: nonce + }); + } +} + +var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); +var REACT_POSTPONE_TYPE = Symbol.for('react.postpone'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +// in case they error. + +var jsxPropsParents = new WeakMap(); +var jsxChildrenParents = new WeakMap(); + +function isObjectPrototype(object) { + if (!object) { + return false; + } + + var ObjectPrototype = Object.prototype; + + if (object === ObjectPrototype) { + return true; + } // It might be an object from a different Realm which is + // still just a plain simple object. + + + if (Object.getPrototypeOf(object)) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + if (!(names[i] in ObjectPrototype)) { + return false; + } + } + + return true; +} + +function isSimpleObject(object) { + if (!isObjectPrototype(Object.getPrototypeOf(object))) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + var descriptor = Object.getOwnPropertyDescriptor(object, names[i]); + + if (!descriptor) { + return false; + } + + if (!descriptor.enumerable) { + if ((names[i] === 'key' || names[i] === 'ref') && typeof descriptor.get === 'function') { + // React adds key and ref getters to props objects to issue warnings. + // Those getters will not be transferred to the client, but that's ok, + // so we'll special case them. + continue; + } + + return false; + } + } + + return true; +} +function objectName(object) { + // $FlowFixMe[method-unbinding] + var name = Object.prototype.toString.call(object); + return name.replace(/^\[object (.*)\]$/, function (m, p0) { + return p0; + }); +} + +function describeKeyForErrorMessage(key) { + var encodedKey = JSON.stringify(key); + return '"' + key + '"' === encodedKey ? key : encodedKey; +} + +function describeValueForErrorMessage(value) { + switch (typeof value) { + case 'string': + { + return JSON.stringify(value.length <= 10 ? value : value.slice(0, 10) + '...'); + } + + case 'object': + { + if (isArray(value)) { + return '[...]'; + } + + var name = objectName(value); + + if (name === 'Object') { + return '{...}'; + } + + return name; + } + + case 'function': + return 'function'; + + default: + // eslint-disable-next-line react-internal/safe-string-coercion + return String(value); + } +} + +function describeElementType(type) { + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeElementType(type.render); + + case REACT_MEMO_TYPE: + return describeElementType(type.type); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeElementType(init(payload)); + } catch (x) {} + } + } + } + + return ''; +} + +function describeObjectForErrorMessage(objectOrArray, expandedName) { + var objKind = objectName(objectOrArray); + + if (objKind !== 'Object' && objKind !== 'Array') { + return objKind; + } + + var str = ''; + var start = -1; + var length = 0; + + if (isArray(objectOrArray)) { + if (jsxChildrenParents.has(objectOrArray)) { + // Print JSX Children + var type = jsxChildrenParents.get(objectOrArray); + str = '<' + describeElementType(type) + '>'; + var array = objectOrArray; + + for (var i = 0; i < array.length; i++) { + var value = array[i]; + var substr = void 0; + + if (typeof value === 'string') { + substr = value; + } else if (typeof value === 'object' && value !== null) { + substr = '{' + describeObjectForErrorMessage(value) + '}'; + } else { + substr = '{' + describeValueForErrorMessage(value) + '}'; + } + + if ('' + i === expandedName) { + start = str.length; + length = substr.length; + str += substr; + } else if (substr.length < 15 && str.length + substr.length < 40) { + str += substr; + } else { + str += '{...}'; + } + } + + str += ''; + } else { + // Print Array + str = '['; + var _array = objectOrArray; + + for (var _i = 0; _i < _array.length; _i++) { + if (_i > 0) { + str += ', '; + } + + var _value = _array[_i]; + + var _substr = void 0; + + if (typeof _value === 'object' && _value !== null) { + _substr = describeObjectForErrorMessage(_value); + } else { + _substr = describeValueForErrorMessage(_value); + } + + if ('' + _i === expandedName) { + start = str.length; + length = _substr.length; + str += _substr; + } else if (_substr.length < 10 && str.length + _substr.length < 40) { + str += _substr; + } else { + str += '...'; + } + } + + str += ']'; + } + } else { + if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) { + str = '<' + describeElementType(objectOrArray.type) + '/>'; + } else if (jsxPropsParents.has(objectOrArray)) { + // Print JSX + var _type = jsxPropsParents.get(objectOrArray); + + str = '<' + (describeElementType(_type) || '...'); + var object = objectOrArray; + var names = Object.keys(object); + + for (var _i2 = 0; _i2 < names.length; _i2++) { + str += ' '; + var name = names[_i2]; + str += describeKeyForErrorMessage(name) + '='; + var _value2 = object[name]; + + var _substr2 = void 0; + + if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) { + _substr2 = describeObjectForErrorMessage(_value2); + } else { + _substr2 = describeValueForErrorMessage(_value2); + } + + if (typeof _value2 !== 'string') { + _substr2 = '{' + _substr2 + '}'; + } + + if (name === expandedName) { + start = str.length; + length = _substr2.length; + str += _substr2; + } else if (_substr2.length < 10 && str.length + _substr2.length < 40) { + str += _substr2; + } else { + str += '...'; + } + } + + str += '>'; + } else { + // Print Object + str = '{'; + var _object = objectOrArray; + + var _names = Object.keys(_object); + + for (var _i3 = 0; _i3 < _names.length; _i3++) { + if (_i3 > 0) { + str += ', '; + } + + var _name = _names[_i3]; + str += describeKeyForErrorMessage(_name) + ': '; + var _value3 = _object[_name]; + + var _substr3 = void 0; + + if (typeof _value3 === 'object' && _value3 !== null) { + _substr3 = describeObjectForErrorMessage(_value3); + } else { + _substr3 = describeValueForErrorMessage(_value3); + } + + if (_name === expandedName) { + start = str.length; + length = _substr3.length; + str += _substr3; + } else if (_substr3.length < 10 && str.length + _substr3.length < 40) { + str += _substr3; + } else { + str += '...'; + } + } + + str += '}'; + } + } + + if (expandedName === undefined) { + return str; + } + + if (start > -1 && length > 0) { + var highlight = ' '.repeat(start) + '^'.repeat(length); + return '\n ' + str + '\n ' + highlight; + } + + return '\n ' + str; +} + +var knownServerReferences = new WeakMap(); // Serializable values +// Thenable +// function serializeByValueID(id: number): string { +// return '$' + id.toString(16); +// } + +function serializePromiseID(id) { + return '$@' + id.toString(16); +} + +function serializeServerReferenceID(id) { + return '$F' + id.toString(16); +} + +function serializeSymbolReference(name) { + return '$S' + name; +} + +function serializeFormDataReference(id) { + // Why K? F is "Function". D is "Date". What else? + return '$K' + id.toString(16); +} + +function serializeNumber(number) { + if (Number.isFinite(number)) { + if (number === 0 && 1 / number === -Infinity) { + return '$-0'; + } else { + return number; + } + } else { + if (number === Infinity) { + return '$Infinity'; + } else if (number === -Infinity) { + return '$-Infinity'; + } else { + return '$NaN'; + } + } +} + +function serializeUndefined() { + return '$undefined'; +} + +function serializeDateFromDateJSON(dateJSON) { + // JSON.stringify automatically calls Date.prototype.toJSON which calls toISOString. + // We need only tack on a $D prefix. + return '$D' + dateJSON; +} + +function serializeBigInt(n) { + return '$n' + n.toString(10); +} + +function serializeMapID(id) { + return '$Q' + id.toString(16); +} + +function serializeSetID(id) { + return '$W' + id.toString(16); +} + +function escapeStringValue(value) { + if (value[0] === '$') { + // We need to escape $ prefixed strings since we use those to encode + // references to IDs and as special symbol values. + return '$' + value; + } else { + return value; + } +} + +function processReply(root, formFieldPrefix, resolve, reject) { + var nextPartId = 1; + var pendingParts = 0; + var formData = null; + + function resolveToJSON(key, value) { + var parent = this; // Make sure that `parent[key]` wasn't JSONified before `value` was passed to us + + { + // $FlowFixMe[incompatible-use] + var originalValue = parent[key]; + + if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) { + if (objectName(originalValue) !== 'Object') { + error('Only plain objects can be passed to Server Functions from the Client. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } else { + error('Only plain objects can be passed to Server Functions from the Client. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props.%s', describeObjectForErrorMessage(parent, key)); + } + } + } + + if (value === null) { + return null; + } + + if (typeof value === 'object') { + // $FlowFixMe[method-unbinding] + if (typeof value.then === 'function') { + // We assume that any object with a .then property is a "Thenable" type, + // or a Promise type. Either of which can be represented by a Promise. + if (formData === null) { + // Upgrade to use FormData to allow us to stream this value. + formData = new FormData(); + } + + pendingParts++; + var promiseId = nextPartId++; + var thenable = value; + thenable.then(function (partValue) { + var partJSON = JSON.stringify(partValue, resolveToJSON); // $FlowFixMe[incompatible-type] We know it's not null because we assigned it above. + + var data = formData; // eslint-disable-next-line react-internal/safe-string-coercion + + data.append(formFieldPrefix + promiseId, partJSON); + pendingParts--; + + if (pendingParts === 0) { + resolve(data); + } + }, function (reason) { + // In the future we could consider serializing this as an error + // that throws on the server instead. + reject(reason); + }); + return serializePromiseID(promiseId); + } // TODO: Should we the Object.prototype.toString.call() to test for cross-realm objects? + + + if (value instanceof FormData) { + if (formData === null) { + // Upgrade to use FormData to allow us to use rich objects as its values. + formData = new FormData(); + } + + var data = formData; + var refId = nextPartId++; // Copy all the form fields with a prefix for this reference. + // These must come first in the form order because we assume that all the + // fields are available before this is referenced. + + var prefix = formFieldPrefix + refId + '_'; // $FlowFixMe[prop-missing]: FormData has forEach. + + value.forEach(function (originalValue, originalKey) { + data.append(prefix + originalKey, originalValue); + }); + return serializeFormDataReference(refId); + } + + if (value instanceof Map) { + var partJSON = JSON.stringify(Array.from(value), resolveToJSON); + + if (formData === null) { + formData = new FormData(); + } + + var mapId = nextPartId++; + formData.append(formFieldPrefix + mapId, partJSON); + return serializeMapID(mapId); + } + + if (value instanceof Set) { + var _partJSON = JSON.stringify(Array.from(value), resolveToJSON); + + if (formData === null) { + formData = new FormData(); + } + + var setId = nextPartId++; + formData.append(formFieldPrefix + setId, _partJSON); + return serializeSetID(setId); + } + + if (!isArray(value)) { + var iteratorFn = getIteratorFn(value); + + if (iteratorFn) { + return Array.from(value); + } + } + + { + if (value !== null && !isArray(value)) { + // Verify that this is a simple plain object. + if (value.$$typeof === REACT_ELEMENT_TYPE) { + error('React Element cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key)); + } else if (value.$$typeof === REACT_LAZY_TYPE) { + error('React Lazy cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key)); + } else if (value.$$typeof === REACT_PROVIDER_TYPE) { + error('React Context Providers cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key)); + } else if (objectName(value) !== 'Object') { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, key)); + } else if (!isSimpleObject(value)) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Classes or other objects with methods are not supported.%s', describeObjectForErrorMessage(parent, key)); + } else if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(value); + + if (symbols.length > 0) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with symbol properties like %s are not supported.%s', symbols[0].description, describeObjectForErrorMessage(parent, key)); + } + } + } + } // $FlowFixMe[incompatible-return] + + + return value; + } + + if (typeof value === 'string') { + // TODO: Maybe too clever. If we support URL there's no similar trick. + if (value[value.length - 1] === 'Z') { + // Possibly a Date, whose toJSON automatically calls toISOString + // $FlowFixMe[incompatible-use] + var _originalValue = parent[key]; + + if (_originalValue instanceof Date) { + return serializeDateFromDateJSON(value); + } + } + + return escapeStringValue(value); + } + + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return serializeNumber(value); + } + + if (typeof value === 'undefined') { + return serializeUndefined(); + } + + if (typeof value === 'function') { + var metaData = knownServerReferences.get(value); + + if (metaData !== undefined) { + var metaDataJSON = JSON.stringify(metaData, resolveToJSON); + + if (formData === null) { + // Upgrade to use FormData to allow us to stream this value. + formData = new FormData(); + } // The reference to this function came from the same client so we can pass it back. + + + var _refId = nextPartId++; // eslint-disable-next-line react-internal/safe-string-coercion + + + formData.set(formFieldPrefix + _refId, metaDataJSON); + return serializeServerReferenceID(_refId); + } + + throw new Error('Client Functions cannot be passed directly to Server Functions. ' + 'Only Functions passed from the Server can be passed back again.'); + } + + if (typeof value === 'symbol') { + // $FlowFixMe[incompatible-type] `description` might be undefined + var name = value.description; + + if (Symbol.for(name) !== value) { + throw new Error('Only global symbols received from Symbol.for(...) can be passed to Server Functions. ' + ("The symbol Symbol.for(" + // $FlowFixMe[incompatible-type] `description` might be undefined + value.description + ") cannot be found among global symbols.")); + } + + return serializeSymbolReference(name); + } + + if (typeof value === 'bigint') { + return serializeBigInt(value); + } + + throw new Error("Type " + typeof value + " is not supported as an argument to a Server Function."); + } // $FlowFixMe[incompatible-type] it's not going to be undefined because we'll encode it. + + + var json = JSON.stringify(root, resolveToJSON); + + if (formData === null) { + // If it's a simple data structure, we just use plain JSON. + resolve(json); + } else { + // Otherwise, we use FormData to let us stream in the result. + formData.set(formFieldPrefix + '0', json); + + if (pendingParts === 0) { + // $FlowFixMe[incompatible-call] this has already been refined. + resolve(formData); + } + } +} +var boundCache = new WeakMap(); + +function encodeFormData(reference) { + var resolve, reject; // We need to have a handle on the thenable so that we can synchronously set + // its status from processReply, when it can complete synchronously. + + var thenable = new Promise(function (res, rej) { + resolve = res; + reject = rej; + }); + processReply(reference, '', function (body) { + if (typeof body === 'string') { + var data = new FormData(); + data.append('0', body); + body = data; + } + + var fulfilled = thenable; + fulfilled.status = 'fulfilled'; + fulfilled.value = body; + resolve(body); + }, function (e) { + var rejected = thenable; + rejected.status = 'rejected'; + rejected.reason = e; + reject(e); + }); + return thenable; +} + +function encodeFormAction(identifierPrefix) { + var reference = knownServerReferences.get(this); + + if (!reference) { + throw new Error('Tried to encode a Server Action from a different instance than the encoder is from. ' + 'This is a bug in React.'); + } + + var data = null; + var name; + var boundPromise = reference.bound; + + if (boundPromise !== null) { + var thenable = boundCache.get(reference); + + if (!thenable) { + thenable = encodeFormData(reference); + boundCache.set(reference, thenable); + } + + if (thenable.status === 'rejected') { + throw thenable.reason; + } else if (thenable.status !== 'fulfilled') { + throw thenable; + } + + var encodedFormData = thenable.value; // This is hacky but we need the identifier prefix to be added to + // all fields but the suspense cache would break since we might get + // a new identifier each time. So we just append it at the end instead. + + var prefixedData = new FormData(); // $FlowFixMe[prop-missing] + + encodedFormData.forEach(function (value, key) { + prefixedData.append('$ACTION_' + identifierPrefix + ':' + key, value); + }); + data = prefixedData; // We encode the name of the prefix containing the data. + + name = '$ACTION_REF_' + identifierPrefix; + } else { + // This is the simple case so we can just encode the ID. + name = '$ACTION_ID_' + reference.id; + } + + return { + name: name, + method: 'POST', + encType: 'multipart/form-data', + data: data + }; +} + +function isSignatureEqual(referenceId, numberOfBoundArgs) { + var reference = knownServerReferences.get(this); + + if (!reference) { + throw new Error('Tried to encode a Server Action from a different instance than the encoder is from. ' + 'This is a bug in React.'); + } + + if (reference.id !== referenceId) { + // These are different functions. + return false; + } // Now check if the number of bound arguments is the same. + + + var boundPromise = reference.bound; + + if (boundPromise === null) { + // No bound arguments. + return numberOfBoundArgs === 0; + } // Unwrap the bound arguments array by suspending, if necessary. As with + // encodeFormData, this means isSignatureEqual can only be called while React + // is rendering. + + + switch (boundPromise.status) { + case 'fulfilled': + { + var boundArgs = boundPromise.value; + return boundArgs.length === numberOfBoundArgs; + } + + case 'pending': + { + throw boundPromise; + } + + case 'rejected': + { + throw boundPromise.reason; + } + + default: + { + if (typeof boundPromise.status === 'string') ; else { + var pendingThenable = boundPromise; + pendingThenable.status = 'pending'; + pendingThenable.then(function (boundArgs) { + var fulfilledThenable = boundPromise; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = boundArgs; + }, function (error) { + var rejectedThenable = boundPromise; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + }); + } + + throw boundPromise; + } + } +} + +function registerServerReference(proxy, reference) { + // Expose encoder for use by SSR, as well as a special bind that can be used to + // keep server capabilities. + { + // Only expose this in builds that would actually use it. Not needed on the client. + Object.defineProperties(proxy, { + $$FORM_ACTION: { + value: encodeFormAction + }, + $$IS_SIGNATURE_EQUAL: { + value: isSignatureEqual + }, + bind: { + value: bind + } + }); + } + + knownServerReferences.set(proxy, reference); +} // $FlowFixMe[method-unbinding] + +var FunctionBind = Function.prototype.bind; // $FlowFixMe[method-unbinding] + +var ArraySlice = Array.prototype.slice; + +function bind() { + // $FlowFixMe[unsupported-syntax] + var newFn = FunctionBind.apply(this, arguments); + var reference = knownServerReferences.get(this); + + if (reference) { + var args = ArraySlice.call(arguments, 1); + var boundPromise = null; + + if (reference.bound !== null) { + boundPromise = Promise.resolve(reference.bound).then(function (boundArgs) { + return boundArgs.concat(args); + }); + } else { + boundPromise = Promise.resolve(args); + } + + registerServerReference(newFn, { + id: reference.id, + bound: boundPromise + }); + } + + return newFn; +} + +function createServerReference$1(id, callServer) { + var proxy = function () { + // $FlowFixMe[method-unbinding] + var args = Array.prototype.slice.call(arguments); + return callServer(id, args); + }; + + registerServerReference(proxy, { + id: id, + bound: null + }); + return proxy; +} + +var ContextRegistry = ReactSharedInternals.ContextRegistry; +function getOrCreateServerContext(globalName) { + if (!ContextRegistry[globalName]) { + var context = { + $$typeof: REACT_SERVER_CONTEXT_TYPE, + // As a workaround to support multiple concurrent renderers, we categorize + // some renderers as primary and others as secondary. We only expect + // there to be two concurrent renderers at most: React Native (primary) and + // Fabric (secondary); React DOM (primary) and React ART (secondary). + // Secondary renderers store their context values on separate fields. + _currentValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + _currentValue2: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + _defaultValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + // Used to track how many concurrent renderers this context currently + // supports within in a single renderer. Such as parallel server rendering. + _threadCount: 0, + // These are circular + Provider: null, + Consumer: null, + _globalName: globalName + }; + context.Provider = { + $$typeof: REACT_PROVIDER_TYPE, + _context: context + }; + + { + var hasWarnedAboutUsingConsumer; + context._currentRenderer = null; + context._currentRenderer2 = null; + Object.defineProperties(context, { + Consumer: { + get: function () { + if (!hasWarnedAboutUsingConsumer) { + error('Consumer pattern is not supported by ReactServerContext'); + + hasWarnedAboutUsingConsumer = true; + } + + return null; + } + } + }); + } + + ContextRegistry[globalName] = context; + } + + return ContextRegistry[globalName]; +} + +var ROW_ID = 0; +var ROW_TAG = 1; +var ROW_LENGTH = 2; +var ROW_CHUNK_BY_NEWLINE = 3; +var ROW_CHUNK_BY_LENGTH = 4; +var PENDING = 'pending'; +var BLOCKED = 'blocked'; +var RESOLVED_MODEL = 'resolved_model'; +var RESOLVED_MODULE = 'resolved_module'; +var INITIALIZED = 'fulfilled'; +var ERRORED = 'rejected'; // $FlowFixMe[missing-this-annot] + +function Chunk(status, value, reason, response) { + this.status = status; + this.value = value; + this.reason = reason; + this._response = response; +} // We subclass Promise.prototype so that we get other methods like .catch + + +Chunk.prototype = Object.create(Promise.prototype); // TODO: This doesn't return a new Promise chain unlike the real .then + +Chunk.prototype.then = function (resolve, reject) { + var chunk = this; // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + resolve(chunk.value); + break; + + case PENDING: + case BLOCKED: + if (resolve) { + if (chunk.value === null) { + chunk.value = []; + } + + chunk.value.push(resolve); + } + + if (reject) { + if (chunk.reason === null) { + chunk.reason = []; + } + + chunk.reason.push(reject); + } + + break; + + default: + reject(chunk.reason); + break; + } +}; + +function readChunk(chunk) { + // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + return chunk.value; + + case PENDING: + case BLOCKED: + // eslint-disable-next-line no-throw-literal + throw chunk; + + default: + throw chunk.reason; + } +} + +function getRoot(response) { + var chunk = getChunk(response, 0); + return chunk; +} + +function createPendingChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(PENDING, null, null, response); +} + +function createBlockedChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(BLOCKED, null, null, response); +} + +function createErrorChunk(response, error) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(ERRORED, null, error, response); +} + +function wakeChunk(listeners, value) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + listener(value); + } +} + +function wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners) { + switch (chunk.status) { + case INITIALIZED: + wakeChunk(resolveListeners, chunk.value); + break; + + case PENDING: + case BLOCKED: + chunk.value = resolveListeners; + chunk.reason = rejectListeners; + break; + + case ERRORED: + if (rejectListeners) { + wakeChunk(rejectListeners, chunk.reason); + } + + break; + } +} + +function triggerErrorOnChunk(chunk, error) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var listeners = chunk.reason; + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + + if (listeners !== null) { + wakeChunk(listeners, error); + } +} + +function createResolvedModelChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODEL, value, null, response); +} + +function createResolvedModuleChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODULE, value, null, response); +} + +function createInitializedTextChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(INITIALIZED, value, null, response); +} + +function createInitializedBufferChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(INITIALIZED, value, null, response); +} + +function resolveModelChunk(chunk, value) { + if (chunk.status !== PENDING) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODEL; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + // This is unfortunate that we're reading this eagerly if + // we already have listeners attached since they might no + // longer be rendered or might not be the highest pri. + initializeModelChunk(resolvedChunk); // The status might have changed after initialization. + + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +function resolveModuleChunk(chunk, value) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODULE; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + initializeModuleChunk(resolvedChunk); + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +var initializingChunk = null; +var initializingChunkBlockedModel = null; + +function initializeModelChunk(chunk) { + var prevChunk = initializingChunk; + var prevBlocked = initializingChunkBlockedModel; + initializingChunk = chunk; + initializingChunkBlockedModel = null; + + try { + var value = parseModel(chunk._response, chunk.value); + + if (initializingChunkBlockedModel !== null && initializingChunkBlockedModel.deps > 0) { + initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved. + // We have to go the BLOCKED state until they're resolved. + + var blockedChunk = chunk; + blockedChunk.status = BLOCKED; + blockedChunk.value = null; + blockedChunk.reason = null; + } else { + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } finally { + initializingChunk = prevChunk; + initializingChunkBlockedModel = prevBlocked; + } +} + +function initializeModuleChunk(chunk) { + try { + var value = requireModule(chunk.value); + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } +} // Report that any missing chunks in the model is now going to throw this +// error upon read. Also notify any pending promises. + + +function reportGlobalError(response, error) { + response._chunks.forEach(function (chunk) { + // If this chunk was already resolved or errored, it won't + // trigger an error but if it wasn't then we need to + // because we won't be getting any new data to resolve it. + if (chunk.status === PENDING) { + triggerErrorOnChunk(chunk, error); + } + }); +} + +function createElement(type, key, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: null, + props: props, + // Record the component responsible for creating this element. + _owner: null + }; + + { + // We don't really need to add any of these but keeping them for good measure. + // Unfortunately, _store is enumerable in jest matchers so for equality to + // work, I need to keep it or make _store non-enumerable in the other file. + element._store = {}; + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: true // This element has already been validated on the server. + + }); + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: null + }); + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: null + }); + } + + return element; +} + +function createLazyChunkWrapper(chunk) { + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: chunk, + _init: readChunk + }; + return lazyType; +} + +function getChunk(response, id) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunk = createPendingChunk(response); + chunks.set(id, chunk); + } + + return chunk; +} + +function createModelResolver(chunk, parentObject, key) { + var blocked; + + if (initializingChunkBlockedModel) { + blocked = initializingChunkBlockedModel; + blocked.deps++; + } else { + blocked = initializingChunkBlockedModel = { + deps: 1, + value: null + }; + } + + return function (value) { + parentObject[key] = value; + blocked.deps--; + + if (blocked.deps === 0) { + if (chunk.status !== BLOCKED) { + return; + } + + var resolveListeners = chunk.value; + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = blocked.value; + + if (resolveListeners !== null) { + wakeChunk(resolveListeners, blocked.value); + } + } + }; +} + +function createModelReject(chunk) { + return function (error) { + return triggerErrorOnChunk(chunk, error); + }; +} + +function createServerReferenceProxy(response, metaData) { + var callServer = response._callServer; + + var proxy = function () { + // $FlowFixMe[method-unbinding] + var args = Array.prototype.slice.call(arguments); + var p = metaData.bound; + + if (!p) { + return callServer(metaData.id, args); + } + + if (p.status === INITIALIZED) { + var bound = p.value; + return callServer(metaData.id, bound.concat(args)); + } // Since this is a fake Promise whose .then doesn't chain, we have to wrap it. + // TODO: Remove the wrapper once that's fixed. + + + return Promise.resolve(p).then(function (bound) { + return callServer(metaData.id, bound.concat(args)); + }); + }; + + registerServerReference(proxy, metaData); + return proxy; +} + +function getOutlinedModel(response, id) { + var chunk = getChunk(response, id); + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + { + return chunk.value; + } + // We always encode it first in the stream so it won't be pending. + + default: + throw chunk.reason; + } +} + +function parseModelString(response, parentObject, key, value) { + if (value[0] === '$') { + if (value === '$') { + // A very common symbol. + return REACT_ELEMENT_TYPE; + } + + switch (value[1]) { + case '$': + { + // This was an escaped string value. + return value.slice(1); + } + + case 'L': + { + // Lazy node + var id = parseInt(value.slice(2), 16); + var chunk = getChunk(response, id); // We create a React.lazy wrapper around any lazy values. + // When passed into React, we'll know how to suspend on this. + + return createLazyChunkWrapper(chunk); + } + + case '@': + { + // Promise + var _id = parseInt(value.slice(2), 16); + + var _chunk = getChunk(response, _id); + + return _chunk; + } + + case 'S': + { + // Symbol + return Symbol.for(value.slice(2)); + } + + case 'P': + { + // Server Context Provider + return getOrCreateServerContext(value.slice(2)).Provider; + } + + case 'F': + { + // Server Reference + var _id2 = parseInt(value.slice(2), 16); + + var metadata = getOutlinedModel(response, _id2); + return createServerReferenceProxy(response, metadata); + } + + case 'Q': + { + // Map + var _id3 = parseInt(value.slice(2), 16); + + var data = getOutlinedModel(response, _id3); + return new Map(data); + } + + case 'W': + { + // Set + var _id4 = parseInt(value.slice(2), 16); + + var _data = getOutlinedModel(response, _id4); + + return new Set(_data); + } + + case 'I': + { + // $Infinity + return Infinity; + } + + case '-': + { + // $-0 or $-Infinity + if (value === '$-0') { + return -0; + } else { + return -Infinity; + } + } + + case 'N': + { + // $NaN + return NaN; + } + + case 'u': + { + // matches "$undefined" + // Special encoding for `undefined` which can't be serialized as JSON otherwise. + return undefined; + } + + case 'D': + { + // Date + return new Date(Date.parse(value.slice(2))); + } + + case 'n': + { + // BigInt + return BigInt(value.slice(2)); + } + + default: + { + // We assume that anything else is a reference ID. + var _id5 = parseInt(value.slice(1), 16); + + var _chunk2 = getChunk(response, _id5); + + switch (_chunk2.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk2); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(_chunk2); + break; + } // The status might have changed after initialization. + + + switch (_chunk2.status) { + case INITIALIZED: + return _chunk2.value; + + case PENDING: + case BLOCKED: + var parentChunk = initializingChunk; + + _chunk2.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); + + return null; + + default: + throw _chunk2.reason; + } + } + } + } + + return value; +} + +function parseModelTuple(response, value) { + var tuple = value; + + if (tuple[0] === REACT_ELEMENT_TYPE) { + // TODO: Consider having React just directly accept these arrays as elements. + // Or even change the ReactElement type to be an array. + return createElement(tuple[1], tuple[2], tuple[3]); + } + + return value; +} + +function missingCall() { + throw new Error('Trying to call a function from "use server" but the callServer option ' + 'was not implemented in your router runtime.'); +} + +function createResponse(bundlerConfig, moduleLoading, callServer, nonce) { + var chunks = new Map(); + var response = { + _bundlerConfig: bundlerConfig, + _moduleLoading: moduleLoading, + _callServer: callServer !== undefined ? callServer : missingCall, + _nonce: nonce, + _chunks: chunks, + _stringDecoder: createStringDecoder(), + _fromJSON: null, + _rowState: 0, + _rowID: 0, + _rowTag: 0, + _rowLength: 0, + _buffer: [] + }; // Don't inline this call because it causes closure to outline the call above. + + response._fromJSON = createFromJSONCallback(response); + return response; +} + +function resolveModel(response, id, model) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createResolvedModelChunk(response, model)); + } else { + resolveModelChunk(chunk, model); + } +} + +function resolveText(response, id, text) { + var chunks = response._chunks; // We assume that we always reference large strings after they've been + // emitted. + + chunks.set(id, createInitializedTextChunk(response, text)); +} + +function resolveBuffer(response, id, buffer) { + var chunks = response._chunks; // We assume that we always reference buffers after they've been emitted. + + chunks.set(id, createInitializedBufferChunk(response, buffer)); +} + +function resolveModule(response, id, model) { + var chunks = response._chunks; + var chunk = chunks.get(id); + var clientReferenceMetadata = parseModel(response, model); + var clientReference = resolveClientReference(response._bundlerConfig, clientReferenceMetadata); + prepareDestinationForModule(response._moduleLoading, response._nonce, clientReferenceMetadata); // TODO: Add an option to encode modules that are lazy loaded. + // For now we preload all modules as early as possible since it's likely + // that we'll need them. + + var promise = preloadModule(clientReference); + + if (promise) { + var blockedChunk; + + if (!chunk) { + // Technically, we should just treat promise as the chunk in this + // case. Because it'll just behave as any other promise. + blockedChunk = createBlockedChunk(response); + chunks.set(id, blockedChunk); + } else { + // This can't actually happen because we don't have any forward + // references to modules. + blockedChunk = chunk; + blockedChunk.status = BLOCKED; + } + + promise.then(function () { + return resolveModuleChunk(blockedChunk, clientReference); + }, function (error) { + return triggerErrorOnChunk(blockedChunk, error); + }); + } else { + if (!chunk) { + chunks.set(id, createResolvedModuleChunk(response, clientReference)); + } else { + // This can't actually happen because we don't have any forward + // references to modules. + resolveModuleChunk(chunk, clientReference); + } + } +} + +function resolveErrorDev(response, id, digest, message, stack) { + + + var error = new Error(message || 'An error occurred in the Server Components render but no message was provided'); + error.stack = stack; + error.digest = digest; + var errorWithDigest = error; + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createErrorChunk(response, errorWithDigest)); + } else { + triggerErrorOnChunk(chunk, errorWithDigest); + } +} + +function resolvePostponeDev(response, id, reason, stack) { + + + var error = new Error(reason || ''); + var postponeInstance = error; + postponeInstance.$$typeof = REACT_POSTPONE_TYPE; + postponeInstance.stack = stack; + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createErrorChunk(response, postponeInstance)); + } else { + triggerErrorOnChunk(chunk, postponeInstance); + } +} + +function resolveHint(response, code, model) { + var hintModel = parseModel(response, model); + dispatchHint(code, hintModel); +} + +function mergeBuffer(buffer, lastChunk) { + var l = buffer.length; // Count the bytes we'll need + + var byteLength = lastChunk.length; + + for (var i = 0; i < l; i++) { + byteLength += buffer[i].byteLength; + } // Allocate enough contiguous space + + + var result = new Uint8Array(byteLength); + var offset = 0; // Copy all the buffers into it. + + for (var _i = 0; _i < l; _i++) { + var chunk = buffer[_i]; + result.set(chunk, offset); + offset += chunk.byteLength; + } + + result.set(lastChunk, offset); + return result; +} + +function resolveTypedArray(response, id, buffer, lastChunk, constructor, bytesPerElement) { + // If the view fits into one original buffer, we just reuse that buffer instead of + // copying it out to a separate copy. This means that it's not always possible to + // transfer these values to other threads without copying first since they may + // share array buffer. For this to work, it must also have bytes aligned to a + // multiple of a size of the type. + var chunk = buffer.length === 0 && lastChunk.byteOffset % bytesPerElement === 0 ? lastChunk : mergeBuffer(buffer, lastChunk); // TODO: The transfer protocol of RSC is little-endian. If the client isn't little-endian + // we should convert it instead. In practice big endian isn't really Web compatible so it's + // somewhat safe to assume that browsers aren't going to run it, but maybe there's some SSR + // server that's affected. + + var view = new constructor(chunk.buffer, chunk.byteOffset, chunk.byteLength / bytesPerElement); + resolveBuffer(response, id, view); +} + +function processFullRow(response, id, tag, buffer, chunk) { + { + switch (tag) { + case 65 + /* "A" */ + : + // We must always clone to extract it into a separate buffer instead of just a view. + resolveBuffer(response, id, mergeBuffer(buffer, chunk).buffer); + return; + + case 67 + /* "C" */ + : + resolveTypedArray(response, id, buffer, chunk, Int8Array, 1); + return; + + case 99 + /* "c" */ + : + resolveBuffer(response, id, buffer.length === 0 ? chunk : mergeBuffer(buffer, chunk)); + return; + + case 85 + /* "U" */ + : + resolveTypedArray(response, id, buffer, chunk, Uint8ClampedArray, 1); + return; + + case 83 + /* "S" */ + : + resolveTypedArray(response, id, buffer, chunk, Int16Array, 2); + return; + + case 115 + /* "s" */ + : + resolveTypedArray(response, id, buffer, chunk, Uint16Array, 2); + return; + + case 76 + /* "L" */ + : + resolveTypedArray(response, id, buffer, chunk, Int32Array, 4); + return; + + case 108 + /* "l" */ + : + resolveTypedArray(response, id, buffer, chunk, Uint32Array, 4); + return; + + case 70 + /* "F" */ + : + resolveTypedArray(response, id, buffer, chunk, Float32Array, 4); + return; + + case 68 + /* "D" */ + : + resolveTypedArray(response, id, buffer, chunk, Float64Array, 8); + return; + + case 78 + /* "N" */ + : + resolveTypedArray(response, id, buffer, chunk, BigInt64Array, 8); + return; + + case 109 + /* "m" */ + : + resolveTypedArray(response, id, buffer, chunk, BigUint64Array, 8); + return; + + case 86 + /* "V" */ + : + resolveTypedArray(response, id, buffer, chunk, DataView, 1); + return; + } + } + + var stringDecoder = response._stringDecoder; + var row = ''; + + for (var i = 0; i < buffer.length; i++) { + row += readPartialStringChunk(stringDecoder, buffer[i]); + } + + row += readFinalStringChunk(stringDecoder, chunk); + + switch (tag) { + case 73 + /* "I" */ + : + { + resolveModule(response, id, row); + return; + } + + case 72 + /* "H" */ + : + { + var code = row[0]; + resolveHint(response, code, row.slice(1)); + return; + } + + case 69 + /* "E" */ + : + { + var errorInfo = JSON.parse(row); + + { + resolveErrorDev(response, id, errorInfo.digest, errorInfo.message, errorInfo.stack); + } + + return; + } + + case 84 + /* "T" */ + : + { + resolveText(response, id, row); + return; + } + + case 80 + /* "P" */ + : + { + { + { + var postponeInfo = JSON.parse(row); + resolvePostponeDev(response, id, postponeInfo.reason, postponeInfo.stack); + } + + return; + } + } + // Fallthrough + + default: + /* """ "{" "[" "t" "f" "n" "0" - "9" */ + { + // We assume anything else is JSON. + resolveModel(response, id, row); + return; + } + } +} + +function processBinaryChunk(response, chunk) { + var i = 0; + var rowState = response._rowState; + var rowID = response._rowID; + var rowTag = response._rowTag; + var rowLength = response._rowLength; + var buffer = response._buffer; + var chunkLength = chunk.length; + + while (i < chunkLength) { + var lastIdx = -1; + + switch (rowState) { + case ROW_ID: + { + var byte = chunk[i++]; + + if (byte === 58 + /* ":" */ + ) { + // Finished the rowID, next we'll parse the tag. + rowState = ROW_TAG; + } else { + rowID = rowID << 4 | (byte > 96 ? byte - 87 : byte - 48); + } + + continue; + } + + case ROW_TAG: + { + var resolvedRowTag = chunk[i]; + + if (resolvedRowTag === 84 + /* "T" */ + || (resolvedRowTag === 65 + /* "A" */ + || resolvedRowTag === 67 + /* "C" */ + || resolvedRowTag === 99 + /* "c" */ + || resolvedRowTag === 85 + /* "U" */ + || resolvedRowTag === 83 + /* "S" */ + || resolvedRowTag === 115 + /* "s" */ + || resolvedRowTag === 76 + /* "L" */ + || resolvedRowTag === 108 + /* "l" */ + || resolvedRowTag === 70 + /* "F" */ + || resolvedRowTag === 68 + /* "D" */ + || resolvedRowTag === 78 + /* "N" */ + || resolvedRowTag === 109 + /* "m" */ + || resolvedRowTag === 86) + /* "V" */ + ) { + rowTag = resolvedRowTag; + rowState = ROW_LENGTH; + i++; + } else if (resolvedRowTag > 64 && resolvedRowTag < 91 + /* "A"-"Z" */ + ) { + rowTag = resolvedRowTag; + rowState = ROW_CHUNK_BY_NEWLINE; + i++; + } else { + rowTag = 0; + rowState = ROW_CHUNK_BY_NEWLINE; // This was an unknown tag so it was probably part of the data. + } + + continue; + } + + case ROW_LENGTH: + { + var _byte = chunk[i++]; + + if (_byte === 44 + /* "," */ + ) { + // Finished the rowLength, next we'll buffer up to that length. + rowState = ROW_CHUNK_BY_LENGTH; + } else { + rowLength = rowLength << 4 | (_byte > 96 ? _byte - 87 : _byte - 48); + } + + continue; + } + + case ROW_CHUNK_BY_NEWLINE: + { + // We're looking for a newline + lastIdx = chunk.indexOf(10 + /* "\n" */ + , i); + break; + } + + case ROW_CHUNK_BY_LENGTH: + { + // We're looking for the remaining byte length + lastIdx = i + rowLength; + + if (lastIdx > chunk.length) { + lastIdx = -1; + } + + break; + } + } + + var offset = chunk.byteOffset + i; + + if (lastIdx > -1) { + // We found the last chunk of the row + var length = lastIdx - i; + var lastChunk = new Uint8Array(chunk.buffer, offset, length); + processFullRow(response, rowID, rowTag, buffer, lastChunk); // Reset state machine for a new row + + i = lastIdx; + + if (rowState === ROW_CHUNK_BY_NEWLINE) { + // If we're trailing by a newline we need to skip it. + i++; + } + + rowState = ROW_ID; + rowTag = 0; + rowID = 0; + rowLength = 0; + buffer.length = 0; + } else { + // The rest of this row is in a future chunk. We stash the rest of the + // current chunk until we can process the full row. + var _length = chunk.byteLength - i; + + var remainingSlice = new Uint8Array(chunk.buffer, offset, _length); + buffer.push(remainingSlice); // Update how many bytes we're still waiting for. If we're looking for + // a newline, this doesn't hurt since we'll just ignore it. + + rowLength -= remainingSlice.byteLength; + break; + } + } + + response._rowState = rowState; + response._rowID = rowID; + response._rowTag = rowTag; + response._rowLength = rowLength; +} + +function parseModel(response, json) { + return JSON.parse(json, response._fromJSON); +} + +function createFromJSONCallback(response) { + // $FlowFixMe[missing-this-annot] + return function (key, value) { + if (typeof value === 'string') { + // We can't use .bind here because we need the "this" value. + return parseModelString(response, this, key, value); + } + + if (typeof value === 'object' && value !== null) { + return parseModelTuple(response, value); + } + + return value; + }; +} + +function close(response) { + // In case there are any remaining unresolved chunks, they won't + // be resolved now. So we need to issue an error to those. + // Ideally we should be able to early bail out if we kept a + // ref count of pending chunks. + reportGlobalError(response, new Error('Connection closed.')); +} + +function noServerCall() { + throw new Error('Server Functions cannot be called during initial render. ' + 'This would create a fetch waterfall. Try to use a Server Component ' + 'to pass data to Client Components instead.'); +} + +function createServerReference(id, callServer) { + return createServerReference$1(id, noServerCall); +} + +function createResponseFromOptions(options) { + return createResponse(options.ssrManifest.moduleMap, options.ssrManifest.moduleLoading, noServerCall, typeof options.nonce === 'string' ? options.nonce : undefined); +} + +function startReadingFromStream(response, stream) { + var reader = stream.getReader(); + + function progress(_ref) { + var done = _ref.done, + value = _ref.value; + + if (done) { + close(response); + return; + } + + var buffer = value; + processBinaryChunk(response, buffer); + return reader.read().then(progress).catch(error); + } + + function error(e) { + reportGlobalError(response, e); + } + + reader.read().then(progress).catch(error); +} + +function createFromReadableStream(stream, options) { + var response = createResponseFromOptions(options); + startReadingFromStream(response, stream); + return getRoot(response); +} + +function createFromFetch(promiseForResponse, options) { + var response = createResponseFromOptions(options); + promiseForResponse.then(function (r) { + startReadingFromStream(response, r.body); + }, function (e) { + reportGlobalError(response, e); + }); + return getRoot(response); +} + +exports.createFromFetch = createFromFetch; +exports.createFromReadableStream = createFromReadableStream; +exports.createServerReference = createServerReference; + })(); +} diff --git a/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-client.edge.production.min.js b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-client.edge.production.min.js new file mode 100644 index 0000000000000..dfe8a18c4e981 --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-client.edge.production.min.js @@ -0,0 +1,44 @@ +/** + * @license React + * react-server-dom-turbopack-client.edge.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var p=require("react-dom"),q=require("react"),r={stream:!0};function u(a,b){if(a){var c=a[b[0]];if(a=c[b[2]])c=a.name;else{a=c["*"];if(!a)throw Error('Could not find the module "'+b[0]+'" in the React SSR Manifest. This is probably a bug in the React Server Components bundler.');c=b[2]}return 4===b.length?[a.id,a.chunks,c,1]:[a.id,a.chunks,c]}return b}var v=new Map; +function x(a){var b=globalThis.__next_require__(a);if("function"!==typeof b.then||"fulfilled"===b.status)return null;b.then(function(c){b.status="fulfilled";b.value=c},function(c){b.status="rejected";b.reason=c});return b}function y(){} +function aa(a){for(var b=a[1],c=[],d=0;dk?(h=k,k=3,l++):(h=0,k=3);continue;case 2:m=f[l++];44===m?k=4:n=n<<4|(96f.length&&(m=-1)}var t=f.byteOffset+l;if(-1 0) { + return Promise.all(promises); + } else { + return null; + } +} // Actually require the module or suspend if it's not yet ready. +// Increase priority if necessary. + +function requireModule(metadata) { + var moduleExports = globalThis.__next_require__(metadata[ID]); + + if (isAsyncImport(metadata)) { + if (typeof moduleExports.then !== 'function') ; else if (moduleExports.status === 'fulfilled') { + // This Promise should've been instrumented by preloadModule. + moduleExports = moduleExports.value; + } else { + throw moduleExports.reason; + } + } + + if (metadata[NAME] === '*') { + // This is a placeholder value that represents that the caller imported this + // as a CommonJS module as is. + return moduleExports; + } + + if (metadata[NAME] === '') { + // This is a placeholder value that represents that the caller accessed the + // default property of this if it was an ESM interop module. + return moduleExports.__esModule ? moduleExports.default : moduleExports; + } + + return moduleExports[metadata[NAME]]; +} + +function loadChunk(filename) { + return globalThis.__next_chunk_load__(filename); +} + +function prepareDestinationWithChunks(moduleLoading, // Chunks are single-indexed filenames +chunks, nonce) { + if (moduleLoading !== null) { + for (var i = 0; i < chunks.length; i++) { + preinitScriptForSSR(moduleLoading.prefix + chunks[i], nonce, moduleLoading.crossOrigin); + } + } +} + +var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +function getCrossOriginString(input) { + if (typeof input === 'string') { + return input === 'use-credentials' ? input : ''; + } + + return undefined; +} + +// This client file is in the shared folder because it applies to both SSR and browser contexts. +var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher; +function dispatchHint(code, model) { + var dispatcher = ReactDOMCurrentDispatcher.current; + + if (dispatcher) { + switch (code) { + case 'D': + { + var refined = refineModel(code, model); + var href = refined; + dispatcher.prefetchDNS(href); + return; + } + + case 'C': + { + var _refined = refineModel(code, model); + + if (typeof _refined === 'string') { + var _href = _refined; + dispatcher.preconnect(_href); + } else { + var _href2 = _refined[0]; + var crossOrigin = _refined[1]; + dispatcher.preconnect(_href2, crossOrigin); + } + + return; + } + + case 'L': + { + var _refined2 = refineModel(code, model); + + var _href3 = _refined2[0]; + var as = _refined2[1]; + + if (_refined2.length === 3) { + var options = _refined2[2]; + dispatcher.preload(_href3, as, options); + } else { + dispatcher.preload(_href3, as); + } + + return; + } + + case 'm': + { + var _refined3 = refineModel(code, model); + + if (typeof _refined3 === 'string') { + var _href4 = _refined3; + dispatcher.preloadModule(_href4); + } else { + var _href5 = _refined3[0]; + var _options = _refined3[1]; + dispatcher.preloadModule(_href5, _options); + } + + return; + } + + case 'S': + { + var _refined4 = refineModel(code, model); + + if (typeof _refined4 === 'string') { + var _href6 = _refined4; + dispatcher.preinitStyle(_href6); + } else { + var _href7 = _refined4[0]; + var precedence = _refined4[1] === 0 ? undefined : _refined4[1]; + + var _options2 = _refined4.length === 3 ? _refined4[2] : undefined; + + dispatcher.preinitStyle(_href7, precedence, _options2); + } + + return; + } + + case 'X': + { + var _refined5 = refineModel(code, model); + + if (typeof _refined5 === 'string') { + var _href8 = _refined5; + dispatcher.preinitScript(_href8); + } else { + var _href9 = _refined5[0]; + var _options3 = _refined5[1]; + dispatcher.preinitScript(_href9, _options3); + } + + return; + } + + case 'M': + { + var _refined6 = refineModel(code, model); + + if (typeof _refined6 === 'string') { + var _href10 = _refined6; + dispatcher.preinitModuleScript(_href10); + } else { + var _href11 = _refined6[0]; + var _options4 = _refined6[1]; + dispatcher.preinitModuleScript(_href11, _options4); + } + + return; + } + } + } +} // Flow is having troulbe refining the HintModels so we help it a bit. +// This should be compiled out in the production build. + +function refineModel(code, model) { + return model; +} +function preinitScriptForSSR(href, nonce, crossOrigin) { + var dispatcher = ReactDOMCurrentDispatcher.current; + + if (dispatcher) { + dispatcher.preinitScript(href, { + crossOrigin: getCrossOriginString(crossOrigin), + nonce: nonce + }); + } +} + +var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); +var REACT_POSTPONE_TYPE = Symbol.for('react.postpone'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +// in case they error. + +var jsxPropsParents = new WeakMap(); +var jsxChildrenParents = new WeakMap(); + +function isObjectPrototype(object) { + if (!object) { + return false; + } + + var ObjectPrototype = Object.prototype; + + if (object === ObjectPrototype) { + return true; + } // It might be an object from a different Realm which is + // still just a plain simple object. + + + if (Object.getPrototypeOf(object)) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + if (!(names[i] in ObjectPrototype)) { + return false; + } + } + + return true; +} + +function isSimpleObject(object) { + if (!isObjectPrototype(Object.getPrototypeOf(object))) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + var descriptor = Object.getOwnPropertyDescriptor(object, names[i]); + + if (!descriptor) { + return false; + } + + if (!descriptor.enumerable) { + if ((names[i] === 'key' || names[i] === 'ref') && typeof descriptor.get === 'function') { + // React adds key and ref getters to props objects to issue warnings. + // Those getters will not be transferred to the client, but that's ok, + // so we'll special case them. + continue; + } + + return false; + } + } + + return true; +} +function objectName(object) { + // $FlowFixMe[method-unbinding] + var name = Object.prototype.toString.call(object); + return name.replace(/^\[object (.*)\]$/, function (m, p0) { + return p0; + }); +} + +function describeKeyForErrorMessage(key) { + var encodedKey = JSON.stringify(key); + return '"' + key + '"' === encodedKey ? key : encodedKey; +} + +function describeValueForErrorMessage(value) { + switch (typeof value) { + case 'string': + { + return JSON.stringify(value.length <= 10 ? value : value.slice(0, 10) + '...'); + } + + case 'object': + { + if (isArray(value)) { + return '[...]'; + } + + var name = objectName(value); + + if (name === 'Object') { + return '{...}'; + } + + return name; + } + + case 'function': + return 'function'; + + default: + // eslint-disable-next-line react-internal/safe-string-coercion + return String(value); + } +} + +function describeElementType(type) { + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeElementType(type.render); + + case REACT_MEMO_TYPE: + return describeElementType(type.type); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeElementType(init(payload)); + } catch (x) {} + } + } + } + + return ''; +} + +function describeObjectForErrorMessage(objectOrArray, expandedName) { + var objKind = objectName(objectOrArray); + + if (objKind !== 'Object' && objKind !== 'Array') { + return objKind; + } + + var str = ''; + var start = -1; + var length = 0; + + if (isArray(objectOrArray)) { + if (jsxChildrenParents.has(objectOrArray)) { + // Print JSX Children + var type = jsxChildrenParents.get(objectOrArray); + str = '<' + describeElementType(type) + '>'; + var array = objectOrArray; + + for (var i = 0; i < array.length; i++) { + var value = array[i]; + var substr = void 0; + + if (typeof value === 'string') { + substr = value; + } else if (typeof value === 'object' && value !== null) { + substr = '{' + describeObjectForErrorMessage(value) + '}'; + } else { + substr = '{' + describeValueForErrorMessage(value) + '}'; + } + + if ('' + i === expandedName) { + start = str.length; + length = substr.length; + str += substr; + } else if (substr.length < 15 && str.length + substr.length < 40) { + str += substr; + } else { + str += '{...}'; + } + } + + str += ''; + } else { + // Print Array + str = '['; + var _array = objectOrArray; + + for (var _i = 0; _i < _array.length; _i++) { + if (_i > 0) { + str += ', '; + } + + var _value = _array[_i]; + + var _substr = void 0; + + if (typeof _value === 'object' && _value !== null) { + _substr = describeObjectForErrorMessage(_value); + } else { + _substr = describeValueForErrorMessage(_value); + } + + if ('' + _i === expandedName) { + start = str.length; + length = _substr.length; + str += _substr; + } else if (_substr.length < 10 && str.length + _substr.length < 40) { + str += _substr; + } else { + str += '...'; + } + } + + str += ']'; + } + } else { + if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) { + str = '<' + describeElementType(objectOrArray.type) + '/>'; + } else if (jsxPropsParents.has(objectOrArray)) { + // Print JSX + var _type = jsxPropsParents.get(objectOrArray); + + str = '<' + (describeElementType(_type) || '...'); + var object = objectOrArray; + var names = Object.keys(object); + + for (var _i2 = 0; _i2 < names.length; _i2++) { + str += ' '; + var name = names[_i2]; + str += describeKeyForErrorMessage(name) + '='; + var _value2 = object[name]; + + var _substr2 = void 0; + + if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) { + _substr2 = describeObjectForErrorMessage(_value2); + } else { + _substr2 = describeValueForErrorMessage(_value2); + } + + if (typeof _value2 !== 'string') { + _substr2 = '{' + _substr2 + '}'; + } + + if (name === expandedName) { + start = str.length; + length = _substr2.length; + str += _substr2; + } else if (_substr2.length < 10 && str.length + _substr2.length < 40) { + str += _substr2; + } else { + str += '...'; + } + } + + str += '>'; + } else { + // Print Object + str = '{'; + var _object = objectOrArray; + + var _names = Object.keys(_object); + + for (var _i3 = 0; _i3 < _names.length; _i3++) { + if (_i3 > 0) { + str += ', '; + } + + var _name = _names[_i3]; + str += describeKeyForErrorMessage(_name) + ': '; + var _value3 = _object[_name]; + + var _substr3 = void 0; + + if (typeof _value3 === 'object' && _value3 !== null) { + _substr3 = describeObjectForErrorMessage(_value3); + } else { + _substr3 = describeValueForErrorMessage(_value3); + } + + if (_name === expandedName) { + start = str.length; + length = _substr3.length; + str += _substr3; + } else if (_substr3.length < 10 && str.length + _substr3.length < 40) { + str += _substr3; + } else { + str += '...'; + } + } + + str += '}'; + } + } + + if (expandedName === undefined) { + return str; + } + + if (start > -1 && length > 0) { + var highlight = ' '.repeat(start) + '^'.repeat(length); + return '\n ' + str + '\n ' + highlight; + } + + return '\n ' + str; +} + +var knownServerReferences = new WeakMap(); // Serializable values +// Thenable +// function serializeByValueID(id: number): string { +// return '$' + id.toString(16); +// } + +function serializePromiseID(id) { + return '$@' + id.toString(16); +} + +function serializeServerReferenceID(id) { + return '$F' + id.toString(16); +} + +function serializeSymbolReference(name) { + return '$S' + name; +} + +function serializeFormDataReference(id) { + // Why K? F is "Function". D is "Date". What else? + return '$K' + id.toString(16); +} + +function serializeNumber(number) { + if (Number.isFinite(number)) { + if (number === 0 && 1 / number === -Infinity) { + return '$-0'; + } else { + return number; + } + } else { + if (number === Infinity) { + return '$Infinity'; + } else if (number === -Infinity) { + return '$-Infinity'; + } else { + return '$NaN'; + } + } +} + +function serializeUndefined() { + return '$undefined'; +} + +function serializeDateFromDateJSON(dateJSON) { + // JSON.stringify automatically calls Date.prototype.toJSON which calls toISOString. + // We need only tack on a $D prefix. + return '$D' + dateJSON; +} + +function serializeBigInt(n) { + return '$n' + n.toString(10); +} + +function serializeMapID(id) { + return '$Q' + id.toString(16); +} + +function serializeSetID(id) { + return '$W' + id.toString(16); +} + +function escapeStringValue(value) { + if (value[0] === '$') { + // We need to escape $ prefixed strings since we use those to encode + // references to IDs and as special symbol values. + return '$' + value; + } else { + return value; + } +} + +function processReply(root, formFieldPrefix, resolve, reject) { + var nextPartId = 1; + var pendingParts = 0; + var formData = null; + + function resolveToJSON(key, value) { + var parent = this; // Make sure that `parent[key]` wasn't JSONified before `value` was passed to us + + { + // $FlowFixMe[incompatible-use] + var originalValue = parent[key]; + + if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) { + if (objectName(originalValue) !== 'Object') { + error('Only plain objects can be passed to Server Functions from the Client. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } else { + error('Only plain objects can be passed to Server Functions from the Client. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props.%s', describeObjectForErrorMessage(parent, key)); + } + } + } + + if (value === null) { + return null; + } + + if (typeof value === 'object') { + // $FlowFixMe[method-unbinding] + if (typeof value.then === 'function') { + // We assume that any object with a .then property is a "Thenable" type, + // or a Promise type. Either of which can be represented by a Promise. + if (formData === null) { + // Upgrade to use FormData to allow us to stream this value. + formData = new FormData(); + } + + pendingParts++; + var promiseId = nextPartId++; + var thenable = value; + thenable.then(function (partValue) { + var partJSON = JSON.stringify(partValue, resolveToJSON); // $FlowFixMe[incompatible-type] We know it's not null because we assigned it above. + + var data = formData; // eslint-disable-next-line react-internal/safe-string-coercion + + data.append(formFieldPrefix + promiseId, partJSON); + pendingParts--; + + if (pendingParts === 0) { + resolve(data); + } + }, function (reason) { + // In the future we could consider serializing this as an error + // that throws on the server instead. + reject(reason); + }); + return serializePromiseID(promiseId); + } // TODO: Should we the Object.prototype.toString.call() to test for cross-realm objects? + + + if (value instanceof FormData) { + if (formData === null) { + // Upgrade to use FormData to allow us to use rich objects as its values. + formData = new FormData(); + } + + var data = formData; + var refId = nextPartId++; // Copy all the form fields with a prefix for this reference. + // These must come first in the form order because we assume that all the + // fields are available before this is referenced. + + var prefix = formFieldPrefix + refId + '_'; // $FlowFixMe[prop-missing]: FormData has forEach. + + value.forEach(function (originalValue, originalKey) { + data.append(prefix + originalKey, originalValue); + }); + return serializeFormDataReference(refId); + } + + if (value instanceof Map) { + var partJSON = JSON.stringify(Array.from(value), resolveToJSON); + + if (formData === null) { + formData = new FormData(); + } + + var mapId = nextPartId++; + formData.append(formFieldPrefix + mapId, partJSON); + return serializeMapID(mapId); + } + + if (value instanceof Set) { + var _partJSON = JSON.stringify(Array.from(value), resolveToJSON); + + if (formData === null) { + formData = new FormData(); + } + + var setId = nextPartId++; + formData.append(formFieldPrefix + setId, _partJSON); + return serializeSetID(setId); + } + + if (!isArray(value)) { + var iteratorFn = getIteratorFn(value); + + if (iteratorFn) { + return Array.from(value); + } + } + + { + if (value !== null && !isArray(value)) { + // Verify that this is a simple plain object. + if (value.$$typeof === REACT_ELEMENT_TYPE) { + error('React Element cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key)); + } else if (value.$$typeof === REACT_LAZY_TYPE) { + error('React Lazy cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key)); + } else if (value.$$typeof === REACT_PROVIDER_TYPE) { + error('React Context Providers cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key)); + } else if (objectName(value) !== 'Object') { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, key)); + } else if (!isSimpleObject(value)) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Classes or other objects with methods are not supported.%s', describeObjectForErrorMessage(parent, key)); + } else if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(value); + + if (symbols.length > 0) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with symbol properties like %s are not supported.%s', symbols[0].description, describeObjectForErrorMessage(parent, key)); + } + } + } + } // $FlowFixMe[incompatible-return] + + + return value; + } + + if (typeof value === 'string') { + // TODO: Maybe too clever. If we support URL there's no similar trick. + if (value[value.length - 1] === 'Z') { + // Possibly a Date, whose toJSON automatically calls toISOString + // $FlowFixMe[incompatible-use] + var _originalValue = parent[key]; + + if (_originalValue instanceof Date) { + return serializeDateFromDateJSON(value); + } + } + + return escapeStringValue(value); + } + + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return serializeNumber(value); + } + + if (typeof value === 'undefined') { + return serializeUndefined(); + } + + if (typeof value === 'function') { + var metaData = knownServerReferences.get(value); + + if (metaData !== undefined) { + var metaDataJSON = JSON.stringify(metaData, resolveToJSON); + + if (formData === null) { + // Upgrade to use FormData to allow us to stream this value. + formData = new FormData(); + } // The reference to this function came from the same client so we can pass it back. + + + var _refId = nextPartId++; // eslint-disable-next-line react-internal/safe-string-coercion + + + formData.set(formFieldPrefix + _refId, metaDataJSON); + return serializeServerReferenceID(_refId); + } + + throw new Error('Client Functions cannot be passed directly to Server Functions. ' + 'Only Functions passed from the Server can be passed back again.'); + } + + if (typeof value === 'symbol') { + // $FlowFixMe[incompatible-type] `description` might be undefined + var name = value.description; + + if (Symbol.for(name) !== value) { + throw new Error('Only global symbols received from Symbol.for(...) can be passed to Server Functions. ' + ("The symbol Symbol.for(" + // $FlowFixMe[incompatible-type] `description` might be undefined + value.description + ") cannot be found among global symbols.")); + } + + return serializeSymbolReference(name); + } + + if (typeof value === 'bigint') { + return serializeBigInt(value); + } + + throw new Error("Type " + typeof value + " is not supported as an argument to a Server Function."); + } // $FlowFixMe[incompatible-type] it's not going to be undefined because we'll encode it. + + + var json = JSON.stringify(root, resolveToJSON); + + if (formData === null) { + // If it's a simple data structure, we just use plain JSON. + resolve(json); + } else { + // Otherwise, we use FormData to let us stream in the result. + formData.set(formFieldPrefix + '0', json); + + if (pendingParts === 0) { + // $FlowFixMe[incompatible-call] this has already been refined. + resolve(formData); + } + } +} +var boundCache = new WeakMap(); + +function encodeFormData(reference) { + var resolve, reject; // We need to have a handle on the thenable so that we can synchronously set + // its status from processReply, when it can complete synchronously. + + var thenable = new Promise(function (res, rej) { + resolve = res; + reject = rej; + }); + processReply(reference, '', function (body) { + if (typeof body === 'string') { + var data = new FormData(); + data.append('0', body); + body = data; + } + + var fulfilled = thenable; + fulfilled.status = 'fulfilled'; + fulfilled.value = body; + resolve(body); + }, function (e) { + var rejected = thenable; + rejected.status = 'rejected'; + rejected.reason = e; + reject(e); + }); + return thenable; +} + +function encodeFormAction(identifierPrefix) { + var reference = knownServerReferences.get(this); + + if (!reference) { + throw new Error('Tried to encode a Server Action from a different instance than the encoder is from. ' + 'This is a bug in React.'); + } + + var data = null; + var name; + var boundPromise = reference.bound; + + if (boundPromise !== null) { + var thenable = boundCache.get(reference); + + if (!thenable) { + thenable = encodeFormData(reference); + boundCache.set(reference, thenable); + } + + if (thenable.status === 'rejected') { + throw thenable.reason; + } else if (thenable.status !== 'fulfilled') { + throw thenable; + } + + var encodedFormData = thenable.value; // This is hacky but we need the identifier prefix to be added to + // all fields but the suspense cache would break since we might get + // a new identifier each time. So we just append it at the end instead. + + var prefixedData = new FormData(); // $FlowFixMe[prop-missing] + + encodedFormData.forEach(function (value, key) { + prefixedData.append('$ACTION_' + identifierPrefix + ':' + key, value); + }); + data = prefixedData; // We encode the name of the prefix containing the data. + + name = '$ACTION_REF_' + identifierPrefix; + } else { + // This is the simple case so we can just encode the ID. + name = '$ACTION_ID_' + reference.id; + } + + return { + name: name, + method: 'POST', + encType: 'multipart/form-data', + data: data + }; +} + +function isSignatureEqual(referenceId, numberOfBoundArgs) { + var reference = knownServerReferences.get(this); + + if (!reference) { + throw new Error('Tried to encode a Server Action from a different instance than the encoder is from. ' + 'This is a bug in React.'); + } + + if (reference.id !== referenceId) { + // These are different functions. + return false; + } // Now check if the number of bound arguments is the same. + + + var boundPromise = reference.bound; + + if (boundPromise === null) { + // No bound arguments. + return numberOfBoundArgs === 0; + } // Unwrap the bound arguments array by suspending, if necessary. As with + // encodeFormData, this means isSignatureEqual can only be called while React + // is rendering. + + + switch (boundPromise.status) { + case 'fulfilled': + { + var boundArgs = boundPromise.value; + return boundArgs.length === numberOfBoundArgs; + } + + case 'pending': + { + throw boundPromise; + } + + case 'rejected': + { + throw boundPromise.reason; + } + + default: + { + if (typeof boundPromise.status === 'string') ; else { + var pendingThenable = boundPromise; + pendingThenable.status = 'pending'; + pendingThenable.then(function (boundArgs) { + var fulfilledThenable = boundPromise; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = boundArgs; + }, function (error) { + var rejectedThenable = boundPromise; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + }); + } + + throw boundPromise; + } + } +} + +function registerServerReference(proxy, reference) { + // Expose encoder for use by SSR, as well as a special bind that can be used to + // keep server capabilities. + { + // Only expose this in builds that would actually use it. Not needed on the client. + Object.defineProperties(proxy, { + $$FORM_ACTION: { + value: encodeFormAction + }, + $$IS_SIGNATURE_EQUAL: { + value: isSignatureEqual + }, + bind: { + value: bind + } + }); + } + + knownServerReferences.set(proxy, reference); +} // $FlowFixMe[method-unbinding] + +var FunctionBind = Function.prototype.bind; // $FlowFixMe[method-unbinding] + +var ArraySlice = Array.prototype.slice; + +function bind() { + // $FlowFixMe[unsupported-syntax] + var newFn = FunctionBind.apply(this, arguments); + var reference = knownServerReferences.get(this); + + if (reference) { + var args = ArraySlice.call(arguments, 1); + var boundPromise = null; + + if (reference.bound !== null) { + boundPromise = Promise.resolve(reference.bound).then(function (boundArgs) { + return boundArgs.concat(args); + }); + } else { + boundPromise = Promise.resolve(args); + } + + registerServerReference(newFn, { + id: reference.id, + bound: boundPromise + }); + } + + return newFn; +} + +function createServerReference$1(id, callServer) { + var proxy = function () { + // $FlowFixMe[method-unbinding] + var args = Array.prototype.slice.call(arguments); + return callServer(id, args); + }; + + registerServerReference(proxy, { + id: id, + bound: null + }); + return proxy; +} + +var ContextRegistry = ReactSharedInternals.ContextRegistry; +function getOrCreateServerContext(globalName) { + if (!ContextRegistry[globalName]) { + var context = { + $$typeof: REACT_SERVER_CONTEXT_TYPE, + // As a workaround to support multiple concurrent renderers, we categorize + // some renderers as primary and others as secondary. We only expect + // there to be two concurrent renderers at most: React Native (primary) and + // Fabric (secondary); React DOM (primary) and React ART (secondary). + // Secondary renderers store their context values on separate fields. + _currentValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + _currentValue2: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + _defaultValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + // Used to track how many concurrent renderers this context currently + // supports within in a single renderer. Such as parallel server rendering. + _threadCount: 0, + // These are circular + Provider: null, + Consumer: null, + _globalName: globalName + }; + context.Provider = { + $$typeof: REACT_PROVIDER_TYPE, + _context: context + }; + + { + var hasWarnedAboutUsingConsumer; + context._currentRenderer = null; + context._currentRenderer2 = null; + Object.defineProperties(context, { + Consumer: { + get: function () { + if (!hasWarnedAboutUsingConsumer) { + error('Consumer pattern is not supported by ReactServerContext'); + + hasWarnedAboutUsingConsumer = true; + } + + return null; + } + } + }); + } + + ContextRegistry[globalName] = context; + } + + return ContextRegistry[globalName]; +} + +var ROW_ID = 0; +var ROW_TAG = 1; +var ROW_LENGTH = 2; +var ROW_CHUNK_BY_NEWLINE = 3; +var ROW_CHUNK_BY_LENGTH = 4; +var PENDING = 'pending'; +var BLOCKED = 'blocked'; +var RESOLVED_MODEL = 'resolved_model'; +var RESOLVED_MODULE = 'resolved_module'; +var INITIALIZED = 'fulfilled'; +var ERRORED = 'rejected'; // $FlowFixMe[missing-this-annot] + +function Chunk(status, value, reason, response) { + this.status = status; + this.value = value; + this.reason = reason; + this._response = response; +} // We subclass Promise.prototype so that we get other methods like .catch + + +Chunk.prototype = Object.create(Promise.prototype); // TODO: This doesn't return a new Promise chain unlike the real .then + +Chunk.prototype.then = function (resolve, reject) { + var chunk = this; // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + resolve(chunk.value); + break; + + case PENDING: + case BLOCKED: + if (resolve) { + if (chunk.value === null) { + chunk.value = []; + } + + chunk.value.push(resolve); + } + + if (reject) { + if (chunk.reason === null) { + chunk.reason = []; + } + + chunk.reason.push(reject); + } + + break; + + default: + reject(chunk.reason); + break; + } +}; + +function readChunk(chunk) { + // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + return chunk.value; + + case PENDING: + case BLOCKED: + // eslint-disable-next-line no-throw-literal + throw chunk; + + default: + throw chunk.reason; + } +} + +function getRoot(response) { + var chunk = getChunk(response, 0); + return chunk; +} + +function createPendingChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(PENDING, null, null, response); +} + +function createBlockedChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(BLOCKED, null, null, response); +} + +function createErrorChunk(response, error) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(ERRORED, null, error, response); +} + +function wakeChunk(listeners, value) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + listener(value); + } +} + +function wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners) { + switch (chunk.status) { + case INITIALIZED: + wakeChunk(resolveListeners, chunk.value); + break; + + case PENDING: + case BLOCKED: + chunk.value = resolveListeners; + chunk.reason = rejectListeners; + break; + + case ERRORED: + if (rejectListeners) { + wakeChunk(rejectListeners, chunk.reason); + } + + break; + } +} + +function triggerErrorOnChunk(chunk, error) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var listeners = chunk.reason; + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + + if (listeners !== null) { + wakeChunk(listeners, error); + } +} + +function createResolvedModelChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODEL, value, null, response); +} + +function createResolvedModuleChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODULE, value, null, response); +} + +function createInitializedTextChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(INITIALIZED, value, null, response); +} + +function createInitializedBufferChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(INITIALIZED, value, null, response); +} + +function resolveModelChunk(chunk, value) { + if (chunk.status !== PENDING) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODEL; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + // This is unfortunate that we're reading this eagerly if + // we already have listeners attached since they might no + // longer be rendered or might not be the highest pri. + initializeModelChunk(resolvedChunk); // The status might have changed after initialization. + + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +function resolveModuleChunk(chunk, value) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODULE; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + initializeModuleChunk(resolvedChunk); + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +var initializingChunk = null; +var initializingChunkBlockedModel = null; + +function initializeModelChunk(chunk) { + var prevChunk = initializingChunk; + var prevBlocked = initializingChunkBlockedModel; + initializingChunk = chunk; + initializingChunkBlockedModel = null; + + try { + var value = parseModel(chunk._response, chunk.value); + + if (initializingChunkBlockedModel !== null && initializingChunkBlockedModel.deps > 0) { + initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved. + // We have to go the BLOCKED state until they're resolved. + + var blockedChunk = chunk; + blockedChunk.status = BLOCKED; + blockedChunk.value = null; + blockedChunk.reason = null; + } else { + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } finally { + initializingChunk = prevChunk; + initializingChunkBlockedModel = prevBlocked; + } +} + +function initializeModuleChunk(chunk) { + try { + var value = requireModule(chunk.value); + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } +} // Report that any missing chunks in the model is now going to throw this +// error upon read. Also notify any pending promises. + + +function reportGlobalError(response, error) { + response._chunks.forEach(function (chunk) { + // If this chunk was already resolved or errored, it won't + // trigger an error but if it wasn't then we need to + // because we won't be getting any new data to resolve it. + if (chunk.status === PENDING) { + triggerErrorOnChunk(chunk, error); + } + }); +} + +function createElement(type, key, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: null, + props: props, + // Record the component responsible for creating this element. + _owner: null + }; + + { + // We don't really need to add any of these but keeping them for good measure. + // Unfortunately, _store is enumerable in jest matchers so for equality to + // work, I need to keep it or make _store non-enumerable in the other file. + element._store = {}; + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: true // This element has already been validated on the server. + + }); + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: null + }); + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: null + }); + } + + return element; +} + +function createLazyChunkWrapper(chunk) { + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: chunk, + _init: readChunk + }; + return lazyType; +} + +function getChunk(response, id) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunk = createPendingChunk(response); + chunks.set(id, chunk); + } + + return chunk; +} + +function createModelResolver(chunk, parentObject, key) { + var blocked; + + if (initializingChunkBlockedModel) { + blocked = initializingChunkBlockedModel; + blocked.deps++; + } else { + blocked = initializingChunkBlockedModel = { + deps: 1, + value: null + }; + } + + return function (value) { + parentObject[key] = value; + blocked.deps--; + + if (blocked.deps === 0) { + if (chunk.status !== BLOCKED) { + return; + } + + var resolveListeners = chunk.value; + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = blocked.value; + + if (resolveListeners !== null) { + wakeChunk(resolveListeners, blocked.value); + } + } + }; +} + +function createModelReject(chunk) { + return function (error) { + return triggerErrorOnChunk(chunk, error); + }; +} + +function createServerReferenceProxy(response, metaData) { + var callServer = response._callServer; + + var proxy = function () { + // $FlowFixMe[method-unbinding] + var args = Array.prototype.slice.call(arguments); + var p = metaData.bound; + + if (!p) { + return callServer(metaData.id, args); + } + + if (p.status === INITIALIZED) { + var bound = p.value; + return callServer(metaData.id, bound.concat(args)); + } // Since this is a fake Promise whose .then doesn't chain, we have to wrap it. + // TODO: Remove the wrapper once that's fixed. + + + return Promise.resolve(p).then(function (bound) { + return callServer(metaData.id, bound.concat(args)); + }); + }; + + registerServerReference(proxy, metaData); + return proxy; +} + +function getOutlinedModel(response, id) { + var chunk = getChunk(response, id); + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + { + return chunk.value; + } + // We always encode it first in the stream so it won't be pending. + + default: + throw chunk.reason; + } +} + +function parseModelString(response, parentObject, key, value) { + if (value[0] === '$') { + if (value === '$') { + // A very common symbol. + return REACT_ELEMENT_TYPE; + } + + switch (value[1]) { + case '$': + { + // This was an escaped string value. + return value.slice(1); + } + + case 'L': + { + // Lazy node + var id = parseInt(value.slice(2), 16); + var chunk = getChunk(response, id); // We create a React.lazy wrapper around any lazy values. + // When passed into React, we'll know how to suspend on this. + + return createLazyChunkWrapper(chunk); + } + + case '@': + { + // Promise + var _id = parseInt(value.slice(2), 16); + + var _chunk = getChunk(response, _id); + + return _chunk; + } + + case 'S': + { + // Symbol + return Symbol.for(value.slice(2)); + } + + case 'P': + { + // Server Context Provider + return getOrCreateServerContext(value.slice(2)).Provider; + } + + case 'F': + { + // Server Reference + var _id2 = parseInt(value.slice(2), 16); + + var metadata = getOutlinedModel(response, _id2); + return createServerReferenceProxy(response, metadata); + } + + case 'Q': + { + // Map + var _id3 = parseInt(value.slice(2), 16); + + var data = getOutlinedModel(response, _id3); + return new Map(data); + } + + case 'W': + { + // Set + var _id4 = parseInt(value.slice(2), 16); + + var _data = getOutlinedModel(response, _id4); + + return new Set(_data); + } + + case 'I': + { + // $Infinity + return Infinity; + } + + case '-': + { + // $-0 or $-Infinity + if (value === '$-0') { + return -0; + } else { + return -Infinity; + } + } + + case 'N': + { + // $NaN + return NaN; + } + + case 'u': + { + // matches "$undefined" + // Special encoding for `undefined` which can't be serialized as JSON otherwise. + return undefined; + } + + case 'D': + { + // Date + return new Date(Date.parse(value.slice(2))); + } + + case 'n': + { + // BigInt + return BigInt(value.slice(2)); + } + + default: + { + // We assume that anything else is a reference ID. + var _id5 = parseInt(value.slice(1), 16); + + var _chunk2 = getChunk(response, _id5); + + switch (_chunk2.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk2); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(_chunk2); + break; + } // The status might have changed after initialization. + + + switch (_chunk2.status) { + case INITIALIZED: + return _chunk2.value; + + case PENDING: + case BLOCKED: + var parentChunk = initializingChunk; + + _chunk2.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); + + return null; + + default: + throw _chunk2.reason; + } + } + } + } + + return value; +} + +function parseModelTuple(response, value) { + var tuple = value; + + if (tuple[0] === REACT_ELEMENT_TYPE) { + // TODO: Consider having React just directly accept these arrays as elements. + // Or even change the ReactElement type to be an array. + return createElement(tuple[1], tuple[2], tuple[3]); + } + + return value; +} + +function missingCall() { + throw new Error('Trying to call a function from "use server" but the callServer option ' + 'was not implemented in your router runtime.'); +} + +function createResponse(bundlerConfig, moduleLoading, callServer, nonce) { + var chunks = new Map(); + var response = { + _bundlerConfig: bundlerConfig, + _moduleLoading: moduleLoading, + _callServer: callServer !== undefined ? callServer : missingCall, + _nonce: nonce, + _chunks: chunks, + _stringDecoder: createStringDecoder(), + _fromJSON: null, + _rowState: 0, + _rowID: 0, + _rowTag: 0, + _rowLength: 0, + _buffer: [] + }; // Don't inline this call because it causes closure to outline the call above. + + response._fromJSON = createFromJSONCallback(response); + return response; +} + +function resolveModel(response, id, model) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createResolvedModelChunk(response, model)); + } else { + resolveModelChunk(chunk, model); + } +} + +function resolveText(response, id, text) { + var chunks = response._chunks; // We assume that we always reference large strings after they've been + // emitted. + + chunks.set(id, createInitializedTextChunk(response, text)); +} + +function resolveBuffer(response, id, buffer) { + var chunks = response._chunks; // We assume that we always reference buffers after they've been emitted. + + chunks.set(id, createInitializedBufferChunk(response, buffer)); +} + +function resolveModule(response, id, model) { + var chunks = response._chunks; + var chunk = chunks.get(id); + var clientReferenceMetadata = parseModel(response, model); + var clientReference = resolveClientReference(response._bundlerConfig, clientReferenceMetadata); + prepareDestinationForModule(response._moduleLoading, response._nonce, clientReferenceMetadata); // TODO: Add an option to encode modules that are lazy loaded. + // For now we preload all modules as early as possible since it's likely + // that we'll need them. + + var promise = preloadModule(clientReference); + + if (promise) { + var blockedChunk; + + if (!chunk) { + // Technically, we should just treat promise as the chunk in this + // case. Because it'll just behave as any other promise. + blockedChunk = createBlockedChunk(response); + chunks.set(id, blockedChunk); + } else { + // This can't actually happen because we don't have any forward + // references to modules. + blockedChunk = chunk; + blockedChunk.status = BLOCKED; + } + + promise.then(function () { + return resolveModuleChunk(blockedChunk, clientReference); + }, function (error) { + return triggerErrorOnChunk(blockedChunk, error); + }); + } else { + if (!chunk) { + chunks.set(id, createResolvedModuleChunk(response, clientReference)); + } else { + // This can't actually happen because we don't have any forward + // references to modules. + resolveModuleChunk(chunk, clientReference); + } + } +} + +function resolveErrorDev(response, id, digest, message, stack) { + + + var error = new Error(message || 'An error occurred in the Server Components render but no message was provided'); + error.stack = stack; + error.digest = digest; + var errorWithDigest = error; + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createErrorChunk(response, errorWithDigest)); + } else { + triggerErrorOnChunk(chunk, errorWithDigest); + } +} + +function resolvePostponeDev(response, id, reason, stack) { + + + var error = new Error(reason || ''); + var postponeInstance = error; + postponeInstance.$$typeof = REACT_POSTPONE_TYPE; + postponeInstance.stack = stack; + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createErrorChunk(response, postponeInstance)); + } else { + triggerErrorOnChunk(chunk, postponeInstance); + } +} + +function resolveHint(response, code, model) { + var hintModel = parseModel(response, model); + dispatchHint(code, hintModel); +} + +function mergeBuffer(buffer, lastChunk) { + var l = buffer.length; // Count the bytes we'll need + + var byteLength = lastChunk.length; + + for (var i = 0; i < l; i++) { + byteLength += buffer[i].byteLength; + } // Allocate enough contiguous space + + + var result = new Uint8Array(byteLength); + var offset = 0; // Copy all the buffers into it. + + for (var _i = 0; _i < l; _i++) { + var chunk = buffer[_i]; + result.set(chunk, offset); + offset += chunk.byteLength; + } + + result.set(lastChunk, offset); + return result; +} + +function resolveTypedArray(response, id, buffer, lastChunk, constructor, bytesPerElement) { + // If the view fits into one original buffer, we just reuse that buffer instead of + // copying it out to a separate copy. This means that it's not always possible to + // transfer these values to other threads without copying first since they may + // share array buffer. For this to work, it must also have bytes aligned to a + // multiple of a size of the type. + var chunk = buffer.length === 0 && lastChunk.byteOffset % bytesPerElement === 0 ? lastChunk : mergeBuffer(buffer, lastChunk); // TODO: The transfer protocol of RSC is little-endian. If the client isn't little-endian + // we should convert it instead. In practice big endian isn't really Web compatible so it's + // somewhat safe to assume that browsers aren't going to run it, but maybe there's some SSR + // server that's affected. + + var view = new constructor(chunk.buffer, chunk.byteOffset, chunk.byteLength / bytesPerElement); + resolveBuffer(response, id, view); +} + +function processFullRow(response, id, tag, buffer, chunk) { + { + switch (tag) { + case 65 + /* "A" */ + : + // We must always clone to extract it into a separate buffer instead of just a view. + resolveBuffer(response, id, mergeBuffer(buffer, chunk).buffer); + return; + + case 67 + /* "C" */ + : + resolveTypedArray(response, id, buffer, chunk, Int8Array, 1); + return; + + case 99 + /* "c" */ + : + resolveBuffer(response, id, buffer.length === 0 ? chunk : mergeBuffer(buffer, chunk)); + return; + + case 85 + /* "U" */ + : + resolveTypedArray(response, id, buffer, chunk, Uint8ClampedArray, 1); + return; + + case 83 + /* "S" */ + : + resolveTypedArray(response, id, buffer, chunk, Int16Array, 2); + return; + + case 115 + /* "s" */ + : + resolveTypedArray(response, id, buffer, chunk, Uint16Array, 2); + return; + + case 76 + /* "L" */ + : + resolveTypedArray(response, id, buffer, chunk, Int32Array, 4); + return; + + case 108 + /* "l" */ + : + resolveTypedArray(response, id, buffer, chunk, Uint32Array, 4); + return; + + case 70 + /* "F" */ + : + resolveTypedArray(response, id, buffer, chunk, Float32Array, 4); + return; + + case 68 + /* "D" */ + : + resolveTypedArray(response, id, buffer, chunk, Float64Array, 8); + return; + + case 78 + /* "N" */ + : + resolveTypedArray(response, id, buffer, chunk, BigInt64Array, 8); + return; + + case 109 + /* "m" */ + : + resolveTypedArray(response, id, buffer, chunk, BigUint64Array, 8); + return; + + case 86 + /* "V" */ + : + resolveTypedArray(response, id, buffer, chunk, DataView, 1); + return; + } + } + + var stringDecoder = response._stringDecoder; + var row = ''; + + for (var i = 0; i < buffer.length; i++) { + row += readPartialStringChunk(stringDecoder, buffer[i]); + } + + row += readFinalStringChunk(stringDecoder, chunk); + + switch (tag) { + case 73 + /* "I" */ + : + { + resolveModule(response, id, row); + return; + } + + case 72 + /* "H" */ + : + { + var code = row[0]; + resolveHint(response, code, row.slice(1)); + return; + } + + case 69 + /* "E" */ + : + { + var errorInfo = JSON.parse(row); + + { + resolveErrorDev(response, id, errorInfo.digest, errorInfo.message, errorInfo.stack); + } + + return; + } + + case 84 + /* "T" */ + : + { + resolveText(response, id, row); + return; + } + + case 80 + /* "P" */ + : + { + { + { + var postponeInfo = JSON.parse(row); + resolvePostponeDev(response, id, postponeInfo.reason, postponeInfo.stack); + } + + return; + } + } + // Fallthrough + + default: + /* """ "{" "[" "t" "f" "n" "0" - "9" */ + { + // We assume anything else is JSON. + resolveModel(response, id, row); + return; + } + } +} + +function processBinaryChunk(response, chunk) { + var i = 0; + var rowState = response._rowState; + var rowID = response._rowID; + var rowTag = response._rowTag; + var rowLength = response._rowLength; + var buffer = response._buffer; + var chunkLength = chunk.length; + + while (i < chunkLength) { + var lastIdx = -1; + + switch (rowState) { + case ROW_ID: + { + var byte = chunk[i++]; + + if (byte === 58 + /* ":" */ + ) { + // Finished the rowID, next we'll parse the tag. + rowState = ROW_TAG; + } else { + rowID = rowID << 4 | (byte > 96 ? byte - 87 : byte - 48); + } + + continue; + } + + case ROW_TAG: + { + var resolvedRowTag = chunk[i]; + + if (resolvedRowTag === 84 + /* "T" */ + || (resolvedRowTag === 65 + /* "A" */ + || resolvedRowTag === 67 + /* "C" */ + || resolvedRowTag === 99 + /* "c" */ + || resolvedRowTag === 85 + /* "U" */ + || resolvedRowTag === 83 + /* "S" */ + || resolvedRowTag === 115 + /* "s" */ + || resolvedRowTag === 76 + /* "L" */ + || resolvedRowTag === 108 + /* "l" */ + || resolvedRowTag === 70 + /* "F" */ + || resolvedRowTag === 68 + /* "D" */ + || resolvedRowTag === 78 + /* "N" */ + || resolvedRowTag === 109 + /* "m" */ + || resolvedRowTag === 86) + /* "V" */ + ) { + rowTag = resolvedRowTag; + rowState = ROW_LENGTH; + i++; + } else if (resolvedRowTag > 64 && resolvedRowTag < 91 + /* "A"-"Z" */ + ) { + rowTag = resolvedRowTag; + rowState = ROW_CHUNK_BY_NEWLINE; + i++; + } else { + rowTag = 0; + rowState = ROW_CHUNK_BY_NEWLINE; // This was an unknown tag so it was probably part of the data. + } + + continue; + } + + case ROW_LENGTH: + { + var _byte = chunk[i++]; + + if (_byte === 44 + /* "," */ + ) { + // Finished the rowLength, next we'll buffer up to that length. + rowState = ROW_CHUNK_BY_LENGTH; + } else { + rowLength = rowLength << 4 | (_byte > 96 ? _byte - 87 : _byte - 48); + } + + continue; + } + + case ROW_CHUNK_BY_NEWLINE: + { + // We're looking for a newline + lastIdx = chunk.indexOf(10 + /* "\n" */ + , i); + break; + } + + case ROW_CHUNK_BY_LENGTH: + { + // We're looking for the remaining byte length + lastIdx = i + rowLength; + + if (lastIdx > chunk.length) { + lastIdx = -1; + } + + break; + } + } + + var offset = chunk.byteOffset + i; + + if (lastIdx > -1) { + // We found the last chunk of the row + var length = lastIdx - i; + var lastChunk = new Uint8Array(chunk.buffer, offset, length); + processFullRow(response, rowID, rowTag, buffer, lastChunk); // Reset state machine for a new row + + i = lastIdx; + + if (rowState === ROW_CHUNK_BY_NEWLINE) { + // If we're trailing by a newline we need to skip it. + i++; + } + + rowState = ROW_ID; + rowTag = 0; + rowID = 0; + rowLength = 0; + buffer.length = 0; + } else { + // The rest of this row is in a future chunk. We stash the rest of the + // current chunk until we can process the full row. + var _length = chunk.byteLength - i; + + var remainingSlice = new Uint8Array(chunk.buffer, offset, _length); + buffer.push(remainingSlice); // Update how many bytes we're still waiting for. If we're looking for + // a newline, this doesn't hurt since we'll just ignore it. + + rowLength -= remainingSlice.byteLength; + break; + } + } + + response._rowState = rowState; + response._rowID = rowID; + response._rowTag = rowTag; + response._rowLength = rowLength; +} + +function parseModel(response, json) { + return JSON.parse(json, response._fromJSON); +} + +function createFromJSONCallback(response) { + // $FlowFixMe[missing-this-annot] + return function (key, value) { + if (typeof value === 'string') { + // We can't use .bind here because we need the "this" value. + return parseModelString(response, this, key, value); + } + + if (typeof value === 'object' && value !== null) { + return parseModelTuple(response, value); + } + + return value; + }; +} + +function close(response) { + // In case there are any remaining unresolved chunks, they won't + // be resolved now. So we need to issue an error to those. + // Ideally we should be able to early bail out if we kept a + // ref count of pending chunks. + reportGlobalError(response, new Error('Connection closed.')); +} + +function noServerCall() { + throw new Error('Server Functions cannot be called during initial render. ' + 'This would create a fetch waterfall. Try to use a Server Component ' + 'to pass data to Client Components instead.'); +} + +function createServerReference(id, callServer) { + return createServerReference$1(id, noServerCall); +} + +function createFromNodeStream(stream, ssrManifest, options) { + var response = createResponse(ssrManifest.moduleMap, ssrManifest.moduleLoading, noServerCall, options && typeof options.nonce === 'string' ? options.nonce : undefined); + stream.on('data', function (chunk) { + processBinaryChunk(response, chunk); + }); + stream.on('error', function (error) { + reportGlobalError(response, error); + }); + stream.on('end', function () { + return close(response); + }); + return getRoot(response); +} + +exports.createFromNodeStream = createFromNodeStream; +exports.createServerReference = createServerReference; + })(); +} diff --git a/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-client.node.production.min.js b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-client.node.production.min.js new file mode 100644 index 0000000000000..fce8b904731e3 --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-client.node.production.min.js @@ -0,0 +1,43 @@ +/** + * @license React + * react-server-dom-turbopack-client.node.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var n=require("util"),q=require("react-dom"),r=require("react"),u={stream:!0};function v(a,b){if(a){var c=a[b[0]];if(a=c[b[2]])c=a.name;else{a=c["*"];if(!a)throw Error('Could not find the module "'+b[0]+'" in the React SSR Manifest. This is probably a bug in the React Server Components bundler.');c=b[2]}return 4===b.length?[a.id,a.chunks,c,1]:[a.id,a.chunks,c]}return b}var w=new Map; +function x(a){var b=globalThis.__next_require__(a);if("function"!==typeof b.then||"fulfilled"===b.status)return null;b.then(function(c){b.status="fulfilled";b.value=c},function(c){b.status="rejected";b.reason=c});return b}function y(){} +function A(a){for(var b=a[1],c=[],d=0;df?(l=f,f=3,g++):(l=0,f=3); +continue;case 2:m=e[g++];44===m?f=4:h=h<<4|(96e.length&&(m=-1)}var p=e.byteOffset+g;if(-1 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); +var REACT_POSTPONE_TYPE = Symbol.for('react.postpone'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +// in case they error. + +var jsxPropsParents = new WeakMap(); +var jsxChildrenParents = new WeakMap(); + +function isObjectPrototype(object) { + if (!object) { + return false; + } + + var ObjectPrototype = Object.prototype; + + if (object === ObjectPrototype) { + return true; + } // It might be an object from a different Realm which is + // still just a plain simple object. + + + if (Object.getPrototypeOf(object)) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + if (!(names[i] in ObjectPrototype)) { + return false; + } + } + + return true; +} + +function isSimpleObject(object) { + if (!isObjectPrototype(Object.getPrototypeOf(object))) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + var descriptor = Object.getOwnPropertyDescriptor(object, names[i]); + + if (!descriptor) { + return false; + } + + if (!descriptor.enumerable) { + if ((names[i] === 'key' || names[i] === 'ref') && typeof descriptor.get === 'function') { + // React adds key and ref getters to props objects to issue warnings. + // Those getters will not be transferred to the client, but that's ok, + // so we'll special case them. + continue; + } + + return false; + } + } + + return true; +} +function objectName(object) { + // $FlowFixMe[method-unbinding] + var name = Object.prototype.toString.call(object); + return name.replace(/^\[object (.*)\]$/, function (m, p0) { + return p0; + }); +} + +function describeKeyForErrorMessage(key) { + var encodedKey = JSON.stringify(key); + return '"' + key + '"' === encodedKey ? key : encodedKey; +} + +function describeValueForErrorMessage(value) { + switch (typeof value) { + case 'string': + { + return JSON.stringify(value.length <= 10 ? value : value.slice(0, 10) + '...'); + } + + case 'object': + { + if (isArray(value)) { + return '[...]'; + } + + var name = objectName(value); + + if (name === 'Object') { + return '{...}'; + } + + return name; + } + + case 'function': + return 'function'; + + default: + // eslint-disable-next-line react-internal/safe-string-coercion + return String(value); + } +} + +function describeElementType(type) { + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeElementType(type.render); + + case REACT_MEMO_TYPE: + return describeElementType(type.type); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeElementType(init(payload)); + } catch (x) {} + } + } + } + + return ''; +} + +function describeObjectForErrorMessage(objectOrArray, expandedName) { + var objKind = objectName(objectOrArray); + + if (objKind !== 'Object' && objKind !== 'Array') { + return objKind; + } + + var str = ''; + var start = -1; + var length = 0; + + if (isArray(objectOrArray)) { + if (jsxChildrenParents.has(objectOrArray)) { + // Print JSX Children + var type = jsxChildrenParents.get(objectOrArray); + str = '<' + describeElementType(type) + '>'; + var array = objectOrArray; + + for (var i = 0; i < array.length; i++) { + var value = array[i]; + var substr = void 0; + + if (typeof value === 'string') { + substr = value; + } else if (typeof value === 'object' && value !== null) { + substr = '{' + describeObjectForErrorMessage(value) + '}'; + } else { + substr = '{' + describeValueForErrorMessage(value) + '}'; + } + + if ('' + i === expandedName) { + start = str.length; + length = substr.length; + str += substr; + } else if (substr.length < 15 && str.length + substr.length < 40) { + str += substr; + } else { + str += '{...}'; + } + } + + str += ''; + } else { + // Print Array + str = '['; + var _array = objectOrArray; + + for (var _i = 0; _i < _array.length; _i++) { + if (_i > 0) { + str += ', '; + } + + var _value = _array[_i]; + + var _substr = void 0; + + if (typeof _value === 'object' && _value !== null) { + _substr = describeObjectForErrorMessage(_value); + } else { + _substr = describeValueForErrorMessage(_value); + } + + if ('' + _i === expandedName) { + start = str.length; + length = _substr.length; + str += _substr; + } else if (_substr.length < 10 && str.length + _substr.length < 40) { + str += _substr; + } else { + str += '...'; + } + } + + str += ']'; + } + } else { + if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) { + str = '<' + describeElementType(objectOrArray.type) + '/>'; + } else if (jsxPropsParents.has(objectOrArray)) { + // Print JSX + var _type = jsxPropsParents.get(objectOrArray); + + str = '<' + (describeElementType(_type) || '...'); + var object = objectOrArray; + var names = Object.keys(object); + + for (var _i2 = 0; _i2 < names.length; _i2++) { + str += ' '; + var name = names[_i2]; + str += describeKeyForErrorMessage(name) + '='; + var _value2 = object[name]; + + var _substr2 = void 0; + + if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) { + _substr2 = describeObjectForErrorMessage(_value2); + } else { + _substr2 = describeValueForErrorMessage(_value2); + } + + if (typeof _value2 !== 'string') { + _substr2 = '{' + _substr2 + '}'; + } + + if (name === expandedName) { + start = str.length; + length = _substr2.length; + str += _substr2; + } else if (_substr2.length < 10 && str.length + _substr2.length < 40) { + str += _substr2; + } else { + str += '...'; + } + } + + str += '>'; + } else { + // Print Object + str = '{'; + var _object = objectOrArray; + + var _names = Object.keys(_object); + + for (var _i3 = 0; _i3 < _names.length; _i3++) { + if (_i3 > 0) { + str += ', '; + } + + var _name = _names[_i3]; + str += describeKeyForErrorMessage(_name) + ': '; + var _value3 = _object[_name]; + + var _substr3 = void 0; + + if (typeof _value3 === 'object' && _value3 !== null) { + _substr3 = describeObjectForErrorMessage(_value3); + } else { + _substr3 = describeValueForErrorMessage(_value3); + } + + if (_name === expandedName) { + start = str.length; + length = _substr3.length; + str += _substr3; + } else if (_substr3.length < 10 && str.length + _substr3.length < 40) { + str += _substr3; + } else { + str += '...'; + } + } + + str += '}'; + } + } + + if (expandedName === undefined) { + return str; + } + + if (start > -1 && length > 0) { + var highlight = ' '.repeat(start) + '^'.repeat(length); + return '\n ' + str + '\n ' + highlight; + } + + return '\n ' + str; +} + +var knownServerReferences = new WeakMap(); // Serializable values +// Thenable +// function serializeByValueID(id: number): string { +// return '$' + id.toString(16); +// } + +function serializePromiseID(id) { + return '$@' + id.toString(16); +} + +function serializeServerReferenceID(id) { + return '$F' + id.toString(16); +} + +function serializeSymbolReference(name) { + return '$S' + name; +} + +function serializeFormDataReference(id) { + // Why K? F is "Function". D is "Date". What else? + return '$K' + id.toString(16); +} + +function serializeNumber(number) { + if (Number.isFinite(number)) { + if (number === 0 && 1 / number === -Infinity) { + return '$-0'; + } else { + return number; + } + } else { + if (number === Infinity) { + return '$Infinity'; + } else if (number === -Infinity) { + return '$-Infinity'; + } else { + return '$NaN'; + } + } +} + +function serializeUndefined() { + return '$undefined'; +} + +function serializeDateFromDateJSON(dateJSON) { + // JSON.stringify automatically calls Date.prototype.toJSON which calls toISOString. + // We need only tack on a $D prefix. + return '$D' + dateJSON; +} + +function serializeBigInt(n) { + return '$n' + n.toString(10); +} + +function serializeMapID(id) { + return '$Q' + id.toString(16); +} + +function serializeSetID(id) { + return '$W' + id.toString(16); +} + +function escapeStringValue(value) { + if (value[0] === '$') { + // We need to escape $ prefixed strings since we use those to encode + // references to IDs and as special symbol values. + return '$' + value; + } else { + return value; + } +} + +function processReply(root, formFieldPrefix, resolve, reject) { + var nextPartId = 1; + var pendingParts = 0; + var formData = null; + + function resolveToJSON(key, value) { + var parent = this; // Make sure that `parent[key]` wasn't JSONified before `value` was passed to us + + { + // $FlowFixMe[incompatible-use] + var originalValue = parent[key]; + + if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) { + if (objectName(originalValue) !== 'Object') { + error('Only plain objects can be passed to Server Functions from the Client. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } else { + error('Only plain objects can be passed to Server Functions from the Client. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props.%s', describeObjectForErrorMessage(parent, key)); + } + } + } + + if (value === null) { + return null; + } + + if (typeof value === 'object') { + // $FlowFixMe[method-unbinding] + if (typeof value.then === 'function') { + // We assume that any object with a .then property is a "Thenable" type, + // or a Promise type. Either of which can be represented by a Promise. + if (formData === null) { + // Upgrade to use FormData to allow us to stream this value. + formData = new FormData(); + } + + pendingParts++; + var promiseId = nextPartId++; + var thenable = value; + thenable.then(function (partValue) { + var partJSON = JSON.stringify(partValue, resolveToJSON); // $FlowFixMe[incompatible-type] We know it's not null because we assigned it above. + + var data = formData; // eslint-disable-next-line react-internal/safe-string-coercion + + data.append(formFieldPrefix + promiseId, partJSON); + pendingParts--; + + if (pendingParts === 0) { + resolve(data); + } + }, function (reason) { + // In the future we could consider serializing this as an error + // that throws on the server instead. + reject(reason); + }); + return serializePromiseID(promiseId); + } // TODO: Should we the Object.prototype.toString.call() to test for cross-realm objects? + + + if (value instanceof FormData) { + if (formData === null) { + // Upgrade to use FormData to allow us to use rich objects as its values. + formData = new FormData(); + } + + var data = formData; + var refId = nextPartId++; // Copy all the form fields with a prefix for this reference. + // These must come first in the form order because we assume that all the + // fields are available before this is referenced. + + var prefix = formFieldPrefix + refId + '_'; // $FlowFixMe[prop-missing]: FormData has forEach. + + value.forEach(function (originalValue, originalKey) { + data.append(prefix + originalKey, originalValue); + }); + return serializeFormDataReference(refId); + } + + if (value instanceof Map) { + var partJSON = JSON.stringify(Array.from(value), resolveToJSON); + + if (formData === null) { + formData = new FormData(); + } + + var mapId = nextPartId++; + formData.append(formFieldPrefix + mapId, partJSON); + return serializeMapID(mapId); + } + + if (value instanceof Set) { + var _partJSON = JSON.stringify(Array.from(value), resolveToJSON); + + if (formData === null) { + formData = new FormData(); + } + + var setId = nextPartId++; + formData.append(formFieldPrefix + setId, _partJSON); + return serializeSetID(setId); + } + + if (!isArray(value)) { + var iteratorFn = getIteratorFn(value); + + if (iteratorFn) { + return Array.from(value); + } + } + + { + if (value !== null && !isArray(value)) { + // Verify that this is a simple plain object. + if (value.$$typeof === REACT_ELEMENT_TYPE) { + error('React Element cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key)); + } else if (value.$$typeof === REACT_LAZY_TYPE) { + error('React Lazy cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key)); + } else if (value.$$typeof === REACT_PROVIDER_TYPE) { + error('React Context Providers cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key)); + } else if (objectName(value) !== 'Object') { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, key)); + } else if (!isSimpleObject(value)) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Classes or other objects with methods are not supported.%s', describeObjectForErrorMessage(parent, key)); + } else if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(value); + + if (symbols.length > 0) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with symbol properties like %s are not supported.%s', symbols[0].description, describeObjectForErrorMessage(parent, key)); + } + } + } + } // $FlowFixMe[incompatible-return] + + + return value; + } + + if (typeof value === 'string') { + // TODO: Maybe too clever. If we support URL there's no similar trick. + if (value[value.length - 1] === 'Z') { + // Possibly a Date, whose toJSON automatically calls toISOString + // $FlowFixMe[incompatible-use] + var _originalValue = parent[key]; + + if (_originalValue instanceof Date) { + return serializeDateFromDateJSON(value); + } + } + + return escapeStringValue(value); + } + + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return serializeNumber(value); + } + + if (typeof value === 'undefined') { + return serializeUndefined(); + } + + if (typeof value === 'function') { + var metaData = knownServerReferences.get(value); + + if (metaData !== undefined) { + var metaDataJSON = JSON.stringify(metaData, resolveToJSON); + + if (formData === null) { + // Upgrade to use FormData to allow us to stream this value. + formData = new FormData(); + } // The reference to this function came from the same client so we can pass it back. + + + var _refId = nextPartId++; // eslint-disable-next-line react-internal/safe-string-coercion + + + formData.set(formFieldPrefix + _refId, metaDataJSON); + return serializeServerReferenceID(_refId); + } + + throw new Error('Client Functions cannot be passed directly to Server Functions. ' + 'Only Functions passed from the Server can be passed back again.'); + } + + if (typeof value === 'symbol') { + // $FlowFixMe[incompatible-type] `description` might be undefined + var name = value.description; + + if (Symbol.for(name) !== value) { + throw new Error('Only global symbols received from Symbol.for(...) can be passed to Server Functions. ' + ("The symbol Symbol.for(" + // $FlowFixMe[incompatible-type] `description` might be undefined + value.description + ") cannot be found among global symbols.")); + } + + return serializeSymbolReference(name); + } + + if (typeof value === 'bigint') { + return serializeBigInt(value); + } + + throw new Error("Type " + typeof value + " is not supported as an argument to a Server Function."); + } // $FlowFixMe[incompatible-type] it's not going to be undefined because we'll encode it. + + + var json = JSON.stringify(root, resolveToJSON); + + if (formData === null) { + // If it's a simple data structure, we just use plain JSON. + resolve(json); + } else { + // Otherwise, we use FormData to let us stream in the result. + formData.set(formFieldPrefix + '0', json); + + if (pendingParts === 0) { + // $FlowFixMe[incompatible-call] this has already been refined. + resolve(formData); + } + } +} +var boundCache = new WeakMap(); + +function encodeFormData(reference) { + var resolve, reject; // We need to have a handle on the thenable so that we can synchronously set + // its status from processReply, when it can complete synchronously. + + var thenable = new Promise(function (res, rej) { + resolve = res; + reject = rej; + }); + processReply(reference, '', function (body) { + if (typeof body === 'string') { + var data = new FormData(); + data.append('0', body); + body = data; + } + + var fulfilled = thenable; + fulfilled.status = 'fulfilled'; + fulfilled.value = body; + resolve(body); + }, function (e) { + var rejected = thenable; + rejected.status = 'rejected'; + rejected.reason = e; + reject(e); + }); + return thenable; +} + +function encodeFormAction(identifierPrefix) { + var reference = knownServerReferences.get(this); + + if (!reference) { + throw new Error('Tried to encode a Server Action from a different instance than the encoder is from. ' + 'This is a bug in React.'); + } + + var data = null; + var name; + var boundPromise = reference.bound; + + if (boundPromise !== null) { + var thenable = boundCache.get(reference); + + if (!thenable) { + thenable = encodeFormData(reference); + boundCache.set(reference, thenable); + } + + if (thenable.status === 'rejected') { + throw thenable.reason; + } else if (thenable.status !== 'fulfilled') { + throw thenable; + } + + var encodedFormData = thenable.value; // This is hacky but we need the identifier prefix to be added to + // all fields but the suspense cache would break since we might get + // a new identifier each time. So we just append it at the end instead. + + var prefixedData = new FormData(); // $FlowFixMe[prop-missing] + + encodedFormData.forEach(function (value, key) { + prefixedData.append('$ACTION_' + identifierPrefix + ':' + key, value); + }); + data = prefixedData; // We encode the name of the prefix containing the data. + + name = '$ACTION_REF_' + identifierPrefix; + } else { + // This is the simple case so we can just encode the ID. + name = '$ACTION_ID_' + reference.id; + } + + return { + name: name, + method: 'POST', + encType: 'multipart/form-data', + data: data + }; +} + +function isSignatureEqual(referenceId, numberOfBoundArgs) { + var reference = knownServerReferences.get(this); + + if (!reference) { + throw new Error('Tried to encode a Server Action from a different instance than the encoder is from. ' + 'This is a bug in React.'); + } + + if (reference.id !== referenceId) { + // These are different functions. + return false; + } // Now check if the number of bound arguments is the same. + + + var boundPromise = reference.bound; + + if (boundPromise === null) { + // No bound arguments. + return numberOfBoundArgs === 0; + } // Unwrap the bound arguments array by suspending, if necessary. As with + // encodeFormData, this means isSignatureEqual can only be called while React + // is rendering. + + + switch (boundPromise.status) { + case 'fulfilled': + { + var boundArgs = boundPromise.value; + return boundArgs.length === numberOfBoundArgs; + } + + case 'pending': + { + throw boundPromise; + } + + case 'rejected': + { + throw boundPromise.reason; + } + + default: + { + if (typeof boundPromise.status === 'string') ; else { + var pendingThenable = boundPromise; + pendingThenable.status = 'pending'; + pendingThenable.then(function (boundArgs) { + var fulfilledThenable = boundPromise; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = boundArgs; + }, function (error) { + var rejectedThenable = boundPromise; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + }); + } + + throw boundPromise; + } + } +} + +function registerServerReference(proxy, reference) { + // Expose encoder for use by SSR, as well as a special bind that can be used to + // keep server capabilities. + { + // Only expose this in builds that would actually use it. Not needed on the client. + Object.defineProperties(proxy, { + $$FORM_ACTION: { + value: encodeFormAction + }, + $$IS_SIGNATURE_EQUAL: { + value: isSignatureEqual + }, + bind: { + value: bind + } + }); + } + + knownServerReferences.set(proxy, reference); +} // $FlowFixMe[method-unbinding] + +var FunctionBind = Function.prototype.bind; // $FlowFixMe[method-unbinding] + +var ArraySlice = Array.prototype.slice; + +function bind() { + // $FlowFixMe[unsupported-syntax] + var newFn = FunctionBind.apply(this, arguments); + var reference = knownServerReferences.get(this); + + if (reference) { + var args = ArraySlice.call(arguments, 1); + var boundPromise = null; + + if (reference.bound !== null) { + boundPromise = Promise.resolve(reference.bound).then(function (boundArgs) { + return boundArgs.concat(args); + }); + } else { + boundPromise = Promise.resolve(args); + } + + registerServerReference(newFn, { + id: reference.id, + bound: boundPromise + }); + } + + return newFn; +} + +function createServerReference$1(id, callServer) { + var proxy = function () { + // $FlowFixMe[method-unbinding] + var args = Array.prototype.slice.call(arguments); + return callServer(id, args); + }; + + registerServerReference(proxy, { + id: id, + bound: null + }); + return proxy; +} + +var ContextRegistry = ReactSharedInternals.ContextRegistry; +function getOrCreateServerContext(globalName) { + if (!ContextRegistry[globalName]) { + var context = { + $$typeof: REACT_SERVER_CONTEXT_TYPE, + // As a workaround to support multiple concurrent renderers, we categorize + // some renderers as primary and others as secondary. We only expect + // there to be two concurrent renderers at most: React Native (primary) and + // Fabric (secondary); React DOM (primary) and React ART (secondary). + // Secondary renderers store their context values on separate fields. + _currentValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + _currentValue2: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + _defaultValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + // Used to track how many concurrent renderers this context currently + // supports within in a single renderer. Such as parallel server rendering. + _threadCount: 0, + // These are circular + Provider: null, + Consumer: null, + _globalName: globalName + }; + context.Provider = { + $$typeof: REACT_PROVIDER_TYPE, + _context: context + }; + + { + var hasWarnedAboutUsingConsumer; + context._currentRenderer = null; + context._currentRenderer2 = null; + Object.defineProperties(context, { + Consumer: { + get: function () { + if (!hasWarnedAboutUsingConsumer) { + error('Consumer pattern is not supported by ReactServerContext'); + + hasWarnedAboutUsingConsumer = true; + } + + return null; + } + } + }); + } + + ContextRegistry[globalName] = context; + } + + return ContextRegistry[globalName]; +} + +var ROW_ID = 0; +var ROW_TAG = 1; +var ROW_LENGTH = 2; +var ROW_CHUNK_BY_NEWLINE = 3; +var ROW_CHUNK_BY_LENGTH = 4; +var PENDING = 'pending'; +var BLOCKED = 'blocked'; +var RESOLVED_MODEL = 'resolved_model'; +var RESOLVED_MODULE = 'resolved_module'; +var INITIALIZED = 'fulfilled'; +var ERRORED = 'rejected'; // $FlowFixMe[missing-this-annot] + +function Chunk(status, value, reason, response) { + this.status = status; + this.value = value; + this.reason = reason; + this._response = response; +} // We subclass Promise.prototype so that we get other methods like .catch + + +Chunk.prototype = Object.create(Promise.prototype); // TODO: This doesn't return a new Promise chain unlike the real .then + +Chunk.prototype.then = function (resolve, reject) { + var chunk = this; // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + resolve(chunk.value); + break; + + case PENDING: + case BLOCKED: + if (resolve) { + if (chunk.value === null) { + chunk.value = []; + } + + chunk.value.push(resolve); + } + + if (reject) { + if (chunk.reason === null) { + chunk.reason = []; + } + + chunk.reason.push(reject); + } + + break; + + default: + reject(chunk.reason); + break; + } +}; + +function readChunk(chunk) { + // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + return chunk.value; + + case PENDING: + case BLOCKED: + // eslint-disable-next-line no-throw-literal + throw chunk; + + default: + throw chunk.reason; + } +} + +function getRoot(response) { + var chunk = getChunk(response, 0); + return chunk; +} + +function createPendingChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(PENDING, null, null, response); +} + +function createBlockedChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(BLOCKED, null, null, response); +} + +function createErrorChunk(response, error) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(ERRORED, null, error, response); +} + +function wakeChunk(listeners, value) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + listener(value); + } +} + +function wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners) { + switch (chunk.status) { + case INITIALIZED: + wakeChunk(resolveListeners, chunk.value); + break; + + case PENDING: + case BLOCKED: + chunk.value = resolveListeners; + chunk.reason = rejectListeners; + break; + + case ERRORED: + if (rejectListeners) { + wakeChunk(rejectListeners, chunk.reason); + } + + break; + } +} + +function triggerErrorOnChunk(chunk, error) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var listeners = chunk.reason; + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + + if (listeners !== null) { + wakeChunk(listeners, error); + } +} + +function createResolvedModelChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODEL, value, null, response); +} + +function createResolvedModuleChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODULE, value, null, response); +} + +function createInitializedTextChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(INITIALIZED, value, null, response); +} + +function createInitializedBufferChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(INITIALIZED, value, null, response); +} + +function resolveModelChunk(chunk, value) { + if (chunk.status !== PENDING) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODEL; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + // This is unfortunate that we're reading this eagerly if + // we already have listeners attached since they might no + // longer be rendered or might not be the highest pri. + initializeModelChunk(resolvedChunk); // The status might have changed after initialization. + + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +function resolveModuleChunk(chunk, value) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODULE; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + initializeModuleChunk(resolvedChunk); + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +var initializingChunk = null; +var initializingChunkBlockedModel = null; + +function initializeModelChunk(chunk) { + var prevChunk = initializingChunk; + var prevBlocked = initializingChunkBlockedModel; + initializingChunk = chunk; + initializingChunkBlockedModel = null; + + try { + var value = parseModel(chunk._response, chunk.value); + + if (initializingChunkBlockedModel !== null && initializingChunkBlockedModel.deps > 0) { + initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved. + // We have to go the BLOCKED state until they're resolved. + + var blockedChunk = chunk; + blockedChunk.status = BLOCKED; + blockedChunk.value = null; + blockedChunk.reason = null; + } else { + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } finally { + initializingChunk = prevChunk; + initializingChunkBlockedModel = prevBlocked; + } +} + +function initializeModuleChunk(chunk) { + try { + var value = requireModule(chunk.value); + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } +} // Report that any missing chunks in the model is now going to throw this +// error upon read. Also notify any pending promises. + + +function reportGlobalError(response, error) { + response._chunks.forEach(function (chunk) { + // If this chunk was already resolved or errored, it won't + // trigger an error but if it wasn't then we need to + // because we won't be getting any new data to resolve it. + if (chunk.status === PENDING) { + triggerErrorOnChunk(chunk, error); + } + }); +} + +function createElement(type, key, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: null, + props: props, + // Record the component responsible for creating this element. + _owner: null + }; + + { + // We don't really need to add any of these but keeping them for good measure. + // Unfortunately, _store is enumerable in jest matchers so for equality to + // work, I need to keep it or make _store non-enumerable in the other file. + element._store = {}; + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: true // This element has already been validated on the server. + + }); + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: null + }); + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: null + }); + } + + return element; +} + +function createLazyChunkWrapper(chunk) { + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: chunk, + _init: readChunk + }; + return lazyType; +} + +function getChunk(response, id) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunk = createPendingChunk(response); + chunks.set(id, chunk); + } + + return chunk; +} + +function createModelResolver(chunk, parentObject, key) { + var blocked; + + if (initializingChunkBlockedModel) { + blocked = initializingChunkBlockedModel; + blocked.deps++; + } else { + blocked = initializingChunkBlockedModel = { + deps: 1, + value: null + }; + } + + return function (value) { + parentObject[key] = value; + blocked.deps--; + + if (blocked.deps === 0) { + if (chunk.status !== BLOCKED) { + return; + } + + var resolveListeners = chunk.value; + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = blocked.value; + + if (resolveListeners !== null) { + wakeChunk(resolveListeners, blocked.value); + } + } + }; +} + +function createModelReject(chunk) { + return function (error) { + return triggerErrorOnChunk(chunk, error); + }; +} + +function createServerReferenceProxy(response, metaData) { + var callServer = response._callServer; + + var proxy = function () { + // $FlowFixMe[method-unbinding] + var args = Array.prototype.slice.call(arguments); + var p = metaData.bound; + + if (!p) { + return callServer(metaData.id, args); + } + + if (p.status === INITIALIZED) { + var bound = p.value; + return callServer(metaData.id, bound.concat(args)); + } // Since this is a fake Promise whose .then doesn't chain, we have to wrap it. + // TODO: Remove the wrapper once that's fixed. + + + return Promise.resolve(p).then(function (bound) { + return callServer(metaData.id, bound.concat(args)); + }); + }; + + registerServerReference(proxy, metaData); + return proxy; +} + +function getOutlinedModel(response, id) { + var chunk = getChunk(response, id); + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + { + return chunk.value; + } + // We always encode it first in the stream so it won't be pending. + + default: + throw chunk.reason; + } +} + +function parseModelString(response, parentObject, key, value) { + if (value[0] === '$') { + if (value === '$') { + // A very common symbol. + return REACT_ELEMENT_TYPE; + } + + switch (value[1]) { + case '$': + { + // This was an escaped string value. + return value.slice(1); + } + + case 'L': + { + // Lazy node + var id = parseInt(value.slice(2), 16); + var chunk = getChunk(response, id); // We create a React.lazy wrapper around any lazy values. + // When passed into React, we'll know how to suspend on this. + + return createLazyChunkWrapper(chunk); + } + + case '@': + { + // Promise + var _id = parseInt(value.slice(2), 16); + + var _chunk = getChunk(response, _id); + + return _chunk; + } + + case 'S': + { + // Symbol + return Symbol.for(value.slice(2)); + } + + case 'P': + { + // Server Context Provider + return getOrCreateServerContext(value.slice(2)).Provider; + } + + case 'F': + { + // Server Reference + var _id2 = parseInt(value.slice(2), 16); + + var metadata = getOutlinedModel(response, _id2); + return createServerReferenceProxy(response, metadata); + } + + case 'Q': + { + // Map + var _id3 = parseInt(value.slice(2), 16); + + var data = getOutlinedModel(response, _id3); + return new Map(data); + } + + case 'W': + { + // Set + var _id4 = parseInt(value.slice(2), 16); + + var _data = getOutlinedModel(response, _id4); + + return new Set(_data); + } + + case 'I': + { + // $Infinity + return Infinity; + } + + case '-': + { + // $-0 or $-Infinity + if (value === '$-0') { + return -0; + } else { + return -Infinity; + } + } + + case 'N': + { + // $NaN + return NaN; + } + + case 'u': + { + // matches "$undefined" + // Special encoding for `undefined` which can't be serialized as JSON otherwise. + return undefined; + } + + case 'D': + { + // Date + return new Date(Date.parse(value.slice(2))); + } + + case 'n': + { + // BigInt + return BigInt(value.slice(2)); + } + + default: + { + // We assume that anything else is a reference ID. + var _id5 = parseInt(value.slice(1), 16); + + var _chunk2 = getChunk(response, _id5); + + switch (_chunk2.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk2); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(_chunk2); + break; + } // The status might have changed after initialization. + + + switch (_chunk2.status) { + case INITIALIZED: + return _chunk2.value; + + case PENDING: + case BLOCKED: + var parentChunk = initializingChunk; + + _chunk2.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); + + return null; + + default: + throw _chunk2.reason; + } + } + } + } + + return value; +} + +function parseModelTuple(response, value) { + var tuple = value; + + if (tuple[0] === REACT_ELEMENT_TYPE) { + // TODO: Consider having React just directly accept these arrays as elements. + // Or even change the ReactElement type to be an array. + return createElement(tuple[1], tuple[2], tuple[3]); + } + + return value; +} + +function missingCall() { + throw new Error('Trying to call a function from "use server" but the callServer option ' + 'was not implemented in your router runtime.'); +} + +function createResponse(bundlerConfig, moduleLoading, callServer, nonce) { + var chunks = new Map(); + var response = { + _bundlerConfig: bundlerConfig, + _moduleLoading: moduleLoading, + _callServer: callServer !== undefined ? callServer : missingCall, + _nonce: nonce, + _chunks: chunks, + _stringDecoder: createStringDecoder(), + _fromJSON: null, + _rowState: 0, + _rowID: 0, + _rowTag: 0, + _rowLength: 0, + _buffer: [] + }; // Don't inline this call because it causes closure to outline the call above. + + response._fromJSON = createFromJSONCallback(response); + return response; +} + +function resolveModel(response, id, model) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createResolvedModelChunk(response, model)); + } else { + resolveModelChunk(chunk, model); + } +} + +function resolveText(response, id, text) { + var chunks = response._chunks; // We assume that we always reference large strings after they've been + // emitted. + + chunks.set(id, createInitializedTextChunk(response, text)); +} + +function resolveBuffer(response, id, buffer) { + var chunks = response._chunks; // We assume that we always reference buffers after they've been emitted. + + chunks.set(id, createInitializedBufferChunk(response, buffer)); +} + +function resolveModule(response, id, model) { + var chunks = response._chunks; + var chunk = chunks.get(id); + var clientReferenceMetadata = parseModel(response, model); + var clientReference = resolveClientReference(response._bundlerConfig, clientReferenceMetadata); + prepareDestinationForModule(response._moduleLoading, response._nonce, clientReferenceMetadata); // TODO: Add an option to encode modules that are lazy loaded. + // For now we preload all modules as early as possible since it's likely + // that we'll need them. + + var promise = preloadModule(clientReference); + + if (promise) { + var blockedChunk; + + if (!chunk) { + // Technically, we should just treat promise as the chunk in this + // case. Because it'll just behave as any other promise. + blockedChunk = createBlockedChunk(response); + chunks.set(id, blockedChunk); + } else { + // This can't actually happen because we don't have any forward + // references to modules. + blockedChunk = chunk; + blockedChunk.status = BLOCKED; + } + + promise.then(function () { + return resolveModuleChunk(blockedChunk, clientReference); + }, function (error) { + return triggerErrorOnChunk(blockedChunk, error); + }); + } else { + if (!chunk) { + chunks.set(id, createResolvedModuleChunk(response, clientReference)); + } else { + // This can't actually happen because we don't have any forward + // references to modules. + resolveModuleChunk(chunk, clientReference); + } + } +} + +function resolveErrorDev(response, id, digest, message, stack) { + + + var error = new Error(message || 'An error occurred in the Server Components render but no message was provided'); + error.stack = stack; + error.digest = digest; + var errorWithDigest = error; + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createErrorChunk(response, errorWithDigest)); + } else { + triggerErrorOnChunk(chunk, errorWithDigest); + } +} + +function resolvePostponeDev(response, id, reason, stack) { + + + var error = new Error(reason || ''); + var postponeInstance = error; + postponeInstance.$$typeof = REACT_POSTPONE_TYPE; + postponeInstance.stack = stack; + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createErrorChunk(response, postponeInstance)); + } else { + triggerErrorOnChunk(chunk, postponeInstance); + } +} + +function resolveHint(response, code, model) { + var hintModel = parseModel(response, model); + dispatchHint(code, hintModel); +} + +function mergeBuffer(buffer, lastChunk) { + var l = buffer.length; // Count the bytes we'll need + + var byteLength = lastChunk.length; + + for (var i = 0; i < l; i++) { + byteLength += buffer[i].byteLength; + } // Allocate enough contiguous space + + + var result = new Uint8Array(byteLength); + var offset = 0; // Copy all the buffers into it. + + for (var _i = 0; _i < l; _i++) { + var chunk = buffer[_i]; + result.set(chunk, offset); + offset += chunk.byteLength; + } + + result.set(lastChunk, offset); + return result; +} + +function resolveTypedArray(response, id, buffer, lastChunk, constructor, bytesPerElement) { + // If the view fits into one original buffer, we just reuse that buffer instead of + // copying it out to a separate copy. This means that it's not always possible to + // transfer these values to other threads without copying first since they may + // share array buffer. For this to work, it must also have bytes aligned to a + // multiple of a size of the type. + var chunk = buffer.length === 0 && lastChunk.byteOffset % bytesPerElement === 0 ? lastChunk : mergeBuffer(buffer, lastChunk); // TODO: The transfer protocol of RSC is little-endian. If the client isn't little-endian + // we should convert it instead. In practice big endian isn't really Web compatible so it's + // somewhat safe to assume that browsers aren't going to run it, but maybe there's some SSR + // server that's affected. + + var view = new constructor(chunk.buffer, chunk.byteOffset, chunk.byteLength / bytesPerElement); + resolveBuffer(response, id, view); +} + +function processFullRow(response, id, tag, buffer, chunk) { + { + switch (tag) { + case 65 + /* "A" */ + : + // We must always clone to extract it into a separate buffer instead of just a view. + resolveBuffer(response, id, mergeBuffer(buffer, chunk).buffer); + return; + + case 67 + /* "C" */ + : + resolveTypedArray(response, id, buffer, chunk, Int8Array, 1); + return; + + case 99 + /* "c" */ + : + resolveBuffer(response, id, buffer.length === 0 ? chunk : mergeBuffer(buffer, chunk)); + return; + + case 85 + /* "U" */ + : + resolveTypedArray(response, id, buffer, chunk, Uint8ClampedArray, 1); + return; + + case 83 + /* "S" */ + : + resolveTypedArray(response, id, buffer, chunk, Int16Array, 2); + return; + + case 115 + /* "s" */ + : + resolveTypedArray(response, id, buffer, chunk, Uint16Array, 2); + return; + + case 76 + /* "L" */ + : + resolveTypedArray(response, id, buffer, chunk, Int32Array, 4); + return; + + case 108 + /* "l" */ + : + resolveTypedArray(response, id, buffer, chunk, Uint32Array, 4); + return; + + case 70 + /* "F" */ + : + resolveTypedArray(response, id, buffer, chunk, Float32Array, 4); + return; + + case 68 + /* "D" */ + : + resolveTypedArray(response, id, buffer, chunk, Float64Array, 8); + return; + + case 78 + /* "N" */ + : + resolveTypedArray(response, id, buffer, chunk, BigInt64Array, 8); + return; + + case 109 + /* "m" */ + : + resolveTypedArray(response, id, buffer, chunk, BigUint64Array, 8); + return; + + case 86 + /* "V" */ + : + resolveTypedArray(response, id, buffer, chunk, DataView, 1); + return; + } + } + + var stringDecoder = response._stringDecoder; + var row = ''; + + for (var i = 0; i < buffer.length; i++) { + row += readPartialStringChunk(stringDecoder, buffer[i]); + } + + row += readFinalStringChunk(stringDecoder, chunk); + + switch (tag) { + case 73 + /* "I" */ + : + { + resolveModule(response, id, row); + return; + } + + case 72 + /* "H" */ + : + { + var code = row[0]; + resolveHint(response, code, row.slice(1)); + return; + } + + case 69 + /* "E" */ + : + { + var errorInfo = JSON.parse(row); + + { + resolveErrorDev(response, id, errorInfo.digest, errorInfo.message, errorInfo.stack); + } + + return; + } + + case 84 + /* "T" */ + : + { + resolveText(response, id, row); + return; + } + + case 80 + /* "P" */ + : + { + { + { + var postponeInfo = JSON.parse(row); + resolvePostponeDev(response, id, postponeInfo.reason, postponeInfo.stack); + } + + return; + } + } + // Fallthrough + + default: + /* """ "{" "[" "t" "f" "n" "0" - "9" */ + { + // We assume anything else is JSON. + resolveModel(response, id, row); + return; + } + } +} + +function processBinaryChunk(response, chunk) { + var i = 0; + var rowState = response._rowState; + var rowID = response._rowID; + var rowTag = response._rowTag; + var rowLength = response._rowLength; + var buffer = response._buffer; + var chunkLength = chunk.length; + + while (i < chunkLength) { + var lastIdx = -1; + + switch (rowState) { + case ROW_ID: + { + var byte = chunk[i++]; + + if (byte === 58 + /* ":" */ + ) { + // Finished the rowID, next we'll parse the tag. + rowState = ROW_TAG; + } else { + rowID = rowID << 4 | (byte > 96 ? byte - 87 : byte - 48); + } + + continue; + } + + case ROW_TAG: + { + var resolvedRowTag = chunk[i]; + + if (resolvedRowTag === 84 + /* "T" */ + || (resolvedRowTag === 65 + /* "A" */ + || resolvedRowTag === 67 + /* "C" */ + || resolvedRowTag === 99 + /* "c" */ + || resolvedRowTag === 85 + /* "U" */ + || resolvedRowTag === 83 + /* "S" */ + || resolvedRowTag === 115 + /* "s" */ + || resolvedRowTag === 76 + /* "L" */ + || resolvedRowTag === 108 + /* "l" */ + || resolvedRowTag === 70 + /* "F" */ + || resolvedRowTag === 68 + /* "D" */ + || resolvedRowTag === 78 + /* "N" */ + || resolvedRowTag === 109 + /* "m" */ + || resolvedRowTag === 86) + /* "V" */ + ) { + rowTag = resolvedRowTag; + rowState = ROW_LENGTH; + i++; + } else if (resolvedRowTag > 64 && resolvedRowTag < 91 + /* "A"-"Z" */ + ) { + rowTag = resolvedRowTag; + rowState = ROW_CHUNK_BY_NEWLINE; + i++; + } else { + rowTag = 0; + rowState = ROW_CHUNK_BY_NEWLINE; // This was an unknown tag so it was probably part of the data. + } + + continue; + } + + case ROW_LENGTH: + { + var _byte = chunk[i++]; + + if (_byte === 44 + /* "," */ + ) { + // Finished the rowLength, next we'll buffer up to that length. + rowState = ROW_CHUNK_BY_LENGTH; + } else { + rowLength = rowLength << 4 | (_byte > 96 ? _byte - 87 : _byte - 48); + } + + continue; + } + + case ROW_CHUNK_BY_NEWLINE: + { + // We're looking for a newline + lastIdx = chunk.indexOf(10 + /* "\n" */ + , i); + break; + } + + case ROW_CHUNK_BY_LENGTH: + { + // We're looking for the remaining byte length + lastIdx = i + rowLength; + + if (lastIdx > chunk.length) { + lastIdx = -1; + } + + break; + } + } + + var offset = chunk.byteOffset + i; + + if (lastIdx > -1) { + // We found the last chunk of the row + var length = lastIdx - i; + var lastChunk = new Uint8Array(chunk.buffer, offset, length); + processFullRow(response, rowID, rowTag, buffer, lastChunk); // Reset state machine for a new row + + i = lastIdx; + + if (rowState === ROW_CHUNK_BY_NEWLINE) { + // If we're trailing by a newline we need to skip it. + i++; + } + + rowState = ROW_ID; + rowTag = 0; + rowID = 0; + rowLength = 0; + buffer.length = 0; + } else { + // The rest of this row is in a future chunk. We stash the rest of the + // current chunk until we can process the full row. + var _length = chunk.byteLength - i; + + var remainingSlice = new Uint8Array(chunk.buffer, offset, _length); + buffer.push(remainingSlice); // Update how many bytes we're still waiting for. If we're looking for + // a newline, this doesn't hurt since we'll just ignore it. + + rowLength -= remainingSlice.byteLength; + break; + } + } + + response._rowState = rowState; + response._rowID = rowID; + response._rowTag = rowTag; + response._rowLength = rowLength; +} + +function parseModel(response, json) { + return JSON.parse(json, response._fromJSON); +} + +function createFromJSONCallback(response) { + // $FlowFixMe[missing-this-annot] + return function (key, value) { + if (typeof value === 'string') { + // We can't use .bind here because we need the "this" value. + return parseModelString(response, this, key, value); + } + + if (typeof value === 'object' && value !== null) { + return parseModelTuple(response, value); + } + + return value; + }; +} + +function close(response) { + // In case there are any remaining unresolved chunks, they won't + // be resolved now. So we need to issue an error to those. + // Ideally we should be able to early bail out if we kept a + // ref count of pending chunks. + reportGlobalError(response, new Error('Connection closed.')); +} + +function noServerCall() { + throw new Error('Server Functions cannot be called during initial render. ' + 'This would create a fetch waterfall. Try to use a Server Component ' + 'to pass data to Client Components instead.'); +} + +function createServerReference(id, callServer) { + return createServerReference$1(id, noServerCall); +} + +function createFromNodeStream(stream, ssrManifest, options) { + var response = createResponse(ssrManifest.moduleMap, ssrManifest.moduleLoading, noServerCall, options && typeof options.nonce === 'string' ? options.nonce : undefined); + stream.on('data', function (chunk) { + processBinaryChunk(response, chunk); + }); + stream.on('error', function (error) { + reportGlobalError(response, error); + }); + stream.on('end', function () { + return close(response); + }); + return getRoot(response); +} + +exports.createFromNodeStream = createFromNodeStream; +exports.createServerReference = createServerReference; + })(); +} diff --git a/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-client.node.unbundled.production.min.js b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-client.node.unbundled.production.min.js new file mode 100644 index 0000000000000..1d6a01a9d268d --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-client.node.unbundled.production.min.js @@ -0,0 +1,41 @@ +/** + * @license React + * react-server-dom-turbopack-client.node.unbundled.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var n=require("util"),q=require("react-dom"),r=require("react"),u={stream:!0};function v(a,b){var d=a[b[0]];if(a=d[b[2]])d=a.name;else{a=d["*"];if(!a)throw Error('Could not find the module "'+b[0]+'" in the React SSR Manifest. This is probably a bug in the React Server Components bundler.');d=b[2]}return{specifier:a.specifier,name:d,async:4===b.length}}var w=new Map; +function x(a){var b=w.get(a.specifier);if(b)return"fulfilled"===b.status?null:b;var d=import(a.specifier);a.async&&(d=d.then(function(c){return c.default}));d.then(function(c){var e=d;e.status="fulfilled";e.value=c},function(c){var e=d;e.status="rejected";e.reason=c});w.set(a.specifier,d);return d} +function z(a,b,d){if(null!==a)for(var c=0;cf?(l=f,f=3,h++):(l=0,f=3); +continue;case 2:m=e[h++];44===m?f=4:g=g<<4|(96e.length&&(m=-1)}var p=e.byteOffset+h;if(-1 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +function scheduleWork(callback) { + callback(); +} +var VIEW_SIZE = 512; +var currentView = null; +var writtenBytes = 0; +function beginWriting(destination) { + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; +} +function writeChunk(destination, chunk) { + if (chunk.byteLength === 0) { + return; + } + + if (chunk.byteLength > VIEW_SIZE) { + { + if (precomputedChunkSet.has(chunk)) { + error('A large precomputed chunk was passed to writeChunk without being copied.' + ' Large chunks get enqueued directly and are not copied. This is incompatible with precomputed chunks because you cannot enqueue the same precomputed chunk twice.' + ' Use "cloneChunk" to make a copy of this large precomputed chunk before writing it. This is a bug in React.'); + } + } // this chunk may overflow a single view which implies it was not + // one that is cached by the streaming renderer. We will enqueu + // it directly and expect it is not re-used + + + if (writtenBytes > 0) { + destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes)); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + destination.enqueue(chunk); + return; + } + + var bytesToWrite = chunk; + var allowableBytes = currentView.length - writtenBytes; + + if (allowableBytes < bytesToWrite.byteLength) { + // this chunk would overflow the current view. We enqueue a full view + // and start a new view with the remaining chunk + if (allowableBytes === 0) { + // the current view is already full, send it + destination.enqueue(currentView); + } else { + // fill up the current view and apply the remaining chunk bytes + // to a new view. + currentView.set(bytesToWrite.subarray(0, allowableBytes), writtenBytes); // writtenBytes += allowableBytes; // this can be skipped because we are going to immediately reset the view + + destination.enqueue(currentView); + bytesToWrite = bytesToWrite.subarray(allowableBytes); + } + + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + currentView.set(bytesToWrite, writtenBytes); + writtenBytes += bytesToWrite.byteLength; +} +function writeChunkAndReturn(destination, chunk) { + writeChunk(destination, chunk); // in web streams there is no backpressure so we can alwas write more + + return true; +} +function completeWriting(destination) { + if (currentView && writtenBytes > 0) { + destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes)); + currentView = null; + writtenBytes = 0; + } +} +function close$1(destination) { + destination.close(); +} +var textEncoder = new TextEncoder(); +function stringToChunk(content) { + return textEncoder.encode(content); +} +var precomputedChunkSet = new Set() ; +function typedArrayToBinaryChunk(content) { + // Convert any non-Uint8Array array to Uint8Array. We could avoid this for Uint8Arrays. + // If we passed through this straight to enqueue we wouldn't have to convert it but since + // we need to copy the buffer in that case, we need to convert it to copy it. + // When we copy it into another array using set() it needs to be a Uint8Array. + var buffer = new Uint8Array(content.buffer, content.byteOffset, content.byteLength); // We clone large chunks so that we can transfer them when we write them. + // Others get copied into the target buffer. + + return content.byteLength > VIEW_SIZE ? buffer.slice() : buffer; +} +function byteLengthOfChunk(chunk) { + return chunk.byteLength; +} +function byteLengthOfBinaryChunk(chunk) { + return chunk.byteLength; +} +function closeWithError(destination, error) { + // $FlowFixMe[method-unbinding] + if (typeof destination.error === 'function') { + // $FlowFixMe[incompatible-call]: This is an Error object or the destination accepts other types. + destination.error(error); + } else { + // Earlier implementations doesn't support this method. In that environment you're + // supposed to throw from a promise returned but we don't return a promise in our + // approach. We could fork this implementation but this is environment is an edge + // case to begin with. It's even less common to run this in an older environment. + // Even then, this is not where errors are supposed to happen and they get reported + // to a global callback in addition to this anyway. So it's fine just to close this. + destination.close(); + } +} + +// eslint-disable-next-line no-unused-vars +var CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference'); +var SERVER_REFERENCE_TAG = Symbol.for('react.server.reference'); +function isClientReference(reference) { + return reference.$$typeof === CLIENT_REFERENCE_TAG; +} +function isServerReference(reference) { + return reference.$$typeof === SERVER_REFERENCE_TAG; +} +function registerClientReference(proxyImplementation, id, exportName) { + return registerClientReferenceImpl(proxyImplementation, id + '#' + exportName, false); +} + +function registerClientReferenceImpl(proxyImplementation, id, async) { + return Object.defineProperties(proxyImplementation, { + $$typeof: { + value: CLIENT_REFERENCE_TAG + }, + $$id: { + value: id + }, + $$async: { + value: async + } + }); +} // $FlowFixMe[method-unbinding] + + +var FunctionBind = Function.prototype.bind; // $FlowFixMe[method-unbinding] + +var ArraySlice = Array.prototype.slice; + +function bind() { + // $FlowFixMe[unsupported-syntax] + var newFn = FunctionBind.apply(this, arguments); + + if (this.$$typeof === SERVER_REFERENCE_TAG) { + var args = ArraySlice.call(arguments, 1); + newFn.$$typeof = SERVER_REFERENCE_TAG; + newFn.$$id = this.$$id; + newFn.$$bound = this.$$bound ? this.$$bound.concat(args) : args; + } + + return newFn; +} + +function registerServerReference(reference, id, exportName) { + return Object.defineProperties(reference, { + $$typeof: { + value: SERVER_REFERENCE_TAG + }, + $$id: { + value: exportName === null ? id : id + '#' + exportName + }, + $$bound: { + value: null + }, + bind: { + value: bind + } + }); +} +var PROMISE_PROTOTYPE = Promise.prototype; +var deepProxyHandlers = { + get: function (target, name, receiver) { + switch (name) { + // These names are read by the Flight runtime if you end up using the exports object. + case '$$typeof': + // These names are a little too common. We should probably have a way to + // have the Flight runtime extract the inner target instead. + return target.$$typeof; + + case '$$id': + return target.$$id; + + case '$$async': + return target.$$async; + + case 'name': + return target.name; + + case 'displayName': + return undefined; + // We need to special case this because createElement reads it if we pass this + // reference. + + case 'defaultProps': + return undefined; + // Avoid this attempting to be serialized. + + case 'toJSON': + return undefined; + + case Symbol.toPrimitive: + // $FlowFixMe[prop-missing] + return Object.prototype[Symbol.toPrimitive]; + + case 'Provider': + throw new Error("Cannot render a Client Context Provider on the Server. " + "Instead, you can export a Client Component wrapper " + "that itself renders a Client Context Provider."); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var expression = String(target.name) + '.' + String(name); + throw new Error("Cannot access " + expression + " on the server. " + 'You cannot dot into a client module from a server component. ' + 'You can only pass the imported name through.'); + }, + set: function () { + throw new Error('Cannot assign to a client module from a server module.'); + } +}; +var proxyHandlers = { + get: function (target, name, receiver) { + switch (name) { + // These names are read by the Flight runtime if you end up using the exports object. + case '$$typeof': + return target.$$typeof; + + case '$$id': + return target.$$id; + + case '$$async': + return target.$$async; + + case 'name': + return target.name; + // We need to special case this because createElement reads it if we pass this + // reference. + + case 'defaultProps': + return undefined; + // Avoid this attempting to be serialized. + + case 'toJSON': + return undefined; + + case Symbol.toPrimitive: + // $FlowFixMe[prop-missing] + return Object.prototype[Symbol.toPrimitive]; + + case '__esModule': + // Something is conditionally checking which export to use. We'll pretend to be + // an ESM compat module but then we'll check again on the client. + var moduleId = target.$$id; + target.default = registerClientReferenceImpl(function () { + throw new Error("Attempted to call the default export of " + moduleId + " from the server " + "but it's on the client. It's not possible to invoke a client function from " + "the server, it can only be rendered as a Component or passed to props of a " + "Client Component."); + }, target.$$id + '#', target.$$async); + return true; + + case 'then': + if (target.then) { + // Use a cached value + return target.then; + } + + if (!target.$$async) { + // If this module is expected to return a Promise (such as an AsyncModule) then + // we should resolve that with a client reference that unwraps the Promise on + // the client. + var clientReference = registerClientReferenceImpl({}, target.$$id, true); + var proxy = new Proxy(clientReference, proxyHandlers); // Treat this as a resolved Promise for React's use() + + target.status = 'fulfilled'; + target.value = proxy; + var then = target.then = registerClientReferenceImpl(function then(resolve, reject) { + // Expose to React. + return Promise.resolve(resolve(proxy)); + }, // If this is not used as a Promise but is treated as a reference to a `.then` + // export then we should treat it as a reference to that name. + target.$$id + '#then', false); + return then; + } else { + // Since typeof .then === 'function' is a feature test we'd continue recursing + // indefinitely if we return a function. Instead, we return an object reference + // if we check further. + return undefined; + } + + } + + var cachedReference = target[name]; + + if (!cachedReference) { + var reference = registerClientReferenceImpl(function () { + throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion + "Attempted to call " + String(name) + "() from the server but " + String(name) + " is on the client. " + "It's not possible to invoke a client function from the server, it can " + "only be rendered as a Component or passed to props of a Client Component."); + }, target.$$id + '#' + name, target.$$async); + Object.defineProperty(reference, 'name', { + value: name + }); + cachedReference = target[name] = new Proxy(reference, deepProxyHandlers); + } + + return cachedReference; + }, + getPrototypeOf: function (target) { + // Pretend to be a Promise in case anyone asks. + return PROMISE_PROTOTYPE; + }, + set: function () { + throw new Error('Cannot assign to a client module from a server module.'); + } +}; +function createClientModuleProxy(moduleId) { + var clientReference = registerClientReferenceImpl({}, // Represents the whole Module object instead of a particular import. + moduleId, false); + return new Proxy(clientReference, proxyHandlers); +} + +function getClientReferenceKey(reference) { + return reference.$$async ? reference.$$id + '#async' : reference.$$id; +} +function resolveClientReferenceMetadata(config, clientReference) { + var modulePath = clientReference.$$id; + var name = ''; + var resolvedModuleData = config[modulePath]; + + if (resolvedModuleData) { + // The potentially aliased name. + name = resolvedModuleData.name; + } else { + // We didn't find this specific export name but we might have the * export + // which contains this name as well. + // TODO: It's unfortunate that we now have to parse this string. We should + // probably go back to encoding path and name separately on the client reference. + var idx = modulePath.lastIndexOf('#'); + + if (idx !== -1) { + name = modulePath.slice(idx + 1); + resolvedModuleData = config[modulePath.slice(0, idx)]; + } + + if (!resolvedModuleData) { + throw new Error('Could not find the module "' + modulePath + '" in the React Client Manifest. ' + 'This is probably a bug in the React Server Components bundler.'); + } + } + + if (clientReference.$$async === true) { + return [resolvedModuleData.id, resolvedModuleData.chunks, name, 1]; + } else { + return [resolvedModuleData.id, resolvedModuleData.chunks, name]; + } +} +function getServerReferenceId(config, serverReference) { + return serverReference.$$id; +} +function getServerReferenceBoundArguments(config, serverReference) { + return serverReference.$$bound; +} + +var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +var ReactDOMFlightServerDispatcher = { + prefetchDNS: prefetchDNS, + preconnect: preconnect, + preload: preload, + preloadModule: preloadModule$1, + preinitStyle: preinitStyle, + preinitScript: preinitScript, + preinitModuleScript: preinitModuleScript +}; + +function prefetchDNS(href) { + { + if (typeof href === 'string' && href) { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'D|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + emitHint(request, 'D', href); + } + } + } +} + +function preconnect(href, crossOrigin) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = "C|" + (crossOrigin == null ? 'null' : crossOrigin) + "|" + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + + if (typeof crossOrigin === 'string') { + emitHint(request, 'C', [href, crossOrigin]); + } else { + emitHint(request, 'C', href); + } + } + } + } +} + +function preload(href, as, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'L'; + + if (as === 'image' && options) { + key += getImagePreloadKey(href, options.imageSrcSet, options.imageSizes); + } else { + key += "[" + as + "]" + href; + } + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + emitHint(request, 'L', [href, as, trimmed]); + } else { + emitHint(request, 'L', [href, as]); + } + } + } + } +} + +function preloadModule$1(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'm|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + return emitHint(request, 'm', [href, trimmed]); + } else { + return emitHint(request, 'm', href); + } + } + } + } +} + +function preinitStyle(href, precedence, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'S|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + return emitHint(request, 'S', [href, typeof precedence === 'string' ? precedence : 0, trimmed]); + } else if (typeof precedence === 'string') { + return emitHint(request, 'S', [href, precedence]); + } else { + return emitHint(request, 'S', href); + } + } + } + } +} + +function preinitScript(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'X|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + return emitHint(request, 'X', [href, trimmed]); + } else { + return emitHint(request, 'X', href); + } + } + } + } +} + +function preinitModuleScript(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'M|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + return emitHint(request, 'M', [href, trimmed]); + } else { + return emitHint(request, 'M', href); + } + } + } + } +} // Flight normally encodes undefined as a special character however for directive option +// arguments we don't want to send unnecessary keys and bloat the payload so we create a +// trimmed object which omits any keys with null or undefined values. +// This is only typesafe because these option objects have entirely optional fields where +// null and undefined represent the same thing as no property. + + +function trimOptions(options) { + if (options == null) return null; + var hasProperties = false; + var trimmed = {}; + + for (var key in options) { + if (options[key] != null) { + hasProperties = true; + trimmed[key] = options[key]; + } + } + + return hasProperties ? trimmed : null; +} + +function getImagePreloadKey(href, imageSrcSet, imageSizes) { + var uniquePart = ''; + + if (typeof imageSrcSet === 'string' && imageSrcSet !== '') { + uniquePart += '[' + imageSrcSet + ']'; + + if (typeof imageSizes === 'string') { + uniquePart += '[' + imageSizes + ']'; + } + } else { + uniquePart += '[][]' + href; + } + + return "[image]" + uniquePart; +} + +var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher; +function prepareHostDispatcher() { + ReactDOMCurrentDispatcher.current = ReactDOMFlightServerDispatcher; +} // Used to distinguish these contexts from ones used in other renderers. +// small, smaller than how we encode undefined, and is unambiguous. We could use +// a different tuple structure to encode this instead but this makes the runtime +// cost cheaper by eliminating a type checks in more positions. +// prettier-ignore + +function createHints() { + return new Set(); +} + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); +var REACT_MEMO_CACHE_SENTINEL = Symbol.for('react.memo_cache_sentinel'); +var REACT_POSTPONE_TYPE = Symbol.for('react.postpone'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +var rendererSigil; + +{ + // Use this to detect multiple renderers using the same context + rendererSigil = {}; +} // Used to store the parent path of all context overrides in a shared linked list. +// Forming a reverse tree. +// The structure of a context snapshot is an implementation of this file. +// Currently, it's implemented as tracking the current active node. + + +var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. +// This global (actually thread local) state represents what state all those "current", +// fields are currently in. + +var currentActiveSnapshot = null; + +function popNode(prev) { + { + prev.context._currentValue = prev.parentValue; + } +} + +function pushNode(next) { + { + next.context._currentValue = next.value; + } +} + +function popToNearestCommonAncestor(prev, next) { + if (prev === next) ; else { + popNode(prev); + var parentPrev = prev.parent; + var parentNext = next.parent; + + if (parentPrev === null) { + if (parentNext !== null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + } else { + if (parentNext === null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + + popToNearestCommonAncestor(parentPrev, parentNext); // On the way back, we push the new ones that weren't common. + + pushNode(next); + } + } +} + +function popAllPrevious(prev) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev !== null) { + popAllPrevious(parentPrev); + } +} + +function pushAllNext(next) { + var parentNext = next.parent; + + if (parentNext !== null) { + pushAllNext(parentNext); + } + + pushNode(next); +} + +function popPreviousToCommonLevel(prev, next) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (parentPrev.depth === next.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(parentPrev, next); + } else { + // We must still be deeper. + popPreviousToCommonLevel(parentPrev, next); + } +} + +function popNextToCommonLevel(prev, next) { + var parentNext = next.parent; + + if (parentNext === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (prev.depth === parentNext.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(prev, parentNext); + } else { + // We must still be deeper. + popNextToCommonLevel(prev, parentNext); + } + + pushNode(next); +} // Perform context switching to the new snapshot. +// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by +// updating all the context's current values. That way reads, always just read the current value. +// At the cost of updating contexts even if they're never read by this subtree. + + +function switchContext(newSnapshot) { + // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. + // We also need to update any new contexts that are now on the stack with the deepest value. + // The easiest way to update new contexts is to just reapply them in reverse order from the + // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack + // for that. Therefore this algorithm is recursive. + // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. + // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. + // 3) Then we reapply new contexts on the way back up the stack. + var prev = currentActiveSnapshot; + var next = newSnapshot; + + if (prev !== next) { + if (prev === null) { + // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev. + pushAllNext(next); + } else if (next === null) { + popAllPrevious(prev); + } else if (prev.depth === next.depth) { + popToNearestCommonAncestor(prev, next); + } else if (prev.depth > next.depth) { + popPreviousToCommonLevel(prev, next); + } else { + popNextToCommonLevel(prev, next); + } + + currentActiveSnapshot = next; + } +} +function pushProvider(context, nextValue) { + var prevValue; + + { + prevValue = context._currentValue; + context._currentValue = nextValue; + + { + if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } + + context._currentRenderer = rendererSigil; + } + } + + var prevNode = currentActiveSnapshot; + var newNode = { + parent: prevNode, + depth: prevNode === null ? 0 : prevNode.depth + 1, + context: context, + parentValue: prevValue, + value: nextValue + }; + currentActiveSnapshot = newNode; + return newNode; +} +function popProvider() { + var prevSnapshot = currentActiveSnapshot; + + if (prevSnapshot === null) { + throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.'); + } + + { + var value = prevSnapshot.parentValue; + + if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) { + prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue; + } else { + prevSnapshot.context._currentValue = value; + } + } + + return currentActiveSnapshot = prevSnapshot.parent; +} +function getActiveContext() { + return currentActiveSnapshot; +} +function readContext$1(context) { + var value = context._currentValue ; + return value; +} + +// Corresponds to ReactFiberWakeable and ReactFizzWakeable modules. Generally, +// changes to one module should be reflected in the others. +// TODO: Rename this module and the corresponding Fiber one to "Thenable" +// instead of "Wakeable". Or some other more appropriate name. +// An error that is thrown (e.g. by `use`) to trigger Suspense. If we +// detect this is caught by userspace, we'll log a warning in development. +var SuspenseException = new Error("Suspense Exception: This is not a real error! It's an implementation " + 'detail of `use` to interrupt the current render. You must either ' + 'rethrow it immediately, or move the `use` call outside of the ' + '`try/catch` block. Capturing without rethrowing will lead to ' + 'unexpected behavior.\n\n' + 'To handle async errors, wrap your component in an error boundary, or ' + "call the promise's `.catch` method and pass the result to `use`"); +function createThenableState() { + // The ThenableState is created the first time a component suspends. If it + // suspends again, we'll reuse the same state. + return []; +} + +function noop() {} + +function trackUsedThenable(thenableState, thenable, index) { + var previous = thenableState[index]; + + if (previous === undefined) { + thenableState.push(thenable); + } else { + if (previous !== thenable) { + // Reuse the previous thenable, and drop the new one. We can assume + // they represent the same value, because components are idempotent. + // Avoid an unhandled rejection errors for the Promises that we'll + // intentionally ignore. + thenable.then(noop, noop); + thenable = previous; + } + } // We use an expando to track the status and result of a thenable so that we + // can synchronously unwrap the value. Think of this as an extension of the + // Promise API, or a custom interface that is a superset of Thenable. + // + // If the thenable doesn't have a status, set it to "pending" and attach + // a listener that will update its status and result when it resolves. + + + switch (thenable.status) { + case 'fulfilled': + { + var fulfilledValue = thenable.value; + return fulfilledValue; + } + + case 'rejected': + { + var rejectedError = thenable.reason; + throw rejectedError; + } + + default: + { + if (typeof thenable.status === 'string') ; else { + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); // Check one more time in case the thenable resolved synchronously + + switch (thenable.status) { + case 'fulfilled': + { + var fulfilledThenable = thenable; + return fulfilledThenable.value; + } + + case 'rejected': + { + var rejectedThenable = thenable; + throw rejectedThenable.reason; + } + } + } // Suspend. + // + // Throwing here is an implementation detail that allows us to unwind the + // call stack. But we shouldn't allow it to leak into userspace. Throw an + // opaque placeholder value instead of the actual thenable. If it doesn't + // get captured by the work loop, log a warning, because that means + // something in userspace must have caught it. + + + suspendedThenable = thenable; + throw SuspenseException; + } + } +} // This is used to track the actual thenable that suspended so it can be +// passed to the rest of the Suspense implementation — which, for historical +// reasons, expects to receive a thenable. + +var suspendedThenable = null; +function getSuspendedThenable() { + // This is called right after `use` suspends by throwing an exception. `use` + // throws an opaque value instead of the thenable itself so that it can't be + // caught in userspace. Then the work loop accesses the actual thenable using + // this function. + if (suspendedThenable === null) { + throw new Error('Expected a suspended thenable. This is a bug in React. Please file ' + 'an issue.'); + } + + var thenable = suspendedThenable; + suspendedThenable = null; + return thenable; +} + +var currentRequest$1 = null; +var thenableIndexCounter = 0; +var thenableState = null; +function prepareToUseHooksForRequest(request) { + currentRequest$1 = request; +} +function resetHooksForRequest() { + currentRequest$1 = null; +} +function prepareToUseHooksForComponent(prevThenableState) { + thenableIndexCounter = 0; + thenableState = prevThenableState; +} +function getThenableStateAfterSuspending() { + var state = thenableState; + thenableState = null; + return state; +} + +function readContext(context) { + { + if (context.$$typeof !== REACT_SERVER_CONTEXT_TYPE) { + if (isClientReference(context)) { + error('Cannot read a Client Context from a Server Component.'); + } else { + error('Only createServerContext is supported in Server Components.'); + } + } + + if (currentRequest$1 === null) { + error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); + } + } + + return readContext$1(context); +} + +var HooksDispatcher = { + useMemo: function (nextCreate) { + return nextCreate(); + }, + useCallback: function (callback) { + return callback; + }, + useDebugValue: function () {}, + useDeferredValue: unsupportedHook, + useTransition: unsupportedHook, + readContext: readContext, + useContext: readContext, + useReducer: unsupportedHook, + useRef: unsupportedHook, + useState: unsupportedHook, + useInsertionEffect: unsupportedHook, + useLayoutEffect: unsupportedHook, + useImperativeHandle: unsupportedHook, + useEffect: unsupportedHook, + useId: useId, + useSyncExternalStore: unsupportedHook, + useCacheRefresh: function () { + return unsupportedRefresh; + }, + useMemoCache: function (size) { + var data = new Array(size); + + for (var i = 0; i < size; i++) { + data[i] = REACT_MEMO_CACHE_SENTINEL; + } + + return data; + }, + use: use +}; + +function unsupportedHook() { + throw new Error('This Hook is not supported in Server Components.'); +} + +function unsupportedRefresh() { + throw new Error('Refreshing the cache is not supported in Server Components.'); +} + +function useId() { + if (currentRequest$1 === null) { + throw new Error('useId can only be used while React is rendering'); + } + + var id = currentRequest$1.identifierCount++; // use 'S' for Flight components to distinguish from 'R' and 'r' in Fizz/Client + + return ':' + currentRequest$1.identifierPrefix + 'S' + id.toString(32) + ':'; +} + +function use(usable) { + if (usable !== null && typeof usable === 'object' || typeof usable === 'function') { + // $FlowFixMe[method-unbinding] + if (typeof usable.then === 'function') { + // This is a thenable. + var thenable = usable; // Track the position of the thenable within this fiber. + + var index = thenableIndexCounter; + thenableIndexCounter += 1; + + if (thenableState === null) { + thenableState = createThenableState(); + } + + return trackUsedThenable(thenableState, thenable, index); + } else if (usable.$$typeof === REACT_SERVER_CONTEXT_TYPE) { + var context = usable; + return readContext(context); + } + } + + { + if (isClientReference(usable)) { + error('Cannot use() an already resolved Client Reference.'); + } + } // eslint-disable-next-line react-internal/safe-string-coercion + + + throw new Error('An unsupported type was passed to use(): ' + String(usable)); +} + +function createSignal() { + return new AbortController().signal; +} + +function resolveCache() { + var request = resolveRequest(); + + if (request) { + return getCache(request); + } + + return new Map(); +} + +var DefaultCacheDispatcher = { + getCacheSignal: function () { + var cache = resolveCache(); + var entry = cache.get(createSignal); + + if (entry === undefined) { + entry = createSignal(); + cache.set(createSignal, entry); + } + + return entry; + }, + getCacheForType: function (resourceType) { + var cache = resolveCache(); + var entry = cache.get(resourceType); + + if (entry === undefined) { + entry = resourceType(); // TODO: Warn if undefined? + + cache.set(resourceType, entry); + } + + return entry; + } +}; + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +// in case they error. + +var jsxPropsParents = new WeakMap(); +var jsxChildrenParents = new WeakMap(); + +function isObjectPrototype(object) { + if (!object) { + return false; + } + + var ObjectPrototype = Object.prototype; + + if (object === ObjectPrototype) { + return true; + } // It might be an object from a different Realm which is + // still just a plain simple object. + + + if (Object.getPrototypeOf(object)) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + if (!(names[i] in ObjectPrototype)) { + return false; + } + } + + return true; +} + +function isSimpleObject(object) { + if (!isObjectPrototype(Object.getPrototypeOf(object))) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + var descriptor = Object.getOwnPropertyDescriptor(object, names[i]); + + if (!descriptor) { + return false; + } + + if (!descriptor.enumerable) { + if ((names[i] === 'key' || names[i] === 'ref') && typeof descriptor.get === 'function') { + // React adds key and ref getters to props objects to issue warnings. + // Those getters will not be transferred to the client, but that's ok, + // so we'll special case them. + continue; + } + + return false; + } + } + + return true; +} +function objectName(object) { + // $FlowFixMe[method-unbinding] + var name = Object.prototype.toString.call(object); + return name.replace(/^\[object (.*)\]$/, function (m, p0) { + return p0; + }); +} + +function describeKeyForErrorMessage(key) { + var encodedKey = JSON.stringify(key); + return '"' + key + '"' === encodedKey ? key : encodedKey; +} + +function describeValueForErrorMessage(value) { + switch (typeof value) { + case 'string': + { + return JSON.stringify(value.length <= 10 ? value : value.slice(0, 10) + '...'); + } + + case 'object': + { + if (isArray(value)) { + return '[...]'; + } + + var name = objectName(value); + + if (name === 'Object') { + return '{...}'; + } + + return name; + } + + case 'function': + return 'function'; + + default: + // eslint-disable-next-line react-internal/safe-string-coercion + return String(value); + } +} + +function describeElementType(type) { + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeElementType(type.render); + + case REACT_MEMO_TYPE: + return describeElementType(type.type); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeElementType(init(payload)); + } catch (x) {} + } + } + } + + return ''; +} + +function describeObjectForErrorMessage(objectOrArray, expandedName) { + var objKind = objectName(objectOrArray); + + if (objKind !== 'Object' && objKind !== 'Array') { + return objKind; + } + + var str = ''; + var start = -1; + var length = 0; + + if (isArray(objectOrArray)) { + if (jsxChildrenParents.has(objectOrArray)) { + // Print JSX Children + var type = jsxChildrenParents.get(objectOrArray); + str = '<' + describeElementType(type) + '>'; + var array = objectOrArray; + + for (var i = 0; i < array.length; i++) { + var value = array[i]; + var substr = void 0; + + if (typeof value === 'string') { + substr = value; + } else if (typeof value === 'object' && value !== null) { + substr = '{' + describeObjectForErrorMessage(value) + '}'; + } else { + substr = '{' + describeValueForErrorMessage(value) + '}'; + } + + if ('' + i === expandedName) { + start = str.length; + length = substr.length; + str += substr; + } else if (substr.length < 15 && str.length + substr.length < 40) { + str += substr; + } else { + str += '{...}'; + } + } + + str += ''; + } else { + // Print Array + str = '['; + var _array = objectOrArray; + + for (var _i = 0; _i < _array.length; _i++) { + if (_i > 0) { + str += ', '; + } + + var _value = _array[_i]; + + var _substr = void 0; + + if (typeof _value === 'object' && _value !== null) { + _substr = describeObjectForErrorMessage(_value); + } else { + _substr = describeValueForErrorMessage(_value); + } + + if ('' + _i === expandedName) { + start = str.length; + length = _substr.length; + str += _substr; + } else if (_substr.length < 10 && str.length + _substr.length < 40) { + str += _substr; + } else { + str += '...'; + } + } + + str += ']'; + } + } else { + if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) { + str = '<' + describeElementType(objectOrArray.type) + '/>'; + } else if (jsxPropsParents.has(objectOrArray)) { + // Print JSX + var _type = jsxPropsParents.get(objectOrArray); + + str = '<' + (describeElementType(_type) || '...'); + var object = objectOrArray; + var names = Object.keys(object); + + for (var _i2 = 0; _i2 < names.length; _i2++) { + str += ' '; + var name = names[_i2]; + str += describeKeyForErrorMessage(name) + '='; + var _value2 = object[name]; + + var _substr2 = void 0; + + if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) { + _substr2 = describeObjectForErrorMessage(_value2); + } else { + _substr2 = describeValueForErrorMessage(_value2); + } + + if (typeof _value2 !== 'string') { + _substr2 = '{' + _substr2 + '}'; + } + + if (name === expandedName) { + start = str.length; + length = _substr2.length; + str += _substr2; + } else if (_substr2.length < 10 && str.length + _substr2.length < 40) { + str += _substr2; + } else { + str += '...'; + } + } + + str += '>'; + } else { + // Print Object + str = '{'; + var _object = objectOrArray; + + var _names = Object.keys(_object); + + for (var _i3 = 0; _i3 < _names.length; _i3++) { + if (_i3 > 0) { + str += ', '; + } + + var _name = _names[_i3]; + str += describeKeyForErrorMessage(_name) + ': '; + var _value3 = _object[_name]; + + var _substr3 = void 0; + + if (typeof _value3 === 'object' && _value3 !== null) { + _substr3 = describeObjectForErrorMessage(_value3); + } else { + _substr3 = describeValueForErrorMessage(_value3); + } + + if (_name === expandedName) { + start = str.length; + length = _substr3.length; + str += _substr3; + } else if (_substr3.length < 10 && str.length + _substr3.length < 40) { + str += _substr3; + } else { + str += '...'; + } + } + + str += '}'; + } + } + + if (expandedName === undefined) { + return str; + } + + if (start > -1 && length > 0) { + var highlight = ' '.repeat(start) + '^'.repeat(length); + return '\n ' + str + '\n ' + highlight; + } + + return '\n ' + str; +} + +var ContextRegistry = ReactSharedInternals.ContextRegistry; +function getOrCreateServerContext(globalName) { + if (!ContextRegistry[globalName]) { + var context = { + $$typeof: REACT_SERVER_CONTEXT_TYPE, + // As a workaround to support multiple concurrent renderers, we categorize + // some renderers as primary and others as secondary. We only expect + // there to be two concurrent renderers at most: React Native (primary) and + // Fabric (secondary); React DOM (primary) and React ART (secondary). + // Secondary renderers store their context values on separate fields. + _currentValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + _currentValue2: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + _defaultValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + // Used to track how many concurrent renderers this context currently + // supports within in a single renderer. Such as parallel server rendering. + _threadCount: 0, + // These are circular + Provider: null, + Consumer: null, + _globalName: globalName + }; + context.Provider = { + $$typeof: REACT_PROVIDER_TYPE, + _context: context + }; + + { + var hasWarnedAboutUsingConsumer; + context._currentRenderer = null; + context._currentRenderer2 = null; + Object.defineProperties(context, { + Consumer: { + get: function () { + if (!hasWarnedAboutUsingConsumer) { + error('Consumer pattern is not supported by ReactServerContext'); + + hasWarnedAboutUsingConsumer = true; + } + + return null; + } + } + }); + } + + ContextRegistry[globalName] = context; + } + + return ContextRegistry[globalName]; +} + +var stringify = JSON.stringify; // Serializable values +// Thenable + +var PENDING$1 = 0; +var COMPLETED = 1; +var ABORTED = 3; +var ERRORED$1 = 4; +var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; +var ReactCurrentCache = ReactSharedInternals.ReactCurrentCache; + +function defaultErrorHandler(error) { + console['error'](error); // Don't transform to our wrapper +} + +function defaultPostponeHandler(reason) {// Noop +} + +var OPEN = 0; +var CLOSING = 1; +var CLOSED = 2; +function createRequest(model, bundlerConfig, onError, context, identifierPrefix, onPostpone) { + if (ReactCurrentCache.current !== null && ReactCurrentCache.current !== DefaultCacheDispatcher) { + throw new Error('Currently React only supports one RSC renderer at a time.'); + } + + prepareHostDispatcher(); + ReactCurrentCache.current = DefaultCacheDispatcher; + var abortSet = new Set(); + var pingedTasks = []; + var hints = createHints(); + var request = { + status: OPEN, + flushScheduled: false, + fatalError: null, + destination: null, + bundlerConfig: bundlerConfig, + cache: new Map(), + nextChunkId: 0, + pendingChunks: 0, + hints: hints, + abortableTasks: abortSet, + pingedTasks: pingedTasks, + completedImportChunks: [], + completedHintChunks: [], + completedRegularChunks: [], + completedErrorChunks: [], + writtenSymbols: new Map(), + writtenClientReferences: new Map(), + writtenServerReferences: new Map(), + writtenProviders: new Map(), + identifierPrefix: identifierPrefix || '', + identifierCount: 1, + onError: onError === undefined ? defaultErrorHandler : onError, + onPostpone: onPostpone === undefined ? defaultPostponeHandler : onPostpone, + // $FlowFixMe[missing-this-annot] + toJSON: function (key, value) { + return resolveModelToJSON(request, this, key, value); + } + }; + request.pendingChunks++; + var rootContext = createRootContext(context); + var rootTask = createTask(request, model, rootContext, abortSet); + pingedTasks.push(rootTask); + return request; +} +var currentRequest = null; +function resolveRequest() { + if (currentRequest) return currentRequest; + + return null; +} + +function createRootContext(reqContext) { + return importServerContexts(reqContext); +} + +var POP = {}; + +function serializeThenable(request, thenable) { + request.pendingChunks++; + var newTask = createTask(request, null, getActiveContext(), request.abortableTasks); + + switch (thenable.status) { + case 'fulfilled': + { + // We have the resolved value, we can go ahead and schedule it for serialization. + newTask.model = thenable.value; + pingTask(request, newTask); + return newTask.id; + } + + case 'rejected': + { + var x = thenable.reason; + + if (typeof x === 'object' && x !== null && x.$$typeof === REACT_POSTPONE_TYPE) { + var postponeInstance = x; + logPostpone(request, postponeInstance.message); + emitPostponeChunk(request, newTask.id, postponeInstance); + } else { + var digest = logRecoverableError(request, x); + emitErrorChunk(request, newTask.id, digest, x); + } + + return newTask.id; + } + + default: + { + if (typeof thenable.status === 'string') { + // Only instrument the thenable if the status if not defined. If + // it's defined, but an unknown value, assume it's been instrumented by + // some custom userspace implementation. We treat it as "pending". + break; + } + + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); + break; + } + } + + thenable.then(function (value) { + newTask.model = value; + pingTask(request, newTask); + }, function (reason) { + newTask.status = ERRORED$1; + request.abortableTasks.delete(newTask); // TODO: We should ideally do this inside performWork so it's scheduled + + var digest = logRecoverableError(request, reason); + emitErrorChunk(request, newTask.id, digest, reason); + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + }); + return newTask.id; +} + +function emitHint(request, code, model) { + emitHintChunk(request, code, model); + enqueueFlush(request); +} +function getHints(request) { + return request.hints; +} +function getCache(request) { + return request.cache; +} + +function readThenable(thenable) { + if (thenable.status === 'fulfilled') { + return thenable.value; + } else if (thenable.status === 'rejected') { + throw thenable.reason; + } + + throw thenable; +} + +function createLazyWrapperAroundWakeable(wakeable) { + // This is a temporary fork of the `use` implementation until we accept + // promises everywhere. + var thenable = wakeable; + + switch (thenable.status) { + case 'fulfilled': + case 'rejected': + break; + + default: + { + if (typeof thenable.status === 'string') { + // Only instrument the thenable if the status if not defined. If + // it's defined, but an unknown value, assume it's been instrumented by + // some custom userspace implementation. We treat it as "pending". + break; + } + + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); + break; + } + } + + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: thenable, + _init: readThenable + }; + return lazyType; +} + +function attemptResolveElement(request, type, key, ref, props, prevThenableState) { + if (ref !== null && ref !== undefined) { + // When the ref moves to the regular props object this will implicitly + // throw for functions. We could probably relax it to a DEV warning for other + // cases. + throw new Error('Refs cannot be used in Server Components, nor passed to Client Components.'); + } + + { + jsxPropsParents.set(props, type); + + if (typeof props.children === 'object' && props.children !== null) { + jsxChildrenParents.set(props.children, type); + } + } + + if (typeof type === 'function') { + if (isClientReference(type)) { + // This is a reference to a Client Component. + return [REACT_ELEMENT_TYPE, type, key, props]; + } // This is a server-side component. + + + prepareToUseHooksForComponent(prevThenableState); + var result = type(props); + + if (typeof result === 'object' && result !== null && typeof result.then === 'function') { + // When the return value is in children position we can resolve it immediately, + // to its value without a wrapper if it's synchronously available. + var thenable = result; + + if (thenable.status === 'fulfilled') { + return thenable.value; + } // TODO: Once we accept Promises as children on the client, we can just return + // the thenable here. + + + return createLazyWrapperAroundWakeable(result); + } + + return result; + } else if (typeof type === 'string') { + // This is a host element. E.g. HTML. + return [REACT_ELEMENT_TYPE, type, key, props]; + } else if (typeof type === 'symbol') { + if (type === REACT_FRAGMENT_TYPE) { + // For key-less fragments, we add a small optimization to avoid serializing + // it as a wrapper. + // TODO: If a key is specified, we should propagate its key to any children. + // Same as if a Server Component has a key. + return props.children; + } // This might be a built-in React component. We'll let the client decide. + // Any built-in works as long as its props are serializable. + + + return [REACT_ELEMENT_TYPE, type, key, props]; + } else if (type != null && typeof type === 'object') { + if (isClientReference(type)) { + // This is a reference to a Client Component. + return [REACT_ELEMENT_TYPE, type, key, props]; + } + + switch (type.$$typeof) { + case REACT_LAZY_TYPE: + { + var payload = type._payload; + var init = type._init; + var wrappedType = init(payload); + return attemptResolveElement(request, wrappedType, key, ref, props, prevThenableState); + } + + case REACT_FORWARD_REF_TYPE: + { + var render = type.render; + prepareToUseHooksForComponent(prevThenableState); + return render(props, undefined); + } + + case REACT_MEMO_TYPE: + { + return attemptResolveElement(request, type.type, key, ref, props, prevThenableState); + } + + case REACT_PROVIDER_TYPE: + { + pushProvider(type._context, props.value); + + { + var extraKeys = Object.keys(props).filter(function (value) { + if (value === 'children' || value === 'value') { + return false; + } + + return true; + }); + + if (extraKeys.length !== 0) { + error('ServerContext can only have a value prop and children. Found: %s', JSON.stringify(extraKeys)); + } + } + + return [REACT_ELEMENT_TYPE, type, key, // Rely on __popProvider being serialized last to pop the provider. + { + value: props.value, + children: props.children, + __pop: POP + }]; + } + } + } + + throw new Error("Unsupported Server Component type: " + describeValueForErrorMessage(type)); +} + +function pingTask(request, task) { + var pingedTasks = request.pingedTasks; + pingedTasks.push(task); + + if (pingedTasks.length === 1) { + request.flushScheduled = request.destination !== null; + scheduleWork(function () { + return performWork(request); + }); + } +} + +function createTask(request, model, context, abortSet) { + var id = request.nextChunkId++; + var task = { + id: id, + status: PENDING$1, + model: model, + context: context, + ping: function () { + return pingTask(request, task); + }, + thenableState: null + }; + abortSet.add(task); + return task; +} + +function serializeByValueID(id) { + return '$' + id.toString(16); +} + +function serializeLazyID(id) { + return '$L' + id.toString(16); +} + +function serializePromiseID(id) { + return '$@' + id.toString(16); +} + +function serializeServerReferenceID(id) { + return '$F' + id.toString(16); +} + +function serializeSymbolReference(name) { + return '$S' + name; +} + +function serializeProviderReference(name) { + return '$P' + name; +} + +function serializeNumber(number) { + if (Number.isFinite(number)) { + if (number === 0 && 1 / number === -Infinity) { + return '$-0'; + } else { + return number; + } + } else { + if (number === Infinity) { + return '$Infinity'; + } else if (number === -Infinity) { + return '$-Infinity'; + } else { + return '$NaN'; + } + } +} + +function serializeUndefined() { + return '$undefined'; +} + +function serializeDateFromDateJSON(dateJSON) { + // JSON.stringify automatically calls Date.prototype.toJSON which calls toISOString. + // We need only tack on a $D prefix. + return '$D' + dateJSON; +} + +function serializeBigInt(n) { + return '$n' + n.toString(10); +} + +function serializeRowHeader(tag, id) { + return id.toString(16) + ':' + tag; +} + +function encodeReferenceChunk(request, id, reference) { + var json = stringify(reference); + var row = id.toString(16) + ':' + json + '\n'; + return stringToChunk(row); +} + +function serializeClientReference(request, parent, key, clientReference) { + var clientReferenceKey = getClientReferenceKey(clientReference); + var writtenClientReferences = request.writtenClientReferences; + var existingId = writtenClientReferences.get(clientReferenceKey); + + if (existingId !== undefined) { + if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { + // If we're encoding the "type" of an element, we can refer + // to that by a lazy reference instead of directly since React + // knows how to deal with lazy values. This lets us suspend + // on this component rather than its parent until the code has + // loaded. + return serializeLazyID(existingId); + } + + return serializeByValueID(existingId); + } + + try { + var clientReferenceMetadata = resolveClientReferenceMetadata(request.bundlerConfig, clientReference); + request.pendingChunks++; + var importId = request.nextChunkId++; + emitImportChunk(request, importId, clientReferenceMetadata); + writtenClientReferences.set(clientReferenceKey, importId); + + if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { + // If we're encoding the "type" of an element, we can refer + // to that by a lazy reference instead of directly since React + // knows how to deal with lazy values. This lets us suspend + // on this component rather than its parent until the code has + // loaded. + return serializeLazyID(importId); + } + + return serializeByValueID(importId); + } catch (x) { + request.pendingChunks++; + var errorId = request.nextChunkId++; + var digest = logRecoverableError(request, x); + emitErrorChunk(request, errorId, digest, x); + return serializeByValueID(errorId); + } +} + +function outlineModel(request, value) { + request.pendingChunks++; + var outlinedId = request.nextChunkId++; // We assume that this object doesn't suspend, but a child might. + + emitModelChunk(request, outlinedId, value); + return outlinedId; +} + +function serializeServerReference(request, parent, key, serverReference) { + var writtenServerReferences = request.writtenServerReferences; + var existingId = writtenServerReferences.get(serverReference); + + if (existingId !== undefined) { + return serializeServerReferenceID(existingId); + } + + var bound = getServerReferenceBoundArguments(request.bundlerConfig, serverReference); + var serverReferenceMetadata = { + id: getServerReferenceId(request.bundlerConfig, serverReference), + bound: bound ? Promise.resolve(bound) : null + }; + var metadataId = outlineModel(request, serverReferenceMetadata); + writtenServerReferences.set(serverReference, metadataId); + return serializeServerReferenceID(metadataId); +} + +function serializeLargeTextString(request, text) { + request.pendingChunks += 2; + var textId = request.nextChunkId++; + var textChunk = stringToChunk(text); + var binaryLength = byteLengthOfChunk(textChunk); + var row = textId.toString(16) + ':T' + binaryLength.toString(16) + ','; + var headerChunk = stringToChunk(row); + request.completedRegularChunks.push(headerChunk, textChunk); + return serializeByValueID(textId); +} + +function serializeMap(request, map) { + var id = outlineModel(request, Array.from(map)); + return '$Q' + id.toString(16); +} + +function serializeSet(request, set) { + var id = outlineModel(request, Array.from(set)); + return '$W' + id.toString(16); +} + +function serializeTypedArray(request, tag, typedArray) { + request.pendingChunks += 2; + var bufferId = request.nextChunkId++; // TODO: Convert to little endian if that's not the server default. + + var binaryChunk = typedArrayToBinaryChunk(typedArray); + var binaryLength = byteLengthOfBinaryChunk(binaryChunk); + var row = bufferId.toString(16) + ':' + tag + binaryLength.toString(16) + ','; + var headerChunk = stringToChunk(row); + request.completedRegularChunks.push(headerChunk, binaryChunk); + return serializeByValueID(bufferId); +} + +function escapeStringValue(value) { + if (value[0] === '$') { + // We need to escape $ prefixed strings since we use those to encode + // references to IDs and as special symbol values. + return '$' + value; + } else { + return value; + } +} + +var insideContextProps = null; +var isInsideContextValue = false; + +function resolveModelToJSON(request, parent, key, value) { + // Make sure that `parent[key]` wasn't JSONified before `value` was passed to us + { + // $FlowFixMe[incompatible-use] + var originalValue = parent[key]; + + if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) { + if (objectName(originalValue) !== 'Object') { + var jsxParentType = jsxChildrenParents.get(parent); + + if (typeof jsxParentType === 'string') { + error('%s objects cannot be rendered as text children. Try formatting it using toString().%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } else { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } + } else { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props.%s', describeObjectForErrorMessage(parent, key)); + } + } + } // Special Symbols + + + switch (value) { + case REACT_ELEMENT_TYPE: + return '$'; + } + + { + if (parent[0] === REACT_ELEMENT_TYPE && parent[1] && parent[1].$$typeof === REACT_PROVIDER_TYPE && key === '3') { + insideContextProps = value; + } else if (insideContextProps === parent && key === 'value') { + isInsideContextValue = true; + } else if (insideContextProps === parent && key === 'children') { + isInsideContextValue = false; + } + } // Resolve Server Components. + + + while (typeof value === 'object' && value !== null && (value.$$typeof === REACT_ELEMENT_TYPE || value.$$typeof === REACT_LAZY_TYPE)) { + { + if (isInsideContextValue) { + error('React elements are not allowed in ServerContext'); + } + } + + try { + switch (value.$$typeof) { + case REACT_ELEMENT_TYPE: + { + // TODO: Concatenate keys of parents onto children. + var element = value; // Attempt to render the Server Component. + + value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, null); + break; + } + + case REACT_LAZY_TYPE: + { + var payload = value._payload; + var init = value._init; + value = init(payload); + break; + } + } + } catch (thrownValue) { + var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical + // reasons, the rest of the Suspense implementation expects the thrown + // value to be a thenable, because before `use` existed that was the + // (unstable) API for suspending. This implementation detail can change + // later, once we deprecate the old API in favor of `use`. + getSuspendedThenable() : thrownValue; + + if (typeof x === 'object' && x !== null) { + // $FlowFixMe[method-unbinding] + if (typeof x.then === 'function') { + // Something suspended, we'll need to create a new task and resolve it later. + request.pendingChunks++; + var newTask = createTask(request, value, getActiveContext(), request.abortableTasks); + var ping = newTask.ping; + x.then(ping, ping); + newTask.thenableState = getThenableStateAfterSuspending(); + return serializeLazyID(newTask.id); + } else if (x.$$typeof === REACT_POSTPONE_TYPE) { + // Something postponed. We'll still send everything we have up until this point. + // We'll replace this element with a lazy reference that postpones on the client. + var postponeInstance = x; + request.pendingChunks++; + var postponeId = request.nextChunkId++; + logPostpone(request, postponeInstance.message); + emitPostponeChunk(request, postponeId, postponeInstance); + return serializeLazyID(postponeId); + } + } // Something errored. We'll still send everything we have up until this point. + // We'll replace this element with a lazy reference that throws on the client + // once it gets rendered. + + + request.pendingChunks++; + var errorId = request.nextChunkId++; + var digest = logRecoverableError(request, x); + emitErrorChunk(request, errorId, digest, x); + return serializeLazyID(errorId); + } + } + + if (value === null) { + return null; + } + + if (typeof value === 'object') { + if (isClientReference(value)) { + return serializeClientReference(request, parent, key, value); // $FlowFixMe[method-unbinding] + } else if (typeof value.then === 'function') { + // We assume that any object with a .then property is a "Thenable" type, + // or a Promise type. Either of which can be represented by a Promise. + var promiseId = serializeThenable(request, value); + return serializePromiseID(promiseId); + } else if (value.$$typeof === REACT_PROVIDER_TYPE) { + var providerKey = value._context._globalName; + var writtenProviders = request.writtenProviders; + var providerId = writtenProviders.get(key); + + if (providerId === undefined) { + request.pendingChunks++; + providerId = request.nextChunkId++; + writtenProviders.set(providerKey, providerId); + emitProviderChunk(request, providerId, providerKey); + } + + return serializeByValueID(providerId); + } else if (value === POP) { + popProvider(); + + { + insideContextProps = null; + isInsideContextValue = false; + } + + return undefined; + } + + if (value instanceof Map) { + return serializeMap(request, value); + } + + if (value instanceof Set) { + return serializeSet(request, value); + } + + { + if (value instanceof ArrayBuffer) { + return serializeTypedArray(request, 'A', new Uint8Array(value)); + } + + if (value instanceof Int8Array) { + // char + return serializeTypedArray(request, 'C', value); + } + + if (value instanceof Uint8Array) { + // unsigned char + return serializeTypedArray(request, 'c', value); + } + + if (value instanceof Uint8ClampedArray) { + // unsigned clamped char + return serializeTypedArray(request, 'U', value); + } + + if (value instanceof Int16Array) { + // sort + return serializeTypedArray(request, 'S', value); + } + + if (value instanceof Uint16Array) { + // unsigned short + return serializeTypedArray(request, 's', value); + } + + if (value instanceof Int32Array) { + // long + return serializeTypedArray(request, 'L', value); + } + + if (value instanceof Uint32Array) { + // unsigned long + return serializeTypedArray(request, 'l', value); + } + + if (value instanceof Float32Array) { + // float + return serializeTypedArray(request, 'F', value); + } + + if (value instanceof Float64Array) { + // double + return serializeTypedArray(request, 'D', value); + } + + if (value instanceof BigInt64Array) { + // number + return serializeTypedArray(request, 'N', value); + } + + if (value instanceof BigUint64Array) { + // unsigned number + // We use "m" instead of "n" since JSON can start with "null" + return serializeTypedArray(request, 'm', value); + } + + if (value instanceof DataView) { + return serializeTypedArray(request, 'V', value); + } + } + + if (!isArray(value)) { + var iteratorFn = getIteratorFn(value); + + if (iteratorFn) { + return Array.from(value); + } + } + + { + if (value !== null && !isArray(value)) { + // Verify that this is a simple plain object. + if (objectName(value) !== 'Object') { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, key)); + } else if (!isSimpleObject(value)) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Classes or other objects with methods are not supported.%s', describeObjectForErrorMessage(parent, key)); + } else if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(value); + + if (symbols.length > 0) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with symbol properties like %s are not supported.%s', symbols[0].description, describeObjectForErrorMessage(parent, key)); + } + } + } + } // $FlowFixMe[incompatible-return] + + + return value; + } + + if (typeof value === 'string') { + // TODO: Maybe too clever. If we support URL there's no similar trick. + if (value[value.length - 1] === 'Z') { + // Possibly a Date, whose toJSON automatically calls toISOString + // $FlowFixMe[incompatible-use] + var _originalValue = parent[key]; + + if (_originalValue instanceof Date) { + return serializeDateFromDateJSON(value); + } + } + + if (value.length >= 1024) { + // For large strings, we encode them outside the JSON payload so that we + // don't have to double encode and double parse the strings. This can also + // be more compact in case the string has a lot of escaped characters. + return serializeLargeTextString(request, value); + } + + return escapeStringValue(value); + } + + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return serializeNumber(value); + } + + if (typeof value === 'undefined') { + return serializeUndefined(); + } + + if (typeof value === 'function') { + if (isClientReference(value)) { + return serializeClientReference(request, parent, key, value); + } + + if (isServerReference(value)) { + return serializeServerReference(request, parent, key, value); + } + + if (/^on[A-Z]/.test(key)) { + throw new Error('Event handlers cannot be passed to Client Component props.' + describeObjectForErrorMessage(parent, key) + '\nIf you need interactivity, consider converting part of this to a Client Component.'); + } else { + throw new Error('Functions cannot be passed directly to Client Components ' + 'unless you explicitly expose it by marking it with "use server".' + describeObjectForErrorMessage(parent, key)); + } + } + + if (typeof value === 'symbol') { + var writtenSymbols = request.writtenSymbols; + var existingId = writtenSymbols.get(value); + + if (existingId !== undefined) { + return serializeByValueID(existingId); + } // $FlowFixMe[incompatible-type] `description` might be undefined + + + var name = value.description; + + if (Symbol.for(name) !== value) { + throw new Error('Only global symbols received from Symbol.for(...) can be passed to Client Components. ' + ("The symbol Symbol.for(" + // $FlowFixMe[incompatible-type] `description` might be undefined + value.description + ") cannot be found among global symbols.") + describeObjectForErrorMessage(parent, key)); + } + + request.pendingChunks++; + var symbolId = request.nextChunkId++; + emitSymbolChunk(request, symbolId, name); + writtenSymbols.set(value, symbolId); + return serializeByValueID(symbolId); + } + + if (typeof value === 'bigint') { + return serializeBigInt(value); + } + + throw new Error("Type " + typeof value + " is not supported in Client Component props." + describeObjectForErrorMessage(parent, key)); +} + +function logPostpone(request, reason) { + var onPostpone = request.onPostpone; + onPostpone(reason); +} + +function logRecoverableError(request, error) { + var onError = request.onError; + var errorDigest = onError(error); + + if (errorDigest != null && typeof errorDigest !== 'string') { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead"); + } + + return errorDigest || ''; +} + +function fatalError(request, error) { + // This is called outside error handling code such as if an error happens in React internals. + if (request.destination !== null) { + request.status = CLOSED; + closeWithError(request.destination, error); + } else { + request.status = CLOSING; + request.fatalError = error; + } +} + +function emitPostponeChunk(request, id, postponeInstance) { + var row; + + { + var reason = ''; + var stack = ''; + + try { + // eslint-disable-next-line react-internal/safe-string-coercion + reason = String(postponeInstance.message); // eslint-disable-next-line react-internal/safe-string-coercion + + stack = String(postponeInstance.stack); + } catch (x) {} + + row = serializeRowHeader('P', id) + stringify({ + reason: reason, + stack: stack + }) + '\n'; + } + + var processedChunk = stringToChunk(row); + request.completedErrorChunks.push(processedChunk); +} + +function emitErrorChunk(request, id, digest, error) { + var errorInfo; + + { + var message; + var stack = ''; + + try { + if (error instanceof Error) { + // eslint-disable-next-line react-internal/safe-string-coercion + message = String(error.message); // eslint-disable-next-line react-internal/safe-string-coercion + + stack = String(error.stack); + } else { + message = 'Error: ' + error; + } + } catch (x) { + message = 'An error occurred but serializing the error message failed.'; + } + + errorInfo = { + digest: digest, + message: message, + stack: stack + }; + } + + var row = serializeRowHeader('E', id) + stringify(errorInfo) + '\n'; + var processedChunk = stringToChunk(row); + request.completedErrorChunks.push(processedChunk); +} + +function emitImportChunk(request, id, clientReferenceMetadata) { + // $FlowFixMe[incompatible-type] stringify can return null + var json = stringify(clientReferenceMetadata); + var row = serializeRowHeader('I', id) + json + '\n'; + var processedChunk = stringToChunk(row); + request.completedImportChunks.push(processedChunk); +} + +function emitHintChunk(request, code, model) { + var json = stringify(model); + var id = request.nextChunkId++; + var row = serializeRowHeader('H' + code, id) + json + '\n'; + var processedChunk = stringToChunk(row); + request.completedHintChunks.push(processedChunk); +} + +function emitSymbolChunk(request, id, name) { + var symbolReference = serializeSymbolReference(name); + var processedChunk = encodeReferenceChunk(request, id, symbolReference); + request.completedImportChunks.push(processedChunk); +} + +function emitProviderChunk(request, id, contextName) { + var contextReference = serializeProviderReference(contextName); + var processedChunk = encodeReferenceChunk(request, id, contextReference); + request.completedRegularChunks.push(processedChunk); +} + +function emitModelChunk(request, id, model) { + // $FlowFixMe[incompatible-type] stringify can return null + var json = stringify(model, request.toJSON); + var row = id.toString(16) + ':' + json + '\n'; + var processedChunk = stringToChunk(row); + request.completedRegularChunks.push(processedChunk); +} + +function retryTask(request, task) { + if (task.status !== PENDING$1) { + // We completed this by other means before we had a chance to retry it. + return; + } + + switchContext(task.context); + + try { + var value = task.model; + + if (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) { + // TODO: Concatenate keys of parents onto children. + var element = value; // When retrying a component, reuse the thenableState from the + // previous attempt. + + var prevThenableState = task.thenableState; // Attempt to render the Server Component. + // Doing this here lets us reuse this same task if the next component + // also suspends. + + task.model = value; + value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, prevThenableState); // Successfully finished this component. We're going to keep rendering + // using the same task, but we reset its thenable state before continuing. + + task.thenableState = null; // Keep rendering and reuse the same task. This inner loop is separate + // from the render above because we don't need to reset the thenable state + // until the next time something suspends and retries. + + while (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) { + // TODO: Concatenate keys of parents onto children. + var nextElement = value; + task.model = value; + value = attemptResolveElement(request, nextElement.type, nextElement.key, nextElement.ref, nextElement.props, null); + } + } + + emitModelChunk(request, task.id, value); + request.abortableTasks.delete(task); + task.status = COMPLETED; + } catch (thrownValue) { + var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical + // reasons, the rest of the Suspense implementation expects the thrown + // value to be a thenable, because before `use` existed that was the + // (unstable) API for suspending. This implementation detail can change + // later, once we deprecate the old API in favor of `use`. + getSuspendedThenable() : thrownValue; + + if (typeof x === 'object' && x !== null) { + // $FlowFixMe[method-unbinding] + if (typeof x.then === 'function') { + // Something suspended again, let's pick it back up later. + var ping = task.ping; + x.then(ping, ping); + task.thenableState = getThenableStateAfterSuspending(); + return; + } else if (x.$$typeof === REACT_POSTPONE_TYPE) { + request.abortableTasks.delete(task); + task.status = ERRORED$1; + var postponeInstance = x; + logPostpone(request, postponeInstance.message); + emitPostponeChunk(request, task.id, postponeInstance); + return; + } + } + + request.abortableTasks.delete(task); + task.status = ERRORED$1; + var digest = logRecoverableError(request, x); + emitErrorChunk(request, task.id, digest, x); + } +} + +function performWork(request) { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = HooksDispatcher; + var prevRequest = currentRequest; + currentRequest = request; + prepareToUseHooksForRequest(request); + + try { + var pingedTasks = request.pingedTasks; + request.pingedTasks = []; + + for (var i = 0; i < pingedTasks.length; i++) { + var task = pingedTasks[i]; + retryTask(request, task); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } finally { + ReactCurrentDispatcher.current = prevDispatcher; + resetHooksForRequest(); + currentRequest = prevRequest; + } +} + +function abortTask(task, request, errorId) { + task.status = ABORTED; // Instead of emitting an error per task.id, we emit a model that only + // has a single value referencing the error. + + var ref = serializeByValueID(errorId); + var processedChunk = encodeReferenceChunk(request, task.id, ref); + request.completedErrorChunks.push(processedChunk); +} + +function flushCompletedChunks(request, destination) { + beginWriting(); + + try { + // We emit module chunks first in the stream so that + // they can be preloaded as early as possible. + var importsChunks = request.completedImportChunks; + var i = 0; + + for (; i < importsChunks.length; i++) { + request.pendingChunks--; + var chunk = importsChunks[i]; + var keepWriting = writeChunkAndReturn(destination, chunk); + + if (!keepWriting) { + request.destination = null; + i++; + break; + } + } + + importsChunks.splice(0, i); // Next comes hints. + + var hintChunks = request.completedHintChunks; + i = 0; + + for (; i < hintChunks.length; i++) { + var _chunk = hintChunks[i]; + + var _keepWriting = writeChunkAndReturn(destination, _chunk); + + if (!_keepWriting) { + request.destination = null; + i++; + break; + } + } + + hintChunks.splice(0, i); // Next comes model data. + + var regularChunks = request.completedRegularChunks; + i = 0; + + for (; i < regularChunks.length; i++) { + request.pendingChunks--; + var _chunk2 = regularChunks[i]; + + var _keepWriting2 = writeChunkAndReturn(destination, _chunk2); + + if (!_keepWriting2) { + request.destination = null; + i++; + break; + } + } + + regularChunks.splice(0, i); // Finally, errors are sent. The idea is that it's ok to delay + // any error messages and prioritize display of other parts of + // the page. + + var errorChunks = request.completedErrorChunks; + i = 0; + + for (; i < errorChunks.length; i++) { + request.pendingChunks--; + var _chunk3 = errorChunks[i]; + + var _keepWriting3 = writeChunkAndReturn(destination, _chunk3); + + if (!_keepWriting3) { + request.destination = null; + i++; + break; + } + } + + errorChunks.splice(0, i); + } finally { + request.flushScheduled = false; + completeWriting(destination); + } + + if (request.pendingChunks === 0) { + // We're done. + close$1(destination); + } +} + +function startWork(request) { + request.flushScheduled = request.destination !== null; + + { + scheduleWork(function () { + return performWork(request); + }); + } +} + +function enqueueFlush(request) { + if (request.flushScheduled === false && // If there are pinged tasks we are going to flush anyway after work completes + request.pingedTasks.length === 0 && // If there is no destination there is nothing we can flush to. A flush will + // happen when we start flowing again + request.destination !== null) { + var destination = request.destination; + request.flushScheduled = true; + scheduleWork(function () { + return flushCompletedChunks(request, destination); + }); + } +} + +function startFlowing(request, destination) { + if (request.status === CLOSING) { + request.status = CLOSED; + closeWithError(destination, request.fatalError); + return; + } + + if (request.status === CLOSED) { + return; + } + + if (request.destination !== null) { + // We're already flowing. + return; + } + + request.destination = destination; + + try { + flushCompletedChunks(request, destination); + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} + +function abort(request, reason) { + try { + var abortableTasks = request.abortableTasks; + + if (abortableTasks.size > 0) { + // We have tasks to abort. We'll emit one error row and then emit a reference + // to that row from every row that's still remaining. + var error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason; + var digest = logRecoverableError(request, error); + request.pendingChunks++; + var errorId = request.nextChunkId++; + emitErrorChunk(request, errorId, digest, error); + abortableTasks.forEach(function (task) { + return abortTask(task, request, errorId); + }); + abortableTasks.clear(); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} + +function importServerContexts(contexts) { + if (contexts) { + var prevContext = getActiveContext(); + switchContext(rootContextSnapshot); + + for (var i = 0; i < contexts.length; i++) { + var _contexts$i = contexts[i], + name = _contexts$i[0], + value = _contexts$i[1]; + var context = getOrCreateServerContext(name); + pushProvider(context, value); + } + + var importedContext = getActiveContext(); + switchContext(prevContext); + return importedContext; + } + + return rootContextSnapshot; +} + +// This is the parsed shape of the wire format which is why it is +// condensed to only the essentialy information +var ID = 0; +var CHUNKS = 1; +var NAME = 2; // export const ASYNC = 3; +// This logic is correct because currently only include the 4th tuple member +// when the module is async. If that changes we will need to actually assert +// the value is true. We don't index into the 4th slot because flow does not +// like the potential out of bounds access + +function isAsyncImport(metadata) { + return metadata.length === 4; +} + +function resolveServerReference(bundlerConfig, id) { + var name = ''; + var resolvedModuleData = bundlerConfig[id]; + + if (resolvedModuleData) { + // The potentially aliased name. + name = resolvedModuleData.name; + } else { + // We didn't find this specific export name but we might have the * export + // which contains this name as well. + // TODO: It's unfortunate that we now have to parse this string. We should + // probably go back to encoding path and name separately on the client reference. + var idx = id.lastIndexOf('#'); + + if (idx !== -1) { + name = id.slice(idx + 1); + resolvedModuleData = bundlerConfig[id.slice(0, idx)]; + } + + if (!resolvedModuleData) { + throw new Error('Could not find the module "' + id + '" in the React Server Manifest. ' + 'This is probably a bug in the React Server Components bundler.'); + } + } // TODO: This needs to return async: true if it's an async module. + + + return [resolvedModuleData.id, resolvedModuleData.chunks, name]; +} // The chunk cache contains all the chunks we've preloaded so far. +// If they're still pending they're a thenable. This map also exists +// in Turbopack but unfortunately it's not exposed so we have to +// replicate it in user space. null means that it has already loaded. + +var chunkCache = new Map(); + +function requireAsyncModule(id) { + // We've already loaded all the chunks. We can require the module. + var promise = __turbopack_require__(id); + + if (typeof promise.then !== 'function') { + // This wasn't a promise after all. + return null; + } else if (promise.status === 'fulfilled') { + // This module was already resolved earlier. + return null; + } else { + // Instrument the Promise to stash the result. + promise.then(function (value) { + var fulfilledThenable = promise; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = value; + }, function (reason) { + var rejectedThenable = promise; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = reason; + }); + return promise; + } +} + +function ignoreReject() {// We rely on rejected promises to be handled by another listener. +} // Start preloading the modules since we might need them soon. +// This function doesn't suspend. + + +function preloadModule(metadata) { + var chunks = metadata[CHUNKS]; + var promises = []; + + for (var i = 0; i < chunks.length; i++) { + var chunkFilename = chunks[i]; + var entry = chunkCache.get(chunkFilename); + + if (entry === undefined) { + var thenable = loadChunk(chunkFilename); + promises.push(thenable); // $FlowFixMe[method-unbinding] + + var resolve = chunkCache.set.bind(chunkCache, chunkFilename, null); + thenable.then(resolve, ignoreReject); + chunkCache.set(chunkFilename, thenable); + } else if (entry !== null) { + promises.push(entry); + } + } + + if (isAsyncImport(metadata)) { + if (promises.length === 0) { + return requireAsyncModule(metadata[ID]); + } else { + return Promise.all(promises).then(function () { + return requireAsyncModule(metadata[ID]); + }); + } + } else if (promises.length > 0) { + return Promise.all(promises); + } else { + return null; + } +} // Actually require the module or suspend if it's not yet ready. +// Increase priority if necessary. + +function requireModule(metadata) { + var moduleExports = __turbopack_require__(metadata[ID]); + + if (isAsyncImport(metadata)) { + if (typeof moduleExports.then !== 'function') ; else if (moduleExports.status === 'fulfilled') { + // This Promise should've been instrumented by preloadModule. + moduleExports = moduleExports.value; + } else { + throw moduleExports.reason; + } + } + + if (metadata[NAME] === '*') { + // This is a placeholder value that represents that the caller imported this + // as a CommonJS module as is. + return moduleExports; + } + + if (metadata[NAME] === '') { + // This is a placeholder value that represents that the caller accessed the + // default property of this if it was an ESM interop module. + return moduleExports.__esModule ? moduleExports.default : moduleExports; + } + + return moduleExports[metadata[NAME]]; +} + +function loadChunk(filename) { + return __turbopack_load__(filename); +} + +// The server acts as a Client of itself when resolving Server References. +var PENDING = 'pending'; +var BLOCKED = 'blocked'; +var RESOLVED_MODEL = 'resolved_model'; +var INITIALIZED = 'fulfilled'; +var ERRORED = 'rejected'; // $FlowFixMe[missing-this-annot] + +function Chunk(status, value, reason, response) { + this.status = status; + this.value = value; + this.reason = reason; + this._response = response; +} // We subclass Promise.prototype so that we get other methods like .catch + + +Chunk.prototype = Object.create(Promise.prototype); // TODO: This doesn't return a new Promise chain unlike the real .then + +Chunk.prototype.then = function (resolve, reject) { + var chunk = this; // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + resolve(chunk.value); + break; + + case PENDING: + case BLOCKED: + if (resolve) { + if (chunk.value === null) { + chunk.value = []; + } + + chunk.value.push(resolve); + } + + if (reject) { + if (chunk.reason === null) { + chunk.reason = []; + } + + chunk.reason.push(reject); + } + + break; + + default: + reject(chunk.reason); + break; + } +}; + +function getRoot(response) { + var chunk = getChunk(response, 0); + return chunk; +} + +function createPendingChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(PENDING, null, null, response); +} + +function wakeChunk(listeners, value) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + listener(value); + } +} + +function triggerErrorOnChunk(chunk, error) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var listeners = chunk.reason; + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + + if (listeners !== null) { + wakeChunk(listeners, error); + } +} + +function createResolvedModelChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODEL, value, null, response); +} + +function bindArgs$1(fn, args) { + return fn.bind.apply(fn, [null].concat(args)); +} + +function loadServerReference$1(response, id, bound, parentChunk, parentObject, key) { + var serverReference = resolveServerReference(response._bundlerConfig, id); // We expect most servers to not really need this because you'd just have all + // the relevant modules already loaded but it allows for lazy loading of code + // if needed. + + var preloadPromise = preloadModule(serverReference); + var promise; + + if (bound) { + promise = Promise.all([bound, preloadPromise]).then(function (_ref) { + var args = _ref[0]; + return bindArgs$1(requireModule(serverReference), args); + }); + } else { + if (preloadPromise) { + promise = Promise.resolve(preloadPromise).then(function () { + return requireModule(serverReference); + }); + } else { + // Synchronously available + return requireModule(serverReference); + } + } + + promise.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); // We need a placeholder value that will be replaced later. + + return null; +} + +var initializingChunk = null; +var initializingChunkBlockedModel = null; + +function initializeModelChunk(chunk) { + var prevChunk = initializingChunk; + var prevBlocked = initializingChunkBlockedModel; + initializingChunk = chunk; + initializingChunkBlockedModel = null; + + try { + var value = JSON.parse(chunk.value, chunk._response._fromJSON); + + if (initializingChunkBlockedModel !== null && initializingChunkBlockedModel.deps > 0) { + initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved. + // We have to go the BLOCKED state until they're resolved. + + var blockedChunk = chunk; + blockedChunk.status = BLOCKED; + blockedChunk.value = null; + blockedChunk.reason = null; + } else { + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } finally { + initializingChunk = prevChunk; + initializingChunkBlockedModel = prevBlocked; + } +} // Report that any missing chunks in the model is now going to throw this +// error upon read. Also notify any pending promises. + + +function reportGlobalError(response, error) { + response._chunks.forEach(function (chunk) { + // If this chunk was already resolved or errored, it won't + // trigger an error but if it wasn't then we need to + // because we won't be getting any new data to resolve it. + if (chunk.status === PENDING) { + triggerErrorOnChunk(chunk, error); + } + }); +} + +function getChunk(response, id) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + var prefix = response._prefix; + var key = prefix + id; // Check if we have this field in the backing store already. + + var backingEntry = response._formData.get(key); + + if (backingEntry != null) { + // We assume that this is a string entry for now. + chunk = createResolvedModelChunk(response, backingEntry); + } else { + // We're still waiting on this entry to stream in. + chunk = createPendingChunk(response); + } + + chunks.set(id, chunk); + } + + return chunk; +} + +function createModelResolver(chunk, parentObject, key) { + var blocked; + + if (initializingChunkBlockedModel) { + blocked = initializingChunkBlockedModel; + blocked.deps++; + } else { + blocked = initializingChunkBlockedModel = { + deps: 1, + value: null + }; + } + + return function (value) { + parentObject[key] = value; + blocked.deps--; + + if (blocked.deps === 0) { + if (chunk.status !== BLOCKED) { + return; + } + + var resolveListeners = chunk.value; + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = blocked.value; + + if (resolveListeners !== null) { + wakeChunk(resolveListeners, blocked.value); + } + } + }; +} + +function createModelReject(chunk) { + return function (error) { + return triggerErrorOnChunk(chunk, error); + }; +} + +function getOutlinedModel(response, id) { + var chunk = getChunk(response, id); + + if (chunk.status === RESOLVED_MODEL) { + initializeModelChunk(chunk); + } + + if (chunk.status !== INITIALIZED) { + // We know that this is emitted earlier so otherwise it's an error. + throw chunk.reason; + } + + return chunk.value; +} + +function parseModelString(response, parentObject, key, value) { + if (value[0] === '$') { + switch (value[1]) { + case '$': + { + // This was an escaped string value. + return value.slice(1); + } + + case '@': + { + // Promise + var id = parseInt(value.slice(2), 16); + var chunk = getChunk(response, id); + return chunk; + } + + case 'S': + { + // Symbol + return Symbol.for(value.slice(2)); + } + + case 'F': + { + // Server Reference + var _id = parseInt(value.slice(2), 16); // TODO: Just encode this in the reference inline instead of as a model. + + + var metaData = getOutlinedModel(response, _id); + return loadServerReference$1(response, metaData.id, metaData.bound, initializingChunk, parentObject, key); + } + + case 'Q': + { + // Map + var _id2 = parseInt(value.slice(2), 16); + + var data = getOutlinedModel(response, _id2); + return new Map(data); + } + + case 'W': + { + // Set + var _id3 = parseInt(value.slice(2), 16); + + var _data = getOutlinedModel(response, _id3); + + return new Set(_data); + } + + case 'K': + { + // FormData + var stringId = value.slice(2); + var formPrefix = response._prefix + stringId + '_'; + + var _data2 = new FormData(); + + var backingFormData = response._formData; // We assume that the reference to FormData always comes after each + // entry that it references so we can assume they all exist in the + // backing store already. + // $FlowFixMe[prop-missing] FormData has forEach on it. + + backingFormData.forEach(function (entry, entryKey) { + if (entryKey.startsWith(formPrefix)) { + _data2.append(entryKey.slice(formPrefix.length), entry); + } + }); + return _data2; + } + + case 'I': + { + // $Infinity + return Infinity; + } + + case '-': + { + // $-0 or $-Infinity + if (value === '$-0') { + return -0; + } else { + return -Infinity; + } + } + + case 'N': + { + // $NaN + return NaN; + } + + case 'u': + { + // matches "$undefined" + // Special encoding for `undefined` which can't be serialized as JSON otherwise. + return undefined; + } + + case 'D': + { + // Date + return new Date(Date.parse(value.slice(2))); + } + + case 'n': + { + // BigInt + return BigInt(value.slice(2)); + } + + default: + { + // We assume that anything else is a reference ID. + var _id4 = parseInt(value.slice(1), 16); + + var _chunk = getChunk(response, _id4); + + switch (_chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk); + break; + } // The status might have changed after initialization. + + + switch (_chunk.status) { + case INITIALIZED: + return _chunk.value; + + case PENDING: + case BLOCKED: + var parentChunk = initializingChunk; + + _chunk.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); + + return null; + + default: + throw _chunk.reason; + } + } + } + } + + return value; +} + +function createResponse(bundlerConfig, formFieldPrefix) { + var backingFormData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new FormData(); + var chunks = new Map(); + var response = { + _bundlerConfig: bundlerConfig, + _prefix: formFieldPrefix, + _formData: backingFormData, + _chunks: chunks, + _fromJSON: function (key, value) { + if (typeof value === 'string') { + // We can't use .bind here because we need the "this" value. + return parseModelString(response, this, key, value); + } + + return value; + } + }; + return response; +} +function close(response) { + // In case there are any remaining unresolved chunks, they won't + // be resolved now. So we need to issue an error to those. + // Ideally we should be able to early bail out if we kept a + // ref count of pending chunks. + reportGlobalError(response, new Error('Connection closed.')); +} + +function bindArgs(fn, args) { + return fn.bind.apply(fn, [null].concat(args)); +} + +function loadServerReference(bundlerConfig, id, bound) { + var serverReference = resolveServerReference(bundlerConfig, id); // We expect most servers to not really need this because you'd just have all + // the relevant modules already loaded but it allows for lazy loading of code + // if needed. + + var preloadPromise = preloadModule(serverReference); + + if (bound) { + return Promise.all([bound, preloadPromise]).then(function (_ref) { + var args = _ref[0]; + return bindArgs(requireModule(serverReference), args); + }); + } else if (preloadPromise) { + return Promise.resolve(preloadPromise).then(function () { + return requireModule(serverReference); + }); + } else { + // Synchronously available + return Promise.resolve(requireModule(serverReference)); + } +} + +function decodeBoundActionMetaData(body, serverManifest, formFieldPrefix) { + // The data for this reference is encoded in multiple fields under this prefix. + var actionResponse = createResponse(serverManifest, formFieldPrefix, body); + close(actionResponse); + var refPromise = getRoot(actionResponse); // Force it to initialize + // $FlowFixMe + + refPromise.then(function () {}); + + if (refPromise.status !== 'fulfilled') { + // $FlowFixMe + throw refPromise.reason; + } + + return refPromise.value; +} + +function decodeAction(body, serverManifest) { + // We're going to create a new formData object that holds all the fields except + // the implementation details of the action data. + var formData = new FormData(); + var action = null; // $FlowFixMe[prop-missing] + + body.forEach(function (value, key) { + if (!key.startsWith('$ACTION_')) { + formData.append(key, value); + return; + } // Later actions may override earlier actions if a button is used to override the default + // form action. + + + if (key.startsWith('$ACTION_REF_')) { + var formFieldPrefix = '$ACTION_' + key.slice(12) + ':'; + var metaData = decodeBoundActionMetaData(body, serverManifest, formFieldPrefix); + action = loadServerReference(serverManifest, metaData.id, metaData.bound); + return; + } + + if (key.startsWith('$ACTION_ID_')) { + var id = key.slice(11); + action = loadServerReference(serverManifest, id, null); + return; + } + }); + + if (action === null) { + return null; + } // Return the action with the remaining FormData bound to the first argument. + + + return action.then(function (fn) { + return fn.bind(null, formData); + }); +} + +function renderToReadableStream(model, turbopackMap, options) { + var request = createRequest(model, turbopackMap, options ? options.onError : undefined, options ? options.context : undefined, options ? options.identifierPrefix : undefined, options ? options.onPostpone : undefined); + + if (options && options.signal) { + var signal = options.signal; + + if (signal.aborted) { + abort(request, signal.reason); + } else { + var listener = function () { + abort(request, signal.reason); + signal.removeEventListener('abort', listener); + }; + + signal.addEventListener('abort', listener); + } + } + + var stream = new ReadableStream({ + type: 'bytes', + start: function (controller) { + startWork(request); + }, + pull: function (controller) { + startFlowing(request, controller); + }, + cancel: function (reason) {} + }, // $FlowFixMe[prop-missing] size() methods are not allowed on byte streams. + { + highWaterMark: 0 + }); + return stream; +} + +function decodeReply(body, turbopackMap) { + if (typeof body === 'string') { + var form = new FormData(); + form.append('0', body); + body = form; + } + + var response = createResponse(turbopackMap, '', body); + close(response); + return getRoot(response); +} + +exports.createClientModuleProxy = createClientModuleProxy; +exports.decodeAction = decodeAction; +exports.decodeReply = decodeReply; +exports.registerClientReference = registerClientReference; +exports.registerServerReference = registerServerReference; +exports.renderToReadableStream = renderToReadableStream; + })(); +} diff --git a/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-server.browser.production.min.js b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-server.browser.production.min.js new file mode 100644 index 0000000000000..7d69bcdb31809 --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-server.browser.production.min.js @@ -0,0 +1,75 @@ +/** + * @license React + * react-server-dom-turbopack-server.browser.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var aa=require("react-dom"),ba=require("react"),l=null,n=0;function p(a,b){if(0!==b.byteLength)if(512a.depth?Fa(b,a):Ga(b,a),D=a)}function Ia(a,b){var d=a._currentValue;a._currentValue=b;var c=D;return D=a={parent:c,depth:null===c?0:c.depth+1,context:a,parentValue:d,value:b}}var Ja=Error("Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`"); +function Ka(){}function La(a,b,d){d=a[d];void 0===d?a.push(b):d!==b&&(b.then(Ka,Ka),b=d);switch(b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;default:if("string"!==typeof b.status)switch(a=b,a.status="pending",a.then(function(c){if("pending"===b.status){var e=b;e.status="fulfilled";e.value=c}},function(c){if("pending"===b.status){var e=b;e.status="rejected";e.reason=c}}),b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;}G=b;throw Ja;}}var G=null; +function Ma(){if(null===G)throw Error("Expected a suspended thenable. This is a bug in React. Please file an issue.");var a=G;G=null;return a}var I=null,J=0,K=null;function Na(){var a=K;K=null;return a}function Oa(a){return a._currentValue} +var Sa={useMemo:function(a){return a()},useCallback:function(a){return a},useDebugValue:function(){},useDeferredValue:L,useTransition:L,readContext:Oa,useContext:Oa,useReducer:L,useRef:L,useState:L,useInsertionEffect:L,useLayoutEffect:L,useImperativeHandle:L,useEffect:L,useId:Pa,useSyncExternalStore:L,useCacheRefresh:function(){return Qa},useMemoCache:function(a){for(var b=Array(a),d=0;d=a.length?a:a.slice(0,10)+"...");case "object":if(Wa(a))return"[...]";a=Xa(a);return"Object"===a?"{...}":a;case "function":return"function";default:return String(a)}} +function M(a){if("string"===typeof a)return a;switch(a){case xa:return"Suspense";case ya:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case wa:return M(a.render);case za:return M(a.type);case A:var b=a._payload;a=a._init;try{return M(a(b))}catch(d){}}return""} +function N(a,b){var d=Xa(a);if("Object"!==d&&"Array"!==d)return d;d=-1;var c=0;if(Wa(a)){var e="[";for(var f=0;fg.length&&40>e.length+g.length?e+g:e+"..."}e+="]"}else if(a.$$typeof===z)e="<"+M(a.type)+"/>";else{e="{";f=Object.keys(a);for(g=0;gk.length&&40>e.length+k.length?e+k:e+"..."}e+="}"}return void 0===b?e:-1 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +function scheduleWork(callback) { + setTimeout(callback, 0); +} +var VIEW_SIZE = 512; +var currentView = null; +var writtenBytes = 0; +function beginWriting(destination) { + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; +} +function writeChunk(destination, chunk) { + if (chunk.byteLength === 0) { + return; + } + + if (chunk.byteLength > VIEW_SIZE) { + { + if (precomputedChunkSet.has(chunk)) { + error('A large precomputed chunk was passed to writeChunk without being copied.' + ' Large chunks get enqueued directly and are not copied. This is incompatible with precomputed chunks because you cannot enqueue the same precomputed chunk twice.' + ' Use "cloneChunk" to make a copy of this large precomputed chunk before writing it. This is a bug in React.'); + } + } // this chunk may overflow a single view which implies it was not + // one that is cached by the streaming renderer. We will enqueu + // it directly and expect it is not re-used + + + if (writtenBytes > 0) { + destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes)); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + destination.enqueue(chunk); + return; + } + + var bytesToWrite = chunk; + var allowableBytes = currentView.length - writtenBytes; + + if (allowableBytes < bytesToWrite.byteLength) { + // this chunk would overflow the current view. We enqueue a full view + // and start a new view with the remaining chunk + if (allowableBytes === 0) { + // the current view is already full, send it + destination.enqueue(currentView); + } else { + // fill up the current view and apply the remaining chunk bytes + // to a new view. + currentView.set(bytesToWrite.subarray(0, allowableBytes), writtenBytes); // writtenBytes += allowableBytes; // this can be skipped because we are going to immediately reset the view + + destination.enqueue(currentView); + bytesToWrite = bytesToWrite.subarray(allowableBytes); + } + + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + currentView.set(bytesToWrite, writtenBytes); + writtenBytes += bytesToWrite.byteLength; +} +function writeChunkAndReturn(destination, chunk) { + writeChunk(destination, chunk); // in web streams there is no backpressure so we can alwas write more + + return true; +} +function completeWriting(destination) { + if (currentView && writtenBytes > 0) { + destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes)); + currentView = null; + writtenBytes = 0; + } +} +function close$1(destination) { + destination.close(); +} +var textEncoder = new TextEncoder(); +function stringToChunk(content) { + return textEncoder.encode(content); +} +var precomputedChunkSet = new Set() ; +function typedArrayToBinaryChunk(content) { + // Convert any non-Uint8Array array to Uint8Array. We could avoid this for Uint8Arrays. + // If we passed through this straight to enqueue we wouldn't have to convert it but since + // we need to copy the buffer in that case, we need to convert it to copy it. + // When we copy it into another array using set() it needs to be a Uint8Array. + var buffer = new Uint8Array(content.buffer, content.byteOffset, content.byteLength); // We clone large chunks so that we can transfer them when we write them. + // Others get copied into the target buffer. + + return content.byteLength > VIEW_SIZE ? buffer.slice() : buffer; +} +function byteLengthOfChunk(chunk) { + return chunk.byteLength; +} +function byteLengthOfBinaryChunk(chunk) { + return chunk.byteLength; +} +function closeWithError(destination, error) { + // $FlowFixMe[method-unbinding] + if (typeof destination.error === 'function') { + // $FlowFixMe[incompatible-call]: This is an Error object or the destination accepts other types. + destination.error(error); + } else { + // Earlier implementations doesn't support this method. In that environment you're + // supposed to throw from a promise returned but we don't return a promise in our + // approach. We could fork this implementation but this is environment is an edge + // case to begin with. It's even less common to run this in an older environment. + // Even then, this is not where errors are supposed to happen and they get reported + // to a global callback in addition to this anyway. So it's fine just to close this. + destination.close(); + } +} + +// eslint-disable-next-line no-unused-vars +var CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference'); +var SERVER_REFERENCE_TAG = Symbol.for('react.server.reference'); +function isClientReference(reference) { + return reference.$$typeof === CLIENT_REFERENCE_TAG; +} +function isServerReference(reference) { + return reference.$$typeof === SERVER_REFERENCE_TAG; +} +function registerClientReference(proxyImplementation, id, exportName) { + return registerClientReferenceImpl(proxyImplementation, id + '#' + exportName, false); +} + +function registerClientReferenceImpl(proxyImplementation, id, async) { + return Object.defineProperties(proxyImplementation, { + $$typeof: { + value: CLIENT_REFERENCE_TAG + }, + $$id: { + value: id + }, + $$async: { + value: async + } + }); +} // $FlowFixMe[method-unbinding] + + +var FunctionBind = Function.prototype.bind; // $FlowFixMe[method-unbinding] + +var ArraySlice = Array.prototype.slice; + +function bind() { + // $FlowFixMe[unsupported-syntax] + var newFn = FunctionBind.apply(this, arguments); + + if (this.$$typeof === SERVER_REFERENCE_TAG) { + var args = ArraySlice.call(arguments, 1); + newFn.$$typeof = SERVER_REFERENCE_TAG; + newFn.$$id = this.$$id; + newFn.$$bound = this.$$bound ? this.$$bound.concat(args) : args; + } + + return newFn; +} + +function registerServerReference(reference, id, exportName) { + return Object.defineProperties(reference, { + $$typeof: { + value: SERVER_REFERENCE_TAG + }, + $$id: { + value: exportName === null ? id : id + '#' + exportName + }, + $$bound: { + value: null + }, + bind: { + value: bind + } + }); +} +var PROMISE_PROTOTYPE = Promise.prototype; +var deepProxyHandlers = { + get: function (target, name, receiver) { + switch (name) { + // These names are read by the Flight runtime if you end up using the exports object. + case '$$typeof': + // These names are a little too common. We should probably have a way to + // have the Flight runtime extract the inner target instead. + return target.$$typeof; + + case '$$id': + return target.$$id; + + case '$$async': + return target.$$async; + + case 'name': + return target.name; + + case 'displayName': + return undefined; + // We need to special case this because createElement reads it if we pass this + // reference. + + case 'defaultProps': + return undefined; + // Avoid this attempting to be serialized. + + case 'toJSON': + return undefined; + + case Symbol.toPrimitive: + // $FlowFixMe[prop-missing] + return Object.prototype[Symbol.toPrimitive]; + + case 'Provider': + throw new Error("Cannot render a Client Context Provider on the Server. " + "Instead, you can export a Client Component wrapper " + "that itself renders a Client Context Provider."); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var expression = String(target.name) + '.' + String(name); + throw new Error("Cannot access " + expression + " on the server. " + 'You cannot dot into a client module from a server component. ' + 'You can only pass the imported name through.'); + }, + set: function () { + throw new Error('Cannot assign to a client module from a server module.'); + } +}; +var proxyHandlers = { + get: function (target, name, receiver) { + switch (name) { + // These names are read by the Flight runtime if you end up using the exports object. + case '$$typeof': + return target.$$typeof; + + case '$$id': + return target.$$id; + + case '$$async': + return target.$$async; + + case 'name': + return target.name; + // We need to special case this because createElement reads it if we pass this + // reference. + + case 'defaultProps': + return undefined; + // Avoid this attempting to be serialized. + + case 'toJSON': + return undefined; + + case Symbol.toPrimitive: + // $FlowFixMe[prop-missing] + return Object.prototype[Symbol.toPrimitive]; + + case '__esModule': + // Something is conditionally checking which export to use. We'll pretend to be + // an ESM compat module but then we'll check again on the client. + var moduleId = target.$$id; + target.default = registerClientReferenceImpl(function () { + throw new Error("Attempted to call the default export of " + moduleId + " from the server " + "but it's on the client. It's not possible to invoke a client function from " + "the server, it can only be rendered as a Component or passed to props of a " + "Client Component."); + }, target.$$id + '#', target.$$async); + return true; + + case 'then': + if (target.then) { + // Use a cached value + return target.then; + } + + if (!target.$$async) { + // If this module is expected to return a Promise (such as an AsyncModule) then + // we should resolve that with a client reference that unwraps the Promise on + // the client. + var clientReference = registerClientReferenceImpl({}, target.$$id, true); + var proxy = new Proxy(clientReference, proxyHandlers); // Treat this as a resolved Promise for React's use() + + target.status = 'fulfilled'; + target.value = proxy; + var then = target.then = registerClientReferenceImpl(function then(resolve, reject) { + // Expose to React. + return Promise.resolve(resolve(proxy)); + }, // If this is not used as a Promise but is treated as a reference to a `.then` + // export then we should treat it as a reference to that name. + target.$$id + '#then', false); + return then; + } else { + // Since typeof .then === 'function' is a feature test we'd continue recursing + // indefinitely if we return a function. Instead, we return an object reference + // if we check further. + return undefined; + } + + } + + var cachedReference = target[name]; + + if (!cachedReference) { + var reference = registerClientReferenceImpl(function () { + throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion + "Attempted to call " + String(name) + "() from the server but " + String(name) + " is on the client. " + "It's not possible to invoke a client function from the server, it can " + "only be rendered as a Component or passed to props of a Client Component."); + }, target.$$id + '#' + name, target.$$async); + Object.defineProperty(reference, 'name', { + value: name + }); + cachedReference = target[name] = new Proxy(reference, deepProxyHandlers); + } + + return cachedReference; + }, + getPrototypeOf: function (target) { + // Pretend to be a Promise in case anyone asks. + return PROMISE_PROTOTYPE; + }, + set: function () { + throw new Error('Cannot assign to a client module from a server module.'); + } +}; +function createClientModuleProxy(moduleId) { + var clientReference = registerClientReferenceImpl({}, // Represents the whole Module object instead of a particular import. + moduleId, false); + return new Proxy(clientReference, proxyHandlers); +} + +function getClientReferenceKey(reference) { + return reference.$$async ? reference.$$id + '#async' : reference.$$id; +} +function resolveClientReferenceMetadata(config, clientReference) { + var modulePath = clientReference.$$id; + var name = ''; + var resolvedModuleData = config[modulePath]; + + if (resolvedModuleData) { + // The potentially aliased name. + name = resolvedModuleData.name; + } else { + // We didn't find this specific export name but we might have the * export + // which contains this name as well. + // TODO: It's unfortunate that we now have to parse this string. We should + // probably go back to encoding path and name separately on the client reference. + var idx = modulePath.lastIndexOf('#'); + + if (idx !== -1) { + name = modulePath.slice(idx + 1); + resolvedModuleData = config[modulePath.slice(0, idx)]; + } + + if (!resolvedModuleData) { + throw new Error('Could not find the module "' + modulePath + '" in the React Client Manifest. ' + 'This is probably a bug in the React Server Components bundler.'); + } + } + + if (clientReference.$$async === true) { + return [resolvedModuleData.id, resolvedModuleData.chunks, name, 1]; + } else { + return [resolvedModuleData.id, resolvedModuleData.chunks, name]; + } +} +function getServerReferenceId(config, serverReference) { + return serverReference.$$id; +} +function getServerReferenceBoundArguments(config, serverReference) { + return serverReference.$$bound; +} + +var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +var ReactDOMFlightServerDispatcher = { + prefetchDNS: prefetchDNS, + preconnect: preconnect, + preload: preload, + preloadModule: preloadModule$1, + preinitStyle: preinitStyle, + preinitScript: preinitScript, + preinitModuleScript: preinitModuleScript +}; + +function prefetchDNS(href) { + { + if (typeof href === 'string' && href) { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'D|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + emitHint(request, 'D', href); + } + } + } +} + +function preconnect(href, crossOrigin) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = "C|" + (crossOrigin == null ? 'null' : crossOrigin) + "|" + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + + if (typeof crossOrigin === 'string') { + emitHint(request, 'C', [href, crossOrigin]); + } else { + emitHint(request, 'C', href); + } + } + } + } +} + +function preload(href, as, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'L'; + + if (as === 'image' && options) { + key += getImagePreloadKey(href, options.imageSrcSet, options.imageSizes); + } else { + key += "[" + as + "]" + href; + } + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + emitHint(request, 'L', [href, as, trimmed]); + } else { + emitHint(request, 'L', [href, as]); + } + } + } + } +} + +function preloadModule$1(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'm|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + return emitHint(request, 'm', [href, trimmed]); + } else { + return emitHint(request, 'm', href); + } + } + } + } +} + +function preinitStyle(href, precedence, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'S|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + return emitHint(request, 'S', [href, typeof precedence === 'string' ? precedence : 0, trimmed]); + } else if (typeof precedence === 'string') { + return emitHint(request, 'S', [href, precedence]); + } else { + return emitHint(request, 'S', href); + } + } + } + } +} + +function preinitScript(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'X|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + return emitHint(request, 'X', [href, trimmed]); + } else { + return emitHint(request, 'X', href); + } + } + } + } +} + +function preinitModuleScript(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'M|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + return emitHint(request, 'M', [href, trimmed]); + } else { + return emitHint(request, 'M', href); + } + } + } + } +} // Flight normally encodes undefined as a special character however for directive option +// arguments we don't want to send unnecessary keys and bloat the payload so we create a +// trimmed object which omits any keys with null or undefined values. +// This is only typesafe because these option objects have entirely optional fields where +// null and undefined represent the same thing as no property. + + +function trimOptions(options) { + if (options == null) return null; + var hasProperties = false; + var trimmed = {}; + + for (var key in options) { + if (options[key] != null) { + hasProperties = true; + trimmed[key] = options[key]; + } + } + + return hasProperties ? trimmed : null; +} + +function getImagePreloadKey(href, imageSrcSet, imageSizes) { + var uniquePart = ''; + + if (typeof imageSrcSet === 'string' && imageSrcSet !== '') { + uniquePart += '[' + imageSrcSet + ']'; + + if (typeof imageSizes === 'string') { + uniquePart += '[' + imageSizes + ']'; + } + } else { + uniquePart += '[][]' + href; + } + + return "[image]" + uniquePart; +} + +var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher; +function prepareHostDispatcher() { + ReactDOMCurrentDispatcher.current = ReactDOMFlightServerDispatcher; +} // Used to distinguish these contexts from ones used in other renderers. +// small, smaller than how we encode undefined, and is unambiguous. We could use +// a different tuple structure to encode this instead but this makes the runtime +// cost cheaper by eliminating a type checks in more positions. +// prettier-ignore + +function createHints() { + return new Set(); +} + +var supportsRequestStorage = typeof AsyncLocalStorage === 'function'; +var requestStorage = supportsRequestStorage ? new AsyncLocalStorage() : null; + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); +var REACT_MEMO_CACHE_SENTINEL = Symbol.for('react.memo_cache_sentinel'); +var REACT_POSTPONE_TYPE = Symbol.for('react.postpone'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +var rendererSigil; + +{ + // Use this to detect multiple renderers using the same context + rendererSigil = {}; +} // Used to store the parent path of all context overrides in a shared linked list. +// Forming a reverse tree. +// The structure of a context snapshot is an implementation of this file. +// Currently, it's implemented as tracking the current active node. + + +var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. +// This global (actually thread local) state represents what state all those "current", +// fields are currently in. + +var currentActiveSnapshot = null; + +function popNode(prev) { + { + prev.context._currentValue = prev.parentValue; + } +} + +function pushNode(next) { + { + next.context._currentValue = next.value; + } +} + +function popToNearestCommonAncestor(prev, next) { + if (prev === next) ; else { + popNode(prev); + var parentPrev = prev.parent; + var parentNext = next.parent; + + if (parentPrev === null) { + if (parentNext !== null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + } else { + if (parentNext === null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + + popToNearestCommonAncestor(parentPrev, parentNext); // On the way back, we push the new ones that weren't common. + + pushNode(next); + } + } +} + +function popAllPrevious(prev) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev !== null) { + popAllPrevious(parentPrev); + } +} + +function pushAllNext(next) { + var parentNext = next.parent; + + if (parentNext !== null) { + pushAllNext(parentNext); + } + + pushNode(next); +} + +function popPreviousToCommonLevel(prev, next) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (parentPrev.depth === next.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(parentPrev, next); + } else { + // We must still be deeper. + popPreviousToCommonLevel(parentPrev, next); + } +} + +function popNextToCommonLevel(prev, next) { + var parentNext = next.parent; + + if (parentNext === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (prev.depth === parentNext.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(prev, parentNext); + } else { + // We must still be deeper. + popNextToCommonLevel(prev, parentNext); + } + + pushNode(next); +} // Perform context switching to the new snapshot. +// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by +// updating all the context's current values. That way reads, always just read the current value. +// At the cost of updating contexts even if they're never read by this subtree. + + +function switchContext(newSnapshot) { + // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. + // We also need to update any new contexts that are now on the stack with the deepest value. + // The easiest way to update new contexts is to just reapply them in reverse order from the + // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack + // for that. Therefore this algorithm is recursive. + // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. + // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. + // 3) Then we reapply new contexts on the way back up the stack. + var prev = currentActiveSnapshot; + var next = newSnapshot; + + if (prev !== next) { + if (prev === null) { + // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev. + pushAllNext(next); + } else if (next === null) { + popAllPrevious(prev); + } else if (prev.depth === next.depth) { + popToNearestCommonAncestor(prev, next); + } else if (prev.depth > next.depth) { + popPreviousToCommonLevel(prev, next); + } else { + popNextToCommonLevel(prev, next); + } + + currentActiveSnapshot = next; + } +} +function pushProvider(context, nextValue) { + var prevValue; + + { + prevValue = context._currentValue; + context._currentValue = nextValue; + + { + if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } + + context._currentRenderer = rendererSigil; + } + } + + var prevNode = currentActiveSnapshot; + var newNode = { + parent: prevNode, + depth: prevNode === null ? 0 : prevNode.depth + 1, + context: context, + parentValue: prevValue, + value: nextValue + }; + currentActiveSnapshot = newNode; + return newNode; +} +function popProvider() { + var prevSnapshot = currentActiveSnapshot; + + if (prevSnapshot === null) { + throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.'); + } + + { + var value = prevSnapshot.parentValue; + + if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) { + prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue; + } else { + prevSnapshot.context._currentValue = value; + } + } + + return currentActiveSnapshot = prevSnapshot.parent; +} +function getActiveContext() { + return currentActiveSnapshot; +} +function readContext$1(context) { + var value = context._currentValue ; + return value; +} + +// Corresponds to ReactFiberWakeable and ReactFizzWakeable modules. Generally, +// changes to one module should be reflected in the others. +// TODO: Rename this module and the corresponding Fiber one to "Thenable" +// instead of "Wakeable". Or some other more appropriate name. +// An error that is thrown (e.g. by `use`) to trigger Suspense. If we +// detect this is caught by userspace, we'll log a warning in development. +var SuspenseException = new Error("Suspense Exception: This is not a real error! It's an implementation " + 'detail of `use` to interrupt the current render. You must either ' + 'rethrow it immediately, or move the `use` call outside of the ' + '`try/catch` block. Capturing without rethrowing will lead to ' + 'unexpected behavior.\n\n' + 'To handle async errors, wrap your component in an error boundary, or ' + "call the promise's `.catch` method and pass the result to `use`"); +function createThenableState() { + // The ThenableState is created the first time a component suspends. If it + // suspends again, we'll reuse the same state. + return []; +} + +function noop() {} + +function trackUsedThenable(thenableState, thenable, index) { + var previous = thenableState[index]; + + if (previous === undefined) { + thenableState.push(thenable); + } else { + if (previous !== thenable) { + // Reuse the previous thenable, and drop the new one. We can assume + // they represent the same value, because components are idempotent. + // Avoid an unhandled rejection errors for the Promises that we'll + // intentionally ignore. + thenable.then(noop, noop); + thenable = previous; + } + } // We use an expando to track the status and result of a thenable so that we + // can synchronously unwrap the value. Think of this as an extension of the + // Promise API, or a custom interface that is a superset of Thenable. + // + // If the thenable doesn't have a status, set it to "pending" and attach + // a listener that will update its status and result when it resolves. + + + switch (thenable.status) { + case 'fulfilled': + { + var fulfilledValue = thenable.value; + return fulfilledValue; + } + + case 'rejected': + { + var rejectedError = thenable.reason; + throw rejectedError; + } + + default: + { + if (typeof thenable.status === 'string') ; else { + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); // Check one more time in case the thenable resolved synchronously + + switch (thenable.status) { + case 'fulfilled': + { + var fulfilledThenable = thenable; + return fulfilledThenable.value; + } + + case 'rejected': + { + var rejectedThenable = thenable; + throw rejectedThenable.reason; + } + } + } // Suspend. + // + // Throwing here is an implementation detail that allows us to unwind the + // call stack. But we shouldn't allow it to leak into userspace. Throw an + // opaque placeholder value instead of the actual thenable. If it doesn't + // get captured by the work loop, log a warning, because that means + // something in userspace must have caught it. + + + suspendedThenable = thenable; + throw SuspenseException; + } + } +} // This is used to track the actual thenable that suspended so it can be +// passed to the rest of the Suspense implementation — which, for historical +// reasons, expects to receive a thenable. + +var suspendedThenable = null; +function getSuspendedThenable() { + // This is called right after `use` suspends by throwing an exception. `use` + // throws an opaque value instead of the thenable itself so that it can't be + // caught in userspace. Then the work loop accesses the actual thenable using + // this function. + if (suspendedThenable === null) { + throw new Error('Expected a suspended thenable. This is a bug in React. Please file ' + 'an issue.'); + } + + var thenable = suspendedThenable; + suspendedThenable = null; + return thenable; +} + +var currentRequest$1 = null; +var thenableIndexCounter = 0; +var thenableState = null; +function prepareToUseHooksForRequest(request) { + currentRequest$1 = request; +} +function resetHooksForRequest() { + currentRequest$1 = null; +} +function prepareToUseHooksForComponent(prevThenableState) { + thenableIndexCounter = 0; + thenableState = prevThenableState; +} +function getThenableStateAfterSuspending() { + var state = thenableState; + thenableState = null; + return state; +} + +function readContext(context) { + { + if (context.$$typeof !== REACT_SERVER_CONTEXT_TYPE) { + if (isClientReference(context)) { + error('Cannot read a Client Context from a Server Component.'); + } else { + error('Only createServerContext is supported in Server Components.'); + } + } + + if (currentRequest$1 === null) { + error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); + } + } + + return readContext$1(context); +} + +var HooksDispatcher = { + useMemo: function (nextCreate) { + return nextCreate(); + }, + useCallback: function (callback) { + return callback; + }, + useDebugValue: function () {}, + useDeferredValue: unsupportedHook, + useTransition: unsupportedHook, + readContext: readContext, + useContext: readContext, + useReducer: unsupportedHook, + useRef: unsupportedHook, + useState: unsupportedHook, + useInsertionEffect: unsupportedHook, + useLayoutEffect: unsupportedHook, + useImperativeHandle: unsupportedHook, + useEffect: unsupportedHook, + useId: useId, + useSyncExternalStore: unsupportedHook, + useCacheRefresh: function () { + return unsupportedRefresh; + }, + useMemoCache: function (size) { + var data = new Array(size); + + for (var i = 0; i < size; i++) { + data[i] = REACT_MEMO_CACHE_SENTINEL; + } + + return data; + }, + use: use +}; + +function unsupportedHook() { + throw new Error('This Hook is not supported in Server Components.'); +} + +function unsupportedRefresh() { + throw new Error('Refreshing the cache is not supported in Server Components.'); +} + +function useId() { + if (currentRequest$1 === null) { + throw new Error('useId can only be used while React is rendering'); + } + + var id = currentRequest$1.identifierCount++; // use 'S' for Flight components to distinguish from 'R' and 'r' in Fizz/Client + + return ':' + currentRequest$1.identifierPrefix + 'S' + id.toString(32) + ':'; +} + +function use(usable) { + if (usable !== null && typeof usable === 'object' || typeof usable === 'function') { + // $FlowFixMe[method-unbinding] + if (typeof usable.then === 'function') { + // This is a thenable. + var thenable = usable; // Track the position of the thenable within this fiber. + + var index = thenableIndexCounter; + thenableIndexCounter += 1; + + if (thenableState === null) { + thenableState = createThenableState(); + } + + return trackUsedThenable(thenableState, thenable, index); + } else if (usable.$$typeof === REACT_SERVER_CONTEXT_TYPE) { + var context = usable; + return readContext(context); + } + } + + { + if (isClientReference(usable)) { + error('Cannot use() an already resolved Client Reference.'); + } + } // eslint-disable-next-line react-internal/safe-string-coercion + + + throw new Error('An unsupported type was passed to use(): ' + String(usable)); +} + +function createSignal() { + return new AbortController().signal; +} + +function resolveCache() { + var request = resolveRequest(); + + if (request) { + return getCache(request); + } + + return new Map(); +} + +var DefaultCacheDispatcher = { + getCacheSignal: function () { + var cache = resolveCache(); + var entry = cache.get(createSignal); + + if (entry === undefined) { + entry = createSignal(); + cache.set(createSignal, entry); + } + + return entry; + }, + getCacheForType: function (resourceType) { + var cache = resolveCache(); + var entry = cache.get(resourceType); + + if (entry === undefined) { + entry = resourceType(); // TODO: Warn if undefined? + + cache.set(resourceType, entry); + } + + return entry; + } +}; + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +// in case they error. + +var jsxPropsParents = new WeakMap(); +var jsxChildrenParents = new WeakMap(); + +function isObjectPrototype(object) { + if (!object) { + return false; + } + + var ObjectPrototype = Object.prototype; + + if (object === ObjectPrototype) { + return true; + } // It might be an object from a different Realm which is + // still just a plain simple object. + + + if (Object.getPrototypeOf(object)) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + if (!(names[i] in ObjectPrototype)) { + return false; + } + } + + return true; +} + +function isSimpleObject(object) { + if (!isObjectPrototype(Object.getPrototypeOf(object))) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + var descriptor = Object.getOwnPropertyDescriptor(object, names[i]); + + if (!descriptor) { + return false; + } + + if (!descriptor.enumerable) { + if ((names[i] === 'key' || names[i] === 'ref') && typeof descriptor.get === 'function') { + // React adds key and ref getters to props objects to issue warnings. + // Those getters will not be transferred to the client, but that's ok, + // so we'll special case them. + continue; + } + + return false; + } + } + + return true; +} +function objectName(object) { + // $FlowFixMe[method-unbinding] + var name = Object.prototype.toString.call(object); + return name.replace(/^\[object (.*)\]$/, function (m, p0) { + return p0; + }); +} + +function describeKeyForErrorMessage(key) { + var encodedKey = JSON.stringify(key); + return '"' + key + '"' === encodedKey ? key : encodedKey; +} + +function describeValueForErrorMessage(value) { + switch (typeof value) { + case 'string': + { + return JSON.stringify(value.length <= 10 ? value : value.slice(0, 10) + '...'); + } + + case 'object': + { + if (isArray(value)) { + return '[...]'; + } + + var name = objectName(value); + + if (name === 'Object') { + return '{...}'; + } + + return name; + } + + case 'function': + return 'function'; + + default: + // eslint-disable-next-line react-internal/safe-string-coercion + return String(value); + } +} + +function describeElementType(type) { + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeElementType(type.render); + + case REACT_MEMO_TYPE: + return describeElementType(type.type); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeElementType(init(payload)); + } catch (x) {} + } + } + } + + return ''; +} + +function describeObjectForErrorMessage(objectOrArray, expandedName) { + var objKind = objectName(objectOrArray); + + if (objKind !== 'Object' && objKind !== 'Array') { + return objKind; + } + + var str = ''; + var start = -1; + var length = 0; + + if (isArray(objectOrArray)) { + if (jsxChildrenParents.has(objectOrArray)) { + // Print JSX Children + var type = jsxChildrenParents.get(objectOrArray); + str = '<' + describeElementType(type) + '>'; + var array = objectOrArray; + + for (var i = 0; i < array.length; i++) { + var value = array[i]; + var substr = void 0; + + if (typeof value === 'string') { + substr = value; + } else if (typeof value === 'object' && value !== null) { + substr = '{' + describeObjectForErrorMessage(value) + '}'; + } else { + substr = '{' + describeValueForErrorMessage(value) + '}'; + } + + if ('' + i === expandedName) { + start = str.length; + length = substr.length; + str += substr; + } else if (substr.length < 15 && str.length + substr.length < 40) { + str += substr; + } else { + str += '{...}'; + } + } + + str += ''; + } else { + // Print Array + str = '['; + var _array = objectOrArray; + + for (var _i = 0; _i < _array.length; _i++) { + if (_i > 0) { + str += ', '; + } + + var _value = _array[_i]; + + var _substr = void 0; + + if (typeof _value === 'object' && _value !== null) { + _substr = describeObjectForErrorMessage(_value); + } else { + _substr = describeValueForErrorMessage(_value); + } + + if ('' + _i === expandedName) { + start = str.length; + length = _substr.length; + str += _substr; + } else if (_substr.length < 10 && str.length + _substr.length < 40) { + str += _substr; + } else { + str += '...'; + } + } + + str += ']'; + } + } else { + if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) { + str = '<' + describeElementType(objectOrArray.type) + '/>'; + } else if (jsxPropsParents.has(objectOrArray)) { + // Print JSX + var _type = jsxPropsParents.get(objectOrArray); + + str = '<' + (describeElementType(_type) || '...'); + var object = objectOrArray; + var names = Object.keys(object); + + for (var _i2 = 0; _i2 < names.length; _i2++) { + str += ' '; + var name = names[_i2]; + str += describeKeyForErrorMessage(name) + '='; + var _value2 = object[name]; + + var _substr2 = void 0; + + if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) { + _substr2 = describeObjectForErrorMessage(_value2); + } else { + _substr2 = describeValueForErrorMessage(_value2); + } + + if (typeof _value2 !== 'string') { + _substr2 = '{' + _substr2 + '}'; + } + + if (name === expandedName) { + start = str.length; + length = _substr2.length; + str += _substr2; + } else if (_substr2.length < 10 && str.length + _substr2.length < 40) { + str += _substr2; + } else { + str += '...'; + } + } + + str += '>'; + } else { + // Print Object + str = '{'; + var _object = objectOrArray; + + var _names = Object.keys(_object); + + for (var _i3 = 0; _i3 < _names.length; _i3++) { + if (_i3 > 0) { + str += ', '; + } + + var _name = _names[_i3]; + str += describeKeyForErrorMessage(_name) + ': '; + var _value3 = _object[_name]; + + var _substr3 = void 0; + + if (typeof _value3 === 'object' && _value3 !== null) { + _substr3 = describeObjectForErrorMessage(_value3); + } else { + _substr3 = describeValueForErrorMessage(_value3); + } + + if (_name === expandedName) { + start = str.length; + length = _substr3.length; + str += _substr3; + } else if (_substr3.length < 10 && str.length + _substr3.length < 40) { + str += _substr3; + } else { + str += '...'; + } + } + + str += '}'; + } + } + + if (expandedName === undefined) { + return str; + } + + if (start > -1 && length > 0) { + var highlight = ' '.repeat(start) + '^'.repeat(length); + return '\n ' + str + '\n ' + highlight; + } + + return '\n ' + str; +} + +var ContextRegistry = ReactSharedInternals.ContextRegistry; +function getOrCreateServerContext(globalName) { + if (!ContextRegistry[globalName]) { + var context = { + $$typeof: REACT_SERVER_CONTEXT_TYPE, + // As a workaround to support multiple concurrent renderers, we categorize + // some renderers as primary and others as secondary. We only expect + // there to be two concurrent renderers at most: React Native (primary) and + // Fabric (secondary); React DOM (primary) and React ART (secondary). + // Secondary renderers store their context values on separate fields. + _currentValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + _currentValue2: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + _defaultValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + // Used to track how many concurrent renderers this context currently + // supports within in a single renderer. Such as parallel server rendering. + _threadCount: 0, + // These are circular + Provider: null, + Consumer: null, + _globalName: globalName + }; + context.Provider = { + $$typeof: REACT_PROVIDER_TYPE, + _context: context + }; + + { + var hasWarnedAboutUsingConsumer; + context._currentRenderer = null; + context._currentRenderer2 = null; + Object.defineProperties(context, { + Consumer: { + get: function () { + if (!hasWarnedAboutUsingConsumer) { + error('Consumer pattern is not supported by ReactServerContext'); + + hasWarnedAboutUsingConsumer = true; + } + + return null; + } + } + }); + } + + ContextRegistry[globalName] = context; + } + + return ContextRegistry[globalName]; +} + +var stringify = JSON.stringify; // Serializable values +// Thenable + +var PENDING$1 = 0; +var COMPLETED = 1; +var ABORTED = 3; +var ERRORED$1 = 4; +var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; +var ReactCurrentCache = ReactSharedInternals.ReactCurrentCache; + +function defaultErrorHandler(error) { + console['error'](error); // Don't transform to our wrapper +} + +function defaultPostponeHandler(reason) {// Noop +} + +var OPEN = 0; +var CLOSING = 1; +var CLOSED = 2; +function createRequest(model, bundlerConfig, onError, context, identifierPrefix, onPostpone) { + if (ReactCurrentCache.current !== null && ReactCurrentCache.current !== DefaultCacheDispatcher) { + throw new Error('Currently React only supports one RSC renderer at a time.'); + } + + prepareHostDispatcher(); + ReactCurrentCache.current = DefaultCacheDispatcher; + var abortSet = new Set(); + var pingedTasks = []; + var hints = createHints(); + var request = { + status: OPEN, + flushScheduled: false, + fatalError: null, + destination: null, + bundlerConfig: bundlerConfig, + cache: new Map(), + nextChunkId: 0, + pendingChunks: 0, + hints: hints, + abortableTasks: abortSet, + pingedTasks: pingedTasks, + completedImportChunks: [], + completedHintChunks: [], + completedRegularChunks: [], + completedErrorChunks: [], + writtenSymbols: new Map(), + writtenClientReferences: new Map(), + writtenServerReferences: new Map(), + writtenProviders: new Map(), + identifierPrefix: identifierPrefix || '', + identifierCount: 1, + onError: onError === undefined ? defaultErrorHandler : onError, + onPostpone: onPostpone === undefined ? defaultPostponeHandler : onPostpone, + // $FlowFixMe[missing-this-annot] + toJSON: function (key, value) { + return resolveModelToJSON(request, this, key, value); + } + }; + request.pendingChunks++; + var rootContext = createRootContext(context); + var rootTask = createTask(request, model, rootContext, abortSet); + pingedTasks.push(rootTask); + return request; +} +var currentRequest = null; +function resolveRequest() { + if (currentRequest) return currentRequest; + + if (supportsRequestStorage) { + var store = requestStorage.getStore(); + if (store) return store; + } + + return null; +} + +function createRootContext(reqContext) { + return importServerContexts(reqContext); +} + +var POP = {}; + +function serializeThenable(request, thenable) { + request.pendingChunks++; + var newTask = createTask(request, null, getActiveContext(), request.abortableTasks); + + switch (thenable.status) { + case 'fulfilled': + { + // We have the resolved value, we can go ahead and schedule it for serialization. + newTask.model = thenable.value; + pingTask(request, newTask); + return newTask.id; + } + + case 'rejected': + { + var x = thenable.reason; + + if (typeof x === 'object' && x !== null && x.$$typeof === REACT_POSTPONE_TYPE) { + var postponeInstance = x; + logPostpone(request, postponeInstance.message); + emitPostponeChunk(request, newTask.id, postponeInstance); + } else { + var digest = logRecoverableError(request, x); + emitErrorChunk(request, newTask.id, digest, x); + } + + return newTask.id; + } + + default: + { + if (typeof thenable.status === 'string') { + // Only instrument the thenable if the status if not defined. If + // it's defined, but an unknown value, assume it's been instrumented by + // some custom userspace implementation. We treat it as "pending". + break; + } + + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); + break; + } + } + + thenable.then(function (value) { + newTask.model = value; + pingTask(request, newTask); + }, function (reason) { + newTask.status = ERRORED$1; + request.abortableTasks.delete(newTask); // TODO: We should ideally do this inside performWork so it's scheduled + + var digest = logRecoverableError(request, reason); + emitErrorChunk(request, newTask.id, digest, reason); + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + }); + return newTask.id; +} + +function emitHint(request, code, model) { + emitHintChunk(request, code, model); + enqueueFlush(request); +} +function getHints(request) { + return request.hints; +} +function getCache(request) { + return request.cache; +} + +function readThenable(thenable) { + if (thenable.status === 'fulfilled') { + return thenable.value; + } else if (thenable.status === 'rejected') { + throw thenable.reason; + } + + throw thenable; +} + +function createLazyWrapperAroundWakeable(wakeable) { + // This is a temporary fork of the `use` implementation until we accept + // promises everywhere. + var thenable = wakeable; + + switch (thenable.status) { + case 'fulfilled': + case 'rejected': + break; + + default: + { + if (typeof thenable.status === 'string') { + // Only instrument the thenable if the status if not defined. If + // it's defined, but an unknown value, assume it's been instrumented by + // some custom userspace implementation. We treat it as "pending". + break; + } + + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); + break; + } + } + + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: thenable, + _init: readThenable + }; + return lazyType; +} + +function attemptResolveElement(request, type, key, ref, props, prevThenableState) { + if (ref !== null && ref !== undefined) { + // When the ref moves to the regular props object this will implicitly + // throw for functions. We could probably relax it to a DEV warning for other + // cases. + throw new Error('Refs cannot be used in Server Components, nor passed to Client Components.'); + } + + { + jsxPropsParents.set(props, type); + + if (typeof props.children === 'object' && props.children !== null) { + jsxChildrenParents.set(props.children, type); + } + } + + if (typeof type === 'function') { + if (isClientReference(type)) { + // This is a reference to a Client Component. + return [REACT_ELEMENT_TYPE, type, key, props]; + } // This is a server-side component. + + + prepareToUseHooksForComponent(prevThenableState); + var result = type(props); + + if (typeof result === 'object' && result !== null && typeof result.then === 'function') { + // When the return value is in children position we can resolve it immediately, + // to its value without a wrapper if it's synchronously available. + var thenable = result; + + if (thenable.status === 'fulfilled') { + return thenable.value; + } // TODO: Once we accept Promises as children on the client, we can just return + // the thenable here. + + + return createLazyWrapperAroundWakeable(result); + } + + return result; + } else if (typeof type === 'string') { + // This is a host element. E.g. HTML. + return [REACT_ELEMENT_TYPE, type, key, props]; + } else if (typeof type === 'symbol') { + if (type === REACT_FRAGMENT_TYPE) { + // For key-less fragments, we add a small optimization to avoid serializing + // it as a wrapper. + // TODO: If a key is specified, we should propagate its key to any children. + // Same as if a Server Component has a key. + return props.children; + } // This might be a built-in React component. We'll let the client decide. + // Any built-in works as long as its props are serializable. + + + return [REACT_ELEMENT_TYPE, type, key, props]; + } else if (type != null && typeof type === 'object') { + if (isClientReference(type)) { + // This is a reference to a Client Component. + return [REACT_ELEMENT_TYPE, type, key, props]; + } + + switch (type.$$typeof) { + case REACT_LAZY_TYPE: + { + var payload = type._payload; + var init = type._init; + var wrappedType = init(payload); + return attemptResolveElement(request, wrappedType, key, ref, props, prevThenableState); + } + + case REACT_FORWARD_REF_TYPE: + { + var render = type.render; + prepareToUseHooksForComponent(prevThenableState); + return render(props, undefined); + } + + case REACT_MEMO_TYPE: + { + return attemptResolveElement(request, type.type, key, ref, props, prevThenableState); + } + + case REACT_PROVIDER_TYPE: + { + pushProvider(type._context, props.value); + + { + var extraKeys = Object.keys(props).filter(function (value) { + if (value === 'children' || value === 'value') { + return false; + } + + return true; + }); + + if (extraKeys.length !== 0) { + error('ServerContext can only have a value prop and children. Found: %s', JSON.stringify(extraKeys)); + } + } + + return [REACT_ELEMENT_TYPE, type, key, // Rely on __popProvider being serialized last to pop the provider. + { + value: props.value, + children: props.children, + __pop: POP + }]; + } + } + } + + throw new Error("Unsupported Server Component type: " + describeValueForErrorMessage(type)); +} + +function pingTask(request, task) { + var pingedTasks = request.pingedTasks; + pingedTasks.push(task); + + if (pingedTasks.length === 1) { + request.flushScheduled = request.destination !== null; + scheduleWork(function () { + return performWork(request); + }); + } +} + +function createTask(request, model, context, abortSet) { + var id = request.nextChunkId++; + var task = { + id: id, + status: PENDING$1, + model: model, + context: context, + ping: function () { + return pingTask(request, task); + }, + thenableState: null + }; + abortSet.add(task); + return task; +} + +function serializeByValueID(id) { + return '$' + id.toString(16); +} + +function serializeLazyID(id) { + return '$L' + id.toString(16); +} + +function serializePromiseID(id) { + return '$@' + id.toString(16); +} + +function serializeServerReferenceID(id) { + return '$F' + id.toString(16); +} + +function serializeSymbolReference(name) { + return '$S' + name; +} + +function serializeProviderReference(name) { + return '$P' + name; +} + +function serializeNumber(number) { + if (Number.isFinite(number)) { + if (number === 0 && 1 / number === -Infinity) { + return '$-0'; + } else { + return number; + } + } else { + if (number === Infinity) { + return '$Infinity'; + } else if (number === -Infinity) { + return '$-Infinity'; + } else { + return '$NaN'; + } + } +} + +function serializeUndefined() { + return '$undefined'; +} + +function serializeDateFromDateJSON(dateJSON) { + // JSON.stringify automatically calls Date.prototype.toJSON which calls toISOString. + // We need only tack on a $D prefix. + return '$D' + dateJSON; +} + +function serializeBigInt(n) { + return '$n' + n.toString(10); +} + +function serializeRowHeader(tag, id) { + return id.toString(16) + ':' + tag; +} + +function encodeReferenceChunk(request, id, reference) { + var json = stringify(reference); + var row = id.toString(16) + ':' + json + '\n'; + return stringToChunk(row); +} + +function serializeClientReference(request, parent, key, clientReference) { + var clientReferenceKey = getClientReferenceKey(clientReference); + var writtenClientReferences = request.writtenClientReferences; + var existingId = writtenClientReferences.get(clientReferenceKey); + + if (existingId !== undefined) { + if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { + // If we're encoding the "type" of an element, we can refer + // to that by a lazy reference instead of directly since React + // knows how to deal with lazy values. This lets us suspend + // on this component rather than its parent until the code has + // loaded. + return serializeLazyID(existingId); + } + + return serializeByValueID(existingId); + } + + try { + var clientReferenceMetadata = resolveClientReferenceMetadata(request.bundlerConfig, clientReference); + request.pendingChunks++; + var importId = request.nextChunkId++; + emitImportChunk(request, importId, clientReferenceMetadata); + writtenClientReferences.set(clientReferenceKey, importId); + + if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { + // If we're encoding the "type" of an element, we can refer + // to that by a lazy reference instead of directly since React + // knows how to deal with lazy values. This lets us suspend + // on this component rather than its parent until the code has + // loaded. + return serializeLazyID(importId); + } + + return serializeByValueID(importId); + } catch (x) { + request.pendingChunks++; + var errorId = request.nextChunkId++; + var digest = logRecoverableError(request, x); + emitErrorChunk(request, errorId, digest, x); + return serializeByValueID(errorId); + } +} + +function outlineModel(request, value) { + request.pendingChunks++; + var outlinedId = request.nextChunkId++; // We assume that this object doesn't suspend, but a child might. + + emitModelChunk(request, outlinedId, value); + return outlinedId; +} + +function serializeServerReference(request, parent, key, serverReference) { + var writtenServerReferences = request.writtenServerReferences; + var existingId = writtenServerReferences.get(serverReference); + + if (existingId !== undefined) { + return serializeServerReferenceID(existingId); + } + + var bound = getServerReferenceBoundArguments(request.bundlerConfig, serverReference); + var serverReferenceMetadata = { + id: getServerReferenceId(request.bundlerConfig, serverReference), + bound: bound ? Promise.resolve(bound) : null + }; + var metadataId = outlineModel(request, serverReferenceMetadata); + writtenServerReferences.set(serverReference, metadataId); + return serializeServerReferenceID(metadataId); +} + +function serializeLargeTextString(request, text) { + request.pendingChunks += 2; + var textId = request.nextChunkId++; + var textChunk = stringToChunk(text); + var binaryLength = byteLengthOfChunk(textChunk); + var row = textId.toString(16) + ':T' + binaryLength.toString(16) + ','; + var headerChunk = stringToChunk(row); + request.completedRegularChunks.push(headerChunk, textChunk); + return serializeByValueID(textId); +} + +function serializeMap(request, map) { + var id = outlineModel(request, Array.from(map)); + return '$Q' + id.toString(16); +} + +function serializeSet(request, set) { + var id = outlineModel(request, Array.from(set)); + return '$W' + id.toString(16); +} + +function serializeTypedArray(request, tag, typedArray) { + request.pendingChunks += 2; + var bufferId = request.nextChunkId++; // TODO: Convert to little endian if that's not the server default. + + var binaryChunk = typedArrayToBinaryChunk(typedArray); + var binaryLength = byteLengthOfBinaryChunk(binaryChunk); + var row = bufferId.toString(16) + ':' + tag + binaryLength.toString(16) + ','; + var headerChunk = stringToChunk(row); + request.completedRegularChunks.push(headerChunk, binaryChunk); + return serializeByValueID(bufferId); +} + +function escapeStringValue(value) { + if (value[0] === '$') { + // We need to escape $ prefixed strings since we use those to encode + // references to IDs and as special symbol values. + return '$' + value; + } else { + return value; + } +} + +var insideContextProps = null; +var isInsideContextValue = false; + +function resolveModelToJSON(request, parent, key, value) { + // Make sure that `parent[key]` wasn't JSONified before `value` was passed to us + { + // $FlowFixMe[incompatible-use] + var originalValue = parent[key]; + + if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) { + if (objectName(originalValue) !== 'Object') { + var jsxParentType = jsxChildrenParents.get(parent); + + if (typeof jsxParentType === 'string') { + error('%s objects cannot be rendered as text children. Try formatting it using toString().%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } else { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } + } else { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props.%s', describeObjectForErrorMessage(parent, key)); + } + } + } // Special Symbols + + + switch (value) { + case REACT_ELEMENT_TYPE: + return '$'; + } + + { + if (parent[0] === REACT_ELEMENT_TYPE && parent[1] && parent[1].$$typeof === REACT_PROVIDER_TYPE && key === '3') { + insideContextProps = value; + } else if (insideContextProps === parent && key === 'value') { + isInsideContextValue = true; + } else if (insideContextProps === parent && key === 'children') { + isInsideContextValue = false; + } + } // Resolve Server Components. + + + while (typeof value === 'object' && value !== null && (value.$$typeof === REACT_ELEMENT_TYPE || value.$$typeof === REACT_LAZY_TYPE)) { + { + if (isInsideContextValue) { + error('React elements are not allowed in ServerContext'); + } + } + + try { + switch (value.$$typeof) { + case REACT_ELEMENT_TYPE: + { + // TODO: Concatenate keys of parents onto children. + var element = value; // Attempt to render the Server Component. + + value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, null); + break; + } + + case REACT_LAZY_TYPE: + { + var payload = value._payload; + var init = value._init; + value = init(payload); + break; + } + } + } catch (thrownValue) { + var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical + // reasons, the rest of the Suspense implementation expects the thrown + // value to be a thenable, because before `use` existed that was the + // (unstable) API for suspending. This implementation detail can change + // later, once we deprecate the old API in favor of `use`. + getSuspendedThenable() : thrownValue; + + if (typeof x === 'object' && x !== null) { + // $FlowFixMe[method-unbinding] + if (typeof x.then === 'function') { + // Something suspended, we'll need to create a new task and resolve it later. + request.pendingChunks++; + var newTask = createTask(request, value, getActiveContext(), request.abortableTasks); + var ping = newTask.ping; + x.then(ping, ping); + newTask.thenableState = getThenableStateAfterSuspending(); + return serializeLazyID(newTask.id); + } else if (x.$$typeof === REACT_POSTPONE_TYPE) { + // Something postponed. We'll still send everything we have up until this point. + // We'll replace this element with a lazy reference that postpones on the client. + var postponeInstance = x; + request.pendingChunks++; + var postponeId = request.nextChunkId++; + logPostpone(request, postponeInstance.message); + emitPostponeChunk(request, postponeId, postponeInstance); + return serializeLazyID(postponeId); + } + } // Something errored. We'll still send everything we have up until this point. + // We'll replace this element with a lazy reference that throws on the client + // once it gets rendered. + + + request.pendingChunks++; + var errorId = request.nextChunkId++; + var digest = logRecoverableError(request, x); + emitErrorChunk(request, errorId, digest, x); + return serializeLazyID(errorId); + } + } + + if (value === null) { + return null; + } + + if (typeof value === 'object') { + if (isClientReference(value)) { + return serializeClientReference(request, parent, key, value); // $FlowFixMe[method-unbinding] + } else if (typeof value.then === 'function') { + // We assume that any object with a .then property is a "Thenable" type, + // or a Promise type. Either of which can be represented by a Promise. + var promiseId = serializeThenable(request, value); + return serializePromiseID(promiseId); + } else if (value.$$typeof === REACT_PROVIDER_TYPE) { + var providerKey = value._context._globalName; + var writtenProviders = request.writtenProviders; + var providerId = writtenProviders.get(key); + + if (providerId === undefined) { + request.pendingChunks++; + providerId = request.nextChunkId++; + writtenProviders.set(providerKey, providerId); + emitProviderChunk(request, providerId, providerKey); + } + + return serializeByValueID(providerId); + } else if (value === POP) { + popProvider(); + + { + insideContextProps = null; + isInsideContextValue = false; + } + + return undefined; + } + + if (value instanceof Map) { + return serializeMap(request, value); + } + + if (value instanceof Set) { + return serializeSet(request, value); + } + + { + if (value instanceof ArrayBuffer) { + return serializeTypedArray(request, 'A', new Uint8Array(value)); + } + + if (value instanceof Int8Array) { + // char + return serializeTypedArray(request, 'C', value); + } + + if (value instanceof Uint8Array) { + // unsigned char + return serializeTypedArray(request, 'c', value); + } + + if (value instanceof Uint8ClampedArray) { + // unsigned clamped char + return serializeTypedArray(request, 'U', value); + } + + if (value instanceof Int16Array) { + // sort + return serializeTypedArray(request, 'S', value); + } + + if (value instanceof Uint16Array) { + // unsigned short + return serializeTypedArray(request, 's', value); + } + + if (value instanceof Int32Array) { + // long + return serializeTypedArray(request, 'L', value); + } + + if (value instanceof Uint32Array) { + // unsigned long + return serializeTypedArray(request, 'l', value); + } + + if (value instanceof Float32Array) { + // float + return serializeTypedArray(request, 'F', value); + } + + if (value instanceof Float64Array) { + // double + return serializeTypedArray(request, 'D', value); + } + + if (value instanceof BigInt64Array) { + // number + return serializeTypedArray(request, 'N', value); + } + + if (value instanceof BigUint64Array) { + // unsigned number + // We use "m" instead of "n" since JSON can start with "null" + return serializeTypedArray(request, 'm', value); + } + + if (value instanceof DataView) { + return serializeTypedArray(request, 'V', value); + } + } + + if (!isArray(value)) { + var iteratorFn = getIteratorFn(value); + + if (iteratorFn) { + return Array.from(value); + } + } + + { + if (value !== null && !isArray(value)) { + // Verify that this is a simple plain object. + if (objectName(value) !== 'Object') { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, key)); + } else if (!isSimpleObject(value)) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Classes or other objects with methods are not supported.%s', describeObjectForErrorMessage(parent, key)); + } else if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(value); + + if (symbols.length > 0) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with symbol properties like %s are not supported.%s', symbols[0].description, describeObjectForErrorMessage(parent, key)); + } + } + } + } // $FlowFixMe[incompatible-return] + + + return value; + } + + if (typeof value === 'string') { + // TODO: Maybe too clever. If we support URL there's no similar trick. + if (value[value.length - 1] === 'Z') { + // Possibly a Date, whose toJSON automatically calls toISOString + // $FlowFixMe[incompatible-use] + var _originalValue = parent[key]; + + if (_originalValue instanceof Date) { + return serializeDateFromDateJSON(value); + } + } + + if (value.length >= 1024) { + // For large strings, we encode them outside the JSON payload so that we + // don't have to double encode and double parse the strings. This can also + // be more compact in case the string has a lot of escaped characters. + return serializeLargeTextString(request, value); + } + + return escapeStringValue(value); + } + + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return serializeNumber(value); + } + + if (typeof value === 'undefined') { + return serializeUndefined(); + } + + if (typeof value === 'function') { + if (isClientReference(value)) { + return serializeClientReference(request, parent, key, value); + } + + if (isServerReference(value)) { + return serializeServerReference(request, parent, key, value); + } + + if (/^on[A-Z]/.test(key)) { + throw new Error('Event handlers cannot be passed to Client Component props.' + describeObjectForErrorMessage(parent, key) + '\nIf you need interactivity, consider converting part of this to a Client Component.'); + } else { + throw new Error('Functions cannot be passed directly to Client Components ' + 'unless you explicitly expose it by marking it with "use server".' + describeObjectForErrorMessage(parent, key)); + } + } + + if (typeof value === 'symbol') { + var writtenSymbols = request.writtenSymbols; + var existingId = writtenSymbols.get(value); + + if (existingId !== undefined) { + return serializeByValueID(existingId); + } // $FlowFixMe[incompatible-type] `description` might be undefined + + + var name = value.description; + + if (Symbol.for(name) !== value) { + throw new Error('Only global symbols received from Symbol.for(...) can be passed to Client Components. ' + ("The symbol Symbol.for(" + // $FlowFixMe[incompatible-type] `description` might be undefined + value.description + ") cannot be found among global symbols.") + describeObjectForErrorMessage(parent, key)); + } + + request.pendingChunks++; + var symbolId = request.nextChunkId++; + emitSymbolChunk(request, symbolId, name); + writtenSymbols.set(value, symbolId); + return serializeByValueID(symbolId); + } + + if (typeof value === 'bigint') { + return serializeBigInt(value); + } + + throw new Error("Type " + typeof value + " is not supported in Client Component props." + describeObjectForErrorMessage(parent, key)); +} + +function logPostpone(request, reason) { + var onPostpone = request.onPostpone; + onPostpone(reason); +} + +function logRecoverableError(request, error) { + var onError = request.onError; + var errorDigest = onError(error); + + if (errorDigest != null && typeof errorDigest !== 'string') { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead"); + } + + return errorDigest || ''; +} + +function fatalError(request, error) { + // This is called outside error handling code such as if an error happens in React internals. + if (request.destination !== null) { + request.status = CLOSED; + closeWithError(request.destination, error); + } else { + request.status = CLOSING; + request.fatalError = error; + } +} + +function emitPostponeChunk(request, id, postponeInstance) { + var row; + + { + var reason = ''; + var stack = ''; + + try { + // eslint-disable-next-line react-internal/safe-string-coercion + reason = String(postponeInstance.message); // eslint-disable-next-line react-internal/safe-string-coercion + + stack = String(postponeInstance.stack); + } catch (x) {} + + row = serializeRowHeader('P', id) + stringify({ + reason: reason, + stack: stack + }) + '\n'; + } + + var processedChunk = stringToChunk(row); + request.completedErrorChunks.push(processedChunk); +} + +function emitErrorChunk(request, id, digest, error) { + var errorInfo; + + { + var message; + var stack = ''; + + try { + if (error instanceof Error) { + // eslint-disable-next-line react-internal/safe-string-coercion + message = String(error.message); // eslint-disable-next-line react-internal/safe-string-coercion + + stack = String(error.stack); + } else { + message = 'Error: ' + error; + } + } catch (x) { + message = 'An error occurred but serializing the error message failed.'; + } + + errorInfo = { + digest: digest, + message: message, + stack: stack + }; + } + + var row = serializeRowHeader('E', id) + stringify(errorInfo) + '\n'; + var processedChunk = stringToChunk(row); + request.completedErrorChunks.push(processedChunk); +} + +function emitImportChunk(request, id, clientReferenceMetadata) { + // $FlowFixMe[incompatible-type] stringify can return null + var json = stringify(clientReferenceMetadata); + var row = serializeRowHeader('I', id) + json + '\n'; + var processedChunk = stringToChunk(row); + request.completedImportChunks.push(processedChunk); +} + +function emitHintChunk(request, code, model) { + var json = stringify(model); + var id = request.nextChunkId++; + var row = serializeRowHeader('H' + code, id) + json + '\n'; + var processedChunk = stringToChunk(row); + request.completedHintChunks.push(processedChunk); +} + +function emitSymbolChunk(request, id, name) { + var symbolReference = serializeSymbolReference(name); + var processedChunk = encodeReferenceChunk(request, id, symbolReference); + request.completedImportChunks.push(processedChunk); +} + +function emitProviderChunk(request, id, contextName) { + var contextReference = serializeProviderReference(contextName); + var processedChunk = encodeReferenceChunk(request, id, contextReference); + request.completedRegularChunks.push(processedChunk); +} + +function emitModelChunk(request, id, model) { + // $FlowFixMe[incompatible-type] stringify can return null + var json = stringify(model, request.toJSON); + var row = id.toString(16) + ':' + json + '\n'; + var processedChunk = stringToChunk(row); + request.completedRegularChunks.push(processedChunk); +} + +function retryTask(request, task) { + if (task.status !== PENDING$1) { + // We completed this by other means before we had a chance to retry it. + return; + } + + switchContext(task.context); + + try { + var value = task.model; + + if (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) { + // TODO: Concatenate keys of parents onto children. + var element = value; // When retrying a component, reuse the thenableState from the + // previous attempt. + + var prevThenableState = task.thenableState; // Attempt to render the Server Component. + // Doing this here lets us reuse this same task if the next component + // also suspends. + + task.model = value; + value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, prevThenableState); // Successfully finished this component. We're going to keep rendering + // using the same task, but we reset its thenable state before continuing. + + task.thenableState = null; // Keep rendering and reuse the same task. This inner loop is separate + // from the render above because we don't need to reset the thenable state + // until the next time something suspends and retries. + + while (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) { + // TODO: Concatenate keys of parents onto children. + var nextElement = value; + task.model = value; + value = attemptResolveElement(request, nextElement.type, nextElement.key, nextElement.ref, nextElement.props, null); + } + } + + emitModelChunk(request, task.id, value); + request.abortableTasks.delete(task); + task.status = COMPLETED; + } catch (thrownValue) { + var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical + // reasons, the rest of the Suspense implementation expects the thrown + // value to be a thenable, because before `use` existed that was the + // (unstable) API for suspending. This implementation detail can change + // later, once we deprecate the old API in favor of `use`. + getSuspendedThenable() : thrownValue; + + if (typeof x === 'object' && x !== null) { + // $FlowFixMe[method-unbinding] + if (typeof x.then === 'function') { + // Something suspended again, let's pick it back up later. + var ping = task.ping; + x.then(ping, ping); + task.thenableState = getThenableStateAfterSuspending(); + return; + } else if (x.$$typeof === REACT_POSTPONE_TYPE) { + request.abortableTasks.delete(task); + task.status = ERRORED$1; + var postponeInstance = x; + logPostpone(request, postponeInstance.message); + emitPostponeChunk(request, task.id, postponeInstance); + return; + } + } + + request.abortableTasks.delete(task); + task.status = ERRORED$1; + var digest = logRecoverableError(request, x); + emitErrorChunk(request, task.id, digest, x); + } +} + +function performWork(request) { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = HooksDispatcher; + var prevRequest = currentRequest; + currentRequest = request; + prepareToUseHooksForRequest(request); + + try { + var pingedTasks = request.pingedTasks; + request.pingedTasks = []; + + for (var i = 0; i < pingedTasks.length; i++) { + var task = pingedTasks[i]; + retryTask(request, task); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } finally { + ReactCurrentDispatcher.current = prevDispatcher; + resetHooksForRequest(); + currentRequest = prevRequest; + } +} + +function abortTask(task, request, errorId) { + task.status = ABORTED; // Instead of emitting an error per task.id, we emit a model that only + // has a single value referencing the error. + + var ref = serializeByValueID(errorId); + var processedChunk = encodeReferenceChunk(request, task.id, ref); + request.completedErrorChunks.push(processedChunk); +} + +function flushCompletedChunks(request, destination) { + beginWriting(); + + try { + // We emit module chunks first in the stream so that + // they can be preloaded as early as possible. + var importsChunks = request.completedImportChunks; + var i = 0; + + for (; i < importsChunks.length; i++) { + request.pendingChunks--; + var chunk = importsChunks[i]; + var keepWriting = writeChunkAndReturn(destination, chunk); + + if (!keepWriting) { + request.destination = null; + i++; + break; + } + } + + importsChunks.splice(0, i); // Next comes hints. + + var hintChunks = request.completedHintChunks; + i = 0; + + for (; i < hintChunks.length; i++) { + var _chunk = hintChunks[i]; + + var _keepWriting = writeChunkAndReturn(destination, _chunk); + + if (!_keepWriting) { + request.destination = null; + i++; + break; + } + } + + hintChunks.splice(0, i); // Next comes model data. + + var regularChunks = request.completedRegularChunks; + i = 0; + + for (; i < regularChunks.length; i++) { + request.pendingChunks--; + var _chunk2 = regularChunks[i]; + + var _keepWriting2 = writeChunkAndReturn(destination, _chunk2); + + if (!_keepWriting2) { + request.destination = null; + i++; + break; + } + } + + regularChunks.splice(0, i); // Finally, errors are sent. The idea is that it's ok to delay + // any error messages and prioritize display of other parts of + // the page. + + var errorChunks = request.completedErrorChunks; + i = 0; + + for (; i < errorChunks.length; i++) { + request.pendingChunks--; + var _chunk3 = errorChunks[i]; + + var _keepWriting3 = writeChunkAndReturn(destination, _chunk3); + + if (!_keepWriting3) { + request.destination = null; + i++; + break; + } + } + + errorChunks.splice(0, i); + } finally { + request.flushScheduled = false; + completeWriting(destination); + } + + if (request.pendingChunks === 0) { + // We're done. + close$1(destination); + } +} + +function startWork(request) { + request.flushScheduled = request.destination !== null; + + if (supportsRequestStorage) { + scheduleWork(function () { + return requestStorage.run(request, performWork, request); + }); + } else { + scheduleWork(function () { + return performWork(request); + }); + } +} + +function enqueueFlush(request) { + if (request.flushScheduled === false && // If there are pinged tasks we are going to flush anyway after work completes + request.pingedTasks.length === 0 && // If there is no destination there is nothing we can flush to. A flush will + // happen when we start flowing again + request.destination !== null) { + var destination = request.destination; + request.flushScheduled = true; + scheduleWork(function () { + return flushCompletedChunks(request, destination); + }); + } +} + +function startFlowing(request, destination) { + if (request.status === CLOSING) { + request.status = CLOSED; + closeWithError(destination, request.fatalError); + return; + } + + if (request.status === CLOSED) { + return; + } + + if (request.destination !== null) { + // We're already flowing. + return; + } + + request.destination = destination; + + try { + flushCompletedChunks(request, destination); + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} + +function abort(request, reason) { + try { + var abortableTasks = request.abortableTasks; + + if (abortableTasks.size > 0) { + // We have tasks to abort. We'll emit one error row and then emit a reference + // to that row from every row that's still remaining. + var error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason; + var digest = logRecoverableError(request, error); + request.pendingChunks++; + var errorId = request.nextChunkId++; + emitErrorChunk(request, errorId, digest, error); + abortableTasks.forEach(function (task) { + return abortTask(task, request, errorId); + }); + abortableTasks.clear(); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} + +function importServerContexts(contexts) { + if (contexts) { + var prevContext = getActiveContext(); + switchContext(rootContextSnapshot); + + for (var i = 0; i < contexts.length; i++) { + var _contexts$i = contexts[i], + name = _contexts$i[0], + value = _contexts$i[1]; + var context = getOrCreateServerContext(name); + pushProvider(context, value); + } + + var importedContext = getActiveContext(); + switchContext(prevContext); + return importedContext; + } + + return rootContextSnapshot; +} + +// This is the parsed shape of the wire format which is why it is +// condensed to only the essentialy information +var ID = 0; +var CHUNKS = 1; +var NAME = 2; // export const ASYNC = 3; +// This logic is correct because currently only include the 4th tuple member +// when the module is async. If that changes we will need to actually assert +// the value is true. We don't index into the 4th slot because flow does not +// like the potential out of bounds access + +function isAsyncImport(metadata) { + return metadata.length === 4; +} + +function resolveServerReference(bundlerConfig, id) { + var name = ''; + var resolvedModuleData = bundlerConfig[id]; + + if (resolvedModuleData) { + // The potentially aliased name. + name = resolvedModuleData.name; + } else { + // We didn't find this specific export name but we might have the * export + // which contains this name as well. + // TODO: It's unfortunate that we now have to parse this string. We should + // probably go back to encoding path and name separately on the client reference. + var idx = id.lastIndexOf('#'); + + if (idx !== -1) { + name = id.slice(idx + 1); + resolvedModuleData = bundlerConfig[id.slice(0, idx)]; + } + + if (!resolvedModuleData) { + throw new Error('Could not find the module "' + id + '" in the React Server Manifest. ' + 'This is probably a bug in the React Server Components bundler.'); + } + } // TODO: This needs to return async: true if it's an async module. + + + return [resolvedModuleData.id, resolvedModuleData.chunks, name]; +} // The chunk cache contains all the chunks we've preloaded so far. +// If they're still pending they're a thenable. This map also exists +// in Turbopack but unfortunately it's not exposed so we have to +// replicate it in user space. null means that it has already loaded. + +var chunkCache = new Map(); + +function requireAsyncModule(id) { + // We've already loaded all the chunks. We can require the module. + var promise = globalThis.__next_require__(id); + + if (typeof promise.then !== 'function') { + // This wasn't a promise after all. + return null; + } else if (promise.status === 'fulfilled') { + // This module was already resolved earlier. + return null; + } else { + // Instrument the Promise to stash the result. + promise.then(function (value) { + var fulfilledThenable = promise; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = value; + }, function (reason) { + var rejectedThenable = promise; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = reason; + }); + return promise; + } +} + +function ignoreReject() {// We rely on rejected promises to be handled by another listener. +} // Start preloading the modules since we might need them soon. +// This function doesn't suspend. + + +function preloadModule(metadata) { + var chunks = metadata[CHUNKS]; + var promises = []; + + for (var i = 0; i < chunks.length; i++) { + var chunkFilename = chunks[i]; + var entry = chunkCache.get(chunkFilename); + + if (entry === undefined) { + var thenable = loadChunk(chunkFilename); + promises.push(thenable); // $FlowFixMe[method-unbinding] + + var resolve = chunkCache.set.bind(chunkCache, chunkFilename, null); + thenable.then(resolve, ignoreReject); + chunkCache.set(chunkFilename, thenable); + } else if (entry !== null) { + promises.push(entry); + } + } + + if (isAsyncImport(metadata)) { + if (promises.length === 0) { + return requireAsyncModule(metadata[ID]); + } else { + return Promise.all(promises).then(function () { + return requireAsyncModule(metadata[ID]); + }); + } + } else if (promises.length > 0) { + return Promise.all(promises); + } else { + return null; + } +} // Actually require the module or suspend if it's not yet ready. +// Increase priority if necessary. + +function requireModule(metadata) { + var moduleExports = globalThis.__next_require__(metadata[ID]); + + if (isAsyncImport(metadata)) { + if (typeof moduleExports.then !== 'function') ; else if (moduleExports.status === 'fulfilled') { + // This Promise should've been instrumented by preloadModule. + moduleExports = moduleExports.value; + } else { + throw moduleExports.reason; + } + } + + if (metadata[NAME] === '*') { + // This is a placeholder value that represents that the caller imported this + // as a CommonJS module as is. + return moduleExports; + } + + if (metadata[NAME] === '') { + // This is a placeholder value that represents that the caller accessed the + // default property of this if it was an ESM interop module. + return moduleExports.__esModule ? moduleExports.default : moduleExports; + } + + return moduleExports[metadata[NAME]]; +} + +function loadChunk(filename) { + return globalThis.__next_chunk_load__(filename); +} + +// The server acts as a Client of itself when resolving Server References. +var PENDING = 'pending'; +var BLOCKED = 'blocked'; +var RESOLVED_MODEL = 'resolved_model'; +var INITIALIZED = 'fulfilled'; +var ERRORED = 'rejected'; // $FlowFixMe[missing-this-annot] + +function Chunk(status, value, reason, response) { + this.status = status; + this.value = value; + this.reason = reason; + this._response = response; +} // We subclass Promise.prototype so that we get other methods like .catch + + +Chunk.prototype = Object.create(Promise.prototype); // TODO: This doesn't return a new Promise chain unlike the real .then + +Chunk.prototype.then = function (resolve, reject) { + var chunk = this; // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + resolve(chunk.value); + break; + + case PENDING: + case BLOCKED: + if (resolve) { + if (chunk.value === null) { + chunk.value = []; + } + + chunk.value.push(resolve); + } + + if (reject) { + if (chunk.reason === null) { + chunk.reason = []; + } + + chunk.reason.push(reject); + } + + break; + + default: + reject(chunk.reason); + break; + } +}; + +function getRoot(response) { + var chunk = getChunk(response, 0); + return chunk; +} + +function createPendingChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(PENDING, null, null, response); +} + +function wakeChunk(listeners, value) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + listener(value); + } +} + +function triggerErrorOnChunk(chunk, error) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var listeners = chunk.reason; + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + + if (listeners !== null) { + wakeChunk(listeners, error); + } +} + +function createResolvedModelChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODEL, value, null, response); +} + +function bindArgs$1(fn, args) { + return fn.bind.apply(fn, [null].concat(args)); +} + +function loadServerReference$1(response, id, bound, parentChunk, parentObject, key) { + var serverReference = resolveServerReference(response._bundlerConfig, id); // We expect most servers to not really need this because you'd just have all + // the relevant modules already loaded but it allows for lazy loading of code + // if needed. + + var preloadPromise = preloadModule(serverReference); + var promise; + + if (bound) { + promise = Promise.all([bound, preloadPromise]).then(function (_ref) { + var args = _ref[0]; + return bindArgs$1(requireModule(serverReference), args); + }); + } else { + if (preloadPromise) { + promise = Promise.resolve(preloadPromise).then(function () { + return requireModule(serverReference); + }); + } else { + // Synchronously available + return requireModule(serverReference); + } + } + + promise.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); // We need a placeholder value that will be replaced later. + + return null; +} + +var initializingChunk = null; +var initializingChunkBlockedModel = null; + +function initializeModelChunk(chunk) { + var prevChunk = initializingChunk; + var prevBlocked = initializingChunkBlockedModel; + initializingChunk = chunk; + initializingChunkBlockedModel = null; + + try { + var value = JSON.parse(chunk.value, chunk._response._fromJSON); + + if (initializingChunkBlockedModel !== null && initializingChunkBlockedModel.deps > 0) { + initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved. + // We have to go the BLOCKED state until they're resolved. + + var blockedChunk = chunk; + blockedChunk.status = BLOCKED; + blockedChunk.value = null; + blockedChunk.reason = null; + } else { + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } finally { + initializingChunk = prevChunk; + initializingChunkBlockedModel = prevBlocked; + } +} // Report that any missing chunks in the model is now going to throw this +// error upon read. Also notify any pending promises. + + +function reportGlobalError(response, error) { + response._chunks.forEach(function (chunk) { + // If this chunk was already resolved or errored, it won't + // trigger an error but if it wasn't then we need to + // because we won't be getting any new data to resolve it. + if (chunk.status === PENDING) { + triggerErrorOnChunk(chunk, error); + } + }); +} + +function getChunk(response, id) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + var prefix = response._prefix; + var key = prefix + id; // Check if we have this field in the backing store already. + + var backingEntry = response._formData.get(key); + + if (backingEntry != null) { + // We assume that this is a string entry for now. + chunk = createResolvedModelChunk(response, backingEntry); + } else { + // We're still waiting on this entry to stream in. + chunk = createPendingChunk(response); + } + + chunks.set(id, chunk); + } + + return chunk; +} + +function createModelResolver(chunk, parentObject, key) { + var blocked; + + if (initializingChunkBlockedModel) { + blocked = initializingChunkBlockedModel; + blocked.deps++; + } else { + blocked = initializingChunkBlockedModel = { + deps: 1, + value: null + }; + } + + return function (value) { + parentObject[key] = value; + blocked.deps--; + + if (blocked.deps === 0) { + if (chunk.status !== BLOCKED) { + return; + } + + var resolveListeners = chunk.value; + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = blocked.value; + + if (resolveListeners !== null) { + wakeChunk(resolveListeners, blocked.value); + } + } + }; +} + +function createModelReject(chunk) { + return function (error) { + return triggerErrorOnChunk(chunk, error); + }; +} + +function getOutlinedModel(response, id) { + var chunk = getChunk(response, id); + + if (chunk.status === RESOLVED_MODEL) { + initializeModelChunk(chunk); + } + + if (chunk.status !== INITIALIZED) { + // We know that this is emitted earlier so otherwise it's an error. + throw chunk.reason; + } + + return chunk.value; +} + +function parseModelString(response, parentObject, key, value) { + if (value[0] === '$') { + switch (value[1]) { + case '$': + { + // This was an escaped string value. + return value.slice(1); + } + + case '@': + { + // Promise + var id = parseInt(value.slice(2), 16); + var chunk = getChunk(response, id); + return chunk; + } + + case 'S': + { + // Symbol + return Symbol.for(value.slice(2)); + } + + case 'F': + { + // Server Reference + var _id = parseInt(value.slice(2), 16); // TODO: Just encode this in the reference inline instead of as a model. + + + var metaData = getOutlinedModel(response, _id); + return loadServerReference$1(response, metaData.id, metaData.bound, initializingChunk, parentObject, key); + } + + case 'Q': + { + // Map + var _id2 = parseInt(value.slice(2), 16); + + var data = getOutlinedModel(response, _id2); + return new Map(data); + } + + case 'W': + { + // Set + var _id3 = parseInt(value.slice(2), 16); + + var _data = getOutlinedModel(response, _id3); + + return new Set(_data); + } + + case 'K': + { + // FormData + var stringId = value.slice(2); + var formPrefix = response._prefix + stringId + '_'; + + var _data2 = new FormData(); + + var backingFormData = response._formData; // We assume that the reference to FormData always comes after each + // entry that it references so we can assume they all exist in the + // backing store already. + // $FlowFixMe[prop-missing] FormData has forEach on it. + + backingFormData.forEach(function (entry, entryKey) { + if (entryKey.startsWith(formPrefix)) { + _data2.append(entryKey.slice(formPrefix.length), entry); + } + }); + return _data2; + } + + case 'I': + { + // $Infinity + return Infinity; + } + + case '-': + { + // $-0 or $-Infinity + if (value === '$-0') { + return -0; + } else { + return -Infinity; + } + } + + case 'N': + { + // $NaN + return NaN; + } + + case 'u': + { + // matches "$undefined" + // Special encoding for `undefined` which can't be serialized as JSON otherwise. + return undefined; + } + + case 'D': + { + // Date + return new Date(Date.parse(value.slice(2))); + } + + case 'n': + { + // BigInt + return BigInt(value.slice(2)); + } + + default: + { + // We assume that anything else is a reference ID. + var _id4 = parseInt(value.slice(1), 16); + + var _chunk = getChunk(response, _id4); + + switch (_chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk); + break; + } // The status might have changed after initialization. + + + switch (_chunk.status) { + case INITIALIZED: + return _chunk.value; + + case PENDING: + case BLOCKED: + var parentChunk = initializingChunk; + + _chunk.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); + + return null; + + default: + throw _chunk.reason; + } + } + } + } + + return value; +} + +function createResponse(bundlerConfig, formFieldPrefix) { + var backingFormData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new FormData(); + var chunks = new Map(); + var response = { + _bundlerConfig: bundlerConfig, + _prefix: formFieldPrefix, + _formData: backingFormData, + _chunks: chunks, + _fromJSON: function (key, value) { + if (typeof value === 'string') { + // We can't use .bind here because we need the "this" value. + return parseModelString(response, this, key, value); + } + + return value; + } + }; + return response; +} +function close(response) { + // In case there are any remaining unresolved chunks, they won't + // be resolved now. So we need to issue an error to those. + // Ideally we should be able to early bail out if we kept a + // ref count of pending chunks. + reportGlobalError(response, new Error('Connection closed.')); +} + +function bindArgs(fn, args) { + return fn.bind.apply(fn, [null].concat(args)); +} + +function loadServerReference(bundlerConfig, id, bound) { + var serverReference = resolveServerReference(bundlerConfig, id); // We expect most servers to not really need this because you'd just have all + // the relevant modules already loaded but it allows for lazy loading of code + // if needed. + + var preloadPromise = preloadModule(serverReference); + + if (bound) { + return Promise.all([bound, preloadPromise]).then(function (_ref) { + var args = _ref[0]; + return bindArgs(requireModule(serverReference), args); + }); + } else if (preloadPromise) { + return Promise.resolve(preloadPromise).then(function () { + return requireModule(serverReference); + }); + } else { + // Synchronously available + return Promise.resolve(requireModule(serverReference)); + } +} + +function decodeBoundActionMetaData(body, serverManifest, formFieldPrefix) { + // The data for this reference is encoded in multiple fields under this prefix. + var actionResponse = createResponse(serverManifest, formFieldPrefix, body); + close(actionResponse); + var refPromise = getRoot(actionResponse); // Force it to initialize + // $FlowFixMe + + refPromise.then(function () {}); + + if (refPromise.status !== 'fulfilled') { + // $FlowFixMe + throw refPromise.reason; + } + + return refPromise.value; +} + +function decodeAction(body, serverManifest) { + // We're going to create a new formData object that holds all the fields except + // the implementation details of the action data. + var formData = new FormData(); + var action = null; // $FlowFixMe[prop-missing] + + body.forEach(function (value, key) { + if (!key.startsWith('$ACTION_')) { + formData.append(key, value); + return; + } // Later actions may override earlier actions if a button is used to override the default + // form action. + + + if (key.startsWith('$ACTION_REF_')) { + var formFieldPrefix = '$ACTION_' + key.slice(12) + ':'; + var metaData = decodeBoundActionMetaData(body, serverManifest, formFieldPrefix); + action = loadServerReference(serverManifest, metaData.id, metaData.bound); + return; + } + + if (key.startsWith('$ACTION_ID_')) { + var id = key.slice(11); + action = loadServerReference(serverManifest, id, null); + return; + } + }); + + if (action === null) { + return null; + } // Return the action with the remaining FormData bound to the first argument. + + + return action.then(function (fn) { + return fn.bind(null, formData); + }); +} + +function renderToReadableStream(model, turbopackMap, options) { + var request = createRequest(model, turbopackMap, options ? options.onError : undefined, options ? options.context : undefined, options ? options.identifierPrefix : undefined, options ? options.onPostpone : undefined); + + if (options && options.signal) { + var signal = options.signal; + + if (signal.aborted) { + abort(request, signal.reason); + } else { + var listener = function () { + abort(request, signal.reason); + signal.removeEventListener('abort', listener); + }; + + signal.addEventListener('abort', listener); + } + } + + var stream = new ReadableStream({ + type: 'bytes', + start: function (controller) { + startWork(request); + }, + pull: function (controller) { + startFlowing(request, controller); + }, + cancel: function (reason) {} + }, // $FlowFixMe[prop-missing] size() methods are not allowed on byte streams. + { + highWaterMark: 0 + }); + return stream; +} + +function decodeReply(body, turbopackMap) { + if (typeof body === 'string') { + var form = new FormData(); + form.append('0', body); + body = form; + } + + var response = createResponse(turbopackMap, '', body); + close(response); + return getRoot(response); +} + +exports.createClientModuleProxy = createClientModuleProxy; +exports.decodeAction = decodeAction; +exports.decodeReply = decodeReply; +exports.registerClientReference = registerClientReference; +exports.registerServerReference = registerServerReference; +exports.renderToReadableStream = renderToReadableStream; + })(); +} diff --git a/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-server.edge.production.min.js b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-server.edge.production.min.js new file mode 100644 index 0000000000000..7c892dc9c2c29 --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-server.edge.production.min.js @@ -0,0 +1,76 @@ +/** + * @license React + * react-server-dom-turbopack-server.edge.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var aa=require("react"),ba=require("react-dom"),m=null,n=0;function q(a,b){if(0!==b.byteLength)if(512a.depth?Ha(b,a):Ia(b,a),D=a)}function Ka(a,b){var d=a._currentValue;a._currentValue=b;var c=D;return D=a={parent:c,depth:null===c?0:c.depth+1,context:a,parentValue:d,value:b}}var La=Error("Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`"); +function Ma(){}function Na(a,b,d){d=a[d];void 0===d?a.push(b):d!==b&&(b.then(Ma,Ma),b=d);switch(b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;default:if("string"!==typeof b.status)switch(a=b,a.status="pending",a.then(function(c){if("pending"===b.status){var e=b;e.status="fulfilled";e.value=c}},function(c){if("pending"===b.status){var e=b;e.status="rejected";e.reason=c}}),b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;}G=b;throw La;}}var G=null; +function Oa(){if(null===G)throw Error("Expected a suspended thenable. This is a bug in React. Please file an issue.");var a=G;G=null;return a}var I=null,J=0,K=null;function Pa(){var a=K;K=null;return a}function Qa(a){return a._currentValue} +var Ua={useMemo:function(a){return a()},useCallback:function(a){return a},useDebugValue:function(){},useDeferredValue:L,useTransition:L,readContext:Qa,useContext:Qa,useReducer:L,useRef:L,useState:L,useInsertionEffect:L,useLayoutEffect:L,useImperativeHandle:L,useEffect:L,useId:Ra,useSyncExternalStore:L,useCacheRefresh:function(){return Sa},useMemoCache:function(a){for(var b=Array(a),d=0;d=a.length?a:a.slice(0,10)+"...");case "object":if(Ya(a))return"[...]";a=Za(a);return"Object"===a?"{...}":a;case "function":return"function";default:return String(a)}} +function M(a){if("string"===typeof a)return a;switch(a){case za:return"Suspense";case Aa:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case ya:return M(a.render);case Ba:return M(a.type);case A:var b=a._payload;a=a._init;try{return M(a(b))}catch(d){}}return""} +function N(a,b){var d=Za(a);if("Object"!==d&&"Array"!==d)return d;d=-1;var c=0;if(Ya(a)){var e="[";for(var f=0;fg.length&&40>e.length+g.length?e+g:e+"..."}e+="]"}else if(a.$$typeof===z)e="<"+M(a.type)+"/>";else{e="{";f=Object.keys(a);for(g=0;gk.length&&40>e.length+k.length?e+k:e+"..."}e+="}"}return void 0===b?e:-1 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +function scheduleWork(callback) { + setImmediate(callback); +} +function flushBuffered(destination) { + // If we don't have any more data to send right now. + // Flush whatever is in the buffer to the wire. + if (typeof destination.flush === 'function') { + // By convention the Zlib streams provide a flush function for this purpose. + // For Express, compression middleware adds this method. + destination.flush(); + } +} +var VIEW_SIZE = 2048; +var currentView = null; +var writtenBytes = 0; +var destinationHasCapacity = true; +function beginWriting(destination) { + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + destinationHasCapacity = true; +} + +function writeStringChunk(destination, stringChunk) { + if (stringChunk.length === 0) { + return; + } // maximum possible view needed to encode entire string + + + if (stringChunk.length * 3 > VIEW_SIZE) { + if (writtenBytes > 0) { + writeToDestination(destination, currentView.subarray(0, writtenBytes)); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + writeToDestination(destination, textEncoder.encode(stringChunk)); + return; + } + + var target = currentView; + + if (writtenBytes > 0) { + target = currentView.subarray(writtenBytes); + } + + var _textEncoder$encodeIn = textEncoder.encodeInto(stringChunk, target), + read = _textEncoder$encodeIn.read, + written = _textEncoder$encodeIn.written; + + writtenBytes += written; + + if (read < stringChunk.length) { + writeToDestination(destination, currentView.subarray(0, writtenBytes)); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = textEncoder.encodeInto(stringChunk.slice(read), currentView).written; + } + + if (writtenBytes === VIEW_SIZE) { + writeToDestination(destination, currentView); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } +} + +function writeViewChunk(destination, chunk) { + if (chunk.byteLength === 0) { + return; + } + + if (chunk.byteLength > VIEW_SIZE) { + { + if (precomputedChunkSet && precomputedChunkSet.has(chunk)) { + error('A large precomputed chunk was passed to writeChunk without being copied.' + ' Large chunks get enqueued directly and are not copied. This is incompatible with precomputed chunks because you cannot enqueue the same precomputed chunk twice.' + ' Use "cloneChunk" to make a copy of this large precomputed chunk before writing it. This is a bug in React.'); + } + } // this chunk may overflow a single view which implies it was not + // one that is cached by the streaming renderer. We will enqueu + // it directly and expect it is not re-used + + + if (writtenBytes > 0) { + writeToDestination(destination, currentView.subarray(0, writtenBytes)); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + writeToDestination(destination, chunk); + return; + } + + var bytesToWrite = chunk; + var allowableBytes = currentView.length - writtenBytes; + + if (allowableBytes < bytesToWrite.byteLength) { + // this chunk would overflow the current view. We enqueue a full view + // and start a new view with the remaining chunk + if (allowableBytes === 0) { + // the current view is already full, send it + writeToDestination(destination, currentView); + } else { + // fill up the current view and apply the remaining chunk bytes + // to a new view. + currentView.set(bytesToWrite.subarray(0, allowableBytes), writtenBytes); + writtenBytes += allowableBytes; + writeToDestination(destination, currentView); + bytesToWrite = bytesToWrite.subarray(allowableBytes); + } + + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + currentView.set(bytesToWrite, writtenBytes); + writtenBytes += bytesToWrite.byteLength; + + if (writtenBytes === VIEW_SIZE) { + writeToDestination(destination, currentView); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } +} + +function writeChunk(destination, chunk) { + if (typeof chunk === 'string') { + writeStringChunk(destination, chunk); + } else { + writeViewChunk(destination, chunk); + } +} + +function writeToDestination(destination, view) { + var currentHasCapacity = destination.write(view); + destinationHasCapacity = destinationHasCapacity && currentHasCapacity; +} + +function writeChunkAndReturn(destination, chunk) { + writeChunk(destination, chunk); + return destinationHasCapacity; +} +function completeWriting(destination) { + if (currentView && writtenBytes > 0) { + destination.write(currentView.subarray(0, writtenBytes)); + } + + currentView = null; + writtenBytes = 0; + destinationHasCapacity = true; +} +function close$1(destination) { + destination.end(); +} +var textEncoder = new util.TextEncoder(); +function stringToChunk(content) { + return content; +} +var precomputedChunkSet = new Set() ; +function typedArrayToBinaryChunk(content) { + // Convert any non-Uint8Array array to Uint8Array. We could avoid this for Uint8Arrays. + return new Uint8Array(content.buffer, content.byteOffset, content.byteLength); +} +function byteLengthOfChunk(chunk) { + return typeof chunk === 'string' ? Buffer.byteLength(chunk, 'utf8') : chunk.byteLength; +} +function byteLengthOfBinaryChunk(chunk) { + return chunk.byteLength; +} +function closeWithError(destination, error) { + // $FlowFixMe[incompatible-call]: This is an Error object or the destination accepts other types. + destination.destroy(error); +} + +// eslint-disable-next-line no-unused-vars +var CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference'); +var SERVER_REFERENCE_TAG = Symbol.for('react.server.reference'); +function isClientReference(reference) { + return reference.$$typeof === CLIENT_REFERENCE_TAG; +} +function isServerReference(reference) { + return reference.$$typeof === SERVER_REFERENCE_TAG; +} +function registerClientReference(proxyImplementation, id, exportName) { + return registerClientReferenceImpl(proxyImplementation, id + '#' + exportName, false); +} + +function registerClientReferenceImpl(proxyImplementation, id, async) { + return Object.defineProperties(proxyImplementation, { + $$typeof: { + value: CLIENT_REFERENCE_TAG + }, + $$id: { + value: id + }, + $$async: { + value: async + } + }); +} // $FlowFixMe[method-unbinding] + + +var FunctionBind = Function.prototype.bind; // $FlowFixMe[method-unbinding] + +var ArraySlice = Array.prototype.slice; + +function bind() { + // $FlowFixMe[unsupported-syntax] + var newFn = FunctionBind.apply(this, arguments); + + if (this.$$typeof === SERVER_REFERENCE_TAG) { + var args = ArraySlice.call(arguments, 1); + newFn.$$typeof = SERVER_REFERENCE_TAG; + newFn.$$id = this.$$id; + newFn.$$bound = this.$$bound ? this.$$bound.concat(args) : args; + } + + return newFn; +} + +function registerServerReference(reference, id, exportName) { + return Object.defineProperties(reference, { + $$typeof: { + value: SERVER_REFERENCE_TAG + }, + $$id: { + value: exportName === null ? id : id + '#' + exportName + }, + $$bound: { + value: null + }, + bind: { + value: bind + } + }); +} +var PROMISE_PROTOTYPE = Promise.prototype; +var deepProxyHandlers = { + get: function (target, name, receiver) { + switch (name) { + // These names are read by the Flight runtime if you end up using the exports object. + case '$$typeof': + // These names are a little too common. We should probably have a way to + // have the Flight runtime extract the inner target instead. + return target.$$typeof; + + case '$$id': + return target.$$id; + + case '$$async': + return target.$$async; + + case 'name': + return target.name; + + case 'displayName': + return undefined; + // We need to special case this because createElement reads it if we pass this + // reference. + + case 'defaultProps': + return undefined; + // Avoid this attempting to be serialized. + + case 'toJSON': + return undefined; + + case Symbol.toPrimitive: + // $FlowFixMe[prop-missing] + return Object.prototype[Symbol.toPrimitive]; + + case 'Provider': + throw new Error("Cannot render a Client Context Provider on the Server. " + "Instead, you can export a Client Component wrapper " + "that itself renders a Client Context Provider."); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var expression = String(target.name) + '.' + String(name); + throw new Error("Cannot access " + expression + " on the server. " + 'You cannot dot into a client module from a server component. ' + 'You can only pass the imported name through.'); + }, + set: function () { + throw new Error('Cannot assign to a client module from a server module.'); + } +}; +var proxyHandlers = { + get: function (target, name, receiver) { + switch (name) { + // These names are read by the Flight runtime if you end up using the exports object. + case '$$typeof': + return target.$$typeof; + + case '$$id': + return target.$$id; + + case '$$async': + return target.$$async; + + case 'name': + return target.name; + // We need to special case this because createElement reads it if we pass this + // reference. + + case 'defaultProps': + return undefined; + // Avoid this attempting to be serialized. + + case 'toJSON': + return undefined; + + case Symbol.toPrimitive: + // $FlowFixMe[prop-missing] + return Object.prototype[Symbol.toPrimitive]; + + case '__esModule': + // Something is conditionally checking which export to use. We'll pretend to be + // an ESM compat module but then we'll check again on the client. + var moduleId = target.$$id; + target.default = registerClientReferenceImpl(function () { + throw new Error("Attempted to call the default export of " + moduleId + " from the server " + "but it's on the client. It's not possible to invoke a client function from " + "the server, it can only be rendered as a Component or passed to props of a " + "Client Component."); + }, target.$$id + '#', target.$$async); + return true; + + case 'then': + if (target.then) { + // Use a cached value + return target.then; + } + + if (!target.$$async) { + // If this module is expected to return a Promise (such as an AsyncModule) then + // we should resolve that with a client reference that unwraps the Promise on + // the client. + var clientReference = registerClientReferenceImpl({}, target.$$id, true); + var proxy = new Proxy(clientReference, proxyHandlers); // Treat this as a resolved Promise for React's use() + + target.status = 'fulfilled'; + target.value = proxy; + var then = target.then = registerClientReferenceImpl(function then(resolve, reject) { + // Expose to React. + return Promise.resolve(resolve(proxy)); + }, // If this is not used as a Promise but is treated as a reference to a `.then` + // export then we should treat it as a reference to that name. + target.$$id + '#then', false); + return then; + } else { + // Since typeof .then === 'function' is a feature test we'd continue recursing + // indefinitely if we return a function. Instead, we return an object reference + // if we check further. + return undefined; + } + + } + + var cachedReference = target[name]; + + if (!cachedReference) { + var reference = registerClientReferenceImpl(function () { + throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion + "Attempted to call " + String(name) + "() from the server but " + String(name) + " is on the client. " + "It's not possible to invoke a client function from the server, it can " + "only be rendered as a Component or passed to props of a Client Component."); + }, target.$$id + '#' + name, target.$$async); + Object.defineProperty(reference, 'name', { + value: name + }); + cachedReference = target[name] = new Proxy(reference, deepProxyHandlers); + } + + return cachedReference; + }, + getPrototypeOf: function (target) { + // Pretend to be a Promise in case anyone asks. + return PROMISE_PROTOTYPE; + }, + set: function () { + throw new Error('Cannot assign to a client module from a server module.'); + } +}; +function createClientModuleProxy(moduleId) { + var clientReference = registerClientReferenceImpl({}, // Represents the whole Module object instead of a particular import. + moduleId, false); + return new Proxy(clientReference, proxyHandlers); +} + +function getClientReferenceKey(reference) { + return reference.$$async ? reference.$$id + '#async' : reference.$$id; +} +function resolveClientReferenceMetadata(config, clientReference) { + var modulePath = clientReference.$$id; + var name = ''; + var resolvedModuleData = config[modulePath]; + + if (resolvedModuleData) { + // The potentially aliased name. + name = resolvedModuleData.name; + } else { + // We didn't find this specific export name but we might have the * export + // which contains this name as well. + // TODO: It's unfortunate that we now have to parse this string. We should + // probably go back to encoding path and name separately on the client reference. + var idx = modulePath.lastIndexOf('#'); + + if (idx !== -1) { + name = modulePath.slice(idx + 1); + resolvedModuleData = config[modulePath.slice(0, idx)]; + } + + if (!resolvedModuleData) { + throw new Error('Could not find the module "' + modulePath + '" in the React Client Manifest. ' + 'This is probably a bug in the React Server Components bundler.'); + } + } + + if (clientReference.$$async === true) { + return [resolvedModuleData.id, resolvedModuleData.chunks, name, 1]; + } else { + return [resolvedModuleData.id, resolvedModuleData.chunks, name]; + } +} +function getServerReferenceId(config, serverReference) { + return serverReference.$$id; +} +function getServerReferenceBoundArguments(config, serverReference) { + return serverReference.$$bound; +} + +var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +var ReactDOMFlightServerDispatcher = { + prefetchDNS: prefetchDNS, + preconnect: preconnect, + preload: preload, + preloadModule: preloadModule$1, + preinitStyle: preinitStyle, + preinitScript: preinitScript, + preinitModuleScript: preinitModuleScript +}; + +function prefetchDNS(href) { + { + if (typeof href === 'string' && href) { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'D|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + emitHint(request, 'D', href); + } + } + } +} + +function preconnect(href, crossOrigin) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = "C|" + (crossOrigin == null ? 'null' : crossOrigin) + "|" + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + + if (typeof crossOrigin === 'string') { + emitHint(request, 'C', [href, crossOrigin]); + } else { + emitHint(request, 'C', href); + } + } + } + } +} + +function preload(href, as, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'L'; + + if (as === 'image' && options) { + key += getImagePreloadKey(href, options.imageSrcSet, options.imageSizes); + } else { + key += "[" + as + "]" + href; + } + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + emitHint(request, 'L', [href, as, trimmed]); + } else { + emitHint(request, 'L', [href, as]); + } + } + } + } +} + +function preloadModule$1(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'm|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + return emitHint(request, 'm', [href, trimmed]); + } else { + return emitHint(request, 'm', href); + } + } + } + } +} + +function preinitStyle(href, precedence, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'S|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + return emitHint(request, 'S', [href, typeof precedence === 'string' ? precedence : 0, trimmed]); + } else if (typeof precedence === 'string') { + return emitHint(request, 'S', [href, precedence]); + } else { + return emitHint(request, 'S', href); + } + } + } + } +} + +function preinitScript(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'X|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + return emitHint(request, 'X', [href, trimmed]); + } else { + return emitHint(request, 'X', href); + } + } + } + } +} + +function preinitModuleScript(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'M|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + return emitHint(request, 'M', [href, trimmed]); + } else { + return emitHint(request, 'M', href); + } + } + } + } +} // Flight normally encodes undefined as a special character however for directive option +// arguments we don't want to send unnecessary keys and bloat the payload so we create a +// trimmed object which omits any keys with null or undefined values. +// This is only typesafe because these option objects have entirely optional fields where +// null and undefined represent the same thing as no property. + + +function trimOptions(options) { + if (options == null) return null; + var hasProperties = false; + var trimmed = {}; + + for (var key in options) { + if (options[key] != null) { + hasProperties = true; + trimmed[key] = options[key]; + } + } + + return hasProperties ? trimmed : null; +} + +function getImagePreloadKey(href, imageSrcSet, imageSizes) { + var uniquePart = ''; + + if (typeof imageSrcSet === 'string' && imageSrcSet !== '') { + uniquePart += '[' + imageSrcSet + ']'; + + if (typeof imageSizes === 'string') { + uniquePart += '[' + imageSizes + ']'; + } + } else { + uniquePart += '[][]' + href; + } + + return "[image]" + uniquePart; +} + +var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher; +function prepareHostDispatcher() { + ReactDOMCurrentDispatcher.current = ReactDOMFlightServerDispatcher; +} // Used to distinguish these contexts from ones used in other renderers. +// small, smaller than how we encode undefined, and is unambiguous. We could use +// a different tuple structure to encode this instead but this makes the runtime +// cost cheaper by eliminating a type checks in more positions. +// prettier-ignore + +function createHints() { + return new Set(); +} + +var requestStorage = new async_hooks.AsyncLocalStorage(); + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); +var REACT_MEMO_CACHE_SENTINEL = Symbol.for('react.memo_cache_sentinel'); +var REACT_POSTPONE_TYPE = Symbol.for('react.postpone'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +var rendererSigil; + +{ + // Use this to detect multiple renderers using the same context + rendererSigil = {}; +} // Used to store the parent path of all context overrides in a shared linked list. +// Forming a reverse tree. +// The structure of a context snapshot is an implementation of this file. +// Currently, it's implemented as tracking the current active node. + + +var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. +// This global (actually thread local) state represents what state all those "current", +// fields are currently in. + +var currentActiveSnapshot = null; + +function popNode(prev) { + { + prev.context._currentValue = prev.parentValue; + } +} + +function pushNode(next) { + { + next.context._currentValue = next.value; + } +} + +function popToNearestCommonAncestor(prev, next) { + if (prev === next) ; else { + popNode(prev); + var parentPrev = prev.parent; + var parentNext = next.parent; + + if (parentPrev === null) { + if (parentNext !== null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + } else { + if (parentNext === null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + + popToNearestCommonAncestor(parentPrev, parentNext); // On the way back, we push the new ones that weren't common. + + pushNode(next); + } + } +} + +function popAllPrevious(prev) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev !== null) { + popAllPrevious(parentPrev); + } +} + +function pushAllNext(next) { + var parentNext = next.parent; + + if (parentNext !== null) { + pushAllNext(parentNext); + } + + pushNode(next); +} + +function popPreviousToCommonLevel(prev, next) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (parentPrev.depth === next.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(parentPrev, next); + } else { + // We must still be deeper. + popPreviousToCommonLevel(parentPrev, next); + } +} + +function popNextToCommonLevel(prev, next) { + var parentNext = next.parent; + + if (parentNext === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (prev.depth === parentNext.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(prev, parentNext); + } else { + // We must still be deeper. + popNextToCommonLevel(prev, parentNext); + } + + pushNode(next); +} // Perform context switching to the new snapshot. +// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by +// updating all the context's current values. That way reads, always just read the current value. +// At the cost of updating contexts even if they're never read by this subtree. + + +function switchContext(newSnapshot) { + // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. + // We also need to update any new contexts that are now on the stack with the deepest value. + // The easiest way to update new contexts is to just reapply them in reverse order from the + // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack + // for that. Therefore this algorithm is recursive. + // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. + // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. + // 3) Then we reapply new contexts on the way back up the stack. + var prev = currentActiveSnapshot; + var next = newSnapshot; + + if (prev !== next) { + if (prev === null) { + // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev. + pushAllNext(next); + } else if (next === null) { + popAllPrevious(prev); + } else if (prev.depth === next.depth) { + popToNearestCommonAncestor(prev, next); + } else if (prev.depth > next.depth) { + popPreviousToCommonLevel(prev, next); + } else { + popNextToCommonLevel(prev, next); + } + + currentActiveSnapshot = next; + } +} +function pushProvider(context, nextValue) { + var prevValue; + + { + prevValue = context._currentValue; + context._currentValue = nextValue; + + { + if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } + + context._currentRenderer = rendererSigil; + } + } + + var prevNode = currentActiveSnapshot; + var newNode = { + parent: prevNode, + depth: prevNode === null ? 0 : prevNode.depth + 1, + context: context, + parentValue: prevValue, + value: nextValue + }; + currentActiveSnapshot = newNode; + return newNode; +} +function popProvider() { + var prevSnapshot = currentActiveSnapshot; + + if (prevSnapshot === null) { + throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.'); + } + + { + var value = prevSnapshot.parentValue; + + if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) { + prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue; + } else { + prevSnapshot.context._currentValue = value; + } + } + + return currentActiveSnapshot = prevSnapshot.parent; +} +function getActiveContext() { + return currentActiveSnapshot; +} +function readContext$1(context) { + var value = context._currentValue ; + return value; +} + +// Corresponds to ReactFiberWakeable and ReactFizzWakeable modules. Generally, +// changes to one module should be reflected in the others. +// TODO: Rename this module and the corresponding Fiber one to "Thenable" +// instead of "Wakeable". Or some other more appropriate name. +// An error that is thrown (e.g. by `use`) to trigger Suspense. If we +// detect this is caught by userspace, we'll log a warning in development. +var SuspenseException = new Error("Suspense Exception: This is not a real error! It's an implementation " + 'detail of `use` to interrupt the current render. You must either ' + 'rethrow it immediately, or move the `use` call outside of the ' + '`try/catch` block. Capturing without rethrowing will lead to ' + 'unexpected behavior.\n\n' + 'To handle async errors, wrap your component in an error boundary, or ' + "call the promise's `.catch` method and pass the result to `use`"); +function createThenableState() { + // The ThenableState is created the first time a component suspends. If it + // suspends again, we'll reuse the same state. + return []; +} + +function noop() {} + +function trackUsedThenable(thenableState, thenable, index) { + var previous = thenableState[index]; + + if (previous === undefined) { + thenableState.push(thenable); + } else { + if (previous !== thenable) { + // Reuse the previous thenable, and drop the new one. We can assume + // they represent the same value, because components are idempotent. + // Avoid an unhandled rejection errors for the Promises that we'll + // intentionally ignore. + thenable.then(noop, noop); + thenable = previous; + } + } // We use an expando to track the status and result of a thenable so that we + // can synchronously unwrap the value. Think of this as an extension of the + // Promise API, or a custom interface that is a superset of Thenable. + // + // If the thenable doesn't have a status, set it to "pending" and attach + // a listener that will update its status and result when it resolves. + + + switch (thenable.status) { + case 'fulfilled': + { + var fulfilledValue = thenable.value; + return fulfilledValue; + } + + case 'rejected': + { + var rejectedError = thenable.reason; + throw rejectedError; + } + + default: + { + if (typeof thenable.status === 'string') ; else { + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); // Check one more time in case the thenable resolved synchronously + + switch (thenable.status) { + case 'fulfilled': + { + var fulfilledThenable = thenable; + return fulfilledThenable.value; + } + + case 'rejected': + { + var rejectedThenable = thenable; + throw rejectedThenable.reason; + } + } + } // Suspend. + // + // Throwing here is an implementation detail that allows us to unwind the + // call stack. But we shouldn't allow it to leak into userspace. Throw an + // opaque placeholder value instead of the actual thenable. If it doesn't + // get captured by the work loop, log a warning, because that means + // something in userspace must have caught it. + + + suspendedThenable = thenable; + throw SuspenseException; + } + } +} // This is used to track the actual thenable that suspended so it can be +// passed to the rest of the Suspense implementation — which, for historical +// reasons, expects to receive a thenable. + +var suspendedThenable = null; +function getSuspendedThenable() { + // This is called right after `use` suspends by throwing an exception. `use` + // throws an opaque value instead of the thenable itself so that it can't be + // caught in userspace. Then the work loop accesses the actual thenable using + // this function. + if (suspendedThenable === null) { + throw new Error('Expected a suspended thenable. This is a bug in React. Please file ' + 'an issue.'); + } + + var thenable = suspendedThenable; + suspendedThenable = null; + return thenable; +} + +var currentRequest$1 = null; +var thenableIndexCounter = 0; +var thenableState = null; +function prepareToUseHooksForRequest(request) { + currentRequest$1 = request; +} +function resetHooksForRequest() { + currentRequest$1 = null; +} +function prepareToUseHooksForComponent(prevThenableState) { + thenableIndexCounter = 0; + thenableState = prevThenableState; +} +function getThenableStateAfterSuspending() { + var state = thenableState; + thenableState = null; + return state; +} + +function readContext(context) { + { + if (context.$$typeof !== REACT_SERVER_CONTEXT_TYPE) { + if (isClientReference(context)) { + error('Cannot read a Client Context from a Server Component.'); + } else { + error('Only createServerContext is supported in Server Components.'); + } + } + + if (currentRequest$1 === null) { + error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); + } + } + + return readContext$1(context); +} + +var HooksDispatcher = { + useMemo: function (nextCreate) { + return nextCreate(); + }, + useCallback: function (callback) { + return callback; + }, + useDebugValue: function () {}, + useDeferredValue: unsupportedHook, + useTransition: unsupportedHook, + readContext: readContext, + useContext: readContext, + useReducer: unsupportedHook, + useRef: unsupportedHook, + useState: unsupportedHook, + useInsertionEffect: unsupportedHook, + useLayoutEffect: unsupportedHook, + useImperativeHandle: unsupportedHook, + useEffect: unsupportedHook, + useId: useId, + useSyncExternalStore: unsupportedHook, + useCacheRefresh: function () { + return unsupportedRefresh; + }, + useMemoCache: function (size) { + var data = new Array(size); + + for (var i = 0; i < size; i++) { + data[i] = REACT_MEMO_CACHE_SENTINEL; + } + + return data; + }, + use: use +}; + +function unsupportedHook() { + throw new Error('This Hook is not supported in Server Components.'); +} + +function unsupportedRefresh() { + throw new Error('Refreshing the cache is not supported in Server Components.'); +} + +function useId() { + if (currentRequest$1 === null) { + throw new Error('useId can only be used while React is rendering'); + } + + var id = currentRequest$1.identifierCount++; // use 'S' for Flight components to distinguish from 'R' and 'r' in Fizz/Client + + return ':' + currentRequest$1.identifierPrefix + 'S' + id.toString(32) + ':'; +} + +function use(usable) { + if (usable !== null && typeof usable === 'object' || typeof usable === 'function') { + // $FlowFixMe[method-unbinding] + if (typeof usable.then === 'function') { + // This is a thenable. + var thenable = usable; // Track the position of the thenable within this fiber. + + var index = thenableIndexCounter; + thenableIndexCounter += 1; + + if (thenableState === null) { + thenableState = createThenableState(); + } + + return trackUsedThenable(thenableState, thenable, index); + } else if (usable.$$typeof === REACT_SERVER_CONTEXT_TYPE) { + var context = usable; + return readContext(context); + } + } + + { + if (isClientReference(usable)) { + error('Cannot use() an already resolved Client Reference.'); + } + } // eslint-disable-next-line react-internal/safe-string-coercion + + + throw new Error('An unsupported type was passed to use(): ' + String(usable)); +} + +function createSignal() { + return new AbortController().signal; +} + +function resolveCache() { + var request = resolveRequest(); + + if (request) { + return getCache(request); + } + + return new Map(); +} + +var DefaultCacheDispatcher = { + getCacheSignal: function () { + var cache = resolveCache(); + var entry = cache.get(createSignal); + + if (entry === undefined) { + entry = createSignal(); + cache.set(createSignal, entry); + } + + return entry; + }, + getCacheForType: function (resourceType) { + var cache = resolveCache(); + var entry = cache.get(resourceType); + + if (entry === undefined) { + entry = resourceType(); // TODO: Warn if undefined? + + cache.set(resourceType, entry); + } + + return entry; + } +}; + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +// in case they error. + +var jsxPropsParents = new WeakMap(); +var jsxChildrenParents = new WeakMap(); + +function isObjectPrototype(object) { + if (!object) { + return false; + } + + var ObjectPrototype = Object.prototype; + + if (object === ObjectPrototype) { + return true; + } // It might be an object from a different Realm which is + // still just a plain simple object. + + + if (Object.getPrototypeOf(object)) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + if (!(names[i] in ObjectPrototype)) { + return false; + } + } + + return true; +} + +function isSimpleObject(object) { + if (!isObjectPrototype(Object.getPrototypeOf(object))) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + var descriptor = Object.getOwnPropertyDescriptor(object, names[i]); + + if (!descriptor) { + return false; + } + + if (!descriptor.enumerable) { + if ((names[i] === 'key' || names[i] === 'ref') && typeof descriptor.get === 'function') { + // React adds key and ref getters to props objects to issue warnings. + // Those getters will not be transferred to the client, but that's ok, + // so we'll special case them. + continue; + } + + return false; + } + } + + return true; +} +function objectName(object) { + // $FlowFixMe[method-unbinding] + var name = Object.prototype.toString.call(object); + return name.replace(/^\[object (.*)\]$/, function (m, p0) { + return p0; + }); +} + +function describeKeyForErrorMessage(key) { + var encodedKey = JSON.stringify(key); + return '"' + key + '"' === encodedKey ? key : encodedKey; +} + +function describeValueForErrorMessage(value) { + switch (typeof value) { + case 'string': + { + return JSON.stringify(value.length <= 10 ? value : value.slice(0, 10) + '...'); + } + + case 'object': + { + if (isArray(value)) { + return '[...]'; + } + + var name = objectName(value); + + if (name === 'Object') { + return '{...}'; + } + + return name; + } + + case 'function': + return 'function'; + + default: + // eslint-disable-next-line react-internal/safe-string-coercion + return String(value); + } +} + +function describeElementType(type) { + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeElementType(type.render); + + case REACT_MEMO_TYPE: + return describeElementType(type.type); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeElementType(init(payload)); + } catch (x) {} + } + } + } + + return ''; +} + +function describeObjectForErrorMessage(objectOrArray, expandedName) { + var objKind = objectName(objectOrArray); + + if (objKind !== 'Object' && objKind !== 'Array') { + return objKind; + } + + var str = ''; + var start = -1; + var length = 0; + + if (isArray(objectOrArray)) { + if (jsxChildrenParents.has(objectOrArray)) { + // Print JSX Children + var type = jsxChildrenParents.get(objectOrArray); + str = '<' + describeElementType(type) + '>'; + var array = objectOrArray; + + for (var i = 0; i < array.length; i++) { + var value = array[i]; + var substr = void 0; + + if (typeof value === 'string') { + substr = value; + } else if (typeof value === 'object' && value !== null) { + substr = '{' + describeObjectForErrorMessage(value) + '}'; + } else { + substr = '{' + describeValueForErrorMessage(value) + '}'; + } + + if ('' + i === expandedName) { + start = str.length; + length = substr.length; + str += substr; + } else if (substr.length < 15 && str.length + substr.length < 40) { + str += substr; + } else { + str += '{...}'; + } + } + + str += ''; + } else { + // Print Array + str = '['; + var _array = objectOrArray; + + for (var _i = 0; _i < _array.length; _i++) { + if (_i > 0) { + str += ', '; + } + + var _value = _array[_i]; + + var _substr = void 0; + + if (typeof _value === 'object' && _value !== null) { + _substr = describeObjectForErrorMessage(_value); + } else { + _substr = describeValueForErrorMessage(_value); + } + + if ('' + _i === expandedName) { + start = str.length; + length = _substr.length; + str += _substr; + } else if (_substr.length < 10 && str.length + _substr.length < 40) { + str += _substr; + } else { + str += '...'; + } + } + + str += ']'; + } + } else { + if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) { + str = '<' + describeElementType(objectOrArray.type) + '/>'; + } else if (jsxPropsParents.has(objectOrArray)) { + // Print JSX + var _type = jsxPropsParents.get(objectOrArray); + + str = '<' + (describeElementType(_type) || '...'); + var object = objectOrArray; + var names = Object.keys(object); + + for (var _i2 = 0; _i2 < names.length; _i2++) { + str += ' '; + var name = names[_i2]; + str += describeKeyForErrorMessage(name) + '='; + var _value2 = object[name]; + + var _substr2 = void 0; + + if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) { + _substr2 = describeObjectForErrorMessage(_value2); + } else { + _substr2 = describeValueForErrorMessage(_value2); + } + + if (typeof _value2 !== 'string') { + _substr2 = '{' + _substr2 + '}'; + } + + if (name === expandedName) { + start = str.length; + length = _substr2.length; + str += _substr2; + } else if (_substr2.length < 10 && str.length + _substr2.length < 40) { + str += _substr2; + } else { + str += '...'; + } + } + + str += '>'; + } else { + // Print Object + str = '{'; + var _object = objectOrArray; + + var _names = Object.keys(_object); + + for (var _i3 = 0; _i3 < _names.length; _i3++) { + if (_i3 > 0) { + str += ', '; + } + + var _name = _names[_i3]; + str += describeKeyForErrorMessage(_name) + ': '; + var _value3 = _object[_name]; + + var _substr3 = void 0; + + if (typeof _value3 === 'object' && _value3 !== null) { + _substr3 = describeObjectForErrorMessage(_value3); + } else { + _substr3 = describeValueForErrorMessage(_value3); + } + + if (_name === expandedName) { + start = str.length; + length = _substr3.length; + str += _substr3; + } else if (_substr3.length < 10 && str.length + _substr3.length < 40) { + str += _substr3; + } else { + str += '...'; + } + } + + str += '}'; + } + } + + if (expandedName === undefined) { + return str; + } + + if (start > -1 && length > 0) { + var highlight = ' '.repeat(start) + '^'.repeat(length); + return '\n ' + str + '\n ' + highlight; + } + + return '\n ' + str; +} + +var ContextRegistry = ReactSharedInternals.ContextRegistry; +function getOrCreateServerContext(globalName) { + if (!ContextRegistry[globalName]) { + var context = { + $$typeof: REACT_SERVER_CONTEXT_TYPE, + // As a workaround to support multiple concurrent renderers, we categorize + // some renderers as primary and others as secondary. We only expect + // there to be two concurrent renderers at most: React Native (primary) and + // Fabric (secondary); React DOM (primary) and React ART (secondary). + // Secondary renderers store their context values on separate fields. + _currentValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + _currentValue2: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + _defaultValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + // Used to track how many concurrent renderers this context currently + // supports within in a single renderer. Such as parallel server rendering. + _threadCount: 0, + // These are circular + Provider: null, + Consumer: null, + _globalName: globalName + }; + context.Provider = { + $$typeof: REACT_PROVIDER_TYPE, + _context: context + }; + + { + var hasWarnedAboutUsingConsumer; + context._currentRenderer = null; + context._currentRenderer2 = null; + Object.defineProperties(context, { + Consumer: { + get: function () { + if (!hasWarnedAboutUsingConsumer) { + error('Consumer pattern is not supported by ReactServerContext'); + + hasWarnedAboutUsingConsumer = true; + } + + return null; + } + } + }); + } + + ContextRegistry[globalName] = context; + } + + return ContextRegistry[globalName]; +} + +var stringify = JSON.stringify; // Serializable values +// Thenable + +var PENDING$1 = 0; +var COMPLETED = 1; +var ABORTED = 3; +var ERRORED$1 = 4; +var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; +var ReactCurrentCache = ReactSharedInternals.ReactCurrentCache; + +function defaultErrorHandler(error) { + console['error'](error); // Don't transform to our wrapper +} + +function defaultPostponeHandler(reason) {// Noop +} + +var OPEN = 0; +var CLOSING = 1; +var CLOSED = 2; +function createRequest(model, bundlerConfig, onError, context, identifierPrefix, onPostpone) { + if (ReactCurrentCache.current !== null && ReactCurrentCache.current !== DefaultCacheDispatcher) { + throw new Error('Currently React only supports one RSC renderer at a time.'); + } + + prepareHostDispatcher(); + ReactCurrentCache.current = DefaultCacheDispatcher; + var abortSet = new Set(); + var pingedTasks = []; + var hints = createHints(); + var request = { + status: OPEN, + flushScheduled: false, + fatalError: null, + destination: null, + bundlerConfig: bundlerConfig, + cache: new Map(), + nextChunkId: 0, + pendingChunks: 0, + hints: hints, + abortableTasks: abortSet, + pingedTasks: pingedTasks, + completedImportChunks: [], + completedHintChunks: [], + completedRegularChunks: [], + completedErrorChunks: [], + writtenSymbols: new Map(), + writtenClientReferences: new Map(), + writtenServerReferences: new Map(), + writtenProviders: new Map(), + identifierPrefix: identifierPrefix || '', + identifierCount: 1, + onError: onError === undefined ? defaultErrorHandler : onError, + onPostpone: onPostpone === undefined ? defaultPostponeHandler : onPostpone, + // $FlowFixMe[missing-this-annot] + toJSON: function (key, value) { + return resolveModelToJSON(request, this, key, value); + } + }; + request.pendingChunks++; + var rootContext = createRootContext(context); + var rootTask = createTask(request, model, rootContext, abortSet); + pingedTasks.push(rootTask); + return request; +} +var currentRequest = null; +function resolveRequest() { + if (currentRequest) return currentRequest; + + { + var store = requestStorage.getStore(); + if (store) return store; + } + + return null; +} + +function createRootContext(reqContext) { + return importServerContexts(reqContext); +} + +var POP = {}; + +function serializeThenable(request, thenable) { + request.pendingChunks++; + var newTask = createTask(request, null, getActiveContext(), request.abortableTasks); + + switch (thenable.status) { + case 'fulfilled': + { + // We have the resolved value, we can go ahead and schedule it for serialization. + newTask.model = thenable.value; + pingTask(request, newTask); + return newTask.id; + } + + case 'rejected': + { + var x = thenable.reason; + + if (typeof x === 'object' && x !== null && x.$$typeof === REACT_POSTPONE_TYPE) { + var postponeInstance = x; + logPostpone(request, postponeInstance.message); + emitPostponeChunk(request, newTask.id, postponeInstance); + } else { + var digest = logRecoverableError(request, x); + emitErrorChunk(request, newTask.id, digest, x); + } + + return newTask.id; + } + + default: + { + if (typeof thenable.status === 'string') { + // Only instrument the thenable if the status if not defined. If + // it's defined, but an unknown value, assume it's been instrumented by + // some custom userspace implementation. We treat it as "pending". + break; + } + + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); + break; + } + } + + thenable.then(function (value) { + newTask.model = value; + pingTask(request, newTask); + }, function (reason) { + newTask.status = ERRORED$1; + request.abortableTasks.delete(newTask); // TODO: We should ideally do this inside performWork so it's scheduled + + var digest = logRecoverableError(request, reason); + emitErrorChunk(request, newTask.id, digest, reason); + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + }); + return newTask.id; +} + +function emitHint(request, code, model) { + emitHintChunk(request, code, model); + enqueueFlush(request); +} +function getHints(request) { + return request.hints; +} +function getCache(request) { + return request.cache; +} + +function readThenable(thenable) { + if (thenable.status === 'fulfilled') { + return thenable.value; + } else if (thenable.status === 'rejected') { + throw thenable.reason; + } + + throw thenable; +} + +function createLazyWrapperAroundWakeable(wakeable) { + // This is a temporary fork of the `use` implementation until we accept + // promises everywhere. + var thenable = wakeable; + + switch (thenable.status) { + case 'fulfilled': + case 'rejected': + break; + + default: + { + if (typeof thenable.status === 'string') { + // Only instrument the thenable if the status if not defined. If + // it's defined, but an unknown value, assume it's been instrumented by + // some custom userspace implementation. We treat it as "pending". + break; + } + + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); + break; + } + } + + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: thenable, + _init: readThenable + }; + return lazyType; +} + +function attemptResolveElement(request, type, key, ref, props, prevThenableState) { + if (ref !== null && ref !== undefined) { + // When the ref moves to the regular props object this will implicitly + // throw for functions. We could probably relax it to a DEV warning for other + // cases. + throw new Error('Refs cannot be used in Server Components, nor passed to Client Components.'); + } + + { + jsxPropsParents.set(props, type); + + if (typeof props.children === 'object' && props.children !== null) { + jsxChildrenParents.set(props.children, type); + } + } + + if (typeof type === 'function') { + if (isClientReference(type)) { + // This is a reference to a Client Component. + return [REACT_ELEMENT_TYPE, type, key, props]; + } // This is a server-side component. + + + prepareToUseHooksForComponent(prevThenableState); + var result = type(props); + + if (typeof result === 'object' && result !== null && typeof result.then === 'function') { + // When the return value is in children position we can resolve it immediately, + // to its value without a wrapper if it's synchronously available. + var thenable = result; + + if (thenable.status === 'fulfilled') { + return thenable.value; + } // TODO: Once we accept Promises as children on the client, we can just return + // the thenable here. + + + return createLazyWrapperAroundWakeable(result); + } + + return result; + } else if (typeof type === 'string') { + // This is a host element. E.g. HTML. + return [REACT_ELEMENT_TYPE, type, key, props]; + } else if (typeof type === 'symbol') { + if (type === REACT_FRAGMENT_TYPE) { + // For key-less fragments, we add a small optimization to avoid serializing + // it as a wrapper. + // TODO: If a key is specified, we should propagate its key to any children. + // Same as if a Server Component has a key. + return props.children; + } // This might be a built-in React component. We'll let the client decide. + // Any built-in works as long as its props are serializable. + + + return [REACT_ELEMENT_TYPE, type, key, props]; + } else if (type != null && typeof type === 'object') { + if (isClientReference(type)) { + // This is a reference to a Client Component. + return [REACT_ELEMENT_TYPE, type, key, props]; + } + + switch (type.$$typeof) { + case REACT_LAZY_TYPE: + { + var payload = type._payload; + var init = type._init; + var wrappedType = init(payload); + return attemptResolveElement(request, wrappedType, key, ref, props, prevThenableState); + } + + case REACT_FORWARD_REF_TYPE: + { + var render = type.render; + prepareToUseHooksForComponent(prevThenableState); + return render(props, undefined); + } + + case REACT_MEMO_TYPE: + { + return attemptResolveElement(request, type.type, key, ref, props, prevThenableState); + } + + case REACT_PROVIDER_TYPE: + { + pushProvider(type._context, props.value); + + { + var extraKeys = Object.keys(props).filter(function (value) { + if (value === 'children' || value === 'value') { + return false; + } + + return true; + }); + + if (extraKeys.length !== 0) { + error('ServerContext can only have a value prop and children. Found: %s', JSON.stringify(extraKeys)); + } + } + + return [REACT_ELEMENT_TYPE, type, key, // Rely on __popProvider being serialized last to pop the provider. + { + value: props.value, + children: props.children, + __pop: POP + }]; + } + } + } + + throw new Error("Unsupported Server Component type: " + describeValueForErrorMessage(type)); +} + +function pingTask(request, task) { + var pingedTasks = request.pingedTasks; + pingedTasks.push(task); + + if (pingedTasks.length === 1) { + request.flushScheduled = request.destination !== null; + scheduleWork(function () { + return performWork(request); + }); + } +} + +function createTask(request, model, context, abortSet) { + var id = request.nextChunkId++; + var task = { + id: id, + status: PENDING$1, + model: model, + context: context, + ping: function () { + return pingTask(request, task); + }, + thenableState: null + }; + abortSet.add(task); + return task; +} + +function serializeByValueID(id) { + return '$' + id.toString(16); +} + +function serializeLazyID(id) { + return '$L' + id.toString(16); +} + +function serializePromiseID(id) { + return '$@' + id.toString(16); +} + +function serializeServerReferenceID(id) { + return '$F' + id.toString(16); +} + +function serializeSymbolReference(name) { + return '$S' + name; +} + +function serializeProviderReference(name) { + return '$P' + name; +} + +function serializeNumber(number) { + if (Number.isFinite(number)) { + if (number === 0 && 1 / number === -Infinity) { + return '$-0'; + } else { + return number; + } + } else { + if (number === Infinity) { + return '$Infinity'; + } else if (number === -Infinity) { + return '$-Infinity'; + } else { + return '$NaN'; + } + } +} + +function serializeUndefined() { + return '$undefined'; +} + +function serializeDateFromDateJSON(dateJSON) { + // JSON.stringify automatically calls Date.prototype.toJSON which calls toISOString. + // We need only tack on a $D prefix. + return '$D' + dateJSON; +} + +function serializeBigInt(n) { + return '$n' + n.toString(10); +} + +function serializeRowHeader(tag, id) { + return id.toString(16) + ':' + tag; +} + +function encodeReferenceChunk(request, id, reference) { + var json = stringify(reference); + var row = id.toString(16) + ':' + json + '\n'; + return stringToChunk(row); +} + +function serializeClientReference(request, parent, key, clientReference) { + var clientReferenceKey = getClientReferenceKey(clientReference); + var writtenClientReferences = request.writtenClientReferences; + var existingId = writtenClientReferences.get(clientReferenceKey); + + if (existingId !== undefined) { + if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { + // If we're encoding the "type" of an element, we can refer + // to that by a lazy reference instead of directly since React + // knows how to deal with lazy values. This lets us suspend + // on this component rather than its parent until the code has + // loaded. + return serializeLazyID(existingId); + } + + return serializeByValueID(existingId); + } + + try { + var clientReferenceMetadata = resolveClientReferenceMetadata(request.bundlerConfig, clientReference); + request.pendingChunks++; + var importId = request.nextChunkId++; + emitImportChunk(request, importId, clientReferenceMetadata); + writtenClientReferences.set(clientReferenceKey, importId); + + if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { + // If we're encoding the "type" of an element, we can refer + // to that by a lazy reference instead of directly since React + // knows how to deal with lazy values. This lets us suspend + // on this component rather than its parent until the code has + // loaded. + return serializeLazyID(importId); + } + + return serializeByValueID(importId); + } catch (x) { + request.pendingChunks++; + var errorId = request.nextChunkId++; + var digest = logRecoverableError(request, x); + emitErrorChunk(request, errorId, digest, x); + return serializeByValueID(errorId); + } +} + +function outlineModel(request, value) { + request.pendingChunks++; + var outlinedId = request.nextChunkId++; // We assume that this object doesn't suspend, but a child might. + + emitModelChunk(request, outlinedId, value); + return outlinedId; +} + +function serializeServerReference(request, parent, key, serverReference) { + var writtenServerReferences = request.writtenServerReferences; + var existingId = writtenServerReferences.get(serverReference); + + if (existingId !== undefined) { + return serializeServerReferenceID(existingId); + } + + var bound = getServerReferenceBoundArguments(request.bundlerConfig, serverReference); + var serverReferenceMetadata = { + id: getServerReferenceId(request.bundlerConfig, serverReference), + bound: bound ? Promise.resolve(bound) : null + }; + var metadataId = outlineModel(request, serverReferenceMetadata); + writtenServerReferences.set(serverReference, metadataId); + return serializeServerReferenceID(metadataId); +} + +function serializeLargeTextString(request, text) { + request.pendingChunks += 2; + var textId = request.nextChunkId++; + var textChunk = stringToChunk(text); + var binaryLength = byteLengthOfChunk(textChunk); + var row = textId.toString(16) + ':T' + binaryLength.toString(16) + ','; + var headerChunk = stringToChunk(row); + request.completedRegularChunks.push(headerChunk, textChunk); + return serializeByValueID(textId); +} + +function serializeMap(request, map) { + var id = outlineModel(request, Array.from(map)); + return '$Q' + id.toString(16); +} + +function serializeSet(request, set) { + var id = outlineModel(request, Array.from(set)); + return '$W' + id.toString(16); +} + +function serializeTypedArray(request, tag, typedArray) { + request.pendingChunks += 2; + var bufferId = request.nextChunkId++; // TODO: Convert to little endian if that's not the server default. + + var binaryChunk = typedArrayToBinaryChunk(typedArray); + var binaryLength = byteLengthOfBinaryChunk(binaryChunk); + var row = bufferId.toString(16) + ':' + tag + binaryLength.toString(16) + ','; + var headerChunk = stringToChunk(row); + request.completedRegularChunks.push(headerChunk, binaryChunk); + return serializeByValueID(bufferId); +} + +function escapeStringValue(value) { + if (value[0] === '$') { + // We need to escape $ prefixed strings since we use those to encode + // references to IDs and as special symbol values. + return '$' + value; + } else { + return value; + } +} + +var insideContextProps = null; +var isInsideContextValue = false; + +function resolveModelToJSON(request, parent, key, value) { + // Make sure that `parent[key]` wasn't JSONified before `value` was passed to us + { + // $FlowFixMe[incompatible-use] + var originalValue = parent[key]; + + if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) { + if (objectName(originalValue) !== 'Object') { + var jsxParentType = jsxChildrenParents.get(parent); + + if (typeof jsxParentType === 'string') { + error('%s objects cannot be rendered as text children. Try formatting it using toString().%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } else { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } + } else { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props.%s', describeObjectForErrorMessage(parent, key)); + } + } + } // Special Symbols + + + switch (value) { + case REACT_ELEMENT_TYPE: + return '$'; + } + + { + if (parent[0] === REACT_ELEMENT_TYPE && parent[1] && parent[1].$$typeof === REACT_PROVIDER_TYPE && key === '3') { + insideContextProps = value; + } else if (insideContextProps === parent && key === 'value') { + isInsideContextValue = true; + } else if (insideContextProps === parent && key === 'children') { + isInsideContextValue = false; + } + } // Resolve Server Components. + + + while (typeof value === 'object' && value !== null && (value.$$typeof === REACT_ELEMENT_TYPE || value.$$typeof === REACT_LAZY_TYPE)) { + { + if (isInsideContextValue) { + error('React elements are not allowed in ServerContext'); + } + } + + try { + switch (value.$$typeof) { + case REACT_ELEMENT_TYPE: + { + // TODO: Concatenate keys of parents onto children. + var element = value; // Attempt to render the Server Component. + + value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, null); + break; + } + + case REACT_LAZY_TYPE: + { + var payload = value._payload; + var init = value._init; + value = init(payload); + break; + } + } + } catch (thrownValue) { + var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical + // reasons, the rest of the Suspense implementation expects the thrown + // value to be a thenable, because before `use` existed that was the + // (unstable) API for suspending. This implementation detail can change + // later, once we deprecate the old API in favor of `use`. + getSuspendedThenable() : thrownValue; + + if (typeof x === 'object' && x !== null) { + // $FlowFixMe[method-unbinding] + if (typeof x.then === 'function') { + // Something suspended, we'll need to create a new task and resolve it later. + request.pendingChunks++; + var newTask = createTask(request, value, getActiveContext(), request.abortableTasks); + var ping = newTask.ping; + x.then(ping, ping); + newTask.thenableState = getThenableStateAfterSuspending(); + return serializeLazyID(newTask.id); + } else if (x.$$typeof === REACT_POSTPONE_TYPE) { + // Something postponed. We'll still send everything we have up until this point. + // We'll replace this element with a lazy reference that postpones on the client. + var postponeInstance = x; + request.pendingChunks++; + var postponeId = request.nextChunkId++; + logPostpone(request, postponeInstance.message); + emitPostponeChunk(request, postponeId, postponeInstance); + return serializeLazyID(postponeId); + } + } // Something errored. We'll still send everything we have up until this point. + // We'll replace this element with a lazy reference that throws on the client + // once it gets rendered. + + + request.pendingChunks++; + var errorId = request.nextChunkId++; + var digest = logRecoverableError(request, x); + emitErrorChunk(request, errorId, digest, x); + return serializeLazyID(errorId); + } + } + + if (value === null) { + return null; + } + + if (typeof value === 'object') { + if (isClientReference(value)) { + return serializeClientReference(request, parent, key, value); // $FlowFixMe[method-unbinding] + } else if (typeof value.then === 'function') { + // We assume that any object with a .then property is a "Thenable" type, + // or a Promise type. Either of which can be represented by a Promise. + var promiseId = serializeThenable(request, value); + return serializePromiseID(promiseId); + } else if (value.$$typeof === REACT_PROVIDER_TYPE) { + var providerKey = value._context._globalName; + var writtenProviders = request.writtenProviders; + var providerId = writtenProviders.get(key); + + if (providerId === undefined) { + request.pendingChunks++; + providerId = request.nextChunkId++; + writtenProviders.set(providerKey, providerId); + emitProviderChunk(request, providerId, providerKey); + } + + return serializeByValueID(providerId); + } else if (value === POP) { + popProvider(); + + { + insideContextProps = null; + isInsideContextValue = false; + } + + return undefined; + } + + if (value instanceof Map) { + return serializeMap(request, value); + } + + if (value instanceof Set) { + return serializeSet(request, value); + } + + { + if (value instanceof ArrayBuffer) { + return serializeTypedArray(request, 'A', new Uint8Array(value)); + } + + if (value instanceof Int8Array) { + // char + return serializeTypedArray(request, 'C', value); + } + + if (value instanceof Uint8Array) { + // unsigned char + return serializeTypedArray(request, 'c', value); + } + + if (value instanceof Uint8ClampedArray) { + // unsigned clamped char + return serializeTypedArray(request, 'U', value); + } + + if (value instanceof Int16Array) { + // sort + return serializeTypedArray(request, 'S', value); + } + + if (value instanceof Uint16Array) { + // unsigned short + return serializeTypedArray(request, 's', value); + } + + if (value instanceof Int32Array) { + // long + return serializeTypedArray(request, 'L', value); + } + + if (value instanceof Uint32Array) { + // unsigned long + return serializeTypedArray(request, 'l', value); + } + + if (value instanceof Float32Array) { + // float + return serializeTypedArray(request, 'F', value); + } + + if (value instanceof Float64Array) { + // double + return serializeTypedArray(request, 'D', value); + } + + if (value instanceof BigInt64Array) { + // number + return serializeTypedArray(request, 'N', value); + } + + if (value instanceof BigUint64Array) { + // unsigned number + // We use "m" instead of "n" since JSON can start with "null" + return serializeTypedArray(request, 'm', value); + } + + if (value instanceof DataView) { + return serializeTypedArray(request, 'V', value); + } + } + + if (!isArray(value)) { + var iteratorFn = getIteratorFn(value); + + if (iteratorFn) { + return Array.from(value); + } + } + + { + if (value !== null && !isArray(value)) { + // Verify that this is a simple plain object. + if (objectName(value) !== 'Object') { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, key)); + } else if (!isSimpleObject(value)) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Classes or other objects with methods are not supported.%s', describeObjectForErrorMessage(parent, key)); + } else if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(value); + + if (symbols.length > 0) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with symbol properties like %s are not supported.%s', symbols[0].description, describeObjectForErrorMessage(parent, key)); + } + } + } + } // $FlowFixMe[incompatible-return] + + + return value; + } + + if (typeof value === 'string') { + // TODO: Maybe too clever. If we support URL there's no similar trick. + if (value[value.length - 1] === 'Z') { + // Possibly a Date, whose toJSON automatically calls toISOString + // $FlowFixMe[incompatible-use] + var _originalValue = parent[key]; + + if (_originalValue instanceof Date) { + return serializeDateFromDateJSON(value); + } + } + + if (value.length >= 1024) { + // For large strings, we encode them outside the JSON payload so that we + // don't have to double encode and double parse the strings. This can also + // be more compact in case the string has a lot of escaped characters. + return serializeLargeTextString(request, value); + } + + return escapeStringValue(value); + } + + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return serializeNumber(value); + } + + if (typeof value === 'undefined') { + return serializeUndefined(); + } + + if (typeof value === 'function') { + if (isClientReference(value)) { + return serializeClientReference(request, parent, key, value); + } + + if (isServerReference(value)) { + return serializeServerReference(request, parent, key, value); + } + + if (/^on[A-Z]/.test(key)) { + throw new Error('Event handlers cannot be passed to Client Component props.' + describeObjectForErrorMessage(parent, key) + '\nIf you need interactivity, consider converting part of this to a Client Component.'); + } else { + throw new Error('Functions cannot be passed directly to Client Components ' + 'unless you explicitly expose it by marking it with "use server".' + describeObjectForErrorMessage(parent, key)); + } + } + + if (typeof value === 'symbol') { + var writtenSymbols = request.writtenSymbols; + var existingId = writtenSymbols.get(value); + + if (existingId !== undefined) { + return serializeByValueID(existingId); + } // $FlowFixMe[incompatible-type] `description` might be undefined + + + var name = value.description; + + if (Symbol.for(name) !== value) { + throw new Error('Only global symbols received from Symbol.for(...) can be passed to Client Components. ' + ("The symbol Symbol.for(" + // $FlowFixMe[incompatible-type] `description` might be undefined + value.description + ") cannot be found among global symbols.") + describeObjectForErrorMessage(parent, key)); + } + + request.pendingChunks++; + var symbolId = request.nextChunkId++; + emitSymbolChunk(request, symbolId, name); + writtenSymbols.set(value, symbolId); + return serializeByValueID(symbolId); + } + + if (typeof value === 'bigint') { + return serializeBigInt(value); + } + + throw new Error("Type " + typeof value + " is not supported in Client Component props." + describeObjectForErrorMessage(parent, key)); +} + +function logPostpone(request, reason) { + var onPostpone = request.onPostpone; + onPostpone(reason); +} + +function logRecoverableError(request, error) { + var onError = request.onError; + var errorDigest = onError(error); + + if (errorDigest != null && typeof errorDigest !== 'string') { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead"); + } + + return errorDigest || ''; +} + +function fatalError(request, error) { + // This is called outside error handling code such as if an error happens in React internals. + if (request.destination !== null) { + request.status = CLOSED; + closeWithError(request.destination, error); + } else { + request.status = CLOSING; + request.fatalError = error; + } +} + +function emitPostponeChunk(request, id, postponeInstance) { + var row; + + { + var reason = ''; + var stack = ''; + + try { + // eslint-disable-next-line react-internal/safe-string-coercion + reason = String(postponeInstance.message); // eslint-disable-next-line react-internal/safe-string-coercion + + stack = String(postponeInstance.stack); + } catch (x) {} + + row = serializeRowHeader('P', id) + stringify({ + reason: reason, + stack: stack + }) + '\n'; + } + + var processedChunk = stringToChunk(row); + request.completedErrorChunks.push(processedChunk); +} + +function emitErrorChunk(request, id, digest, error) { + var errorInfo; + + { + var message; + var stack = ''; + + try { + if (error instanceof Error) { + // eslint-disable-next-line react-internal/safe-string-coercion + message = String(error.message); // eslint-disable-next-line react-internal/safe-string-coercion + + stack = String(error.stack); + } else { + message = 'Error: ' + error; + } + } catch (x) { + message = 'An error occurred but serializing the error message failed.'; + } + + errorInfo = { + digest: digest, + message: message, + stack: stack + }; + } + + var row = serializeRowHeader('E', id) + stringify(errorInfo) + '\n'; + var processedChunk = stringToChunk(row); + request.completedErrorChunks.push(processedChunk); +} + +function emitImportChunk(request, id, clientReferenceMetadata) { + // $FlowFixMe[incompatible-type] stringify can return null + var json = stringify(clientReferenceMetadata); + var row = serializeRowHeader('I', id) + json + '\n'; + var processedChunk = stringToChunk(row); + request.completedImportChunks.push(processedChunk); +} + +function emitHintChunk(request, code, model) { + var json = stringify(model); + var id = request.nextChunkId++; + var row = serializeRowHeader('H' + code, id) + json + '\n'; + var processedChunk = stringToChunk(row); + request.completedHintChunks.push(processedChunk); +} + +function emitSymbolChunk(request, id, name) { + var symbolReference = serializeSymbolReference(name); + var processedChunk = encodeReferenceChunk(request, id, symbolReference); + request.completedImportChunks.push(processedChunk); +} + +function emitProviderChunk(request, id, contextName) { + var contextReference = serializeProviderReference(contextName); + var processedChunk = encodeReferenceChunk(request, id, contextReference); + request.completedRegularChunks.push(processedChunk); +} + +function emitModelChunk(request, id, model) { + // $FlowFixMe[incompatible-type] stringify can return null + var json = stringify(model, request.toJSON); + var row = id.toString(16) + ':' + json + '\n'; + var processedChunk = stringToChunk(row); + request.completedRegularChunks.push(processedChunk); +} + +function retryTask(request, task) { + if (task.status !== PENDING$1) { + // We completed this by other means before we had a chance to retry it. + return; + } + + switchContext(task.context); + + try { + var value = task.model; + + if (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) { + // TODO: Concatenate keys of parents onto children. + var element = value; // When retrying a component, reuse the thenableState from the + // previous attempt. + + var prevThenableState = task.thenableState; // Attempt to render the Server Component. + // Doing this here lets us reuse this same task if the next component + // also suspends. + + task.model = value; + value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, prevThenableState); // Successfully finished this component. We're going to keep rendering + // using the same task, but we reset its thenable state before continuing. + + task.thenableState = null; // Keep rendering and reuse the same task. This inner loop is separate + // from the render above because we don't need to reset the thenable state + // until the next time something suspends and retries. + + while (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) { + // TODO: Concatenate keys of parents onto children. + var nextElement = value; + task.model = value; + value = attemptResolveElement(request, nextElement.type, nextElement.key, nextElement.ref, nextElement.props, null); + } + } + + emitModelChunk(request, task.id, value); + request.abortableTasks.delete(task); + task.status = COMPLETED; + } catch (thrownValue) { + var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical + // reasons, the rest of the Suspense implementation expects the thrown + // value to be a thenable, because before `use` existed that was the + // (unstable) API for suspending. This implementation detail can change + // later, once we deprecate the old API in favor of `use`. + getSuspendedThenable() : thrownValue; + + if (typeof x === 'object' && x !== null) { + // $FlowFixMe[method-unbinding] + if (typeof x.then === 'function') { + // Something suspended again, let's pick it back up later. + var ping = task.ping; + x.then(ping, ping); + task.thenableState = getThenableStateAfterSuspending(); + return; + } else if (x.$$typeof === REACT_POSTPONE_TYPE) { + request.abortableTasks.delete(task); + task.status = ERRORED$1; + var postponeInstance = x; + logPostpone(request, postponeInstance.message); + emitPostponeChunk(request, task.id, postponeInstance); + return; + } + } + + request.abortableTasks.delete(task); + task.status = ERRORED$1; + var digest = logRecoverableError(request, x); + emitErrorChunk(request, task.id, digest, x); + } +} + +function performWork(request) { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = HooksDispatcher; + var prevRequest = currentRequest; + currentRequest = request; + prepareToUseHooksForRequest(request); + + try { + var pingedTasks = request.pingedTasks; + request.pingedTasks = []; + + for (var i = 0; i < pingedTasks.length; i++) { + var task = pingedTasks[i]; + retryTask(request, task); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } finally { + ReactCurrentDispatcher.current = prevDispatcher; + resetHooksForRequest(); + currentRequest = prevRequest; + } +} + +function abortTask(task, request, errorId) { + task.status = ABORTED; // Instead of emitting an error per task.id, we emit a model that only + // has a single value referencing the error. + + var ref = serializeByValueID(errorId); + var processedChunk = encodeReferenceChunk(request, task.id, ref); + request.completedErrorChunks.push(processedChunk); +} + +function flushCompletedChunks(request, destination) { + beginWriting(); + + try { + // We emit module chunks first in the stream so that + // they can be preloaded as early as possible. + var importsChunks = request.completedImportChunks; + var i = 0; + + for (; i < importsChunks.length; i++) { + request.pendingChunks--; + var chunk = importsChunks[i]; + var keepWriting = writeChunkAndReturn(destination, chunk); + + if (!keepWriting) { + request.destination = null; + i++; + break; + } + } + + importsChunks.splice(0, i); // Next comes hints. + + var hintChunks = request.completedHintChunks; + i = 0; + + for (; i < hintChunks.length; i++) { + var _chunk = hintChunks[i]; + + var _keepWriting = writeChunkAndReturn(destination, _chunk); + + if (!_keepWriting) { + request.destination = null; + i++; + break; + } + } + + hintChunks.splice(0, i); // Next comes model data. + + var regularChunks = request.completedRegularChunks; + i = 0; + + for (; i < regularChunks.length; i++) { + request.pendingChunks--; + var _chunk2 = regularChunks[i]; + + var _keepWriting2 = writeChunkAndReturn(destination, _chunk2); + + if (!_keepWriting2) { + request.destination = null; + i++; + break; + } + } + + regularChunks.splice(0, i); // Finally, errors are sent. The idea is that it's ok to delay + // any error messages and prioritize display of other parts of + // the page. + + var errorChunks = request.completedErrorChunks; + i = 0; + + for (; i < errorChunks.length; i++) { + request.pendingChunks--; + var _chunk3 = errorChunks[i]; + + var _keepWriting3 = writeChunkAndReturn(destination, _chunk3); + + if (!_keepWriting3) { + request.destination = null; + i++; + break; + } + } + + errorChunks.splice(0, i); + } finally { + request.flushScheduled = false; + completeWriting(destination); + } + + flushBuffered(destination); + + if (request.pendingChunks === 0) { + // We're done. + close$1(destination); + } +} + +function startWork(request) { + request.flushScheduled = request.destination !== null; + + { + scheduleWork(function () { + return requestStorage.run(request, performWork, request); + }); + } +} + +function enqueueFlush(request) { + if (request.flushScheduled === false && // If there are pinged tasks we are going to flush anyway after work completes + request.pingedTasks.length === 0 && // If there is no destination there is nothing we can flush to. A flush will + // happen when we start flowing again + request.destination !== null) { + var destination = request.destination; + request.flushScheduled = true; + scheduleWork(function () { + return flushCompletedChunks(request, destination); + }); + } +} + +function startFlowing(request, destination) { + if (request.status === CLOSING) { + request.status = CLOSED; + closeWithError(destination, request.fatalError); + return; + } + + if (request.status === CLOSED) { + return; + } + + if (request.destination !== null) { + // We're already flowing. + return; + } + + request.destination = destination; + + try { + flushCompletedChunks(request, destination); + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} + +function abort(request, reason) { + try { + var abortableTasks = request.abortableTasks; + + if (abortableTasks.size > 0) { + // We have tasks to abort. We'll emit one error row and then emit a reference + // to that row from every row that's still remaining. + var error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason; + var digest = logRecoverableError(request, error); + request.pendingChunks++; + var errorId = request.nextChunkId++; + emitErrorChunk(request, errorId, digest, error); + abortableTasks.forEach(function (task) { + return abortTask(task, request, errorId); + }); + abortableTasks.clear(); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} + +function importServerContexts(contexts) { + if (contexts) { + var prevContext = getActiveContext(); + switchContext(rootContextSnapshot); + + for (var i = 0; i < contexts.length; i++) { + var _contexts$i = contexts[i], + name = _contexts$i[0], + value = _contexts$i[1]; + var context = getOrCreateServerContext(name); + pushProvider(context, value); + } + + var importedContext = getActiveContext(); + switchContext(prevContext); + return importedContext; + } + + return rootContextSnapshot; +} + +// This is the parsed shape of the wire format which is why it is +// condensed to only the essentialy information +var ID = 0; +var CHUNKS = 1; +var NAME = 2; // export const ASYNC = 3; +// This logic is correct because currently only include the 4th tuple member +// when the module is async. If that changes we will need to actually assert +// the value is true. We don't index into the 4th slot because flow does not +// like the potential out of bounds access + +function isAsyncImport(metadata) { + return metadata.length === 4; +} + +function resolveServerReference(bundlerConfig, id) { + var name = ''; + var resolvedModuleData = bundlerConfig[id]; + + if (resolvedModuleData) { + // The potentially aliased name. + name = resolvedModuleData.name; + } else { + // We didn't find this specific export name but we might have the * export + // which contains this name as well. + // TODO: It's unfortunate that we now have to parse this string. We should + // probably go back to encoding path and name separately on the client reference. + var idx = id.lastIndexOf('#'); + + if (idx !== -1) { + name = id.slice(idx + 1); + resolvedModuleData = bundlerConfig[id.slice(0, idx)]; + } + + if (!resolvedModuleData) { + throw new Error('Could not find the module "' + id + '" in the React Server Manifest. ' + 'This is probably a bug in the React Server Components bundler.'); + } + } // TODO: This needs to return async: true if it's an async module. + + + return [resolvedModuleData.id, resolvedModuleData.chunks, name]; +} // The chunk cache contains all the chunks we've preloaded so far. +// If they're still pending they're a thenable. This map also exists +// in Turbopack but unfortunately it's not exposed so we have to +// replicate it in user space. null means that it has already loaded. + +var chunkCache = new Map(); + +function requireAsyncModule(id) { + // We've already loaded all the chunks. We can require the module. + var promise = globalThis.__next_require__(id); + + if (typeof promise.then !== 'function') { + // This wasn't a promise after all. + return null; + } else if (promise.status === 'fulfilled') { + // This module was already resolved earlier. + return null; + } else { + // Instrument the Promise to stash the result. + promise.then(function (value) { + var fulfilledThenable = promise; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = value; + }, function (reason) { + var rejectedThenable = promise; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = reason; + }); + return promise; + } +} + +function ignoreReject() {// We rely on rejected promises to be handled by another listener. +} // Start preloading the modules since we might need them soon. +// This function doesn't suspend. + + +function preloadModule(metadata) { + var chunks = metadata[CHUNKS]; + var promises = []; + + for (var i = 0; i < chunks.length; i++) { + var chunkFilename = chunks[i]; + var entry = chunkCache.get(chunkFilename); + + if (entry === undefined) { + var thenable = loadChunk(chunkFilename); + promises.push(thenable); // $FlowFixMe[method-unbinding] + + var resolve = chunkCache.set.bind(chunkCache, chunkFilename, null); + thenable.then(resolve, ignoreReject); + chunkCache.set(chunkFilename, thenable); + } else if (entry !== null) { + promises.push(entry); + } + } + + if (isAsyncImport(metadata)) { + if (promises.length === 0) { + return requireAsyncModule(metadata[ID]); + } else { + return Promise.all(promises).then(function () { + return requireAsyncModule(metadata[ID]); + }); + } + } else if (promises.length > 0) { + return Promise.all(promises); + } else { + return null; + } +} // Actually require the module or suspend if it's not yet ready. +// Increase priority if necessary. + +function requireModule(metadata) { + var moduleExports = globalThis.__next_require__(metadata[ID]); + + if (isAsyncImport(metadata)) { + if (typeof moduleExports.then !== 'function') ; else if (moduleExports.status === 'fulfilled') { + // This Promise should've been instrumented by preloadModule. + moduleExports = moduleExports.value; + } else { + throw moduleExports.reason; + } + } + + if (metadata[NAME] === '*') { + // This is a placeholder value that represents that the caller imported this + // as a CommonJS module as is. + return moduleExports; + } + + if (metadata[NAME] === '') { + // This is a placeholder value that represents that the caller accessed the + // default property of this if it was an ESM interop module. + return moduleExports.__esModule ? moduleExports.default : moduleExports; + } + + return moduleExports[metadata[NAME]]; +} + +function loadChunk(filename) { + return globalThis.__next_chunk_load__(filename); +} + +// The server acts as a Client of itself when resolving Server References. +var PENDING = 'pending'; +var BLOCKED = 'blocked'; +var RESOLVED_MODEL = 'resolved_model'; +var INITIALIZED = 'fulfilled'; +var ERRORED = 'rejected'; // $FlowFixMe[missing-this-annot] + +function Chunk(status, value, reason, response) { + this.status = status; + this.value = value; + this.reason = reason; + this._response = response; +} // We subclass Promise.prototype so that we get other methods like .catch + + +Chunk.prototype = Object.create(Promise.prototype); // TODO: This doesn't return a new Promise chain unlike the real .then + +Chunk.prototype.then = function (resolve, reject) { + var chunk = this; // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + resolve(chunk.value); + break; + + case PENDING: + case BLOCKED: + if (resolve) { + if (chunk.value === null) { + chunk.value = []; + } + + chunk.value.push(resolve); + } + + if (reject) { + if (chunk.reason === null) { + chunk.reason = []; + } + + chunk.reason.push(reject); + } + + break; + + default: + reject(chunk.reason); + break; + } +}; + +function getRoot(response) { + var chunk = getChunk(response, 0); + return chunk; +} + +function createPendingChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(PENDING, null, null, response); +} + +function wakeChunk(listeners, value) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + listener(value); + } +} + +function wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners) { + switch (chunk.status) { + case INITIALIZED: + wakeChunk(resolveListeners, chunk.value); + break; + + case PENDING: + case BLOCKED: + chunk.value = resolveListeners; + chunk.reason = rejectListeners; + break; + + case ERRORED: + if (rejectListeners) { + wakeChunk(rejectListeners, chunk.reason); + } + + break; + } +} + +function triggerErrorOnChunk(chunk, error) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var listeners = chunk.reason; + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + + if (listeners !== null) { + wakeChunk(listeners, error); + } +} + +function createResolvedModelChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODEL, value, null, response); +} + +function resolveModelChunk(chunk, value) { + if (chunk.status !== PENDING) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODEL; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + // This is unfortunate that we're reading this eagerly if + // we already have listeners attached since they might no + // longer be rendered or might not be the highest pri. + initializeModelChunk(resolvedChunk); // The status might have changed after initialization. + + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +function bindArgs$1(fn, args) { + return fn.bind.apply(fn, [null].concat(args)); +} + +function loadServerReference$1(response, id, bound, parentChunk, parentObject, key) { + var serverReference = resolveServerReference(response._bundlerConfig, id); // We expect most servers to not really need this because you'd just have all + // the relevant modules already loaded but it allows for lazy loading of code + // if needed. + + var preloadPromise = preloadModule(serverReference); + var promise; + + if (bound) { + promise = Promise.all([bound, preloadPromise]).then(function (_ref) { + var args = _ref[0]; + return bindArgs$1(requireModule(serverReference), args); + }); + } else { + if (preloadPromise) { + promise = Promise.resolve(preloadPromise).then(function () { + return requireModule(serverReference); + }); + } else { + // Synchronously available + return requireModule(serverReference); + } + } + + promise.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); // We need a placeholder value that will be replaced later. + + return null; +} + +var initializingChunk = null; +var initializingChunkBlockedModel = null; + +function initializeModelChunk(chunk) { + var prevChunk = initializingChunk; + var prevBlocked = initializingChunkBlockedModel; + initializingChunk = chunk; + initializingChunkBlockedModel = null; + + try { + var value = JSON.parse(chunk.value, chunk._response._fromJSON); + + if (initializingChunkBlockedModel !== null && initializingChunkBlockedModel.deps > 0) { + initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved. + // We have to go the BLOCKED state until they're resolved. + + var blockedChunk = chunk; + blockedChunk.status = BLOCKED; + blockedChunk.value = null; + blockedChunk.reason = null; + } else { + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } finally { + initializingChunk = prevChunk; + initializingChunkBlockedModel = prevBlocked; + } +} // Report that any missing chunks in the model is now going to throw this +// error upon read. Also notify any pending promises. + + +function reportGlobalError(response, error) { + response._chunks.forEach(function (chunk) { + // If this chunk was already resolved or errored, it won't + // trigger an error but if it wasn't then we need to + // because we won't be getting any new data to resolve it. + if (chunk.status === PENDING) { + triggerErrorOnChunk(chunk, error); + } + }); +} + +function getChunk(response, id) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + var prefix = response._prefix; + var key = prefix + id; // Check if we have this field in the backing store already. + + var backingEntry = response._formData.get(key); + + if (backingEntry != null) { + // We assume that this is a string entry for now. + chunk = createResolvedModelChunk(response, backingEntry); + } else { + // We're still waiting on this entry to stream in. + chunk = createPendingChunk(response); + } + + chunks.set(id, chunk); + } + + return chunk; +} + +function createModelResolver(chunk, parentObject, key) { + var blocked; + + if (initializingChunkBlockedModel) { + blocked = initializingChunkBlockedModel; + blocked.deps++; + } else { + blocked = initializingChunkBlockedModel = { + deps: 1, + value: null + }; + } + + return function (value) { + parentObject[key] = value; + blocked.deps--; + + if (blocked.deps === 0) { + if (chunk.status !== BLOCKED) { + return; + } + + var resolveListeners = chunk.value; + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = blocked.value; + + if (resolveListeners !== null) { + wakeChunk(resolveListeners, blocked.value); + } + } + }; +} + +function createModelReject(chunk) { + return function (error) { + return triggerErrorOnChunk(chunk, error); + }; +} + +function getOutlinedModel(response, id) { + var chunk = getChunk(response, id); + + if (chunk.status === RESOLVED_MODEL) { + initializeModelChunk(chunk); + } + + if (chunk.status !== INITIALIZED) { + // We know that this is emitted earlier so otherwise it's an error. + throw chunk.reason; + } + + return chunk.value; +} + +function parseModelString(response, parentObject, key, value) { + if (value[0] === '$') { + switch (value[1]) { + case '$': + { + // This was an escaped string value. + return value.slice(1); + } + + case '@': + { + // Promise + var id = parseInt(value.slice(2), 16); + var chunk = getChunk(response, id); + return chunk; + } + + case 'S': + { + // Symbol + return Symbol.for(value.slice(2)); + } + + case 'F': + { + // Server Reference + var _id = parseInt(value.slice(2), 16); // TODO: Just encode this in the reference inline instead of as a model. + + + var metaData = getOutlinedModel(response, _id); + return loadServerReference$1(response, metaData.id, metaData.bound, initializingChunk, parentObject, key); + } + + case 'Q': + { + // Map + var _id2 = parseInt(value.slice(2), 16); + + var data = getOutlinedModel(response, _id2); + return new Map(data); + } + + case 'W': + { + // Set + var _id3 = parseInt(value.slice(2), 16); + + var _data = getOutlinedModel(response, _id3); + + return new Set(_data); + } + + case 'K': + { + // FormData + var stringId = value.slice(2); + var formPrefix = response._prefix + stringId + '_'; + + var _data2 = new FormData(); + + var backingFormData = response._formData; // We assume that the reference to FormData always comes after each + // entry that it references so we can assume they all exist in the + // backing store already. + // $FlowFixMe[prop-missing] FormData has forEach on it. + + backingFormData.forEach(function (entry, entryKey) { + if (entryKey.startsWith(formPrefix)) { + _data2.append(entryKey.slice(formPrefix.length), entry); + } + }); + return _data2; + } + + case 'I': + { + // $Infinity + return Infinity; + } + + case '-': + { + // $-0 or $-Infinity + if (value === '$-0') { + return -0; + } else { + return -Infinity; + } + } + + case 'N': + { + // $NaN + return NaN; + } + + case 'u': + { + // matches "$undefined" + // Special encoding for `undefined` which can't be serialized as JSON otherwise. + return undefined; + } + + case 'D': + { + // Date + return new Date(Date.parse(value.slice(2))); + } + + case 'n': + { + // BigInt + return BigInt(value.slice(2)); + } + + default: + { + // We assume that anything else is a reference ID. + var _id4 = parseInt(value.slice(1), 16); + + var _chunk = getChunk(response, _id4); + + switch (_chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk); + break; + } // The status might have changed after initialization. + + + switch (_chunk.status) { + case INITIALIZED: + return _chunk.value; + + case PENDING: + case BLOCKED: + var parentChunk = initializingChunk; + + _chunk.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); + + return null; + + default: + throw _chunk.reason; + } + } + } + } + + return value; +} + +function createResponse(bundlerConfig, formFieldPrefix) { + var backingFormData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new FormData(); + var chunks = new Map(); + var response = { + _bundlerConfig: bundlerConfig, + _prefix: formFieldPrefix, + _formData: backingFormData, + _chunks: chunks, + _fromJSON: function (key, value) { + if (typeof value === 'string') { + // We can't use .bind here because we need the "this" value. + return parseModelString(response, this, key, value); + } + + return value; + } + }; + return response; +} +function resolveField(response, key, value) { + // Add this field to the backing store. + response._formData.append(key, value); + + var prefix = response._prefix; + + if (key.startsWith(prefix)) { + var chunks = response._chunks; + var id = +key.slice(prefix.length); + var chunk = chunks.get(id); + + if (chunk) { + // We were waiting on this key so now we can resolve it. + resolveModelChunk(chunk, value); + } + } +} +function resolveFileInfo(response, key, filename, mime) { + return { + chunks: [], + filename: filename, + mime: mime + }; +} +function resolveFileChunk(response, handle, chunk) { + handle.chunks.push(chunk); +} +function resolveFileComplete(response, key, handle) { + // Add this file to the backing store. + // Node.js doesn't expose a global File constructor so we need to use + // the append() form that takes the file name as the third argument, + // to create a File object. + var blob = new Blob(handle.chunks, { + type: handle.mime + }); + + response._formData.append(key, blob, handle.filename); +} +function close(response) { + // In case there are any remaining unresolved chunks, they won't + // be resolved now. So we need to issue an error to those. + // Ideally we should be able to early bail out if we kept a + // ref count of pending chunks. + reportGlobalError(response, new Error('Connection closed.')); +} + +function bindArgs(fn, args) { + return fn.bind.apply(fn, [null].concat(args)); +} + +function loadServerReference(bundlerConfig, id, bound) { + var serverReference = resolveServerReference(bundlerConfig, id); // We expect most servers to not really need this because you'd just have all + // the relevant modules already loaded but it allows for lazy loading of code + // if needed. + + var preloadPromise = preloadModule(serverReference); + + if (bound) { + return Promise.all([bound, preloadPromise]).then(function (_ref) { + var args = _ref[0]; + return bindArgs(requireModule(serverReference), args); + }); + } else if (preloadPromise) { + return Promise.resolve(preloadPromise).then(function () { + return requireModule(serverReference); + }); + } else { + // Synchronously available + return Promise.resolve(requireModule(serverReference)); + } +} + +function decodeBoundActionMetaData(body, serverManifest, formFieldPrefix) { + // The data for this reference is encoded in multiple fields under this prefix. + var actionResponse = createResponse(serverManifest, formFieldPrefix, body); + close(actionResponse); + var refPromise = getRoot(actionResponse); // Force it to initialize + // $FlowFixMe + + refPromise.then(function () {}); + + if (refPromise.status !== 'fulfilled') { + // $FlowFixMe + throw refPromise.reason; + } + + return refPromise.value; +} + +function decodeAction(body, serverManifest) { + // We're going to create a new formData object that holds all the fields except + // the implementation details of the action data. + var formData = new FormData(); + var action = null; // $FlowFixMe[prop-missing] + + body.forEach(function (value, key) { + if (!key.startsWith('$ACTION_')) { + formData.append(key, value); + return; + } // Later actions may override earlier actions if a button is used to override the default + // form action. + + + if (key.startsWith('$ACTION_REF_')) { + var formFieldPrefix = '$ACTION_' + key.slice(12) + ':'; + var metaData = decodeBoundActionMetaData(body, serverManifest, formFieldPrefix); + action = loadServerReference(serverManifest, metaData.id, metaData.bound); + return; + } + + if (key.startsWith('$ACTION_ID_')) { + var id = key.slice(11); + action = loadServerReference(serverManifest, id, null); + return; + } + }); + + if (action === null) { + return null; + } // Return the action with the remaining FormData bound to the first argument. + + + return action.then(function (fn) { + return fn.bind(null, formData); + }); +} + +function createDrainHandler(destination, request) { + return function () { + return startFlowing(request, destination); + }; +} + +function renderToPipeableStream(model, turbopackMap, options) { + var request = createRequest(model, turbopackMap, options ? options.onError : undefined, options ? options.context : undefined, options ? options.identifierPrefix : undefined, options ? options.onPostpone : undefined); + var hasStartedFlowing = false; + startWork(request); + return { + pipe: function (destination) { + if (hasStartedFlowing) { + throw new Error('React currently only supports piping to one writable stream.'); + } + + hasStartedFlowing = true; + startFlowing(request, destination); + destination.on('drain', createDrainHandler(destination, request)); + return destination; + }, + abort: function (reason) { + abort(request, reason); + } + }; +} + +function decodeReplyFromBusboy(busboyStream, turbopackMap) { + var response = createResponse(turbopackMap, ''); + var pendingFiles = 0; + var queuedFields = []; + busboyStream.on('field', function (name, value) { + if (pendingFiles > 0) { + // Because the 'end' event fires two microtasks after the next 'field' + // we would resolve files and fields out of order. To handle this properly + // we queue any fields we receive until the previous file is done. + queuedFields.push(name, value); + } else { + resolveField(response, name, value); + } + }); + busboyStream.on('file', function (name, value, _ref) { + var filename = _ref.filename, + encoding = _ref.encoding, + mimeType = _ref.mimeType; + + if (encoding.toLowerCase() === 'base64') { + throw new Error("React doesn't accept base64 encoded file uploads because we don't expect " + "form data passed from a browser to ever encode data that way. If that's " + 'the wrong assumption, we can easily fix it.'); + } + + pendingFiles++; + var file = resolveFileInfo(response, name, filename, mimeType); + value.on('data', function (chunk) { + resolveFileChunk(response, file, chunk); + }); + value.on('end', function () { + resolveFileComplete(response, name, file); + pendingFiles--; + + if (pendingFiles === 0) { + // Release any queued fields + for (var i = 0; i < queuedFields.length; i += 2) { + resolveField(response, queuedFields[i], queuedFields[i + 1]); + } + + queuedFields.length = 0; + } + }); + }); + busboyStream.on('finish', function () { + close(response); + }); + busboyStream.on('error', function (err) { + reportGlobalError(response, // $FlowFixMe[incompatible-call] types Error and mixed are incompatible + err); + }); + return getRoot(response); +} + +function decodeReply(body, turbopackMap) { + if (typeof body === 'string') { + var form = new FormData(); + form.append('0', body); + body = form; + } + + var response = createResponse(turbopackMap, '', body); + close(response); + return getRoot(response); +} + +exports.createClientModuleProxy = createClientModuleProxy; +exports.decodeAction = decodeAction; +exports.decodeReply = decodeReply; +exports.decodeReplyFromBusboy = decodeReplyFromBusboy; +exports.registerClientReference = registerClientReference; +exports.registerServerReference = registerServerReference; +exports.renderToPipeableStream = renderToPipeableStream; + })(); +} diff --git a/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-server.node.production.min.js b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-server.node.production.min.js new file mode 100644 index 0000000000000..10d0e65f75a64 --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-server.node.production.min.js @@ -0,0 +1,80 @@ +/** + * @license React + * react-server-dom-turbopack-server.node.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var aa=require("util");require("crypto");var ba=require("async_hooks"),ca=require("react"),da=require("react-dom"),l=null,m=0,r=!0;function t(a,b){a=a.write(b);r=r&&a} +function u(a,b){if("string"===typeof b){if(0!==b.length)if(2048<3*b.length)0a.depth?Ia(b,a):Ja(b,a),F=a)}function La(a,b){var d=a._currentValue;a._currentValue=b;var c=F;return F=a={parent:c,depth:null===c?0:c.depth+1,context:a,parentValue:d,value:b}}var Ma=Error("Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`"); +function Na(){}function Oa(a,b,d){d=a[d];void 0===d?a.push(b):d!==b&&(b.then(Na,Na),b=d);switch(b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;default:if("string"!==typeof b.status)switch(a=b,a.status="pending",a.then(function(c){if("pending"===b.status){var e=b;e.status="fulfilled";e.value=c}},function(c){if("pending"===b.status){var e=b;e.status="rejected";e.reason=c}}),b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;}I=b;throw Ma;}}var I=null; +function Pa(){if(null===I)throw Error("Expected a suspended thenable. This is a bug in React. Please file an issue.");var a=I;I=null;return a}var J=null,K=0,L=null;function Qa(){var a=L;L=null;return a}function Ra(a){return a._currentValue} +var Va={useMemo:function(a){return a()},useCallback:function(a){return a},useDebugValue:function(){},useDeferredValue:M,useTransition:M,readContext:Ra,useContext:Ra,useReducer:M,useRef:M,useState:M,useInsertionEffect:M,useLayoutEffect:M,useImperativeHandle:M,useEffect:M,useId:Sa,useSyncExternalStore:M,useCacheRefresh:function(){return Ta},useMemoCache:function(a){for(var b=Array(a),d=0;d=a.length?a:a.slice(0,10)+"...");case "object":if(Za(a))return"[...]";a=$a(a);return"Object"===a?"{...}":a;case "function":return"function";default:return String(a)}} +function bb(a){if("string"===typeof a)return a;switch(a){case Aa:return"Suspense";case Ba:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case za:return bb(a.render);case Ca:return bb(a.type);case C:var b=a._payload;a=a._init;try{return bb(a(b))}catch(d){}}return""} +function N(a,b){var d=$a(a);if("Object"!==d&&"Array"!==d)return d;d=-1;var c=0;if(Za(a)){var e="[";for(var f=0;fg.length&&40>e.length+g.length?e+g:e+"..."}e+="]"}else if(a.$$typeof===B)e="<"+bb(a.type)+"/>";else{e="{";f=Object.keys(a);for(g=0;gk.length&&40>e.length+k.length?e+k:e+"..."}e+="}"}return void 0===b?e:-1 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +function scheduleWork(callback) { + setImmediate(callback); +} +function flushBuffered(destination) { + // If we don't have any more data to send right now. + // Flush whatever is in the buffer to the wire. + if (typeof destination.flush === 'function') { + // By convention the Zlib streams provide a flush function for this purpose. + // For Express, compression middleware adds this method. + destination.flush(); + } +} +var VIEW_SIZE = 2048; +var currentView = null; +var writtenBytes = 0; +var destinationHasCapacity = true; +function beginWriting(destination) { + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + destinationHasCapacity = true; +} + +function writeStringChunk(destination, stringChunk) { + if (stringChunk.length === 0) { + return; + } // maximum possible view needed to encode entire string + + + if (stringChunk.length * 3 > VIEW_SIZE) { + if (writtenBytes > 0) { + writeToDestination(destination, currentView.subarray(0, writtenBytes)); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + writeToDestination(destination, textEncoder.encode(stringChunk)); + return; + } + + var target = currentView; + + if (writtenBytes > 0) { + target = currentView.subarray(writtenBytes); + } + + var _textEncoder$encodeIn = textEncoder.encodeInto(stringChunk, target), + read = _textEncoder$encodeIn.read, + written = _textEncoder$encodeIn.written; + + writtenBytes += written; + + if (read < stringChunk.length) { + writeToDestination(destination, currentView.subarray(0, writtenBytes)); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = textEncoder.encodeInto(stringChunk.slice(read), currentView).written; + } + + if (writtenBytes === VIEW_SIZE) { + writeToDestination(destination, currentView); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } +} + +function writeViewChunk(destination, chunk) { + if (chunk.byteLength === 0) { + return; + } + + if (chunk.byteLength > VIEW_SIZE) { + { + if (precomputedChunkSet && precomputedChunkSet.has(chunk)) { + error('A large precomputed chunk was passed to writeChunk without being copied.' + ' Large chunks get enqueued directly and are not copied. This is incompatible with precomputed chunks because you cannot enqueue the same precomputed chunk twice.' + ' Use "cloneChunk" to make a copy of this large precomputed chunk before writing it. This is a bug in React.'); + } + } // this chunk may overflow a single view which implies it was not + // one that is cached by the streaming renderer. We will enqueu + // it directly and expect it is not re-used + + + if (writtenBytes > 0) { + writeToDestination(destination, currentView.subarray(0, writtenBytes)); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + writeToDestination(destination, chunk); + return; + } + + var bytesToWrite = chunk; + var allowableBytes = currentView.length - writtenBytes; + + if (allowableBytes < bytesToWrite.byteLength) { + // this chunk would overflow the current view. We enqueue a full view + // and start a new view with the remaining chunk + if (allowableBytes === 0) { + // the current view is already full, send it + writeToDestination(destination, currentView); + } else { + // fill up the current view and apply the remaining chunk bytes + // to a new view. + currentView.set(bytesToWrite.subarray(0, allowableBytes), writtenBytes); + writtenBytes += allowableBytes; + writeToDestination(destination, currentView); + bytesToWrite = bytesToWrite.subarray(allowableBytes); + } + + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + currentView.set(bytesToWrite, writtenBytes); + writtenBytes += bytesToWrite.byteLength; + + if (writtenBytes === VIEW_SIZE) { + writeToDestination(destination, currentView); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } +} + +function writeChunk(destination, chunk) { + if (typeof chunk === 'string') { + writeStringChunk(destination, chunk); + } else { + writeViewChunk(destination, chunk); + } +} + +function writeToDestination(destination, view) { + var currentHasCapacity = destination.write(view); + destinationHasCapacity = destinationHasCapacity && currentHasCapacity; +} + +function writeChunkAndReturn(destination, chunk) { + writeChunk(destination, chunk); + return destinationHasCapacity; +} +function completeWriting(destination) { + if (currentView && writtenBytes > 0) { + destination.write(currentView.subarray(0, writtenBytes)); + } + + currentView = null; + writtenBytes = 0; + destinationHasCapacity = true; +} +function close$1(destination) { + destination.end(); +} +var textEncoder = new util.TextEncoder(); +function stringToChunk(content) { + return content; +} +var precomputedChunkSet = new Set() ; +function typedArrayToBinaryChunk(content) { + // Convert any non-Uint8Array array to Uint8Array. We could avoid this for Uint8Arrays. + return new Uint8Array(content.buffer, content.byteOffset, content.byteLength); +} +function byteLengthOfChunk(chunk) { + return typeof chunk === 'string' ? Buffer.byteLength(chunk, 'utf8') : chunk.byteLength; +} +function byteLengthOfBinaryChunk(chunk) { + return chunk.byteLength; +} +function closeWithError(destination, error) { + // $FlowFixMe[incompatible-call]: This is an Error object or the destination accepts other types. + destination.destroy(error); +} + +// eslint-disable-next-line no-unused-vars +var CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference'); +var SERVER_REFERENCE_TAG = Symbol.for('react.server.reference'); +function isClientReference(reference) { + return reference.$$typeof === CLIENT_REFERENCE_TAG; +} +function isServerReference(reference) { + return reference.$$typeof === SERVER_REFERENCE_TAG; +} +function registerClientReference(proxyImplementation, id, exportName) { + return registerClientReferenceImpl(proxyImplementation, id + '#' + exportName, false); +} + +function registerClientReferenceImpl(proxyImplementation, id, async) { + return Object.defineProperties(proxyImplementation, { + $$typeof: { + value: CLIENT_REFERENCE_TAG + }, + $$id: { + value: id + }, + $$async: { + value: async + } + }); +} // $FlowFixMe[method-unbinding] + + +var FunctionBind = Function.prototype.bind; // $FlowFixMe[method-unbinding] + +var ArraySlice = Array.prototype.slice; + +function bind() { + // $FlowFixMe[unsupported-syntax] + var newFn = FunctionBind.apply(this, arguments); + + if (this.$$typeof === SERVER_REFERENCE_TAG) { + var args = ArraySlice.call(arguments, 1); + newFn.$$typeof = SERVER_REFERENCE_TAG; + newFn.$$id = this.$$id; + newFn.$$bound = this.$$bound ? this.$$bound.concat(args) : args; + } + + return newFn; +} + +function registerServerReference(reference, id, exportName) { + return Object.defineProperties(reference, { + $$typeof: { + value: SERVER_REFERENCE_TAG + }, + $$id: { + value: exportName === null ? id : id + '#' + exportName + }, + $$bound: { + value: null + }, + bind: { + value: bind + } + }); +} +var PROMISE_PROTOTYPE = Promise.prototype; +var deepProxyHandlers = { + get: function (target, name, receiver) { + switch (name) { + // These names are read by the Flight runtime if you end up using the exports object. + case '$$typeof': + // These names are a little too common. We should probably have a way to + // have the Flight runtime extract the inner target instead. + return target.$$typeof; + + case '$$id': + return target.$$id; + + case '$$async': + return target.$$async; + + case 'name': + return target.name; + + case 'displayName': + return undefined; + // We need to special case this because createElement reads it if we pass this + // reference. + + case 'defaultProps': + return undefined; + // Avoid this attempting to be serialized. + + case 'toJSON': + return undefined; + + case Symbol.toPrimitive: + // $FlowFixMe[prop-missing] + return Object.prototype[Symbol.toPrimitive]; + + case 'Provider': + throw new Error("Cannot render a Client Context Provider on the Server. " + "Instead, you can export a Client Component wrapper " + "that itself renders a Client Context Provider."); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var expression = String(target.name) + '.' + String(name); + throw new Error("Cannot access " + expression + " on the server. " + 'You cannot dot into a client module from a server component. ' + 'You can only pass the imported name through.'); + }, + set: function () { + throw new Error('Cannot assign to a client module from a server module.'); + } +}; +var proxyHandlers = { + get: function (target, name, receiver) { + switch (name) { + // These names are read by the Flight runtime if you end up using the exports object. + case '$$typeof': + return target.$$typeof; + + case '$$id': + return target.$$id; + + case '$$async': + return target.$$async; + + case 'name': + return target.name; + // We need to special case this because createElement reads it if we pass this + // reference. + + case 'defaultProps': + return undefined; + // Avoid this attempting to be serialized. + + case 'toJSON': + return undefined; + + case Symbol.toPrimitive: + // $FlowFixMe[prop-missing] + return Object.prototype[Symbol.toPrimitive]; + + case '__esModule': + // Something is conditionally checking which export to use. We'll pretend to be + // an ESM compat module but then we'll check again on the client. + var moduleId = target.$$id; + target.default = registerClientReferenceImpl(function () { + throw new Error("Attempted to call the default export of " + moduleId + " from the server " + "but it's on the client. It's not possible to invoke a client function from " + "the server, it can only be rendered as a Component or passed to props of a " + "Client Component."); + }, target.$$id + '#', target.$$async); + return true; + + case 'then': + if (target.then) { + // Use a cached value + return target.then; + } + + if (!target.$$async) { + // If this module is expected to return a Promise (such as an AsyncModule) then + // we should resolve that with a client reference that unwraps the Promise on + // the client. + var clientReference = registerClientReferenceImpl({}, target.$$id, true); + var proxy = new Proxy(clientReference, proxyHandlers); // Treat this as a resolved Promise for React's use() + + target.status = 'fulfilled'; + target.value = proxy; + var then = target.then = registerClientReferenceImpl(function then(resolve, reject) { + // Expose to React. + return Promise.resolve(resolve(proxy)); + }, // If this is not used as a Promise but is treated as a reference to a `.then` + // export then we should treat it as a reference to that name. + target.$$id + '#then', false); + return then; + } else { + // Since typeof .then === 'function' is a feature test we'd continue recursing + // indefinitely if we return a function. Instead, we return an object reference + // if we check further. + return undefined; + } + + } + + var cachedReference = target[name]; + + if (!cachedReference) { + var reference = registerClientReferenceImpl(function () { + throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion + "Attempted to call " + String(name) + "() from the server but " + String(name) + " is on the client. " + "It's not possible to invoke a client function from the server, it can " + "only be rendered as a Component or passed to props of a Client Component."); + }, target.$$id + '#' + name, target.$$async); + Object.defineProperty(reference, 'name', { + value: name + }); + cachedReference = target[name] = new Proxy(reference, deepProxyHandlers); + } + + return cachedReference; + }, + getPrototypeOf: function (target) { + // Pretend to be a Promise in case anyone asks. + return PROMISE_PROTOTYPE; + }, + set: function () { + throw new Error('Cannot assign to a client module from a server module.'); + } +}; +function createClientModuleProxy(moduleId) { + var clientReference = registerClientReferenceImpl({}, // Represents the whole Module object instead of a particular import. + moduleId, false); + return new Proxy(clientReference, proxyHandlers); +} + +function getClientReferenceKey(reference) { + return reference.$$async ? reference.$$id + '#async' : reference.$$id; +} +function resolveClientReferenceMetadata(config, clientReference) { + var modulePath = clientReference.$$id; + var name = ''; + var resolvedModuleData = config[modulePath]; + + if (resolvedModuleData) { + // The potentially aliased name. + name = resolvedModuleData.name; + } else { + // We didn't find this specific export name but we might have the * export + // which contains this name as well. + // TODO: It's unfortunate that we now have to parse this string. We should + // probably go back to encoding path and name separately on the client reference. + var idx = modulePath.lastIndexOf('#'); + + if (idx !== -1) { + name = modulePath.slice(idx + 1); + resolvedModuleData = config[modulePath.slice(0, idx)]; + } + + if (!resolvedModuleData) { + throw new Error('Could not find the module "' + modulePath + '" in the React Client Manifest. ' + 'This is probably a bug in the React Server Components bundler.'); + } + } + + if (clientReference.$$async === true) { + return [resolvedModuleData.id, resolvedModuleData.chunks, name, 1]; + } else { + return [resolvedModuleData.id, resolvedModuleData.chunks, name]; + } +} +function getServerReferenceId(config, serverReference) { + return serverReference.$$id; +} +function getServerReferenceBoundArguments(config, serverReference) { + return serverReference.$$bound; +} + +var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +var ReactDOMFlightServerDispatcher = { + prefetchDNS: prefetchDNS, + preconnect: preconnect, + preload: preload, + preloadModule: preloadModule$1, + preinitStyle: preinitStyle, + preinitScript: preinitScript, + preinitModuleScript: preinitModuleScript +}; + +function prefetchDNS(href) { + { + if (typeof href === 'string' && href) { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'D|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + emitHint(request, 'D', href); + } + } + } +} + +function preconnect(href, crossOrigin) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = "C|" + (crossOrigin == null ? 'null' : crossOrigin) + "|" + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + + if (typeof crossOrigin === 'string') { + emitHint(request, 'C', [href, crossOrigin]); + } else { + emitHint(request, 'C', href); + } + } + } + } +} + +function preload(href, as, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'L'; + + if (as === 'image' && options) { + key += getImagePreloadKey(href, options.imageSrcSet, options.imageSizes); + } else { + key += "[" + as + "]" + href; + } + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + emitHint(request, 'L', [href, as, trimmed]); + } else { + emitHint(request, 'L', [href, as]); + } + } + } + } +} + +function preloadModule$1(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'm|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + return emitHint(request, 'm', [href, trimmed]); + } else { + return emitHint(request, 'm', href); + } + } + } + } +} + +function preinitStyle(href, precedence, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'S|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + return emitHint(request, 'S', [href, typeof precedence === 'string' ? precedence : 0, trimmed]); + } else if (typeof precedence === 'string') { + return emitHint(request, 'S', [href, precedence]); + } else { + return emitHint(request, 'S', href); + } + } + } + } +} + +function preinitScript(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'X|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + return emitHint(request, 'X', [href, trimmed]); + } else { + return emitHint(request, 'X', href); + } + } + } + } +} + +function preinitModuleScript(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'M|' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + var trimmed = trimOptions(options); + + if (trimmed) { + return emitHint(request, 'M', [href, trimmed]); + } else { + return emitHint(request, 'M', href); + } + } + } + } +} // Flight normally encodes undefined as a special character however for directive option +// arguments we don't want to send unnecessary keys and bloat the payload so we create a +// trimmed object which omits any keys with null or undefined values. +// This is only typesafe because these option objects have entirely optional fields where +// null and undefined represent the same thing as no property. + + +function trimOptions(options) { + if (options == null) return null; + var hasProperties = false; + var trimmed = {}; + + for (var key in options) { + if (options[key] != null) { + hasProperties = true; + trimmed[key] = options[key]; + } + } + + return hasProperties ? trimmed : null; +} + +function getImagePreloadKey(href, imageSrcSet, imageSizes) { + var uniquePart = ''; + + if (typeof imageSrcSet === 'string' && imageSrcSet !== '') { + uniquePart += '[' + imageSrcSet + ']'; + + if (typeof imageSizes === 'string') { + uniquePart += '[' + imageSizes + ']'; + } + } else { + uniquePart += '[][]' + href; + } + + return "[image]" + uniquePart; +} + +var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher; +function prepareHostDispatcher() { + ReactDOMCurrentDispatcher.current = ReactDOMFlightServerDispatcher; +} // Used to distinguish these contexts from ones used in other renderers. +// small, smaller than how we encode undefined, and is unambiguous. We could use +// a different tuple structure to encode this instead but this makes the runtime +// cost cheaper by eliminating a type checks in more positions. +// prettier-ignore + +function createHints() { + return new Set(); +} + +var requestStorage = new async_hooks.AsyncLocalStorage(); + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); +var REACT_MEMO_CACHE_SENTINEL = Symbol.for('react.memo_cache_sentinel'); +var REACT_POSTPONE_TYPE = Symbol.for('react.postpone'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +var rendererSigil; + +{ + // Use this to detect multiple renderers using the same context + rendererSigil = {}; +} // Used to store the parent path of all context overrides in a shared linked list. +// Forming a reverse tree. +// The structure of a context snapshot is an implementation of this file. +// Currently, it's implemented as tracking the current active node. + + +var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. +// This global (actually thread local) state represents what state all those "current", +// fields are currently in. + +var currentActiveSnapshot = null; + +function popNode(prev) { + { + prev.context._currentValue = prev.parentValue; + } +} + +function pushNode(next) { + { + next.context._currentValue = next.value; + } +} + +function popToNearestCommonAncestor(prev, next) { + if (prev === next) ; else { + popNode(prev); + var parentPrev = prev.parent; + var parentNext = next.parent; + + if (parentPrev === null) { + if (parentNext !== null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + } else { + if (parentNext === null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + + popToNearestCommonAncestor(parentPrev, parentNext); // On the way back, we push the new ones that weren't common. + + pushNode(next); + } + } +} + +function popAllPrevious(prev) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev !== null) { + popAllPrevious(parentPrev); + } +} + +function pushAllNext(next) { + var parentNext = next.parent; + + if (parentNext !== null) { + pushAllNext(parentNext); + } + + pushNode(next); +} + +function popPreviousToCommonLevel(prev, next) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (parentPrev.depth === next.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(parentPrev, next); + } else { + // We must still be deeper. + popPreviousToCommonLevel(parentPrev, next); + } +} + +function popNextToCommonLevel(prev, next) { + var parentNext = next.parent; + + if (parentNext === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (prev.depth === parentNext.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(prev, parentNext); + } else { + // We must still be deeper. + popNextToCommonLevel(prev, parentNext); + } + + pushNode(next); +} // Perform context switching to the new snapshot. +// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by +// updating all the context's current values. That way reads, always just read the current value. +// At the cost of updating contexts even if they're never read by this subtree. + + +function switchContext(newSnapshot) { + // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. + // We also need to update any new contexts that are now on the stack with the deepest value. + // The easiest way to update new contexts is to just reapply them in reverse order from the + // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack + // for that. Therefore this algorithm is recursive. + // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. + // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. + // 3) Then we reapply new contexts on the way back up the stack. + var prev = currentActiveSnapshot; + var next = newSnapshot; + + if (prev !== next) { + if (prev === null) { + // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev. + pushAllNext(next); + } else if (next === null) { + popAllPrevious(prev); + } else if (prev.depth === next.depth) { + popToNearestCommonAncestor(prev, next); + } else if (prev.depth > next.depth) { + popPreviousToCommonLevel(prev, next); + } else { + popNextToCommonLevel(prev, next); + } + + currentActiveSnapshot = next; + } +} +function pushProvider(context, nextValue) { + var prevValue; + + { + prevValue = context._currentValue; + context._currentValue = nextValue; + + { + if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } + + context._currentRenderer = rendererSigil; + } + } + + var prevNode = currentActiveSnapshot; + var newNode = { + parent: prevNode, + depth: prevNode === null ? 0 : prevNode.depth + 1, + context: context, + parentValue: prevValue, + value: nextValue + }; + currentActiveSnapshot = newNode; + return newNode; +} +function popProvider() { + var prevSnapshot = currentActiveSnapshot; + + if (prevSnapshot === null) { + throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.'); + } + + { + var value = prevSnapshot.parentValue; + + if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) { + prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue; + } else { + prevSnapshot.context._currentValue = value; + } + } + + return currentActiveSnapshot = prevSnapshot.parent; +} +function getActiveContext() { + return currentActiveSnapshot; +} +function readContext$1(context) { + var value = context._currentValue ; + return value; +} + +// Corresponds to ReactFiberWakeable and ReactFizzWakeable modules. Generally, +// changes to one module should be reflected in the others. +// TODO: Rename this module and the corresponding Fiber one to "Thenable" +// instead of "Wakeable". Or some other more appropriate name. +// An error that is thrown (e.g. by `use`) to trigger Suspense. If we +// detect this is caught by userspace, we'll log a warning in development. +var SuspenseException = new Error("Suspense Exception: This is not a real error! It's an implementation " + 'detail of `use` to interrupt the current render. You must either ' + 'rethrow it immediately, or move the `use` call outside of the ' + '`try/catch` block. Capturing without rethrowing will lead to ' + 'unexpected behavior.\n\n' + 'To handle async errors, wrap your component in an error boundary, or ' + "call the promise's `.catch` method and pass the result to `use`"); +function createThenableState() { + // The ThenableState is created the first time a component suspends. If it + // suspends again, we'll reuse the same state. + return []; +} + +function noop() {} + +function trackUsedThenable(thenableState, thenable, index) { + var previous = thenableState[index]; + + if (previous === undefined) { + thenableState.push(thenable); + } else { + if (previous !== thenable) { + // Reuse the previous thenable, and drop the new one. We can assume + // they represent the same value, because components are idempotent. + // Avoid an unhandled rejection errors for the Promises that we'll + // intentionally ignore. + thenable.then(noop, noop); + thenable = previous; + } + } // We use an expando to track the status and result of a thenable so that we + // can synchronously unwrap the value. Think of this as an extension of the + // Promise API, or a custom interface that is a superset of Thenable. + // + // If the thenable doesn't have a status, set it to "pending" and attach + // a listener that will update its status and result when it resolves. + + + switch (thenable.status) { + case 'fulfilled': + { + var fulfilledValue = thenable.value; + return fulfilledValue; + } + + case 'rejected': + { + var rejectedError = thenable.reason; + throw rejectedError; + } + + default: + { + if (typeof thenable.status === 'string') ; else { + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); // Check one more time in case the thenable resolved synchronously + + switch (thenable.status) { + case 'fulfilled': + { + var fulfilledThenable = thenable; + return fulfilledThenable.value; + } + + case 'rejected': + { + var rejectedThenable = thenable; + throw rejectedThenable.reason; + } + } + } // Suspend. + // + // Throwing here is an implementation detail that allows us to unwind the + // call stack. But we shouldn't allow it to leak into userspace. Throw an + // opaque placeholder value instead of the actual thenable. If it doesn't + // get captured by the work loop, log a warning, because that means + // something in userspace must have caught it. + + + suspendedThenable = thenable; + throw SuspenseException; + } + } +} // This is used to track the actual thenable that suspended so it can be +// passed to the rest of the Suspense implementation — which, for historical +// reasons, expects to receive a thenable. + +var suspendedThenable = null; +function getSuspendedThenable() { + // This is called right after `use` suspends by throwing an exception. `use` + // throws an opaque value instead of the thenable itself so that it can't be + // caught in userspace. Then the work loop accesses the actual thenable using + // this function. + if (suspendedThenable === null) { + throw new Error('Expected a suspended thenable. This is a bug in React. Please file ' + 'an issue.'); + } + + var thenable = suspendedThenable; + suspendedThenable = null; + return thenable; +} + +var currentRequest$1 = null; +var thenableIndexCounter = 0; +var thenableState = null; +function prepareToUseHooksForRequest(request) { + currentRequest$1 = request; +} +function resetHooksForRequest() { + currentRequest$1 = null; +} +function prepareToUseHooksForComponent(prevThenableState) { + thenableIndexCounter = 0; + thenableState = prevThenableState; +} +function getThenableStateAfterSuspending() { + var state = thenableState; + thenableState = null; + return state; +} + +function readContext(context) { + { + if (context.$$typeof !== REACT_SERVER_CONTEXT_TYPE) { + if (isClientReference(context)) { + error('Cannot read a Client Context from a Server Component.'); + } else { + error('Only createServerContext is supported in Server Components.'); + } + } + + if (currentRequest$1 === null) { + error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); + } + } + + return readContext$1(context); +} + +var HooksDispatcher = { + useMemo: function (nextCreate) { + return nextCreate(); + }, + useCallback: function (callback) { + return callback; + }, + useDebugValue: function () {}, + useDeferredValue: unsupportedHook, + useTransition: unsupportedHook, + readContext: readContext, + useContext: readContext, + useReducer: unsupportedHook, + useRef: unsupportedHook, + useState: unsupportedHook, + useInsertionEffect: unsupportedHook, + useLayoutEffect: unsupportedHook, + useImperativeHandle: unsupportedHook, + useEffect: unsupportedHook, + useId: useId, + useSyncExternalStore: unsupportedHook, + useCacheRefresh: function () { + return unsupportedRefresh; + }, + useMemoCache: function (size) { + var data = new Array(size); + + for (var i = 0; i < size; i++) { + data[i] = REACT_MEMO_CACHE_SENTINEL; + } + + return data; + }, + use: use +}; + +function unsupportedHook() { + throw new Error('This Hook is not supported in Server Components.'); +} + +function unsupportedRefresh() { + throw new Error('Refreshing the cache is not supported in Server Components.'); +} + +function useId() { + if (currentRequest$1 === null) { + throw new Error('useId can only be used while React is rendering'); + } + + var id = currentRequest$1.identifierCount++; // use 'S' for Flight components to distinguish from 'R' and 'r' in Fizz/Client + + return ':' + currentRequest$1.identifierPrefix + 'S' + id.toString(32) + ':'; +} + +function use(usable) { + if (usable !== null && typeof usable === 'object' || typeof usable === 'function') { + // $FlowFixMe[method-unbinding] + if (typeof usable.then === 'function') { + // This is a thenable. + var thenable = usable; // Track the position of the thenable within this fiber. + + var index = thenableIndexCounter; + thenableIndexCounter += 1; + + if (thenableState === null) { + thenableState = createThenableState(); + } + + return trackUsedThenable(thenableState, thenable, index); + } else if (usable.$$typeof === REACT_SERVER_CONTEXT_TYPE) { + var context = usable; + return readContext(context); + } + } + + { + if (isClientReference(usable)) { + error('Cannot use() an already resolved Client Reference.'); + } + } // eslint-disable-next-line react-internal/safe-string-coercion + + + throw new Error('An unsupported type was passed to use(): ' + String(usable)); +} + +function createSignal() { + return new AbortController().signal; +} + +function resolveCache() { + var request = resolveRequest(); + + if (request) { + return getCache(request); + } + + return new Map(); +} + +var DefaultCacheDispatcher = { + getCacheSignal: function () { + var cache = resolveCache(); + var entry = cache.get(createSignal); + + if (entry === undefined) { + entry = createSignal(); + cache.set(createSignal, entry); + } + + return entry; + }, + getCacheForType: function (resourceType) { + var cache = resolveCache(); + var entry = cache.get(resourceType); + + if (entry === undefined) { + entry = resourceType(); // TODO: Warn if undefined? + + cache.set(resourceType, entry); + } + + return entry; + } +}; + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +// in case they error. + +var jsxPropsParents = new WeakMap(); +var jsxChildrenParents = new WeakMap(); + +function isObjectPrototype(object) { + if (!object) { + return false; + } + + var ObjectPrototype = Object.prototype; + + if (object === ObjectPrototype) { + return true; + } // It might be an object from a different Realm which is + // still just a plain simple object. + + + if (Object.getPrototypeOf(object)) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + if (!(names[i] in ObjectPrototype)) { + return false; + } + } + + return true; +} + +function isSimpleObject(object) { + if (!isObjectPrototype(Object.getPrototypeOf(object))) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + var descriptor = Object.getOwnPropertyDescriptor(object, names[i]); + + if (!descriptor) { + return false; + } + + if (!descriptor.enumerable) { + if ((names[i] === 'key' || names[i] === 'ref') && typeof descriptor.get === 'function') { + // React adds key and ref getters to props objects to issue warnings. + // Those getters will not be transferred to the client, but that's ok, + // so we'll special case them. + continue; + } + + return false; + } + } + + return true; +} +function objectName(object) { + // $FlowFixMe[method-unbinding] + var name = Object.prototype.toString.call(object); + return name.replace(/^\[object (.*)\]$/, function (m, p0) { + return p0; + }); +} + +function describeKeyForErrorMessage(key) { + var encodedKey = JSON.stringify(key); + return '"' + key + '"' === encodedKey ? key : encodedKey; +} + +function describeValueForErrorMessage(value) { + switch (typeof value) { + case 'string': + { + return JSON.stringify(value.length <= 10 ? value : value.slice(0, 10) + '...'); + } + + case 'object': + { + if (isArray(value)) { + return '[...]'; + } + + var name = objectName(value); + + if (name === 'Object') { + return '{...}'; + } + + return name; + } + + case 'function': + return 'function'; + + default: + // eslint-disable-next-line react-internal/safe-string-coercion + return String(value); + } +} + +function describeElementType(type) { + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeElementType(type.render); + + case REACT_MEMO_TYPE: + return describeElementType(type.type); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeElementType(init(payload)); + } catch (x) {} + } + } + } + + return ''; +} + +function describeObjectForErrorMessage(objectOrArray, expandedName) { + var objKind = objectName(objectOrArray); + + if (objKind !== 'Object' && objKind !== 'Array') { + return objKind; + } + + var str = ''; + var start = -1; + var length = 0; + + if (isArray(objectOrArray)) { + if (jsxChildrenParents.has(objectOrArray)) { + // Print JSX Children + var type = jsxChildrenParents.get(objectOrArray); + str = '<' + describeElementType(type) + '>'; + var array = objectOrArray; + + for (var i = 0; i < array.length; i++) { + var value = array[i]; + var substr = void 0; + + if (typeof value === 'string') { + substr = value; + } else if (typeof value === 'object' && value !== null) { + substr = '{' + describeObjectForErrorMessage(value) + '}'; + } else { + substr = '{' + describeValueForErrorMessage(value) + '}'; + } + + if ('' + i === expandedName) { + start = str.length; + length = substr.length; + str += substr; + } else if (substr.length < 15 && str.length + substr.length < 40) { + str += substr; + } else { + str += '{...}'; + } + } + + str += ''; + } else { + // Print Array + str = '['; + var _array = objectOrArray; + + for (var _i = 0; _i < _array.length; _i++) { + if (_i > 0) { + str += ', '; + } + + var _value = _array[_i]; + + var _substr = void 0; + + if (typeof _value === 'object' && _value !== null) { + _substr = describeObjectForErrorMessage(_value); + } else { + _substr = describeValueForErrorMessage(_value); + } + + if ('' + _i === expandedName) { + start = str.length; + length = _substr.length; + str += _substr; + } else if (_substr.length < 10 && str.length + _substr.length < 40) { + str += _substr; + } else { + str += '...'; + } + } + + str += ']'; + } + } else { + if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) { + str = '<' + describeElementType(objectOrArray.type) + '/>'; + } else if (jsxPropsParents.has(objectOrArray)) { + // Print JSX + var _type = jsxPropsParents.get(objectOrArray); + + str = '<' + (describeElementType(_type) || '...'); + var object = objectOrArray; + var names = Object.keys(object); + + for (var _i2 = 0; _i2 < names.length; _i2++) { + str += ' '; + var name = names[_i2]; + str += describeKeyForErrorMessage(name) + '='; + var _value2 = object[name]; + + var _substr2 = void 0; + + if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) { + _substr2 = describeObjectForErrorMessage(_value2); + } else { + _substr2 = describeValueForErrorMessage(_value2); + } + + if (typeof _value2 !== 'string') { + _substr2 = '{' + _substr2 + '}'; + } + + if (name === expandedName) { + start = str.length; + length = _substr2.length; + str += _substr2; + } else if (_substr2.length < 10 && str.length + _substr2.length < 40) { + str += _substr2; + } else { + str += '...'; + } + } + + str += '>'; + } else { + // Print Object + str = '{'; + var _object = objectOrArray; + + var _names = Object.keys(_object); + + for (var _i3 = 0; _i3 < _names.length; _i3++) { + if (_i3 > 0) { + str += ', '; + } + + var _name = _names[_i3]; + str += describeKeyForErrorMessage(_name) + ': '; + var _value3 = _object[_name]; + + var _substr3 = void 0; + + if (typeof _value3 === 'object' && _value3 !== null) { + _substr3 = describeObjectForErrorMessage(_value3); + } else { + _substr3 = describeValueForErrorMessage(_value3); + } + + if (_name === expandedName) { + start = str.length; + length = _substr3.length; + str += _substr3; + } else if (_substr3.length < 10 && str.length + _substr3.length < 40) { + str += _substr3; + } else { + str += '...'; + } + } + + str += '}'; + } + } + + if (expandedName === undefined) { + return str; + } + + if (start > -1 && length > 0) { + var highlight = ' '.repeat(start) + '^'.repeat(length); + return '\n ' + str + '\n ' + highlight; + } + + return '\n ' + str; +} + +var ContextRegistry = ReactSharedInternals.ContextRegistry; +function getOrCreateServerContext(globalName) { + if (!ContextRegistry[globalName]) { + var context = { + $$typeof: REACT_SERVER_CONTEXT_TYPE, + // As a workaround to support multiple concurrent renderers, we categorize + // some renderers as primary and others as secondary. We only expect + // there to be two concurrent renderers at most: React Native (primary) and + // Fabric (secondary); React DOM (primary) and React ART (secondary). + // Secondary renderers store their context values on separate fields. + _currentValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + _currentValue2: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + _defaultValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, + // Used to track how many concurrent renderers this context currently + // supports within in a single renderer. Such as parallel server rendering. + _threadCount: 0, + // These are circular + Provider: null, + Consumer: null, + _globalName: globalName + }; + context.Provider = { + $$typeof: REACT_PROVIDER_TYPE, + _context: context + }; + + { + var hasWarnedAboutUsingConsumer; + context._currentRenderer = null; + context._currentRenderer2 = null; + Object.defineProperties(context, { + Consumer: { + get: function () { + if (!hasWarnedAboutUsingConsumer) { + error('Consumer pattern is not supported by ReactServerContext'); + + hasWarnedAboutUsingConsumer = true; + } + + return null; + } + } + }); + } + + ContextRegistry[globalName] = context; + } + + return ContextRegistry[globalName]; +} + +var stringify = JSON.stringify; // Serializable values +// Thenable + +var PENDING$1 = 0; +var COMPLETED = 1; +var ABORTED = 3; +var ERRORED$1 = 4; +var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; +var ReactCurrentCache = ReactSharedInternals.ReactCurrentCache; + +function defaultErrorHandler(error) { + console['error'](error); // Don't transform to our wrapper +} + +function defaultPostponeHandler(reason) {// Noop +} + +var OPEN = 0; +var CLOSING = 1; +var CLOSED = 2; +function createRequest(model, bundlerConfig, onError, context, identifierPrefix, onPostpone) { + if (ReactCurrentCache.current !== null && ReactCurrentCache.current !== DefaultCacheDispatcher) { + throw new Error('Currently React only supports one RSC renderer at a time.'); + } + + prepareHostDispatcher(); + ReactCurrentCache.current = DefaultCacheDispatcher; + var abortSet = new Set(); + var pingedTasks = []; + var hints = createHints(); + var request = { + status: OPEN, + flushScheduled: false, + fatalError: null, + destination: null, + bundlerConfig: bundlerConfig, + cache: new Map(), + nextChunkId: 0, + pendingChunks: 0, + hints: hints, + abortableTasks: abortSet, + pingedTasks: pingedTasks, + completedImportChunks: [], + completedHintChunks: [], + completedRegularChunks: [], + completedErrorChunks: [], + writtenSymbols: new Map(), + writtenClientReferences: new Map(), + writtenServerReferences: new Map(), + writtenProviders: new Map(), + identifierPrefix: identifierPrefix || '', + identifierCount: 1, + onError: onError === undefined ? defaultErrorHandler : onError, + onPostpone: onPostpone === undefined ? defaultPostponeHandler : onPostpone, + // $FlowFixMe[missing-this-annot] + toJSON: function (key, value) { + return resolveModelToJSON(request, this, key, value); + } + }; + request.pendingChunks++; + var rootContext = createRootContext(context); + var rootTask = createTask(request, model, rootContext, abortSet); + pingedTasks.push(rootTask); + return request; +} +var currentRequest = null; +function resolveRequest() { + if (currentRequest) return currentRequest; + + { + var store = requestStorage.getStore(); + if (store) return store; + } + + return null; +} + +function createRootContext(reqContext) { + return importServerContexts(reqContext); +} + +var POP = {}; + +function serializeThenable(request, thenable) { + request.pendingChunks++; + var newTask = createTask(request, null, getActiveContext(), request.abortableTasks); + + switch (thenable.status) { + case 'fulfilled': + { + // We have the resolved value, we can go ahead and schedule it for serialization. + newTask.model = thenable.value; + pingTask(request, newTask); + return newTask.id; + } + + case 'rejected': + { + var x = thenable.reason; + + if (typeof x === 'object' && x !== null && x.$$typeof === REACT_POSTPONE_TYPE) { + var postponeInstance = x; + logPostpone(request, postponeInstance.message); + emitPostponeChunk(request, newTask.id, postponeInstance); + } else { + var digest = logRecoverableError(request, x); + emitErrorChunk(request, newTask.id, digest, x); + } + + return newTask.id; + } + + default: + { + if (typeof thenable.status === 'string') { + // Only instrument the thenable if the status if not defined. If + // it's defined, but an unknown value, assume it's been instrumented by + // some custom userspace implementation. We treat it as "pending". + break; + } + + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); + break; + } + } + + thenable.then(function (value) { + newTask.model = value; + pingTask(request, newTask); + }, function (reason) { + newTask.status = ERRORED$1; + request.abortableTasks.delete(newTask); // TODO: We should ideally do this inside performWork so it's scheduled + + var digest = logRecoverableError(request, reason); + emitErrorChunk(request, newTask.id, digest, reason); + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + }); + return newTask.id; +} + +function emitHint(request, code, model) { + emitHintChunk(request, code, model); + enqueueFlush(request); +} +function getHints(request) { + return request.hints; +} +function getCache(request) { + return request.cache; +} + +function readThenable(thenable) { + if (thenable.status === 'fulfilled') { + return thenable.value; + } else if (thenable.status === 'rejected') { + throw thenable.reason; + } + + throw thenable; +} + +function createLazyWrapperAroundWakeable(wakeable) { + // This is a temporary fork of the `use` implementation until we accept + // promises everywhere. + var thenable = wakeable; + + switch (thenable.status) { + case 'fulfilled': + case 'rejected': + break; + + default: + { + if (typeof thenable.status === 'string') { + // Only instrument the thenable if the status if not defined. If + // it's defined, but an unknown value, assume it's been instrumented by + // some custom userspace implementation. We treat it as "pending". + break; + } + + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); + break; + } + } + + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: thenable, + _init: readThenable + }; + return lazyType; +} + +function attemptResolveElement(request, type, key, ref, props, prevThenableState) { + if (ref !== null && ref !== undefined) { + // When the ref moves to the regular props object this will implicitly + // throw for functions. We could probably relax it to a DEV warning for other + // cases. + throw new Error('Refs cannot be used in Server Components, nor passed to Client Components.'); + } + + { + jsxPropsParents.set(props, type); + + if (typeof props.children === 'object' && props.children !== null) { + jsxChildrenParents.set(props.children, type); + } + } + + if (typeof type === 'function') { + if (isClientReference(type)) { + // This is a reference to a Client Component. + return [REACT_ELEMENT_TYPE, type, key, props]; + } // This is a server-side component. + + + prepareToUseHooksForComponent(prevThenableState); + var result = type(props); + + if (typeof result === 'object' && result !== null && typeof result.then === 'function') { + // When the return value is in children position we can resolve it immediately, + // to its value without a wrapper if it's synchronously available. + var thenable = result; + + if (thenable.status === 'fulfilled') { + return thenable.value; + } // TODO: Once we accept Promises as children on the client, we can just return + // the thenable here. + + + return createLazyWrapperAroundWakeable(result); + } + + return result; + } else if (typeof type === 'string') { + // This is a host element. E.g. HTML. + return [REACT_ELEMENT_TYPE, type, key, props]; + } else if (typeof type === 'symbol') { + if (type === REACT_FRAGMENT_TYPE) { + // For key-less fragments, we add a small optimization to avoid serializing + // it as a wrapper. + // TODO: If a key is specified, we should propagate its key to any children. + // Same as if a Server Component has a key. + return props.children; + } // This might be a built-in React component. We'll let the client decide. + // Any built-in works as long as its props are serializable. + + + return [REACT_ELEMENT_TYPE, type, key, props]; + } else if (type != null && typeof type === 'object') { + if (isClientReference(type)) { + // This is a reference to a Client Component. + return [REACT_ELEMENT_TYPE, type, key, props]; + } + + switch (type.$$typeof) { + case REACT_LAZY_TYPE: + { + var payload = type._payload; + var init = type._init; + var wrappedType = init(payload); + return attemptResolveElement(request, wrappedType, key, ref, props, prevThenableState); + } + + case REACT_FORWARD_REF_TYPE: + { + var render = type.render; + prepareToUseHooksForComponent(prevThenableState); + return render(props, undefined); + } + + case REACT_MEMO_TYPE: + { + return attemptResolveElement(request, type.type, key, ref, props, prevThenableState); + } + + case REACT_PROVIDER_TYPE: + { + pushProvider(type._context, props.value); + + { + var extraKeys = Object.keys(props).filter(function (value) { + if (value === 'children' || value === 'value') { + return false; + } + + return true; + }); + + if (extraKeys.length !== 0) { + error('ServerContext can only have a value prop and children. Found: %s', JSON.stringify(extraKeys)); + } + } + + return [REACT_ELEMENT_TYPE, type, key, // Rely on __popProvider being serialized last to pop the provider. + { + value: props.value, + children: props.children, + __pop: POP + }]; + } + } + } + + throw new Error("Unsupported Server Component type: " + describeValueForErrorMessage(type)); +} + +function pingTask(request, task) { + var pingedTasks = request.pingedTasks; + pingedTasks.push(task); + + if (pingedTasks.length === 1) { + request.flushScheduled = request.destination !== null; + scheduleWork(function () { + return performWork(request); + }); + } +} + +function createTask(request, model, context, abortSet) { + var id = request.nextChunkId++; + var task = { + id: id, + status: PENDING$1, + model: model, + context: context, + ping: function () { + return pingTask(request, task); + }, + thenableState: null + }; + abortSet.add(task); + return task; +} + +function serializeByValueID(id) { + return '$' + id.toString(16); +} + +function serializeLazyID(id) { + return '$L' + id.toString(16); +} + +function serializePromiseID(id) { + return '$@' + id.toString(16); +} + +function serializeServerReferenceID(id) { + return '$F' + id.toString(16); +} + +function serializeSymbolReference(name) { + return '$S' + name; +} + +function serializeProviderReference(name) { + return '$P' + name; +} + +function serializeNumber(number) { + if (Number.isFinite(number)) { + if (number === 0 && 1 / number === -Infinity) { + return '$-0'; + } else { + return number; + } + } else { + if (number === Infinity) { + return '$Infinity'; + } else if (number === -Infinity) { + return '$-Infinity'; + } else { + return '$NaN'; + } + } +} + +function serializeUndefined() { + return '$undefined'; +} + +function serializeDateFromDateJSON(dateJSON) { + // JSON.stringify automatically calls Date.prototype.toJSON which calls toISOString. + // We need only tack on a $D prefix. + return '$D' + dateJSON; +} + +function serializeBigInt(n) { + return '$n' + n.toString(10); +} + +function serializeRowHeader(tag, id) { + return id.toString(16) + ':' + tag; +} + +function encodeReferenceChunk(request, id, reference) { + var json = stringify(reference); + var row = id.toString(16) + ':' + json + '\n'; + return stringToChunk(row); +} + +function serializeClientReference(request, parent, key, clientReference) { + var clientReferenceKey = getClientReferenceKey(clientReference); + var writtenClientReferences = request.writtenClientReferences; + var existingId = writtenClientReferences.get(clientReferenceKey); + + if (existingId !== undefined) { + if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { + // If we're encoding the "type" of an element, we can refer + // to that by a lazy reference instead of directly since React + // knows how to deal with lazy values. This lets us suspend + // on this component rather than its parent until the code has + // loaded. + return serializeLazyID(existingId); + } + + return serializeByValueID(existingId); + } + + try { + var clientReferenceMetadata = resolveClientReferenceMetadata(request.bundlerConfig, clientReference); + request.pendingChunks++; + var importId = request.nextChunkId++; + emitImportChunk(request, importId, clientReferenceMetadata); + writtenClientReferences.set(clientReferenceKey, importId); + + if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { + // If we're encoding the "type" of an element, we can refer + // to that by a lazy reference instead of directly since React + // knows how to deal with lazy values. This lets us suspend + // on this component rather than its parent until the code has + // loaded. + return serializeLazyID(importId); + } + + return serializeByValueID(importId); + } catch (x) { + request.pendingChunks++; + var errorId = request.nextChunkId++; + var digest = logRecoverableError(request, x); + emitErrorChunk(request, errorId, digest, x); + return serializeByValueID(errorId); + } +} + +function outlineModel(request, value) { + request.pendingChunks++; + var outlinedId = request.nextChunkId++; // We assume that this object doesn't suspend, but a child might. + + emitModelChunk(request, outlinedId, value); + return outlinedId; +} + +function serializeServerReference(request, parent, key, serverReference) { + var writtenServerReferences = request.writtenServerReferences; + var existingId = writtenServerReferences.get(serverReference); + + if (existingId !== undefined) { + return serializeServerReferenceID(existingId); + } + + var bound = getServerReferenceBoundArguments(request.bundlerConfig, serverReference); + var serverReferenceMetadata = { + id: getServerReferenceId(request.bundlerConfig, serverReference), + bound: bound ? Promise.resolve(bound) : null + }; + var metadataId = outlineModel(request, serverReferenceMetadata); + writtenServerReferences.set(serverReference, metadataId); + return serializeServerReferenceID(metadataId); +} + +function serializeLargeTextString(request, text) { + request.pendingChunks += 2; + var textId = request.nextChunkId++; + var textChunk = stringToChunk(text); + var binaryLength = byteLengthOfChunk(textChunk); + var row = textId.toString(16) + ':T' + binaryLength.toString(16) + ','; + var headerChunk = stringToChunk(row); + request.completedRegularChunks.push(headerChunk, textChunk); + return serializeByValueID(textId); +} + +function serializeMap(request, map) { + var id = outlineModel(request, Array.from(map)); + return '$Q' + id.toString(16); +} + +function serializeSet(request, set) { + var id = outlineModel(request, Array.from(set)); + return '$W' + id.toString(16); +} + +function serializeTypedArray(request, tag, typedArray) { + request.pendingChunks += 2; + var bufferId = request.nextChunkId++; // TODO: Convert to little endian if that's not the server default. + + var binaryChunk = typedArrayToBinaryChunk(typedArray); + var binaryLength = byteLengthOfBinaryChunk(binaryChunk); + var row = bufferId.toString(16) + ':' + tag + binaryLength.toString(16) + ','; + var headerChunk = stringToChunk(row); + request.completedRegularChunks.push(headerChunk, binaryChunk); + return serializeByValueID(bufferId); +} + +function escapeStringValue(value) { + if (value[0] === '$') { + // We need to escape $ prefixed strings since we use those to encode + // references to IDs and as special symbol values. + return '$' + value; + } else { + return value; + } +} + +var insideContextProps = null; +var isInsideContextValue = false; + +function resolveModelToJSON(request, parent, key, value) { + // Make sure that `parent[key]` wasn't JSONified before `value` was passed to us + { + // $FlowFixMe[incompatible-use] + var originalValue = parent[key]; + + if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) { + if (objectName(originalValue) !== 'Object') { + var jsxParentType = jsxChildrenParents.get(parent); + + if (typeof jsxParentType === 'string') { + error('%s objects cannot be rendered as text children. Try formatting it using toString().%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } else { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } + } else { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props.%s', describeObjectForErrorMessage(parent, key)); + } + } + } // Special Symbols + + + switch (value) { + case REACT_ELEMENT_TYPE: + return '$'; + } + + { + if (parent[0] === REACT_ELEMENT_TYPE && parent[1] && parent[1].$$typeof === REACT_PROVIDER_TYPE && key === '3') { + insideContextProps = value; + } else if (insideContextProps === parent && key === 'value') { + isInsideContextValue = true; + } else if (insideContextProps === parent && key === 'children') { + isInsideContextValue = false; + } + } // Resolve Server Components. + + + while (typeof value === 'object' && value !== null && (value.$$typeof === REACT_ELEMENT_TYPE || value.$$typeof === REACT_LAZY_TYPE)) { + { + if (isInsideContextValue) { + error('React elements are not allowed in ServerContext'); + } + } + + try { + switch (value.$$typeof) { + case REACT_ELEMENT_TYPE: + { + // TODO: Concatenate keys of parents onto children. + var element = value; // Attempt to render the Server Component. + + value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, null); + break; + } + + case REACT_LAZY_TYPE: + { + var payload = value._payload; + var init = value._init; + value = init(payload); + break; + } + } + } catch (thrownValue) { + var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical + // reasons, the rest of the Suspense implementation expects the thrown + // value to be a thenable, because before `use` existed that was the + // (unstable) API for suspending. This implementation detail can change + // later, once we deprecate the old API in favor of `use`. + getSuspendedThenable() : thrownValue; + + if (typeof x === 'object' && x !== null) { + // $FlowFixMe[method-unbinding] + if (typeof x.then === 'function') { + // Something suspended, we'll need to create a new task and resolve it later. + request.pendingChunks++; + var newTask = createTask(request, value, getActiveContext(), request.abortableTasks); + var ping = newTask.ping; + x.then(ping, ping); + newTask.thenableState = getThenableStateAfterSuspending(); + return serializeLazyID(newTask.id); + } else if (x.$$typeof === REACT_POSTPONE_TYPE) { + // Something postponed. We'll still send everything we have up until this point. + // We'll replace this element with a lazy reference that postpones on the client. + var postponeInstance = x; + request.pendingChunks++; + var postponeId = request.nextChunkId++; + logPostpone(request, postponeInstance.message); + emitPostponeChunk(request, postponeId, postponeInstance); + return serializeLazyID(postponeId); + } + } // Something errored. We'll still send everything we have up until this point. + // We'll replace this element with a lazy reference that throws on the client + // once it gets rendered. + + + request.pendingChunks++; + var errorId = request.nextChunkId++; + var digest = logRecoverableError(request, x); + emitErrorChunk(request, errorId, digest, x); + return serializeLazyID(errorId); + } + } + + if (value === null) { + return null; + } + + if (typeof value === 'object') { + if (isClientReference(value)) { + return serializeClientReference(request, parent, key, value); // $FlowFixMe[method-unbinding] + } else if (typeof value.then === 'function') { + // We assume that any object with a .then property is a "Thenable" type, + // or a Promise type. Either of which can be represented by a Promise. + var promiseId = serializeThenable(request, value); + return serializePromiseID(promiseId); + } else if (value.$$typeof === REACT_PROVIDER_TYPE) { + var providerKey = value._context._globalName; + var writtenProviders = request.writtenProviders; + var providerId = writtenProviders.get(key); + + if (providerId === undefined) { + request.pendingChunks++; + providerId = request.nextChunkId++; + writtenProviders.set(providerKey, providerId); + emitProviderChunk(request, providerId, providerKey); + } + + return serializeByValueID(providerId); + } else if (value === POP) { + popProvider(); + + { + insideContextProps = null; + isInsideContextValue = false; + } + + return undefined; + } + + if (value instanceof Map) { + return serializeMap(request, value); + } + + if (value instanceof Set) { + return serializeSet(request, value); + } + + { + if (value instanceof ArrayBuffer) { + return serializeTypedArray(request, 'A', new Uint8Array(value)); + } + + if (value instanceof Int8Array) { + // char + return serializeTypedArray(request, 'C', value); + } + + if (value instanceof Uint8Array) { + // unsigned char + return serializeTypedArray(request, 'c', value); + } + + if (value instanceof Uint8ClampedArray) { + // unsigned clamped char + return serializeTypedArray(request, 'U', value); + } + + if (value instanceof Int16Array) { + // sort + return serializeTypedArray(request, 'S', value); + } + + if (value instanceof Uint16Array) { + // unsigned short + return serializeTypedArray(request, 's', value); + } + + if (value instanceof Int32Array) { + // long + return serializeTypedArray(request, 'L', value); + } + + if (value instanceof Uint32Array) { + // unsigned long + return serializeTypedArray(request, 'l', value); + } + + if (value instanceof Float32Array) { + // float + return serializeTypedArray(request, 'F', value); + } + + if (value instanceof Float64Array) { + // double + return serializeTypedArray(request, 'D', value); + } + + if (value instanceof BigInt64Array) { + // number + return serializeTypedArray(request, 'N', value); + } + + if (value instanceof BigUint64Array) { + // unsigned number + // We use "m" instead of "n" since JSON can start with "null" + return serializeTypedArray(request, 'm', value); + } + + if (value instanceof DataView) { + return serializeTypedArray(request, 'V', value); + } + } + + if (!isArray(value)) { + var iteratorFn = getIteratorFn(value); + + if (iteratorFn) { + return Array.from(value); + } + } + + { + if (value !== null && !isArray(value)) { + // Verify that this is a simple plain object. + if (objectName(value) !== 'Object') { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, key)); + } else if (!isSimpleObject(value)) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Classes or other objects with methods are not supported.%s', describeObjectForErrorMessage(parent, key)); + } else if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(value); + + if (symbols.length > 0) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with symbol properties like %s are not supported.%s', symbols[0].description, describeObjectForErrorMessage(parent, key)); + } + } + } + } // $FlowFixMe[incompatible-return] + + + return value; + } + + if (typeof value === 'string') { + // TODO: Maybe too clever. If we support URL there's no similar trick. + if (value[value.length - 1] === 'Z') { + // Possibly a Date, whose toJSON automatically calls toISOString + // $FlowFixMe[incompatible-use] + var _originalValue = parent[key]; + + if (_originalValue instanceof Date) { + return serializeDateFromDateJSON(value); + } + } + + if (value.length >= 1024) { + // For large strings, we encode them outside the JSON payload so that we + // don't have to double encode and double parse the strings. This can also + // be more compact in case the string has a lot of escaped characters. + return serializeLargeTextString(request, value); + } + + return escapeStringValue(value); + } + + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return serializeNumber(value); + } + + if (typeof value === 'undefined') { + return serializeUndefined(); + } + + if (typeof value === 'function') { + if (isClientReference(value)) { + return serializeClientReference(request, parent, key, value); + } + + if (isServerReference(value)) { + return serializeServerReference(request, parent, key, value); + } + + if (/^on[A-Z]/.test(key)) { + throw new Error('Event handlers cannot be passed to Client Component props.' + describeObjectForErrorMessage(parent, key) + '\nIf you need interactivity, consider converting part of this to a Client Component.'); + } else { + throw new Error('Functions cannot be passed directly to Client Components ' + 'unless you explicitly expose it by marking it with "use server".' + describeObjectForErrorMessage(parent, key)); + } + } + + if (typeof value === 'symbol') { + var writtenSymbols = request.writtenSymbols; + var existingId = writtenSymbols.get(value); + + if (existingId !== undefined) { + return serializeByValueID(existingId); + } // $FlowFixMe[incompatible-type] `description` might be undefined + + + var name = value.description; + + if (Symbol.for(name) !== value) { + throw new Error('Only global symbols received from Symbol.for(...) can be passed to Client Components. ' + ("The symbol Symbol.for(" + // $FlowFixMe[incompatible-type] `description` might be undefined + value.description + ") cannot be found among global symbols.") + describeObjectForErrorMessage(parent, key)); + } + + request.pendingChunks++; + var symbolId = request.nextChunkId++; + emitSymbolChunk(request, symbolId, name); + writtenSymbols.set(value, symbolId); + return serializeByValueID(symbolId); + } + + if (typeof value === 'bigint') { + return serializeBigInt(value); + } + + throw new Error("Type " + typeof value + " is not supported in Client Component props." + describeObjectForErrorMessage(parent, key)); +} + +function logPostpone(request, reason) { + var onPostpone = request.onPostpone; + onPostpone(reason); +} + +function logRecoverableError(request, error) { + var onError = request.onError; + var errorDigest = onError(error); + + if (errorDigest != null && typeof errorDigest !== 'string') { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead"); + } + + return errorDigest || ''; +} + +function fatalError(request, error) { + // This is called outside error handling code such as if an error happens in React internals. + if (request.destination !== null) { + request.status = CLOSED; + closeWithError(request.destination, error); + } else { + request.status = CLOSING; + request.fatalError = error; + } +} + +function emitPostponeChunk(request, id, postponeInstance) { + var row; + + { + var reason = ''; + var stack = ''; + + try { + // eslint-disable-next-line react-internal/safe-string-coercion + reason = String(postponeInstance.message); // eslint-disable-next-line react-internal/safe-string-coercion + + stack = String(postponeInstance.stack); + } catch (x) {} + + row = serializeRowHeader('P', id) + stringify({ + reason: reason, + stack: stack + }) + '\n'; + } + + var processedChunk = stringToChunk(row); + request.completedErrorChunks.push(processedChunk); +} + +function emitErrorChunk(request, id, digest, error) { + var errorInfo; + + { + var message; + var stack = ''; + + try { + if (error instanceof Error) { + // eslint-disable-next-line react-internal/safe-string-coercion + message = String(error.message); // eslint-disable-next-line react-internal/safe-string-coercion + + stack = String(error.stack); + } else { + message = 'Error: ' + error; + } + } catch (x) { + message = 'An error occurred but serializing the error message failed.'; + } + + errorInfo = { + digest: digest, + message: message, + stack: stack + }; + } + + var row = serializeRowHeader('E', id) + stringify(errorInfo) + '\n'; + var processedChunk = stringToChunk(row); + request.completedErrorChunks.push(processedChunk); +} + +function emitImportChunk(request, id, clientReferenceMetadata) { + // $FlowFixMe[incompatible-type] stringify can return null + var json = stringify(clientReferenceMetadata); + var row = serializeRowHeader('I', id) + json + '\n'; + var processedChunk = stringToChunk(row); + request.completedImportChunks.push(processedChunk); +} + +function emitHintChunk(request, code, model) { + var json = stringify(model); + var id = request.nextChunkId++; + var row = serializeRowHeader('H' + code, id) + json + '\n'; + var processedChunk = stringToChunk(row); + request.completedHintChunks.push(processedChunk); +} + +function emitSymbolChunk(request, id, name) { + var symbolReference = serializeSymbolReference(name); + var processedChunk = encodeReferenceChunk(request, id, symbolReference); + request.completedImportChunks.push(processedChunk); +} + +function emitProviderChunk(request, id, contextName) { + var contextReference = serializeProviderReference(contextName); + var processedChunk = encodeReferenceChunk(request, id, contextReference); + request.completedRegularChunks.push(processedChunk); +} + +function emitModelChunk(request, id, model) { + // $FlowFixMe[incompatible-type] stringify can return null + var json = stringify(model, request.toJSON); + var row = id.toString(16) + ':' + json + '\n'; + var processedChunk = stringToChunk(row); + request.completedRegularChunks.push(processedChunk); +} + +function retryTask(request, task) { + if (task.status !== PENDING$1) { + // We completed this by other means before we had a chance to retry it. + return; + } + + switchContext(task.context); + + try { + var value = task.model; + + if (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) { + // TODO: Concatenate keys of parents onto children. + var element = value; // When retrying a component, reuse the thenableState from the + // previous attempt. + + var prevThenableState = task.thenableState; // Attempt to render the Server Component. + // Doing this here lets us reuse this same task if the next component + // also suspends. + + task.model = value; + value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, prevThenableState); // Successfully finished this component. We're going to keep rendering + // using the same task, but we reset its thenable state before continuing. + + task.thenableState = null; // Keep rendering and reuse the same task. This inner loop is separate + // from the render above because we don't need to reset the thenable state + // until the next time something suspends and retries. + + while (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) { + // TODO: Concatenate keys of parents onto children. + var nextElement = value; + task.model = value; + value = attemptResolveElement(request, nextElement.type, nextElement.key, nextElement.ref, nextElement.props, null); + } + } + + emitModelChunk(request, task.id, value); + request.abortableTasks.delete(task); + task.status = COMPLETED; + } catch (thrownValue) { + var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical + // reasons, the rest of the Suspense implementation expects the thrown + // value to be a thenable, because before `use` existed that was the + // (unstable) API for suspending. This implementation detail can change + // later, once we deprecate the old API in favor of `use`. + getSuspendedThenable() : thrownValue; + + if (typeof x === 'object' && x !== null) { + // $FlowFixMe[method-unbinding] + if (typeof x.then === 'function') { + // Something suspended again, let's pick it back up later. + var ping = task.ping; + x.then(ping, ping); + task.thenableState = getThenableStateAfterSuspending(); + return; + } else if (x.$$typeof === REACT_POSTPONE_TYPE) { + request.abortableTasks.delete(task); + task.status = ERRORED$1; + var postponeInstance = x; + logPostpone(request, postponeInstance.message); + emitPostponeChunk(request, task.id, postponeInstance); + return; + } + } + + request.abortableTasks.delete(task); + task.status = ERRORED$1; + var digest = logRecoverableError(request, x); + emitErrorChunk(request, task.id, digest, x); + } +} + +function performWork(request) { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = HooksDispatcher; + var prevRequest = currentRequest; + currentRequest = request; + prepareToUseHooksForRequest(request); + + try { + var pingedTasks = request.pingedTasks; + request.pingedTasks = []; + + for (var i = 0; i < pingedTasks.length; i++) { + var task = pingedTasks[i]; + retryTask(request, task); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } finally { + ReactCurrentDispatcher.current = prevDispatcher; + resetHooksForRequest(); + currentRequest = prevRequest; + } +} + +function abortTask(task, request, errorId) { + task.status = ABORTED; // Instead of emitting an error per task.id, we emit a model that only + // has a single value referencing the error. + + var ref = serializeByValueID(errorId); + var processedChunk = encodeReferenceChunk(request, task.id, ref); + request.completedErrorChunks.push(processedChunk); +} + +function flushCompletedChunks(request, destination) { + beginWriting(); + + try { + // We emit module chunks first in the stream so that + // they can be preloaded as early as possible. + var importsChunks = request.completedImportChunks; + var i = 0; + + for (; i < importsChunks.length; i++) { + request.pendingChunks--; + var chunk = importsChunks[i]; + var keepWriting = writeChunkAndReturn(destination, chunk); + + if (!keepWriting) { + request.destination = null; + i++; + break; + } + } + + importsChunks.splice(0, i); // Next comes hints. + + var hintChunks = request.completedHintChunks; + i = 0; + + for (; i < hintChunks.length; i++) { + var _chunk = hintChunks[i]; + + var _keepWriting = writeChunkAndReturn(destination, _chunk); + + if (!_keepWriting) { + request.destination = null; + i++; + break; + } + } + + hintChunks.splice(0, i); // Next comes model data. + + var regularChunks = request.completedRegularChunks; + i = 0; + + for (; i < regularChunks.length; i++) { + request.pendingChunks--; + var _chunk2 = regularChunks[i]; + + var _keepWriting2 = writeChunkAndReturn(destination, _chunk2); + + if (!_keepWriting2) { + request.destination = null; + i++; + break; + } + } + + regularChunks.splice(0, i); // Finally, errors are sent. The idea is that it's ok to delay + // any error messages and prioritize display of other parts of + // the page. + + var errorChunks = request.completedErrorChunks; + i = 0; + + for (; i < errorChunks.length; i++) { + request.pendingChunks--; + var _chunk3 = errorChunks[i]; + + var _keepWriting3 = writeChunkAndReturn(destination, _chunk3); + + if (!_keepWriting3) { + request.destination = null; + i++; + break; + } + } + + errorChunks.splice(0, i); + } finally { + request.flushScheduled = false; + completeWriting(destination); + } + + flushBuffered(destination); + + if (request.pendingChunks === 0) { + // We're done. + close$1(destination); + } +} + +function startWork(request) { + request.flushScheduled = request.destination !== null; + + { + scheduleWork(function () { + return requestStorage.run(request, performWork, request); + }); + } +} + +function enqueueFlush(request) { + if (request.flushScheduled === false && // If there are pinged tasks we are going to flush anyway after work completes + request.pingedTasks.length === 0 && // If there is no destination there is nothing we can flush to. A flush will + // happen when we start flowing again + request.destination !== null) { + var destination = request.destination; + request.flushScheduled = true; + scheduleWork(function () { + return flushCompletedChunks(request, destination); + }); + } +} + +function startFlowing(request, destination) { + if (request.status === CLOSING) { + request.status = CLOSED; + closeWithError(destination, request.fatalError); + return; + } + + if (request.status === CLOSED) { + return; + } + + if (request.destination !== null) { + // We're already flowing. + return; + } + + request.destination = destination; + + try { + flushCompletedChunks(request, destination); + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} + +function abort(request, reason) { + try { + var abortableTasks = request.abortableTasks; + + if (abortableTasks.size > 0) { + // We have tasks to abort. We'll emit one error row and then emit a reference + // to that row from every row that's still remaining. + var error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason; + var digest = logRecoverableError(request, error); + request.pendingChunks++; + var errorId = request.nextChunkId++; + emitErrorChunk(request, errorId, digest, error); + abortableTasks.forEach(function (task) { + return abortTask(task, request, errorId); + }); + abortableTasks.clear(); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} + +function importServerContexts(contexts) { + if (contexts) { + var prevContext = getActiveContext(); + switchContext(rootContextSnapshot); + + for (var i = 0; i < contexts.length; i++) { + var _contexts$i = contexts[i], + name = _contexts$i[0], + value = _contexts$i[1]; + var context = getOrCreateServerContext(name); + pushProvider(context, value); + } + + var importedContext = getActiveContext(); + switchContext(prevContext); + return importedContext; + } + + return rootContextSnapshot; +} + +function resolveServerReference(bundlerConfig, id) { + var idx = id.lastIndexOf('#'); + var specifier = id.slice(0, idx); + var name = id.slice(idx + 1); + return { + specifier: specifier, + name: name + }; +} +var asyncModuleCache = new Map(); +function preloadModule(metadata) { + var existingPromise = asyncModuleCache.get(metadata.specifier); + + if (existingPromise) { + if (existingPromise.status === 'fulfilled') { + return null; + } + + return existingPromise; + } else { + // $FlowFixMe[unsupported-syntax] + var modulePromise = import(metadata.specifier); + + if (metadata.async) { + // If the module is async, it must have been a CJS module. + // CJS modules are accessed through the default export in + // Node.js so we have to get the default export to get the + // full module exports. + modulePromise = modulePromise.then(function (value) { + return value.default; + }); + } + + modulePromise.then(function (value) { + var fulfilledThenable = modulePromise; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = value; + }, function (reason) { + var rejectedThenable = modulePromise; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = reason; + }); + asyncModuleCache.set(metadata.specifier, modulePromise); + return modulePromise; + } +} +function requireModule(metadata) { + var moduleExports; // We assume that preloadModule has been called before, which + // should have added something to the module cache. + + var promise = asyncModuleCache.get(metadata.specifier); + + if (promise.status === 'fulfilled') { + moduleExports = promise.value; + } else { + throw promise.reason; + } + + if (metadata.name === '*') { + // This is a placeholder value that represents that the caller imported this + // as a CommonJS module as is. + return moduleExports; + } + + if (metadata.name === '') { + // This is a placeholder value that represents that the caller accessed the + // default property of this if it was an ESM interop module. + return moduleExports.default; + } + + return moduleExports[metadata.name]; +} + +// The server acts as a Client of itself when resolving Server References. +var PENDING = 'pending'; +var BLOCKED = 'blocked'; +var RESOLVED_MODEL = 'resolved_model'; +var INITIALIZED = 'fulfilled'; +var ERRORED = 'rejected'; // $FlowFixMe[missing-this-annot] + +function Chunk(status, value, reason, response) { + this.status = status; + this.value = value; + this.reason = reason; + this._response = response; +} // We subclass Promise.prototype so that we get other methods like .catch + + +Chunk.prototype = Object.create(Promise.prototype); // TODO: This doesn't return a new Promise chain unlike the real .then + +Chunk.prototype.then = function (resolve, reject) { + var chunk = this; // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + resolve(chunk.value); + break; + + case PENDING: + case BLOCKED: + if (resolve) { + if (chunk.value === null) { + chunk.value = []; + } + + chunk.value.push(resolve); + } + + if (reject) { + if (chunk.reason === null) { + chunk.reason = []; + } + + chunk.reason.push(reject); + } + + break; + + default: + reject(chunk.reason); + break; + } +}; + +function getRoot(response) { + var chunk = getChunk(response, 0); + return chunk; +} + +function createPendingChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(PENDING, null, null, response); +} + +function wakeChunk(listeners, value) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + listener(value); + } +} + +function wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners) { + switch (chunk.status) { + case INITIALIZED: + wakeChunk(resolveListeners, chunk.value); + break; + + case PENDING: + case BLOCKED: + chunk.value = resolveListeners; + chunk.reason = rejectListeners; + break; + + case ERRORED: + if (rejectListeners) { + wakeChunk(rejectListeners, chunk.reason); + } + + break; + } +} + +function triggerErrorOnChunk(chunk, error) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var listeners = chunk.reason; + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + + if (listeners !== null) { + wakeChunk(listeners, error); + } +} + +function createResolvedModelChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODEL, value, null, response); +} + +function resolveModelChunk(chunk, value) { + if (chunk.status !== PENDING) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODEL; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + // This is unfortunate that we're reading this eagerly if + // we already have listeners attached since they might no + // longer be rendered or might not be the highest pri. + initializeModelChunk(resolvedChunk); // The status might have changed after initialization. + + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +function bindArgs$1(fn, args) { + return fn.bind.apply(fn, [null].concat(args)); +} + +function loadServerReference$1(response, id, bound, parentChunk, parentObject, key) { + var serverReference = resolveServerReference(response._bundlerConfig, id); // We expect most servers to not really need this because you'd just have all + // the relevant modules already loaded but it allows for lazy loading of code + // if needed. + + var preloadPromise = preloadModule(serverReference); + var promise; + + if (bound) { + promise = Promise.all([bound, preloadPromise]).then(function (_ref) { + var args = _ref[0]; + return bindArgs$1(requireModule(serverReference), args); + }); + } else { + if (preloadPromise) { + promise = Promise.resolve(preloadPromise).then(function () { + return requireModule(serverReference); + }); + } else { + // Synchronously available + return requireModule(serverReference); + } + } + + promise.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); // We need a placeholder value that will be replaced later. + + return null; +} + +var initializingChunk = null; +var initializingChunkBlockedModel = null; + +function initializeModelChunk(chunk) { + var prevChunk = initializingChunk; + var prevBlocked = initializingChunkBlockedModel; + initializingChunk = chunk; + initializingChunkBlockedModel = null; + + try { + var value = JSON.parse(chunk.value, chunk._response._fromJSON); + + if (initializingChunkBlockedModel !== null && initializingChunkBlockedModel.deps > 0) { + initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved. + // We have to go the BLOCKED state until they're resolved. + + var blockedChunk = chunk; + blockedChunk.status = BLOCKED; + blockedChunk.value = null; + blockedChunk.reason = null; + } else { + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } finally { + initializingChunk = prevChunk; + initializingChunkBlockedModel = prevBlocked; + } +} // Report that any missing chunks in the model is now going to throw this +// error upon read. Also notify any pending promises. + + +function reportGlobalError(response, error) { + response._chunks.forEach(function (chunk) { + // If this chunk was already resolved or errored, it won't + // trigger an error but if it wasn't then we need to + // because we won't be getting any new data to resolve it. + if (chunk.status === PENDING) { + triggerErrorOnChunk(chunk, error); + } + }); +} + +function getChunk(response, id) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + var prefix = response._prefix; + var key = prefix + id; // Check if we have this field in the backing store already. + + var backingEntry = response._formData.get(key); + + if (backingEntry != null) { + // We assume that this is a string entry for now. + chunk = createResolvedModelChunk(response, backingEntry); + } else { + // We're still waiting on this entry to stream in. + chunk = createPendingChunk(response); + } + + chunks.set(id, chunk); + } + + return chunk; +} + +function createModelResolver(chunk, parentObject, key) { + var blocked; + + if (initializingChunkBlockedModel) { + blocked = initializingChunkBlockedModel; + blocked.deps++; + } else { + blocked = initializingChunkBlockedModel = { + deps: 1, + value: null + }; + } + + return function (value) { + parentObject[key] = value; + blocked.deps--; + + if (blocked.deps === 0) { + if (chunk.status !== BLOCKED) { + return; + } + + var resolveListeners = chunk.value; + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = blocked.value; + + if (resolveListeners !== null) { + wakeChunk(resolveListeners, blocked.value); + } + } + }; +} + +function createModelReject(chunk) { + return function (error) { + return triggerErrorOnChunk(chunk, error); + }; +} + +function getOutlinedModel(response, id) { + var chunk = getChunk(response, id); + + if (chunk.status === RESOLVED_MODEL) { + initializeModelChunk(chunk); + } + + if (chunk.status !== INITIALIZED) { + // We know that this is emitted earlier so otherwise it's an error. + throw chunk.reason; + } + + return chunk.value; +} + +function parseModelString(response, parentObject, key, value) { + if (value[0] === '$') { + switch (value[1]) { + case '$': + { + // This was an escaped string value. + return value.slice(1); + } + + case '@': + { + // Promise + var id = parseInt(value.slice(2), 16); + var chunk = getChunk(response, id); + return chunk; + } + + case 'S': + { + // Symbol + return Symbol.for(value.slice(2)); + } + + case 'F': + { + // Server Reference + var _id = parseInt(value.slice(2), 16); // TODO: Just encode this in the reference inline instead of as a model. + + + var metaData = getOutlinedModel(response, _id); + return loadServerReference$1(response, metaData.id, metaData.bound, initializingChunk, parentObject, key); + } + + case 'Q': + { + // Map + var _id2 = parseInt(value.slice(2), 16); + + var data = getOutlinedModel(response, _id2); + return new Map(data); + } + + case 'W': + { + // Set + var _id3 = parseInt(value.slice(2), 16); + + var _data = getOutlinedModel(response, _id3); + + return new Set(_data); + } + + case 'K': + { + // FormData + var stringId = value.slice(2); + var formPrefix = response._prefix + stringId + '_'; + + var _data2 = new FormData(); + + var backingFormData = response._formData; // We assume that the reference to FormData always comes after each + // entry that it references so we can assume they all exist in the + // backing store already. + // $FlowFixMe[prop-missing] FormData has forEach on it. + + backingFormData.forEach(function (entry, entryKey) { + if (entryKey.startsWith(formPrefix)) { + _data2.append(entryKey.slice(formPrefix.length), entry); + } + }); + return _data2; + } + + case 'I': + { + // $Infinity + return Infinity; + } + + case '-': + { + // $-0 or $-Infinity + if (value === '$-0') { + return -0; + } else { + return -Infinity; + } + } + + case 'N': + { + // $NaN + return NaN; + } + + case 'u': + { + // matches "$undefined" + // Special encoding for `undefined` which can't be serialized as JSON otherwise. + return undefined; + } + + case 'D': + { + // Date + return new Date(Date.parse(value.slice(2))); + } + + case 'n': + { + // BigInt + return BigInt(value.slice(2)); + } + + default: + { + // We assume that anything else is a reference ID. + var _id4 = parseInt(value.slice(1), 16); + + var _chunk = getChunk(response, _id4); + + switch (_chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk); + break; + } // The status might have changed after initialization. + + + switch (_chunk.status) { + case INITIALIZED: + return _chunk.value; + + case PENDING: + case BLOCKED: + var parentChunk = initializingChunk; + + _chunk.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); + + return null; + + default: + throw _chunk.reason; + } + } + } + } + + return value; +} + +function createResponse(bundlerConfig, formFieldPrefix) { + var backingFormData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new FormData(); + var chunks = new Map(); + var response = { + _bundlerConfig: bundlerConfig, + _prefix: formFieldPrefix, + _formData: backingFormData, + _chunks: chunks, + _fromJSON: function (key, value) { + if (typeof value === 'string') { + // We can't use .bind here because we need the "this" value. + return parseModelString(response, this, key, value); + } + + return value; + } + }; + return response; +} +function resolveField(response, key, value) { + // Add this field to the backing store. + response._formData.append(key, value); + + var prefix = response._prefix; + + if (key.startsWith(prefix)) { + var chunks = response._chunks; + var id = +key.slice(prefix.length); + var chunk = chunks.get(id); + + if (chunk) { + // We were waiting on this key so now we can resolve it. + resolveModelChunk(chunk, value); + } + } +} +function resolveFileInfo(response, key, filename, mime) { + return { + chunks: [], + filename: filename, + mime: mime + }; +} +function resolveFileChunk(response, handle, chunk) { + handle.chunks.push(chunk); +} +function resolveFileComplete(response, key, handle) { + // Add this file to the backing store. + // Node.js doesn't expose a global File constructor so we need to use + // the append() form that takes the file name as the third argument, + // to create a File object. + var blob = new Blob(handle.chunks, { + type: handle.mime + }); + + response._formData.append(key, blob, handle.filename); +} +function close(response) { + // In case there are any remaining unresolved chunks, they won't + // be resolved now. So we need to issue an error to those. + // Ideally we should be able to early bail out if we kept a + // ref count of pending chunks. + reportGlobalError(response, new Error('Connection closed.')); +} + +function bindArgs(fn, args) { + return fn.bind.apply(fn, [null].concat(args)); +} + +function loadServerReference(bundlerConfig, id, bound) { + var serverReference = resolveServerReference(bundlerConfig, id); // We expect most servers to not really need this because you'd just have all + // the relevant modules already loaded but it allows for lazy loading of code + // if needed. + + var preloadPromise = preloadModule(serverReference); + + if (bound) { + return Promise.all([bound, preloadPromise]).then(function (_ref) { + var args = _ref[0]; + return bindArgs(requireModule(serverReference), args); + }); + } else if (preloadPromise) { + return Promise.resolve(preloadPromise).then(function () { + return requireModule(serverReference); + }); + } else { + // Synchronously available + return Promise.resolve(requireModule(serverReference)); + } +} + +function decodeBoundActionMetaData(body, serverManifest, formFieldPrefix) { + // The data for this reference is encoded in multiple fields under this prefix. + var actionResponse = createResponse(serverManifest, formFieldPrefix, body); + close(actionResponse); + var refPromise = getRoot(actionResponse); // Force it to initialize + // $FlowFixMe + + refPromise.then(function () {}); + + if (refPromise.status !== 'fulfilled') { + // $FlowFixMe + throw refPromise.reason; + } + + return refPromise.value; +} + +function decodeAction(body, serverManifest) { + // We're going to create a new formData object that holds all the fields except + // the implementation details of the action data. + var formData = new FormData(); + var action = null; // $FlowFixMe[prop-missing] + + body.forEach(function (value, key) { + if (!key.startsWith('$ACTION_')) { + formData.append(key, value); + return; + } // Later actions may override earlier actions if a button is used to override the default + // form action. + + + if (key.startsWith('$ACTION_REF_')) { + var formFieldPrefix = '$ACTION_' + key.slice(12) + ':'; + var metaData = decodeBoundActionMetaData(body, serverManifest, formFieldPrefix); + action = loadServerReference(serverManifest, metaData.id, metaData.bound); + return; + } + + if (key.startsWith('$ACTION_ID_')) { + var id = key.slice(11); + action = loadServerReference(serverManifest, id, null); + return; + } + }); + + if (action === null) { + return null; + } // Return the action with the remaining FormData bound to the first argument. + + + return action.then(function (fn) { + return fn.bind(null, formData); + }); +} + +function createDrainHandler(destination, request) { + return function () { + return startFlowing(request, destination); + }; +} + +function renderToPipeableStream(model, turbopackMap, options) { + var request = createRequest(model, turbopackMap, options ? options.onError : undefined, options ? options.context : undefined, options ? options.identifierPrefix : undefined, options ? options.onPostpone : undefined); + var hasStartedFlowing = false; + startWork(request); + return { + pipe: function (destination) { + if (hasStartedFlowing) { + throw new Error('React currently only supports piping to one writable stream.'); + } + + hasStartedFlowing = true; + startFlowing(request, destination); + destination.on('drain', createDrainHandler(destination, request)); + return destination; + }, + abort: function (reason) { + abort(request, reason); + } + }; +} + +function decodeReplyFromBusboy(busboyStream, turbopackMap) { + var response = createResponse(turbopackMap, ''); + var pendingFiles = 0; + var queuedFields = []; + busboyStream.on('field', function (name, value) { + if (pendingFiles > 0) { + // Because the 'end' event fires two microtasks after the next 'field' + // we would resolve files and fields out of order. To handle this properly + // we queue any fields we receive until the previous file is done. + queuedFields.push(name, value); + } else { + resolveField(response, name, value); + } + }); + busboyStream.on('file', function (name, value, _ref) { + var filename = _ref.filename, + encoding = _ref.encoding, + mimeType = _ref.mimeType; + + if (encoding.toLowerCase() === 'base64') { + throw new Error("React doesn't accept base64 encoded file uploads because we don't expect " + "form data passed from a browser to ever encode data that way. If that's " + 'the wrong assumption, we can easily fix it.'); + } + + pendingFiles++; + var file = resolveFileInfo(response, name, filename, mimeType); + value.on('data', function (chunk) { + resolveFileChunk(response, file, chunk); + }); + value.on('end', function () { + resolveFileComplete(response, name, file); + pendingFiles--; + + if (pendingFiles === 0) { + // Release any queued fields + for (var i = 0; i < queuedFields.length; i += 2) { + resolveField(response, queuedFields[i], queuedFields[i + 1]); + } + + queuedFields.length = 0; + } + }); + }); + busboyStream.on('finish', function () { + close(response); + }); + busboyStream.on('error', function (err) { + reportGlobalError(response, // $FlowFixMe[incompatible-call] types Error and mixed are incompatible + err); + }); + return getRoot(response); +} + +function decodeReply(body, turbopackMap) { + if (typeof body === 'string') { + var form = new FormData(); + form.append('0', body); + body = form; + } + + var response = createResponse(turbopackMap, '', body); + close(response); + return getRoot(response); +} + +exports.createClientModuleProxy = createClientModuleProxy; +exports.decodeAction = decodeAction; +exports.decodeReply = decodeReply; +exports.decodeReplyFromBusboy = decodeReplyFromBusboy; +exports.registerClientReference = registerClientReference; +exports.registerServerReference = registerServerReference; +exports.renderToPipeableStream = renderToPipeableStream; + })(); +} diff --git a/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-server.node.unbundled.production.min.js b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-server.node.unbundled.production.min.js new file mode 100644 index 0000000000000..596bf223646a1 --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-server.node.unbundled.production.min.js @@ -0,0 +1,77 @@ +/** + * @license React + * react-server-dom-turbopack-server.node.unbundled.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var aa=require("util");require("crypto");var ba=require("async_hooks"),ca=require("react"),da=require("react-dom"),l=null,m=0,r=!0;function t(a,b){a=a.write(b);r=r&&a} +function u(a,b){if("string"===typeof b){if(0!==b.length)if(2048<3*b.length)0a.depth?Ia(b,a):Ja(b,a),F=a)}function La(a,b){var d=a._currentValue;a._currentValue=b;var c=F;return F=a={parent:c,depth:null===c?0:c.depth+1,context:a,parentValue:d,value:b}}var Ma=Error("Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`"); +function Na(){}function Oa(a,b,d){d=a[d];void 0===d?a.push(b):d!==b&&(b.then(Na,Na),b=d);switch(b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;default:if("string"!==typeof b.status)switch(a=b,a.status="pending",a.then(function(c){if("pending"===b.status){var e=b;e.status="fulfilled";e.value=c}},function(c){if("pending"===b.status){var e=b;e.status="rejected";e.reason=c}}),b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;}I=b;throw Ma;}}var I=null; +function Pa(){if(null===I)throw Error("Expected a suspended thenable. This is a bug in React. Please file an issue.");var a=I;I=null;return a}var J=null,K=0,L=null;function Qa(){var a=L;L=null;return a}function Ra(a){return a._currentValue} +var Va={useMemo:function(a){return a()},useCallback:function(a){return a},useDebugValue:function(){},useDeferredValue:M,useTransition:M,readContext:Ra,useContext:Ra,useReducer:M,useRef:M,useState:M,useInsertionEffect:M,useLayoutEffect:M,useImperativeHandle:M,useEffect:M,useId:Sa,useSyncExternalStore:M,useCacheRefresh:function(){return Ta},useMemoCache:function(a){for(var b=Array(a),d=0;d=a.length?a:a.slice(0,10)+"...");case "object":if(Za(a))return"[...]";a=$a(a);return"Object"===a?"{...}":a;case "function":return"function";default:return String(a)}} +function bb(a){if("string"===typeof a)return a;switch(a){case Aa:return"Suspense";case Ba:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case za:return bb(a.render);case Ca:return bb(a.type);case C:var b=a._payload;a=a._init;try{return bb(a(b))}catch(d){}}return""} +function N(a,b){var d=$a(a);if("Object"!==d&&"Array"!==d)return d;d=-1;var c=0;if(Za(a)){var e="[";for(var f=0;fg.length&&40>e.length+g.length?e+g:e+"..."}e+="]"}else if(a.$$typeof===B)e="<"+bb(a.type)+"/>";else{e="{";f=Object.keys(a);for(g=0;gk.length&&40>e.length+k.length?e+k:e+"..."}e+="}"}return void 0===b?e:-1{if(e){if(e.file){this.addDependency(r.default.normalize(e.file))}s(new a.default(e));return}let n=t.map?JSON.parse(t.map):null;if(n&&c){n=(0,o.normalizeSourceMap)(n,this.rootContext)}t.stats.includedFiles.forEach((e=>{const t=r.default.normalize(e);if(r.default.isAbsolute(t)){this.addDependency(t)}}));s(null,t.css.toString(),n)}))}var i=loader;t["default"]=i},125:function(__unused_webpack_module,exports,__nccwpck_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getRenderFunctionFromSassImplementation=getRenderFunctionFromSassImplementation;exports.getSassImplementation=getSassImplementation;exports.getSassOptions=getSassOptions;exports.getWebpackImporter=getWebpackImporter;exports.getWebpackResolver=getWebpackResolver;exports.isSupportedFibers=isSupportedFibers;exports.normalizeSourceMap=normalizeSourceMap;var _url=_interopRequireDefault(__nccwpck_require__(310));var _path=_interopRequireDefault(__nccwpck_require__(17));var _full=__nccwpck_require__(12);var _neoAsync=_interopRequireDefault(__nccwpck_require__(175));var _SassWarning=_interopRequireDefault(__nccwpck_require__(186));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function getDefaultSassImplementation(){let sassImplPkg="sass";try{eval("require").resolve("sass")}catch(error){try{eval("require").resolve("node-sass");sassImplPkg="node-sass"}catch(e){sassImplPkg="sass"}}return __nccwpck_require__(438)}function getSassImplementation(e,t){let s=t;if(!s){try{s=getDefaultSassImplementation()}catch(t){e.emitError(t);return}}if(typeof s==="string"){try{s=require(s)}catch(t){e.emitError(t);return}}const{info:r}=s;if(!r){e.emitError(new Error("Unknown Sass implementation."));return}const n=r.split("\t");if(n.length<2){e.emitError(new Error(`Unknown Sass implementation "${r}".`));return}const[o]=n;if(o==="dart-sass"){return s}else if(o==="node-sass"){return s}e.emitError(new Error(`Unknown Sass implementation "${o}".`))}function isProductionLikeMode(e){return e.mode==="production"||!e.mode}function proxyCustomImporters(e,t){return[].concat(e).map((e=>function proxyImporter(...s){const r={...this,webpackLoaderContext:t};return e.apply(r,s)}))}function isSupportedFibers(){const[e]=process.versions.node.split(".");return Number(e)<16}async function getSassOptions(e,t,s,r,n){const o=(0,_full.klona)(t.sassOptions?typeof t.sassOptions==="function"?t.sassOptions(e)||{}:t.sassOptions:{});const a=r.info.includes("dart-sass");if(a&&isSupportedFibers()){const e=!o.fiber&&o.fiber!==false;if(e){let e;try{e=require.resolve("fibers")}catch(e){}if(e){o.fiber=require(e)}}else if(o.fiber===false){delete o.fiber}}else{delete o.fiber}o.file=e.resourcePath;o.data=t.additionalData?typeof t.additionalData==="function"?await t.additionalData(s,e):`${t.additionalData}\n${s}`:s;if(!o.outputStyle&&isProductionLikeMode(e)){o.outputStyle="compressed"}if(n){o.sourceMap=true;o.outFile=_path.default.join(e.rootContext,"style.css.map");o.sourceMapContents=true;o.omitSourceMapUrl=true;o.sourceMapEmbed=false}const{resourcePath:i}=e;const c=_path.default.extname(i);if(c&&c.toLowerCase()===".sass"&&typeof o.indentedSyntax==="undefined"){o.indentedSyntax=true}else{o.indentedSyntax=Boolean(o.indentedSyntax)}o.importer=o.importer?proxyCustomImporters(Array.isArray(o.importer)?o.importer:[o.importer],e):[];o.includePaths=[].concat(process.cwd()).concat((o.includePaths||[]).map((e=>_path.default.isAbsolute(e)?e:_path.default.join(process.cwd(),e)))).concat(process.env.SASS_PATH?process.env.SASS_PATH.split(process.platform==="win32"?";":":"):[]);if(typeof o.charset==="undefined"){o.charset=true}if(!o.logger){const s=t.warnRuleAsWarning===true;const r=e.getLogger("sass-loader");const formatSpan=e=>`${e.url||"-"}:${e.start.line}:${e.start.column}: `;o.logger={debug(e,t){let s="";if(t.span){s=formatSpan(t.span)}s+=e;r.debug(s)},warn(t,n){let o="";if(n.deprecation){o+="Deprecation "}if(n.span&&!n.stack){o=formatSpan(n.span)}o+=t;if(n.stack){o+=`\n\n${n.stack}`}if(s){e.emitWarning(new _SassWarning.default(o,n))}else{r.warn(o)}}}}return o}const MODULE_REQUEST_REGEX=/^[^?]*~/;const IS_MODULE_IMPORT=/^~([^/]+|[^/]+\/|@[^/]+[/][^/]+|@[^/]+\/?|@[^/]+[/][^/]+\/)$/;function getPossibleRequests(e,t=false,s=false){let r=e;if(t){if(MODULE_REQUEST_REGEX.test(e)){r=r.replace(MODULE_REQUEST_REGEX,"")}if(IS_MODULE_IMPORT.test(e)){r=r[r.length-1]==="/"?r:`${r}/`;return[...new Set([r,e])]}}const n=_path.default.extname(r).toLowerCase();if(n===".css"){return[]}const o=_path.default.dirname(r);const a=o==="."?"":`${o}/`;const i=_path.default.basename(r);const c=_path.default.basename(r,n);return[...new Set([].concat(s?[`${a}_${c}.import${n}`,`${a}${c}.import${n}`]:[]).concat([`${a}_${i}`,`${a}${i}`]).concat(t?[e]:[]))]}function promiseResolve(e){return(t,s)=>new Promise(((r,n)=>{e(t,s,((e,t)=>{if(e){n(e)}else{r(t)}}))}))}const IS_SPECIAL_MODULE_IMPORT=/^~[^/]+$/;const IS_NATIVE_WIN32_PATH=/^[a-z]:[/\\]|^\\\\/i;function getWebpackResolver(e,t,s=[]){async function startResolving(e){if(e.length===0){return Promise.reject()}const[{possibleRequests:t}]=e;if(t.length===0){return Promise.reject()}const[{resolve:s,context:r}]=e;try{return await s(r,t[0])}catch(s){const[,...r]=t;if(r.length===0){const[,...t]=e;return startResolving(t)}e[0].possibleRequests=r;return startResolving(e)}}const r=t.info.includes("dart-sass");const n=promiseResolve(e({alias:[],aliasFields:[],conditionNames:[],descriptionFiles:[],extensions:[".sass",".scss",".css"],exportsFields:[],mainFields:[],mainFiles:["_index","index"],modules:[],restrictions:[/\.((sa|sc|c)ss)$/i],preferRelative:true}));const o=promiseResolve(e({alias:[],aliasFields:[],conditionNames:[],descriptionFiles:[],extensions:[".sass",".scss",".css"],exportsFields:[],mainFields:[],mainFiles:["_index.import","_index","index.import","index"],modules:[],restrictions:[/\.((sa|sc|c)ss)$/i],preferRelative:true}));const a=promiseResolve(e({dependencyType:"sass",conditionNames:["sass","style"],mainFields:["sass","style","main","..."],mainFiles:["_index","index","..."],extensions:[".sass",".scss",".css"],restrictions:[/\.((sa|sc|c)ss)$/i],preferRelative:true}));const i=promiseResolve(e({dependencyType:"sass",conditionNames:["sass","style"],mainFields:["sass","style","main","..."],mainFiles:["_index.import","_index","index.import","index","..."],extensions:[".sass",".scss",".css"],restrictions:[/\.((sa|sc|c)ss)$/i],preferRelative:true}));return(e,t,c)=>{if(!r&&!_path.default.isAbsolute(e)){return Promise.reject()}const l=t;const u=l.slice(0,5).toLowerCase()==="file:";if(u){try{t=_url.default.fileURLToPath(l)}catch(e){t=t.slice(7)}}let p=[];const f=!IS_SPECIAL_MODULE_IMPORT.test(t)&&!u&&!l.startsWith("/")&&!IS_NATIVE_WIN32_PATH.test(l);if(s.length>0&&f){const a=getPossibleRequests(t,false,c);if(!r){p=p.concat({resolve:c?o:n,context:_path.default.dirname(e),possibleRequests:a})}p=p.concat(s.map((e=>({resolve:c?o:n,context:e,possibleRequests:a}))))}const d=getPossibleRequests(t,true,c);p=p.concat({resolve:c?i:a,context:_path.default.dirname(e),possibleRequests:d});return startResolving(p)}}const MATCH_CSS=/\.css$/i;function getWebpackImporter(e,t,s){const r=getWebpackResolver(e.getResolve,t,s);return function importer(t,s,n){const{fromImport:o}=this;r(s,t,o).then((t=>{e.addDependency(_path.default.normalize(t));n({file:t.replace(MATCH_CSS,"")})})).catch((()=>{n({file:t})}))}}let nodeSassJobQueue=null;function getRenderFunctionFromSassImplementation(e){const t=e.info.includes("dart-sass");if(t){return e.render.bind(e)}if(nodeSassJobQueue===null){const t=Number(process.env.UV_THREADPOOL_SIZE||4);nodeSassJobQueue=_neoAsync.default.queue(e.render.bind(e),t-1)}return nodeSassJobQueue.push.bind(nodeSassJobQueue)}const ABSOLUTE_SCHEME=/^[A-Za-z0-9+\-.]+:/;function getURLType(e){if(e[0]==="/"){if(e[1]==="/"){return"scheme-relative"}return"path-absolute"}if(IS_NATIVE_WIN32_PATH.test(e)){return"path-absolute"}return ABSOLUTE_SCHEME.test(e)?"absolute":"path-relative"}function normalizeSourceMap(e,t){const s=e;delete s.file;s.sourceRoot="";s.sources=s.sources.map((e=>{const s=getURLType(e);if(s==="path-relative"){return _path.default.resolve(t,_path.default.normalize(e))}return e}));return s}},175:function(e){"use strict";e.exports=require("next/dist/compiled/neo-async")},17:function(e){"use strict";e.exports=require("path")},438:function(e){"use strict";e.exports=require("sass")},310:function(e){"use strict";e.exports=require("url")},596:function(e){"use strict";e.exports=JSON.parse('{"title":"Sass Loader options","type":"object","properties":{"implementation":{"description":"The implementation of the sass to be used.","link":"https://github.com/webpack-contrib/sass-loader#implementation","anyOf":[{"type":"string"},{"type":"object"}]},"sassOptions":{"description":"Options for `node-sass` or `sass` (`Dart Sass`) implementation.","link":"https://github.com/webpack-contrib/sass-loader#sassoptions","anyOf":[{"type":"object","additionalProperties":true},{"instanceof":"Function"}]},"additionalData":{"description":"Prepends/Appends `Sass`/`SCSS` code before the actual entry file.","link":"https://github.com/webpack-contrib/sass-loader#additionaldata","anyOf":[{"type":"string"},{"instanceof":"Function"}]},"sourceMap":{"description":"Enables/Disables generation of source maps.","link":"https://github.com/webpack-contrib/sass-loader#sourcemap","type":"boolean"},"webpackImporter":{"description":"Enables/Disables default `webpack` importer.","link":"https://github.com/webpack-contrib/sass-loader#webpackimporter","type":"boolean"},"warnRuleAsWarning":{"description":"Treats the \'@warn\' rule as a webpack warning.","link":"https://github.com/webpack-contrib/sass-loader#warnruleaswarning","type":"boolean"}},"additionalProperties":false}')}};var __webpack_module_cache__={};function __nccwpck_require__(e){var t=__webpack_module_cache__[e];if(t!==undefined){return t.exports}var s=__webpack_module_cache__[e]={exports:{}};var r=true;try{__webpack_modules__[e](s,s.exports,__nccwpck_require__);r=false}finally{if(r)delete __webpack_module_cache__[e]}return s.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var __webpack_exports__=__nccwpck_require__(917);module.exports=__webpack_exports__})(); \ No newline at end of file +(function(){var __webpack_modules__={12:function(e,t){function set(e,t,s){if(typeof s.value==="object")s.value=klona(s.value);if(!s.enumerable||s.get||s.set||!s.configurable||!s.writable||t==="__proto__"){Object.defineProperty(e,t,s)}else e[t]=s.value}function klona(e){if(typeof e!=="object")return e;var t=0,s,r,n,o=Object.prototype.toString.call(e);if(o==="[object Object]"){n=Object.create(e.__proto__||null)}else if(o==="[object Array]"){n=Array(e.length)}else if(o==="[object Set]"){n=new Set;e.forEach((function(e){n.add(klona(e))}))}else if(o==="[object Map]"){n=new Map;e.forEach((function(e,t){n.set(klona(t),klona(e))}))}else if(o==="[object Date]"){n=new Date(+e)}else if(o==="[object RegExp]"){n=new RegExp(e.source,e.flags)}else if(o==="[object DataView]"){n=new e.constructor(klona(e.buffer))}else if(o==="[object ArrayBuffer]"){n=e.slice(0)}else if(o.slice(-6)==="Array]"){n=new e.constructor(e)}if(n){for(r=Object.getOwnPropertySymbols(e);t{if(e){if(e.file){this.addDependency(r.default.normalize(e.file))}s(new a.default(e));return}let n=t.map?JSON.parse(t.map):null;if(n&&c){n=(0,o.normalizeSourceMap)(n,this.rootContext)}t.stats.includedFiles.forEach((e=>{const t=r.default.normalize(e);if(r.default.isAbsolute(t)){this.addDependency(t)}}));s(null,t.css.toString(),n)}))}var i=loader;t["default"]=i},636:function(__unused_webpack_module,exports,__nccwpck_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getRenderFunctionFromSassImplementation=getRenderFunctionFromSassImplementation;exports.getSassImplementation=getSassImplementation;exports.getSassOptions=getSassOptions;exports.getWebpackImporter=getWebpackImporter;exports.getWebpackResolver=getWebpackResolver;exports.isSupportedFibers=isSupportedFibers;exports.normalizeSourceMap=normalizeSourceMap;var _url=_interopRequireDefault(__nccwpck_require__(310));var _path=_interopRequireDefault(__nccwpck_require__(17));var _full=__nccwpck_require__(12);var _neoAsync=_interopRequireDefault(__nccwpck_require__(175));var _SassWarning=_interopRequireDefault(__nccwpck_require__(955));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function getDefaultSassImplementation(){let sassImplPkg="sass";try{eval("require").resolve("sass")}catch(error){try{eval("require").resolve("node-sass");sassImplPkg="node-sass"}catch(e){sassImplPkg="sass"}}return __nccwpck_require__(438)}function getSassImplementation(e,t){let s=t;if(!s){try{s=getDefaultSassImplementation()}catch(t){e.emitError(t);return}}if(typeof s==="string"){try{s=require(s)}catch(t){e.emitError(t);return}}const{info:r}=s;if(!r){e.emitError(new Error("Unknown Sass implementation."));return}const n=r.split("\t");if(n.length<2){e.emitError(new Error(`Unknown Sass implementation "${r}".`));return}const[o]=n;if(o==="dart-sass"){return s}else if(o==="node-sass"){return s}e.emitError(new Error(`Unknown Sass implementation "${o}".`))}function isProductionLikeMode(e){return e.mode==="production"||!e.mode}function proxyCustomImporters(e,t){return[].concat(e).map((e=>function proxyImporter(...s){const r={...this,webpackLoaderContext:t};return e.apply(r,s)}))}function isSupportedFibers(){const[e]=process.versions.node.split(".");return Number(e)<16}async function getSassOptions(e,t,s,r,n){const o=(0,_full.klona)(t.sassOptions?typeof t.sassOptions==="function"?t.sassOptions(e)||{}:t.sassOptions:{});const a=r.info.includes("dart-sass");if(a&&isSupportedFibers()){const e=!o.fiber&&o.fiber!==false;if(e){let e;try{e=require.resolve("fibers")}catch(e){}if(e){o.fiber=require(e)}}else if(o.fiber===false){delete o.fiber}}else{delete o.fiber}o.file=e.resourcePath;o.data=t.additionalData?typeof t.additionalData==="function"?await t.additionalData(s,e):`${t.additionalData}\n${s}`:s;if(!o.outputStyle&&isProductionLikeMode(e)){o.outputStyle="compressed"}if(n){o.sourceMap=true;o.outFile=_path.default.join(e.rootContext,"style.css.map");o.sourceMapContents=true;o.omitSourceMapUrl=true;o.sourceMapEmbed=false}const{resourcePath:i}=e;const c=_path.default.extname(i);if(c&&c.toLowerCase()===".sass"&&typeof o.indentedSyntax==="undefined"){o.indentedSyntax=true}else{o.indentedSyntax=Boolean(o.indentedSyntax)}o.importer=o.importer?proxyCustomImporters(Array.isArray(o.importer)?o.importer:[o.importer],e):[];o.includePaths=[].concat(process.cwd()).concat((o.includePaths||[]).map((e=>_path.default.isAbsolute(e)?e:_path.default.join(process.cwd(),e)))).concat(process.env.SASS_PATH?process.env.SASS_PATH.split(process.platform==="win32"?";":":"):[]);if(typeof o.charset==="undefined"){o.charset=true}if(!o.logger){const s=t.warnRuleAsWarning===true;const r=e.getLogger("sass-loader");const formatSpan=e=>`${e.url||"-"}:${e.start.line}:${e.start.column}: `;o.logger={debug(e,t){let s="";if(t.span){s=formatSpan(t.span)}s+=e;r.debug(s)},warn(t,n){let o="";if(n.deprecation){o+="Deprecation "}if(n.span&&!n.stack){o=formatSpan(n.span)}o+=t;if(n.stack){o+=`\n\n${n.stack}`}if(s){e.emitWarning(new _SassWarning.default(o,n))}else{r.warn(o)}}}}return o}const MODULE_REQUEST_REGEX=/^[^?]*~/;const IS_MODULE_IMPORT=/^~([^/]+|[^/]+\/|@[^/]+[/][^/]+|@[^/]+\/?|@[^/]+[/][^/]+\/)$/;function getPossibleRequests(e,t=false,s=false){let r=e;if(t){if(MODULE_REQUEST_REGEX.test(e)){r=r.replace(MODULE_REQUEST_REGEX,"")}if(IS_MODULE_IMPORT.test(e)){r=r[r.length-1]==="/"?r:`${r}/`;return[...new Set([r,e])]}}const n=_path.default.extname(r).toLowerCase();if(n===".css"){return[]}const o=_path.default.dirname(r);const a=o==="."?"":`${o}/`;const i=_path.default.basename(r);const c=_path.default.basename(r,n);return[...new Set([].concat(s?[`${a}_${c}.import${n}`,`${a}${c}.import${n}`]:[]).concat([`${a}_${i}`,`${a}${i}`]).concat(t?[e]:[]))]}function promiseResolve(e){return(t,s)=>new Promise(((r,n)=>{e(t,s,((e,t)=>{if(e){n(e)}else{r(t)}}))}))}const IS_SPECIAL_MODULE_IMPORT=/^~[^/]+$/;const IS_NATIVE_WIN32_PATH=/^[a-z]:[/\\]|^\\\\/i;function getWebpackResolver(e,t,s=[]){async function startResolving(e){if(e.length===0){return Promise.reject()}const[{possibleRequests:t}]=e;if(t.length===0){return Promise.reject()}const[{resolve:s,context:r}]=e;try{return await s(r,t[0])}catch(s){const[,...r]=t;if(r.length===0){const[,...t]=e;return startResolving(t)}e[0].possibleRequests=r;return startResolving(e)}}const r=t.info.includes("dart-sass");const n=promiseResolve(e({alias:[],aliasFields:[],conditionNames:[],descriptionFiles:[],extensions:[".sass",".scss",".css"],exportsFields:[],mainFields:[],mainFiles:["_index","index"],modules:[],restrictions:[/\.((sa|sc|c)ss)$/i],preferRelative:true}));const o=promiseResolve(e({alias:[],aliasFields:[],conditionNames:[],descriptionFiles:[],extensions:[".sass",".scss",".css"],exportsFields:[],mainFields:[],mainFiles:["_index.import","_index","index.import","index"],modules:[],restrictions:[/\.((sa|sc|c)ss)$/i],preferRelative:true}));const a=promiseResolve(e({dependencyType:"sass",conditionNames:["sass","style"],mainFields:["sass","style","main","..."],mainFiles:["_index","index","..."],extensions:[".sass",".scss",".css"],restrictions:[/\.((sa|sc|c)ss)$/i],preferRelative:true}));const i=promiseResolve(e({dependencyType:"sass",conditionNames:["sass","style"],mainFields:["sass","style","main","..."],mainFiles:["_index.import","_index","index.import","index","..."],extensions:[".sass",".scss",".css"],restrictions:[/\.((sa|sc|c)ss)$/i],preferRelative:true}));return(e,t,c)=>{if(!r&&!_path.default.isAbsolute(e)){return Promise.reject()}const l=t;const u=l.slice(0,5).toLowerCase()==="file:";if(u){try{t=_url.default.fileURLToPath(l)}catch(e){t=t.slice(7)}}let p=[];const f=!IS_SPECIAL_MODULE_IMPORT.test(t)&&!u&&!l.startsWith("/")&&!IS_NATIVE_WIN32_PATH.test(l);if(s.length>0&&f){const a=getPossibleRequests(t,false,c);if(!r){p=p.concat({resolve:c?o:n,context:_path.default.dirname(e),possibleRequests:a})}p=p.concat(s.map((e=>({resolve:c?o:n,context:e,possibleRequests:a}))))}const d=getPossibleRequests(t,true,c);p=p.concat({resolve:c?i:a,context:_path.default.dirname(e),possibleRequests:d});return startResolving(p)}}const MATCH_CSS=/\.css$/i;function getWebpackImporter(e,t,s){const r=getWebpackResolver(e.getResolve,t,s);return function importer(t,s,n){const{fromImport:o}=this;r(s,t,o).then((t=>{e.addDependency(_path.default.normalize(t));n({file:t.replace(MATCH_CSS,"")})})).catch((()=>{n({file:t})}))}}let nodeSassJobQueue=null;function getRenderFunctionFromSassImplementation(e){const t=e.info.includes("dart-sass");if(t){return e.render.bind(e)}if(nodeSassJobQueue===null){const t=Number(process.env.UV_THREADPOOL_SIZE||4);nodeSassJobQueue=_neoAsync.default.queue(e.render.bind(e),t-1)}return nodeSassJobQueue.push.bind(nodeSassJobQueue)}const ABSOLUTE_SCHEME=/^[A-Za-z0-9+\-.]+:/;function getURLType(e){if(e[0]==="/"){if(e[1]==="/"){return"scheme-relative"}return"path-absolute"}if(IS_NATIVE_WIN32_PATH.test(e)){return"path-absolute"}return ABSOLUTE_SCHEME.test(e)?"absolute":"path-relative"}function normalizeSourceMap(e,t){const s=e;delete s.file;s.sourceRoot="";s.sources=s.sources.map((e=>{const s=getURLType(e);if(s==="path-relative"){return _path.default.resolve(t,_path.default.normalize(e))}return e}));return s}},175:function(e){"use strict";e.exports=require("next/dist/compiled/neo-async")},17:function(e){"use strict";e.exports=require("path")},438:function(e){"use strict";e.exports=require("sass")},310:function(e){"use strict";e.exports=require("url")},921:function(e){"use strict";e.exports=JSON.parse('{"title":"Sass Loader options","type":"object","properties":{"implementation":{"description":"The implementation of the sass to be used.","link":"https://github.com/webpack-contrib/sass-loader#implementation","anyOf":[{"type":"string"},{"type":"object"}]},"sassOptions":{"description":"Options for `node-sass` or `sass` (`Dart Sass`) implementation.","link":"https://github.com/webpack-contrib/sass-loader#sassoptions","anyOf":[{"type":"object","additionalProperties":true},{"instanceof":"Function"}]},"additionalData":{"description":"Prepends/Appends `Sass`/`SCSS` code before the actual entry file.","link":"https://github.com/webpack-contrib/sass-loader#additionaldata","anyOf":[{"type":"string"},{"instanceof":"Function"}]},"sourceMap":{"description":"Enables/Disables generation of source maps.","link":"https://github.com/webpack-contrib/sass-loader#sourcemap","type":"boolean"},"webpackImporter":{"description":"Enables/Disables default `webpack` importer.","link":"https://github.com/webpack-contrib/sass-loader#webpackimporter","type":"boolean"},"warnRuleAsWarning":{"description":"Treats the \'@warn\' rule as a webpack warning.","link":"https://github.com/webpack-contrib/sass-loader#warnruleaswarning","type":"boolean"}},"additionalProperties":false}')}};var __webpack_module_cache__={};function __nccwpck_require__(e){var t=__webpack_module_cache__[e];if(t!==undefined){return t.exports}var s=__webpack_module_cache__[e]={exports:{}};var r=true;try{__webpack_modules__[e](s,s.exports,__nccwpck_require__);r=false}finally{if(r)delete __webpack_module_cache__[e]}return s.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var __webpack_exports__=__nccwpck_require__(601);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/packages/next/src/experimental/testmode/playwright/page-route.ts b/packages/next/src/experimental/testmode/playwright/page-route.ts index 1bd083d03fdbe..9c8bafac21e1f 100644 --- a/packages/next/src/experimental/testmode/playwright/page-route.ts +++ b/packages/next/src/experimental/testmode/playwright/page-route.ts @@ -1,9 +1,13 @@ -import type { Page, Route, Request } from '@playwright/test' +import type { + Page, + Route, + Request as PlaywrightRequest, +} from '@playwright/test' import type { FetchHandler } from './next-worker-fixture' function continueRoute( route: Route, - request: Request, + request: PlaywrightRequest, testHeaders: Record ): Promise { return route.continue({ diff --git a/packages/next/src/export/index.ts b/packages/next/src/export/index.ts index b57f8500b0d7f..650c8437e667b 100644 --- a/packages/next/src/export/index.ts +++ b/packages/next/src/export/index.ts @@ -15,7 +15,8 @@ import '../server/require-hook' import { Worker } from '../lib/worker' import { dirname, join, resolve, sep } from 'path' -import { AmpPageStatus, formatAmpMessages } from '../build/output/index' +import { formatAmpMessages } from '../build/output/index' +import type { AmpPageStatus } from '../build/output/index' import * as Log from '../build/output/log' import createSpinner from '../build/spinner' import { SSG_FALLBACK_EXPORT_ERROR } from '../lib/constants' @@ -36,7 +37,7 @@ import { APP_PATH_ROUTES_MANIFEST, } from '../shared/lib/constants' import loadConfig from '../server/config' -import { ExportPathMap, NextConfigComplete } from '../server/config-shared' +import type { ExportPathMap, NextConfigComplete } from '../server/config-shared' import { eventCliSession } from '../telemetry/events' import { hasNextSupport } from '../telemetry/ci-info' import { Telemetry } from '../telemetry/storage' @@ -45,9 +46,9 @@ import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-pa import { loadEnvConfig } from '@next/env' import { isAPIRoute } from '../lib/is-api-route' import { getPagePath } from '../server/require' -import { Span } from '../trace' -import { FontConfig } from '../server/font-utils' -import { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin' +import type { Span } from '../trace' +import type { FontConfig } from '../server/font-utils' +import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin' import { isAppRouteRoute } from '../lib/is-app-route-route' import { isAppPageRoute } from '../lib/is-app-page-route' import isError from '../lib/is-error' diff --git a/packages/next/src/export/routes/app-page.ts b/packages/next/src/export/routes/app-page.ts index 71a4a9afc60ff..b94b8fd26e417 100644 --- a/packages/next/src/export/routes/app-page.ts +++ b/packages/next/src/export/routes/app-page.ts @@ -3,7 +3,10 @@ import type { RenderOpts } from '../../server/app-render/types' import type { OutgoingHttpHeaders } from 'http' import type { NextParsedUrlQuery } from '../../server/request-meta' -import { MockedRequest, MockedResponse } from '../../server/lib/mock-request' +import type { + MockedRequest, + MockedResponse, +} from '../../server/lib/mock-request' import { RSC, NEXT_URL, diff --git a/packages/next/src/export/routes/app-route.ts b/packages/next/src/export/routes/app-route.ts index 0cfb77748d4e4..c580cea6ce8e1 100644 --- a/packages/next/src/export/routes/app-route.ts +++ b/packages/next/src/export/routes/app-route.ts @@ -12,7 +12,10 @@ import { signalFromNodeResponse, } from '../../server/web/spec-extension/adapters/next-request' import { toNodeOutgoingHttpHeaders } from '../../server/web/utils' -import { MockedRequest, MockedResponse } from '../../server/lib/mock-request' +import type { + MockedRequest, + MockedResponse, +} from '../../server/lib/mock-request' import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error' import { SERVER_DIRECTORY } from '../../shared/lib/constants' import { hasNextSupport } from '../../telemetry/ci-info' diff --git a/packages/next/src/export/routes/pages.ts b/packages/next/src/export/routes/pages.ts index 6c056de3a3547..31b1db6a3e401 100644 --- a/packages/next/src/export/routes/pages.ts +++ b/packages/next/src/export/routes/pages.ts @@ -6,7 +6,10 @@ import type { NextParsedUrlQuery } from '../../server/request-meta' import RenderResult from '../../server/render-result' import { join } from 'path' -import { MockedRequest, MockedResponse } from '../../server/lib/mock-request' +import type { + MockedRequest, + MockedResponse, +} from '../../server/lib/mock-request' import { isInAmpMode } from '../../shared/lib/amp-mode' import { SERVER_PROPS_EXPORT_ERROR } from '../../lib/constants' import { NEXT_DYNAMIC_NO_SSR_CODE } from '../../shared/lib/lazy-dynamic/no-ssr-error' diff --git a/packages/next/src/lib/batcher.ts b/packages/next/src/lib/batcher.ts index 480b70df15f00..66a69be757c4a 100644 --- a/packages/next/src/lib/batcher.ts +++ b/packages/next/src/lib/batcher.ts @@ -2,7 +2,7 @@ // this imported module. import './polyfill-promise-with-resolvers' -import { SchedulerFn } from '../server/lib/schedule-on-next-tick' +import type { SchedulerFn } from '../server/lib/schedule-on-next-tick' type CacheKeyFn = ( key: K diff --git a/packages/next/src/lib/command-args.ts b/packages/next/src/lib/command-args.ts index 00d1e4164e020..6e132025854a3 100644 --- a/packages/next/src/lib/command-args.ts +++ b/packages/next/src/lib/command-args.ts @@ -1,4 +1,4 @@ -import { getValidatedArgs } from './get-validated-args' +import type { getValidatedArgs } from './get-validated-args' export type CliCommand = (args: ReturnType) => void diff --git a/packages/next/src/lib/commands.ts b/packages/next/src/lib/commands.ts index d921a8583cb56..d3f9b292da6ba 100644 --- a/packages/next/src/lib/commands.ts +++ b/packages/next/src/lib/commands.ts @@ -1,4 +1,4 @@ -import { getValidatedArgs } from './get-validated-args' +import type { getValidatedArgs } from './get-validated-args' export type CliCommand = (args: ReturnType) => void diff --git a/packages/next/src/lib/create-client-router-filter.ts b/packages/next/src/lib/create-client-router-filter.ts index dcf0a6a0bd43c..c4a7d08dd7a12 100644 --- a/packages/next/src/lib/create-client-router-filter.ts +++ b/packages/next/src/lib/create-client-router-filter.ts @@ -1,8 +1,8 @@ -import { Token } from 'next/dist/compiled/path-to-regexp' +import type { Token } from 'next/dist/compiled/path-to-regexp' import { BloomFilter } from '../shared/lib/bloom-filter' import { isDynamicRoute } from '../shared/lib/router/utils' import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash' -import { Redirect } from './load-custom-routes' +import type { Redirect } from './load-custom-routes' import { tryToParsePath } from './try-to-parse-path' export function createClientRouterFilter( diff --git a/packages/next/src/lib/eslint/runLintCheck.ts b/packages/next/src/lib/eslint/runLintCheck.ts index 6482f7b10e36a..525dbb24f2893 100644 --- a/packages/next/src/lib/eslint/runLintCheck.ts +++ b/packages/next/src/lib/eslint/runLintCheck.ts @@ -6,7 +6,8 @@ import findUp from 'next/dist/compiled/find-up' import semver from 'next/dist/compiled/semver' import * as CommentJson from 'next/dist/compiled/comment-json' -import { LintResult, formatResults } from './customFormatter' +import { formatResults } from './customFormatter' +import type { LintResult } from './customFormatter' import { writeDefaultConfig } from './writeDefaultConfig' import { hasEslintConfiguration } from './hasEslintConfiguration' import { writeOutputFile } from './writeOutputFile' @@ -17,7 +18,7 @@ import { installDependencies } from '../install-dependencies' import { hasNecessaryDependencies } from '../has-necessary-dependencies' import * as Log from '../../build/output/log' -import { EventLintCheckCompleted } from '../../telemetry/events/build' +import type { EventLintCheckCompleted } from '../../telemetry/events/build' import isError, { getProperError } from '../is-error' import { getPkgManager } from '../helpers/get-pkg-manager' diff --git a/packages/next/src/lib/eslint/writeDefaultConfig.ts b/packages/next/src/lib/eslint/writeDefaultConfig.ts index 53acf19407878..f897ece5d4bb9 100644 --- a/packages/next/src/lib/eslint/writeDefaultConfig.ts +++ b/packages/next/src/lib/eslint/writeDefaultConfig.ts @@ -3,7 +3,7 @@ import { bold, green } from '../picocolors' import os from 'os' import path from 'path' import * as CommentJson from 'next/dist/compiled/comment-json' -import { ConfigAvailable } from './hasEslintConfiguration' +import type { ConfigAvailable } from './hasEslintConfiguration' import * as Log from '../../build/output/log' diff --git a/packages/next/src/lib/generate-interception-routes-rewrites.ts b/packages/next/src/lib/generate-interception-routes-rewrites.ts index c2f96563c6132..85fed64167498 100644 --- a/packages/next/src/lib/generate-interception-routes-rewrites.ts +++ b/packages/next/src/lib/generate-interception-routes-rewrites.ts @@ -5,7 +5,7 @@ import { extractInterceptionRouteInformation, isInterceptionRouteAppPath, } from '../server/future/helpers/interception-routes' -import { Rewrite } from './load-custom-routes' +import type { Rewrite } from './load-custom-routes' // a function that converts normalised paths (e.g. /foo/[bar]/[baz]) to the format expected by pathToRegexp (e.g. /foo/:bar/:baz) function toPathToRegexpPath(path: string): string { diff --git a/packages/next/src/lib/install-dependencies.ts b/packages/next/src/lib/install-dependencies.ts index c1b125bc292a5..ef51f6e048321 100644 --- a/packages/next/src/lib/install-dependencies.ts +++ b/packages/next/src/lib/install-dependencies.ts @@ -1,7 +1,7 @@ import { cyan } from './picocolors' import path from 'path' -import { MissingDependency } from './has-necessary-dependencies' +import type { MissingDependency } from './has-necessary-dependencies' import { getPkgManager } from './helpers/get-pkg-manager' import { install } from './helpers/install' import { getOnline } from './helpers/get-online' diff --git a/packages/next/src/lib/is-edge-runtime.ts b/packages/next/src/lib/is-edge-runtime.ts index 0908e9e7613c4..486f73006d2f5 100644 --- a/packages/next/src/lib/is-edge-runtime.ts +++ b/packages/next/src/lib/is-edge-runtime.ts @@ -1,4 +1,4 @@ -import { ServerRuntime } from '../../types' +import type { ServerRuntime } from '../../types' import { SERVER_RUNTIME } from './constants' export function isEdgeRuntime(value?: string): value is ServerRuntime { diff --git a/packages/next/src/lib/metadata/generate/alternate.tsx b/packages/next/src/lib/metadata/generate/alternate.tsx index 6788d3fbc24aa..8ccc816ba509d 100644 --- a/packages/next/src/lib/metadata/generate/alternate.tsx +++ b/packages/next/src/lib/metadata/generate/alternate.tsx @@ -1,7 +1,7 @@ import type { ResolvedMetadata } from '../types/metadata-interface' import React from 'react' -import { AlternateLinkDescriptor } from '../types/alternative-urls-types' +import type { AlternateLinkDescriptor } from '../types/alternative-urls-types' import { MetaFilter } from './meta' function AlternateLink({ diff --git a/packages/next/src/lib/metadata/metadata.tsx b/packages/next/src/lib/metadata/metadata.tsx index e32ed342dfae3..1f2f7ab7efdea 100644 --- a/packages/next/src/lib/metadata/metadata.tsx +++ b/packages/next/src/lib/metadata/metadata.tsx @@ -18,7 +18,7 @@ import { import { IconsMetadata } from './generate/icons' import { resolveMetadata } from './resolve-metadata' import { MetaFilter } from './generate/meta' -import { ResolvedMetadata } from './types/metadata-interface' +import type { ResolvedMetadata } from './types/metadata-interface' import { createDefaultMetadata } from './default-metadata' import { isNotFoundError } from '../../client/components/not-found' diff --git a/packages/next/src/lib/metadata/resolve-metadata.test.ts b/packages/next/src/lib/metadata/resolve-metadata.test.ts index fff221ac1c872..20feb3ca32d5f 100644 --- a/packages/next/src/lib/metadata/resolve-metadata.test.ts +++ b/packages/next/src/lib/metadata/resolve-metadata.test.ts @@ -1,8 +1,6 @@ -import { - accumulateMetadata as originAccumulateMetadata, - MetadataItems, -} from './resolve-metadata' -import { Metadata } from './types/metadata-interface' +import { accumulateMetadata as originAccumulateMetadata } from './resolve-metadata' +import type { MetadataItems } from './resolve-metadata' +import type { Metadata } from './types/metadata-interface' function accumulateMetadata(metadataItems: MetadataItems) { return originAccumulateMetadata(metadataItems, { diff --git a/packages/next/src/lib/metadata/resolve-metadata.ts b/packages/next/src/lib/metadata/resolve-metadata.ts index 0ec2630dfdee0..e7eed1efa65f7 100644 --- a/packages/next/src/lib/metadata/resolve-metadata.ts +++ b/packages/next/src/lib/metadata/resolve-metadata.ts @@ -9,6 +9,7 @@ import type { Twitter } from './types/twitter-types' import type { OpenGraph } from './types/opengraph-types' import type { ComponentsType } from '../../build/webpack/loaders/next-app-loader' import type { MetadataContext } from './types/resolvers' +import type { LoaderTree } from '../../server/lib/app-dir-module' import { createDefaultMetadata } from './default-metadata' import { resolveOpenGraph, resolveTwitter } from './resolvers/resolve-opengraph' import { resolveTitle } from './resolvers/resolve-title' @@ -17,7 +18,6 @@ import { isClientReference } from '../client-reference' import { getComponentTypeModule, getLayoutOrPageModule, - LoaderTree, } from '../../server/lib/app-dir-module' import { interopDefault } from '../interop-default' import { diff --git a/packages/next/src/lib/metadata/types/metadata-interface.ts b/packages/next/src/lib/metadata/types/metadata-interface.ts index a29c6f47534ea..29450d21c9e42 100644 --- a/packages/next/src/lib/metadata/types/metadata-interface.ts +++ b/packages/next/src/lib/metadata/types/metadata-interface.ts @@ -577,4 +577,4 @@ declare namespace MetadataRoute { export type Manifest = ManifestFile } -export { Metadata, ResolvedMetadata, ResolvingMetadata, MetadataRoute } +export type { Metadata, ResolvedMetadata, ResolvingMetadata, MetadataRoute } diff --git a/packages/next/src/lib/metadata/types/resolvers.ts b/packages/next/src/lib/metadata/types/resolvers.ts index f7feab5115863..994917b068f16 100644 --- a/packages/next/src/lib/metadata/types/resolvers.ts +++ b/packages/next/src/lib/metadata/types/resolvers.ts @@ -1,4 +1,4 @@ -import { Metadata, ResolvedMetadata } from './metadata-interface' +import type { Metadata, ResolvedMetadata } from './metadata-interface' export type FieldResolver = ( T: Metadata[Key] diff --git a/packages/next/src/lib/recursive-copy.ts b/packages/next/src/lib/recursive-copy.ts index df9d163de5d11..68936115c4cd9 100644 --- a/packages/next/src/lib/recursive-copy.ts +++ b/packages/next/src/lib/recursive-copy.ts @@ -1,5 +1,6 @@ import path from 'path' -import { promises, constants, Dirent, Stats } from 'fs' +import type { Dirent, Stats } from 'fs' +import { promises, constants } from 'fs' import { Sema } from 'next/dist/compiled/async-sema' import isError from './is-error' diff --git a/packages/next/src/lib/recursive-delete.ts b/packages/next/src/lib/recursive-delete.ts index 78f3ea4948fc7..9675eee728509 100644 --- a/packages/next/src/lib/recursive-delete.ts +++ b/packages/next/src/lib/recursive-delete.ts @@ -1,4 +1,5 @@ -import { Dirent, promises } from 'fs' +import type { Dirent } from 'fs' +import { promises } from 'fs' import { join, isAbsolute, dirname } from 'path' import isError from './is-error' diff --git a/packages/next/src/lib/turbopack-warning.ts b/packages/next/src/lib/turbopack-warning.ts index 3d0951abab6c3..e55b259dee029 100644 --- a/packages/next/src/lib/turbopack-warning.ts +++ b/packages/next/src/lib/turbopack-warning.ts @@ -1,6 +1,6 @@ import path from 'path' import loadConfig from '../server/config' -import { NextConfig } from '../server/config-shared' +import type { NextConfig } from '../server/config-shared' import { PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants' const supportedTurbopackNextConfigOptions = [ diff --git a/packages/next/src/lib/typescript/missingDependencyError.ts b/packages/next/src/lib/typescript/missingDependencyError.ts index 8cba0a6e7a0d6..d63aedfc7aad8 100644 --- a/packages/next/src/lib/typescript/missingDependencyError.ts +++ b/packages/next/src/lib/typescript/missingDependencyError.ts @@ -1,7 +1,7 @@ import { bold, cyan, red } from '../picocolors' import { getOxfordCommaList } from '../oxford-comma-list' -import { MissingDependency } from '../has-necessary-dependencies' +import type { MissingDependency } from '../has-necessary-dependencies' import { FatalError } from '../fatal-error' import { getPkgManager } from '../helpers/get-pkg-manager' diff --git a/packages/next/src/lib/typescript/writeConfigurationDefaults.ts b/packages/next/src/lib/typescript/writeConfigurationDefaults.ts index 12d90a9caad33..1f10977bddf4a 100644 --- a/packages/next/src/lib/typescript/writeConfigurationDefaults.ts +++ b/packages/next/src/lib/typescript/writeConfigurationDefaults.ts @@ -20,7 +20,7 @@ type DesiredCompilerOptionsShape = { function getDesiredCompilerOptions( ts: typeof import('typescript'), - userTsConfig?: { compilerOptions?: CompilerOptions } + tsOptions?: CompilerOptions ): DesiredCompilerOptionsShape { const o: DesiredCompilerOptionsShape = { // These are suggested values and will be set when not present in the @@ -80,7 +80,7 @@ function getDesiredCompilerOptions( reason: 'to match webpack resolution', }, resolveJsonModule: { value: true, reason: 'to match webpack resolution' }, - ...(userTsConfig?.compilerOptions?.verbatimModuleSyntax === true + ...(tsOptions?.verbatimModuleSyntax === true ? undefined : { isolatedModules: { @@ -139,7 +139,7 @@ export async function writeConfigurationDefaults( isFirstTimeSetup = true } - const desiredCompilerOptions = getDesiredCompilerOptions(ts, userTsConfig) + const desiredCompilerOptions = getDesiredCompilerOptions(ts, tsOptions) const suggestedActions: string[] = [] const requiredActions: string[] = [] diff --git a/packages/next/src/lib/verify-partytown-setup.ts b/packages/next/src/lib/verify-partytown-setup.ts index 0844ec373117e..fb2e439337d7d 100644 --- a/packages/next/src/lib/verify-partytown-setup.ts +++ b/packages/next/src/lib/verify-partytown-setup.ts @@ -2,10 +2,8 @@ import { promises } from 'fs' import { bold, cyan, red } from './picocolors' import path from 'path' -import { - hasNecessaryDependencies, - NecessaryDependencies, -} from './has-necessary-dependencies' +import { hasNecessaryDependencies } from './has-necessary-dependencies' +import type { NecessaryDependencies } from './has-necessary-dependencies' import { fileExists, FileType } from './file-exists' import { FatalError } from './fatal-error' import * as Log from '../build/output/log' diff --git a/packages/next/src/lib/verifyTypeScriptSetup.ts b/packages/next/src/lib/verify-typescript-setup.ts similarity index 96% rename from packages/next/src/lib/verifyTypeScriptSetup.ts rename to packages/next/src/lib/verify-typescript-setup.ts index f6f18ebf3eb31..b84b745531965 100644 --- a/packages/next/src/lib/verifyTypeScriptSetup.ts +++ b/packages/next/src/lib/verify-typescript-setup.ts @@ -1,16 +1,14 @@ import { bold, cyan, red, yellow } from './picocolors' import path from 'path' -import { - hasNecessaryDependencies, - NecessaryDependencies, -} from './has-necessary-dependencies' +import { hasNecessaryDependencies } from './has-necessary-dependencies' +import type { NecessaryDependencies } from './has-necessary-dependencies' import semver from 'next/dist/compiled/semver' import { CompileError } from './compile-error' import * as log from '../build/output/log' import { getTypeScriptIntent } from './typescript/getTypeScriptIntent' -import { TypeCheckResult } from './typescript/runTypeCheck' +import type { TypeCheckResult } from './typescript/runTypeCheck' import { writeAppTypeDeclarations } from './typescript/writeAppTypeDeclarations' import { writeConfigurationDefaults } from './typescript/writeConfigurationDefaults' import { installDependencies } from './install-dependencies' diff --git a/packages/next/src/lib/verifyAndLint.ts b/packages/next/src/lib/verifyAndLint.ts index 6dfbc59fa2b79..ff3e308623203 100644 --- a/packages/next/src/lib/verifyAndLint.ts +++ b/packages/next/src/lib/verifyAndLint.ts @@ -3,7 +3,7 @@ import { Worker } from 'next/dist/compiled/jest-worker' import { existsSync } from 'fs' import { join } from 'path' import { ESLINT_DEFAULT_DIRS } from './constants' -import { Telemetry } from '../telemetry/storage' +import type { Telemetry } from '../telemetry/storage' import { eventLintCheckCompleted } from '../telemetry/events' import { CompileError } from './compile-error' import isError from './is-error' diff --git a/packages/next/src/lib/worker.ts b/packages/next/src/lib/worker.ts index 05f1bf4ccf2cd..67e2c94dc4c09 100644 --- a/packages/next/src/lib/worker.ts +++ b/packages/next/src/lib/worker.ts @@ -1,4 +1,4 @@ -import { ChildProcess } from 'child_process' +import type { ChildProcess } from 'child_process' import { Worker as JestWorker } from 'next/dist/compiled/jest-worker' import { getNodeOptionsWithoutInspect } from '../server/lib/utils' diff --git a/packages/next/src/pages/_app.tsx b/packages/next/src/pages/_app.tsx index 2a064dd1c927a..7573e00cdd239 100644 --- a/packages/next/src/pages/_app.tsx +++ b/packages/next/src/pages/_app.tsx @@ -11,9 +11,9 @@ import type { Router } from '../client/router' import { loadGetInitialProps } from '../shared/lib/utils' -export { AppInitialProps, AppType } +export type { AppInitialProps, AppType } -export { NextWebVitalsMetric } +export type { NextWebVitalsMetric } export type AppContext = AppContextType diff --git a/packages/next/src/pages/_document.tsx b/packages/next/src/pages/_document.tsx index f0a29cb15d1fc..78ea281d96b17 100644 --- a/packages/next/src/pages/_document.tsx +++ b/packages/next/src/pages/_document.tsx @@ -1,4 +1,5 @@ -import React, { ReactElement, ReactNode } from 'react' +import React from 'react' +import type { ReactElement, ReactNode } from 'react' import { OPTIMIZED_FONT_PROVIDERS, NEXT_BUILTIN_DOCUMENT, @@ -13,7 +14,8 @@ import type { import type { ScriptProps } from '../client/script' import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin' -import { BuildManifest, getPageFiles } from '../server/get-page-files' +import { getPageFiles } from '../server/get-page-files' +import type { BuildManifest } from '../server/get-page-files' import { htmlEscapeJsonString } from '../server/htmlescape' import isError from '../lib/is-error' @@ -23,7 +25,7 @@ import { } from '../shared/lib/html-context.shared-runtime' import type { HtmlProps } from '../shared/lib/html-context.shared-runtime' -export { DocumentContext, DocumentInitialProps, DocumentProps } +export type { DocumentContext, DocumentInitialProps, DocumentProps } export type OriginProps = { nonce?: string diff --git a/packages/next/src/server/api-utils/node/api-resolver.ts b/packages/next/src/server/api-utils/node/api-resolver.ts index 529b6a62818be..e638fedaf7a5d 100644 --- a/packages/next/src/server/api-utils/node/api-resolver.ts +++ b/packages/next/src/server/api-utils/node/api-resolver.ts @@ -1,7 +1,7 @@ import type { IncomingMessage, ServerResponse } from 'http' import type { NextApiRequest, NextApiResponse } from '../../../shared/lib/utils' import type { PageConfig, ResponseLimit } from 'next/types' -import { __ApiPreviewProps } from '../.' +import type { __ApiPreviewProps } from '../.' import type { CookieSerializeOptions } from 'next/dist/compiled/cookie' import bytes from 'next/dist/compiled/bytes' diff --git a/packages/next/src/server/api-utils/node/try-get-preview-data.ts b/packages/next/src/server/api-utils/node/try-get-preview-data.ts index bebe98cf4495f..ca81d1379e0bb 100644 --- a/packages/next/src/server/api-utils/node/try-get-preview-data.ts +++ b/packages/next/src/server/api-utils/node/try-get-preview-data.ts @@ -1,6 +1,7 @@ import type { IncomingMessage, ServerResponse } from 'http' import type { NextApiResponse } from '../../../shared/lib/utils' -import { checkIsOnDemandRevalidate, __ApiPreviewProps } from '../.' +import { checkIsOnDemandRevalidate } from '../.' +import type { __ApiPreviewProps } from '../.' import type { BaseNextRequest, BaseNextResponse } from '../../base-http' import type { PreviewData } from 'next/types' diff --git a/packages/next/src/server/app-render/action-handler.ts b/packages/next/src/server/app-render/action-handler.ts index 93d4a62b80fdf..aaa5f5af8b7d0 100644 --- a/packages/next/src/server/app-render/action-handler.ts +++ b/packages/next/src/server/app-render/action-handler.ts @@ -19,10 +19,10 @@ import { isRedirectError, } from '../../client/components/redirect' import RenderResult from '../render-result' -import { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' +import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' import { FlightRenderResult } from './flight-render-result' -import { ActionResult } from './types' -import { ActionAsyncStorage } from '../../client/components/action-async-storage.external' +import type { ActionResult } from './types' +import type { ActionAsyncStorage } from '../../client/components/action-async-storage.external' import { filterReqHeaders, actionsForbiddenHeaders, @@ -32,7 +32,7 @@ import { getModifiedCookieValues, } from '../web/spec-extension/adapters/request-cookies' -import { RequestStore } from '../../client/components/request-async-storage.external' +import type { RequestStore } from '../../client/components/request-async-storage.external' import { NEXT_CACHE_REVALIDATED_TAGS_HEADER, NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER, diff --git a/packages/next/src/server/app-render/app-render.tsx b/packages/next/src/server/app-render/app-render.tsx index fcc5089e693c9..649264ffccb16 100644 --- a/packages/next/src/server/app-render/app-render.tsx +++ b/packages/next/src/server/app-render/app-render.tsx @@ -10,11 +10,13 @@ import type { RenderOpts, Segment, } from './types' +import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external' +import type { RequestStore } from '../../client/components/request-async-storage.external' import React from 'react' import { createServerComponentRenderer } from './create-server-components-renderer' -import { NextParsedUrlQuery } from '../request-meta' +import type { NextParsedUrlQuery } from '../request-meta' import RenderResult, { type RenderResultMetadata } from '../render-result' import { renderToInitialFizzStream, @@ -37,7 +39,8 @@ import { createMetadataComponents } from '../../lib/metadata/metadata' import { RequestAsyncStorageWrapper } from '../async-storage/request-async-storage-wrapper' import { StaticGenerationAsyncStorageWrapper } from '../async-storage/static-generation-async-storage-wrapper' import { isClientReference } from '../../lib/client-reference' -import { getLayoutOrPageModule, LoaderTree } from '../lib/app-dir-module' +import { getLayoutOrPageModule } from '../lib/app-dir-module' +import type { LoaderTree } from '../lib/app-dir-module' import { isNotFoundError } from '../../client/components/not-found' import { getURLFromRedirectError, @@ -151,24 +154,21 @@ function hasLoadingComponentInTree(tree: LoaderTree): boolean { ) as boolean } -export type AppPageRender = ( +type AppRenderContext = { + staticGenerationStore: StaticGenerationStore + requestStore: RequestStore +} + +const wrappedRender = async ( req: IncomingMessage, res: ServerResponse, pagePath: string, query: NextParsedUrlQuery, - renderOpts: RenderOpts -) => Promise - -export const renderToHTMLOrFlight: AppPageRender = ( - req, - res, - pagePath, - query, - renderOpts + renderOpts: RenderOpts, + ctx: AppRenderContext ) => { const isFlight = req.headers[RSC.toLowerCase()] !== undefined const isNotFoundPath = pagePath === '/404' - const pathname = validateURL(req.url) // A unique request timestamp used by development to ensure that it's // consistent and won't change during this request. This is important to @@ -189,6 +189,7 @@ export const renderToHTMLOrFlight: AppPageRender = ( buildId, deploymentId, appDirDevErrorLogger, + assetPrefix = '', } = renderOpts // We need to expose the bundled `require` API globally for @@ -205,6 +206,7 @@ export const renderToHTMLOrFlight: AppPageRender = ( const appUsingSizeAdjust = !!nextFontManifest?.appUsingSizeAdjust + // TODO: fix this typescript const clientReferenceManifest = renderOpts.clientReferenceManifest! const capturedErrors: Error[] = [] @@ -252,8 +254,6 @@ export const renderToHTMLOrFlight: AppPageRender = ( // Pull out the hooks/references from the component. const { - staticGenerationAsyncStorage, - requestAsyncStorage, staticGenerationBailout, LayoutRouter, RenderFromTemplateContext, @@ -270,626 +270,598 @@ export const renderToHTMLOrFlight: AppPageRender = ( preloadStyle, } = ComponentMod - // we wrap the render in an AsyncLocalStorage context - const wrappedRender = async () => { - const staticGenerationStore = staticGenerationAsyncStorage.getStore() - if (!staticGenerationStore) { - throw new Error( - `Invariant: Render expects to have staticGenerationAsyncStorage, none found` - ) - } - - staticGenerationStore.fetchMetrics = [] - extraRenderResultMeta.fetchMetrics = staticGenerationStore.fetchMetrics + const { staticGenerationStore, requestStore } = ctx + const { urlPathname } = staticGenerationStore - const requestStore = requestAsyncStorage.getStore() - if (!requestStore) { - throw new Error( - `Invariant: Render expects to have requestAsyncStorage, none found` - ) - } + staticGenerationStore.fetchMetrics = [] + extraRenderResultMeta.fetchMetrics = staticGenerationStore.fetchMetrics - // don't modify original query object - query = { ...query } - stripInternalQueries(query) + // don't modify original query object + query = { ...query } + stripInternalQueries(query) - const isPrefetch = - req.headers[NEXT_ROUTER_PREFETCH.toLowerCase()] !== undefined + const isPrefetch = + req.headers[NEXT_ROUTER_PREFETCH.toLowerCase()] !== undefined - /** - * Router state provided from the client-side router. Used to handle rendering from the common layout down. - */ - let providedFlightRouterState = isFlight - ? parseAndValidateFlightRouterState( - req.headers[NEXT_ROUTER_STATE_TREE.toLowerCase()] - ) - : undefined + /** + * Router state provided from the client-side router. Used to handle rendering from the common layout down. + */ + let providedFlightRouterState = isFlight + ? parseAndValidateFlightRouterState( + req.headers[NEXT_ROUTER_STATE_TREE.toLowerCase()] + ) + : undefined - /** - * The metadata items array created in next-app-loader with all relevant information - * that we need to resolve the final metadata. - */ + /** + * The metadata items array created in next-app-loader with all relevant information + * that we need to resolve the final metadata. + */ - let requestId: string + let requestId: string - if (process.env.NEXT_RUNTIME === 'edge') { - requestId = crypto.randomUUID() - } else { - requestId = require('next/dist/compiled/nanoid').nanoid() - } + if (process.env.NEXT_RUNTIME === 'edge') { + requestId = crypto.randomUUID() + } else { + requestId = require('next/dist/compiled/nanoid').nanoid() + } - const isStaticGeneration = staticGenerationStore.isStaticGeneration - // During static generation we need to call the static generation bailout when reading searchParams - const providedSearchParams = isStaticGeneration - ? createSearchParamsBailoutProxy() - : query - const searchParamsProps = { searchParams: providedSearchParams } + const isStaticGeneration = staticGenerationStore.isStaticGeneration + // During static generation we need to call the static generation bailout when reading searchParams + const providedSearchParams = isStaticGeneration + ? createSearchParamsBailoutProxy() + : query + const searchParamsProps = { searchParams: providedSearchParams } - /** - * Server Context is specifically only available in Server Components. - * It has to hold values that can't change while rendering from the common layout down. - * An example of this would be that `headers` are available but `searchParams` are not because that'd mean we have to render from the root layout down on all requests. - */ + /** + * Server Context is specifically only available in Server Components. + * It has to hold values that can't change while rendering from the common layout down. + * An example of this would be that `headers` are available but `searchParams` are not because that'd mean we have to render from the root layout down on all requests. + */ - const serverContexts: Array<[string, any]> = [ - ['WORKAROUND', null], // TODO-APP: First value has a bug currently where the value is not set on the second request: https://github.com/facebook/react/issues/24849 - ] + const serverContexts: Array<[string, any]> = [ + ['WORKAROUND', null], // TODO-APP: First value has a bug currently where the value is not set on the second request: https://github.com/facebook/react/issues/24849 + ] - type CreateSegmentPath = (child: FlightSegmentPath) => FlightSegmentPath + type CreateSegmentPath = (child: FlightSegmentPath) => FlightSegmentPath - /** - * Dynamic parameters. E.g. when you visit `/dashboard/vercel` which is rendered by `/dashboard/[slug]` the value will be {"slug": "vercel"}. - */ - const params = renderOpts.params ?? {} + /** + * Dynamic parameters. E.g. when you visit `/dashboard/vercel` which is rendered by `/dashboard/[slug]` the value will be {"slug": "vercel"}. + */ + const params = renderOpts.params ?? {} - /** - * Parse the dynamic segment and return the associated value. - */ - const getDynamicParamFromSegment: GetDynamicParamFromSegment = ( - // [slug] / [[slug]] / [...slug] - segment: string - ) => { - const segmentParam = getSegmentParam(segment) - if (!segmentParam) { - return null - } + /** + * Parse the dynamic segment and return the associated value. + */ + const getDynamicParamFromSegment: GetDynamicParamFromSegment = ( + // [slug] / [[slug]] / [...slug] + segment: string + ) => { + const segmentParam = getSegmentParam(segment) + if (!segmentParam) { + return null + } - const key = segmentParam.param + const key = segmentParam.param - let value = params[key] + let value = params[key] - // this is a special marker that will be present for interception routes - if (value === '__NEXT_EMPTY_PARAM__') { - value = undefined - } + // this is a special marker that will be present for interception routes + if (value === '__NEXT_EMPTY_PARAM__') { + value = undefined + } - if (Array.isArray(value)) { - value = value.map((i) => encodeURIComponent(i)) - } else if (typeof value === 'string') { - value = encodeURIComponent(value) - } + if (Array.isArray(value)) { + value = value.map((i) => encodeURIComponent(i)) + } else if (typeof value === 'string') { + value = encodeURIComponent(value) + } - if (!value) { - // Handle case where optional catchall does not have a value, e.g. `/dashboard/[...slug]` when requesting `/dashboard` - if (segmentParam.type === 'optional-catchall') { - const type = dynamicParamTypes[segmentParam.type] - return { - param: key, - value: null, - type: type, - // This value always has to be a string. - treeSegment: [key, '', type], - } + if (!value) { + // Handle case where optional catchall does not have a value, e.g. `/dashboard/[...slug]` when requesting `/dashboard` + if (segmentParam.type === 'optional-catchall') { + const type = dynamicParamTypes[segmentParam.type] + return { + param: key, + value: null, + type: type, + // This value always has to be a string. + treeSegment: [key, '', type], } - return findDynamicParamFromRouterState( - providedFlightRouterState, - segment - ) } + return findDynamicParamFromRouterState(providedFlightRouterState, segment) + } - const type = getShortDynamicParamType(segmentParam.type) + const type = getShortDynamicParamType(segmentParam.type) - return { - param: key, - // The value that is passed to user code. - value: value, - // The value that is rendered in the router tree. - treeSegment: [ - key, - Array.isArray(value) ? value.join('/') : value, - type, - ], - type: type, - } + return { + param: key, + // The value that is passed to user code. + value: value, + // The value that is rendered in the router tree. + treeSegment: [key, Array.isArray(value) ? value.join('/') : value, type], + type: type, } + } - let defaultRevalidate: false | undefined | number = false - - const assetPrefix = renderOpts.assetPrefix || '' + let defaultRevalidate: false | undefined | number = false - const getAssetQueryString = (addTimestamp: boolean) => { - const isDev = process.env.NODE_ENV === 'development' - let qs = '' + const getAssetQueryString = (addTimestamp: boolean) => { + const isDev = process.env.NODE_ENV === 'development' + let qs = '' - if (isDev && addTimestamp) { - qs += `?v=${DEV_REQUEST_TS}` - } + if (isDev && addTimestamp) { + qs += `?v=${DEV_REQUEST_TS}` + } - if (deploymentId) { - qs += `${isDev ? '&' : '?'}dpl=${deploymentId}` - } - return qs + if (deploymentId) { + qs += `${isDev ? '&' : '?'}dpl=${deploymentId}` } + return qs + } - const createComponentAndStyles = async ({ + const createComponentAndStyles = async ({ + filePath, + getComponent, + injectedCSS, + }: { + filePath: string + getComponent: () => any + injectedCSS: Set + }): Promise => { + const cssHrefs = getCssInlinedLinkTags( + clientReferenceManifest, filePath, - getComponent, - injectedCSS, - }: { - filePath: string - getComponent: () => any - injectedCSS: Set - }): Promise => { - const cssHrefs = getCssInlinedLinkTags( - clientReferenceManifest, - filePath, - injectedCSS - ) + injectedCSS + ) - const styles = cssHrefs - ? cssHrefs.map((href, index) => { - // In dev, Safari and Firefox will cache the resource during HMR: - // - https://github.com/vercel/next.js/issues/5860 - // - https://bugs.webkit.org/show_bug.cgi?id=187726 - // Because of this, we add a `?v=` query to bypass the cache during - // development. We need to also make sure that the number is always - // increasing. - const fullHref = `${assetPrefix}/_next/${href}${getAssetQueryString( - true - )}` - - // `Precedence` is an opt-in signal for React to handle resource - // loading and deduplication, etc. It's also used as the key to sort - // resources so they will be injected in the correct order. - // During HMR, it's critical to use different `precedence` values - // for different stylesheets, so their order will be kept. - // https://github.com/facebook/react/pull/25060 - const precedence = - process.env.NODE_ENV === 'development' ? 'next_' + href : 'next' + const styles = cssHrefs + ? cssHrefs.map((href, index) => { + // In dev, Safari and Firefox will cache the resource during HMR: + // - https://github.com/vercel/next.js/issues/5860 + // - https://bugs.webkit.org/show_bug.cgi?id=187726 + // Because of this, we add a `?v=` query to bypass the cache during + // development. We need to also make sure that the number is always + // increasing. + const fullHref = `${assetPrefix}/_next/${href}${getAssetQueryString( + true + )}` - return ( - - ) - }) - : null + // `Precedence` is an opt-in signal for React to handle resource + // loading and deduplication, etc. It's also used as the key to sort + // resources so they will be injected in the correct order. + // During HMR, it's critical to use different `precedence` values + // for different stylesheets, so their order will be kept. + // https://github.com/facebook/react/pull/25060 + const precedence = + process.env.NODE_ENV === 'development' ? 'next_' + href : 'next' - const Comp = interopDefault(await getComponent()) + return ( + + ) + }) + : null - return [Comp, styles] - } + const Comp = interopDefault(await getComponent()) - const getLayerAssets = ({ - layoutOrPagePath, - injectedCSS: injectedCSSWithCurrentLayout, - injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout, - }: { - layoutOrPagePath: string | undefined - injectedCSS: Set - injectedFontPreloadTags: Set - }): React.ReactNode => { - const stylesheets: string[] = layoutOrPagePath - ? getCssInlinedLinkTags( - clientReferenceManifest, - layoutOrPagePath, - injectedCSSWithCurrentLayout, - true - ) - : [] + return [Comp, styles] + } - const preloadedFontFiles = layoutOrPagePath - ? getPreloadableFonts( - nextFontManifest, - layoutOrPagePath, - injectedFontPreloadTagsWithCurrentLayout - ) - : null - - if (preloadedFontFiles) { - if (preloadedFontFiles.length) { - for (let i = 0; i < preloadedFontFiles.length; i++) { - const fontFilename = preloadedFontFiles[i] - const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(fontFilename)![1] - const type = `font/${ext}` - const href = `${assetPrefix}/_next/${fontFilename}` - preloadFont(href, type, renderOpts.crossOrigin) - } - } else { - try { - let url = new URL(assetPrefix) - preconnect(url.origin, 'anonymous') - } catch (error) { - // assetPrefix must not be a fully qualified domain name. We assume - // we should preconnect to same origin instead - preconnect('/', 'anonymous') - } + const getLayerAssets = ({ + layoutOrPagePath, + injectedCSS: injectedCSSWithCurrentLayout, + injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout, + }: { + layoutOrPagePath: string | undefined + injectedCSS: Set + injectedFontPreloadTags: Set + }): React.ReactNode => { + const stylesheets: string[] = layoutOrPagePath + ? getCssInlinedLinkTags( + clientReferenceManifest, + layoutOrPagePath, + injectedCSSWithCurrentLayout, + true + ) + : [] + + const preloadedFontFiles = layoutOrPagePath + ? getPreloadableFonts( + nextFontManifest, + layoutOrPagePath, + injectedFontPreloadTagsWithCurrentLayout + ) + : null + + if (preloadedFontFiles) { + if (preloadedFontFiles.length) { + for (let i = 0; i < preloadedFontFiles.length; i++) { + const fontFilename = preloadedFontFiles[i] + const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(fontFilename)![1] + const type = `font/${ext}` + const href = `${assetPrefix}/_next/${fontFilename}` + preloadFont(href, type, renderOpts.crossOrigin) + } + } else { + try { + let url = new URL(assetPrefix) + preconnect(url.origin, 'anonymous') + } catch (error) { + // assetPrefix must not be a fully qualified domain name. We assume + // we should preconnect to same origin instead + preconnect('/', 'anonymous') } } + } - const styles = stylesheets - ? stylesheets.map((href, index) => { - // In dev, Safari and Firefox will cache the resource during HMR: - // - https://github.com/vercel/next.js/issues/5860 - // - https://bugs.webkit.org/show_bug.cgi?id=187726 - // Because of this, we add a `?v=` query to bypass the cache during - // development. We need to also make sure that the number is always - // increasing. - const fullHref = `${assetPrefix}/_next/${href}${getAssetQueryString( - true - )}` - - // `Precedence` is an opt-in signal for React to handle resource - // loading and deduplication, etc. It's also used as the key to sort - // resources so they will be injected in the correct order. - // During HMR, it's critical to use different `precedence` values - // for different stylesheets, so their order will be kept. - // https://github.com/facebook/react/pull/25060 - const precedence = - process.env.NODE_ENV === 'development' ? 'next_' + href : 'next' - - preloadStyle(fullHref, renderOpts.crossOrigin) + const styles = stylesheets + ? stylesheets.map((href, index) => { + // In dev, Safari and Firefox will cache the resource during HMR: + // - https://github.com/vercel/next.js/issues/5860 + // - https://bugs.webkit.org/show_bug.cgi?id=187726 + // Because of this, we add a `?v=` query to bypass the cache during + // development. We need to also make sure that the number is always + // increasing. + const fullHref = `${assetPrefix}/_next/${href}${getAssetQueryString( + true + )}` - return ( - - ) - }) - : null + // `Precedence` is an opt-in signal for React to handle resource + // loading and deduplication, etc. It's also used as the key to sort + // resources so they will be injected in the correct order. + // During HMR, it's critical to use different `precedence` values + // for different stylesheets, so their order will be kept. + // https://github.com/facebook/react/pull/25060 + const precedence = + process.env.NODE_ENV === 'development' ? 'next_' + href : 'next' - return styles - } + preloadStyle(fullHref, renderOpts.crossOrigin) - const parseLoaderTree = (tree: LoaderTree) => { - const [segment, parallelRoutes, components] = tree - const { layout } = components - let { page } = components - // a __DEFAULT__ segment means that this route didn't match any of the - // segments in the route, so we should use the default page + return ( + + ) + }) + : null - page = segment === '__DEFAULT__' ? components.defaultPage : page + return styles + } - const layoutOrPagePath = layout?.[1] || page?.[1] + const parseLoaderTree = (tree: LoaderTree) => { + const [segment, parallelRoutes, components] = tree + const { layout } = components + let { page } = components + // a __DEFAULT__ segment means that this route didn't match any of the + // segments in the route, so we should use the default page - return { - page, - segment, - components, - layoutOrPagePath, - parallelRoutes, - } - } + page = segment === '__DEFAULT__' ? components.defaultPage : page - /** - * Use the provided loader tree to create the React Component tree. - */ - const createComponentTree = async ({ - createSegmentPath, - loaderTree: tree, - parentParams, - firstItem, - rootLayoutIncluded, - injectedCSS, - injectedFontPreloadTags, - asNotFound, - metadataOutlet, - }: { - createSegmentPath: CreateSegmentPath - loaderTree: LoaderTree - parentParams: { [key: string]: any } - rootLayoutIncluded: boolean - firstItem?: boolean - injectedCSS: Set - injectedFontPreloadTags: Set - asNotFound?: boolean - metadataOutlet?: React.ReactNode - }): Promise<{ - Component: React.ComponentType - styles: React.ReactNode - }> => { - const { page, layoutOrPagePath, segment, components, parallelRoutes } = - parseLoaderTree(tree) - - const { - layout, - template, - error, - loading, - 'not-found': notFound, - } = components + const layoutOrPagePath = layout?.[1] || page?.[1] - const injectedCSSWithCurrentLayout = new Set(injectedCSS) - const injectedFontPreloadTagsWithCurrentLayout = new Set( - injectedFontPreloadTags - ) + return { + page, + segment, + components, + layoutOrPagePath, + parallelRoutes, + } + } - const styles = getLayerAssets({ - layoutOrPagePath, - injectedCSS: injectedCSSWithCurrentLayout, - injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout, - }) + /** + * Use the provided loader tree to create the React Component tree. + */ + const createComponentTree = async ({ + createSegmentPath, + loaderTree: tree, + parentParams, + firstItem, + rootLayoutIncluded, + injectedCSS, + injectedFontPreloadTags, + asNotFound, + metadataOutlet, + }: { + createSegmentPath: CreateSegmentPath + loaderTree: LoaderTree + parentParams: { [key: string]: any } + rootLayoutIncluded: boolean + firstItem?: boolean + injectedCSS: Set + injectedFontPreloadTags: Set + asNotFound?: boolean + metadataOutlet?: React.ReactNode + }): Promise<{ + Component: React.ComponentType + styles: React.ReactNode + }> => { + const { page, layoutOrPagePath, segment, components, parallelRoutes } = + parseLoaderTree(tree) + + const { + layout, + template, + error, + loading, + 'not-found': notFound, + } = components + + const injectedCSSWithCurrentLayout = new Set(injectedCSS) + const injectedFontPreloadTagsWithCurrentLayout = new Set( + injectedFontPreloadTags + ) - const [Template, templateStyles] = template - ? await createComponentAndStyles({ - filePath: template[1], - getComponent: template[0], - injectedCSS: injectedCSSWithCurrentLayout, - }) - : [React.Fragment] + const styles = getLayerAssets({ + layoutOrPagePath, + injectedCSS: injectedCSSWithCurrentLayout, + injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout, + }) - const [ErrorComponent, errorStyles] = error - ? await createComponentAndStyles({ - filePath: error[1], - getComponent: error[0], - injectedCSS: injectedCSSWithCurrentLayout, - }) - : [] + const [Template, templateStyles] = template + ? await createComponentAndStyles({ + filePath: template[1], + getComponent: template[0], + injectedCSS: injectedCSSWithCurrentLayout, + }) + : [React.Fragment] - const [Loading, loadingStyles] = loading - ? await createComponentAndStyles({ - filePath: loading[1], - getComponent: loading[0], - injectedCSS: injectedCSSWithCurrentLayout, - }) - : [] + const [ErrorComponent, errorStyles] = error + ? await createComponentAndStyles({ + filePath: error[1], + getComponent: error[0], + injectedCSS: injectedCSSWithCurrentLayout, + }) + : [] - const isLayout = typeof layout !== 'undefined' - const isPage = typeof page !== 'undefined' - const [layoutOrPageMod] = await getLayoutOrPageModule(tree) + const [Loading, loadingStyles] = loading + ? await createComponentAndStyles({ + filePath: loading[1], + getComponent: loading[0], + injectedCSS: injectedCSSWithCurrentLayout, + }) + : [] - /** - * Checks if the current segment is a root layout. - */ - const rootLayoutAtThisLevel = isLayout && !rootLayoutIncluded - /** - * Checks if the current segment or any level above it has a root layout. - */ - const rootLayoutIncludedAtThisLevelOrAbove = - rootLayoutIncluded || rootLayoutAtThisLevel + const isLayout = typeof layout !== 'undefined' + const isPage = typeof page !== 'undefined' + const [layoutOrPageMod] = await getLayoutOrPageModule(tree) - const [NotFound, notFoundStyles] = notFound - ? await createComponentAndStyles({ - filePath: notFound[1], - getComponent: notFound[0], - injectedCSS: injectedCSSWithCurrentLayout, - }) - : [] - - let dynamic = layoutOrPageMod?.dynamic - - if (nextConfigOutput === 'export') { - if (!dynamic || dynamic === 'auto') { - dynamic = 'error' - } else if (dynamic === 'force-dynamic') { - staticGenerationStore.forceDynamic = true - staticGenerationStore.dynamicShouldError = true - staticGenerationBailout(`output: export`, { - dynamic, - link: 'https://nextjs.org/docs/advanced-features/static-html-export', - }) - } + /** + * Checks if the current segment is a root layout. + */ + const rootLayoutAtThisLevel = isLayout && !rootLayoutIncluded + /** + * Checks if the current segment or any level above it has a root layout. + */ + const rootLayoutIncludedAtThisLevelOrAbove = + rootLayoutIncluded || rootLayoutAtThisLevel + + const [NotFound, notFoundStyles] = notFound + ? await createComponentAndStyles({ + filePath: notFound[1], + getComponent: notFound[0], + injectedCSS: injectedCSSWithCurrentLayout, + }) + : [] + + let dynamic = layoutOrPageMod?.dynamic + + if (nextConfigOutput === 'export') { + if (!dynamic || dynamic === 'auto') { + dynamic = 'error' + } else if (dynamic === 'force-dynamic') { + staticGenerationStore.forceDynamic = true + staticGenerationStore.dynamicShouldError = true + staticGenerationBailout(`output: export`, { + dynamic, + link: 'https://nextjs.org/docs/advanced-features/static-html-export', + }) } + } - if (typeof dynamic === 'string') { - // the nested most config wins so we only force-static - // if it's configured above any parent that configured - // otherwise - if (dynamic === 'error') { - staticGenerationStore.dynamicShouldError = true - } else if (dynamic === 'force-dynamic') { - staticGenerationStore.forceDynamic = true - staticGenerationBailout(`force-dynamic`, { dynamic }) + if (typeof dynamic === 'string') { + // the nested most config wins so we only force-static + // if it's configured above any parent that configured + // otherwise + if (dynamic === 'error') { + staticGenerationStore.dynamicShouldError = true + } else if (dynamic === 'force-dynamic') { + staticGenerationStore.forceDynamic = true + staticGenerationBailout(`force-dynamic`, { dynamic }) + } else { + staticGenerationStore.dynamicShouldError = false + if (dynamic === 'force-static') { + staticGenerationStore.forceStatic = true } else { - staticGenerationStore.dynamicShouldError = false - if (dynamic === 'force-static') { - staticGenerationStore.forceStatic = true - } else { - staticGenerationStore.forceStatic = false - } + staticGenerationStore.forceStatic = false } } + } - if (typeof layoutOrPageMod?.fetchCache === 'string') { - staticGenerationStore.fetchCache = layoutOrPageMod?.fetchCache - } + if (typeof layoutOrPageMod?.fetchCache === 'string') { + staticGenerationStore.fetchCache = layoutOrPageMod?.fetchCache + } - if (typeof layoutOrPageMod?.revalidate === 'number') { - defaultRevalidate = layoutOrPageMod.revalidate as number + if (typeof layoutOrPageMod?.revalidate === 'number') { + defaultRevalidate = layoutOrPageMod.revalidate as number - if ( - typeof staticGenerationStore.revalidate === 'undefined' || - (typeof staticGenerationStore.revalidate === 'number' && - staticGenerationStore.revalidate > defaultRevalidate) - ) { - staticGenerationStore.revalidate = defaultRevalidate - } + if ( + typeof staticGenerationStore.revalidate === 'undefined' || + (typeof staticGenerationStore.revalidate === 'number' && + staticGenerationStore.revalidate > defaultRevalidate) + ) { + staticGenerationStore.revalidate = defaultRevalidate + } - if ( - staticGenerationStore.isStaticGeneration && - defaultRevalidate === 0 - ) { - const dynamicUsageDescription = `revalidate: 0 configured ${segment}` - staticGenerationStore.dynamicUsageDescription = - dynamicUsageDescription + if (staticGenerationStore.isStaticGeneration && defaultRevalidate === 0) { + const dynamicUsageDescription = `revalidate: 0 configured ${segment}` + staticGenerationStore.dynamicUsageDescription = dynamicUsageDescription - throw new DynamicServerError(dynamicUsageDescription) - } + throw new DynamicServerError(dynamicUsageDescription) } + } - if (staticGenerationStore?.dynamicUsageErr) { - throw staticGenerationStore.dynamicUsageErr - } + if (staticGenerationStore?.dynamicUsageErr) { + throw staticGenerationStore.dynamicUsageErr + } - const LayoutOrPage = layoutOrPageMod - ? interopDefault(layoutOrPageMod) - : undefined + const LayoutOrPage = layoutOrPageMod + ? interopDefault(layoutOrPageMod) + : undefined - /** - * The React Component to render. - */ - let Component = LayoutOrPage - const parallelKeys = Object.keys(parallelRoutes) - const hasSlotKey = parallelKeys.length > 1 - - if (hasSlotKey && rootLayoutAtThisLevel) { - Component = (componentProps: any) => { - const NotFoundComponent = NotFound - const RootLayoutComponent = LayoutOrPage - return ( - - {styles} - - {notFoundStyles} - - - - } - > - - - ) - } + /** + * The React Component to render. + */ + let Component = LayoutOrPage + const parallelKeys = Object.keys(parallelRoutes) + const hasSlotKey = parallelKeys.length > 1 + + if (hasSlotKey && rootLayoutAtThisLevel) { + Component = (componentProps: any) => { + const NotFoundComponent = NotFound + const RootLayoutComponent = LayoutOrPage + return ( + + {styles} + + {notFoundStyles} + + + + } + > + + + ) } + } - if (dev) { - const { isValidElementType } = require('next/dist/compiled/react-is') - if ( - (isPage || typeof Component !== 'undefined') && - !isValidElementType(Component) - ) { - throw new Error( - `The default export is not a React Component in page: "${pagePath}"` - ) - } - - if ( - typeof ErrorComponent !== 'undefined' && - !isValidElementType(ErrorComponent) - ) { - throw new Error( - `The default export of error is not a React Component in page: ${segment}` - ) - } - - if (typeof Loading !== 'undefined' && !isValidElementType(Loading)) { - throw new Error( - `The default export of loading is not a React Component in ${segment}` - ) - } + if (dev) { + const { isValidElementType } = require('next/dist/compiled/react-is') + if ( + (isPage || typeof Component !== 'undefined') && + !isValidElementType(Component) + ) { + throw new Error( + `The default export is not a React Component in page: "${pagePath}"` + ) + } - if (typeof NotFound !== 'undefined' && !isValidElementType(NotFound)) { - throw new Error( - `The default export of notFound is not a React Component in ${segment}` - ) - } + if ( + typeof ErrorComponent !== 'undefined' && + !isValidElementType(ErrorComponent) + ) { + throw new Error( + `The default export of error is not a React Component in page: ${segment}` + ) } - // Handle dynamic segment params. - const segmentParam = getDynamicParamFromSegment(segment) - /** - * Create object holding the parent params and current params - */ - const currentParams = - // Handle null case where dynamic param is optional - segmentParam && segmentParam.value !== null - ? { - ...parentParams, - [segmentParam.param]: segmentParam.value, - } - : // Pass through parent params to children - parentParams - // Resolve the segment param - const actualSegment = segmentParam ? segmentParam.treeSegment : segment - - // This happens outside of rendering in order to eagerly kick off data fetching for layouts / the page further down - const parallelRouteMap = await Promise.all( - Object.keys(parallelRoutes).map( - async (parallelRouteKey): Promise<[string, React.ReactNode]> => { - const isChildrenRouteKey = parallelRouteKey === 'children' - const currentSegmentPath: FlightSegmentPath = firstItem - ? [parallelRouteKey] - : [actualSegment, parallelRouteKey] + if (typeof Loading !== 'undefined' && !isValidElementType(Loading)) { + throw new Error( + `The default export of loading is not a React Component in ${segment}` + ) + } - const parallelRoute = parallelRoutes[parallelRouteKey] + if (typeof NotFound !== 'undefined' && !isValidElementType(NotFound)) { + throw new Error( + `The default export of notFound is not a React Component in ${segment}` + ) + } + } - const childSegment = parallelRoute[0] - const childSegmentParam = getDynamicParamFromSegment(childSegment) - const notFoundComponent = - NotFound && isChildrenRouteKey ? : undefined - - function getParallelRoutePair( - currentChildProp: ChildProp, - currentStyles: React.ReactNode - ): [string, React.ReactNode] { - // This is turned back into an object below. - return [ - parallelRouteKey, - : undefined} - loadingStyles={loadingStyles} - // TODO-APP: Add test for loading returning `undefined`. This currently can't be tested as the `webdriver()` tab will wait for the full page to load before returning. - hasLoading={Boolean(Loading)} - error={ErrorComponent} - errorStyles={errorStyles} - template={ - - } - templateStyles={templateStyles} - notFound={notFoundComponent} - notFoundStyles={notFoundStyles} - childProp={currentChildProp} - styles={currentStyles} - />, - ] - } + // Handle dynamic segment params. + const segmentParam = getDynamicParamFromSegment(segment) + /** + * Create object holding the parent params and current params + */ + const currentParams = + // Handle null case where dynamic param is optional + segmentParam && segmentParam.value !== null + ? { + ...parentParams, + [segmentParam.param]: segmentParam.value, + } + : // Pass through parent params to children + parentParams + // Resolve the segment param + const actualSegment = segmentParam ? segmentParam.treeSegment : segment + + // This happens outside of rendering in order to eagerly kick off data fetching for layouts / the page further down + const parallelRouteMap = await Promise.all( + Object.keys(parallelRoutes).map( + async (parallelRouteKey): Promise<[string, React.ReactNode]> => { + const isChildrenRouteKey = parallelRouteKey === 'children' + const currentSegmentPath: FlightSegmentPath = firstItem + ? [parallelRouteKey] + : [actualSegment, parallelRouteKey] + + const parallelRoute = parallelRoutes[parallelRouteKey] + + const childSegment = parallelRoute[0] + const childSegmentParam = getDynamicParamFromSegment(childSegment) + const notFoundComponent = + NotFound && isChildrenRouteKey ? : undefined + + function getParallelRoutePair( + currentChildProp: ChildProp, + currentStyles: React.ReactNode + ): [string, React.ReactNode] { + // This is turned back into an object below. + return [ + parallelRouteKey, + : undefined} + loadingStyles={loadingStyles} + // TODO-APP: Add test for loading returning `undefined`. This currently can't be tested as the `webdriver()` tab will wait for the full page to load before returning. + hasLoading={Boolean(Loading)} + error={ErrorComponent} + errorStyles={errorStyles} + template={ + + } + templateStyles={templateStyles} + notFound={notFoundComponent} + notFoundStyles={notFoundStyles} + childProp={currentChildProp} + styles={currentStyles} + />, + ] + } - // if we're prefetching and that there's a Loading component, we bail out - // otherwise we keep rendering for the prefetch. - // We also want to bail out if there's no Loading component in the tree. - let currentStyles = undefined - let childElement = null - const childPropSegment = addSearchParamsIfPageSegment( - childSegmentParam ? childSegmentParam.treeSegment : childSegment, - query + // if we're prefetching and that there's a Loading component, we bail out + // otherwise we keep rendering for the prefetch. + // We also want to bail out if there's no Loading component in the tree. + let currentStyles = undefined + let childElement = null + const childPropSegment = addSearchParamsIfPageSegment( + childSegmentParam ? childSegmentParam.treeSegment : childSegment, + query + ) + if ( + !( + isPrefetch && + (Loading || !hasLoadingComponentInTree(parallelRoute)) ) - if ( - !( - isPrefetch && - (Loading || !hasLoadingComponentInTree(parallelRoute)) - ) - ) { - // Create the child component - const { - Component: ChildComponent, - styles: childComponentStyles, - } = await createComponentTree({ + ) { + // Create the child component + const { Component: ChildComponent, styles: childComponentStyles } = + await createComponentTree({ createSegmentPath: (child) => { return createSegmentPath([...currentSegmentPath, ...child]) }, @@ -903,924 +875,935 @@ export const renderToHTMLOrFlight: AppPageRender = ( metadataOutlet, }) - currentStyles = childComponentStyles - childElement = - } + currentStyles = childComponentStyles + childElement = + } - const childProp: ChildProp = { - current: childElement, - segment: childPropSegment, - } - - return getParallelRoutePair(childProp, currentStyles) + const childProp: ChildProp = { + current: childElement, + segment: childPropSegment, } - ) - ) - // Convert the parallel route map into an object after all promises have been resolved. - const parallelRouteComponents = parallelRouteMap.reduce( - (list, [parallelRouteKey, Comp]) => { - list[parallelRouteKey] = Comp - return list - }, - {} as { [key: string]: React.ReactNode } + return getParallelRoutePair(childProp, currentStyles) + } ) + ) - // When the segment does not have a layout or page we still have to add the layout router to ensure the path holds the loading component - if (!Component) { - return { - Component: () => <>{parallelRouteComponents.children}, - styles, - } + // Convert the parallel route map into an object after all promises have been resolved. + const parallelRouteComponents = parallelRouteMap.reduce( + (list, [parallelRouteKey, Comp]) => { + list[parallelRouteKey] = Comp + return list + }, + {} as { [key: string]: React.ReactNode } + ) + + // When the segment does not have a layout or page we still have to add the layout router to ensure the path holds the loading component + if (!Component) { + return { + Component: () => <>{parallelRouteComponents.children}, + styles, } + } - const isClientComponent = isClientReference(layoutOrPageMod) + const isClientComponent = isClientReference(layoutOrPageMod) + + // If it's a not found route, and we don't have any matched parallel + // routes, we try to render the not found component if it exists. + let notFoundComponent = {} + if ( + NotFound && + asNotFound && + // In development, it could hit the parallel-route-default not found, so we only need to check the segment. + // Or if there's no parallel routes means it reaches the end. + !parallelRouteMap.length + ) { + notFoundComponent = { + children: ( + <> + + {process.env.NODE_ENV === 'development' && ( + + )} + {notFoundStyles} + + + ), + } + } - // If it's a not found route, and we don't have any matched parallel - // routes, we try to render the not found component if it exists. - let notFoundComponent = {} - if ( - NotFound && - asNotFound && - // In development, it could hit the parallel-route-default not found, so we only need to check the segment. - // Or if there's no parallel routes means it reaches the end. - !parallelRouteMap.length - ) { - notFoundComponent = { - children: ( - <> - - {process.env.NODE_ENV === 'development' && ( - - )} - {notFoundStyles} - - - ), + const props = { + ...parallelRouteComponents, + ...notFoundComponent, + // TODO-APP: params and query have to be blocked parallel route names. Might have to add a reserved name list. + // Params are always the current params that apply to the layout + // If you have a `/dashboard/[team]/layout.js` it will provide `team` as a param but not anything further down. + params: currentParams, + // Query is only provided to page + ...(() => { + if (isClientComponent && isStaticGeneration) { + return {} } - } - const props = { - ...parallelRouteComponents, - ...notFoundComponent, - // TODO-APP: params and query have to be blocked parallel route names. Might have to add a reserved name list. - // Params are always the current params that apply to the layout - // If you have a `/dashboard/[team]/layout.js` it will provide `team` as a param but not anything further down. - params: currentParams, - // Query is only provided to page - ...(() => { - if (isClientComponent && isStaticGeneration) { - return {} - } + if (isPage) { + return searchParamsProps + } + })(), + } - if (isPage) { - return searchParamsProps - } - })(), - } + // Eagerly execute layout/page component to trigger fetches early. + if (!isClientComponent) { + Component = await Promise.resolve().then(() => + preloadComponent(Component, props) + ) + } - // Eagerly execute layout/page component to trigger fetches early. - if (!isClientComponent) { - Component = await Promise.resolve().then(() => - preloadComponent(Component, props) + return { + Component: () => { + return ( + <> + {isPage ? metadataOutlet : null} + {/* needs to be the first element because we use `findDOMNode` in layout router to locate it. */} + {isPage && isClientComponent ? ( + + ) : ( + + )} + {/* This null is currently critical. The wrapped Component can render null and if there was not fragment + surrounding it this would look like a pending tree data state on the client which will cause an errror + and break the app. Long-term we need to move away from using null as a partial tree identifier since it + is a valid return type for the components we wrap. Once we make this change we can safely remove the + fragment. The reason the extra null here is required is that fragments which only have 1 child are elided. + If the Component above renders null the actual treedata will look like `[null, null]`. If we remove the extra + null it will look like `null` (the array is elided) and this is what confuses the client router. + TODO-APP update router to use a Symbol for partial tree detection */} + {null} + ) - } - - return { - Component: () => { - return ( - <> - {isPage ? metadataOutlet : null} - {/* needs to be the first element because we use `findDOMNode` in layout router to locate it. */} - {isPage && isClientComponent ? ( - - ) : ( - - )} - {/* This null is currently critical. The wrapped Component can render null and if there was not fragment - surrounding it this would look like a pending tree data state on the client which will cause an errror - and break the app. Long-term we need to move away from using null as a partial tree identifier since it - is a valid return type for the components we wrap. Once we make this change we can safely remove the - fragment. The reason the extra null here is required is that fragments which only have 1 child are elided. - If the Component above renders null the actual treedata will look like `[null, null]`. If we remove the extra - null it will look like `null` (the array is elided) and this is what confuses the client router. - TODO-APP update router to use a Symbol for partial tree detection */} - {null} - - ) - }, - styles, - } + }, + styles, } + } - // Handle Flight render request. This is only used when client-side navigating. E.g. when you `router.push('/dashboard')` or `router.reload()`. - const generateFlight = async (options?: { - actionResult: ActionResult - skipFlight: boolean + // Handle Flight render request. This is only used when client-side navigating. E.g. when you `router.push('/dashboard')` or `router.reload()`. + const generateFlight = async (options?: { + actionResult: ActionResult + skipFlight: boolean + asNotFound?: boolean + }): Promise => { + /** + * Use router state to decide at what common layout to render the page. + * This can either be the common layout between two pages or a specific place to start rendering from using the "refetch" marker in the tree. + */ + const walkTreeWithFlightRouterState = async ({ + createSegmentPath, + loaderTreeToFilter, + parentParams, + isFirst, + flightRouterState, + parentRendered, + rscPayloadHead, + injectedCSS, + injectedFontPreloadTags, + rootLayoutIncluded, + asNotFound, + metadataOutlet, + }: { + createSegmentPath: CreateSegmentPath + loaderTreeToFilter: LoaderTree + parentParams: { [key: string]: string | string[] } + isFirst: boolean + flightRouterState?: FlightRouterState + parentRendered?: boolean + rscPayloadHead: React.ReactNode + injectedCSS: Set + injectedFontPreloadTags: Set + rootLayoutIncluded: boolean asNotFound?: boolean - }): Promise => { + metadataOutlet: React.ReactNode + }): Promise => { + const [segment, parallelRoutes, components] = loaderTreeToFilter + + const parallelRoutesKeys = Object.keys(parallelRoutes) + + const { layout } = components + const isLayout = typeof layout !== 'undefined' + /** - * Use router state to decide at what common layout to render the page. - * This can either be the common layout between two pages or a specific place to start rendering from using the "refetch" marker in the tree. + * Checks if the current segment is a root layout. */ - const walkTreeWithFlightRouterState = async ({ - createSegmentPath, - loaderTreeToFilter, - parentParams, - isFirst, - flightRouterState, - parentRendered, - rscPayloadHead, - injectedCSS, - injectedFontPreloadTags, - rootLayoutIncluded, - asNotFound, - metadataOutlet, - }: { - createSegmentPath: CreateSegmentPath - loaderTreeToFilter: LoaderTree - parentParams: { [key: string]: string | string[] } - isFirst: boolean - flightRouterState?: FlightRouterState - parentRendered?: boolean - rscPayloadHead: React.ReactNode - injectedCSS: Set - injectedFontPreloadTags: Set - rootLayoutIncluded: boolean - asNotFound?: boolean - metadataOutlet: React.ReactNode - }): Promise => { - const [segment, parallelRoutes, components] = loaderTreeToFilter - - const parallelRoutesKeys = Object.keys(parallelRoutes) - - const { layout } = components - const isLayout = typeof layout !== 'undefined' - - /** - * Checks if the current segment is a root layout. - */ - const rootLayoutAtThisLevel = isLayout && !rootLayoutIncluded - /** - * Checks if the current segment or any level above it has a root layout. - */ - const rootLayoutIncludedAtThisLevelOrAbove = - rootLayoutIncluded || rootLayoutAtThisLevel - - // Because this function walks to a deeper point in the tree to start rendering we have to track the dynamic parameters up to the point where rendering starts - const segmentParam = getDynamicParamFromSegment(segment) - const currentParams = - // Handle null case where dynamic param is optional - segmentParam && segmentParam.value !== null - ? { - ...parentParams, - [segmentParam.param]: segmentParam.value, - } - : parentParams - const actualSegment: Segment = addSearchParamsIfPageSegment( - segmentParam ? segmentParam.treeSegment : segment, - query - ) + const rootLayoutAtThisLevel = isLayout && !rootLayoutIncluded + /** + * Checks if the current segment or any level above it has a root layout. + */ + const rootLayoutIncludedAtThisLevelOrAbove = + rootLayoutIncluded || rootLayoutAtThisLevel - /** - * Decide if the current segment is where rendering has to start. - */ - const renderComponentsOnThisLevel = - // No further router state available - !flightRouterState || - // Segment in router state does not match current segment - !matchSegment(actualSegment, flightRouterState[0]) || - // Last item in the tree - parallelRoutesKeys.length === 0 || - // Explicit refresh - flightRouterState[3] === 'refetch' - - const shouldSkipComponentTree = - isPrefetch && - !Boolean(components.loading) && - (flightRouterState || - // If there is no flightRouterState, we need to check the entire loader tree, as otherwise we'll be only checking the root - !hasLoadingComponentInTree(loaderTree)) - - if (!parentRendered && renderComponentsOnThisLevel) { - const overriddenSegment = - flightRouterState && - canSegmentBeOverridden(actualSegment, flightRouterState[0]) - ? flightRouterState[0] - : null - - return [ - [ - overriddenSegment ?? actualSegment, - createFlightRouterStateFromLoaderTree( - // Create router state using the slice of the loaderTree - loaderTreeToFilter, - getDynamicParamFromSegment, - query - ), - shouldSkipComponentTree - ? null - : // Create component tree using the slice of the loaderTree - // @ts-expect-error TODO-APP: fix async component type - React.createElement(async () => { - const { Component } = await createComponentTree( - // This ensures flightRouterPath is valid and filters down the tree - { - createSegmentPath, - loaderTree: loaderTreeToFilter, - parentParams: currentParams, - firstItem: isFirst, - injectedCSS, - injectedFontPreloadTags, - // This is intentionally not "rootLayoutIncludedAtThisLevelOrAbove" as createComponentTree starts at the current level and does a check for "rootLayoutAtThisLevel" too. - rootLayoutIncluded, - asNotFound, - metadataOutlet, - } - ) - - return - }), - shouldSkipComponentTree - ? null - : (() => { - const { layoutOrPagePath } = - parseLoaderTree(loaderTreeToFilter) - - const styles = getLayerAssets({ - layoutOrPagePath, - injectedCSS: new Set(injectedCSS), - injectedFontPreloadTags: new Set(injectedFontPreloadTags), - }) - - return ( - <> - {styles} - {rscPayloadHead} - - ) - })(), - ], - ] - } + // Because this function walks to a deeper point in the tree to start rendering we have to track the dynamic parameters up to the point where rendering starts + const segmentParam = getDynamicParamFromSegment(segment) + const currentParams = + // Handle null case where dynamic param is optional + segmentParam && segmentParam.value !== null + ? { + ...parentParams, + [segmentParam.param]: segmentParam.value, + } + : parentParams + const actualSegment: Segment = addSearchParamsIfPageSegment( + segmentParam ? segmentParam.treeSegment : segment, + query + ) + + /** + * Decide if the current segment is where rendering has to start. + */ + const renderComponentsOnThisLevel = + // No further router state available + !flightRouterState || + // Segment in router state does not match current segment + !matchSegment(actualSegment, flightRouterState[0]) || + // Last item in the tree + parallelRoutesKeys.length === 0 || + // Explicit refresh + flightRouterState[3] === 'refetch' + + const shouldSkipComponentTree = + isPrefetch && + !Boolean(components.loading) && + (flightRouterState || + // If there is no flightRouterState, we need to check the entire loader tree, as otherwise we'll be only checking the root + !hasLoadingComponentInTree(loaderTree)) + + if (!parentRendered && renderComponentsOnThisLevel) { + const overriddenSegment = + flightRouterState && + canSegmentBeOverridden(actualSegment, flightRouterState[0]) + ? flightRouterState[0] + : null + + return [ + [ + overriddenSegment ?? actualSegment, + createFlightRouterStateFromLoaderTree( + // Create router state using the slice of the loaderTree + loaderTreeToFilter, + getDynamicParamFromSegment, + query + ), + shouldSkipComponentTree + ? null + : // Create component tree using the slice of the loaderTree + // @ts-expect-error TODO-APP: fix async component type + React.createElement(async () => { + const { Component } = await createComponentTree( + // This ensures flightRouterPath is valid and filters down the tree + { + createSegmentPath, + loaderTree: loaderTreeToFilter, + parentParams: currentParams, + firstItem: isFirst, + injectedCSS, + injectedFontPreloadTags, + // This is intentionally not "rootLayoutIncludedAtThisLevelOrAbove" as createComponentTree starts at the current level and does a check for "rootLayoutAtThisLevel" too. + rootLayoutIncluded, + asNotFound, + metadataOutlet, + } + ) + + return + }), + shouldSkipComponentTree + ? null + : (() => { + const { layoutOrPagePath } = + parseLoaderTree(loaderTreeToFilter) + + const styles = getLayerAssets({ + layoutOrPagePath, + injectedCSS: new Set(injectedCSS), + injectedFontPreloadTags: new Set(injectedFontPreloadTags), + }) + + return ( + <> + {styles} + {rscPayloadHead} + + ) + })(), + ], + ] + } - // If we are not rendering on this level we need to check if the current - // segment has a layout. If so, we need to track all the used CSS to make - // the result consistent. - const layoutPath = layout?.[1] - const injectedCSSWithCurrentLayout = new Set(injectedCSS) - const injectedFontPreloadTagsWithCurrentLayout = new Set( - injectedFontPreloadTags + // If we are not rendering on this level we need to check if the current + // segment has a layout. If so, we need to track all the used CSS to make + // the result consistent. + const layoutPath = layout?.[1] + const injectedCSSWithCurrentLayout = new Set(injectedCSS) + const injectedFontPreloadTagsWithCurrentLayout = new Set( + injectedFontPreloadTags + ) + if (layoutPath) { + getCssInlinedLinkTags( + clientReferenceManifest, + layoutPath, + injectedCSSWithCurrentLayout, + true ) - if (layoutPath) { - getCssInlinedLinkTags( - clientReferenceManifest, - layoutPath, - injectedCSSWithCurrentLayout, - true - ) - getPreloadableFonts( - nextFontManifest, - layoutPath, - injectedFontPreloadTagsWithCurrentLayout - ) - } + getPreloadableFonts( + nextFontManifest, + layoutPath, + injectedFontPreloadTagsWithCurrentLayout + ) + } - // Walk through all parallel routes. - const paths: FlightDataPath[] = ( - await Promise.all( - parallelRoutesKeys.map(async (parallelRouteKey) => { - // for (const parallelRouteKey of parallelRoutesKeys) { - const parallelRoute = parallelRoutes[parallelRouteKey] + // Walk through all parallel routes. + const paths: FlightDataPath[] = ( + await Promise.all( + parallelRoutesKeys.map(async (parallelRouteKey) => { + // for (const parallelRouteKey of parallelRoutesKeys) { + const parallelRoute = parallelRoutes[parallelRouteKey] - const currentSegmentPath: FlightSegmentPath = isFirst - ? [parallelRouteKey] - : [actualSegment, parallelRouteKey] + const currentSegmentPath: FlightSegmentPath = isFirst + ? [parallelRouteKey] + : [actualSegment, parallelRouteKey] - const path = await walkTreeWithFlightRouterState({ - createSegmentPath: (child) => { - return createSegmentPath([...currentSegmentPath, ...child]) - }, - loaderTreeToFilter: parallelRoute, - parentParams: currentParams, - flightRouterState: - flightRouterState && flightRouterState[1][parallelRouteKey], - parentRendered: parentRendered || renderComponentsOnThisLevel, - isFirst: false, - rscPayloadHead, - injectedCSS: injectedCSSWithCurrentLayout, - injectedFontPreloadTags: - injectedFontPreloadTagsWithCurrentLayout, - rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove, - asNotFound, - metadataOutlet, + const path = await walkTreeWithFlightRouterState({ + createSegmentPath: (child) => { + return createSegmentPath([...currentSegmentPath, ...child]) + }, + loaderTreeToFilter: parallelRoute, + parentParams: currentParams, + flightRouterState: + flightRouterState && flightRouterState[1][parallelRouteKey], + parentRendered: parentRendered || renderComponentsOnThisLevel, + isFirst: false, + rscPayloadHead, + injectedCSS: injectedCSSWithCurrentLayout, + injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout, + rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove, + asNotFound, + metadataOutlet, + }) + + return path + .map((item) => { + // we don't need to send over default routes in the flight data + // because they are always ignored by the client, unless it's a refetch + if ( + item[0] === '__DEFAULT__' && + flightRouterState && + !!flightRouterState[1][parallelRouteKey][0] && + flightRouterState[1][parallelRouteKey][3] !== 'refetch' + ) { + return null + } + return [actualSegment, parallelRouteKey, ...item] }) + .filter(Boolean) as FlightDataPath[] + }) + ) + ).flat() - return path - .map((item) => { - // we don't need to send over default routes in the flight data - // because they are always ignored by the client, unless it's a refetch - if ( - item[0] === '__DEFAULT__' && - flightRouterState && - !!flightRouterState[1][parallelRouteKey][0] && - flightRouterState[1][parallelRouteKey][3] !== 'refetch' - ) { - return null - } - return [actualSegment, parallelRouteKey, ...item] - }) - .filter(Boolean) as FlightDataPath[] - }) - ) - ).flat() + return paths + } - return paths + // Flight data that is going to be passed to the browser. + // Currently a single item array but in the future multiple patches might be combined in a single request. + + let flightData: FlightData | null = null + if (!options?.skipFlight) { + const [MetadataTree, MetadataOutlet] = createMetadataComponents({ + tree: loaderTree, + pathname: urlPathname, + searchParams: providedSearchParams, + getDynamicParamFromSegment, + appUsingSizeAdjust, + }) + flightData = ( + await walkTreeWithFlightRouterState({ + createSegmentPath: (child) => child, + loaderTreeToFilter: loaderTree, + parentParams: {}, + flightRouterState: providedFlightRouterState, + isFirst: true, + // For flight, render metadata inside leaf page + rscPayloadHead: ( + // Adding requestId as react key to make metadata remount for each render + + ), + injectedCSS: new Set(), + injectedFontPreloadTags: new Set(), + rootLayoutIncluded: false, + asNotFound: isNotFoundPath || options?.asNotFound, + metadataOutlet: , + }) + ).map((path) => path.slice(1)) // remove the '' (root) segment + } + + const buildIdFlightDataPair = [buildId, flightData] + + // For app dir, use the bundled version of Flight server renderer (renderToReadableStream) + // which contains the subset React. + const flightReadableStream = renderToReadableStream( + options + ? [options.actionResult, buildIdFlightDataPair] + : buildIdFlightDataPair, + clientReferenceManifest.clientModules, + { + context: serverContexts, + onError: flightDataRendererErrorHandler, } + ).pipeThrough(createBufferedTransformStream()) - // Flight data that is going to be passed to the browser. - // Currently a single item array but in the future multiple patches might be combined in a single request. + return new FlightRenderResult(flightReadableStream) + } - let flightData: FlightData | null = null - if (!options?.skipFlight) { - const [MetadataTree, MetadataOutlet] = createMetadataComponents({ - tree: loaderTree, - pathname, - searchParams: providedSearchParams, - getDynamicParamFromSegment, - appUsingSizeAdjust, - }) - flightData = ( - await walkTreeWithFlightRouterState({ - createSegmentPath: (child) => child, - loaderTreeToFilter: loaderTree, - parentParams: {}, - flightRouterState: providedFlightRouterState, - isFirst: true, - // For flight, render metadata inside leaf page - rscPayloadHead: ( - // Adding requestId as react key to make metadata remount for each render - + if (isFlight && !staticGenerationStore.isStaticGeneration) { + return generateFlight() + } + + // Get the nonce from the incoming request if it has one. + const csp = req.headers['content-security-policy'] + let nonce: string | undefined + if (csp && typeof csp === 'string') { + nonce = getScriptNonceFromHeader(csp) + } + + const serverComponentsRenderOpts = { + inlinedDataTransformStream: new TransformStream(), + clientReferenceManifest, + serverContexts, + formState: null, + } + + const validateRootLayout = dev + ? { + validateRootLayout: { + assetPrefix: renderOpts.assetPrefix, + getTree: () => + createFlightRouterStateFromLoaderTree( + loaderTree, + getDynamicParamFromSegment, + query ), - injectedCSS: new Set(), - injectedFontPreloadTags: new Set(), - rootLayoutIncluded: false, - asNotFound: isNotFoundPath || options?.asNotFound, - metadataOutlet: , - }) - ).map((path) => path.slice(1)) // remove the '' (root) segment + }, } + : {} - const buildIdFlightDataPair = [buildId, flightData] - - // For app dir, use the bundled version of Flight server renderer (renderToReadableStream) - // which contains the subset React. - const flightReadableStream = renderToReadableStream( - options - ? [options.actionResult, buildIdFlightDataPair] - : buildIdFlightDataPair, - clientReferenceManifest.clientModules, - { - context: serverContexts, - onError: flightDataRendererErrorHandler, - } - ).pipeThrough(createBufferedTransformStream()) + /** + * A new React Component that renders the provided React Component + * using Flight which can then be rendered to HTML. + */ + const createServerComponentsRenderer = ( + loaderTreeToRender: LoaderTree, + preinitScripts: () => void, + formState: null | any + ) => + createServerComponentRenderer<{ + asNotFound: boolean + }>( + async (props) => { + preinitScripts() + // Create full component tree from root to leaf. + const injectedCSS = new Set() + const injectedFontPreloadTags = new Set() + const initialTree = createFlightRouterStateFromLoaderTree( + loaderTreeToRender, + getDynamicParamFromSegment, + query + ) - return new FlightRenderResult(flightReadableStream) - } + const [MetadataTree, MetadataOutlet] = createMetadataComponents({ + tree: loaderTreeToRender, + errorType: props.asNotFound ? 'not-found' : undefined, + pathname: urlPathname, + searchParams: providedSearchParams, + getDynamicParamFromSegment: getDynamicParamFromSegment, + appUsingSizeAdjust: appUsingSizeAdjust, + }) - if (isFlight && !staticGenerationStore.isStaticGeneration) { - return generateFlight() - } + const { Component: ComponentTree, styles } = await createComponentTree({ + createSegmentPath: (child) => child, + loaderTree: loaderTreeToRender, + parentParams: {}, + firstItem: true, + injectedCSS, + injectedFontPreloadTags, + rootLayoutIncluded: false, + asNotFound: props.asNotFound, + metadataOutlet: , + }) - // Get the nonce from the incoming request if it has one. - const csp = req.headers['content-security-policy'] - let nonce: string | undefined - if (csp && typeof csp === 'string') { - nonce = getScriptNonceFromHeader(csp) - } + return ( + <> + {styles} + + {res.statusCode > 400 && ( + + )} + {/* Adding requestId as react key to make metadata remount for each render */} + + + } + globalErrorComponent={GlobalError} + > + + + + ) + }, + ComponentMod, + { ...serverComponentsRenderOpts, formState }, + serverComponentsErrorHandler, + nonce + ) - const serverComponentsRenderOpts = { - inlinedDataTransformStream: new TransformStream(), - clientReferenceManifest, - serverContexts, - formState: null, - } + const { HeadManagerContext } = + require('../../shared/lib/head-manager-context.shared-runtime') as typeof import('../../shared/lib/head-manager-context.shared-runtime') + + // On each render, create a new `ServerInsertedHTML` context to capture + // injected nodes from user code (`useServerInsertedHTML`). + const { ServerInsertedHTMLProvider, renderServerInsertedHTML } = + createServerInsertedHTML() + + getTracer().getRootSpanAttributes()?.set('next.route', pagePath) + const bodyResult = getTracer().wrap( + AppRenderSpan.getBodyResult, + { + spanName: `render route (app) ${pagePath}`, + attributes: { + 'next.route': pagePath, + }, + }, + async ({ + asNotFound, + tree, + formState, + }: { + /** + * This option is used to indicate that the page should be rendered as + * if it was not found. When it's enabled, instead of rendering the + * page component, it renders the not-found segment. + * + */ + asNotFound: boolean + tree: LoaderTree + formState: any + }) => { + const polyfills: JSX.IntrinsicElements['script'][] = + buildManifest.polyfillFiles + .filter( + (polyfill) => + polyfill.endsWith('.js') && !polyfill.endsWith('.module.js') + ) + .map((polyfill) => ({ + src: `${assetPrefix}/_next/${polyfill}${getAssetQueryString( + false + )}`, + integrity: subresourceIntegrityManifest?.[polyfill], + crossOrigin: renderOpts.crossOrigin, + noModule: true, + nonce, + })) + + const [preinitScripts, bootstrapScript] = getRequiredScripts( + buildManifest, + assetPrefix, + renderOpts.crossOrigin, + subresourceIntegrityManifest, + getAssetQueryString(true), + nonce + ) + const ServerComponentsRenderer = createServerComponentsRenderer( + tree, + preinitScripts, + formState + ) + const content = ( + + + + + + ) - const validateRootLayout = dev - ? { - validateRootLayout: { - assetPrefix: renderOpts.assetPrefix, - getTree: () => - createFlightRouterStateFromLoaderTree( - loaderTree, - getDynamicParamFromSegment, - query - ), - }, + let polyfillsFlushed = false + let flushedErrorMetaTagsUntilIndex = 0 + const getServerInsertedHTML = (serverCapturedErrors: Error[]) => { + // Loop through all the errors that have been captured but not yet + // flushed. + const errorMetaTags = [] + for ( + ; + flushedErrorMetaTagsUntilIndex < serverCapturedErrors.length; + flushedErrorMetaTagsUntilIndex++ + ) { + const error = serverCapturedErrors[flushedErrorMetaTagsUntilIndex] + + if (isNotFoundError(error)) { + errorMetaTags.push( + , + process.env.NODE_ENV === 'development' ? ( + + ) : null + ) + } else if (isRedirectError(error)) { + const redirectUrl = getURLFromRedirectError(error) + const isPermanent = + getRedirectStatusCodeFromError(error) === 308 ? true : false + if (redirectUrl) { + errorMetaTags.push( + + ) + } + } } - : {} - /** - * A new React Component that renders the provided React Component - * using Flight which can then be rendered to HTML. - */ - const createServerComponentsRenderer = ( - loaderTreeToRender: LoaderTree, - preinitScripts: () => void, - formState: null | any - ) => - createServerComponentRenderer<{ - asNotFound: boolean - }>( - async (props) => { - preinitScripts() - // Create full component tree from root to leaf. - const injectedCSS = new Set() - const injectedFontPreloadTags = new Set() - const initialTree = createFlightRouterStateFromLoaderTree( - loaderTreeToRender, - getDynamicParamFromSegment, - query - ) + const flushed = renderToString({ + ReactDOMServer: require('react-dom/server.edge'), + element: ( + <> + {polyfillsFlushed + ? null + : polyfills?.map((polyfill) => { + return