diff --git a/packages/angular/build/src/builders/application/execute-build.ts b/packages/angular/build/src/builders/application/execute-build.ts index 7fc43de92b00..16cf5b76fce8 100644 --- a/packages/angular/build/src/builders/application/execute-build.ts +++ b/packages/angular/build/src/builders/application/execute-build.ts @@ -393,9 +393,11 @@ export async function executeBuild( ); } + let localizedNames: Map | undefined; // Perform i18n translation inlining if enabled if (i18nOptions.shouldInline) { const result = await inlineI18n(browserMetafile, options, executionResult, initialFiles); + localizedNames = result.renamedFiles; executionResult.addErrors(result.errors); executionResult.addWarnings(result.warnings); executionResult.addPrerenderedRoutes(result.prerenderedRoutes); @@ -427,11 +429,32 @@ export async function executeBuild( ); } + let statsMetafile = browserMetafile; + if (options.stats && localizedNames?.size) { + const names = localizedNames; + statsMetafile = { + ...browserMetafile, + outputs: Object.fromEntries( + Object.entries(browserMetafile.outputs).map(([path, output]) => [ + names.get(path) ?? path, + { + ...output, + imports: output.imports.map((entry) => { + const renamedPath = !entry.external && names.get(entry.path); + + return renamedPath ? { ...entry, path: renamedPath } : entry; + }), + }, + ]), + ), + }; + } + // Write metafiles if stats option is enabled if (options.stats) { executionResult.addOutputFile( 'browser-stats.json', - stableStringify(browserMetafile), + stableStringify(statsMetafile), BuildOutputFileType.Root, ); @@ -458,6 +481,7 @@ export async function executeBuild( estimatedTransferSizes, !!ssrOptions, verbose, + localizedNames, ), ); } diff --git a/packages/angular/build/src/builders/application/i18n.ts b/packages/angular/build/src/builders/application/i18n.ts index 839384421f1f..ea54c581ef31 100644 --- a/packages/angular/build/src/builders/application/i18n.ts +++ b/packages/angular/build/src/builders/application/i18n.ts @@ -17,6 +17,7 @@ import { } from '../../tools/esbuild/bundler-execution-result'; import { BuildOutputFileType, InitialFileRecord } from '../../tools/esbuild/bundler-files'; import { I18nInliner } from '../../tools/i18n'; +import { createLocalizedOutputHasher } from '../../tools/i18n/i18n-output-hashes'; import { maxInlinerWorkers } from '../../utils/environment-options'; import { loadTranslations } from '../../utils/i18n-options'; import { createTranslationLoader } from '../../utils/load-translations'; @@ -44,6 +45,7 @@ export async function inlineI18n( errors: string[]; warnings: string[]; prerenderedRoutes: PrerenderedRoutesRecord; + renamedFiles?: Map; }> { const { i18nOptions, baseHref, cacheOptions } = options; @@ -64,6 +66,7 @@ export async function inlineI18n( errors: string[]; warnings: string[]; prerenderedRoutes: PrerenderedRoutesRecord; + renamedFiles?: Map; } = { errors: [], warnings: [], @@ -98,6 +101,15 @@ export async function inlineI18n( }); const inlinedLocales = await inliner.inlineAll(executionResult.outputFiles, localesToInline); + const hashLocalizedOutputs = options.i18nContentHashing + ? createLocalizedOutputHasher( + executionResult.outputFiles, + new Set( + options.globalScripts.filter(({ initial }) => !initial).map(({ name }) => name + '.js'), + ), + metafile, + ) + : undefined; for (const locale of i18nOptions.inlineLocales) { const localeInlineResult = inlinedLocales.get(locale); @@ -105,6 +117,14 @@ export async function inlineI18n( const localeOutputFiles = localeInlineResult.outputFiles; inlineResult.errors.push(...localeInlineResult.errors); inlineResult.warnings.push(...localeInlineResult.warnings); + const renamedFiles = hashLocalizedOutputs?.(localeOutputFiles); + // As with the pre-localization build summary, report a single set of output names. + inlineResult.renamedFiles ??= renamedFiles; + const localeInitialFiles = renamedFiles?.size + ? new Map( + Array.from(initialFiles, ([path, record]) => [renamedFiles.get(path) ?? path, record]), + ) + : initialFiles; const { errors, @@ -120,7 +140,7 @@ export async function inlineI18n( }, [...unModifiedOutputFiles, ...localeOutputFiles], executionResult.assetFiles, - initialFiles, + localeInitialFiles, locale, ); diff --git a/packages/angular/build/src/builders/application/options.ts b/packages/angular/build/src/builders/application/options.ts index d27caa25153f..a7fee64cfa81 100644 --- a/packages/angular/build/src/builders/application/options.ts +++ b/packages/angular/build/src/builders/application/options.ts @@ -544,6 +544,14 @@ export async function normalizeOptions( tailwindConfiguration, postcssConfiguration, i18nOptions, + // Server and watch builds still use the names produced by the bundler throughout the build. + i18nContentHashing: + i18nOptions.shouldInline && + outputNames.bundles.includes('[hash]') && + !serverEntryPoint && + !watch && + !outExtension && + !extensions?.codePlugins?.length, namedChunks, budgets: budgets?.length ? budgets : undefined, publicPath: deployUrl, diff --git a/packages/angular/build/src/tools/esbuild/application-code-bundle.ts b/packages/angular/build/src/tools/esbuild/application-code-bundle.ts index 6cd2b09f5a67..1a795f508a6b 100644 --- a/packages/angular/build/src/tools/esbuild/application-code-bundle.ts +++ b/packages/angular/build/src/tools/esbuild/application-code-bundle.ts @@ -572,7 +572,7 @@ function getEsBuildCommonOptions(options: NormalizedApplicationBuildOptions): Bu // change when translation files have changed. If this is not done the post processed files may have // different content but would retain identical production file names which would lead to browser caching problems. let footer; - if (i18nOptions.shouldInline) { + if (i18nOptions.shouldInline && !options.i18nContentHashing) { // Update file hashes to include translation file content const i18nHash = Object.values(i18nOptions.locales).reduce( (data, locale) => data + locale.files.map((file) => file.integrity || '').join('|'), diff --git a/packages/angular/build/src/tools/esbuild/utils.ts b/packages/angular/build/src/tools/esbuild/utils.ts index 105471e32b2a..41ad5ffe01dc 100644 --- a/packages/angular/build/src/tools/esbuild/utils.ts +++ b/packages/angular/build/src/tools/esbuild/utils.ts @@ -30,6 +30,7 @@ export function logBuildStats( estimatedTransferSizes?: Map, ssrOutputEnabled?: boolean, verbose?: boolean, + displayNames?: ReadonlyMap, ): string { // Remove the i18n subpath in case the build is using i18n. // en-US/main.js -> main.js @@ -69,7 +70,12 @@ export function logBuildStats( const name = initial.get(file)?.name ?? getChunkNameFromMetafile(metafiles, file); const stat: BundleStats = { initial: initial.has(file), - stats: [file, name ?? '-', size, estimatedTransferSizes?.get(file) ?? '-'], + stats: [ + displayNames?.get(file) ?? file, + name ?? '-', + size, + estimatedTransferSizes?.get(file) ?? '-', + ], }; if (isPlatformServer) { diff --git a/packages/angular/build/src/tools/i18n/i18n-inliner_spec.ts b/packages/angular/build/src/tools/i18n/i18n-inliner_spec.ts index 2fbb6e02ce31..c2e7c8eeb2e2 100644 --- a/packages/angular/build/src/tools/i18n/i18n-inliner_spec.ts +++ b/packages/angular/build/src/tools/i18n/i18n-inliner_spec.ts @@ -8,6 +8,7 @@ import type { ɵParsedTranslation } from '@angular/localize'; import { transform } from 'esbuild'; +import assert from 'node:assert'; import fs from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; @@ -20,6 +21,7 @@ import { createOutputFile, } from '../esbuild/bundler-files'; import { I18nInliner, type I18nInlinerOptions } from './i18n-inliner'; +import { createLocalizedOutputHasher } from './i18n-output-hashes'; /** * A module that uses a `$localize` message with an explicit message identifier so that the @@ -1185,3 +1187,161 @@ describe('I18nInliner', () => { }); }); }); + +describe('Localized output hashing', () => { + beforeAll(initializeHash); + + function renamed(names: ReadonlyMap, file: string): string { + const result = names.get(file); + assert(result, 'Expected renamed output file: ' + file); + + return result; + } + + function outputMetadata( + ...entries: [string, [string, 'import-statement' | 'dynamic-import', boolean?][]][] + ): Parameters[2] { + return { + inputs: {}, + outputs: Object.fromEntries( + entries.map(([file, imports]) => [ + file, + { + bytes: 0, + inputs: {}, + exports: [], + imports: imports.map(([path, kind, external]) => ({ path, kind, external })), + }, + ]), + ), + }; + } + + it('invalidates a cycle and its importers without invalidating a separate cycle', () => { + const original = [ + browserFile('first-AAAAAAAA.js', 'console.log($localize`A`); import "./second-BBBBBBBB.js";'), + browserFile('second-BBBBBBBB.js', 'export {} from "./first-AAAAAAAA.js";'), + browserFile('third-CCCCCCCC.js', 'import "./fourth-DDDDDDDD.js"; console.log($localize`B`);'), + browserFile('fourth-DDDDDDDD.js', 'import "./third-CCCCCCCC.js";'), + browserFile('main-EEEEEEEE.js', 'import(`./second-BBBBBBBB.js`);'), + ]; + const hash = createLocalizedOutputHasher( + original, + new Set(), + outputMetadata( + ['first-AAAAAAAA.js', [['second-BBBBBBBB.js', 'import-statement']]], + ['second-BBBBBBBB.js', [['first-AAAAAAAA.js', 'import-statement']]], + ['third-CCCCCCCC.js', [['fourth-DDDDDDDD.js', 'import-statement']]], + ['fourth-DDDDDDDD.js', [['third-CCCCCCCC.js', 'import-statement']]], + ['main-EEEEEEEE.js', [['second-BBBBBBBB.js', 'dynamic-import']]], + ), + ); + const localize = (text: string) => + original.map((file) => + browserFile( + file.path, + file.text + .replace('$localize`A`', JSON.stringify(text)) + .replace('$localize`B`', '"Other"'), + ), + ); + + const firstFiles = localize('Before'); + const first = hash(firstFiles); + const secondFiles = localize('Après 😀'); + const second = hash(secondFiles); + + expect(second.size).toBe(5); + for (const path of ['first-AAAAAAAA.js', 'second-BBBBBBBB.js', 'main-EEEEEEEE.js']) { + expect(second.get(path)).not.toBe(first.get(path)); + } + for (const path of ['third-CCCCCCCC.js', 'fourth-DDDDDDDD.js']) { + expect(second.get(path)).toBe(first.get(path)); + } + expect(findFile(secondFiles, renamed(second, 'first-AAAAAAAA.js')).text).toContain( + renamed(second, 'second-BBBBBBBB.js'), + ); + expect(findFile(secondFiles, renamed(second, 'second-BBBBBBBB.js')).text).toContain( + renamed(second, 'first-AAAAAAAA.js'), + ); + expect(findFile(secondFiles, renamed(second, 'main-EEEEEEEE.js')).text).toContain( + renamed(second, 'second-BBBBBBBB.js'), + ); + }); + + it('rewrites only actual module specifiers using workspace-relative metadata', () => { + const main = 'app/main-AAAAAAAA.js'; + const leaf = 'chunk-BBBBBBBB.js'; + const external = 'chunk-CCCCCCCC.js'; + const source = `export {a, b} from '../${leaf}'; import(\`../${leaf}\`); import('../${external}'); console.log('../${leaf}');`; + const files = [ + browserFile(main, source), + browserFile(leaf, 'export const a = $localize`Hello`, b = 1;'), + browserFile(external, 'export const a = $localize`Hello`;'), + ]; + const hash = createLocalizedOutputHasher( + files, + new Set(), + outputMetadata( + [ + main, + [ + ['./' + leaf, 'import-statement'], + ['./' + leaf, 'dynamic-import'], + [external, 'dynamic-import', true], + ], + ], + [leaf, []], + [external, []], + ), + ); + const localized = files.map((file) => + browserFile(file.path, file.text.replace('$localize`Hello`', '"Bonjour"')), + ); + + const names = hash(localized); + const newLeaf = renamed(names, leaf); + expect(renamed(names, external)).not.toBe(external); + const mainText = findFile(localized, renamed(names, main)).text; + expect(mainText).toBe( + `export {a, b} from '../${newLeaf}'; import(\`../${newLeaf}\`); import('../${external}'); console.log('../${leaf}');`, + ); + }); + + it('rewrites a worker URL and its source map without rewriting other strings', () => { + const worker = 'worker-aB3_-9cD.js'; + const main = 'main-BBBBBBBB.js'; + const mainFile = browserFile( + main, + `console.log("${worker}"); + new Worker(new URL("${worker}", import.meta.url)); + new Worker(new URL(\`./${worker}\`, import.meta.url));`, + ); + const sourceMap = browserFile(worker + '.map', JSON.stringify({ version: 3, file: worker })); + const hash = createLocalizedOutputHasher( + [mainFile, browserFile(worker, 'console.log($localize`Hello`);'), sourceMap], + new Set(), + outputMetadata([main, []], [worker, []]), + ); + const files = [ + mainFile.clone(), + browserFile( + worker, + `console.log("Bonjour"); +//# sourceMappingURL=${worker}.map +`, + ), + sourceMap.clone(), + ]; + + const names = hash(files); + const newWorker = renamed(names, worker); + expect(newWorker).not.toBe(worker); + const mainText = findFile(files, renamed(names, main)).text; + expect(mainText).toContain(`new URL("${newWorker}"`); + expect(mainText).toContain(`new URL(\`./${newWorker}\``); + expect(mainText).toContain(`console.log("${worker}")`); + expect(findFile(files, newWorker).text).toContain(`sourceMappingURL=${newWorker}.map`); + expect(JSON.parse(findFile(files, newWorker + '.map').text).file).toBe(newWorker); + }); +}); diff --git a/packages/angular/build/src/tools/i18n/i18n-output-hashes.ts b/packages/angular/build/src/tools/i18n/i18n-output-hashes.ts new file mode 100644 index 000000000000..91f3fdee11fe --- /dev/null +++ b/packages/angular/build/src/tools/i18n/i18n-output-hashes.ts @@ -0,0 +1,405 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Metafile } from 'esbuild'; +import assert from 'node:assert'; +import { posix } from 'node:path'; +import { Visitor, parseSync } from 'oxc-parser'; +import { calculateHash } from '../../utils/hash'; +import { toPosixPath } from '../../utils/path'; +import { BuildOutputFile, BuildOutputFileType } from '../esbuild/bundler-files'; + +const HASHED_SCRIPT = /-[a-zA-Z0-9_-]{8}\.js$/; +const WORKER_SCRIPT = /^worker-[a-zA-Z0-9_-]{8}\.js$/; +const WORKER_REFERENCE = /worker-[a-zA-Z0-9_-]{8}\.js['"`]/; + +interface Reference { + path: string; + start: number; + end: number; + worker: boolean; +} + +/** + * Assigns names to localized browser scripts based on their content and internal dependencies. + * Files whose bytes and dependency URLs do not change keep the original bundler name. + */ +export function createLocalizedOutputHasher( + originalFiles: BuildOutputFile[], + unhashedScripts: ReadonlySet, + metafile: Metafile, +): (files: BuildOutputFile[]) => Map { + const originals = new Map(originalFiles.map((file) => [file.path, file])); + const outputPaths = new Map( + originalFiles + .filter(({ type, path }) => type === BuildOutputFileType.Browser && HASHED_SCRIPT.test(path)) + .map(({ path }) => [toPosixPath(path), path]), + ); + const hasWorkers = [...outputPaths.keys()].some((path) => + WORKER_SCRIPT.test(posix.basename(path)), + ); + const references = new Map(); + const encoder = new TextEncoder(); + const canRename = (path: string) => + outputPaths.has(toPosixPath(path)) && !unhashedScripts.has(path); + const dependencies = new Map(); + const dependents = new Map>(); + + // Both esbuild and the chunk optimizer expose a workspace-relative output graph. + // Worker URLs are not ESM edges; look for them only when a worker bundle exists. + for (const file of originalFiles) { + const { type, path } = file; + if (type !== BuildOutputFileType.Browser || !path.endsWith('.js')) { + continue; + } + const metadata = metafile.outputs[toPosixPath(path)] ?? metafile.outputs[path]; + const targets = new Set(); + if (metadata) { + for (const { kind, path: target, external } of metadata.imports) { + if (!external && (kind === 'import-statement' || kind === 'dynamic-import')) { + const targetPath = toPosixPath(target); + const output = + outputPaths.get(targetPath) ?? outputPaths.get(posix.normalize(targetPath)); + if (output) { + targets.add(output); + } + } + } + } + if (!metadata || (hasWorkers && WORKER_REFERENCE.test(file.text))) { + const refs = findReferences(file, outputPaths, hasWorkers); + references.set(path, refs); + for (const { path: target, worker } of refs) { + if (!metadata || worker) { + targets.add(target); + } + } + } + + if (!targets.size) { + continue; + } + dependencies.set(path, [...targets].sort()); + for (const dependency of targets) { + let importers = dependents.get(dependency); + if (!importers) { + dependents.set(dependency, (importers = new Set())); + } + importers.add(path); + } + } + + return (files) => { + const outputs = new Map(files.map((file) => [file.path, file])); + const scripts = files.filter( + ({ type, path }) => type === BuildOutputFileType.Browser && path.endsWith('.js'), + ); + const changed = new Set(); + const changedCode = new Set(); + + for (const { path } of scripts) { + if (differs(path)) { + changedCode.add(path); + } + if (canRename(path) && (changedCode.has(path) || differs(path + '.map'))) { + changed.add(path); + } + } + + function differs(path: string): boolean { + return contentsDiffer(originals.get(path)?.contents, outputs.get(path)?.contents); + } + + // An importer changes when any of the URLs in its code changes. + for (const path of changed) { + for (const importer of dependents.get(path) ?? []) { + if (canRename(importer)) { + changed.add(importer); + } + } + } + + const names = new Map(); + const fingerprint = (path: string) => { + const output = outputs.get(path); + assert(output, 'Expected browser output file: ' + path); + const map = outputs.get(path + '.map'); + + return [ + path, + calculateHash(output.contents), + map && calculateHash(map.contents), + dependencies + .get(path) + ?.map((target) => names.get(target)) + .filter(Boolean), + ]; + }; + const setName = (path: string, seed: unknown) => { + // Use 40 bits, the same length as esbuild's hash. Keeping the filename width also + // preserves generated columns in source maps when import specifiers are rewritten. + const digest = calculateHash(JSON.stringify(seed)).slice(0, 10); + const suffix = Number.parseInt(digest, 16).toString(36).toUpperCase().padStart(8, '0'); + names.set(path, path.replace(HASHED_SCRIPT, `-${suffix}.js`)); + }; + + for (const component of dependencyComponents(changed, dependencies, dependents)) { + if (component.length === 1) { + setName(component[0], fingerprint(component[0])); + } else { + // Cyclic files depend on each other's final URLs. Hash them together so that + // changes invalidate the cycle and its importers without touching other cycles. + const digest = calculateHash(JSON.stringify(component.sort().map(fingerprint))); + for (const path of component) { + setName(path, [path, digest]); + } + } + } + + for (const file of scripts) { + const newName = names.get(file.path); + const targets = dependencies.get(file.path)?.filter((target) => names.has(target)); + let edits: Reference[] = []; + if (targets?.length) { + let refs = changedCode.has(file.path) ? undefined : references.get(file.path); + if (!refs) { + refs = findReferences(file, outputPaths, hasWorkers); + if (!changedCode.has(file.path)) { + references.set(file.path, refs); + } + } + const renamedTargets = new Set(targets); + edits = refs.filter(({ path }) => renamedTargets.has(path)); + } + if (!newName && !edits.length) { + continue; + } + + const original = file.text; + const parts: string[] = []; + let cursor = 0; + for (const { path, start, end } of edits.sort((a, b) => a.start - b.start)) { + const name = names.get(path); + assert(name, 'Expected renamed dependency: ' + path); + const specifier = original + .slice(start, end) + .replace(/-[a-zA-Z0-9_-]{8}\.js(?=['"`]$)/, name.slice(-12)); + parts.push(original.slice(cursor, start), specifier); + cursor = end; + } + parts.push(original.slice(cursor)); + let code = parts.join(''); + + if (newName) { + const map = outputs.get(file.path + '.map'); + if (map) { + const oldMapName = posix.basename(toPosixPath(map.path)); + map.path = newName + '.map'; + const newMapName = posix.basename(toPosixPath(map.path)); + code = code.replace(/(\/\/# sourceMappingURL=)([^\r\n]+)\s*$/, (match, prefix, url) => + url === oldMapName ? match.replace(prefix + url, prefix + newMapName) : match, + ); + const sourceMap = JSON.parse(map.text); + if (sourceMap.file === posix.basename(toPosixPath(file.path))) { + sourceMap.file = posix.basename(toPosixPath(newName)); + map.contents = encoder.encode(JSON.stringify(sourceMap)); + } + names.set(file.path + '.map', map.path); + } + + file.path = newName; + } + if (code !== original) { + file.contents = encoder.encode(code); + } + } + + return names; + }; +} + +function contentsDiffer(before: Uint8Array | undefined, after: Uint8Array | undefined): boolean { + return ( + before !== after && + (!before || + !after || + before.length !== after.length || + !Buffer.from(before.buffer, before.byteOffset, before.byteLength).equals(after)) + ); +} + +/** Visits strongly connected components in dependency-first order (iterative Kosaraju). */ +function* dependencyComponents( + changed: ReadonlySet, + dependencies: ReadonlyMap, + dependents: ReadonlyMap>, +): Iterable { + const seen = new Set(); + const order: string[] = []; + for (const start of changed) { + if (seen.has(start)) { + continue; + } + + const stack = [{ path: start, exiting: false }]; + for (let item = stack.pop(); item; item = stack.pop()) { + const { path, exiting } = item; + if (exiting) { + order.push(path); + } else if (!seen.has(path)) { + seen.add(path); + stack.push({ path, exiting: true }); + for (const importer of dependents.get(path) ?? []) { + if (changed.has(importer) && !seen.has(importer)) { + stack.push({ path: importer, exiting: false }); + } + } + } + } + } + + seen.clear(); + for (let i = order.length - 1; i >= 0; i--) { + const path = order[i]; + if (seen.has(path)) { + continue; + } + + const component = [path]; + seen.add(path); + for (const member of component) { + for (const dependency of dependencies.get(member) ?? []) { + if (changed.has(dependency) && !seen.has(dependency)) { + seen.add(dependency); + component.push(dependency); + } + } + } + yield component; + } +} + +function findReferences( + file: BuildOutputFile, + outputPaths: ReadonlyMap, + hasWorkers: boolean, +): Reference[] { + const { path, text } = file; + if (!/-[a-zA-Z0-9_-]{8}\.js['"`]/.test(text)) { + return []; + } + const references: Reference[] = []; + const directory = posix.dirname(toPosixPath(path)); + const add = (value: string, start: number, end: number, worker = false) => { + if (!worker && !value.startsWith('./') && !value.startsWith('../')) { + return; + } + const target = outputPaths.get(posix.join(directory, value)); + if (target && HASHED_SCRIPT.test(target)) { + references.push({ path: target, start, end, worker }); + } + }; + + const result = parseSync(path, text); + // OXC can expose the offsets without materializing the full AST. Empty re-exports + // are omitted by its module view, and worker URLs also require inspecting the AST. + if (!(hasWorkers && WORKER_REFERENCE.test(text)) && !/\bexport\s*(?:\/|\{\s*[/}])/.test(text)) { + const { staticImports, staticExports, dynamicImports } = result.module; + let needsAst = false; + for (const { + moduleRequest: { start, end }, + } of dynamicImports) { + const raw = text.slice(start, end); + const quote = raw[0]; + if (quote !== '"' && quote !== "'" && quote !== '`') { + continue; + } + if (raw.includes('\\')) { + needsAst = true; + break; + } + const value = raw.slice(1, -1); + if ( + raw.at(-1) === quote && + !value.includes(quote) && + !(quote === '`' && value.includes('${')) + ) { + add(value, start, end); + } + } + if (!needsAst) { + for (const { + moduleRequest: { value, start, end }, + } of staticImports) { + add(value, start, end); + } + for (const { entries } of staticExports) { + const request = entries.find(({ moduleRequest }) => moduleRequest)?.moduleRequest; + if (request) { + add(request.value, request.start, request.end); + } + } + + return references; + } + references.length = 0; + } + + const visitor = new Visitor({ + ImportDeclaration({ source }) { + add(source.value, source.start, source.end); + }, + ExportAllDeclaration({ source }) { + add(source.value, source.start, source.end); + }, + ExportNamedDeclaration({ source }) { + if (source) { + add(source.value, source.start, source.end); + } + }, + ImportExpression({ source }) { + if (source.type === 'Literal' && typeof source.value === 'string') { + add(source.value, source.start, source.end); + } else if (source.type === 'TemplateLiteral' && !source.expressions.length) { + const value = source.quasis[0].value.cooked; + if (value != null) { + add(value, source.start, source.end); + } + } + }, + NewExpression({ callee, arguments: args }) { + const [source, base] = args; + if ( + callee.type !== 'Identifier' || + callee.name !== 'URL' || + !source || + base?.type !== 'MemberExpression' || + base.object.type !== 'MetaProperty' || + base.object.meta.name !== 'import' || + base.computed || + base.property.type !== 'Identifier' || + base.property.name !== 'url' + ) { + return; + } + // Rolldown can print a static worker URL as a template literal. + const value = + source.type === 'Literal' + ? source.value + : source.type === 'TemplateLiteral' && !source.expressions.length + ? source.quasis[0].value.cooked + : undefined; + if (typeof value === 'string' && WORKER_SCRIPT.test(value.replace(/^\.\//, ''))) { + add(value, source.start, source.end, true); + } + }, + }); + visitor.visit(result.program); + + return references; +} diff --git a/tests/e2e/tests/i18n/ivy-localize-hashes.ts b/tests/e2e/tests/i18n/ivy-localize-hashes.ts index 2f682ca76988..0fc3d7cc7986 100644 --- a/tests/e2e/tests/i18n/ivy-localize-hashes.ts +++ b/tests/e2e/tests/i18n/ivy-localize-hashes.ts @@ -6,8 +6,12 @@ * found in the LICENSE file at https://angular.dev/license */ -import * as fs from 'node:fs'; -import { appendToFile } from '../../utils/fs'; +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import fs from 'node:fs'; +import { join } from 'node:path'; +import { getGlobalVariable } from '../../utils/env'; +import { appendToFile, replaceInFile, writeFile } from '../../utils/fs'; import { ng } from '../../utils/process'; import { langTranslations, setupI18nConfig } from './setup'; @@ -17,6 +21,12 @@ export default async function () { // Setup i18n tests and config. await setupI18nConfig(); + if (getGlobalVariable('argv')['esbuild']) { + await checkLocalizedChunkHashes(); + + return; + } + // Build each locale and record output file hashes const hashes = new Map(); await ng('build', '--output-hashing=all', '--configuration=development'); @@ -66,3 +76,84 @@ export default async function () { throw new Error('Missing output entries: ' + JSON.stringify(Array.from(hashes.values()))); } } + +async function checkLocalizedChunkHashes(): Promise { + await writeFile( + 'src/app/translated.ts', + "import type {} from '@angular/localize';\nexport const text = $localize`:@@lazyText:Lazy text`;", + ); + await appendToFile( + 'src/app/app.ts', + "void import('./translated').then(({ text }) => console.log(text));", + ); + for (const [locale, translation] of [ + ['de', 'Deutscher Text'], + ['fr', 'Texte français'], + ]) { + await replaceInFile( + `src/locale/messages.${locale}.xlf`, + '', + `Lazy text${translation}`, + ); + } + + const build = () => + ng( + 'build', + '--configuration=production', + '--output-hashing=all', + '--named-chunks', + '--source-map', + '--subresource-integrity', + ); + const getFiles = () => + langTranslations.map(({ outputPath }) => { + const files = fs.readdirSync(outputPath); + const script = (name: string) => { + const path = files.find((file) => file.startsWith(name + '-') && file.endsWith('.js')); + assert(path, `Missing ${name} in ${outputPath}`); + + return { path, content: fs.readFileSync(join(outputPath, path), 'utf-8') }; + }; + + return { + main: script('main'), + translated: script('translated'), + independent: script('dynamic'), + polyfills: script('polyfills'), + index: fs.readFileSync(join(outputPath, 'index.html'), 'utf-8'), + }; + }); + + await build(); + const before = getFiles(); + + await replaceInFile('src/locale/messages.fr.xlf', 'Texte français', 'Nouveau texte'); + await build(); + const after = getFiles(); + + for (const [i, { lang, outputPath }] of langTranslations.entries()) { + const previous = before[i]; + const current = after[i]; + assert.deepEqual(current.independent, previous.independent); + assert.deepEqual(current.polyfills, previous.polyfills); + + if (lang === 'fr') { + assert.notEqual(current.translated.path, previous.translated.path); + assert.notEqual(current.main.path, previous.main.path); + assert(current.translated.content.includes('Nouveau texte')); + } else { + assert.deepEqual(current.translated, previous.translated); + assert.deepEqual(current.main, previous.main); + } + + assert(current.main.content.includes(`./${current.translated.path}`)); + const mainTag = current.index + .match(/]*>/g) + ?.find((tag) => tag.includes(`src="${current.main.path}"`)); + const integrity = createHash('sha384').update(current.main.content).digest('base64'); + assert(mainTag?.includes(`integrity="sha384-${integrity}"`)); + assert(current.translated.content.includes(`sourceMappingURL=${current.translated.path}.map`)); + assert(fs.existsSync(join(outputPath, current.translated.path + '.map'))); + } +}