@pbuilder/sdk 0.5.1 → 0.10.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,216 @@
1
+ import { atRule, decl, parse, rule } from "postcss";
2
+ import { dialectError } from "../../core/dialect-error.js";
3
+ import { validatedOp } from "../../core/jsx-name-validator.js";
4
+ const REGULAR_PROPERTY = /^-?[A-Za-z_][A-Za-z0-9_-]*$/;
5
+ // `*` admits Tailwind's namespace resets (`--color-*: initial`).
6
+ const CUSTOM_PROPERTY = /^--[A-Za-z0-9_*\u0080-\uFFFF-]+$/;
7
+ const AT_RULE_NAME = /^[A-Za-z][A-Za-z0-9-]*$/;
8
+ function label(target) {
9
+ const at = target.atRule === undefined ? [] : [`@${target.atRule} ${target.params?.trim() ?? ""}`.trim()];
10
+ return [...at, ...(target.selector === undefined ? [] : [target.selector.trim()])].join(" ");
11
+ }
12
+ function fail(op, target, why) {
13
+ throw dialectError(`${op}(${label(target)}) — ${why}`);
14
+ }
15
+ function tryParse(css) {
16
+ try {
17
+ return parse(css);
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ }
23
+ // The selector, params, and value checks re-parse the argument alone and require PostCSS to
24
+ // read back exactly one node with the same text: anything that would close the node or add
25
+ // another one (`;`, `}`, `{`) is rejected before it can reach the printed file.
26
+ function assertTarget(op, target) {
27
+ const t = target;
28
+ const shaped = typeof target === "object" && target !== null && [t.selector, t.atRule, t.params].every((v) => v === undefined || typeof v === "string");
29
+ if (!shaped)
30
+ throw dialectError(`${op} — a target is an object of string \`selector\`, \`atRule\`, and \`params\`.`);
31
+ if (t.params !== undefined && t.atRule === undefined)
32
+ throw dialectError(`${op} — \`params\` needs an \`atRule\`.`);
33
+ if (t.selector === undefined && t.atRule === undefined) {
34
+ throw dialectError(`${op} — a target needs a \`selector\`, an \`atRule\`, or both.`);
35
+ }
36
+ if (t.atRule !== undefined && !AT_RULE_NAME.test(t.atRule)) {
37
+ fail(op, t, `\`${t.atRule}\` is not an at-rule name; write it without \`@\`.`);
38
+ }
39
+ if (t.params !== undefined) {
40
+ const nodes = tryParse(`@${t.atRule} ${t.params}{}`)?.nodes;
41
+ if (nodes?.length !== 1 || nodes[0].type !== "atrule" || nodes[0].params !== t.params.trim()) {
42
+ fail(op, t, `\`${t.params}\` is not at-rule params.`);
43
+ }
44
+ }
45
+ if (t.selector !== undefined) {
46
+ const nodes = tryParse(`${t.selector}{}`)?.nodes;
47
+ if (t.selector.trim() === "" || nodes?.length !== 1 || nodes[0].type !== "rule" || nodes[0].selector !== t.selector.trim()) {
48
+ fail(op, t, `\`${t.selector}\` is not a single selector.`);
49
+ }
50
+ }
51
+ }
52
+ const isCustom = (property) => property.startsWith("--");
53
+ function assertProperty(op, target, property) {
54
+ if (typeof property !== "string" || !(isCustom(property) ? CUSTOM_PROPERTY : REGULAR_PROPERTY).test(property)) {
55
+ fail(op, target, `\`${String(property)}\` is not a CSS property name.`);
56
+ }
57
+ }
58
+ function assertValue(op, target, property, value) {
59
+ const parsed = typeof value === "string" ? tryParse(`a{${property}:${value}}`) : undefined;
60
+ const block = parsed?.nodes.length === 1 && parsed.first?.type === "rule" ? parsed.first.nodes : [];
61
+ const node = block.length === 1 && block[0].type === "decl" ? block[0] : undefined;
62
+ if (node?.important)
63
+ fail(op, target, "put `!important` in the `important` option, not in the value.");
64
+ // PostCSS keeps the surrounding whitespace of a custom property's value, so compare trimmed.
65
+ if (node === undefined || node.prop !== property || node.value.trim() === "" || node.value.trim() !== value.trim()) {
66
+ fail(op, target, `\`${String(value)}\` is not a single declaration value.`);
67
+ }
68
+ }
69
+ function assertOptions(op, target, options) {
70
+ if (options === undefined)
71
+ return;
72
+ if (typeof options !== "object" || options === null)
73
+ fail(op, target, "options must be an object.");
74
+ const { before, after, important } = options;
75
+ if (before !== undefined && after !== undefined)
76
+ fail(op, target, "pass `before` or `after`, not both.");
77
+ for (const anchor of [before, after])
78
+ if (anchor !== undefined)
79
+ assertProperty(op, target, anchor);
80
+ if (important !== undefined && typeof important !== "boolean")
81
+ fail(op, target, "`important` must be a boolean.");
82
+ }
83
+ function only(op, target, nodes, match) {
84
+ const found = nodes.filter(match);
85
+ if (found.length > 1)
86
+ fail(op, target, `\`${label(target)}\` matches ${found.length} blocks; the target is ambiguous.`);
87
+ return found[0];
88
+ }
89
+ function findBlock(op, root, target) {
90
+ let scope = root;
91
+ if (target.atRule !== undefined) {
92
+ const name = target.atRule.toLowerCase();
93
+ const params = target.params?.trim() ?? "";
94
+ scope = only(op, target, root.nodes, (node) => node.type === "atrule" && node.nodes !== undefined && node.name.toLowerCase() === name && node.params === params);
95
+ }
96
+ if (scope === undefined || target.selector === undefined)
97
+ return scope;
98
+ const selector = target.selector.trim();
99
+ return only(op, target, scope.nodes ?? [], (node) => node.type === "rule" && node.selector === selector);
100
+ }
101
+ function findDeclaration(op, target, block, property) {
102
+ const same = (prop) => (isCustom(property) ? prop === property : prop.toLowerCase() === property.toLowerCase());
103
+ const found = (block.nodes ?? []).filter((node) => node.type === "decl" && same(node.prop));
104
+ if (found.length > 1)
105
+ fail(op, target, `\`${property}\` is declared ${found.length} times in the block.`);
106
+ return found[0];
107
+ }
108
+ // The file's own newline and the indentation of its first top-level declaration, so a block the
109
+ // ops create reads like the blocks around it. PostCSS's own inference writes `selector{` here.
110
+ function styleOf(root) {
111
+ let indent = " ";
112
+ root.walkDecls((node) => {
113
+ if (node.parent?.parent?.type !== "root")
114
+ return;
115
+ // A declaration on its brace's line (`:root { --a: 1; }`) carries no indentation.
116
+ if (node.raws.before?.includes("\n"))
117
+ indent = /[ \t]*$/.exec(node.raws.before)[0] || indent;
118
+ return false;
119
+ });
120
+ return { newline: root.source?.input.css.includes("\r\n") ? "\r\n" : "\n", indent };
121
+ }
122
+ function place(parent, child, style) {
123
+ const level = parent.type === "root" ? 0 : parent.parent?.type === "root" ? 1 : 2;
124
+ const indent = style.indent.repeat(level);
125
+ if ((parent.nodes ?? []).length === 0) {
126
+ child.raws.before = parent.type === "root" ? "" : style.newline + indent;
127
+ parent.raws.after = style.newline + style.indent.repeat(Math.max(level - 1, 0));
128
+ if (parent.type !== "root")
129
+ parent.raws.semicolon = true;
130
+ }
131
+ else if (child.type !== "decl") {
132
+ child.raws.before = style.newline + style.newline + indent;
133
+ }
134
+ parent.append(child);
135
+ return child;
136
+ }
137
+ function createBlock(op, root, target) {
138
+ const style = styleOf(root);
139
+ let parent = root;
140
+ if (target.atRule !== undefined) {
141
+ const params = target.params?.trim() ?? "";
142
+ parent =
143
+ findBlock(op, root, { atRule: target.atRule, params }) ??
144
+ place(root, atRule({ name: target.atRule, params, raws: { afterName: params === "" ? "" : " ", between: " " } }), style);
145
+ }
146
+ if (target.selector === undefined)
147
+ return parent;
148
+ return place(parent, rule({ selector: target.selector.trim(), raws: { between: " " } }), style);
149
+ }
150
+ /**
151
+ * Sets `property` to `value` in the `target` block: an existing declaration is updated in place,
152
+ * a new one goes last in the block or next to the `before` / `after` anchor, and a missing block
153
+ * is created at the end of the file. Setting the value a declaration already has changes nothing.
154
+ */
155
+ export const setDeclaration = validatedOp(([target, property, value, options]) => {
156
+ assertTarget("setDeclaration", target);
157
+ assertProperty("setDeclaration", target, property);
158
+ assertValue("setDeclaration", target, property, value);
159
+ assertOptions("setDeclaration", target, options);
160
+ }, (root, target, property, value, options = {}) => {
161
+ const op = "setDeclaration";
162
+ const text = value.trim();
163
+ const important = options.important === true;
164
+ const block = findBlock(op, root, target);
165
+ const existing = block === undefined ? undefined : findDeclaration(op, target, block, property);
166
+ if (existing !== undefined) {
167
+ if (existing.value.trim() !== text)
168
+ existing.value = text;
169
+ if (existing.important !== important)
170
+ existing.important = important;
171
+ return;
172
+ }
173
+ const anchorName = options.before ?? options.after;
174
+ const anchor = anchorName === undefined || block === undefined ? undefined : findDeclaration(op, target, block, anchorName);
175
+ if (anchorName !== undefined && anchor === undefined)
176
+ fail(op, target, `the anchor \`${anchorName}\` is not declared in the block.`);
177
+ const created = decl({ prop: property, value: text, important });
178
+ if (anchor === undefined)
179
+ place(block ?? createBlock(op, root, target), created, styleOf(root));
180
+ else if (options.before !== undefined)
181
+ anchor.before(created);
182
+ else
183
+ anchor.after(created);
184
+ });
185
+ /**
186
+ * Reads `property` from the `target` block of a parsed `Root`, such as the one `.modify(fn)`
187
+ * receives: `{ value, important }`, or `undefined` when the block or declaration is missing.
188
+ * Not an op — it returns a value — so it is called directly, never chained on a handle.
189
+ *
190
+ * @example
191
+ * import * as css from "@pbuilder/sdk/css";
192
+ *
193
+ * // tokens.css: @theme {\n --radius: 4px;\n}\n
194
+ * export const run = async () => {
195
+ * await css.find("tokens.css").modify((root) => {
196
+ * const radius = css.getDeclaration(root, { atRule: "theme" }, "--radius");
197
+ * // -> { value: "4px", important: false }
198
+ * });
199
+ * };
200
+ */
201
+ export function getDeclaration(root, target, property) {
202
+ assertTarget("getDeclaration", target);
203
+ assertProperty("getDeclaration", target, property);
204
+ const block = findBlock("getDeclaration", root, target);
205
+ const found = block === undefined ? undefined : findDeclaration("getDeclaration", target, block, property);
206
+ return found === undefined ? undefined : { value: found.value.trim(), important: found.important === true };
207
+ }
208
+ /** Removes `property` from the `target` block; a missing block or declaration is a no-op. */
209
+ export const removeDeclaration = validatedOp(([target, property]) => {
210
+ assertTarget("removeDeclaration", target);
211
+ assertProperty("removeDeclaration", target, property);
212
+ }, (root, target, property) => {
213
+ const block = findBlock("removeDeclaration", root, target);
214
+ if (block !== undefined)
215
+ findDeclaration("removeDeclaration", target, block, property)?.remove();
216
+ });
@@ -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;