@pbuilder/sdk 0.19.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 (67) hide show
  1. package/README.md +46 -3
  2. package/dist/acl/irwire/stdio-engine-client.d.ts +1 -0
  3. package/dist/acl/irwire/stdio-engine-client.js +9 -0
  4. package/dist/bin/pbuilder-codegen.js +90 -18
  5. package/dist/bounded-contexts/authoring/application/usecases/authoring-verbs/index.d.ts +15 -0
  6. package/dist/bounded-contexts/authoring/application/usecases/authoring-verbs/index.js +17 -0
  7. package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.d.ts +16 -3
  8. package/dist/bounded-contexts/authoring/application/usecases/run-factory/context.js +45 -11
  9. package/dist/bounded-contexts/authoring/domain/aggregates/session/session.d.ts +3 -1
  10. package/dist/bounded-contexts/authoring/domain/aggregates/session/session.js +10 -1
  11. package/dist/bounded-contexts/authoring/domain/ports/engine-client.d.ts +1 -0
  12. package/dist/bounded-contexts/authoring/domain/services/define-dialect.d.ts +28 -1
  13. package/dist/bounded-contexts/authoring/domain/services/define-dialect.js +27 -3
  14. package/dist/bounded-contexts/authoring/domain/services/evaluation.d.ts +29 -0
  15. package/dist/bounded-contexts/authoring/domain/services/evaluation.js +43 -0
  16. package/dist/bounded-contexts/authoring/domain/services/glob-match.d.ts +4 -0
  17. package/dist/bounded-contexts/authoring/domain/services/glob-match.js +81 -0
  18. package/dist/bounded-contexts/authoring/domain/services/schema/input-rejection.d.ts +1 -0
  19. package/dist/bounded-contexts/authoring/domain/services/schema/input-rejection.js +4 -0
  20. package/dist/bounded-contexts/authoring/domain/services/schema/schema-validate.d.ts +2 -1
  21. package/dist/bounded-contexts/authoring/domain/services/schema/schema-validate.js +6 -2
  22. package/dist/bounded-contexts/authoring/domain/valueobjects/findings.d.ts +12 -0
  23. package/dist/bounded-contexts/authoring/domain/valueobjects/findings.js +57 -0
  24. package/dist/bounded-contexts/authoring/domain/valueobjects/schema-model.d.ts +2 -0
  25. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/cli.d.ts +7 -2
  26. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/cli.js +28 -7
  27. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/emit-type.d.ts +6 -2
  28. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/emit-type.js +23 -13
  29. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/project-codegen.d.ts +1 -0
  30. package/dist/bounded-contexts/authoring/infrastructure/in/codegen/project-codegen.js +5 -2
  31. package/dist/bounded-contexts/authoring/infrastructure/in/commons/index.d.ts +2 -1
  32. package/dist/bounded-contexts/authoring/infrastructure/in/commons/index.js +1 -1
  33. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/angular/index.d.ts +14 -1
  34. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/angular/index.js +15 -0
  35. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.d.ts +14 -1
  36. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/aspnet/index.js +15 -0
  37. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/index.d.ts +14 -1
  38. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/csharp/index.js +15 -0
  39. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/css/index.d.ts +14 -1
  40. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/css/index.js +15 -0
  41. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/json/index.d.ts +14 -1
  42. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/json/index.js +15 -0
  43. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.d.ts +14 -1
  44. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/msbuild/index.js +15 -0
  45. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/nestjs/index.d.ts +14 -1
  46. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/nestjs/index.js +15 -0
  47. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/index.d.ts +14 -1
  48. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/react/index.js +15 -0
  49. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/index.d.ts +14 -1
  50. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/typescript/index.js +15 -0
  51. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/yaml/index.d.ts +14 -1
  52. package/dist/bounded-contexts/authoring/infrastructure/out/dialects/yaml/index.js +15 -0
  53. package/dist/bounded-contexts/authoring/testing/contract-fake.d.ts +1 -0
  54. package/dist/bounded-contexts/authoring/testing/contract-fake.js +8 -0
  55. package/dist/bounded-contexts/authoring/testing/glob-pattern.d.ts +5 -0
  56. package/dist/bounded-contexts/authoring/testing/glob-pattern.js +20 -0
  57. package/dist/bounded-contexts/authoring/testing/harness/index.d.ts +8 -0
  58. package/dist/bounded-contexts/authoring/testing/harness/index.js +12 -1
  59. package/dist/bounded-contexts/authoring/testing/run-vehicle.d.ts +1 -0
  60. package/dist/bounded-contexts/authoring/testing/run-vehicle.js +4 -0
  61. package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.d.ts +3 -0
  62. package/dist/bounded-contexts/runner-hosting/infrastructure/in/bootstrap-bridge.js +4 -0
  63. package/dist/bounded-contexts/runner-hosting/infrastructure/in/runner.js +15 -3
  64. package/dist/runner-manifest.json +33 -9
  65. package/dist/shared-kernel/wire-protocol.d.ts +1 -1
  66. package/dist/shared-kernel/wire-protocol.js +1 -1
  67. package/package.json +1 -1
package/README.md CHANGED
@@ -258,6 +258,41 @@ cycles, `undefined` or non-finite numbers. Its JSON encoding may take at most 1
258
258
  fails, the run fails with an `AuthoringError` whose reason is `invalid-result`, and nothing
259
259
  is written. A declared `null` is a Result and is returned as `null`.
260
260
 
261
+ ## Evaluation schematics
262
+
263
+ A schematic whose Collection definition entry declares `"role": "evaluation"` reads the
264
+ workspace and returns `Findings`, which the role fixes as its Result (A-120). It declares no
265
+ `result` in `schema.json`, and no input named `include` or `exclude`; codegen refuses either.
266
+ Codegen reads the role only in project mode (`pbuilder-codegen` or `--project`), since a single
267
+ directory has no Collection definition entry. For an evaluation schematic it emits `Findings`
268
+ as the `Result` type, and adds the scope inputs `include` and `exclude`, arrays of globs, to
269
+ `Input` (A-122):
270
+
271
+ ```ts
272
+ import type { Input, Result } from "./schema.generated.ts";
273
+ import { glob } from "@pbuilder/sdk/commons";
274
+
275
+ export default async (input: Input): Promise<Result> => {
276
+ const routes = await glob("src/**/route.ts");
277
+ return {
278
+ items: routes.length > 0 ? [] : [{ rule: "route-missing", message: "no route file", severity: "error" }],
279
+ };
280
+ };
281
+ ```
282
+
283
+ A finding has `rule`, `message` and `severity` (`error` or `warning`), and may have a
284
+ workspace-relative `path`, a 1-based `range` (`{ start: { line, column }, end? }`) and a `fix`
285
+ (`{ schematic: "collection:schematic", inputs? }`). The SDK checks the returned value against
286
+ that shape as it checks any Result, then sets each finding's `source` to the schematic's
287
+ qualified name. A finding that sets `source` itself fails the run with `invalid-result` (A-121).
288
+
289
+ The scope is what `include` names, less what `exclude` names; `exclude` alone keeps every file
290
+ it does not name, and with neither nothing is narrowed. Every `glob` result, from commons or a
291
+ Dialect, is narrowed to the scope (A-123), and a finding whose `path` falls outside it is dropped
292
+ before the Result leaves the schematic (A-124). A finding without `path` is always kept. `find`
293
+ is not narrowed, so a check can read the files it compares against (A-125). Every verb a
294
+ generator has is offered as well; the engine discards an evaluation Frame's edits (A-126).
295
+
261
296
  ## Project-wide type generation
262
297
 
263
298
  ```sh
@@ -277,7 +312,7 @@ Two registration forms are supported:
277
312
  ```json
278
313
  {
279
314
  "collections": {
280
- "local": { "hello": { "path": "./schematics/hello" } },
315
+ "local": { "hello": { "path": "./schematics/hello" }, "check": { "path": "./schematics/check", "role": "evaluation" } },
281
316
  "shared": { "path": "./schematics/collection.json" }
282
317
  }
283
318
  }
@@ -352,10 +387,13 @@ The verbs that write to a new path — `create`, `rename`, `move`, `copy`, `copy
352
387
  overwrite: `create` and `scaffold` inside their options/args object, the rest as a
353
388
  trailing argument.
354
389
 
355
- Three companions round out the surface:
390
+ Four companions round out the surface:
356
391
 
357
392
  - [`find(path).read()`](./docs/guides/authoring-verbs.md#the-read-trichotomy-findpathread) — read
358
393
  a file back from the staging tree.
394
+ - [`glob(pattern, { ignore })`](./docs/guides/authoring-verbs.md#many-files-at-once-globpattern--ignore-)
395
+ resolves a handle for every file the pattern matches, ordered by path, or `[]` when none
396
+ does. Every dialect has its own `glob`, which keeps the files of the extensions it declares.
359
397
  - [`scaffold({ from, to, options })`](./docs/guides/authoring-verbs.md#scaffold) — mirror an
360
398
  entire package-local folder into the tree, with dynamic file names. The workhorse for
361
399
  multi-file generators — see [Scaffolding a folder of templates](#scaffolding-a-folder-of-templates).
@@ -597,6 +635,10 @@ Three things to know:
597
635
  against the `result` its `schema.json` declares (see [Returning a Result](#returning-a-result)).
598
636
  It is `undefined` when the factory declares none or the run failed.
599
637
 
638
+ - `role: "evaluation"` with `name: "collection:schematic"` runs the factory as an
639
+ [evaluation schematic](#evaluation-schematics): `result.result` holds its Findings with their
640
+ `source`, narrowed to the scope of the `include` and `exclude` inputs.
641
+
600
642
  - `result.reads` counts the reads the engine served for each path, so a test can check
601
643
  that the factory reads a file once however many ops it chains on it. A path the factory
602
644
  never read is absent.
@@ -625,7 +667,8 @@ ship today: `@pbuilder/sdk/typescript`, `@pbuilder/sdk/react`, `@pbuilder/sdk/ne
625
667
  A dialect's entry point is its own `find(path)`: it opens a **coalescing, awaitable
626
668
  handle**. Every op you chain mutates the same live AST, and the handle serializes to
627
669
  exactly **one** `replaceContent`-style directive when it flushes — chaining three ops does
628
- not produce three writes.
670
+ not produce three writes. Its `glob(pattern, { ignore })` opens every matching file of the
671
+ dialect's extensions the same way.
629
672
 
630
673
  ### `@pbuilder/sdk/typescript`
631
674
 
@@ -22,6 +22,7 @@ export declare class StdioEngineClient implements EngineClient {
22
22
  });
23
23
  emit(batch: Batch): Promise<void>;
24
24
  read(path: string): Promise<string | undefined>;
25
+ list(pattern: string, ignore?: readonly string[]): Promise<readonly string[]>;
25
26
  commit(result?: unknown): Promise<void>;
26
27
  discard(): Promise<void>;
27
28
  }
@@ -228,6 +228,15 @@ export class StdioEngineClient {
228
228
  return undefined;
229
229
  return result.content;
230
230
  }
231
+ // ADR-0070 (engine): `ignore` is optional on the wire, so it is sent only when given. A host
232
+ // rejection, such as a pattern that escapes the workspace, throws as a read's does.
233
+ async list(pattern, ignore) {
234
+ const response = await this.#call("tree.list", ignore === undefined ? { pattern } : { pattern, ignore });
235
+ if (response.error !== undefined) {
236
+ throw new IntentRejectedError(response.error.message);
237
+ }
238
+ return response.result.paths;
239
+ }
231
240
  // A-14: the Result rides in the ir.commit params, the key present only when one is declared.
232
241
  async commit(result) {
233
242
  const response = await this.#call("ir.commit", result === undefined ? {} : { result });
@@ -351,6 +351,57 @@ function isErrnoException(err) {
351
351
  return err instanceof Error && "code" in err;
352
352
  }
353
353
 
354
+ // src/bounded-contexts/authoring/domain/valueobjects/findings.ts
355
+ var SCOPE_INPUTS = ["include", "exclude"];
356
+ var STRING = { types: ["string"] };
357
+ var NUMBER = { types: ["number"] };
358
+ var POSITION = {
359
+ types: ["object"],
360
+ properties: [
361
+ { key: "line", schema: NUMBER },
362
+ { key: "column", schema: NUMBER }
363
+ ],
364
+ required: ["line", "column"]
365
+ };
366
+ function findingsWith(extra) {
367
+ const finding = {
368
+ types: ["object"],
369
+ properties: [
370
+ { key: "rule", schema: STRING },
371
+ { key: "message", schema: STRING },
372
+ { key: "severity", schema: { types: ["string"], choices: ["error", "warning"] } },
373
+ { key: "path", schema: STRING },
374
+ {
375
+ key: "range",
376
+ schema: {
377
+ types: ["object"],
378
+ properties: [
379
+ { key: "start", schema: POSITION },
380
+ { key: "end", schema: POSITION }
381
+ ],
382
+ required: ["start"]
383
+ }
384
+ },
385
+ {
386
+ key: "fix",
387
+ schema: {
388
+ types: ["object"],
389
+ properties: [
390
+ { key: "schematic", schema: STRING },
391
+ { key: "inputs", schema: { types: ["object"] } }
392
+ ],
393
+ required: ["schematic"]
394
+ }
395
+ },
396
+ ...extra
397
+ ],
398
+ required: ["rule", "message", "severity"]
399
+ };
400
+ return { types: ["object"], properties: [{ key: "items", schema: { types: ["array"], items: finding } }], required: ["items"] };
401
+ }
402
+ var FINDINGS = findingsWith([]);
403
+ var SOURCED_FINDINGS = findingsWith([{ key: "source", schema: STRING }]);
404
+
354
405
  // src/bounded-contexts/authoring/infrastructure/in/codegen/emit-type.ts
355
406
  var GENERATED_HEADER = "// AUTO-GENERATED by pbuilder-codegen — do not edit. Regenerate: pbuilder-codegen <package-dir>";
356
407
  var IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/;
@@ -399,24 +450,24 @@ function emitResult(result) {
399
450
  const members = result.properties.map(({ key, schema }) => `${emitPropertyKey(key)}${required.has(key) ? "" : "?"}: ${emitResult(schema)}`);
400
451
  return members.length === 0 ? "Record<string, never>" : `{ ${members.join("; ")} }`;
401
452
  }
453
+ case "string":
454
+ return result.choices === undefined ? kind : result.choices.map((choice) => JSON.stringify(choice)).join(" | ");
402
455
  default:
403
456
  return kind;
404
457
  }
405
458
  }).join(" | ");
406
459
  }
407
- function emitInputType(schema, digest) {
408
- const members = schema.properties.map(emitProperty).join(`
460
+ var SCOPE_MEMBERS = [
461
+ " /** Globs or literal paths to check */",
462
+ " include?: string[];",
463
+ " /** Globs or literal paths to skip */",
464
+ " exclude?: string[];"
465
+ ];
466
+ function emitInputType(schema, digest, evaluation = false) {
467
+ const members = [...schema.properties.map(emitProperty), ...evaluation ? SCOPE_MEMBERS : []].join(`
409
468
  `);
410
- return [
411
- GENERATED_HEADER,
412
- `// @schema-digest sha256:${digest}`,
413
- "",
414
- "export type Input = {",
415
- members,
416
- "};",
417
- ...schema.result === undefined ? [] : ["", `export type Result = ${emitResult(schema.result)};`],
418
- ""
419
- ].join(`
469
+ const result = evaluation ? ["", `export type Findings = ${emitResult(FINDINGS)};`, "", "export type Result = Findings;"] : schema.result === undefined ? [] : ["", `export type Result = ${emitResult(schema.result)};`];
470
+ return [GENERATED_HEADER, `// @schema-digest sha256:${digest}`, "", "export type Input = {", members, "};", ...result, ""].join(`
420
471
  `);
421
472
  }
422
473
 
@@ -431,6 +482,9 @@ function readObject(path) {
431
482
  throw new Error("invalid object");
432
483
  return value;
433
484
  }
485
+ function isEvaluation(registration) {
486
+ return isPlainObject(registration) && registration.role === "evaluation";
487
+ }
434
488
  function discoverProject(directory) {
435
489
  let selected = resolve(directory ?? process.cwd());
436
490
  if (directory === undefined) {
@@ -494,7 +548,7 @@ function discoverProject(directory) {
494
548
  try {
495
549
  if (!statSync(module).isFile())
496
550
  throw new Error("nonregular module");
497
- entries.push({ kind: "target", label, directory: dirname(realpathSync(module)) });
551
+ entries.push({ kind: "target", label, directory: dirname(realpathSync(module)), evaluation: isEvaluation(registration) });
498
552
  } catch {
499
553
  entries.push({ kind: "failure", label, diagnostic: `cannot resolve factory module ${JSON.stringify(module)}` });
500
554
  }
@@ -535,7 +589,7 @@ function discoverProject(directory) {
535
589
  }
536
590
  if (factories !== 1)
537
591
  throw new Error("ambiguous or missing factory");
538
- entries.push({ kind: "target", label, directory: realpathSync(path) });
592
+ entries.push({ kind: "target", label, directory: realpathSync(path), evaluation: isEvaluation(registration) });
539
593
  } catch {
540
594
  entries.push({ kind: "failure", label, diagnostic: `directory requires exactly one regular factory.ts or factory.js: ${JSON.stringify(path)}` });
541
595
  }
@@ -563,6 +617,22 @@ class SchemaSufficiencyFailure extends Error {
563
617
  }
564
618
  }
565
619
 
620
+ class RoleContractFailure extends Error {
621
+ constructor(problem) {
622
+ super(problem);
623
+ this.name = "RoleContractFailure";
624
+ }
625
+ }
626
+ function checkEvaluationSchema(schema) {
627
+ if (schema.result !== undefined) {
628
+ throw new RoleContractFailure("an evaluation schematic declares a Result, which the role fixes as Findings");
629
+ }
630
+ const imposed = schema.properties.find((property) => SCOPE_INPUTS.includes(property.key));
631
+ if (imposed !== undefined) {
632
+ throw new RoleContractFailure(`an evaluation schematic declares the input ${JSON.stringify(imposed.key)}, which the role imposes`);
633
+ }
634
+ }
635
+
566
636
  class OutputWriteFailure extends Error {
567
637
  constructor(outputPath, cause, reason) {
568
638
  const code = isErrnoException(cause) ? cause.code : undefined;
@@ -585,7 +655,7 @@ function assertOutputLeaf(outputPath) {
585
655
  throw err instanceof OutputWriteFailure ? err : new OutputWriteFailure(outputPath, err);
586
656
  }
587
657
  }
588
- function generateSchema(packageDir) {
658
+ function generateSchema(packageDir, evaluation = false) {
589
659
  const schemaPath = schemaPathFor(packageDir);
590
660
  const raw = readFileSync2(schemaPath, "utf-8");
591
661
  const schema = parseSchema(raw);
@@ -593,8 +663,10 @@ function generateSchema(packageDir) {
593
663
  if (sufficiencyFindings.length > 0) {
594
664
  throw new SchemaSufficiencyFailure(sufficiencyFindings);
595
665
  }
666
+ if (evaluation)
667
+ checkEvaluationSchema(schema);
596
668
  const digest = computeSchemaDigest(raw);
597
- const output = emitInputType(schema, digest);
669
+ const output = emitInputType(schema, digest, evaluation);
598
670
  const outputPath = join3(packageDir, GENERATED_FILENAME);
599
671
  try {
600
672
  if (process.platform === "linux" || process.platform === "darwin") {
@@ -777,11 +849,11 @@ function runProject(directory) {
777
849
  seen.add(output);
778
850
  if (!statSync2(schemaPath).isFile())
779
851
  throw new Error("nonregular schema");
780
- generateSchema(entry.directory);
852
+ generateSchema(entry.directory, entry.evaluation);
781
853
  generated++;
782
854
  } catch (error) {
783
855
  failed++;
784
- const diagnostic = error instanceof SchemaParseFailure ? formatParseError(schemaPath, error) : error instanceof SchemaSufficiencyFailure ? formatSufficiencyError(schemaPath, error) : error instanceof WriteContainmentRefusal ? "refusing to write outside the selected project root" : error instanceof OutputWriteFailure ? "cannot write a regular, non-symbolic-link output" : "cannot read or generate schema.json";
856
+ const diagnostic = error instanceof SchemaParseFailure ? formatParseError(schemaPath, error) : error instanceof SchemaSufficiencyFailure ? formatSufficiencyError(schemaPath, error) : error instanceof RoleContractFailure ? `pbuilder-codegen: ${schemaPath}: ${error.message}` : error instanceof WriteContainmentRefusal ? "refusing to write outside the selected project root" : error instanceof OutputWriteFailure ? "cannot write a regular, non-symbolic-link output" : "cannot read or generate schema.json";
785
857
  console.error(`pbuilder-codegen: ${JSON.stringify(entry.label)} (${JSON.stringify(entry.directory)}): ${JSON.stringify(diagnostic)}`);
786
858
  }
787
859
  }
@@ -1,6 +1,7 @@
1
1
  import type { JsonValue } from "../../../domain/valueobjects/wire.ts";
2
2
  import type { FoundHandle, WritableHandle } from "../../../domain/entities/handle-state.ts";
3
3
  import type { PendingDirective } from "../pending-directives/render.ts";
4
+ import type { GlobOptions } from "../../../domain/services/define-dialect.ts";
4
5
  /**
5
6
  * Locates an existing file and returns a `FoundHandle` for reading or removing it.
6
7
  *
@@ -17,6 +18,20 @@ import type { PendingDirective } from "../pending-directives/render.ts";
17
18
  * else replaceContent("src/config.ts", patch(c));
18
19
  */
19
20
  export declare function find(path: string): FoundHandle;
21
+ /**
22
+ * Opens every file `pattern` matches as a `FoundHandle`, ordered by path, leaving out every file
23
+ * an `ignore` pattern matches; resolves `[]` when none matches (A-130). `*` matches within one
24
+ * path segment, `?` one character, `**` any number of segments and `{a,b}` either alternative;
25
+ * every other character is literal, so `ignore` is the only way to leave files out. It sees the
26
+ * run (A-131): a file created earlier is listed, one removed earlier is not. Unlike `find`, it
27
+ * is asynchronous, because it lists files first.
28
+ *
29
+ * @example
30
+ * for (const file of await glob("src/domain/**", { ignore: ["**\/*.test.ts"] })) {
31
+ * const content = await file.read();
32
+ * }
33
+ */
34
+ export declare function glob(pattern: string, options?: GlobOptions): Promise<FoundHandle[]>;
20
35
  export declare function create(path: string, opts: {
21
36
  options: JsonValue | undefined;
22
37
  force?: boolean;
@@ -86,6 +86,23 @@ function buildFoundHandle(path) {
86
86
  export function find(path) {
87
87
  return buildFoundHandle(path);
88
88
  }
89
+ /**
90
+ * Opens every file `pattern` matches as a `FoundHandle`, ordered by path, leaving out every file
91
+ * an `ignore` pattern matches; resolves `[]` when none matches (A-130). `*` matches within one
92
+ * path segment, `?` one character, `**` any number of segments and `{a,b}` either alternative;
93
+ * every other character is literal, so `ignore` is the only way to leave files out. It sees the
94
+ * run (A-131): a file created earlier is listed, one removed earlier is not. Unlike `find`, it
95
+ * is asynchronous, because it lists files first.
96
+ *
97
+ * @example
98
+ * for (const file of await glob("src/domain/**", { ignore: ["**\/*.test.ts"] })) {
99
+ * const content = await file.read();
100
+ * }
101
+ */
102
+ export async function glob(pattern, options) {
103
+ const paths = await currentContext().session.list(pattern, options?.ignore);
104
+ return paths.map(buildFoundHandle);
105
+ }
89
106
  // `template` receives the defaulted options and runs after the active run is resolved, so a
90
107
  // call outside a run fails before any template file is read.
91
108
  export function create(path, opts, template) {
@@ -27,6 +27,14 @@ export declare function requirePackageAnchors(missingAnchorMessage: string): {
27
27
  packageDir: string;
28
28
  files: PackageFiles;
29
29
  };
30
+ /** What a run of a wrapped factory receives besides its input. */
31
+ export interface RunDeps {
32
+ client: EngineClient;
33
+ /** The role of the schematic (CA-14), as the runner received it; only `evaluation` changes the run. */
34
+ role?: string;
35
+ /** The qualified name `collection:schematic` of the schematic, as the runner received it. */
36
+ name?: string;
37
+ }
30
38
  /**
31
39
  * Builds a SessionContext and runs the factory inside it, flushing buffered
32
40
  * directives at run end (REQ-KIT-05) — a write-only factory still emits.
@@ -81,6 +89,13 @@ export declare function requirePackageAnchors(missingAnchorMessage: string): {
81
89
  *
82
90
  * const runner = defineFactory<Input>(bareFactory, { packageDir: import.meta.dir });
83
91
  * await runner(input, { client });
92
+ *
93
+ * The returned runner takes, besides the client, the `role` and the qualified `name` of the
94
+ * schematic it runs, as the caller received them (CA-19). With the role `evaluation`, `fn`
95
+ * returns its Findings, checked against the shape the role imposes, each finding's `source` is
96
+ * set to `name`, and `fn` receives the scope inputs `include` and `exclude`; every `glob` result
97
+ * is narrowed to the scope and so is every finding with a path (A-120 to A-124). Any other role,
98
+ * or none, runs as a generator.
84
99
  */
85
100
  export declare function defineFactory<O, R = void>(fn: (o: O) => R | Promise<R>, options?: ({
86
101
  packageDir: string | URL;
@@ -90,6 +105,4 @@ export declare function defineFactory<O, R = void>(fn: (o: O) => R | Promise<R>,
90
105
  packageFiles?: undefined;
91
106
  }) & {
92
107
  declaredDialects?: readonly string[];
93
- }): (o: O, deps: {
94
- client: EngineClient;
95
- }) => Promise<R>;
108
+ }): (o: O, deps: RunDeps) => Promise<R>;
@@ -10,7 +10,9 @@ import { currentRun, getSessionAls } from "../../../domain/services/run-context.
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
12
  import { checkResult, validateInput } from "../../../domain/services/schema/schema-validate.js";
13
- import { rejectionFor, rejectionForReservedName, rejectionForResult } from "../../../domain/services/schema/input-rejection.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));
@@ -119,7 +121,7 @@ function validateAtRunBoundary(pkg, input) {
119
121
  console.warn(emptySchemaWarning(pkg));
120
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);
@@ -145,6 +147,22 @@ function checkReservedNames(pkg) {
145
147
  throw rejectionForReservedName(reserved);
146
148
  }
147
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
+ }
148
166
  /**
149
167
  * Builds a SessionContext and runs the factory inside it, flushing buffered
150
168
  * directives at run end (REQ-KIT-05) — a write-only factory still emits.
@@ -199,23 +217,41 @@ function checkReservedNames(pkg) {
199
217
  *
200
218
  * const runner = defineFactory<Input>(bareFactory, { packageDir: import.meta.dir });
201
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.
202
227
  */
203
228
  export function defineFactory(fn, options) {
204
- 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;
205
234
  let packageAnchors;
206
235
  let packageFiles;
207
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
+ }
208
244
  if (options?.packageDir !== undefined) {
209
245
  const pkg = { files: options.packageFiles, dir: resolvePackageDir(options.packageDir) };
210
246
  // REQ-RBV-06: exactly TWO reads, in this order — reserved-name check, then schema
211
247
  // validation. No third (containment-ceiling) read exists (ADR-0077 §C).
212
248
  checkReservedNames(pkg);
213
- schema = validateAtRunBoundary(pkg, o);
249
+ schema = validateAtRunBoundary(pkg, o, source === undefined ? [] : SCOPE_INPUTS);
214
250
  packageAnchors = { packageDir: pkg.dir };
215
251
  packageFiles = pkg.files;
216
252
  }
217
253
  const ctx = {
218
- session: new Session(client),
254
+ session: new Session(client, inScope),
219
255
  factory: new DirectiveFactory(),
220
256
  dialects: new DialectRegistryImpl(),
221
257
  packageAnchors,
@@ -237,12 +273,10 @@ export function defineFactory(fn, options) {
237
273
  try {
238
274
  const returned = await getSessionAls().run(ctx, () => fn(o));
239
275
  await ctx.dialects.drain();
240
- const checked = checkResult(schema?.result, returned);
241
- if ("problem" in checked)
242
- throw rejectionForResult(checked.problem);
276
+ const result = handOn(source === undefined ? schema?.result : SOURCED_FINDINGS, returned, source, inScope);
243
277
  await ctx.session.flush();
244
- await ctx.session.commit(checked.result);
245
- return checked.result;
278
+ await ctx.session.commit(result);
279
+ return result;
246
280
  }
247
281
  catch (thrown) {
248
282
  // A thrown `undefined` or `null` would read as success to anyone testing the error.
@@ -2,12 +2,14 @@ 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>;
12
+ list(pattern: string, ignore?: readonly string[]): Promise<readonly string[]>;
11
13
  commit(result?: unknown): Promise<void>;
12
14
  discard(): Promise<void>;
13
15
  flush(): Promise<void>;
@@ -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,6 +73,12 @@ 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
84
  async commit(result) {
@@ -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
+ list(pattern: string, ignore?: readonly string[]): Promise<readonly string[]>;
5
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 —