@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.
@@ -0,0 +1,43 @@
1
+ import type { SourceFile } from "ts-morph";
2
+ import { type Handle } from "../../core/define-dialect.ts";
3
+ import { typescriptOps } from "../typescript/pack.ts";
4
+ export * as astLibrary from "ts-morph";
5
+ type ModuleOps = {
6
+ addProvider: (ast: SourceFile, name: string, from: string) => void;
7
+ addController: (ast: SourceFile, name: string, from: string) => void;
8
+ addModuleImport: (ast: SourceFile, name: string, from: string) => void;
9
+ addExport: (ast: SourceFile, name: string, from: string) => void;
10
+ };
11
+ type NestOps = typeof typescriptOps & ModuleOps;
12
+ /**
13
+ * Opens a `.ts` file of a NestJS project for editing. The handle carries every
14
+ * `@pbuilder/sdk/typescript` op plus the `@Module` ops below, chained on one handle and
15
+ * written once.
16
+ *
17
+ * `addProvider`, `addController`, `addModuleImport` and `addExport` each take
18
+ * `(name, from)`: they add `import { name } from "from"` with the same rules as `addImport`,
19
+ * then append `name` to the `providers`, `controllers`, `imports` or `exports` array of the
20
+ * file's only `@Module` class, creating the metadata object or the array when missing. They
21
+ * reject, leaving the file unchanged, when the file has no `@Module` class or more than one,
22
+ * or when the metadata or the array is not a literal. Use `.modify(fn)` for those files and
23
+ * for entries that are not a plain class name, such as `ConfigModule.forRoot()`.
24
+ *
25
+ * @example
26
+ * import * as nestjs from "@pbuilder/sdk/nestjs";
27
+ *
28
+ * // src/app.module.ts before:
29
+ * // @Module({ providers: [AppService] })
30
+ * // export class AppModule {}
31
+ * export const run = async () => {
32
+ * await nestjs
33
+ * .find("src/app.module.ts")
34
+ * .addModuleImport("UsersModule", "./users/users.module")
35
+ * .addProvider("UsersService", "./users/users.service");
36
+ * };
37
+ * // -> import { UsersModule } from "./users/users.module";
38
+ * // -> import { UsersService } from "./users/users.service";
39
+ * // ->
40
+ * // -> @Module({ providers: [AppService, UsersService], imports: [UsersModule] })
41
+ * // -> export class AppModule {}
42
+ */
43
+ export declare function find(path: string): Handle<"found", SourceFile, NestOps>;
@@ -0,0 +1,46 @@
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 { addController, addExport, addModuleImport, addProvider } from "./ops.js";
5
+ export * as astLibrary from "ts-morph";
6
+ const moduleOps = defineOpPack({ addProvider, addController, addModuleImport, addExport });
7
+ const baseDialect = defineDialect({
8
+ extensions: [".ts"],
9
+ ast: { parse, print },
10
+ ops: {},
11
+ });
12
+ const nestjsDialect = withOps(baseDialect, typescriptOps, moduleOps);
13
+ /**
14
+ * Opens a `.ts` file of a NestJS project for editing. The handle carries every
15
+ * `@pbuilder/sdk/typescript` op plus the `@Module` ops below, chained on one handle and
16
+ * written once.
17
+ *
18
+ * `addProvider`, `addController`, `addModuleImport` and `addExport` each take
19
+ * `(name, from)`: they add `import { name } from "from"` with the same rules as `addImport`,
20
+ * then append `name` to the `providers`, `controllers`, `imports` or `exports` array of the
21
+ * file's only `@Module` class, creating the metadata object or the array when missing. They
22
+ * reject, leaving the file unchanged, when the file has no `@Module` class or more than one,
23
+ * or when the metadata or the array is not a literal. Use `.modify(fn)` for those files and
24
+ * for entries that are not a plain class name, such as `ConfigModule.forRoot()`.
25
+ *
26
+ * @example
27
+ * import * as nestjs from "@pbuilder/sdk/nestjs";
28
+ *
29
+ * // src/app.module.ts before:
30
+ * // @Module({ providers: [AppService] })
31
+ * // export class AppModule {}
32
+ * export const run = async () => {
33
+ * await nestjs
34
+ * .find("src/app.module.ts")
35
+ * .addModuleImport("UsersModule", "./users/users.module")
36
+ * .addProvider("UsersService", "./users/users.service");
37
+ * };
38
+ * // -> import { UsersModule } from "./users/users.module";
39
+ * // -> import { UsersService } from "./users/users.service";
40
+ * // ->
41
+ * // -> @Module({ providers: [AppService, UsersService], imports: [UsersModule] })
42
+ * // -> export class AppModule {}
43
+ */
44
+ export function find(path) {
45
+ return nestjsDialect.find(path);
46
+ }
@@ -0,0 +1,13 @@
1
+ import { type SourceFile } from "ts-morph";
2
+ /**
3
+ * Imports `name` from `from` and adds it to the `providers` array of the file's only
4
+ * `@Module` class, creating the metadata object or the array when missing. An entry already
5
+ * named `name` is left as it is.
6
+ */
7
+ export declare const addProvider: (ast: SourceFile, name: string, from: string) => void;
8
+ /** Same as `addProvider`, for the `controllers` array. */
9
+ export declare const addController: (ast: SourceFile, name: string, from: string) => void;
10
+ /** Same as `addProvider`, for the `imports` array (other Nest modules). */
11
+ export declare const addModuleImport: (ast: SourceFile, name: string, from: string) => void;
12
+ /** Same as `addProvider`, for the `exports` array. */
13
+ export declare const addExport: (ast: SourceFile, name: string, from: string) => void;
@@ -0,0 +1,75 @@
1
+ import { 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 { appendEntry } from "../typescript/array-element.js";
6
+ import { addImport } from "../typescript/ops.js";
7
+ function moduleDecorator(ast, fail) {
8
+ const decorators = ast
9
+ .getClasses()
10
+ .map((cls) => cls.getDecorator("Module"))
11
+ .filter((decorator) => decorator !== undefined);
12
+ if (decorators.length === 0)
13
+ fail("no class decorated with @Module was found");
14
+ if (decorators.length > 1)
15
+ fail(`${decorators.length} classes are decorated with @Module; exactly one is required`);
16
+ return decorators[0];
17
+ }
18
+ function locate(ast, property, name, fail) {
19
+ const decorator = moduleDecorator(ast, fail);
20
+ const [metadata] = decorator.getArguments();
21
+ if (metadata === undefined)
22
+ return { kind: "addArgument", decorator };
23
+ if (metadata.getKind() !== SyntaxKind.ObjectLiteralExpression)
24
+ fail("the @Module argument is not an object literal");
25
+ const object = metadata.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);
26
+ const member = object.getProperty(property);
27
+ if (member === undefined)
28
+ return { kind: "addProperty", metadata: object };
29
+ const list = member.asKind(SyntaxKind.PropertyAssignment)?.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression);
30
+ if (list === undefined)
31
+ fail(`@Module "${property}" is not an array literal`);
32
+ if (list.getElements().some((element) => element.getText() === name))
33
+ return { kind: "present" };
34
+ return { kind: "append", list };
35
+ }
36
+ function write(ast, placement, property, name) {
37
+ const entry = `${property}: [${name}]`;
38
+ switch (placement.kind) {
39
+ case "present":
40
+ return;
41
+ case "append":
42
+ appendEntry(ast, placement.list, placement.list.getElements(), name, `[${name}]`);
43
+ return;
44
+ case "addProperty":
45
+ appendEntry(ast, placement.metadata, placement.metadata.getProperties(), entry, `{ ${entry} }`);
46
+ return;
47
+ case "addArgument":
48
+ placement.decorator.addArgument(`{ ${entry} }`);
49
+ }
50
+ }
51
+ function moduleArrayOp(verb, property) {
52
+ return (ast, name, from) => {
53
+ assertValidImportBinding(name);
54
+ const fail = (reason) => {
55
+ throw dialectError(`${verb}("${name}") on "${handlePathFor(ast)}" — ${reason}. Edit it with .modify().`);
56
+ };
57
+ // Locating first rejects an unusable @Module before addImport mutates the file; the
58
+ // nodes are located again afterwards because addImport may have rewritten them.
59
+ locate(ast, property, name, fail);
60
+ addImport(ast, name, from);
61
+ write(ast, locate(ast, property, name, fail), property, name);
62
+ };
63
+ }
64
+ /**
65
+ * Imports `name` from `from` and adds it to the `providers` array of the file's only
66
+ * `@Module` class, creating the metadata object or the array when missing. An entry already
67
+ * named `name` is left as it is.
68
+ */
69
+ export const addProvider = moduleArrayOp("addProvider", "providers");
70
+ /** Same as `addProvider`, for the `controllers` array. */
71
+ export const addController = moduleArrayOp("addController", "controllers");
72
+ /** Same as `addProvider`, for the `imports` array (other Nest modules). */
73
+ export const addModuleImport = moduleArrayOp("addModuleImport", "imports");
74
+ /** Same as `addProvider`, for the `exports` array. */
75
+ export const addExport = moduleArrayOp("addExport", "exports");
@@ -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;