Unverified Commit 47ed9ed2 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Load client reference manifests without a new VM context

Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 7657545d
......@@ -529,6 +529,11 @@ async fn build_manifest(
// note this only applies to the manifests, assets are placed to the original
// path still (same as webpack does)
let normalized_manifest_entry = entry_name.replace("%5F", "_");
// The shape of this file (including the deployment ID suffix) is
// recognized by `classifyClientReferenceManifestSource` in
// `packages/next/src/server/load-manifest.external.ts` to load it faster.
// Keep both in sync; unrecognized shapes still work but fall back to a
// slower evaluation.
Ok(ClientReferenceManifestResult {
content: AssetContent::file(
FileContent::Content(File::from(formatdoc! {
......
import path from 'path'
import { promises as fs, statSync } from 'fs'
import { promises as fs, readFileSync, statSync } from 'fs'
import {
APP_PATHS_MANIFEST,
CLIENT_REFERENCE_MANIFEST,
......@@ -7,6 +7,7 @@ import {
} from '../shared/lib/constants'
import type { BuildManifest } from '../server/get-page-files'
import { filterAndSortList } from './utils'
import { evalClientReferenceManifestSource } from '../server/load-manifest.external'
const ROUTE_BUNDLE_STATS_FILE = 'route-bundle-stats.json'
......@@ -67,9 +68,10 @@ function buildRouteToAppPathsMap(
return routeToAppPaths
}
// Reads the manfiest file and gets the entry JS files. The manifest file is
// a JavaScript file that sets a global variable (__RSC_MANIFEST). We require()
// it with a save/restore of the global
// Reads the manifest file and gets the entry JS files. The manifest file is
// a JavaScript file that sets a global variable (__RSC_MANIFEST). It is
// loaded with `evalClientReferenceManifestSource`, which parses the generated
// shapes as JSON where possible instead of require()-ing the file.
function readEntryJSFiles(
distDir: string,
pagePath: string,
......@@ -82,14 +84,11 @@ function readEntryJSFiles(
`${pagePath}_${CLIENT_REFERENCE_MANIFEST}.js`
)
try {
const g = global as Record<string, unknown>
const prev = g.__RSC_MANIFEST
g.__RSC_MANIFEST = undefined
require(manifestFile)
const rscManifest = g.__RSC_MANIFEST as
const rscManifest = evalClientReferenceManifestSource(
readFileSync(manifestFile, 'utf8')
).__RSC_MANIFEST as
| Record<string, { entryJSFiles?: Record<string, string[]> }>
| undefined
g.__RSC_MANIFEST = prev
// The key in __RSC_MANIFEST is the app path (e.g. /blog/[slug]/page)
const manifestEntry = rscManifest?.[pagePath] ?? rscManifest?.[appRoute]
......
......@@ -602,6 +602,9 @@ export class ClientReferenceManifestPlugin {
const pagePath = pageName.replace(/%5F/g, '_')
const pageBundlePath = normalizePagePath(pagePath.slice('app'.length))
// This shape is recognized and parsed as JSON by
// `classifyClientReferenceManifestSource` in
// `server/load-manifest.external.ts`. Keep both in sync.
compilation.emitAsset(
'server/app' + pageBundlePath + '_' + CLIENT_REFERENCE_MANIFEST + '.js',
new sources.RawSource(
......
......@@ -2,7 +2,8 @@ import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { join } from 'path'
import { readFileSync } from 'fs'
import { runInNewContext } from 'vm'
import { createContext, runInContext, runInNewContext } from 'vm'
import type { Context } from 'vm'
import { deepFreeze } from '../shared/lib/deep-freeze'
const sharedCache = new Map<string, unknown>()
......@@ -118,10 +119,7 @@ export function evalManifest<T extends object>(
throw new Error('Manifest file is empty')
}
let contextObject = {
process: { env: { NEXT_DEPLOYMENT_ID: process.env.NEXT_DEPLOYMENT_ID } },
}
runInNewContext(content, contextObject)
let contextObject = evalClientReferenceManifestSource(content)
// Freeze the context object so it cannot be modified if we're caching it.
if (shouldCache) {
......@@ -135,6 +133,241 @@ export function evalManifest<T extends object>(
return contextObject as T
}
export type ClientReferenceManifestSourceKind =
| {
/** A plain `globalThis.__RSC_MANIFEST[key] = <JSON>;` assignment. */
type: 'json'
key: string
value: unknown
}
| {
/** The JSON assignment followed by Turbopack's deployment ID suffix. */
type: 'deployment-id'
}
| {
/** Anything else: must be evaluated in an isolated V8 context. */
type: 'unknown'
}
const MANIFEST_PREFIX_RE =
// Webpack: `globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});`
// Turbopack: `globalThis.__RSC_MANIFEST = globalThis.__RSC_MANIFEST || {};`
/^\s*globalThis\.__RSC_MANIFEST\s*=\s*(?:\(\s*globalThis\.__RSC_MANIFEST\s*\|\|\s*\{\s*\}\s*\)|globalThis\.__RSC_MANIFEST\s*\|\|\s*\{\s*\})\s*;\s*globalThis\.__RSC_MANIFEST\[/
const ASSIGNMENT_RE = /\s*\]\s*=\s*/y
/**
* The deployment ID suffix Turbopack appends to client reference manifests
* when the deployment ID is added at runtime. Must be kept in sync with
* `crates/next-core/src/next_manifests/client_reference_manifest.rs`.
* `KEY` is replaced with the entry name string literal.
*/
const DEPLOYMENT_ID_SUFFIX_TEMPLATE = `
for (const key in globalThis.__RSC_MANIFEST[KEY].clientModules) {
const val = { ...globalThis.__RSC_MANIFEST[KEY].clientModules[key] }
globalThis.__RSC_MANIFEST[KEY].clientModules[key] = val
val.chunks = val.chunks.map((c) =>
typeof c === 'string'
? \`\${c}?dpl=\${process.env.NEXT_DEPLOYMENT_ID}\`
: [\`\${c[0]}?dpl=\${process.env.NEXT_DEPLOYMENT_ID}\`, c[1], c[2]])
}
`
/**
* Splits source into its non-empty lines with surrounding whitespace removed.
* Line breaks are preserved (they matter for ASI), only indentation and blank
* lines are ignored.
*/
function toNormalizedLines(source: string): string[] {
const lines: string[] = []
for (const line of source.split(/\r?\n/)) {
const trimmed = line.trim()
if (trimmed !== '') {
lines.push(trimmed)
}
}
return lines
}
function isDeploymentIdSuffix(suffix: string, keyLiteral: string): boolean {
const expected = toNormalizedLines(
DEPLOYMENT_ID_SUFFIX_TEMPLATE.split('[KEY]').join(`[${keyLiteral}]`)
)
const actual = toNormalizedLines(suffix)
return (
actual.length === expected.length &&
actual.every((line, i) => line === expected[i])
)
}
function hasOwnProtoKey(value: unknown): boolean {
if (value === null || typeof value !== 'object') {
return false
}
if (Object.hasOwn(value, '__proto__')) {
return true
}
for (const child of Object.values(value)) {
if (hasOwnProtoKey(child)) {
return true
}
}
return false
}
/**
* Classifies the source of a `*_client-reference-manifest.js` file without
* evaluating it. The webpack and Turbopack generated files are a JSON object
* assigned to `globalThis.__RSC_MANIFEST[<entry name>]`, which can be read
* with `JSON.parse` instead of evaluating JavaScript (`json`). Turbopack's
* deployment ID variant appends a fixed loop that still has to be evaluated
* (`deployment-id`).
*
* Anything that doesn't exactly match a known generated shape is classified
* as `unknown`, so the caller falls back to evaluating it in a new context.
*/
export function classifyClientReferenceManifestSource(
content: string
): ClientReferenceManifestSourceKind {
const unknown = { type: 'unknown' } as const
// `JSON.parse` treats `__proto__` as a regular key whereas an object
// literal sets the prototype, so the results could differ.
if (content.includes('__proto__')) {
return unknown
}
const prefix = MANIFEST_PREFIX_RE.exec(content)
if (!prefix) {
return unknown
}
// The entry name is a JSON string literal.
const keyStart = prefix[0].length
if (content[keyStart] !== '"') {
return unknown
}
let keyEnd = keyStart + 1
while (keyEnd < content.length && content[keyEnd] !== '"') {
keyEnd += content[keyEnd] === '\\' ? 2 : 1
}
if (keyEnd >= content.length) {
return unknown
}
const keyLiteral = content.slice(keyStart, keyEnd + 1)
ASSIGNMENT_RE.lastIndex = keyEnd + 1
if (!ASSIGNMENT_RE.test(content)) {
return unknown
}
const bodyStart = ASSIGNMENT_RE.lastIndex
// The generated JSON is serialized without line breaks, so the assignment
// ends on the line it starts on. Anything after it is a suffix.
const rest = content.slice(bodyStart)
const lineBreak = rest.search(/[\r\n]/)
const assignment = (
lineBreak === -1 ? rest : rest.slice(0, lineBreak)
).trimEnd()
const suffix = lineBreak === -1 ? '' : rest.slice(lineBreak)
if (!assignment.endsWith(';')) {
return unknown
}
let key: string
let value: unknown
try {
key = JSON.parse(keyLiteral)
value = JSON.parse(assignment.slice(0, -1))
} catch {
return unknown
}
// `__proto__` can also be spelled with unicode escapes, which the
// `includes` check above doesn't catch.
if (
content.includes('\\u') &&
(key === '__proto__' || hasOwnProtoKey(value))
) {
return unknown
}
if (suffix.trim() === '') {
return { type: 'json', key, value }
}
if (isDeploymentIdSuffix(suffix, keyLiteral)) {
return { type: 'deployment-id' }
}
return unknown
}
let deploymentIdManifestContext: Context | undefined
/**
* Evaluates a Turbopack client reference manifest with the deployment ID
* suffix. Creating a V8 context is expensive, so a single context is reused.
* This is only done for sources that were verified to exactly match the
* generated shape (see `classifyClientReferenceManifestSource`), which only
* write `globalThis.__RSC_MANIFEST` and read `process.env`, both of which are
* reset for every call. The context itself is never returned.
*/
function evalDeploymentIdManifest(content: string) {
deploymentIdManifestContext ??= createContext({})
const context = deploymentIdManifestContext
const processObject = {
env: { NEXT_DEPLOYMENT_ID: process.env.NEXT_DEPLOYMENT_ID },
}
context.process = processObject
context.__RSC_MANIFEST = undefined
try {
runInContext(content, context)
return {
process: processObject,
__RSC_MANIFEST: context.__RSC_MANIFEST,
}
} finally {
context.process = undefined
context.__RSC_MANIFEST = undefined
}
}
/**
* Evaluates the source of a `*_client-reference-manifest.js` file and returns
* the resulting global object (`{ process, __RSC_MANIFEST }`):
* - plain generated assignments are parsed with `JSON.parse`,
* - Turbopack's generated deployment ID variant runs in a reused V8 context,
* - anything else runs in a new V8 context.
*/
export function evalClientReferenceManifestSource(content: string): {
process: { env: { NEXT_DEPLOYMENT_ID: string | undefined } }
__RSC_MANIFEST?: Record<string, unknown>
[key: string]: unknown
} {
const kind = classifyClientReferenceManifestSource(content)
switch (kind.type) {
case 'json':
return {
process: {
env: { NEXT_DEPLOYMENT_ID: process.env.NEXT_DEPLOYMENT_ID },
},
__RSC_MANIFEST: { [kind.key]: kind.value },
}
case 'deployment-id':
return evalDeploymentIdManifest(content)
default: {
const contextObject = {
process: {
env: { NEXT_DEPLOYMENT_ID: process.env.NEXT_DEPLOYMENT_ID },
},
}
runInNewContext(content, contextObject)
return contextObject
}
}
}
export function evalManifestFromRelativePath<T extends object>({
projectDir,
distDir,
......
import { runInNewContext } from 'vm'
import { mkdtempSync, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import {
classifyClientReferenceManifestSource,
evalClientReferenceManifestSource,
evalManifest,
} from 'next/dist/server/load-manifest.external'
import { deepFreeze } from 'next/dist/shared/lib/deep-freeze'
const manifest = {
moduleLoading: { prefix: '/_next/', crossOrigin: null },
clientModules: {
'[project]/app/page.tsx <module evaluation>': {
id: 1,
name: '*',
chunks: ['static/chunks/a.js', ['static/chunks/b.js', 1, 2]],
async: false,
},
},
entryCSSFiles: { '[project]/app/page': [{ path: 'static/{css}/a.css' }] },
entryJSFiles: { '[project]/app/page': ['static/chunks/a.js'] },
}
// Mirrors `build/webpack/plugins/flight-manifest-plugin.ts`.
function webpackSource(key: string, value: unknown = manifest) {
return `globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST[${JSON.stringify(
key
)}]=${JSON.stringify(value)};`
}
// Mirrors `crates/next-core/src/next_manifests/client_reference_manifest.rs`.
function turbopackSource(
key: string,
{ deploymentId = false, value = manifest as unknown } = {}
) {
const k = JSON.stringify(key)
let source = `globalThis.__RSC_MANIFEST = globalThis.__RSC_MANIFEST || {};
globalThis.__RSC_MANIFEST[${k}] = ${JSON.stringify(value)};
`
if (deploymentId) {
source += `for (const key in globalThis.__RSC_MANIFEST[${k}].clientModules) {
const val = { ...globalThis.__RSC_MANIFEST[${k}].clientModules[key] }
globalThis.__RSC_MANIFEST[${k}].clientModules[key] = val
val.chunks = val.chunks.map((c) =>
typeof c === 'string'
? \`\${c}?dpl=\${process.env.NEXT_DEPLOYMENT_ID}\`
: [\`\${c[0]}?dpl=\${process.env.NEXT_DEPLOYMENT_ID}\`, c[1], c[2]])
}
`
}
return source
}
function evalInNewContext(source: string) {
const contextObject = {
process: { env: { NEXT_DEPLOYMENT_ID: process.env.NEXT_DEPLOYMENT_ID } },
}
runInNewContext(source, contextObject)
return contextObject
}
// Objects created in another V8 context have different prototypes, so compare
// a structural JSON copy.
function plain(value: unknown) {
return JSON.parse(JSON.stringify(value))
}
function expectSameAsNewContext(source: string) {
expect(plain(evalClientReferenceManifestSource(source))).toEqual(
plain(evalInNewContext(source))
)
}
describe('evalClientReferenceManifestSource', () => {
const originalDeploymentId = process.env.NEXT_DEPLOYMENT_ID
afterEach(() => {
if (originalDeploymentId === undefined) {
delete process.env.NEXT_DEPLOYMENT_ID
} else {
process.env.NEXT_DEPLOYMENT_ID = originalDeploymentId
}
})
it.each([
['webpack', webpackSource('/page')],
['turbopack', turbopackSource('/page')],
])('parses the %s shape as JSON', (_, source) => {
expect(classifyClientReferenceManifestSource(source)).toEqual({
type: 'json',
key: '/page',
value: manifest,
})
expectSameAsNewContext(source)
})
it('includes NEXT_DEPLOYMENT_ID in the result like the VM context', () => {
process.env.NEXT_DEPLOYMENT_ID = 'dpl_123'
const source = webpackSource('/page')
expect(evalClientReferenceManifestSource(source).process).toEqual({
env: { NEXT_DEPLOYMENT_ID: 'dpl_123' },
})
expectSameAsNewContext(source)
})
it.each([
'/[teamSlug]/page',
'/(group)/[...slug]/page',
'/a"b]c\\d/page',
'/\u00e9\u2028/page',
])('handles the entry name %j', (key) => {
for (const source of [webpackSource(key), turbopackSource(key)]) {
const kind = classifyClientReferenceManifestSource(source)
expect(kind).toEqual({ type: 'json', key, value: manifest })
expectSameAsNewContext(source)
}
})
it('accepts escaped entry names', () => {
const source = `globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["\\u002fpage"]={"a":1};`
expect(classifyClientReferenceManifestSource(source)).toEqual({
type: 'json',
key: '/page',
value: { a: 1 },
})
expectSameAsNewContext(source)
})
it('evaluates the turbopack deployment ID shape in a reused context', () => {
const source = turbopackSource('/page', { deploymentId: true })
expect(classifyClientReferenceManifestSource(source)).toEqual({
type: 'deployment-id',
})
process.env.NEXT_DEPLOYMENT_ID = 'dpl_1'
const result = evalClientReferenceManifestSource(source)
expect(
plain(result.__RSC_MANIFEST!['/page']).clientModules[
'[project]/app/page.tsx <module evaluation>'
].chunks
).toEqual([
'static/chunks/a.js?dpl=dpl_1',
['static/chunks/b.js?dpl=dpl_1', 1, 2],
])
expectSameAsNewContext(source)
})
it('does not leak state between deployment ID evaluations', () => {
process.env.NEXT_DEPLOYMENT_ID = 'dpl_1'
const first = deepFreeze(
evalClientReferenceManifestSource(
turbopackSource('/a/page', { deploymentId: true })
)
)
process.env.NEXT_DEPLOYMENT_ID = 'dpl_2'
const secondSource = turbopackSource('/b/page', { deploymentId: true })
const second = evalClientReferenceManifestSource(secondSource)
expect(Object.keys(first.__RSC_MANIFEST!)).toEqual(['/a/page'])
expect(Object.keys(second.__RSC_MANIFEST!)).toEqual(['/b/page'])
expect(first.process.env.NEXT_DEPLOYMENT_ID).toBe('dpl_1')
expect(second.process.env.NEXT_DEPLOYMENT_ID).toBe('dpl_2')
expect(plain(second)).toEqual(plain(evalInNewContext(secondSource)))
expect(
plain(first.__RSC_MANIFEST!['/a/page']).clientModules[
'[project]/app/page.tsx <module evaluation>'
].chunks[0]
).toBe('static/chunks/a.js?dpl=dpl_1')
})
it('falls back to a new context when `__proto__` is present', () => {
const source = webpackSource('/page', { __proto__: { polluted: true } })
// JSON.stringify drops the prototype, so build the source by hand.
const withProto = source.replace(
/=\{\};$/,
'={"__proto__":{"polluted":true}};'
)
expect(classifyClientReferenceManifestSource(withProto)).toEqual({
type: 'unknown',
})
const result = evalClientReferenceManifestSource(withProto)
expect(Object.keys(result.__RSC_MANIFEST!['/page'] as object)).toEqual([])
expect((result.__RSC_MANIFEST!['/page'] as any).polluted).toBe(true)
})
it.each([
[
'webpack',
`globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/page"]={"a":{"__pr\\u006fto__":{"polluted":true}}};`,
],
[
'turbopack deployment ID',
turbopackSource('/page', { deploymentId: true }).replace(
'{"moduleLoading":',
'{"__pr\\u006fto__":{"polluted":true},"moduleLoading":'
),
],
])(
'falls back to a new context for an escaped `__proto__` key (%s)',
(_, source) => {
expect(classifyClientReferenceManifestSource(source)).toEqual({
type: 'unknown',
})
expectSameAsNewContext(source)
const result = evalClientReferenceManifestSource(source)
const value = result.__RSC_MANIFEST!['/page'] as any
const target = value.a ?? value
expect(Object.hasOwn(target, '__proto__')).toBe(false)
expect(target.polluted).toBe(true)
}
)
it('falls back to a new context for an escaped `__proto__` entry name', () => {
const source = `globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["__pr\\u006fto__"]={"a":1};`
expect(classifyClientReferenceManifestSource(source)).toEqual({
type: 'unknown',
})
const result = evalClientReferenceManifestSource(source)
expect(Object.hasOwn(result.__RSC_MANIFEST!, '__proto__')).toBe(false)
expect((result.__RSC_MANIFEST as any).a).toBe(1)
})
it.each([
['trailing code', webpackSource('/page') + 'globalThis.extra = 1;'],
[
'trailing code on a new line',
turbopackSource('/page') + 'globalThis.extra = 1;\n',
],
[
'a modified deployment ID suffix',
turbopackSource('/page', { deploymentId: true }).replace(
'?dpl=',
'?other='
),
],
[
'an extra statement in the deployment ID suffix',
turbopackSource('/page', { deploymentId: true }) +
'globalThis.extra = 1\n',
],
[
'a non-JSON body',
`globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/page"]={a:1};`,
],
[
'code inside the body',
`globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/page"]={"a":1};globalThis.extra={"b":2};`,
],
['a missing prefix', `globalThis.__RSC_MANIFEST = {"/page": {"a": 1}};`],
[
'a single quoted key',
`globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST['/page']={"a":1};`,
],
])('falls back to a new context for %s', (_, source) => {
expect(classifyClientReferenceManifestSource(source)).toEqual({
type: 'unknown',
})
expectSameAsNewContext(source)
})
it('propagates errors from the fallback', () => {
expect(() =>
evalClientReferenceManifestSource('throw new Error("boom")')
).toThrow('boom')
})
it('isolates globals and intrinsics of unrecognized sources', () => {
const first = evalClientReferenceManifestSource(
'globalThis.leaked = 1; Array.prototype.polluted = true;'
)
expect(first.leaked).toBe(1)
const second = evalClientReferenceManifestSource(
'globalThis.sawLeak = typeof leaked; globalThis.sawPollution = [].polluted;'
)
expect(second.sawLeak).toBe('undefined')
expect(second.sawPollution).toBeUndefined()
expect((Array.prototype as any).polluted).toBeUndefined()
})
it('handles tricky entry names in the deployment ID shape', () => {
process.env.NEXT_DEPLOYMENT_ID = 'dpl_1'
for (const key of ['/[teamSlug]/page', '/a"b]c\\d/page']) {
const source = turbopackSource(key, { deploymentId: true })
expect(classifyClientReferenceManifestSource(source)).toEqual({
type: 'deployment-id',
})
expectSameAsNewContext(source)
}
})
it('falls back to a new context for a non-JSON body with the deployment ID suffix', () => {
const source = turbopackSource('/page', { deploymentId: true }).replace(
'{"moduleLoading":',
'{moduleLoading:'
)
expect(classifyClientReferenceManifestSource(source)).toEqual({
type: 'unknown',
})
expectSameAsNewContext(source)
})
it('recovers the reused context after a failing deployment ID evaluation', () => {
process.env.NEXT_DEPLOYMENT_ID = 'dpl_1'
// Recognized shape whose suffix throws because a chunk is not a string or
// an array.
const failing = turbopackSource('/bad/page', {
deploymentId: true,
value: { clientModules: { m: { chunks: null } } },
})
expect(classifyClientReferenceManifestSource(failing)).toEqual({
type: 'deployment-id',
})
expect(() => evalClientReferenceManifestSource(failing)).toThrow()
const source = turbopackSource('/page', { deploymentId: true })
const result = evalClientReferenceManifestSource(source)
expect(Object.keys(result.__RSC_MANIFEST!)).toEqual(['/page'])
expect(plain(result)).toEqual(plain(evalInNewContext(source)))
})
})
describe('evalManifest', () => {
const originalDeploymentId = process.env.NEXT_DEPLOYMENT_ID
let dir: string
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'eval-manifest-'))
})
afterEach(() => {
rmSync(dir, { recursive: true, force: true })
if (originalDeploymentId === undefined) {
delete process.env.NEXT_DEPLOYMENT_ID
} else {
process.env.NEXT_DEPLOYMENT_ID = originalDeploymentId
}
})
function write(name: string, source: string) {
const file = join(dir, name)
writeFileSync(file, source)
return file
}
it('caches and freezes the result', () => {
const cache = new Map<string, unknown>()
const file = write('page.js', webpackSource('/page'))
const result = evalManifest<any>(file, true, cache)
expect(plain(result.__RSC_MANIFEST['/page'])).toEqual(manifest)
expect(Object.isFrozen(result)).toBe(true)
expect(Object.isFrozen(result.__RSC_MANIFEST['/page'].clientModules)).toBe(
true
)
expect(evalManifest(file, true, cache)).toBe(result)
})
it('does not cache or freeze when caching is disabled', () => {
const cache = new Map<string, unknown>()
const file = write('page.js', turbopackSource('/page'))
const result = evalManifest<any>(file, false, cache)
expect(Object.isFrozen(result)).toBe(false)
expect(cache.size).toBe(0)
})
it('returns undefined for a missing file when handleMissing is set', () => {
const cache = new Map<string, unknown>()
expect(
evalManifest(join(dir, 'missing.js'), true, cache, true)
).toBeUndefined()
})
it('throws for an empty file', () => {
const file = write('empty.js', '')
expect(() => evalManifest(file, false)).toThrow('Manifest file is empty')
})
it('keeps frozen deployment ID results independent', () => {
const cache = new Map<string, unknown>()
process.env.NEXT_DEPLOYMENT_ID = 'dpl_a'
const a = evalManifest<any>(
write('a.js', turbopackSource('/a/page', { deploymentId: true })),
true,
cache
)
process.env.NEXT_DEPLOYMENT_ID = 'dpl_b'
const b = evalManifest<any>(
write('b.js', turbopackSource('/b/page', { deploymentId: true })),
true,
cache
)
expect(Object.isFrozen(a)).toBe(true)
expect(Object.keys(a.__RSC_MANIFEST)).toEqual(['/a/page'])
expect(Object.keys(b.__RSC_MANIFEST)).toEqual(['/b/page'])
expect(b.process.env.NEXT_DEPLOYMENT_ID).toBe('dpl_b')
expect(
b.__RSC_MANIFEST['/b/page'].clientModules[
'[project]/app/page.tsx <module evaluation>'
].chunks[0]
).toBe('static/chunks/a.js?dpl=dpl_b')
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment