|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google LLC 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 | + |
| 9 | +import { Rule, SchematicContext, Tree, UpdateRecorder, chain } from '@angular-devkit/schematics'; |
| 10 | +import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks'; |
| 11 | +import assert from 'assert'; |
| 12 | +import * as ts from '../../third_party/github.com/Microsoft/TypeScript/lib/typescript'; |
| 13 | +import { |
| 14 | + NodeDependency, |
| 15 | + getPackageJsonDependency, |
| 16 | + removePackageJsonDependency, |
| 17 | +} from '../../utility/dependencies'; |
| 18 | +import { allWorkspaceTargets, getWorkspace } from '../../utility/workspace'; |
| 19 | + |
| 20 | +/** |
| 21 | + * Migrates all polyfills files of projects to remove two dependencies originally needed by Internet |
| 22 | + * Explorer, but which are no longer needed now that support for IE has been dropped (`classlist.js` |
| 23 | + * and `web-animations-js`). |
| 24 | + * |
| 25 | + * The polyfills file includes side-effectful imports of these dependencies with comments about |
| 26 | + * their usage: |
| 27 | + * |
| 28 | + * ``` |
| 29 | + * /** |
| 30 | + * * IE11 requires the following for NgClass support on SVG elements |
| 31 | + * *\/ |
| 32 | + * import 'classlist.js'; |
| 33 | + * |
| 34 | + * /** |
| 35 | + * * Web Animations `@angular/platform-browser/animations` |
| 36 | + * * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. |
| 37 | + * * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). |
| 38 | + * *\/ |
| 39 | + * import 'web-animations-js'; |
| 40 | + * ``` |
| 41 | + * |
| 42 | + * This migration removes the `import` statements as well as any preceeding comments. It also |
| 43 | + * removes these dependencies from `package.json` if present and schedules an `npm install` task to |
| 44 | + * remove them from `node_modules/`. |
| 45 | + * |
| 46 | + * Also, the polyfills file has previously been generated with these imports commented out, to not |
| 47 | + * include the dependencies by default, but still allow users to easily uncomment and enable them |
| 48 | + * when required. So the migration also looks for: |
| 49 | + * |
| 50 | + * ``` |
| 51 | + * // import 'classlist.js'; // Run `npm install --save classlist.js`. |
| 52 | + * // OR |
| 53 | + * // import 'web-animations-js'; // Run `npm install --save web-animations-js`. |
| 54 | + * ``` |
| 55 | + * |
| 56 | + * And removes them as well. This keeps the polyfills files clean and up to date. Whitespace is |
| 57 | + * handled by leaving all trailing whitespace alone, and deleting all the leading newlines until the |
| 58 | + * previous non-empty line of code. This means any extra lines before a removed polyfill is dropped, |
| 59 | + * while any extra lines after a polyfill are retained. This roughly correlates to how a real |
| 60 | + * developer might write such a file. |
| 61 | + */ |
| 62 | +export default function (): Rule { |
| 63 | + return async (tree: Tree, ctx: SchematicContext) => { |
| 64 | + const modulesToDrop = new Set(['classlist.js', 'web-animations-js']); |
| 65 | + |
| 66 | + // Remove modules from `package.json` dependencies. |
| 67 | + const moduleDeps = Array.from(modulesToDrop.values()) |
| 68 | + .map((module) => getPackageJsonDependency(tree, module)) |
| 69 | + .filter((dep) => !!dep) as NodeDependency[]; |
| 70 | + for (const { name } of moduleDeps) { |
| 71 | + removePackageJsonDependency(tree, name); |
| 72 | + } |
| 73 | + |
| 74 | + // Run `npm install` after removal. This isn't strictly necessary, as keeping the dependencies |
| 75 | + // in `node_modules/` doesn't break anything. however non-polyfill usages of these dependencies |
| 76 | + // will work while they are in `node_modules/` but then break on the next `npm install`. If any |
| 77 | + // such usages exist, it is better for them to fail immediately after the migration instead of |
| 78 | + // the next time the user happens to `npm install`. As an optimization, only run `npm install` |
| 79 | + // if a dependency was actually removed. |
| 80 | + if (moduleDeps.length > 0) { |
| 81 | + ctx.addTask(new NodePackageInstallTask()); |
| 82 | + } |
| 83 | + |
| 84 | + // Find all the polyfill files in the workspace. |
| 85 | + const wksp = await getWorkspace(tree); |
| 86 | + const polyfills = Array.from(allWorkspaceTargets(wksp)) |
| 87 | + .filter(([_, target]) => !!target.options?.polyfills) |
| 88 | + .map(([_, target]) => target.options?.polyfills as string); |
| 89 | + const uniquePolyfills = Array.from(new Set(polyfills)); |
| 90 | + |
| 91 | + // Drop the modules from each polyfill. |
| 92 | + return chain(uniquePolyfills.map((polyfillPath) => dropModules(polyfillPath, modulesToDrop))); |
| 93 | + }; |
| 94 | +} |
| 95 | + |
| 96 | +/** Processes the given polyfill path and removes any `import` statements for the given modules. */ |
| 97 | +function dropModules(polyfillPath: string, modules: Set<string>): Rule { |
| 98 | + return (tree: Tree, ctx: SchematicContext) => { |
| 99 | + const sourceContent = tree.read(polyfillPath); |
| 100 | + if (!sourceContent) { |
| 101 | + ctx.logger.warn( |
| 102 | + 'Polyfill path from workspace configuration could not be read, does the file exist?', |
| 103 | + { polyfillPath }, |
| 104 | + ); |
| 105 | + |
| 106 | + return; |
| 107 | + } |
| 108 | + const content = sourceContent.toString('utf8'); |
| 109 | + |
| 110 | + const sourceFile = ts.createSourceFile( |
| 111 | + polyfillPath, |
| 112 | + content.replace(/^\uFEFF/, ''), |
| 113 | + ts.ScriptTarget.Latest, |
| 114 | + true /* setParentNodes */, |
| 115 | + ); |
| 116 | + |
| 117 | + // Remove polyfills for the given module specifiers. |
| 118 | + const recorder = tree.beginUpdate(polyfillPath); |
| 119 | + removePolyfillImports(recorder, sourceFile, modules); |
| 120 | + removePolyfillImportComments(recorder, sourceFile, modules); |
| 121 | + tree.commitUpdate(recorder); |
| 122 | + |
| 123 | + return tree; |
| 124 | + }; |
| 125 | +} |
| 126 | + |
| 127 | +/** |
| 128 | + * Searches the source file for any `import '${module}';` statements and removes them along with |
| 129 | + * any preceeding comments. |
| 130 | + * |
| 131 | + * @param recorder The recorder to remove from. |
| 132 | + * @param sourceFile The source file containing the `import` statements. |
| 133 | + * @param modules The module specifiers to remove. |
| 134 | + */ |
| 135 | +function removePolyfillImports( |
| 136 | + recorder: UpdateRecorder, |
| 137 | + sourceFile: ts.SourceFile, |
| 138 | + modules: Set<string>, |
| 139 | +): void { |
| 140 | + const imports = sourceFile.statements.filter((stmt) => |
| 141 | + ts.isImportDeclaration(stmt), |
| 142 | + ) as ts.ImportDeclaration[]; |
| 143 | + |
| 144 | + for (const i of imports) { |
| 145 | + // Should always be a string literal. |
| 146 | + assert(ts.isStringLiteral(i.moduleSpecifier)); |
| 147 | + |
| 148 | + // Ignore other modules. |
| 149 | + if (!modules.has(i.moduleSpecifier.text)) { |
| 150 | + continue; |
| 151 | + } |
| 152 | + |
| 153 | + // Remove the module import statement. |
| 154 | + recorder.remove(i.getStart(), i.getWidth()); |
| 155 | + |
| 156 | + // Remove leading comments. "Leading" comments seems to include comments within the node, so |
| 157 | + // even though `getFullText()` returns an index before any leading comments to a node, it will |
| 158 | + // still find and process them. |
| 159 | + ts.forEachLeadingCommentRange( |
| 160 | + sourceFile.getFullText(), |
| 161 | + i.getFullStart(), |
| 162 | + (start, end, _, hasTrailingNewLine) => { |
| 163 | + // Include both leading **and** trailing newlines because these are comments that *preceed* |
| 164 | + // the `import` statement, so "trailing" newlines here are actually in-between the `import` |
| 165 | + // and it's leading comments. |
| 166 | + const commentRangeWithoutNewLines = { start, end }; |
| 167 | + const commentRangeWithTrailingNewLines = hasTrailingNewLine |
| 168 | + ? includeTrailingNewLine(sourceFile, commentRangeWithoutNewLines) |
| 169 | + : commentRangeWithoutNewLines; |
| 170 | + const commentRange = includeLeadingNewLines(sourceFile, commentRangeWithTrailingNewLines); |
| 171 | + |
| 172 | + if (!isProtectedComment(sourceFile, commentRange)) { |
| 173 | + recorder.remove(commentRange.start, commentRange.end - commentRange.start); |
| 174 | + } |
| 175 | + }, |
| 176 | + ); |
| 177 | + } |
| 178 | +} |
| 179 | + |
| 180 | +/** |
| 181 | + * Searches the source file for any `// import '${module}';` comments and removes them along with |
| 182 | + * any preceeding comments. |
| 183 | + * |
| 184 | + * Recent `ng new` invocations generate polyfills commented out and not used by default. Ex: |
| 185 | + * /** |
| 186 | + * * IE11 requires the following for NgClass support on SVG elements |
| 187 | + * *\/ |
| 188 | + * // import 'classlist.js'; // Run `npm install --save classlist.js`. |
| 189 | + * |
| 190 | + * This function identifies any commented out import statements for the given module specifiers and |
| 191 | + * removes them along with immediately preceeding comments. |
| 192 | + * |
| 193 | + * @param recorder The recorder to remove from. |
| 194 | + * @param sourceFile The source file containing the commented `import` statements. |
| 195 | + * @param modules The module specifiers to remove. |
| 196 | + */ |
| 197 | +function removePolyfillImportComments( |
| 198 | + recorder: UpdateRecorder, |
| 199 | + sourceFile: ts.SourceFile, |
| 200 | + modules: Set<string>, |
| 201 | +): void { |
| 202 | + // Find all comment ranges in the source file. |
| 203 | + const commentRanges = getCommentRanges(sourceFile); |
| 204 | + |
| 205 | + // Find the indexes of comments which contain `import` statements for the given modules. |
| 206 | + const moduleImportCommentIndexes = filterIndex(commentRanges, ({ start, end }) => { |
| 207 | + const comment = getCommentText(sourceFile.getFullText().slice(start, end)); |
| 208 | + |
| 209 | + return Array.from(modules.values()).some((module) => comment.startsWith(`import '${module}';`)); |
| 210 | + }); |
| 211 | + |
| 212 | + // Use the module import comment **and** it's preceding comment if present. |
| 213 | + const commentIndexesToRemove = moduleImportCommentIndexes.flatMap((index) => { |
| 214 | + if (index === 0) { |
| 215 | + return [0]; |
| 216 | + } else { |
| 217 | + return [index - 1, index]; |
| 218 | + } |
| 219 | + }); |
| 220 | + |
| 221 | + // Get all the ranges for the comments to remove. |
| 222 | + const commentRangesToRemove = commentIndexesToRemove |
| 223 | + .map((index) => commentRanges[index]) |
| 224 | + // Include leading newlines but **not** trailing newlines in order to leave appropriate space |
| 225 | + // between any remaining polyfills. |
| 226 | + .map((range) => includeLeadingNewLines(sourceFile, range)) |
| 227 | + .filter((range) => !isProtectedComment(sourceFile, range)); |
| 228 | + |
| 229 | + // Remove the comments. |
| 230 | + for (const { start, end } of commentRangesToRemove) { |
| 231 | + recorder.remove(start, end - start); |
| 232 | + } |
| 233 | +} |
| 234 | + |
| 235 | +/** Represents a segment of text in a source file starting and ending at the given offsets. */ |
| 236 | +interface SourceRange { |
| 237 | + start: number; |
| 238 | + end: number; |
| 239 | +} |
| 240 | + |
| 241 | +/** |
| 242 | + * Returns whether a comment range is "protected", meaning it should **not** be deleted. |
| 243 | + * |
| 244 | + * There are two comments which are considered "protected": |
| 245 | + * 1. The file overview doc comment previously generated by `ng new`. |
| 246 | + * 2. The browser polyfills header (/***** BROWSER POLYFILLS *\/). |
| 247 | + */ |
| 248 | +function isProtectedComment(sourceFile: ts.SourceFile, { start, end }: SourceRange): boolean { |
| 249 | + const comment = getCommentText(sourceFile.getFullText().slice(start, end)); |
| 250 | + |
| 251 | + const isFileOverviewDocComment = comment.startsWith( |
| 252 | + 'This file includes polyfills needed by Angular and is loaded before the app.', |
| 253 | + ); |
| 254 | + const isBrowserPolyfillsHeader = comment.startsWith('BROWSER POLYFILLS'); |
| 255 | + |
| 256 | + return isFileOverviewDocComment || isBrowserPolyfillsHeader; |
| 257 | +} |
| 258 | + |
| 259 | +/** Returns all the comments in the given source file. */ |
| 260 | +function getCommentRanges(sourceFile: ts.SourceFile): SourceRange[] { |
| 261 | + const commentRanges = [] as SourceRange[]; |
| 262 | + |
| 263 | + // Comments trailing the last node are also included in this. |
| 264 | + ts.forEachChild(sourceFile, (node) => { |
| 265 | + ts.forEachLeadingCommentRange(sourceFile.getFullText(), node.getFullStart(), (start, end) => { |
| 266 | + commentRanges.push({ start, end }); |
| 267 | + }); |
| 268 | + }); |
| 269 | + |
| 270 | + return commentRanges; |
| 271 | +} |
| 272 | + |
| 273 | +/** Returns a `SourceRange` with any leading newlines' characters included if present. */ |
| 274 | +function includeLeadingNewLines( |
| 275 | + sourceFile: ts.SourceFile, |
| 276 | + { start, end }: SourceRange, |
| 277 | +): SourceRange { |
| 278 | + const text = sourceFile.getFullText(); |
| 279 | + while (start > 0) { |
| 280 | + if (start > 2 && text.slice(start - 2, start) === '\r\n') { |
| 281 | + // Preceeded by `\r\n`, include that. |
| 282 | + start -= 2; |
| 283 | + } else if (start > 1 && text[start - 1] === '\n') { |
| 284 | + // Preceeded by `\n`, include that. |
| 285 | + start--; |
| 286 | + } else { |
| 287 | + // Not preceeded by any newline characters, don't include anything else. |
| 288 | + break; |
| 289 | + } |
| 290 | + } |
| 291 | + |
| 292 | + return { start, end }; |
| 293 | +} |
| 294 | + |
| 295 | +/** Returns a `SourceRange` with the trailing newline characters included if present. */ |
| 296 | +function includeTrailingNewLine( |
| 297 | + sourceFile: ts.SourceFile, |
| 298 | + { start, end }: SourceRange, |
| 299 | +): SourceRange { |
| 300 | + const newline = sourceFile.getFullText().slice(end, end + 2); |
| 301 | + if (newline === '\r\n') { |
| 302 | + return { start, end: end + 2 }; |
| 303 | + } else if (newline.startsWith('\n')) { |
| 304 | + return { start, end: end + 1 }; |
| 305 | + } else { |
| 306 | + throw new Error('Expected comment to end in a newline character (either `\\n` or `\\r\\n`).'); |
| 307 | + } |
| 308 | +} |
| 309 | + |
| 310 | +/** |
| 311 | + * Extracts the text from a comment. Attempts to remove any extraneous syntax and trims the content. |
| 312 | + */ |
| 313 | +function getCommentText(commentInput: string): string { |
| 314 | + const comment = commentInput.trim(); |
| 315 | + if (comment.startsWith('//')) { |
| 316 | + return comment.slice('//'.length).trim(); |
| 317 | + } else if (comment.startsWith('/*')) { |
| 318 | + const withoutPrefix = comment.replace(/\/\*+/, ''); |
| 319 | + const withoutSuffix = withoutPrefix.replace(/\*+\//, ''); |
| 320 | + const withoutNewlineAsterisks = withoutSuffix.replace(/^\s*\*\s*/, ''); |
| 321 | + |
| 322 | + return withoutNewlineAsterisks.trim(); |
| 323 | + } else { |
| 324 | + throw new Error(`Expected a comment, but got: "${comment}".`); |
| 325 | + } |
| 326 | +} |
| 327 | + |
| 328 | +/** Like `Array.prototype.filter`, but returns the index of each item rather than its value. */ |
| 329 | +function filterIndex<Item>(items: Item[], filter: (item: Item) => boolean): number[] { |
| 330 | + return Array.from(items.entries()) |
| 331 | + .filter(([_, item]) => filter(item)) |
| 332 | + .map(([index]) => index); |
| 333 | +} |
0 commit comments