|
| 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, SchematicsException, Tree } from '@angular-devkit/schematics'; |
| 9 | +import { NodeModulesEngineHost } from '@angular-devkit/schematics/tools'; |
| 10 | +import { readFileSync } from 'fs'; |
| 11 | +import { parse as parseJson } from 'jsonc-parser'; |
| 12 | +import { dirname, resolve } from 'path'; |
| 13 | +import { Script } from 'vm'; |
| 14 | + |
| 15 | +/** |
| 16 | + * Environment variable to control schematic package redirection |
| 17 | + * Default: Angular schematics only |
| 18 | + */ |
| 19 | +const schematicRedirectVariable = process.env['NG_SCHEMATIC_REDIRECT']?.toLowerCase(); |
| 20 | + |
| 21 | +function shouldWrapSchematic(schematicFile: string): boolean { |
| 22 | + // Check environment variable if present |
| 23 | + if (schematicRedirectVariable !== undefined) { |
| 24 | + switch (schematicRedirectVariable) { |
| 25 | + case '0': |
| 26 | + case 'false': |
| 27 | + case 'off': |
| 28 | + case 'none': |
| 29 | + return false; |
| 30 | + case 'all': |
| 31 | + return true; |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + // Never wrap `@schematics/update` when executed directly |
| 36 | + // It communicates with the update command via `global` |
| 37 | + if (/[\/\\]node_modules[\/\\]@schematics[\/\\]update[\/\\]/.test(schematicFile)) { |
| 38 | + return false; |
| 39 | + } |
| 40 | + |
| 41 | + // Default is only first-party Angular schematic packages |
| 42 | + // Angular schematics are safe to use in the wrapped VM context |
| 43 | + return /[\/\\]node_modules[\/\\]@(?:angular|schematics|nguniversal)[\/\\]/.test(schematicFile); |
| 44 | +} |
| 45 | + |
| 46 | +export class SchematicEngineHost extends NodeModulesEngineHost { |
| 47 | + protected _resolveReferenceString(refString: string, parentPath: string) { |
| 48 | + const [path, name] = refString.split('#', 2); |
| 49 | + // Mimic behavior of ExportStringRef class used in default behavior |
| 50 | + const fullPath = path[0] === '.' ? resolve(parentPath ?? process.cwd(), path) : path; |
| 51 | + |
| 52 | + const schematicFile = require.resolve(fullPath, { paths: [parentPath] }); |
| 53 | + |
| 54 | + if (shouldWrapSchematic(schematicFile)) { |
| 55 | + const schematicPath = dirname(schematicFile); |
| 56 | + |
| 57 | + const moduleCache = new Map<string, unknown>(); |
| 58 | + const factoryInitializer = wrap( |
| 59 | + schematicFile, |
| 60 | + schematicPath, |
| 61 | + moduleCache, |
| 62 | + name || 'default', |
| 63 | + ) as () => RuleFactory<{}>; |
| 64 | + |
| 65 | + const factory = factoryInitializer(); |
| 66 | + if (!factory || typeof factory !== 'function') { |
| 67 | + return null; |
| 68 | + } |
| 69 | + |
| 70 | + return { ref: factory, path: schematicPath }; |
| 71 | + } |
| 72 | + |
| 73 | + // All other schematics use default behavior |
| 74 | + return super._resolveReferenceString(refString, parentPath); |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +/** |
| 79 | + * Minimal shim modules for legacy deep imports of `@schematics/angular` |
| 80 | + */ |
| 81 | +const legacyModules: Record<string, unknown> = { |
| 82 | + '@schematics/angular/utility/config': { |
| 83 | + getWorkspace(host: Tree) { |
| 84 | + const path = '/.angular.json'; |
| 85 | + const data = host.read(path); |
| 86 | + if (!data) { |
| 87 | + throw new SchematicsException(`Could not find (${path})`); |
| 88 | + } |
| 89 | + |
| 90 | + return parseJson(data.toString(), [], { allowTrailingComma: true }); |
| 91 | + }, |
| 92 | + }, |
| 93 | + '@schematics/angular/utility/project': { |
| 94 | + buildDefaultPath(project: { sourceRoot?: string; root: string; projectType: string }): string { |
| 95 | + const root = project.sourceRoot ? `/${project.sourceRoot}/` : `/${project.root}/src/`; |
| 96 | + |
| 97 | + return `${root}${project.projectType === 'application' ? 'app' : 'lib'}`; |
| 98 | + }, |
| 99 | + }, |
| 100 | +}; |
| 101 | + |
| 102 | +/** |
| 103 | + * Wrap a JavaScript file in a VM context to allow specific Angular dependencies to be redirected. |
| 104 | + * This VM setup is ONLY intended to redirect dependencies. |
| 105 | + * |
| 106 | + * @param schematicFile A JavaScript schematic file path that should be wrapped. |
| 107 | + * @param schematicDirectory A directory that will be used as the location of the JavaScript file. |
| 108 | + * @param moduleCache A map to use for caching repeat module usage and proper `instanceof` support. |
| 109 | + * @param exportName An optional name of a specific export to return. Otherwise, return all exports. |
| 110 | + */ |
| 111 | +function wrap( |
| 112 | + schematicFile: string, |
| 113 | + schematicDirectory: string, |
| 114 | + moduleCache: Map<string, unknown>, |
| 115 | + exportName?: string, |
| 116 | +): () => unknown { |
| 117 | + const { createRequire, createRequireFromPath } = require('module'); |
| 118 | + // Node.js 10.x does not support `createRequire` so fallback to `createRequireFromPath` |
| 119 | + // `createRequireFromPath` is deprecated in 12+ and can be removed once 10.x support is removed |
| 120 | + const scopedRequire = createRequire?.(schematicFile) || createRequireFromPath(schematicFile); |
| 121 | + |
| 122 | + const customRequire = function (id: string) { |
| 123 | + if (legacyModules[id]) { |
| 124 | + // Provide compatibility modules for older versions of @angular/cdk |
| 125 | + return legacyModules[id]; |
| 126 | + } else if (id.startsWith('@angular-devkit/') || id.startsWith('@schematics/')) { |
| 127 | + // Resolve from inside the `@angular/cli` project |
| 128 | + const packagePath = require.resolve(id); |
| 129 | + |
| 130 | + return require(packagePath); |
| 131 | + } else if (id.startsWith('.') || id.startsWith('@angular/cdk')) { |
| 132 | + // Wrap relative files inside the schematic collection |
| 133 | + // Also wrap `@angular/cdk`, it contains helper utilities that import core schematic packages |
| 134 | + |
| 135 | + // Resolve from the original file |
| 136 | + const modulePath = scopedRequire.resolve(id); |
| 137 | + |
| 138 | + // Use cached module if available |
| 139 | + const cachedModule = moduleCache.get(modulePath); |
| 140 | + if (cachedModule) { |
| 141 | + return cachedModule; |
| 142 | + } |
| 143 | + |
| 144 | + // Do not wrap vendored third-party packages or JSON files |
| 145 | + if ( |
| 146 | + !/[\/\\]node_modules[\/\\]@schematics[\/\\]angular[\/\\]third_party[\/\\]/.test( |
| 147 | + modulePath, |
| 148 | + ) && |
| 149 | + !modulePath.endsWith('.json') |
| 150 | + ) { |
| 151 | + // Wrap module and save in cache |
| 152 | + const wrappedModule = wrap(modulePath, dirname(modulePath), moduleCache)(); |
| 153 | + moduleCache.set(modulePath, wrappedModule); |
| 154 | + |
| 155 | + return wrappedModule; |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + // All others are required directly from the original file |
| 160 | + return scopedRequire(id); |
| 161 | + }; |
| 162 | + |
| 163 | + // Setup a wrapper function to capture the module's exports |
| 164 | + const schematicCode = readFileSync(schematicFile, 'utf8'); |
| 165 | + // `module` is required due to @angular/localize ng-add being in UMD format |
| 166 | + const headerCode = '(function() {\nvar exports = {};\nvar module = { exports };\n'; |
| 167 | + const footerCode = exportName ? `\nreturn exports['${exportName}'];});` : '\nreturn exports;});'; |
| 168 | + |
| 169 | + const script = new Script(headerCode + schematicCode + footerCode, { |
| 170 | + filename: schematicFile, |
| 171 | + lineOffset: 3, |
| 172 | + }); |
| 173 | + |
| 174 | + const context = { |
| 175 | + __dirname: schematicDirectory, |
| 176 | + __filename: schematicFile, |
| 177 | + Buffer, |
| 178 | + console, |
| 179 | + process, |
| 180 | + get global() { |
| 181 | + return this; |
| 182 | + }, |
| 183 | + require: customRequire, |
| 184 | + }; |
| 185 | + |
| 186 | + const exportsFactory = script.runInNewContext(context); |
| 187 | + |
| 188 | + return exportsFactory; |
| 189 | +} |
0 commit comments