@pbuilder/sdk 0.4.0 → 0.5.1

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.
Files changed (41) hide show
  1. package/README.md +67 -2
  2. package/dist/commons/index.js +5 -2
  3. package/dist/conformance/index.d.ts +2 -2
  4. package/dist/conformance/index.js +38 -19
  5. package/dist/core/define-dialect.js +15 -8
  6. package/dist/core/dialect-handle.js +1 -1
  7. package/dist/core/json-value.d.ts +14 -0
  8. package/dist/core/json-value.js +43 -0
  9. package/dist/dialects/json/ast.d.ts +24 -0
  10. package/dist/dialects/json/ast.js +21 -0
  11. package/dist/dialects/json/index.d.ts +55 -0
  12. package/dist/dialects/json/index.js +54 -0
  13. package/dist/dialects/json/ops.d.ts +46 -0
  14. package/dist/dialects/json/ops.js +561 -0
  15. package/dist/dialects/nestjs/index.d.ts +43 -0
  16. package/dist/dialects/nestjs/index.js +46 -0
  17. package/dist/dialects/nestjs/ops.d.ts +13 -0
  18. package/dist/dialects/nestjs/ops.js +100 -0
  19. package/dist/dialects/typescript/index.d.ts +15 -2
  20. package/dist/dialects/typescript/index.js +5 -10
  21. package/dist/dialects/typescript/ops.d.ts +65 -5
  22. package/dist/dialects/typescript/ops.js +272 -37
  23. package/dist/dialects/typescript/pack.d.ts +16 -0
  24. package/dist/dialects/typescript/pack.js +18 -0
  25. package/dist/dialects/yaml/ast.d.ts +15 -0
  26. package/dist/dialects/yaml/ast.js +154 -0
  27. package/dist/dialects/yaml/documents.d.ts +8 -0
  28. package/dist/dialects/yaml/documents.js +24 -0
  29. package/dist/dialects/yaml/index.d.ts +69 -0
  30. package/dist/dialects/yaml/index.js +70 -0
  31. package/dist/dialects/yaml/paths.d.ts +55 -0
  32. package/dist/dialects/yaml/paths.js +208 -0
  33. package/dist/dialects/yaml/presentation.d.ts +24 -0
  34. package/dist/dialects/yaml/presentation.js +264 -0
  35. package/dist/dialects/yaml/structural.d.ts +39 -0
  36. package/dist/dialects/yaml/structural.js +307 -0
  37. package/dist/runner-manifest.json +3 -3
  38. package/dist/transport/error-text.d.ts +6 -1
  39. package/dist/transport/error-text.js +94 -31
  40. package/package.json +21 -3
  41. package/schemas/project-builder.schema.json +112 -0
@@ -0,0 +1,100 @@
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 { addImport } from "../typescript/ops.js";
6
+ function moduleDecorator(ast, fail) {
7
+ const decorators = ast
8
+ .getClasses()
9
+ .map((cls) => cls.getDecorator("Module"))
10
+ .filter((decorator) => decorator !== undefined);
11
+ if (decorators.length === 0)
12
+ fail("no class decorated with @Module was found");
13
+ if (decorators.length > 1)
14
+ fail(`${decorators.length} classes are decorated with @Module; exactly one is required`);
15
+ return decorators[0];
16
+ }
17
+ function locate(ast, property, name, fail) {
18
+ const decorator = moduleDecorator(ast, fail);
19
+ const [metadata] = decorator.getArguments();
20
+ if (metadata === undefined)
21
+ return { kind: "addArgument", decorator };
22
+ if (metadata.getKind() !== SyntaxKind.ObjectLiteralExpression)
23
+ fail("the @Module argument is not an object literal");
24
+ const object = metadata.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);
25
+ const member = object.getProperty(property);
26
+ if (member === undefined)
27
+ return { kind: "addProperty", metadata: object };
28
+ const list = member.asKind(SyntaxKind.PropertyAssignment)?.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression);
29
+ if (list === undefined)
30
+ fail(`@Module "${property}" is not an array literal`);
31
+ if (list.getElements().some((element) => element.getText() === name))
32
+ return { kind: "present" };
33
+ return { kind: "append", list };
34
+ }
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
+ function write(ast, placement, property, name) {
62
+ const entry = `${property}: [${name}]`;
63
+ switch (placement.kind) {
64
+ case "present":
65
+ return;
66
+ case "append":
67
+ appendEntry(ast, placement.list, placement.list.getElements(), name, `[${name}]`);
68
+ return;
69
+ case "addProperty":
70
+ appendEntry(ast, placement.metadata, placement.metadata.getProperties(), entry, `{ ${entry} }`);
71
+ return;
72
+ case "addArgument":
73
+ placement.decorator.addArgument(`{ ${entry} }`);
74
+ }
75
+ }
76
+ function moduleArrayOp(verb, property) {
77
+ return (ast, name, from) => {
78
+ assertValidImportBinding(name);
79
+ const fail = (reason) => {
80
+ throw dialectError(`${verb}("${name}") on "${handlePathFor(ast)}" — ${reason}. Edit it with .modify().`);
81
+ };
82
+ // Locating first rejects an unusable @Module before addImport mutates the file; the
83
+ // nodes are located again afterwards because addImport may have rewritten them.
84
+ locate(ast, property, name, fail);
85
+ addImport(ast, name, from);
86
+ write(ast, locate(ast, property, name, fail), property, name);
87
+ };
88
+ }
89
+ /**
90
+ * Imports `name` from `from` and adds it to the `providers` array of the file's only
91
+ * `@Module` class, creating the metadata object or the array when missing. An entry already
92
+ * named `name` is left as it is.
93
+ */
94
+ export const addProvider = moduleArrayOp("addProvider", "providers");
95
+ /** Same as `addProvider`, for the `controllers` array. */
96
+ export const addController = moduleArrayOp("addController", "controllers");
97
+ /** Same as `addProvider`, for the `imports` array (other Nest modules). */
98
+ export const addModuleImport = moduleArrayOp("addModuleImport", "imports");
99
+ /** Same as `addProvider`, for the `exports` array. */
100
+ export const addExport = moduleArrayOp("addExport", "exports");
@@ -3,6 +3,14 @@ import { type Handle } from "../../core/define-dialect.ts";
3
3
  export * as astLibrary from "ts-morph";
4
4
  type TypeScriptOps = {
5
5
  addImport: (ast: SourceFile, name: string, from: string) => void;
6
+ addDefaultImport: (ast: SourceFile, name: string, from: string) => void;
7
+ addNamespaceImport: (ast: SourceFile, name: string, from: string) => void;
8
+ addTypeImport: (ast: SourceFile, name: string, from: string) => void;
9
+ addSideEffectImport: (ast: SourceFile, from: string) => void;
10
+ addReExport: (ast: SourceFile, name: string, from: string) => void;
11
+ addExportAll: (ast: SourceFile, from: string, options?: {
12
+ as?: string;
13
+ }) => void;
6
14
  addFunction: (ast: SourceFile, name: string, source: string, options?: {
7
15
  export?: boolean;
8
16
  }) => void;
@@ -14,12 +22,17 @@ type TypeScriptOps = {
14
22
  export?: boolean;
15
23
  }) => void;
16
24
  removeImport: (ast: SourceFile, name: string, from: string) => void;
25
+ removeExport: (ast: SourceFile, name: string, from: string) => void;
26
+ removeExportAll: (ast: SourceFile, from: string, options?: {
27
+ as?: string;
28
+ }) => void;
17
29
  };
18
30
  /**
19
31
  * Opens a TypeScript file for dialect-aware editing — the dialect's entry verb into a Session
20
32
  * (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
33
+ * escape hatch plus the dialect's named ops (`addImport`, `addDefaultImport`,
34
+ * `addNamespaceImport`, `addTypeImport`, `addSideEffectImport`, `addReExport`, `addExportAll`,
35
+ * `addFunction`, `addVariable`, `addClass`, `removeImport`, `removeExport`, `removeExportAll`). Reads route through `Session.read` only (REQ-MC-03); edits
23
36
  * coalesce into a single `modify` at flush (REQ-MC-01/02).
24
37
  *
25
38
  * @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,9 @@ 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`). Reads route through `Session.read` only (REQ-MC-03); edits
30
25
  * coalesce into a single `modify` at flush (REQ-MC-01/02).
31
26
  *
32
27
  * @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
+ }
@@ -0,0 +1,16 @@
1
+ import { addImport, addDefaultImport, addNamespaceImport, addTypeImport, addSideEffectImport, addReExport, addExportAll, addFunction, addVariable, addClass, removeImport, removeExport, removeExportAll } from "./ops.ts";
2
+ export declare const typescriptOps: {
3
+ addImport: typeof addImport;
4
+ addDefaultImport: typeof addDefaultImport;
5
+ addNamespaceImport: typeof addNamespaceImport;
6
+ addTypeImport: typeof addTypeImport;
7
+ addSideEffectImport: typeof addSideEffectImport;
8
+ addReExport: typeof addReExport;
9
+ addExportAll: typeof addExportAll;
10
+ addFunction: typeof addFunction;
11
+ addVariable: typeof addVariable;
12
+ addClass: typeof addClass;
13
+ removeImport: typeof removeImport;
14
+ removeExport: typeof removeExport;
15
+ removeExportAll: typeof removeExportAll;
16
+ };