ng-packagr 22.0.0 → 22.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/lib/ng-package/entry-point/write-package.transform.js +12 -1
- package/src/lib/ng-package/entry-point/write-package.transform.js.map +1 -1
- package/src/lib/ngc/compile-source-files.js +1 -1
- package/src/lib/ngc/compile-source-files.js.map +1 -1
- package/src/lib/styles/bundler-context.d.ts +1 -1
- package/src/lib/styles/bundler-context.js +21 -3
- package/src/lib/styles/bundler-context.js.map +1 -1
- package/src/lib/styles/cache.d.ts +5 -0
- package/src/lib/styles/cache.js +82 -6
- package/src/lib/styles/cache.js.map +1 -1
- package/src/lib/styles/sass/sass-service.js +97 -54
- package/src/lib/styles/sass/sass-service.js.map +1 -1
package/package.json
CHANGED
|
@@ -75,7 +75,18 @@ const writePackageTransform = (options) => (0, transform_1.transformFromPromise)
|
|
|
75
75
|
spinner.start('Writing package manifest');
|
|
76
76
|
if (!options.watch) {
|
|
77
77
|
const primary = ngPackageNode.data.primary;
|
|
78
|
-
|
|
78
|
+
const nestedPackageJsons = [];
|
|
79
|
+
// Secondary entry-points package.json
|
|
80
|
+
for (const { data } of entryPoints) {
|
|
81
|
+
if (!data.entryPoint.isSecondaryEntryPoint) {
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
const packageJsonPath = (0, path_1.ensureUnixPath)(path.join(path.relative(primary.destinationPath, data.entryPoint.destinationPath), 'package.json'));
|
|
85
|
+
nestedPackageJsons.push(packageJsonPath);
|
|
86
|
+
}
|
|
87
|
+
if (nestedPackageJsons.length) {
|
|
88
|
+
await (0, fs_1.writeFile)(path.join(primary.destinationPath, '.npmignore'), `# Nested package.json's are only needed for development.\n${nestedPackageJsons.join('\n')}`);
|
|
89
|
+
}
|
|
79
90
|
}
|
|
80
91
|
const { compilationMode } = entryPoint.data.tsConfig.options;
|
|
81
92
|
await writePackageJson(ngEntryPoint, ngPackage, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"write-package.transform.js","sourceRoot":"","sources":["../../../../../src/lib/ng-package/entry-point/write-package.transform.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,8CAAoC;AACpC,2CAA6B;AAC7B,2CAAkC;AAGlC,2CAAwC;AACxC,+CAAkD;AAClD,qDAA6D;AAC7D,6CAA2C;AAC3C,uCAAyE;AACzE,qDAAuC;AACvC,2DAA2G;AAC3G,2CAAkD;AAClD,oCAA+F;AAOxF,MAAM,qBAAqB,GAAG,CAAC,OAAyB,EAAE,EAAE,CACjE,IAAA,gCAAoB,EAAC,KAAK,EAAC,KAAK,EAAC,EAAE;IACjC,MAAM,OAAO,GAAG,IAAA,aAAG,EAAC,EAAE,UAAU,EAAE,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAChE,MAAM,WAAW,GAAG,KAAK,CAAC,MAAM,CAAC,oBAAY,CAAC,CAAC;IAC/C,MAAM,UAAU,GAAG,WAAW,CAAC,IAAI,CAAC,qBAAY,CAAC,CAAC;IAClD,MAAM,YAAY,GAAiB,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC;IAC9D,MAAM,aAAa,GAAG,IAAA,uBAAe,EAAC,KAAK,CAAC,CAAC;IAC7C,MAAM,SAAS,GAAG,aAAa,CAAC,IAAI,CAAC;IACrC,MAAM,EAAE,gBAAgB,EAAE,GAAG,UAAU,CAAC,IAAI,CAAC;IAE7C,IAAI,CAAC,YAAY,CAAC,qBAAqB,EAAE,CAAC;QACxC,OAAO,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;QAChC,IAAI,CAAC;YACH,MAAM,UAAU,CAAC,KAAK,EAAE,UAAU,EAAE,aAAa,EAAE,WAAW,CAAC,CAAC;QAClE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,IAAI,EAAE,CAAC;YACf,MAAM,KAAK,CAA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AAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;YAC3C,GAAG,CAAC,KAAK,CAAC,cAAc,GAAG,mBAAmB,QAAQ,GAAG,CAAC,CAAC;QAC7D,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,IAAI,CACV,cAAM,CAAC,MAAM,CACX,mCAAmC,QAAQ,gDAAgD,GAAG,GAAG;gBAC/F,4CAA4C,QAAQ,IAAI,CAC3D,CACF,CAAC;YACF,MAAM,IAAI,KAAK,CAAC,cAAc,GAAG,4EAA4E,CAAC,CAAC;QACjH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import ora, { type Ora } from 'ora';\nimport * as path from 'path';\nimport { glob } from 'tinyglobby';\nimport { AssetPattern } from '../../../ng-package.schema';\nimport { BuildGraph } from '../../graph/build-graph';\nimport { Node } from '../../graph/node';\nimport { isInProgress } from '../../graph/select';\nimport { transformFromPromise } from '../../graph/transform';\nimport { colors } from '../../utils/color';\nimport { copyFile, mkdir, rmdir, stat, writeFile } from '../../utils/fs';\nimport * as log from '../../utils/log';\nimport { ConditionalExport, generatePackageExports, generateWatchVersion } from '../../utils/package-json';\nimport { ensureUnixPath } from '../../utils/path';\nimport { EntryPointNode, PackageNode, fileUrl, findPackageNode, isEntryPoint } from '../nodes';\nimport { NgPackagrOptions } from '../options.di';\nimport { NgPackage } from '../package';\nimport { NgEntryPoint } from './entry-point';\n\ntype CompilationMode = 'partial' | 'full' | undefined;\n\nexport const writePackageTransform = (options: NgPackagrOptions) =>\n transformFromPromise(async graph => {\n const spinner = ora({ hideCursor: false, discardStdin: false });\n const entryPoints = graph.filter(isEntryPoint);\n const entryPoint = entryPoints.find(isInProgress);\n const ngEntryPoint: NgEntryPoint = entryPoint.data.entryPoint;\n const ngPackageNode = findPackageNode(graph);\n const ngPackage = ngPackageNode.data;\n const { destinationFiles } = entryPoint.data;\n\n if (!ngEntryPoint.isSecondaryEntryPoint) {\n spinner.start('Copying assets');\n try {\n await copyAssets(graph, entryPoint, ngPackageNode, entryPoints);\n } catch (error) {\n spinner.fail();\n throw error;\n }\n spinner.succeed();\n }\n\n // 6. WRITE PACKAGE.JSON\n const relativeUnixFromDestPath = (filePath: string) =>\n ensureUnixPath(path.relative(ngEntryPoint.destinationPath, filePath));\n\n if (!ngEntryPoint.isSecondaryEntryPoint) {\n try {\n spinner.start('Writing package manifest');\n if (!options.watch) {\n const primary = ngPackageNode.data.primary;\n await writeFile(\n path.join(primary.destinationPath, '.npmignore'),\n `# Nested package.json's are only needed for development.\\n**/package.json`,\n );\n }\n\n const { compilationMode } = entryPoint.data.tsConfig.options;\n\n await writePackageJson(\n ngEntryPoint,\n ngPackage,\n {\n module: relativeUnixFromDestPath(destinationFiles.fesm2022),\n typings: relativeUnixFromDestPath(destinationFiles.declarationsBundled),\n exports: generatePackageExports(ngEntryPoint, entryPoints),\n // webpack v4+ specific flag to enable advanced optimizations and code splitting\n sideEffects: ngEntryPoint.packageJson.sideEffects ?? false,\n },\n !!options.watch,\n compilationMode as CompilationMode,\n spinner,\n );\n } catch (error) {\n spinner.fail();\n throw error;\n }\n spinner.succeed();\n } else if (ngEntryPoint.isSecondaryEntryPoint) {\n // Write a package.json in each secondary entry-point\n // This is need for esbuild to secondary entry-points in dist correctly.\n await mkdir(ngEntryPoint.destinationPath, { recursive: true });\n await writeFile(\n path.join(ngEntryPoint.destinationPath, 'package.json'),\n JSON.stringify(\n {\n module: relativeUnixFromDestPath(destinationFiles.fesm2022),\n typings: relativeUnixFromDestPath(destinationFiles.declarationsBundled),\n },\n undefined,\n 2,\n ),\n );\n }\n\n spinner.succeed(`Built ${ngEntryPoint.moduleId}`);\n });\n\ntype AssetEntry = Exclude<AssetPattern, string>;\n\nasync function copyAssets(\n graph: BuildGraph,\n entryPointNode: EntryPointNode,\n ngPackageNode: PackageNode,\n entryPoints: EntryPointNode[],\n): Promise<void> {\n const ngPackage = ngPackageNode.data;\n const globsForceIgnored: string[] = ['.gitkeep', '**/.DS_Store', '**/Thumbs.db', `${ngPackage.dest}/**`];\n const defaultAssets: AssetEntry[] = [\n { glob: 'LICENSE', input: '/', output: '/' },\n ...entryPoints.map(({ data }) => {\n const subpath = data.entryPoint.destinationFiles.directory || '/';\n\n return { glob: 'README.md', input: subpath, output: subpath };\n }),\n ];\n\n const assets: AssetEntry[] = [];\n for (const assetPath of [...ngPackage.assets, ...defaultAssets]) {\n let asset: AssetEntry;\n if (typeof assetPath === 'object') {\n asset = { ...assetPath };\n } else {\n const [isDir, isFile] = await stat(path.join(ngPackage.src, assetPath))\n .then(stats => [stats.isDirectory(), stats.isFile()])\n .catch(() => [false, false]);\n if (isDir) {\n asset = { glob: '**/*', input: assetPath, output: assetPath };\n } else if (isFile) {\n // filenames are their own glob\n asset = { glob: path.basename(assetPath), input: path.dirname(assetPath), output: path.dirname(assetPath) };\n } else {\n asset = { glob: assetPath, input: '/', output: '/' };\n }\n }\n\n asset.input = path.join(ngPackage.src, asset.input);\n asset.output = path.join(ngPackage.dest, asset.output);\n\n const isAncestorPath = (target: string, datum: string) => path.relative(datum, target).startsWith('..');\n if (isAncestorPath(asset.input, ngPackage.src)) {\n throw new Error('Cannot read assets from a location outside of the project root.');\n }\n if (isAncestorPath(asset.output, ngPackage.dest)) {\n throw new Error('Cannot write assets to a location outside of the output path.');\n }\n\n assets.push(asset);\n }\n\n for (const asset of assets) {\n const filePaths = await glob(asset.glob, {\n cwd: asset.input,\n ignore: [...(asset.ignore ?? []), ...globsForceIgnored],\n dot: true,\n onlyFiles: true,\n followSymbolicLinks: asset.followSymlinks,\n });\n for (const filePath of filePaths) {\n const fileSrcFullPath = path.join(asset.input, filePath);\n const fileDestFullPath = path.join(asset.output, filePath);\n const nodeUri = fileUrl(ensureUnixPath(fileSrcFullPath));\n let node = graph.get(nodeUri);\n if (!node) {\n node = new Node(nodeUri);\n graph.put(node);\n }\n entryPointNode.dependsOn(node);\n await copyFile(fileSrcFullPath, fileDestFullPath);\n }\n }\n}\n\n/**\n * Creates and writes a `package.json` file of the entry point used by the `node_module`\n * resolution strategies.\n *\n * #### Example\n *\n * A consumer of the entry point depends on it by `import {..} from '@my/module/id';`.\n * The module id `@my/module/id` will be resolved to the `package.json` file that is written by\n * this build step.\n * The properties `main`, `module`, `typings` (and so on) in the `package.json` point to the\n * flattened JavaScript bundles, type definitions, (...).\n *\n * @param entryPoint An entry point of an Angular package / library\n * @param additionalProperties Additional properties, e.g. binary artefacts (bundle files), to merge into `package.json`\n */\nasync function writePackageJson(\n entryPoint: NgEntryPoint,\n pkg: NgPackage,\n additionalProperties: { [key: string]: string | boolean | string[] | ConditionalExport },\n isWatchMode: boolean,\n compilationMode: CompilationMode,\n spinner: Ora,\n): Promise<void> {\n log.debug('Writing package.json');\n\n // set additional properties\n const packageJson = { ...entryPoint.packageJson, ...additionalProperties };\n packageJson.type ??= 'module';\n\n // read tslib version from `@angular/compiler` so that our tslib\n // version at least matches that of angular if we use require('tslib').version\n // it will get what installed and not the minimum version nor if it is a `~` or `^`\n // this is only required for primary\n if (isWatchMode) {\n // Needed because of Webpack's 5 `cachemanagedpaths`\n // https://github.com/angular/angular-cli/issues/20962\n packageJson.version = generateWatchVersion();\n }\n\n if (!packageJson.peerDependencies?.tslib && !packageJson.dependencies?.tslib) {\n const {\n peerDependencies: angularPeerDependencies = {},\n dependencies: angularDependencies = {},\n } = require('@angular/compiler/package.json');\n const tsLibVersion = angularPeerDependencies.tslib || angularDependencies.tslib;\n\n if (tsLibVersion) {\n packageJson.dependencies = { ...packageJson.dependencies, tslib: tsLibVersion };\n }\n } else if (packageJson.peerDependencies?.tslib) {\n spinner.warn(\n colors.yellow(\n `'tslib' is no longer recommended to be used as a 'peerDependencies'. Moving it to 'dependencies'.`,\n ),\n );\n packageJson.dependencies = { ...(packageJson.dependencies || {}), tslib: packageJson.peerDependencies.tslib };\n\n delete packageJson.peerDependencies.tslib;\n }\n\n // Verify non-peerDependencies as they can easily lead to duplicate installs or version conflicts\n // in the node_modules folder of an application\n const allowedList = pkg.allowedNonPeerDependencies.map(value => new RegExp(value));\n try {\n checkNonPeerDependencies(packageJson, 'dependencies', allowedList, spinner);\n } catch (e) {\n await rmdir(entryPoint.destinationPath, { recursive: true });\n throw e;\n }\n\n // Removes scripts from package.json after build\n if (packageJson.scripts) {\n if (pkg.keepLifecycleScripts !== true) {\n spinner.info(`Removing scripts section in package.json as it's considered a potential security vulnerability.`);\n delete packageJson.scripts;\n } else {\n spinner.warn(\n colors.yellow(\n `You enabled keepLifecycleScripts explicitly. The scripts section in package.json will be published to npm.`,\n ),\n );\n }\n }\n\n if (compilationMode !== 'partial') {\n const scripts = packageJson.scripts || (packageJson.scripts = {});\n scripts.prepublishOnly =\n 'node --eval \"console.error(\\'' +\n 'ERROR: Trying to publish a package that has been compiled in full compilation mode. This is not allowed.\\\\n' +\n 'Please delete and rebuild the package with partial compilation mode, before attempting to publish.\\\\n' +\n '\\')\" ' +\n '&& exit 1';\n }\n\n // keep the dist package.json clean\n // this will not throw if ngPackage field does not exist\n delete packageJson.ngPackage;\n\n const packageJsonPropertiesToDelete = [\n 'stylelint',\n 'prettier',\n 'browserslist',\n 'devDependencies',\n 'jest',\n 'workspaces',\n 'husky',\n ];\n\n for (const prop of packageJsonPropertiesToDelete) {\n if (prop in packageJson) {\n delete packageJson[prop];\n spinner.info(`Removing ${prop} section in package.json.`);\n }\n }\n\n packageJson.name = entryPoint.moduleId;\n await writeFile(path.join(entryPoint.destinationPath, 'package.json'), JSON.stringify(packageJson, undefined, 2));\n}\n\nfunction checkNonPeerDependencies(\n packageJson: Record<string, unknown>,\n property: string,\n allowed: RegExp[],\n spinner: Ora,\n) {\n if (!packageJson[property]) {\n return;\n }\n\n for (const dep of Object.keys(packageJson[property])) {\n if (allowed.some(regex => regex.test(dep))) {\n log.debug(`Dependency ${dep} is allowed in '${property}'`);\n } else {\n spinner.warn(\n colors.yellow(\n `Distributing npm packages with '${property}' is not recommended. Please consider adding ${dep} ` +\n `to 'peerDependencies' or remove it from '${property}'.`,\n ),\n );\n throw new Error(`Dependency ${dep} must be explicitly allowed using the \"allowedNonPeerDependencies\" option.`);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"write-package.transform.js","sourceRoot":"","sources":["../../../../../src/lib/ng-package/entry-point/write-package.transform.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,8CAAoC;AACpC,2CAA6B;AAC7B,2CAAkC;AAGlC,2CAAwC;AACxC,+CAAkD;AAClD,qDAA6D;AAC7D,6CAA2C;AAC3C,uCAAyE;AACzE,qDAAuC;AACvC,2DAA2G;AAC3G,2CAAkD;AAClD,oCAA+F;AAOxF,MAAM,qBAAqB,GAAG,CAAC,OAAyB,EAAE,EAAE,CACjE,IAAA,gCAAoB,EAAC,KAAK,EAAC,KAAK,EAAC,EAAE;IACjC,MAAM,OAAO,GAAG,IAAA,aAAG,EAAC,EAAE,UAAU,EAAE,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAChE,MAAM,WAAW,GAAG,KAAK,CAAC,MAAM,CAAC,oBAAY,CAAC,CAAC;IAC/C,MAAM,UAAU,GAAG,WAAW,CAAC,IAAI,CAAC,qBAAY,CAAC,CAAC;IAClD,MAAM,YAAY,GAAiB,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC;IAC9D,MAAM,aAAa,GAAG,IAAA,uBAAe,EAAC,KAAK,CAAC,CAAC;IAC7C,MAAM,SAAS,GAAG,aAAa,CAAC,IAAI,CAAC;IACrC,MAAM,EAAE,gBAAgB,EAAE,GAAG,UAAU,CAAC,IAAI,CAAC;IAE7C,IAAI,CAAC,YAAY,CAAC,qBAAqB,EAAE,CAAC;QACxC,OAAO,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;QAChC,IAAI,CAAC;YACH,MAAM,UAAU,CAAC,KAAK,EAAE,UAAU,EAAE,aAAa,EAAE,WAAW,CAAC,CAAC;QAClE,CAAC;QAA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,OAAO,WAAW,CAAC,IAAI,CAAC,CAAC;YACzB,OAAO,CAAC,IAAI,CAAC,YAAY,IAAI,2BAA2B,CAAC,CAAC;QAC5D,CAAC;IACH,CAAC;IAED,WAAW,CAAC,IAAI,GAAG,UAAU,CAAC,QAAQ,CAAC;IACvC,MAAM,IAAA,cAAS,EAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,eAAe,EAAE,cAAc,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,WAAW,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC;AACpH,CAAC;AAED,SAAS,wBAAwB,CAC/B,WAAoC,EACpC,QAAgB,EAChB,OAAiB,EACjB,OAAY;IAEZ,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC3B,OAAO;IACT,CAAC;IAED,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC;QACrD,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;YAC3C,GAAG,CAAC,KAAK,CAAC,cAAc,GAAG,mBAAmB,QAAQ,GAAG,CAAC,CAAC;QAC7D,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,IAAI,CACV,cAAM,CAAC,MAAM,CACX,mCAAmC,QAAQ,gDAAgD,GAAG,GAAG;gBAC/F,4CAA4C,QAAQ,IAAI,CAC3D,CACF,CAAC;YACF,MAAM,IAAI,KAAK,CAAC,cAAc,GAAG,4EAA4E,CAAC,CAAC;QACjH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import ora, { type Ora } from 'ora';\nimport * as path from 'path';\nimport { glob } from 'tinyglobby';\nimport { AssetPattern } from '../../../ng-package.schema';\nimport { BuildGraph } from '../../graph/build-graph';\nimport { Node } from '../../graph/node';\nimport { isInProgress } from '../../graph/select';\nimport { transformFromPromise } from '../../graph/transform';\nimport { colors } from '../../utils/color';\nimport { copyFile, mkdir, rmdir, stat, writeFile } from '../../utils/fs';\nimport * as log from '../../utils/log';\nimport { ConditionalExport, generatePackageExports, generateWatchVersion } from '../../utils/package-json';\nimport { ensureUnixPath } from '../../utils/path';\nimport { EntryPointNode, PackageNode, fileUrl, findPackageNode, isEntryPoint } from '../nodes';\nimport { NgPackagrOptions } from '../options.di';\nimport { NgPackage } from '../package';\nimport { NgEntryPoint } from './entry-point';\n\ntype CompilationMode = 'partial' | 'full' | undefined;\n\nexport const writePackageTransform = (options: NgPackagrOptions) =>\n transformFromPromise(async graph => {\n const spinner = ora({ hideCursor: false, discardStdin: false });\n const entryPoints = graph.filter(isEntryPoint);\n const entryPoint = entryPoints.find(isInProgress);\n const ngEntryPoint: NgEntryPoint = entryPoint.data.entryPoint;\n const ngPackageNode = findPackageNode(graph);\n const ngPackage = ngPackageNode.data;\n const { destinationFiles } = entryPoint.data;\n\n if (!ngEntryPoint.isSecondaryEntryPoint) {\n spinner.start('Copying assets');\n try {\n await copyAssets(graph, entryPoint, ngPackageNode, entryPoints);\n } catch (error) {\n spinner.fail();\n throw error;\n }\n spinner.succeed();\n }\n\n // 6. WRITE PACKAGE.JSON\n const relativeUnixFromDestPath = (filePath: string) =>\n ensureUnixPath(path.relative(ngEntryPoint.destinationPath, filePath));\n\n if (!ngEntryPoint.isSecondaryEntryPoint) {\n try {\n spinner.start('Writing package manifest');\n if (!options.watch) {\n const primary = ngPackageNode.data.primary;\n\n const nestedPackageJsons: string[] = [];\n // Secondary entry-points package.json\n for (const { data } of entryPoints) {\n if (!data.entryPoint.isSecondaryEntryPoint) {\n continue;\n }\n\n const packageJsonPath = ensureUnixPath(\n path.join(path.relative(primary.destinationPath, data.entryPoint.destinationPath), 'package.json'),\n );\n nestedPackageJsons.push(packageJsonPath);\n }\n\n if (nestedPackageJsons.length) {\n await writeFile(\n path.join(primary.destinationPath, '.npmignore'),\n `# Nested package.json's are only needed for development.\\n${nestedPackageJsons.join('\\n')}`,\n );\n }\n }\n\n const { compilationMode } = entryPoint.data.tsConfig.options;\n\n await writePackageJson(\n ngEntryPoint,\n ngPackage,\n {\n module: relativeUnixFromDestPath(destinationFiles.fesm2022),\n typings: relativeUnixFromDestPath(destinationFiles.declarationsBundled),\n exports: generatePackageExports(ngEntryPoint, entryPoints),\n // webpack v4+ specific flag to enable advanced optimizations and code splitting\n sideEffects: ngEntryPoint.packageJson.sideEffects ?? false,\n },\n !!options.watch,\n compilationMode as CompilationMode,\n spinner,\n );\n } catch (error) {\n spinner.fail();\n throw error;\n }\n spinner.succeed();\n } else if (ngEntryPoint.isSecondaryEntryPoint) {\n // Write a package.json in each secondary entry-point\n // This is need for esbuild to secondary entry-points in dist correctly.\n await mkdir(ngEntryPoint.destinationPath, { recursive: true });\n await writeFile(\n path.join(ngEntryPoint.destinationPath, 'package.json'),\n JSON.stringify(\n {\n module: relativeUnixFromDestPath(destinationFiles.fesm2022),\n typings: relativeUnixFromDestPath(destinationFiles.declarationsBundled),\n },\n undefined,\n 2,\n ),\n );\n }\n\n spinner.succeed(`Built ${ngEntryPoint.moduleId}`);\n });\n\ntype AssetEntry = Exclude<AssetPattern, string>;\n\nasync function copyAssets(\n graph: BuildGraph,\n entryPointNode: EntryPointNode,\n ngPackageNode: PackageNode,\n entryPoints: EntryPointNode[],\n): Promise<void> {\n const ngPackage = ngPackageNode.data;\n const globsForceIgnored: string[] = ['.gitkeep', '**/.DS_Store', '**/Thumbs.db', `${ngPackage.dest}/**`];\n const defaultAssets: AssetEntry[] = [\n { glob: 'LICENSE', input: '/', output: '/' },\n ...entryPoints.map(({ data }) => {\n const subpath = data.entryPoint.destinationFiles.directory || '/';\n\n return { glob: 'README.md', input: subpath, output: subpath };\n }),\n ];\n\n const assets: AssetEntry[] = [];\n for (const assetPath of [...ngPackage.assets, ...defaultAssets]) {\n let asset: AssetEntry;\n if (typeof assetPath === 'object') {\n asset = { ...assetPath };\n } else {\n const [isDir, isFile] = await stat(path.join(ngPackage.src, assetPath))\n .then(stats => [stats.isDirectory(), stats.isFile()])\n .catch(() => [false, false]);\n if (isDir) {\n asset = { glob: '**/*', input: assetPath, output: assetPath };\n } else if (isFile) {\n // filenames are their own glob\n asset = { glob: path.basename(assetPath), input: path.dirname(assetPath), output: path.dirname(assetPath) };\n } else {\n asset = { glob: assetPath, input: '/', output: '/' };\n }\n }\n\n asset.input = path.join(ngPackage.src, asset.input);\n asset.output = path.join(ngPackage.dest, asset.output);\n\n const isAncestorPath = (target: string, datum: string) => path.relative(datum, target).startsWith('..');\n if (isAncestorPath(asset.input, ngPackage.src)) {\n throw new Error('Cannot read assets from a location outside of the project root.');\n }\n if (isAncestorPath(asset.output, ngPackage.dest)) {\n throw new Error('Cannot write assets to a location outside of the output path.');\n }\n\n assets.push(asset);\n }\n\n for (const asset of assets) {\n const filePaths = await glob(asset.glob, {\n cwd: asset.input,\n ignore: [...(asset.ignore ?? []), ...globsForceIgnored],\n dot: true,\n onlyFiles: true,\n followSymbolicLinks: asset.followSymlinks,\n });\n for (const filePath of filePaths) {\n const fileSrcFullPath = path.join(asset.input, filePath);\n const fileDestFullPath = path.join(asset.output, filePath);\n const nodeUri = fileUrl(ensureUnixPath(fileSrcFullPath));\n let node = graph.get(nodeUri);\n if (!node) {\n node = new Node(nodeUri);\n graph.put(node);\n }\n entryPointNode.dependsOn(node);\n await copyFile(fileSrcFullPath, fileDestFullPath);\n }\n }\n}\n\n/**\n * Creates and writes a `package.json` file of the entry point used by the `node_module`\n * resolution strategies.\n *\n * #### Example\n *\n * A consumer of the entry point depends on it by `import {..} from '@my/module/id';`.\n * The module id `@my/module/id` will be resolved to the `package.json` file that is written by\n * this build step.\n * The properties `main`, `module`, `typings` (and so on) in the `package.json` point to the\n * flattened JavaScript bundles, type definitions, (...).\n *\n * @param entryPoint An entry point of an Angular package / library\n * @param additionalProperties Additional properties, e.g. binary artefacts (bundle files), to merge into `package.json`\n */\nasync function writePackageJson(\n entryPoint: NgEntryPoint,\n pkg: NgPackage,\n additionalProperties: { [key: string]: string | boolean | string[] | ConditionalExport },\n isWatchMode: boolean,\n compilationMode: CompilationMode,\n spinner: Ora,\n): Promise<void> {\n log.debug('Writing package.json');\n\n // set additional properties\n const packageJson = { ...entryPoint.packageJson, ...additionalProperties };\n packageJson.type ??= 'module';\n\n // read tslib version from `@angular/compiler` so that our tslib\n // version at least matches that of angular if we use require('tslib').version\n // it will get what installed and not the minimum version nor if it is a `~` or `^`\n // this is only required for primary\n if (isWatchMode) {\n // Needed because of Webpack's 5 `cachemanagedpaths`\n // https://github.com/angular/angular-cli/issues/20962\n packageJson.version = generateWatchVersion();\n }\n\n if (!packageJson.peerDependencies?.tslib && !packageJson.dependencies?.tslib) {\n const {\n peerDependencies: angularPeerDependencies = {},\n dependencies: angularDependencies = {},\n } = require('@angular/compiler/package.json');\n const tsLibVersion = angularPeerDependencies.tslib || angularDependencies.tslib;\n\n if (tsLibVersion) {\n packageJson.dependencies = { ...packageJson.dependencies, tslib: tsLibVersion };\n }\n } else if (packageJson.peerDependencies?.tslib) {\n spinner.warn(\n colors.yellow(\n `'tslib' is no longer recommended to be used as a 'peerDependencies'. Moving it to 'dependencies'.`,\n ),\n );\n packageJson.dependencies = { ...(packageJson.dependencies || {}), tslib: packageJson.peerDependencies.tslib };\n\n delete packageJson.peerDependencies.tslib;\n }\n\n // Verify non-peerDependencies as they can easily lead to duplicate installs or version conflicts\n // in the node_modules folder of an application\n const allowedList = pkg.allowedNonPeerDependencies.map(value => new RegExp(value));\n try {\n checkNonPeerDependencies(packageJson, 'dependencies', allowedList, spinner);\n } catch (e) {\n await rmdir(entryPoint.destinationPath, { recursive: true });\n throw e;\n }\n\n // Removes scripts from package.json after build\n if (packageJson.scripts) {\n if (pkg.keepLifecycleScripts !== true) {\n spinner.info(`Removing scripts section in package.json as it's considered a potential security vulnerability.`);\n delete packageJson.scripts;\n } else {\n spinner.warn(\n colors.yellow(\n `You enabled keepLifecycleScripts explicitly. The scripts section in package.json will be published to npm.`,\n ),\n );\n }\n }\n\n if (compilationMode !== 'partial') {\n const scripts = packageJson.scripts || (packageJson.scripts = {});\n scripts.prepublishOnly =\n 'node --eval \"console.error(\\'' +\n 'ERROR: Trying to publish a package that has been compiled in full compilation mode. This is not allowed.\\\\n' +\n 'Please delete and rebuild the package with partial compilation mode, before attempting to publish.\\\\n' +\n '\\')\" ' +\n '&& exit 1';\n }\n\n // keep the dist package.json clean\n // this will not throw if ngPackage field does not exist\n delete packageJson.ngPackage;\n\n const packageJsonPropertiesToDelete = [\n 'stylelint',\n 'prettier',\n 'browserslist',\n 'devDependencies',\n 'jest',\n 'workspaces',\n 'husky',\n ];\n\n for (const prop of packageJsonPropertiesToDelete) {\n if (prop in packageJson) {\n delete packageJson[prop];\n spinner.info(`Removing ${prop} section in package.json.`);\n }\n }\n\n packageJson.name = entryPoint.moduleId;\n await writeFile(path.join(entryPoint.destinationPath, 'package.json'), JSON.stringify(packageJson, undefined, 2));\n}\n\nfunction checkNonPeerDependencies(\n packageJson: Record<string, unknown>,\n property: string,\n allowed: RegExp[],\n spinner: Ora,\n) {\n if (!packageJson[property]) {\n return;\n }\n\n for (const dep of Object.keys(packageJson[property])) {\n if (allowed.some(regex => regex.test(dep))) {\n log.debug(`Dependency ${dep} is allowed in '${property}'`);\n } else {\n spinner.warn(\n colors.yellow(\n `Distributing npm packages with '${property}' is not recommended. Please consider adding ${dep} ` +\n `to 'peerDependencies' or remove it from '${property}'.`,\n ),\n );\n throw new Error(`Dependency ${dep} must be explicitly allowed using the \"allowedNonPeerDependencies\" option.`);\n }\n }\n}\n"]}
|
|
@@ -166,7 +166,7 @@ async function compileSourceFiles(graph, tsConfig, moduleResolutionCache, option
|
|
|
166
166
|
}
|
|
167
167
|
}
|
|
168
168
|
if (otherDiagnostics.length) {
|
|
169
|
-
log.msg(formatDiagnostics(
|
|
169
|
+
log.msg(formatDiagnostics(otherDiagnostics));
|
|
170
170
|
}
|
|
171
171
|
if (errorDiagnostics.length) {
|
|
172
172
|
throw new Error(formatDiagnostics(errorDiagnostics));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compile-source-files.js","sourceRoot":"","sources":["../../../../src/lib/ngc/compile-source-files.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,gDA+MC;AAxND,yCAAiC;AACjC,4DAA4B;AAE5B,+CAAgF;AAGhF,mEAA4F;AAC5F,kDAAoC;AAE7B,KAAK,UAAU,kBAAkB,CACtC,KAAiB,EACjB,QAA6B,EAC7B,qBAA+C,EAC/C,OAAyB,EACzB,YAAuC,EACvC,mBAAyC;IAEzC,MAAM,EAAE,YAAY,EAAE,iBAAiB,EAAE,GAAG,wDAAa,uBAAuB,GAAC,CAAC;IAClF,MAAM,EAAE,cAAc,EAAE,KAAK,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC;IACxD,MAAM,eAAe,GAAoB,EAAE,GAAG,QAAQ,CAAC,OAAO,EAAE,GAAG,YAAY,EAAE,CAAC;IAClF,MAAM,UAAU,GAAG,IAAA,gCAAwB,EAAC,KAAK,CAAC,CAAC;IACnD,MAAM,aAAa,GAAG,IAAA,uBAAe,EAAC,KAAK,CAAC,CAAC;IAC7C,MAAM,mBAAmB,GAAG,aAAa,CAAC,IAAI,CAAC,mBAAmB,CAAC;IAEnE,MAAM,QAAQ,GAAG,YAAY,IAAI,cAAc,CAAC;IAChD,IAAI,QAAQ,EAAE,CAAC;QACb,eAAe,CAAC,WAAW,KAAK,IAAI,CAAC;QACrC,eAAe,CAAC,eAAe,KAAK,IAAA,gBAAI,EACtC,QAAQ,EACR,eAAe,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC,cAAc,cAAc,CACvE,CAAC;IACJ,CAAC;IAED,MAAM,cAAc,GAAG,IAAA,uCAAiB,EACtC,KAAK,EACL,UAAU,EACV,eAAe,EACf,qBAAqB,EACrB,mBAAmB,EACnB,mBAAmB,CACpB,CAAC;IAEF,MA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ACD,QAAQ;QACV,CAAC;IACH,CAAC;IAED,KAAK,MAAM,UAAU,IAAI,OAAO,CAAC,cAAc,EAAE,EAAE,CAAC;QAClD,IAAI,aAAa,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;YAClC,SAAS;QACX,CAAC;QAED,IAAI,eAAe,CAAC,sBAAsB,CAAC,cAAc,CAAC,UAAU,CAAC,EAAE,CAAC;YACtE,SAAS;QACX,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,YAAY,CAAC,CAAC;QACxE,eAAe,CAAC,sBAAsB,CAAC,oBAAoB,CAAC,UAAU,CAAC,CAAC;IAC1E,CAAC;AACH,CAAC","sourcesContent":["import { CompilerOptions, ParsedConfiguration } from '@angular/compiler-cli';\nimport { join } from 'node:path';\nimport ts from 'typescript';\nimport { BuildGraph } from '../graph/build-graph';\nimport { findEntryPointInProgress, findPackageNode } from '../ng-package/nodes';\nimport { NgPackagrOptions } from '../ng-package/options.di';\nimport { StylesheetProcessor } from '../styles/stylesheet-processor';\nimport { augmentProgramWithVersioning, cacheCompilerHost } from '../ts/cache-compiler-host';\nimport * as log from '../utils/log';\n\nexport async function compileSourceFiles(\n graph: BuildGraph,\n tsConfig: ParsedConfiguration,\n moduleResolutionCache: ts.ModuleResolutionCache,\n options: NgPackagrOptions,\n extraOptions?: Partial<CompilerOptions>,\n stylesheetProcessor?: StylesheetProcessor,\n) {\n const { NgtscProgram, formatDiagnostics } = await import('@angular/compiler-cli');\n const { cacheDirectory, watch, cacheEnabled } = options;\n const tsConfigOptions: CompilerOptions = { ...tsConfig.options, ...extraOptions };\n const entryPoint = findEntryPointInProgress(graph);\n const ngPackageNode = findPackageNode(graph);\n const inlineStyleLanguage = ngPackageNode.data.inlineStyleLanguage;\n\n const cacheDir = cacheEnabled && cacheDirectory;\n if (cacheDir) {\n tsConfigOptions.incremental ??= true;\n tsConfigOptions.tsBuildInfoFile ??= join(\n cacheDir,\n `tsbuildinfo/${entryPoint.data.entryPoint.flatModuleFile}.tsbuildinfo`,\n );\n }\n\n const tsCompilerHost = cacheCompilerHost(\n graph,\n entryPoint,\n tsConfigOptions,\n moduleResolutionCache,\n stylesheetProcessor,\n inlineStyleLanguage,\n );\n\n const cache = entryPoint.cache;\n let usingBuildInfo = false;\n\n let oldBuilder = cache.oldBuilder;\n if (!oldBuilder && cacheDir) {\n oldBuilder = ts.readBuilderProgram(tsConfigOptions, tsCompilerHost);\n usingBuildInfo = true;\n }\n\n // Create the Angular specific program that contains the Angular compiler\n const angularProgram = new NgtscProgram(tsConfig.rootNames, tsConfigOptions, tsCompilerHost, cache.oldNgtscProgram);\n\n const angularCompiler = angularProgram.compiler;\n const { ignoreForDiagnostics, ignoreForEmit } = angularCompiler;\n\n // SourceFile versions are required for builder programs.\n // The wrapped host inside NgtscProgram adds additional files that will not have versions.\n const typeScriptProgram = angularProgram.getTsProgram();\n augmentProgramWithVersioning(typeScriptProgram);\n\n let builder: ts.BuilderProgram | ts.EmitAndSemanticDiagnosticsBuilderProgram;\n if (watch || cacheDir) {\n builder = cache.oldBuilder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(\n typeScriptProgram,\n tsCompilerHost,\n oldBuilder,\n );\n cache.oldNgtscProgram = angularProgram;\n } else {\n builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(typeScriptProgram, tsCompilerHost);\n }\n\n // Update semantic diagnostics cache\n const affectedFiles = new Set<ts.SourceFile>();\n\n // Analyze affected files when in watch mode for incremental type checking\n if ('getSemanticDiagnosticsOfNextAffectedFile' in builder) {\n while (true) {\n const result = builder.getSemanticDiagnosticsOfNextAffectedFile(undefined, sourceFile => {\n // If the affected file is a TTC shim, add the shim's original source file.\n // This ensures that changes that affect TTC are typechecked even when the changes\n // are otherwise unrelated from a TS perspective and do not result in Ivy codegen changes.\n // For example, changing @Input property types of a directive used in another component's\n // template.\n if (ignoreForDiagnostics.has(sourceFile) && sourceFile.fileName.endsWith('.ngtypecheck.ts')) {\n // This file name conversion relies on internal compiler logic and should be converted\n // to an official method when available. 15 is length of `.ngtypecheck.ts`\n const originalFilename = sourceFile.fileName.slice(0, -15) + '.ts';\n const originalSourceFile = builder.getSourceFile(originalFilename);\n if (originalSourceFile) {\n affectedFiles.add(originalSourceFile);\n }\n\n return true;\n }\n\n return false;\n });\n\n if (!result) {\n break;\n }\n\n affectedFiles.add(result.affected as ts.SourceFile);\n }\n\n // Add all files with associated template type checking files.\n // Stored TS build info does not have knowledge of the AOT compiler or the typechecking state of the templates.\n // To ensure that errors are reported correctly, all AOT component diagnostics need to be analyzed even if build\n // info is present.\n if (usingBuildInfo) {\n for (const sourceFile of builder.getSourceFiles()) {\n if (ignoreForDiagnostics.has(sourceFile) && sourceFile.fileName.endsWith('.ngtypecheck.ts')) {\n // This file name conversion relies on internal compiler logic and should be converted\n // to an official method when available. 15 is length of `.ngtypecheck.ts`\n const originalFilename = sourceFile.fileName.slice(0, -15) + '.ts';\n const originalSourceFile = builder.getSourceFile(originalFilename);\n if (originalSourceFile) {\n affectedFiles.add(originalSourceFile);\n }\n }\n }\n }\n }\n\n // Collect program level diagnostics\n const allDiagnostics: ts.Diagnostic[] = [\n ...angularCompiler.getOptionDiagnostics(),\n ...builder.getOptionsDiagnostics(),\n ...builder.getGlobalDiagnostics(),\n ];\n\n // Required to support asynchronous resource loading\n // Must be done before creating transformers or getting template diagnostics\n await angularCompiler.analyzeAsync();\n\n // Collect source file specific diagnostics\n const angularDiagnosticCache = cache.angularDiagnosticCache;\n for (const sourceFile of builder.getSourceFiles()) {\n if (ignoreForDiagnostics.has(sourceFile)) {\n continue;\n }\n\n allDiagnostics.push(\n ...builder.getSyntacticDiagnostics(sourceFile),\n ...builder.getSemanticDiagnostics(sourceFile),\n // We use the `typeScriptProgram` instead of `builder` here as a\n // performance workaround for: https://github.com/microsoft/TypeScript/issues/60970\n ...typeScriptProgram.getDeclarationDiagnostics(sourceFile),\n );\n\n // Declaration files cannot have template diagnostics\n if (sourceFile.isDeclarationFile) {\n continue;\n }\n\n // Only request Angular template diagnostics for affected files to avoid\n // overhead of template diagnostics for unchanged files.\n if (affectedFiles.has(sourceFile) || !angularDiagnosticCache.has(sourceFile)) {\n const angularDiagnostics = angularCompiler.getDiagnosticsForFile(\n sourceFile,\n affectedFiles.size === 1 ? /** OptimizeFor.SingleFile **/ 0 : /** OptimizeFor.WholeProgram */ 1,\n );\n\n angularDiagnosticCache.update(sourceFile, angularDiagnostics);\n }\n\n allDiagnostics.push(...angularDiagnosticCache.get(sourceFile));\n }\n\n const otherDiagnostics = [];\n const errorDiagnostics = [];\n for (const diagnostic of allDiagnostics) {\n if (diagnostic.category === ts.DiagnosticCategory.Error) {\n errorDiagnostics.push(diagnostic);\n } else {\n otherDiagnostics.push(diagnostic);\n }\n }\n\n if (otherDiagnostics.length) {\n log.msg(formatDiagnostics(errorDiagnostics));\n }\n\n if (errorDiagnostics.length) {\n throw new Error(formatDiagnostics(errorDiagnostics));\n }\n\n const transformers = angularCompiler.prepareEmit().transformers;\n\n if ('getSemanticDiagnosticsOfNextAffectedFile' in builder) {\n while (\n builder.emitNextAffectedFile((fileName, data, writeByteOrderMark, onError, sourceFiles) => {\n if (fileName.endsWith('.tsbuildinfo')) {\n tsCompilerHost.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles);\n }\n })\n ) {\n // empty\n }\n }\n\n for (const sourceFile of builder.getSourceFiles()) {\n if (ignoreForEmit.has(sourceFile)) {\n continue;\n }\n\n if (angularCompiler.incrementalCompilation.safeToSkipEmit(sourceFile)) {\n continue;\n }\n\n builder.emit(sourceFile, undefined, undefined, undefined, transformers);\n angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"compile-source-files.js","sourceRoot":"","sources":["../../../../src/lib/ngc/compile-source-files.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,gDA+MC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AAc,CAAC,UAAU,CAAC,EAAE,CAAC;YACtE,SAAS;QACX,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,YAAY,CAAC,CAAC;QACxE,eAAe,CAAC,sBAAsB,CAAC,oBAAoB,CAAC,UAAU,CAAC,CAAC;IAC1E,CAAC;AACH,CAAC","sourcesContent":["import { CompilerOptions, ParsedConfiguration } from '@angular/compiler-cli';\nimport { join } from 'node:path';\nimport ts from 'typescript';\nimport { BuildGraph } from '../graph/build-graph';\nimport { findEntryPointInProgress, findPackageNode } from '../ng-package/nodes';\nimport { NgPackagrOptions } from '../ng-package/options.di';\nimport { StylesheetProcessor } from '../styles/stylesheet-processor';\nimport { augmentProgramWithVersioning, cacheCompilerHost } from '../ts/cache-compiler-host';\nimport * as log from '../utils/log';\n\nexport async function compileSourceFiles(\n graph: BuildGraph,\n tsConfig: ParsedConfiguration,\n moduleResolutionCache: ts.ModuleResolutionCache,\n options: NgPackagrOptions,\n extraOptions?: Partial<CompilerOptions>,\n stylesheetProcessor?: StylesheetProcessor,\n) {\n const { NgtscProgram, formatDiagnostics } = await import('@angular/compiler-cli');\n const { cacheDirectory, watch, cacheEnabled } = options;\n const tsConfigOptions: CompilerOptions = { ...tsConfig.options, ...extraOptions };\n const entryPoint = findEntryPointInProgress(graph);\n const ngPackageNode = findPackageNode(graph);\n const inlineStyleLanguage = ngPackageNode.data.inlineStyleLanguage;\n\n const cacheDir = cacheEnabled && cacheDirectory;\n if (cacheDir) {\n tsConfigOptions.incremental ??= true;\n tsConfigOptions.tsBuildInfoFile ??= join(\n cacheDir,\n `tsbuildinfo/${entryPoint.data.entryPoint.flatModuleFile}.tsbuildinfo`,\n );\n }\n\n const tsCompilerHost = cacheCompilerHost(\n graph,\n entryPoint,\n tsConfigOptions,\n moduleResolutionCache,\n stylesheetProcessor,\n inlineStyleLanguage,\n );\n\n const cache = entryPoint.cache;\n let usingBuildInfo = false;\n\n let oldBuilder = cache.oldBuilder;\n if (!oldBuilder && cacheDir) {\n oldBuilder = ts.readBuilderProgram(tsConfigOptions, tsCompilerHost);\n usingBuildInfo = true;\n }\n\n // Create the Angular specific program that contains the Angular compiler\n const angularProgram = new NgtscProgram(tsConfig.rootNames, tsConfigOptions, tsCompilerHost, cache.oldNgtscProgram);\n\n const angularCompiler = angularProgram.compiler;\n const { ignoreForDiagnostics, ignoreForEmit } = angularCompiler;\n\n // SourceFile versions are required for builder programs.\n // The wrapped host inside NgtscProgram adds additional files that will not have versions.\n const typeScriptProgram = angularProgram.getTsProgram();\n augmentProgramWithVersioning(typeScriptProgram);\n\n let builder: ts.BuilderProgram | ts.EmitAndSemanticDiagnosticsBuilderProgram;\n if (watch || cacheDir) {\n builder = cache.oldBuilder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(\n typeScriptProgram,\n tsCompilerHost,\n oldBuilder,\n );\n cache.oldNgtscProgram = angularProgram;\n } else {\n builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(typeScriptProgram, tsCompilerHost);\n }\n\n // Update semantic diagnostics cache\n const affectedFiles = new Set<ts.SourceFile>();\n\n // Analyze affected files when in watch mode for incremental type checking\n if ('getSemanticDiagnosticsOfNextAffectedFile' in builder) {\n while (true) {\n const result = builder.getSemanticDiagnosticsOfNextAffectedFile(undefined, sourceFile => {\n // If the affected file is a TTC shim, add the shim's original source file.\n // This ensures that changes that affect TTC are typechecked even when the changes\n // are otherwise unrelated from a TS perspective and do not result in Ivy codegen changes.\n // For example, changing @Input property types of a directive used in another component's\n // template.\n if (ignoreForDiagnostics.has(sourceFile) && sourceFile.fileName.endsWith('.ngtypecheck.ts')) {\n // This file name conversion relies on internal compiler logic and should be converted\n // to an official method when available. 15 is length of `.ngtypecheck.ts`\n const originalFilename = sourceFile.fileName.slice(0, -15) + '.ts';\n const originalSourceFile = builder.getSourceFile(originalFilename);\n if (originalSourceFile) {\n affectedFiles.add(originalSourceFile);\n }\n\n return true;\n }\n\n return false;\n });\n\n if (!result) {\n break;\n }\n\n affectedFiles.add(result.affected as ts.SourceFile);\n }\n\n // Add all files with associated template type checking files.\n // Stored TS build info does not have knowledge of the AOT compiler or the typechecking state of the templates.\n // To ensure that errors are reported correctly, all AOT component diagnostics need to be analyzed even if build\n // info is present.\n if (usingBuildInfo) {\n for (const sourceFile of builder.getSourceFiles()) {\n if (ignoreForDiagnostics.has(sourceFile) && sourceFile.fileName.endsWith('.ngtypecheck.ts')) {\n // This file name conversion relies on internal compiler logic and should be converted\n // to an official method when available. 15 is length of `.ngtypecheck.ts`\n const originalFilename = sourceFile.fileName.slice(0, -15) + '.ts';\n const originalSourceFile = builder.getSourceFile(originalFilename);\n if (originalSourceFile) {\n affectedFiles.add(originalSourceFile);\n }\n }\n }\n }\n }\n\n // Collect program level diagnostics\n const allDiagnostics: ts.Diagnostic[] = [\n ...angularCompiler.getOptionDiagnostics(),\n ...builder.getOptionsDiagnostics(),\n ...builder.getGlobalDiagnostics(),\n ];\n\n // Required to support asynchronous resource loading\n // Must be done before creating transformers or getting template diagnostics\n await angularCompiler.analyzeAsync();\n\n // Collect source file specific diagnostics\n const angularDiagnosticCache = cache.angularDiagnosticCache;\n for (const sourceFile of builder.getSourceFiles()) {\n if (ignoreForDiagnostics.has(sourceFile)) {\n continue;\n }\n\n allDiagnostics.push(\n ...builder.getSyntacticDiagnostics(sourceFile),\n ...builder.getSemanticDiagnostics(sourceFile),\n // We use the `typeScriptProgram` instead of `builder` here as a\n // performance workaround for: https://github.com/microsoft/TypeScript/issues/60970\n ...typeScriptProgram.getDeclarationDiagnostics(sourceFile),\n );\n\n // Declaration files cannot have template diagnostics\n if (sourceFile.isDeclarationFile) {\n continue;\n }\n\n // Only request Angular template diagnostics for affected files to avoid\n // overhead of template diagnostics for unchanged files.\n if (affectedFiles.has(sourceFile) || !angularDiagnosticCache.has(sourceFile)) {\n const angularDiagnostics = angularCompiler.getDiagnosticsForFile(\n sourceFile,\n affectedFiles.size === 1 ? /** OptimizeFor.SingleFile **/ 0 : /** OptimizeFor.WholeProgram */ 1,\n );\n\n angularDiagnosticCache.update(sourceFile, angularDiagnostics);\n }\n\n allDiagnostics.push(...angularDiagnosticCache.get(sourceFile));\n }\n\n const otherDiagnostics = [];\n const errorDiagnostics = [];\n for (const diagnostic of allDiagnostics) {\n if (diagnostic.category === ts.DiagnosticCategory.Error) {\n errorDiagnostics.push(diagnostic);\n } else {\n otherDiagnostics.push(diagnostic);\n }\n }\n\n if (otherDiagnostics.length) {\n log.msg(formatDiagnostics(otherDiagnostics));\n }\n\n if (errorDiagnostics.length) {\n throw new Error(formatDiagnostics(errorDiagnostics));\n }\n\n const transformers = angularCompiler.prepareEmit().transformers;\n\n if ('getSemanticDiagnosticsOfNextAffectedFile' in builder) {\n while (\n builder.emitNextAffectedFile((fileName, data, writeByteOrderMark, onError, sourceFiles) => {\n if (fileName.endsWith('.tsbuildinfo')) {\n tsCompilerHost.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles);\n }\n })\n ) {\n // empty\n }\n }\n\n for (const sourceFile of builder.getSourceFiles()) {\n if (ignoreForEmit.has(sourceFile)) {\n continue;\n }\n\n if (angularCompiler.incrementalCompilation.safeToSkipEmit(sourceFile)) {\n continue;\n }\n\n builder.emit(sourceFile, undefined, undefined, undefined, transformers);\n angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile);\n }\n}\n"]}
|
|
@@ -45,7 +45,7 @@ export declare class BundlerContext {
|
|
|
45
45
|
* @returns If output files are generated, the full esbuild BuildResult; if not, the
|
|
46
46
|
* warnings and errors for the attempted build.
|
|
47
47
|
*/
|
|
48
|
-
bundle(): Promise<BundleContextResult>;
|
|
48
|
+
bundle(force?: boolean): Promise<BundleContextResult>;
|
|
49
49
|
/**
|
|
50
50
|
* Invalidate a stored bundler result based on the previous watch files
|
|
51
51
|
* and a list of changed files.
|
|
@@ -26,6 +26,8 @@ class BundlerContext {
|
|
|
26
26
|
#esbuildContext;
|
|
27
27
|
#esbuildOptions;
|
|
28
28
|
#esbuildResult;
|
|
29
|
+
#activeBundlePromise;
|
|
30
|
+
#disposed = false;
|
|
29
31
|
#optionsFactory;
|
|
30
32
|
#shouldCacheResult;
|
|
31
33
|
#loadCache;
|
|
@@ -53,12 +55,21 @@ class BundlerContext {
|
|
|
53
55
|
* @returns If output files are generated, the full esbuild BuildResult; if not, the
|
|
54
56
|
* warnings and errors for the attempted build.
|
|
55
57
|
*/
|
|
56
|
-
async bundle() {
|
|
58
|
+
async bundle(force = false) {
|
|
57
59
|
// Return existing result if present
|
|
58
60
|
if (this.#esbuildResult) {
|
|
59
61
|
return this.#esbuildResult;
|
|
60
62
|
}
|
|
61
|
-
|
|
63
|
+
if (!force && this.#activeBundlePromise !== undefined) {
|
|
64
|
+
return this.#activeBundlePromise;
|
|
65
|
+
}
|
|
66
|
+
const bundlePromise = this.#performBundle().finally(() => {
|
|
67
|
+
if (this.#activeBundlePromise === bundlePromise) {
|
|
68
|
+
this.#activeBundlePromise = undefined;
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
this.#activeBundlePromise = bundlePromise;
|
|
72
|
+
const result = await bundlePromise;
|
|
62
73
|
if (this.#shouldCacheResult) {
|
|
63
74
|
this.#esbuildResult = result;
|
|
64
75
|
}
|
|
@@ -84,7 +95,12 @@ class BundlerContext {
|
|
|
84
95
|
else if (this.incremental) {
|
|
85
96
|
// Create an incremental build context and perform the first build.
|
|
86
97
|
// Context creation does not perform a build.
|
|
87
|
-
|
|
98
|
+
const esbuildContext = await (0, esbuild_1.context)(this.#esbuildOptions);
|
|
99
|
+
if (this.#disposed) {
|
|
100
|
+
await esbuildContext.dispose();
|
|
101
|
+
throw new Error('BundlerContext was disposed during build.');
|
|
102
|
+
}
|
|
103
|
+
this.#esbuildContext = esbuildContext;
|
|
88
104
|
result = await this.#esbuildContext.rebuild();
|
|
89
105
|
}
|
|
90
106
|
else {
|
|
@@ -187,9 +203,11 @@ class BundlerContext {
|
|
|
187
203
|
* @returns A promise that resolves when disposal is complete.
|
|
188
204
|
*/
|
|
189
205
|
async dispose() {
|
|
206
|
+
this.#disposed = true;
|
|
190
207
|
try {
|
|
191
208
|
this.#esbuildOptions = undefined;
|
|
192
209
|
this.#esbuildResult = undefined;
|
|
210
|
+
this.#activeBundlePromise = undefined;
|
|
193
211
|
this.#loadCache = undefined;
|
|
194
212
|
await this.#esbuildContext?.dispose();
|
|
195
213
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundler-context.js","sourceRoot":"","sources":["../../../../src/lib/styles/bundler-context.ts"],"names":[],"mappings":";;;AAAA,qCAUiB;AACjB,yCAAiC;AACjC,2DAA6E;AAoB7E,IAAY,mBAMX;AAND,WAAY,mBAAmB;IAC7B,mEAAO,CAAA;IACP,+DAAK,CAAA;IACL,uFAAiB,CAAA;IACjB,yEAAU,CAAA;IACV,6DAAI,CAAA;AACN,CAAC,EANW,mBAAmB,mCAAnB,mBAAmB,QAM9B;AAYD;;;;GAIG;AACH,SAAS,gBAAgB,CAAC,KAAc;IACtC,OAAO,CAAC,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,QAAQ,IAAI,KAAK,IAAI,UAAU,IAAI,KAAK,CAAC;AAC1F,CAAC;AAED,MAAa,cAAc;IAUf;IACA;IAVV,eAAe,CAAkD;IACjE,eAAe,CAAmD;IAClE,cAAc,CAAuB;IACrC,eAAe,CAAyE;IACxF,kBAAkB,CAAU;IAC5B,UAAU,CAAyB;IAC1B,UAAU,GAAgB,IAAI,GAAG,EAAU,CAAC;IAErD,YACU,aAAqB,EACrB,WAAoB,EAC5B,OAA6C;QAFrC,kBAAa,GAAb,aAAa,CAAQ;QACrB,gBAAW,GAAX,WAAW,CAAS;QAG5B,2FAA2F;QAC3F,IAAI,CAAC,kBAAkB,GAAG,WAAW,IAAI,OAAO,OAAO,KAAK,UAAU,CAAC;QACvE,IAAI,CAAC,eAAe,GAAG,CAAC,GAAG,IAAI,EAAE,EAAE;YACjC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;;;;;;OAMG;IACH,UAAU,CAAC,KAAuB;QAChC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;YACtB,OAAO,KAAK,CAAC;QACf,CAAC;QAED,IAAI,OAAO,GAAG,KAAK,CAAC;QACpB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YACzB,IAAI,IAAI,CAAC,UAAU,EAAE,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;gBACtC,OAAO,GAAG,IAAI,CAAC;gBACf,SAAS;YACX,CAAC;YAED,OAAO,KAAK,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACxC,CAAC;QAED,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAClC,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,OAAO;QACX,IAAI,CAAC;YACH,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;YACjC,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;YAChC,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;YAC5B,MAAM,IAAI,CAAC,eAAe,EAAE,OAAO,EAAE,CAAC;QACxC,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACnC,CAAC;IACH,CAAC;CACF;AA/LD,wCA+LC;AAED,SAAS,qBAAqB,CAAC,IAAY;IACzC,OAAO,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;AACrC,CAAC","sourcesContent":["import {\n BuildContext,\n BuildFailure,\n BuildOptions,\n BuildResult,\n Message,\n Metafile,\n OutputFile,\n build,\n context,\n} from 'esbuild';\nimport { join } from 'node:path';\nimport { LoadResultCache, MemoryLoadResultCache } from './load-result-cache';\n\nexport type BundleContextResult =\n | { errors: Message[]; warnings: Message[] }\n | {\n errors: undefined;\n warnings: Message[];\n metafile: Metafile;\n outputFiles: BuildOutputFile[];\n };\n\nexport interface InitialFileRecord {\n entrypoint: boolean;\n name?: string;\n type: 'script' | 'style';\n external?: boolean;\n serverFile: boolean;\n depth: number;\n}\n\nexport enum BuildOutputFileType {\n Browser,\n Media,\n ServerApplication,\n ServerRoot,\n Root,\n}\n\nexport interface BuildOutputFile extends OutputFile {\n type: BuildOutputFileType;\n readonly size: number;\n clone: () => BuildOutputFile;\n}\n\nexport type BundlerOptionsFactory<T extends BuildOptions = BuildOptions> = (\n loadCache: LoadResultCache | undefined,\n) => T;\n\n/**\n * Determines if an unknown value is an esbuild BuildFailure error object thrown by esbuild.\n * @param value A potential esbuild BuildFailure error object.\n * @returns `true` if the object is determined to be a BuildFailure object; otherwise, `false`.\n */\nfunction isEsBuildFailure(value: unknown): value is BuildFailure {\n return !!value && typeof value === 'object' && 'errors' in value && 'warnings' in value;\n}\n\nexport class BundlerContext {\n #esbuildContext?: BuildContext<{ metafile: true; write: false }>;\n #esbuildOptions?: BuildOptions & { metafile: true; write: false };\n #esbuildResult?: BundleContextResult;\n #optionsFactory: BundlerOptionsFactory<BuildOptions & { metafile: true; write: false }>;\n #shouldCacheResult: boolean;\n #loadCache?: MemoryLoadResultCache;\n readonly watchFiles: Set<string> = new Set<string>();\n\n constructor(\n private workspaceRoot: string,\n private incremental: boolean,\n options: BuildOptions | BundlerOptionsFactory,\n ) {\n // To cache the results an option factory is needed to capture the full set of dependencies\n this.#shouldCacheResult = incremental && typeof options === 'function';\n this.#optionsFactory = (...args) => {\n const baseOptions = typeof options === 'function' ? options(...args) : options;\n\n return {\n ...baseOptions,\n metafile: true,\n write: false,\n };\n };\n }\n\n /**\n * Executes the esbuild build function and normalizes the build result in the event of a\n * build failure that results in no output being generated.\n * All builds use the `write` option with a value of `false` to allow for the output files\n * build result array to be populated.\n *\n * @returns If output files are generated, the full esbuild BuildResult; if not, the\n * warnings and errors for the attempted build.\n */\n async bundle(): Promise<BundleContextResult> {\n // Return existing result if present\n if (this.#esbuildResult) {\n return this.#esbuildResult;\n }\n\n const result = await this.#performBundle();\n if (this.#shouldCacheResult) {\n this.#esbuildResult = result;\n }\n\n return result;\n }\n\n async #performBundle(): Promise<BundleContextResult> {\n // Create esbuild options if not present\n if (this.#esbuildOptions === undefined) {\n if (this.incremental) {\n this.#loadCache = new MemoryLoadResultCache();\n }\n this.#esbuildOptions = this.#optionsFactory(this.#loadCache);\n }\n\n if (this.incremental) {\n this.watchFiles.clear();\n }\n\n let result: BuildResult<{ metafile: true; write: false }>;\n try {\n if (this.#esbuildContext) {\n // Rebuild using the existing incremental build context\n result = await this.#esbuildContext.rebuild();\n } else if (this.incremental) {\n // Create an incremental build context and perform the first build.\n // Context creation does not perform a build.\n this.#esbuildContext = await context(this.#esbuildOptions);\n result = await this.#esbuildContext.rebuild();\n } else {\n // For non-incremental builds, perform a single build\n result = await build(this.#esbuildOptions);\n }\n } catch (failure) {\n // Build failures will throw an exception which contains errors/warnings\n if (isEsBuildFailure(failure)) {\n this.#addErrorsToWatch(failure);\n\n return failure;\n } else {\n throw failure;\n }\n } finally {\n if (this.incremental) {\n // When incremental always add any files from the load result cache\n if (this.#loadCache) {\n for (const file of this.#loadCache.watchFiles) {\n if (!isInternalAngularFile(file)) {\n // watch files are fully resolved paths\n this.watchFiles.add(file);\n }\n }\n }\n }\n }\n\n // Update files that should be watched.\n // While this should technically not be linked to incremental mode, incremental is only\n // currently enabled with watch mode where watch files are needed.\n if (this.incremental) {\n // Add input files except virtual angular files which do not exist on disk\n for (const input of Object.keys(result.metafile.inputs)) {\n if (!isInternalAngularFile(input)) {\n // input file paths are always relative to the workspace root\n this.watchFiles.add(join(this.workspaceRoot, input));\n }\n }\n }\n\n // Return if the build encountered any errors\n if (result.errors.length) {\n this.#addErrorsToWatch(result);\n\n return {\n errors: result.errors,\n warnings: result.warnings,\n };\n }\n\n // Return the successful build results\n return {\n errors: undefined,\n warnings: result.warnings,\n metafile: result.metafile,\n outputFiles: result.outputFiles as BuildOutputFile[],\n };\n }\n\n #addErrorsToWatch(result: BuildFailure | BuildResult): void {\n for (const error of result.errors) {\n let file = error.location?.file;\n if (file && !isInternalAngularFile(file)) {\n this.watchFiles.add(join(this.workspaceRoot, file));\n }\n for (const note of error.notes) {\n file = note.location?.file;\n if (file && !isInternalAngularFile(file)) {\n this.watchFiles.add(join(this.workspaceRoot, file));\n }\n }\n }\n }\n\n /**\n * Invalidate a stored bundler result based on the previous watch files\n * and a list of changed files.\n * The context must be created with incremental mode enabled for results\n * to be stored.\n * @returns True, if the result was invalidated; False, otherwise.\n */\n invalidate(files: Iterable<string>): boolean {\n if (!this.incremental) {\n return false;\n }\n\n let invalid = false;\n for (const file of files) {\n if (this.#loadCache?.invalidate(file)) {\n invalid = true;\n continue;\n }\n\n invalid ||= this.watchFiles.has(file);\n }\n\n if (invalid) {\n this.#esbuildResult = undefined;\n }\n\n return invalid;\n }\n\n /**\n * Disposes incremental build resources present in the context.\n *\n * @returns A promise that resolves when disposal is complete.\n */\n async dispose(): Promise<void> {\n try {\n this.#esbuildOptions = undefined;\n this.#esbuildResult = undefined;\n this.#loadCache = undefined;\n await this.#esbuildContext?.dispose();\n } finally {\n this.#esbuildContext = undefined;\n }\n }\n}\n\nfunction isInternalAngularFile(file: string) {\n return file.startsWith('angular:');\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bundler-context.js","sourceRoot":"","sources":["../../../../src/lib/styles/bundler-context.ts"],"names":[],"mappings":";;;AAAA,qCAUiB;AACjB,yCAAiC;AACjC,2DAA6E;AAoB7E,IAAY,mBAMX;AAND,WAAY,mBAAmB;IAC7B,mEAAO,CAAA;IACP,+DAAK,CAAA;IACL,uFAAiB,CAAA;IACjB,yEAAU,CAAA;IACV,6DAAI,CAAA;AACN,CAAC,EANW,mBAAmB,mCAAnB,mBAAmB,QAM9B;AAYD;;;;GAIG;AACH,SAAS,gBAAgB,CAAC,KAAc;IACtC,OAAO,CAAC,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,QAAQ,IAAI,KAAK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AAK,CAAC;QACf,CAAC;QAED,IAAI,OAAO,GAAG,KAAK,CAAC;QACpB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YACzB,IAAI,IAAI,CAAC,UAAU,EAAE,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;gBACtC,OAAO,GAAG,IAAI,CAAC;gBACf,SAAS;YACX,CAAC;YAED,OAAO,KAAK,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACxC,CAAC;QAED,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAClC,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,OAAO;QACX,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC;YACH,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;YACjC,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;YAChC,IAAI,CAAC,oBAAoB,GAAG,SAAS,CAAC;YACtC,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;YAC5B,MAAM,IAAI,CAAC,eAAe,EAAE,OAAO,EAAE,CAAC;QACxC,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACnC,CAAC;IACH,CAAC;CACF;AAnND,wCAmNC;AAED,SAAS,qBAAqB,CAAC,IAAY;IACzC,OAAO,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;AACrC,CAAC","sourcesContent":["import {\n BuildContext,\n BuildFailure,\n BuildOptions,\n BuildResult,\n Message,\n Metafile,\n OutputFile,\n build,\n context,\n} from 'esbuild';\nimport { join } from 'node:path';\nimport { LoadResultCache, MemoryLoadResultCache } from './load-result-cache';\n\nexport type BundleContextResult =\n | { errors: Message[]; warnings: Message[] }\n | {\n errors: undefined;\n warnings: Message[];\n metafile: Metafile;\n outputFiles: BuildOutputFile[];\n };\n\nexport interface InitialFileRecord {\n entrypoint: boolean;\n name?: string;\n type: 'script' | 'style';\n external?: boolean;\n serverFile: boolean;\n depth: number;\n}\n\nexport enum BuildOutputFileType {\n Browser,\n Media,\n ServerApplication,\n ServerRoot,\n Root,\n}\n\nexport interface BuildOutputFile extends OutputFile {\n type: BuildOutputFileType;\n readonly size: number;\n clone: () => BuildOutputFile;\n}\n\nexport type BundlerOptionsFactory<T extends BuildOptions = BuildOptions> = (\n loadCache: LoadResultCache | undefined,\n) => T;\n\n/**\n * Determines if an unknown value is an esbuild BuildFailure error object thrown by esbuild.\n * @param value A potential esbuild BuildFailure error object.\n * @returns `true` if the object is determined to be a BuildFailure object; otherwise, `false`.\n */\nfunction isEsBuildFailure(value: unknown): value is BuildFailure {\n return !!value && typeof value === 'object' && 'errors' in value && 'warnings' in value;\n}\n\nexport class BundlerContext {\n #esbuildContext?: BuildContext<{ metafile: true; write: false }>;\n #esbuildOptions?: BuildOptions & { metafile: true; write: false };\n #esbuildResult?: BundleContextResult;\n #activeBundlePromise?: Promise<BundleContextResult>;\n #disposed = false;\n #optionsFactory: BundlerOptionsFactory<BuildOptions & { metafile: true; write: false }>;\n #shouldCacheResult: boolean;\n #loadCache?: MemoryLoadResultCache;\n readonly watchFiles: Set<string> = new Set<string>();\n\n constructor(\n private workspaceRoot: string,\n private incremental: boolean,\n options: BuildOptions | BundlerOptionsFactory,\n ) {\n // To cache the results an option factory is needed to capture the full set of dependencies\n this.#shouldCacheResult = incremental && typeof options === 'function';\n this.#optionsFactory = (...args) => {\n const baseOptions = typeof options === 'function' ? options(...args) : options;\n\n return {\n ...baseOptions,\n metafile: true,\n write: false,\n };\n };\n }\n\n /**\n * Executes the esbuild build function and normalizes the build result in the event of a\n * build failure that results in no output being generated.\n * All builds use the `write` option with a value of `false` to allow for the output files\n * build result array to be populated.\n *\n * @returns If output files are generated, the full esbuild BuildResult; if not, the\n * warnings and errors for the attempted build.\n */\n async bundle(force = false): Promise<BundleContextResult> {\n // Return existing result if present\n if (this.#esbuildResult) {\n return this.#esbuildResult;\n }\n\n if (!force && this.#activeBundlePromise !== undefined) {\n return this.#activeBundlePromise;\n }\n\n const bundlePromise = this.#performBundle().finally(() => {\n if (this.#activeBundlePromise === bundlePromise) {\n this.#activeBundlePromise = undefined;\n }\n });\n this.#activeBundlePromise = bundlePromise;\n\n const result = await bundlePromise;\n if (this.#shouldCacheResult) {\n this.#esbuildResult = result;\n }\n\n return result;\n }\n\n async #performBundle(): Promise<BundleContextResult> {\n // Create esbuild options if not present\n if (this.#esbuildOptions === undefined) {\n if (this.incremental) {\n this.#loadCache = new MemoryLoadResultCache();\n }\n this.#esbuildOptions = this.#optionsFactory(this.#loadCache);\n }\n\n if (this.incremental) {\n this.watchFiles.clear();\n }\n\n let result: BuildResult<{ metafile: true; write: false }>;\n try {\n if (this.#esbuildContext) {\n // Rebuild using the existing incremental build context\n result = await this.#esbuildContext.rebuild();\n } else if (this.incremental) {\n // Create an incremental build context and perform the first build.\n // Context creation does not perform a build.\n const esbuildContext = await context(this.#esbuildOptions);\n if (this.#disposed) {\n await esbuildContext.dispose();\n throw new Error('BundlerContext was disposed during build.');\n }\n this.#esbuildContext = esbuildContext;\n result = await this.#esbuildContext.rebuild();\n } else {\n // For non-incremental builds, perform a single build\n result = await build(this.#esbuildOptions);\n }\n } catch (failure) {\n // Build failures will throw an exception which contains errors/warnings\n if (isEsBuildFailure(failure)) {\n this.#addErrorsToWatch(failure);\n\n return failure;\n } else {\n throw failure;\n }\n } finally {\n if (this.incremental) {\n // When incremental always add any files from the load result cache\n if (this.#loadCache) {\n for (const file of this.#loadCache.watchFiles) {\n if (!isInternalAngularFile(file)) {\n // watch files are fully resolved paths\n this.watchFiles.add(file);\n }\n }\n }\n }\n }\n\n // Update files that should be watched.\n // While this should technically not be linked to incremental mode, incremental is only\n // currently enabled with watch mode where watch files are needed.\n if (this.incremental) {\n // Add input files except virtual angular files which do not exist on disk\n for (const input of Object.keys(result.metafile.inputs)) {\n if (!isInternalAngularFile(input)) {\n // input file paths are always relative to the workspace root\n this.watchFiles.add(join(this.workspaceRoot, input));\n }\n }\n }\n\n // Return if the build encountered any errors\n if (result.errors.length) {\n this.#addErrorsToWatch(result);\n\n return {\n errors: result.errors,\n warnings: result.warnings,\n };\n }\n\n // Return the successful build results\n return {\n errors: undefined,\n warnings: result.warnings,\n metafile: result.metafile,\n outputFiles: result.outputFiles as BuildOutputFile[],\n };\n }\n\n #addErrorsToWatch(result: BuildFailure | BuildResult): void {\n for (const error of result.errors) {\n let file = error.location?.file;\n if (file && !isInternalAngularFile(file)) {\n this.watchFiles.add(join(this.workspaceRoot, file));\n }\n for (const note of error.notes) {\n file = note.location?.file;\n if (file && !isInternalAngularFile(file)) {\n this.watchFiles.add(join(this.workspaceRoot, file));\n }\n }\n }\n }\n\n /**\n * Invalidate a stored bundler result based on the previous watch files\n * and a list of changed files.\n * The context must be created with incremental mode enabled for results\n * to be stored.\n * @returns True, if the result was invalidated; False, otherwise.\n */\n invalidate(files: Iterable<string>): boolean {\n if (!this.incremental) {\n return false;\n }\n\n let invalid = false;\n for (const file of files) {\n if (this.#loadCache?.invalidate(file)) {\n invalid = true;\n continue;\n }\n\n invalid ||= this.watchFiles.has(file);\n }\n\n if (invalid) {\n this.#esbuildResult = undefined;\n }\n\n return invalid;\n }\n\n /**\n * Disposes incremental build resources present in the context.\n *\n * @returns A promise that resolves when disposal is complete.\n */\n async dispose(): Promise<void> {\n this.#disposed = true;\n try {\n this.#esbuildOptions = undefined;\n this.#esbuildResult = undefined;\n this.#activeBundlePromise = undefined;\n this.#loadCache = undefined;\n await this.#esbuildContext?.dispose();\n } finally {\n this.#esbuildContext = undefined;\n }\n }\n}\n\nfunction isInternalAngularFile(file: string) {\n return file.startsWith('angular:');\n}\n"]}
|
|
@@ -28,6 +28,7 @@ export interface CacheStore<V> {
|
|
|
28
28
|
* to use a cache.
|
|
29
29
|
*/
|
|
30
30
|
export declare class Cache<V, S extends CacheStore<V> = CacheStore<V>> {
|
|
31
|
+
#private;
|
|
31
32
|
protected readonly store: S;
|
|
32
33
|
readonly namespace?: string;
|
|
33
34
|
constructor(store: S, namespace?: string);
|
|
@@ -59,6 +60,10 @@ export declare class Cache<V, S extends CacheStore<V> = CacheStore<V>> {
|
|
|
59
60
|
* @param value A value to put in the cache.
|
|
60
61
|
*/
|
|
61
62
|
put(key: string, value: V): Promise<void>;
|
|
63
|
+
/**
|
|
64
|
+
* Clears the base class internal state (requests, write counts, and pending gets).
|
|
65
|
+
*/
|
|
66
|
+
protected clearInternal(): void;
|
|
62
67
|
}
|
|
63
68
|
/**
|
|
64
69
|
* A lightweight in-memory cache implementation based on a JavaScript Map object.
|
package/src/lib/styles/cache.js
CHANGED
|
@@ -9,10 +9,23 @@ exports.MemoryCache = exports.Cache = void 0;
|
|
|
9
9
|
class Cache {
|
|
10
10
|
store;
|
|
11
11
|
namespace;
|
|
12
|
+
// In-flight creator promises to deduplicate concurrent requests for the same key.
|
|
13
|
+
#requests = new Map();
|
|
14
|
+
// Track how many writes occurred for a key to detect mutations during await gaps.
|
|
15
|
+
#writeCounts = new Map();
|
|
16
|
+
// Count the number of active, pending getOrCreate operations per key to avoid memory leaks.
|
|
17
|
+
#pendingGets = new Map();
|
|
12
18
|
constructor(store, namespace) {
|
|
13
19
|
this.store = store;
|
|
14
20
|
this.namespace = namespace;
|
|
15
21
|
}
|
|
22
|
+
#incrementWrite(key) {
|
|
23
|
+
// Only track write counts if there is a pending getOrCreate operation active for the key.
|
|
24
|
+
// This ensures that write counts are not leaked when no concurrent gets are running.
|
|
25
|
+
if (this.#pendingGets.has(key)) {
|
|
26
|
+
this.#writeCounts.set(key, (this.#writeCounts.get(key) || 0) + 1);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
16
29
|
/**
|
|
17
30
|
* Prefixes a key with the cache namespace if present.
|
|
18
31
|
* @param key A key string to prefix.
|
|
@@ -34,12 +47,63 @@ class Cache {
|
|
|
34
47
|
*/
|
|
35
48
|
async getOrCreate(key, creator) {
|
|
36
49
|
const namespacedKey = this.withNamespace(key);
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
50
|
+
// 1. If another call is already running the creator for this key, share its promise.
|
|
51
|
+
let activeRequest = this.#requests.get(namespacedKey);
|
|
52
|
+
if (activeRequest !== undefined) {
|
|
53
|
+
return activeRequest;
|
|
54
|
+
}
|
|
55
|
+
// Increment pending gets count to enable write-tracking for this key.
|
|
56
|
+
const currentPending = this.#pendingGets.get(namespacedKey) || 0;
|
|
57
|
+
this.#pendingGets.set(namespacedKey, currentPending + 1);
|
|
58
|
+
try {
|
|
59
|
+
const startWriteCount = this.#writeCounts.get(namespacedKey) || 0;
|
|
60
|
+
// 2. Query the backing store. Since store.get can be async, we yield to the event loop.
|
|
61
|
+
const value = await this.store.get(namespacedKey);
|
|
62
|
+
// If a write (e.g. put) occurred during the store.get await gap, we must abort
|
|
63
|
+
// the current execution and restart to ensure we return the newly written value.
|
|
64
|
+
if ((this.#writeCounts.get(namespacedKey) || 0) !== startWriteCount) {
|
|
65
|
+
return this.getOrCreate(key, creator);
|
|
66
|
+
}
|
|
67
|
+
if (value !== undefined) {
|
|
68
|
+
return value;
|
|
69
|
+
}
|
|
70
|
+
// 3. Recheck active request after the await gap in case another concurrent call
|
|
71
|
+
// initiated a creator during the store.get wait.
|
|
72
|
+
activeRequest = this.#requests.get(namespacedKey);
|
|
73
|
+
if (activeRequest !== undefined) {
|
|
74
|
+
return activeRequest;
|
|
75
|
+
}
|
|
76
|
+
// 4. Run the creator to produce the new value, and store its promise in #requests.
|
|
77
|
+
activeRequest = Promise.resolve(creator()).then(async (newValue) => {
|
|
78
|
+
// Ensure this request is still the active one before writing back to the store
|
|
79
|
+
// (prevents overwriting newer data if put() was called before resolution).
|
|
80
|
+
if (this.#requests.get(namespacedKey) === activeRequest) {
|
|
81
|
+
this.#incrementWrite(namespacedKey);
|
|
82
|
+
await this.store.set(namespacedKey, newValue);
|
|
83
|
+
this.#requests.delete(namespacedKey);
|
|
84
|
+
}
|
|
85
|
+
return newValue;
|
|
86
|
+
}, error => {
|
|
87
|
+
// Clean up the active request if the creator fails.
|
|
88
|
+
if (this.#requests.get(namespacedKey) === activeRequest) {
|
|
89
|
+
this.#requests.delete(namespacedKey);
|
|
90
|
+
}
|
|
91
|
+
throw error;
|
|
92
|
+
});
|
|
93
|
+
this.#requests.set(namespacedKey, activeRequest);
|
|
94
|
+
return activeRequest;
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
// Clean up write counts and pending gets once all concurrent gets for this key finish.
|
|
98
|
+
const current = this.#pendingGets.get(namespacedKey) || 0;
|
|
99
|
+
if (current <= 1) {
|
|
100
|
+
this.#pendingGets.delete(namespacedKey);
|
|
101
|
+
this.#writeCounts.delete(namespacedKey);
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
this.#pendingGets.set(namespacedKey, current - 1);
|
|
105
|
+
}
|
|
41
106
|
}
|
|
42
|
-
return value;
|
|
43
107
|
}
|
|
44
108
|
/**
|
|
45
109
|
* Gets the value associated with a provided key if available.
|
|
@@ -57,7 +121,18 @@ class Cache {
|
|
|
57
121
|
* @param value A value to put in the cache.
|
|
58
122
|
*/
|
|
59
123
|
async put(key, value) {
|
|
60
|
-
|
|
124
|
+
const namespacedKey = this.withNamespace(key);
|
|
125
|
+
this.#requests.delete(namespacedKey);
|
|
126
|
+
this.#incrementWrite(namespacedKey);
|
|
127
|
+
await this.store.set(namespacedKey, value);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Clears the base class internal state (requests, write counts, and pending gets).
|
|
131
|
+
*/
|
|
132
|
+
clearInternal() {
|
|
133
|
+
this.#requests.clear();
|
|
134
|
+
this.#writeCounts.clear();
|
|
135
|
+
this.#pendingGets.clear();
|
|
61
136
|
}
|
|
62
137
|
}
|
|
63
138
|
exports.Cache = Cache;
|
|
@@ -72,6 +147,7 @@ class MemoryCache extends Cache {
|
|
|
72
147
|
* Removes all entries from the cache instance.
|
|
73
148
|
*/
|
|
74
149
|
clear() {
|
|
150
|
+
this.clearInternal();
|
|
75
151
|
this.store.clear();
|
|
76
152
|
}
|
|
77
153
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache.js","sourceRoot":"","sources":["../../../../src/lib/styles/cache.ts"],"names":[],"mappings":";;;AA2BA;;;;GAIG;AACH,MAAa,KAAK;IAEK;IACV;IAFX,YACqB,KAAQ,EAClB,SAAkB;QADR,UAAK,GAAL,KAAK,CAAG;QAClB,cAAS,GAAT,SAAS,CAAS;IAC1B,CAAC;IAEJ;;;;OAIG;IACO,aAAa,CAAC,GAAW;QACjC,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACnB,OAAO,GAAG,IAAI,CAAC,SAAS,IAAI,GAAG,EAAE,CAAC;QACpC,CAAC;QAED,OAAO,GAAG,CAAC;IACb,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,WAAW,CAAC,GAAW,EAAE,OAA6B;QAC1D,MAAM,aAAa,GAAG,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;QAC9C,IAAI,KAAK,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;QAEhD,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,KAAK,GAAG,MAAM,OAAO,EAAE,CAAC;YACxB,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;QAC7C,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,GAAG,CAAC,GAAW;QACnB,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC;QAE5D,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,GAAG,CAAC,GAAW,EAAE,KAAQ;QAC7B,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC;IACvD,CAAC;CACF;AA3DD,sBA2DC;AAED;;GAEG;AACH,MAAa,WAAe,SAAQ,KAAwB;IAC1D;QACE,KAAK,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC;IACnB,CAAC;IAED;;OAEG;IACH,KAAK;QACH,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;IAED;;;OAGG;IACH,MAAM;QACJ,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC;IAC7B,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;IAC9B,CAAC;CACF;AA3BD,kCA2BC","sourcesContent":["/**\n * A backing data store for one or more Cache instances.\n * The interface is intentionally designed to support using a JavaScript\n * Map instance as a potential cache store.\n */\nexport interface CacheStore<V> {\n /**\n * Returns the specified value from the cache store or `undefined` if not found.\n * @param key The key to retrieve from the store.\n */\n get(key: string): V | undefined | Promise<V | undefined>;\n\n /**\n * Returns whether the provided key is present in the cache store.\n * @param key The key to check from the store.\n */\n has(key: string): boolean | Promise<boolean>;\n\n /**\n * Adds a new value to the cache store if the key is not present.\n * Updates the value for the key if already present.\n * @param key The key to associate with the value in the cache store.\n * @param value The value to add to the cache store.\n */\n set(key: string, value: V): this | Promise<this>;\n}\n\n/**\n * A cache object that allows accessing and storing key/value pairs in\n * an underlying CacheStore. This class is the primary method for consumers\n * to use a cache.\n */\nexport class Cache<V, S extends CacheStore<V> = CacheStore<V>> {\n constructor(\n protected readonly store: S,\n readonly namespace?: string,\n ) {}\n\n /**\n * Prefixes a key with the cache namespace if present.\n * @param key A key string to prefix.\n * @returns A prefixed key if a namespace is present. Otherwise the provided key.\n */\n protected withNamespace(key: string): string {\n if (this.namespace) {\n return `${this.namespace}:${key}`;\n }\n\n return key;\n }\n\n /**\n * Gets the value associated with a provided key if available.\n * Otherwise, creates a value using the factory creator function, puts the value\n * in the cache, and returns the new value.\n * @param key A key associated with the value.\n * @param creator A factory function for the value if no value is present.\n * @returns A value associated with the provided key.\n */\n async getOrCreate(key: string, creator: () => V | Promise<V>): Promise<V> {\n const namespacedKey = this.withNamespace(key);\n let value = await this.store.get(namespacedKey);\n\n if (value === undefined) {\n value = await creator();\n await this.store.set(namespacedKey, value);\n }\n\n return value;\n }\n\n /**\n * Gets the value associated with a provided key if available.\n * @param key A key associated with the value.\n * @returns A value associated with the provided key if present. Otherwise, `undefined`.\n */\n async get(key: string): Promise<V | undefined> {\n const value = await this.store.get(this.withNamespace(key));\n\n return value;\n }\n\n /**\n * Puts a value in the cache and associates it with the provided key.\n * If the key is already present, the value is updated instead.\n * @param key A key associated with the value.\n * @param value A value to put in the cache.\n */\n async put(key: string, value: V): Promise<void> {\n await this.store.set(this.withNamespace(key), value);\n }\n}\n\n/**\n * A lightweight in-memory cache implementation based on a JavaScript Map object.\n */\nexport class MemoryCache<V> extends Cache<V, Map<string, V>> {\n constructor() {\n super(new Map());\n }\n\n /**\n * Removes all entries from the cache instance.\n */\n clear() {\n this.store.clear();\n }\n\n /**\n * Provides all the values currently present in the cache instance.\n * @returns An iterable of all values in the cache.\n */\n values() {\n return this.store.values();\n }\n\n /**\n * Provides all the keys/values currently present in the cache instance.\n * @returns An iterable of all key/value pairs in the cache.\n */\n entries() {\n return this.store.entries();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cache.js","sourceRoot":"","sources":["../../../../src/lib/styles/cache.ts"],"names":[],"mappings":";;;AA2BA;;;;GAIG;AACH,MAAa,KAAK;IASK;IACV;IATX,kFAAkF;IACzE,SAAS,GAAG,IAAI,GAAG,EAAsB,CAAC;IACnD,kFAAkF;IACzE,YAAY,GAAG,IAAI,GAAG,EAAkB,CAAC;IAClD,4FAA4F;IACnF,YAAY,GAAG,IAAI,GAAG,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AC1B,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,CAAC;IAC5B,CAAC;CACF;AAnJD,sBAmJC;AAED;;GAEG;AACH,MAAa,WAAe,SAAQ,KAAwB;IAC1D;QACE,KAAK,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC;IACnB,CAAC;IAED;;OAEG;IACH,KAAK;QACH,IAAI,CAAC,aAAa,EAAE,CAAC;QACrB,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;IAED;;;OAGG;IACH,MAAM;QACJ,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC;IAC7B,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;IAC9B,CAAC;CACF;AA5BD,kCA4BC","sourcesContent":["/**\n * A backing data store for one or more Cache instances.\n * The interface is intentionally designed to support using a JavaScript\n * Map instance as a potential cache store.\n */\nexport interface CacheStore<V> {\n /**\n * Returns the specified value from the cache store or `undefined` if not found.\n * @param key The key to retrieve from the store.\n */\n get(key: string): V | undefined | Promise<V | undefined>;\n\n /**\n * Returns whether the provided key is present in the cache store.\n * @param key The key to check from the store.\n */\n has(key: string): boolean | Promise<boolean>;\n\n /**\n * Adds a new value to the cache store if the key is not present.\n * Updates the value for the key if already present.\n * @param key The key to associate with the value in the cache store.\n * @param value The value to add to the cache store.\n */\n set(key: string, value: V): this | Promise<this>;\n}\n\n/**\n * A cache object that allows accessing and storing key/value pairs in\n * an underlying CacheStore. This class is the primary method for consumers\n * to use a cache.\n */\nexport class Cache<V, S extends CacheStore<V> = CacheStore<V>> {\n // In-flight creator promises to deduplicate concurrent requests for the same key.\n readonly #requests = new Map<string, Promise<V>>();\n // Track how many writes occurred for a key to detect mutations during await gaps.\n readonly #writeCounts = new Map<string, number>();\n // Count the number of active, pending getOrCreate operations per key to avoid memory leaks.\n readonly #pendingGets = new Map<string, number>();\n\n constructor(\n protected readonly store: S,\n readonly namespace?: string,\n ) {}\n\n #incrementWrite(key: string) {\n // Only track write counts if there is a pending getOrCreate operation active for the key.\n // This ensures that write counts are not leaked when no concurrent gets are running.\n if (this.#pendingGets.has(key)) {\n this.#writeCounts.set(key, (this.#writeCounts.get(key) || 0) + 1);\n }\n }\n\n /**\n * Prefixes a key with the cache namespace if present.\n * @param key A key string to prefix.\n * @returns A prefixed key if a namespace is present. Otherwise the provided key.\n */\n protected withNamespace(key: string): string {\n if (this.namespace) {\n return `${this.namespace}:${key}`;\n }\n\n return key;\n }\n\n /**\n * Gets the value associated with a provided key if available.\n * Otherwise, creates a value using the factory creator function, puts the value\n * in the cache, and returns the new value.\n * @param key A key associated with the value.\n * @param creator A factory function for the value if no value is present.\n * @returns A value associated with the provided key.\n */\n async getOrCreate(key: string, creator: () => V | Promise<V>): Promise<V> {\n const namespacedKey = this.withNamespace(key);\n\n // 1. If another call is already running the creator for this key, share its promise.\n let activeRequest = this.#requests.get(namespacedKey);\n if (activeRequest !== undefined) {\n return activeRequest;\n }\n\n // Increment pending gets count to enable write-tracking for this key.\n const currentPending = this.#pendingGets.get(namespacedKey) || 0;\n this.#pendingGets.set(namespacedKey, currentPending + 1);\n\n try {\n const startWriteCount = this.#writeCounts.get(namespacedKey) || 0;\n\n // 2. Query the backing store. Since store.get can be async, we yield to the event loop.\n const value = await this.store.get(namespacedKey);\n\n // If a write (e.g. put) occurred during the store.get await gap, we must abort\n // the current execution and restart to ensure we return the newly written value.\n if ((this.#writeCounts.get(namespacedKey) || 0) !== startWriteCount) {\n return this.getOrCreate(key, creator);\n }\n\n if (value !== undefined) {\n return value;\n }\n\n // 3. Recheck active request after the await gap in case another concurrent call\n // initiated a creator during the store.get wait.\n activeRequest = this.#requests.get(namespacedKey);\n if (activeRequest !== undefined) {\n return activeRequest;\n }\n\n // 4. Run the creator to produce the new value, and store its promise in #requests.\n activeRequest = Promise.resolve(creator()).then(\n async newValue => {\n // Ensure this request is still the active one before writing back to the store\n // (prevents overwriting newer data if put() was called before resolution).\n if (this.#requests.get(namespacedKey) === activeRequest) {\n this.#incrementWrite(namespacedKey);\n await this.store.set(namespacedKey, newValue);\n this.#requests.delete(namespacedKey);\n }\n\n return newValue;\n },\n error => {\n // Clean up the active request if the creator fails.\n if (this.#requests.get(namespacedKey) === activeRequest) {\n this.#requests.delete(namespacedKey);\n }\n throw error;\n },\n );\n\n this.#requests.set(namespacedKey, activeRequest);\n\n return activeRequest;\n } finally {\n // Clean up write counts and pending gets once all concurrent gets for this key finish.\n const current = this.#pendingGets.get(namespacedKey) || 0;\n if (current <= 1) {\n this.#pendingGets.delete(namespacedKey);\n this.#writeCounts.delete(namespacedKey);\n } else {\n this.#pendingGets.set(namespacedKey, current - 1);\n }\n }\n }\n\n /**\n * Gets the value associated with a provided key if available.\n * @param key A key associated with the value.\n * @returns A value associated with the provided key if present. Otherwise, `undefined`.\n */\n async get(key: string): Promise<V | undefined> {\n const value = await this.store.get(this.withNamespace(key));\n\n return value;\n }\n\n /**\n * Puts a value in the cache and associates it with the provided key.\n * If the key is already present, the value is updated instead.\n * @param key A key associated with the value.\n * @param value A value to put in the cache.\n */\n async put(key: string, value: V): Promise<void> {\n const namespacedKey = this.withNamespace(key);\n this.#requests.delete(namespacedKey);\n this.#incrementWrite(namespacedKey);\n await this.store.set(namespacedKey, value);\n }\n\n /**\n * Clears the base class internal state (requests, write counts, and pending gets).\n */\n protected clearInternal(): void {\n this.#requests.clear();\n this.#writeCounts.clear();\n this.#pendingGets.clear();\n }\n}\n\n/**\n * A lightweight in-memory cache implementation based on a JavaScript Map object.\n */\nexport class MemoryCache<V> extends Cache<V, Map<string, V>> {\n constructor() {\n super(new Map());\n }\n\n /**\n * Removes all entries from the cache instance.\n */\n clear() {\n this.clearInternal();\n this.store.clear();\n }\n\n /**\n * Provides all the values currently present in the cache instance.\n * @returns An iterable of all values in the cache.\n */\n values() {\n return this.store.values();\n }\n\n /**\n * Provides all the keys/values currently present in the cache instance.\n * @returns An iterable of all key/value pairs in the cache.\n */\n entries() {\n return this.store.entries();\n }\n}\n"]}
|
|
@@ -78,9 +78,45 @@ class SassWorkerImplementation {
|
|
|
78
78
|
rebase;
|
|
79
79
|
maxThreads;
|
|
80
80
|
#workerPool;
|
|
81
|
+
/** Queue of pending transformation tasks waiting for an active concurrency slot. */
|
|
82
|
+
#pendingTasks = [];
|
|
83
|
+
/** Current count of actively executing transformation tasks. */
|
|
84
|
+
#activeTasks = 0;
|
|
85
|
+
/** Maximum number of transformation tasks allowed to execute concurrently. */
|
|
86
|
+
#maxConcurrent;
|
|
81
87
|
constructor(rebase = false, maxThreads = MAX_RENDER_WORKERS) {
|
|
82
88
|
this.rebase = rebase;
|
|
83
89
|
this.maxThreads = maxThreads;
|
|
90
|
+
// Maintain 2 active tasks per worker thread to keep transformation pipelines fully saturated
|
|
91
|
+
this.#maxConcurrent = Math.max(1, maxThreads * 2);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Executes a transformation action using a semaphore-based backpressure throttle.
|
|
95
|
+
* Prevents libuv thread pool saturation and excessive V8 heap accumulation.
|
|
96
|
+
* @param action A callback that produces a promise for the transformation result.
|
|
97
|
+
* @returns A promise resolving to the transformation result.
|
|
98
|
+
*/
|
|
99
|
+
async #runWithThrottle(action) {
|
|
100
|
+
if (this.#activeTasks >= this.#maxConcurrent) {
|
|
101
|
+
await new Promise((resolve, reject) => {
|
|
102
|
+
this.#pendingTasks.push({ resolve, reject });
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
this.#activeTasks++;
|
|
107
|
+
}
|
|
108
|
+
try {
|
|
109
|
+
return await action();
|
|
110
|
+
}
|
|
111
|
+
finally {
|
|
112
|
+
const next = this.#pendingTasks.shift();
|
|
113
|
+
if (next) {
|
|
114
|
+
next.resolve();
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
this.#activeTasks--;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
84
120
|
}
|
|
85
121
|
#ensureWorkerPool() {
|
|
86
122
|
this.#workerPool ??= new worker_pool_1.WorkerPool({
|
|
@@ -109,63 +145,65 @@ class SassWorkerImplementation {
|
|
|
109
145
|
* @param options The `dart-sass` options to use when rendering the stylesheet.
|
|
110
146
|
*/
|
|
111
147
|
async compileStringAsync(source, options) {
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
148
|
+
// The `functions`, `logger` and `importer` options are JavaScript functions that cannot be transferred.
|
|
149
|
+
// If any additional function options are added in the future, they must be excluded as well.
|
|
150
|
+
const { functions, importers, url, logger, ...serializableOptions } = options;
|
|
151
|
+
// The CLI's configuration does not use or expose the ability to define custom Sass functions
|
|
152
|
+
if (functions && Object.keys(functions).length > 0) {
|
|
153
|
+
throw new Error('Sass custom functions are not supported.');
|
|
154
|
+
}
|
|
155
|
+
return this.#runWithThrottle(async () => {
|
|
156
|
+
const env_1 = { stack: [], error: void 0, hasError: false };
|
|
157
|
+
try {
|
|
158
|
+
const importerChannel = __addDisposableResource(env_1, importers?.length ? this.#createImporterChannel(importers) : undefined, false);
|
|
159
|
+
const response = (await this.#ensureWorkerPool().run({
|
|
160
|
+
source,
|
|
161
|
+
importerChannel,
|
|
162
|
+
hasLogger: !!logger,
|
|
163
|
+
rebase: this.rebase,
|
|
164
|
+
options: {
|
|
165
|
+
...serializableOptions,
|
|
166
|
+
// URL is not serializable so to convert to string here and back to URL in the worker.
|
|
167
|
+
url: url ? (0, node_url_1.fileURLToPath)(url) : undefined,
|
|
168
|
+
},
|
|
169
|
+
}, {
|
|
170
|
+
transferList: importerChannel ? [importerChannel.port] : undefined,
|
|
171
|
+
}));
|
|
172
|
+
const { result, error, warnings } = response;
|
|
173
|
+
if (warnings && logger?.warn) {
|
|
174
|
+
for (const { message, span, ...options } of warnings) {
|
|
175
|
+
logger.warn(message, {
|
|
176
|
+
...options,
|
|
177
|
+
span: span && {
|
|
178
|
+
...span,
|
|
179
|
+
url: span.url ? (0, node_url_1.pathToFileURL)(span.url) : undefined,
|
|
180
|
+
},
|
|
181
|
+
});
|
|
182
|
+
}
|
|
145
183
|
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
184
|
+
if (error) {
|
|
185
|
+
// Convert stringified url value required for cloning back to a URL object
|
|
186
|
+
const url = error.span?.url;
|
|
187
|
+
if (url) {
|
|
188
|
+
error.span.url = (0, node_url_1.pathToFileURL)(url);
|
|
189
|
+
}
|
|
190
|
+
throw error;
|
|
152
191
|
}
|
|
153
|
-
|
|
192
|
+
(0, node_assert_1.default)(result, 'Sass render worker should always return a result or an error');
|
|
193
|
+
return {
|
|
194
|
+
...result,
|
|
195
|
+
// URL is not serializable so in the worker we convert to string and here back to URL.
|
|
196
|
+
loadedUrls: result.loadedUrls.map(p => (0, node_url_1.pathToFileURL)(p)),
|
|
197
|
+
};
|
|
154
198
|
}
|
|
155
|
-
(
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
env_1.error = e_1;
|
|
164
|
-
env_1.hasError = true;
|
|
165
|
-
}
|
|
166
|
-
finally {
|
|
167
|
-
__disposeResources(env_1);
|
|
168
|
-
}
|
|
199
|
+
catch (e_1) {
|
|
200
|
+
env_1.error = e_1;
|
|
201
|
+
env_1.hasError = true;
|
|
202
|
+
}
|
|
203
|
+
finally {
|
|
204
|
+
__disposeResources(env_1);
|
|
205
|
+
}
|
|
206
|
+
});
|
|
169
207
|
}
|
|
170
208
|
/**
|
|
171
209
|
* Shutdown the Sass render worker.
|
|
@@ -173,6 +211,11 @@ class SassWorkerImplementation {
|
|
|
173
211
|
* @returns A void promise that resolves when closing is complete.
|
|
174
212
|
*/
|
|
175
213
|
async close() {
|
|
214
|
+
const pending = this.#pendingTasks;
|
|
215
|
+
this.#pendingTasks = [];
|
|
216
|
+
for (const task of pending) {
|
|
217
|
+
task.reject(new Error('SassWorkerImplementation closed.'));
|
|
218
|
+
}
|
|
176
219
|
if (this.#workerPool) {
|
|
177
220
|
try {
|
|
178
221
|
await this.#workerPool.destroy();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sass-service.js","sourceRoot":"","sources":["../../../../../src/lib/styles/sass/sass-service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,8DAAiC;AACjC,uCAAwD;AACxD,6DAAqD;AAarD,gDAA4C;AAE5C,MAAM,kBAAkB,GAAG,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;AAC/D,MAAM,UAAU,GAAG,OAAO,kBAAkB,KAAK,QAAQ,IAAI,kBAAkB,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,CAAC;AAEjH,yCAAyC;AAExC,MAAc,CAAC,OAAO,KAAK,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAErD;;GAEG;AACH,MAAM,kBAAkB,GAAG,UAAU,CAAC;AA+CtC;;;;;GAKG;AACH,MAAa,wBAAwB;IAIhB;IACR;IAJX,WAAW,CAAyB;IAEpC,YACmB,SAAS,KAAK,EACtB,aAAa,kBAAkB;QADvB,WAAM,GAAN,MAAM,CAAQ;QACtB,eAAU,GAAV,UAAU,CAAqB;IACvC,CAAC;IAEJ,iBAAiB;Q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AM,CAAC,OAAO,CAAC;gBACd,gBAAgB,CAAC,KAAK,EAAE,CAAC;YAC3B,CAAC;SACF,CAAC;IACJ,CAAC;IAEO,KAAK,CAAC,gBAAgB,CAC5B,SAA8B,EAC9B,GAAW,EACX,OAA4B;QAE5B,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACnC,WAAW;gBACX,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;YACxD,CAAC;YAED,uCAAuC;YACvC,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;YACxD,IAAI,MAAM,EAAE,CAAC;gBACX,OAAO,IAAA,wBAAa,EAAC,MAAM,CAAC,CAAC;YAC/B,CAAC;QACH,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;IAEO,cAAc,CAAC,KAAgB;QACrC,OAAO,aAAa,IAAI,KAAK,CAAC;IAChC,CAAC;CACF;AA5KD,4DA4KC","sourcesContent":["import assert from 'node:assert';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { MessageChannel } from 'node:worker_threads';\nimport type {\n CanonicalizeContext,\n CompileResult,\n Deprecation,\n Exception,\n FileImporter,\n Importer,\n NodePackageImporter,\n SourceSpan,\n StringOptions,\n} from 'sass';\n\nimport { WorkerPool } from '../worker-pool';\n\nconst maxWorkersVariable = process.env['NG_BUILD_MAX_WORKERS'];\nconst maxWorkers = typeof maxWorkersVariable === 'string' && maxWorkersVariable !== '' ? +maxWorkersVariable : 4;\n\n// Polyfill Symbol.dispose if not present\n\n(Symbol as any).dispose ??= Symbol('Symbol Dispose');\n\n/**\n * The maximum number of Workers that will be created to execute render requests.\n */\nconst MAX_RENDER_WORKERS = maxWorkers;\n\n/**\n * All available importer types.\n */\ntype Importers =\n | Importer<'sync'>\n | Importer<'async'>\n | FileImporter<'sync'>\n | FileImporter<'async'>\n | NodePackageImporter;\n\nexport interface SerializableVersion {\n major: number;\n minor: number;\n patch: number;\n}\n\nexport interface SerializableDeprecation extends Omit<Deprecation, 'obsoleteIn' | 'deprecatedIn'> {\n /** The version this deprecation first became active in. */\n deprecatedIn: SerializableVersion | null;\n\n /** The version this deprecation became obsolete in. */\n obsoleteIn: SerializableVersion | null;\n}\n\nexport type SerializableWarningMessage = (\n | {\n deprecation: true;\n deprecationType: SerializableDeprecation;\n }\n | { deprecation: false }\n) & {\n message: string;\n span?: Omit<SourceSpan, 'url'> & { url?: string };\n stack?: string;\n};\n\n/**\n * A response from the Sass render Worker containing the result of the operation.\n */\ninterface RenderResponseMessage {\n error?: Exception;\n result?: Omit<CompileResult, 'loadedUrls'> & { loadedUrls: string[] };\n warnings?: SerializableWarningMessage[];\n}\n\n/**\n * A Sass renderer implementation that provides an interface that can be used by Webpack's\n * `sass-loader`. The implementation uses a Worker thread to perform the Sass rendering\n * with the `dart-sass` package. The `dart-sass` synchronous render function is used within\n * the worker which can be up to two times faster than the asynchronous variant.\n */\nexport class SassWorkerImplementation {\n #workerPool: WorkerPool | undefined;\n\n constructor(\n private readonly rebase = false,\n readonly maxThreads = MAX_RENDER_WORKERS,\n ) {}\n\n #ensureWorkerPool(): WorkerPool {\n this.#workerPool ??= new WorkerPool({\n filename: require.resolve('./worker'),\n maxThreads: this.maxThreads,\n });\n\n return this.#workerPool;\n }\n\n /**\n * Provides information about the Sass implementation.\n * This mimics enough of the `dart-sass` value to be used with the `sass-loader`.\n */\n get info(): string {\n return 'dart-sass\\tworker';\n }\n\n /**\n * The synchronous render function is not used by the `sass-loader`.\n */\n compileString(): never {\n throw new Error('Sass compileString is not supported.');\n }\n\n /**\n * Asynchronously request a Sass stylesheet to be renderered.\n *\n * @param source The contents to compile.\n * @param options The `dart-sass` options to use when rendering the stylesheet.\n */\n async compileStringAsync(source: string, options: StringOptions<'async'>): Promise<CompileResult> {\n // The `functions`, `logger` and `importer` options are JavaScript functions that cannot be transferred.\n // If any additional function options are added in the future, they must be excluded as well.\n const { functions, importers, url, logger, ...serializableOptions } = options;\n\n // The CLI's configuration does not use or expose the ability to define custom Sass functions\n if (functions && Object.keys(functions).length > 0) {\n throw new Error('Sass custom functions are not supported.');\n }\n\n using importerChannel = importers?.length ? this.#createImporterChannel(importers) : undefined;\n\n const response = (await this.#ensureWorkerPool().run(\n {\n source,\n importerChannel,\n hasLogger: !!logger,\n rebase: this.rebase,\n options: {\n ...serializableOptions,\n // URL is not serializable so to convert to string here and back to URL in the worker.\n url: url ? fileURLToPath(url) : undefined,\n },\n },\n {\n transferList: importerChannel ? [importerChannel.port] : undefined,\n },\n )) as RenderResponseMessage;\n\n const { result, error, warnings } = response;\n\n if (warnings && logger?.warn) {\n for (const { message, span, ...options } of warnings) {\n logger.warn(message, {\n ...options,\n span: span && {\n ...span,\n url: span.url ? pathToFileURL(span.url) : undefined,\n },\n });\n }\n }\n\n if (error) {\n // Convert stringified url value required for cloning back to a URL object\n const url = error.span?.url as unknown as string | undefined;\n if (url) {\n error.span.url = pathToFileURL(url);\n }\n\n throw error;\n }\n\n assert(result, 'Sass render worker should always return a result or an error');\n\n return {\n ...result,\n // URL is not serializable so in the worker we convert to string and here back to URL.\n loadedUrls: result.loadedUrls.map(p => pathToFileURL(p)),\n };\n }\n\n /**\n * Shutdown the Sass render worker.\n * Executing this method will stop any pending render requests.\n * @returns A void promise that resolves when closing is complete.\n */\n async close(): Promise<void> {\n if (this.#workerPool) {\n try {\n await this.#workerPool.destroy();\n } finally {\n this.#workerPool = undefined;\n }\n }\n }\n\n #createImporterChannel(importers: Iterable<Importers>) {\n const { port1: mainImporterPort, port2: workerImporterPort } = new MessageChannel();\n const importerSignal = new Int32Array(new SharedArrayBuffer(4));\n\n mainImporterPort.on('message', ({ url, options }: { url: string; options: CanonicalizeContext }) => {\n this.processImporters(importers, url, {\n ...options,\n // URL is not serializable so in the worker we convert to string and here back to URL.\n containingUrl: options.containingUrl ? pathToFileURL(options.containingUrl as unknown as string) : null,\n })\n .then(result => {\n mainImporterPort.postMessage(result);\n })\n .catch(error => {\n mainImporterPort.postMessage(error);\n })\n .finally(() => {\n Atomics.store(importerSignal, 0, 1);\n Atomics.notify(importerSignal, 0);\n });\n });\n\n mainImporterPort.unref();\n\n return {\n port: workerImporterPort,\n signal: importerSignal,\n [Symbol.dispose]() {\n mainImporterPort.close();\n },\n };\n }\n\n private async processImporters(\n importers: Iterable<Importers>,\n url: string,\n options: CanonicalizeContext,\n ): Promise<string | null> {\n for (const importer of importers) {\n if (!this.isFileImporter(importer)) {\n // Importer\n throw new Error('Only File Importers are supported.');\n }\n\n // File importer (Can be sync or aync).\n const result = await importer.findFileUrl(url, options);\n if (result) {\n return fileURLToPath(result);\n }\n }\n\n return null;\n }\n\n private isFileImporter(value: Importers): value is FileImporter {\n return 'findFileUrl' in value;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sass-service.js","sourceRoot":"","sources":["../../../../../src/lib/styles/sass/sass-service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,8DAAiC;AACjC,uCAAwD;AACxD,6DAAqD;AAarD,gDAA4C;AAE5C,MAAM,kBAAkB,GAAG,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;AAC/D,MAAM,UAAU,GAAG,OAAO,kBAAkB,KAAK,QAAQ,IAAI,kBAAkB,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,CAAC;AAEjH,yCAAyC;AAExC,MAAc,CAAC,OAAO,KAAK,MAAM,CAAC,gBAAgB,CAAC,CAAC;AAErD;;GAEG;AACH,MAAM,kBAAkB,GAAG,UAAU,CAAC;AA+CtC;;;;;GAKG;AACH,MAAa,wBAAwB;IAahB;IACR;IAbX,WAAW,CAAyB;IAEpC,oFAAoF;IACpF,aAAa,GAA+D,EAAE,CAAC;IAE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AAC;QAEzB,OAAO;YACL,IAAI,EAAE,kBAAkB;YACxB,MAAM,EAAE,cAAc;YACtB,CAAC,MAAM,CAAC,OAAO,CAAC;gBACd,gBAAgB,CAAC,KAAK,EAAE,CAAC;YAC3B,CAAC;SACF,CAAC;IACJ,CAAC;IAEO,KAAK,CAAC,gBAAgB,CAC5B,SAA8B,EAC9B,GAAW,EACX,OAA4B;QAE5B,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACnC,WAAW;gBACX,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;YACxD,CAAC;YAED,uCAAuC;YACvC,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;YACxD,IAAI,MAAM,EAAE,CAAC;gBACX,OAAO,IAAA,wBAAa,EAAC,MAAM,CAAC,CAAC;YAC/B,CAAC;QACH,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;IAEO,cAAc,CAAC,KAAgB;QACrC,OAAO,aAAa,IAAI,KAAK,CAAC;IAChC,CAAC;CACF;AA3ND,4DA2NC","sourcesContent":["import assert from 'node:assert';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { MessageChannel } from 'node:worker_threads';\nimport type {\n CanonicalizeContext,\n CompileResult,\n Deprecation,\n Exception,\n FileImporter,\n Importer,\n NodePackageImporter,\n SourceSpan,\n StringOptions,\n} from 'sass';\n\nimport { WorkerPool } from '../worker-pool';\n\nconst maxWorkersVariable = process.env['NG_BUILD_MAX_WORKERS'];\nconst maxWorkers = typeof maxWorkersVariable === 'string' && maxWorkersVariable !== '' ? +maxWorkersVariable : 4;\n\n// Polyfill Symbol.dispose if not present\n\n(Symbol as any).dispose ??= Symbol('Symbol Dispose');\n\n/**\n * The maximum number of Workers that will be created to execute render requests.\n */\nconst MAX_RENDER_WORKERS = maxWorkers;\n\n/**\n * All available importer types.\n */\ntype Importers =\n | Importer<'sync'>\n | Importer<'async'>\n | FileImporter<'sync'>\n | FileImporter<'async'>\n | NodePackageImporter;\n\nexport interface SerializableVersion {\n major: number;\n minor: number;\n patch: number;\n}\n\nexport interface SerializableDeprecation extends Omit<Deprecation, 'obsoleteIn' | 'deprecatedIn'> {\n /** The version this deprecation first became active in. */\n deprecatedIn: SerializableVersion | null;\n\n /** The version this deprecation became obsolete in. */\n obsoleteIn: SerializableVersion | null;\n}\n\nexport type SerializableWarningMessage = (\n | {\n deprecation: true;\n deprecationType: SerializableDeprecation;\n }\n | { deprecation: false }\n) & {\n message: string;\n span?: Omit<SourceSpan, 'url'> & { url?: string };\n stack?: string;\n};\n\n/**\n * A response from the Sass render Worker containing the result of the operation.\n */\ninterface RenderResponseMessage {\n error?: Exception;\n result?: Omit<CompileResult, 'loadedUrls'> & { loadedUrls: string[] };\n warnings?: SerializableWarningMessage[];\n}\n\n/**\n * A Sass renderer implementation that provides an interface that can be used by Webpack's\n * `sass-loader`. The implementation uses a Worker thread to perform the Sass rendering\n * with the `dart-sass` package. The `dart-sass` synchronous render function is used within\n * the worker which can be up to two times faster than the asynchronous variant.\n */\nexport class SassWorkerImplementation {\n #workerPool: WorkerPool | undefined;\n\n /** Queue of pending transformation tasks waiting for an active concurrency slot. */\n #pendingTasks: { resolve: () => void; reject: (reason: Error) => void }[] = [];\n\n /** Current count of actively executing transformation tasks. */\n #activeTasks = 0;\n\n /** Maximum number of transformation tasks allowed to execute concurrently. */\n readonly #maxConcurrent: number;\n\n constructor(\n private readonly rebase = false,\n readonly maxThreads = MAX_RENDER_WORKERS,\n ) {\n // Maintain 2 active tasks per worker thread to keep transformation pipelines fully saturated\n this.#maxConcurrent = Math.max(1, maxThreads * 2);\n }\n\n /**\n * Executes a transformation action using a semaphore-based backpressure throttle.\n * Prevents libuv thread pool saturation and excessive V8 heap accumulation.\n * @param action A callback that produces a promise for the transformation result.\n * @returns A promise resolving to the transformation result.\n */\n async #runWithThrottle<T>(action: () => Promise<T>): Promise<T> {\n if (this.#activeTasks >= this.#maxConcurrent) {\n await new Promise<void>((resolve, reject) => {\n this.#pendingTasks.push({ resolve, reject });\n });\n } else {\n this.#activeTasks++;\n }\n\n try {\n return await action();\n } finally {\n const next = this.#pendingTasks.shift();\n if (next) {\n next.resolve();\n } else {\n this.#activeTasks--;\n }\n }\n }\n\n #ensureWorkerPool(): WorkerPool {\n this.#workerPool ??= new WorkerPool({\n filename: require.resolve('./worker'),\n maxThreads: this.maxThreads,\n });\n\n return this.#workerPool;\n }\n\n /**\n * Provides information about the Sass implementation.\n * This mimics enough of the `dart-sass` value to be used with the `sass-loader`.\n */\n get info(): string {\n return 'dart-sass\\tworker';\n }\n\n /**\n * The synchronous render function is not used by the `sass-loader`.\n */\n compileString(): never {\n throw new Error('Sass compileString is not supported.');\n }\n\n /**\n * Asynchronously request a Sass stylesheet to be renderered.\n *\n * @param source The contents to compile.\n * @param options The `dart-sass` options to use when rendering the stylesheet.\n */\n async compileStringAsync(source: string, options: StringOptions<'async'>): Promise<CompileResult> {\n // The `functions`, `logger` and `importer` options are JavaScript functions that cannot be transferred.\n // If any additional function options are added in the future, they must be excluded as well.\n const { functions, importers, url, logger, ...serializableOptions } = options;\n\n // The CLI's configuration does not use or expose the ability to define custom Sass functions\n if (functions && Object.keys(functions).length > 0) {\n throw new Error('Sass custom functions are not supported.');\n }\n\n return this.#runWithThrottle(async () => {\n using importerChannel = importers?.length ? this.#createImporterChannel(importers) : undefined;\n\n const response = (await this.#ensureWorkerPool().run(\n {\n source,\n importerChannel,\n hasLogger: !!logger,\n rebase: this.rebase,\n options: {\n ...serializableOptions,\n // URL is not serializable so to convert to string here and back to URL in the worker.\n url: url ? fileURLToPath(url) : undefined,\n },\n },\n {\n transferList: importerChannel ? [importerChannel.port] : undefined,\n },\n )) as RenderResponseMessage;\n\n const { result, error, warnings } = response;\n\n if (warnings && logger?.warn) {\n for (const { message, span, ...options } of warnings) {\n logger.warn(message, {\n ...options,\n span: span && {\n ...span,\n url: span.url ? pathToFileURL(span.url) : undefined,\n },\n });\n }\n }\n\n if (error) {\n // Convert stringified url value required for cloning back to a URL object\n const url = error.span?.url as unknown as string | undefined;\n if (url) {\n error.span.url = pathToFileURL(url);\n }\n\n throw error;\n }\n\n assert(result, 'Sass render worker should always return a result or an error');\n\n return {\n ...result,\n // URL is not serializable so in the worker we convert to string and here back to URL.\n loadedUrls: result.loadedUrls.map(p => pathToFileURL(p)),\n };\n });\n }\n\n /**\n * Shutdown the Sass render worker.\n * Executing this method will stop any pending render requests.\n * @returns A void promise that resolves when closing is complete.\n */\n async close(): Promise<void> {\n const pending = this.#pendingTasks;\n this.#pendingTasks = [];\n for (const task of pending) {\n task.reject(new Error('SassWorkerImplementation closed.'));\n }\n\n if (this.#workerPool) {\n try {\n await this.#workerPool.destroy();\n } finally {\n this.#workerPool = undefined;\n }\n }\n }\n\n #createImporterChannel(importers: Iterable<Importers>) {\n const { port1: mainImporterPort, port2: workerImporterPort } = new MessageChannel();\n const importerSignal = new Int32Array(new SharedArrayBuffer(4));\n\n mainImporterPort.on('message', ({ url, options }: { url: string; options: CanonicalizeContext }) => {\n this.processImporters(importers, url, {\n ...options,\n // URL is not serializable so in the worker we convert to string and here back to URL.\n containingUrl: options.containingUrl ? pathToFileURL(options.containingUrl as unknown as string) : null,\n })\n .then(result => {\n mainImporterPort.postMessage(result);\n })\n .catch(error => {\n mainImporterPort.postMessage(error);\n })\n .finally(() => {\n Atomics.store(importerSignal, 0, 1);\n Atomics.notify(importerSignal, 0);\n });\n });\n\n mainImporterPort.unref();\n\n return {\n port: workerImporterPort,\n signal: importerSignal,\n [Symbol.dispose]() {\n mainImporterPort.close();\n },\n };\n }\n\n private async processImporters(\n importers: Iterable<Importers>,\n url: string,\n options: CanonicalizeContext,\n ): Promise<string | null> {\n for (const importer of importers) {\n if (!this.isFileImporter(importer)) {\n // Importer\n throw new Error('Only File Importers are supported.');\n }\n\n // File importer (Can be sync or aync).\n const result = await importer.findFileUrl(url, options);\n if (result) {\n return fileURLToPath(result);\n }\n }\n\n return null;\n }\n\n private isFileImporter(value: Importers): value is FileImporter {\n return 'findFileUrl' in value;\n }\n}\n"]}
|