Unverified Commit 28f84cea authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Durable use cache: fix next/image pulling in NEXT_DEPLOYMENT_ID (#98739)

If you do
```js
import Image from "next/image";

export function data(){
	"use cache: remote";
	return <Image .../>
}
```
then this previously ended up pulling in
`process.env.NEXT_DEPLOYMENT_ID` via
```
app/user-code.js
node_modules/next/image.js
node_modules/next/dist/shared/lib/image-external.js
node_modules/next/dist/shared/lib/get-img-props.js
node_modules/next/dist/shared/lib/deployment-id.js
```

But actually making `image-external.js` a barrel file ensures that we
don't pull in `get-img-props.js` when just importing the `Image` client
component. Then `NEXT_DEPLOYMENT_ID` isn't referenced anymore.
parent 3204d86c
......@@ -1951,6 +1951,21 @@ impl Project {
// `ends_with` is the correct matcher here.
static FEATURE_MODULE_PATH_SUFFIXES: &[(&str, &str)] = &[
("next/image", "/next/image.js"),
("next/image", "/next/dist/api/image.js"),
("next/image", "/next/dist/esm/api/image.js"),
// next/dist/api/image.js re-exports this module. When Turbopack can prove that
// the re-export has no side effects, it may flatten the re-export
// chain and leave this as the feature module in the graph.
("next/image", "/next/dist/client/image-component.js"),
("next/image", "/next/dist/esm/client/image-component.js"),
(
"next/image",
"/next/dist/shared/lib/image-external-get-image-props.js",
),
(
"next/image",
"/next/dist/esm/shared/lib/image-external-get-image-props.js",
),
("next/future/image", "/next/future/image.js"),
("next/legacy/image", "/next/legacy/image.js"),
("next/script", "/next/script.js"),
......@@ -2054,6 +2069,9 @@ impl Project {
module_graph.traverse_edges_unordered(|parent, node| {
if let Some((parent_node, _)) = parent
&& let Some(&feature) = matching.get(&node)
// A feature's public entry point may re-export another matched module. Only
// count the external importer, not the internal re-export edge.
&& matching.get(&parent_node) != Some(&feature)
{
pairs.insert((feature, parent_node));
}
......
......@@ -65,6 +65,11 @@ pub async fn get_next_client_import_map(
) -> Result<Vc<ImportMap>> {
let mut import_map = ImportMap::empty();
import_map.insert_exact_alias(
rcstr!("next/image"),
request_to_import_mapping(project_path.clone(), rcstr!("next/dist/api/image")),
);
insert_next_shared_aliases(
&mut import_map,
project_path.clone(),
......@@ -282,6 +287,11 @@ pub async fn get_next_server_import_map(
) -> Result<Vc<ImportMap>> {
let mut import_map = ImportMap::empty();
import_map.insert_exact_alias(
rcstr!("next/image"),
request_to_import_mapping(project_path.clone(), rcstr!("next/dist/api/image")),
);
insert_next_shared_aliases(
&mut import_map,
project_path.clone(),
......
export { default } from '../shared/lib/image-external'
export * from '../shared/lib/image-external'
'use turbopack: no side effects'
// This doesn't reexport from ../shared/lib/image-external.js to provide better tree shaking as ./shared/lib/image-external.js is usually a CJS file.
export { Image as default } from '../client/image-component'
export { getImageProps } from '../shared/lib/image-external-get-image-props'
export type * from '../shared/lib/image-external'
import type { ImageConfigComplete } from './image-config'
import type { ImageProps } from './get-img-props'
import { getImgProps } from './get-img-props'
// This is replaced by a bundler alias. Use a namespace import so a custom
// loader without a default export can reach the framework's runtime validation
// instead of failing static ESM export validation first.
import * as defaultLoaderModule from 'next/dist/shared/lib/image-loader'
const defaultLoader = Reflect.get(defaultLoaderModule, 'default')
/**
* For more advanced use cases, you can call `getImageProps()`
* to get the props that would be passed to the underlying `<img>` element,
* and instead pass to them to another component, style, canvas, etc.
*
* Read more: [Next.js docs: `getImageProps`](https://nextjs.org/docs/app/api-reference/components/image#getimageprops)
*/
export function getImageProps(imgProps: ImageProps) {
const { props } = getImgProps(imgProps, {
defaultLoader,
// This is replaced by webpack define plugin
imgConf: process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete,
})
// Normally we don't care about undefined props because we pass to JSX,
// but this exported function could be used by the end user for anything
// so we delete undefined props to clean it up a little.
for (const [key, value] of Object.entries(props)) {
if (value === undefined) {
delete props[key as keyof typeof props]
}
}
return { props }
}
import type { ImageConfigComplete, ImageLoaderProps } from './image-config'
'use turbopack: no side effects'
import type { ImageLoaderProps } from './image-config'
import type { ImageProps, ImageLoader, StaticImageData } from './get-img-props'
import { getImgProps } from './get-img-props'
import { Image } from '../../client/image-component'
// This is replaced by webpack alias
import defaultLoader from 'next/dist/shared/lib/image-loader'
/**
* For more advanced use cases, you can call `getImageProps()`
* to get the props that would be passed to the underlying `<img>` element,
* and instead pass to them to another component, style, canvas, etc.
*
* Read more: [Next.js docs: `getImageProps`](https://nextjs.org/docs/app/api-reference/components/image#getimageprops)
*/
export function getImageProps(imgProps: ImageProps) {
const { props } = getImgProps(imgProps, {
defaultLoader,
// This is replaced by webpack define plugin
imgConf: process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete,
})
// Normally we don't care about undefined props because we pass to JSX,
// but this exported function could be used by the end user for anything
// so we delete undefined props to clean it up a little.
for (const [key, value] of Object.entries(props)) {
if (value === undefined) {
delete props[key as keyof typeof props]
}
}
return { props }
}
export default Image
export { Image as default } from '../../client/image-component'
export { getImageProps } from './image-external-get-image-props'
export type { ImageProps, ImageLoaderProps, ImageLoader, StaticImageData }
import { getImageProps } from 'next/image'
async function logic() {
'use cache'
return getImageProps({
src: '/vercel.svg',
alt: 'Vercel Logo',
width: 72,
height: 16,
}).props.src
}
export default async function Page() {
return <p>{await logic()}</p>
}
......@@ -62,13 +62,6 @@ async function getCodeHashes(
})
it('lists non-inlined runtime env vars', async () => {
// TODO ideally app/next-image/page wouldn't include NEXT_DEPLOYMENT_ID.
// But currently the import chain
// next/image.js
// -> packages/next/src/shared/lib/get-img-props.ts
// -> packages/next/src/shared/lib/deployment-id.ts
// reads NEXT_DEPLOYMENT_ID
const data = await getCodeHashes(next)
expect(
Object.fromEntries(
......@@ -104,7 +97,7 @@ async function getCodeHashes(
"exist NEXT_PRIVATE_DEBUG_RUNTIME_DATA",
"exist NEXT_PRIVATE_DEBUG_VALIDATION",
],
"app/next-image/page": [
"app/next-image-props/page": [
"NEXT_OTEL_VERBOSE",
"NEXT_OTEL_PERFORMANCE_PREFIX",
"NEXT_SERVER_ACTIONS_ENCRYPTION_KEY",
......@@ -114,6 +107,15 @@ async function getCodeHashes(
"exist NEXT_PRIVATE_DEBUG_RUNTIME_DATA",
"exist NEXT_PRIVATE_DEBUG_VALIDATION",
],
"app/next-image/page": [
"NEXT_OTEL_VERBOSE",
"NEXT_OTEL_PERFORMANCE_PREFIX",
"NEXT_SERVER_ACTIONS_ENCRYPTION_KEY",
"exist NEXT_PRIVATE_DEBUG_CACHE",
"exist __NEXT_DEV_SERVER",
"exist NEXT_PRIVATE_DEBUG_RUNTIME_DATA",
"exist NEXT_PRIVATE_DEBUG_VALIDATION",
],
"app/use-cache-client/page": [
"NEXT_OTEL_VERBOSE",
"NEXT_OTEL_PERFORMANCE_PREFIX",
......
import { Suspense } from 'react'
import Image from 'next/image'
import { cacheLife } from 'next/cache'
import { connection } from 'next/server'
import { getDate } from '../logic'
async function DynamicCache() {
'use cache: remote'
cacheLife('days')
return (
<>
<Image
id="cached-image"
src="/vercel.svg"
alt="Vercel Logo"
width={72}
height={16}
/>
<span id="data">{getDate()}</span>
</>
)
}
export const instant = false
export default async function Page() {
await connection()
return (
<main>
<Suspense>
<DynamicCache />
</Suspense>
</main>
)
}
......@@ -15,6 +15,7 @@ async function execute(next: NextInstance, envKey: string, id: string) {
keyArgumentUseServer: string,
keyPrerender: string,
keyImportUseClient: string,
keyImportUseClientImage: string,
keyImportUseClientNested: string,
keyRoute: string,
dataRoot: string,
......@@ -24,8 +25,10 @@ async function execute(next: NextInstance, envKey: string, id: string) {
dataArgumentUseServer: string,
dataPrerender: string,
dataImportUseClient: string,
dataImportUseClientImage: string,
dataImportUseClientNested: string,
dataRoute: string
dataRoute: string,
imageSrc: string
{
const match = next.cliOutput.match(
/^CustomCacheHandler::get .* \[\["_N_T_\/layout","_N_T_\/prerender\/layout","_N_T_\/prerender\/page","_N_T_\/prerender"\]\]$/m
......@@ -53,6 +56,20 @@ async function execute(next: NextInstance, envKey: string, id: string) {
keyImportUseClient = matches.map((m) => m[0]).join('\n')
}
{
const logs = next.getCliOutputFromHere()
const browser = await next.browser(`/import-use-client-image`)
dataImportUseClientImage = await browser.elementById('data').text()
imageSrc = await browser.elementById('cached-image').getAttribute('src')
const matches = [
...logs().matchAll(
/^CustomCacheHandler::get .* \[\["_N_T_\/layout","_N_T_\/import-use-client-image\/layout","_N_T_\/import-use-client-image\/page","_N_T_\/import-use-client-image"\]\]$/gm
),
]
expect(matches).not.toBeEmpty()
keyImportUseClientImage = matches.map((m) => m[0]).join('\n')
}
{
const logs = next.getCliOutputFromHere()
const browser = await next.browser(`/import-use-client-nested`)
......@@ -145,6 +162,7 @@ async function execute(next: NextInstance, envKey: string, id: string) {
keyArgumentUseServer,
keyPrerender,
keyImportUseClient,
keyImportUseClientImage,
keyImportUseClientNested,
keyRoute,
dataRoot,
......@@ -154,8 +172,10 @@ async function execute(next: NextInstance, envKey: string, id: string) {
dataArgumentUseServer,
dataPrerender,
dataImportUseClient,
dataImportUseClientImage,
dataImportUseClientNested,
dataRoute,
imageSrc,
}
} finally {
if (envKey !== 'default') {
......@@ -190,6 +210,13 @@ describe.each(['NEXT_DEPLOYMENT_ID', 'BUILD_ID', 'default'])(
expect(key1.keyImportUseClient).not.toBe(key2.keyImportUseClient)
expect(key1.dataImportUseClient).not.toBe(key2.dataImportUseClient)
expect(key1.keyImportUseClientImage).not.toBe(
key2.keyImportUseClientImage
)
expect(key1.dataImportUseClientImage).not.toBe(
key2.dataImportUseClientImage
)
expect(key1.keyImportUseClientNested).not.toBe(
key2.keyImportUseClientNested
)
......@@ -268,6 +295,11 @@ describe.each(['NEXT_DEPLOYMENT_ID', 'BUILD_ID', 'default'])(
expect(key1.keyImportUseClient).toBe(key2.keyImportUseClient)
expect(key1.dataImportUseClient).toBe(key2.dataImportUseClient)
expect(key1.keyImportUseClientImage).toBe(key2.keyImportUseClientImage)
expect(key1.dataImportUseClientImage).toBe(key2.dataImportUseClientImage)
expect(key1.imageSrc).toContain('dpl=dpl-id-1')
expect(key2.imageSrc).toContain('dpl=dpl-id-2')
expect(key1.keyImportUseClientNested).toBe(key2.keyImportUseClientNested)
expect(key1.dataImportUseClientNested).toBe(
key2.dataImportUseClientNested
......@@ -298,6 +330,14 @@ describe.each(['NEXT_DEPLOYMENT_ID', 'BUILD_ID', 'default'])(
expect(key1.dataImportUseClient).not.toBe(key2.dataImportUseClient)
expect(key2.dataImportUseClient).toBe(value)
expect(key1.keyImportUseClientImage).not.toBe(
key2.keyImportUseClientImage
)
expect(key1.dataImportUseClientImage).not.toBe(
key2.dataImportUseClientImage
)
expect(key2.dataImportUseClientImage).toBe(value)
expect(key1.keyImportUseClientNested).not.toBe(
key2.keyImportUseClientNested
)
......
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