@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,63 @@
1
+ // REQ-WPS-08: the factory pointer grammar `<url>#<export>` — `<url>` is validated per
2
+ // RUN-02, `<export>` is an optional fragment naming a non-default export (absent fragment
3
+ // == default export). S-001 owns the pure grammar parse below; RUN-02's `file:`+
4
+ // empty-host allowlist, RUN-03's 3-form export resolution, and RUN-06's double-wrap check
5
+ // are S-002 additions to this same file. RUN-07's import-failure split lives in runner.ts
6
+ // (it classifies the dynamic `import()` call itself, which this file never performs).
7
+ import { isDefineFactoryWrapped } from "../core/context.js";
8
+ // Splits on the FIRST '#' only — a url containing a later literal '#' (e.g. percent-encoded
9
+ // as %23 in practice, but defensively handled here regardless) is never mis-split.
10
+ export function parseFactoryPointer(pointer) {
11
+ const hashIndex = pointer.indexOf("#");
12
+ if (hashIndex === -1) {
13
+ return { url: pointer, exportName: undefined };
14
+ }
15
+ const url = pointer.slice(0, hashIndex);
16
+ const fragment = pointer.slice(hashIndex + 1);
17
+ return { url, exportName: fragment.length > 0 ? fragment : undefined };
18
+ }
19
+ // REQ-RUN-02: the factory pointer's URL scheme MUST be exactly `file:` AND its host
20
+ // component MUST be empty — checked BEFORE any dynamic import, since the factory's
21
+ // top-level code runs at import (input validation after import is not a containment
22
+ // control).
23
+ export function validateFactoryUrl(url) {
24
+ let parsed;
25
+ try {
26
+ parsed = new URL(url);
27
+ }
28
+ catch {
29
+ return { ok: false, message: `factory pointer is not a valid URL: "${url}"` };
30
+ }
31
+ if (parsed.protocol !== "file:") {
32
+ return { ok: false, message: `factory pointer must use the file: scheme, got "${parsed.protocol}"` };
33
+ }
34
+ if (parsed.hostname !== "") {
35
+ return {
36
+ ok: false,
37
+ message: `factory pointer's file: URL must have an empty host, got "${parsed.hostname}"`,
38
+ };
39
+ }
40
+ return { ok: true };
41
+ }
42
+ // REQ-RUN-03 (3-form export resolution) + REQ-RUN-06 (double-wrap detection): resolves
43
+ // `exportName` (undefined == default export) against `moduleNamespace`, classifying
44
+ // failure into exactly four distinct, actionable forms. The double-wrap check (ADR-04's
45
+ // brand marker) runs only once a callable value is found — it is arity-independent
46
+ // (RUN-06.2: an author's bare arity-2 factory is an ordinary bare factory, never
47
+ // misclassified), so "not callable" and "double-wrapped" are checked in sequence, never
48
+ // confused with each other.
49
+ export function resolveFactoryExport(moduleNamespace, exportName) {
50
+ const resolved = exportName === undefined ? moduleNamespace.default : moduleNamespace[exportName];
51
+ if (resolved === undefined) {
52
+ return exportName === undefined
53
+ ? { ok: false, kind: "missing-default-export" }
54
+ : { ok: false, kind: "missing-named-export", exportName };
55
+ }
56
+ if (typeof resolved !== "function") {
57
+ return { ok: false, kind: "not-callable", exportName };
58
+ }
59
+ if (isDefineFactoryWrapped(resolved)) {
60
+ return { ok: false, kind: "double-wrapped" };
61
+ }
62
+ return { ok: true, fn: resolved };
63
+ }
@@ -0,0 +1,10 @@
1
+ import { TransportFault } from "./stdio-engine-client.ts";
2
+ export declare class FrameFault {
3
+ readonly fault: TransportFault;
4
+ constructor(fault: TransportFault);
5
+ }
6
+ export declare class FrameReader {
7
+ #private;
8
+ constructor(source: AsyncIterable<Uint8Array>);
9
+ frames(): AsyncGenerator<unknown>;
10
+ }
@@ -0,0 +1,81 @@
1
+ // src/transport/frame-reader.ts — streaming reassembler over raw chunks (e.g. stdin) into
2
+ // logical frames. Owns chunk-boundary handling (split/coalesced/EOF-mid-frame, SEC-10);
3
+ // never byte-scans for a delimiter — length-prefixed only. Delegates body decoding AND the
4
+ // inbound reject-before-alloc cap check to framing.ts (single owner of the codec, fit-31 /
5
+ // fit-32). REQ-SEC-08.1/.2 (malformed JSON, desync): both collapse to the SAME `kind:
6
+ // "malformed"` classification in this implementation — mechanically, an undercounted length
7
+ // prefix (desync) manifests identically to deliberately-corrupt JSON once the misaligned
8
+ // byte range reaches decodeFrameBody (a JSON.parse failure); there is no reliable signal at
9
+ // this layer to distinguish "corrupt on purpose" from "corrupt because the frame boundary
10
+ // drifted" without risking false positives against REQ-WPS-03's silent-discard territory
11
+ // (a structurally-odd-but-valid-JSON object, e.g. `{type:"notification"}`, is WPS-03's job,
12
+ // never a frame-reader fail-closed fault).
13
+ import { decodeFrameBody, isOversizeDeclaredLength, LENGTH_PREFIX_BYTES } from "./framing.js";
14
+ import { TransportFault } from "./stdio-engine-client.js";
15
+ // REQ-SEC-08.1: the per-frame fault marker. A malformed BODY is fully consumed by the time
16
+ // decoding fails (its boundary was known from the length prefix), so failing the ONE pending
17
+ // call is enough — the stream itself is still aligned. The generator YIELDS this marker
18
+ // instead of throwing, because a generator throw completes it permanently and would tear the
19
+ // connection down, contradicting SEC-08.1's "remains usable for subsequent calls". Consumers
20
+ // (runner.ts's FrameChannel, test/support/frame-host.ts) convert it to a rejection of the
21
+ // pending read. `oversize` and `eof` stay THROWN (fatal, fail-closed): after either, the
22
+ // stream position is not trustworthy or the stream is gone.
23
+ export class FrameFault {
24
+ fault;
25
+ constructor(fault) {
26
+ this.fault = fault;
27
+ }
28
+ }
29
+ export class FrameReader {
30
+ #buffer = Buffer.alloc(0);
31
+ #source;
32
+ constructor(source) {
33
+ this.#source = source;
34
+ }
35
+ async *frames() {
36
+ for await (const chunk of this.#source) {
37
+ this.#buffer = Buffer.concat([this.#buffer, chunk]);
38
+ for (const frame of this.#drainCompleteFrames()) {
39
+ yield frame;
40
+ }
41
+ }
42
+ // REQ-SEC-10.5: the stream ended (EOF) with an incomplete frame still buffered
43
+ // (partial prefix or partial body) — fail closed, the partial is NEVER dispatched.
44
+ // A clean EOF with nothing buffered is a normal, expected closure — not a fault.
45
+ if (this.#buffer.length > 0) {
46
+ throw new TransportFault("eof", `stream ended with ${this.#buffer.length} buffered byte(s) short of a complete frame`);
47
+ }
48
+ }
49
+ *#drainCompleteFrames() {
50
+ for (;;) {
51
+ if (this.#buffer.length < LENGTH_PREFIX_BYTES)
52
+ return;
53
+ const bodyLength = this.#buffer.readUInt32BE(0);
54
+ // REQ-WPS-04.2/.4: reject-before-alloc — classified BEFORE waiting for/allocating a
55
+ // buffer for the declared body, using the raw declared length alone (unsigned read,
56
+ // never misread as negative/small — WPS-04.4).
57
+ if (isOversizeDeclaredLength(bodyLength)) {
58
+ throw new TransportFault("oversize", `inbound frame declares ${bodyLength} bytes, exceeding the reject-before-alloc cap`);
59
+ }
60
+ const frameLength = LENGTH_PREFIX_BYTES + bodyLength;
61
+ if (this.#buffer.length < frameLength)
62
+ return;
63
+ const body = this.#buffer.subarray(LENGTH_PREFIX_BYTES, frameLength);
64
+ this.#buffer = this.#buffer.subarray(frameLength);
65
+ let decoded;
66
+ try {
67
+ decoded = decodeFrameBody(body);
68
+ }
69
+ catch {
70
+ // REQ-SEC-08.1/.2: fails the pending call closed, attributed structurally by the
71
+ // caller (SEC-02 single-in-flight) — never resynchronized by byte-scanning
72
+ // (SEC-08.2). Yielded as a FrameFault marker, NOT thrown: the malformed body was
73
+ // fully consumed at a boundary the prefix declared, so the stream stays aligned and
74
+ // the connection remains usable for subsequent calls (SEC-08.1).
75
+ yield new FrameFault(new TransportFault("malformed", "inbound frame body failed to parse as JSON"));
76
+ continue;
77
+ }
78
+ yield decoded;
79
+ }
80
+ }
81
+ }
@@ -0,0 +1,20 @@
1
+ export declare const LENGTH_PREFIX_BYTES = 4;
2
+ export declare function withPreserializedBody<T extends object>(value: T, body: Buffer): T;
3
+ export declare function encodeFrameBody(value: unknown): Buffer;
4
+ export declare function encodeFrame(value: unknown): Buffer;
5
+ export declare function decodeFrameBody(body: Uint8Array): unknown;
6
+ export declare function isOversizeDeclaredLength(bodyLength: number): boolean;
7
+ export declare function captureFd1FrameWriter(): (value: unknown) => void;
8
+ /**
9
+ * REQ-BRB-03/RUN-08/REQ-SEC-09.1: redirects the ENTIRE console surface to stderr — belt-and-
10
+ * suspenders alongside the engine's own dup (A2), and the SAME guarantee on both entry
11
+ * paths (the direct-spawn bin and the in-process bridge both call this). A single owner,
12
+ * mirrored by `captureFd1FrameWriter`'s single ownership of the fd-1 side.
13
+ *
14
+ * Judgment-day F2: a per-method override of log/info/warn/error/debug is NOT enough — in
15
+ * Bun, `console.table/dir/group/count/trace` (and friends) write NATIVELY to fd 1, bypassing
16
+ * both such overrides and the `process.stdout` stub (verified empirically). Replacing the
17
+ * global console with a `node:console` Console bound to stderr on BOTH streams reroutes
18
+ * every method at once, with no per-method list to drift as the console API grows.
19
+ */
20
+ export declare function redirectConsoleToStderr(): void;
@@ -0,0 +1,98 @@
1
+ // REQ-WPS-01: single owner of frame encode/decode — 4-byte big-endian length prefix +
2
+ // UTF-8 JSON body, symmetric in both directions (host<->runner). fit-31 (single-owner-of-
3
+ // framing) guards that no other module re-implements this codec.
4
+ import { Console } from "node:console";
5
+ import { exceedsBatchCap } from "../core/wire.js";
6
+ export const LENGTH_PREFIX_BYTES = 4;
7
+ // REQ-WPS-04.1 (owner ruling R2): the outbound cap is enforced on the ENCODED FRAME BODY, so
8
+ // the emitting client must serialize the frame value BEFORE the writer does. To keep that a
9
+ // single serialization (a Batch can be 4 MiB), the client attaches its already-encoded body
10
+ // to the frame value under this module-private symbol; `encodeFrame` below reuses those
11
+ // exact bytes. Non-enumerable + symbol-keyed: invisible to JSON, to structural inspection,
12
+ // and to every existing FrameChannel double.
13
+ const PRESERIALIZED_BODY = Symbol("pbuilder.preserializedFrameBody");
14
+ export function withPreserializedBody(value, body) {
15
+ Object.defineProperty(value, PRESERIALIZED_BODY, { value: body });
16
+ return value;
17
+ }
18
+ function preserializedBody(value) {
19
+ if (typeof value !== "object" || value === null)
20
+ return undefined;
21
+ const body = value[PRESERIALIZED_BODY];
22
+ return Buffer.isBuffer(body) ? body : undefined;
23
+ }
24
+ // The body half of the codec (fit-31 single-owner-of-framing: serialization lives HERE, the
25
+ // emitting client calls this instead of re-implementing it). UTF-8 SERIALIZED byte length —
26
+ // never the JS string's UTF-16 .length — so multi-byte payloads (WPS-01.3) round-trip exactly.
27
+ export function encodeFrameBody(value) {
28
+ return preserializedBody(value) ?? Buffer.from(JSON.stringify(value), "utf8");
29
+ }
30
+ export function encodeFrame(value) {
31
+ const body = encodeFrameBody(value);
32
+ const frame = Buffer.alloc(LENGTH_PREFIX_BYTES + body.length);
33
+ frame.writeUInt32BE(body.length, 0);
34
+ body.copy(frame, LENGTH_PREFIX_BYTES);
35
+ return frame;
36
+ }
37
+ export function decodeFrameBody(body) {
38
+ return JSON.parse(Buffer.from(body).toString("utf8"));
39
+ }
40
+ // REQ-WPS-04: reject-before-alloc on the INBOUND leg — checks the raw declared length
41
+ // prefix BEFORE the reader waits for/allocates a buffer for that many body bytes. A thin,
42
+ // semantically-named wrapper: the sole `>` comparison lives in wire.ts's `exceedsBatchCap`
43
+ // (fit-32 cap-single-source), never re-derived here.
44
+ export function isOversizeDeclaredLength(bodyLength) {
45
+ return exceedsBatchCap(bodyLength);
46
+ }
47
+ /**
48
+ * The ONE sanctioned stdout reference in `src/transport/**` (fit-30 stdout-protocol-sacred):
49
+ * captures the process's fd-1 write handle AT CALL TIME — call it before any factory import
50
+ * — so later author-code reassignment of `process.stdout` cannot hijack the wire (the
51
+ * BRB-02/RUN-08 defence, e2e-proven in S-003).
52
+ *
53
+ * REQ-SEC-09: capturing a reference alone is not enough — an author calling that stream's
54
+ * own `.write(...)` DIRECTLY (no reassignment) would still reach the real fd, since it's
55
+ * the SAME underlying object. So immediately after capturing the real write function,
56
+ * `process.stdout` itself is replaced with a stub whose `.write` redirects to
57
+ * stderr. Only the writer closure returned below (closed over the reference captured BEFORE
58
+ * the replacement) still reaches the real fd; any later author access to `process.stdout` —
59
+ * a direct `.write()` call, or a full reassignment/monkey-patch (BRB-02.1) — lands on the
60
+ * stub, never the wire.
61
+ */
62
+ // Judgment-day F10: the real fd-1 write handle, cached at module scope by the FIRST capture.
63
+ // A second capture (a second sequential enterBridge run in one engine process) must reuse it
64
+ // — re-capturing would bind the first capture's own stderr-redirecting stub as "fd 1" and
65
+ // silently send the whole second run's frames to stderr.
66
+ let realFd1Write;
67
+ export function captureFd1FrameWriter() {
68
+ if (realFd1Write === undefined) {
69
+ realFd1Write = process.stdout.write.bind(process.stdout);
70
+ const stub = {
71
+ write: (chunk) => {
72
+ process.stderr.write(typeof chunk === "string" || Buffer.isBuffer(chunk) ? chunk : String(chunk));
73
+ return true;
74
+ },
75
+ };
76
+ Object.defineProperty(process, "stdout", { value: stub, writable: true, configurable: true });
77
+ }
78
+ const write = realFd1Write;
79
+ return (value) => {
80
+ write(encodeFrame(value));
81
+ };
82
+ }
83
+ /**
84
+ * REQ-BRB-03/RUN-08/REQ-SEC-09.1: redirects the ENTIRE console surface to stderr — belt-and-
85
+ * suspenders alongside the engine's own dup (A2), and the SAME guarantee on both entry
86
+ * paths (the direct-spawn bin and the in-process bridge both call this). A single owner,
87
+ * mirrored by `captureFd1FrameWriter`'s single ownership of the fd-1 side.
88
+ *
89
+ * Judgment-day F2: a per-method override of log/info/warn/error/debug is NOT enough — in
90
+ * Bun, `console.table/dir/group/count/trace` (and friends) write NATIVELY to fd 1, bypassing
91
+ * both such overrides and the `process.stdout` stub (verified empirically). Replacing the
92
+ * global console with a `node:console` Console bound to stderr on BOTH streams reroutes
93
+ * every method at once, with no per-method list to drift as the console API grows.
94
+ */
95
+ export function redirectConsoleToStderr() {
96
+ const stderrConsole = new Console({ stdout: process.stderr, stderr: process.stderr });
97
+ Object.defineProperty(globalThis, "console", { value: stderrConsole, writable: true, configurable: true });
98
+ }
@@ -0,0 +1,25 @@
1
+ export interface RunnerIo {
2
+ /** Raw inbound byte stream (stdin on the spawned path; injectable for in-process tests). */
3
+ input: AsyncIterable<Uint8Array>;
4
+ /** Writes one outbound frame VALUE; encoding is the caller's captured-fd-1 writer (framing.ts). */
5
+ writeFrame: (value: unknown) => void;
6
+ /** Bounded operator-visible notes (stderr on the spawned path). Never the wire. */
7
+ writeStderr: (text: string) => void;
8
+ }
9
+ export declare const INPUT_FILE_SIZE_CAP_BYTES: number;
10
+ /**
11
+ * Runs one factory over the framed wire: parses/validates argv and input (RUN-01/04),
12
+ * awaits versioned `ready` (WPS-02, fail-at-greeting), probes the single-instance SDK
13
+ * pin (SEC-07), validates + resolves the factory pointer (RUN-02/03/06/07), then
14
+ * `defineFactory`-wraps it with `packageDir = dirname(factory)` (RUN-05) and serves the
15
+ * run's reverse callbacks through `StdioEngineClient`. Returns the process exit code
16
+ * (EXC-01 taxonomy).
17
+ *
18
+ * REQ-SEC-02: a second invocation while one is already in flight in this process REJECTS
19
+ * immediately (never resolves to an exit code — overlap is NOT part of the EXC-01 taxonomy,
20
+ * it never reaches the wire) with a stable `OverlappingRunError` identity, touching NEITHER
21
+ * `io.writeFrame` NOR `io.writeStderr` — there is nothing to send over the wire for an
22
+ * attempt that never left the process, and the first in-flight run's own io/state is
23
+ * entirely untouched by the rejected attempt.
24
+ */
25
+ export declare function runRunner(argv: string[], io: RunnerIo): Promise<number>;
@@ -0,0 +1,308 @@
1
+ // The runner composition root (design § 4.2, ADR-01): lives in src/transport/ — NOT bin/ —
2
+ // so BOTH entry paths (argv spawn via src/bin/pbuilder-runner.ts, in-process bridge in S-003)
3
+ // share this ONE validation-gate chokepoint (FIT-15 bars src/->bin/ imports).
4
+ //
5
+ // ADR-07: this file is the sanctioned production `defineFactory` caller — fit-29's
6
+ // allow-list names exactly this FILE. `context.ts`'s @internal note names "the future
7
+ // production runner" as the legitimate wrapper of that seam; this is that runner. The
8
+ // import is direct from ../core/context.ts (the sanctioned-caller idiom), never the barrel.
9
+ //
10
+ // S-002 closes the gate scope: RUN-01 (argv XOR), RUN-02 (factory URL scheme+host, via
11
+ // factory-pointer.ts), RUN-03/RUN-06 (export resolution + double-wrap, factory-pointer.ts),
12
+ // RUN-04 (input-file size-cap + fail-closed parse), RUN-07 (import-failure classification),
13
+ // SEC-07 (single-instance probe, before import), and EXC-01/02 (exit-code taxonomy via
14
+ // exit-codes.ts). RUN-05/RUN-08/SEC-02 are S-000/S-003 territory, unchanged here.
15
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
16
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
17
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
18
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
19
+ });
20
+ }
21
+ return path;
22
+ };
23
+ import { dirname } from "node:path";
24
+ import { fileURLToPath } from "node:url";
25
+ import { readFileSync, statSync } from "node:fs";
26
+ import { defineFactory } from "../core/context.js";
27
+ import { AuthoringError } from "../core/authoring-error.js";
28
+ import { locateFirstJsonSyntaxError } from "../core/schema/schema-locate.js";
29
+ import { formatLocator } from "../core/schema/schema-parse.js";
30
+ import { FrameReader, FrameFault } from "./frame-reader.js";
31
+ import { WIRE_PROTOCOL_VERSION, isStructurallyValidGreeting, versionMatches } from "./wire-protocol.js";
32
+ import { StdioEngineClient, TransportFault, IntentRejectedError, OverlappingRunError, } from "./stdio-engine-client.js";
33
+ import { boundMessage, composeWithToken, toProjectRelativePath } from "./error-text.js";
34
+ import { parseFactoryPointer, validateFactoryUrl, resolveFactoryExport } from "./factory-pointer.js";
35
+ import { probeSingleInstance } from "./single-instance-probe.js";
36
+ import { classifyExitCode } from "./exit-codes.js";
37
+ // REQ-RUN-04: the SDK-chosen input-file size cap — same provenance posture as SEC-05's
38
+ // timeout bound and WPS-06's BATCH_CAP_BYTES (pending engine-side confirmation).
39
+ export const INPUT_FILE_SIZE_CAP_BYTES = 10 * 1024 * 1024; // 10 MiB
40
+ function note(io, text) {
41
+ io.writeStderr(`${boundMessage(text)}\n`);
42
+ }
43
+ // REQ-RUN-01: `--factory <url>#<export>` required; exactly one of `--input <json>` XOR
44
+ // `--input-file <path>`; any unrecognized flag fails closed.
45
+ function parseArgv(argv) {
46
+ let factory;
47
+ let inputJson;
48
+ let inputFile;
49
+ for (let i = 0; i < argv.length; i += 2) {
50
+ const flag = argv[i];
51
+ const value = argv[i + 1];
52
+ if (flag === undefined || value === undefined) {
53
+ return { error: `pbuilder-runner: missing value for flag "${flag ?? ""}"` };
54
+ }
55
+ if (flag === "--factory")
56
+ factory = value;
57
+ else if (flag === "--input")
58
+ inputJson = value;
59
+ else if (flag === "--input-file")
60
+ inputFile = value;
61
+ else
62
+ return { error: composeWithToken("pbuilder-runner: unrecognized flag ", flag) };
63
+ }
64
+ if (factory === undefined)
65
+ return { error: "pbuilder-runner: --factory is required" };
66
+ if (inputJson !== undefined && inputFile !== undefined) {
67
+ return { error: "pbuilder-runner: --input and --input-file are mutually exclusive — pass exactly one" };
68
+ }
69
+ if (inputJson === undefined && inputFile === undefined) {
70
+ return { error: "pbuilder-runner: exactly one of --input or --input-file is required" };
71
+ }
72
+ return {
73
+ factory,
74
+ input: inputJson !== undefined ? { kind: "inline", json: inputJson } : { kind: "file", path: inputFile },
75
+ };
76
+ }
77
+ // REQ-RUN-04: size-cap check BEFORE reading contents; fail-closed on any JSON parse error,
78
+ // reporting ONLY the parse failure's line/column (never raw file content — mirrors
79
+ // `formatParseError`, bin/pbuilder-codegen.ts:126).
80
+ function resolveInput(input) {
81
+ if (input.kind === "inline") {
82
+ try {
83
+ return { ok: true, value: JSON.parse(input.json) };
84
+ }
85
+ catch {
86
+ return { ok: false, message: "pbuilder-runner: --input is not valid JSON" };
87
+ }
88
+ }
89
+ // REQ-WPS-07 (judgment-day F9): fixed text + a project-relative path — NEVER the raw OS
90
+ // error message, which embeds the absolute path (`ENOENT: ..., stat '/abs/path'`).
91
+ const unreadable = () => ({
92
+ ok: false,
93
+ message: `pbuilder-runner: --input-file could not be read — ${toProjectRelativePath(input.path)} is not a readable file`,
94
+ });
95
+ let size;
96
+ try {
97
+ size = statSync(input.path).size;
98
+ }
99
+ catch {
100
+ return unreadable();
101
+ }
102
+ if (size > INPUT_FILE_SIZE_CAP_BYTES) {
103
+ return { ok: false, message: `pbuilder-runner: --input-file exceeds the ${INPUT_FILE_SIZE_CAP_BYTES}-byte cap` };
104
+ }
105
+ // Same fail-closed shape for the read itself (judgment-day F4): a stat that succeeded does
106
+ // not guarantee a readable file (permissions, TOCTOU) — a throw here must never escape as
107
+ // an uncaught rejection.
108
+ let raw;
109
+ try {
110
+ raw = readFileSync(input.path, "utf-8");
111
+ }
112
+ catch {
113
+ return unreadable();
114
+ }
115
+ try {
116
+ return { ok: true, value: JSON.parse(raw) };
117
+ }
118
+ catch {
119
+ const locator = locateFirstJsonSyntaxError(raw);
120
+ return {
121
+ ok: false,
122
+ message: `pbuilder-runner: --input-file is not valid JSON ${formatLocator(locator?.line, locator?.column)}`,
123
+ };
124
+ }
125
+ }
126
+ // REQ-RUN-07: classifies a factory-module `import()` failure into RUN-07's form 1 — the
127
+ // module "cannot be found or loaded" (exits 1) — vs. an author top-level throw (exits 4).
128
+ // Form 1 covers BOTH resolution failures (`ERR_MODULE_NOT_FOUND`, Bun's `ResolveMessage`)
129
+ // AND load-time parse/build failures (judgment-day F13): a syntactically invalid module
130
+ // never RAN, so "its top-level code threw" would be factually false. Verified empirically
131
+ // in this Bun version: a syntax-error import rejects with an `AggregateError` whose
132
+ // `errors` are `BuildMessage`s (or a single bare `BuildMessage`); neither `BuildMessage`
133
+ // nor `ResolveMessage` is an `Error` instance, so the checks read `name`/`code` directly
134
+ // off any object shape (never `instanceof`-gated). `SyntaxError` covers Node's shape for
135
+ // the same failure. An author-thrown AggregateError of plain Errors matches none of these
136
+ // and still classifies as a top-level throw (exit 4).
137
+ function isModuleLoadFailure(err) {
138
+ if (typeof err !== "object" || err === null)
139
+ return false;
140
+ const candidate = err;
141
+ if (candidate.code === "ERR_MODULE_NOT_FOUND")
142
+ return true;
143
+ if (candidate.name === "ResolveMessage" || candidate.name === "BuildMessage")
144
+ return true;
145
+ if (err instanceof SyntaxError)
146
+ return true;
147
+ if (Array.isArray(candidate.errors)) {
148
+ return candidate.errors.some((inner) => isModuleLoadFailure(inner));
149
+ }
150
+ return false;
151
+ }
152
+ // REQ-SEC-02: the composition root's own reentrancy guard. A single spawned process (the
153
+ // direct-argv path) only ever calls runRunner once by construction; the bridge is the
154
+ // realistic reentrant caller (a single long-lived engine process CAN dynamic-import and
155
+ // invoke the bridge more than once). module-level, not per-instance: "each process runs
156
+ // exactly one factory" (WPS-09) — the guard's scope is the PROCESS, matching that.
157
+ let runInFlight = false;
158
+ /**
159
+ * Runs one factory over the framed wire: parses/validates argv and input (RUN-01/04),
160
+ * awaits versioned `ready` (WPS-02, fail-at-greeting), probes the single-instance SDK
161
+ * pin (SEC-07), validates + resolves the factory pointer (RUN-02/03/06/07), then
162
+ * `defineFactory`-wraps it with `packageDir = dirname(factory)` (RUN-05) and serves the
163
+ * run's reverse callbacks through `StdioEngineClient`. Returns the process exit code
164
+ * (EXC-01 taxonomy).
165
+ *
166
+ * REQ-SEC-02: a second invocation while one is already in flight in this process REJECTS
167
+ * immediately (never resolves to an exit code — overlap is NOT part of the EXC-01 taxonomy,
168
+ * it never reaches the wire) with a stable `OverlappingRunError` identity, touching NEITHER
169
+ * `io.writeFrame` NOR `io.writeStderr` — there is nothing to send over the wire for an
170
+ * attempt that never left the process, and the first in-flight run's own io/state is
171
+ * entirely untouched by the rejected attempt.
172
+ */
173
+ export async function runRunner(argv, io) {
174
+ if (runInFlight) {
175
+ throw new OverlappingRunError("pbuilder-runner: a run is already in flight in this process — overlapping run rejected");
176
+ }
177
+ runInFlight = true;
178
+ try {
179
+ return await runRunnerBody(argv, io);
180
+ }
181
+ finally {
182
+ runInFlight = false;
183
+ }
184
+ }
185
+ async function runRunnerBody(argv, io) {
186
+ const parsed = parseArgv(argv);
187
+ if ("error" in parsed) {
188
+ note(io, parsed.error);
189
+ return 1;
190
+ }
191
+ const resolvedInput = resolveInput(parsed.input);
192
+ if (!resolvedInput.ok) {
193
+ note(io, resolvedInput.message);
194
+ return 1;
195
+ }
196
+ const { url: moduleUrl, exportName } = parseFactoryPointer(parsed.factory);
197
+ const urlValidation = validateFactoryUrl(moduleUrl);
198
+ if (!urlValidation.ok) {
199
+ note(io, `pbuilder-runner: ${urlValidation.message}`);
200
+ return 1;
201
+ }
202
+ const reader = new FrameReader(io.input);
203
+ const frames = reader.frames();
204
+ // WPS-02: fail at greeting, BEFORE any reverse callback can dispatch — the client is not
205
+ // even constructed until the greeting is accepted. A TRANSPORT fault at greeting time
206
+ // (judgment-day F4) — an oversize/0x80000000 length prefix (thrown, WPS-04.2/.4), EOF
207
+ // mid-frame (thrown), or a malformed greeting body (yielded as a FrameFault) — classifies
208
+ // exit 3 with a bounded note (EXC-01, WPS-07), never an uncaught rejection's raw stack.
209
+ // A clean EOF or a structurally-wrong-but-valid frame stays exit 1 (WPS-02.3).
210
+ let first;
211
+ try {
212
+ first = await frames.next();
213
+ }
214
+ catch (err) {
215
+ note(io, `pbuilder-runner: ${err instanceof TransportFault ? err.message : "transport fault while awaiting the greeting"}`);
216
+ return classifyExitCode(err);
217
+ }
218
+ if (!first.done && first.value instanceof FrameFault) {
219
+ note(io, `pbuilder-runner: ${first.value.fault.message}`);
220
+ return classifyExitCode(first.value.fault);
221
+ }
222
+ if (first.done || !isStructurallyValidGreeting(first.value)) {
223
+ note(io, `pbuilder-runner: invalid greeting — expected {method:"ready", protocolVersion:<integer>}`);
224
+ return 1;
225
+ }
226
+ if (!versionMatches(first.value)) {
227
+ note(io, `pbuilder-runner: wire protocol version mismatch — host sent ${first.value.protocolVersion}, ` +
228
+ `runner expects ${WIRE_PROTOCOL_VERSION}`);
229
+ return 1;
230
+ }
231
+ // REQ-SEC-07: handshake-time, resolution-only, BEFORE the factory import proceeds.
232
+ const probe = probeSingleInstance(moduleUrl);
233
+ if (!probe.ok) {
234
+ note(io, `pbuilder-runner: ${probe.message}`);
235
+ return 1;
236
+ }
237
+ let moduleNamespace;
238
+ try {
239
+ // SANCTIONED-FACTORY-IMPORT — the ONE dynamic import() Constraint 2 permits in the runner
240
+ // closure, and the deliberate author-code boundary. The sanction is per-SITE, not
241
+ // per-file: a second import() anywhere, including in this file, fails the build (fit-42).
242
+ moduleNamespace = (await import(__rewriteRelativeImportExtension(moduleUrl)));
243
+ }
244
+ catch (err) {
245
+ if (isModuleLoadFailure(err)) {
246
+ note(io, "pbuilder-runner: factory module could not be resolved or loaded");
247
+ return 1;
248
+ }
249
+ note(io, "pbuilder-runner: factory module's top-level code threw during import");
250
+ return 4;
251
+ }
252
+ const exportResolution = resolveFactoryExport(moduleNamespace, exportName);
253
+ if (!exportResolution.ok) {
254
+ switch (exportResolution.kind) {
255
+ case "missing-default-export":
256
+ note(io, "pbuilder-runner: factory module has no default export");
257
+ return 1;
258
+ case "missing-named-export":
259
+ note(io, composeWithToken("pbuilder-runner: factory module has no export named ", exportResolution.exportName));
260
+ return 1;
261
+ case "not-callable":
262
+ note(io, composeWithToken("pbuilder-runner: resolved factory export is not a function — malformed factory export: ", exportResolution.exportName ?? "default"));
263
+ return 1;
264
+ case "double-wrapped":
265
+ note(io, "pbuilder-runner: resolved factory export is already wrapped by defineFactory — export the BARE " +
266
+ "factory function instead, the runner wraps it internally");
267
+ return 1;
268
+ }
269
+ }
270
+ // RUN-05: wrap through the SAME defineFactory seam runFactoryForTest uses, anchored to
271
+ // the factory's own directory — schema-derived validation and reserved-name checks apply
272
+ // identically on both vehicles.
273
+ const packageDir = dirname(fileURLToPath(new URL(moduleUrl)));
274
+ const run = defineFactory(exportResolution.fn, { packageDir });
275
+ const channel = {
276
+ write: io.writeFrame,
277
+ writeStderr: io.writeStderr,
278
+ async read() {
279
+ const next = await frames.next();
280
+ // REQ-SEC-08.3: a clean EOF (frames() completes with nothing buffered) while a
281
+ // reverse callback is pending is itself a fault — the reader only ever gets asked
282
+ // to read again when a callback IS pending (StdioEngineClient's routing loop).
283
+ if (next.done)
284
+ throw new TransportFault("eof", "wire closed while a response was pending");
285
+ // REQ-SEC-08.1: a malformed frame body rejects THIS read (the sole pending call,
286
+ // attributed structurally) — the reader itself stays alive for subsequent calls.
287
+ if (next.value instanceof FrameFault)
288
+ throw next.value.fault;
289
+ return next.value;
290
+ },
291
+ };
292
+ const client = new StdioEngineClient(channel);
293
+ try {
294
+ await run(resolvedInput.value, { client });
295
+ return 0;
296
+ }
297
+ catch (err) {
298
+ // EXC-01/02: classification reads ONLY err's own identity — a double-fault `.cause`
299
+ // (context.ts's discard-after-throw path) never overrides E1's class. IntentRejectedError
300
+ // (judgment-day F3): the host's refusal message surfaces — bounded by note() — instead
301
+ // of being swallowed into a generic "run failed".
302
+ const label = err instanceof AuthoringError || err instanceof TransportFault || err instanceof IntentRejectedError
303
+ ? err.message
304
+ : "run failed";
305
+ note(io, `pbuilder-runner: ${label}`);
306
+ return classifyExitCode(err);
307
+ }
308
+ }
@@ -0,0 +1,23 @@
1
+ export type SingleInstanceProbeResult = {
2
+ ok: true;
3
+ } | {
4
+ ok: false;
5
+ message: string;
6
+ };
7
+ /**
8
+ * REQ-SEC-07: probes whether `factoryUrl`'s module graph would resolve the SAME
9
+ * `@pbuilder/sdk` copy the runner itself is. MUST be called BEFORE the factory's dynamic
10
+ * import (RUN-02/RUN-03) proceeds — resolution-only, never executes any of the factory's
11
+ * or the resolved package's top-level code. A resolution failure (the factory's location
12
+ * has no resolvable `@pbuilder/sdk` at all) fails closed the same way a split does — never
13
+ * throws, never guesses a match.
14
+ *
15
+ * `resolveSpecifier` is injectable (mirrors this codebase's `FrameChannel`/`RunnerIo`
16
+ * pattern) — production always uses the default (real `createRequire` resolution); tests
17
+ * override it ONLY where real package resolution has an orthogonal fixture-construction
18
+ * problem (this repo's own `package.json` has no CJS-`require`-resolvable `exports`
19
+ * condition, so it cannot itself be used as a synthetic "same package" fixture). The
20
+ * resolution MECHANISM itself (never executes, genuinely finds real packages) is proven
21
+ * with the REAL default resolver in the split/unresolvable test cases.
22
+ */
23
+ export declare function probeSingleInstance(factoryUrl: string, resolveSpecifier?: (specifier: string, anchorUrl: string) => string): SingleInstanceProbeResult;