@pbuilder/sdk 0.18.0 → 0.20.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 (79) hide show
  1. package/README.md +89 -3
  2. package/dist/acl/irwire/stdio-engine-client.d.ts +2 -1
  3. package/dist/acl/irwire/stdio-engine-client.js +12 -2
  4. package/dist/bin/pbuilder-codegen.js +148 -18
  5. package/dist/bin/pbuilder-conformance.js +24 -5
  6. package/dist/bounded-contexts/authoring/application/usecases/authoring-verbs/index.d.ts +15 -0
  7. package/dist/bounded-contexts/authoring/application/usecases/authoring-verbs/index.js +17 -0
  8. package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.d.ts +21 -5
  9. package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.js +59 -12
  10. package/dist/bounded-contexts/authoring/domain/aggregates/session/session.d.ts +4 -2
  11. package/dist/bounded-contexts/authoring/domain/aggregates/session/session.js +12 -3
  12. package/dist/bounded-contexts/authoring/domain/ports/engine-client.d.ts +2 -1
  13. package/dist/bounded-contexts/authoring/domain/services/define-dialect.d.ts +28 -1
  14. package/dist/bounded-contexts/authoring/domain/services/define-dialect.js +27 -3
  15. package/dist/bounded-contexts/authoring/domain/services/evaluation.d.ts +29 -0
  16. package/dist/bounded-contexts/authoring/domain/services/evaluation.js +43 -0
  17. package/dist/bounded-contexts/authoring/domain/services/glob-match.d.ts +4 -0
  18. package/dist/bounded-contexts/authoring/domain/services/glob-match.js +81 -0
  19. package/dist/bounded-contexts/authoring/domain/services/schema/input-rejection.d.ts +2 -0
  20. package/dist/bounded-contexts/authoring/domain/services/schema/input-rejection.js +8 -0
  21. package/dist/bounded-contexts/authoring/domain/services/schema/schema-parse.d.ts +3 -2
  22. package/dist/bounded-contexts/authoring/domain/services/schema/schema-parse.js +46 -4
  23. package/dist/bounded-contexts/authoring/domain/services/schema/schema-validate.d.ts +18 -2
  24. package/dist/bounded-contexts/authoring/domain/services/schema/schema-validate.js +131 -2
  25. package/dist/bounded-contexts/authoring/domain/valueobjects/authoring-error.d.ts +3 -2
  26. package/dist/bounded-contexts/authoring/domain/valueobjects/authoring-error.js +2 -0
  27. package/dist/bounded-contexts/authoring/domain/valueobjects/findings.d.ts +12 -0
  28. package/dist/bounded-contexts/authoring/domain/valueobjects/findings.js +57 -0
  29. package/dist/bounded-contexts/authoring/domain/valueobjects/schema-model.d.ts +19 -0
  30. package/dist/bounded-contexts/authoring/domain/valueobjects/schema-model.js +1 -0
  31. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/cli.d.ts +7 -2
  32. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/cli.js +28 -7
  33. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/emit-type.d.ts +6 -1
  34. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/emit-type.js +44 -11
  35. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/project-codegen.d.ts +1 -0
  36. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/project-codegen.js +5 -2
  37. package/dist/bounded-contexts/authoring/infrastructure/in/commons/index.d.ts +2 -1
  38. package/dist/bounded-contexts/authoring/infrastructure/in/commons/index.js +1 -1
  39. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/angular/index.d.ts +14 -1
  40. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/angular/index.js +15 -0
  41. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.d.ts +14 -1
  42. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.js +15 -0
  43. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/index.d.ts +14 -1
  44. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/index.js +15 -0
  45. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/css/index.d.ts +14 -1
  46. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/css/index.js +15 -0
  47. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/json/index.d.ts +14 -1
  48. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/json/index.js +15 -0
  49. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.d.ts +14 -1
  50. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.js +15 -0
  51. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/nestjs/index.d.ts +14 -1
  52. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/nestjs/index.js +15 -0
  53. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/index.d.ts +14 -1
  54. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/index.js +15 -0
  55. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/index.d.ts +14 -1
  56. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/index.js +15 -0
  57. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/yaml/index.d.ts +14 -1
  58. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/yaml/index.js +15 -0
  59. package/dist/bounded-contexts/authoring/testing/conformance/run-package.d.ts +17 -0
  60. package/dist/bounded-contexts/authoring/testing/conformance/run-package.js +124 -44
  61. package/dist/bounded-contexts/authoring/testing/contract-fake.d.ts +1 -0
  62. package/dist/bounded-contexts/authoring/testing/contract-fake.js +8 -0
  63. package/dist/bounded-contexts/authoring/testing/glob-pattern.d.ts +5 -0
  64. package/dist/bounded-contexts/authoring/testing/glob-pattern.js +20 -0
  65. package/dist/bounded-contexts/authoring/testing/harness/index.d.ts +18 -4
  66. package/dist/bounded-contexts/authoring/testing/harness/index.js +17 -4
  67. package/dist/bounded-contexts/authoring/testing/run-vehicle.d.ts +1 -0
  68. package/dist/bounded-contexts/authoring/testing/run-vehicle.js +4 -0
  69. package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.d.ts +3 -0
  70. package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.js +4 -0
  71. package/dist/bounded-contexts/runner-hosting/infrastructure/in/runner.js +52 -13
  72. package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.d.ts +14 -3
  73. package/dist/bounded-contexts/runner-hosting/infrastructure/in/single-instance-probe.js +17 -8
  74. package/dist/conformance/index.d.ts +1 -1
  75. package/dist/conformance/index.js +1 -1
  76. package/dist/runner-manifest.json +37 -13
  77. package/dist/shared-kernel/wire-protocol.d.ts +1 -1
  78. package/dist/shared-kernel/wire-protocol.js +1 -1
  79. package/package.json +1 -1
@@ -9,8 +9,10 @@ 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, rejectionForScopeInput, } from "../../../domain/services/schema/input-rejection.js";
14
+ import { handedOnFindings, scopeOf } from "../../../domain/services/evaluation.js";
15
+ import { SCOPE_INPUTS, SOURCED_FINDINGS } from "../../../domain/valueobjects/findings.js";
14
16
  class DialectRegistryImpl {
15
17
  #handles = [];
16
18
  register(handle) {
@@ -90,7 +92,7 @@ function emptySchemaWarning(pkg) {
90
92
  // a corrupt/unreadable schema file, only for author-input rejections (invalid-input /
91
93
  // reserved-name). A parsed-but-empty schema (zero declared properties) is distinct from no
92
94
  // schema at all (REQ-RBV-05.2) — it warns and skips validation, it does not opt out.
93
- function validateAtRunBoundary(pkg, input) {
95
+ function validateAtRunBoundary(pkg, input, imposed) {
94
96
  let raw;
95
97
  try {
96
98
  raw = pkg.files.readText(schemaPathFor(pkg.dir));
@@ -103,7 +105,7 @@ function validateAtRunBoundary(pkg, input) {
103
105
  }
104
106
  if (raw === undefined) {
105
107
  console.warn(noSchemaWarning(pkg));
106
- return;
108
+ return undefined;
107
109
  }
108
110
  let schema;
109
111
  try {
@@ -117,13 +119,14 @@ function validateAtRunBoundary(pkg, input) {
117
119
  }
118
120
  if (schema.properties.length === 0) {
119
121
  console.warn(emptySchemaWarning(pkg));
120
- return;
122
+ return schema;
121
123
  }
122
- const findings = validateInput(schema, input);
124
+ const findings = validateInput(schema, input, imposed);
123
125
  const [firstFinding] = findings;
124
126
  if (firstFinding !== undefined) {
125
127
  throw rejectionFor(firstFinding);
126
128
  }
129
+ return schema;
127
130
  }
128
131
  // Reserved-lifecycle-name enforcement (S-004, ADR-0028, REQ-RLN-01/02): resolves
129
132
  // reserved-name status from the factory package's OWN MODULE STRUCTURE only — never from
@@ -144,6 +147,22 @@ function checkReservedNames(pkg) {
144
147
  throw rejectionForReservedName(reserved);
145
148
  }
146
149
  }
150
+ // A-14 / A-121 / A-124: the Result as it leaves the factory. An evaluation's Findings are checked
151
+ // again once sourced and narrowed, since the `source` it adds counts towards the ceiling (E-40).
152
+ function handOn(declared, returned, source, inScope) {
153
+ const checked = checkResult(declared, returned);
154
+ if ("problem" in checked)
155
+ throw rejectionForResult(checked.problem);
156
+ if (source === undefined)
157
+ return checked.result;
158
+ const handed = handedOnFindings(checked.result, source, inScope);
159
+ if ("problem" in handed)
160
+ throw rejectionForResult(handed.problem);
161
+ const recheck = checkResult(SOURCED_FINDINGS, handed.result);
162
+ if ("problem" in recheck)
163
+ throw rejectionForResult(recheck.problem);
164
+ return recheck.result;
165
+ }
147
166
  /**
148
167
  * Builds a SessionContext and runs the factory inside it, flushing buffered
149
168
  * directives at run end (REQ-KIT-05) — a write-only factory still emits.
@@ -163,7 +182,10 @@ function checkReservedNames(pkg) {
163
182
  * Author code never imports this directly; it calls `runFactoryForTest` (test-time) or the
164
183
  * future production runner instead — both wrap this SAME seam internally.
165
184
  *
166
- * @param fn - the authoring logic; receives the resolved, schema-validated input.
185
+ * @param fn - the authoring logic; receives the resolved, schema-validated input and returns
186
+ * the schematic's Result, or nothing when its `schema.json` declares none (A-14). The Result
187
+ * is checked against that declaration before the flush; the runner resolves to the committed
188
+ * copy. A bare `defineFactory(fn)` declares no Result, so `fn` must return nothing.
167
189
  * @param options.packageFiles - the package-files adapter the two reads go through; every
168
190
  * caller passes it with `packageDir`.
169
191
  * @param options.packageDir - opts into schema-derived input validation and reserved-name
@@ -195,22 +217,41 @@ function checkReservedNames(pkg) {
195
217
  *
196
218
  * const runner = defineFactory<Input>(bareFactory, { packageDir: import.meta.dir });
197
219
  * await runner(input, { client });
220
+ *
221
+ * The returned runner takes, besides the client, the `role` and the qualified `name` of the
222
+ * schematic it runs, as the caller received them (CA-19). With the role `evaluation`, `fn`
223
+ * returns its Findings, checked against the shape the role imposes, each finding's `source` is
224
+ * set to `name`, and `fn` receives the scope inputs `include` and `exclude`; every `glob` result
225
+ * is narrowed to the scope and so is every finding with a path (A-120 to A-124). Any other role,
226
+ * or none, runs as a generator.
198
227
  */
199
228
  export function defineFactory(fn, options) {
200
- const wrapped = async (o, { client }) => {
229
+ const wrapped = async (o, { client, role, name }) => {
230
+ if (role === "evaluation" && name === undefined) {
231
+ throw new Error("defineFactory: an evaluation factory needs the qualified name collection:schematic of the schematic");
232
+ }
233
+ const source = role === "evaluation" ? name : undefined;
201
234
  let packageAnchors;
202
235
  let packageFiles;
236
+ let schema;
237
+ let inScope;
238
+ if (source !== undefined) {
239
+ const scope = scopeOf(o);
240
+ if ("problem" in scope)
241
+ throw rejectionForScopeInput(scope.problem);
242
+ inScope = scope.inScope;
243
+ }
203
244
  if (options?.packageDir !== undefined) {
204
245
  const pkg = { files: options.packageFiles, dir: resolvePackageDir(options.packageDir) };
205
246
  // REQ-RBV-06: exactly TWO reads, in this order — reserved-name check, then schema
206
247
  // validation. No third (containment-ceiling) read exists (ADR-0077 §C).
207
248
  checkReservedNames(pkg);
208
- validateAtRunBoundary(pkg, o);
249
+ schema = validateAtRunBoundary(pkg, o, source === undefined ? [] : SCOPE_INPUTS);
209
250
  packageAnchors = { packageDir: pkg.dir };
210
251
  packageFiles = pkg.files;
211
252
  }
212
253
  const ctx = {
213
- session: new Session(client),
254
+ session: new Session(client, inScope),
214
255
  factory: new DirectiveFactory(),
215
256
  dialects: new DialectRegistryImpl(),
216
257
  packageAnchors,
@@ -225,11 +266,17 @@ export function defineFactory(fn, options) {
225
266
  // unawaited dialect chain (forgotten `await`) still completes and commits; a drain
226
267
  // rejection (an unawaited chain that threw) routes through the SAME catch below as a
227
268
  // flush rejection already does.
269
+ //
270
+ // A-14: the Result is checked after the drain and before the final flush, so an invalid
271
+ // one takes the discard path below and nothing is written. A bare factory, or one with no `result` in its schema,
272
+ // declares none and must return nothing; the commit then carries no Result.
228
273
  try {
229
- await getSessionAls().run(ctx, () => fn(o));
274
+ const returned = await getSessionAls().run(ctx, () => fn(o));
230
275
  await ctx.dialects.drain();
276
+ const result = handOn(source === undefined ? schema?.result : SOURCED_FINDINGS, returned, source, inScope);
231
277
  await ctx.session.flush();
232
- await ctx.session.commit();
278
+ await ctx.session.commit(result);
279
+ return result;
233
280
  }
234
281
  catch (thrown) {
235
282
  // A thrown `undefined` or `null` would read as success to anyone testing the error.
@@ -2,13 +2,15 @@ import type { EngineClient } from "../../ports/engine-client.ts";
2
2
  import type { Directive } from "../../valueobjects/wire.ts";
3
3
  export declare class Session {
4
4
  #private;
5
- constructor(client: EngineClient);
5
+ /** `inScope`, when given, narrows every listing to the paths it keeps (A-123). */
6
+ constructor(client: EngineClient, inScope?: (path: string) => boolean);
6
7
  buffer(directive: Directive): void;
7
8
  versionOf(path: string): number;
8
9
  pendingDirectives(): readonly Directive[];
9
10
  isPending(directive: Directive): boolean;
10
11
  read(path: string): Promise<string | undefined>;
11
- commit(): Promise<void>;
12
+ list(pattern: string, ignore?: readonly string[]): Promise<readonly string[]>;
13
+ commit(result?: unknown): Promise<void>;
12
14
  discard(): Promise<void>;
13
15
  flush(): Promise<void>;
14
16
  }
@@ -43,8 +43,11 @@ export class Session {
43
43
  // The batches being emitted, so a read or a later flush never overtakes them.
44
44
  #emitting = Promise.resolve();
45
45
  #inFlight = 0;
46
- constructor(client) {
46
+ #inScope;
47
+ /** `inScope`, when given, narrows every listing to the paths it keeps (A-123). */
48
+ constructor(client, inScope) {
47
49
  this.#client = client;
50
+ this.#inScope = inScope;
48
51
  }
49
52
  buffer(directive) {
50
53
  this.#pending.push(directive);
@@ -70,10 +73,16 @@ export class Session {
70
73
  await this.flush();
71
74
  return this.#client.read(path);
72
75
  }
76
+ // A-131: like read(), a listing flushes first, so it sees every write buffered before it.
77
+ async list(pattern, ignore) {
78
+ await this.flush();
79
+ const paths = await this.#client.list(pattern, ignore);
80
+ return this.#inScope === undefined ? paths : paths.filter(this.#inScope);
81
+ }
73
82
  // SEAM-03 (ADR-01): thin wrappers delegating to #client. Session owns #client, so the
74
83
  // commit boundary stays inside Session — defineFactory never names #client directly.
75
- async commit() {
76
- await this.#client.commit();
84
+ async commit(result) {
85
+ await this.#client.commit(result);
77
86
  }
78
87
  async discard() {
79
88
  await this.#client.discard();
@@ -2,6 +2,7 @@ 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
+ list(pattern: string, ignore?: readonly string[]): Promise<readonly string[]>;
6
+ commit(result?: unknown): Promise<void>;
6
7
  discard(): Promise<void>;
7
8
  }
@@ -59,12 +59,27 @@ export type Handle<State extends "found" | "writable" = "found", Ast = any, Ops
59
59
  } & OpMethods<Ast, Ops> & (State extends "found" ? {
60
60
  remove(): void;
61
61
  } : {}) & PromiseLike<void>;
62
+ /**
63
+ * The options of `glob`: the patterns of the files to leave out (A-130).
64
+ *
65
+ * @example
66
+ * const options: GlobOptions = { ignore: ["**\/*.test.ts", "src/generated/**"] };
67
+ */
68
+ export interface GlobOptions {
69
+ ignore?: readonly string[];
70
+ }
62
71
  export interface Dialect<Ast = any, Ops extends OpPack<Ast> = OpPack<Ast>> {
63
72
  readonly name?: string;
64
73
  readonly extensions: readonly string[];
65
74
  readonly ast: DialectAst<Ast>;
66
75
  readonly ops: Ops;
67
76
  find(path: string): Handle<"found", Ast, Ops>;
77
+ /**
78
+ * Opens every file `pattern` matches whose extension the dialect declares, ordered by path; a
79
+ * file of any other extension is left out without an error (A-132). Resolves `[]` when none
80
+ * matches. The pattern syntax and `ignore` are commons `glob`'s.
81
+ */
82
+ glob(pattern: string, options?: GlobOptions): Promise<Handle<"found", Ast, Ops>[]>;
68
83
  }
69
84
  /**
70
85
  * Declares a named collection of ops over one AST type — usable standalone (REQ-DG-02.3),
@@ -156,16 +171,28 @@ type DialectsByExtension = {
156
171
  readonly [extension: string]: Dialect;
157
172
  };
158
173
  type HandleOf<D> = D extends Dialect<infer A, infer O> ? Handle<"found", A, O> : never;
174
+ type RouteHandle<M extends DialectsByExtension, K extends keyof M & string> = {
175
+ [Key in K]: HandleOf<M[Key]> & {
176
+ readonly extension: Key;
177
+ };
178
+ }[K];
159
179
  type MatchingKey<M, P extends string> = {
160
180
  [K in keyof M & string]: P extends `${string}${K}` ? K : never;
161
181
  }[keyof M & string];
162
182
  type LongestKey<Ks extends string> = {
163
183
  [K in Ks]: [Extract<Exclude<Ks, K>, `${string}${K}`>] extends [never] ? K : never;
164
184
  }[Ks];
165
- type RoutedHandle<M extends DialectsByExtension, P extends string> = string extends P ? HandleOf<M[keyof M]> : HandleOf<M[LongestKey<MatchingKey<M, P>>]>;
185
+ type RoutedHandle<M extends DialectsByExtension, P extends string> = string extends P ? RouteHandle<M, keyof M & string> : RouteHandle<M, LongestKey<MatchingKey<M, P>>>;
186
+ type GlobbedHandle<M extends DialectsByExtension, P extends string> = [LongestKey<MatchingKey<M, P>>] extends [never] ? RouteHandle<M, keyof M & string> : RoutedHandle<M, P>;
166
187
  export interface ExtensionRouter<M extends DialectsByExtension> {
167
188
  readonly extensions: readonly (keyof M & string)[];
168
189
  find<P extends string>(path: P): RoutedHandle<M, P>;
190
+ /**
191
+ * Opens every file `pattern` matches that a route takes, ordered by path, each through the
192
+ * dialect of its longest matching extension (A-133); other files are left out without an
193
+ * error. Each handle carries its route's key as `extension`.
194
+ */
195
+ glob<P extends string>(pattern: P, options?: GlobOptions): Promise<GlobbedHandle<M, P>[]>;
169
196
  }
170
197
  /**
171
198
  * Routes `find` by file extension to one dialect per extension, each with its own AST and ops —
@@ -13,8 +13,13 @@
13
13
  // "don't care about the concrete Ast" erasure this bare form needs.
14
14
  import { basename } from "node:path";
15
15
  import { createDialectHandle } from "../entities/dialect-handle.js";
16
+ import { currentRun } from "./run-context.js";
16
17
  import { dialectError } from "../valueobjects/dialect-error.js";
17
18
  export { query } from "../entities/dialect-handle.js";
19
+ /** The paths a `glob` of the active run lists, after the run's buffered writes (A-131). */
20
+ function listed(pattern, options) {
21
+ return currentRun().session.list(pattern, options?.ignore);
22
+ }
18
23
  /**
19
24
  * Declares a named collection of ops over one AST type — usable standalone (REQ-DG-02.3),
20
25
  * e.g. shareable across two dialects targeting the same AST type, before any `withOps`
@@ -54,7 +59,7 @@ export function defineDialect(d) {
54
59
  // The handle spreads its ops over its verbs, so an op named after a verb would replace it.
55
60
  for (const name of Object.keys(d.ops))
56
61
  assertNotReserved(name);
57
- return {
62
+ const dialect = {
58
63
  name: d.name,
59
64
  extensions: d.extensions,
60
65
  ast: d.ast,
@@ -65,7 +70,13 @@ export function defineDialect(d) {
65
70
  }
66
71
  return createDialectHandle(d.ast, d.ops, path, d.name);
67
72
  },
73
+ // A-133: written once here, so every dialect built from a descriptor has it.
74
+ async glob(pattern, options) {
75
+ const paths = await listed(pattern, options);
76
+ return paths.filter((path) => hasDeclaredExtension(path, d.extensions)).map((path) => dialect.find(path));
77
+ },
68
78
  };
79
+ return dialect;
69
80
  }
70
81
  /**
71
82
  * Defines an author-defined dialect, named by the package that ships it (A-16): a factory opens
@@ -209,16 +220,29 @@ export function byExtension(dialects) {
209
220
  if (!declared.includes(extension)) {
210
221
  throw new Error(`dialect routing failed: "${extension}" is not an extension its dialect declares (${declared.join(", ")}).`);
211
222
  }
223
+ // A-134: the routing key is set as `extension` on every handle, over any op of that name.
224
+ if (Object.hasOwn(dialects[extension].ops, "extension")) {
225
+ throw new Error(`dialect routing failed: the dialect of "${extension}" has an op named "extension", the field that carries the routing key on its handles.`);
226
+ }
212
227
  }
213
228
  const longestFirst = [...extensions].sort((a, b) => b.length - a.length);
229
+ const routeOf = (path) => longestFirst.find((candidate) => hasDeclaredExtension(path, [candidate]));
230
+ const open = (path, extension) => Object.assign(dialects[extension].find(path), { extension });
214
231
  return {
215
232
  extensions,
216
233
  find(path) {
217
- const extension = longestFirst.find((candidate) => hasDeclaredExtension(path, [candidate]));
234
+ const extension = routeOf(path);
218
235
  if (extension === undefined) {
219
236
  throw dialectError(`find(${JSON.stringify(path)}) — the file's extension is not one this dialect declares (${extensions.join(", ")}).`);
220
237
  }
221
- return dialects[extension].find(path);
238
+ return open(path, extension);
239
+ },
240
+ async glob(pattern, options) {
241
+ const paths = await listed(pattern, options);
242
+ return paths.flatMap((path) => {
243
+ const extension = routeOf(path);
244
+ return extension === undefined ? [] : [open(path, extension)];
245
+ });
222
246
  },
223
247
  };
224
248
  }
@@ -0,0 +1,29 @@
1
+ /** Whether a workspace-relative path is in the scope. */
2
+ export type InScope = (path: string) => boolean;
3
+ /**
4
+ * The scope `include` less `exclude` names, or no scope when neither is given. A problem names the
5
+ * scope input that is not an array of strings.
6
+ */
7
+ export declare function scopeOf(input: unknown): {
8
+ readonly inScope?: InScope;
9
+ } | {
10
+ readonly problem: string;
11
+ };
12
+ type Finding = {
13
+ [key: string]: unknown;
14
+ };
15
+ /**
16
+ * The Findings a factory returned, already checked against SOURCED_FINDINGS: each kept finding
17
+ * gets `source`, and one whose `path` falls outside the scope is dropped. A problem names the first
18
+ * finding whose author set `source`.
19
+ */
20
+ export declare function handedOnFindings(findings: {
21
+ readonly items: readonly Finding[];
22
+ }, source: string, inScope: InScope | undefined): {
23
+ readonly result: {
24
+ items: Finding[];
25
+ };
26
+ } | {
27
+ readonly problem: string;
28
+ };
29
+ export {};
@@ -0,0 +1,43 @@
1
+ // The run-boundary side of the role `evaluation`: the scope its inputs name (A-122, A-123) and
2
+ // the Findings it hands on, each with the `source` the SDK sets (A-121) and inside the scope (A-124).
3
+ import { isPlainObject } from "../valueobjects/schema-model.js";
4
+ import { globMatcher } from "./glob-match.js";
5
+ function globsOf(record, name) {
6
+ const value = Object.hasOwn(record, name) ? record[name] : undefined;
7
+ if (value === undefined)
8
+ return undefined;
9
+ if (!Array.isArray(value) || !value.every((entry) => typeof entry === "string")) {
10
+ return `invalid input: ${name} must be an array of strings`;
11
+ }
12
+ return value.map(globMatcher);
13
+ }
14
+ /**
15
+ * The scope `include` less `exclude` names, or no scope when neither is given. A problem names the
16
+ * scope input that is not an array of strings.
17
+ */
18
+ export function scopeOf(input) {
19
+ const record = isPlainObject(input) ? input : {};
20
+ const include = globsOf(record, "include");
21
+ if (typeof include === "string")
22
+ return { problem: include };
23
+ const exclude = globsOf(record, "exclude");
24
+ if (typeof exclude === "string")
25
+ return { problem: exclude };
26
+ if (include === undefined && exclude === undefined)
27
+ return {};
28
+ return {
29
+ inScope: (path) => (include === undefined || include.some((matches) => matches(path))) && !(exclude ?? []).some((matches) => matches(path)),
30
+ };
31
+ }
32
+ /**
33
+ * The Findings a factory returned, already checked against SOURCED_FINDINGS: each kept finding
34
+ * gets `source`, and one whose `path` falls outside the scope is dropped. A problem names the first
35
+ * finding whose author set `source`.
36
+ */
37
+ export function handedOnFindings(findings, source, inScope) {
38
+ const sourced = findings.items.findIndex((finding) => Object.hasOwn(finding, "source"));
39
+ if (sourced !== -1)
40
+ return { problem: `Result.items[${sourced}].source is set by the SDK, and a finding may not set it` };
41
+ const kept = findings.items.filter((finding) => inScope === undefined || typeof finding.path !== "string" || inScope(finding.path));
42
+ return { result: { items: kept.map((finding) => ({ ...finding, source })) } };
43
+ }
@@ -0,0 +1,4 @@
1
+ /** Every brace-free pattern `{a,b}` groups stand for. A `{` with no closing `}` is literal. */
2
+ export declare function alternatives(pattern: string): string[];
3
+ /** Whether a workspace-relative path matches `pattern`. */
4
+ export declare function globMatcher(pattern: string): (path: string) => boolean;
@@ -0,0 +1,81 @@
1
+ // Glob matching as the engine's `tree.list` matches (E-37, engine ADR-0070): `*` is any run of
2
+ // characters in one segment, `?` one character, `**` as a whole segment any number of segments,
3
+ // zero included, and `{a,b}` either alternative, nested groups included. Every other character is
4
+ // literal, so there is no negation and no class.
5
+ /** Every brace-free pattern `{a,b}` groups stand for. A `{` with no closing `}` is literal. */
6
+ export function alternatives(pattern) {
7
+ const open = pattern.indexOf("{");
8
+ if (open === -1)
9
+ return [pattern];
10
+ const commas = [];
11
+ let depth = 0;
12
+ for (let i = open; i < pattern.length; i++) {
13
+ const char = pattern[i];
14
+ if (char === "{")
15
+ depth++;
16
+ else if (char === "," && depth === 1)
17
+ commas.push(i);
18
+ else if (char === "}" && --depth === 0) {
19
+ const bounds = [open, ...commas, i];
20
+ const rest = pattern.slice(i + 1);
21
+ return bounds
22
+ .slice(1)
23
+ .flatMap((end, k) => alternatives(pattern.slice(0, open) + pattern.slice(bounds[k] + 1, end) + rest));
24
+ }
25
+ }
26
+ return alternatives(pattern.slice(open + 1)).map((tail) => pattern.slice(0, open + 1) + tail);
27
+ }
28
+ // Matched without RegExp, which the runner closure does not admit (Constraint 4).
29
+ // `*` is any run of characters in one segment and `?` one character, by backtracking on the last `*`.
30
+ function segmentMatches(pattern, text) {
31
+ let p = 0;
32
+ let t = 0;
33
+ let star = -1;
34
+ let mark = 0;
35
+ while (t < text.length) {
36
+ if (p < pattern.length && pattern[p] === "*") {
37
+ star = p++;
38
+ mark = t;
39
+ }
40
+ else if (p < pattern.length && (pattern[p] === "?" || pattern[p] === text[t])) {
41
+ p++;
42
+ t++;
43
+ }
44
+ else if (star !== -1) {
45
+ p = star + 1;
46
+ t = ++mark;
47
+ }
48
+ else {
49
+ return false;
50
+ }
51
+ }
52
+ while (pattern[p] === "*")
53
+ p++;
54
+ return p === pattern.length;
55
+ }
56
+ // A `**` segment matches any number of segments, zero included; as the last segment it matches
57
+ // the rest of the path, so it needs at least one more segment there.
58
+ function segmentsMatch(pattern, path, i, j) {
59
+ if (i === pattern.length)
60
+ return j === path.length;
61
+ const segment = pattern[i];
62
+ if (segment !== "**")
63
+ return j < path.length && segmentMatches(segment, path[j]) && segmentsMatch(pattern, path, i + 1, j + 1);
64
+ if (i === pattern.length - 1)
65
+ return j < path.length;
66
+ for (let k = j; k <= path.length; k++) {
67
+ if (k > j && path[k - 1] === "")
68
+ return false;
69
+ if (segmentsMatch(pattern, path, i + 1, k))
70
+ return true;
71
+ }
72
+ return false;
73
+ }
74
+ /** Whether a workspace-relative path matches `pattern`. */
75
+ export function globMatcher(pattern) {
76
+ const compiled = alternatives(pattern).map((alternative) => alternative.split("/"));
77
+ return (path) => {
78
+ const segments = path.split("/");
79
+ return compiled.some((alternative) => segmentsMatch(alternative, segments, 0, 0));
80
+ };
81
+ }
@@ -2,3 +2,5 @@ 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;
6
+ export declare function rejectionForScopeInput(problem: string): AuthoringError;
@@ -30,3 +30,11 @@ 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
+ }
37
+ // A-122: a scope input of an evaluation factory that is not an array of strings.
38
+ export function rejectionForScopeInput(problem) {
39
+ return rejection("invalid-input", problem);
40
+ }
@@ -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;
@@ -11,4 +11,20 @@ export type ValidationFinding = {
11
11
  kind: "disallowed-key";
12
12
  field: string;
13
13
  };
14
- export declare function validateInput(schema: Schema, input: unknown): ValidationFinding[];
14
+ /** `imposed` names the inputs a role adds, which `schema.json` never declares (A-122). */
15
+ export declare function validateInput(schema: Schema, input: unknown, imposed?: readonly string[]): ValidationFinding[];
16
+ /** E-40: the largest JSON encoding of a Result, in UTF-8 bytes; exactly at it is allowed. */
17
+ export declare const RESULT_CEILING_BYTES = 1048576;
18
+ export type ResultCheck = {
19
+ readonly result: unknown;
20
+ } | {
21
+ readonly problem: string;
22
+ };
23
+ /**
24
+ * Checks `value` as the Result of a factory whose declaration is `declared`. Without a
25
+ * declaration only `undefined`, no Result, passes. A Result that passes comes back as a copy
26
+ * parsed from its JSON encoding, so what is committed is exactly what was checked. The
27
+ * declaration is a parameter so a Result shape a role imposes can be checked the same way as
28
+ * one read from `schema.json`.
29
+ */
30
+ export declare function checkResult(declared: ResultSchema | undefined, value: unknown): ResultCheck;