@pbuilder/sdk 0.1.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 (121) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +202 -0
  3. package/dist/bin/pbuilder-codegen.js +506 -0
  4. package/dist/bin/pbuilder-runner.d.ts +1 -0
  5. package/dist/bin/pbuilder-runner.js +47 -0
  6. package/dist/commons/classify-content.d.ts +40 -0
  7. package/dist/commons/classify-content.js +32 -0
  8. package/dist/commons/index.d.ts +271 -0
  9. package/dist/commons/index.js +276 -0
  10. package/dist/conformance/index.d.ts +115 -0
  11. package/dist/conformance/index.js +218 -0
  12. package/dist/conformance/run-vehicle.d.ts +19 -0
  13. package/dist/conformance/run-vehicle.js +104 -0
  14. package/dist/core/authoring-error.d.ts +116 -0
  15. package/dist/core/authoring-error.js +205 -0
  16. package/dist/core/base-handle.d.ts +17 -0
  17. package/dist/core/base-handle.js +4 -0
  18. package/dist/core/context.d.ts +85 -0
  19. package/dist/core/context.js +356 -0
  20. package/dist/core/deep-equal.d.ts +1 -0
  21. package/dist/core/deep-equal.js +29 -0
  22. package/dist/core/define-dialect.d.ts +94 -0
  23. package/dist/core/define-dialect.js +121 -0
  24. package/dist/core/dialect-error.d.ts +8 -0
  25. package/dist/core/dialect-error.js +26 -0
  26. package/dist/core/dialect-handle.d.ts +21 -0
  27. package/dist/core/dialect-handle.js +382 -0
  28. package/dist/core/directive-factory.d.ts +47 -0
  29. package/dist/core/directive-factory.js +154 -0
  30. package/dist/core/emit-rejection.d.ts +19 -0
  31. package/dist/core/emit-rejection.js +31 -0
  32. package/dist/core/engine-client.d.ts +7 -0
  33. package/dist/core/engine-client.js +5 -0
  34. package/dist/core/fs-errors.d.ts +1 -0
  35. package/dist/core/fs-errors.js +5 -0
  36. package/dist/core/handle-state.d.ts +24 -0
  37. package/dist/core/handle-state.js +4 -0
  38. package/dist/core/index.d.ts +10 -0
  39. package/dist/core/index.js +6 -0
  40. package/dist/core/jsx-name-validator.d.ts +19 -0
  41. package/dist/core/jsx-name-validator.js +104 -0
  42. package/dist/core/reject-tail.d.ts +23 -0
  43. package/dist/core/reject-tail.js +63 -0
  44. package/dist/core/schema/input-rejection.d.ts +4 -0
  45. package/dist/core/schema/input-rejection.js +32 -0
  46. package/dist/core/schema/schema-digest.d.ts +1 -0
  47. package/dist/core/schema/schema-digest.js +7 -0
  48. package/dist/core/schema/schema-discovery.d.ts +13 -0
  49. package/dist/core/schema/schema-discovery.js +51 -0
  50. package/dist/core/schema/schema-locate.d.ts +10 -0
  51. package/dist/core/schema/schema-locate.js +192 -0
  52. package/dist/core/schema/schema-model.d.ts +18 -0
  53. package/dist/core/schema/schema-model.js +15 -0
  54. package/dist/core/schema/schema-parse.d.ts +20 -0
  55. package/dist/core/schema/schema-parse.js +80 -0
  56. package/dist/core/schema/schema-sufficiency.d.ts +17 -0
  57. package/dist/core/schema/schema-sufficiency.js +54 -0
  58. package/dist/core/schema/schema-validate.d.ts +14 -0
  59. package/dist/core/schema/schema-validate.js +64 -0
  60. package/dist/core/session.d.ts +13 -0
  61. package/dist/core/session.js +72 -0
  62. package/dist/core/wire.d.ts +87 -0
  63. package/dist/core/wire.js +49 -0
  64. package/dist/dialects/react/ast.d.ts +25 -0
  65. package/dist/dialects/react/ast.js +80 -0
  66. package/dist/dialects/react/index.d.ts +39 -0
  67. package/dist/dialects/react/index.js +71 -0
  68. package/dist/dialects/react/ops.d.ts +56 -0
  69. package/dist/dialects/react/ops.js +186 -0
  70. package/dist/dialects/typescript/ast.d.ts +42 -0
  71. package/dist/dialects/typescript/ast.js +93 -0
  72. package/dist/dialects/typescript/index.d.ts +32 -0
  73. package/dist/dialects/typescript/index.js +40 -0
  74. package/dist/dialects/typescript/ops.d.ts +123 -0
  75. package/dist/dialects/typescript/ops.js +365 -0
  76. package/dist/dry-run/index.d.ts +2 -0
  77. package/dist/dry-run/index.js +1 -0
  78. package/dist/dry-run/plan.d.ts +69 -0
  79. package/dist/dry-run/plan.js +44 -0
  80. package/dist/index.d.ts +1 -0
  81. package/dist/index.js +3 -0
  82. package/dist/runner-manifest.json +104 -0
  83. package/dist/scaffold/classify-transport.d.ts +57 -0
  84. package/dist/scaffold/classify-transport.js +123 -0
  85. package/dist/scaffold/containment.d.ts +54 -0
  86. package/dist/scaffold/containment.js +242 -0
  87. package/dist/scaffold/expander.d.ts +30 -0
  88. package/dist/scaffold/expander.js +161 -0
  89. package/dist/scaffold/filename-pipeline.d.ts +39 -0
  90. package/dist/scaffold/filename-pipeline.js +125 -0
  91. package/dist/scaffold/index.d.ts +45 -0
  92. package/dist/scaffold/index.js +99 -0
  93. package/dist/scaffold/walk.d.ts +25 -0
  94. package/dist/scaffold/walk.js +124 -0
  95. package/dist/testing/contract-fake.d.ts +17 -0
  96. package/dist/testing/contract-fake.js +221 -0
  97. package/dist/testing/index.d.ts +84 -0
  98. package/dist/testing/index.js +82 -0
  99. package/dist/testing/rejection-messages.d.ts +7 -0
  100. package/dist/testing/rejection-messages.js +12 -0
  101. package/dist/transport/bootstrap-bridge.d.ts +33 -0
  102. package/dist/transport/bootstrap-bridge.js +65 -0
  103. package/dist/transport/error-text.d.ts +8 -0
  104. package/dist/transport/error-text.js +44 -0
  105. package/dist/transport/exit-codes.d.ts +2 -0
  106. package/dist/transport/exit-codes.js +35 -0
  107. package/dist/transport/factory-pointer.d.ts +32 -0
  108. package/dist/transport/factory-pointer.js +63 -0
  109. package/dist/transport/frame-reader.d.ts +10 -0
  110. package/dist/transport/frame-reader.js +81 -0
  111. package/dist/transport/framing.d.ts +20 -0
  112. package/dist/transport/framing.js +98 -0
  113. package/dist/transport/runner.d.ts +25 -0
  114. package/dist/transport/runner.js +308 -0
  115. package/dist/transport/single-instance-probe.d.ts +23 -0
  116. package/dist/transport/single-instance-probe.js +119 -0
  117. package/dist/transport/stdio-engine-client.d.ts +27 -0
  118. package/dist/transport/stdio-engine-client.js +243 -0
  119. package/dist/transport/wire-protocol.d.ts +33 -0
  120. package/dist/transport/wire-protocol.js +22 -0
  121. package/package.json +93 -0
@@ -0,0 +1,121 @@
1
+ // S-001: defineDialect / defineOpPack / withOps — real generics (KIT-04 / ADR-0010 /
2
+ // ADR-0037). Replaces the T-M2 thin stub: an AST type parameter, value-level op-pack
3
+ // intersection compile-enforced, and an awaitable coalescing Handle<State, Ast, Ops>.
4
+ //
5
+ // Bare (no type-argument) usage of `Dialect`/`OpPack`/`Handle` resolves via default type
6
+ // parameters to `<any, OpPack<any>>` — this is what lets src/conformance/index.ts's
7
+ // fixtures stay generic-erased ("some dialect, don't care about the concrete Ast") without
8
+ // re-parameterising the conformance kit itself (design §4.3's literal code block uses bare
9
+ // `Dialect`/`OpPack`). `any`, not `unknown`: `Op<Ast>`'s `ast` parameter is CONTRAVARIANT —
10
+ // a concrete `Dialect<ToyAst, ...>` is not structurally assignable to `Dialect<unknown, ...>`
11
+ // (target's param `unknown` must be assignable to source's param `ToyAst`, which it is not),
12
+ // but `any` short-circuits variance checking in both directions, which is exactly the
13
+ // "don't care about the concrete Ast" erasure this bare form needs.
14
+ import { createDialectHandle } from "./dialect-handle.js";
15
+ /**
16
+ * Declares a named collection of ops over one AST type — usable standalone (REQ-DG-02.3),
17
+ * e.g. shareable across two dialects targeting the same AST type, before any `withOps`
18
+ * composition occurs.
19
+ *
20
+ * @example
21
+ * const addImportPack = defineOpPack<SourceFile, { addImport(ast: SourceFile, name: string, from: string): void }>({
22
+ * addImport(ast, name, from) { ast.addImportDeclaration({ namedImports: [name], moduleSpecifier: from }); },
23
+ * });
24
+ */
25
+ export function defineOpPack(ops) {
26
+ return ops;
27
+ }
28
+ /**
29
+ * Assembles a `Dialect` from its frozen descriptor (extensions, an AST parse/print pair,
30
+ * and an op-pack). `find` is the dialect's ONLY entry verb into a run (REQ-DG-01.2) — it
31
+ * returns an open, coalescing `Handle`.
32
+ *
33
+ * @example
34
+ * const myDialect = defineDialect({
35
+ * extensions: [".ts"],
36
+ * ast: { parse: (s) => project.addSourceFileAtPath(s), print: (ast) => ast.getFullText() },
37
+ * ops: {},
38
+ * });
39
+ */
40
+ export function defineDialect(d) {
41
+ return {
42
+ extensions: d.extensions,
43
+ ast: d.ast,
44
+ ops: d.ops,
45
+ find(path) {
46
+ return createDialectHandle(d.ast, d.ops, path);
47
+ },
48
+ };
49
+ }
50
+ /**
51
+ * The base handle's own vocabulary (REQ-DG-02, ADR-0010 amendment) — an op-pack op sharing
52
+ * any of these names would silently shadow a base verb; `then` in particular would break the
53
+ * handle's `PromiseLike` join. `raw` stays reserved even though the verb itself is retired
54
+ * (ADR-0050) — a muscle-memory guardrail against authors reaching for the old name. Exported,
55
+ * ordered array (REQ-DG-02.7 pins this exact order via `toEqual`); `assertNoCompositionCollision`
56
+ * below consumes it through the derived, non-exported `RESERVED_SET`.
57
+ *
58
+ * @internal Exported for test/conformance observability only (so collision/exact-set tests can
59
+ * import it instead of hand-typing a second literal) — NOT a supported public API member, not
60
+ * semver-covered beyond the FIT-04 baseline pin it already sits inside (ORCHESTRATOR RULING R2).
61
+ */
62
+ export const RESERVED_HANDLE_NAMES = [
63
+ "then",
64
+ "read",
65
+ "raw",
66
+ "modify",
67
+ "replaceContent",
68
+ "rename",
69
+ "move",
70
+ "copy",
71
+ "remove",
72
+ ];
73
+ const RESERVED_SET = new Set(RESERVED_HANDLE_NAMES);
74
+ const _reservedCoversSurface = true;
75
+ void _reservedCoversSurface;
76
+ /**
77
+ * Eager, synchronous, fail-closed check run at `withOps` composition time (REQ-DG-02,
78
+ * ADR-0010 amendment): throws on a cross-pack op-name duplicate (including a collision
79
+ * against `base.ops`) or on an op name in `RESERVED_HANDLE_NAMES`. Both throws are PLAIN
80
+ * `Error`s, NOT minted via `dialectError()` — they are not run-op contained rejects and must
81
+ * never be recognised by `isContained` as passthrough (design §4.5's own rationale).
82
+ */
83
+ function assertNoCompositionCollision(baseOpNames, packs) {
84
+ const claimed = new Set(baseOpNames);
85
+ for (const pack of packs) {
86
+ for (const name of Object.keys(pack)) {
87
+ if (RESERVED_SET.has(name)) {
88
+ const hint = name === "raw" ? " — the live AST-fn escape hatch is .modify(fn)" : "";
89
+ throw new Error(`op-pack composition failed: op "${name}" collides with a reserved handle verb${hint}`);
90
+ }
91
+ if (claimed.has(name)) {
92
+ throw new Error(`op-pack composition failed: duplicate op "${name}" declared by more than one pack.`);
93
+ }
94
+ claimed.add(name);
95
+ }
96
+ }
97
+ }
98
+ /**
99
+ * Composes additional op-packs onto a base dialect. The resulting handle type is the
100
+ * INTERSECTION of the base's ops and every attached pack's ops (ADR-0010) — an op from an
101
+ * unattached pack, or a typo, is a compile error (REQ-DG-02.1). At composition time, an
102
+ * eager RUNTIME check (REQ-DG-02.2–02.5, ADR-0010 amendment) throws synchronously on a
103
+ * cross-pack op-name duplicate (or a collision against `base.ops`) or a reserved-vocabulary
104
+ * collision — composition never silently resolves to whichever pack happened to be spread
105
+ * last.
106
+ *
107
+ * @example
108
+ * const tsDialect = withOps(baseTsDialect, addImportPack);
109
+ */
110
+ export function withOps(base, ...packs) {
111
+ assertNoCompositionCollision(Object.keys(base.ops), packs);
112
+ const merged = Object.assign({}, base.ops, ...packs);
113
+ return {
114
+ extensions: base.extensions,
115
+ ast: base.ast,
116
+ ops: merged,
117
+ find(path) {
118
+ return createDialectHandle(base.ast, merged, path);
119
+ },
120
+ };
121
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Mints a fresh, WeakSet-branded contained error with the frozen presentation prefix. A
3
+ * fresh `Error` is constructed at the call site (stack cleanliness by construction) —
4
+ * `.cause` is always absent; the caller's own tail is the ONLY variable content.
5
+ */
6
+ export declare function dialectError(tail: string): Error;
7
+ /** WeakSet membership test — the sole containment discriminator (see F1 above). */
8
+ export declare function isContained(err: unknown): boolean;
@@ -0,0 +1,26 @@
1
+ // S-000: kit-internal contained-error module (ADR-0037 clause 0, no public symbol, out of
2
+ // every barrel/subpath). Sibling of ./deep-equal.ts — same kit-internal-shared-in-core
3
+ // pattern (ADR-0012 amendment clause 4 folds both under one decision, no separate ADR).
4
+ //
5
+ // F1 (BLOCKING, ADR-0037 amendment): the containment discriminator is this module-private
6
+ // WeakSet brand, NEVER a `message.startsWith(prefix)` match — a buggy op interpolating a
7
+ // caught foreign error into a message that happens to start with the frozen prefix would
8
+ // otherwise be rethrown verbatim (bypassing leak sanitisation), and a coincidental foreign
9
+ // prefix would misclassify. The WeakSet is unforgeable, non-enumerable, and carries no class
10
+ // name into the error (leak budget).
11
+ const ERROR_PREFIX = "dialect operation failed: ";
12
+ const contained = new WeakSet();
13
+ /**
14
+ * Mints a fresh, WeakSet-branded contained error with the frozen presentation prefix. A
15
+ * fresh `Error` is constructed at the call site (stack cleanliness by construction) —
16
+ * `.cause` is always absent; the caller's own tail is the ONLY variable content.
17
+ */
18
+ export function dialectError(tail) {
19
+ const err = new Error(ERROR_PREFIX + tail);
20
+ contained.add(err);
21
+ return err;
22
+ }
23
+ /** WeakSet membership test — the sole containment discriminator (see F1 above). */
24
+ export function isContained(err) {
25
+ return err instanceof Error && contained.has(err);
26
+ }
@@ -0,0 +1,21 @@
1
+ import type { OpPack, Handle } from "./define-dialect.ts";
2
+ interface DialectAst<Ast> {
3
+ parse(source: string): Ast;
4
+ print(ast: Ast): string;
5
+ }
6
+ /**
7
+ * Recovers the author-facing handle path for a live AST instance previously registered by
8
+ * `#ensureLive` — the ONLY channel through which an op function can reach the path for its
9
+ * own `dialectError()`-branded message (design §4.4's "on {path}" clause; unreachable any
10
+ * other way, since `Op<Ast>` and `DialectAst.parse()` carry no path parameter). Throws if
11
+ * called with an AST instance never registered by a handle — a contributor bug, not an
12
+ * author-reachable state.
13
+ */
14
+ export declare function handlePathFor(ast: object): string;
15
+ /**
16
+ * Builds the public-shaped `Handle<"found", Ast, Ops>` object backed by a
17
+ * `DialectHandleController`. Op methods are attached dynamically from `ops`' own keys —
18
+ * `Object.keys(ops)` is exactly the set `OpMethods<Ast, Ops>` describes at the type level.
19
+ */
20
+ export declare function createDialectHandle<Ast, Ops extends OpPack<Ast>>(dialectAst: DialectAst<Ast>, ops: Ops, path: string): Handle<"found", Ast, Ops>;
21
+ export {};
@@ -0,0 +1,382 @@
1
+ // S-001: the coalescing dialect handle factory (ADR-0037, kit-internal). Owns the seam
2
+ // ADR-0006 describes: read-through-parse once, hold ONE live AST, mutate it in place across
3
+ // a chain, serialize once — lazily, memoized — at whichever flush first drains it.
4
+ //
5
+ // Kit-internal handle-factory signature is EXECUTOR LATITUDE (design §4.3, Q4, rev 4): this
6
+ // module lives under src/core/**, is never a public subpath, and its shape is not
7
+ // fitness-pinned. Only the PUBLIC `find(path)` signature and the `Handle<State, Ast, Ops>`
8
+ // TYPE (define-dialect.ts) are frozen.
9
+ import { currentContext } from "./context.js";
10
+ import { dialectError, isContained } from "./dialect-error.js";
11
+ // `.modify()`'s `fn` is typed `(ast: Ast) => void`, but TS's void-return compatibility lets an
12
+ // author pass an async function anyway — this is the runtime check that catches that case.
13
+ function isThenable(value) {
14
+ return (typeof value === "object" &&
15
+ value !== null &&
16
+ typeof value.then === "function");
17
+ }
18
+ // Final-verify fix (F-1, position-independent path channel): keyed by the live AST
19
+ // instance itself, so an op can recover its handle's author-facing path WITHOUT any
20
+ // positional coupling to the op's own (variable-arity, author-optional) argument list. A
21
+ // WeakMap entry lives exactly as long as the AST instance it's keyed on (set once in
22
+ // #ensureLive, alongside `#live` itself) — no separate cleanup needed.
23
+ const astHandlePaths = new WeakMap();
24
+ /**
25
+ * Recovers the author-facing handle path for a live AST instance previously registered by
26
+ * `#ensureLive` — the ONLY channel through which an op function can reach the path for its
27
+ * own `dialectError()`-branded message (design §4.4's "on {path}" clause; unreachable any
28
+ * other way, since `Op<Ast>` and `DialectAst.parse()` carry no path parameter). Throws if
29
+ * called with an AST instance never registered by a handle — a contributor bug, not an
30
+ * author-reachable state.
31
+ */
32
+ export function handlePathFor(ast) {
33
+ const path = astHandlePaths.get(ast);
34
+ if (path === undefined) {
35
+ throw new Error("dialect-handle: handlePathFor() called with an unregistered AST instance");
36
+ }
37
+ return path;
38
+ }
39
+ // A getter-backed modify directive: `content` resolves lazily, exactly once, memoized — at
40
+ // whichever flush first `JSON.stringify`s the batch (ADR-0006's "serialize once at flush").
41
+ // `dryRun()` never triggers this: `dryRunPlan` reads only `verb`/`path` (REQ-MC-05).
42
+ //
43
+ // Row-145: `resolve` is nulled out immediately after its one use (rather than a separate
44
+ // `resolved` boolean) — the memoized getter's closure retained the ts-morph `Project` (via
45
+ // this print callback's own closure over the live AST) for the directive's entire lifetime
46
+ // even after resolving; nulling the reference makes the `Project`/live AST GC-eligible as
47
+ // soon as the content is known. Memory-only, no observable behavioral change (see
48
+ // test/core/dialect-handle.test.ts's row-145 note — deliberately untested there).
49
+ function lazyModifyDirective(path, resolveFn) {
50
+ let cached;
51
+ let resolve = resolveFn;
52
+ return {
53
+ op: "modify",
54
+ modify: {
55
+ path,
56
+ get content() {
57
+ if (resolve !== undefined) {
58
+ cached = resolve();
59
+ resolve = undefined;
60
+ }
61
+ return cached;
62
+ },
63
+ },
64
+ };
65
+ }
66
+ /**
67
+ * Owns the private state (`#tail`, the live AST, the open directive) behind one dialect
68
+ * handle. `createDialectHandle` below wraps this in the public-shaped object literal the
69
+ * `Handle<State, Ast, Ops>` type describes.
70
+ */
71
+ class DialectHandleController {
72
+ #tail = Promise.resolve();
73
+ #dialectAst;
74
+ #ops;
75
+ #path;
76
+ #live;
77
+ #openDirective;
78
+ #registered = false;
79
+ // Mutation-gate baseline (ADR-0037 clause 2), seeded from #ensureLive's own read — the
80
+ // ORIGINAL file content, before any op runs. #ensureOpen compares a fresh print against
81
+ // this to decide whether an op actually changed anything (REQ-TSD-08.4's zero-directive
82
+ // no-op) — never re-derived from a print-after-parse (would cost a redundant print).
83
+ #lastEmittedText;
84
+ constructor(dialectAst, ops, path) {
85
+ this.#dialectAst = dialectAst;
86
+ this.#ops = ops;
87
+ this.#path = path;
88
+ }
89
+ get ops() {
90
+ return this.#ops;
91
+ }
92
+ // The ONE containment primitive (ADR-0037, Q3): chains `step` onto `#tail` and
93
+ // EAGER-marks the updated `#tail` handled, synchronously, in the same turn — before
94
+ // returning to the caller. This closes the pre-drain `unhandledRejection` window for a
95
+ // forgotten-`await` throwing chain; the real rejection stays observable on `#tail` for
96
+ // author-`await` and `settle()`, and on the returned step-result promise for callers
97
+ // (like `read()`) that surface the step's value.
98
+ //
99
+ // F2 poison flag (ADR-0037 amendment, REQ-DG-07.3): every step and every read() route
100
+ // through this ONE wrapper. SAME-handle fail-closed sequencing is emergent — a rejected
101
+ // `#tail` already skips `guardedStep` via ordinary promise-chain semantics, no flag
102
+ // needed. The flag exists for the CROSS-handle case: a different handle's `#tail` is
103
+ // independent, so without this check its step WOULD run (mutate/buffer) even though
104
+ // nothing ever commits. `ctx.runFailure` is consulted at step entry (never attempted as a
105
+ // fresh operation) and set FIRST-WINS on catch (the earliest rejection in the run is the
106
+ // one every later op/read surfaces, unchanged).
107
+ #chain(step) {
108
+ const guardedStep = async () => {
109
+ const ctx = currentContext();
110
+ if (ctx.runFailure !== undefined) {
111
+ throw ctx.runFailure.reason;
112
+ }
113
+ try {
114
+ return await step();
115
+ }
116
+ catch (err) {
117
+ if (ctx.runFailure === undefined) {
118
+ ctx.runFailure = { reason: err };
119
+ }
120
+ throw ctx.runFailure.reason;
121
+ }
122
+ };
123
+ const result = this.#tail.then(guardedStep);
124
+ this.#tail = result.then(() => undefined);
125
+ this.#tail.catch(() => {
126
+ // Eager shadow-catch — intentionally empty. See module doc + ADR-0037.
127
+ });
128
+ this.#registerOnce();
129
+ return result;
130
+ }
131
+ #enqueue(step) {
132
+ void this.#chain(step);
133
+ }
134
+ #bufferDirective(build) {
135
+ this.#enqueue(() => {
136
+ const { session, factory } = currentContext();
137
+ session.buffer(build(factory));
138
+ });
139
+ }
140
+ #registerOnce() {
141
+ if (this.#registered)
142
+ return;
143
+ this.#registered = true;
144
+ currentContext().dialects.register({ settle: () => this.settle() });
145
+ }
146
+ async #ensureLive() {
147
+ if (this.#live !== undefined)
148
+ return;
149
+ const { session } = currentContext();
150
+ const content = await session.read(this.#path);
151
+ if (content === undefined) {
152
+ throw dialectError(`"${this.#path}" does not exist — create it first in this run`);
153
+ }
154
+ try {
155
+ this.#live = this.#dialectAst.parse(content);
156
+ }
157
+ catch {
158
+ throw dialectError(`could not parse "${this.#path}" as TypeScript`);
159
+ }
160
+ astHandlePaths.set(this.#live, this.#path);
161
+ this.#lastEmittedText = content;
162
+ }
163
+ #printContained() {
164
+ try {
165
+ return this.#dialectAst.print(this.#live);
166
+ }
167
+ catch {
168
+ throw dialectError(`could not print "${this.#path}"`);
169
+ }
170
+ }
171
+ // Shared predicate (row-141/row-136): is this handle's own AST-op directive still
172
+ // buffered, undrained? #ensureOpen consults it to skip re-registration while the prior
173
+ // directive is still pending; runReplaceContent consults the SAME check to reject a
174
+ // conflicting .replaceContent() (ADR-0039). `session` is passed in rather than re-derived
175
+ // via currentContext() — both call sites already have it in scope from their own context
176
+ // lookup.
177
+ #hasOpenPendingDirective(session) {
178
+ return this.#openDirective !== undefined && session.isPending(this.#openDirective);
179
+ }
180
+ // FIT-19 orphan guard (ADR-0037): re-registers a FRESH directive whenever the prior one
181
+ // is no longer present in the session's pending buffer (an IDENTITY check, never a value
182
+ // check) — this is what turns a global flush mid-chain into the split-into-two-modifies
183
+ // contract (REQ-MC-02), with no edit lost and no double-buffer.
184
+ //
185
+ // Mutation gate (ADR-0037 clause 2, row-141): registration only happens if the op
186
+ // actually changed the print vs #lastEmittedText — a true no-op (e.g. removeImport on an
187
+ // absent binding) never registers, so its run emits ZERO directives (REQ-TSD-08.4). Must
188
+ // be called AFTER the op has run (never before) so the print reflects its effect.
189
+ //
190
+ // Judgment-day round 2 (convergence fix, generalizes round 1's Issue 1): a directive can
191
+ // drain WITHOUT this handle's own read() ever running — a DIFFERENT handle's read() is
192
+ // ALSO a global flush-before-read (ADR-0015) and drains this handle's open directive too.
193
+ // So the "was it drained?" re-baseline can't live only in read() (round 1's fix) — it has
194
+ // to run HERE, right before the gate, for BOTH drain sources. When #hasOpenPendingDirective
195
+ // is false but #openDirective is still set, the prior directive was drained (by either
196
+ // path) since it was last registered: re-baseline #lastEmittedText to its content — the
197
+ // getter memoized the print the instant flush's JSON.stringify walked it (module doc,
198
+ // "serialize once ... at whichever flush first" — the value is already fixed, no fresh
199
+ // print needed nor possible after the op already mutated the live AST past it) — and clear
200
+ // #openDirective so the zero-directive gate below re-evaluates against the fresh baseline
201
+ // instead of unconditionally re-registering a byte-identical directive.
202
+ #ensureOpen() {
203
+ const { session } = currentContext();
204
+ if (this.#hasOpenPendingDirective(session)) {
205
+ return;
206
+ }
207
+ if (this.#openDirective !== undefined) {
208
+ if (this.#openDirective.op === "modify") {
209
+ this.#lastEmittedText = this.#openDirective.modify.content;
210
+ }
211
+ this.#openDirective = undefined;
212
+ }
213
+ if (this.#printContained() === this.#lastEmittedText) {
214
+ return;
215
+ }
216
+ this.#openDirective = lazyModifyDirective(this.#path, () => this.#printContained());
217
+ session.buffer(this.#openDirective);
218
+ }
219
+ // Shared containment primitive (ADR-0037 amendment clause 1): runs `fn`, awaits a
220
+ // thenable result INSIDE the try (so an async op's rejection is contained, never an
221
+ // unhandled rejection), and on catch discriminates by the WeakSet brand (`isContained`,
222
+ // NEVER `message.startsWith`) — a caught error already carrying the brand (an author's
223
+ // deliberate `dialectError` reject) is RETHROWN VERBATIM (REQ-DG-06.5, no double-wrap, no
224
+ // `.cause`); any foreign error is wrapped fresh via `dialectError(foreignTail)`.
225
+ async #invokeContained(fn, foreignTail) {
226
+ try {
227
+ const result = fn();
228
+ if (isThenable(result)) {
229
+ await result;
230
+ }
231
+ }
232
+ catch (caught) {
233
+ if (isContained(caught))
234
+ throw caught;
235
+ throw dialectError(foreignTail);
236
+ }
237
+ }
238
+ // Chaining is the WRAPPER's job (createDialectHandle, below) — these return void; the
239
+ // wrapper's dispatchers always return the public handle object, never `this` controller.
240
+ // `opName` names the tail for BOTH the foreign-wrap message (constraint: `{op}() on
241
+ // "{path}" threw`) and #ensureOpen runs AFTER the op (never before) — the mutation gate
242
+ // needs the op's effect already applied to compare against the baseline.
243
+ //
244
+ // Final-verify fix (F-1): the author-facing path is NEVER threaded as a runtime arg to
245
+ // `fn` — a trailing positional arg collided with the `options` slot whenever an
246
+ // add-op's OWN optional trailing param was omitted (the common call form), silently
247
+ // rendering "on \"undefined\"" in the collision message. The path channel is now
248
+ // POSITION-INDEPENDENT: `astHandlePaths` (module scope above), keyed by the live AST
249
+ // instance itself, set once in #ensureLive. An op needing the path for its own
250
+ // dialectError()-branded message calls the exported `handlePathFor(ast)` — no arity
251
+ // coupling to the author's own (variable, optional) argument list, so this is immune to
252
+ // however many params the author did or didn't supply.
253
+ runOp(fn, args, opName) {
254
+ this.#enqueue(async () => {
255
+ await this.#ensureLive();
256
+ await this.#invokeContained(() => fn(this.#live, ...args), `${opName}() on "${this.#path}" threw`);
257
+ this.#ensureOpen();
258
+ });
259
+ }
260
+ // Council fix pass (security note 1, ADR-0037): an ASYNC `fn` is awaited INSIDE the SAME
261
+ // shared containment `runOp` uses (`#invokeContained`) — the enqueued step already runs
262
+ // in the async `#tail` chain, so awaiting is natural. Without this, `fn`'s returned
263
+ // promise floats unobserved: a rejection surfaces as an uncontained `unhandledRejection`
264
+ // (leaking the raw internal message) while the run COMMITS as if successful, and a
265
+ // resolve-after-delay's mutation may race the print.
266
+ runModify(fn) {
267
+ this.#enqueue(async () => {
268
+ await this.#ensureLive();
269
+ await this.#invokeContained(() => fn(this.#live), `modify() on "${this.#path}" threw`);
270
+ this.#ensureOpen();
271
+ });
272
+ }
273
+ // ADR-0039 (row-136, amended by ADR-0050): rejects when this handle's own open AST-op
274
+ // directive is STILL PENDING (undrained) — the IDENTICAL predicate #ensureOpen already
275
+ // tests. This guard follows the SEMANTICS (wholesale replace clobbering a pending
276
+ // structured edit), not the verb spelling — it lives here, never on `.modify(fn)`
277
+ // (REQ-MC-08.5: `.modify(fn)` coalesces freely, no guard). Checked INSIDE the enqueued
278
+ // step (not at call time): #openDirective is only set once addImport's own async step has
279
+ // actually run, which #tail sequencing guarantees has happened by the time THIS step
280
+ // executes. `.read()` remains the documented escape (it drains the pending directive
281
+ // first, so a `.replaceContent()` chained after a `.read()` is unaffected).
282
+ runReplaceContent(content) {
283
+ this.#enqueue(() => {
284
+ const { session, factory } = currentContext();
285
+ if (this.#hasOpenPendingDirective(session)) {
286
+ throw dialectError(`cannot .replaceContent() "${this.#path}" while a structured edit is pending — the pending edit would be lost; call .read() to commit it first, then .replaceContent()`);
287
+ }
288
+ session.buffer(factory.modify({ path: this.#path, content }));
289
+ });
290
+ }
291
+ runRename(newName, opts) {
292
+ this.#bufferDirective((factory) => factory.rename({ path: this.#path, newName, force: opts?.force }));
293
+ }
294
+ runMove(toDir, opts) {
295
+ this.#bufferDirective((factory) => factory.move({ path: this.#path, toDir, force: opts?.force }));
296
+ }
297
+ runCopy(to, opts) {
298
+ this.#bufferDirective((factory) => factory.copy({ from: this.#path, to, force: opts?.force }));
299
+ }
300
+ runRemove() {
301
+ this.#bufferDirective((factory) => factory.remove({ path: this.#path }));
302
+ }
303
+ // Sequenced on #tail (author order): a mid-chain read must observe every op enqueued
304
+ // before it. Session.read is the GLOBAL flush-before-read (ADR-0015) — this drains this
305
+ // handle's own open directive (and every other handle's), which is exactly what makes
306
+ // read-your-own-writes hold (REQ-MC-02.2). The drain itself needs no re-baseline here:
307
+ // #ensureOpen (judgment-day round 2) detects a drained-but-still-set #openDirective on
308
+ // the NEXT op, from EITHER drain source (this handle's own read(), like this one, or a
309
+ // different handle's), and re-baselines from the drained directive's memoized content —
310
+ // one mechanism instead of two subtly different ones.
311
+ read() {
312
+ return this.#chain(async () => {
313
+ const { session } = currentContext();
314
+ return session.read(this.#path);
315
+ });
316
+ }
317
+ // Awaited by the run-boundary drain, and delegated to by `then()` for an author `await`.
318
+ // Force-resolves the open directive's getter AFTER `#tail` settles, so a print-throw
319
+ // surfaces here (at drain) rather than silently later.
320
+ settle() {
321
+ return this.#tail.then(() => {
322
+ if (this.#openDirective?.op === "modify") {
323
+ // Trigger (and thereby memoize) the lazy getter now.
324
+ void this.#openDirective.modify.content;
325
+ }
326
+ });
327
+ }
328
+ then(onfulfilled, onrejected) {
329
+ return this.#tail.then(onfulfilled, onrejected);
330
+ }
331
+ }
332
+ /**
333
+ * Builds the public-shaped `Handle<"found", Ast, Ops>` object backed by a
334
+ * `DialectHandleController`. Op methods are attached dynamically from `ops`' own keys —
335
+ * `Object.keys(ops)` is exactly the set `OpMethods<Ast, Ops>` describes at the type level.
336
+ */
337
+ export function createDialectHandle(dialectAst, ops, path) {
338
+ const controller = new DialectHandleController(dialectAst, ops, path);
339
+ // Every chaining method returns `handle` (the PUBLIC wrapper below), never the
340
+ // controller directly — the author-facing chain must keep landing on an object that
341
+ // carries `.modify`/`.push`(op methods)/etc., which the controller itself does not expose.
342
+ // Safe forward reference: these are closures, only evaluated when called — by then
343
+ // `handle` below is already assigned.
344
+ const base = {
345
+ read: () => controller.read(),
346
+ modify: (fn) => {
347
+ controller.runModify(fn);
348
+ return handle;
349
+ },
350
+ replaceContent: (content) => {
351
+ controller.runReplaceContent(content);
352
+ return handle;
353
+ },
354
+ rename: (newName, opts) => {
355
+ controller.runRename(newName, opts);
356
+ return handle;
357
+ },
358
+ move: (toDir, opts) => {
359
+ controller.runMove(toDir, opts);
360
+ return handle;
361
+ },
362
+ copy: (to, opts) => {
363
+ controller.runCopy(to, opts);
364
+ return handle;
365
+ },
366
+ remove: () => {
367
+ controller.runRemove();
368
+ },
369
+ then: (onfulfilled, onrejected) => controller.then(onfulfilled, onrejected),
370
+ };
371
+ // The op-derived members — one bound dispatcher per key in `ops` (exactly what
372
+ // `OpMethods<Ast, Ops>` describes at the type level).
373
+ const opMethods = Object.fromEntries(Object.keys(ops).map((opName) => [
374
+ opName,
375
+ (...args) => {
376
+ controller.runOp(ops[opName], args, opName);
377
+ return handle;
378
+ },
379
+ ]));
380
+ const handle = Object.assign({}, base, opMethods);
381
+ return handle;
382
+ }
@@ -0,0 +1,47 @@
1
+ import type { Directive, JsonValue } from "./wire.ts";
2
+ export interface CreateArgs {
3
+ pathTemplate: string;
4
+ template: string;
5
+ options: JsonValue;
6
+ force?: boolean;
7
+ }
8
+ export interface ModifyArgs {
9
+ path: string;
10
+ content: string;
11
+ }
12
+ export interface RemoveArgs {
13
+ path: string;
14
+ }
15
+ export interface RenameArgs {
16
+ path: string;
17
+ newName: string;
18
+ force?: boolean;
19
+ }
20
+ export interface MoveArgs {
21
+ path: string;
22
+ toDir: string;
23
+ force?: boolean;
24
+ }
25
+ export interface CopyArgs {
26
+ from: string;
27
+ to: string;
28
+ force?: boolean;
29
+ }
30
+ export interface CopyInArgs {
31
+ from: string;
32
+ to: string;
33
+ force?: boolean;
34
+ }
35
+ export declare function forceEntry(force: boolean | undefined): {
36
+ force?: boolean;
37
+ };
38
+ export declare function encodeOptions(options: JsonValue): JsonValue;
39
+ export declare class DirectiveFactory {
40
+ create(a: CreateArgs): Directive;
41
+ modify(a: ModifyArgs): Directive;
42
+ remove(a: RemoveArgs): Directive;
43
+ rename(a: RenameArgs): Directive;
44
+ move(a: MoveArgs): Directive;
45
+ copy(a: CopyArgs): Directive;
46
+ copyIn(a: CopyInArgs): Directive;
47
+ }