@pbuilder/sdk 0.18.0 → 0.19.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 (33) hide show
  1. package/README.md +43 -0
  2. package/dist/acl/irwire/stdio-engine-client.d.ts +1 -1
  3. package/dist/acl/irwire/stdio-engine-client.js +3 -2
  4. package/dist/bin/pbuilder-codegen.js +59 -1
  5. package/dist/bin/pbuilder-conformance.js +24 -5
  6. package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.d.ts +6 -3
  7. package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.js +21 -8
  8. package/dist/bounded-contexts/authoring/domain/aggregates/session/session.d.ts +1 -1
  9. package/dist/bounded-contexts/authoring/domain/aggregates/session/session.js +2 -2
  10. package/dist/bounded-contexts/authoring/domain/ports/engine-client.d.ts +1 -1
  11. package/dist/bounded-contexts/authoring/domain/services/schema/input-rejection.d.ts +1 -0
  12. package/dist/bounded-contexts/authoring/domain/services/schema/input-rejection.js +4 -0
  13. package/dist/bounded-contexts/authoring/domain/services/schema/schema-parse.d.ts +3 -2
  14. package/dist/bounded-contexts/authoring/domain/services/schema/schema-parse.js +46 -4
  15. package/dist/bounded-contexts/authoring/domain/services/schema/schema-validate.d.ts +16 -1
  16. package/dist/bounded-contexts/authoring/domain/services/schema/schema-validate.js +125 -0
  17. package/dist/bounded-contexts/authoring/domain/valueobjects/authoring-error.d.ts +3 -2
  18. package/dist/bounded-contexts/authoring/domain/valueobjects/authoring-error.js +2 -0
  19. package/dist/bounded-contexts/authoring/domain/valueobjects/schema-model.d.ts +17 -0
  20. package/dist/bounded-contexts/authoring/domain/valueobjects/schema-model.js +1 -0
  21. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/emit-type.d.ts +1 -0
  22. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/emit-type.js +23 -0
  23. package/dist/bounded-contexts/authoring/testing/conformance/run-package.d.ts +17 -0
  24. package/dist/bounded-contexts/authoring/testing/conformance/run-package.js +124 -44
  25. package/dist/bounded-contexts/authoring/testing/harness/index.d.ts +10 -4
  26. package/dist/bounded-contexts/authoring/testing/harness/index.js +5 -3
  27. package/dist/bounded-contexts/runner-hosting/infrastructure/in/runner.js +37 -10
  28. package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.d.ts +14 -3
  29. package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.js +17 -8
  30. package/dist/conformance/index.d.ts +1 -1
  31. package/dist/conformance/index.js +1 -1
  32. package/dist/runner-manifest.json +12 -12
  33. package/package.json +1 -1
package/README.md CHANGED
@@ -219,6 +219,45 @@ everything you can do inside a factory, and the
219
219
  [quickstart](./docs/guides/quickstart.md) covers the standalone-package setup (tsconfig
220
220
  included) in more depth.
221
221
 
222
+ ## Returning a Result
223
+
224
+ A factory may hand a value back: to Launch when it is the root schematic, with the Plan of a
225
+ Dry Run or the applied operations of a Commit. Declare it under `result` in `schema.json`,
226
+ next to `properties`:
227
+
228
+ ```json
229
+ {
230
+ "properties": {},
231
+ "result": {
232
+ "type": "object",
233
+ "properties": { "name": { "type": "string" }, "files": { "type": "array", "items": { "type": "string" } } },
234
+ "required": ["name"]
235
+ }
236
+ }
237
+ ```
238
+
239
+ `type` is one of `string`, `number`, `boolean`, `null`, `object` and `array`, or a list of
240
+ them (`["string", "null"]`). An object with `properties` accepts only the keys it names, and
241
+ `required` lists the ones it must have; an object without `properties` accepts any JSON
242
+ object. An array may give its `items`. A key that is not `required` may be left out, but never set to
243
+ `undefined`: `undefined` is not JSON, so `{ "name": "a", "files": undefined }` fails. The
244
+ generated type marks such a key `files?:`, which TypeScript lets you set to `undefined` unless
245
+ your tsconfig enables `exactOptionalPropertyTypes`; leave the key out instead. Codegen emits the matching `Result` type next to
246
+ `Input`, so the compiler checks what the factory returns:
247
+
248
+ ```ts
249
+ import type { Input, Result } from "./schema.generated.ts";
250
+
251
+ export default (input: Input): Result => ({ name: "payments", files: [] });
252
+ ```
253
+
254
+ The SDK checks the returned value at the factory boundary before anything is written. It
255
+ must match the declaration and be JSON: no functions, class instances (a `Date`, a `Map`),
256
+ cycles, `undefined` or non-finite numbers. Its JSON encoding may take at most 1 MiB
257
+ (1048576 bytes). A schematic that declares no Result must return nothing. When any of this
258
+ fails, the run fails with an `AuthoringError` whose reason is `invalid-result`, and nothing
259
+ is written. A declared `null` is a Result and is returned as `null`.
260
+
222
261
  ## Project-wide type generation
223
262
 
224
263
  ```sh
@@ -554,6 +593,10 @@ Three things to know:
554
593
  into schema-derived input validation against the adjacent `schema.json`. Without it those
555
594
  verbs have nothing to resolve against.
556
595
 
596
+ - `result.result` is the Result the run committed: what the factory returned, checked
597
+ against the `result` its `schema.json` declares (see [Returning a Result](#returning-a-result)).
598
+ It is `undefined` when the factory declares none or the run failed.
599
+
557
600
  - `result.reads` counts the reads the engine served for each path, so a test can check
558
601
  that the factory reads a file once however many ops it chains on it. A path the factory
559
602
  never read is absent.
@@ -22,6 +22,6 @@ export declare class StdioEngineClient implements EngineClient {
22
22
  });
23
23
  emit(batch: Batch): Promise<void>;
24
24
  read(path: string): Promise<string | undefined>;
25
- commit(): Promise<void>;
25
+ commit(result?: unknown): Promise<void>;
26
26
  discard(): Promise<void>;
27
27
  }
@@ -228,8 +228,9 @@ export class StdioEngineClient {
228
228
  return undefined;
229
229
  return result.content;
230
230
  }
231
- async commit() {
232
- const response = await this.#call("ir.commit", {});
231
+ // A-14: the Result rides in the ir.commit params, the key present only when one is declared.
232
+ async commit(result) {
233
+ const response = await this.#call("ir.commit", result === undefined ? {} : { result });
233
234
  if (response.error !== undefined) {
234
235
  throw new IntentRejectedError(response.error.message);
235
236
  }
@@ -19,6 +19,7 @@ import {
19
19
  import { join as join3, dirname as dirname2, basename, resolve as resolve2, sep } from "node:path";
20
20
 
21
21
  // src/bounded-contexts/authoring/domain/valueobjects/schema-model.ts
22
+ var RESULT_KINDS = new Set(["string", "number", "boolean", "null", "object", "array"]);
22
23
  var FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
23
24
  function isPlainObject(value) {
24
25
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -256,7 +257,46 @@ function parseSchema(raw) {
256
257
  description: typeof value.description === "string" ? value.description : undefined
257
258
  });
258
259
  }
259
- return { properties };
260
+ if (!Object.hasOwn(parsed, "result"))
261
+ return { properties };
262
+ const result = parseResult(parsed.result);
263
+ if (result === undefined) {
264
+ throw new SchemaParseFailure({ problem: 'invalid "result" declaration', line: undefined, column: undefined });
265
+ }
266
+ return { properties, result };
267
+ }
268
+ function parseResult(raw) {
269
+ if (!isPlainObject(raw))
270
+ return;
271
+ const types = Array.isArray(raw.type) ? raw.type : [raw.type];
272
+ if (types.length === 0 || !types.every((type) => typeof type === "string" && RESULT_KINDS.has(type)))
273
+ return;
274
+ const schema = { types };
275
+ if (raw.properties !== undefined) {
276
+ if (!isPlainObject(raw.properties))
277
+ return;
278
+ const properties = [];
279
+ for (const key of Object.keys(raw.properties)) {
280
+ const property = FORBIDDEN_KEYS.has(key) ? undefined : parseResult(raw.properties[key]);
281
+ if (property === undefined)
282
+ return;
283
+ properties.push({ key, schema: property });
284
+ }
285
+ schema.properties = properties;
286
+ }
287
+ if (raw.required !== undefined) {
288
+ const declared = new Set(schema.properties?.map((property) => property.key));
289
+ if (!Array.isArray(raw.required) || !raw.required.every((key) => typeof key === "string" && declared.has(key)))
290
+ return;
291
+ schema.required = raw.required;
292
+ }
293
+ if (raw.items !== undefined) {
294
+ const items = parseResult(raw.items);
295
+ if (items === undefined)
296
+ return;
297
+ schema.items = items;
298
+ }
299
+ return schema;
260
300
  }
261
301
 
262
302
  // src/bounded-contexts/authoring/domain/services/schema/schema-digest.ts
@@ -347,6 +387,23 @@ function emitProperty(property) {
347
387
  ` : "";
348
388
  return `${doc} ${key}${optional}: ${type};`;
349
389
  }
390
+ function emitResult(result) {
391
+ return result.types.map((kind) => {
392
+ switch (kind) {
393
+ case "array":
394
+ return `Array<${result.items === undefined ? "unknown" : emitResult(result.items)}>`;
395
+ case "object": {
396
+ if (result.properties === undefined)
397
+ return "{ [key: string]: unknown }";
398
+ const required = new Set(result.required);
399
+ const members = result.properties.map(({ key, schema }) => `${emitPropertyKey(key)}${required.has(key) ? "" : "?"}: ${emitResult(schema)}`);
400
+ return members.length === 0 ? "Record<string, never>" : `{ ${members.join("; ")} }`;
401
+ }
402
+ default:
403
+ return kind;
404
+ }
405
+ }).join(" | ");
406
+ }
350
407
  function emitInputType(schema, digest) {
351
408
  const members = schema.properties.map(emitProperty).join(`
352
409
  `);
@@ -357,6 +414,7 @@ function emitInputType(schema, digest) {
357
414
  "export type Input = {",
358
415
  members,
359
416
  "};",
417
+ ...schema.result === undefined ? [] : ["", `export type Result = ${emitResult(schema.result)};`],
360
418
  ""
361
419
  ].join(`
362
420
  `);
@@ -1,21 +1,40 @@
1
1
  #!/usr/bin/env bun
2
- // `pbuilder-conformance --dialect <installed package dir>` (CA-13): prints one JSON report line.
2
+ // `pbuilder-conformance --dialect <installed package dir>` (CA-13), or
3
+ // `pbuilder-conformance --local <name> --conformance <file> --path <base file>` for a local dialect
4
+ // (CA-18): prints one JSON report line.
3
5
  // Exit 0: the fixture passed. Exit 1: it ran and failed, a missing fixture included. Exit 2: it
4
6
  // could not run, with nothing on stdout. Runs under Bun, from the SDK root of the Run, so the
5
7
  // dialect's `@pbuilder/sdk` imports reach this same SDK.
6
- import { checkDialectPackage } from "../conformance/index.js";
8
+ import { checkDialectPackage, checkLocalDialect } from "../conformance/index.js";
7
9
  import { redirectConsoleToStderr } from "../shared-kernel/framing.js";
8
10
  // The fixture runs the author's code, so everything but the report goes to stderr.
9
11
  const writeReport = process.stdout.write.bind(process.stdout);
10
12
  Object.defineProperty(process, "stdout", { value: process.stderr, writable: true, configurable: true });
11
13
  redirectConsoleToStderr();
12
14
  const COULD_NOT_RUN = 2;
15
+ const USAGE = "usage: pbuilder-conformance --dialect <installed package dir>\n" +
16
+ " pbuilder-conformance --local <name> --conformance <file> --path <base file>\n";
17
+ function check(argv) {
18
+ if (argv.some((value) => value === ""))
19
+ return undefined;
20
+ if (argv.length === 2 && argv[0] === "--dialect")
21
+ return checkDialectPackage(argv[1]);
22
+ if (argv.length !== 6 || argv[0] !== "--local")
23
+ return undefined;
24
+ const flags = new Map([[argv[2], argv[3]], [argv[4], argv[5]]]);
25
+ const conformance = flags.get("--conformance");
26
+ const path = flags.get("--path");
27
+ if (conformance === undefined || path === undefined)
28
+ return undefined;
29
+ return checkLocalDialect({ name: argv[1], conformance, path });
30
+ }
13
31
  async function main(argv) {
14
- if (argv.length !== 2 || argv[0] !== "--dialect" || argv[1] === "") {
15
- process.stderr.write("usage: pbuilder-conformance --dialect <installed package dir>\n");
32
+ const checking = check(argv);
33
+ if (checking === undefined) {
34
+ process.stderr.write(USAGE);
16
35
  return COULD_NOT_RUN;
17
36
  }
18
- const report = await checkDialectPackage(argv[1]);
37
+ const report = await checking;
19
38
  await new Promise((done) => writeReport(`${JSON.stringify(report)}\n`, () => done()));
20
39
  return report.passed ? 0 : 1;
21
40
  }
@@ -46,7 +46,10 @@ export declare function requirePackageAnchors(missingAnchorMessage: string): {
46
46
  * Author code never imports this directly; it calls `runFactoryForTest` (test-time) or the
47
47
  * future production runner instead — both wrap this SAME seam internally.
48
48
  *
49
- * @param fn - the authoring logic; receives the resolved, schema-validated input.
49
+ * @param fn - the authoring logic; receives the resolved, schema-validated input and returns
50
+ * the schematic's Result, or nothing when its `schema.json` declares none (A-14). The Result
51
+ * is checked against that declaration before the flush; the runner resolves to the committed
52
+ * copy. A bare `defineFactory(fn)` declares no Result, so `fn` must return nothing.
50
53
  * @param options.packageFiles - the package-files adapter the two reads go through; every
51
54
  * caller passes it with `packageDir`.
52
55
  * @param options.packageDir - opts into schema-derived input validation and reserved-name
@@ -79,7 +82,7 @@ export declare function requirePackageAnchors(missingAnchorMessage: string): {
79
82
  * const runner = defineFactory<Input>(bareFactory, { packageDir: import.meta.dir });
80
83
  * await runner(input, { client });
81
84
  */
82
- export declare function defineFactory<O>(fn: (o: O) => void | Promise<void>, options?: ({
85
+ export declare function defineFactory<O, R = void>(fn: (o: O) => R | Promise<R>, options?: ({
83
86
  packageDir: string | URL;
84
87
  packageFiles: PackageFiles;
85
88
  } | {
@@ -89,4 +92,4 @@ export declare function defineFactory<O>(fn: (o: O) => void | Promise<void>, opt
89
92
  declaredDialects?: readonly string[];
90
93
  }): (o: O, deps: {
91
94
  client: EngineClient;
92
- }) => Promise<void>;
95
+ }) => Promise<R>;
@@ -9,8 +9,8 @@ import { invalidInput } from "../../../domain/valueobjects/authoring-error.js";
9
9
  import { currentRun, getSessionAls } from "../../../domain/services/run-context.js";
10
10
  import { schemaPathFor } from "../../../domain/services/schema/schema-files.js";
11
11
  import { parseSchema, SchemaParseFailure, formatLocator } from "../../../domain/services/schema/schema-parse.js";
12
- import { validateInput } from "../../../domain/services/schema/schema-validate.js";
13
- import { rejectionFor, rejectionForReservedName } from "../../../domain/services/schema/input-rejection.js";
12
+ import { checkResult, validateInput } from "../../../domain/services/schema/schema-validate.js";
13
+ import { rejectionFor, rejectionForReservedName, rejectionForResult } from "../../../domain/services/schema/input-rejection.js";
14
14
  class DialectRegistryImpl {
15
15
  #handles = [];
16
16
  register(handle) {
@@ -103,7 +103,7 @@ function validateAtRunBoundary(pkg, input) {
103
103
  }
104
104
  if (raw === undefined) {
105
105
  console.warn(noSchemaWarning(pkg));
106
- return;
106
+ return undefined;
107
107
  }
108
108
  let schema;
109
109
  try {
@@ -117,13 +117,14 @@ function validateAtRunBoundary(pkg, input) {
117
117
  }
118
118
  if (schema.properties.length === 0) {
119
119
  console.warn(emptySchemaWarning(pkg));
120
- return;
120
+ return schema;
121
121
  }
122
122
  const findings = validateInput(schema, input);
123
123
  const [firstFinding] = findings;
124
124
  if (firstFinding !== undefined) {
125
125
  throw rejectionFor(firstFinding);
126
126
  }
127
+ return schema;
127
128
  }
128
129
  // Reserved-lifecycle-name enforcement (S-004, ADR-0028, REQ-RLN-01/02): resolves
129
130
  // reserved-name status from the factory package's OWN MODULE STRUCTURE only — never from
@@ -163,7 +164,10 @@ function checkReservedNames(pkg) {
163
164
  * Author code never imports this directly; it calls `runFactoryForTest` (test-time) or the
164
165
  * future production runner instead — both wrap this SAME seam internally.
165
166
  *
166
- * @param fn - the authoring logic; receives the resolved, schema-validated input.
167
+ * @param fn - the authoring logic; receives the resolved, schema-validated input and returns
168
+ * the schematic's Result, or nothing when its `schema.json` declares none (A-14). The Result
169
+ * is checked against that declaration before the flush; the runner resolves to the committed
170
+ * copy. A bare `defineFactory(fn)` declares no Result, so `fn` must return nothing.
167
171
  * @param options.packageFiles - the package-files adapter the two reads go through; every
168
172
  * caller passes it with `packageDir`.
169
173
  * @param options.packageDir - opts into schema-derived input validation and reserved-name
@@ -200,12 +204,13 @@ export function defineFactory(fn, options) {
200
204
  const wrapped = async (o, { client }) => {
201
205
  let packageAnchors;
202
206
  let packageFiles;
207
+ let schema;
203
208
  if (options?.packageDir !== undefined) {
204
209
  const pkg = { files: options.packageFiles, dir: resolvePackageDir(options.packageDir) };
205
210
  // REQ-RBV-06: exactly TWO reads, in this order — reserved-name check, then schema
206
211
  // validation. No third (containment-ceiling) read exists (ADR-0077 §C).
207
212
  checkReservedNames(pkg);
208
- validateAtRunBoundary(pkg, o);
213
+ schema = validateAtRunBoundary(pkg, o);
209
214
  packageAnchors = { packageDir: pkg.dir };
210
215
  packageFiles = pkg.files;
211
216
  }
@@ -225,11 +230,19 @@ export function defineFactory(fn, options) {
225
230
  // unawaited dialect chain (forgotten `await`) still completes and commits; a drain
226
231
  // rejection (an unawaited chain that threw) routes through the SAME catch below as a
227
232
  // flush rejection already does.
233
+ //
234
+ // A-14: the Result is checked after the drain and before the final flush, so an invalid
235
+ // one takes the discard path below and nothing is written. A bare factory, or one with no `result` in its schema,
236
+ // declares none and must return nothing; the commit then carries no Result.
228
237
  try {
229
- await getSessionAls().run(ctx, () => fn(o));
238
+ const returned = await getSessionAls().run(ctx, () => fn(o));
230
239
  await ctx.dialects.drain();
240
+ const checked = checkResult(schema?.result, returned);
241
+ if ("problem" in checked)
242
+ throw rejectionForResult(checked.problem);
231
243
  await ctx.session.flush();
232
- await ctx.session.commit();
244
+ await ctx.session.commit(checked.result);
245
+ return checked.result;
233
246
  }
234
247
  catch (thrown) {
235
248
  // A thrown `undefined` or `null` would read as success to anyone testing the error.
@@ -8,7 +8,7 @@ export declare class Session {
8
8
  pendingDirectives(): readonly Directive[];
9
9
  isPending(directive: Directive): boolean;
10
10
  read(path: string): Promise<string | undefined>;
11
- commit(): Promise<void>;
11
+ commit(result?: unknown): Promise<void>;
12
12
  discard(): Promise<void>;
13
13
  flush(): Promise<void>;
14
14
  }
@@ -72,8 +72,8 @@ export class Session {
72
72
  }
73
73
  // SEAM-03 (ADR-01): thin wrappers delegating to #client. Session owns #client, so the
74
74
  // commit boundary stays inside Session — defineFactory never names #client directly.
75
- async commit() {
76
- await this.#client.commit();
75
+ async commit(result) {
76
+ await this.#client.commit(result);
77
77
  }
78
78
  async discard() {
79
79
  await this.#client.discard();
@@ -2,6 +2,6 @@ import type { Batch } from "../valueobjects/wire.ts";
2
2
  export interface EngineClient {
3
3
  emit(batch: Batch): Promise<void>;
4
4
  read(path: string): Promise<string | undefined>;
5
- commit(): Promise<void>;
5
+ commit(result?: unknown): Promise<void>;
6
6
  discard(): Promise<void>;
7
7
  }
@@ -2,3 +2,4 @@ import { AuthoringError } from "../../valueobjects/authoring-error.ts";
2
2
  import type { ValidationFinding } from "./schema-validate.ts";
3
3
  export declare function rejectionFor(finding: ValidationFinding): AuthoringError;
4
4
  export declare function rejectionForReservedName(name: string): AuthoringError;
5
+ export declare function rejectionForResult(problem: string): AuthoringError;
@@ -30,3 +30,7 @@ export function rejectionFor(finding) {
30
30
  export function rejectionForReservedName(name) {
31
31
  return rejection("reserved-name", `reserved lifecycle name: ${name} is reserved and cannot be declared by a factory module`);
32
32
  }
33
+ // A-14 / E-40: an invalid or oversized Result, from `checkResult`.
34
+ export function rejectionForResult(problem) {
35
+ return rejection("invalid-result", `invalid Result: ${problem}`);
36
+ }
@@ -13,8 +13,9 @@ export declare class SchemaParseFailure extends Error {
13
13
  export declare function formatLocator(line: number | undefined, column: number | undefined): string;
14
14
  /**
15
15
  * Parses the on-disk WRAPPED `schema.json` wire shape (ADR-0027: top-level
16
- * `{ "properties": { "<key>": {...} } }`) into the in-memory `Schema` array model.
17
- * Fail-closed: invalid JSON or a missing/non-object `"properties"` key both throw
16
+ * `{ "properties": { "<key>": {...} } }`, plus an optional `"result"` declaration, A-14) into
17
+ * the in-memory `Schema` array model.
18
+ * Fail-closed: invalid JSON, a missing/non-object `"properties"` key or an invalid `"result"` throw
18
19
  * `SchemaParseFailure` on the same path — the raw content is never echoed.
19
20
  */
20
21
  export declare function parseSchema(raw: string): Schema;
@@ -1,7 +1,7 @@
1
1
  // Bytes -> Schema. Shared by the bin (TFO-04's parse-error template) and the runtime
2
2
  // (RBV-05.1's fail-closed literal) — both format SchemaParseFailure into their own
3
3
  // vocabulary; this module never renders a caller-facing message itself (no-echo, ADR-0027).
4
- import { isPlainObject } from "../../valueobjects/schema-model.js";
4
+ import { FORBIDDEN_KEYS, isPlainObject, RESULT_KINDS } from "../../valueobjects/schema-model.js";
5
5
  import { locateFirstJsonSyntaxError } from "./schema-locate.js";
6
6
  export class SchemaParseFailure extends Error {
7
7
  problem;
@@ -23,8 +23,9 @@ export function formatLocator(line, column) {
23
23
  }
24
24
  /**
25
25
  * Parses the on-disk WRAPPED `schema.json` wire shape (ADR-0027: top-level
26
- * `{ "properties": { "<key>": {...} } }`) into the in-memory `Schema` array model.
27
- * Fail-closed: invalid JSON or a missing/non-object `"properties"` key both throw
26
+ * `{ "properties": { "<key>": {...} } }`, plus an optional `"result"` declaration, A-14) into
27
+ * the in-memory `Schema` array model.
28
+ * Fail-closed: invalid JSON, a missing/non-object `"properties"` key or an invalid `"result"` throw
28
29
  * `SchemaParseFailure` on the same path — the raw content is never echoed.
29
30
  */
30
31
  export function parseSchema(raw) {
@@ -64,5 +65,46 @@ export function parseSchema(raw) {
64
65
  description: typeof value.description === "string" ? value.description : undefined,
65
66
  });
66
67
  }
67
- return { properties };
68
+ if (!Object.hasOwn(parsed, "result"))
69
+ return { properties };
70
+ const result = parseResult(parsed.result);
71
+ if (result === undefined) {
72
+ throw new SchemaParseFailure({ problem: 'invalid "result" declaration', line: undefined, column: undefined });
73
+ }
74
+ return { properties, result };
75
+ }
76
+ // A-14: `type` (one kind or a list of kinds), and for an object `properties` and `required`,
77
+ // for an array `items`. Anything else, or a nested declaration that fails, is undefined.
78
+ function parseResult(raw) {
79
+ if (!isPlainObject(raw))
80
+ return undefined;
81
+ const types = Array.isArray(raw.type) ? raw.type : [raw.type];
82
+ if (types.length === 0 || !types.every((type) => typeof type === "string" && RESULT_KINDS.has(type)))
83
+ return undefined;
84
+ const schema = { types: types };
85
+ if (raw.properties !== undefined) {
86
+ if (!isPlainObject(raw.properties))
87
+ return undefined;
88
+ const properties = [];
89
+ for (const key of Object.keys(raw.properties)) {
90
+ const property = FORBIDDEN_KEYS.has(key) ? undefined : parseResult(raw.properties[key]);
91
+ if (property === undefined)
92
+ return undefined;
93
+ properties.push({ key, schema: property });
94
+ }
95
+ schema.properties = properties;
96
+ }
97
+ if (raw.required !== undefined) {
98
+ const declared = new Set(schema.properties?.map((property) => property.key));
99
+ if (!Array.isArray(raw.required) || !raw.required.every((key) => typeof key === "string" && declared.has(key)))
100
+ return undefined;
101
+ schema.required = raw.required;
102
+ }
103
+ if (raw.items !== undefined) {
104
+ const items = parseResult(raw.items);
105
+ if (items === undefined)
106
+ return undefined;
107
+ schema.items = items;
108
+ }
109
+ return schema;
68
110
  }
@@ -1,4 +1,4 @@
1
- import type { Schema } from "../../valueobjects/schema-model.ts";
1
+ import type { ResultSchema, Schema } from "../../valueobjects/schema-model.ts";
2
2
  export type ValidationFinding = {
3
3
  kind: "missing";
4
4
  field: string;
@@ -12,3 +12,18 @@ export type ValidationFinding = {
12
12
  field: string;
13
13
  };
14
14
  export declare function validateInput(schema: Schema, input: unknown): ValidationFinding[];
15
+ /** E-40: the largest JSON encoding of a Result, in UTF-8 bytes; exactly at it is allowed. */
16
+ export declare const RESULT_CEILING_BYTES = 1048576;
17
+ export type ResultCheck = {
18
+ readonly result: unknown;
19
+ } | {
20
+ readonly problem: string;
21
+ };
22
+ /**
23
+ * Checks `value` as the Result of a factory whose declaration is `declared`. Without a
24
+ * declaration only `undefined`, no Result, passes. A Result that passes comes back as a copy
25
+ * parsed from its JSON encoding, so what is committed is exactly what was checked. The
26
+ * declaration is a parameter so a Result shape a role imposes can be checked the same way as
27
+ * one read from `schema.json`.
28
+ */
29
+ export declare function checkResult(declared: ResultSchema | undefined, value: unknown): ResultCheck;
@@ -62,3 +62,128 @@ export function validateInput(schema, input) {
62
62
  }
63
63
  return findings;
64
64
  }
65
+ /** E-40: the largest JSON encoding of a Result, in UTF-8 bytes; exactly at it is allowed. */
66
+ export const RESULT_CEILING_BYTES = 1048576;
67
+ /**
68
+ * Checks `value` as the Result of a factory whose declaration is `declared`. Without a
69
+ * declaration only `undefined`, no Result, passes. A Result that passes comes back as a copy
70
+ * parsed from its JSON encoding, so what is committed is exactly what was checked. The
71
+ * declaration is a parameter so a Result shape a role imposes can be checked the same way as
72
+ * one read from `schema.json`.
73
+ */
74
+ export function checkResult(declared, value) {
75
+ if (declared === undefined) {
76
+ return value === undefined ? { result: undefined } : { problem: "the factory declares no Result in schema.json but returned a value" };
77
+ }
78
+ let encoded;
79
+ try {
80
+ const problem = jsonProblem(value, "Result", new Set());
81
+ if (problem !== undefined)
82
+ return { problem };
83
+ encoded = JSON.stringify(value);
84
+ }
85
+ catch (err) {
86
+ // A getter or proxy that throws, or nesting too deep to walk; what it threw is not echoed.
87
+ return { problem: err instanceof RangeError ? "the Result is nested too deeply" : "the Result could not be read" };
88
+ }
89
+ const result = JSON.parse(encoded);
90
+ const problem = shapeProblem(declared, result, "Result");
91
+ if (problem !== undefined)
92
+ return { problem };
93
+ const bytes = Buffer.byteLength(encoded, "utf8");
94
+ return bytes > RESULT_CEILING_BYTES
95
+ ? { problem: `the JSON encoding of the Result is ${bytes} bytes, past the 1 MiB ceiling (${RESULT_CEILING_BYTES} bytes)` }
96
+ : { result };
97
+ }
98
+ // JSON.stringify drops or rewrites what is not JSON (undefined, functions, NaN, a Date's
99
+ // toJSON) instead of failing, so the walk refuses each of them explicitly.
100
+ function jsonProblem(value, where, ancestors) {
101
+ switch (typeof value) {
102
+ case "string":
103
+ case "boolean":
104
+ return undefined;
105
+ case "number":
106
+ // NaN and ±Infinity are the numbers for which this is not 0 (the runner closure admits no Number.isFinite).
107
+ return value - value === 0 ? undefined : `${where} is a non-finite number`;
108
+ case "undefined":
109
+ case "function":
110
+ case "bigint":
111
+ case "symbol":
112
+ return `${where} is ${typeof value === "undefined" ? "undefined" : `a ${typeof value}`}`;
113
+ }
114
+ if (value === null)
115
+ return undefined;
116
+ const object = value;
117
+ if (ancestors.has(object))
118
+ return `${where} is a cycle`;
119
+ if (!Array.isArray(object)) {
120
+ const prototype = Object.getPrototypeOf(object);
121
+ if (prototype !== Object.prototype && prototype !== null) {
122
+ return `${where} is ${object instanceof Date ? "a Date" : object instanceof Map ? "a Map" : "a class instance"}`;
123
+ }
124
+ if (typeof object.toJSON === "function")
125
+ return `${where} has a toJSON method`;
126
+ }
127
+ // Ancestors only, so a value shared twice without a cycle is accepted, as JSON.stringify does.
128
+ ancestors.add(object);
129
+ try {
130
+ const entries = [];
131
+ if (Array.isArray(object)) {
132
+ for (let index = 0; index < object.length; index++)
133
+ entries.push([`${where}[${index}]`, object[index]]);
134
+ }
135
+ else {
136
+ for (const key of Object.keys(object))
137
+ entries.push([`${where}.${key}`, object[key]]);
138
+ }
139
+ for (const [at, item] of entries) {
140
+ const problem = jsonProblem(item, at, ancestors);
141
+ if (problem !== undefined)
142
+ return problem;
143
+ }
144
+ return undefined;
145
+ }
146
+ finally {
147
+ ancestors.delete(object);
148
+ }
149
+ }
150
+ function kindOf(value) {
151
+ if (value === null)
152
+ return "null";
153
+ if (Array.isArray(value))
154
+ return "array";
155
+ return typeof value;
156
+ }
157
+ // Runs on the parsed copy, so every value here is JSON.
158
+ function shapeProblem(declared, value, where) {
159
+ const kind = kindOf(value);
160
+ if (!declared.types.includes(kind))
161
+ return `${where} must be ${declared.types.join(" or ")}`;
162
+ if (kind === "array" && declared.items !== undefined) {
163
+ const items = declared.items;
164
+ for (const [index, item] of value.entries()) {
165
+ const problem = shapeProblem(items, item, `${where}[${index}]`);
166
+ if (problem !== undefined)
167
+ return problem;
168
+ }
169
+ }
170
+ if (kind === "object" && declared.properties !== undefined) {
171
+ const record = value;
172
+ const required = new Set(declared.required);
173
+ for (const { key, schema } of declared.properties) {
174
+ if (!Object.hasOwn(record, key)) {
175
+ if (required.has(key))
176
+ return `${where}.${key} must be ${schema.types.join(" or ")}`;
177
+ continue;
178
+ }
179
+ const problem = shapeProblem(schema, record[key], `${where}.${key}`);
180
+ if (problem !== undefined)
181
+ return problem;
182
+ }
183
+ const declaredKeys = new Set(declared.properties.map((property) => property.key));
184
+ const extra = Object.keys(record).find((key) => !declaredKeys.has(key));
185
+ if (extra !== undefined)
186
+ return `${where}.${extra} is not declared`;
187
+ }
188
+ return undefined;
189
+ }
@@ -52,11 +52,12 @@ export type AuthoringVerb = "create" | "modify" | "remove" | "rename" | "move" |
52
52
  * case "source-not-found":
53
53
  * case "source-not-regular-file":
54
54
  * case "source-unreadable":
55
+ * case "invalid-result":
55
56
  * console.error(err.message);
56
57
  * break;
57
58
  * }
58
59
  */
59
- export type AuthoringReason = "path-collision" | "path-not-found" | "unrepresentable-content" | "changes-too-large" | "outside-session" | "unknown" | "invalid-input" | "reserved-name" | "source-not-found" | "source-not-regular-file" | "source-unreadable";
60
+ export type AuthoringReason = "path-collision" | "path-not-found" | "unrepresentable-content" | "changes-too-large" | "outside-session" | "unknown" | "invalid-input" | "reserved-name" | "source-not-found" | "source-not-regular-file" | "source-unreadable" | "invalid-result";
60
61
  /**
61
62
  * Distinguishes an engine-refused write from an SDK-side misuse (2.4, ADR-0021) —
62
63
  * DERIVED from `reason`, never producer-set.
@@ -106,7 +107,7 @@ export declare class AuthoringError extends Error {
106
107
  appliedCount: number;
107
108
  /**
108
109
  * Overrides the derived message. REQUIRED for `reason: "invalid-input"` /
109
- * `"reserved-name"` (REQ-AEC-09) — their templates interpolate caller-known data
110
+ * `"reserved-name"` (REQ-AEC-09) / `"invalid-result"` (A-14) — their templates interpolate caller-known data
110
111
  * (`{field}`, `{expectedType}`, `{name}`) `messageFor` cannot derive from `verb`/`path`
111
112
  * alone. Optional for every other reason, which derive their message from `reason` +
112
113
  * `verb` + `path` as before.
@@ -36,6 +36,7 @@ function originFor(reason) {
36
36
  case "source-not-found":
37
37
  case "source-not-regular-file":
38
38
  case "source-unreadable":
39
+ case "invalid-result":
39
40
  return "authoring-rejected";
40
41
  default: {
41
42
  const _exhaustive = reason;
@@ -121,6 +122,7 @@ function messageFor(reason, verb, path) {
121
122
  return `source file unreadable: ${path} could not be read`;
122
123
  case "invalid-input":
123
124
  case "reserved-name":
125
+ case "invalid-result":
124
126
  throw new Error(`messageFor: reason "${reason}" has no default template (REQ-AEC-09) — construct AuthoringError with an explicit \`message\``);
125
127
  // Parity with originFor: noImplicitReturns is off, so without this arm a 13th reason
126
128
  // would fall through to an implicit `undefined` return instead of a build break.