@pbuilder/sdk 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -559,9 +559,9 @@ conformance-tests a *dialect or op-pack* implementation — not the same audienc
559
559
 
560
560
  When string-level mutation isn't enough — "add an import to this module", "set a prop on
561
561
  this JSX element" — **dialects** provide structured, AST-aware operations for one file
562
- type: see [authoring a dialect](./docs/authoring-a-dialect.md) for the full story. Four
563
- ship today: `@pbuilder/sdk/typescript`, `@pbuilder/sdk/react`, `@pbuilder/sdk/json`, and
564
- `@pbuilder/sdk/yaml`.
562
+ type: see [authoring a dialect](./docs/authoring-a-dialect.md) for the full story. Six
563
+ ship today: `@pbuilder/sdk/typescript`, `@pbuilder/sdk/react`, `@pbuilder/sdk/nestjs`,
564
+ `@pbuilder/sdk/angular`, `@pbuilder/sdk/json`, and `@pbuilder/sdk/yaml`.
565
565
 
566
566
  A dialect's entry point is its own `find(path)`: it opens a **coalescing, awaitable
567
567
  handle**. Every op you chain mutates the same live AST, and the handle serializes to
@@ -581,7 +581,17 @@ await ts.find("src/index.ts")
581
581
  | Op | What it does |
582
582
  |---|---|
583
583
  | `addImport(name, from)` | Adds `import { name } from "from"`, merging into an existing clause from the same module. Idempotent — calling it twice never duplicates the import. |
584
+ | `addDefaultImport(name, from)` | Adds `import name from "from"`, merging into a declaration of that module with no default yet. Rejects a second default under another name. |
585
+ | `addNamespaceImport(name, from)` | Adds `import * as name from "from"`, merging into a default-only declaration; beside named imports it opens its own. |
586
+ | `addTypeImport(name, from)` | Adds `import type { name } from "from"` as its own statement. A no-op when the module already imports `name`, by value or as a type. |
587
+ | `addSideEffectImport(from)` | Adds `import "from"`. A no-op when that bare import already exists. |
588
+ | `addReExport(name, from)` | Adds `export { name } from "from"`, merging into an existing re-export of that module. Rejects a name the file already exports. |
589
+ | `addExportAll(from, { as? })` | Adds `export * from "from"`, or `export * as ns from "from"` with `{ as: "ns" }`. |
584
590
  | `removeImport(name, from)` | Removes the named binding; deletes the whole statement when it was the last one. Idempotent on an absent binding. |
591
+ | `removeExport(name, from)` | Removes a named re-export; deletes the statement when it was the last one. Idempotent on an absent one. |
592
+ | `removeExportAll(from, { as? })` | Removes `export * from "from"` (or the `as` form). Idempotent on an absent one. |
593
+ | `addArrayElement(locator, element)` | Appends to the array literal `locator` points at (a variable, a call argument, or a decorator argument, then a `path` of keys and `{ key: "value" }` matches), keeping its layout. Creates missing keys; a no-op when the element is already listed. `element` is an identifier, or `{ expression }` for code. |
594
+ | `addClassProperty(className, name, initializer, opts?)` | Adds `{scope }{readonly }name = initializer;` to the only class named `className`, after its last property. A no-op when the same property exists; any other member named `name` rejects. |
585
595
  | `addFunction(name, source, opts?)` | Appends a top-level function. `source` **includes** the braces (`"(): void {}"`). |
586
596
  | `addVariable(name, initializer, opts?)` | Appends a top-level variable (`kind` defaults to `const`). |
587
597
  | `addClass(name, source, opts?)` | Appends a top-level class. `source` **excludes** the braces — the op adds them. |
@@ -660,6 +670,44 @@ Extra named ops: `setComment`, `removeComment`, `setAnchor`, `removeAnchor`, `se
660
670
  `addMergeKey`, `setStyle`, `setTag`, `addDocument`, `removeDocument`. `.modify(fn)` exposes
661
671
  [yaml](https://eemeli.org/yaml/). See [the YAML dialect guide](./docs/yaml-dialect.md).
662
672
 
673
+ ### `@pbuilder/sdk/nestjs`
674
+
675
+ Every `@pbuilder/sdk/typescript` op, plus ops that import a class and register it in the
676
+ file's `@Module` decorator, keeping the list's layout.
677
+
678
+ ```ts
679
+ import * as nestjs from "@pbuilder/sdk/nestjs";
680
+
681
+ await nestjs
682
+ .find("src/app.module.ts")
683
+ .addModuleImport("UsersModule", "./users/users.module")
684
+ .addProvider("UsersService", "./users/users.service");
685
+ ```
686
+
687
+ Extra named ops: `addProvider`, `addController`, `addModuleImport`, `addExport`. `.modify(fn)`
688
+ exposes ts-morph. See [the NestJS dialect guide](./docs/nestjs-dialect.md).
689
+
690
+ ### `@pbuilder/sdk/angular`
691
+
692
+ Every `@pbuilder/sdk/typescript` op, plus ops for standalone components, the application's root
693
+ providers, routes, signal inputs, outputs and state, and injected dependencies.
694
+ Each op adds the imports its code needs.
695
+
696
+ ```ts
697
+ import * as angular from "@pbuilder/sdk/angular";
698
+
699
+ await angular.find("src/app/app.config.ts").addRootProvider({ expression: "provideHttpClient(withFetch())" }, [
700
+ { name: "provideHttpClient", from: "@angular/common/http" },
701
+ { name: "withFetch", from: "@angular/common/http" },
702
+ ]);
703
+ await angular.find("src/app/app.routes.ts").addLazyRoute({ path: "admin", loadChildren: "./admin/admin.routes" });
704
+ ```
705
+
706
+ Extra named ops: `addComponentImport`, `addComponentProvider`, `addRootProvider`, `addRoute`,
707
+ `addLazyRoute`, `addInjection`, `addInput`, `addModel`, `addOutput`, `addSignal`, `addComputed`.
708
+ `.modify(fn)` exposes ts-morph. See
709
+ [the Angular dialect guide](./docs/angular-dialect.md).
710
+
663
711
  ### `.modify()` — the universal escape hatch
664
712
 
665
713
  Every dialect handle carries one universal op alongside its named ops: `.modify(ast => …)`.
@@ -10,7 +10,12 @@ export declare function assertValidElementName(elementName: string): void;
10
10
  * `IdentifierName` (including reserved words) — `import { name }` requires a `BindingIdentifier`,
11
11
  * so a reserved-word check (V5, SEC-1) runs alongside the denylist.
12
12
  */
13
- export declare function assertValidImportBinding(name: string): void;
13
+ export declare function assertValidImportBinding(name: string, argName?: string): void;
14
+ /**
15
+ * A plain-identifier object key. Reserved words are legal keys (`{ default: 1 }`), so only the
16
+ * grammar and the denylist apply: a created `__proto__: [...]` would set the prototype.
17
+ */
18
+ export declare function assertValidPropertyKey(key: string, argName: string): void;
14
19
  /**
15
20
  * The single validate-before-mutate chokepoint (ADR-02): `validators` runs first over the
16
21
  * op's full argument tuple and throws via `dialectError` on any failure — `body` (the actual
@@ -86,10 +86,18 @@ export function assertValidElementName(elementName) {
86
86
  * `IdentifierName` (including reserved words) — `import { name }` requires a `BindingIdentifier`,
87
87
  * so a reserved-word check (V5, SEC-1) runs alongside the denylist.
88
88
  */
89
- export function assertValidImportBinding(name) {
90
- assertGrammar("name", name, IMPORT_BINDING_GRAMMAR, "be a valid JavaScript identifier");
91
- assertNotReservedWord("name", name);
92
- assertNotDenylisted("name", name);
89
+ export function assertValidImportBinding(name, argName = "name") {
90
+ assertGrammar(argName, name, IMPORT_BINDING_GRAMMAR, "be a valid JavaScript identifier");
91
+ assertNotReservedWord(argName, name);
92
+ assertNotDenylisted(argName, name);
93
+ }
94
+ /**
95
+ * A plain-identifier object key. Reserved words are legal keys (`{ default: 1 }`), so only the
96
+ * grammar and the denylist apply: a created `__proto__: [...]` would set the prototype.
97
+ */
98
+ export function assertValidPropertyKey(key, argName) {
99
+ assertGrammar(argName, key, IMPORT_BINDING_GRAMMAR, "use object keys that are valid JavaScript identifiers");
100
+ assertNotDenylisted(argName, key);
93
101
  }
94
102
  /**
95
103
  * The single validate-before-mutate chokepoint (ADR-02): `validators` runs first over the
@@ -0,0 +1,58 @@
1
+ import type { SourceFile } from "ts-morph";
2
+ import { type Handle } from "../../core/define-dialect.ts";
3
+ import { typescriptOps } from "../typescript/pack.ts";
4
+ import type { ArrayElement } from "../typescript/array-element.ts";
5
+ import { type InjectionOptions, type InputOptions, type LazyRouteSpec, type NamedImport, type OutputOptions, type RouteSpec, type StateOptions } from "./ops.ts";
6
+ export * as astLibrary from "ts-morph";
7
+ export type { InjectionOptions, InputOptions, LazyRouteSpec, NamedImport, OutputOptions, RouteSpec, StateOptions };
8
+ type InsertOp = (ast: SourceFile, element: ArrayElement, imports?: readonly NamedImport[]) => void;
9
+ type AngularOps = {
10
+ addComponentImport: InsertOp;
11
+ addComponentProvider: InsertOp;
12
+ addRootProvider: InsertOp;
13
+ addRoute: (ast: SourceFile, route: RouteSpec) => void;
14
+ addLazyRoute: (ast: SourceFile, route: LazyRouteSpec) => void;
15
+ addInjection: (ast: SourceFile, name: string, token: ArrayElement, options?: InjectionOptions) => void;
16
+ addInput: (ast: SourceFile, name: string, options?: InputOptions) => void;
17
+ addModel: (ast: SourceFile, name: string, options?: InputOptions) => void;
18
+ addOutput: (ast: SourceFile, name: string, options?: OutputOptions) => void;
19
+ addSignal: (ast: SourceFile, name: string, initial: string, options?: StateOptions) => void;
20
+ addComputed: (ast: SourceFile, name: string, expression: string, options?: StateOptions) => void;
21
+ };
22
+ /**
23
+ * Opens a `.ts` file of an Angular project for editing. The handle carries every
24
+ * `@pbuilder/sdk/typescript` op plus the Angular ops below, chained on one handle and written
25
+ * once.
26
+ *
27
+ * Each op takes `(element, imports?)`: `element` is an identifier, or `{ expression }` for
28
+ * code such as `provideHttpClient(withFetch())`, and `imports` lists the `{ name, from }`
29
+ * named imports that code needs, each added with `addImport`'s rules. An element already
30
+ * listed is a no-op.
31
+ *
32
+ * - `addComponentImport` / `addComponentProvider` append to `imports` / `providers` of the
33
+ * file's only `@Component`, creating the metadata object or the array when missing.
34
+ * - `addRootProvider` appends to the root `providers` of the file's only variable typed
35
+ * `ApplicationConfig`, or of the only `bootstrapApplication(...)` config object.
36
+ * - `addRoute({ path, component, from })` imports `component` and adds an eager route;
37
+ * `addLazyRoute({ path, loadComponent | loadChildren, export? })` adds a lazy one. Both go
38
+ * to the file's only variable typed `Routes` or `Route[]`, before a `**` route when there is
39
+ * one, since the first matching route wins. A different route with the same `path` rejects.
40
+ *
41
+ * They reject, leaving the file unchanged, when the target is missing, ambiguous, or not a
42
+ * literal. Use `.modify(fn)` for those files.
43
+ *
44
+ * @example
45
+ * import * as angular from "@pbuilder/sdk/angular";
46
+ *
47
+ * // src/app/app.config.ts before:
48
+ * // export const appConfig: ApplicationConfig = { providers: [provideRouter(routes)] };
49
+ * export const run = async () => {
50
+ * await angular.find("src/app/app.config.ts").addRootProvider({ expression: "provideHttpClient(withFetch())" }, [
51
+ * { name: "provideHttpClient", from: "@angular/common/http" },
52
+ * { name: "withFetch", from: "@angular/common/http" },
53
+ * ]);
54
+ * };
55
+ * // -> import { provideHttpClient, withFetch } from "@angular/common/http";
56
+ * // -> export const appConfig: ApplicationConfig = { providers: [provideRouter(routes), provideHttpClient(withFetch())] };
57
+ */
58
+ export declare function find(path: string): Handle<"found", SourceFile, AngularOps & typeof typescriptOps>;
@@ -0,0 +1,63 @@
1
+ import { defineDialect, defineOpPack, withOps } from "../../core/define-dialect.js";
2
+ import { parse, print } from "../typescript/ast.js";
3
+ import { typescriptOps } from "../typescript/pack.js";
4
+ import { addComponentImport, addComponentProvider, addComputed, addInjection, addInput, addLazyRoute, addModel, addOutput, addRootProvider, addRoute, addSignal, } from "./ops.js";
5
+ export * as astLibrary from "ts-morph";
6
+ const angularOps = defineOpPack({
7
+ addComponentImport,
8
+ addComponentProvider,
9
+ addRootProvider,
10
+ addRoute,
11
+ addLazyRoute,
12
+ addInjection,
13
+ addInput,
14
+ addModel,
15
+ addOutput,
16
+ addSignal,
17
+ addComputed,
18
+ });
19
+ const baseDialect = defineDialect({
20
+ extensions: [".ts"],
21
+ ast: { parse, print },
22
+ ops: {},
23
+ });
24
+ const angularDialect = withOps(baseDialect, typescriptOps, angularOps);
25
+ /**
26
+ * Opens a `.ts` file of an Angular project for editing. The handle carries every
27
+ * `@pbuilder/sdk/typescript` op plus the Angular ops below, chained on one handle and written
28
+ * once.
29
+ *
30
+ * Each op takes `(element, imports?)`: `element` is an identifier, or `{ expression }` for
31
+ * code such as `provideHttpClient(withFetch())`, and `imports` lists the `{ name, from }`
32
+ * named imports that code needs, each added with `addImport`'s rules. An element already
33
+ * listed is a no-op.
34
+ *
35
+ * - `addComponentImport` / `addComponentProvider` append to `imports` / `providers` of the
36
+ * file's only `@Component`, creating the metadata object or the array when missing.
37
+ * - `addRootProvider` appends to the root `providers` of the file's only variable typed
38
+ * `ApplicationConfig`, or of the only `bootstrapApplication(...)` config object.
39
+ * - `addRoute({ path, component, from })` imports `component` and adds an eager route;
40
+ * `addLazyRoute({ path, loadComponent | loadChildren, export? })` adds a lazy one. Both go
41
+ * to the file's only variable typed `Routes` or `Route[]`, before a `**` route when there is
42
+ * one, since the first matching route wins. A different route with the same `path` rejects.
43
+ *
44
+ * They reject, leaving the file unchanged, when the target is missing, ambiguous, or not a
45
+ * literal. Use `.modify(fn)` for those files.
46
+ *
47
+ * @example
48
+ * import * as angular from "@pbuilder/sdk/angular";
49
+ *
50
+ * // src/app/app.config.ts before:
51
+ * // export const appConfig: ApplicationConfig = { providers: [provideRouter(routes)] };
52
+ * export const run = async () => {
53
+ * await angular.find("src/app/app.config.ts").addRootProvider({ expression: "provideHttpClient(withFetch())" }, [
54
+ * { name: "provideHttpClient", from: "@angular/common/http" },
55
+ * { name: "withFetch", from: "@angular/common/http" },
56
+ * ]);
57
+ * };
58
+ * // -> import { provideHttpClient, withFetch } from "@angular/common/http";
59
+ * // -> export const appConfig: ApplicationConfig = { providers: [provideRouter(routes), provideHttpClient(withFetch())] };
60
+ */
61
+ export function find(path) {
62
+ return angularDialect.find(path);
63
+ }
@@ -0,0 +1,97 @@
1
+ import { type SourceFile } from "ts-morph";
2
+ import { type ArrayElement } from "../typescript/array-element.ts";
3
+ import { type ClassPropertyOptions } from "../typescript/class-property.ts";
4
+ /** A named import an inserted element needs: `import { name } from "from"`. */
5
+ export type NamedImport = {
6
+ name: string;
7
+ from: string;
8
+ };
9
+ /**
10
+ * Appends `element` to the `imports` of the file's only `@Component`, creating the metadata
11
+ * object or the array when missing, then adds each of `imports`. An equal element is a no-op.
12
+ */
13
+ export declare const addComponentImport: (ast: SourceFile, element: ArrayElement, imports?: readonly NamedImport[]) => void;
14
+ /** Same as `addComponentImport`, for the component's `providers`. */
15
+ export declare const addComponentProvider: (ast: SourceFile, element: ArrayElement, imports?: readonly NamedImport[]) => void;
16
+ /**
17
+ * Appends `element` to the application's root `providers`: those of the file's only top-level
18
+ * variable typed `ApplicationConfig`, else those of the only `bootstrapApplication(...)` call's
19
+ * config object, created when missing. A config passed by name rejects with the module to edit.
20
+ */
21
+ export declare const addRootProvider: (ast: SourceFile, element: ArrayElement, imports?: readonly NamedImport[]) => void;
22
+ /** An eager route: `{ path, component }`, with `component` imported from `from`. */
23
+ export type RouteSpec = {
24
+ path: string;
25
+ component: string;
26
+ from: string;
27
+ };
28
+ /** A lazy route: `loadComponent` or `loadChildren` is the module to import; `export` names its export, else the default one. */
29
+ export type LazyRouteSpec = {
30
+ path: string;
31
+ loadComponent?: string;
32
+ loadChildren?: string;
33
+ export?: string;
34
+ };
35
+ /**
36
+ * Imports `route.component` from `route.from` and adds `{ path, component }` to the file's only
37
+ * top-level variable typed `Routes` or `Route[]`, before a `**` route when there is one. An
38
+ * equal route is a no-op; a different route with the same `path` rejects.
39
+ */
40
+ export declare function addRoute(ast: SourceFile, route: RouteSpec): void;
41
+ /**
42
+ * Same placement and duplicate rules as `addRoute`, for a lazy route:
43
+ * `{ path, loadComponent: () => import("<module>") }`, or `loadChildren`, followed by
44
+ * `.then((m) => m.<export>)` when `export` is given. Adds no import.
45
+ */
46
+ export declare function addLazyRoute(ast: SourceFile, route: LazyRouteSpec): void;
47
+ type Scope = NonNullable<ClassPropertyOptions["scope"]>;
48
+ /** Options of `addInput` and `addModel`; `type` is the generic argument, `initial` the default value. */
49
+ export type InputOptions = {
50
+ type?: string;
51
+ initial?: string;
52
+ required?: boolean;
53
+ imports?: readonly NamedImport[];
54
+ };
55
+ /** Options of `addOutput`. */
56
+ export type OutputOptions = {
57
+ type?: string;
58
+ imports?: readonly NamedImport[];
59
+ };
60
+ /** Options of `addInjection`; `scope` defaults to `private`. */
61
+ export type InjectionOptions = {
62
+ scope?: Scope;
63
+ imports?: readonly NamedImport[];
64
+ };
65
+ /**
66
+ * Adds `readonly name = input<type>(initial)`, or `input.required<type>()` with `required`, to
67
+ * the file's only `@Component` or `@Directive` class, after its last property, and imports
68
+ * `input`. The same declaration already there is a no-op.
69
+ */
70
+ export declare const addInput: (ast: SourceFile, name: string, options?: InputOptions) => void;
71
+ /** Same as `addInput`, with `model()` for a two-way bound property. */
72
+ export declare const addModel: (ast: SourceFile, name: string, options?: InputOptions) => void;
73
+ /** Adds `readonly name = output<type>()` to the file's only `@Component` or `@Directive` class and imports `output`. */
74
+ export declare function addOutput(ast: SourceFile, name: string, options?: OutputOptions): void;
75
+ /**
76
+ * Adds `private readonly name = inject(token)` to the file's only class decorated with
77
+ * `@Component`, `@Directive`, `@Pipe`, `@Injectable` or `@Service`, and imports `inject`.
78
+ * `token` is an identifier or `{ expression }`; `options.scope` replaces `private`.
79
+ */
80
+ export declare function addInjection(ast: SourceFile, name: string, token: ArrayElement, options?: InjectionOptions): void;
81
+ /** Options of `addSignal` and `addComputed`; `scope` defaults to `protected`. */
82
+ export type StateOptions = {
83
+ type?: string;
84
+ scope?: Scope;
85
+ imports?: readonly NamedImport[];
86
+ };
87
+ /**
88
+ * Adds `protected readonly name = signal<type>(initial)` to the file's only `@Component` or
89
+ * `@Directive` class and imports `signal`. `options.scope` replaces `protected`.
90
+ */
91
+ export declare function addSignal(ast: SourceFile, name: string, initial: string, options?: StateOptions): void;
92
+ /**
93
+ * Adds `protected readonly name = computed<type>(() => expression)` to the file's only
94
+ * `@Component` or `@Directive` class and imports `computed`. `options.scope` replaces `protected`.
95
+ */
96
+ export declare function addComputed(ast: SourceFile, name: string, expression: string, options?: StateOptions): void;
97
+ export {};
@@ -0,0 +1,302 @@
1
+ import { Node, SyntaxKind } from "ts-morph";
2
+ import { dialectError } from "../../core/dialect-error.js";
3
+ import { handlePathFor } from "../../core/dialect-handle.js";
4
+ import { assertValidImportBinding } from "../../core/jsx-name-validator.js";
5
+ import { elementNameEcho } from "../../core/reject-tail.js";
6
+ import { appendArrayElement, elementText, isSameElement, unwrap, } from "../typescript/array-element.js";
7
+ import { parse } from "../typescript/ast.js";
8
+ import { insertClassProperty } from "../typescript/class-property.js";
9
+ import { addImport } from "../typescript/ops.js";
10
+ const IMPORTS_SHAPE = "`imports` must be a list of { name, from } strings — fix the imports, or use `.modify()` to make this edit directly.";
11
+ function assertImports(imports) {
12
+ if (imports === undefined)
13
+ return;
14
+ const valid = Array.isArray(imports) &&
15
+ imports.every((entry) => typeof entry === "object" &&
16
+ entry !== null &&
17
+ Object.keys(entry).sort().join() === "from,name" &&
18
+ typeof entry.name === "string" &&
19
+ typeof entry.from === "string");
20
+ if (!valid)
21
+ throw dialectError(IMPORTS_SHAPE);
22
+ for (const { name } of imports)
23
+ assertValidImportBinding(name);
24
+ }
25
+ // An insert op: `locate` turns the file into the array the element goes to, then every
26
+ // import the element needs is added with `addImport`'s rules.
27
+ function insertOp(opName, locate) {
28
+ return (ast, element, imports) => {
29
+ assertImports(imports);
30
+ const label = `${opName}("${elementNameEcho(elementText(element))}")`;
31
+ const fail = (reason) => {
32
+ throw dialectError(`${label} on "${handlePathFor(ast)}" — ${reason}. Edit it with .modify().`);
33
+ };
34
+ appendArrayElement(ast, locate(ast, fail), element, label);
35
+ for (const { name, from } of imports ?? [])
36
+ addImport(ast, name, from);
37
+ };
38
+ }
39
+ // The declared type of a top-level variable: its annotation, or the type it `satisfies`.
40
+ function declaredType(decl) {
41
+ const initializer = decl.getInitializer();
42
+ return decl.getTypeNode()?.getText() ?? (Node.isSatisfiesExpression(initializer) ? initializer.getTypeNode()?.getText() : undefined);
43
+ }
44
+ function typedVariables(ast, types) {
45
+ return ast.getVariableDeclarations().filter((decl) => types.includes(declaredType(decl) ?? ""));
46
+ }
47
+ function rootProviders(ast, fail) {
48
+ const configs = typedVariables(ast, ["ApplicationConfig"]);
49
+ if (configs.length > 1)
50
+ fail(`${configs.length} top-level variables are typed ApplicationConfig; exactly one is required`);
51
+ if (configs.length === 1)
52
+ return { variable: configs[0].getName(), path: ["providers"] };
53
+ const calls = ast
54
+ .getDescendantsOfKind(SyntaxKind.CallExpression)
55
+ .filter((call) => call.getExpression().getText() === "bootstrapApplication");
56
+ if (calls.length === 0)
57
+ fail("no top-level variable typed ApplicationConfig and no bootstrapApplication call was found");
58
+ // Providers passed by reference live where that config is declared, usually another file.
59
+ const config = calls.length === 1 ? calls[0].getArguments()[1] : undefined;
60
+ if (Node.isIdentifier(config)) {
61
+ const name = config.getText();
62
+ const from = ast
63
+ .getImportDeclarations()
64
+ .find((decl) => decl.getNamedImports().some((spec) => (spec.getAliasNode() ?? spec.getNameNode()).getText() === name))
65
+ ?.getModuleSpecifierValue();
66
+ fail(`the bootstrapApplication config is "${elementNameEcho(name)}"` +
67
+ (from === undefined ? "; add the provider where it is declared" : `, imported from "${elementNameEcho(from)}"; add the provider in that file`));
68
+ }
69
+ return { call: "bootstrapApplication", argument: 1, path: ["providers"] };
70
+ }
71
+ /**
72
+ * Appends `element` to the `imports` of the file's only `@Component`, creating the metadata
73
+ * object or the array when missing, then adds each of `imports`. An equal element is a no-op.
74
+ */
75
+ export const addComponentImport = insertOp("addComponentImport", () => ({ decorator: "Component", path: ["imports"] }));
76
+ /** Same as `addComponentImport`, for the component's `providers`. */
77
+ export const addComponentProvider = insertOp("addComponentProvider", () => ({ decorator: "Component", path: ["providers"] }));
78
+ /**
79
+ * Appends `element` to the application's root `providers`: those of the file's only top-level
80
+ * variable typed `ApplicationConfig`, else those of the only `bootstrapApplication(...)` call's
81
+ * config object, created when missing. A config passed by name rejects with the module to edit.
82
+ */
83
+ export const addRootProvider = insertOp("addRootProvider", rootProviders);
84
+ const ROUTE_SHAPE = "`route` must be { path, component, from } strings — fix the route, or use `.modify()` to make this edit directly.";
85
+ const LAZY_ROUTE_SHAPE = "`route` must be { path, loadComponent | loadChildren, export? } strings — fix the route, or use `.modify()` to make this edit " +
86
+ "directly.";
87
+ function isStringRecord(value, required, optional = []) {
88
+ if (typeof value !== "object" || value === null || Array.isArray(value))
89
+ return false;
90
+ const keys = Object.keys(value);
91
+ return (required.every((key) => keys.includes(key)) &&
92
+ keys.every((key) => required.includes(key) || optional.includes(key)) &&
93
+ Object.values(value).every((field) => typeof field === "string"));
94
+ }
95
+ function pathOf(element) {
96
+ const route = unwrap(element);
97
+ if (!Node.isObjectLiteralExpression(route))
98
+ return undefined;
99
+ const value = route.getProperty("path")?.asKind(SyntaxKind.PropertyAssignment)?.getInitializer();
100
+ return Node.isStringLiteral(value) || Node.isNoSubstitutionTemplateLiteral(value) ? value.getLiteralValue() : undefined;
101
+ }
102
+ // Adds `text` to the file's only `Routes` array. Angular matches routes in order and the first
103
+ // match wins, so a new route goes before a top-level `**` route instead of after it.
104
+ function insertRoute(ast, opName, path, text) {
105
+ const label = `${opName}("${elementNameEcho(path)}")`;
106
+ const fail = (reason) => {
107
+ throw dialectError(`${label} on "${handlePathFor(ast)}" — ${reason}. Edit it with .modify().`);
108
+ };
109
+ if (path.startsWith("/"))
110
+ fail('a route path cannot start with "/"');
111
+ const declarations = typedVariables(ast, ["Routes", "Route[]"]);
112
+ if (declarations.length === 0)
113
+ fail("no top-level variable typed Routes or Route[] was found");
114
+ if (declarations.length > 1)
115
+ fail(`${declarations.length} top-level variables are typed Routes or Route[]; exactly one is required`);
116
+ const name = declarations[0].getName();
117
+ const list = unwrap(declarations[0].getInitializerOrThrow());
118
+ if (!Node.isArrayLiteralExpression(list))
119
+ fail(`"${elementNameEcho(name)}" is not an array literal`);
120
+ const element = { expression: text };
121
+ const elements = list.getElements();
122
+ const samePath = elements.find((candidate) => pathOf(candidate) === path);
123
+ if (samePath !== undefined) {
124
+ if (isSameElement(samePath, element))
125
+ return;
126
+ fail(`a different route with path "${elementNameEcho(path)}" already exists`);
127
+ }
128
+ const wildcard = elements.find((candidate) => pathOf(candidate) === "**");
129
+ if (wildcard === undefined) {
130
+ appendArrayElement(ast, { variable: name, path: [] }, element, label);
131
+ return;
132
+ }
133
+ const source = ast.getFullText();
134
+ if (!source.slice(list.getStart(), list.getEnd()).includes("\n")) {
135
+ ast.insertText(wildcard.getStart(), `${text}, `);
136
+ return;
137
+ }
138
+ const indent = /^[ \t]*/.exec(source.slice(source.lastIndexOf("\n", wildcard.getStart()) + 1))[0];
139
+ ast.insertText(wildcard.getStart(), `${text},\n${indent}`);
140
+ }
141
+ /**
142
+ * Imports `route.component` from `route.from` and adds `{ path, component }` to the file's only
143
+ * top-level variable typed `Routes` or `Route[]`, before a `**` route when there is one. An
144
+ * equal route is a no-op; a different route with the same `path` rejects.
145
+ */
146
+ export function addRoute(ast, route) {
147
+ if (!isStringRecord(route, ["path", "component", "from"]))
148
+ throw dialectError(ROUTE_SHAPE);
149
+ assertValidImportBinding(route.component, "component");
150
+ insertRoute(ast, "addRoute", route.path, `{ path: ${JSON.stringify(route.path)}, component: ${route.component} }`);
151
+ addImport(ast, route.component, route.from);
152
+ }
153
+ /**
154
+ * Same placement and duplicate rules as `addRoute`, for a lazy route:
155
+ * `{ path, loadComponent: () => import("<module>") }`, or `loadChildren`, followed by
156
+ * `.then((m) => m.<export>)` when `export` is given. Adds no import.
157
+ */
158
+ export function addLazyRoute(ast, route) {
159
+ if (!isStringRecord(route, ["path"], ["loadComponent", "loadChildren", "export"]))
160
+ throw dialectError(LAZY_ROUTE_SHAPE);
161
+ const kind = route.loadComponent !== undefined ? "loadComponent" : "loadChildren";
162
+ const from = route[kind];
163
+ if (from === undefined || (route.loadComponent !== undefined && route.loadChildren !== undefined))
164
+ throw dialectError(LAZY_ROUTE_SHAPE);
165
+ if (route.export !== undefined)
166
+ assertValidImportBinding(route.export, "export");
167
+ const loader = `import(${JSON.stringify(from)})${route.export === undefined ? "" : `.then((m) => m.${route.export})`}`;
168
+ insertRoute(ast, "addLazyRoute", route.path, `{ path: ${JSON.stringify(route.path)}, ${kind}: () => ${loader} }`);
169
+ }
170
+ // Angular only reads input(), model() and output() in component and directive initializers.
171
+ const VIEW_DECORATORS = ["Component", "Directive"];
172
+ const INJECTABLE_DECORATORS = ["Component", "Directive", "Pipe", "Injectable", "Service"];
173
+ function decoratorList(decorators) {
174
+ const names = decorators.map((name) => `@${name}`);
175
+ return names.length === 1 ? names[0] : `${names.slice(0, -1).join(", ")} or ${names.at(-1)}`;
176
+ }
177
+ function decoratedClass(ast, decorators, fail) {
178
+ const classes = ast
179
+ .getDescendantsOfKind(SyntaxKind.ClassDeclaration)
180
+ .filter((cls) => cls.getDecorators().some((decorator) => decorators.includes(decorator.getName())));
181
+ if (classes.length === 0)
182
+ fail(`no class decorated with ${decoratorList(decorators)} was found`);
183
+ if (classes.length > 1)
184
+ fail(`${classes.length} classes are decorated with ${decoratorList(decorators)}; exactly one is required`);
185
+ return classes[0];
186
+ }
187
+ function assertOptions(options, keys) {
188
+ if (options === undefined)
189
+ return;
190
+ const shape = `\`options\` must be { ${keys.map((key) => `${key}?`).join(", ")} } — fix the options, or use \`.modify()\` to make this edit directly.`;
191
+ if (typeof options !== "object" || options === null || Array.isArray(options))
192
+ throw dialectError(shape);
193
+ const record = options;
194
+ const valid = Object.keys(record).every((key) => {
195
+ const value = record[key];
196
+ if (!keys.includes(key))
197
+ return false;
198
+ if (key === "required")
199
+ return typeof value === "boolean";
200
+ if (key === "scope")
201
+ return value === "public" || value === "protected" || value === "private";
202
+ if (key === "imports")
203
+ return true;
204
+ return typeof value === "string";
205
+ });
206
+ if (!valid)
207
+ throw dialectError(shape);
208
+ assertImports(record.imports);
209
+ }
210
+ const TYPE_RULE = "`type` must be exactly one TypeScript type — fix the type, or use `.modify()` to make this edit directly.";
211
+ // `<type>` once proven to be one type: a breakout such as `T>(); evil(<T` parses differently.
212
+ function typeArgument(type) {
213
+ if (type === undefined)
214
+ return "";
215
+ let statements;
216
+ try {
217
+ statements = parse(`let x: ${type};`).getStatements();
218
+ }
219
+ catch {
220
+ throw dialectError(TYPE_RULE);
221
+ }
222
+ const [statement, ...rest] = statements;
223
+ const declaration = statement?.asKind(SyntaxKind.VariableStatement)?.getDeclarations();
224
+ const typeNode = declaration?.length === 1 ? declaration[0].getTypeNode() : undefined;
225
+ if (rest.length > 0 || typeNode === undefined || declaration[0].hasInitializer() || typeNode.getText() !== type.trim()) {
226
+ throw dialectError(TYPE_RULE);
227
+ }
228
+ return `<${typeNode.getText()}>`;
229
+ }
230
+ // Adds `property` to the file's only class with one of `decorators`, then the Angular
231
+ // function it calls (from `@angular/core`) and the author's `imports`.
232
+ function addMember(ast, opName, name, decorators, property, imports) {
233
+ const fail = (reason) => {
234
+ throw dialectError(`${opName}("${elementNameEcho(name)}") on "${handlePathFor(ast)}" — ${reason}. Edit it with .modify().`);
235
+ };
236
+ const cls = decoratedClass(ast, decorators, fail);
237
+ insertClassProperty(ast, cls, { name, initializer: property.initializer, scope: property.scope, readonly: true }, fail);
238
+ addImport(ast, property.core, "@angular/core");
239
+ for (const entry of imports ?? [])
240
+ addImport(ast, entry.name, entry.from);
241
+ }
242
+ function signalInputOp(opName, fn) {
243
+ return (ast, name, options) => {
244
+ assertValidImportBinding(name, "name");
245
+ assertOptions(options, ["type", "initial", "required", "imports"]);
246
+ if (options?.required && options.initial !== undefined) {
247
+ throw dialectError("`required` and `initial` cannot be combined — drop one, or use `.modify()` to make this edit directly.");
248
+ }
249
+ const generic = typeArgument(options?.type);
250
+ const initial = options?.initial === undefined ? "" : elementText({ expression: options.initial });
251
+ const initializer = options?.required ? `${fn}.required${generic}()` : `${fn}${generic}(${initial})`;
252
+ addMember(ast, opName, name, VIEW_DECORATORS, { initializer, core: fn }, options?.imports);
253
+ };
254
+ }
255
+ /**
256
+ * Adds `readonly name = input<type>(initial)`, or `input.required<type>()` with `required`, to
257
+ * the file's only `@Component` or `@Directive` class, after its last property, and imports
258
+ * `input`. The same declaration already there is a no-op.
259
+ */
260
+ export const addInput = signalInputOp("addInput", "input");
261
+ /** Same as `addInput`, with `model()` for a two-way bound property. */
262
+ export const addModel = signalInputOp("addModel", "model");
263
+ /** Adds `readonly name = output<type>()` to the file's only `@Component` or `@Directive` class and imports `output`. */
264
+ export function addOutput(ast, name, options) {
265
+ assertValidImportBinding(name, "name");
266
+ assertOptions(options, ["type", "imports"]);
267
+ addMember(ast, "addOutput", name, VIEW_DECORATORS, { initializer: `output${typeArgument(options?.type)}()`, core: "output" }, options?.imports);
268
+ }
269
+ /**
270
+ * Adds `private readonly name = inject(token)` to the file's only class decorated with
271
+ * `@Component`, `@Directive`, `@Pipe`, `@Injectable` or `@Service`, and imports `inject`.
272
+ * `token` is an identifier or `{ expression }`; `options.scope` replaces `private`.
273
+ */
274
+ export function addInjection(ast, name, token, options) {
275
+ assertValidImportBinding(name, "name");
276
+ assertOptions(options, ["scope", "imports"]);
277
+ const initializer = `inject(${elementText(token)})`;
278
+ addMember(ast, "addInjection", name, INJECTABLE_DECORATORS, { initializer, scope: options?.scope ?? "private", core: "inject" }, options?.imports);
279
+ }
280
+ /**
281
+ * Adds `protected readonly name = signal<type>(initial)` to the file's only `@Component` or
282
+ * `@Directive` class and imports `signal`. `options.scope` replaces `protected`.
283
+ */
284
+ export function addSignal(ast, name, initial, options) {
285
+ assertValidImportBinding(name, "name");
286
+ assertOptions(options, ["type", "scope", "imports"]);
287
+ const initializer = `signal${typeArgument(options?.type)}(${elementText({ expression: initial })})`;
288
+ addMember(ast, "addSignal", name, VIEW_DECORATORS, { initializer, scope: options?.scope ?? "protected", core: "signal" }, options?.imports);
289
+ }
290
+ /**
291
+ * Adds `protected readonly name = computed<type>(() => expression)` to the file's only
292
+ * `@Component` or `@Directive` class and imports `computed`. `options.scope` replaces `protected`.
293
+ */
294
+ export function addComputed(ast, name, expression, options) {
295
+ assertValidImportBinding(name, "name");
296
+ assertOptions(options, ["type", "scope", "imports"]);
297
+ const body = elementText({ expression });
298
+ // An arrow function reads a leading `{` as a block, so an object literal needs parentheses.
299
+ const arrow = body.startsWith("{") ? `() => (${body})` : `() => ${body}`;
300
+ const initializer = `computed${typeArgument(options?.type)}(${arrow})`;
301
+ addMember(ast, "addComputed", name, VIEW_DECORATORS, { initializer, scope: options?.scope ?? "protected", core: "computed" }, options?.imports);
302
+ }