ng-packagr 14.0.2 → 14.1.0-next.0
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/lib/ng-package/entry-point/write-package.transform.js +19 -1
- package/lib/ng-package/entry-point/write-package.transform.js.map +1 -1
- package/lib/ngc/ngcc-processor.d.ts +1 -1
- package/lib/ngc/ngcc-processor.js +10 -6
- package/lib/ngc/ngcc-processor.js.map +1 -1
- package/lib/ts/cache-compiler-host.js +13 -8
- package/lib/ts/cache-compiler-host.js.map +1 -1
- package/package.json +1 -1
|
@@ -84,6 +84,18 @@ const writePackageTransform = (options) => (0, transform_1.transformFromPromise)
|
|
|
84
84
|
}
|
|
85
85
|
spinner.succeed();
|
|
86
86
|
}
|
|
87
|
+
else if (options.watch) {
|
|
88
|
+
// update the watch version of the primary entry point `package.json` file.
|
|
89
|
+
// this is needed because of Webpack's 5 `cachemanagedpaths`
|
|
90
|
+
// https://github.com/ng-packagr/ng-packagr/issues/2069
|
|
91
|
+
const primary = ngPackageNode.data.primary;
|
|
92
|
+
const packageJsonPath = path.join(primary.destinationPath, 'package.json');
|
|
93
|
+
if (await (0, fs_1.exists)(packageJsonPath)) {
|
|
94
|
+
const packageJson = JSON.parse(await (0, fs_1.readFile)(packageJsonPath, { encoding: 'utf8' }));
|
|
95
|
+
packageJson.version = generateWatchVersion();
|
|
96
|
+
await (0, fs_1.writeFile)(path.join(primary.destinationPath, 'package.json'), JSON.stringify(packageJson, undefined, 2));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
87
99
|
spinner.succeed(`Built ${ngEntryPoint.moduleId}`);
|
|
88
100
|
return graph;
|
|
89
101
|
});
|
|
@@ -182,7 +194,7 @@ async function writePackageJson(entryPoint, pkg, additionalProperties, isWatchMo
|
|
|
182
194
|
if (isWatchMode) {
|
|
183
195
|
// Needed because of Webpack's 5 `cachemanagedpaths`
|
|
184
196
|
// https://github.com/angular/angular-cli/issues/20962
|
|
185
|
-
packageJson.version =
|
|
197
|
+
packageJson.version = generateWatchVersion();
|
|
186
198
|
}
|
|
187
199
|
if (!((_a = packageJson.peerDependencies) === null || _a === void 0 ? void 0 : _a.tslib) && !((_b = packageJson.dependencies) === null || _b === void 0 ? void 0 : _b.tslib)) {
|
|
188
200
|
const { peerDependencies: angularPeerDependencies = {}, dependencies: angularDependencies = {}, } = require('@angular/compiler/package.json');
|
|
@@ -308,4 +320,10 @@ function generatePackageExports({ destinationPath, packageJson }, graph) {
|
|
|
308
320
|
}
|
|
309
321
|
return exports;
|
|
310
322
|
}
|
|
323
|
+
/**
|
|
324
|
+
* Generates a new version for the package `package.json` when runing in watch mode.
|
|
325
|
+
*/
|
|
326
|
+
function generateWatchVersion() {
|
|
327
|
+
return `0.0.0-watch+${Date.now()}`;
|
|
328
|
+
}
|
|
311
329
|
//# sourceMappingURL=write-package.transform.js.map
|
|
@@ -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,8CAAsB;AACtB,2CAA6B;AAG7B,2CAAwC;AACxC,qDAA6D;AAC7D,6CAA2C;AAC3C,uCAAkE;AAClE,2CAA6C;AAC7C,qDAAuC;AACvC,2CAAkD;AAClD,oCAAiH;AAO1G,MAAM,qBAAqB,GAAG,CAAC,OAAyB,EAAE,EAAE,CACjE,IAAA,gCAAoB,EAAC,KAAK,EAAC,KAAK,EAAC,EAAE;;IACjC,MAAM,OAAO,GAAG,IAAA,aAAG,EAAC;QAClB,UAAU,EAAE,KAAK;QACjB,YAAY,EAAE,KAAK;KACpB,CAAC,CAAC;IACH,MAAM,UAAU,GAAmB,KAAK,CAAC,IAAI,CAAC,IAAA,8BAAsB,GAAE,CAAC,CAAC;IACxE,MAAM,YAAY,GAAiB,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC;IAC9D,MAAM,aAAa,GAAgB,KA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CAAC,KAAK,gBAAgB,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;QAEhF,oBAAoB,CAAC,OAAO,EAAE;YAC5B,KAAK,EAAE,wBAAwB,CAAC,gBAAgB,CAAC,YAAY,CAAC;YAC9D,OAAO,EAAE,wBAAwB,CAAC,gBAAgB,CAAC,OAAO,CAAC;YAC3D,MAAM,EAAE,wBAAwB,CAAC,gBAAgB,CAAC,QAAQ,CAAC;YAC3D,MAAM,EAAE,wBAAwB,CAAC,gBAAgB,CAAC,QAAQ,CAAC;YAC3D,IAAI,EAAE,wBAAwB,CAAC,gBAAgB,CAAC,QAAQ,CAAC;YACzD,OAAO,EAAE,wBAAwB,CAAC,gBAAgB,CAAC,QAAQ,CAAC;SAC7D,CAAC,CAAC;KACJ;IAED,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import ora from 'ora';\nimport * as path from 'path';\nimport { AssetPattern } from '../../../ng-package.schema';\nimport { BuildGraph } from '../../graph/build-graph';\nimport { Node } from '../../graph/node';\nimport { transformFromPromise } from '../../graph/transform';\nimport { colors } from '../../utils/color';\nimport { copyFile, rmdir, stat, writeFile } from '../../utils/fs';\nimport { globFiles } from '../../utils/glob';\nimport * as log from '../../utils/log';\nimport { ensureUnixPath } from '../../utils/path';\nimport { EntryPointNode, PackageNode, fileUrl, isEntryPoint, isEntryPointInProgress, isPackage } 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({\n hideCursor: false,\n discardStdin: false,\n });\n const entryPoint: EntryPointNode = graph.find(isEntryPointInProgress());\n const ngEntryPoint: NgEntryPoint = entryPoint.data.entryPoint;\n const ngPackageNode: PackageNode = graph.find(isPackage);\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);\n } catch (error) {\n spinner.fail();\n throw error;\n }\n spinner.succeed();\n }\n\n // 6. WRITE PACKAGE.JSON\n // As of APF 14 only the primary entrypoint has a package.json\n if (!ngEntryPoint.isSecondaryEntryPoint) {\n try {\n spinner.start('Writing package manifest');\n const relativeUnixFromDestPath = (filePath: string) =>\n ensureUnixPath(path.relative(ngEntryPoint.destinationPath, filePath));\n\n const { compilationMode } = entryPoint.data.tsConfig.options;\n\n await writePackageJson(\n ngEntryPoint,\n ngPackage,\n {\n module: relativeUnixFromDestPath(destinationFiles.fesm2015),\n es2020: relativeUnixFromDestPath(destinationFiles.fesm2020),\n esm2020: relativeUnixFromDestPath(destinationFiles.esm2020),\n fesm2020: relativeUnixFromDestPath(destinationFiles.fesm2020),\n fesm2015: relativeUnixFromDestPath(destinationFiles.fesm2015),\n typings: relativeUnixFromDestPath(destinationFiles.declarations),\n exports: generatePackageExports(ngEntryPoint, graph),\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 }\n\n spinner.succeed(`Built ${ngEntryPoint.moduleId}`);\n\n return graph;\n });\n\ntype AssetEntry = Exclude<AssetPattern, string>;\n\nasync function copyAssets(\n graph: BuildGraph,\n entryPointNode: EntryPointNode,\n ngPackageNode: PackageNode,\n): Promise<void> {\n const ngPackage = ngPackageNode.data;\n\n const globsForceIgnored: string[] = ['.gitkeep', '**/.DS_Store', '**/Thumbs.db', `${ngPackage.dest}/**`];\n const defaultAssets: AssetEntry[] = [\n { glob: 'LICENSE', input: '/', output: '/' },\n { glob: '**/README.md', input: '/', output: '/' },\n ];\n const assets: AssetEntry[] = [];\n\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 = {\n glob: path.basename(assetPath),\n input: path.dirname(assetPath),\n output: path.dirname(assetPath),\n };\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 globFiles(asset.glob, {\n cwd: asset.input,\n ignore: [...(asset.ignore ?? []), ...globsForceIgnored],\n cache: ngPackageNode.cache.globCache,\n dot: true,\n nodir: true,\n follow: 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.Ora,\n): Promise<void> {\n log.debug('Writing package.json');\n\n // set additional properties\n const packageJson = { ...entryPoint.packageJson, ...additionalProperties };\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 = `0.0.0-watch+${Date.now()}`;\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 = {\n ...packageJson.dependencies,\n tslib: tsLibVersion,\n };\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 = {\n ...(packageJson.dependencies || {}),\n tslib: packageJson.peerDependencies.tslib,\n };\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 by Ivy in full compilation mode. This is not allowed.\\\\n' +\n 'Please delete and rebuild the package with Ivy 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.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\ntype PackageExports = Record<string, ConditionalExport>;\n\n/**\n * Type describing the conditional exports descriptor for an entry-point.\n * https://nodejs.org/api/packages.html#packages_conditional_exports\n */\ntype ConditionalExport = {\n node?: string;\n types?: string;\n esm2020?: string;\n es2020?: string;\n es2015?: string;\n default?: string;\n};\n\n/**\n * Generates the `package.json` package exports following APF v13.\n * This is supposed to match with: https://github.com/angular/angular/blob/e0667efa6eada64d1fb8b143840689090fc82e52/packages/bazel/src/ng_package/packager.ts#L415.\n */\nfunction generatePackageExports({ destinationPath, packageJson }: NgEntryPoint, graph: BuildGraph): PackageExports {\n const exports: PackageExports = packageJson.exports ? JSON.parse(JSON.stringify(packageJson.exports)) : {};\n\n const insertMappingOrError = (subpath: string, mapping: ConditionalExport) => {\n if (exports[subpath] === undefined) {\n exports[subpath] = {};\n }\n\n const subpathExport = exports[subpath];\n\n // Go through all conditions that should be inserted. If the condition is already\n // manually set of the subpath export, we throw an error. In general, we allow for\n // additional conditions to be set. These will always precede the generated ones.\n for (const conditionName of Object.keys(mapping) as [keyof ConditionalExport]) {\n if (subpathExport[conditionName] !== undefined) {\n throw Error(\n `Found a conflicting export condition for \"${subpath}\". The \"${conditionName}\" ` +\n `condition would be overridden by ng-packagr. Please unset it.`,\n );\n }\n\n // **Note**: The order of the conditions is preserved even though we are setting\n // the conditions once at a time (the latest assignment will be at the end).\n subpathExport[conditionName] = mapping[conditionName];\n }\n };\n\n const relativeUnixFromDestPath = (filePath: string) =>\n './' + ensureUnixPath(path.relative(destinationPath, filePath));\n\n insertMappingOrError('./package.json', { default: './package.json' });\n\n const entryPoints = graph.filter(isEntryPoint);\n for (const entryPoint of entryPoints) {\n const { destinationFiles, isSecondaryEntryPoint } = entryPoint.data.entryPoint;\n const subpath = isSecondaryEntryPoint ? `./${destinationFiles.directory}` : '.';\n\n insertMappingOrError(subpath, {\n types: relativeUnixFromDestPath(destinationFiles.declarations),\n esm2020: relativeUnixFromDestPath(destinationFiles.esm2020),\n es2020: relativeUnixFromDestPath(destinationFiles.fesm2020),\n es2015: relativeUnixFromDestPath(destinationFiles.fesm2015),\n node: relativeUnixFromDestPath(destinationFiles.fesm2015),\n default: relativeUnixFromDestPath(destinationFiles.fesm2020),\n });\n }\n\n return exports;\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,8CAAsB;AACtB,2CAA6B;AAG7B,2CAAwC;AACxC,qDAA6D;AAC7D,6CAA2C;AAC3C,uCAAoF;AACpF,2CAA6C;AAC7C,qDAAuC;AACvC,2CAAkD;AAClD,oCAAiH;AAO1G,MAAM,qBAAqB,GAAG,CAAC,OAAyB,EAAE,EAAE,CACjE,IAAA,gCAAoB,EAAC,KAAK,EAAC,KAAK,EAAC,EAAE;;IACjC,MAAM,OAAO,GAAG,IAAA,aAAG,EAAC;QAClB,UAAU,EAAE,KAAK;QACjB,YAAY,EAAE,KAAK;KACpB,CAAC,CAAC;IACH,MAAM,UAAU,GAAmB,KAAK,CAAC,IAAI,CAAC,IAAA,8BAAsB,GAAE,CAAC,CAAC;IACxE,MAAM,YAAY,GAAiB,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC;IAC9D,MAAM,aAAa,GAAgB,KAAK,CAAC,IAAI,CAAC,iBAAS,CAAC,CAAC;IACzD,MAAM,SAAS,GAAG,aAAa,CAAC,IAAI,CAAC;IACrC,MAAM,EAAE,gBAAgB,EAAE,GAAG,UAAU,CAAC,IAAI,CAAC;IAE7C,IAAI,CAAC,YAAY,CAAC,qBAAqB,EAAE;QACvC,OAAO,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;QAChC,IAAI;YACF,MAAM,UAAU,CAAC,KAAK,EAAE,UAAU,EAAE,aAAa,CAAC,CAAC;SACpD;QAAC,OAAO,KAAK,EAAE;YACd,OAAO,CAAC,IAAI,EAAE,CAAC;YACf,MAAM,KAAK,CAAC;SACb;QACD,OAAO,CAAC,OAAO,EAAE,CAAC;KACnB;IAED,wBAAwB;IACxB,8DAA8D;IAC9D,IAAI,CAAC,YAAY,CAAC,qB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AAgB,EAAE,qBAAqB,EAAE,GAAG,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC;QAC/E,MAAM,OAAO,GAAG,qBAAqB,CAAC,CAAC,CAAC,KAAK,gBAAgB,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;QAEhF,oBAAoB,CAAC,OAAO,EAAE;YAC5B,KAAK,EAAE,wBAAwB,CAAC,gBAAgB,CAAC,YAAY,CAAC;YAC9D,OAAO,EAAE,wBAAwB,CAAC,gBAAgB,CAAC,OAAO,CAAC;YAC3D,MAAM,EAAE,wBAAwB,CAAC,gBAAgB,CAAC,QAAQ,CAAC;YAC3D,MAAM,EAAE,wBAAwB,CAAC,gBAAgB,CAAC,QAAQ,CAAC;YAC3D,IAAI,EAAE,wBAAwB,CAAC,gBAAgB,CAAC,QAAQ,CAAC;YACzD,OAAO,EAAE,wBAAwB,CAAC,gBAAgB,CAAC,QAAQ,CAAC;SAC7D,CAAC,CAAC;KACJ;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;GAEG;AACH,SAAS,oBAAoB;IAC3B,OAAO,eAAe,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;AACrC,CAAC","sourcesContent":["import ora from 'ora';\nimport * as path from 'path';\nimport { AssetPattern } from '../../../ng-package.schema';\nimport { BuildGraph } from '../../graph/build-graph';\nimport { Node } from '../../graph/node';\nimport { transformFromPromise } from '../../graph/transform';\nimport { colors } from '../../utils/color';\nimport { copyFile, exists, readFile, rmdir, stat, writeFile } from '../../utils/fs';\nimport { globFiles } from '../../utils/glob';\nimport * as log from '../../utils/log';\nimport { ensureUnixPath } from '../../utils/path';\nimport { EntryPointNode, PackageNode, fileUrl, isEntryPoint, isEntryPointInProgress, isPackage } 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({\n hideCursor: false,\n discardStdin: false,\n });\n const entryPoint: EntryPointNode = graph.find(isEntryPointInProgress());\n const ngEntryPoint: NgEntryPoint = entryPoint.data.entryPoint;\n const ngPackageNode: PackageNode = graph.find(isPackage);\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);\n } catch (error) {\n spinner.fail();\n throw error;\n }\n spinner.succeed();\n }\n\n // 6. WRITE PACKAGE.JSON\n // As of APF 14 only the primary entrypoint has a package.json\n if (!ngEntryPoint.isSecondaryEntryPoint) {\n try {\n spinner.start('Writing package manifest');\n const relativeUnixFromDestPath = (filePath: string) =>\n ensureUnixPath(path.relative(ngEntryPoint.destinationPath, filePath));\n\n const { compilationMode } = entryPoint.data.tsConfig.options;\n\n await writePackageJson(\n ngEntryPoint,\n ngPackage,\n {\n module: relativeUnixFromDestPath(destinationFiles.fesm2015),\n es2020: relativeUnixFromDestPath(destinationFiles.fesm2020),\n esm2020: relativeUnixFromDestPath(destinationFiles.esm2020),\n fesm2020: relativeUnixFromDestPath(destinationFiles.fesm2020),\n fesm2015: relativeUnixFromDestPath(destinationFiles.fesm2015),\n typings: relativeUnixFromDestPath(destinationFiles.declarations),\n exports: generatePackageExports(ngEntryPoint, graph),\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 (options.watch) {\n // update the watch version of the primary entry point `package.json` file.\n // this is needed because of Webpack's 5 `cachemanagedpaths`\n // https://github.com/ng-packagr/ng-packagr/issues/2069\n const primary = ngPackageNode.data.primary;\n const packageJsonPath = path.join(primary.destinationPath, 'package.json');\n\n if (await exists(packageJsonPath)) {\n const packageJson = JSON.parse(await readFile(packageJsonPath, { encoding: 'utf8' }));\n packageJson.version = generateWatchVersion();\n await writeFile(path.join(primary.destinationPath, 'package.json'), JSON.stringify(packageJson, undefined, 2));\n }\n }\n\n spinner.succeed(`Built ${ngEntryPoint.moduleId}`);\n\n return graph;\n });\n\ntype AssetEntry = Exclude<AssetPattern, string>;\n\nasync function copyAssets(\n graph: BuildGraph,\n entryPointNode: EntryPointNode,\n ngPackageNode: PackageNode,\n): Promise<void> {\n const ngPackage = ngPackageNode.data;\n\n const globsForceIgnored: string[] = ['.gitkeep', '**/.DS_Store', '**/Thumbs.db', `${ngPackage.dest}/**`];\n const defaultAssets: AssetEntry[] = [\n { glob: 'LICENSE', input: '/', output: '/' },\n { glob: '**/README.md', input: '/', output: '/' },\n ];\n const assets: AssetEntry[] = [];\n\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 = {\n glob: path.basename(assetPath),\n input: path.dirname(assetPath),\n output: path.dirname(assetPath),\n };\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 globFiles(asset.glob, {\n cwd: asset.input,\n ignore: [...(asset.ignore ?? []), ...globsForceIgnored],\n cache: ngPackageNode.cache.globCache,\n dot: true,\n nodir: true,\n follow: 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.Ora,\n): Promise<void> {\n log.debug('Writing package.json');\n\n // set additional properties\n const packageJson = { ...entryPoint.packageJson, ...additionalProperties };\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 = {\n ...packageJson.dependencies,\n tslib: tsLibVersion,\n };\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 = {\n ...(packageJson.dependencies || {}),\n tslib: packageJson.peerDependencies.tslib,\n };\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 by Ivy in full compilation mode. This is not allowed.\\\\n' +\n 'Please delete and rebuild the package with Ivy 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.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\ntype PackageExports = Record<string, ConditionalExport>;\n\n/**\n * Type describing the conditional exports descriptor for an entry-point.\n * https://nodejs.org/api/packages.html#packages_conditional_exports\n */\ntype ConditionalExport = {\n node?: string;\n types?: string;\n esm2020?: string;\n es2020?: string;\n es2015?: string;\n default?: string;\n};\n\n/**\n * Generates the `package.json` package exports following APF v13.\n * This is supposed to match with: https://github.com/angular/angular/blob/e0667efa6eada64d1fb8b143840689090fc82e52/packages/bazel/src/ng_package/packager.ts#L415.\n */\nfunction generatePackageExports({ destinationPath, packageJson }: NgEntryPoint, graph: BuildGraph): PackageExports {\n const exports: PackageExports = packageJson.exports ? JSON.parse(JSON.stringify(packageJson.exports)) : {};\n\n const insertMappingOrError = (subpath: string, mapping: ConditionalExport) => {\n if (exports[subpath] === undefined) {\n exports[subpath] = {};\n }\n\n const subpathExport = exports[subpath];\n\n // Go through all conditions that should be inserted. If the condition is already\n // manually set of the subpath export, we throw an error. In general, we allow for\n // additional conditions to be set. These will always precede the generated ones.\n for (const conditionName of Object.keys(mapping) as [keyof ConditionalExport]) {\n if (subpathExport[conditionName] !== undefined) {\n throw Error(\n `Found a conflicting export condition for \"${subpath}\". The \"${conditionName}\" ` +\n `condition would be overridden by ng-packagr. Please unset it.`,\n );\n }\n\n // **Note**: The order of the conditions is preserved even though we are setting\n // the conditions once at a time (the latest assignment will be at the end).\n subpathExport[conditionName] = mapping[conditionName];\n }\n };\n\n const relativeUnixFromDestPath = (filePath: string) =>\n './' + ensureUnixPath(path.relative(destinationPath, filePath));\n\n insertMappingOrError('./package.json', { default: './package.json' });\n\n const entryPoints = graph.filter(isEntryPoint);\n for (const entryPoint of entryPoints) {\n const { destinationFiles, isSecondaryEntryPoint } = entryPoint.data.entryPoint;\n const subpath = isSecondaryEntryPoint ? `./${destinationFiles.directory}` : '.';\n\n insertMappingOrError(subpath, {\n types: relativeUnixFromDestPath(destinationFiles.declarations),\n esm2020: relativeUnixFromDestPath(destinationFiles.esm2020),\n es2020: relativeUnixFromDestPath(destinationFiles.fesm2020),\n es2015: relativeUnixFromDestPath(destinationFiles.fesm2015),\n node: relativeUnixFromDestPath(destinationFiles.fesm2015),\n default: relativeUnixFromDestPath(destinationFiles.fesm2020),\n });\n }\n\n return exports;\n}\n\n/**\n * Generates a new version for the package `package.json` when runing in watch mode.\n */\nfunction generateWatchVersion() {\n return `0.0.0-watch+${Date.now()}`;\n}\n"]}
|
|
@@ -15,7 +15,7 @@ export declare class NgccProcessor {
|
|
|
15
15
|
constructor(compilerNgcc: typeof import('@angular/compiler-cli/ngcc'), ngccProcessingCache: NgccProcessingCache, projectPath: string, compilerOptions: ts.CompilerOptions, entryPoints: EntryPointNode[]);
|
|
16
16
|
/** Process the entire node modules tree. */
|
|
17
17
|
process(): Promise<void>;
|
|
18
|
-
/** Process a module and
|
|
18
|
+
/** Process a module and its dependencies. */
|
|
19
19
|
processModule(moduleName: string, resolvedModule: ts.ResolvedModule | ts.ResolvedTypeReferenceDirective): void;
|
|
20
20
|
/**
|
|
21
21
|
* Try resolve a package.json file from the resolved .d.ts file.
|
|
@@ -48,8 +48,10 @@ class NgccProcessor {
|
|
|
48
48
|
}
|
|
49
49
|
/** Process the entire node modules tree. */
|
|
50
50
|
async process() {
|
|
51
|
-
// Under Bazel when running in sandbox mode parts of the filesystem is read-only
|
|
52
|
-
|
|
51
|
+
// Under Bazel when running in sandbox mode parts of the filesystem is read-only, or when using
|
|
52
|
+
// Yarn PnP there may not be a node_modules directory. ngcc can't run in those cases, so the
|
|
53
|
+
// processing is skipped.
|
|
54
|
+
if (process.env.BAZEL_TARGET || !this._nodeModulesDirectory) {
|
|
53
55
|
return;
|
|
54
56
|
}
|
|
55
57
|
// Only allow running this during the first run.
|
|
@@ -140,14 +142,16 @@ class NgccProcessor {
|
|
|
140
142
|
}
|
|
141
143
|
}
|
|
142
144
|
}
|
|
143
|
-
/** Process a module and
|
|
145
|
+
/** Process a module and its dependencies. */
|
|
144
146
|
processModule(moduleName, resolvedModule) {
|
|
145
147
|
const resolvedFileName = resolvedModule.resolvedFileName;
|
|
146
|
-
if (!
|
|
148
|
+
if (!this._nodeModulesDirectory ||
|
|
149
|
+
!resolvedFileName ||
|
|
147
150
|
moduleName.startsWith('.') ||
|
|
148
151
|
this.ngccProcessingCache.hasProcessed(moduleName) ||
|
|
149
152
|
this._entryPointsUrl.includes((0, nodes_1.ngUrl)(moduleName))) {
|
|
150
|
-
// Skip when module is unknown, relative, an
|
|
153
|
+
// Skip when module_modules directory is not present, module is unknown, relative, an
|
|
154
|
+
// entrypoint or already processed.
|
|
151
155
|
return;
|
|
152
156
|
}
|
|
153
157
|
const packageJsonPath = this.tryResolvePackage(moduleName, resolvedFileName);
|
|
@@ -201,7 +205,7 @@ class NgccProcessor {
|
|
|
201
205
|
}
|
|
202
206
|
current = path.dirname(current);
|
|
203
207
|
}
|
|
204
|
-
|
|
208
|
+
return null;
|
|
205
209
|
}
|
|
206
210
|
}
|
|
207
211
|
exports.NgccProcessor = NgccProcessor;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ngcc-processor.js","sourceRoot":"","sources":["../../../src/lib/ngc/ngcc-processor.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,iDAA0C;AAC1C,mCAAoC;AACpC,2BAAuD;AACvD,2CAA6B;AAG7B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;IAC5B,CAAC;IAED,IAAI,CAAC,GAAG,IAAc;QACpB,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3B,CAAC;IAED,IAAI,CAAC,GAAG,IAAc;QACpB,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3B,CAAC;IAED,KAAK,CAAC,GAAG,IAAc;QACrB,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IAC5B,CAAC;CACF;AAED,SAAS,cAAc,CAAC,QAAgB;IACtC,IAAI;QACF,IAAA,eAAU,EAAC,QAAQ,EAAE,cAAS,CAAC,IAAI,CAAC,CAAC;QAErC,OAAO,KAAK,CAAC;KACd;IAAC,MAAM;QACN,OAAO,IAAI,CAAC;KACb;AACH,CAAC","sourcesContent":["import type { Logger } from '@angular/compiler-cli/ngcc';\nimport { spawnSync } from 'child_process';\nimport { createHash } from 'crypto';\nimport { accessSync, constants, existsSync } from 'fs';\nimport * as path from 'path';\nimport ts from 'typescript';\nimport { NgccProcessingCache } from '../ng-package/ngcc-cache';\nimport { EntryPointNode, ngUrl } from '../ng-package/nodes';\nimport { defaultTsConfigPath } from '../ts/tsconfig';\nimport { exists, mkdir, readFile, writeFile } from '../utils/fs';\nimport * as log from '../utils/log';\n\n// Transform a package and its typings when NGTSC is resolving a module.\nexport class NgccProcessor {\n private _logger: NgccLogger;\n private _nodeModulesDirectory: string;\n private _entryPointsUrl: string[];\n private readonly propertiesToConsider = ['es2015', 'browser', 'module', 'main'];\n private skipProcessing = false;\n\n constructor(\n private readonly compilerNgcc: typeof import('@angular/compiler-cli/ngcc'),\n private readonly ngccProcessingCache: NgccProcessingCache,\n private readonly projectPath: string,\n private readonly compilerOptions: ts.CompilerOptions,\n private readonly entryPoints: EntryPointNode[],\n ) {\n this._entryPointsUrl = this.entryPoints.map(({ url }) => ngUrl(url));\n\n const { baseUrl } = this.compilerOptions;\n this._nodeModulesDirectory = this.findNodeModulesDirectory(baseUrl);\n }\n\n /** Process the entire node modules tree. */\n async process(): Promise<void> {\n // Under Bazel when running in sandbox mode parts of the filesystem is read-only.\n if (process.env.BAZEL_TARGET) {\n return;\n }\n\n // Only allow running this during the first run.\n if (this.skipProcessing) {\n return;\n }\n\n // Skip if node_modules are read-only\n const corePackage = this.tryResolvePackage('@angular/core', this._nodeModulesDirectory);\n if (corePackage && isReadOnlyFile(corePackage)) {\n return;\n }\n\n // Perform a ngcc run check to determine if an initial execution is required.\n // If a run hash file exists that matches the current package manager lock file and the\n // project's tsconfig, then an initial ngcc run has already been performed.\n let runHashFilePath: string | undefined;\n const runHashBasePath = path.join(this._nodeModulesDirectory, '.ng-packagr-ngcc');\n const projectBasePath = path.join(this._nodeModulesDirectory, '..');\n try {\n let lockData;\n let lockFile = 'yarn.lock';\n try {\n lockData = await readFile(path.join(projectBasePath, lockFile));\n } catch {\n lockFile = 'package-lock.json';\n lockData = await readFile(path.join(projectBasePath, lockFile));\n }\n\n let ngccConfigData;\n try {\n ngccConfigData = await readFile(path.join(projectBasePath, 'ngcc.config.js'));\n } catch {\n ngccConfigData = '';\n }\n\n const relativeTsconfigPath = path.relative(projectBasePath, this.projectPath);\n const tsconfigData = await readFile(this.projectPath);\n\n // Generate a hash that represents the state of the package lock file and used tsconfig\n const runHash = createHash('sha256')\n .update(lockData)\n .update(lockFile)\n .update(ngccConfigData)\n .update(tsconfigData)\n .update(relativeTsconfigPath)\n .digest('hex');\n\n // The hash is used directly in the file name to mitigate potential read/write race\n // conditions as well as to only require a file existence check\n runHashFilePath = path.join(runHashBasePath, runHash + '.lock');\n\n // If the run hash lock file exists, then ngcc was already run against this project state\n if (await exists(runHashFilePath)) {\n this.skipProcessing = true;\n\n return;\n }\n } catch {\n // Any error means an ngcc execution is needed\n }\n\n const { status, error } = spawnSync(\n process.execPath,\n [\n this.compilerNgcc.ngccMainFilePath,\n '--source' /** basePath */,\n this._nodeModulesDirectory,\n '--properties' /** propertiesToConsider */,\n ...this.propertiesToConsider,\n '--first-only' /** compileAllFormats */,\n '--create-ivy-entry-points' /** createNewEntryPointFormats */,\n '--async',\n '--tsconfig' /** tsConfigPath */,\n path.normalize(this.projectPath) === defaultTsConfigPath ? '' : this.projectPath,\n '--use-program-dependencies',\n '--typings-only' /** typingsOnly */,\n ],\n {\n stdio: ['inherit', process.stderr, process.stderr],\n },\n );\n\n this.skipProcessing = true;\n\n if (status !== 0) {\n const errorMessage = error?.message || '';\n throw new Error(errorMessage + `NGCC failed${errorMessage ? ', see above' : ''}.`);\n }\n\n // ngcc was successful so if a run hash was generated, write it for next time\n if (runHashFilePath) {\n try {\n if (!existsSync(runHashBasePath)) {\n await mkdir(runHashBasePath, { recursive: true });\n }\n await writeFile(runHashFilePath, '');\n } catch {\n // Errors are non-fatal\n }\n }\n }\n\n /** Process a module and it's depedencies. */\n processModule(moduleName: string, resolvedModule: ts.ResolvedModule | ts.ResolvedTypeReferenceDirective): void {\n const resolvedFileName = resolvedModule.resolvedFileName;\n if (\n !resolvedFileName ||\n moduleName.startsWith('.') ||\n this.ngccProcessingCache.hasProcessed(moduleName) ||\n this._entryPointsUrl.includes(ngUrl(moduleName))\n ) {\n // Skip when module is unknown, relative, an entrypoint or already processed.\n return;\n }\n\n const packageJsonPath = this.tryResolvePackage(moduleName, resolvedFileName);\n if (!packageJsonPath) {\n // add it to processed so the second time round we skip this.\n this.ngccProcessingCache.markProcessed(moduleName);\n\n return;\n }\n\n // If the package.json is read only we should skip calling NGCC.\n // With Bazel when running under sandbox the filesystem is read-only.\n if (isReadOnlyFile(packageJsonPath)) {\n // add it to processed so the second time round we skip this.\n this.ngccProcessingCache.markProcessed(moduleName);\n\n return;\n }\n\n this.compilerNgcc.process({\n basePath: this._nodeModulesDirectory,\n targetEntryPointPath: path.dirname(packageJsonPath),\n compileAllFormats: false,\n typingsOnly: true,\n propertiesToConsider: this.propertiesToConsider,\n createNewEntryPointFormats: true,\n logger: this._logger,\n tsConfigPath: this.projectPath === defaultTsConfigPath ? undefined : this.projectPath,\n });\n\n this.ngccProcessingCache.markProcessed(moduleName);\n }\n\n /**\n * Try resolve a package.json file from the resolved .d.ts file.\n */\n private tryResolvePackage(moduleName: string, resolvedFileName: string): string | undefined {\n try {\n return require.resolve(`${moduleName}/package.json`, {\n paths: [resolvedFileName],\n });\n } catch {\n // if it fails this might be a deep import which doesn't have a package.json\n // Ex: @angular/compiler/src/i18n/i18n_ast/package.json\n // or local libraries which don't reside in node_modules\n const packageJsonPath = path.resolve(resolvedFileName, '../package.json');\n\n return existsSync(packageJsonPath) ? packageJsonPath : undefined;\n }\n }\n\n private findNodeModulesDirectory(startPoint: string): string {\n let current = startPoint;\n while (path.dirname(current) !== current) {\n const nodePath = path.join(current, 'node_modules');\n if (existsSync(nodePath)) {\n return nodePath;\n }\n\n current = path.dirname(current);\n }\n\n throw new Error(`Cannot locate the 'node_modules' directory.`);\n }\n}\n\nclass NgccLogger implements Logger {\n level = /** LogLevel.info**/ 1;\n\n debug(...args: string[]) {\n log.debug(args.join(' '));\n }\n\n info(...args: string[]) {\n log.info(args.join(' '));\n }\n\n warn(...args: string[]) {\n log.warn(args.join(' '));\n }\n\n error(...args: string[]) {\n log.error(args.join(' '));\n }\n}\n\nfunction isReadOnlyFile(fileName: string): boolean {\n try {\n accessSync(fileName, constants.W_OK);\n\n return false;\n } catch {\n return true;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ngcc-processor.js","sourceRoot":"","sources":["../../../src/lib/ngc/ngcc-processor.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,iDAA0C;AAC1C,mCAAoC;AACpC,2BAAuD;AACvD,2CAA6B;AAG7B,+CAA4D;AAC5D,6CAAqD;AACrD,oCAAiE;AACjE,kDAAoC;AAEpC,wEAAwE;AACxE,MAAa,aAAa;IAOxB,YACmB,YAAyD,EACzD,mBAAwC,EACxC,WAAmB,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G,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3B,CAAC;IAED,IAAI,CAAC,GAAG,IAAc;QACpB,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IAC3B,CAAC;IAED,KAAK,CAAC,GAAG,IAAc;QACrB,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IAC5B,CAAC;CACF;AAED,SAAS,cAAc,CAAC,QAAgB;IACtC,IAAI;QACF,IAAA,eAAU,EAAC,QAAQ,EAAE,cAAS,CAAC,IAAI,CAAC,CAAC;QAErC,OAAO,KAAK,CAAC;KACd;IAAC,MAAM;QACN,OAAO,IAAI,CAAC;KACb;AACH,CAAC","sourcesContent":["import type { Logger } from '@angular/compiler-cli/ngcc';\nimport { spawnSync } from 'child_process';\nimport { createHash } from 'crypto';\nimport { accessSync, constants, existsSync } from 'fs';\nimport * as path from 'path';\nimport ts from 'typescript';\nimport { NgccProcessingCache } from '../ng-package/ngcc-cache';\nimport { EntryPointNode, ngUrl } from '../ng-package/nodes';\nimport { defaultTsConfigPath } from '../ts/tsconfig';\nimport { exists, mkdir, readFile, writeFile } from '../utils/fs';\nimport * as log from '../utils/log';\n\n// Transform a package and its typings when NGTSC is resolving a module.\nexport class NgccProcessor {\n private _logger: NgccLogger;\n private _nodeModulesDirectory: string | null;\n private _entryPointsUrl: string[];\n private readonly propertiesToConsider = ['es2015', 'browser', 'module', 'main'];\n private skipProcessing = false;\n\n constructor(\n private readonly compilerNgcc: typeof import('@angular/compiler-cli/ngcc'),\n private readonly ngccProcessingCache: NgccProcessingCache,\n private readonly projectPath: string,\n private readonly compilerOptions: ts.CompilerOptions,\n private readonly entryPoints: EntryPointNode[],\n ) {\n this._entryPointsUrl = this.entryPoints.map(({ url }) => ngUrl(url));\n\n const { baseUrl } = this.compilerOptions;\n this._nodeModulesDirectory = this.findNodeModulesDirectory(baseUrl);\n }\n\n /** Process the entire node modules tree. */\n async process(): Promise<void> {\n // Under Bazel when running in sandbox mode parts of the filesystem is read-only, or when using\n // Yarn PnP there may not be a node_modules directory. ngcc can't run in those cases, so the\n // processing is skipped.\n if (process.env.BAZEL_TARGET || !this._nodeModulesDirectory) {\n return;\n }\n\n // Only allow running this during the first run.\n if (this.skipProcessing) {\n return;\n }\n\n // Skip if node_modules are read-only\n const corePackage = this.tryResolvePackage('@angular/core', this._nodeModulesDirectory);\n if (corePackage && isReadOnlyFile(corePackage)) {\n return;\n }\n\n // Perform a ngcc run check to determine if an initial execution is required.\n // If a run hash file exists that matches the current package manager lock file and the\n // project's tsconfig, then an initial ngcc run has already been performed.\n let runHashFilePath: string | undefined;\n const runHashBasePath = path.join(this._nodeModulesDirectory, '.ng-packagr-ngcc');\n const projectBasePath = path.join(this._nodeModulesDirectory, '..');\n try {\n let lockData;\n let lockFile = 'yarn.lock';\n try {\n lockData = await readFile(path.join(projectBasePath, lockFile));\n } catch {\n lockFile = 'package-lock.json';\n lockData = await readFile(path.join(projectBasePath, lockFile));\n }\n\n let ngccConfigData;\n try {\n ngccConfigData = await readFile(path.join(projectBasePath, 'ngcc.config.js'));\n } catch {\n ngccConfigData = '';\n }\n\n const relativeTsconfigPath = path.relative(projectBasePath, this.projectPath);\n const tsconfigData = await readFile(this.projectPath);\n\n // Generate a hash that represents the state of the package lock file and used tsconfig\n const runHash = createHash('sha256')\n .update(lockData)\n .update(lockFile)\n .update(ngccConfigData)\n .update(tsconfigData)\n .update(relativeTsconfigPath)\n .digest('hex');\n\n // The hash is used directly in the file name to mitigate potential read/write race\n // conditions as well as to only require a file existence check\n runHashFilePath = path.join(runHashBasePath, runHash + '.lock');\n\n // If the run hash lock file exists, then ngcc was already run against this project state\n if (await exists(runHashFilePath)) {\n this.skipProcessing = true;\n\n return;\n }\n } catch {\n // Any error means an ngcc execution is needed\n }\n\n const { status, error } = spawnSync(\n process.execPath,\n [\n this.compilerNgcc.ngccMainFilePath,\n '--source' /** basePath */,\n this._nodeModulesDirectory,\n '--properties' /** propertiesToConsider */,\n ...this.propertiesToConsider,\n '--first-only' /** compileAllFormats */,\n '--create-ivy-entry-points' /** createNewEntryPointFormats */,\n '--async',\n '--tsconfig' /** tsConfigPath */,\n path.normalize(this.projectPath) === defaultTsConfigPath ? '' : this.projectPath,\n '--use-program-dependencies',\n '--typings-only' /** typingsOnly */,\n ],\n {\n stdio: ['inherit', process.stderr, process.stderr],\n },\n );\n\n this.skipProcessing = true;\n\n if (status !== 0) {\n const errorMessage = error?.message || '';\n throw new Error(errorMessage + `NGCC failed${errorMessage ? ', see above' : ''}.`);\n }\n\n // ngcc was successful so if a run hash was generated, write it for next time\n if (runHashFilePath) {\n try {\n if (!existsSync(runHashBasePath)) {\n await mkdir(runHashBasePath, { recursive: true });\n }\n await writeFile(runHashFilePath, '');\n } catch {\n // Errors are non-fatal\n }\n }\n }\n\n /** Process a module and its dependencies. */\n processModule(moduleName: string, resolvedModule: ts.ResolvedModule | ts.ResolvedTypeReferenceDirective): void {\n const resolvedFileName = resolvedModule.resolvedFileName;\n if (\n !this._nodeModulesDirectory ||\n !resolvedFileName ||\n moduleName.startsWith('.') ||\n this.ngccProcessingCache.hasProcessed(moduleName) ||\n this._entryPointsUrl.includes(ngUrl(moduleName))\n ) {\n // Skip when module_modules directory is not present, module is unknown, relative, an\n // entrypoint or already processed.\n return;\n }\n\n const packageJsonPath = this.tryResolvePackage(moduleName, resolvedFileName);\n if (!packageJsonPath) {\n // add it to processed so the second time round we skip this.\n this.ngccProcessingCache.markProcessed(moduleName);\n\n return;\n }\n\n // If the package.json is read only we should skip calling NGCC.\n // With Bazel when running under sandbox the filesystem is read-only.\n if (isReadOnlyFile(packageJsonPath)) {\n // add it to processed so the second time round we skip this.\n this.ngccProcessingCache.markProcessed(moduleName);\n\n return;\n }\n\n this.compilerNgcc.process({\n basePath: this._nodeModulesDirectory,\n targetEntryPointPath: path.dirname(packageJsonPath),\n compileAllFormats: false,\n typingsOnly: true,\n propertiesToConsider: this.propertiesToConsider,\n createNewEntryPointFormats: true,\n logger: this._logger,\n tsConfigPath: this.projectPath === defaultTsConfigPath ? undefined : this.projectPath,\n });\n\n this.ngccProcessingCache.markProcessed(moduleName);\n }\n\n /**\n * Try resolve a package.json file from the resolved .d.ts file.\n */\n private tryResolvePackage(moduleName: string, resolvedFileName: string): string | undefined {\n try {\n return require.resolve(`${moduleName}/package.json`, {\n paths: [resolvedFileName],\n });\n } catch {\n // if it fails this might be a deep import which doesn't have a package.json\n // Ex: @angular/compiler/src/i18n/i18n_ast/package.json\n // or local libraries which don't reside in node_modules\n const packageJsonPath = path.resolve(resolvedFileName, '../package.json');\n\n return existsSync(packageJsonPath) ? packageJsonPath : undefined;\n }\n }\n\n private findNodeModulesDirectory(startPoint: string): string | null {\n let current = startPoint;\n while (path.dirname(current) !== current) {\n const nodePath = path.join(current, 'node_modules');\n if (existsSync(nodePath)) {\n return nodePath;\n }\n\n current = path.dirname(current);\n }\n\n return null;\n }\n}\n\nclass NgccLogger implements Logger {\n level = /** LogLevel.info**/ 1;\n\n debug(...args: string[]) {\n log.debug(args.join(' '));\n }\n\n info(...args: string[]) {\n log.info(args.join(' '));\n }\n\n warn(...args: string[]) {\n log.warn(args.join(' '));\n }\n\n error(...args: string[]) {\n log.error(args.join(' '));\n }\n}\n\nfunction isReadOnlyFile(fileName: string): boolean {\n try {\n accessSync(fileName, constants.W_OK);\n\n return false;\n } catch {\n return true;\n }\n}\n"]}
|
|
@@ -48,8 +48,9 @@ function cacheCompilerHost(graph, entryPoint, compilerOptions, moduleResolutionC
|
|
|
48
48
|
const node = getNode(fileName);
|
|
49
49
|
entryPoint.dependsOn(node);
|
|
50
50
|
};
|
|
51
|
-
const { flatModuleFile, entryFile } = entryPoint.data.entryPoint;
|
|
51
|
+
const { flatModuleFile, destinationPath, entryFile } = entryPoint.data.entryPoint;
|
|
52
52
|
const flatModuleFileDtsFilename = `${flatModuleFile}.d.ts`;
|
|
53
|
+
const flatModuleFileDtsPath = (0, path_1.ensureUnixPath)(path.join(destinationPath, flatModuleFileDtsFilename));
|
|
53
54
|
const hasIndexEntryFile = path.basename(entryFile.toLowerCase()) === 'index.ts';
|
|
54
55
|
return {
|
|
55
56
|
...compilerHost,
|
|
@@ -71,14 +72,18 @@ function cacheCompilerHost(graph, entryPoint, compilerOptions, moduleResolutionC
|
|
|
71
72
|
},
|
|
72
73
|
writeFile: (fileName, data, writeByteOrderMark, onError, sourceFiles) => {
|
|
73
74
|
if (fileName.endsWith('.d.ts')) {
|
|
74
|
-
if (
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
75
|
+
if (fileName === flatModuleFileDtsPath) {
|
|
76
|
+
if (hasIndexEntryFile) {
|
|
77
|
+
// In case the entry file is index.ts, we should not emit the `d.ts` which are a re-export of the `index.ts`.
|
|
78
|
+
// Because it will cause a conflict.
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
// Rename file to index.d.ts so that TypeScript can resolve types without
|
|
83
|
+
// them needing to be referenced in the package.json manifest.
|
|
84
|
+
fileName = fileName.replace(flatModuleFileDtsFilename, 'index.d.ts');
|
|
85
|
+
}
|
|
78
86
|
}
|
|
79
|
-
// Rename file to index.d.ts so that TypeScript can resolve types without
|
|
80
|
-
// them needing to be referenced in the package.json manifest.
|
|
81
|
-
fileName = fileName.replace(flatModuleFileDtsFilename, 'index.d.ts');
|
|
82
87
|
sourceFiles.forEach(source => {
|
|
83
88
|
const cache = sourcesFileCache.getOrCreate(source.fileName);
|
|
84
89
|
if (!cache.declarationFileName) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-compiler-host.js","sourceRoot":"","sources":["../../../src/lib/ts/cache-compiler-host.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,mCAAoC;AACpC,2CAA6B;AAC7B,4DAA4B;AAI5B,wCAAqC;AACrC,+CA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AAS,EAAE;gBAC9B,IAAI,CAAC,OAAO,GAAG,IAAA,mBAAU,EAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;aACrE;SACF;QAED,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;AACJ,CAAC;AAbD,oEAaC","sourcesContent":["import type { CompilerHost, CompilerOptions } from '@angular/compiler-cli';\n\nimport { createHash } from 'crypto';\nimport * as path from 'path';\nimport ts from 'typescript';\nimport { NgPackageConfig } from '../../ng-package.schema';\nimport { FileCache } from '../file-system/file-cache';\nimport { BuildGraph } from '../graph/build-graph';\nimport { Node } from '../graph/node';\nimport { EntryPointNode, fileUrl } from '../ng-package/nodes';\nimport { StylesheetProcessor } from '../styles/stylesheet-processor';\nimport { ensureUnixPath } from '../utils/path';\n\nexport function cacheCompilerHost(\n graph: BuildGraph,\n entryPoint: EntryPointNode,\n compilerOptions: CompilerOptions,\n moduleResolutionCache: ts.ModuleResolutionCache,\n stylesheetProcessor?: StylesheetProcessor,\n inlineStyleLanguage?: NgPackageConfig['inlineStyleLanguage'],\n sourcesFileCache: FileCache = entryPoint.cache.sourcesFileCache,\n): CompilerHost {\n const compilerHost = ts.createIncrementalCompilerHost(compilerOptions);\n\n const getNode = (fileName: string) => {\n const nodeUri = fileUrl(ensureUnixPath(fileName));\n let node = graph.get(nodeUri);\n\n if (!node) {\n node = new Node(nodeUri);\n graph.put(node);\n }\n\n return node;\n };\n\n const addDependee = (fileName: string) => {\n const node = getNode(fileName);\n entryPoint.dependsOn(node);\n };\n\n const { flatModuleFile, entryFile } = entryPoint.data.entryPoint;\n const flatModuleFileDtsFilename = `${flatModuleFile}.d.ts`;\n const hasIndexEntryFile = path.basename(entryFile.toLowerCase()) === 'index.ts';\n\n return {\n ...compilerHost,\n\n // ts specific\n fileExists: (fileName: string) => {\n const cache = sourcesFileCache.getOrCreate(fileName);\n if (cache.exists === undefined) {\n cache.exists = compilerHost.fileExists.call(this, fileName);\n }\n\n return cache.exists;\n },\n\n getSourceFile: (fileName: string, languageVersion: ts.ScriptTarget) => {\n addDependee(fileName);\n const cache = sourcesFileCache.getOrCreate(fileName);\n if (!cache.sourceFile) {\n cache.sourceFile = compilerHost.getSourceFile.call(this, fileName, languageVersion);\n }\n\n return cache.sourceFile;\n },\n\n writeFile: (\n fileName: string,\n data: string,\n writeByteOrderMark: boolean,\n onError?: (message: string) => void,\n sourceFiles?: ReadonlyArray<ts.SourceFile>,\n ) => {\n if (fileName.endsWith('.d.ts')) {\n if (hasIndexEntryFile && path.basename(fileName) === flatModuleFileDtsFilename) {\n // In case the entry file is index.ts, we should not emit the `d.ts` which are a re-export of the `index.ts`.\n // Because it will cause a conflict.\n return;\n }\n\n // Rename file to index.d.ts so that TypeScript can resolve types without\n // them needing to be referenced in the package.json manifest.\n fileName = fileName.replace(flatModuleFileDtsFilename, 'index.d.ts');\n sourceFiles.forEach(source => {\n const cache = sourcesFileCache.getOrCreate(source.fileName);\n if (!cache.declarationFileName) {\n cache.declarationFileName = ensureUnixPath(fileName);\n }\n });\n } else {\n fileName = fileName.replace(/\\.js(\\.map)?$/, '.mjs$1');\n const outputCache = entryPoint.cache.outputCache;\n\n outputCache.set(fileName, {\n content: data,\n version: createHash('sha256').update(data).digest('hex'),\n });\n }\n\n compilerHost.writeFile.call(this, fileName, data, writeByteOrderMark, onError, sourceFiles);\n },\n\n readFile: (fileName: string) => {\n addDependee(fileName);\n const cache = sourcesFileCache.getOrCreate(fileName);\n if (cache.content === undefined) {\n cache.content = compilerHost.readFile.call(this, fileName);\n }\n\n return cache.content;\n },\n\n resolveModuleNames: (moduleNames: string[], containingFile: string) => {\n return moduleNames.map(moduleName => {\n const { resolvedModule } = ts.resolveModuleName(\n moduleName,\n ensureUnixPath(containingFile),\n compilerOptions,\n compilerHost,\n moduleResolutionCache,\n );\n\n return resolvedModule;\n });\n },\n\n resourceNameToFileName: (resourceName: string, containingFilePath: string) => {\n const resourcePath = path.resolve(path.dirname(containingFilePath), resourceName);\n const containingNode = getNode(containingFilePath);\n const resourceNode = getNode(resourcePath);\n containingNode.dependsOn(resourceNode);\n\n return resourcePath;\n },\n\n readResource: async (fileName: string) => {\n addDependee(fileName);\n\n const cache = sourcesFileCache.getOrCreate(fileName);\n if (cache.content === undefined) {\n if (/(?:html?|svg)$/.test(path.extname(fileName))) {\n // template\n cache.content = compilerHost.readFile.call(this, fileName);\n } else {\n // stylesheet\n cache.content = await stylesheetProcessor.process({\n filePath: fileName,\n content: compilerHost.readFile.call(this, fileName),\n });\n }\n\n if (cache.content === undefined) {\n throw new Error(`Cannot read file ${fileName}.`);\n }\n\n cache.exists = true;\n }\n\n return cache.content;\n },\n transformResource: async (data, context) => {\n if (context.resourceFile || context.type !== 'style') {\n return null;\n }\n\n if (inlineStyleLanguage) {\n const key = createHash('sha1').update(data).digest('hex');\n const fileName = `${context.containingFile}-${key}.${inlineStyleLanguage}`;\n const cache = sourcesFileCache.getOrCreate(fileName);\n if (cache.content === undefined) {\n cache.content = await stylesheetProcessor.process({\n filePath: fileName,\n content: data,\n });\n\n const virtualFileNode = getNode(fileName);\n const containingFileNode = getNode(context.containingFile);\n virtualFileNode.dependsOn(containingFileNode);\n }\n\n cache.exists = true;\n\n return { content: cache.content };\n }\n\n return null;\n },\n };\n}\n\nexport function augmentProgramWithVersioning(program: ts.Program): void {\n const baseGetSourceFiles = program.getSourceFiles;\n program.getSourceFiles = function (...parameters) {\n const files: readonly (ts.SourceFile & { version?: string })[] = baseGetSourceFiles(...parameters);\n\n for (const file of files) {\n if (file.version === undefined) {\n file.version = createHash('sha256').update(file.text).digest('hex');\n }\n }\n\n return files;\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cache-compiler-host.js","sourceRoot":"","sources":["../../../src/lib/ts/cache-compiler-host.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,mCAAoC;AACpC,2CAA6B;AAC7B,4DAA4B;AAI5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,MAAM,KAAK,GAAsD,kBAAkB,CAAC,GAAG,UAAU,CAAC,CAAC;QAEnG,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;YACxB,IAAI,IAAI,CAAC,OAAO,KAAK,SAAS,EAAE;gBAC9B,IAAI,CAAC,OAAO,GAAG,IAAA,mBAAU,EAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;aACrE;SACF;QAED,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;AACJ,CAAC;AAbD,oEAaC","sourcesContent":["import type { CompilerHost, CompilerOptions } from '@angular/compiler-cli';\n\nimport { createHash } from 'crypto';\nimport * as path from 'path';\nimport ts from 'typescript';\nimport { NgPackageConfig } from '../../ng-package.schema';\nimport { FileCache } from '../file-system/file-cache';\nimport { BuildGraph } from '../graph/build-graph';\nimport { Node } from '../graph/node';\nimport { EntryPointNode, fileUrl } from '../ng-package/nodes';\nimport { StylesheetProcessor } from '../styles/stylesheet-processor';\nimport { ensureUnixPath } from '../utils/path';\n\nexport function cacheCompilerHost(\n graph: BuildGraph,\n entryPoint: EntryPointNode,\n compilerOptions: CompilerOptions,\n moduleResolutionCache: ts.ModuleResolutionCache,\n stylesheetProcessor?: StylesheetProcessor,\n inlineStyleLanguage?: NgPackageConfig['inlineStyleLanguage'],\n sourcesFileCache: FileCache = entryPoint.cache.sourcesFileCache,\n): CompilerHost {\n const compilerHost = ts.createIncrementalCompilerHost(compilerOptions);\n\n const getNode = (fileName: string) => {\n const nodeUri = fileUrl(ensureUnixPath(fileName));\n let node = graph.get(nodeUri);\n\n if (!node) {\n node = new Node(nodeUri);\n graph.put(node);\n }\n\n return node;\n };\n\n const addDependee = (fileName: string) => {\n const node = getNode(fileName);\n entryPoint.dependsOn(node);\n };\n\n const { flatModuleFile, destinationPath, entryFile } = entryPoint.data.entryPoint;\n const flatModuleFileDtsFilename = `${flatModuleFile}.d.ts`;\n const flatModuleFileDtsPath = ensureUnixPath(path.join(destinationPath, flatModuleFileDtsFilename));\n const hasIndexEntryFile = path.basename(entryFile.toLowerCase()) === 'index.ts';\n\n return {\n ...compilerHost,\n\n // ts specific\n fileExists: (fileName: string) => {\n const cache = sourcesFileCache.getOrCreate(fileName);\n if (cache.exists === undefined) {\n cache.exists = compilerHost.fileExists.call(this, fileName);\n }\n\n return cache.exists;\n },\n\n getSourceFile: (fileName: string, languageVersion: ts.ScriptTarget) => {\n addDependee(fileName);\n const cache = sourcesFileCache.getOrCreate(fileName);\n if (!cache.sourceFile) {\n cache.sourceFile = compilerHost.getSourceFile.call(this, fileName, languageVersion);\n }\n\n return cache.sourceFile;\n },\n\n writeFile: (\n fileName: string,\n data: string,\n writeByteOrderMark: boolean,\n onError?: (message: string) => void,\n sourceFiles?: ReadonlyArray<ts.SourceFile>,\n ) => {\n if (fileName.endsWith('.d.ts')) {\n if (fileName === flatModuleFileDtsPath) {\n if (hasIndexEntryFile) {\n // In case the entry file is index.ts, we should not emit the `d.ts` which are a re-export of the `index.ts`.\n // Because it will cause a conflict.\n return;\n } else {\n // Rename file to index.d.ts so that TypeScript can resolve types without\n // them needing to be referenced in the package.json manifest.\n fileName = fileName.replace(flatModuleFileDtsFilename, 'index.d.ts');\n }\n }\n\n sourceFiles.forEach(source => {\n const cache = sourcesFileCache.getOrCreate(source.fileName);\n if (!cache.declarationFileName) {\n cache.declarationFileName = ensureUnixPath(fileName);\n }\n });\n } else {\n fileName = fileName.replace(/\\.js(\\.map)?$/, '.mjs$1');\n const outputCache = entryPoint.cache.outputCache;\n\n outputCache.set(fileName, {\n content: data,\n version: createHash('sha256').update(data).digest('hex'),\n });\n }\n\n compilerHost.writeFile.call(this, fileName, data, writeByteOrderMark, onError, sourceFiles);\n },\n\n readFile: (fileName: string) => {\n addDependee(fileName);\n const cache = sourcesFileCache.getOrCreate(fileName);\n if (cache.content === undefined) {\n cache.content = compilerHost.readFile.call(this, fileName);\n }\n\n return cache.content;\n },\n\n resolveModuleNames: (moduleNames: string[], containingFile: string) => {\n return moduleNames.map(moduleName => {\n const { resolvedModule } = ts.resolveModuleName(\n moduleName,\n ensureUnixPath(containingFile),\n compilerOptions,\n compilerHost,\n moduleResolutionCache,\n );\n\n return resolvedModule;\n });\n },\n\n resourceNameToFileName: (resourceName: string, containingFilePath: string) => {\n const resourcePath = path.resolve(path.dirname(containingFilePath), resourceName);\n const containingNode = getNode(containingFilePath);\n const resourceNode = getNode(resourcePath);\n containingNode.dependsOn(resourceNode);\n\n return resourcePath;\n },\n\n readResource: async (fileName: string) => {\n addDependee(fileName);\n\n const cache = sourcesFileCache.getOrCreate(fileName);\n if (cache.content === undefined) {\n if (/(?:html?|svg)$/.test(path.extname(fileName))) {\n // template\n cache.content = compilerHost.readFile.call(this, fileName);\n } else {\n // stylesheet\n cache.content = await stylesheetProcessor.process({\n filePath: fileName,\n content: compilerHost.readFile.call(this, fileName),\n });\n }\n\n if (cache.content === undefined) {\n throw new Error(`Cannot read file ${fileName}.`);\n }\n\n cache.exists = true;\n }\n\n return cache.content;\n },\n transformResource: async (data, context) => {\n if (context.resourceFile || context.type !== 'style') {\n return null;\n }\n\n if (inlineStyleLanguage) {\n const key = createHash('sha1').update(data).digest('hex');\n const fileName = `${context.containingFile}-${key}.${inlineStyleLanguage}`;\n const cache = sourcesFileCache.getOrCreate(fileName);\n if (cache.content === undefined) {\n cache.content = await stylesheetProcessor.process({\n filePath: fileName,\n content: data,\n });\n\n const virtualFileNode = getNode(fileName);\n const containingFileNode = getNode(context.containingFile);\n virtualFileNode.dependsOn(containingFileNode);\n }\n\n cache.exists = true;\n\n return { content: cache.content };\n }\n\n return null;\n },\n };\n}\n\nexport function augmentProgramWithVersioning(program: ts.Program): void {\n const baseGetSourceFiles = program.getSourceFiles;\n program.getSourceFiles = function (...parameters) {\n const files: readonly (ts.SourceFile & { version?: string })[] = baseGetSourceFiles(...parameters);\n\n for (const file of files) {\n if (file.version === undefined) {\n file.version = createHash('sha256').update(file.text).digest('hex');\n }\n }\n\n return files;\n };\n}\n"]}
|