_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/base_class.ts_0_595
// tslint:disable import {Directive, Input} from '@angular/core'; class BaseNonAngular { disabled: string = ''; } @Directive() class Sub implements BaseNonAngular { // should not be migrated because of the interface. @Input() disabled = ''; } class BaseWithAngular { @Input() disabled: string = ''; } @Directive() class Sub2 extends BaseWithAngular { @Input() disabled = ''; } interface BaseNonAngularInterface { disabled: string; } @Directive() class Sub3 implements BaseNonAngularInterface { // should not be migrated because of the interface. @Input() disabled = ''; }
{ "end_byte": 595, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/base_class.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/transform_incompatible_types.ts_0_303
// tslint:disable import {Directive, Input} from '@angular/core'; // see: button-base Material. @Directive() class TransformIncompatibleTypes { // @ts-ignore Simulate `--strictPropertyInitialization=false`. @Input({transform: (v: unknown) => (v === null ? undefined : !!v)}) disabled: boolean; }
{ "end_byte": 303, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/transform_incompatible_types.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/nested_template_prop_access.ts_0_267
// tslint:disable import {Component, Input} from '@angular/core'; interface Config { bla?: string; } @Component({ template: ` <span [id]="config.bla"> Test </span> `, }) export class NestedTemplatePropAccess { @Input() config: Config = {}; }
{ "end_byte": 267, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/nested_template_prop_access.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/object_expansion.ts_0_362
// tslint:disable import {Component, Input} from '@angular/core'; @Component({}) export class ObjectExpansion { @Input() bla: string = ''; expansion() { const {bla} = this; bla.charAt(0); } deeperExpansion() { const { bla: {charAt}, } = this; charAt(0); } expansionAsParameter({bla} = this) { bla.charAt(0); } }
{ "end_byte": 362, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/object_expansion.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/different_instantiations_of_reference.ts_0_1086
// tslint:disable import {Input, Directive, Component} from '@angular/core'; // Material form field test case let nextUniqueId = 0; @Directive() export class MatHint { align: string = ''; @Input() id = `mat-hint-${nextUniqueId++}`; } @Component({ template: ``, }) export class MatFormFieldTest { private declare _hintChildren: MatHint[]; private _control = true; private _somethingElse = false; private _syncDescribedByIds() { if (this._control) { let ids: string[] = []; const startHint = this._hintChildren ? this._hintChildren.find((hint) => hint.align === 'start') : null; const endHint = this._hintChildren ? this._hintChildren.find((hint) => hint.align === 'end') : null; if (startHint) { ids.push(startHint.id); } else if (this._somethingElse) { ids.push(`val:${this._somethingElse}`); } if (endHint) { // Same input reference `MatHint#id`, but different instantiation! // Should not be shared!. ids.push(endHint.id); } } } }
{ "end_byte": 1086, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/different_instantiations_of_reference.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/BUILD.bazel_0_230
package( default_visibility = ["//packages/core/schematics/migrations/signal-migration/test:__pkg__"], ) filegroup( name = "test_files", srcs = glob( ["*"], exclude = ["BUILD.bazel"], ), )
{ "end_byte": 230, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/BUILD.bazel" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/optimize_test.ts_0_383
// tslint:disable import {AppComponent} from './index'; function assertValidLoadingInput(dir: AppComponent) { if (dir.withUndefinedInput && dir.narrowableMultipleTimes) { throw new Error(``); } const validInputs = ['auto', 'eager', 'lazy']; if (typeof dir.withUndefinedInput === 'string' && !validInputs.includes(dir.withUndefinedInput)) { throw new Error(); } }
{ "end_byte": 383, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/optimize_test.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/template.html_0_216
<span class="mat-mdc-optgroup-label" role="presentation"> <span class="mdc-list-item__primary-text">{{ input }} <ng-content></ng-content></span> </span> <ng-content select="mat-option, ng-container"></ng-content>
{ "end_byte": 216, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/template.html" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/narrowing.ts_0_669
// tslint:disable import {Input, Directive} from '@angular/core'; @Directive() export class Narrowing { @Input() name: string | undefined = undefined; narrowingArrowFn() { [this].map((x) => x.name && x.name.charAt(0)); } narrowingArrowFnMultiLineWrapped() { [this].map( (x) => x.name && x.name.includes( 'A super long string to ensure this is wrapped and we can test formatting.', ), ); } narrowingObjectExpansion() { [this].map(({name}) => name && name.charAt(0)); } narrowingNormalThenObjectExpansion() { if (this.name) { const {charAt} = this.name; charAt(0); } } }
{ "end_byte": 669, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/narrowing.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/cross_references.ts_0_317
// tslint:disable import {Component, Input} from '@angular/core'; @Component({ template: ` {{label}} `, }) class Group { @Input() label!: string; } @Component({ template: ` @if (true) { {{group.label}} } {{group.label}} `, }) class Option { constructor(public group: Group) {} }
{ "end_byte": 317, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/cross_references.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/index.ts_0_2600
// tslint:disable import {Component, Input} from '@angular/core'; interface Vehicle {} interface Car extends Vehicle { __car: true; } interface Audi extends Car { __audi: true; } @Component({ selector: 'app-component', templateUrl: './template.html', }) export class AppComponent { @Input() input: string | null = null; @Input({transform: disabledTransform, required: true}) bla: boolean = false; @Input() narrowableMultipleTimes: Vehicle | null = null; @Input() withUndefinedInput: string | undefined; @Input() incompatible: string | null = null; private _bla: any; @Input() set ngSwitch(newValue: any) { this._bla = newValue; if (newValue === 0) { console.log('test'); } } someControlFlowCase() { if (this.input) { this.input.charAt(0); } } moreComplexControlFlowCase() { if (!this.input) { return; } this.doSomething(); (() => { // might be a different input value now?! // No! it can't because we don't allow writes to "input"!!. console.log(this.input.substring(0)); })(); } doSomething() { this.incompatible = 'some other value'; } vsd() { if (!this.input && this.narrowableMultipleTimes !== null) { return this.narrowableMultipleTimes; } return this.input ? 'eager' : 'lazy'; } allTheSameNoNarrowing() { console.log(this.input); console.log(this.input); } test() { if (this.narrowableMultipleTimes) { console.log(); const x = () => { // @ts-expect-error if (isCar(this.narrowableMultipleTimes)) { } }; console.log(); console.log(); x(); x(); } } extremeNarrowingNested() { if (this.narrowableMultipleTimes && isCar(this.narrowableMultipleTimes)) { this.narrowableMultipleTimes.__car; let car = this.narrowableMultipleTimes; let ctx = this; function nestedFn() { if (isAudi(car)) { console.log(car.__audi); } if (!isCar(ctx.narrowableMultipleTimes!) || !isAudi(ctx.narrowableMultipleTimes)) { return; } ctx.narrowableMultipleTimes.__audi; } // iife (() => { if (isAudi(this.narrowableMultipleTimes)) { this.narrowableMultipleTimes.__audi; } })(); } } } function disabledTransform(bla: string | boolean): boolean { return true; } function isCar(v: Vehicle): v is Car { return true; } function isAudi(v: Car): v is Audi { return true; } const x: AppComponent = null!; x.incompatible = null;
{ "end_byte": 2600, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/index.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/writing_to_inputs.ts_0_328
// tslint:disable import {Input} from '@angular/core'; export class TestCmp { @Input() testParenthesisInput = false; @Input() notMutated = true; testParenthesis() { // prettier-ignore ((this.testParenthesisInput)) = true; } testNotMutated() { let fixture: boolean; fixture = this.notMutated; } }
{ "end_byte": 328, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/writing_to_inputs.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/required-no-explicit-type-extra.ts_0_137
// tslint:disable import {ComponentMirror} from '@angular/core'; export const COMPLEX_VAR = { x: null! as ComponentMirror<never>, };
{ "end_byte": 137, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/required-no-explicit-type-extra.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/jit_true_component_external_tmpl.html_0_9
{{test}}
{ "end_byte": 9, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/jit_true_component_external_tmpl.html" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/with_getters_reference.ts_0_249
// tslint:disable import {WithSettersAndGetters} from './with_getters'; class WithGettersExternalRef { instance: WithSettersAndGetters = null!; test() { if (this.instance.accessor) { console.log(this.instance.accessor); } } }
{ "end_byte": 249, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/with_getters_reference.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/identifier_collisions.ts_0_1030
/** * @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 */ // tslint:disable import {Component, Input} from '@angular/core'; const complex = 'some global variable'; @Component({template: ''}) class MyComp { @Input() name: string | null = null; @Input() complex: string | null = null; valid() { if (this.name) { this.name.charAt(0); } } // Input read cannot be stored in a variable: `name`. simpleLocalCollision() { const name = 'some other name'; if (this.name) { this.name.charAt(0); } } // `this.complex` should conflict with the file-level `complex` variable, // and result in a suffix variable. complexParentCollision() { if (this.complex) { this.complex.charAt(0); } } nestedShadowing() { if (this.name) { this.name.charAt(0); } function nested() { const name = ''; } } }
{ "end_byte": 1030, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/identifier_collisions.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/with_jsdoc.ts_0_189
// tslint:disable import {Input} from '@angular/core'; class WithJsdoc { /** * Works */ @Input() simpleInput!: string; @Input() withCommentInside?: /* intended */ boolean; }
{ "end_byte": 189, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/with_jsdoc.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/problematic_type_reference.ts_0_346
// tslint:disable import {Component, Directive, QueryList, Input} from '@angular/core'; @Component({ template: ` {{label}} `, }) class Group { @Input() label!: string; } @Directive() class Base { _items = new QueryList<{ label: string; }>(); } @Directive({}) class Option extends Base { _items = new QueryList<Group>(); }
{ "end_byte": 346, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/problematic_type_reference.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/index_spec.ts_0_873
// tslint:disable import {NgIf} from '@angular/common'; import {Component, input} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {AppComponent} from '.'; describe('bla', () => { it('should work', () => { @Component({ template: ` <app-component #ref /> {{ref.input.ok}} `, }) class TestCmp {} TestBed.configureTestingModule({ imports: [AppComponent], }); const fixture = TestBed.createComponent(TestCmp); fixture.detectChanges(); }); it('', () => { it('', () => { // Define `Ng2Component` @Component({ selector: 'ng2', standalone: true, template: '<div *ngIf="show()"><ng1A></ng1A> | <ng1B></ng1B></div>', imports: [NgIf], }) class Ng2Component { show = input<boolean>(false); } }); }); });
{ "end_byte": 873, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/index_spec.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/any_test.ts_0_852
// tslint:disable import {DebugElement, Input} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; function it(msg: string, fn: () => void) {} const harness = { query<T>(v: T): DebugElement { return null!; }, }; class SubDir { @Input() name = 'John'; @Input() name2 = ''; } class MyComp { @Input() hello = ''; } it('should work', () => { const fixture = TestBed.createComponent(MyComp); // `.componentInstance` is using `any` :O const sub = fixture.debugElement.query(By.directive(SubDir)).componentInstance; expect(sub.name).toBe('John'); }); it('should work2', () => { const fixture = TestBed.createComponent(MyComp); // `.componentInstance` is using `any` :O const sub = harness.query(SubDir).componentInstance; expect(sub.name2).toBe('John'); });
{ "end_byte": 852, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/any_test.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/scope_sharing.ts_0_312
// tslint:disable import {Input} from '@angular/core'; export class TestCmp { @Input() shared = false; bla() { if (TestCmp.arguments) { this.someFn(this.shared); } else { this.shared.valueOf(); } this.someFn(this.shared); } someFn(bla: boolean): asserts bla is true {} }
{ "end_byte": 312, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/scope_sharing.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/derived_class.ts_0_396
// tslint:disable import {Input, Directive} from '@angular/core'; @Directive() class Base { @Input() bla = true; } class Derived extends Base { override bla = false; } // overridden in separate file @Directive() export class Base2 { @Input() bla = true; } // overridden in separate file @Directive() export class Base3 { @Input() bla = true; click() { this.bla = false; } }
{ "end_byte": 396, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/derived_class.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/derived_class_separate_file.ts_0_256
// tslint:disable import {Input} from '@angular/core'; import {Base2, Base3} from './derived_class'; class DerivedExternal extends Base2 { override bla = false; } export class DerivedExternalWithInput extends Base3 { @Input() override bla = true; }
{ "end_byte": 256, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/derived_class_separate_file.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/getters.ts_0_379
// tslint:disable import {Directive, Input} from '@angular/core'; @Directive({}) export class WithGetters { @Input() get disabled() { return this._disabled; } set disabled(value: boolean | string) { this._disabled = typeof value === 'string' ? value === '' : !!value; } private _disabled: boolean = false; bla() { console.log(this._disabled); } }
{ "end_byte": 379, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/getters.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/loop_labels.ts_0_507
// tslint:disable import {Input} from '@angular/core'; class MyTestCmp { @Input({required: true}) someInput!: boolean | string; tmpValue = false; test() { for (let i = 0, cell = null; i < Number.MIN_SAFE_INTEGER; i++) { this.tmpValue = !!this.someInput; this.tmpValue = !this.someInput; } } test2() { while (isBla(this.someInput)) { this.tmpValue = this.someInput.includes('someText'); } } } function isBla(value: any): value is string { return true; }
{ "end_byte": 507, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/loop_labels.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/template_object_shorthand.ts_0_253
// tslint:disable import {Component, Input} from '@angular/core'; @Component({ template: ` <div [bla]="{myInput}"> </div> `, host: { '[style]': '{myInput}', }, }) export class TemplateObjectShorthand { @Input() myInput = true; }
{ "end_byte": 253, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/template_object_shorthand.ts" }
angular/packages/core/schematics/migrations/signal-migration/test/ts-versions/index.bzl_0_147
"""Exposes information about the tested TS versions.""" TS_VERSIONS = [ "typescript-5.5.4", "typescript-5.5.3", "typescript-5.5.2", ]
{ "end_byte": 147, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/ts-versions/index.bzl" }
angular/packages/core/schematics/migrations/signal-migration/test/ts-versions/yarn.lock_0_940
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "typescript-5.5.2@npm:typescript@5.5.2": version "5.5.2" resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.5.2.tgz#c26f023cb0054e657ce04f72583ea2d85f8d0507" integrity sha512-NcRtPEOsPFFWjobJEtfihkLCZCXZt/os3zf8nTxjVH3RvTSxjrCamJpbExGvYOF+tFHc3pA65qpdwPbzjohhew== "typescript-5.5.3@npm:typescript@5.5.3": version "5.5.3" resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.5.3.tgz#e1b0a3c394190838a0b168e771b0ad56a0af0faa" integrity sha512-/hreyEujaB0w76zKo6717l3L0o/qEUtRgdvUBvlkhoWeOVMjMuHNHk0BRBzikzuGDqNmPQbg5ifMEqsHLiIUcQ== "typescript-5.5.4@npm:typescript@5.5.4": version "5.5.4" resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.5.4.tgz#d9852d6c82bad2d2eda4fd74a5762a8f5909e9ba" integrity sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==
{ "end_byte": 940, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/ts-versions/yarn.lock" }
angular/packages/core/schematics/migrations/signal-migration/test/ts-versions/hooks.mjs_0_747
/** * @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 {runfiles} from '@bazel/runfiles'; const PACKAGE_PATH = runfiles.resolve(`npm_ts_versions/node_modules/${process.env.TS_VERSION_PACKAGE}`); /** * NodeJS hook that ensures TypeScript is imported from the configured * TS version package. This allows us to conveniently test against multiple * TS versions. */ export async function resolve(specifier, context, nextResolve) { if (specifier === 'typescript') { return nextResolve(`${PACKAGE_PATH}/lib/typescript.js`, context); } return nextResolve(specifier, context); }
{ "end_byte": 747, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/ts-versions/hooks.mjs" }
angular/packages/core/schematics/migrations/signal-migration/test/ts-versions/loader.mjs_0_329
/** * @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 {register} from 'node:module'; // Registers the TypeScript version loader. register('./hooks.mjs', import.meta.url);
{ "end_byte": 329, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/ts-versions/loader.mjs" }
angular/packages/core/schematics/migrations/signal-migration/test/ts-versions/BUILD.bazel_0_91
exports_files([ "package.json", "yarn.lock", "loader.mjs", "hooks.mjs", ])
{ "end_byte": 91, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/ts-versions/BUILD.bazel" }
angular/packages/core/schematics/migrations/signal-migration/src/phase_migrate.ts_0_2802
/** * @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 {AnalysisProgramInfo} from './analysis_deps'; import {KnownInputs} from './input_detection/known_inputs'; import {MigrationHost} from './migration_host'; import {pass6__migrateInputDeclarations} from './passes/6_migrate_input_declarations'; import {MigrationResult} from './result'; import {pass10_applyImportManager} from './passes/10_apply_import_manager'; import {ImportManager} from '@angular/compiler-cli/src/ngtsc/translator'; import {InputDescriptor} from './utils/input_id'; import {ReferenceMigrationHost} from './passes/reference_migration/reference_migration_host'; import {pass5__migrateTypeScriptReferences} from './passes/5_migrate_ts_references'; import {pass7__migrateTemplateReferences} from './passes/7_migrate_template_references'; import {pass8__migrateHostBindings} from './passes/8_migrate_host_bindings'; import {pass9__migrateTypeScriptTypeReferences} from './passes/9_migrate_ts_type_references'; /** * Executes the migration phase. * * This involves: * - migrating TS references. * - migrating `@Input()` declarations. * - migrating template references. * - migrating host binding references. */ export function executeMigrationPhase( host: MigrationHost, knownInputs: KnownInputs, result: MigrationResult, info: AnalysisProgramInfo, ) { const {typeChecker, sourceFiles} = info; const importManager = new ImportManager({ // For the purpose of this migration, we always use `input` and don't alias // it to e.g. `input_1`. generateUniqueIdentifier: () => null, }); const referenceMigrationHost: ReferenceMigrationHost<InputDescriptor> = { printer: result.printer, replacements: result.replacements, shouldMigrateReferencesToField: (inputDescr) => knownInputs.has(inputDescr) && knownInputs.get(inputDescr)!.isIncompatible() === false, shouldMigrateReferencesToClass: (clazz) => knownInputs.getDirectiveInfoForClass(clazz) !== undefined && knownInputs.getDirectiveInfoForClass(clazz)!.hasMigratedFields(), }; // Migrate passes. pass5__migrateTypeScriptReferences(referenceMigrationHost, result.references, typeChecker, info); pass6__migrateInputDeclarations(host, typeChecker, result, knownInputs, importManager, info); pass7__migrateTemplateReferences(referenceMigrationHost, result.references); pass8__migrateHostBindings(referenceMigrationHost, result.references, info); pass9__migrateTypeScriptTypeReferences( referenceMigrationHost, result.references, importManager, info, ); pass10_applyImportManager(importManager, result, sourceFiles, info); }
{ "end_byte": 2802, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/phase_migrate.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/phase_analysis.ts_0_4434
/** * @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 {isShim} from '@angular/compiler-cli/src/ngtsc/shims'; import {AnalysisProgramInfo} from './analysis_deps'; import {KnownInputs} from './input_detection/known_inputs'; import {MigrationHost} from './migration_host'; import {pass1__IdentifySourceFileAndDeclarationInputs} from './passes/1_identify_inputs'; import {pass3__checkIncompatiblePatterns} from './passes/3_check_incompatible_patterns'; import {pass2_IdentifySourceFileReferences} from './passes/2_find_source_file_references'; import {MigrationResult} from './result'; import {InheritanceGraph} from './utils/inheritance_graph'; import {GroupedTsAstVisitor} from './utils/grouped_ts_ast_visitor'; import { isHostBindingReference, isTemplateReference, isTsReference, } from './passes/reference_resolution/reference_kinds'; import {FieldIncompatibilityReason} from './passes/problematic_patterns/incompatibility'; /** * Executes the analysis phase of the migration. * * This includes: * - finding all inputs * - finding all references * - determining incompatible inputs * - checking inheritance */ export function executeAnalysisPhase( host: MigrationHost, knownInputs: KnownInputs, result: MigrationResult, { sourceFiles, fullProgramSourceFiles, reflector, dtsMetadataReader, typeChecker, templateTypeChecker, resourceLoader, evaluator, refEmitter, }: AnalysisProgramInfo, ) { // Pass 1 fullProgramSourceFiles.forEach( (sf) => // Shim shim files. Those are unnecessary and might cause unexpected slowness. // e.g. `ngtypecheck` files. !isShim(sf) && pass1__IdentifySourceFileAndDeclarationInputs( sf, host, typeChecker, reflector, dtsMetadataReader, evaluator, refEmitter, knownInputs, result, ), ); const fieldNamesToConsiderForReferenceLookup = new Set<string>(); for (const input of knownInputs.knownInputIds.values()) { if (host.config.shouldMigrateInput?.(input) === false) { continue; } fieldNamesToConsiderForReferenceLookup.add(input.descriptor.node.name.text); } // A graph starting with source files is sufficient. We will resolve into // declaration files if a source file depends on such. const inheritanceGraph = new InheritanceGraph(typeChecker).expensivePopulate(sourceFiles); const pass2And3SourceFileVisitor = new GroupedTsAstVisitor(sourceFiles); // Register pass 2. Find all source file references. pass2_IdentifySourceFileReferences( host.programInfo, typeChecker, reflector, resourceLoader, evaluator, templateTypeChecker, pass2And3SourceFileVisitor, knownInputs, result, fieldNamesToConsiderForReferenceLookup, ); // Register pass 3. Check incompatible patterns pass. pass3__checkIncompatiblePatterns( host, inheritanceGraph, typeChecker, pass2And3SourceFileVisitor, knownInputs, ); // Perform Pass 2 and Pass 3, efficiently in one pass. pass2And3SourceFileVisitor.execute(); // Determine incompatible inputs based on resolved references. for (const reference of result.references) { if (isTsReference(reference) && reference.from.isWrite) { knownInputs.markFieldIncompatible(reference.target, { reason: FieldIncompatibilityReason.WriteAssignment, context: reference.from.node, }); } if (isTemplateReference(reference) || isHostBindingReference(reference)) { if (reference.from.isWrite) { knownInputs.markFieldIncompatible(reference.target, { reason: FieldIncompatibilityReason.WriteAssignment, // No TS node context available for template or host bindings. context: null, }); } } // TODO: Remove this when we support signal narrowing in templates. // https://github.com/angular/angular/pull/55456. if (isTemplateReference(reference)) { if (reference.from.isLikelyPartOfNarrowing) { knownInputs.markFieldIncompatible(reference.target, { reason: FieldIncompatibilityReason.PotentiallyNarrowedInTemplateButNoSupportYet, context: null, }); } } } return {inheritanceGraph}; }
{ "end_byte": 4434, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/phase_analysis.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/migration.ts_0_1872
/** * @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 {AbsoluteFsPath, FileSystem} from '@angular/compiler-cli/src/ngtsc/file_system'; import {confirmAsSerializable, Serializable} from '../../../utils/tsurge/helpers/serializable'; import {BaseProgramInfo, ProgramInfo} from '../../../utils/tsurge/program_info'; import {TsurgeComplexMigration} from '../../../utils/tsurge/migration'; import {CompilationUnitData} from './batch/unit_data'; import {KnownInputs} from './input_detection/known_inputs'; import {AnalysisProgramInfo, prepareAnalysisInfo} from './analysis_deps'; import {MigrationResult} from './result'; import {MigrationHost} from './migration_host'; import {executeAnalysisPhase} from './phase_analysis'; import {pass4__checkInheritanceOfInputs} from './passes/4_check_inheritance'; import {getCompilationUnitMetadata} from './batch/extract'; import {convertToGlobalMeta, combineCompilationUnitData} from './batch/merge_unit_data'; import {Replacement} from '../../../utils/tsurge/replacement'; import {populateKnownInputsFromGlobalData} from './batch/populate_global_data'; import {executeMigrationPhase} from './phase_migrate'; import {filterIncompatibilitiesForBestEffortMode} from './best_effort_mode'; import assert from 'assert'; import { ClassIncompatibilityReason, FieldIncompatibilityReason, } from './passes/problematic_patterns/incompatibility'; import {MigrationConfig} from './migration_config'; import {ClassFieldUniqueKey} from './passes/reference_resolution/known_fields'; import {createNgtscProgram} from '../../../utils/tsurge/helpers/ngtsc_program'; /** * Tsurge migration for migrating Angular `@Input()` declarations to * signal inputs, with support for batch execution. */
{ "end_byte": 1872, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/migration.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/migration.ts_1873_10522
export class SignalInputMigration extends TsurgeComplexMigration< CompilationUnitData, CompilationUnitData > { upgradedAnalysisPhaseResults: { replacements: Replacement[]; projectRoot: AbsoluteFsPath; knownInputs: KnownInputs; } | null = null; constructor(private readonly config: MigrationConfig = {}) { super(); } // Override the default ngtsc program creation, to add extra flags. override createProgram(tsconfigAbsPath: string, fs?: FileSystem): BaseProgramInfo { return createNgtscProgram(tsconfigAbsPath, fs, { _compilePoisonedComponents: true, // We want to migrate non-exported classes too. compileNonExportedClasses: true, // Always generate as much TCB code as possible. // This allows us to check references in templates as much as possible. // Note that this may yield more diagnostics, but we are not collecting these anyway. strictTemplates: true, }); } override prepareProgram(baseInfo: BaseProgramInfo): ProgramInfo { const info = super.prepareProgram(baseInfo); // Optional filter for testing. Allows for simulation of parallel execution // even if some tsconfig's have overlap due to sharing of TS sources. // (this is commonly not the case in g3 where deps are `.d.ts` files). const limitToRootNamesOnly = process.env['LIMIT_TO_ROOT_NAMES_ONLY'] === '1'; const filteredSourceFiles = info.sourceFiles.filter( (f) => // Optional replacement filter. Allows parallel execution in case // some tsconfig's have overlap due to sharing of TS sources. // (this is commonly not the case in g3 where deps are `.d.ts` files). !limitToRootNamesOnly || info.programAbsoluteRootFileNames!.includes(f.fileName), ); return { ...info, sourceFiles: filteredSourceFiles, }; } // Extend the program info with the analysis information we need in every phase. prepareAnalysisDeps(info: ProgramInfo): AnalysisProgramInfo { assert(info.ngCompiler !== null, 'Expected `NgCompiler` to be configured.'); const analysisInfo = { ...info, ...prepareAnalysisInfo(info.program, info.ngCompiler, info.programAbsoluteRootFileNames), }; return analysisInfo; } override async analyze(info: ProgramInfo) { const analysisDeps = this.prepareAnalysisDeps(info); const knownInputs = new KnownInputs(info, this.config); const result = new MigrationResult(); const host = createMigrationHost(info, this.config); this.config.reportProgressFn?.(10, 'Analyzing project (input usages)..'); const {inheritanceGraph} = executeAnalysisPhase(host, knownInputs, result, analysisDeps); // Mark filtered inputs before checking inheritance. This ensures filtered // inputs properly influence e.g. inherited or derived inputs that now wouldn't // be safe either (BUT can still be skipped via best effort mode later). filterInputsViaConfig(result, knownInputs, this.config); // Analyze inheritance, track edges etc. and later propagate incompatibilities in // the merge stage. this.config.reportProgressFn?.(40, 'Checking inheritance..'); pass4__checkInheritanceOfInputs(inheritanceGraph, analysisDeps.metaRegistry, knownInputs); // Filter best effort incompatibilities, so that the new filtered ones can // be accordingly respected in the merge phase. if (this.config.bestEffortMode) { filterIncompatibilitiesForBestEffortMode(knownInputs); } const unitData = getCompilationUnitMetadata(knownInputs); // Non-batch mode! if (this.config.upgradeAnalysisPhaseToAvoidBatch) { const globalMeta = await this.globalMeta(unitData); const {replacements} = await this.migrate(globalMeta, info, { knownInputs, result, host, analysisDeps, }); this.config.reportProgressFn?.(100, 'Completed migration.'); // Expose the upgraded analysis stage results. this.upgradedAnalysisPhaseResults = { replacements, projectRoot: info.projectRoot, knownInputs, }; } return confirmAsSerializable(unitData); } override async combine( unitA: CompilationUnitData, unitB: CompilationUnitData, ): Promise<Serializable<CompilationUnitData>> { return confirmAsSerializable(combineCompilationUnitData(unitA, unitB)); } override async globalMeta( combinedData: CompilationUnitData, ): Promise<Serializable<CompilationUnitData>> { return confirmAsSerializable(convertToGlobalMeta(combinedData)); } override async migrate( globalMetadata: CompilationUnitData, info: ProgramInfo, nonBatchData?: { knownInputs: KnownInputs; result: MigrationResult; host: MigrationHost; analysisDeps: AnalysisProgramInfo; }, ) { const knownInputs = nonBatchData?.knownInputs ?? new KnownInputs(info, this.config); const result = nonBatchData?.result ?? new MigrationResult(); const host = nonBatchData?.host ?? createMigrationHost(info, this.config); const analysisDeps = nonBatchData?.analysisDeps ?? this.prepareAnalysisDeps(info); // Can't re-use analysis structures, so re-build them. if (nonBatchData === undefined) { executeAnalysisPhase(host, knownInputs, result, analysisDeps); } // Incorporate global metadata into known inputs. populateKnownInputsFromGlobalData(knownInputs, globalMetadata); if (this.config.bestEffortMode) { filterIncompatibilitiesForBestEffortMode(knownInputs); } this.config.reportProgressFn?.(60, 'Collecting migration changes..'); executeMigrationPhase(host, knownInputs, result, analysisDeps); return {replacements: result.replacements}; } override async stats(globalMetadata: CompilationUnitData) { let fullCompilationInputs = 0; let sourceInputs = 0; let incompatibleInputs = 0; const fieldIncompatibleCounts: Partial< Record<`input-field-incompatibility-${string}`, number> > = {}; const classIncompatibleCounts: Partial< Record<`input-owning-class-incompatibility-${string}`, number> > = {}; for (const [id, input] of Object.entries(globalMetadata.knownInputs)) { fullCompilationInputs++; const isConsideredSourceInput = input.seenAsSourceInput && input.memberIncompatibility !== FieldIncompatibilityReason.OutsideOfMigrationScope && input.memberIncompatibility !== FieldIncompatibilityReason.SkippedViaConfigFilter; // We won't track incompatibilities to inputs that aren't considered source inputs. // Tracking their statistics wouldn't provide any value. if (!isConsideredSourceInput) { continue; } sourceInputs++; if (input.memberIncompatibility !== null || input.owningClassIncompatibility !== null) { incompatibleInputs++; } if (input.memberIncompatibility !== null) { const reasonName = FieldIncompatibilityReason[input.memberIncompatibility]; const key = `input-field-incompatibility-${reasonName}` as const; fieldIncompatibleCounts[key] ??= 0; fieldIncompatibleCounts[key]++; } if (input.owningClassIncompatibility !== null) { const reasonName = ClassIncompatibilityReason[input.owningClassIncompatibility]; const key = `input-owning-class-incompatibility-${reasonName}` as const; classIncompatibleCounts[key] ??= 0; classIncompatibleCounts[key]++; } } return { counters: { fullCompilationInputs, sourceInputs, incompatibleInputs, ...fieldIncompatibleCounts, ...classIncompatibleCounts, }, }; } } /** * Updates the migration state to filter inputs based on a filter * method defined in the migration config. */ function filterInputsViaConfig( result: MigrationResult, knownInputs: KnownInputs, config: MigrationConfig, ) { if (config.shouldMigrateInput === undefined) { return; } const skippedInputs = new Set<ClassFieldUniqueKey>(); // Mark all skipped inputs as incompatible for migration. for (const input of knownInputs.knownInputIds.values()) { if (!config.shouldMigrateInput(input)) { skippedInputs.add(input.descriptor.key); knownInputs.markFieldIncompatible(input.descriptor, { context: null, reason: FieldIncompatibilityReason.SkippedViaConfigFilter, }); } } } function createMigrationHost(info: ProgramInfo, config: MigrationConfig): MigrationHost { return new MigrationHost(/* isMigratingCore */ false, info, config, info.sourceFiles); }
{ "end_byte": 10522, "start_byte": 1873, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/migration.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/cli.ts_0_1375
/** * @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 path from 'path'; import assert from 'assert'; import {SignalInputMigration} from './migration'; import {writeMigrationReplacements} from './write_replacements'; main( path.resolve(process.argv[2]), process.argv.includes('--best-effort-mode'), process.argv.includes('--insert-todos'), ).catch((e) => { console.error(e); process.exitCode = 1; }); /** * Runs the signal input migration for the given TypeScript project. */ export async function main( absoluteTsconfigPath: string, bestEffortMode: boolean, insertTodosForSkippedFields: boolean, ) { const migration = new SignalInputMigration({ bestEffortMode, insertTodosForSkippedFields, upgradeAnalysisPhaseToAvoidBatch: true, }); const baseInfo = migration.createProgram(absoluteTsconfigPath); const info = migration.prepareProgram(baseInfo); await migration.analyze(info); assert( migration.upgradedAnalysisPhaseResults, 'Expected upgraded analysis phase results; batch mode is disabled.', ); const {replacements, projectRoot} = migration.upgradedAnalysisPhaseResults; // Apply replacements writeMigrationReplacements(replacements, projectRoot); }
{ "end_byte": 1375, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/cli.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/write_replacements.ts_0_976
/** * @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 {applyTextUpdates, Replacement} from '../../../utils/tsurge/replacement'; import {groupReplacementsByFile} from '../../../utils/tsurge/helpers/group_replacements'; import {AbsoluteFsPath, getFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system'; /** Applies the migration result and applies it to the file system. */ export function writeMigrationReplacements( replacements: Replacement[], projectRoot: AbsoluteFsPath, ) { const fs = getFileSystem(); for (const [projectRelativePath, updates] of groupReplacementsByFile(replacements)) { const filePath = fs.join(projectRoot, projectRelativePath); const fileText = fs.readFile(filePath); const newText = applyTextUpdates(fileText, updates); fs.writeFile(filePath, newText); } }
{ "end_byte": 976, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/write_replacements.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/result.ts_0_1548
/** * @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 ts from 'typescript'; import {InputDescriptor} from './utils/input_id'; import {ConvertInputPreparation} from './convert-input/prepare_and_check'; import {Replacement} from '../../../utils/tsurge/replacement'; import {ReferenceResult} from './passes/reference_resolution/reference_result'; import {Reference} from './passes/reference_resolution/reference_kinds'; /** * State of the migration that is passed between * the individual phases. * * The state/phase captures information like: * - list of inputs that are defined in `.ts` and need migration. * - list of references. * - keeps track of computed replacements. * - imports that may need to be updated. */ export class MigrationResult implements ReferenceResult<InputDescriptor> { printer = ts.createPrinter({newLine: ts.NewLineKind.LineFeed}); // May be `null` if the input cannot be converted. This is also // signified by an incompatibility- but the input is tracked here as it // still is a "source input". sourceInputs = new Map<InputDescriptor, ConvertInputPreparation | null>(); references: Reference<InputDescriptor>[] = []; // Execution data replacements: Replacement[] = []; inputDecoratorSpecifiers = new Map< ts.SourceFile, {node: ts.ImportSpecifier; kind: 'signal-input-import' | 'decorator-input-import'}[] >(); }
{ "end_byte": 1548, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/result.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/migration_config.ts_0_2055
/** * @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 type {KnownInputInfo} from './input_detection/known_inputs'; export interface MigrationConfig { /** * Whether to migrate as much as possible, even if certain inputs would otherwise * be marked as incompatible for migration. */ bestEffortMode?: boolean; /** * Whether to insert TODOs for skipped fields, and reasons on why they * were skipped. */ insertTodosForSkippedFields?: boolean; /** * Whether the given input should be migrated. With batch execution, this * callback fires for foreign inputs from other compilation units too. * * Treating an input as non-migrated means that no references to it are * migrated, nor the actual declaration (if it's part of the sources). * * If no function is specified here, the migration will migrate all * inputs and references it discovers in compilation units. This is the * running assumption for batch mode and LSC mode where the migration * assumes all seen inputs (even those in `.d.ts`) are intended to be * migrated. */ shouldMigrateInput?: (input: KnownInputInfo) => boolean; /** * Whether to upgrade analysis phase to avoid batch execution. * * This is useful when not running against multiple compilation units. * The analysis phase will re-use the same program and information, without * re-analyzing in the `migrate` phase. * * Results will be available as {@link SignalInputMigration#upgradedAnalysisPhaseResults} * after executing the analyze stage. */ upgradeAnalysisPhaseToAvoidBatch?: boolean; /** * Optional function to receive updates on progress of the migration. Useful * for integration with the language service to give some kind of indication * what the migration is currently doing. */ reportProgressFn?: (percentage: number, updateMessage: string) => void; }
{ "end_byte": 2055, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/migration_config.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/migration_host.ts_0_1138
/** * @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 {NgCompilerOptions} from '@angular/compiler-cli/src/ngtsc/core/api'; import ts from 'typescript'; import {ProgramInfo} from '../../../utils/tsurge'; import {MigrationConfig} from './migration_config'; /** * A migration host is in practice a container object that * exposes commonly accessed contextual helpers throughout * the whole migration. */ export class MigrationHost { private _sourceFiles: WeakSet<ts.SourceFile>; compilerOptions: NgCompilerOptions; constructor( public isMigratingCore: boolean, public programInfo: ProgramInfo, public config: MigrationConfig, sourceFiles: readonly ts.SourceFile[], ) { this._sourceFiles = new WeakSet(sourceFiles); this.compilerOptions = programInfo.userOptions; } /** Whether the given file is a source file to be migrated. */ isSourceFileForCurrentMigration(file: ts.SourceFile): boolean { return this._sourceFiles.has(file); } }
{ "end_byte": 1138, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/migration_host.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/best_effort_mode.ts_0_879
/** * @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 {KnownInputs} from './input_detection/known_inputs'; import {nonIgnorableFieldIncompatibilities} from './passes/problematic_patterns/incompatibility'; /** Filters ignorable input incompatibilities when best effort mode is enabled. */ export function filterIncompatibilitiesForBestEffortMode(knownInputs: KnownInputs) { knownInputs.knownInputIds.forEach(({container: c}) => { // All class incompatibilities are "filterable" right now. c.incompatible = null; for (const [key, i] of c.memberIncompatibility.entries()) { if (!nonIgnorableFieldIncompatibilities.includes(i.reason)) { c.memberIncompatibility.delete(key); } } }); }
{ "end_byte": 879, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/best_effort_mode.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/BUILD.bazel_0_2363
load("//tools:defaults.bzl", "nodejs_binary", "ts_library") ts_library( name = "src", srcs = glob( ["**/*.ts"], exclude = ["test/**"], ), visibility = [ "//packages/core/schematics/migrations/output-migration:__pkg__", "//packages/core/schematics/migrations/signal-migration/test:__pkg__", "//packages/core/schematics/migrations/signal-queries-migration:__pkg__", "//packages/core/schematics/ng-generate/signal-input-migration:__pkg__", "//packages/language-service:__subpackages__", ], deps = [ "//packages/compiler", "//packages/compiler-cli", "//packages/compiler-cli/src/ngtsc/annotations", "//packages/compiler-cli/src/ngtsc/annotations/common", "//packages/compiler-cli/src/ngtsc/annotations/component", "//packages/compiler-cli/src/ngtsc/annotations/directive", "//packages/compiler-cli/src/ngtsc/core", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/incremental", "//packages/compiler-cli/src/ngtsc/metadata", "//packages/compiler-cli/src/ngtsc/partial_evaluator", "//packages/compiler-cli/src/ngtsc/program_driver", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/shims", "//packages/compiler-cli/src/ngtsc/transform", "//packages/compiler-cli/src/ngtsc/translator", "//packages/compiler-cli/src/ngtsc/typecheck", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/core/schematics/utils", "//packages/core/schematics/utils/tsurge", "//packages/core/schematics/utils/tsurge/helpers/ast", "@npm//@types/node", "@npm//magic-string", "@npm//typescript", ], ) nodejs_binary( name = "bin", data = [":src"], entry_point = ":cli.ts", visibility = ["//packages/core/schematics/migrations/signal-migration/test:__pkg__"], ) nodejs_binary( name = "batch_test_bin", data = [":src"], entry_point = ":batch/test_bin.ts", visibility = ["//packages/core/schematics/migrations/signal-migration/test:__pkg__"], )
{ "end_byte": 2363, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/BUILD.bazel" }
angular/packages/core/schematics/migrations/signal-migration/src/index.ts_0_1021
/** * @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 */ export {type KnownInputInfo, KnownInputs} from './input_detection/known_inputs'; export { type InputNameNode, type InputNode, isInputContainerNode, } from './input_detection/input_node'; export {type ClassFieldDescriptor} from './passes/reference_resolution/known_fields'; export {type InputDescriptor, getInputDescriptor, isInputDescriptor} from './utils/input_id'; export {SignalInputMigration} from './migration'; export {type MigrationConfig} from './migration_config'; export { type FieldIncompatibility, FieldIncompatibilityReason, ClassIncompatibilityReason, nonIgnorableFieldIncompatibilities, } from './passes/problematic_patterns/incompatibility'; export { getMessageForClassIncompatibility, getMessageForFieldIncompatibility, } from './passes/problematic_patterns/incompatibility_human';
{ "end_byte": 1021, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/index.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/analysis_deps.ts_0_3313
/** * @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 ts from 'typescript'; import {DtsMetadataReader, MetadataReader} from '@angular/compiler-cli/src/ngtsc/metadata'; import {PartialEvaluator} from '@angular/compiler-cli/src/ngtsc/partial_evaluator'; import {TypeScriptReflectionHost} from '@angular/compiler-cli/src/ngtsc/reflection'; import {ResourceLoader} from '@angular/compiler-cli/src/ngtsc/annotations'; import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core'; import {ReferenceEmitter} from '@angular/compiler-cli/src/ngtsc/imports'; import {TemplateTypeChecker} from '@angular/compiler-cli/src/ngtsc/typecheck/api'; import assert from 'assert'; import {ProgramInfo} from '../../../utils/tsurge/program_info'; /** * Interface containing the analysis information * for an Angular program to be migrated. */ export interface AnalysisProgramInfo extends ProgramInfo { reflector: TypeScriptReflectionHost; typeChecker: ts.TypeChecker; templateTypeChecker: TemplateTypeChecker; metaRegistry: MetadataReader; dtsMetadataReader: DtsMetadataReader; evaluator: PartialEvaluator; refEmitter: ReferenceEmitter; resourceLoader: ResourceLoader; } /** * Prepares migration analysis for the given program. * * Unlike {@link createAndPrepareAnalysisProgram} this does not create the program, * and can be used for integrations with e.g. the language service. */ export function prepareAnalysisInfo( userProgram: ts.Program, compiler: NgCompiler, programAbsoluteRootPaths?: string[], ) { // Analyze sync and retrieve necessary dependencies. // Note: `getTemplateTypeChecker` requires the `enableTemplateTypeChecker` flag, but // this has negative effects as it causes optional TCB operations to execute, which may // error with unsuccessful reference emits that previously were ignored outside of the migration. // The migration is resilient to TCB information missing, so this is fine, and all the information // we need is part of required TCB operations anyway. const {refEmitter, metaReader, templateTypeChecker} = compiler['ensureAnalyzed'](); // Generate all type check blocks. templateTypeChecker.generateAllTypeCheckBlocks(); const typeChecker = userProgram.getTypeChecker(); const reflector = new TypeScriptReflectionHost(typeChecker); const evaluator = new PartialEvaluator(reflector, typeChecker, null); const dtsMetadataReader = new DtsMetadataReader(typeChecker, reflector); const resourceLoader = compiler['resourceManager']; // Optional filter for testing. Allows for simulation of parallel execution // even if some tsconfig's have overlap due to sharing of TS sources. // (this is commonly not the case in g3 where deps are `.d.ts` files). const limitToRootNamesOnly = process.env['LIMIT_TO_ROOT_NAMES_ONLY'] === '1'; if (limitToRootNamesOnly) { assert( programAbsoluteRootPaths !== undefined, 'Expected absolute root paths when limiting to root names.', ); } return { metaRegistry: metaReader, dtsMetadataReader, evaluator, reflector, typeChecker, refEmitter, templateTypeChecker, resourceLoader, }; }
{ "end_byte": 3313, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/analysis_deps.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/10_apply_import_manager.ts_0_976
/** * @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 {ImportManager} from '@angular/compiler-cli/src/ngtsc/translator'; import ts from 'typescript'; import {applyImportManagerChanges} from '../../../../utils/tsurge/helpers/apply_import_manager'; import {MigrationResult} from '../result'; import {AbsoluteFsPath} from '@angular/compiler-cli/src/ngtsc/file_system'; import {ProgramInfo} from '../../../../utils/tsurge'; /** * Phase that applies all changes recorded by the import manager in * previous migrate phases. */ export function pass10_applyImportManager( importManager: ImportManager, result: MigrationResult, sourceFiles: readonly ts.SourceFile[], info: Pick<ProgramInfo, 'sortedRootDirs' | 'projectRoot'>, ) { applyImportManagerChanges(importManager, result.replacements, sourceFiles, info); }
{ "end_byte": 976, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/10_apply_import_manager.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/5_migrate_ts_references.ts_0_1101
/** * @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 ts from 'typescript'; import {migrateTypeScriptReferences} from './reference_migration/migrate_ts_references'; import {ProgramInfo} from '../../../../utils/tsurge'; import {Reference} from './reference_resolution/reference_kinds'; import {ClassFieldDescriptor} from './reference_resolution/known_fields'; import {ReferenceMigrationHost} from './reference_migration/reference_migration_host'; /** * Phase that migrates TypeScript input references to be signal compatible. * * The phase takes care of control flow analysis and generates temporary variables * where needed to ensure narrowing continues to work. E.g. */ export function pass5__migrateTypeScriptReferences<D extends ClassFieldDescriptor>( host: ReferenceMigrationHost<D>, references: Reference<D>[], checker: ts.TypeChecker, info: ProgramInfo, ) { migrateTypeScriptReferences(host, references, checker, info); }
{ "end_byte": 1101, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/5_migrate_ts_references.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/6_migrate_input_declarations.ts_0_2548
/** * @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 {ImportManager} from '@angular/compiler-cli/src/ngtsc/translator'; import assert from 'assert'; import ts from 'typescript'; import {ProgramInfo, projectFile, Replacement, TextUpdate} from '../../../../utils/tsurge'; import {convertToSignalInput} from '../convert-input/convert_to_signal'; import {KnownInputs} from '../input_detection/known_inputs'; import {MigrationHost} from '../migration_host'; import {MigrationResult} from '../result'; import {insertTodoForIncompatibility} from './problematic_patterns/incompatibility_todos'; /** * Phase that migrates `@Input()` declarations to signal inputs and * manages imports within the given file. */ export function pass6__migrateInputDeclarations( host: MigrationHost, checker: ts.TypeChecker, result: MigrationResult, knownInputs: KnownInputs, importManager: ImportManager, info: ProgramInfo, ) { let filesWithMigratedInputs = new Set<ts.SourceFile>(); let filesWithIncompatibleInputs = new WeakSet<ts.SourceFile>(); for (const [input, metadata] of result.sourceInputs) { const sf = input.node.getSourceFile(); const inputInfo = knownInputs.get(input)!; // Do not migrate incompatible inputs. if (inputInfo.isIncompatible()) { const incompatibilityReason = inputInfo.container.getInputMemberIncompatibility(input); // Add a TODO for the incompatible input, if desired. if (incompatibilityReason !== null && host.config.insertTodosForSkippedFields) { result.replacements.push( ...insertTodoForIncompatibility(input.node, info, incompatibilityReason, { single: 'input', plural: 'inputs', }), ); } filesWithIncompatibleInputs.add(sf); continue; } assert(metadata !== null, `Expected metadata to exist for input isn't marked incompatible.`); assert(!ts.isAccessor(input.node), 'Accessor inputs are incompatible.'); filesWithMigratedInputs.add(sf); result.replacements.push( ...convertToSignalInput(input.node, metadata, info, checker, importManager, result), ); } for (const file of filesWithMigratedInputs) { // All inputs were migrated, so we can safely remove the `Input` symbol. if (!filesWithIncompatibleInputs.has(file)) { importManager.removeImport(file, 'Input', '@angular/core'); } } }
{ "end_byte": 2548, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/6_migrate_input_declarations.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/7_migrate_template_references.ts_0_1851
/** * @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 {Replacement, TextUpdate} from '../../../../utils/tsurge'; import {ReferenceMigrationHost} from './reference_migration/reference_migration_host'; import {ClassFieldDescriptor} from './reference_resolution/known_fields'; import {isTemplateReference, Reference} from './reference_resolution/reference_kinds'; /** * Phase that migrates Angular template references to * unwrap signals. */ export function pass7__migrateTemplateReferences<D extends ClassFieldDescriptor>( host: ReferenceMigrationHost<D>, references: Reference<D>[], ) { const seenFileReferences = new Set<string>(); for (const reference of references) { // This pass only deals with HTML template references. if (!isTemplateReference(reference)) { continue; } // Skip references to incompatible inputs. if (!host.shouldMigrateReferencesToField(reference.target)) { continue; } // Skip duplicate references. E.g. if a template is shared. const fileReferenceId = `${reference.from.templateFile.id}:${reference.from.read.sourceSpan.end}`; if (seenFileReferences.has(fileReferenceId)) { continue; } seenFileReferences.add(fileReferenceId); // Expand shorthands like `{bla}` to `{bla: bla()}`. const appendText = reference.from.isObjectShorthandExpression ? `: ${reference.from.read.name}()` : `()`; host.replacements.push( new Replacement( reference.from.templateFile, new TextUpdate({ position: reference.from.read.sourceSpan.end, end: reference.from.read.sourceSpan.end, toInsert: appendText, }), ), ); } }
{ "end_byte": 1851, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/7_migrate_template_references.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/2_find_source_file_references.ts_0_1904
/** * @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 {ResourceLoader} from '@angular/compiler-cli/src/ngtsc/annotations'; import {PartialEvaluator} from '@angular/compiler-cli/src/ngtsc/partial_evaluator'; import {ReflectionHost} from '@angular/compiler-cli/src/ngtsc/reflection'; import {TemplateTypeChecker} from '@angular/compiler-cli/src/ngtsc/typecheck/api'; import ts from 'typescript'; import {KnownInputs} from '../input_detection/known_inputs'; import {MigrationResult} from '../result'; import {ProgramInfo} from '../../../../utils/tsurge'; import {GroupedTsAstVisitor} from '../utils/grouped_ts_ast_visitor'; import {createFindAllSourceFileReferencesVisitor} from './reference_resolution'; /** * Phase where problematic patterns are detected and advise * the migration to skip certain inputs. * * For example, detects classes that are instantiated manually. Those * cannot be migrated as `input()` requires an injection context. * * In addition, spying onto an input may be problematic- so we skip migrating * such. */ export function pass2_IdentifySourceFileReferences( programInfo: ProgramInfo, checker: ts.TypeChecker, reflector: ReflectionHost, resourceLoader: ResourceLoader, evaluator: PartialEvaluator, templateTypeChecker: TemplateTypeChecker, groupedTsAstVisitor: GroupedTsAstVisitor, knownInputs: KnownInputs, result: MigrationResult, fieldNamesToConsiderForReferenceLookup: Set<string> | null, ) { groupedTsAstVisitor.register( createFindAllSourceFileReferencesVisitor( programInfo, checker, reflector, resourceLoader, evaluator, templateTypeChecker, knownInputs, fieldNamesToConsiderForReferenceLookup, result, ).visitor, ); }
{ "end_byte": 1904, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/2_find_source_file_references.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/1_identify_inputs.ts_0_3627
/** * @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 assert from 'assert'; import ts from 'typescript'; import {ReferenceEmitter} from '@angular/compiler-cli/src/ngtsc/imports'; import {DtsMetadataReader} from '@angular/compiler-cli/src/ngtsc/metadata'; import {PartialEvaluator} from '@angular/compiler-cli/src/ngtsc/partial_evaluator'; import {TypeScriptReflectionHost} from '@angular/compiler-cli/src/ngtsc/reflection'; import {extractDecoratorInput} from '../input_detection/input_decorator'; import {isInputContainerNode} from '../input_detection/input_node'; import {KnownInputs} from '../input_detection/known_inputs'; import {MigrationHost} from '../migration_host'; import {MigrationResult} from '../result'; import {getInputDescriptor} from '../utils/input_id'; import {prepareAndCheckForConversion} from '../convert-input/prepare_and_check'; import {isFieldIncompatibility} from './problematic_patterns/incompatibility'; /** * Phase where we iterate through all source files of the program (including `.d.ts`) * and keep track of all `@Input`'s we discover. */ export function pass1__IdentifySourceFileAndDeclarationInputs( sf: ts.SourceFile, host: MigrationHost, checker: ts.TypeChecker, reflector: TypeScriptReflectionHost, dtsMetadataReader: DtsMetadataReader, evaluator: PartialEvaluator, refEmitter: ReferenceEmitter, knownDecoratorInputs: KnownInputs, result: MigrationResult, ) { const visitor = (node: ts.Node) => { const decoratorInput = extractDecoratorInput( node, host, reflector, dtsMetadataReader, evaluator, refEmitter, ); if (decoratorInput !== null) { assert(isInputContainerNode(node), 'Expected input to be declared on accessor or property.'); const inputDescr = getInputDescriptor(host, node); // track all inputs, even from declarations for reference resolution. knownDecoratorInputs.register({descriptor: inputDescr, metadata: decoratorInput, node}); // track source file inputs in the result of this target. // these are then later migrated in the migration phase. if (decoratorInput.inSourceFile && host.isSourceFileForCurrentMigration(sf)) { const conversionPreparation = prepareAndCheckForConversion( node, decoratorInput, checker, host.compilerOptions, ); if (isFieldIncompatibility(conversionPreparation)) { knownDecoratorInputs.markFieldIncompatible(inputDescr, conversionPreparation); result.sourceInputs.set(inputDescr, null); } else { result.sourceInputs.set(inputDescr, conversionPreparation); } } } // track all imports to `Input` or `input`. let importName: string | null = null; if ( ts.isImportSpecifier(node) && ((importName = (node.propertyName ?? node.name).text) === 'Input' || importName === 'input') && ts.isStringLiteral(node.parent.parent.parent.moduleSpecifier) && (host.isMigratingCore || node.parent.parent.parent.moduleSpecifier.text === '@angular/core') ) { if (!result.inputDecoratorSpecifiers.has(sf)) { result.inputDecoratorSpecifiers.set(sf, []); } result.inputDecoratorSpecifiers.get(sf)!.push({ kind: importName === 'input' ? 'signal-input-import' : 'decorator-input-import', node, }); } ts.forEachChild(node, visitor); }; ts.forEachChild(sf, visitor); }
{ "end_byte": 3627, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/1_identify_inputs.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/3_check_incompatible_patterns.ts_0_1900
/** * @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 ts from 'typescript'; import {KnownInputs} from '../input_detection/known_inputs'; import {MigrationHost} from '../migration_host'; import {GroupedTsAstVisitor} from '../utils/grouped_ts_ast_visitor'; import {InheritanceGraph} from '../utils/inheritance_graph'; import {checkIncompatiblePatterns} from './problematic_patterns/common_incompatible_patterns'; import {getAngularDecorators} from '@angular/compiler-cli/src/ngtsc/annotations'; import {FieldIncompatibilityReason} from './problematic_patterns/incompatibility'; /** * Phase where problematic patterns are detected and advise * the migration to skip certain inputs. * * For example, detects classes that are instantiated manually. Those * cannot be migrated as `input()` requires an injection context. * * In addition, spying onto an input may be problematic- so we skip migrating * such. */ export function pass3__checkIncompatiblePatterns( host: MigrationHost, inheritanceGraph: InheritanceGraph, checker: ts.TypeChecker, groupedTsAstVisitor: GroupedTsAstVisitor, knownInputs: KnownInputs, ) { checkIncompatiblePatterns(inheritanceGraph, checker, groupedTsAstVisitor, knownInputs, () => knownInputs.getAllInputContainingClasses(), ); for (const input of knownInputs.knownInputIds.values()) { const hostBindingDecorators = getAngularDecorators( input.metadata.fieldDecorators, ['HostBinding'], host.isMigratingCore, ); if (hostBindingDecorators.length > 0) { knownInputs.markFieldIncompatible(input.descriptor, { context: hostBindingDecorators[0].node, reason: FieldIncompatibilityReason.SignalIncompatibleWithHostBinding, }); } } }
{ "end_byte": 1900, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/3_check_incompatible_patterns.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/8_migrate_host_bindings.ts_0_2150
/** * @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 ts from 'typescript'; import {ReferenceMigrationHost} from './reference_migration/reference_migration_host'; import {ClassFieldDescriptor} from './reference_resolution/known_fields'; import {isHostBindingReference, Reference} from './reference_resolution/reference_kinds'; import {ProgramInfo, projectFile, Replacement, TextUpdate} from '../../../../utils/tsurge'; /** * Phase that migrates Angular host binding references to * unwrap signals. */ export function pass8__migrateHostBindings<D extends ClassFieldDescriptor>( host: ReferenceMigrationHost<D>, references: Reference<D>[], info: ProgramInfo, ) { const seenReferences = new WeakMap<ts.Node, Set<number>>(); for (const reference of references) { // This pass only deals with host binding references. if (!isHostBindingReference(reference)) { continue; } // Skip references to incompatible inputs. if (!host.shouldMigrateReferencesToField(reference.target)) { continue; } const bindingField = reference.from.hostPropertyNode; const expressionOffset = bindingField.getStart() + 1; // account for quotes. const readEndPos = expressionOffset + reference.from.read.sourceSpan.end; // Skip duplicate references. Can happen if the host object is shared. if (seenReferences.get(bindingField)?.has(readEndPos)) { continue; } if (seenReferences.has(bindingField)) { seenReferences.get(bindingField)!.add(readEndPos); } else { seenReferences.set(bindingField, new Set([readEndPos])); } // Expand shorthands like `{bla}` to `{bla: bla()}`. const appendText = reference.from.isObjectShorthandExpression ? `: ${reference.from.read.name}()` : `()`; host.replacements.push( new Replacement( projectFile(bindingField.getSourceFile(), info), new TextUpdate({position: readEndPos, end: readEndPos, toInsert: appendText}), ), ); } }
{ "end_byte": 2150, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/8_migrate_host_bindings.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/4_check_inheritance.ts_0_1673
/** * @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 {MetadataReader} from '@angular/compiler-cli/src/ngtsc/metadata'; import assert from 'assert'; import {KnownInputs} from '../input_detection/known_inputs'; import {InheritanceGraph} from '../utils/inheritance_graph'; import {checkInheritanceOfKnownFields} from './problematic_patterns/check_inheritance'; /** * Phase that propagates incompatibilities to derived classes or * base classes. For example, consider: * * ``` * class Base { * bla = true; * } * * class Derived extends Base { * @Input() bla = false; * } * ``` * * Whenever we migrate `Derived`, the inheritance would fail * and result in a build breakage because `Base#bla` is not an Angular input. * * The logic here detects such cases and marks `bla` as incompatible. If `Derived` * would then have other derived classes as well, it would propagate the status. */ export function pass4__checkInheritanceOfInputs( inheritanceGraph: InheritanceGraph, metaRegistry: MetadataReader, knownInputs: KnownInputs, ) { checkInheritanceOfKnownFields(inheritanceGraph, metaRegistry, knownInputs, { isClassWithKnownFields: (clazz) => knownInputs.isInputContainingClass(clazz), getFieldsForClass: (clazz) => { const directiveInfo = knownInputs.getDirectiveInfoForClass(clazz); assert(directiveInfo !== undefined, 'Expected directive info to exist for input.'); return Array.from(directiveInfo.inputFields.values()).map((i) => i.descriptor); }, }); }
{ "end_byte": 1673, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/4_check_inheritance.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/9_migrate_ts_type_references.ts_0_1117
/** * @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 {ImportManager} from '@angular/compiler-cli/src/ngtsc/translator'; import {ProgramInfo} from '../../../../utils/tsurge'; import {migrateTypeScriptTypeReferences} from './reference_migration/migrate_ts_type_references'; import {ReferenceMigrationHost} from './reference_migration/reference_migration_host'; import {ClassFieldDescriptor} from './reference_resolution/known_fields'; import {Reference} from './reference_resolution/reference_kinds'; /** * Migrates TypeScript "ts.Type" references. E.g. * - `Partial<MyComp>` will be converted to `UnwrapSignalInputs<Partial<MyComp>>`. in Catalyst test files. */ export function pass9__migrateTypeScriptTypeReferences<D extends ClassFieldDescriptor>( host: ReferenceMigrationHost<D>, references: Reference<D>[], importManager: ImportManager, info: ProgramInfo, ) { migrateTypeScriptTypeReferences(host, references, importManager, info); }
{ "end_byte": 1117, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/9_migrate_ts_type_references.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/problematic_patterns/common_incompatible_patterns.ts_0_4925
/** * @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 {unwrapExpression} from '@angular/compiler-cli/src/ngtsc/annotations/common'; import assert from 'assert'; import ts from 'typescript'; import {ClassIncompatibilityReason} from './incompatibility'; import {SpyOnFieldPattern} from '../../pattern_advisors/spy_on_pattern'; import {getMemberName} from '../../utils/class_member_names'; import {GroupedTsAstVisitor} from '../../utils/grouped_ts_ast_visitor'; import {InheritanceGraph} from '../../utils/inheritance_graph'; import {ClassFieldDescriptor, KnownFields} from '../reference_resolution/known_fields'; import {ProblematicFieldRegistry} from './problematic_field_registry'; /** * Phase where problematic patterns are detected and advise * the migration to skip certain inputs. * * For example, detects classes that are instantiated manually. Those * cannot be migrated as `input()` requires an injection context. * * In addition, spying onto an input may be problematic- so we skip migrating * such. */ export function checkIncompatiblePatterns<D extends ClassFieldDescriptor>( inheritanceGraph: InheritanceGraph, checker: ts.TypeChecker, groupedTsAstVisitor: GroupedTsAstVisitor, fields: KnownFields<D> & ProblematicFieldRegistry<D>, getAllClassesWithKnownFields: () => ts.ClassDeclaration[], ) { const inputClassSymbolsToClass = new Map<ts.Symbol, ts.ClassDeclaration>(); for (const knownFieldClass of getAllClassesWithKnownFields()) { const classSymbol = checker.getTypeAtLocation(knownFieldClass).symbol; assert( classSymbol != null, 'Expected a symbol to exist for the container of known field class.', ); assert( classSymbol.valueDeclaration !== undefined, 'Expected declaration to exist for known field class.', ); assert( ts.isClassDeclaration(classSymbol.valueDeclaration), 'Expected declaration to be a class.', ); // track class symbol for derived class checks. inputClassSymbolsToClass.set(classSymbol, classSymbol.valueDeclaration); } const spyOnPattern = new SpyOnFieldPattern(checker, fields); const visitor = (node: ts.Node) => { // Check for manual class instantiations. if (ts.isNewExpression(node) && ts.isIdentifier(unwrapExpression(node.expression))) { let newTarget = checker.getSymbolAtLocation(unwrapExpression(node.expression)); // Plain identifier references can point to alias symbols (e.g. imports). if (newTarget !== undefined && newTarget.flags & ts.SymbolFlags.Alias) { newTarget = checker.getAliasedSymbol(newTarget); } if (newTarget && inputClassSymbolsToClass.has(newTarget)) { fields.markClassIncompatible( inputClassSymbolsToClass.get(newTarget)!, ClassIncompatibilityReason.ClassManuallyInstantiated, ); } } // Detect `spyOn` problematic usages and record them. spyOnPattern.detect(node); const insidePropertyDeclaration = groupedTsAstVisitor.state.insidePropertyDeclaration; // Check for problematic class references inside property declarations. // These are likely problematic, causing type conflicts, if the containing // class inherits a non-input member with the same name. // Suddenly the derived class changes its signature, but the base class may not. problematicReferencesCheck: if ( insidePropertyDeclaration !== null && ts.isIdentifier(node) && insidePropertyDeclaration.parent.heritageClauses !== undefined ) { let newTarget = checker.getSymbolAtLocation(unwrapExpression(node)); // Plain identifier references can point to alias symbols (e.g. imports). if (newTarget !== undefined && newTarget.flags & ts.SymbolFlags.Alias) { newTarget = checker.getAliasedSymbol(newTarget); } if (newTarget && inputClassSymbolsToClass.has(newTarget)) { const memberName = getMemberName(insidePropertyDeclaration); if (memberName === null) { break problematicReferencesCheck; } const {derivedMembers, inherited} = inheritanceGraph.checkOverlappingMembers( insidePropertyDeclaration.parent, insidePropertyDeclaration, memberName, ); // Member is not inherited, or derived. // Hence the reference is unproblematic and is expected to not // cause any type conflicts. if (derivedMembers.length === 0 && inherited === undefined) { break problematicReferencesCheck; } fields.markClassIncompatible( inputClassSymbolsToClass.get(newTarget)!, ClassIncompatibilityReason.OwningClassReferencedInClassProperty, ); } } }; groupedTsAstVisitor.register(visitor); }
{ "end_byte": 4925, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/problematic_patterns/common_incompatible_patterns.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/problematic_patterns/problematic_field_registry.ts_0_1187
/** * @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 ts from 'typescript'; import {ClassFieldDescriptor} from '../reference_resolution/known_fields'; import {ClassIncompatibilityReason, FieldIncompatibility} from './incompatibility'; /** * Interface describing a registry for identifying and checking * of problematic fields that cannot be migrated due to given * incompatibility reasons. * * This is useful for sharing the input incompatibility logic for e.g. * inheritance or common patterns across migrations, like with the queries * migration. * * Notably, the incompatibility reasons at this point are still tied to the * "input" name. This is acceptable to simplify the mental complexity of parsing * all related code. */ export interface ProblematicFieldRegistry<D extends ClassFieldDescriptor> { isFieldIncompatible(descriptor: D): boolean; markFieldIncompatible(field: D, info: FieldIncompatibility): void; markClassIncompatible(node: ts.ClassDeclaration, reason: ClassIncompatibilityReason): void; }
{ "end_byte": 1187, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/problematic_patterns/problematic_field_registry.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/problematic_patterns/incompatibility.ts_0_2913
/** * @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 ts from 'typescript'; /** * Reasons why a field cannot be migrated. * * Higher values of incompatibility reasons indicate a more significant * incompatibility reason. Lower ones may be overridden by higher ones. * */ export enum FieldIncompatibilityReason { OverriddenByDerivedClass = 1, RedeclaredViaDerivedClassInputsArray = 2, TypeConflictWithBaseClass = 3, ParentIsIncompatible = 4, DerivedIsIncompatible = 5, SpyOnThatOverwritesField = 6, PotentiallyNarrowedInTemplateButNoSupportYet = 7, SignalIncompatibleWithHostBinding = 8, SignalInput__RequiredButNoGoodExplicitTypeExtractable = 9, SignalInput__QuestionMarkButNoGoodExplicitTypeExtractable = 10, SignalQueries__QueryListProblematicFieldAccessed = 11, SignalQueries__IncompatibleMultiUnionType = 12, WriteAssignment = 13, Accessor = 14, OutsideOfMigrationScope = 15, SkippedViaConfigFilter = 16, } /** Field reasons that cannot be ignored. */ export const nonIgnorableFieldIncompatibilities: FieldIncompatibilityReason[] = [ // Outside of scope fields should not be migrated. E.g. references to inputs in `node_modules/`. FieldIncompatibilityReason.OutsideOfMigrationScope, // Explicitly filtered fields cannot be skipped via best effort mode. FieldIncompatibilityReason.SkippedViaConfigFilter, // There is no good output for accessor fields. FieldIncompatibilityReason.Accessor, // There is no good output for such inputs. We can't perform "conversion". FieldIncompatibilityReason.SignalInput__RequiredButNoGoodExplicitTypeExtractable, FieldIncompatibilityReason.SignalInput__QuestionMarkButNoGoodExplicitTypeExtractable, ]; /** Reasons why a whole class and its fields cannot be migrated. */ export enum ClassIncompatibilityReason { ClassManuallyInstantiated, OwningClassReferencedInClassProperty, } /** Description of a field incompatibility and some helpful debug context. */ export interface FieldIncompatibility { reason: FieldIncompatibilityReason; context: ts.Node | null; } /** Whether the given value refers to an field incompatibility. */ export function isFieldIncompatibility(value: unknown): value is FieldIncompatibility { return ( (value as Partial<FieldIncompatibility>).reason !== undefined && (value as Partial<FieldIncompatibility>).context !== undefined && FieldIncompatibilityReason.hasOwnProperty((value as Partial<FieldIncompatibility>).reason!) ); } /** Picks the more significant field compatibility. */ export function pickFieldIncompatibility( a: FieldIncompatibility, b: FieldIncompatibility | null, ): FieldIncompatibility { if (b === null) { return a; } if (a.reason < b.reason) { return b; } return a; }
{ "end_byte": 2913, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/problematic_patterns/incompatibility.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/problematic_patterns/incompatibility_todos.ts_0_1974
/** * @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 {ProgramInfo, Replacement} from '../../../../../utils/tsurge'; import { getMessageForClassIncompatibility, getMessageForFieldIncompatibility, } from './incompatibility_human'; import {insertPrecedingLine} from '../../../../../utils/tsurge/helpers/ast/insert_preceding_line'; import {cutStringToLineLimit} from '../../../../../utils/tsurge/helpers/string_manipulation/cut_string_line_length'; import { ClassIncompatibilityReason, FieldIncompatibility, FieldIncompatibilityReason, isFieldIncompatibility, } from './incompatibility'; import ts from 'typescript'; /** * Inserts a TODO for the incompatibility blocking the given node * from being migrated. */ export function insertTodoForIncompatibility( node: ts.ClassElement, programInfo: ProgramInfo, incompatibility: FieldIncompatibility | ClassIncompatibilityReason, fieldName: {single: string; plural: string}, ): Replacement[] { // If a field is skipped via config filter or outside migration scope, do not // insert TODOs, as this could results in lots of unnecessary comments. if ( isFieldIncompatibility(incompatibility) && (incompatibility.reason === FieldIncompatibilityReason.SkippedViaConfigFilter || incompatibility.reason === FieldIncompatibilityReason.OutsideOfMigrationScope) ) { return []; } const message = isFieldIncompatibility(incompatibility) ? getMessageForFieldIncompatibility(incompatibility.reason, fieldName).short : getMessageForClassIncompatibility(incompatibility, fieldName).short; const lines = cutStringToLineLimit(message, 70); return [ insertPrecedingLine(node, programInfo, `// TODO: Skipped for migration because:`), ...lines.map((line) => insertPrecedingLine(node, programInfo, `// ${line}`)), ]; }
{ "end_byte": 1974, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/problematic_patterns/incompatibility_todos.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/problematic_patterns/incompatibility_human.ts_0_7018
/** * @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 {ClassIncompatibilityReason, FieldIncompatibilityReason} from './incompatibility'; /** * Gets human-readable message information for the given field incompatibility. * This text will be used by the language service, or CLI-based migration. */ export function getMessageForFieldIncompatibility( reason: FieldIncompatibilityReason, fieldName: {single: string; plural: string}, ): { short: string; extra: string; } { switch (reason) { case FieldIncompatibilityReason.Accessor: return { short: `Accessor ${fieldName.plural} cannot be migrated as they are too complex.`, extra: 'The migration potentially requires usage of `effect` or `computed`, but ' + 'the intent is unclear. The migration cannot safely migrate.', }; case FieldIncompatibilityReason.OverriddenByDerivedClass: return { short: `The ${fieldName.single} cannot be migrated because the field is overridden by a subclass.`, extra: 'The field in the subclass is not a signal, so migrating would break your build.', }; case FieldIncompatibilityReason.ParentIsIncompatible: return { short: `This ${fieldName.single} is inherited from a superclass, but the parent cannot be migrated.`, extra: 'Migrating this field would cause your build to fail.', }; case FieldIncompatibilityReason.DerivedIsIncompatible: return { short: `This ${fieldName.single} cannot be migrated because the field is overridden by a subclass.`, extra: 'The field in the subclass is incompatible for migration, so migrating this field would ' + 'break your build.', }; case FieldIncompatibilityReason.SignalIncompatibleWithHostBinding: return { short: `This ${fieldName.single} is used in combination with \`@HostBinding\` and ` + `migrating would break.`, extra: `\`@HostBinding\` does not invoke the signal automatically and your code would. ` + `break after migration. Use \`host\` of \`@Directive\`/\`@Component\`for host bindings.`, }; case FieldIncompatibilityReason.PotentiallyNarrowedInTemplateButNoSupportYet: return { short: `This ${fieldName.single} is used in a control flow expression (e.g. \`@if\` or \`*ngIf\`) and ` + 'migrating would break narrowing currently.', extra: `In the future, Angular intends to support narrowing of signals.`, }; case FieldIncompatibilityReason.RedeclaredViaDerivedClassInputsArray: return { short: `The ${fieldName.single} is overridden by a subclass that cannot be migrated.`, extra: `The subclass overrides this ${fieldName.single} via the \`inputs\` array in @Directive/@Component. ` + 'Migrating the field would break your build because the subclass field cannot be a signal.', }; case FieldIncompatibilityReason.SignalInput__RequiredButNoGoodExplicitTypeExtractable: return { short: `Input is required, but the migration cannot determine a good type for the input.`, extra: 'Consider adding an explicit type to make the migration possible.', }; case FieldIncompatibilityReason.SignalInput__QuestionMarkButNoGoodExplicitTypeExtractable: return { short: `Input is marked with a question mark. Migration could not determine a good type for the input.`, extra: 'The migration needs to be able to resolve a type, so that it can include `undefined` in your type. ' + 'Consider adding an explicit type to make the migration possible.', }; case FieldIncompatibilityReason.SignalQueries__QueryListProblematicFieldAccessed: return { short: `There are references to this query that cannot be migrated automatically.`, extra: "For example, it's not possible to migrate `.changes` or `.dirty` trivially.", }; case FieldIncompatibilityReason.SignalQueries__IncompatibleMultiUnionType: return { short: `Query type is too complex to automatically migrate.`, extra: "The new query API doesn't allow us to migrate safely without breaking your app.", }; case FieldIncompatibilityReason.SkippedViaConfigFilter: return { short: `This ${fieldName.single} is not part of the current migration scope.`, extra: 'Skipped via migration config.', }; case FieldIncompatibilityReason.SpyOnThatOverwritesField: return { short: 'A jasmine `spyOn` call spies on this field. This breaks with signals.', extra: `Migration cannot safely migrate as "spyOn" writes to the ${fieldName.single}. ` + `Signal ${fieldName.plural} are readonly.`, }; case FieldIncompatibilityReason.TypeConflictWithBaseClass: return { short: `This ${fieldName.single} overrides a field from a superclass, while the superclass ` + `field is not migrated.`, extra: 'Migrating the field would break your build because of a type conflict.', }; case FieldIncompatibilityReason.WriteAssignment: return { short: `Your application code writes to the ${fieldName.single}. This prevents migration.`, extra: `Signal ${fieldName.plural} are readonly, so migrating would break your build.`, }; case FieldIncompatibilityReason.OutsideOfMigrationScope: return { short: `This ${fieldName.single} is not part of any source files in your project.`, extra: `The migration excludes ${fieldName.plural} if no source file declaring them was seen.`, }; } } /** * Gets human-readable message information for the given class incompatibility. * This text will be used by the language service, or CLI-based migration. */ export function getMessageForClassIncompatibility( reason: ClassIncompatibilityReason, fieldName: {single: string; plural: string}, ): { short: string; extra: string; } { switch (reason) { case ClassIncompatibilityReason.OwningClassReferencedInClassProperty: return { short: `Class of this ${fieldName.single} is referenced in the signature of another class.`, extra: 'The other class is likely typed to expect a non-migrated field, so ' + 'migration is skipped to not break your build.', }; case ClassIncompatibilityReason.ClassManuallyInstantiated: return { short: `Class of this ${fieldName.single} is manually instantiated. ` + 'This is discouraged and prevents migration', extra: `Signal ${fieldName.plural} require a DI injection context. Manually instantiating ` + 'breaks this requirement in some cases, so the migration is skipped.', }; } }
{ "end_byte": 7018, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/problematic_patterns/incompatibility_human.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/problematic_patterns/check_inheritance.ts_0_5260
/** * @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 {Reference} from '@angular/compiler-cli/src/ngtsc/imports'; import {MetadataReader} from '@angular/compiler-cli/src/ngtsc/metadata'; import {ClassDeclaration} from '@angular/compiler-cli/src/ngtsc/reflection'; import assert from 'assert'; import ts from 'typescript'; import {getMemberName} from '../../utils/class_member_names'; import {InheritanceGraph} from '../../utils/inheritance_graph'; import {ClassFieldDescriptor, KnownFields} from '../reference_resolution/known_fields'; export interface InheritanceTracker<D extends ClassFieldDescriptor> { captureKnownFieldInheritanceRelationship(derived: D, parent: D): void; captureUnknownDerivedField(field: D): void; captureUnknownParentField(field: D): void; } /** * Phase that propagates incompatibilities to derived classes or * base classes. For example, consider: * * ``` * class Base { * bla = true; * } * * class Derived extends Base { * @Input() bla = false; * } * ``` * * Whenever we migrate `Derived`, the inheritance would fail * and result in a build breakage because `Base#bla` is not an Angular input. * * The logic here detects such cases and marks `bla` as incompatible. If `Derived` * would then have other derived classes as well, it would propagate the status. */ export function checkInheritanceOfKnownFields<D extends ClassFieldDescriptor>( inheritanceGraph: InheritanceGraph, metaRegistry: MetadataReader, fields: KnownFields<D> & InheritanceTracker<D>, opts: { getFieldsForClass: (node: ts.ClassDeclaration) => D[]; isClassWithKnownFields: (node: ts.ClassDeclaration) => boolean; }, ) { const allInputClasses = Array.from(inheritanceGraph.allClassesInInheritance).filter( (t) => ts.isClassDeclaration(t) && opts.isClassWithKnownFields(t), ); for (const inputClass of allInputClasses) { // Note: Class parents of `inputClass` were already checked by // the previous iterations (given the reverse topological sort)— // hence it's safe to assume that incompatibility of parent classes will // not change again, at a later time. assert(ts.isClassDeclaration(inputClass), 'Expected input graph node to be always a class.'); const classFields = opts.getFieldsForClass(inputClass); // Iterate through derived class chains and determine all inputs that are overridden // via class metadata fields. e.g `@Component#inputs`. This is later used to mark a // potential similar class input as incompatible— because those cannot be migrated. const inputFieldNamesFromMetadataArray = new Set<string>(); for (const derivedClasses of inheritanceGraph.traceDerivedClasses(inputClass)) { const derivedMeta = ts.isClassDeclaration(derivedClasses) && derivedClasses.name !== undefined ? metaRegistry.getDirectiveMetadata(new Reference(derivedClasses as ClassDeclaration)) : null; if (derivedMeta !== null && derivedMeta.inputFieldNamesFromMetadataArray !== null) { derivedMeta.inputFieldNamesFromMetadataArray.forEach((b) => inputFieldNamesFromMetadataArray.add(b), ); } } // Check inheritance of every input in the given "directive class". inputCheck: for (const fieldDescr of classFields) { const inputNode = fieldDescr.node; const {derivedMembers, inherited} = inheritanceGraph.checkOverlappingMembers( inputClass, inputNode, getMemberName(inputNode)!, ); // If we discover a derived, input re-declared via class metadata, then it // will cause conflicts as we cannot migrate it/ nor mark it as signal-based. if ( fieldDescr.node.name !== undefined && (ts.isIdentifier(fieldDescr.node.name) || ts.isStringLiteralLike(fieldDescr.node.name)) && inputFieldNamesFromMetadataArray.has(fieldDescr.node.name.text) ) { fields.captureUnknownDerivedField(fieldDescr); } for (const derived of derivedMembers) { const derivedInput = fields.attemptRetrieveDescriptorFromSymbol(derived); if (derivedInput !== null) { // Note: We always track dependencies from the child to the parent, // so skip here for now. continue; } // If we discover a derived, non-input member, then it will cause // conflicts, and we mark the current input as incompatible. fields.captureUnknownDerivedField(fieldDescr); continue inputCheck; } // If there is no parent, we are done. Otherwise, check the parent // to either inherit or check the incompatibility with the inheritance. if (inherited === undefined) { continue; } const inheritedMemberInput = fields.attemptRetrieveDescriptorFromSymbol(inherited); // Parent is not an input, and hence will conflict.. if (inheritedMemberInput === null) { fields.captureUnknownParentField(fieldDescr); continue; } fields.captureKnownFieldInheritanceRelationship(fieldDescr, inheritedMemberInput); } } }
{ "end_byte": 5260, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/problematic_patterns/check_inheritance.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/reference_migration/migrate_ts_type_references.ts_0_3046
/** * @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 ts from 'typescript'; import {ProgramInfo, projectFile, Replacement, TextUpdate} from '../../../../../utils/tsurge'; import assert from 'assert'; import {ImportManager} from '@angular/compiler-cli/src/ngtsc/translator'; import {isTsClassTypeReference, Reference} from '../reference_resolution/reference_kinds'; import {ReferenceMigrationHost} from './reference_migration_host'; import {ClassFieldDescriptor} from '../reference_resolution/known_fields'; /** * Migrates TypeScript "ts.Type" references. E.g. * - `Partial<MyComp>` will be converted to `UnwrapSignalInputs<Partial<MyComp>>`. in Catalyst test files. */ export function migrateTypeScriptTypeReferences<D extends ClassFieldDescriptor>( host: ReferenceMigrationHost<D>, references: Reference<D>[], importManager: ImportManager, info: ProgramInfo, ) { const seenTypeNodes = new WeakSet<ts.TypeReferenceNode>(); for (const reference of references) { // This pass only deals with TS input class type references. if (!isTsClassTypeReference(reference)) { continue; } // Skip references to classes that are not fully migrated. if (!host.shouldMigrateReferencesToClass(reference.target)) { continue; } // Skip duplicate references. E.g. in batching. if (seenTypeNodes.has(reference.from.node)) { continue; } seenTypeNodes.add(reference.from.node); if (reference.isPartialReference && reference.isPartOfCatalystFile) { assert(reference.from.node.typeArguments, 'Expected type arguments for partial reference.'); assert(reference.from.node.typeArguments.length === 1, 'Expected an argument for reference.'); const firstArg = reference.from.node.typeArguments[0]; const sf = firstArg.getSourceFile(); // Naive detection of the import. Sufficient for this test file migration. const catalystImport = sf.text.includes( 'google3/javascript/angular2/testing/catalyst/fake_async', ) ? 'google3/javascript/angular2/testing/catalyst/fake_async' : 'google3/javascript/angular2/testing/catalyst/async'; const unwrapImportExpr = importManager.addImport({ exportModuleSpecifier: catalystImport, exportSymbolName: 'UnwrapSignalInputs', requestedFile: sf, }); host.replacements.push( new Replacement( projectFile(sf, info), new TextUpdate({ position: firstArg.getStart(), end: firstArg.getStart(), toInsert: `${host.printer.printNode(ts.EmitHint.Unspecified, unwrapImportExpr, sf)}<`, }), ), ); host.replacements.push( new Replacement( projectFile(sf, info), new TextUpdate({position: firstArg.getEnd(), end: firstArg.getEnd(), toInsert: '>'}), ), ); } } }
{ "end_byte": 3046, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/reference_migration/migrate_ts_type_references.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/reference_migration/migrate_ts_references.ts_0_2973
/** * @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 ts from 'typescript'; import { migrateBindingElementInputReference, IdentifierOfBindingElement, } from './helpers/object_expansion_refs'; import {migrateStandardTsReference, NarrowableTsReferences} from './helpers/standard_reference'; import {ProgramInfo} from '../../../../../utils/tsurge'; import {ClassFieldDescriptor, ClassFieldUniqueKey} from '../reference_resolution/known_fields'; import {isTsReference, Reference} from '../reference_resolution/reference_kinds'; import {ReferenceMigrationHost} from './reference_migration_host'; /** * Migrates TypeScript input references to be signal compatible. * * The phase takes care of control flow analysis and generates temporary variables * where needed to ensure narrowing continues to work. E.g. * * ``` * someMethod() { * if (this.input) { * this.input.charAt(0); * } * } * ``` * * will be transformed into: * * ``` * someMethod() { * const input_1 = this.input(); * if (input_1) { * input_1.charAt(0); * } * } * ``` */ export function migrateTypeScriptReferences<D extends ClassFieldDescriptor>( host: ReferenceMigrationHost<D>, references: Reference<D>[], checker: ts.TypeChecker, info: ProgramInfo, ) { const tsReferencesWithNarrowing = new Map<ClassFieldUniqueKey, NarrowableTsReferences>(); const tsReferencesInBindingElements = new Set<IdentifierOfBindingElement>(); const seenIdentifiers = new WeakSet<ts.Identifier>(); for (const reference of references) { // This pass only deals with TS references. if (!isTsReference(reference)) { continue; } // Skip references to incompatible inputs. if (!host.shouldMigrateReferencesToField(reference.target)) { continue; } // Never attempt to migrate write references. // Those usually invalidate the target input most of the time, but in // best-effort mode they are not. if (reference.from.isWrite) { continue; } // Skip duplicate references. E.g. in batching. if (seenIdentifiers.has(reference.from.node)) { continue; } seenIdentifiers.add(reference.from.node); const targetKey = reference.target.key; if (reference.from.isPartOfElementBinding) { tsReferencesInBindingElements.add(reference.from.node as IdentifierOfBindingElement); } else { if (!tsReferencesWithNarrowing.has(targetKey)) { tsReferencesWithNarrowing.set(targetKey, {accesses: []}); } tsReferencesWithNarrowing.get(targetKey)!.accesses.push(reference.from.node); } } migrateBindingElementInputReference( tsReferencesInBindingElements, info, host.replacements, host.printer, ); migrateStandardTsReference(tsReferencesWithNarrowing, checker, info, host.replacements); }
{ "end_byte": 2973, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/reference_migration/migrate_ts_references.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/reference_migration/migrate_template_references.ts_0_1830
/** * @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 {Replacement, TextUpdate} from '../../../../../utils/tsurge'; import {ClassFieldDescriptor} from '../reference_resolution/known_fields'; import {isTemplateReference, Reference} from '../reference_resolution/reference_kinds'; import {ReferenceMigrationHost} from './reference_migration_host'; /** * Phase that migrates Angular template references to * unwrap signals. */ export function migrateTemplateReferences<D extends ClassFieldDescriptor>( host: ReferenceMigrationHost<D>, references: Reference<D>[], ) { const seenFileReferences = new Set<string>(); for (const reference of references) { // This pass only deals with HTML template references. if (!isTemplateReference(reference)) { continue; } // Skip references to incompatible inputs. if (!host.shouldMigrateReferencesToField(reference.target)) { continue; } // Skip duplicate references. E.g. if a template is shared. const fileReferenceId = `${reference.from.templateFile.id}:${reference.from.read.sourceSpan.end}`; if (seenFileReferences.has(fileReferenceId)) { continue; } seenFileReferences.add(fileReferenceId); // Expand shorthands like `{bla}` to `{bla: bla()}`. const appendText = reference.from.isObjectShorthandExpression ? `: ${reference.from.read.name}()` : `()`; host.replacements.push( new Replacement( reference.from.templateFile, new TextUpdate({ position: reference.from.read.sourceSpan.end, end: reference.from.read.sourceSpan.end, toInsert: appendText, }), ), ); } }
{ "end_byte": 1830, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/reference_migration/migrate_template_references.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/reference_migration/reference_migration_host.ts_0_633
/** * @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 ts from 'typescript'; import {Replacement} from '../../../../../utils/tsurge'; import {ClassFieldDescriptor} from '../reference_resolution/known_fields'; export interface ReferenceMigrationHost<D extends ClassFieldDescriptor> { shouldMigrateReferencesToField: (descriptor: D) => boolean; shouldMigrateReferencesToClass: (clazz: ts.ClassDeclaration) => boolean; replacements: Replacement[]; printer: ts.Printer; }
{ "end_byte": 633, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/reference_migration/reference_migration_host.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/reference_migration/migrate_host_bindings.ts_0_2128
/** * @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 ts from 'typescript'; import {ProgramInfo, projectFile, Replacement, TextUpdate} from '../../../../../utils/tsurge'; import {ClassFieldDescriptor} from '../reference_resolution/known_fields'; import {isHostBindingReference, Reference} from '../reference_resolution/reference_kinds'; import {ReferenceMigrationHost} from './reference_migration_host'; /** * Phase that migrates Angular host binding references to * unwrap signals. */ export function migrateHostBindings<D extends ClassFieldDescriptor>( host: ReferenceMigrationHost<D>, references: Reference<D>[], info: ProgramInfo, ) { const seenReferences = new WeakMap<ts.Node, Set<number>>(); for (const reference of references) { // This pass only deals with host binding references. if (!isHostBindingReference(reference)) { continue; } // Skip references to incompatible inputs. if (!host.shouldMigrateReferencesToField(reference.target)) { continue; } const bindingField = reference.from.hostPropertyNode; const expressionOffset = bindingField.getStart() + 1; // account for quotes. const readEndPos = expressionOffset + reference.from.read.sourceSpan.end; // Skip duplicate references. Can happen if the host object is shared. if (seenReferences.get(bindingField)?.has(readEndPos)) { continue; } if (seenReferences.has(bindingField)) { seenReferences.get(bindingField)!.add(readEndPos); } else { seenReferences.set(bindingField, new Set([readEndPos])); } // Expand shorthands like `{bla}` to `{bla: bla()}`. const appendText = reference.from.isObjectShorthandExpression ? `: ${reference.from.read.name}()` : `()`; host.replacements.push( new Replacement( projectFile(bindingField.getSourceFile(), info), new TextUpdate({position: readEndPos, end: readEndPos, toInsert: appendText}), ), ); } }
{ "end_byte": 2128, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/reference_migration/migrate_host_bindings.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/reference_migration/helpers/create_block_arrow_function.ts_0_1983
/** * @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 ts from 'typescript'; import {ProjectFile, Replacement, TextUpdate} from '../../../../../../utils/tsurge'; /** * Creates replacements to insert the given statement as * first statement into the arrow function. * * The arrow function is converted to a block-based arrow function * that can hold multiple statements. The original expression is * simply returned like before. */ export function createNewBlockToInsertVariable( node: ts.ArrowFunction, file: ProjectFile, toInsert: string, ): Replacement[] { const sf = node.getSourceFile(); // For indentation, we traverse up and find the earliest statement. // This node is most of the time a good candidate for acceptable // indentation of a new block. const spacingNode = ts.findAncestor(node, ts.isStatement) ?? node.parent; const {character} = ts.getLineAndCharacterOfPosition(sf, spacingNode.getStart()); const blockSpace = ' '.repeat(character); const contentSpace = ' '.repeat(character + 2); return [ // Delete leading whitespace of the concise body. new Replacement( file, new TextUpdate({ position: node.body.getFullStart(), end: node.body.getStart(), toInsert: '', }), ), // Insert leading block braces, and `toInsert` content. // Wrap the previous expression in a return now. new Replacement( file, new TextUpdate({ position: node.body.getStart(), end: node.body.getStart(), toInsert: ` {\n${contentSpace}${toInsert}\n${contentSpace}return `, }), ), // Add trailing brace. new Replacement( file, new TextUpdate({ position: node.body.getEnd(), end: node.body.getEnd(), toInsert: `;\n${blockSpace}}`, }), ), ]; }
{ "end_byte": 1983, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/reference_migration/helpers/create_block_arrow_function.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/reference_migration/helpers/standard_reference.ts_0_4582
/** * @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 ts from 'typescript'; import {analyzeControlFlow} from '../../../flow_analysis'; import {ProgramInfo, projectFile, Replacement, TextUpdate} from '../../../../../../utils/tsurge'; import {traverseAccess} from '../../../utils/traverse_access'; import {UniqueNamesGenerator} from '../../../utils/unique_names'; import {createNewBlockToInsertVariable} from '../helpers/create_block_arrow_function'; export interface NarrowableTsReferences { accesses: ts.Identifier[]; } export function migrateStandardTsReference( tsReferencesWithNarrowing: Map<unknown, NarrowableTsReferences>, checker: ts.TypeChecker, info: ProgramInfo, replacements: Replacement[], ) { const nameGenerator = new UniqueNamesGenerator(['Value', 'Val', 'Input']); // TODO: Consider checking/properly handling optional chaining and narrowing. for (const reference of tsReferencesWithNarrowing.values()) { const controlFlowResult = analyzeControlFlow(reference.accesses, checker); const idToSharedField = new Map<number, string>(); for (const {id, originalNode, recommendedNode} of controlFlowResult) { const sf = originalNode.getSourceFile(); // Original node is preserved. No narrowing, and hence not shared. // Unwrap the signal directly. if (recommendedNode === 'preserve') { // Append `()` to unwrap the signal. replacements.push( new Replacement( projectFile(sf, info), new TextUpdate({ position: originalNode.getEnd(), end: originalNode.getEnd(), toInsert: '()', }), ), ); continue; } // This reference is shared with a previous reference. Replace the access // with the temporary variable. if (typeof recommendedNode === 'number') { const replaceNode = traverseAccess(originalNode); replacements.push( new Replacement( projectFile(sf, info), new TextUpdate({ position: replaceNode.getStart(), end: replaceNode.getEnd(), // Extract the shared field name. toInsert: idToSharedField.get(recommendedNode)!, }), ), ); continue; } // Otherwise, we are creating a "shared reference" at the given node and // block. // Iterate up the original node, until we hit the "recommended block" level. // We then use the previous child as anchor for inserting. This allows us // to insert right before the first reference in the container, at the proper // block level— instead of always inserting at the beginning of the container. let parent = originalNode.parent; let referenceNodeInBlock: ts.Node = originalNode; while (parent !== recommendedNode) { referenceNodeInBlock = parent; parent = parent.parent; } const replaceNode = traverseAccess(originalNode); const fieldName = nameGenerator.generate(originalNode.text, referenceNodeInBlock); const filePath = projectFile(sf, info); const temporaryVariableStr = `const ${fieldName} = ${replaceNode.getText()}();`; idToSharedField.set(id, fieldName); // If the common ancestor block of all shared references is an arrow function // without a block, convert the arrow function to a block and insert the temporary // variable at the beginning. if (ts.isArrowFunction(parent) && !ts.isBlock(parent.body)) { replacements.push( ...createNewBlockToInsertVariable(parent, filePath, temporaryVariableStr), ); } else { const leadingSpace = ts.getLineAndCharacterOfPosition(sf, referenceNodeInBlock.getStart()); replacements.push( new Replacement( filePath, new TextUpdate({ position: referenceNodeInBlock.getStart(), end: referenceNodeInBlock.getStart(), toInsert: `${temporaryVariableStr}\n${' '.repeat(leadingSpace.character)}`, }), ), ); } replacements.push( new Replacement( projectFile(sf, info), new TextUpdate({ position: replaceNode.getStart(), end: replaceNode.getEnd(), toInsert: fieldName, }), ), ); } } }
{ "end_byte": 4582, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/reference_migration/helpers/standard_reference.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/reference_migration/helpers/object_expansion_refs.ts_0_6459
/** * @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 ts from 'typescript'; import { Replacement, TextUpdate, ProgramInfo, projectFile, ProjectFile, } from '../../../../../../utils/tsurge'; import {getBindingElementDeclaration} from '../../../utils/binding_elements'; import {UniqueNamesGenerator} from '../../../utils/unique_names'; import assert from 'assert'; import {createNewBlockToInsertVariable} from './create_block_arrow_function'; /** An identifier part of a binding element. */ export interface IdentifierOfBindingElement extends ts.Identifier { parent: ts.BindingElement; } /** * Migrates a binding element that refers to an Angular input. * * E.g. `const {myInput} = this`. * * For references in binding elements, we extract the element into a variable * where we unwrap the input. This ensures narrowing naturally works in subsequent * places, and we also don't need to detect potential aliases. * * ```ts * const {myInput} = this; * // turns into * const {myInput: myInputValue} = this; * const myInput = myInputValue(); * ``` */ export function migrateBindingElementInputReference( tsReferencesInBindingElements: Set<IdentifierOfBindingElement>, info: ProgramInfo, replacements: Replacement[], printer: ts.Printer, ) { const nameGenerator = new UniqueNamesGenerator(['Input', 'Signal', 'Ref']); for (const reference of tsReferencesInBindingElements) { const bindingElement = reference.parent; const bindingDecl = getBindingElementDeclaration(bindingElement); const sourceFile = bindingElement.getSourceFile(); const file = projectFile(sourceFile, info); const inputFieldName = bindingElement.propertyName ?? bindingElement.name; assert( !ts.isObjectBindingPattern(inputFieldName) && !ts.isArrayBindingPattern(inputFieldName), 'Property of binding element cannot be another pattern.', ); const tmpName: string | undefined = nameGenerator.generate(reference.text, bindingElement); // Only use the temporary name, if really needed. A temporary name is needed if // the input field simply aliased via the binding element, or if the exposed identifier // is a string-literal like. const useTmpNameForInputField = !ts.isObjectBindingPattern(bindingElement.name) || !ts.isIdentifier(inputFieldName); const propertyName = useTmpNameForInputField ? inputFieldName : undefined; const exposedName = useTmpNameForInputField ? ts.factory.createIdentifier(tmpName) : inputFieldName; const newBindingToAccessInputField = ts.factory.updateBindingElement( bindingElement, bindingElement.dotDotDotToken, propertyName, exposedName, bindingElement.initializer, ); const temporaryVariableReplacements = insertTemporaryVariableForBindingElement( bindingDecl, file, `const ${bindingElement.name.getText()} = ${exposedName.text}();`, ); if (temporaryVariableReplacements === null) { console.error(`Could not migrate reference ${reference.text} in ${file.rootRelativePath}`); continue; } replacements.push( new Replacement( file, new TextUpdate({ position: bindingElement.getStart(), end: bindingElement.getEnd(), toInsert: printer.printNode( ts.EmitHint.Unspecified, newBindingToAccessInputField, sourceFile, ), }), ), ...temporaryVariableReplacements, ); } } /** * Inserts the given code snippet after the given variable or * parameter declaration. * * If this is a parameter of an arrow function, a block may be * added automatically. */ function insertTemporaryVariableForBindingElement( expansionDecl: ts.VariableDeclaration | ts.ParameterDeclaration, file: ProjectFile, toInsert: string, ): Replacement[] | null { const sf = expansionDecl.getSourceFile(); const parent = expansionDecl.parent; // The snippet is simply inserted after the variable declaration. // The other case of a variable declaration inside a catch clause is handled // below. if (ts.isVariableDeclaration(expansionDecl) && ts.isVariableDeclarationList(parent)) { const leadingSpaceCount = ts.getLineAndCharacterOfPosition(sf, parent.getStart()).character; const leadingSpace = ' '.repeat(leadingSpaceCount); const statement: ts.Statement = parent.parent; return [ new Replacement( file, new TextUpdate({ position: statement.getEnd(), end: statement.getEnd(), toInsert: `\n${leadingSpace}${toInsert}`, }), ), ]; } // If we are dealing with a object expansion inside a parameter of // a function-like declaration w/ block, add the variable as the first // node inside the block. const bodyBlock = getBodyBlockOfNode(parent); if (bodyBlock !== null) { const firstElementInBlock = bodyBlock.statements[0] as ts.Statement | undefined; const spaceReferenceNode = firstElementInBlock ?? bodyBlock; const spaceOffset = firstElementInBlock !== undefined ? 0 : 2; const leadingSpaceCount = ts.getLineAndCharacterOfPosition(sf, spaceReferenceNode.getStart()).character + spaceOffset; const leadingSpace = ' '.repeat(leadingSpaceCount); return [ new Replacement( file, new TextUpdate({ position: bodyBlock.getStart() + 1, end: bodyBlock.getStart() + 1, toInsert: `\n${leadingSpace}${toInsert}`, }), ), ]; } // Other cases where we see an arrow function without a block. // We need to create one now. if (ts.isArrowFunction(parent) && !ts.isBlock(parent.body)) { return createNewBlockToInsertVariable(parent, file, toInsert); } return null; } /** Gets the body block of a given node, if available. */ function getBodyBlockOfNode(node: ts.Node): ts.Block | null { if ( (ts.isMethodDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isGetAccessorDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isArrowFunction(node)) && node.body !== undefined && ts.isBlock(node.body) ) { return node.body; } if (ts.isCatchClause(node.parent)) { return node.parent.block; } return null; }
{ "end_byte": 6459, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/reference_migration/helpers/object_expansion_refs.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/identify_host_references.ts_0_5352
/** * @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 {getAngularDecorators} from '@angular/compiler-cli/src/ngtsc/annotations'; import {unwrapExpression} from '@angular/compiler-cli/src/ngtsc/annotations/common'; import {ReflectionHost, reflectObjectLiteral} from '@angular/compiler-cli/src/ngtsc/reflection'; import ts from 'typescript'; import { AST, ParseLocation, ParseSourceSpan, ParsedEvent, ParsedProperty, makeBindingParser, } from '../../../../../../../compiler/public_api'; import {ProgramInfo, projectFile} from '../../../../../utils/tsurge'; import { TemplateExpressionReferenceVisitor, TmplInputExpressionReference, } from './template_reference_visitor'; import {ReferenceResult} from './reference_result'; import {ClassFieldDescriptor, KnownFields} from './known_fields'; import {ReferenceKind} from './reference_kinds'; /** * Checks host bindings of the given class and tracks all * references to inputs within bindings. */ export function identifyHostBindingReferences<D extends ClassFieldDescriptor>( node: ts.ClassDeclaration, programInfo: ProgramInfo, checker: ts.TypeChecker, reflector: ReflectionHost, result: ReferenceResult<D>, knownFields: KnownFields<D>, fieldNamesToConsiderForReferenceLookup: Set<string> | null, ) { if (node.name === undefined) { return; } const decorators = reflector.getDecoratorsOfDeclaration(node); if (decorators === null) { return; } const angularDecorators = getAngularDecorators( decorators, ['Directive', 'Component'], /* isAngularCore */ false, ); if (angularDecorators.length === 0) { return; } // Assume only one Angular decorator per class. const ngDecorator = angularDecorators[0]; if (ngDecorator.args?.length !== 1) { return; } const metadataNode = unwrapExpression(ngDecorator.args[0]); if (!ts.isObjectLiteralExpression(metadataNode)) { return; } const metadata = reflectObjectLiteral(metadataNode); if (!metadata.has('host')) { return; } let hostField: ts.Node | undefined = unwrapExpression(metadata.get('host')!); // Special-case in case host bindings are shared via a variable. // e.g. Material button shares host bindings as a constant in the same target. if (ts.isIdentifier(hostField)) { let symbol = checker.getSymbolAtLocation(hostField); // Plain identifier references can point to alias symbols (e.g. imports). if (symbol !== undefined && symbol.flags & ts.SymbolFlags.Alias) { symbol = checker.getAliasedSymbol(symbol); } if ( symbol !== undefined && symbol.valueDeclaration !== undefined && ts.isVariableDeclaration(symbol.valueDeclaration) ) { hostField = symbol?.valueDeclaration.initializer; } } if (hostField === undefined || !ts.isObjectLiteralExpression(hostField)) { return; } const hostMap = reflectObjectLiteral(hostField); const expressionResult: TmplInputExpressionReference<ts.Node, D>[] = []; const expressionVisitor = new TemplateExpressionReferenceVisitor<ts.Node, D>( checker, null, node, knownFields, fieldNamesToConsiderForReferenceLookup, ); for (const [rawName, expression] of hostMap.entries()) { if (!ts.isStringLiteralLike(expression)) { continue; } const isEventBinding = rawName.startsWith('('); const isPropertyBinding = rawName.startsWith('['); // Only migrate property or event bindings. if (!isPropertyBinding && !isEventBinding) { continue; } const parser = makeBindingParser(); const sourceSpan: ParseSourceSpan = new ParseSourceSpan( // Fake source span to keep parsing offsets zero-based. // We then later combine these with the expression TS node offsets. new ParseLocation({content: '', url: ''}, 0, 0, 0), new ParseLocation({content: '', url: ''}, 0, 0, 0), ); const name = rawName.substring(1, rawName.length - 1); let parsed: AST | undefined = undefined; if (isEventBinding) { const result: ParsedEvent[] = []; parser.parseEvent( name.substring(1, name.length - 1), expression.text, false, sourceSpan, sourceSpan, [], result, sourceSpan, ); parsed = result[0].handler; } else { const result: ParsedProperty[] = []; parser.parsePropertyBinding( name, expression.text, true, /* isTwoWayBinding */ false, sourceSpan, 0, sourceSpan, [], result, sourceSpan, ); parsed = result[0].expression; } if (parsed != null) { expressionResult.push(...expressionVisitor.checkTemplateExpression(expression, parsed)); } } for (const ref of expressionResult) { result.references.push({ kind: ReferenceKind.InHostBinding, from: { read: ref.read, readAstPath: ref.readAstPath, isObjectShorthandExpression: ref.isObjectShorthandExpression, isWrite: ref.isWrite, file: projectFile(ref.context.getSourceFile(), programInfo), hostPropertyNode: ref.context, }, target: ref.targetField, }); } }
{ "end_byte": 5352, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/identify_host_references.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/reference_kinds.ts_0_5602
/** * @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 */ /** * @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 ts from 'typescript'; import {AST, PropertyRead, TmplAstNode} from '@angular/compiler'; import {ProjectFile} from '../../../../../utils/tsurge'; import {ClassFieldDescriptor} from './known_fields'; /** Possible types of references to known fields detected. */ export enum ReferenceKind { InTemplate, InHostBinding, TsReference, TsClassTypeReference, } /** Interface describing a template reference to a known field. */ export interface TemplateReference<D extends ClassFieldDescriptor> { kind: ReferenceKind.InTemplate; /** From where the reference is made. */ from: { /** Template file containing the reference. */ templateFile: ProjectFile; /** TypeScript file that references, or contains the template. */ originatingTsFile: ProjectFile; /** HTML AST node that contains the reference. */ node: TmplAstNode; /** Expression AST node that represents the reference. */ read: PropertyRead; /** * Expression AST sequentially visited to reach the given read. * This follows top-down down ordering. The last element is the actual read. */ readAstPath: AST[]; /** Whether the reference is part of an object shorthand expression. */ isObjectShorthandExpression: boolean; /** Whether this reference is part of a likely-narrowing expression. */ isLikelyPartOfNarrowing: boolean; /** Whether the reference is a write. E.g. two way binding, or assignment. */ isWrite: boolean; }; /** Target field addressed by the reference. */ target: D; } /** Interface describing a host binding reference to a known field. */ export interface HostBindingReference<D extends ClassFieldDescriptor> { kind: ReferenceKind.InHostBinding; /** From where the reference is made. */ from: { /** File that contains the host binding reference. */ file: ProjectFile; /** TypeScript property node containing the reference. */ hostPropertyNode: ts.Node; /** Expression AST node that represents the reference. */ read: PropertyRead; /** * Expression AST sequentially visited to reach the given read. * This follows top-down down ordering. The last element is the actual read. */ readAstPath: AST[]; /** Whether the reference is part of an object shorthand expression. */ isObjectShorthandExpression: boolean; /** Whether the reference is a write. E.g. an event assignment. */ isWrite: boolean; }; /** Target field addressed by the reference. */ target: D; } /** Interface describing a TypeScript reference to a known field. */ export interface TsReference<D extends ClassFieldDescriptor> { kind: ReferenceKind.TsReference; /** From where the reference is made. */ from: { /** File that contains the TypeScript reference. */ file: ProjectFile; /** TypeScript AST node representing the reference. */ node: ts.Identifier; /** Whether the reference is a write. */ isWrite: boolean; /** Whether the reference is part of an element binding */ isPartOfElementBinding: boolean; }; /** Target field addressed by the reference. */ target: D; } /** * Interface describing a TypeScript `ts.Type` reference to a * class containing known fields. */ export interface TsClassTypeReference { kind: ReferenceKind.TsClassTypeReference; /** From where the reference is made. */ from: { /** File that contains the TypeScript reference. */ file: ProjectFile; /** TypeScript AST node representing the reference. */ node: ts.TypeReferenceNode; }; /** Whether the reference is using `Partial<T>`. */ isPartialReference: boolean; /** Whether the reference is part of a file using Catalyst. */ isPartOfCatalystFile: boolean; /** Target class that contains at least one known field (e.g. inputs) */ target: ts.ClassDeclaration; } /** Possible structures representing known field references. */ export type Reference<D extends ClassFieldDescriptor> = | TsReference<D> | TemplateReference<D> | HostBindingReference<D> | TsClassTypeReference; /** Whether the given reference is a TypeScript reference. */ export function isTsReference<D extends ClassFieldDescriptor>( ref: Reference<D>, ): ref is TsReference<D> { return (ref as Partial<TsReference<D>>).kind === ReferenceKind.TsReference; } /** Whether the given reference is a template reference. */ export function isTemplateReference<D extends ClassFieldDescriptor>( ref: Reference<D>, ): ref is TemplateReference<D> { return (ref as Partial<TemplateReference<D>>).kind === ReferenceKind.InTemplate; } /** Whether the given reference is a host binding reference. */ export function isHostBindingReference<D extends ClassFieldDescriptor>( ref: Reference<D>, ): ref is HostBindingReference<D> { return (ref as Partial<HostBindingReference<D>>).kind === ReferenceKind.InHostBinding; } /** * Whether the given reference is a TypeScript `ts.Type` reference * to a class containing known fields. */ export function isTsClassTypeReference<D extends ClassFieldDescriptor>( ref: Reference<D>, ): ref is TsClassTypeReference { return (ref as Partial<TsClassTypeReference>).kind === ReferenceKind.TsClassTypeReference; }
{ "end_byte": 5602, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/reference_kinds.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/identify_template_references.ts_0_5249
/** * @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 {TmplAstNode} from '@angular/compiler'; import {ResourceLoader} from '@angular/compiler-cli/src/ngtsc/annotations'; import {extractTemplate} from '@angular/compiler-cli/src/ngtsc/annotations/component/src/resources'; import {NgCompilerOptions} from '@angular/compiler-cli/src/ngtsc/core/api'; import {absoluteFrom} from '@angular/compiler-cli/src/ngtsc/file_system'; import {PartialEvaluator} from '@angular/compiler-cli/src/ngtsc/partial_evaluator'; import {ClassDeclaration, ReflectionHost} from '@angular/compiler-cli/src/ngtsc/reflection'; import {CompilationMode} from '@angular/compiler-cli/src/ngtsc/transform'; import {OptimizeFor, TemplateTypeChecker} from '@angular/compiler-cli/src/ngtsc/typecheck/api'; import ts from 'typescript'; import {ProgramInfo, projectFile} from '../../../../../utils/tsurge'; import {TemplateReferenceVisitor} from './template_reference_visitor'; import {attemptExtractTemplateDefinition} from '../../utils/extract_template'; import {ReferenceResult} from './reference_result'; import {ClassFieldDescriptor, KnownFields} from './known_fields'; import {ReferenceKind} from './reference_kinds'; /** * Checks whether the given class has an Angular template, and resolves * all of the references to inputs. */ export function identifyTemplateReferences<D extends ClassFieldDescriptor>( programInfo: ProgramInfo, node: ts.ClassDeclaration, reflector: ReflectionHost, checker: ts.TypeChecker, evaluator: PartialEvaluator, templateTypeChecker: TemplateTypeChecker, resourceLoader: ResourceLoader, options: NgCompilerOptions, result: ReferenceResult<D>, knownFields: KnownFields<D>, fieldNamesToConsiderForReferenceLookup: Set<string> | null, ) { const template = templateTypeChecker.getTemplate(node, OptimizeFor.WholeProgram) ?? // If there is no template registered in the TCB or compiler, the template may // be skipped due to an explicit `jit: true` setting. We try to detect this case // and parse the template manually. extractTemplateWithoutCompilerAnalysis( node, checker, reflector, resourceLoader, evaluator, options, ); if (template !== null) { const visitor = new TemplateReferenceVisitor( checker, templateTypeChecker, node, knownFields, fieldNamesToConsiderForReferenceLookup, ); template.forEach((node) => node.visit(visitor)); for (const res of visitor.result) { const templateFilePath = res.context.sourceSpan.start.file.url; // Templates without an URL are non-mappable artifacts of e.g. // string concatenated templates. See the `indirect` template // source mapping concept in the compiler. We skip such references // as those cannot be migrated, but print an error for now. if (templateFilePath === '') { // TODO: Incorporate a TODO potentially. console.error( `Found reference to field ${res.targetField.key} that cannot be ` + `migrated because the template cannot be parsed with source map information ` + `(in file: ${node.getSourceFile().fileName}).`, ); continue; } result.references.push({ kind: ReferenceKind.InTemplate, from: { read: res.read, readAstPath: res.readAstPath, node: res.context, isObjectShorthandExpression: res.isObjectShorthandExpression, originatingTsFile: projectFile(node.getSourceFile(), programInfo), templateFile: projectFile(absoluteFrom(templateFilePath), programInfo), isLikelyPartOfNarrowing: res.isLikelyNarrowed, isWrite: res.isWrite, }, target: res.targetField, }); } } } /** * Attempts to extract a `@Component` template from the given class, * without relying on the `NgCompiler` program analysis. * * This is useful for JIT components using `jit: true` which were not * processed by the Angular compiler, but may still have templates that * contain references to inputs that we can resolve via the fallback * reference resolutions (that does not use the type check block). */ function extractTemplateWithoutCompilerAnalysis( node: ts.ClassDeclaration, checker: ts.TypeChecker, reflector: ReflectionHost, resourceLoader: ResourceLoader, evaluator: PartialEvaluator, options: NgCompilerOptions, ): TmplAstNode[] | null { if (node.name === undefined) { return null; } const tmplDef = attemptExtractTemplateDefinition(node, checker, reflector, resourceLoader); if (tmplDef === null) { return null; } return extractTemplate( node as ClassDeclaration, tmplDef, evaluator, null, resourceLoader, { enableBlockSyntax: true, enableLetSyntax: true, usePoisonedData: true, enableI18nLegacyMessageIdFormat: options.enableI18nLegacyMessageIdFormat !== false, i18nNormalizeLineEndingsInICUs: options.i18nNormalizeLineEndingsInICUs === true, }, CompilationMode.FULL, ).nodes; }
{ "end_byte": 5249, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/identify_template_references.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/identify_ts_references.ts_0_4295
/** * @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 ts from 'typescript'; import {ProgramInfo, projectFile} from '../../../../../utils/tsurge'; import {lookupPropertyAccess} from '../../../../../utils/tsurge/helpers/ast/lookup_property_access'; import {DebugElementComponentInstance} from '../../pattern_advisors/debug_element_component_instance'; import {resolveBindingElement} from '../../utils/binding_elements'; import {traverseAccess} from '../../utils/traverse_access'; import {unwrapParent} from '../../utils/unwrap_parent'; import {writeBinaryOperators} from '../../utils/write_operators'; import {ReferenceResult} from './reference_result'; import {ClassFieldDescriptor, KnownFields} from './known_fields'; import {ReferenceKind} from './reference_kinds'; /** * Checks whether given TypeScript reference refers to an Angular input, and captures * the reference if possible. * * @param fieldNamesToConsiderForReferenceLookup List of field names that should be * respected when expensively looking up references to known fields. * May be null if all identifiers should be inspected. */ export function identifyPotentialTypeScriptReference<D extends ClassFieldDescriptor>( node: ts.Identifier, programInfo: ProgramInfo, checker: ts.TypeChecker, knownFields: KnownFields<D>, result: ReferenceResult<D>, fieldNamesToConsiderForReferenceLookup: Set<string> | null, advisors: { debugElComponentInstanceTracker: DebugElementComponentInstance; }, ): void { // Skip all identifiers that never can point to a migrated field. // TODO: Capture these assumptions and performance optimizations in the design doc. if ( fieldNamesToConsiderForReferenceLookup !== null && !fieldNamesToConsiderForReferenceLookup.has(node.text) ) { return; } let target: ts.Symbol | undefined = undefined; // Resolve binding elements to their declaration symbol. // Commonly inputs are accessed via object expansion. e.g. `const {input} = this;`. if (ts.isBindingElement(node.parent)) { // Skip binding elements that are using spread. if (node.parent.dotDotDotToken !== undefined) { return; } const bindingInfo = resolveBindingElement(node.parent); if (bindingInfo === null) { // The declaration could not be resolved. Skip analyzing this. return; } const bindingType = checker.getTypeAtLocation(bindingInfo.pattern); const resolved = lookupPropertyAccess(checker, bindingType, [bindingInfo.propertyName]); target = resolved?.symbol; } else { target = checker.getSymbolAtLocation(node); } noTargetSymbolCheck: if (target === undefined) { if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { const propAccessSymbol = checker.getSymbolAtLocation(node.parent.expression); if ( propAccessSymbol !== undefined && propAccessSymbol.valueDeclaration !== undefined && ts.isVariableDeclaration(propAccessSymbol.valueDeclaration) && propAccessSymbol.valueDeclaration.initializer !== undefined ) { target = advisors.debugElComponentInstanceTracker .detect(propAccessSymbol.valueDeclaration.initializer) ?.getProperty(node.text); // We found a target in the fallback path. Break out. if (target !== undefined) { break noTargetSymbolCheck; } } } return; } let targetInput = knownFields.attemptRetrieveDescriptorFromSymbol(target); if (targetInput === null) { return; } const access = unwrapParent(traverseAccess(node)); const accessParent = access.parent; const isWriteReference = ts.isBinaryExpression(accessParent) && accessParent.left === access && writeBinaryOperators.includes(accessParent.operatorToken.kind); // track accesses from source files to known fields. result.references.push({ kind: ReferenceKind.TsReference, from: { node, file: projectFile(node.getSourceFile(), programInfo), isWrite: isWriteReference, isPartOfElementBinding: ts.isBindingElement(node.parent), }, target: targetInput, }); }
{ "end_byte": 4295, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/identify_ts_references.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/index.ts_0_5163
/** * @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 {ResourceLoader} from '@angular/compiler-cli/src/ngtsc/annotations'; import {PartialEvaluator} from '@angular/compiler-cli/src/ngtsc/partial_evaluator'; import {ReflectionHost} from '@angular/compiler-cli/src/ngtsc/reflection'; import {TemplateTypeChecker} from '@angular/compiler-cli/src/ngtsc/typecheck/api'; import ts from 'typescript'; import {ProgramInfo, projectFile} from '../../../../../utils/tsurge'; import {isInputContainerNode} from '../../input_detection/input_node'; import {DebugElementComponentInstance} from '../../pattern_advisors/debug_element_component_instance'; import {PartialDirectiveTypeInCatalystTests} from '../../pattern_advisors/partial_directive_type'; import {identifyHostBindingReferences} from './identify_host_references'; import {identifyTemplateReferences} from './identify_template_references'; import {identifyPotentialTypeScriptReference} from './identify_ts_references'; import {ClassFieldDescriptor, KnownFields} from './known_fields'; import {ReferenceKind} from './reference_kinds'; import {ReferenceResult} from './reference_result'; /** * Phase where we iterate through all source file references and * detect references to known fields (e.g. commonly inputs). * * This is useful, for example in the signal input migration whe * references need to be migrated to unwrap signals, given that * their target properties is no longer holding a raw value, but * instead an `InputSignal`. * * This phase detects references in all types of locations: * - TS source files * - Angular templates (inline or external) * - Host binding expressions. */ export function createFindAllSourceFileReferencesVisitor<D extends ClassFieldDescriptor>( programInfo: ProgramInfo, checker: ts.TypeChecker, reflector: ReflectionHost, resourceLoader: ResourceLoader, evaluator: PartialEvaluator, templateTypeChecker: TemplateTypeChecker, knownFields: KnownFields<D>, fieldNamesToConsiderForReferenceLookup: Set<string> | null, result: ReferenceResult<D>, ) { const debugElComponentInstanceTracker = new DebugElementComponentInstance(checker); const partialDirectiveCatalystTracker = new PartialDirectiveTypeInCatalystTests( checker, knownFields, ); const perfCounters = { template: 0, hostBindings: 0, tsReferences: 0, tsTypes: 0, }; // Schematic NodeJS execution may not have `global.performance` defined. const currentTimeInMs = () => typeof global.performance !== 'undefined' ? global.performance.now() : Date.now(); const visitor = (node: ts.Node) => { let lastTime = currentTimeInMs(); if (ts.isClassDeclaration(node)) { identifyTemplateReferences( programInfo, node, reflector, checker, evaluator, templateTypeChecker, resourceLoader, programInfo.userOptions, result, knownFields, fieldNamesToConsiderForReferenceLookup, ); perfCounters.template += (currentTimeInMs() - lastTime) / 1000; lastTime = currentTimeInMs(); identifyHostBindingReferences( node, programInfo, checker, reflector, result, knownFields, fieldNamesToConsiderForReferenceLookup, ); perfCounters.hostBindings += (currentTimeInMs() - lastTime) / 1000; lastTime = currentTimeInMs(); } lastTime = currentTimeInMs(); // find references, but do not capture input declarations itself. if ( ts.isIdentifier(node) && !(isInputContainerNode(node.parent) && node.parent.name === node) ) { identifyPotentialTypeScriptReference( node, programInfo, checker, knownFields, result, fieldNamesToConsiderForReferenceLookup, { debugElComponentInstanceTracker, }, ); } perfCounters.tsReferences += (currentTimeInMs() - lastTime) / 1000; lastTime = currentTimeInMs(); // Detect `Partial<T>` references. // Those are relevant to be tracked as they may be updated in Catalyst to // unwrap signal inputs. Commonly people use `Partial` in Catalyst to type // some "component initial values". const partialDirectiveInCatalyst = partialDirectiveCatalystTracker.detect(node); if (partialDirectiveInCatalyst !== null) { result.references.push({ kind: ReferenceKind.TsClassTypeReference, from: { file: projectFile(partialDirectiveInCatalyst.referenceNode.getSourceFile(), programInfo), node: partialDirectiveInCatalyst.referenceNode, }, isPartialReference: true, isPartOfCatalystFile: true, target: partialDirectiveInCatalyst.targetClass, }); } perfCounters.tsTypes += (currentTimeInMs() - lastTime) / 1000; }; return { visitor, debugPrintMetrics: () => { console.info('Source file analysis performance', perfCounters); }, }; }
{ "end_byte": 5163, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/index.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/reference_result.ts_0_402
/** * @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 {ClassFieldDescriptor} from './known_fields'; import {Reference} from './reference_kinds'; export interface ReferenceResult<D extends ClassFieldDescriptor> { references: Reference<D>[]; }
{ "end_byte": 402, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/reference_result.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/known_fields.ts_0_1671
/** * @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 ts from 'typescript'; import {UniqueID} from '../../../../../utils/tsurge'; /** * Unique key for an class field in a project. * * This is the serializable variant, raw string form that * is serializable and allows for cross-target knowledge * needed for the batching capability (via e.g. go/tsunami). */ export type ClassFieldUniqueKey = UniqueID<'ClassField Unique ID'>; /** * Interface describing a recognized class field that can be * uniquely identified throughout the whole migration project * (not necessarily just within an isolated compilation unit) */ export interface ClassFieldDescriptor { node: ts.ClassElement; key: ClassFieldUniqueKey; } /** * Registry of known fields that are considered when inspecting * references throughout the project. */ export interface KnownFields<D extends ClassFieldDescriptor> { /** * Attempt to retrieve a known field descriptor for the given symbol. * * May be null if this is an irrelevant field. */ attemptRetrieveDescriptorFromSymbol(symbol: ts.Symbol): D | null; /** * Whether the given class should also be respected for reference resolution. * * E.g. commonly may be implemented to check whether the given contains any * known fields. E.g. a reference to the class may be tracked when fields inside * are migrated to signal inputs and the public class signature therefore changed. */ shouldTrackClassReference(clazz: ts.ClassDeclaration): boolean; }
{ "end_byte": 1671, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/known_fields.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/template_reference_visitor.ts_0_8071
/** * @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 ts from 'typescript'; import {SymbolKind, TemplateTypeChecker} from '@angular/compiler-cli/src/ngtsc/typecheck/api'; import { AST, BindingType, Conditional, ImplicitReceiver, LiteralMap, ParsedEventType, PropertyRead, PropertyWrite, RecursiveAstVisitor, SafePropertyRead, ThisReceiver, TmplAstBoundAttribute, TmplAstBoundEvent, TmplAstBoundText, TmplAstDeferredBlock, TmplAstForLoopBlock, TmplAstIfBlockBranch, TmplAstNode, TmplAstRecursiveVisitor, TmplAstSwitchBlock, TmplAstSwitchBlockCase, TmplAstTemplate, tmplAstVisitAll, } from '../../../../../../../compiler'; import {BoundAttribute, BoundEvent} from '../../../../../../../compiler/src/render3/r3_ast'; import {lookupPropertyAccess} from '../../../../../utils/tsurge/helpers/ast/lookup_property_access'; import {ClassFieldDescriptor, KnownFields} from './known_fields'; /** * Interface describing a reference to an input from within * an Angular template, or host binding "template expression". */ export interface TmplInputExpressionReference<ExprContext, D extends ClassFieldDescriptor> { targetNode: ts.Node; targetField: D; read: PropertyRead; readAstPath: AST[]; context: ExprContext; isObjectShorthandExpression: boolean; isLikelyNarrowed: boolean; isWrite: boolean; } /** * AST visitor that iterates through a template and finds all * input references. * * This resolution is important to be able to migrate references to inputs * that will be migrated to signal inputs. */ export class TemplateReferenceVisitor< D extends ClassFieldDescriptor, > extends TmplAstRecursiveVisitor { result: TmplInputExpressionReference<TmplAstNode, D>[] = []; /** * Whether we are currently descending into HTML AST nodes * where all bound attributes are considered potentially narrowing. * * Keeps track of all referenced inputs in such attribute expressions. */ private templateAttributeReferencedFields: TmplInputExpressionReference<TmplAstNode, D>[] | null = null; private expressionVisitor: TemplateExpressionReferenceVisitor<TmplAstNode, D>; private seenKnownFieldsCount = new Map<D['key'], number>(); constructor( typeChecker: ts.TypeChecker, templateTypeChecker: TemplateTypeChecker, componentClass: ts.ClassDeclaration, knownFields: KnownFields<D>, fieldNamesToConsiderForReferenceLookup: Set<string> | null, ) { super(); this.expressionVisitor = new TemplateExpressionReferenceVisitor( typeChecker, templateTypeChecker, componentClass, knownFields, fieldNamesToConsiderForReferenceLookup, ); } private checkExpressionForReferencedFields(activeNode: TmplAstNode, expressionNode: AST) { const referencedFields = this.expressionVisitor.checkTemplateExpression( activeNode, expressionNode, ); // Add all references to the overall visitor result. this.result.push(...referencedFields); // Count usages of seen input references. We'll use this to make decisions // based on whether inputs are potentially narrowed or not. for (const input of referencedFields) { this.seenKnownFieldsCount.set( input.targetField.key, (this.seenKnownFieldsCount.get(input.targetField.key) ?? 0) + 1, ); } return referencedFields; } private descendAndCheckForNarrowedSimilarReferences( potentiallyNarrowedInputs: TmplInputExpressionReference<TmplAstNode, D>[], descend: () => void, ) { const inputs = potentiallyNarrowedInputs.map((i) => ({ ref: i, key: i.targetField.key, pastCount: this.seenKnownFieldsCount.get(i.targetField.key) ?? 0, })); descend(); for (const input of inputs) { // Input was referenced inside a narrowable spot, and is used in child nodes. // This is a sign for the input to be narrowed. Mark it as such. if ((this.seenKnownFieldsCount.get(input.key) ?? 0) > input.pastCount) { input.ref.isLikelyNarrowed = true; } } } override visitTemplate(template: TmplAstTemplate): void { // Note: We assume all bound expressions for templates may be subject // to TCB narrowing. This is relevant for now until we support narrowing // of signal calls in templates. // TODO: Remove with: https://github.com/angular/angular/pull/55456. this.templateAttributeReferencedFields = []; tmplAstVisitAll(this, template.attributes); tmplAstVisitAll(this, template.templateAttrs); // If we are dealing with a microsyntax template, do not check // inputs and outputs as those are already passed to the children. // Template attributes may contain relevant expressions though. if (template.tagName === 'ng-template') { tmplAstVisitAll(this, template.inputs); tmplAstVisitAll(this, template.outputs); } const referencedInputs = this.templateAttributeReferencedFields; this.templateAttributeReferencedFields = null; this.descendAndCheckForNarrowedSimilarReferences(referencedInputs, () => { tmplAstVisitAll(this, template.children); tmplAstVisitAll(this, template.references); tmplAstVisitAll(this, template.variables); }); } override visitIfBlockBranch(block: TmplAstIfBlockBranch): void { if (block.expression) { const referencedFields = this.checkExpressionForReferencedFields(block, block.expression); this.descendAndCheckForNarrowedSimilarReferences(referencedFields, () => { super.visitIfBlockBranch(block); }); } else { super.visitIfBlockBranch(block); } } override visitForLoopBlock(block: TmplAstForLoopBlock): void { this.checkExpressionForReferencedFields(block, block.expression); this.checkExpressionForReferencedFields(block, block.trackBy); super.visitForLoopBlock(block); } override visitSwitchBlock(block: TmplAstSwitchBlock): void { const referencedFields = this.checkExpressionForReferencedFields(block, block.expression); this.descendAndCheckForNarrowedSimilarReferences(referencedFields, () => { super.visitSwitchBlock(block); }); } override visitSwitchBlockCase(block: TmplAstSwitchBlockCase): void { if (block.expression) { const referencedFields = this.checkExpressionForReferencedFields(block, block.expression); this.descendAndCheckForNarrowedSimilarReferences(referencedFields, () => { super.visitSwitchBlockCase(block); }); } else { super.visitSwitchBlockCase(block); } } override visitDeferredBlock(deferred: TmplAstDeferredBlock): void { if (deferred.triggers.when) { this.checkExpressionForReferencedFields(deferred, deferred.triggers.when.value); } if (deferred.prefetchTriggers.when) { this.checkExpressionForReferencedFields(deferred, deferred.prefetchTriggers.when.value); } super.visitDeferredBlock(deferred); } override visitBoundText(text: TmplAstBoundText): void { this.checkExpressionForReferencedFields(text, text.value); } override visitBoundEvent(attribute: TmplAstBoundEvent): void { this.checkExpressionForReferencedFields(attribute, attribute.handler); } override visitBoundAttribute(attribute: TmplAstBoundAttribute): void { const referencedFields = this.checkExpressionForReferencedFields(attribute, attribute.value); // Attributes inside templates are potentially "narrowed" and hence we // keep track of all referenced inputs to see if they actually are. if (this.templateAttributeReferencedFields !== null) { this.templateAttributeReferencedFields.push(...referencedFields); } } } /** * Expression AST visitor that checks whether a given expression references * a known `@Input()`. * * This resolution is important to be able to migrate references to inputs * that will be migrated to signal inputs. */
{ "end_byte": 8071, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/template_reference_visitor.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/template_reference_visitor.ts_8072_16232
export class TemplateExpressionReferenceVisitor< ExprContext, D extends ClassFieldDescriptor, > extends RecursiveAstVisitor { private activeTmplAstNode: ExprContext | null = null; private detectedInputReferences: TmplInputExpressionReference<ExprContext, D>[] = []; private isInsideObjectShorthandExpression = false; private insideConditionalExpressionsWithReads: AST[] = []; constructor( private typeChecker: ts.TypeChecker, private templateTypeChecker: TemplateTypeChecker | null, private componentClass: ts.ClassDeclaration, private knownFields: KnownFields<D>, private fieldNamesToConsiderForReferenceLookup: Set<string> | null, ) { super(); } /** Checks the given AST expression. */ checkTemplateExpression( activeNode: ExprContext, expressionNode: AST, ): TmplInputExpressionReference<ExprContext, D>[] { this.detectedInputReferences = []; this.activeTmplAstNode = activeNode; expressionNode.visit(this, []); return this.detectedInputReferences; } override visit(ast: AST, context: AST[]) { super.visit(ast, [...context, ast]); } // Keep track when we are inside an object shorthand expression. This is // necessary as we need to expand the shorthand to invoke a potential new signal. // E.g. `{bla}` may be transformed to `{bla: bla()}`. override visitLiteralMap(ast: LiteralMap, context: any) { for (const [idx, key] of ast.keys.entries()) { this.isInsideObjectShorthandExpression = !!key.isShorthandInitialized; (ast.values[idx] as AST).visit(this, context); this.isInsideObjectShorthandExpression = false; } } override visitPropertyRead(ast: PropertyRead, context: AST[]) { this._inspectPropertyAccess(ast, context); super.visitPropertyRead(ast, context); } override visitSafePropertyRead(ast: SafePropertyRead, context: AST[]) { this._inspectPropertyAccess(ast, context); super.visitPropertyRead(ast, context); } override visitPropertyWrite(ast: PropertyWrite, context: AST[]) { this._inspectPropertyAccess(ast, context); super.visitPropertyWrite(ast, context); } override visitConditional(ast: Conditional, context: AST[]) { this.visit(ast.condition, context); this.insideConditionalExpressionsWithReads.push(ast.condition); this.visit(ast.trueExp, context); this.visit(ast.falseExp, context); this.insideConditionalExpressionsWithReads.pop(); } /** * Inspects the property access and attempts to resolve whether they access * a known field. If so, the result is captured. */ private _inspectPropertyAccess(ast: PropertyRead | PropertyWrite, astPath: AST[]) { if ( this.fieldNamesToConsiderForReferenceLookup !== null && !this.fieldNamesToConsiderForReferenceLookup.has(ast.name) ) { return; } const isWrite = !!( ast instanceof PropertyWrite || (this.activeTmplAstNode && isTwoWayBindingNode(this.activeTmplAstNode)) ); this._checkAccessViaTemplateTypeCheckBlock(ast, isWrite, astPath) || this._checkAccessViaOwningComponentClassType(ast, isWrite, astPath); } /** * Checks whether the node refers to an input using the TCB information. * Type check block may not exist for e.g. test components, so this can return `null`. */ private _checkAccessViaTemplateTypeCheckBlock( ast: PropertyRead | PropertyWrite, isWrite: boolean, astPath: AST[], ): boolean { // There might be no template type checker. E.g. if we check host bindings. if (this.templateTypeChecker === null) { return false; } const symbol = this.templateTypeChecker.getSymbolOfNode(ast, this.componentClass); if (symbol?.kind !== SymbolKind.Expression || symbol.tsSymbol === null) { return false; } // Dangerous: Type checking symbol retrieval is a totally different `ts.Program`, // than the one where we analyzed `knownInputs`. // --> Find the input via its input id. const targetInput = this.knownFields.attemptRetrieveDescriptorFromSymbol(symbol.tsSymbol); if (targetInput === null) { return false; } this.detectedInputReferences.push({ targetNode: targetInput.node, targetField: targetInput, read: ast, readAstPath: astPath, context: this.activeTmplAstNode!, isLikelyNarrowed: this._isPartOfNarrowingTernary(ast), isObjectShorthandExpression: this.isInsideObjectShorthandExpression, isWrite, }); return true; } /** * Simple resolution checking whether the given AST refers to a known input. * This is a fallback for when there is no type checking information (e.g. in host bindings). * * It attempts to resolve references by traversing accesses of the "component class" type. * e.g. `this.bla` is resolved via `CompType#bla` and further. */ private _checkAccessViaOwningComponentClassType( ast: PropertyRead | PropertyWrite, isWrite: boolean, astPath: AST[], ): void { // We might check host bindings, which can never point to template variables or local refs. const expressionTemplateTarget = this.templateTypeChecker === null ? null : this.templateTypeChecker.getExpressionTarget(ast, this.componentClass); // Skip checking if: // - the reference resolves to a template variable or local ref. No way to resolve without TCB. // - the owning component does not have a name (should not happen technically). if (expressionTemplateTarget !== null || this.componentClass.name === undefined) { return; } const property = traverseReceiverAndLookupSymbol( ast, this.componentClass as ts.ClassDeclaration & {name: ts.Identifier}, this.typeChecker, ); if (property === null) { return; } const matchingTarget = this.knownFields.attemptRetrieveDescriptorFromSymbol(property); if (matchingTarget === null) { return; } this.detectedInputReferences.push({ targetNode: matchingTarget.node, targetField: matchingTarget, read: ast, readAstPath: astPath, context: this.activeTmplAstNode!, isLikelyNarrowed: this._isPartOfNarrowingTernary(ast), isObjectShorthandExpression: this.isInsideObjectShorthandExpression, isWrite, }); } private _isPartOfNarrowingTernary(read: PropertyRead | PropertyWrite) { // Note: We do not safe check that the reads are fully matching 1:1. This is acceptable // as worst case we just skip an input from being migrated. This is very unlikely too. return this.insideConditionalExpressionsWithReads.some( (r): r is PropertyRead | PropertyWrite | SafePropertyRead => (r instanceof PropertyRead || r instanceof PropertyWrite || r instanceof SafePropertyRead) && r.name === read.name, ); } } /** * Emulates an access to a given field using the TypeScript `ts.Type` * of the given class. The resolved symbol of the access is returned. */ function traverseReceiverAndLookupSymbol( readOrWrite: PropertyRead | PropertyWrite, componentClass: ts.ClassDeclaration & {name: ts.Identifier}, checker: ts.TypeChecker, ) { const path: string[] = [readOrWrite.name]; let node = readOrWrite; while (node.receiver instanceof PropertyRead || node.receiver instanceof PropertyWrite) { node = node.receiver; path.unshift(node.name); } if (!(node.receiver instanceof ImplicitReceiver || node.receiver instanceof ThisReceiver)) { return null; } const classType = checker.getTypeAtLocation(componentClass.name); return ( lookupPropertyAccess(checker, classType, path, { // Necessary to avoid breaking the resolution if there is // some narrowing involved. E.g. `myClass ? myClass.input`. ignoreNullability: true, })?.symbol ?? null ); } /** Whether the given node refers to a two-way binding AST node. */ function isTwoWayBindingNode(node: unknown): boolean { return ( (node instanceof BoundAttribute && node.type === BindingType.TwoWay) || (node instanceof BoundEvent && node.type === ParsedEventType.TwoWay) ); }
{ "end_byte": 16232, "start_byte": 8072, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/passes/reference_resolution/template_reference_visitor.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/convert-input/convert_to_signal.ts_0_8077
/** * @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 assert from 'assert'; import ts from 'typescript'; import {ConvertInputPreparation} from './prepare_and_check'; import {DecoratorInputTransform} from '@angular/compiler-cli/src/ngtsc/metadata'; import {ImportManager} from '@angular/compiler-cli/src/ngtsc/translator'; import {removeFromUnionIfPossible} from '../utils/remove_from_union'; import {MigrationResult} from '../result'; import {ProgramInfo, projectFile, Replacement, TextUpdate} from '../../../../utils/tsurge'; import {insertPrecedingLine} from '../../../../utils/tsurge/helpers/ast/insert_preceding_line'; import {cutStringToLineLimit} from '../../../../utils/tsurge/helpers/string_manipulation/cut_string_line_length'; // TODO: Consider initializations inside the constructor. Those are not migrated right now // though, as they are writes. /** * Converts an `@Input()` property declaration to a signal input. * * @returns Replacements for converting the input. */ export function convertToSignalInput( node: ts.PropertyDeclaration, { resolvedMetadata: metadata, resolvedType, preferShorthandIfPossible, originalInputDecorator, initialValue, leadingTodoText, }: ConvertInputPreparation, info: ProgramInfo, checker: ts.TypeChecker, importManager: ImportManager, result: MigrationResult, ): Replacement[] { let optionsLiteral: ts.ObjectLiteralExpression | null = null; // We need an options array for the input because: // - the input is either aliased, // - or we have a transform. if (metadata.bindingPropertyName !== metadata.classPropertyName || metadata.transform !== null) { const properties: ts.ObjectLiteralElementLike[] = []; if (metadata.bindingPropertyName !== metadata.classPropertyName) { properties.push( ts.factory.createPropertyAssignment( 'alias', ts.factory.createStringLiteral(metadata.bindingPropertyName), ), ); } if (metadata.transform !== null) { const transformRes = extractTransformOfInput(metadata.transform, resolvedType, checker); properties.push(transformRes.node); // Propagate TODO if one was requested from the transform extraction/validation. if (transformRes.leadingTodoText !== null) { leadingTodoText = (leadingTodoText ? `${leadingTodoText} ` : '') + transformRes.leadingTodoText; } } optionsLiteral = ts.factory.createObjectLiteralExpression(properties); } // The initial value is `undefined` or none is present: // - We may be able to use the `input()` shorthand // - or we use an explicit `undefined` initial value. if (initialValue === undefined) { // Shorthand not possible, so explicitly add `undefined`. if (preferShorthandIfPossible === null) { initialValue = ts.factory.createIdentifier('undefined'); } else { resolvedType = preferShorthandIfPossible.originalType; // When using the `input()` shorthand, try cutting of `undefined` from potential // union types. `undefined` will be automatically included in the type. if (ts.isUnionTypeNode(resolvedType)) { resolvedType = removeFromUnionIfPossible( resolvedType, (t) => t.kind !== ts.SyntaxKind.UndefinedKeyword, ); } } } const inputArgs: ts.Expression[] = []; const typeArguments: ts.TypeNode[] = []; if (resolvedType !== undefined) { typeArguments.push(resolvedType); if (metadata.transform !== null) { // Note: The TCB code generation may use the same type node and attach // synthetic comments for error reporting. We remove those explicitly here. typeArguments.push(ts.setSyntheticTrailingComments(metadata.transform.type.node, undefined)); } } // Always add an initial value when the input is optional, and we have one, or we need one // to be able to pass options as the second argument. if (!metadata.required && (initialValue !== undefined || optionsLiteral !== null)) { inputArgs.push(initialValue ?? ts.factory.createIdentifier('undefined')); } if (optionsLiteral !== null) { inputArgs.push(optionsLiteral); } const inputFnRef = importManager.addImport({ exportModuleSpecifier: '@angular/core', exportSymbolName: 'input', requestedFile: node.getSourceFile(), }); const inputInitializerFn = metadata.required ? ts.factory.createPropertyAccessExpression(inputFnRef, 'required') : inputFnRef; const inputInitializer = ts.factory.createCallExpression( inputInitializerFn, typeArguments, inputArgs, ); let modifiersWithoutInputDecorator = node.modifiers?.filter((m) => m !== originalInputDecorator.node) ?? []; // Add `readonly` to all new signal input declarations. if (!modifiersWithoutInputDecorator?.some((s) => s.kind === ts.SyntaxKind.ReadonlyKeyword)) { modifiersWithoutInputDecorator.push(ts.factory.createModifier(ts.SyntaxKind.ReadonlyKeyword)); } const newNode = ts.factory.createPropertyDeclaration( modifiersWithoutInputDecorator, node.name, undefined, undefined, inputInitializer, ); const newPropertyText = result.printer.printNode( ts.EmitHint.Unspecified, newNode, node.getSourceFile(), ); const replacements: Replacement[] = []; if (leadingTodoText !== null) { replacements.push( insertPrecedingLine(node, info, '// TODO: Notes from signal input migration:'), ...cutStringToLineLimit(leadingTodoText, 70).map((line) => insertPrecedingLine(node, info, `// ${line}`), ), ); } replacements.push( new Replacement( projectFile(node.getSourceFile(), info), new TextUpdate({ position: node.getStart(), end: node.getEnd(), toInsert: newPropertyText, }), ), ); return replacements; } /** * Extracts the transform for the given input and returns a property assignment * that works for the new signal `input()` API. */ function extractTransformOfInput( transform: DecoratorInputTransform, resolvedType: ts.TypeNode | undefined, checker: ts.TypeChecker, ): {node: ts.PropertyAssignment; leadingTodoText: string | null} { assert(ts.isExpression(transform.node), `Expected transform to be an expression.`); let transformFn: ts.Expression = transform.node; let leadingTodoText: string | null = null; // If there is an explicit type, check if the transform return type actually works. // In some cases, the transform function is not compatible because with decorator inputs, // those were not checked. We cast the transform to `any` and add a TODO. // TODO: Capture this in the design doc. if (resolvedType !== undefined && !ts.isSyntheticExpression(resolvedType)) { // Note: If the type is synthetic, we cannot check, and we accept that in the worst case // we will create code that is not necessarily compiling. This is unlikely, but notably // the errors would be correct and valuable. const transformType = checker.getTypeAtLocation(transform.node); const transformSignature = transformType.getCallSignatures()[0]; assert(transformSignature !== undefined, 'Expected transform to be an invoke-able.'); if ( !checker.isTypeAssignableTo( checker.getReturnTypeOfSignature(transformSignature), checker.getTypeFromTypeNode(resolvedType), ) ) { leadingTodoText = 'Input type is incompatible with transform. The migration added an `any` cast. ' + 'This worked previously because Angular was unable to check transforms.'; transformFn = ts.factory.createAsExpression( ts.factory.createParenthesizedExpression(transformFn), ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), ); } } return { node: ts.factory.createPropertyAssignment('transform', transformFn), leadingTodoText, }; }
{ "end_byte": 8077, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/convert-input/convert_to_signal.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/convert-input/prepare_and_check.ts_0_8319
/** * @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 ts from 'typescript'; import {ExtractedInput} from '../input_detection/input_decorator'; import { FieldIncompatibility, FieldIncompatibilityReason, } from '../passes/problematic_patterns/incompatibility'; import {InputNode} from '../input_detection/input_node'; import {Decorator} from '@angular/compiler-cli/src/ngtsc/reflection'; import assert from 'assert'; import {NgCompilerOptions} from '@angular/compiler-cli/src/ngtsc/core/api'; /** * Interface describing analysis performed when the input * was verified to be convert-able. */ export interface ConvertInputPreparation { resolvedType: ts.TypeNode | undefined; preferShorthandIfPossible: {originalType: ts.TypeNode} | null; requiredButIncludedUndefinedPreviously: boolean; resolvedMetadata: ExtractedInput; originalInputDecorator: Decorator; initialValue: ts.Expression | undefined; leadingTodoText: string | null; } /** * Prepares a potential migration of the given node by performing * initial analysis and checking whether it an be migrated. * * For example, required inputs that don't have an explicit type may not * be migrated as we don't have a good type for `input.required<T>`. * (Note: `typeof Bla` may be usable— but isn't necessarily a good practice * for complex expressions) */ export function prepareAndCheckForConversion( node: InputNode, metadata: ExtractedInput, checker: ts.TypeChecker, options: NgCompilerOptions, ): FieldIncompatibility | ConvertInputPreparation { // Accessor inputs cannot be migrated right now. if (ts.isAccessor(node)) { return { context: node, reason: FieldIncompatibilityReason.Accessor, }; } assert( metadata.inputDecorator !== null, 'Expected an input decorator for inputs that are being migrated.', ); let initialValue = node.initializer; let isUndefinedInitialValue = node.initializer === undefined || (ts.isIdentifier(node.initializer) && node.initializer.text === 'undefined'); const strictNullChecksEnabled = options.strict === true || options.strictNullChecks === true; const strictPropertyInitialization = options.strict === true || options.strictPropertyInitialization === true; // Shorthand should never be used, as would expand the type of `T` to be `T|undefined`. // This wouldn't matter with strict null checks disabled, but it can break if this is // a library that is later consumed with strict null checks enabled. const avoidTypeExpansion = !strictNullChecksEnabled; // If an input can be required, due to the non-null assertion on the property, // make it required if there is no initializer. if (node.exclamationToken !== undefined && initialValue === undefined) { metadata.required = true; } let typeToAdd: ts.TypeNode | undefined = node.type; let preferShorthandIfPossible: {originalType: ts.TypeNode} | null = null; // If there is no initial value, or it's `undefined`, we can prefer the `input()` // shorthand which automatically uses `undefined` as initial value, and includes it // in the input type. if ( !metadata.required && node.type !== undefined && isUndefinedInitialValue && !avoidTypeExpansion ) { preferShorthandIfPossible = {originalType: node.type}; } // If the input is using `@Input() bla?: string;` with the "optional question mark", // then we try to explicitly add `undefined` as type, if it's not part of the type already. // This is ensuring correctness, as `bla?` automatically includes `undefined` currently. if (node.questionToken !== undefined) { // If there is no type, but we have an initial value, try inferring // it from the initializer. if (typeToAdd === undefined && initialValue !== undefined) { const inferredType = inferImportableTypeForInput(checker, node, initialValue); if (inferredType !== null) { typeToAdd = inferredType; } } if (typeToAdd === undefined) { return { context: node, reason: FieldIncompatibilityReason.SignalInput__QuestionMarkButNoGoodExplicitTypeExtractable, }; } if ( !checker.isTypeAssignableTo( checker.getUndefinedType(), checker.getTypeFromTypeNode(typeToAdd), ) ) { typeToAdd = ts.factory.createUnionTypeNode([ typeToAdd, ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword), ]); } } let leadingTodoText: string | null = null; // If the input does not have an initial value, and strict property initialization // is disabled, while strict null checks are enabled; then we know that `undefined` // cannot be used as initial value, nor do we want to expand the input's type magically. // Instead, we detect this case and migrate to `undefined!` which leaves the behavior unchanged. if ( strictNullChecksEnabled && !strictPropertyInitialization && node.initializer === undefined && node.type !== undefined && node.questionToken === undefined && node.exclamationToken === undefined && metadata.required === false && !checker.isTypeAssignableTo(checker.getUndefinedType(), checker.getTypeFromTypeNode(node.type)) ) { leadingTodoText = 'Input is initialized to `undefined` but type does not allow this value. ' + 'This worked with `@Input` because your project uses `--strictPropertyInitialization=false`.'; isUndefinedInitialValue = false; initialValue = ts.factory.createNonNullExpression(ts.factory.createIdentifier('undefined')); } // Attempt to extract type from input initial value. No explicit type, but input is required. // Hence we need an explicit type, or fall back to `typeof`. if (typeToAdd === undefined && initialValue !== undefined && metadata.required) { const inferredType = inferImportableTypeForInput(checker, node, initialValue); if (inferredType !== null) { typeToAdd = inferredType; } else { // Note that we could use `typeToTypeNode` here but it's likely breaking because // the generated type might depend on imports that we cannot add here (nor want). return { context: node, reason: FieldIncompatibilityReason.SignalInput__RequiredButNoGoodExplicitTypeExtractable, }; } } return { requiredButIncludedUndefinedPreviously: metadata.required && node.questionToken !== undefined, resolvedMetadata: metadata, resolvedType: typeToAdd, preferShorthandIfPossible, originalInputDecorator: metadata.inputDecorator, initialValue: isUndefinedInitialValue ? undefined : initialValue, leadingTodoText, }; } function inferImportableTypeForInput( checker: ts.TypeChecker, node: InputNode, initialValue: ts.Node, ): ts.TypeNode | null { const propertyType = checker.getTypeAtLocation(node); // If the resolved type is a primitive, or union of primitive types, // return a type node fully derived from the resolved type. if ( isPrimitiveImportableTypeNode(propertyType) || (propertyType.isUnion() && propertyType.types.every(isPrimitiveImportableTypeNode)) ) { return checker.typeToTypeNode(propertyType, node, ts.NodeBuilderFlags.NoTypeReduction) ?? null; } // Alternatively, try to infer a simple importable type from\ // the initializer. if (ts.isIdentifier(initialValue)) { // @Input({required: true}) bla = SOME_DEFAULT; return ts.factory.createTypeQueryNode(initialValue); } else if ( ts.isPropertyAccessExpression(initialValue) && ts.isIdentifier(initialValue.name) && ts.isIdentifier(initialValue.expression) ) { // @Input({required: true}) bla = prop.SOME_DEFAULT; return ts.factory.createTypeQueryNode( ts.factory.createQualifiedName(initialValue.name, initialValue.expression), ); } return null; } function isPrimitiveImportableTypeNode(type: ts.Type): boolean { return !!( type.flags & ts.TypeFlags.BooleanLike || type.flags & ts.TypeFlags.StringLike || type.flags & ts.TypeFlags.NumberLike || type.flags & ts.TypeFlags.Undefined || type.flags & ts.TypeFlags.Null ); }
{ "end_byte": 8319, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/convert-input/prepare_and_check.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/utils/unwrap_parent.ts_0_591
/** * @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 ts from 'typescript'; /** * Unwraps the parent of the given node, if it's a * parenthesized expression or `as` expression. */ export function unwrapParent(node: ts.Node): ts.Node { if (ts.isParenthesizedExpression(node.parent)) { return unwrapParent(node.parent); } else if (ts.isAsExpression(node.parent)) { return unwrapParent(node.parent); } return node; }
{ "end_byte": 591, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/utils/unwrap_parent.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/utils/write_operators.ts_0_878
/** * @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 ts from 'typescript'; /** * List of binary operators that indicate a write operation. * * Useful for figuring out whether an expression assigns to * something or not. */ export const writeBinaryOperators: ts.BinaryOperator[] = [ ts.SyntaxKind.EqualsToken, ts.SyntaxKind.BarBarEqualsToken, ts.SyntaxKind.BarEqualsToken, ts.SyntaxKind.AmpersandEqualsToken, ts.SyntaxKind.AmpersandAmpersandEqualsToken, ts.SyntaxKind.SlashEqualsToken, ts.SyntaxKind.MinusEqualsToken, ts.SyntaxKind.PlusEqualsToken, ts.SyntaxKind.CaretEqualsToken, ts.SyntaxKind.PercentEqualsToken, ts.SyntaxKind.AsteriskEqualsToken, ts.SyntaxKind.ExclamationEqualsToken, ];
{ "end_byte": 878, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/utils/write_operators.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/utils/input_id.ts_0_2365
/** * @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 ts from 'typescript'; import {InputNode} from '../input_detection/input_node'; import {ProgramInfo, projectFile} from '../../../../utils/tsurge'; import {MigrationHost} from '../migration_host'; import { ClassFieldDescriptor, ClassFieldUniqueKey, } from '../passes/reference_resolution/known_fields'; /** * Interface that describes an input recognized in the * migration and project. */ export interface InputDescriptor extends ClassFieldDescriptor { node: InputNode; } /** * Gets the descriptor for the given input node. * * An input descriptor describes a recognized input in the * whole project (regardless of batching) and allows easy * access to the associated TypeScript declaration node, while * also providing a unique key for the input that can be used * for serializable communication between compilation units * (e.g. when running via batching; in e.g. go/tsunami). */ export function getInputDescriptor(host: MigrationHost, node: InputNode): InputDescriptor; export function getInputDescriptor(info: ProgramInfo, node: InputNode): InputDescriptor; export function getInputDescriptor( hostOrInfo: ProgramInfo | MigrationHost, node: InputNode, ): InputDescriptor { let className: string; if (ts.isAccessor(node)) { className = node.parent.name?.text || '<anonymous>'; } else { className = node.parent.name?.text ?? '<anonymous>'; } const info = hostOrInfo instanceof MigrationHost ? hostOrInfo.programInfo : hostOrInfo; const file = projectFile(node.getSourceFile(), info); // Inputs may be detected in `.d.ts` files. Ensure that if the file IDs // match regardless of extension. E.g. `/google3/blaze-out/bin/my_file.ts` should // have the same ID as `/google3/my_file.ts`. const id = file.id.replace(/\.d\.ts$/, '.ts'); return { key: `${id}@@${className}@@${node.name.text}` as unknown as ClassFieldUniqueKey, node, }; } /** Whether the given value is an input descriptor. */ export function isInputDescriptor(v: unknown): v is InputDescriptor { return ( (v as Partial<InputDescriptor>).key !== undefined && (v as Partial<InputDescriptor>).node !== undefined ); }
{ "end_byte": 2365, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/utils/input_id.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/utils/inheritance_sort.ts_0_1921
/** * @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 */ export interface GraphNode<T> { data: T; incoming: Set<GraphNode<T>>; outgoing: Set<GraphNode<T>>; } /** * Sorts the inheritance graph topologically, so that * nodes without incoming edges are returned first. * * I.e. The returned list is sorted, so that dependencies * of a given class are guaranteed to be included at * an earlier position than the inspected class. * * This sort is helpful for detecting inheritance problems * for the migration in simpler ways, without having to * check in both directions (base classes, and derived classes). */ export function topologicalSort<T>(graph: GraphNode<T>[]) { // All nodes without incoming edges. const S = graph.filter((n) => n.incoming.size === 0); const result: GraphNode<T>[] = []; const invalidatedEdges = new WeakMap<GraphNode<T>, WeakSet<GraphNode<T>>>(); const invalidateEdge = (from: GraphNode<T>, to: GraphNode<T>) => { if (!invalidatedEdges.has(from)) { invalidatedEdges.set(from, new Set()); } invalidatedEdges.get(from)!.add(to); }; const filterEdges = (from: GraphNode<T>, edges: Set<GraphNode<T>>) => { return Array.from(edges).filter( (e) => !invalidatedEdges.has(from) || !invalidatedEdges.get(from)!.has(e), ); }; while (S.length) { const node = S.pop()!; result.push(node); for (const next of filterEdges(node, node.outgoing)) { // Remove edge from "node -> next". invalidateEdge(node, next); // Remove edge from "next -> node". invalidateEdge(next, node); // if there are no incoming edges for `next`. add it to `S`. if (filterEdges(next, next.incoming).length === 0) { S.push(next); } } } return result; }
{ "end_byte": 1921, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/utils/inheritance_sort.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/utils/extract_template.ts_0_3000
/** * @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 ts from 'typescript'; import {ReflectionHost, reflectObjectLiteral} from '@angular/compiler-cli/src/ngtsc/reflection'; import {MigrationHost} from '../migration_host'; import {getAngularDecorators, ResourceLoader} from '@angular/compiler-cli/src/ngtsc/annotations'; import {PartialEvaluator} from '@angular/compiler-cli/src/ngtsc/partial_evaluator'; import { ExternalTemplateDeclaration, InlineTemplateDeclaration, } from '@angular/compiler-cli/src/ngtsc/annotations/component/src/resources'; import {DEFAULT_INTERPOLATION_CONFIG} from '@angular/compiler'; /** * Attempts to extract the `TemplateDefinition` for the given * class, if possible. * * The definition can then be used with the Angular compiler to * load/parse the given template. */ export function attemptExtractTemplateDefinition( node: ts.ClassDeclaration, checker: ts.TypeChecker, reflector: ReflectionHost, resourceLoader: ResourceLoader, ): InlineTemplateDeclaration | ExternalTemplateDeclaration | null { const classDecorators = reflector.getDecoratorsOfDeclaration(node); const evaluator = new PartialEvaluator(reflector, checker, null); const ngDecorators = classDecorators !== null ? getAngularDecorators(classDecorators, ['Component'], /* isAngularCore */ false) : []; if ( ngDecorators.length === 0 || ngDecorators[0].args === null || ngDecorators[0].args.length === 0 || !ts.isObjectLiteralExpression(ngDecorators[0].args[0]) ) { return null; } const properties = reflectObjectLiteral(ngDecorators[0].args[0]); const templateProp = properties.get('template'); const templateUrlProp = properties.get('templateUrl'); const containingFile = node.getSourceFile().fileName; // inline template. if (templateProp !== undefined) { const templateStr = evaluator.evaluate(templateProp); if (typeof templateStr === 'string') { return { isInline: true, expression: templateProp, interpolationConfig: DEFAULT_INTERPOLATION_CONFIG, preserveWhitespaces: false, resolvedTemplateUrl: containingFile, templateUrl: containingFile, } as InlineTemplateDeclaration; } } try { // external template. if (templateUrlProp !== undefined) { const templateUrl = evaluator.evaluate(templateUrlProp); if (typeof templateUrl === 'string') { return { isInline: false, interpolationConfig: DEFAULT_INTERPOLATION_CONFIG, preserveWhitespaces: false, templateUrlExpression: templateUrlProp, templateUrl, resolvedTemplateUrl: resourceLoader.resolve(templateUrl, containingFile), }; } } } catch (e) { console.error(`Could not parse external template: ${e}`); } return null; }
{ "end_byte": 3000, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/utils/extract_template.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/utils/class_member_names.ts_0_597
/** * @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 ts from 'typescript'; export function getMemberName(member: ts.ClassElement | ts.PropertyAssignment): string | null { if (member.name === undefined) { return null; } if (ts.isIdentifier(member.name) || ts.isStringLiteralLike(member.name)) { return member.name.text; } if (ts.isPrivateIdentifier(member.name)) { return `#${member.name.text}`; } return null; }
{ "end_byte": 597, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/utils/class_member_names.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/utils/unique_names.ts_0_1650
/** * @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 ts from 'typescript'; import {isIdentifierFreeInScope, ReservedMarker} from './is_identifier_free_in_scope'; /** * Helper that can generate unique identifier names at a * given location. * * Used for generating unique names to extract input reads * to support narrowing. */ export class UniqueNamesGenerator { constructor(private readonly fallbackSuffixes: string[]) {} generate(base: string, location: ts.Node): string { const checkNameAndClaimIfAvailable = (name: string): boolean => { const freeInfo = isIdentifierFreeInScope(name, location); if (freeInfo === null) { return false; } // Claim the locals to avoid conflicts with future generations. freeInfo.container.locals ??= new Map(); freeInfo.container.locals.set(name, ReservedMarker); return true; }; // Check the base name. Ideally, we'd use this one. if (checkNameAndClaimIfAvailable(base)) { return base; } // Try any of the possible suffixes. for (const suffix of this.fallbackSuffixes) { const name = `${base}${suffix}`; if (checkNameAndClaimIfAvailable(name)) { return name; } } // Worst case, suffix the base name with a unique number until // we find an available name. let name = null; let counter = 1; do { name = `${base}_${counter++}`; } while (!checkNameAndClaimIfAvailable(name)); return name; } }
{ "end_byte": 1650, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/utils/unique_names.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/utils/is_identifier_free_in_scope.ts_0_4406
/** * @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 assert from 'assert'; import ts from 'typescript'; import {isNodeDescendantOf} from './is_descendant_of'; /** Symbol that can be used to mark a variable as reserved, synthetically. */ export const ReservedMarker = Symbol(); // typescript/stable/src/compiler/types.ts;l=967;rcl=651008033 export interface LocalsContainer extends ts.Node { locals?: Map<string, ts.Symbol | typeof ReservedMarker>; nextContainer?: LocalsContainer; } /** * Gets whether the given identifier name is free for use in the * given location, avoiding shadowed variable names. * */ export function isIdentifierFreeInScope( name: string, location: ts.Node, ): null | {container: LocalsContainer} { const startContainer = findClosestParentLocalsContainer(location); assert(startContainer !== undefined, 'Expecting a locals container.'); // Traverse up and check for potential collisions. let container: LocalsContainer | undefined = startContainer; let firstNextContainer: LocalsContainer | undefined = undefined; while (container !== undefined) { if (!isIdentifierFreeInContainer(name, container)) { return null; } if (firstNextContainer === undefined && container.nextContainer !== undefined) { firstNextContainer = container.nextContainer; } container = findClosestParentLocalsContainer(container.parent); } // Check descendent local containers to avoid shadowing variables. // Note that this is not strictly needed, but it's helping avoid // some lint errors, like TSLint's no shadowed variables. container = firstNextContainer; while (container && isNodeDescendantOf(container, startContainer)) { if (!isIdentifierFreeInContainer(name, container)) { return null; } container = container.nextContainer; } return {container: startContainer}; } /** Finds the closest parent locals container. */ function findClosestParentLocalsContainer(node: ts.Node): LocalsContainer | undefined { return ts.findAncestor(node, isLocalsContainer); } /** Whether the given identifier is free in the given locals container. */ function isIdentifierFreeInContainer(name: string, container: LocalsContainer): boolean { if (container.locals === undefined || !container.locals.has(name)) { return true; } // We consider alias symbols as locals conservatively. // Note: This check is similar to the check by the TypeScript emitter. // typescript/stable/src/compiler/emitter.ts;l=5436;rcl=651008033 const local = container.locals.get(name)!; return ( local !== ReservedMarker && !(local.flags & (ts.SymbolFlags.Value | ts.SymbolFlags.ExportValue | ts.SymbolFlags.Alias)) ); } /** * Whether the given node can contain local variables. * * Note: This is similar to TypeScript's `canHaveLocals` internal helper. * typescript/stable/src/compiler/utilitiesPublic.ts;l=2265;rcl=651008033 */ function isLocalsContainer(node: ts.Node): node is LocalsContainer { switch (node.kind) { case ts.SyntaxKind.ArrowFunction: case ts.SyntaxKind.Block: case ts.SyntaxKind.CallSignature: case ts.SyntaxKind.CaseBlock: case ts.SyntaxKind.CatchClause: case ts.SyntaxKind.ClassStaticBlockDeclaration: case ts.SyntaxKind.ConditionalType: case ts.SyntaxKind.Constructor: case ts.SyntaxKind.ConstructorType: case ts.SyntaxKind.ConstructSignature: case ts.SyntaxKind.ForStatement: case ts.SyntaxKind.ForInStatement: case ts.SyntaxKind.ForOfStatement: case ts.SyntaxKind.FunctionDeclaration: case ts.SyntaxKind.FunctionExpression: case ts.SyntaxKind.FunctionType: case ts.SyntaxKind.GetAccessor: case ts.SyntaxKind.IndexSignature: case ts.SyntaxKind.JSDocCallbackTag: case ts.SyntaxKind.JSDocEnumTag: case ts.SyntaxKind.JSDocFunctionType: case ts.SyntaxKind.JSDocSignature: case ts.SyntaxKind.JSDocTypedefTag: case ts.SyntaxKind.MappedType: case ts.SyntaxKind.MethodDeclaration: case ts.SyntaxKind.MethodSignature: case ts.SyntaxKind.ModuleDeclaration: case ts.SyntaxKind.SetAccessor: case ts.SyntaxKind.SourceFile: case ts.SyntaxKind.TypeAliasDeclaration: return true; default: return false; } }
{ "end_byte": 4406, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/utils/is_identifier_free_in_scope.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/utils/heritage_types.ts_0_748
/** * @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 ts from 'typescript'; /** Gets all types that are inherited (implemented or extended). */ export function getInheritedTypes( node: ts.ClassLikeDeclaration | ts.InterfaceDeclaration, checker: ts.TypeChecker, ): ts.Type[] { if (node.heritageClauses === undefined) { return []; } const heritageTypes: ts.Type[] = []; for (const heritageClause of node.heritageClauses) { for (const typeNode of heritageClause.types) { heritageTypes.push(checker.getTypeFromTypeNode(typeNode)); } } return heritageTypes; }
{ "end_byte": 748, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/utils/heritage_types.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/utils/remove_from_union.ts_0_693
/** * @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 ts from 'typescript'; export function removeFromUnionIfPossible( union: ts.UnionTypeNode, filter: (v: ts.TypeNode) => boolean, ): ts.TypeNode { const filtered = union.types.filter(filter); if (filtered.length === union.types.length) { return union; } // If there is only item at this point, avoid the union structure. if (filtered.length === 1) { return filtered[0]; } return ts.factory.updateUnionTypeNode(union, ts.factory.createNodeArray(filtered)); }
{ "end_byte": 693, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/utils/remove_from_union.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/utils/inheritance_graph.ts_0_4679
/** * @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 ts from 'typescript'; import {getInheritedTypes} from './heritage_types'; /** * Node captured in the inheritance graph. */ export type GraphNode = ts.ClassDeclaration | ts.ClassExpression | ts.InterfaceDeclaration; /** * Inheritance graph tracks edges between classes that describe * heritage. * * This graph is helpful for efficient lookups whether e.g. an input * is overridden, or inherited etc. This is helpful when detecting * and propagating input incompatibility statuses. */ export class InheritanceGraph { /** Maps nodes to their parent nodes. */ classToParents = new Map<GraphNode, GraphNode[]>(); /** Maps nodes to their derived nodes. */ parentToChildren = new Map<GraphNode, GraphNode[]>(); /** All classes seen participating in inheritance chains. */ allClassesInInheritance = new Set<GraphNode>(); constructor(private checker: ts.TypeChecker) {} /** Registers a given class in the graph. */ registerClass(clazz: GraphNode, parents: GraphNode[]) { this.classToParents.set(clazz, parents); this.allClassesInInheritance.add(clazz); for (const parent of parents) { this.allClassesInInheritance.add(parent); if (!this.parentToChildren.has(parent)) { this.parentToChildren.set(parent, []); } this.parentToChildren.get(parent)!.push(clazz); } } /** * Checks if the given class has overlapping members, either * inherited or derived. * * @returns Symbols of the inherited or derived members, if they exist. */ checkOverlappingMembers( clazz: GraphNode, member: ts.ClassElement, memberName: string, ): { inherited: ts.Symbol | undefined; derivedMembers: ts.Symbol[]; } { const inheritedTypes = (this.classToParents.get(clazz) ?? []).map((c) => this.checker.getTypeAtLocation(c), ); const derivedLeafs = this._traceDerivedChainToLeafs(clazz).map((c) => this.checker.getTypeAtLocation(c), ); const inheritedMember = inheritedTypes .map((t) => t.getProperty(memberName)) .find((m) => m !== undefined); const derivedMembers = derivedLeafs .map((t) => t.getProperty(memberName)) // Skip members that point back to the current class element. The derived type // might look up back to our starting point— which we ignore. .filter((m): m is ts.Symbol => m !== undefined && m.valueDeclaration !== member); return {inherited: inheritedMember, derivedMembers}; } /** Gets all leaf derived classes that extend from the given class. */ private _traceDerivedChainToLeafs(clazz: GraphNode): GraphNode[] { const queue = [clazz]; const leafs: GraphNode[] = []; while (queue.length) { const node = queue.shift()!; if (!this.parentToChildren.has(node)) { if (node !== clazz) { leafs.push(node); } continue; } queue.push(...this.parentToChildren.get(node)!); } return leafs; } /** Gets all derived classes of the given node. */ traceDerivedClasses(clazz: GraphNode): GraphNode[] { const queue = [clazz]; const derived: GraphNode[] = []; while (queue.length) { const node = queue.shift()!; if (node !== clazz) { derived.push(node); } if (!this.parentToChildren.has(node)) { continue; } queue.push(...this.parentToChildren.get(node)!); } return derived; } /** * Populates the graph. * * NOTE: This is expensive and should be called with caution. */ expensivePopulate(files: readonly ts.SourceFile[]) { for (const file of files) { const visitor = (node: ts.Node) => { if ( (ts.isClassLike(node) || ts.isInterfaceDeclaration(node)) && node.heritageClauses !== undefined ) { const heritageTypes = getInheritedTypes(node, this.checker); const parents = heritageTypes // Interfaces participate in the graph and are not "value declarations". // Also, symbol may be undefined for unresolvable nodes. .map((t) => (t.symbol ? t.symbol.declarations?.[0] : undefined)) .filter( (d): d is GraphNode => d !== undefined && (ts.isClassLike(d) || ts.isInterfaceDeclaration(d)), ); this.registerClass(node, parents); } ts.forEachChild(node, visitor); }; ts.forEachChild(file, visitor); } return this; } }
{ "end_byte": 4679, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/utils/inheritance_graph.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/utils/traverse_access.ts_0_1033
/** * @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 ts from 'typescript'; /** * Expands the given reference to its containing expression, capturing * the full context. * * E.g. `traverseAccess(ref<`bla`>)` may return `this.bla` * or `traverseAccess(ref<`bla`>)` may return `this.someObj.a.b.c.bla`. * * This helper is useful as we will replace the full access with a temporary * variable for narrowing. Replacing just the identifier is wrong. */ export function traverseAccess( access: ts.Identifier, ): ts.Identifier | ts.PropertyAccessExpression | ts.ElementAccessExpression { if (ts.isPropertyAccessExpression(access.parent) && access.parent.name === access) { return access.parent; } else if ( ts.isElementAccessExpression(access.parent) && access.parent.argumentExpression === access ) { return access.parent; } return access; }
{ "end_byte": 1033, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/utils/traverse_access.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/utils/binding_elements.ts_0_1066
/** * @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 ts from 'typescript'; /** Gets the pattern and property name for a given binding element. */ export function resolveBindingElement(node: ts.BindingElement): { pattern: ts.BindingPattern; propertyName: string; } | null { const name = node.propertyName ?? node.name; // If we are discovering a non-analyzable element in the path, abort. if (!ts.isStringLiteralLike(name) && !ts.isIdentifier(name)) { return null; } return { pattern: node.parent, propertyName: name.text, }; } /** Gets the declaration node of the given binding element. */ export function getBindingElementDeclaration( node: ts.BindingElement, ): ts.VariableDeclaration | ts.ParameterDeclaration { while (true) { if (ts.isBindingElement(node.parent.parent)) { node = node.parent.parent; } else { return node.parent.parent; } } }
{ "end_byte": 1066, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/utils/binding_elements.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/utils/grouped_ts_ast_visitor.ts_0_1430
/** * @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 ts from 'typescript'; /** * Class that allows for efficient grouping of TypeScript node AST * traversal. * * Allows visitors to execute in a single pass when visiting all * children of source files. */ export class GroupedTsAstVisitor { private visitors: Array<(node: ts.Node) => void> = []; private doneFns: Array<() => void> = []; constructor(private files: readonly ts.SourceFile[]) {} state = { insidePropertyDeclaration: null as ts.PropertyDeclaration | null, }; register(visitor: (node: ts.Node) => void, done?: () => void) { this.visitors.push(visitor); if (done !== undefined) { this.doneFns.push(done); } } execute() { const visitor = (node: ts.Node) => { for (const v of this.visitors) { v(node); } if (ts.isPropertyDeclaration(node)) { this.state.insidePropertyDeclaration = node; ts.forEachChild(node, visitor); this.state.insidePropertyDeclaration = null; } else { ts.forEachChild(node, visitor); } }; for (const file of this.files) { ts.forEachChild(file, visitor); } for (const doneFn of this.doneFns) { doneFn(); } this.visitors = []; } }
{ "end_byte": 1430, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/utils/grouped_ts_ast_visitor.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/utils/is_descendant_of.ts_0_498
/** * @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 ts from 'typescript'; /** Whether the given node is a descendant of the given ancestor. */ export function isNodeDescendantOf(node: ts.Node, ancestor: ts.Node | undefined): boolean { while (node) { if (node === ancestor) return true; node = node.parent; } return false; }
{ "end_byte": 498, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/utils/is_descendant_of.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/pattern_advisors/debug_element_component_instance.ts_0_2426
/** * @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 ts from 'typescript'; /** * Detects `query(By.directive(T)).componentInstance` patterns and enhances * them with information of `T`. This is important because `.componentInstance` * is currently typed as `any` and may cause runtime test failures after input * migrations then. * * The reference resolution pass leverages information from this pattern * recognizer. */ export class DebugElementComponentInstance { private cache = new WeakMap<ts.Node, ts.Type | null>(); constructor(private checker: ts.TypeChecker) {} detect(node: ts.Node): ts.Type | null { if (this.cache.has(node)) { return this.cache.get(node)!; } if (!ts.isPropertyAccessExpression(node)) { return null; } // Check for `<>.componentInstance`. if (!ts.isIdentifier(node.name) || node.name.text !== 'componentInstance') { return null; } // Check for `<>.query(..).<>`. if ( !ts.isCallExpression(node.expression) || !ts.isPropertyAccessExpression(node.expression.expression) || !ts.isIdentifier(node.expression.expression.name) || node.expression.expression.name.text !== 'query' ) { return null; } const queryCall: ts.CallExpression = node.expression; if (queryCall.arguments.length !== 1) { return null; } const queryArg = queryCall.arguments[0]; let typeExpr: ts.Node; if ( ts.isCallExpression(queryArg) && queryArg.arguments.length === 1 && ts.isIdentifier(queryArg.arguments[0]) ) { // Detect references, like: `query(By.directive(T))`. typeExpr = queryArg.arguments[0]; } else if (ts.isIdentifier(queryArg)) { // Detect references, like: `harness.query(T)`. typeExpr = queryArg; } else { return null; } const symbol = this.checker.getSymbolAtLocation(typeExpr); if ( symbol?.valueDeclaration === undefined || !ts.isClassDeclaration(symbol?.valueDeclaration) ) { // Cache this as we use the expensive type checker. this.cache.set(node, null); return null; } const type = this.checker.getTypeAtLocation(symbol.valueDeclaration); this.cache.set(node, type); return type; } }
{ "end_byte": 2426, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/pattern_advisors/debug_element_component_instance.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/pattern_advisors/spy_on_pattern.ts_0_1693
/** * @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 ts from 'typescript'; import {ClassFieldDescriptor, KnownFields} from '../passes/reference_resolution/known_fields'; import {ProblematicFieldRegistry} from '../passes/problematic_patterns/problematic_field_registry'; import {FieldIncompatibilityReason} from '../passes/problematic_patterns/incompatibility'; /** * Detects `spyOn(dirInstance, 'myInput')` calls that likely modify * the input signal. There is no way to change the value inside the input signal, * and hence observing is not possible. */ export class SpyOnFieldPattern<D extends ClassFieldDescriptor> { constructor( private checker: ts.TypeChecker, private fields: KnownFields<D> & ProblematicFieldRegistry<D>, ) {} detect(node: ts.Node) { if ( ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'spyOn' && node.arguments.length === 2 && ts.isStringLiteralLike(node.arguments[1]) ) { const spyTargetType = this.checker.getTypeAtLocation(node.arguments[0]); const spyProperty = spyTargetType.getProperty(node.arguments[1].text); if (spyProperty === undefined) { return; } const fieldTarget = this.fields.attemptRetrieveDescriptorFromSymbol(spyProperty); if (fieldTarget === null) { return; } this.fields.markFieldIncompatible(fieldTarget, { reason: FieldIncompatibilityReason.SpyOnThatOverwritesField, context: node, }); } } }
{ "end_byte": 1693, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/pattern_advisors/spy_on_pattern.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/pattern_advisors/partial_directive_type.ts_0_2382
/** * @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 ts from 'typescript'; import {ClassFieldDescriptor, KnownFields} from '../passes/reference_resolution/known_fields'; /** * Recognizes `Partial<T>` instances in Catalyst tests. Those type queries * are likely used for typing property initialization values for the given class `T` * and we have a few scenarios: * * 1. The API does not unwrap signal inputs. In which case, the values are likely no * longer assignable to an `InputSignal`. * 2. The API does unwrap signal inputs, in which case we need to unwrap the `Partial` * because the values are raw initial values, like they were before. * * We can enable this heuristic when we detect Catalyst as we know it supports unwrapping. */ export class PartialDirectiveTypeInCatalystTests<D extends ClassFieldDescriptor> { constructor( private checker: ts.TypeChecker, private knownFields: KnownFields<D>, ) {} detect( node: ts.Node, ): null | {referenceNode: ts.TypeReferenceNode; targetClass: ts.ClassDeclaration} { // Detect `Partial<...>` if ( !ts.isTypeReferenceNode(node) || !ts.isIdentifier(node.typeName) || node.typeName.text !== 'Partial' ) { return null; } // Ignore if the source file doesn't reference Catalyst. if (!node.getSourceFile().text.includes('angular2/testing/catalyst')) { return null; } // Extract T of `Partial<T>`. const cmpTypeArg = node.typeArguments?.[0]; if ( !cmpTypeArg || !ts.isTypeReferenceNode(cmpTypeArg) || !ts.isIdentifier(cmpTypeArg.typeName) ) { return null; } const cmpType = cmpTypeArg.typeName; const symbol = this.checker.getSymbolAtLocation(cmpType); // Note: Technically the class might be derived of an input-containing class, // but this is out of scope for now. We can expand if we see it's a common case. if ( symbol?.valueDeclaration === undefined || !ts.isClassDeclaration(symbol.valueDeclaration) || !this.knownFields.shouldTrackClassReference(symbol.valueDeclaration) ) { return null; } return {referenceNode: node, targetClass: symbol.valueDeclaration}; } }
{ "end_byte": 2382, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/pattern_advisors/partial_directive_type.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/batch/extract.ts_0_1467
/** * @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 {KnownInputs} from '../input_detection/known_inputs'; import {ClassFieldUniqueKey} from '../passes/reference_resolution/known_fields'; import {CompilationUnitData} from './unit_data'; export function getCompilationUnitMetadata(knownInputs: KnownInputs) { const struct: CompilationUnitData = { knownInputs: Array.from(knownInputs.knownInputIds.entries()).reduce( (res, [inputClassFieldIdStr, info]) => { const classIncompatibility = info.container.incompatible !== null ? info.container.incompatible : null; const memberIncompatibility = info.container.memberIncompatibility.has(inputClassFieldIdStr) ? info.container.memberIncompatibility.get(inputClassFieldIdStr)!.reason : null; // Note: Trim off the `context` as it cannot be serialized with e.g. TS nodes. return { ...res, [inputClassFieldIdStr as string & ClassFieldUniqueKey]: { owningClassIncompatibility: classIncompatibility, memberIncompatibility, seenAsSourceInput: info.metadata.inSourceFile, extendsFrom: info.extendsFrom?.key ?? null, }, }; }, {} as CompilationUnitData['knownInputs'], ), }; return struct; }
{ "end_byte": 1467, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/batch/extract.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/batch/unit_data.ts_0_1016
/** * @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 { ClassIncompatibilityReason, FieldIncompatibilityReason, } from '../passes/problematic_patterns/incompatibility'; import {ClassFieldUniqueKey} from '../passes/reference_resolution/known_fields'; /** * Type describing a serializable compilation unit data. * * The metadata files are built for every compilation unit in batching * mode, and can be merged later, and then used as global analysis metadata * when migrating. */ export interface CompilationUnitData { knownInputs: { // Use `string` here so that it's a usable index key. [inputIdKey: string]: { owningClassIncompatibility: ClassIncompatibilityReason | null; memberIncompatibility: FieldIncompatibilityReason | null; seenAsSourceInput: boolean; extendsFrom: ClassFieldUniqueKey | null; }; }; }
{ "end_byte": 1016, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/batch/unit_data.ts" }
angular/packages/core/schematics/migrations/signal-migration/src/batch/populate_global_data.ts_0_1252
/** * @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 {KnownInputs} from '../input_detection/known_inputs'; import {ClassFieldUniqueKey} from '../passes/reference_resolution/known_fields'; import {CompilationUnitData} from './unit_data'; export function populateKnownInputsFromGlobalData( knownInputs: KnownInputs, globalData: CompilationUnitData, ) { // Populate from batch metadata. for (const [_key, info] of Object.entries(globalData.knownInputs)) { const key = _key as unknown as ClassFieldUniqueKey; // irrelevant for this compilation unit. if (!knownInputs.has({key})) { continue; } const inputMetadata = knownInputs.get({key})!; if (info.memberIncompatibility !== null) { knownInputs.markFieldIncompatible(inputMetadata.descriptor, { context: null, // No context serializable. reason: info.memberIncompatibility, }); } if (info.owningClassIncompatibility !== null) { knownInputs.markClassIncompatible( inputMetadata.container.clazz, info.owningClassIncompatibility, ); } } }
{ "end_byte": 1252, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/batch/populate_global_data.ts" }