Skip to content

Commit 15a92ab

Browse files
committed
fix(@angular/cli): direct Angular schematic dependency requests to known versions
This change adds logic to redirect module resolution requests for Angular schematics to ensure that the correct versions of core schematic related packages are used. This also ensures that the runtime version of the schematics package matches the version used inside the schematic and that object instances passed into the schematic are compatible. The current set of core schematic related packages are `@angular-devkit/*` and `@schematics/angular`. Only first-party Angular schematics are currently affected by this change.
1 parent 6a524c5 commit 15a92ab

File tree

4 files changed

+149
-4
lines changed

4 files changed

+149
-4
lines changed

packages/angular/cli/models/schematic-command.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import {
2323
FileSystemCollection,
2424
FileSystemEngine,
2525
FileSystemSchematic,
26-
FileSystemSchematicDescription,
2726
NodeWorkflow,
2827
} from '@angular-devkit/schematics/tools';
2928
import * as inquirer from 'inquirer';
@@ -37,6 +36,7 @@ import { isPackageNameSafeForAnalytics } from './analytics';
3736
import { BaseCommandOptions, Command } from './command';
3837
import { Arguments, CommandContext, CommandDescription, Option } from './interface';
3938
import { parseArguments, parseFreeFormArguments } from './parser';
39+
import { SchematicEngineHost } from './schematic-engine-host';
4040

4141
export interface BaseSchematicSchema {
4242
debug?: boolean;
@@ -258,6 +258,7 @@ export abstract class SchematicCommand<
258258
...current,
259259
}),
260260
],
261+
engineHostCreator: (options) => new SchematicEngineHost(options.resolvePaths),
261262
});
262263

263264
const getProjectName = () => {
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
/**
2+
* @license
3+
* Copyright Google Inc. All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
import { RuleFactory } from '@angular-devkit/schematics';
9+
import { NodeModulesEngineHost } from '@angular-devkit/schematics/tools';
10+
import { readFileSync } from 'fs';
11+
import { dirname } from 'path';
12+
import { Script } from 'vm';
13+
14+
export class SchematicEngineHost extends NodeModulesEngineHost {
15+
protected _resolveReferenceString(refString: string, parentPath: string) {
16+
const [path, name] = refString.split('#', 2);
17+
const schematicFile = require.resolve(path, { paths: [parentPath] });
18+
19+
const isAngularSchematic = /[\/\\]node_modules[\/\\]@(?:angular|schematics)[\/\\]/.test(
20+
schematicFile,
21+
);
22+
23+
// Angular schematics are safe to use in the wrapped VM context
24+
if (isAngularSchematic) {
25+
const schematicPath = dirname(schematicFile);
26+
27+
const moduleCache = new Map<string, unknown>();
28+
const factoryInitializer = wrap(
29+
schematicFile,
30+
schematicPath,
31+
moduleCache,
32+
name || 'default',
33+
) as () => RuleFactory<{}>;
34+
35+
const factory = factoryInitializer();
36+
if (!factory || typeof factory !== 'function') {
37+
return null;
38+
}
39+
40+
return { ref: factory, path: schematicPath };
41+
}
42+
43+
// All other schematics use default behavior
44+
return super._resolveReferenceString(refString, parentPath);
45+
}
46+
}
47+
48+
/**
49+
* Wrap a JavaScript file in a VM context to allow specific Angular dependencies to be redirected.
50+
* This VM setup is ONLY intended to redirect dependencies.
51+
*
52+
* @param schematicFile A JavaScript schematic file path that should be wrapped.
53+
* @param schematicDirectory A directory that will be used as the location of the JavaScript file.
54+
* @param moduleCache A map to use for caching repeat module usage and proper `instanceof` support.
55+
* @param exportName An optional name of a specific export to return. Otherwise, return all exports.
56+
*/
57+
function wrap(
58+
schematicFile: string,
59+
schematicDirectory: string,
60+
moduleCache: Map<string, unknown>,
61+
exportName?: string,
62+
): () => unknown {
63+
const { createRequire, createRequireFromPath } = require('module');
64+
// Node.js 10.x does not support `createRequire` so fallback to `createRequireFromPath`
65+
// `createRequireFromPath` is deprecated in 12+ and can be removed once 10.x support is removed
66+
const scopedRequire = createRequire?.(schematicFile) || createRequireFromPath(schematicDirectory);
67+
68+
const customRequire = function (id: string) {
69+
if (id.startsWith('@angular-devkit/') || id.startsWith('@schematics/')) {
70+
// Resolve from inside the @angular/cli project
71+
const packagePath = require.resolve(id);
72+
73+
return require(packagePath);
74+
} else if (id.startsWith('.') || id.startsWith('@angular/cdk')) {
75+
// Resolve from the original file
76+
const modulePath = scopedRequire.resolve(id);
77+
78+
// Do not wrap vendored third-party packages
79+
if (!modulePath.includes('@schematics/angular/third_party')) {
80+
const cachedModule = moduleCache.get(modulePath);
81+
if (cachedModule) {
82+
return cachedModule;
83+
}
84+
85+
const wrappedModule = wrap(modulePath, dirname(modulePath), moduleCache)();
86+
moduleCache.set(modulePath, wrappedModule);
87+
88+
return wrappedModule;
89+
}
90+
}
91+
92+
// All others are required directly from the original file
93+
return scopedRequire(id);
94+
};
95+
96+
// Setup a wrapper function to capture the module's exports
97+
const schematicCode = readFileSync(schematicFile, 'utf8');
98+
// `module` is required due to @angular/localize ng-add being in UMD format
99+
const headerCode = '(function() {\nvar exports = Object.create(null);\nvar module = { exports };\n';
100+
const footerCode = exportName ? `\nreturn exports['${exportName}'];});` : '\nreturn exports;});';
101+
102+
const script = new Script(headerCode + schematicCode + footerCode, {
103+
filename: schematicFile,
104+
lineOffset: 3,
105+
});
106+
107+
const context = {
108+
__dirname: schematicDirectory,
109+
__filename: schematicFile,
110+
Buffer,
111+
console,
112+
process,
113+
get global() {
114+
return this;
115+
},
116+
require: customRequire,
117+
};
118+
119+
const exportsFactory = script.runInNewContext(context);
120+
121+
return exportsFactory;
122+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { join } from 'path';
2+
import { expectFileToMatch } from '../../utils/fs';
3+
import { ng } from '../../utils/process';
4+
import { installPackage, uninstallPackage } from '../../utils/packages';
5+
import { isPrereleaseCli } from '../../utils/project';
6+
7+
export default async function () {
8+
const componentDir = join('src', 'app', 'test-component');
9+
10+
// Install old and incompatible version
11+
// Must directly use npm registry since old versions are not hosted locally
12+
await installPackage('@schematics/angular@7', 'https://registry.npmjs.org')
13+
14+
const tag = await isPrereleaseCli() ? '@next' : '';
15+
await ng('add', `@angular/material${tag}`);
16+
await expectFileToMatch('package.json', /@angular\/material/);
17+
18+
// Clean up existing cdk package
19+
// Not doing so can cause adding material to fail if an incompatible cdk is present
20+
await uninstallPackage('@angular/cdk');
21+
}

tests/legacy-cli/e2e/utils/packages.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,13 @@ export async function installWorkspacePackages(updateWebdriver = true): Promise<
2727
}
2828
}
2929

30-
export async function installPackage(specifier: string): Promise<ProcessOutput> {
30+
export async function installPackage(specifier: string, registry?: string): Promise<ProcessOutput> {
31+
const registryOption = registry ? [`--registry=${registry}`] : [];
3132
switch (getActivePackageManager()) {
3233
case 'npm':
33-
return silentNpm('install', specifier);
34+
return silentNpm('install', specifier, ...registryOption);
3435
case 'yarn':
35-
return silentYarn('add', specifier);
36+
return silentYarn('add', specifier, ...registryOption);
3637
}
3738
}
3839

0 commit comments

Comments
 (0)