-
Notifications
You must be signed in to change notification settings - Fork 29k
feat(core): add syntactic sugar for initializers #53152
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
21 changes: 21 additions & 0 deletions
21
packages/core/schematics/migrations/provide-initializer/BUILD.bazel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| load("//tools:defaults.bzl", "ts_library") | ||
|
|
||
| package( | ||
| default_visibility = [ | ||
| "//packages/core/schematics:__pkg__", | ||
| "//packages/core/schematics/migrations/google3:__pkg__", | ||
| "//packages/core/schematics/test:__pkg__", | ||
| ], | ||
| ) | ||
|
|
||
| ts_library( | ||
| name = "provide-initializer", | ||
| srcs = glob(["**/*.ts"]), | ||
| tsconfig = "//packages/core/schematics:tsconfig.json", | ||
| deps = [ | ||
| "//packages/core/schematics/utils", | ||
| "@npm//@angular-devkit/schematics", | ||
| "@npm//@types/node", | ||
| "@npm//typescript", | ||
| ], | ||
| ) |
25 changes: 25 additions & 0 deletions
25
packages/core/schematics/migrations/provide-initializer/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| ## Replace `APP_INITIALIZER`, `ENVIRONMENT_INITIALIZER`, and `PLATFORM_INITIALIZER` with provider functions | ||
|
|
||
| Replaces `APP_INITIALIZER`, `ENVIRONMENT_INITIALIZER`, and `PLATFORM_INITIALIZER` with their respective provider functions: `provideAppInitializer`, `provideEnvironmentInitializer`, and `providePlatformInitializer`. | ||
|
|
||
| #### Before | ||
|
|
||
| ```ts | ||
| import {APP_INITIALIZER} from '@angular/core'; | ||
|
|
||
| const providers = [ | ||
| { | ||
| provide: APP_INITIALIZER, | ||
| useValue: () => { console.log('hello'); }, | ||
| multi: true, | ||
| } | ||
| ]; | ||
| ``` | ||
|
|
||
| #### After | ||
|
|
||
| ```ts | ||
| import {provideAppInitializer} from '@angular/core'; | ||
|
|
||
| const providers = [provideAppInitializer(() => { console.log('hello'); })]; | ||
| ``` |
58 changes: 58 additions & 0 deletions
58
packages/core/schematics/migrations/provide-initializer/index.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| /** | ||
| * @license | ||
| * Copyright Google LLC All Rights Reserved. | ||
| * | ||
| * Use of this source code is governed by an MIT-style license that can be | ||
| * found in the LICENSE file at https://angular.dev/license | ||
| */ | ||
|
|
||
| import {Rule, SchematicsException, Tree, UpdateRecorder} from '@angular-devkit/schematics'; | ||
| import {relative} from 'path'; | ||
| import {getProjectTsConfigPaths} from '../../utils/project_tsconfig_paths'; | ||
| import {canMigrateFile, createMigrationProgram} from '../../utils/typescript/compiler_host'; | ||
| import {migrateFile} from './utils'; | ||
|
|
||
| export function migrate(): Rule { | ||
| return async (tree: Tree) => { | ||
| const {buildPaths, testPaths} = await getProjectTsConfigPaths(tree); | ||
| const basePath = process.cwd(); | ||
| const allPaths = [...buildPaths, ...testPaths]; | ||
|
|
||
| if (!allPaths.length) { | ||
| throw new SchematicsException( | ||
| 'Could not find any tsconfig file. Cannot run the provide initializer migration.', | ||
| ); | ||
| } | ||
|
|
||
| for (const tsconfigPath of allPaths) { | ||
| runMigration(tree, tsconfigPath, basePath); | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| function runMigration(tree: Tree, tsconfigPath: string, basePath: string) { | ||
| const program = createMigrationProgram(tree, tsconfigPath, basePath); | ||
| const sourceFiles = program | ||
| .getSourceFiles() | ||
| .filter((sourceFile) => canMigrateFile(basePath, sourceFile, program)); | ||
|
|
||
| for (const sourceFile of sourceFiles) { | ||
| let update: UpdateRecorder | null = null; | ||
|
|
||
| const rewriter = (startPos: number, width: number, text: string | null) => { | ||
| if (update === null) { | ||
| // Lazily initialize update, because most files will not require migration. | ||
| update = tree.beginUpdate(relative(basePath, sourceFile.fileName)); | ||
| } | ||
| update.remove(startPos, width); | ||
| if (text !== null) { | ||
| update.insertLeft(startPos, text); | ||
| } | ||
| }; | ||
| migrateFile(sourceFile, rewriter); | ||
|
|
||
| if (update !== null) { | ||
| tree.commitUpdate(update); | ||
| } | ||
| } | ||
| } |
194 changes: 194 additions & 0 deletions
194
packages/core/schematics/migrations/provide-initializer/utils.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,194 @@ | ||
| /** | ||
| * @license | ||
| * Copyright Google LLC All Rights Reserved. | ||
| * | ||
| * Use of this source code is governed by an MIT-style license that can be | ||
| * found in the LICENSE file at https://angular.io/license | ||
| */ | ||
|
|
||
| import ts from 'typescript'; | ||
|
|
||
| import {ChangeTracker} from '../../utils/change_tracker'; | ||
| import {getImportSpecifier} from '../../utils/typescript/imports'; | ||
| import {closestNode} from '../../utils/typescript/nodes'; | ||
|
|
||
| export type RewriteFn = (startPos: number, width: number, text: string) => void; | ||
|
|
||
| export function migrateFile(sourceFile: ts.SourceFile, rewriteFn: RewriteFn) { | ||
| const changeTracker = new ChangeTracker(ts.createPrinter()); | ||
|
|
||
| const visitNode = (node: ts.Node) => { | ||
| const provider = tryParseProviderExpression(node); | ||
|
|
||
| if (provider) { | ||
| replaceProviderWithNewApi({ | ||
| sourceFile: sourceFile, | ||
| node: node, | ||
| provider: provider, | ||
| changeTracker, | ||
| }); | ||
| return; | ||
| } | ||
|
|
||
| ts.forEachChild(node, visitNode); | ||
| }; | ||
|
|
||
| ts.forEachChild(sourceFile, visitNode); | ||
|
|
||
| for (const change of changeTracker.recordChanges().get(sourceFile)?.values() ?? []) { | ||
| rewriteFn(change.start, change.removeLength ?? 0, change.text); | ||
| } | ||
| } | ||
|
|
||
| function replaceProviderWithNewApi({ | ||
| sourceFile, | ||
| node, | ||
| provider, | ||
| changeTracker, | ||
| }: { | ||
| sourceFile: ts.SourceFile; | ||
| node: ts.Node; | ||
| provider: ProviderInfo; | ||
| changeTracker: ChangeTracker; | ||
| }) { | ||
| const {initializerCode, importInject, provideInitializerFunctionName, initializerToken} = | ||
| provider; | ||
|
|
||
| const initializerTokenSpecifier = getImportSpecifier( | ||
| sourceFile, | ||
| angularCoreModule, | ||
| initializerToken, | ||
| ); | ||
|
|
||
| // The token doesn't come from `@angular/core`. | ||
| if (!initializerTokenSpecifier) { | ||
| return; | ||
| } | ||
|
|
||
| // Replace the provider with the new provide function. | ||
| changeTracker.replaceText( | ||
| sourceFile, | ||
| node.getStart(), | ||
| node.getWidth(), | ||
| `${provideInitializerFunctionName}(${initializerCode})`, | ||
| ); | ||
|
|
||
| // Import declaration and named imports are necessarily there. | ||
| const namedImports = closestNode(initializerTokenSpecifier, ts.isNamedImports)!; | ||
|
|
||
| // `provide*Initializer` function is already imported. | ||
| const hasProvideInitializeFunction = namedImports.elements.some( | ||
| (element) => element.name.getText() === provideInitializerFunctionName, | ||
| ); | ||
|
|
||
| const newNamedImports = ts.factory.updateNamedImports(namedImports, [ | ||
| // Remove the `*_INITIALIZER` token from imports. | ||
| ...namedImports.elements.filter((element) => element !== initializerTokenSpecifier), | ||
| // Add the `inject` function to imports if needed. | ||
| ...(importInject ? [createImportSpecifier('inject')] : []), | ||
| // Add the `provide*Initializer` function to imports. | ||
| ...(!hasProvideInitializeFunction | ||
| ? [createImportSpecifier(provideInitializerFunctionName)] | ||
| : []), | ||
| ]); | ||
| changeTracker.replaceNode(namedImports, newNamedImports); | ||
| } | ||
|
|
||
| function createImportSpecifier(name: string): ts.ImportSpecifier { | ||
| return ts.factory.createImportSpecifier(false, undefined, ts.factory.createIdentifier(name)); | ||
| } | ||
|
|
||
| function tryParseProviderExpression(node: ts.Node): ProviderInfo | undefined { | ||
| if (!ts.isObjectLiteralExpression(node)) { | ||
| return; | ||
| } | ||
|
|
||
| let deps: string[] = []; | ||
| let initializerToken: string | undefined; | ||
| let useExisting: ts.Expression | undefined; | ||
| let useFactory: ts.Expression | undefined; | ||
| let useValue: ts.Expression | undefined; | ||
| let multi = false; | ||
|
|
||
| for (const property of node.properties) { | ||
| if (!ts.isPropertyAssignment(property) || !ts.isIdentifier(property.name)) { | ||
| continue; | ||
| } | ||
|
|
||
| switch (property.name.text) { | ||
| case 'deps': | ||
| if (ts.isArrayLiteralExpression(property.initializer)) { | ||
| deps = property.initializer.elements.map((el) => el.getText()); | ||
| } | ||
| break; | ||
| case 'provide': | ||
| initializerToken = property.initializer.getText(); | ||
| break; | ||
| case 'useExisting': | ||
| useExisting = property.initializer; | ||
| break; | ||
| case 'useFactory': | ||
| useFactory = property.initializer; | ||
| break; | ||
| case 'useValue': | ||
| useValue = property.initializer; | ||
| break; | ||
| case 'multi': | ||
| multi = property.initializer.kind === ts.SyntaxKind.TrueKeyword; | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| if (!initializerToken || !multi) { | ||
| return; | ||
| } | ||
|
|
||
| const provideInitializerFunctionName = initializerTokenToFunctionMap.get(initializerToken); | ||
| if (!provideInitializerFunctionName) { | ||
| return; | ||
| } | ||
|
|
||
| const info = { | ||
| initializerToken, | ||
| provideInitializerFunctionName, | ||
| importInject: false, | ||
| } satisfies Partial<ProviderInfo>; | ||
|
|
||
| if (useExisting) { | ||
| return { | ||
| ...info, | ||
| importInject: true, | ||
| initializerCode: `() => inject(${useExisting.getText()})()`, | ||
| }; | ||
| } | ||
|
|
||
| if (useFactory) { | ||
| const args = deps.map((dep) => `inject(${dep})`); | ||
| return { | ||
| ...info, | ||
| importInject: deps.length > 0, | ||
| initializerCode: `() => { return (${useFactory.getText()})(${args.join(', ')}); }`, | ||
| }; | ||
| } | ||
|
|
||
| if (useValue) { | ||
| return {...info, initializerCode: useValue.getText()}; | ||
| } | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| const angularCoreModule = '@angular/core'; | ||
|
|
||
| const initializerTokenToFunctionMap = new Map<string, string>([ | ||
| ['APP_INITIALIZER', 'provideAppInitializer'], | ||
| ['ENVIRONMENT_INITIALIZER', 'provideEnvironmentInitializer'], | ||
| ['PLATFORM_INITIALIZER', 'providePlatformInitializer'], | ||
| ]); | ||
|
|
||
| interface ProviderInfo { | ||
| initializerToken: string; | ||
| provideInitializerFunctionName: string; | ||
| initializerCode: string; | ||
| importInject: boolean; | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't think this migration is safe to run automatically. The provider functions in this PR return
EnvironmentProviders(as they should) but existing usages may not be typed in a way to handle that type.We can exclude it and use it as an optional migration for now.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note: to make it optional you can just add
“optional”: trueUh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice catch!
What would be the solution to make it automatic for v20?
We could detect where it is used and transform when it is safe. When it's not safe what would be the fallback? A type cast? A compact function? 🤔
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thx @JeanMeche for handling this while I'm AFK 😊