@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,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,8 +1,18 @@
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;
8
+ addDefaultImport: (ast: SourceFile, name: string, from: string) => void;
9
+ addNamespaceImport: (ast: SourceFile, name: string, from: string) => void;
10
+ addTypeImport: (ast: SourceFile, name: string, from: string) => void;
11
+ addSideEffectImport: (ast: SourceFile, from: string) => void;
12
+ addReExport: (ast: SourceFile, name: string, from: string) => void;
13
+ addExportAll: (ast: SourceFile, from: string, options?: {
14
+ as?: string;
15
+ }) => void;
6
16
  addFunction: (ast: SourceFile, name: string, source: string, options?: {
7
17
  export?: boolean;
8
18
  }) => void;
@@ -14,12 +24,20 @@ type TypeScriptOps = {
14
24
  export?: boolean;
15
25
  }) => void;
16
26
  removeImport: (ast: SourceFile, name: string, from: string) => void;
27
+ removeExport: (ast: SourceFile, name: string, from: string) => void;
28
+ removeExportAll: (ast: SourceFile, from: string, options?: {
29
+ as?: string;
30
+ }) => void;
31
+ addArrayElement: (ast: SourceFile, locator: ArrayLocator, element: ArrayElement) => void;
32
+ addClassProperty: (ast: SourceFile, className: string, name: string, initializer: string, options?: ClassPropertyOptions) => void;
17
33
  };
18
34
  /**
19
35
  * Opens a TypeScript file for dialect-aware editing — the dialect's entry verb into a Session
20
36
  * (REQ-DG-01.2). Returns an awaitable, chainable `Handle` exposing the universal `.modify()`
21
- * escape hatch plus the dialect's named ops (`addImport`, `addFunction`, `addVariable`,
22
- * `addClass`, `removeImport`). Reads route through `Session.read` only (REQ-MC-03); edits
37
+ * escape hatch plus the dialect's named ops (`addImport`, `addDefaultImport`,
38
+ * `addNamespaceImport`, `addTypeImport`, `addSideEffectImport`, `addReExport`, `addExportAll`,
39
+ * `addFunction`, `addVariable`, `addClass`, `removeImport`, `removeExport`, `removeExportAll`,
40
+ * `addArrayElement`, `addClassProperty`). Reads route through `Session.read` only (REQ-MC-03); edits
23
41
  * coalesce into a single `modify` at flush (REQ-MC-01/02).
24
42
  *
25
43
  * @example
@@ -7,15 +7,9 @@
7
7
  // then `ts.find(path)`.
8
8
  import { defineDialect, defineOpPack, withOps } from "../../core/define-dialect.js";
9
9
  import { parse, print } from "./ast.js";
10
- import { addImport, addFunction, addVariable, addClass, removeImport } from "./ops.js";
10
+ import { typescriptOps } from "./pack.js";
11
11
  export * as astLibrary from "ts-morph";
12
- const opsPack = defineOpPack({
13
- addImport,
14
- addFunction,
15
- addVariable,
16
- addClass,
17
- removeImport,
18
- });
12
+ const opsPack = defineOpPack(typescriptOps);
19
13
  const baseDialect = defineDialect({
20
14
  extensions: [".ts"],
21
15
  ast: { parse, print },
@@ -25,8 +19,10 @@ const typescriptDialect = withOps(baseDialect, opsPack);
25
19
  /**
26
20
  * Opens a TypeScript file for dialect-aware editing — the dialect's entry verb into a Session
27
21
  * (REQ-DG-01.2). Returns an awaitable, chainable `Handle` exposing the universal `.modify()`
28
- * escape hatch plus the dialect's named ops (`addImport`, `addFunction`, `addVariable`,
29
- * `addClass`, `removeImport`). Reads route through `Session.read` only (REQ-MC-03); edits
22
+ * escape hatch plus the dialect's named ops (`addImport`, `addDefaultImport`,
23
+ * `addNamespaceImport`, `addTypeImport`, `addSideEffectImport`, `addReExport`, `addExportAll`,
24
+ * `addFunction`, `addVariable`, `addClass`, `removeImport`, `removeExport`, `removeExportAll`,
25
+ * `addArrayElement`, `addClassProperty`). Reads route through `Session.read` only (REQ-MC-03); edits
30
26
  * coalesce into a single `modify` at flush (REQ-MC-01/02).
31
27
  *
32
28
  * @example
@@ -47,13 +47,42 @@ import { type SourceFile } from "ts-morph";
47
47
  * Idempotent: calling this twice with the same `name`+`from` produces a single import line,
48
48
  * never a duplicate (REQ-TSD-03.10).
49
49
  *
50
- * Trust boundary (REQ-TSD-13.5): `name` and `from` are the ONLY two channels this op
51
- * validates. `addFunction`/`addVariable`/`addClass`'s own `name`/`source`/`initializer`
52
- * arguments remain RAW-SPLICED, author-trusted input this change does NOT validate or
53
- * protect — that gap is tracked separately in `project/pending-changes`, out of this
54
- * change's scope.
50
+ * Trust boundary (REQ-TSD-13.5): every op in this dialect validates its `name` the same way
51
+ * (and `addVariable` its `kind`), but `addFunction`'s `source`, `addVariable`'s `initializer`
52
+ * and `addClass`'s `source` are code bodies, not identifiers — they remain RAW-SPLICED,
53
+ * author-trusted input that no op validates or escapes.
55
54
  */
56
55
  export declare function addImport(ast: SourceFile, name: string, from: string): void;
56
+ /**
57
+ * Adds `import name from "from";` (V2 REQ-TSD-13). `name` is validated first, as in
58
+ * `addImport`. A no-op when `from` already has the default import `name`. Rejects when `from`
59
+ * already has a default import under another name (a module has one default export), or when
60
+ * `name` is bound anywhere else in the file — a type-only `import type name` included. Merges
61
+ * into the first value declaration for `from` that has no default yet (`import name, { a }` or
62
+ * `import name, * as ns`); otherwise inserts a fresh declaration after any directive prologue.
63
+ */
64
+ export declare function addDefaultImport(ast: SourceFile, name: string, from: string): void;
65
+ /**
66
+ * Adds `import * as name from "from";` (V2 REQ-TSD-14). `name` is validated first. A no-op
67
+ * when `from` already has the namespace import `name`. Rejects when `from` already has a
68
+ * namespace import under another name, or when `name` is bound anywhere else. Merges into a
69
+ * default-only value declaration for `from` (`import Def, * as name`); a declaration with
70
+ * named imports cannot also hold a namespace import, so it gets a fresh declaration instead.
71
+ */
72
+ export declare function addNamespaceImport(ast: SourceFile, name: string, from: string): void;
73
+ /**
74
+ * Adds `import type { name } from "from";` (V2 REQ-TSD-15), always as its own declaration —
75
+ * never merged into another, never the inline `{ type name }` form. `name` is validated first.
76
+ * A no-op when any declaration for `from` already binds `name` through an unaliased (or
77
+ * self-aliased) named specifier, type-only or value: a value import already provides the type.
78
+ * Rejects when `name` is bound anywhere else.
79
+ */
80
+ export declare function addTypeImport(ast: SourceFile, name: string, from: string): void;
81
+ /**
82
+ * Adds `import "from";` (V2 REQ-TSD-16) as its own declaration. A no-op when that bare import
83
+ * already exists; an import that binds names from the same module does not count.
84
+ */
85
+ export declare function addSideEffectImport(ast: SourceFile, from: string): void;
57
86
  type DeclarationOptions = {
58
87
  export?: boolean;
59
88
  };
@@ -120,4 +149,35 @@ export declare function addClass(ast: SourceFile, name: string, source: string,
120
149
  * is first-match-only. Sibling declarations from the same module are never touched.
121
150
  */
122
151
  export declare function removeImport(ast: SourceFile, name: string, from: string): void;
152
+ /**
153
+ * Adds `export { name } from "from";` (V2 REQ-TSD-17), merging into the first non-type-only
154
+ * `export { … } from "from"` clause. `name` is validated first. A no-op when that module is
155
+ * already re-exported under `name` — matched by SOURCE name, so `export { name as Y }` counts.
156
+ * Rejects when the file already exports `name` any other way, including as the visible alias
157
+ * of another re-export: two exports sharing a name are invalid TypeScript.
158
+ */
159
+ export declare function addReExport(ast: SourceFile, name: string, from: string): void;
160
+ /**
161
+ * Adds `export * from "from";`, or `export * as ns from "from";` with `{ as: "ns" }` (V2
162
+ * REQ-TSD-18, extended with `as`). The two forms are different statements: each is a no-op
163
+ * only on its own output. `as` is validated like a name and rejects when the file already
164
+ * exports it.
165
+ */
166
+ export declare function addExportAll(ast: SourceFile, from: string, options?: {
167
+ as?: string;
168
+ }): void;
169
+ /**
170
+ * Removes the re-export of `name` from `export { … } from "from"` (V2 REQ-TSD-19), deleting
171
+ * the statement when it was the last specifier; an absent re-export is a no-op. Matched by
172
+ * SOURCE name: `export { name as Y }` matches `name`, never `Y`. Local `export { x }` and
173
+ * `export *` statements are never touched — see `removeExportAll`.
174
+ */
175
+ export declare function removeExport(ast: SourceFile, name: string, from: string): void;
176
+ /**
177
+ * Removes `export * from "from";`, or `export * as ns from "from";` with `{ as: "ns" }`. Each
178
+ * form only removes itself; an absent statement is a no-op.
179
+ */
180
+ export declare function removeExportAll(ast: SourceFile, from: string, options?: {
181
+ as?: string;
182
+ }): void;
123
183
  export {};
@@ -26,7 +26,7 @@
26
26
  // runs INLINE as `addImport`'s first statement, strictly BEFORE Step 1/2/3/4 ever evaluate
27
27
  // `name` (REQ-TSD-13.6 precedence pin). Its PATH-LESS reject shape is deliberately distinct
28
28
  // from Step 2's path-ful `dialectError` tail below — see `addImport`'s own JSDoc.
29
- import { SyntaxKind } from "ts-morph";
29
+ import { SyntaxKind, } from "ts-morph";
30
30
  import { dialectError } from "../../core/dialect-error.js";
31
31
  import { handlePathFor } from "../../core/dialect-handle.js";
32
32
  import { elementNameEcho } from "../../core/reject-tail.js";
@@ -193,11 +193,10 @@ function directiveInsertIndex(ast, directiveCount) {
193
193
  * Idempotent: calling this twice with the same `name`+`from` produces a single import line,
194
194
  * never a duplicate (REQ-TSD-03.10).
195
195
  *
196
- * Trust boundary (REQ-TSD-13.5): `name` and `from` are the ONLY two channels this op
197
- * validates. `addFunction`/`addVariable`/`addClass`'s own `name`/`source`/`initializer`
198
- * arguments remain RAW-SPLICED, author-trusted input this change does NOT validate or
199
- * protect — that gap is tracked separately in `project/pending-changes`, out of this
200
- * change's scope.
196
+ * Trust boundary (REQ-TSD-13.5): every op in this dialect validates its `name` the same way
197
+ * (and `addVariable` its `kind`), but `addFunction`'s `source`, `addVariable`'s `initializer`
198
+ * and `addClass`'s `source` are code bodies, not identifiers — they remain RAW-SPLICED,
199
+ * author-trusted input that no op validates or escapes.
201
200
  */
202
201
  export function addImport(ast, name, from) {
203
202
  // REQ-TSD-13 validation gate: a deliberately PATH-LESS reject (contrast Step 2's path-ful
@@ -220,46 +219,142 @@ export function addImport(ast, name, from) {
220
219
  return;
221
220
  const claimed = declarationBoundNames.some(([, bound]) => bound.some((b) => b.localName === name)) ||
222
221
  isValueNamespaceClaimed(ast, name);
223
- if (claimed) {
224
- // `name` is POST-VALIDATION here (Step 0 already ran) but its grammar has no length
225
- // ceiling — echoed through `elementNameEcho` (the wide, marked 100-char bound shared with
226
- // `setJsxProp`'s reject tails), never left raw, so a pathological-length name can't blow up
227
- // this message (REQ-TSD-01.32 pins realistic names, e.g. 29 chars, staying UNCUT).
228
- const echoedName = elementNameEcho(name);
229
- throw dialectError(`addImport("${echoedName}") on "${handlePathFor(ast)}" — a value or import binding named "${echoedName}" already exists; ` +
230
- `TypeScript forbids two bindings sharing a name. Rename or remove the existing one, or edit it with .modify().`);
231
- }
222
+ if (claimed)
223
+ throw claimedBindingError(ast, "addImport", name);
232
224
  const mergeTarget = declarationsForModule.find(isNonTypeOnlyNamedImportClause);
233
225
  if (mergeTarget !== undefined) {
234
226
  mergeTarget.addNamedImport(name);
235
227
  return;
236
228
  }
229
+ insertImport(ast, { moduleSpecifier: from, namedImports: [name] });
230
+ }
231
+ // True when `name` is already bound anywhere in the file: any import binding (default,
232
+ // namespace, or named, type-only included) or a top-level value-namespace declaration.
233
+ function isBindingClaimed(ast, name) {
234
+ return (isValueNamespaceClaimed(ast, name) ||
235
+ ast.getImportDeclarations().some((decl) => boundNamesIn(decl).some((bound) => bound.localName === name)));
236
+ }
237
+ // `name` is post-validation but its grammar has no length ceiling, so it is echoed through
238
+ // `elementNameEcho` (the marked 100-char bound shared with `setJsxProp`'s reject tails), never
239
+ // raw (REQ-TSD-01.32 pins realistic names, e.g. 29 chars, staying uncut).
240
+ function claimedBindingError(ast, opName, name) {
241
+ const echoedName = elementNameEcho(name);
242
+ return dialectError(`${opName}("${echoedName}") on "${handlePathFor(ast)}" — a value or import binding named "${echoedName}" already exists; ` +
243
+ `TypeScript forbids two bindings sharing a name. Rename or remove the existing one, or edit it with .modify().`);
244
+ }
245
+ // A fresh import declaration goes after a leading directive prologue, never above it
246
+ // (REQ-TSD-01.21).
247
+ function insertImport(ast, structure) {
237
248
  const directiveCount = leadingDirectiveCount(ast);
238
249
  if (directiveCount === 0) {
239
- ast.addImportDeclaration({ moduleSpecifier: from, namedImports: [name] });
250
+ ast.addImportDeclaration(structure);
240
251
  }
241
252
  else {
242
- ast.insertImportDeclaration(directiveInsertIndex(ast, directiveCount), {
243
- moduleSpecifier: from,
244
- namedImports: [name],
245
- });
253
+ ast.insertImportDeclaration(directiveInsertIndex(ast, directiveCount), structure);
254
+ }
255
+ }
256
+ // The value-bound (not whole-declaration type-only) declarations importing `from`.
257
+ function valueImportsOf(ast, from) {
258
+ return ast.getImportDeclarations().filter((decl) => decl.getModuleSpecifierValue() === from && !decl.isTypeOnly());
259
+ }
260
+ /**
261
+ * Adds `import name from "from";` (V2 REQ-TSD-13). `name` is validated first, as in
262
+ * `addImport`. A no-op when `from` already has the default import `name`. Rejects when `from`
263
+ * already has a default import under another name (a module has one default export), or when
264
+ * `name` is bound anywhere else in the file — a type-only `import type name` included. Merges
265
+ * into the first value declaration for `from` that has no default yet (`import name, { a }` or
266
+ * `import name, * as ns`); otherwise inserts a fresh declaration after any directive prologue.
267
+ */
268
+ export function addDefaultImport(ast, name, from) {
269
+ assertValidImportBinding(name);
270
+ const declarations = valueImportsOf(ast, from);
271
+ const existing = declarations.map((decl) => decl.getDefaultImport()?.getText()).find((text) => text !== undefined);
272
+ if (existing === name)
273
+ return;
274
+ if (existing !== undefined) {
275
+ throw dialectError(`addDefaultImport("${elementNameEcho(name)}") on "${handlePathFor(ast)}" — "${elementNameEcho(from)}" already has a default import named "${existing}"; ` +
276
+ "a module has one default export. Use that name, or remove the existing import first.");
277
+ }
278
+ if (isBindingClaimed(ast, name))
279
+ throw claimedBindingError(ast, "addDefaultImport", name);
280
+ const mergeTarget = declarations.find((decl) => decl.getImportClause() !== undefined);
281
+ if (mergeTarget !== undefined) {
282
+ mergeTarget.setDefaultImport(name);
283
+ return;
246
284
  }
285
+ insertImport(ast, { moduleSpecifier: from, defaultImport: name });
247
286
  }
287
+ /**
288
+ * Adds `import * as name from "from";` (V2 REQ-TSD-14). `name` is validated first. A no-op
289
+ * when `from` already has the namespace import `name`. Rejects when `from` already has a
290
+ * namespace import under another name, or when `name` is bound anywhere else. Merges into a
291
+ * default-only value declaration for `from` (`import Def, * as name`); a declaration with
292
+ * named imports cannot also hold a namespace import, so it gets a fresh declaration instead.
293
+ */
294
+ export function addNamespaceImport(ast, name, from) {
295
+ assertValidImportBinding(name);
296
+ const declarations = valueImportsOf(ast, from);
297
+ const existing = declarations.map((decl) => decl.getNamespaceImport()?.getText()).find((text) => text !== undefined);
298
+ if (existing === name)
299
+ return;
300
+ if (existing !== undefined) {
301
+ throw dialectError(`addNamespaceImport("${elementNameEcho(name)}") on "${handlePathFor(ast)}" — "${elementNameEcho(from)}" already has a namespace import named "${existing}"; ` +
302
+ "use that name, or remove the existing import first.");
303
+ }
304
+ if (isBindingClaimed(ast, name))
305
+ throw claimedBindingError(ast, "addNamespaceImport", name);
306
+ const mergeTarget = declarations.find((decl) => decl.getDefaultImport() !== undefined && decl.getImportClause()?.getNamedBindings() === undefined);
307
+ if (mergeTarget !== undefined) {
308
+ mergeTarget.setNamespaceImport(name);
309
+ return;
310
+ }
311
+ insertImport(ast, { moduleSpecifier: from, namespaceImport: name });
312
+ }
313
+ /**
314
+ * Adds `import type { name } from "from";` (V2 REQ-TSD-15), always as its own declaration —
315
+ * never merged into another, never the inline `{ type name }` form. `name` is validated first.
316
+ * A no-op when any declaration for `from` already binds `name` through an unaliased (or
317
+ * self-aliased) named specifier, type-only or value: a value import already provides the type.
318
+ * Rejects when `name` is bound anywhere else.
319
+ */
320
+ export function addTypeImport(ast, name, from) {
321
+ assertValidImportBinding(name);
322
+ const alreadyBound = ast
323
+ .getImportDeclarations()
324
+ .some((decl) => decl.getModuleSpecifierValue() === from &&
325
+ boundNamesIn(decl).some((bound) => bound.localName === name && bound.kind === "named" && (!bound.aliased || bound.selfAliased)));
326
+ if (alreadyBound)
327
+ return;
328
+ // A type-only import lives in the type namespace, so unlike `addImport` a local
329
+ // `type`/`interface` of the same name conflicts with it (TS2440).
330
+ const typeClaimed = ast.getTypeAlias(name) !== undefined || ast.getInterface(name) !== undefined;
331
+ if (typeClaimed || isBindingClaimed(ast, name))
332
+ throw claimedBindingError(ast, "addTypeImport", name);
333
+ insertImport(ast, { moduleSpecifier: from, isTypeOnly: true, namedImports: [name] });
334
+ }
335
+ /**
336
+ * Adds `import "from";` (V2 REQ-TSD-16) as its own declaration. A no-op when that bare import
337
+ * already exists; an import that binds names from the same module does not count.
338
+ */
339
+ export function addSideEffectImport(ast, from) {
340
+ const exists = ast
341
+ .getImportDeclarations()
342
+ .some((decl) => decl.getModuleSpecifierValue() === from && decl.getImportClause() === undefined);
343
+ if (exists)
344
+ return;
345
+ insertImport(ast, { moduleSpecifier: from });
346
+ }
347
+ const VARIABLE_KINDS = ["const", "let", "var"];
248
348
  function exportPrefixFor(options) {
249
349
  return options?.export === true ? "export " : "";
250
350
  }
251
351
  // ADR-0039 collision-namespace pin (owner ruling #4): a VALUE-namespace declaration
252
- // (`isValueNamespaceClaimed`, S-001-extracted, shared with `addImport`'s Step 2 above) OR a
253
- // named-import binding under `name` collides, cross-kind; `type`/`interface` are exempt
254
- // (legal TS coexistence). Syntactic search only (no language service, per REQ-TSD-02.3's own
255
- // no-LS commitment) — SourceFile-wide, not scope-aware (matches the "no language service
256
- // needed" owner framing; every signed scenario seeds top-level declarations only).
257
- //
258
- // Behaviour-preservation (S-001, ops-declarations.test.ts guard): the import-binding half of
259
- // this predicate stays NAMED-imports-only, UNCHANGED by the extraction — `addFunction`/
260
- // `addVariable`/`addClass` stay blind to a default/namespace import collision, same as
261
- // before (design §4.8's registered "sibling collision-scan asymmetry" followup, not closed
262
- // by this change).
352
+ // (`isValueNamespaceClaimed`, S-001-extracted, shared with `addImport`'s Step 2 above) OR any
353
+ // import binding under `name` — default, namespace, or named, via the same `boundNamesIn`
354
+ // walk `addImport` uses — collides, cross-kind; `type`/`interface` are exempt (legal TS
355
+ // coexistence). Syntactic search only (no language service, per REQ-TSD-02.3's own no-LS
356
+ // commitment) — SourceFile-wide, not scope-aware (matches the "no language service needed"
357
+ // owner framing; every signed scenario seeds top-level declarations only).
263
358
  //
264
359
  // `handlePathFor(ast)` (final-verify fix, dialect-handle.ts) is the ONLY channel through
265
360
  // which an op function can recover the author-facing path for its own dialectError()-branded
@@ -267,11 +362,7 @@ function exportPrefixFor(options) {
267
362
  // live AST instance, not a runtime argument position), so it can never collide with `name`/
268
363
  // `options` regardless of which trailing args the author omitted.
269
364
  function assertNoCollision(ast, name, opName) {
270
- const collides = isValueNamespaceClaimed(ast, name) ||
271
- ast
272
- .getImportDeclarations()
273
- .some((decl) => decl.getNamedImports().some((named) => (named.getAliasNode()?.getText() ?? named.getName()) === name));
274
- if (!collides)
365
+ if (!isBindingClaimed(ast, name))
275
366
  return;
276
367
  throw dialectError(`${opName}("${name}") on "${handlePathFor(ast)}" — a value or import binding named "${name}" already exists; ` +
277
368
  `TypeScript forbids two value declarations sharing a name. Rename or remove the existing one, or edit it with .modify().`);
@@ -291,6 +382,7 @@ function assertNoCollision(ast, name, opName) {
291
382
  * // contrast addClass, whose source EXCLUDES braces (the op adds them).
292
383
  */
293
384
  export function addFunction(ast, name, source, options) {
385
+ assertValidImportBinding(name);
294
386
  assertNoCollision(ast, name, "addFunction");
295
387
  ast.addStatements(`${exportPrefixFor(options)}function ${name}${source}`);
296
388
  }
@@ -305,8 +397,15 @@ export function addFunction(ast, name, source, options) {
305
397
  * ts.find(path).addVariable("counter", "0", { export: true, kind: "let" }); // -> export let counter = 0;
306
398
  */
307
399
  export function addVariable(ast, name, initializer, options) {
308
- assertNoCollision(ast, name, "addVariable");
400
+ assertValidImportBinding(name);
309
401
  const kind = options?.kind ?? "const";
402
+ // `kind` is spliced into the emitted statement, so a value outside the TS type (a cast, or
403
+ // a plain-JS caller) must never reach `addStatements`; it is never echoed back.
404
+ if (!VARIABLE_KINDS.includes(kind)) {
405
+ throw dialectError(`addVariable("${name}") on "${handlePathFor(ast)}" — \`kind\` must be "const", "let", or "var". ` +
406
+ "Fix the option, or edit the file with .modify().");
407
+ }
408
+ assertNoCollision(ast, name, "addVariable");
310
409
  ast.addStatements(`${exportPrefixFor(options)}${kind} ${name} = ${initializer};`);
311
410
  }
312
411
  /**
@@ -324,6 +423,7 @@ export function addVariable(ast, name, initializer, options) {
324
423
  * // contrast addFunction, whose source INCLUDES braces (the op does NOT add them itself).
325
424
  */
326
425
  export function addClass(ast, name, source, options) {
426
+ assertValidImportBinding(name);
327
427
  assertNoCollision(ast, name, "addClass");
328
428
  ast.addStatements(`${exportPrefixFor(options)}class ${name} {\n${source}\n}`);
329
429
  }
@@ -347,6 +447,7 @@ export function addClass(ast, name, source, options) {
347
447
  * is first-match-only. Sibling declarations from the same module are never touched.
348
448
  */
349
449
  export function removeImport(ast, name, from) {
450
+ assertValidImportBinding(name);
350
451
  const decls = ast.getImportDeclarations().filter((d) => d.getModuleSpecifierValue() === from);
351
452
  for (const decl of decls) {
352
453
  const namedImports = decl.getNamedImports();
@@ -363,3 +464,137 @@ export function removeImport(ast, name, from) {
363
464
  return;
364
465
  }
365
466
  }
467
+ // Every name the file already exports: re-export specifiers (by their visible name),
468
+ // `export * as ns`, and exported top-level declarations. Syntactic only, like the import-side
469
+ // collision scan — no language service.
470
+ function exportedNamesOf(ast) {
471
+ const names = [];
472
+ for (const decl of ast.getExportDeclarations()) {
473
+ for (const specifier of decl.getNamedExports()) {
474
+ names.push(specifier.getAliasNode()?.getText() ?? specifier.getName());
475
+ }
476
+ const namespaceExport = decl.getNamespaceExport();
477
+ if (namespaceExport !== undefined)
478
+ names.push(namespaceExport.getName());
479
+ }
480
+ const declarations = [
481
+ ...ast.getFunctions(),
482
+ ...ast.getClasses(),
483
+ ...ast.getInterfaces(),
484
+ ...ast.getTypeAliases(),
485
+ ...ast.getEnums(),
486
+ ...ast.getModules(),
487
+ ];
488
+ for (const declaration of declarations) {
489
+ const name = declaration.getName();
490
+ if (declaration.isExported() && name !== undefined)
491
+ names.push(name);
492
+ }
493
+ for (const statement of ast.getVariableStatements()) {
494
+ if (!statement.isExported())
495
+ continue;
496
+ for (const declaration of statement.getDeclarations()) {
497
+ const nameNode = declaration.getNameNode();
498
+ if (nameNode.getKind() === SyntaxKind.Identifier) {
499
+ names.push(nameNode.getText());
500
+ continue;
501
+ }
502
+ // A destructuring pattern binds each element's own name (`{ a: X }` binds `X`, not `a`).
503
+ for (const element of nameNode.getDescendantsOfKind(SyntaxKind.BindingElement)) {
504
+ const elementName = element.getNameNode();
505
+ if (elementName.getKind() === SyntaxKind.Identifier)
506
+ names.push(elementName.getText());
507
+ }
508
+ }
509
+ }
510
+ return names;
511
+ }
512
+ function assertNotExported(ast, name, opName) {
513
+ if (!exportedNamesOf(ast).includes(name))
514
+ return;
515
+ const echoedName = elementNameEcho(name);
516
+ throw dialectError(`${opName}("${echoedName}") on "${handlePathFor(ast)}" — the file already exports a binding named "${echoedName}"; ` +
517
+ "TypeScript forbids two exports sharing a name. Rename or remove the existing one, or edit it with .modify().");
518
+ }
519
+ function exportsOf(ast, from) {
520
+ return ast.getExportDeclarations().filter((decl) => decl.getModuleSpecifierValue() === from);
521
+ }
522
+ // `export * from "m"` when `as` is undefined, `export * as ns from "m"` when it is "ns".
523
+ function isExportAll(decl, as) {
524
+ if (decl.isTypeOnly())
525
+ return false;
526
+ if (as === undefined)
527
+ return decl.compilerNode.exportClause === undefined;
528
+ return decl.getNamespaceExport()?.getName() === as;
529
+ }
530
+ /**
531
+ * Adds `export { name } from "from";` (V2 REQ-TSD-17), merging into the first non-type-only
532
+ * `export { … } from "from"` clause. `name` is validated first. A no-op when that module is
533
+ * already re-exported under `name` — matched by SOURCE name, so `export { name as Y }` counts.
534
+ * Rejects when the file already exports `name` any other way, including as the visible alias
535
+ * of another re-export: two exports sharing a name are invalid TypeScript.
536
+ */
537
+ export function addReExport(ast, name, from) {
538
+ assertValidImportBinding(name);
539
+ const declarations = exportsOf(ast, from).filter((decl) => !decl.isTypeOnly());
540
+ const alreadyExported = declarations.some((decl) => decl.getNamedExports().some((specifier) => specifier.getName() === name && !specifier.isTypeOnly()));
541
+ if (alreadyExported)
542
+ return;
543
+ assertNotExported(ast, name, "addReExport");
544
+ const mergeTarget = declarations.find((decl) => decl.hasNamedExports());
545
+ if (mergeTarget !== undefined) {
546
+ mergeTarget.addNamedExport(name);
547
+ return;
548
+ }
549
+ ast.addExportDeclaration({ moduleSpecifier: from, namedExports: [name] });
550
+ }
551
+ /**
552
+ * Adds `export * from "from";`, or `export * as ns from "from";` with `{ as: "ns" }` (V2
553
+ * REQ-TSD-18, extended with `as`). The two forms are different statements: each is a no-op
554
+ * only on its own output. `as` is validated like a name and rejects when the file already
555
+ * exports it.
556
+ */
557
+ export function addExportAll(ast, from, options) {
558
+ const as = options?.as;
559
+ if (as !== undefined)
560
+ assertValidImportBinding(as);
561
+ if (exportsOf(ast, from).some((decl) => isExportAll(decl, as)))
562
+ return;
563
+ if (as !== undefined)
564
+ assertNotExported(ast, as, "addExportAll");
565
+ ast.addExportDeclaration(as === undefined ? { moduleSpecifier: from } : { moduleSpecifier: from, namespaceExport: as });
566
+ }
567
+ /**
568
+ * Removes the re-export of `name` from `export { … } from "from"` (V2 REQ-TSD-19), deleting
569
+ * the statement when it was the last specifier; an absent re-export is a no-op. Matched by
570
+ * SOURCE name: `export { name as Y }` matches `name`, never `Y`. Local `export { x }` and
571
+ * `export *` statements are never touched — see `removeExportAll`.
572
+ */
573
+ export function removeExport(ast, name, from) {
574
+ assertValidImportBinding(name);
575
+ for (const decl of exportsOf(ast, from)) {
576
+ const namedExports = decl.getNamedExports();
577
+ const specifier = namedExports.find((named) => named.getName() === name);
578
+ if (specifier === undefined)
579
+ continue;
580
+ if (namedExports.length === 1) {
581
+ decl.remove();
582
+ }
583
+ else {
584
+ specifier.remove();
585
+ }
586
+ return;
587
+ }
588
+ }
589
+ /**
590
+ * Removes `export * from "from";`, or `export * as ns from "from";` with `{ as: "ns" }`. Each
591
+ * form only removes itself; an absent statement is a no-op.
592
+ */
593
+ export function removeExportAll(ast, from, options) {
594
+ const as = options?.as;
595
+ if (as !== undefined)
596
+ assertValidImportBinding(as);
597
+ exportsOf(ast, from)
598
+ .find((decl) => isExportAll(decl, as))
599
+ ?.remove();
600
+ }