@pbuilder/sdk 0.17.0 → 0.18.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.
Files changed (45) hide show
  1. package/README.md +26 -3
  2. package/dist/bin/pbuilder-conformance.d.ts +2 -0
  3. package/dist/bin/pbuilder-conformance.js +26 -0
  4. package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.d.ts +7 -1
  5. package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.js +2 -1
  6. package/dist/bounded-contexts/authoring/application/usecases/scaffold/expander.js +4 -4
  7. package/dist/bounded-contexts/authoring/domain/aggregates/session/session.d.ts +1 -0
  8. package/dist/bounded-contexts/authoring/domain/aggregates/session/session.js +54 -4
  9. package/dist/bounded-contexts/authoring/domain/entities/dialect-handle.d.ts +2 -1
  10. package/dist/bounded-contexts/authoring/domain/entities/dialect-handle.js +108 -30
  11. package/dist/bounded-contexts/authoring/domain/services/define-dialect.d.ts +48 -10
  12. package/dist/bounded-contexts/authoring/domain/services/define-dialect.js +37 -9
  13. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/angular/index.js +2 -2
  14. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.d.ts +8 -5
  15. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.js +7 -4
  16. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/ops.d.ts +1 -1
  17. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/ops.js +20 -7
  18. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.d.ts +20 -2
  19. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.js +19 -3
  20. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ops.d.ts +5 -0
  21. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/ops.js +89 -20
  22. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/nestjs/index.js +2 -2
  23. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/ast.d.ts +2 -0
  24. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/ast.js +4 -0
  25. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/index.js +3 -3
  26. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/ast.d.ts +2 -0
  27. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/ast.js +4 -0
  28. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/index.js +2 -2
  29. package/dist/bounded-contexts/authoring/testing/conformance/index.d.ts +10 -12
  30. package/dist/bounded-contexts/authoring/testing/conformance/index.js +17 -2
  31. package/dist/bounded-contexts/authoring/testing/conformance/run-package.d.ts +20 -0
  32. package/dist/bounded-contexts/authoring/testing/conformance/run-package.js +129 -0
  33. package/dist/bounded-contexts/authoring/testing/harness/index.d.ts +3 -0
  34. package/dist/bounded-contexts/authoring/testing/harness/index.js +5 -1
  35. package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.d.ts +3 -0
  36. package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.js +2 -0
  37. package/dist/bounded-contexts/runner-hosting/infrastructure/in/runner.js +42 -3
  38. package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.d.ts +13 -0
  39. package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.js +25 -1
  40. package/dist/conformance/index.d.ts +1 -0
  41. package/dist/conformance/index.js +1 -0
  42. package/dist/dialect/index.d.ts +2 -0
  43. package/dist/dialect/index.js +3 -0
  44. package/dist/runner-manifest.json +6 -6
  45. package/package.json +8 -2
package/README.md CHANGED
@@ -613,6 +613,7 @@ await ts.find("src/index.ts")
613
613
  | `addVariable(name, initializer, opts?)` | Appends a top-level variable (`kind` defaults to `const`). A no-op when the same declaration exists; another binding of `name` rejects. |
614
614
  | `addClass(name, source, opts?)` | Appends a top-level class. `source` **excludes** the braces — the op adds them. A no-op when the same declaration exists; another binding of `name` rejects. |
615
615
  | `.modify(fn)` | The universal escape hatch: direct [ts-morph](https://ts-morph.com) access to the file's AST for anything the named ops don't cover. |
616
+ | `.inspect(fn)` | The read escape hatch: hands `fn` the same live AST and resolves to what `fn` returns. Ends the chain; a callback that changes the file fails the factory. |
616
617
 
617
618
  The `add*` ops fail loud on a name collision with an existing value declaration or import
618
619
  binding (two value declarations sharing a name is invalid TypeScript); a `type`/`interface`
@@ -750,8 +751,8 @@ See [the ASP.NET dialect guide](./docs/guides/aspnet-dialect.md).
750
751
 
751
752
  ### `@pbuilder/sdk/msbuild`
752
753
 
753
- Adds project references to `.csproj`, `.props`, `.targets` and `.slnx` files by editing the XML
754
- text, never through the `dotnet` CLI; the classic `.sln` is rejected.
754
+ Adds project references to `.csproj`, `.props` and `.targets` files, and projects to `.slnx`
755
+ solutions, by editing the XML text, never through the `dotnet` CLI; the classic `.sln` is rejected.
755
756
 
756
757
  ```ts
757
758
  import * as msbuild from "@pbuilder/sdk/msbuild";
@@ -759,9 +760,11 @@ import * as msbuild from "@pbuilder/sdk/msbuild";
759
760
  await msbuild
760
761
  .find("src/Shop.Infrastructure/Shop.Infrastructure.csproj")
761
762
  .addProjectReference("../Shop.Application/Shop.Application.csproj");
763
+
764
+ await msbuild.find("Shop.slnx").addProject("src/Shop.Api/Shop.Api.csproj", { folder: "/src/" });
762
765
  ```
763
766
 
764
- Named op: `addProjectReference`. `.modify(fn)` exposes [saxes](https://github.com/lddubeau/saxes).
767
+ Named ops: `addProjectReference`, `addProject`. `.modify(fn)` exposes [saxes](https://github.com/lddubeau/saxes).
765
768
  See [the MSBuild dialect guide](./docs/guides/msbuild-dialect.md).
766
769
 
767
770
  ### `@pbuilder/sdk/nestjs`
@@ -837,6 +840,26 @@ still flushes as a **single** write. Two things to respect:
837
840
  callbacks are your own trust; before importing a *third-party* dialect or op-pack built
838
841
  on it, read [SECURITY.md](./SECURITY.md).
839
842
 
843
+ ### `.inspect()` — reading the AST back
844
+
845
+ `.inspect(ast => value)` is the read counterpart of `.modify()`. It hands the callback the same
846
+ live AST, after every op chained before it, and resolves to what the callback returns. It ends
847
+ the chain, emits nothing, and is offered to every factory, so a generator can read a value to
848
+ decide what to write:
849
+
850
+ ```ts
851
+ import * as ts from "@pbuilder/sdk/typescript";
852
+
853
+ const imports = await ts.find("src/main.ts")
854
+ .addImport("BooksModule", "./books/books.module")
855
+ .inspect((ast) => ast.getImportDeclarations().length);
856
+ ```
857
+
858
+ The callback must not change the AST. The SDK prints the file before and after it, and a
859
+ difference fails the factory with `inspect() must not change "<path>"`. A callback that throws
860
+ fails it with `inspect() on "<path>" threw`, without the original message. Return plain data:
861
+ a node you keep goes stale after the next edit.
862
+
840
863
  ### Going deeper
841
864
 
842
865
  Everything dialect-related lives in one reference page —
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ export {};
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env bun
2
+ // `pbuilder-conformance --dialect <installed package dir>` (CA-13): prints one JSON report line.
3
+ // Exit 0: the fixture passed. Exit 1: it ran and failed, a missing fixture included. Exit 2: it
4
+ // could not run, with nothing on stdout. Runs under Bun, from the SDK root of the Run, so the
5
+ // dialect's `@pbuilder/sdk` imports reach this same SDK.
6
+ import { checkDialectPackage } from "../conformance/index.js";
7
+ import { redirectConsoleToStderr } from "../shared-kernel/framing.js";
8
+ // The fixture runs the author's code, so everything but the report goes to stderr.
9
+ const writeReport = process.stdout.write.bind(process.stdout);
10
+ Object.defineProperty(process, "stdout", { value: process.stderr, writable: true, configurable: true });
11
+ redirectConsoleToStderr();
12
+ const COULD_NOT_RUN = 2;
13
+ async function main(argv) {
14
+ if (argv.length !== 2 || argv[0] !== "--dialect" || argv[1] === "") {
15
+ process.stderr.write("usage: pbuilder-conformance --dialect <installed package dir>\n");
16
+ return COULD_NOT_RUN;
17
+ }
18
+ const report = await checkDialectPackage(argv[1]);
19
+ await new Promise((done) => writeReport(`${JSON.stringify(report)}\n`, () => done()));
20
+ return report.passed ? 0 : 1;
21
+ }
22
+ // Exits explicitly: a timer or socket the author's code left open must not keep the process alive.
23
+ main(process.argv.slice(2)).then((code) => process.exit(code), (err) => {
24
+ const detail = err instanceof Error && err.message.startsWith("pbuilder-conformance:") ? err.message : "the fixture could not run";
25
+ process.stderr.write(`${detail}\n`, () => process.exit(COULD_NOT_RUN));
26
+ });
@@ -19,6 +19,7 @@ export interface SessionContext {
19
19
  packageDir: string;
20
20
  };
21
21
  packageFiles?: PackageFiles;
22
+ declaredDialects?: ReadonlySet<string>;
22
23
  }
23
24
  export declare function isDefineFactoryWrapped(value: unknown): boolean;
24
25
  export declare function currentContext(): SessionContext;
@@ -78,9 +79,14 @@ export declare function requirePackageAnchors(missingAnchorMessage: string): {
78
79
  * const runner = defineFactory<Input>(bareFactory, { packageDir: import.meta.dir });
79
80
  * await runner(input, { client });
80
81
  */
81
- export declare function defineFactory<O>(fn: (o: O) => void | Promise<void>, options?: {
82
+ export declare function defineFactory<O>(fn: (o: O) => void | Promise<void>, options?: ({
82
83
  packageDir: string | URL;
83
84
  packageFiles: PackageFiles;
85
+ } | {
86
+ packageDir?: undefined;
87
+ packageFiles?: undefined;
88
+ }) & {
89
+ declaredDialects?: readonly string[];
84
90
  }): (o: O, deps: {
85
91
  client: EngineClient;
86
92
  }) => Promise<void>;
@@ -200,7 +200,7 @@ export function defineFactory(fn, options) {
200
200
  const wrapped = async (o, { client }) => {
201
201
  let packageAnchors;
202
202
  let packageFiles;
203
- if (options !== undefined) {
203
+ if (options?.packageDir !== undefined) {
204
204
  const pkg = { files: options.packageFiles, dir: resolvePackageDir(options.packageDir) };
205
205
  // REQ-RBV-06: exactly TWO reads, in this order — reserved-name check, then schema
206
206
  // validation. No third (containment-ceiling) read exists (ADR-0077 §C).
@@ -215,6 +215,7 @@ export function defineFactory(fn, options) {
215
215
  dialects: new DialectRegistryImpl(),
216
216
  packageAnchors,
217
217
  packageFiles,
218
+ declaredDialects: new Set(options?.declaredDialects),
218
219
  };
219
220
  // ADR-01: no `finally` — success (commit) and failure (discard) are distinct paths.
220
221
  // The final flush is INSIDE the try, so a flush-time emit rejection (already an
@@ -16,10 +16,10 @@
16
16
  // — no synchronous flush variant may be added. The bridge is the EXISTING `DialectRegistry`
17
17
  // (`context.ts`, ADR-0037), documented as generic over "anything with a `settle()`": a
18
18
  // mid-run `session.flush()` call is fired here WITHOUT awaiting (its synchronous prefix —
19
- // draining `#pending`, building the batch, and the fake's entirely-synchronous `#apply`
20
- // loop — still runs to completion before `flush()`'s own `await` suspends it, so the
21
- // `#tree` mutation for this group happens in-order, synchronously, before the next group
22
- // starts buffering) and REGISTERED as a dialect handle. `defineFactory` already awaits
19
+ // draining `#pending`, building the batch, and, when no earlier batch is still in flight, the
20
+ // fake's entirely-synchronous `#apply` loop — runs before `flush()` suspends; a batch fired
21
+ // while another is in flight waits its turn, so each group's `#tree` mutation still lands in
22
+ // order) and REGISTERED as a dialect handle. `defineFactory` already awaits
23
23
  // `ctx.dialects.drain()` BEFORE its own run-end `session.flush()` (which covers the final,
24
24
  // still-pending group) and BEFORE `commit()` — so a later-chunk rejection surfaces through
25
25
  // `drain()`, routes to `defineFactory`'s existing catch, and `discard()` clears the SAME
@@ -4,6 +4,7 @@ export declare class Session {
4
4
  #private;
5
5
  constructor(client: EngineClient);
6
6
  buffer(directive: Directive): void;
7
+ versionOf(path: string): number;
7
8
  pendingDirectives(): readonly Directive[];
8
9
  isPending(directive: Directive): boolean;
9
10
  read(path: string): Promise<string | undefined>;
@@ -1,5 +1,5 @@
1
- // KIT-02 / ADR-0008: holds ONLY the pending directive buffer + the EngineClient.
2
- // No path-keyed map, no tree. read() flushes pending BEFORE delegating to the client.
1
+ // KIT-02 / ADR-0008: holds the pending directive buffer, the EngineClient, and one content
2
+ // version per path as typed (A-7). No tree. read() flushes pending BEFORE delegating to the client.
3
3
  // REQ-KIT-05: flush() is package-internal — called by defineFactory after fn resolves
4
4
  // so write-only factories (no read call) still emit their batch.
5
5
  //
@@ -8,14 +8,52 @@
8
8
  // here because the author API has no run-wide force concept yet. The fake's Row-3 test
9
9
  // (FAKE-04) is intentional engine-contract coverage, not dead-code coverage.
10
10
  import { toAuthoringError } from "../../valueobjects/authoring-error.js";
11
+ const dirOf = (path) => path.slice(0, path.lastIndexOf("/") + 1);
12
+ const baseOf = (path) => path.slice(path.lastIndexOf("/") + 1);
13
+ // A loop, not a /\/+$/ regex: toDir comes from the author, and that regex backtracks polynomially.
14
+ function withoutTrailingSlashes(dir) {
15
+ let end = dir.length;
16
+ while (end > 0 && dir[end - 1] === "/")
17
+ end--;
18
+ return dir.slice(0, end);
19
+ }
20
+ /** The paths whose content a directive replaces or removes, spelled as the commons verbs spell them; a copy's source is untouched. */
21
+ function touchedPaths(directive) {
22
+ switch (directive.op) {
23
+ case "create":
24
+ return [directive.create.pathTemplate];
25
+ case "modify":
26
+ return [directive.modify.path];
27
+ case "delete":
28
+ return [directive.delete.path];
29
+ case "rename":
30
+ return [directive.rename.path, dirOf(directive.rename.path) + directive.rename.newName];
31
+ case "move":
32
+ return [directive.move.path, `${withoutTrailingSlashes(directive.move.toDir)}/${baseOf(directive.move.path)}`];
33
+ case "copy":
34
+ return [directive.copy.to];
35
+ case "copyIn":
36
+ return [directive.copyIn.to];
37
+ }
38
+ }
11
39
  export class Session {
12
40
  #client;
13
41
  #pending = [];
42
+ #versions = new Map();
43
+ // The batches being emitted, so a read or a later flush never overtakes them.
44
+ #emitting = Promise.resolve();
45
+ #inFlight = 0;
14
46
  constructor(client) {
15
47
  this.#client = client;
16
48
  }
17
49
  buffer(directive) {
18
50
  this.#pending.push(directive);
51
+ for (const path of touchedPaths(directive))
52
+ this.#versions.set(path, this.versionOf(path) + 1);
53
+ }
54
+ // A-7: how many buffered directives have changed this path's content, keyed by the path as typed.
55
+ versionOf(path) {
56
+ return this.#versions.get(path) ?? 0;
19
57
  }
20
58
  // SEAM-02 (REQ-03): a defensive copy of the pending buffer for the pending Directives renderer.
21
59
  // Later mutations to #pending must NOT affect a snapshot taken earlier.
@@ -52,14 +90,26 @@ export class Session {
52
90
  // identity, not `instanceof`: importing the TransportFault class here would pull the whole
53
91
  // transport client into core's (and the ./commons bundle's) module graph, inverting the
54
92
  // port direction. ERM-03's degrade still applies to everything else non-EmitRejection.
55
- async flush() {
93
+ // The batch is taken synchronously, so a read started right after this call already waits for
94
+ // it. With no batch in flight the client's emit starts synchronously, as callers that fire a
95
+ // flush without awaiting it (scaffold's batch cap) rely on; otherwise it waits its turn.
96
+ flush() {
56
97
  if (this.#pending.length === 0)
57
- return;
98
+ return this.#emitting;
58
99
  const batch = {
59
100
  protocolVersion: 1,
60
101
  force: false,
61
102
  instructions: this.#pending.splice(0),
62
103
  };
104
+ const emit = this.#inFlight === 0 ? this.#emit(batch) : this.#emitting.then(() => this.#emit(batch));
105
+ this.#inFlight++;
106
+ const done = () => {
107
+ this.#inFlight--;
108
+ };
109
+ this.#emitting = emit.then(done, done);
110
+ return emit;
111
+ }
112
+ async #emit(batch) {
63
113
  try {
64
114
  await this.#client.emit(batch);
65
115
  }
@@ -2,6 +2,7 @@ import type { OpPack, Handle, Query } from "../services/define-dialect.ts";
2
2
  interface DialectAst<Ast> {
3
3
  parse(source: string): Ast;
4
4
  print(ast: Ast): string;
5
+ retire?(ast: Ast): void;
5
6
  }
6
7
  /**
7
8
  * Marks an op-pack entry as a query: on the handle it ends the chain and resolves to `fn`'s
@@ -30,5 +31,5 @@ export declare function handlePathFor(ast: object): string;
30
31
  * `DialectHandleController`. Op methods are attached dynamically from `ops`' own keys —
31
32
  * `Object.keys(ops)` is exactly the set `OpMethods<Ast, Ops>` describes at the type level.
32
33
  */
33
- export declare function createDialectHandle<Ast, Ops extends OpPack<Ast>>(dialectAst: DialectAst<Ast>, ops: Ops, path: string): Handle<"found", Ast, Ops>;
34
+ export declare function createDialectHandle<Ast, Ops extends OpPack<Ast>>(dialectAst: DialectAst<Ast>, ops: Ops, path: string, name?: string): Handle<"found", Ast, Ops>;
34
35
  export {};
@@ -6,7 +6,7 @@
6
6
  // module lives under src/core/**, is never a public subpath, and its shape is not
7
7
  // fitness-pinned. Only the PUBLIC `find(path)` signature and the `Handle<State, Ast, Ops>`
8
8
  // TYPE (define-dialect.ts) are frozen.
9
- import { currentRun } from "../services/run-context.js";
9
+ import { currentRun, getSessionAls } from "../services/run-context.js";
10
10
  import { dialectError, isContained } from "../valueobjects/dialect-error.js";
11
11
  // `.modify()`'s `fn` is typed `(ast: Ast) => void`, but TS's void-return compatibility lets an
12
12
  // author pass an async function anyway — this is the runtime check that catches that case.
@@ -96,6 +96,7 @@ class DialectHandleController {
96
96
  #dialectAst;
97
97
  #ops;
98
98
  #path;
99
+ #name;
99
100
  #live;
100
101
  #openDirective;
101
102
  #registered = false;
@@ -104,10 +105,28 @@ class DialectHandleController {
104
105
  // this to decide whether an op actually changed anything (REQ-TSD-08.4's zero-directive
105
106
  // no-op) — never re-derived from a print-after-parse (would cost a redundant print).
106
107
  #lastEmittedText;
107
- constructor(dialectAst, ops, path) {
108
+ // A-7: the Session, and its content version of #path, that #live reflects, own writes included.
109
+ #session;
110
+ #version;
111
+ // A-8: set once the handle re-parsed away from a tree, so a failing .modify() names the remedy.
112
+ #retired = false;
113
+ constructor(dialectAst, ops, path, name) {
108
114
  this.#dialectAst = dialectAst;
109
115
  this.#ops = ops;
110
116
  this.#path = path;
117
+ this.#name = name;
118
+ }
119
+ // A-16: a handle opened inside a run fails the run at its end even when no step follows.
120
+ // Outside a run there is no declared set yet, so the first step checks instead.
121
+ checkDeclaredInRun() {
122
+ if (this.#name !== undefined && getSessionAls().getStore() !== undefined)
123
+ this.#enqueue(() => { });
124
+ }
125
+ #assertDeclared(ctx) {
126
+ if (this.#name !== undefined && ctx.declaredDialects?.has(this.#name) !== true) {
127
+ throw dialectError(`the dialect "${this.#name}" is not declared in the Manifest of this schematic's library — ` +
128
+ `add it to the "dialects" section of its project-builder.json.`);
129
+ }
111
130
  }
112
131
  get ops() {
113
132
  return this.#ops;
@@ -134,6 +153,7 @@ class DialectHandleController {
134
153
  throw ctx.sessionFailure.reason;
135
154
  }
136
155
  try {
156
+ this.#assertDeclared(ctx);
137
157
  return await step();
138
158
  }
139
159
  catch (err) {
@@ -166,26 +186,48 @@ class DialectHandleController {
166
186
  this.#registered = true;
167
187
  currentRun().dialects.register({ settle: () => this.settle() });
168
188
  }
169
- async #ensureLive() {
170
- if (this.#live !== undefined)
171
- return;
189
+ // A-7: #live is a cache of the path's content, fresh while no other writer moved the path's
190
+ // content version since it was parsed. Callers loop `while (!#isFresh()) await #reparse()` and
191
+ // run the op in the same synchronous turn as the last check, so no write can land in between.
192
+ #isFresh() {
193
+ const { session } = currentRun();
194
+ return this.#live !== undefined && session === this.#session && session.versionOf(this.#path) === this.#version;
195
+ }
196
+ // The read flushes pending edits first; a version that moves while the read is in flight means
197
+ // the content read is already stale, so the caller's loop reads again.
198
+ async #reparse() {
172
199
  const { session } = currentRun();
200
+ const version = session.versionOf(this.#path);
173
201
  const content = await session.read(this.#path);
202
+ if (session.versionOf(this.#path) !== version)
203
+ return;
174
204
  if (content === undefined) {
175
205
  throw dialectError(`"${this.#path}" does not exist — create it first in this run`);
176
206
  }
207
+ let next;
177
208
  try {
178
- this.#live = this.#dialectAst.parse(content);
209
+ next = this.#dialectAst.parse(content);
179
210
  }
180
211
  catch {
181
212
  throw dialectError(`could not parse "${this.#path}"`);
182
213
  }
183
- astHandlePaths.set(this.#live, this.#path);
214
+ // The drained directive prints the AST it was built from; fix its content before retiring it.
215
+ if (this.#openDirective?.op === "modify")
216
+ void this.#openDirective.modify.content;
217
+ if (this.#live !== undefined) {
218
+ this.#dialectAst.retire?.(this.#live);
219
+ this.#retired = true;
220
+ }
221
+ this.#live = next;
222
+ astHandlePaths.set(next, this.#path);
184
223
  this.#lastEmittedText = content;
224
+ this.#openDirective = undefined;
225
+ this.#session = session;
226
+ this.#version = version;
185
227
  }
186
- #printContained() {
228
+ #printContained(ast = this.#live) {
187
229
  try {
188
- return this.#dialectAst.print(this.#live);
230
+ return this.#dialectAst.print(ast);
189
231
  }
190
232
  catch {
191
233
  throw dialectError(`could not print "${this.#path}"`);
@@ -224,6 +266,10 @@ class DialectHandleController {
224
266
  // instead of unconditionally re-registering a byte-identical directive.
225
267
  #ensureOpen() {
226
268
  const { session } = currentRun();
269
+ // An async op let another writer change the path; printing #live now would erase that write.
270
+ if (session.versionOf(this.#path) !== this.#version) {
271
+ throw dialectError(`"${this.#path}" changed while an op on it ran — await each op before another writer edits the file`);
272
+ }
227
273
  if (this.#hasOpenPendingDirective(session)) {
228
274
  return;
229
275
  }
@@ -236,8 +282,10 @@ class DialectHandleController {
236
282
  if (this.#printContained() === this.#lastEmittedText) {
237
283
  return;
238
284
  }
239
- this.#openDirective = lazyModifyDirective(this.#path, () => this.#printContained());
285
+ const live = this.#live;
286
+ this.#openDirective = lazyModifyDirective(this.#path, () => this.#printContained(live));
240
287
  session.buffer(this.#openDirective);
288
+ this.#version = session.versionOf(this.#path);
241
289
  }
242
290
  // Shared containment primitive (ADR-0037 amendment clause 1): runs `fn`, awaits a
243
291
  // thenable result INSIDE the try (so an async op's rejection is contained, never an
@@ -245,18 +293,23 @@ class DialectHandleController {
245
293
  // NEVER `message.startsWith`) — a caught error already carrying the brand (an author's
246
294
  // deliberate `dialectError` reject) is RETHROWN VERBATIM (REQ-DG-06.5, no double-wrap, no
247
295
  // `.cause`); any foreign error is wrapped fresh via `dialectError(foreignTail)`.
248
- async #invokeContained(fn, foreignTail) {
249
- try {
250
- const result = fn();
251
- if (isThenable(result)) {
252
- await result;
253
- }
254
- }
255
- catch (caught) {
296
+ //
297
+ // Synchronous for a synchronous `fn`, so an op and the #ensureOpen after it run in the turn of
298
+ // the freshness check (A-7); only a thenable result returns a promise.
299
+ #invokeContained(fn, foreignTail) {
300
+ const rethrow = (caught) => {
256
301
  if (isContained(caught))
257
302
  throw caught;
258
303
  throw dialectError(foreignTail);
304
+ };
305
+ let result;
306
+ try {
307
+ result = fn();
308
+ }
309
+ catch (caught) {
310
+ rethrow(caught);
259
311
  }
312
+ return isThenable(result) ? Promise.resolve(result).then(() => undefined, rethrow) : undefined;
260
313
  }
261
314
  // Chaining is the WRAPPER's job (createDialectHandle, below) — these return void; the
262
315
  // wrapper's dispatchers always return the public handle object, never `this` controller.
@@ -275,25 +328,30 @@ class DialectHandleController {
275
328
  // however many params the author did or didn't supply.
276
329
  runOp(fn, args, opName) {
277
330
  this.#enqueue(async () => {
278
- await this.#ensureLive();
279
- await this.#invokeContained(() => fn(this.#live, ...args), `${opName}() on "${this.#path}" threw`);
331
+ while (!this.#isFresh())
332
+ await this.#reparse();
333
+ const pending = this.#invokeContained(() => fn(this.#live, ...args), `${opName}() on "${this.#path}" threw`);
334
+ if (pending !== undefined)
335
+ await pending;
280
336
  this.#ensureOpen();
281
337
  });
282
338
  }
283
339
  // Sequenced on #tail like an op, but it never calls #ensureOpen: a query only reads the live
284
340
  // AST, so it registers no directive (#ensureLive's first read still drains, as for an op).
285
341
  // The print comparison is what keeps it read-only: a query that edits the AST would
286
- // otherwise smuggle its edit into the next op's directive.
287
- runQuery(fn, args, name) {
342
+ // otherwise smuggle its edit into the next op's directive. `.inspect()` runs through here too,
343
+ // under its own name and its own wording for a change.
344
+ runQuery(fn, args, name, changed = `${name}() is a query and must not change`) {
288
345
  return this.#chain(async () => {
289
- await this.#ensureLive();
346
+ while (!this.#isFresh())
347
+ await this.#reparse();
290
348
  const before = this.#printContained();
291
349
  let result;
292
350
  await this.#invokeContained(async () => {
293
351
  result = await fn(this.#live, ...args);
294
352
  }, `${name}() on "${this.#path}" threw`);
295
353
  if (this.#printContained() !== before) {
296
- throw dialectError(`${name}() is a query and must not change "${this.#path}"`);
354
+ throw dialectError(`${changed} "${this.#path}"`);
297
355
  }
298
356
  return result;
299
357
  });
@@ -306,8 +364,14 @@ class DialectHandleController {
306
364
  // resolve-after-delay's mutation may race the print.
307
365
  runModify(fn) {
308
366
  this.#enqueue(async () => {
309
- await this.#ensureLive();
310
- await this.#invokeContained(() => fn(this.#live), `modify() on "${this.#path}" threw`);
367
+ while (!this.#isFresh())
368
+ await this.#reparse();
369
+ const remedy = this.#retired
370
+ ? ` — if it uses a node kept from before "${this.#path}" was re-parsed, look the node up again inside .modify()`
371
+ : "";
372
+ const pending = this.#invokeContained(() => fn(this.#live), `modify() on "${this.#path}" threw${remedy}`);
373
+ if (pending !== undefined)
374
+ await pending;
311
375
  this.#ensureOpen();
312
376
  });
313
377
  }
@@ -330,10 +394,22 @@ class DialectHandleController {
330
394
  });
331
395
  }
332
396
  runRename(newName, opts) {
333
- this.#bufferDirective((factory) => factory.rename({ path: this.#path, newName, force: opts?.force }));
397
+ this.#relocate((factory) => factory.rename({ path: this.#path, newName, force: opts?.force }));
334
398
  }
335
399
  runMove(toDir, opts) {
336
- this.#bufferDirective((factory) => factory.move({ path: this.#path, toDir, force: opts?.force }));
400
+ this.#relocate((factory) => factory.move({ path: this.#path, toDir, force: opts?.force }));
401
+ }
402
+ // The handle's own rename or move, buffered after its still-pending edit, is not another writer:
403
+ // the next op joins that edit, which reaches the engine before the relocation, as it did before
404
+ // A-7. With nothing pending the version moves, and the next op reads the old path again.
405
+ #relocate(build) {
406
+ this.#enqueue(() => {
407
+ const { session, factory } = currentRun();
408
+ const absorb = this.#hasOpenPendingDirective(session) && session === this.#session && session.versionOf(this.#path) === this.#version;
409
+ session.buffer(build(factory));
410
+ if (absorb)
411
+ this.#version = session.versionOf(this.#path);
412
+ });
337
413
  }
338
414
  runCopy(to, opts) {
339
415
  this.#bufferDirective((factory) => factory.copy({ from: this.#path, to, force: opts?.force }));
@@ -375,8 +451,9 @@ class DialectHandleController {
375
451
  * `DialectHandleController`. Op methods are attached dynamically from `ops`' own keys —
376
452
  * `Object.keys(ops)` is exactly the set `OpMethods<Ast, Ops>` describes at the type level.
377
453
  */
378
- export function createDialectHandle(dialectAst, ops, path) {
379
- const controller = new DialectHandleController(dialectAst, ops, path);
454
+ export function createDialectHandle(dialectAst, ops, path, name) {
455
+ const controller = new DialectHandleController(dialectAst, ops, path, name);
456
+ controller.checkDeclaredInRun();
380
457
  // Every chaining method returns `handle` (the PUBLIC wrapper below), never the
381
458
  // controller directly — the author-facing chain must keep landing on an object that
382
459
  // carries `.modify`/`.push`(op methods)/etc., which the controller itself does not expose.
@@ -388,6 +465,7 @@ export function createDialectHandle(dialectAst, ops, path) {
388
465
  controller.runModify(fn);
389
466
  return handle;
390
467
  },
468
+ inspect: (fn) => controller.runQuery(fn, [], "inspect", "inspect() must not change"),
391
469
  replaceContent: (content) => {
392
470
  controller.runReplaceContent(content);
393
471
  return handle;
@@ -6,12 +6,24 @@ export type Query<Ast = any, A extends unknown[] = any[], R = unknown> = ((ast:
6
6
  readonly [QUERY]: true;
7
7
  };
8
8
  export type OpPack<Ast = any> = Record<string, Op<Ast>>;
9
+ /**
10
+ * How a dialect reads and writes its files. `retire`, when given, is called on a tree a handle
11
+ * re-parsed away from (A-8): it must make every node of that tree fail when used, so a node kept
12
+ * from before the re-parse never edits a tree no file reflects.
13
+ */
14
+ export interface DialectAst<Ast = any> {
15
+ parse(source: string): Ast;
16
+ print(ast: Ast): string;
17
+ retire?(ast: Ast): void;
18
+ }
9
19
  export interface DialectDescriptor<Ast = any, Ops extends OpPack<Ast> = OpPack<Ast>> {
20
+ /**
21
+ * The name of the package that ships an author-defined dialect, the name its Dialect
22
+ * declaration uses (A-16). The SDK's dialects carry none and are never declared.
23
+ */
24
+ name?: string;
10
25
  extensions: string[];
11
- ast: {
12
- parse(source: string): Ast;
13
- print(ast: Ast): string;
14
- };
26
+ ast: DialectAst<Ast>;
15
27
  ops: Ops;
16
28
  }
17
29
  type Bound<Ast, F> = F extends (ast: Ast, ...rest: infer R) => void ? (...rest: R) => void : never;
@@ -33,15 +45,24 @@ type DialectWriteOps<Ast, Ops extends OpPack<Ast>> = {
33
45
  };
34
46
  export type Handle<State extends "found" | "writable" = "found", Ast = any, Ops extends OpPack<Ast> = OpPack<Ast>> = ReadOps & DialectWriteOps<Ast, Ops> & {
35
47
  modify(fn: (ast: Ast) => void): Edited<Ast, Ops>;
48
+ /**
49
+ * The read escape hatch, as `.modify()` is the write one (A-128). Hands `fn` the live AST,
50
+ * after every op chained before it, and resolves to what `fn` returns; it ends the chain.
51
+ * The AST is printed before and after `fn`, and a difference fails the factory with
52
+ * `inspect() must not change "<path>"`. Return plain data: a node kept after the next edit
53
+ * is stale (A-8).
54
+ *
55
+ * @example
56
+ * const count = await typescript.find("src/a.ts").addImport("x", "y").inspect((ast) => ast.getImportDeclarations().length);
57
+ */
58
+ inspect<R>(fn: (ast: Ast) => R): Promise<Awaited<R>>;
36
59
  } & OpMethods<Ast, Ops> & (State extends "found" ? {
37
60
  remove(): void;
38
61
  } : {}) & PromiseLike<void>;
39
62
  export interface Dialect<Ast = any, Ops extends OpPack<Ast> = OpPack<Ast>> {
63
+ readonly name?: string;
40
64
  readonly extensions: readonly string[];
41
- readonly ast: {
42
- parse(source: string): Ast;
43
- print(ast: Ast): string;
44
- };
65
+ readonly ast: DialectAst<Ast>;
45
66
  readonly ops: Ops;
46
67
  find(path: string): Handle<"found", Ast, Ops>;
47
68
  }
@@ -59,7 +80,8 @@ export declare function defineOpPack<Ast, Ops extends OpPack<Ast>>(ops: Ops): Op
59
80
  /**
60
81
  * Assembles a `Dialect` from its frozen descriptor (extensions, an AST parse/print pair,
61
82
  * and an op-pack). `find` is the dialect's ONLY entry verb into a Session (REQ-DG-01.2) — it
62
- * returns an open, coalescing `Handle`.
83
+ * returns an open, coalescing `Handle`. Throws when an op in `ops` takes the name of a handle
84
+ * verb (`RESERVED_HANDLE_NAMES`).
63
85
  *
64
86
  * @example
65
87
  * const myDialect = defineDialect({
@@ -69,6 +91,22 @@ export declare function defineOpPack<Ast, Ops extends OpPack<Ast>>(ops: Ops): Op
69
91
  * });
70
92
  */
71
93
  export declare function defineDialect<Ast, Ops extends OpPack<Ast>>(d: DialectDescriptor<Ast, Ops>): Dialect<Ast, Ops>;
94
+ /**
95
+ * Defines an author-defined dialect, named by the package that ships it (A-16): a factory opens
96
+ * its handles only when the schematic's library declares that name in its Manifest, and the
97
+ * conformance fixture rejects a name that is not the package's.
98
+ *
99
+ * @example
100
+ * export const ini = defineDialect({
101
+ * name: "@company/ini-dialect",
102
+ * extensions: [".ini"],
103
+ * ast: { parse: (text) => parseIni(text), print: (tree) => printIni(tree) },
104
+ * ops: {},
105
+ * });
106
+ */
107
+ export declare function defineAuthorDialect<Ast, Ops extends OpPack<Ast>>(d: DialectDescriptor<Ast, Ops> & {
108
+ name: string;
109
+ }): Dialect<Ast, Ops>;
72
110
  type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
73
111
  /**
74
112
  * The base handle's own vocabulary (REQ-DG-02, ADR-0010 amendment) — an op-pack op sharing
@@ -82,7 +120,7 @@ type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) exten
82
120
  * import it instead of hand-typing a second literal) — NOT a supported public API member, not
83
121
  * semver-covered beyond the FIT-04 baseline pin it already sits inside (ORCHESTRATOR RULING R2).
84
122
  */
85
- export declare const RESERVED_HANDLE_NAMES: readonly ["then", "read", "raw", "modify", "replaceContent", "rename", "move", "copy", "remove"];
123
+ export declare const RESERVED_HANDLE_NAMES: readonly ["then", "read", "raw", "modify", "inspect", "replaceContent", "rename", "move", "copy", "remove"];
86
124
  /**
87
125
  * Composes additional op-packs onto a base dialect. The resulting handle type is the
88
126
  * INTERSECTION of the base's ops and every attached pack's ops (ADR-0010) — an op from an