Unverified Commit 26cfeb85 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Allow overriding outputHashSalt in modifyConfig (#92856)

parent f4972228
......@@ -370,11 +370,6 @@ pub struct ProjectOptions {
/// Whether server-side HMR is enabled (disabled with --no-server-fast-refresh).
pub server_hmr: bool,
/// A salt to mix into chunk and asset content hashes, allowing users to
/// force new filenames without changing file content. Empty string means
/// no salt.
pub hash_salt: RcStr,
}
#[derive(Default)]
......@@ -425,9 +420,6 @@ pub struct PartialProjectOptions {
/// Debug build paths for selective builds.
/// When set, only routes matching these paths will be included in the build.
pub debug_build_paths: Option<DebugBuildPaths>,
/// An optional salt to mix into chunk and asset content hashes.
pub hash_salt: Option<RcStr>,
}
#[derive(
......@@ -687,7 +679,6 @@ impl ProjectContainer {
no_mangling,
write_routes_hashes_manifest,
debug_build_paths,
hash_salt,
} = options;
let mut new_options = this
......@@ -738,9 +729,6 @@ impl ProjectContainer {
if let Some(debug_build_paths) = debug_build_paths {
new_options.debug_build_paths = Some(debug_build_paths);
}
if let Some(hash_salt) = hash_salt {
new_options.hash_salt = hash_salt;
}
// TODO: Handle mode switch, should prevent mode being switched.
let watch = new_options.watch;
......@@ -823,7 +811,6 @@ impl ProjectContainer {
let deferred_entries;
let is_persistent_caching_enabled;
let server_hmr;
let hash_salt;
{
let options = self.options_state.get();
let options = options
......@@ -852,7 +839,6 @@ impl ProjectContainer {
deferred_entries = options.deferred_entries.clone().unwrap_or_default();
is_persistent_caching_enabled = options.is_persistent_caching_enabled;
server_hmr = options.server_hmr;
hash_salt = options.hash_salt.clone();
}
let root_path = ResolvedVc::cell(root_path_str);
......@@ -884,7 +870,6 @@ impl ProjectContainer {
deferred_entries,
is_persistent_caching_enabled,
server_hmr,
hash_salt,
}
.cell())
}
......@@ -988,10 +973,6 @@ pub struct Project {
/// Whether server-side HMR is enabled (disabled with --no-server-fast-refresh).
server_hmr: bool,
/// A salt to mix into chunk and asset content hashes. Empty string means
/// no salt.
hash_salt: RcStr,
}
#[turbo_tasks::value]
......@@ -1249,11 +1230,6 @@ impl Project {
Vc::cell(self.no_mangling)
}
#[turbo_tasks::function]
pub(crate) fn hash_salt(&self) -> Vc<RcStr> {
Vc::cell(self.hash_salt.clone())
}
#[turbo_tasks::function]
pub(super) async fn execution_context(self: Vc<Self>) -> Result<Vc<ExecutionContext>> {
let node_root = self.node_root().owned().await?;
......@@ -1609,7 +1585,7 @@ impl Project {
debug_ids: self.next_config().turbopack_debug_ids(),
should_use_absolute_url_references: self.next_config().inline_css(),
css_url_suffix,
hash_salt: self.hash_salt().to_resolved().await?,
hash_salt: self.next_config().output_hash_salt().to_resolved().await?,
cross_origin: self.next_config().cross_origin(),
}))
}
......@@ -1645,7 +1621,7 @@ impl Project {
.await?,
asset_prefix: self.next_config().computed_asset_prefix().owned().await?,
css_url_suffix,
hash_salt: self.hash_salt().to_resolved().await?,
hash_salt: self.next_config().output_hash_salt().to_resolved().await?,
};
Ok(if client_assets {
get_server_chunking_context_with_client_assets(options)
......@@ -1684,7 +1660,7 @@ impl Project {
.await?,
asset_prefix: self.next_config().computed_asset_prefix().owned().await?,
css_url_suffix,
hash_salt: self.hash_salt().to_resolved().await?,
hash_salt: self.next_config().output_hash_salt().to_resolved().await?,
cross_origin: self.next_config().cross_origin(),
};
Ok(if client_assets {
......
......@@ -143,7 +143,10 @@ impl Asset for AssetHashesManifestAsset {
Ok((
path,
asset
.content_hash(self.project.hash_salt(), HashAlgorithm::Xxh3Hash128Base38)
.content_hash(
self.project.next_config().output_hash_salt(),
HashAlgorithm::Xxh3Hash128Base38,
)
.await?,
))
})
......
......@@ -190,7 +190,6 @@ fn main() {
is_persistent_caching_enabled: false,
next_version: rcstr!("0.0.0"),
server_hmr: false,
hash_salt: rcstr!(""),
};
let json = serde_json::to_string_pretty(&options).unwrap();
......
......@@ -1090,6 +1090,10 @@ pub struct ExperimentalConfig {
runtime_server_deployment_id: Option<bool>,
supports_immutable_assets: Option<bool>,
/// A salt to mix into chunk and asset content hashes. Empty string means
/// no salt.
output_hash_salt: Option<RcStr>,
// ---
// UNSUPPORTED
// ---
......@@ -2349,6 +2353,16 @@ impl NextConfig {
.collect::<Result<Vec<_>>>()?;
Ok(Vc::cell(rules))
}
#[turbo_tasks::function]
pub fn output_hash_salt(&self) -> Vc<RcStr> {
Vc::cell(
self.experimental
.output_hash_salt
.clone()
.unwrap_or_default(),
)
}
}
/// A subset of ts/jsconfig that next.js implicitly
......
......@@ -216,11 +216,6 @@ pub struct NapiProjectOptions {
/// Whether server-side HMR is enabled (disabled with --no-server-fast-refresh).
pub server_hmr: Option<bool>,
/// A salt to mix into chunk and asset content hashes, allowing users to
/// force new filenames without changing file content. Empty string means
/// no salt.
pub hash_salt: RcStr,
}
/// [NapiProjectOptions] with all fields optional.
......@@ -271,9 +266,6 @@ pub struct NapiPartialProjectOptions {
/// local names for variables, functions etc., which can be useful for
/// debugging/profiling purposes.
pub no_mangling: Option<bool>,
/// An optional salt to mix into chunk and asset content hashes.
pub hash_salt: Option<RcStr>,
}
#[napi(object)]
......@@ -334,7 +326,6 @@ impl From<NapiProjectOptions> for ProjectOptions {
is_persistent_caching_enabled,
next_version,
server_hmr,
hash_salt,
} = val;
ProjectOptions {
root_path,
......@@ -359,7 +350,6 @@ impl From<NapiProjectOptions> for ProjectOptions {
is_persistent_caching_enabled,
next_version,
server_hmr: server_hmr.unwrap_or(false),
hash_salt,
}
}
}
......@@ -380,7 +370,6 @@ impl From<NapiPartialProjectOptions> for PartialProjectOptions {
browserslist_query,
no_mangling,
write_routes_hashes_manifest,
hash_salt,
} = val;
PartialProjectOptions {
root_path,
......@@ -397,7 +386,6 @@ impl From<NapiPartialProjectOptions> for PartialProjectOptions {
no_mangling,
write_routes_hashes_manifest,
debug_build_paths: None,
hash_salt,
}
}
}
......
......@@ -258,12 +258,6 @@ export interface NapiProjectOptions {
nextVersion: RcStr
/** Whether server-side HMR is enabled (disabled with --no-server-fast-refresh). */
serverHmr?: boolean
/**
* A salt to mix into chunk and asset content hashes, allowing users to
* force new filenames without changing file content. Empty string means
* no salt.
*/
hashSalt: RcStr
}
/** [NapiProjectOptions] with all fields optional. */
export interface NapiPartialProjectOptions {
......@@ -308,8 +302,6 @@ export interface NapiPartialProjectOptions {
* debugging/profiling purposes.
*/
noMangling?: boolean
/** An optional salt to mix into chunk and asset content hashes. */
hashSalt?: RcStr
}
export interface NapiDefineEnv {
client: Array<NapiOptionEnvVar>
......
......@@ -91,7 +91,6 @@ export async function turbopackAnalyze(
currentNodeJsVersion,
isPersistentCachingEnabled: persistentCaching,
nextVersion: process.env.__NEXT_VERSION as string,
hashSalt: config.hashSalt,
},
{
memoryLimit: config.experimental?.turbopackMemoryLimit,
......
......@@ -114,7 +114,6 @@ export async function turbopackBuild(): Promise<{
isPersistentCachingEnabled: persistentCaching,
deferredEntries: config.experimental.deferredEntries,
nextVersion: process.env.__NEXT_VERSION as string,
hashSalt: config.hashSalt,
}
const sharedTurboOptions = {
......
......@@ -1347,7 +1347,9 @@ export default async function getBaseWebpackConfig(
hashDigestLength: 16,
// Webpack requires hashSalt to be a non-empty string; omit it entirely
// when no salt is configured.
...(config.hashSalt ? { hashSalt: config.hashSalt } : {}),
...(config.experimental?.outputHashSalt
? { hashSalt: config.experimental.outputHashSalt }
: {}),
},
performance: false,
resolve: resolveConfig,
......@@ -1799,7 +1801,7 @@ export default async function getBaseWebpackConfig(
compilerType,
basePath: config.basePath,
assetPrefix: config.assetPrefix,
hashSalt: config.hashSalt,
outputHashSalt: config.experimental?.outputHashSalt,
},
},
]
......
......@@ -10,21 +10,22 @@ interface Options {
isDev: boolean
assetPrefix: string
basePath: string
hashSalt: string
outputHashSalt: string
}
function nextImageLoader(this: any, content: Buffer) {
const imageLoaderSpan = this.currentTraceSpan.traceChild('next-image-loader')
return imageLoaderSpan.traceAsyncFn(async () => {
const options: Options = this.getOptions()
const { compilerType, isDev, assetPrefix, basePath, hashSalt } = options
const { compilerType, isDev, assetPrefix, basePath, outputHashSalt } =
options
const context = this.rootContext
// Prepend the hash salt to the content for filename hash computation, so
// that NEXT_HASH_SALT causes image filenames to change (like it does for
// chunks). The actual file content is unaffected.
const contentForHash = hashSalt
? Buffer.concat([Buffer.from(hashSalt, 'utf8'), content])
const contentForHash = outputHashSalt
? Buffer.concat([Buffer.from(outputHashSalt, 'utf8'), content])
: content
const opts = { context, content: contentForHash }
const interpolatedName = loaderUtils.interpolateName(
......
......@@ -40,9 +40,6 @@ export type NextConfigComplete = Required<Omit<NextConfig, 'configFile'>> & {
// since development builds use `{distDir}/dev`. This is used to ensure that the bundler doesn't
// traverse into the output directory.
distDirRoot: string
// Pre-computed effective hash salt: experimental.outputHashSalt (from config)
// concatenated with NEXT_HASH_SALT (from env). Used by both Webpack and Turbopack.
hashSalt: string
}
export type I18NDomains = readonly DomainLocale[]
......
......@@ -1045,6 +1045,11 @@ function assignDefaultsAndValidate(
result.experimental.supportsImmutableAssets = true
}
if (process.env.NEXT_HASH_SALT) {
result.experimental.outputHashSalt =
(result.experimental.outputHashSalt ?? '') + process.env.NEXT_HASH_SALT
}
const tracingRoot = result?.outputFileTracingRoot
const turbopackRoot = result?.turbopack?.root
......@@ -1516,10 +1521,7 @@ function assignDefaultsAndValidate(
// Store the distDirRoot in the config before it is modified for development mode
;(result as NextConfigComplete).distDirRoot = result.distDir
// Pre-compute the effective hash salt (used by both Webpack and Turbopack).
;(result as NextConfigComplete).hashSalt =
(result.experimental?.outputHashSalt ?? '') +
(process.env.NEXT_HASH_SALT ?? '')
if (phase === PHASE_DEVELOPMENT_SERVER) {
result.distDir = join(result.distDir, 'dev')
}
......
......@@ -414,7 +414,6 @@ export async function createHotReloaderTurbopack(
),
nextVersion: process.env.__NEXT_VERSION as string,
serverHmr: serverFastRefresh,
hashSalt: opts.nextConfig.hashSalt,
},
{
memoryLimit: opts.nextConfig.experimental?.turbopackMemoryLimit,
......
......@@ -233,7 +233,6 @@ async function main() {
currentNodeJsVersion: '18.0.0',
isPersistentCachingEnabled: false,
nextVersion: '0.0.0',
hashSalt: '',
});
const entrypointsSubscription = project.entrypointsSubscribe();
......@@ -394,7 +393,6 @@ describe('next.rs api', () => {
currentNodeJsVersion: '18.0.0',
isPersistentCachingEnabled: false,
nextVersion: '0.0.0',
hashSalt: '',
})
projectUpdateSubscription = filterMapAsyncIterator(
project.updateInfoSubscribe(1000),
......
......@@ -83,45 +83,68 @@ describe('experimental.outputHashSalt', () => {
async function buildWithSalts(opts: {
configSalt?: string
envSalt?: string
adapterSalt?: string
}) {
const env: Record<string, string> = {}
if (opts.configSalt) env.OUTPUT_HASH_SALT_CONFIG = opts.configSalt
if (opts.envSalt) env.NEXT_HASH_SALT = opts.envSalt
if (opts.adapterSalt) env.ADAPTER_HASH_SALT = opts.adapterSalt
await next.clean()
await next.build({ env })
const chunks = (
await listClientChunks(join(next.testDir, next.distDir))
).filter((f) => f.includes('/chunks/') && f.endsWith('.js'))
return chunks
return chunks.sort()
}
let noSaltChunks: string[]
let configOnlyChunks: string[]
let envOnlyChunks: string[]
let bothChunks: string[]
let adapterEnvOnlyChunks: string[]
let configAndEnvChunks: string[]
let configAndAdapterEnvChunks: string[]
let envAndAdapterEnvChunks: string[]
beforeAll(
async () => {
noSaltChunks = await buildWithSalts({})
configOnlyChunks = await buildWithSalts({ configSalt: 'config-salt' })
envOnlyChunks = await buildWithSalts({ envSalt: 'env-salt' })
bothChunks = await buildWithSalts({
adapterEnvOnlyChunks = await buildWithSalts({
adapterSalt: 'adapter-salt',
})
configAndEnvChunks = await buildWithSalts({
configSalt: 'config-salt',
envSalt: 'env-salt',
})
configAndAdapterEnvChunks = await buildWithSalts({
configSalt: 'config-salt',
adapterSalt: 'adapter-salt',
})
envAndAdapterEnvChunks = await buildWithSalts({
envSalt: 'env-salt',
adapterSalt: 'adapter-salt',
})
},
5 * 60 * 1000
)
it('config salt changes filenames compared to no salt', () => {
expect(configOnlyChunks.sort()).not.toEqual(noSaltChunks.sort())
expect(configOnlyChunks).not.toEqual(noSaltChunks)
})
it('config-and-env salt differs', () => {
expect(configAndEnvChunks).not.toEqual(envOnlyChunks)
expect(configAndEnvChunks).not.toEqual(configOnlyChunks)
})
it('combined salt differs from env-var-only salt', () => {
expect(bothChunks.sort()).not.toEqual(envOnlyChunks.sort())
it('config-and-adapter-env salt differs', () => {
expect(configAndAdapterEnvChunks).not.toEqual(configOnlyChunks)
expect(configAndAdapterEnvChunks).not.toEqual(adapterEnvOnlyChunks)
})
it('combined salt differs from config-only salt', () => {
expect(bothChunks.sort()).not.toEqual(configOnlyChunks.sort())
it('env-and-adapter-env salt differs', () => {
expect(envAndAdapterEnvChunks).not.toEqual(envOnlyChunks)
expect(envAndAdapterEnvChunks).not.toEqual(adapterEnvOnlyChunks)
})
})
// @ts-check
/** @type {import('next').NextAdapter } */
const myAdapter = {
name: 'my-custom-adapter',
modifyConfig: (config) => {
if (process.env.ADAPTER_HASH_SALT != null) {
config.experimental.outputHashSalt =
(config.experimental.outputHashSalt ?? '') +
process.env.ADAPTER_HASH_SALT
}
return config
},
}
export default myAdapter
......@@ -4,4 +4,5 @@ module.exports = {
// Allow tests to inject outputHashSalt via env var without touching source.
outputHashSalt: process.env.OUTPUT_HASH_SALT_CONFIG || undefined,
},
adapterPath: require.resolve('./my-adapter.mjs'),
}
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