@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,17 @@
1
+ import type { EngineClient } from "../core/engine-client.ts";
2
+ import type { Batch } from "../core/wire.ts";
3
+ export type ServedFrom = "tree" | "disk";
4
+ export interface ContractFakeOptions {
5
+ seed: Record<string, string>;
6
+ }
7
+ export declare class ContractFake implements EngineClient {
8
+ #private;
9
+ lastServed: ServedFrom | null;
10
+ constructor({ seed }: ContractFakeOptions);
11
+ emit(batch: Batch): Promise<void>;
12
+ commit(): Promise<void>;
13
+ discard(): Promise<void>;
14
+ committedTree(): ReadonlyMap<string, string>;
15
+ stagingTree(): ReadonlyMap<string, string>;
16
+ read(filePath: string): Promise<string | undefined>;
17
+ }
@@ -0,0 +1,221 @@
1
+ // FAKE-01..06 (S-002 full fidelity): seeded flat in-memory tree, single-phase eager apply.
2
+ // Tree-first read: staged content takes precedence over the seed.
3
+ // served:"tree"|"disk" is fake-internal test state (lastServed), never in the EngineClient.read return.
4
+ // Force semantics (FAKE-04): effective = envelope.force OR op.force.
5
+ // create/rename/copy over an existing target → error unless effective.
6
+ // Idempotent delete (FAKE-05): absent target → succeed (no error).
7
+ import { posix as path } from "node:path";
8
+ import { EMIT_BATCH_BUDGET_BYTES, EMIT_FRAME_ENVELOPE_ALLOWANCE_BYTES, exceedsEmitBatchBudget } from "../core/wire.js";
9
+ import { EmitRejection } from "../core/emit-rejection.js";
10
+ import { deepEqual } from "../core/deep-equal.js";
11
+ import { CONTRACT_FAKE_PREFIX, ALREADY_EXISTS, USE_FORCE_TO_OVERWRITE, NOT_FOUND, EXCEEDS_SIZE_CAP, ROUND_TRIP_FIDELITY_CHECK, JSON_SERIALIZATION, } from "./rejection-messages.js";
12
+ export class ContractFake {
13
+ // Null-prototype + Object.hasOwn everywhere below: a plain-prototype seed object makes
14
+ // "path in seed" / seed[path] leak Object.prototype members ("__proto__", "constructor",
15
+ // "toString", ...) as spuriously present, even when the caller never seeded them.
16
+ #seed;
17
+ #tree = new Map();
18
+ // ADR-01 two-phase model: #committed is empty until commit() promotes staging into it.
19
+ // read() NEVER consults #committed — read-your-own-writes stays bound to #tree (staging).
20
+ #committed = new Map();
21
+ // Tracks paths that have been explicitly deleted (so deleted seed paths stay absent).
22
+ #deleted = new Set();
23
+ lastServed = null;
24
+ constructor({ seed }) {
25
+ this.#seed = Object.assign(Object.create(null), seed);
26
+ }
27
+ async emit(batch) {
28
+ // boundary REQ-02 (stringify-throw family): BigInt/circular values make
29
+ // JSON.stringify itself throw. Guarded here — once, shared with the cap check below
30
+ // and the round-trip compare — so the throw surfaces as an `emit` rejection instead
31
+ // of an uncaught crash.
32
+ let serialized;
33
+ try {
34
+ serialized = JSON.stringify(batch);
35
+ }
36
+ catch (err) {
37
+ throw new EmitRejection("unrepresentable", `${CONTRACT_FAKE_PREFIX} batch failed ${JSON_SERIALIZATION}: "${err instanceof Error ? err.message : String(err)}"`);
38
+ }
39
+ // ADR-0019: cap enforced HERE — the fake is the engine stand-in and the sole judge
40
+ // of size (ADR-0018); Session.flush calls emit unconditionally, no SDK-side branch.
41
+ // fit-32 cap-single-source + FEH-01 parity (spec V4 REQ-WPS-04.1): routed through the
42
+ // SAME `exceedsEmitBatchBudget` measurer `StdioEngineClient.emit` uses — the fake and
43
+ // the real transport can never diverge on an accept/reject verdict for the same batch.
44
+ if (exceedsEmitBatchBudget(batch)) {
45
+ const size = Buffer.byteLength(serialized, "utf8");
46
+ throw new EmitRejection("cap", `${CONTRACT_FAKE_PREFIX} batch ${EXCEEDS_SIZE_CAP} — ${size} bytes serialized, budget is ${EMIT_BATCH_BUDGET_BYTES} bytes (the frame cap minus the ${EMIT_FRAME_ENVELOPE_ALLOWANCE_BYTES}-byte envelope allowance)`);
47
+ }
48
+ // boundary REQ-01/02 (silent-drop family): stringify can SUCCEED while quietly
49
+ // dropping function/undefined/Symbol values — only a structural compare against the
50
+ // original catches that.
51
+ const roundTripped = JSON.parse(serialized);
52
+ if (!deepEqual(batch, roundTripped)) {
53
+ throw new EmitRejection("unrepresentable", `${CONTRACT_FAKE_PREFIX} batch failed ${ROUND_TRIP_FIDELITY_CHECK}: non-JSON-safe value detected`);
54
+ }
55
+ for (const [index, directive] of batch.instructions.entries()) {
56
+ this.#apply(directive, batch.force, index);
57
+ }
58
+ }
59
+ // ADR-01: promote the staging tree into the committed tree atomically, then clear staging.
60
+ // Staged deletions remove the path from committed. All-or-nothing: a single call promotes
61
+ // the whole staged set.
62
+ async commit() {
63
+ for (const [p, content] of this.#tree) {
64
+ this.#committed.set(p, content);
65
+ }
66
+ for (const p of this.#deleted) {
67
+ this.#committed.delete(p);
68
+ }
69
+ this.#tree.clear();
70
+ this.#deleted.clear();
71
+ }
72
+ // ADR-01: drop the staging tree; the committed tree is untouched.
73
+ async discard() {
74
+ this.#tree.clear();
75
+ this.#deleted.clear();
76
+ }
77
+ // Test-only assertion accessors (NOT on the EngineClient port).
78
+ committedTree() {
79
+ return new Map(this.#committed);
80
+ }
81
+ stagingTree() {
82
+ return new Map(this.#tree);
83
+ }
84
+ // ADR-01: not-found returns `undefined` (NOT a throw). Absence is detected by KEY MEMBERSHIP
85
+ // (#deleted.has / !#tree.has / !(in #seed)) — never truthiness — so a seeded "" returns "".
86
+ async read(filePath) {
87
+ if (this.#deleted.has(filePath)) {
88
+ return undefined;
89
+ }
90
+ if (this.#tree.has(filePath)) {
91
+ this.lastServed = "tree";
92
+ return this.#tree.get(filePath);
93
+ }
94
+ if (Object.hasOwn(this.#seed, filePath)) {
95
+ this.lastServed = "disk";
96
+ return this.#seed[filePath];
97
+ }
98
+ return undefined;
99
+ }
100
+ #exists(p) {
101
+ if (this.#deleted.has(p))
102
+ return false;
103
+ return this.#tree.has(p) || Object.hasOwn(this.#seed, p);
104
+ }
105
+ #getContent(p) {
106
+ if (this.#tree.has(p))
107
+ return this.#tree.get(p);
108
+ return this.#seed[p];
109
+ }
110
+ // FAKE-04: envelope force wins over an absent/false op-level force.
111
+ #effectiveForce(envelopeForce, opForce) {
112
+ return envelopeForce || (opForce ?? false);
113
+ }
114
+ #requireExists(target, label, pos) {
115
+ if (!this.#exists(target)) {
116
+ throw new EmitRejection("not-found", `${CONTRACT_FAKE_PREFIX} ${label} ${NOT_FOUND}: "${target}"`, pos);
117
+ }
118
+ }
119
+ #rejectIfCollides(target, effective, label, pos) {
120
+ if (this.#exists(target) && !effective) {
121
+ throw new EmitRejection("collision", `${CONTRACT_FAKE_PREFIX} ${label} ${ALREADY_EXISTS} (${USE_FORCE_TO_OVERWRITE})`, pos);
122
+ }
123
+ }
124
+ // `index` is this directive's position in the batch — every earlier directive already
125
+ // applied (eager array-order apply), so a throw HERE means `appliedCount === index`
126
+ // (emit-rejection-metadata REQ-ERM-01).
127
+ #apply(directive, envelopeForce, index) {
128
+ const pos = { failedIndex: index, appliedCount: index };
129
+ if (directive.op === "create") {
130
+ const { pathTemplate, template, force: opForce } = directive.create;
131
+ const effective = this.#effectiveForce(envelopeForce, opForce);
132
+ this.#rejectIfCollides(pathTemplate, effective, `create collision — "${pathTemplate}"`, pos);
133
+ // The fake stores the template as content; rendering is the engine's concern.
134
+ this.#deleted.delete(pathTemplate);
135
+ this.#tree.set(pathTemplate, template);
136
+ return;
137
+ }
138
+ if (directive.op === "modify") {
139
+ const { path: p, content } = directive.modify;
140
+ // ADR-0017 rule 2: modify never materializes a new file — the target must already
141
+ // exist (staging counts: eager array-order apply means an earlier create/modify in
142
+ // the same batch is visible here).
143
+ this.#requireExists(p, "modify target", pos);
144
+ this.#deleted.delete(p);
145
+ this.#tree.set(p, content);
146
+ return;
147
+ }
148
+ if (directive.op === "delete") {
149
+ const { path: p } = directive.delete;
150
+ // Idempotent: absent target is not an error.
151
+ this.#tree.delete(p);
152
+ this.#deleted.add(p);
153
+ return;
154
+ }
155
+ if (directive.op === "rename") {
156
+ const { path: src, newName, force: opForce } = directive.rename;
157
+ // The real engine cannot rename a non-existent file (FAKE-06 fidelity).
158
+ this.#requireExists(src, "rename source", pos);
159
+ const dir = path.dirname(src);
160
+ const dst = dir === "." ? newName : path.join(dir, newName);
161
+ const effective = this.#effectiveForce(envelopeForce, opForce);
162
+ this.#rejectIfCollides(dst, effective, `rename collision — destination "${dst}"`, pos);
163
+ const content = this.#getContent(src);
164
+ // Remove source, write destination.
165
+ this.#tree.delete(src);
166
+ this.#deleted.add(src);
167
+ this.#deleted.delete(dst);
168
+ this.#tree.set(dst, content);
169
+ return;
170
+ }
171
+ if (directive.op === "copy") {
172
+ const { from, to, force: opForce } = directive.copy;
173
+ // The real engine cannot copy a non-existent source (FAKE-06 fidelity).
174
+ this.#requireExists(from, "copy source", pos);
175
+ const effective = this.#effectiveForce(envelopeForce, opForce);
176
+ this.#rejectIfCollides(to, effective, `copy collision — destination "${to}"`, pos);
177
+ const content = this.#getContent(from);
178
+ this.#deleted.delete(to);
179
+ this.#tree.set(to, content);
180
+ return;
181
+ }
182
+ // ADR-0045 division of labor: the SDK's own pre-emit containment/stat validation is
183
+ // the legitimate origin of a missing-source rejection (REQ-BRC-06) — the fake is NOT
184
+ // required to re-check package disk, so unlike `copy` there is no `#requireExists`
185
+ // call here. Emit-only: a successful copyIn NEVER writes `#tree` (REQ-ATH-15.1, Q21 —
186
+ // no simulation surface ever materializes by-reference bytes) — only the destination
187
+ // collision is checked, mirroring `create`'s own collision semantics (REQ-BRC-05).
188
+ if (directive.op === "copyIn") {
189
+ const { to, force: opForce } = directive.copyIn;
190
+ const effective = this.#effectiveForce(envelopeForce, opForce);
191
+ this.#rejectIfCollides(to, effective, `copyIn collision — destination "${to}"`, pos);
192
+ return;
193
+ }
194
+ if (directive.op === "move") {
195
+ const { path: src, toDir, force: opForce } = directive.move;
196
+ // The real engine cannot move a non-existent source (FAKE-06 fidelity).
197
+ this.#requireExists(src, "move source", pos);
198
+ const base = path.basename(src);
199
+ // Use path.join to normalize trailing-slash toDir (e.g. "lib/" → "lib/foo.ts").
200
+ const dst = path.join(toDir, base);
201
+ const effective = this.#effectiveForce(envelopeForce, opForce);
202
+ // ADR-0017 self-move identity amendment: dst === src is not a collision — a
203
+ // self-move is a file-preserving success, no force required.
204
+ const isSelfMove = dst === src;
205
+ if (!isSelfMove) {
206
+ this.#rejectIfCollides(dst, effective, `move collision — destination "${dst}"`, pos);
207
+ }
208
+ const content = this.#getContent(src);
209
+ this.#tree.delete(src);
210
+ this.#deleted.add(src);
211
+ this.#deleted.delete(dst);
212
+ this.#tree.set(dst, content);
213
+ return;
214
+ }
215
+ // Exhaustiveness guard (final-verify remediation): an 8th wire op would otherwise
216
+ // compile through this if-chain and silently no-op — mirrors the `_exhaustive: never`
217
+ // idiom `authoring-error.ts`'s `messageFor`/`originFor` switches already use.
218
+ const _exhaustive = directive;
219
+ throw new Error(`unhandled directive op: ${_exhaustive.op}`);
220
+ }
221
+ }
@@ -0,0 +1,84 @@
1
+ import type { Batch, Directive } from "../core/wire.ts";
2
+ import type { AuthoringError } from "../core/authoring-error.ts";
3
+ /**
4
+ * The outcome of running a factory via `runFactoryForTest`.
5
+ *
6
+ * @example
7
+ * const result: RunResult = await runFactoryForTest(run, input);
8
+ * if (result.error === undefined) {
9
+ * console.log(result.tree.get("src/greeting.ts"));
10
+ * }
11
+ */
12
+ export interface RunResult {
13
+ /**
14
+ * The committed tree (`ContractFake.committedTree()`), path → content. Committed writes
15
+ * ONLY — an unmodified seed path is never present here, even if the factory read it.
16
+ * Content is stored verbatim — `{{...}}` template placeholders are never rendered here;
17
+ * interpolation is the engine's job, not the harness's.
18
+ */
19
+ tree: ReadonlyMap<string, string>;
20
+ /** One `Batch` per `emit()` call, in call order. */
21
+ emitted: Batch[];
22
+ /**
23
+ * `undefined` on success. On a rejected write, the attributed `AuthoringError` from the
24
+ * emit seam. On a factory throw, the original thrown value, unmodified.
25
+ */
26
+ error: AuthoringError | unknown;
27
+ }
28
+ export type { Batch, Directive };
29
+ /**
30
+ * Runs a bare author factory in-memory against a normative fake engine and returns what
31
+ * actually happened — closing the gap where a write-only factory (one that buffers
32
+ * directives but is never observed to commit them) has no author-facing test to catch it.
33
+ *
34
+ * `fn` is the bare `(input) => void | Promise<void>` author function — never a
35
+ * `defineFactory`-wrapped runner. `runFactoryForTest` wraps `fn` internally by delegating to
36
+ * `defineFactory`, the SAME seam a future production runner will call (single-wrap-seam
37
+ * invariant) — it never reimplements the wrap. The harness constructs its own in-memory fake
38
+ * and spy client internally — callers never construct or pass a client.
39
+ *
40
+ * 0.x, semver-exempt: this module's result shape may still change before the SDK's first
41
+ * stable release, independent of the kit's own semver policy.
42
+ *
43
+ * `./testing` is the supported author-facing test harness — distinct from `./conformance`,
44
+ * which exercises dialect-authoring conformance, not factory behaviour.
45
+ *
46
+ * @param fn - the bare authoring function; receives the resolved input.
47
+ * @param input - the resolved input passed through to `fn`.
48
+ * @param options.seed - pre-existing tree content visible to the factory's own reads
49
+ * (`Record<string,string>`) — the SOLE seeding channel; never reflected in `result.tree`
50
+ * unless the factory itself modifies the seeded path.
51
+ * @param options.packageDir - opts the run into schema-derived run-boundary validation
52
+ * against an adjacent `schema.json` (pass `import.meta.dir`, never `import.meta.url`); when
53
+ * absent the run is the untyped, unvalidated tier, byte-identical to a run with no
54
+ * `packageDir` at all.
55
+ *
56
+ * @example
57
+ * import { runFactoryForTest } from "@pbuilder/sdk/testing";
58
+ * import { create, AuthoringError } from "@pbuilder/sdk/commons";
59
+ * import { expect, test } from "bun:test";
60
+ *
61
+ * test("factory writes a greeting file", async () => {
62
+ * const run = (input: { name: string }) => {
63
+ * create("src/greeting.ts", {
64
+ * template: "export const greeting = '{{name}}';",
65
+ * options: { name: input.name },
66
+ * });
67
+ * };
68
+ *
69
+ * const result = await runFactoryForTest(run, { name: "hello" });
70
+ *
71
+ * if (result.error !== undefined) {
72
+ * if (result.error instanceof AuthoringError) {
73
+ * throw new Error(`unexpected rejection: ${result.error.reason}`);
74
+ * }
75
+ * throw result.error;
76
+ * }
77
+ *
78
+ * expect(result.tree.get("src/greeting.ts")).toEqual("export const greeting = '{{name}}';");
79
+ * });
80
+ */
81
+ export declare function runFactoryForTest<O>(fn: (input: O) => void | Promise<void>, input: O, options?: {
82
+ seed?: Record<string, string>;
83
+ packageDir?: string | URL;
84
+ }): Promise<RunResult>;
@@ -0,0 +1,82 @@
1
+ import { defineFactory } from "../core/context.js";
2
+ import { ContractFake } from "./contract-fake.js";
3
+ /**
4
+ * Runs a bare author factory in-memory against a normative fake engine and returns what
5
+ * actually happened — closing the gap where a write-only factory (one that buffers
6
+ * directives but is never observed to commit them) has no author-facing test to catch it.
7
+ *
8
+ * `fn` is the bare `(input) => void | Promise<void>` author function — never a
9
+ * `defineFactory`-wrapped runner. `runFactoryForTest` wraps `fn` internally by delegating to
10
+ * `defineFactory`, the SAME seam a future production runner will call (single-wrap-seam
11
+ * invariant) — it never reimplements the wrap. The harness constructs its own in-memory fake
12
+ * and spy client internally — callers never construct or pass a client.
13
+ *
14
+ * 0.x, semver-exempt: this module's result shape may still change before the SDK's first
15
+ * stable release, independent of the kit's own semver policy.
16
+ *
17
+ * `./testing` is the supported author-facing test harness — distinct from `./conformance`,
18
+ * which exercises dialect-authoring conformance, not factory behaviour.
19
+ *
20
+ * @param fn - the bare authoring function; receives the resolved input.
21
+ * @param input - the resolved input passed through to `fn`.
22
+ * @param options.seed - pre-existing tree content visible to the factory's own reads
23
+ * (`Record<string,string>`) — the SOLE seeding channel; never reflected in `result.tree`
24
+ * unless the factory itself modifies the seeded path.
25
+ * @param options.packageDir - opts the run into schema-derived run-boundary validation
26
+ * against an adjacent `schema.json` (pass `import.meta.dir`, never `import.meta.url`); when
27
+ * absent the run is the untyped, unvalidated tier, byte-identical to a run with no
28
+ * `packageDir` at all.
29
+ *
30
+ * @example
31
+ * import { runFactoryForTest } from "@pbuilder/sdk/testing";
32
+ * import { create, AuthoringError } from "@pbuilder/sdk/commons";
33
+ * import { expect, test } from "bun:test";
34
+ *
35
+ * test("factory writes a greeting file", async () => {
36
+ * const run = (input: { name: string }) => {
37
+ * create("src/greeting.ts", {
38
+ * template: "export const greeting = '{{name}}';",
39
+ * options: { name: input.name },
40
+ * });
41
+ * };
42
+ *
43
+ * const result = await runFactoryForTest(run, { name: "hello" });
44
+ *
45
+ * if (result.error !== undefined) {
46
+ * if (result.error instanceof AuthoringError) {
47
+ * throw new Error(`unexpected rejection: ${result.error.reason}`);
48
+ * }
49
+ * throw result.error;
50
+ * }
51
+ *
52
+ * expect(result.tree.get("src/greeting.ts")).toEqual("export const greeting = '{{name}}';");
53
+ * });
54
+ */
55
+ export async function runFactoryForTest(fn, input, options) {
56
+ const fake = new ContractFake({ seed: options?.seed ?? {} });
57
+ const emitted = [];
58
+ const client = {
59
+ emit(batch) {
60
+ emitted.push(batch);
61
+ return fake.emit(batch);
62
+ },
63
+ read(path) {
64
+ return fake.read(path);
65
+ },
66
+ commit() {
67
+ return fake.commit();
68
+ },
69
+ discard() {
70
+ return fake.discard();
71
+ },
72
+ };
73
+ const run = defineFactory(fn, options?.packageDir !== undefined ? { packageDir: options.packageDir } : undefined);
74
+ let error;
75
+ try {
76
+ await run(input, { client });
77
+ }
78
+ catch (caught) {
79
+ error = caught;
80
+ }
81
+ return { tree: fake.committedTree(), emitted, error };
82
+ }
@@ -0,0 +1,7 @@
1
+ export declare const CONTRACT_FAKE_PREFIX = "ContractFake:";
2
+ export declare const ALREADY_EXISTS = "already exists";
3
+ export declare const USE_FORCE_TO_OVERWRITE = "use force to overwrite";
4
+ export declare const NOT_FOUND = "not found";
5
+ export declare const EXCEEDS_SIZE_CAP = "exceeds size cap";
6
+ export declare const ROUND_TRIP_FIDELITY_CHECK = "round-trip fidelity check";
7
+ export declare const JSON_SERIALIZATION = "JSON serialization";
@@ -0,0 +1,12 @@
1
+ // Shared message-fragment dictionary (design §4.7 / REQ-AEC-05): the SAME constants the
2
+ // fake's throw sites compose their messages from AND FIT-11's leak-scan dictionary reads
3
+ // from. Rewording a fake message can never silently false-green the leak scan — both
4
+ // sides read this one module, so a wording drift shows up as a compile-time/test failure
5
+ // at the fake's throw site, not a stale copy nobody remembers to update.
6
+ export const CONTRACT_FAKE_PREFIX = "ContractFake:";
7
+ export const ALREADY_EXISTS = "already exists";
8
+ export const USE_FORCE_TO_OVERWRITE = "use force to overwrite";
9
+ export const NOT_FOUND = "not found";
10
+ export const EXCEEDS_SIZE_CAP = "exceeds size cap";
11
+ export const ROUND_TRIP_FIDELITY_CHECK = "round-trip fidelity check";
12
+ export const JSON_SERIALIZATION = "JSON serialization";
@@ -0,0 +1,33 @@
1
+ import { type RunnerIo } from "./runner.ts";
2
+ export declare class BridgeVersionMismatchError extends Error {
3
+ constructor(expected: number, actual: number);
4
+ }
5
+ export type BridgeInput = {
6
+ kind: "inline";
7
+ json: string;
8
+ } | {
9
+ kind: "file";
10
+ path: string;
11
+ };
12
+ export interface BridgeParams {
13
+ factory: string;
14
+ input: BridgeInput;
15
+ }
16
+ export interface BridgeIo {
17
+ input: RunnerIo["input"];
18
+ writeStderr: RunnerIo["writeStderr"];
19
+ }
20
+ export interface BridgeProtection {
21
+ captureFrameWriter(): RunnerIo["writeFrame"];
22
+ redirectConsole(): void;
23
+ }
24
+ /**
25
+ * REQ-BRB-01: the engine's embedded bootstrap calls this ONCE, having already dynamic-
26
+ * imported this module, passing the bridge contract version IT expects and the
27
+ * argv-equivalent params (factory pointer, input/input-file). Rejects immediately — no
28
+ * protection armed, no factory-related code reached — on a version mismatch, naming both
29
+ * versions. On a match, arms the SAME fd-1/console protection RUN-08 gives the direct-spawn
30
+ * path (BRB-02/03), then hands the params to runner.ts's composition root through the SAME
31
+ * RUN-01..04 gates argv uses (BRB-01.3) — never a duplicated, weaker check.
32
+ */
33
+ export declare function enterBridge(expectedVersion: number, params: BridgeParams, io: BridgeIo, protection?: BridgeProtection): Promise<number>;
@@ -0,0 +1,65 @@
1
+ // REQ-BRB-01/02/03: the versioned in-process entry point the engine's embedded bootstrap
2
+ // dynamic-imports to hand off control (owner ruling #2157 point 3) — independent of the
3
+ // wire's ready.protocolVersion (WPS-02). Delegates to runner.ts's SAME composition root
4
+ // (RUN-01..04 gates) rather than re-implementing parameter validation (BRB-01.3).
5
+ //
6
+ // CRITICAL (engram discovery obs #2205): this module runs IN THE ENGINE'S OWN PROCESS
7
+ // (embedded, not spawned) — it MUST NEVER call process.exit; only src/bin/pbuilder-runner.ts
8
+ // (the spawned argv entry) holds that privilege. Failure is communicated exclusively via a
9
+ // thrown error or a rejected Promise — the caller (the engine's own bootstrap, out of this
10
+ // repo's scope) decides what to do with that outcome, including whether/how to exit its own
11
+ // process. test/fixtures/bridge-bootstrap-stub.ts is a TEST-ONLY stand-in playing that role
12
+ // for the e2e suite (the real engine bootstrap lives in the engine repo).
13
+ //
14
+ // Derived mechanism (design.md gives prose only, no literal signature — S-003's own call):
15
+ // fd-1 capture + console redirect (BRB-02/03) are INJECTABLE (the `protection` parameter,
16
+ // defaulting to framing.ts's real mechanism) rather than raw top-level module code. Both
17
+ // mutate GLOBAL process state (the process's stdout stream, console.*); if they ran merely
18
+ // by IMPORTING
19
+ // this module, an integration test importing it inside bun test's SHARED process would
20
+ // corrupt every other test's console/stdout output. The default still satisfies "before any
21
+ // factory-related code runs": it fires at the very start of enterBridge, strictly before
22
+ // the ONLY path to a factory import (runRunner's dynamic import()). e2e tests exercise the
23
+ // REAL default in an isolated spawned child; integration tests inject a no-op stand-in
24
+ // (mirrors single-instance-probe.ts's injectable resolver).
25
+ import { runRunner } from "./runner.js";
26
+ import { captureFd1FrameWriter, redirectConsoleToStderr } from "./framing.js";
27
+ import { BRIDGE_CONTRACT_VERSION } from "./wire-protocol.js";
28
+ export class BridgeVersionMismatchError extends Error {
29
+ constructor(expected, actual) {
30
+ super(`bootstrap-bridge: contract version mismatch — bootstrap expects ${expected}, installed SDK bridge is ${actual}`);
31
+ this.name = "BridgeVersionMismatchError";
32
+ }
33
+ }
34
+ const realProtection = {
35
+ captureFrameWriter: captureFd1FrameWriter,
36
+ redirectConsole: redirectConsoleToStderr,
37
+ };
38
+ // REQ-BRB-01.3: converts the bridge's typed params into the SAME argv shape RUN-01's parser
39
+ // consumes — the gates below (runRunner -> parseArgv/validateFactoryUrl/...) are literally
40
+ // the argv-spawn code path, never re-implemented for the bridge.
41
+ function toArgv(params) {
42
+ const argv = ["--factory", params.factory];
43
+ if (params.input.kind === "inline")
44
+ argv.push("--input", params.input.json);
45
+ else
46
+ argv.push("--input-file", params.input.path);
47
+ return argv;
48
+ }
49
+ /**
50
+ * REQ-BRB-01: the engine's embedded bootstrap calls this ONCE, having already dynamic-
51
+ * imported this module, passing the bridge contract version IT expects and the
52
+ * argv-equivalent params (factory pointer, input/input-file). Rejects immediately — no
53
+ * protection armed, no factory-related code reached — on a version mismatch, naming both
54
+ * versions. On a match, arms the SAME fd-1/console protection RUN-08 gives the direct-spawn
55
+ * path (BRB-02/03), then hands the params to runner.ts's composition root through the SAME
56
+ * RUN-01..04 gates argv uses (BRB-01.3) — never a duplicated, weaker check.
57
+ */
58
+ export async function enterBridge(expectedVersion, params, io, protection = realProtection) {
59
+ if (expectedVersion !== BRIDGE_CONTRACT_VERSION) {
60
+ throw new BridgeVersionMismatchError(expectedVersion, BRIDGE_CONTRACT_VERSION);
61
+ }
62
+ protection.redirectConsole();
63
+ const writeFrame = protection.captureFrameWriter();
64
+ return runRunner(toArgv(params), { input: io.input, writeFrame, writeStderr: io.writeStderr });
65
+ }
@@ -0,0 +1,8 @@
1
+ export declare const MESSAGE_CEILING_CHARS = 2000;
2
+ export declare const TOKEN_CEILING_CHARS = 200;
3
+ export declare const OUTSIDE_PROJECT_TOKEN = "<outside-project>";
4
+ export declare function truncateToken(token: string): string;
5
+ export declare function boundMessage(message: string): string;
6
+ export declare function formatRelativeCandidate(candidate: string): string;
7
+ export declare function toProjectRelativePath(subjectPath: string, projectRoot?: string): string;
8
+ export declare function composeWithToken(prefix: string, token: string, suffix?: string): string;
@@ -0,0 +1,44 @@
1
+ // REQ-WPS-07: bounded, no-echo, project-relative error text. Any error text that crosses
2
+ // the wire or is written to stderr routes through here — bounded to a documented ceiling
3
+ // (never echoes raw host/engine internals verbatim: no stack frames, no absolute paths, no
4
+ // module source excerpts, no raw peer frame bytes), and every path is expressed
5
+ // project-relative, NEVER absolute (falling back to the `<outside-project>` placeholder
6
+ // when no relative form is meaningful, e.g. a different filesystem root).
7
+ import { isAbsolute, relative } from "node:path";
8
+ // SDK-chosen placeholders pending engine-side confirmation — same provenance posture as
9
+ // SEC-05's timeout bound and WPS-06's BATCH_CAP_BYTES.
10
+ export const MESSAGE_CEILING_CHARS = 2000;
11
+ export const TOKEN_CEILING_CHARS = 200;
12
+ export const OUTSIDE_PROJECT_TOKEN = "<outside-project>";
13
+ // REQ-WPS-07.3: an echoed host-controlled identifier (e.g. an unrecognized argv flag, a
14
+ // malformed export name) is truncated to this per-token max BEFORE composition — names
15
+ // surface, values never (bin/pbuilder-codegen.ts's describeSufficiencyFinding precedent).
16
+ export function truncateToken(token) {
17
+ return token.length > TOKEN_CEILING_CHARS ? token.slice(0, TOKEN_CEILING_CHARS) : token;
18
+ }
19
+ // REQ-WPS-07.1: the WHOLE message, including any embedded echoed token, is bounded to this
20
+ // ceiling.
21
+ export function boundMessage(message) {
22
+ return message.length > MESSAGE_CEILING_CHARS ? message.slice(0, MESSAGE_CEILING_CHARS) : message;
23
+ }
24
+ // REQ-WPS-07.2: applies the outside-project fallback rule to an already-computed relative
25
+ // path candidate. Split out from `toProjectRelativePath` so the fallback rule itself is
26
+ // directly testable without depending on this environment's actual filesystem layout (on
27
+ // POSIX, `path.relative` between two absolute paths can always express SOME `../`-relative
28
+ // form — there is no real "different filesystem root" case to construct here — but the
29
+ // substitution rule the fallback exists for is still a real, testable contract).
30
+ export function formatRelativeCandidate(candidate) {
31
+ return isAbsolute(candidate) ? OUTSIDE_PROJECT_TOKEN : candidate;
32
+ }
33
+ // REQ-WPS-07.2: expresses `subjectPath` relative to `projectRoot` (default: cwd) as a
34
+ // `../`-relative path, or the `<outside-project>` placeholder when no relative form can be
35
+ // constructed — NEVER the absolute path.
36
+ export function toProjectRelativePath(subjectPath, projectRoot = process.cwd()) {
37
+ return formatRelativeCandidate(relative(projectRoot, subjectPath));
38
+ }
39
+ // REQ-WPS-07.3: composes a prefix + a bounded echoed token + an optional suffix, then
40
+ // applies the whole-message ceiling — the echoed token never escapes its own cap even if
41
+ // the surrounding prefix/suffix is itself sizeable.
42
+ export function composeWithToken(prefix, token, suffix = "") {
43
+ return boundMessage(`${prefix}${truncateToken(token)}${suffix}`);
44
+ }
@@ -0,0 +1,2 @@
1
+ export type ExitCode = 0 | 1 | 2 | 3 | 4;
2
+ export declare function classifyExitCode(err: unknown): 1 | 2 | 3 | 4;
@@ -0,0 +1,35 @@
1
+ // REQ-EXC-01/EXC-02: classifies a run's terminal error into the runner's exit-code
2
+ // taxonomy. Mutually exclusive by construction (spec's own framing): `AuthoringError.origin`
3
+ // is a closed derived enum and `TransportFault` is a distinct class, so no precedence rule
4
+ // is needed between them.
5
+ //
6
+ // REQ-EXC-02: classification reads ONLY the error's own identity (instanceof checks) — it
7
+ // NEVER consults `.cause`. `context.ts`'s defineFactory already attaches a double-fault (E2,
8
+ // e.g. a failed discard()) as E1's `.cause` and re-throws E1 unchanged; because this
9
+ // classifier never looks past the error it is handed, E2 can never override E1's class —
10
+ // preservation falls out of the classifier's own narrowness, not a special case.
11
+ import { AuthoringError } from "../core/authoring-error.js";
12
+ import { TransportFault, IntentRejectedError } from "./stdio-engine-client.js";
13
+ // REQ-EXC-01 table: 1 validation-failure, 2 emit-rejection, 3 transport-fault,
14
+ // 4 crash (the fallback for anything unclassified, including a non-Error thrown value —
15
+ // never throws while classifying). IntentRejectedError is code 2 by the table's own text:
16
+ // "the host refused a write or an advisory commit/discard intent" — the host-refusal
17
+ // family, distinct from a wire-level fault (3) and from an unclassified crash (4).
18
+ export function classifyExitCode(err) {
19
+ if (err instanceof AuthoringError) {
20
+ return err.origin === "authoring-rejected" ? 1 : 2;
21
+ }
22
+ if (err instanceof IntentRejectedError) {
23
+ return 2;
24
+ }
25
+ if (err instanceof TransportFault) {
26
+ return 3;
27
+ }
28
+ // EXC-01 code-1 / BRB-01.2: a bridge contract version mismatch is a validation failure.
29
+ // NAME-based (not instanceof): importing bootstrap-bridge.ts here would close a cycle
30
+ // (bootstrap-bridge → runner → exit-codes), and the class already pins its own `name`.
31
+ if (err instanceof Error && err.name === "BridgeVersionMismatchError") {
32
+ return 1;
33
+ }
34
+ return 4;
35
+ }
@@ -0,0 +1,32 @@
1
+ export interface ParsedFactoryPointer {
2
+ url: string;
3
+ exportName: string | undefined;
4
+ }
5
+ export declare function parseFactoryPointer(pointer: string): ParsedFactoryPointer;
6
+ export type FactoryUrlValidation = {
7
+ ok: true;
8
+ } | {
9
+ ok: false;
10
+ message: string;
11
+ };
12
+ export declare function validateFactoryUrl(url: string): FactoryUrlValidation;
13
+ export type BareFactoryFn = (o: unknown) => void | Promise<void>;
14
+ export type FactoryExportResolution = {
15
+ ok: true;
16
+ fn: BareFactoryFn;
17
+ } | {
18
+ ok: false;
19
+ kind: "missing-default-export";
20
+ } | {
21
+ ok: false;
22
+ kind: "missing-named-export";
23
+ exportName: string;
24
+ } | {
25
+ ok: false;
26
+ kind: "not-callable";
27
+ exportName: string | undefined;
28
+ } | {
29
+ ok: false;
30
+ kind: "double-wrapped";
31
+ };
32
+ export declare function resolveFactoryExport(moduleNamespace: Record<string, unknown>, exportName: string | undefined): FactoryExportResolution;