@pbuilder/sdk 0.5.1 → 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 +25 -2
- package/dist/core/jsx-name-validator.d.ts +6 -1
- package/dist/core/jsx-name-validator.js +12 -4
- package/dist/dialects/angular/index.d.ts +58 -0
- package/dist/dialects/angular/index.js +63 -0
- package/dist/dialects/angular/ops.d.ts +97 -0
- package/dist/dialects/angular/ops.js +302 -0
- package/dist/dialects/nestjs/ops.js +1 -26
- package/dist/dialects/typescript/array-element.d.ts +41 -0
- package/dist/dialects/typescript/array-element.js +323 -0
- package/dist/dialects/typescript/class-property.d.ts +24 -0
- package/dist/dialects/typescript/class-property.js +98 -0
- package/dist/dialects/typescript/index.d.ts +6 -1
- package/dist/dialects/typescript/index.js +2 -1
- package/dist/dialects/typescript/pack.d.ts +4 -0
- package/dist/dialects/typescript/pack.js +4 -0
- package/dist/runner-manifest.json +2 -2
- package/package.json +6 -1
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.
|
|
562
|
+
type: see [authoring a dialect](./docs/authoring-a-dialect.md) for the full story. Six
|
|
563
563
|
ship today: `@pbuilder/sdk/typescript`, `@pbuilder/sdk/react`, `@pbuilder/sdk/nestjs`,
|
|
564
|
-
`@pbuilder/sdk/json`, and `@pbuilder/sdk/yaml`.
|
|
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
|
|
@@ -590,6 +590,8 @@ await ts.find("src/index.ts")
|
|
|
590
590
|
| `removeImport(name, from)` | Removes the named binding; deletes the whole statement when it was the last one. Idempotent on an absent binding. |
|
|
591
591
|
| `removeExport(name, from)` | Removes a named re-export; deletes the statement when it was the last one. Idempotent on an absent one. |
|
|
592
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. |
|
|
593
595
|
| `addFunction(name, source, opts?)` | Appends a top-level function. `source` **includes** the braces (`"(): void {}"`). |
|
|
594
596
|
| `addVariable(name, initializer, opts?)` | Appends a top-level variable (`kind` defaults to `const`). |
|
|
595
597
|
| `addClass(name, source, opts?)` | Appends a top-level class. `source` **excludes** the braces — the op adds them. |
|
|
@@ -685,6 +687,27 @@ await nestjs
|
|
|
685
687
|
Extra named ops: `addProvider`, `addController`, `addModuleImport`, `addExport`. `.modify(fn)`
|
|
686
688
|
exposes ts-morph. See [the NestJS dialect guide](./docs/nestjs-dialect.md).
|
|
687
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
|
+
|
|
688
711
|
### `.modify()` — the universal escape hatch
|
|
689
712
|
|
|
690
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(
|
|
91
|
-
assertNotReservedWord(
|
|
92
|
-
assertNotDenylisted(
|
|
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
|
+
}
|
|
@@ -2,6 +2,7 @@ import { SyntaxKind, } from "ts-morph";
|
|
|
2
2
|
import { dialectError } from "../../core/dialect-error.js";
|
|
3
3
|
import { handlePathFor } from "../../core/dialect-handle.js";
|
|
4
4
|
import { assertValidImportBinding } from "../../core/jsx-name-validator.js";
|
|
5
|
+
import { appendEntry } from "../typescript/array-element.js";
|
|
5
6
|
import { addImport } from "../typescript/ops.js";
|
|
6
7
|
function moduleDecorator(ast, fail) {
|
|
7
8
|
const decorators = ast
|
|
@@ -32,32 +33,6 @@ function locate(ast, property, name, fail) {
|
|
|
32
33
|
return { kind: "present" };
|
|
33
34
|
return { kind: "append", list };
|
|
34
35
|
}
|
|
35
|
-
// Appends `item` after the last entry of an array or object literal, keeping its layout: one
|
|
36
|
-
// line stays one line, a multi-line list gets a new line at the last entry's indentation, and
|
|
37
|
-
// a trailing comma stays trailing.
|
|
38
|
-
function appendEntry(ast, list, entries, item, empty) {
|
|
39
|
-
const last = entries.at(-1);
|
|
40
|
-
if (last === undefined) {
|
|
41
|
-
list.replaceWithText(empty);
|
|
42
|
-
return;
|
|
43
|
-
}
|
|
44
|
-
const text = ast.getFullText();
|
|
45
|
-
const closeAt = list.getEnd() - 1;
|
|
46
|
-
const commaAt = text.indexOf(",", last.getEnd());
|
|
47
|
-
const trailingComma = commaAt !== -1 && commaAt < closeAt;
|
|
48
|
-
if (!text.slice(list.getStart(), closeAt).includes("\n")) {
|
|
49
|
-
if (trailingComma)
|
|
50
|
-
ast.insertText(commaAt + 1, ` ${item},`);
|
|
51
|
-
else
|
|
52
|
-
ast.insertText(last.getEnd(), `, ${item}`);
|
|
53
|
-
return;
|
|
54
|
-
}
|
|
55
|
-
const indent = /^[ \t]*/.exec(text.slice(text.lastIndexOf("\n", last.getStart()) + 1))[0];
|
|
56
|
-
if (trailingComma)
|
|
57
|
-
ast.insertText(commaAt + 1, `\n${indent}${item},`);
|
|
58
|
-
else
|
|
59
|
-
ast.insertText(last.getEnd(), `,\n${indent}${item}`);
|
|
60
|
-
}
|
|
61
36
|
function write(ast, placement, property, name) {
|
|
62
37
|
const entry = `${property}: [${name}]`;
|
|
63
38
|
switch (placement.kind) {
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { Node, type Expression, type SourceFile } from "ts-morph";
|
|
2
|
+
/** A string is an object key; `{ key: "value" }` selects the only array element whose `key` is that string. */
|
|
3
|
+
export type PathSegment = string | Readonly<Record<string, string>>;
|
|
4
|
+
export type ArrayLocator = {
|
|
5
|
+
variable: string;
|
|
6
|
+
path: readonly PathSegment[];
|
|
7
|
+
} | {
|
|
8
|
+
call: string;
|
|
9
|
+
argument: number;
|
|
10
|
+
path: readonly PathSegment[];
|
|
11
|
+
} | {
|
|
12
|
+
decorator: string;
|
|
13
|
+
path: readonly PathSegment[];
|
|
14
|
+
};
|
|
15
|
+
/** An identifier, validated; or `{ expression }`, which must parse as exactly one expression. */
|
|
16
|
+
export type ArrayElement = string | {
|
|
17
|
+
expression: string;
|
|
18
|
+
};
|
|
19
|
+
export declare function appendEntry(ast: SourceFile, list: Node, entries: Node[], item: string, empty: string): void;
|
|
20
|
+
export declare function tokensOf(node: Node): string[];
|
|
21
|
+
/** True when `node` and the validated `element` are the same code, compared token by token. */
|
|
22
|
+
export declare function isSameElement(node: Node, element: unknown): boolean;
|
|
23
|
+
export declare function unwrap(node: Expression): Expression;
|
|
24
|
+
/**
|
|
25
|
+
* Appends `element` to the array literal `locator` points at, keeping the list's layout. The
|
|
26
|
+
* locator starts at a top-level variable, an argument of the only call to a callee, or the
|
|
27
|
+
* only decorator with a name, then follows `path`: a string is an object key, and
|
|
28
|
+
* `{ key: "value" }` selects the only array element whose `key` is that string. Missing keys and
|
|
29
|
+
* the next missing call argument are created; a missing root or matched element rejects. An
|
|
30
|
+
* element already listed, compared token by token, is a no-op. The element is an identifier, or
|
|
31
|
+
* `{ expression }` for code, which must parse as exactly one expression and is otherwise
|
|
32
|
+
* author-trusted, like `addFunction`'s `source`.
|
|
33
|
+
*/
|
|
34
|
+
export declare function addArrayElement(ast: SourceFile, locator: ArrayLocator, element: ArrayElement): void;
|
|
35
|
+
/** The validated source text of `element`; rejects like `addArrayElement` does. */
|
|
36
|
+
export declare function elementText(element: unknown): string;
|
|
37
|
+
/**
|
|
38
|
+
* `addArrayElement` for a dialect that builds `locator` itself: `label` heads the reject
|
|
39
|
+
* tail in place of `addArrayElement(<locator>)`.
|
|
40
|
+
*/
|
|
41
|
+
export declare function appendArrayElement(ast: SourceFile, locator: ArrayLocator, element: unknown, label: string): void;
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import { Node, SyntaxKind, ts, } from "ts-morph";
|
|
2
|
+
import { dialectError } from "../../core/dialect-error.js";
|
|
3
|
+
import { handlePathFor } from "../../core/dialect-handle.js";
|
|
4
|
+
import { elementNameEcho } from "../../core/reject-tail.js";
|
|
5
|
+
import { assertValidImportBinding, assertValidPropertyKey } from "../../core/jsx-name-validator.js";
|
|
6
|
+
import { parse } from "./ast.js";
|
|
7
|
+
// Appends `item` after the last entry of an array or object literal, keeping its layout: one
|
|
8
|
+
// line stays one line, a multi-line list gets a new line at the last entry's indentation, and
|
|
9
|
+
// a trailing comma stays trailing.
|
|
10
|
+
export function appendEntry(ast, list, entries, item, empty) {
|
|
11
|
+
const last = entries.at(-1);
|
|
12
|
+
if (last === undefined) {
|
|
13
|
+
list.replaceWithText(empty);
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
const text = ast.getFullText();
|
|
17
|
+
const closeAt = list.getEnd() - 1;
|
|
18
|
+
// The comma is read from the list's tokens: a comma inside a comment is trivia, not one.
|
|
19
|
+
const trailing = list.getFirstChildByKind(SyntaxKind.SyntaxList)?.getLastChild();
|
|
20
|
+
const trailingComma = trailing?.getKind() === SyntaxKind.CommaToken;
|
|
21
|
+
const commaAt = trailingComma ? trailing.getStart() : -1;
|
|
22
|
+
if (!text.slice(list.getStart(), closeAt).includes("\n")) {
|
|
23
|
+
if (trailingComma)
|
|
24
|
+
ast.insertText(commaAt + 1, ` ${item},`);
|
|
25
|
+
else
|
|
26
|
+
ast.insertText(last.getEnd(), `, ${item}`);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
const indent = /^[ \t]*/.exec(text.slice(text.lastIndexOf("\n", last.getStart()) + 1))[0];
|
|
30
|
+
if (trailingComma)
|
|
31
|
+
ast.insertText(commaAt + 1, `\n${indent}${item},`);
|
|
32
|
+
else
|
|
33
|
+
ast.insertText(last.getEnd(), `,\n${indent}${item}`);
|
|
34
|
+
}
|
|
35
|
+
const LOCATOR_SHAPE = "`locator` must be { variable, path }, { call, argument, path }, or { decorator, path } — fix the locator, " +
|
|
36
|
+
"or use `.modify()` to make this edit directly.";
|
|
37
|
+
const ELEMENT_SHAPE = "`element` must be an identifier string or { expression: string } — fix the element, or use `.modify()` to " +
|
|
38
|
+
"make this edit directly.";
|
|
39
|
+
const EXPRESSION_RULE = "`expression` must be exactly one JavaScript expression — fix the expression, or use `.modify()` to make this " +
|
|
40
|
+
"edit directly.";
|
|
41
|
+
function isPlainObject(value) {
|
|
42
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
43
|
+
}
|
|
44
|
+
function hasExactKeys(value, keys) {
|
|
45
|
+
const own = Object.keys(value);
|
|
46
|
+
return own.length === keys.length && keys.every((key) => Object.hasOwn(value, key));
|
|
47
|
+
}
|
|
48
|
+
function assertLocator(locator) {
|
|
49
|
+
if (!isPlainObject(locator))
|
|
50
|
+
throw dialectError(LOCATOR_SHAPE);
|
|
51
|
+
const shape = Object.hasOwn(locator, "call") ? ["call", "argument", "path"] : ["variable" in locator ? "variable" : "decorator", "path"];
|
|
52
|
+
if (!hasExactKeys(locator, shape) || !Array.isArray(locator.path))
|
|
53
|
+
throw dialectError(LOCATOR_SHAPE);
|
|
54
|
+
const root = shape[0];
|
|
55
|
+
if (typeof locator[root] !== "string")
|
|
56
|
+
throw dialectError(LOCATOR_SHAPE);
|
|
57
|
+
if (root === "call" && !(Number.isInteger(locator.argument) && locator.argument >= 0)) {
|
|
58
|
+
throw dialectError(LOCATOR_SHAPE);
|
|
59
|
+
}
|
|
60
|
+
assertValidImportBinding(locator[root], root);
|
|
61
|
+
for (const segment of locator.path) {
|
|
62
|
+
if (typeof segment === "string") {
|
|
63
|
+
assertValidPropertyKey(segment, "path");
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const entries = isPlainObject(segment) ? Object.entries(segment) : [];
|
|
67
|
+
if (entries.length !== 1 || typeof entries[0][1] !== "string") {
|
|
68
|
+
throw dialectError("`path` segments must be object keys or { key: \"value\" } matches — fix the path, or use `.modify()` to " +
|
|
69
|
+
"make this edit directly.");
|
|
70
|
+
}
|
|
71
|
+
assertValidPropertyKey(entries[0][0], "path");
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
// The only element of `[text]`, or undefined when `text` is not exactly one plain element.
|
|
75
|
+
function parseElement(text) {
|
|
76
|
+
let parsed;
|
|
77
|
+
try {
|
|
78
|
+
parsed = parse(`[${text}]`);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
const [statement, ...rest] = parsed.getStatements();
|
|
84
|
+
const list = statement?.asKind(SyntaxKind.ExpressionStatement)?.getExpressionIfKind(SyntaxKind.ArrayLiteralExpression);
|
|
85
|
+
const elements = list?.getElements() ?? [];
|
|
86
|
+
if (rest.length > 0 || elements.length !== 1 || Node.isSpreadElement(elements[0]) || Node.isOmittedExpression(elements[0])) {
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
return elements[0];
|
|
90
|
+
}
|
|
91
|
+
// Returns the element's parsed node once it is proven to be a single array element.
|
|
92
|
+
function elementNode(element) {
|
|
93
|
+
if (typeof element === "string") {
|
|
94
|
+
assertValidImportBinding(element, "element");
|
|
95
|
+
return parseElement(element);
|
|
96
|
+
}
|
|
97
|
+
if (!isPlainObject(element) || !hasExactKeys(element, ["expression"]) || typeof element.expression !== "string") {
|
|
98
|
+
throw dialectError(ELEMENT_SHAPE);
|
|
99
|
+
}
|
|
100
|
+
// Wrapping in brackets and requiring exactly one plain element blocks every breakout: a
|
|
101
|
+
// closed bracket, a comma, or a comment that swallows `]` yields a different parse.
|
|
102
|
+
const node = parseElement(element.expression.trim());
|
|
103
|
+
if (node === undefined)
|
|
104
|
+
throw dialectError(EXPRESSION_RULE);
|
|
105
|
+
return node;
|
|
106
|
+
}
|
|
107
|
+
// Tokens without trivia, so formatting, comments, and trailing commas never make two equal
|
|
108
|
+
// elements look different.
|
|
109
|
+
export function tokensOf(node) {
|
|
110
|
+
const sourceFile = node.getSourceFile().compilerNode;
|
|
111
|
+
const tokens = [];
|
|
112
|
+
const visit = (current) => {
|
|
113
|
+
if (current.kind >= ts.SyntaxKind.FirstJSDocNode && current.kind <= ts.SyntaxKind.LastJSDocNode)
|
|
114
|
+
return;
|
|
115
|
+
const children = current.getChildren(sourceFile);
|
|
116
|
+
if (children.length === 0) {
|
|
117
|
+
const text = current.getText(sourceFile);
|
|
118
|
+
if (text !== "")
|
|
119
|
+
tokens.push(text);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
children.forEach(visit);
|
|
123
|
+
};
|
|
124
|
+
visit(node.compilerNode);
|
|
125
|
+
return tokens.filter((token, index) => token !== "," || ![")", "]", "}"].includes(tokens[index + 1] ?? ""));
|
|
126
|
+
}
|
|
127
|
+
function sameTokens(a, b) {
|
|
128
|
+
return a.length === b.length && a.every((token, index) => token === b[index]);
|
|
129
|
+
}
|
|
130
|
+
/** True when `node` and the validated `element` are the same code, compared token by token. */
|
|
131
|
+
export function isSameElement(node, element) {
|
|
132
|
+
return sameTokens(tokensOf(node), tokensOf(elementNode(element)));
|
|
133
|
+
}
|
|
134
|
+
export function unwrap(node) {
|
|
135
|
+
let current = node;
|
|
136
|
+
while (Node.isAsExpression(current) ||
|
|
137
|
+
Node.isSatisfiesExpression(current) ||
|
|
138
|
+
Node.isParenthesizedExpression(current) ||
|
|
139
|
+
Node.isTypeAssertion(current) ||
|
|
140
|
+
Node.isNonNullExpression(current)) {
|
|
141
|
+
current = current.getExpression();
|
|
142
|
+
}
|
|
143
|
+
return current;
|
|
144
|
+
}
|
|
145
|
+
function propertyKey(member) {
|
|
146
|
+
if (!Node.isPropertyAssignment(member) &&
|
|
147
|
+
!Node.isShorthandPropertyAssignment(member) &&
|
|
148
|
+
!Node.isMethodDeclaration(member) &&
|
|
149
|
+
!Node.isGetAccessorDeclaration(member) &&
|
|
150
|
+
!Node.isSetAccessorDeclaration(member)) {
|
|
151
|
+
return undefined;
|
|
152
|
+
}
|
|
153
|
+
const name = member.getNameNode();
|
|
154
|
+
if (Node.isIdentifier(name))
|
|
155
|
+
return name.getText();
|
|
156
|
+
if (Node.isStringLiteral(name) || Node.isNoSubstitutionTemplateLiteral(name))
|
|
157
|
+
return name.getLiteralValue();
|
|
158
|
+
return undefined;
|
|
159
|
+
}
|
|
160
|
+
function stringValue(node) {
|
|
161
|
+
const value = node === undefined ? undefined : unwrap(node);
|
|
162
|
+
return Node.isStringLiteral(value) || Node.isNoSubstitutionTemplateLiteral(value) ? value.getLiteralValue() : undefined;
|
|
163
|
+
}
|
|
164
|
+
function locateRoot(ast, locator, fail) {
|
|
165
|
+
if ("variable" in locator) {
|
|
166
|
+
const declarations = ast.getVariableDeclarations().filter((decl) => decl.getName() === locator.variable);
|
|
167
|
+
if (declarations.length === 0)
|
|
168
|
+
fail(`no top-level variable named "${elementNameEcho(locator.variable)}" was found`);
|
|
169
|
+
if (declarations.length > 1)
|
|
170
|
+
fail(`${declarations.length} top-level variables are named "${elementNameEcho(locator.variable)}"; exactly one is required`);
|
|
171
|
+
const initializer = declarations[0].getInitializer();
|
|
172
|
+
if (initializer === undefined)
|
|
173
|
+
fail(`"${elementNameEcho(locator.variable)}" has no initializer`);
|
|
174
|
+
return { kind: "node", node: initializer };
|
|
175
|
+
}
|
|
176
|
+
let owner;
|
|
177
|
+
let argument = 0;
|
|
178
|
+
if ("call" in locator) {
|
|
179
|
+
const calls = ast
|
|
180
|
+
.getDescendantsOfKind(SyntaxKind.CallExpression)
|
|
181
|
+
.filter((call) => Node.isIdentifier(call.getExpression()) && call.getExpression().getText() === locator.call);
|
|
182
|
+
if (calls.length === 0)
|
|
183
|
+
fail(`no call to "${elementNameEcho(locator.call)}" was found`);
|
|
184
|
+
if (calls.length > 1)
|
|
185
|
+
fail(`${calls.length} calls to "${elementNameEcho(locator.call)}" were found; exactly one is required`);
|
|
186
|
+
owner = calls[0];
|
|
187
|
+
argument = locator.argument;
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
const decorators = ast.getDescendantsOfKind(SyntaxKind.Decorator).filter((decorator) => decorator.getName() === locator.decorator);
|
|
191
|
+
if (decorators.length === 0)
|
|
192
|
+
fail(`no "@${elementNameEcho(locator.decorator)}" decorator was found`);
|
|
193
|
+
if (decorators.length > 1)
|
|
194
|
+
fail(`${decorators.length} "@${elementNameEcho(locator.decorator)}" decorators were found; exactly one is required`);
|
|
195
|
+
owner = decorators[0];
|
|
196
|
+
if (!owner.isDecoratorFactory())
|
|
197
|
+
fail(`"@${elementNameEcho(locator.decorator)}" is not called with an argument list`);
|
|
198
|
+
}
|
|
199
|
+
const args = owner.getArguments();
|
|
200
|
+
if (argument < args.length)
|
|
201
|
+
return { kind: "node", node: args[argument] };
|
|
202
|
+
const name = "call" in locator ? elementNameEcho(locator.call) : `@${elementNameEcho(locator.decorator)}`;
|
|
203
|
+
if (argument > args.length)
|
|
204
|
+
fail(`"${name}" is called with ${args.length} arguments; only argument ${args.length} can be created`);
|
|
205
|
+
return missingLevels(locator.path, 0, `argument ${argument}`, fail, (keys) => ({ kind: "addArgument", owner, keys }));
|
|
206
|
+
}
|
|
207
|
+
// Only keys can be created: a match segment names an element that does not exist yet.
|
|
208
|
+
function missingLevels(path, from, missing, fail, placement) {
|
|
209
|
+
const keys = path.slice(from);
|
|
210
|
+
if (keys.every((segment) => typeof segment === "string"))
|
|
211
|
+
return placement(keys);
|
|
212
|
+
fail(`${missing} is missing and cannot be created before a match segment`);
|
|
213
|
+
}
|
|
214
|
+
function locate(ast, locator, item, fail) {
|
|
215
|
+
const root = locateRoot(ast, locator, fail);
|
|
216
|
+
if (root.kind !== "node")
|
|
217
|
+
return root;
|
|
218
|
+
let node = unwrap(root.node);
|
|
219
|
+
for (const [index, segment] of locator.path.entries()) {
|
|
220
|
+
if (typeof segment === "string") {
|
|
221
|
+
if (!Node.isObjectLiteralExpression(node))
|
|
222
|
+
fail(`path[${index}] "${elementNameEcho(segment)}" expects an object literal`);
|
|
223
|
+
const object = node;
|
|
224
|
+
const members = object.getProperties().filter((member) => propertyKey(member) === segment);
|
|
225
|
+
if (members.length === 0) {
|
|
226
|
+
// A spread or a computed key may already supply the key; a created one would shadow it.
|
|
227
|
+
const opaque = object
|
|
228
|
+
.getProperties()
|
|
229
|
+
.some((member) => Node.isSpreadAssignment(member) || (Node.hasName(member) && Node.isComputedPropertyName(member.getNameNode())));
|
|
230
|
+
if (opaque)
|
|
231
|
+
fail(`path[${index}] "${elementNameEcho(segment)}" may already come from a spread or a computed key, so it cannot be created`);
|
|
232
|
+
const missing = `path[${index}] "${elementNameEcho(segment)}"`;
|
|
233
|
+
return missingLevels(locator.path, index, missing, fail, (keys) => ({ kind: "addProperty", object, keys }));
|
|
234
|
+
}
|
|
235
|
+
if (members.length > 1)
|
|
236
|
+
fail(`path[${index}] "${elementNameEcho(segment)}" is assigned ${members.length} times`);
|
|
237
|
+
const member = members[0];
|
|
238
|
+
if (!Node.isPropertyAssignment(member))
|
|
239
|
+
fail(`path[${index}] "${elementNameEcho(segment)}" is not a plain property assignment`);
|
|
240
|
+
node = unwrap(member.getInitializerOrThrow());
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
if (!Node.isArrayLiteralExpression(node))
|
|
244
|
+
fail(`path[${index}] expects an array literal`);
|
|
245
|
+
const [[key, value]] = Object.entries(segment);
|
|
246
|
+
const matches = node.getElements().filter((element) => {
|
|
247
|
+
const candidate = unwrap(element);
|
|
248
|
+
if (!Node.isObjectLiteralExpression(candidate))
|
|
249
|
+
return false;
|
|
250
|
+
const property = candidate.getProperties().find((member) => propertyKey(member) === key);
|
|
251
|
+
return Node.isPropertyAssignment(property) && stringValue(property.getInitializer()) === value;
|
|
252
|
+
});
|
|
253
|
+
if (matches.length === 0)
|
|
254
|
+
fail(`path[${index}] matched no element`);
|
|
255
|
+
if (matches.length > 1)
|
|
256
|
+
fail(`path[${index}] matched ${matches.length} elements; exactly one is required`);
|
|
257
|
+
node = unwrap(matches[0]);
|
|
258
|
+
}
|
|
259
|
+
if (!Node.isArrayLiteralExpression(node))
|
|
260
|
+
fail("the target is not an array literal");
|
|
261
|
+
const itemTokens = tokensOf(item);
|
|
262
|
+
const present = node.getElements().some((element) => sameTokens(tokensOf(element), itemTokens));
|
|
263
|
+
return present ? { kind: "present" } : { kind: "append", list: node };
|
|
264
|
+
}
|
|
265
|
+
// `keys` are the levels still missing below the located node; the last one holds the array.
|
|
266
|
+
function nested(keys, item) {
|
|
267
|
+
return keys.reduceRight((inner, key) => `{ ${key}: ${inner} }`, `[${item}]`);
|
|
268
|
+
}
|
|
269
|
+
function locatorEcho(locator) {
|
|
270
|
+
const path = locator.path.map((segment) => typeof segment === "string"
|
|
271
|
+
? elementNameEcho(segment)
|
|
272
|
+
: Object.fromEntries(Object.entries(segment).map(([k, v]) => [elementNameEcho(k), elementNameEcho(v)])));
|
|
273
|
+
if ("variable" in locator)
|
|
274
|
+
return JSON.stringify({ variable: elementNameEcho(locator.variable), path });
|
|
275
|
+
if ("call" in locator)
|
|
276
|
+
return JSON.stringify({ call: elementNameEcho(locator.call), argument: locator.argument, path });
|
|
277
|
+
return JSON.stringify({ decorator: elementNameEcho(locator.decorator), path });
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Appends `element` to the array literal `locator` points at, keeping the list's layout. The
|
|
281
|
+
* locator starts at a top-level variable, an argument of the only call to a callee, or the
|
|
282
|
+
* only decorator with a name, then follows `path`: a string is an object key, and
|
|
283
|
+
* `{ key: "value" }` selects the only array element whose `key` is that string. Missing keys and
|
|
284
|
+
* the next missing call argument are created; a missing root or matched element rejects. An
|
|
285
|
+
* element already listed, compared token by token, is a no-op. The element is an identifier, or
|
|
286
|
+
* `{ expression }` for code, which must parse as exactly one expression and is otherwise
|
|
287
|
+
* author-trusted, like `addFunction`'s `source`.
|
|
288
|
+
*/
|
|
289
|
+
export function addArrayElement(ast, locator, element) {
|
|
290
|
+
assertLocator(locator);
|
|
291
|
+
appendArrayElement(ast, locator, element, `addArrayElement(${locatorEcho(locator)})`);
|
|
292
|
+
}
|
|
293
|
+
/** The validated source text of `element`; rejects like `addArrayElement` does. */
|
|
294
|
+
export function elementText(element) {
|
|
295
|
+
return elementNode(element).getText();
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* `addArrayElement` for a dialect that builds `locator` itself: `label` heads the reject
|
|
299
|
+
* tail in place of `addArrayElement(<locator>)`.
|
|
300
|
+
*/
|
|
301
|
+
export function appendArrayElement(ast, locator, element, label) {
|
|
302
|
+
const node = elementNode(element);
|
|
303
|
+
const item = node.getText();
|
|
304
|
+
const fail = (reason) => {
|
|
305
|
+
throw dialectError(`${label} on "${handlePathFor(ast)}" — ${reason}. Edit it with .modify().`);
|
|
306
|
+
};
|
|
307
|
+
const placement = locate(ast, locator, node, fail);
|
|
308
|
+
switch (placement.kind) {
|
|
309
|
+
case "present":
|
|
310
|
+
return;
|
|
311
|
+
case "append":
|
|
312
|
+
appendEntry(ast, placement.list, placement.list.getElements(), item, `[${item}]`);
|
|
313
|
+
return;
|
|
314
|
+
case "addProperty": {
|
|
315
|
+
const [key, ...rest] = placement.keys;
|
|
316
|
+
const entry = `${key}: ${nested(rest, item)}`;
|
|
317
|
+
appendEntry(ast, placement.object, placement.object.getProperties(), entry, `{ ${entry} }`);
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
case "addArgument":
|
|
321
|
+
placement.owner.addArgument(nested(placement.keys, item));
|
|
322
|
+
}
|
|
323
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type ClassDeclaration, type SourceFile } from "ts-morph";
|
|
2
|
+
export type ClassPropertyOptions = {
|
|
3
|
+
scope?: "public" | "protected" | "private";
|
|
4
|
+
readonly?: boolean;
|
|
5
|
+
};
|
|
6
|
+
/** A property to insert; `initializer` is already validated as one expression. */
|
|
7
|
+
export type ClassProperty = ClassPropertyOptions & {
|
|
8
|
+
name: string;
|
|
9
|
+
initializer: string;
|
|
10
|
+
};
|
|
11
|
+
export declare function assertClassPropertyOptions(options: unknown): asserts options is ClassPropertyOptions | undefined;
|
|
12
|
+
/**
|
|
13
|
+
* Inserts `property` into `cls`: after its last property, else before its first member, else
|
|
14
|
+
* into its empty body. A member named `property.name` with the same declaration is a no-op;
|
|
15
|
+
* any other member with that name rejects through `fail`.
|
|
16
|
+
*/
|
|
17
|
+
export declare function insertClassProperty(ast: SourceFile, cls: ClassDeclaration, property: ClassProperty, fail: (reason: string) => never): void;
|
|
18
|
+
/**
|
|
19
|
+
* Adds `{scope }{readonly }name = initializer;` to the only class named `className`, after its
|
|
20
|
+
* last property, else as its first member, keeping the members' indentation. `initializer` must
|
|
21
|
+
* parse as exactly one expression and is otherwise author-trusted. A property with the same
|
|
22
|
+
* declaration is a no-op; any other member named `name` rejects.
|
|
23
|
+
*/
|
|
24
|
+
export declare function addClassProperty(ast: SourceFile, className: string, name: string, initializer: string, options?: ClassPropertyOptions): void;
|
|
@@ -0,0 +1,98 @@
|
|
|
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 { elementText, tokensOf } from "./array-element.js";
|
|
7
|
+
import { parse } from "./ast.js";
|
|
8
|
+
const OPTIONS_SHAPE = '`options` must be { scope?, readonly? } with scope "public", "protected" or "private" — fix the options, or use ' +
|
|
9
|
+
"`.modify()` to make this edit directly.";
|
|
10
|
+
export function assertClassPropertyOptions(options) {
|
|
11
|
+
if (options === undefined)
|
|
12
|
+
return;
|
|
13
|
+
const valid = typeof options === "object" &&
|
|
14
|
+
options !== null &&
|
|
15
|
+
Object.keys(options).every((key) => key === "scope" || key === "readonly") &&
|
|
16
|
+
[undefined, "public", "protected", "private"].includes(options.scope) &&
|
|
17
|
+
[undefined, true, false].includes(options.readonly);
|
|
18
|
+
if (!valid)
|
|
19
|
+
throw dialectError(OPTIONS_SHAPE);
|
|
20
|
+
}
|
|
21
|
+
function declarationOf(property) {
|
|
22
|
+
const modifiers = [property.scope, property.readonly ? "readonly" : undefined].filter((m) => m !== undefined);
|
|
23
|
+
return [...modifiers, `${property.name} = ${property.initializer};`].join(" ");
|
|
24
|
+
}
|
|
25
|
+
// Tokens without a trailing `;`, so `b = 1` and `b = 1;` are the same declaration.
|
|
26
|
+
function declarationTokens(node) {
|
|
27
|
+
const tokens = tokensOf(node);
|
|
28
|
+
return tokens.at(-1) === ";" ? tokens.slice(0, -1) : tokens;
|
|
29
|
+
}
|
|
30
|
+
function sameDeclaration(member, text) {
|
|
31
|
+
const parsed = parse(`class X {\n${text}\n}`).getClassOrThrow("X").getMembers()[0];
|
|
32
|
+
const a = declarationTokens(member);
|
|
33
|
+
const b = declarationTokens(parsed);
|
|
34
|
+
return a.length === b.length && a.every((token, index) => token === b[index]);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Inserts `property` into `cls`: after its last property, else before its first member, else
|
|
38
|
+
* into its empty body. A member named `property.name` with the same declaration is a no-op;
|
|
39
|
+
* any other member with that name rejects through `fail`.
|
|
40
|
+
*/
|
|
41
|
+
export function insertClassProperty(ast, cls, property, fail) {
|
|
42
|
+
const text = declarationOf(property);
|
|
43
|
+
const members = cls.getMembers();
|
|
44
|
+
const named = members.filter((member) => Node.hasName(member) && member.getName() === property.name);
|
|
45
|
+
if (named.length > 0) {
|
|
46
|
+
if (named.length === 1 && Node.isPropertyDeclaration(named[0]) && sameDeclaration(named[0], text))
|
|
47
|
+
return;
|
|
48
|
+
fail(`the class already has a different member named "${elementNameEcho(property.name)}"`);
|
|
49
|
+
}
|
|
50
|
+
const source = ast.getFullText();
|
|
51
|
+
const indentAt = (position) => /^[ \t]*/.exec(source.slice(source.lastIndexOf("\n", position - 1) + 1))[0];
|
|
52
|
+
const anchor = members.filter((member) => Node.isPropertyDeclaration(member)).at(-1);
|
|
53
|
+
if (anchor !== undefined) {
|
|
54
|
+
const lineEnd = source.indexOf("\n", anchor.getEnd());
|
|
55
|
+
const rest = source.slice(anchor.getEnd(), lineEnd === -1 ? source.length : lineEnd);
|
|
56
|
+
// Only trivia after the property means it ends its line: the new one goes on the next line.
|
|
57
|
+
if (lineEnd !== -1 && /^\s*(\/\/.*|\/\*.*\*\/\s*)?$/.test(rest))
|
|
58
|
+
ast.insertText(lineEnd, `\n${indentAt(anchor.getStart())}${text}`);
|
|
59
|
+
else
|
|
60
|
+
ast.insertText(anchor.getEnd(), ` ${text}`);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const first = members[0];
|
|
64
|
+
if (first !== undefined) {
|
|
65
|
+
const start = first.getStart(true);
|
|
66
|
+
const open = cls.getFirstChildByKindOrThrow(SyntaxKind.OpenBraceToken);
|
|
67
|
+
if (source.slice(open.getEnd(), start).includes("\n"))
|
|
68
|
+
ast.insertText(start, `${text}\n${indentAt(start)}`);
|
|
69
|
+
else
|
|
70
|
+
ast.insertText(start, `${text} `);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const open = cls.getFirstChildByKindOrThrow(SyntaxKind.OpenBraceToken);
|
|
74
|
+
const close = cls.getLastChildByKindOrThrow(SyntaxKind.CloseBraceToken);
|
|
75
|
+
const indent = indentAt(cls.getStart());
|
|
76
|
+
ast.replaceText([open.getEnd(), close.getStart()], `\n${indent} ${text}\n${indent}`);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Adds `{scope }{readonly }name = initializer;` to the only class named `className`, after its
|
|
80
|
+
* last property, else as its first member, keeping the members' indentation. `initializer` must
|
|
81
|
+
* parse as exactly one expression and is otherwise author-trusted. A property with the same
|
|
82
|
+
* declaration is a no-op; any other member named `name` rejects.
|
|
83
|
+
*/
|
|
84
|
+
export function addClassProperty(ast, className, name, initializer, options) {
|
|
85
|
+
assertValidImportBinding(className, "className");
|
|
86
|
+
assertValidImportBinding(name, "name");
|
|
87
|
+
assertClassPropertyOptions(options);
|
|
88
|
+
const value = elementText({ expression: initializer });
|
|
89
|
+
const fail = (reason) => {
|
|
90
|
+
throw dialectError(`addClassProperty("${elementNameEcho(className)}", "${elementNameEcho(name)}") on "${handlePathFor(ast)}" — ${reason}. Edit it with .modify().`);
|
|
91
|
+
};
|
|
92
|
+
const classes = ast.getDescendantsOfKind(SyntaxKind.ClassDeclaration).filter((cls) => cls.getName() === className);
|
|
93
|
+
if (classes.length === 0)
|
|
94
|
+
fail(`no class named "${elementNameEcho(className)}" was found`);
|
|
95
|
+
if (classes.length > 1)
|
|
96
|
+
fail(`${classes.length} classes are named "${elementNameEcho(className)}"; exactly one is required`);
|
|
97
|
+
insertClassProperty(ast, classes[0], { ...options, name, initializer: value }, fail);
|
|
98
|
+
}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { SourceFile } from "ts-morph";
|
|
2
2
|
import { type Handle } from "../../core/define-dialect.ts";
|
|
3
|
+
import type { ArrayElement, ArrayLocator } from "./array-element.ts";
|
|
4
|
+
import type { ClassPropertyOptions } from "./class-property.ts";
|
|
3
5
|
export * as astLibrary from "ts-morph";
|
|
4
6
|
type TypeScriptOps = {
|
|
5
7
|
addImport: (ast: SourceFile, name: string, from: string) => void;
|
|
@@ -26,13 +28,16 @@ type TypeScriptOps = {
|
|
|
26
28
|
removeExportAll: (ast: SourceFile, from: string, options?: {
|
|
27
29
|
as?: string;
|
|
28
30
|
}) => void;
|
|
31
|
+
addArrayElement: (ast: SourceFile, locator: ArrayLocator, element: ArrayElement) => void;
|
|
32
|
+
addClassProperty: (ast: SourceFile, className: string, name: string, initializer: string, options?: ClassPropertyOptions) => void;
|
|
29
33
|
};
|
|
30
34
|
/**
|
|
31
35
|
* Opens a TypeScript file for dialect-aware editing — the dialect's entry verb into a Session
|
|
32
36
|
* (REQ-DG-01.2). Returns an awaitable, chainable `Handle` exposing the universal `.modify()`
|
|
33
37
|
* escape hatch plus the dialect's named ops (`addImport`, `addDefaultImport`,
|
|
34
38
|
* `addNamespaceImport`, `addTypeImport`, `addSideEffectImport`, `addReExport`, `addExportAll`,
|
|
35
|
-
* `addFunction`, `addVariable`, `addClass`, `removeImport`, `removeExport`, `removeExportAll
|
|
39
|
+
* `addFunction`, `addVariable`, `addClass`, `removeImport`, `removeExport`, `removeExportAll`,
|
|
40
|
+
* `addArrayElement`, `addClassProperty`). Reads route through `Session.read` only (REQ-MC-03); edits
|
|
36
41
|
* coalesce into a single `modify` at flush (REQ-MC-01/02).
|
|
37
42
|
*
|
|
38
43
|
* @example
|
|
@@ -21,7 +21,8 @@ const typescriptDialect = withOps(baseDialect, opsPack);
|
|
|
21
21
|
* (REQ-DG-01.2). Returns an awaitable, chainable `Handle` exposing the universal `.modify()`
|
|
22
22
|
* escape hatch plus the dialect's named ops (`addImport`, `addDefaultImport`,
|
|
23
23
|
* `addNamespaceImport`, `addTypeImport`, `addSideEffectImport`, `addReExport`, `addExportAll`,
|
|
24
|
-
* `addFunction`, `addVariable`, `addClass`, `removeImport`, `removeExport`, `removeExportAll
|
|
24
|
+
* `addFunction`, `addVariable`, `addClass`, `removeImport`, `removeExport`, `removeExportAll`,
|
|
25
|
+
* `addArrayElement`, `addClassProperty`). Reads route through `Session.read` only (REQ-MC-03); edits
|
|
25
26
|
* coalesce into a single `modify` at flush (REQ-MC-01/02).
|
|
26
27
|
*
|
|
27
28
|
* @example
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { addImport, addDefaultImport, addNamespaceImport, addTypeImport, addSideEffectImport, addReExport, addExportAll, addFunction, addVariable, addClass, removeImport, removeExport, removeExportAll } from "./ops.ts";
|
|
2
|
+
import { addArrayElement } from "./array-element.ts";
|
|
3
|
+
import { addClassProperty } from "./class-property.ts";
|
|
2
4
|
export declare const typescriptOps: {
|
|
3
5
|
addImport: typeof addImport;
|
|
4
6
|
addDefaultImport: typeof addDefaultImport;
|
|
@@ -13,4 +15,6 @@ export declare const typescriptOps: {
|
|
|
13
15
|
removeImport: typeof removeImport;
|
|
14
16
|
removeExport: typeof removeExport;
|
|
15
17
|
removeExportAll: typeof removeExportAll;
|
|
18
|
+
addArrayElement: typeof addArrayElement;
|
|
19
|
+
addClassProperty: typeof addClassProperty;
|
|
16
20
|
};
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// The runtime op pack lives apart from index.ts so a dialect that extends TypeScript
|
|
2
2
|
// (src/dialects/nestjs) composes the same ops without importing the `find` entry point.
|
|
3
3
|
import { addImport, addDefaultImport, addNamespaceImport, addTypeImport, addSideEffectImport, addReExport, addExportAll, addFunction, addVariable, addClass, removeImport, removeExport, removeExportAll, } from "./ops.js";
|
|
4
|
+
import { addArrayElement } from "./array-element.js";
|
|
5
|
+
import { addClassProperty } from "./class-property.js";
|
|
4
6
|
export const typescriptOps = {
|
|
5
7
|
addImport,
|
|
6
8
|
addDefaultImport,
|
|
@@ -15,4 +17,6 @@ export const typescriptOps = {
|
|
|
15
17
|
removeImport,
|
|
16
18
|
removeExport,
|
|
17
19
|
removeExportAll,
|
|
20
|
+
addArrayElement,
|
|
21
|
+
addClassProperty,
|
|
18
22
|
};
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"manifestVersion": 1,
|
|
3
3
|
"algorithm": "sha256",
|
|
4
4
|
"entry": "dist/bin/pbuilder-runner.js",
|
|
5
|
-
"packageVersion": "0.
|
|
5
|
+
"packageVersion": "0.7.0",
|
|
6
6
|
"files": [
|
|
7
7
|
{
|
|
8
8
|
"path": "dist/bin/pbuilder-runner.js",
|
|
@@ -98,7 +98,7 @@
|
|
|
98
98
|
},
|
|
99
99
|
{
|
|
100
100
|
"path": "package.json",
|
|
101
|
-
"sha256": "
|
|
101
|
+
"sha256": "a2906e287cb0269c41091afa18cf1f4db8ee583753762b5bc1a868922dff87f8"
|
|
102
102
|
}
|
|
103
103
|
]
|
|
104
104
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pbuilder/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "The public TypeScript/Bun authoring layer for Project Builder schematics. Authors file mutations (create, replaceContent, remove, rename, move, copy, copyIn), lowers them to IR, and talks to the Project Builder engine over framed stdio (see docs/engine-sdk-wire-spec.md).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -78,6 +78,11 @@
|
|
|
78
78
|
"import": "./dist/dialects/nestjs/index.js",
|
|
79
79
|
"default": "./dist/dialects/nestjs/index.js"
|
|
80
80
|
},
|
|
81
|
+
"./angular": {
|
|
82
|
+
"types": "./dist/dialects/angular/index.d.ts",
|
|
83
|
+
"import": "./dist/dialects/angular/index.js",
|
|
84
|
+
"default": "./dist/dialects/angular/index.js"
|
|
85
|
+
},
|
|
81
86
|
"./yaml": {
|
|
82
87
|
"types": "./dist/dialects/yaml/index.d.ts",
|
|
83
88
|
"import": "./dist/dialects/yaml/index.js",
|