Unverified Commit 689f6fe3 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Add `NEXT_DEPLOYMENT_ID` global (#86738)

- Adds a `process.env.NEXT_DEPLOYMENT_ID` -> `globalThis.NEXT_DEPLOYMENT_ID` replacement
- On startup, `globalThis.NEXT_DEPLOYMENT_ID` is initialized to `process.env.NEXT_DEPLOYMENT_ID_COMPILE_TIME`

This prepares for https://github.com/vercel/next.js/pull/88761 to replace `process.env.NEXT_DEPLOYMENT_ID_COMPILE_TIME` with reading `<html data-dpl-id>` so that we can remove the env var inlining

However, all of this is only done for Turbopack, because we cannot forward `globalThis.NEXT_DEPLOYMENT_ID` to web workers with Webpack easily.
parent 363783db
......@@ -41,11 +41,14 @@ export interface DefineEnvOptions {
}
}
const DEFINE_ENV_EXPRESSION = Symbol('DEFINE_ENV_EXPRESSION')
interface DefineEnv {
[key: string]:
| string
| string[]
| boolean
| { [DEFINE_ENV_EXPRESSION]: string }
| ProxyMatcher[]
| BloomFilter
| Partial<NextConfigComplete['images']>
......@@ -64,7 +67,9 @@ function serializeDefineEnv(defineEnv: DefineEnv): SerializedDefineEnv {
const defineEnvStringified: SerializedDefineEnv = Object.fromEntries(
Object.entries(defineEnv).map(([key, value]) => [
key,
JSON.stringify(value),
typeof value === 'object' && DEFINE_ENV_EXPRESSION in value
? value[DEFINE_ENV_EXPRESSION]
: JSON.stringify(value),
])
)
return defineEnvStringified
......@@ -165,23 +170,32 @@ export function getDefineEnv({
'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled,
'process.env.__NEXT_USE_CACHE': isUseCacheEnabled,
...(isClient
...(config.experimental?.useSkewCookie || !config.deploymentId
? {
// TODO use `globalThis.NEXT_DEPLOYMENT_ID` on client to still support accessing
// process.env.NEXT_DEPLOYMENT_ID in userland
'process.env.NEXT_DEPLOYMENT_ID': config.experimental?.useSkewCookie
? false
: config.deploymentId || false,
'process.env.NEXT_DEPLOYMENT_ID': false,
}
: config.experimental?.runtimeServerDeploymentId
? {
// Don't inline at all, keep process.env.NEXT_DEPLOYMENT_ID as is
}
: {
'process.env.NEXT_DEPLOYMENT_ID': config.experimental?.useSkewCookie
? false
: config.deploymentId || false,
}),
: isClient
? isTurbopack
? {
'process.env.NEXT_DEPLOYMENT_ID': {
[DEFINE_ENV_EXPRESSION]: 'globalThis.NEXT_DEPLOYMENT_ID',
},
// TODO replace with read from HTML document attribute
'process.env.NEXT_DEPLOYMENT_ID_COMPILE_TIME':
config.deploymentId,
}
: {
// For Webpack, we currently don't use the non-inlining globalThis.NEXT_DEPLOYMENT_ID
// approach because we cannot forward this global variable to web workers easily.
'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || false,
}
: config.experimental?.runtimeServerDeploymentId
? {
// Don't inline at all, keep process.env.NEXT_DEPLOYMENT_ID as is
}
: {
'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || false,
}),
// Propagates the `__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING` environment
// variable to the client.
......
import './register-deployment-id-global'
import { appBootstrap } from './app-bootstrap'
import { isRecoverableError } from './react-client-callbacks/on-recoverable-error'
......
// Override chunk URL mapping in the webpack runtime
// https://github.com/webpack/webpack/blob/2738eebc7880835d88c727d364ad37f3ec557593/lib/RuntimeGlobals.js#L204
import { getDeploymentIdQueryOrEmptyString } from '../shared/lib/deployment-id'
import './register-deployment-id-global'
import {
getDeploymentId,
getDeploymentIdQueryOrEmptyString,
} from '../shared/lib/deployment-id'
import { encodeURIPath } from '../shared/lib/encode-uri-path'
declare const __webpack_require__: any
// If we have a deployment ID, we need to append it to the webpack chunk names
// I am keeping the process check explicit so this can be statically optimized
if (process.env.NEXT_DEPLOYMENT_ID) {
if (getDeploymentId()) {
const suffix = getDeploymentIdQueryOrEmptyString()
const getChunkScriptFilename = __webpack_require__.u
__webpack_require__.u = (...args: any[]) =>
......
// TODO: Remove use of `any` type.
import './register-deployment-id-global'
import { initialize, version, router, emitter } from './'
import initHMR from './dev/hot-middleware-client'
......
// TODO: Remove use of `any` type.
import './register-deployment-id-global'
import './webpack'
import { initialize, version, router, emitter } from './'
import initHMR from './dev/hot-middleware-client'
......
// A client-side entry point for Turbopack builds. Includes logic to load chunks,
// but does not include development-time features like hot module reloading.
import './register-deployment-id-global'
import '../lib/require-instrumentation-client'
// TODO: Remove use of `any` type.
......
import './register-deployment-id-global'
import './webpack'
import '../lib/require-instrumentation-client'
......
import { getDeploymentId } from '../shared/lib/deployment-id'
;(globalThis as any).NEXT_DEPLOYMENT_ID = getDeploymentId()
// This could also be a variable instead of a function, but some unit tests want to change the ID at
// runtime. Even though that would never happen in a real deployment.
export function getDeploymentId(): string | undefined {
return process.env.NEXT_DEPLOYMENT_ID
return (
process.env.NEXT_DEPLOYMENT_ID ??
process.env.NEXT_DEPLOYMENT_ID_COMPILE_TIME
)
}
export function getDeploymentIdQueryOrEmptyString(): string {
......
const deploymentId = process.env.NEXT_DEPLOYMENT_ID
self.postMessage(deploymentId)
'use client'
import { useState } from 'react'
export default function Home() {
const [workerDeploymentId, setWorkerDeploymentId] = useState('default')
const mainDeploymentId = process.env.NEXT_DEPLOYMENT_ID
return (
<div>
<button
onClick={() => {
const worker = new Worker(
new URL('../deployment-id-worker', import.meta.url),
{
type: 'module',
}
)
worker.addEventListener('message', (event) => {
setWorkerDeploymentId(event.data)
})
}}
>
Get deployment ID from worker
</button>
<p>
Main deployment ID:{' '}
<span id="main-deployment-id">{mainDeploymentId}</span>
</p>
<p>
Worker deployment ID:{' '}
<span id="worker-deployment-id">{workerDeploymentId}</span>
</p>
</div>
)
}
......@@ -68,4 +68,32 @@ describe('app dir - workers', () => {
)
)
})
it('should have access to NEXT_DEPLOYMENT_ID in web worker', async () => {
const browser = await next.browser('/deployment-id', {
beforePageLoad,
})
// Verify main thread has deployment ID and it's not empty
const mainDeploymentId = await browser
.elementByCss('#main-deployment-id')
.text()
expect(mainDeploymentId).toBe('test-deployment-id')
// Initial worker state should be default
expect(await browser.elementByCss('#worker-deployment-id').text()).toBe(
'default'
)
// Trigger worker to get deployment ID
await browser.elementByCss('button').click()
// Wait for worker to respond and verify it matches main thread
await retry(async () => {
const workerDeploymentId = await browser
.elementByCss('#worker-deployment-id')
.text()
expect(workerDeploymentId).toBe('test-deployment-id')
})
})
})
/* eslint-env jest */
import { getImageProps } from 'next/image'
let deploymentId
jest.mock('next/dist/shared/lib/deployment-id.js', () => {
return {
__esModule: true,
getDeploymentId() {
return deploymentId
},
}
})
describe('getImageProps()', () => {
let warningMessages: string[]
const originalConsoleWarn = console.warn
......@@ -9,6 +20,7 @@ describe('getImageProps()', () => {
console.warn = (m: string) => {
warningMessages.push(m)
}
deploymentId = undefined
})
afterEach(() => {
......@@ -612,7 +624,7 @@ describe('getImageProps()', () => {
})
it('should add query string for imported local image when NEXT_DEPLOYMENT_ID defined', async () => {
try {
process.env.NEXT_DEPLOYMENT_ID = 'dpl_123'
deploymentId = 'dpl_123'
const { props } = getImageProps({
alt: 'a nice desc',
src: '/_next/static/media/test.abc123.png',
......@@ -637,12 +649,12 @@ describe('getImageProps()', () => {
],
])
} finally {
delete process.env.NEXT_DEPLOYMENT_ID
deploymentId = undefined
}
})
it('should add query string for imported local image from microfrontend when NEXT_DEPLOYMENT_ID defined', async () => {
try {
process.env.NEXT_DEPLOYMENT_ID = 'dpl_123'
deploymentId = 'dpl_123'
const { props } = getImageProps({
alt: 'a nice desc',
src: '/microfrontend/_next/static/media/test.abc123.png', // simulating microfrontend path
......@@ -667,12 +679,12 @@ describe('getImageProps()', () => {
],
])
} finally {
delete process.env.NEXT_DEPLOYMENT_ID
deploymentId = undefined
}
})
it('should add query string for relative local image when NEXT_DEPLOYMENT_ID defined', async () => {
try {
process.env.NEXT_DEPLOYMENT_ID = 'dpl_123'
deploymentId = 'dpl_123'
const { props } = getImageProps({
alt: 'a nice desc',
src: '/test.png',
......@@ -694,12 +706,12 @@ describe('getImageProps()', () => {
['src', '/_next/image?url=%2Ftest.png&w=256&q=75&dpl=dpl_123'],
])
} finally {
delete process.env.NEXT_DEPLOYMENT_ID
deploymentId = undefined
}
})
it('should not add query string for absolute remote image when NEXT_DEPLOYMENT_ID defined', async () => {
try {
process.env.NEXT_DEPLOYMENT_ID = 'dpl_123'
deploymentId = 'dpl_123'
const { props } = getImageProps({
alt: 'a nice desc',
src: 'http://example.com/test.png',
......@@ -724,12 +736,12 @@ describe('getImageProps()', () => {
],
])
} finally {
delete process.env.NEXT_DEPLOYMENT_ID
deploymentId = undefined
}
})
it('should add query string with question mark for unoptimized relative svg when NEXT_DEPLOYMENT_ID defined', async () => {
try {
process.env.NEXT_DEPLOYMENT_ID = 'dpl_123'
deploymentId = 'dpl_123'
const { props } = getImageProps({
alt: 'a nice desc',
src: '/test.svg',
......@@ -747,12 +759,12 @@ describe('getImageProps()', () => {
['src', '/test.svg?dpl=dpl_123'],
])
} finally {
delete process.env.NEXT_DEPLOYMENT_ID
deploymentId = undefined
}
})
it('should add query string with ampersand for unoptimized relative svg when NEXT_DEPLOYMENT_ID defined', async () => {
try {
process.env.NEXT_DEPLOYMENT_ID = 'dpl_123'
deploymentId = 'dpl_123'
const { props } = getImageProps({
alt: 'a nice desc',
src: '/test.svg?v=1',
......@@ -770,12 +782,12 @@ describe('getImageProps()', () => {
['src', '/test.svg?v=1&dpl=dpl_123'],
])
} finally {
delete process.env.NEXT_DEPLOYMENT_ID
deploymentId = undefined
}
})
it('should not add query string for unoptimized absolute remote svg when NEXT_DEPLOYMENT_ID defined', async () => {
try {
process.env.NEXT_DEPLOYMENT_ID = 'dpl_123'
deploymentId = 'dpl_123'
const { props } = getImageProps({
alt: 'a nice desc',
src: 'http://example.com/test.svg',
......@@ -793,12 +805,12 @@ describe('getImageProps()', () => {
['src', 'http://example.com/test.svg'],
])
} finally {
delete process.env.NEXT_DEPLOYMENT_ID
deploymentId = undefined
}
})
it('should not add query string for unoptimized with no protocol when NEXT_DEPLOYMENT_ID defined', async () => {
try {
process.env.NEXT_DEPLOYMENT_ID = 'dpl_123'
deploymentId = 'dpl_123'
const { props } = getImageProps({
alt: 'a nice desc',
src: '//example.com/test.png',
......@@ -817,7 +829,7 @@ describe('getImageProps()', () => {
['src', '//example.com/test.png'],
])
} finally {
delete process.env.NEXT_DEPLOYMENT_ID
deploymentId = undefined
}
})
})
......@@ -323,6 +323,7 @@ function getWorkerBlobURL(chunks: ChunkPath[]): string {
// evaluated by poping urls off of this array. See `getPathFromScript`
let bootstrap = `self.TURBOPACK_WORKER_LOCATION = ${JSON.stringify(location.origin)};
self.TURBOPACK_CHUNK_SUFFIX = ${JSON.stringify(CHUNK_SUFFIX)};
self.NEXT_DEPLOYMENT_ID = ${JSON.stringify((globalThis as any).NEXT_DEPLOYMENT_ID)};
self.TURBOPACK_NEXT_CHUNK_URLS = ${JSON.stringify(chunks.reverse().map(getChunkRelativeUrl), null, 2)};
importScripts(...self.TURBOPACK_NEXT_CHUNK_URLS.map(c => self.TURBOPACK_WORKER_LOCATION + c).reverse());`
let blob = new Blob([bootstrap], { type: 'text/javascript' })
......
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="ae0c8767-ff94-abb9-fa13-d8c5ded28f9e")}catch(e){}}();
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="3834607a-5e38-b3f2-d7f2-094bfde98e30")}catch(e){}}();
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push([
"output/ba425_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js",
{"otherChunks":["output/aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0b8736b3.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]}
......@@ -691,6 +691,7 @@ browserContextPrototype.P = resolveAbsolutePath;
// evaluated by poping urls off of this array. See `getPathFromScript`
let bootstrap = `self.TURBOPACK_WORKER_LOCATION = ${JSON.stringify(location.origin)};
self.TURBOPACK_CHUNK_SUFFIX = ${JSON.stringify(CHUNK_SUFFIX)};
self.NEXT_DEPLOYMENT_ID = ${JSON.stringify(globalThis.NEXT_DEPLOYMENT_ID)};
self.TURBOPACK_NEXT_CHUNK_URLS = ${JSON.stringify(chunks.reverse().map(getChunkRelativeUrl), null, 2)};
importScripts(...self.TURBOPACK_NEXT_CHUNK_URLS.map(c => self.TURBOPACK_WORKER_LOCATION + c).reverse());`;
let blob = new Blob([
......@@ -1861,5 +1862,5 @@ chunkListsToRegister.forEach(registerChunkList);
})();
//# debugId=ae0c8767-ff94-abb9-fa13-d8c5ded28f9e
//# debugId=3834607a-5e38-b3f2-d7f2-094bfde98e30
//# sourceMappingURL=aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js.map
\ No newline at end of file
......@@ -690,6 +690,7 @@ browserContextPrototype.P = resolveAbsolutePath;
// evaluated by poping urls off of this array. See `getPathFromScript`
let bootstrap = `self.TURBOPACK_WORKER_LOCATION = ${JSON.stringify(location.origin)};
self.TURBOPACK_CHUNK_SUFFIX = ${JSON.stringify(CHUNK_SUFFIX)};
self.NEXT_DEPLOYMENT_ID = ${JSON.stringify(globalThis.NEXT_DEPLOYMENT_ID)};
self.TURBOPACK_NEXT_CHUNK_URLS = ${JSON.stringify(chunks.reverse().map(getChunkRelativeUrl), null, 2)};
importScripts(...self.TURBOPACK_NEXT_CHUNK_URLS.map(c => self.TURBOPACK_WORKER_LOCATION + c).reverse());`;
let blob = new Blob([
......
......@@ -1188,6 +1188,7 @@ browserContextPrototype.P = resolveAbsolutePath;
// evaluated by poping urls off of this array. See `getPathFromScript`
var bootstrap = `self.TURBOPACK_WORKER_LOCATION = ${JSON.stringify(location.origin)};
self.TURBOPACK_CHUNK_SUFFIX = ${JSON.stringify(CHUNK_SUFFIX)};
self.NEXT_DEPLOYMENT_ID = ${JSON.stringify(globalThis.NEXT_DEPLOYMENT_ID)};
self.TURBOPACK_NEXT_CHUNK_URLS = ${JSON.stringify(chunks.reverse().map(getChunkRelativeUrl), null, 2)};
importScripts(...self.TURBOPACK_NEXT_CHUNK_URLS.map(c => self.TURBOPACK_WORKER_LOCATION + c).reverse());`;
var blob = new Blob([
......
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