@pbuilder/sdk 0.3.1 → 0.5.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 (54) hide show
  1. package/README.md +57 -17
  2. package/dist/commons/index.d.ts +22 -22
  3. package/dist/commons/index.js +25 -22
  4. package/dist/conformance/index.d.ts +2 -2
  5. package/dist/conformance/index.js +38 -19
  6. package/dist/core/authoring-error.d.ts +3 -3
  7. package/dist/core/authoring-error.js +5 -5
  8. package/dist/core/context.d.ts +6 -6
  9. package/dist/core/context.js +18 -18
  10. package/dist/core/define-dialect.d.ts +1 -1
  11. package/dist/core/define-dialect.js +16 -9
  12. package/dist/core/dialect-handle.js +9 -9
  13. package/dist/core/index.d.ts +1 -1
  14. package/dist/core/json-value.d.ts +14 -0
  15. package/dist/core/json-value.js +43 -0
  16. package/dist/core/session.d.ts +1 -1
  17. package/dist/core/session.js +2 -2
  18. package/dist/dialects/json/ast.d.ts +24 -0
  19. package/dist/dialects/json/ast.js +21 -0
  20. package/dist/dialects/json/index.d.ts +55 -0
  21. package/dist/dialects/json/index.js +54 -0
  22. package/dist/dialects/json/ops.d.ts +46 -0
  23. package/dist/dialects/json/ops.js +561 -0
  24. package/dist/dialects/react/index.d.ts +1 -1
  25. package/dist/dialects/react/index.js +1 -1
  26. package/dist/dialects/typescript/index.d.ts +2 -2
  27. package/dist/dialects/typescript/index.js +2 -2
  28. package/dist/dialects/typescript/ops.js +1 -1
  29. package/dist/dialects/yaml/ast.d.ts +15 -0
  30. package/dist/dialects/yaml/ast.js +154 -0
  31. package/dist/dialects/yaml/documents.d.ts +8 -0
  32. package/dist/dialects/yaml/documents.js +24 -0
  33. package/dist/dialects/yaml/index.d.ts +69 -0
  34. package/dist/dialects/yaml/index.js +70 -0
  35. package/dist/dialects/yaml/paths.d.ts +55 -0
  36. package/dist/dialects/yaml/paths.js +208 -0
  37. package/dist/dialects/yaml/presentation.d.ts +24 -0
  38. package/dist/dialects/yaml/presentation.js +264 -0
  39. package/dist/dialects/yaml/structural.d.ts +39 -0
  40. package/dist/dialects/yaml/structural.js +307 -0
  41. package/dist/pending-directives/index.d.ts +2 -0
  42. package/dist/pending-directives/index.js +1 -0
  43. package/dist/{dry-run/plan.d.ts → pending-directives/render.d.ts} +8 -33
  44. package/dist/{dry-run/plan.js → pending-directives/render.js} +5 -5
  45. package/dist/runner-manifest.json +6 -6
  46. package/dist/scaffold/expander.js +3 -3
  47. package/dist/scaffold/index.d.ts +1 -1
  48. package/dist/scaffold/index.js +1 -1
  49. package/dist/transport/error-text.d.ts +6 -1
  50. package/dist/transport/error-text.js +94 -31
  51. package/package.json +16 -3
  52. package/schemas/project-builder.schema.json +112 -0
  53. package/dist/dry-run/index.d.ts +0 -2
  54. package/dist/dry-run/index.js +0 -1
package/README.md CHANGED
@@ -21,14 +21,14 @@ sequenceDiagram
21
21
  CLI->>E: start engine
22
22
  E->>E: raise staging tree
23
23
  E->>F: start Bun sidecar, run factory
24
- loop commit phase — the SDK ↔ engine conversation
24
+ loop Stage — the SDK ↔ engine conversation
25
25
  F->>E: read a file (find().read())
26
26
  E-->>F: content, answered from the staging tree
27
27
  F->>E: IR directives (create, replaceContent, …)
28
- E->>E: commit directive to the staging tree
28
+ E->>E: stage the Instruction on the staging tree
29
29
  end
30
30
  F-->>E: factory returns
31
- E->>E: apply phase — staged result written to disk
31
+ E->>E: Commit — the Plan is written to disk
32
32
  E-->>CLI: result
33
33
  CLI-->>U: ✓ done
34
34
  ```
@@ -41,10 +41,10 @@ sequenceDiagram
41
41
  testing harness — and lowers everything you author into a small, stable **IR**
42
42
  (instruction records). It holds a conversation with the engine over framed stdio: reads
43
43
  come back from the staging tree, directives go out as IR. It never writes to disk.
44
- - The **engine** owns execution, in two phases. During the run — the **commit phase** —
44
+ - The **engine** owns execution, in two steps. During the Run, it **stages**:
45
45
  it raises the staging tree, starts the Bun sidecar that runs your factory, answers its
46
- read-backs, and commits every incoming IR directive to the staging tree. Only after the
47
- factory returns does the **apply phase** begin: the staged result is written to disk.
46
+ read-backs, and stages every incoming IR Instruction on the staging tree. Only after the
47
+ factory returns does it **commit**: the staged result is written to disk.
48
48
  The engine is the only component that ever writes — and a failed run writes nothing.
49
49
 
50
50
  That staging tree is what makes a schematic a conversation rather than a one-shot: while
@@ -304,7 +304,7 @@ Everything a factory can do to the tree is one of seven mutation verbs, all impo
304
304
  | [`rename(path, newName)`](./docs/authoring-verbs.md#rename) | A basename-only rename in place. |
305
305
  | [`move(path, toDir)`](./docs/authoring-verbs.md#move) | A move to a different directory. |
306
306
  | [`copy(from, to)`](./docs/authoring-verbs.md#copy) | A tree-to-tree copy, chainable via the returned handle. |
307
- | [`copyIn(from, to)`](./docs/authoring-verbs.md#copyin) | A package-local file copied into the tree **verbatim** — the never-render escape hatch. |
307
+ | [`copyIn(from, to)`](./docs/authoring-verbs.md#copyin) | A package-local file copied into the tree **verbatim** — never rendered. |
308
308
 
309
309
  The verbs that write to a new path — `create`, `rename`, `move`, `copy`, `copyIn`, and
310
310
  `scaffold` — are fail-closed on collision and accept `{ force: true }` for a deliberate
@@ -318,7 +318,7 @@ Three companions round out the surface:
318
318
  - [`scaffold({ from, to, options })`](./docs/authoring-verbs.md#scaffold) — mirror an
319
319
  entire package-local folder into the tree, with dynamic file names. The workhorse for
320
320
  multi-file generators — see [Scaffolding a folder of templates](#scaffolding-a-folder-of-templates).
321
- - [`dryRun()`](./docs/dry-run.md) — inspect the directives still **pending**. A `read()`
321
+ - [`pendingDirectives()`](./docs/pending-directives.md) — inspect the directives still **pending**. A `read()`
322
322
  drains the buffer, so call it before reading if you want the full picture.
323
323
 
324
324
  ### What to keep in mind
@@ -337,9 +337,9 @@ Rules that save you real debugging time — each one is a mistake we've watched
337
337
  example shows the read-back mechanics — a production factory would also skip the append
338
338
  when the name is already listed.
339
339
  - **Nothing touches disk while your factory runs.** Verbs *schedule* directives; during the
340
- run the engine commits them to the staging tree only (that's why reading a path you
341
- created earlier in the same run sees the staged content). Disk writes happen in the apply
342
- phase, after the factory returns — a thrown error before return means nothing is written
340
+ Run the engine stages them on the staging tree only (that's why reading a path you
341
+ created earlier in the same run sees the staged content). Disk writes happen at Commit,
342
+ after the factory returns — a thrown error before return means nothing is written
343
343
  at all.
344
344
  - **Errors are structured.** A rejected run surfaces an `AuthoringError` with
345
345
  `verb`/`path`/`reason` fields telling you which directive failed and why (one label
@@ -409,7 +409,7 @@ Two traps worth knowing before they bite: **empty arrays and objects are falsy**
409
409
  the numeric type** they're compared against (option numbers are decimals: `eq .count 2.0`,
410
410
  never `eq .count 2`).
411
411
 
412
- If templating gets in your way, the escape hatch is always available: build the final
412
+ If templating gets in your way, there is always a way out: build the final
413
413
  strings in TypeScript and pass a token-free template — it renders verbatim. For the full
414
414
  language — `with`, variables, whitespace rules, output-path templating, sandbox limits, and
415
415
  the error taxonomy — see [Authoring `create` templates](./docs/create-templates.md).
@@ -559,8 +559,9 @@ conformance-tests a *dialect or op-pack* implementation — not the same audienc
559
559
 
560
560
  When string-level mutation isn't enough — "add an import to this module", "set a prop on
561
561
  this JSX element" — **dialects** provide structured, AST-aware operations for one file
562
- type: see [authoring a dialect](./docs/authoring-a-dialect.md) for the full story. Two
563
- ship today: `@pbuilder/sdk/typescript` and `@pbuilder/sdk/react`.
562
+ type: see [authoring a dialect](./docs/authoring-a-dialect.md) for the full story. Four
563
+ ship today: `@pbuilder/sdk/typescript`, `@pbuilder/sdk/react`, `@pbuilder/sdk/json`, and
564
+ `@pbuilder/sdk/yaml`.
564
565
 
565
566
  A dialect's entry point is its own `find(path)`: it opens a **coalescing, awaitable
566
567
  handle**. Every op you chain mutates the same live AST, and the handle serializes to
@@ -596,7 +597,7 @@ untrusted input is the author's responsibility to sanitize.
596
597
 
597
598
  Mutates `.tsx` files — `find()` requires the explicit `.tsx` extension (extensionless and
598
599
  `.jsx` paths are rejected, never normalized). The v1 op-pack — a dialect's bundle of named
599
- ops — is deliberately minimal: two structured ops, with `.modify(fn)` as the escape hatch
600
+ ops — is deliberately minimal: two named ops, with `.modify(fn)` as the escape hatch
600
601
  for everything else:
601
602
 
602
603
  ```ts
@@ -620,12 +621,51 @@ await react
620
621
  the TypeScript `source` strings. One React-specific subtlety: an inserted prop lands after
621
622
  a trailing `{...spread}`, so it **wins** at runtime under React's later-position precedence.
622
623
 
624
+ ### `@pbuilder/sdk/json`
625
+
626
+ Mutates `.json` and `.jsonc` files by path, editing only the bytes it changes: comments,
627
+ indentation, key order, and line endings survive. Paths are arrays (`["scripts", "build"]`,
628
+ `["plugins", 0]`).
629
+
630
+ ```ts
631
+ import * as json from "@pbuilder/sdk/json";
632
+
633
+ await json
634
+ .find("package.json")
635
+ .setValue(["scripts", "build"], "tsc")
636
+ .appendItem(["keywords"], "schematics", { unique: true });
637
+ ```
638
+
639
+ Named ops: `setValue`, `addKey`, `removeKey`, `renameKey`, `insertItem`, `appendItem`,
640
+ `removeItem`, `removeValue`, `replaceItem`, `moveItem`, `merge`, `updateValue`, `moveValue`,
641
+ `copyValue`, `sortKeys`. `.modify(fn)` exposes [jsonc-parser](https://github.com/microsoft/node-jsonc-parser).
642
+ See [the JSON dialect guide](./docs/json-dialect.md).
643
+
644
+ ### `@pbuilder/sdk/yaml`
645
+
646
+ Mutates `.yaml` and `.yml` files with the same path-based ops as the JSON dialect, plus
647
+ comments, anchors and aliases, merge keys, styles, tags, and multi-document files. A
648
+ document no op touched prints byte-identical.
649
+
650
+ ```ts
651
+ import * as yaml from "@pbuilder/sdk/yaml";
652
+
653
+ await yaml
654
+ .find("docker-compose.yml")
655
+ .setValue(["services", "web", "image"], "node:22")
656
+ .setComment(["services", "web"], "Public entrypoint");
657
+ ```
658
+
659
+ Extra named ops: `setComment`, `removeComment`, `setAnchor`, `removeAnchor`, `setAlias`,
660
+ `addMergeKey`, `setStyle`, `setTag`, `addDocument`, `removeDocument`. `.modify(fn)` exposes
661
+ [yaml](https://eemeli.org/yaml/). See [the YAML dialect guide](./docs/yaml-dialect.md).
662
+
623
663
  ### `.modify()` — the universal escape hatch
624
664
 
625
665
  Every dialect handle carries one universal op alongside its named ops: `.modify(ast => …)`.
626
666
  Your callback receives the **same live AST instance the named ops mutate** — a ts-morph
627
667
  `SourceFile` — so anything a named op could do, `.modify()` can do too, without waiting for
628
- a structured op to exist:
668
+ a named op to exist:
629
669
 
630
670
  ```ts
631
671
  import * as ts from "@pbuilder/sdk/typescript";
@@ -673,7 +713,7 @@ The full reading path lives in [`docs/`](./docs/README.md):
673
713
  2. [Authoring verbs](./docs/authoring-verbs.md) — the seven verbs + `find().read()` in full.
674
714
  3. [Authoring `create` templates](./docs/create-templates.md) — the template language.
675
715
  4. [Error contract](./docs/authoring-errors.md) — `AuthoringError` and recovery.
676
- 5. [Dry-run](./docs/dry-run.md) — previewing planned changes.
716
+ 5. [Pending Directives](./docs/pending-directives.md) — previewing pending changes.
677
717
  6. [Authoring a dialect](./docs/authoring-a-dialect.md) — AST-aware mutation per file type.
678
718
 
679
719
  ## Design at a glance
@@ -25,7 +25,7 @@ export interface CreateOptions {
25
25
  /**
26
26
  * Options for the `create({ templateFile })` render request — an explicit, package-local
27
27
  * alternative to an inline `template` string (REQ-FEH-01). `templateFile` is a
28
- * package-relative path (resolved against the active run's `packageDir`), read at
28
+ * package-relative path (resolved against the active Session's `packageDir`), read at
29
29
  * emission time; its content becomes the `create` directive's `template` field —
30
30
  * the existing `create` IR, zero wire change. `templateFile` REQUESTS a render: a binary
31
31
  * or oversized source fails loud (`invalid-input`), it never silently falls back to a
@@ -69,12 +69,12 @@ export declare function find(path: string): FoundHandle;
69
69
  *
70
70
  * Creating over an existing file is rejected at the engine seam unless
71
71
  * `{ force: true }` is passed (overwrite-on-collision, ADR-0017 fail-closed) — a
72
- * rejected run throws `AuthoringError`.
72
+ * rejected Session throws `AuthoringError`.
73
73
  *
74
74
  * `templateFile` is a THIRD overload (REQ-FEH-01): pass a package-local path instead of an
75
75
  * inline `template` string — its content is read at emission time and becomes the
76
76
  * directive's `template` field. `template` and `templateFile` are mutually exclusive forms;
77
- * only usable inside a factory run started with packageDir (there is no resolution anchor
77
+ * only usable inside a factory invocation started with packageDir (there is no resolution anchor
78
78
  * to read a package-local file against otherwise — `invalid-input`, never a cwd fallback).
79
79
  * `templateFile`'s VALUE is a literal package-relative path, read verbatim by CONTENT —
80
80
  * it is NOT run through `scaffold`'s filename pipeline (no rename remap, no `__x__` token
@@ -121,7 +121,7 @@ export declare function create(path: string, opts: CreateFromTemplateFileOptions
121
121
  */
122
122
  export type ScaffoldOptions = ScaffoldArgs;
123
123
  /**
124
- * Walks a package-local folder (`from`, resolved against the active run's `packageDir`)
124
+ * Walks a package-local folder (`from`, resolved against the active Session's `packageDir`)
125
125
  * and mirrors every entry into `to`, applying the rename → filename-token-translation →
126
126
  * `.template`-strip pipeline (REQ-FSC-05) and include/exclude glob filtering (REQ-FSC-03,
127
127
  * `exclude` wins on overlap). Each source classifies by-value or by-reference
@@ -132,7 +132,7 @@ export type ScaffoldOptions = ScaffoldArgs;
132
132
  * `false`) passes through unchanged to every emitted directive, no per-file override
133
133
  * (REQ-FSC-06). Two or more sources collapsing to the same destination reject fail-loud,
134
134
  * naming every offending source (REQ-FSC-08). Only usable inside a
135
- * factory run started with packageDir — there is no resolution anchor to walk a
135
+ * factory invocation started with packageDir — there is no resolution anchor to walk a
136
136
  * package-local folder against otherwise (`invalid-input`, never a cwd fallback).
137
137
  *
138
138
  * `rename` is a static REMAP TABLE (`Record<originalSourceRelativePath,
@@ -176,7 +176,7 @@ export declare function scaffold(args: ScaffoldOptions): void;
176
176
  * `from`/`to` are mandatory; `force` defaults `false`. A missing `from`/`to` rejects
177
177
  * fail-loud before any emission (REQ-FEH-04.1/.2). Collision without `force` rejects;
178
178
  * `force: true` overwrites (`by-reference-copy-wire` REQ-BRC-05). Only usable inside a
179
- * factory run started with packageDir — there is no resolution anchor to read a
179
+ * factory invocation started with packageDir — there is no resolution anchor to read a
180
180
  * package-local file against otherwise (`invalid-input`, never a cwd fallback).
181
181
  *
182
182
  * Returns `void` (REQ-FEH-04.3) — NOT a `WritableHandle`, unlike `copy`: a by-reference
@@ -193,7 +193,7 @@ export declare function copyIn(from: string, to: string, opts?: {
193
193
  }): void;
194
194
  /**
195
195
  * Schedules an in-place content replacement for an existing file and returns a `WritableHandle`.
196
- * A rejected run (e.g. the target does not exist) throws `AuthoringError`.
196
+ * A rejected Session (e.g. the target does not exist) throws `AuthoringError`.
197
197
  *
198
198
  * @example
199
199
  * replaceContent("src/config.json", '{ "version": "2.0.0" }');
@@ -210,7 +210,7 @@ export declare function remove(path: string): void;
210
210
  * Schedules a file rename (basename only) and returns a `WritableHandle` for the new path.
211
211
  * Renaming onto an existing path is rejected at the engine seam unless
212
212
  * `{ force: true }` is passed (overwrite-on-collision, ADR-0017 fail-closed) — a
213
- * rejected run throws `AuthoringError`.
213
+ * rejected Session throws `AuthoringError`.
214
214
  *
215
215
  * @example
216
216
  * rename("src/foo.ts", "bar.ts");
@@ -222,7 +222,7 @@ export declare function rename(path: string, newName: string, opts?: {
222
222
  * Schedules a file move to a different directory and returns a `WritableHandle`.
223
223
  * Moving onto an existing destination is rejected at the engine seam unless
224
224
  * `{ force: true }` is passed (overwrite-on-collision, ADR-0017 fail-closed) — a
225
- * rejected run throws `AuthoringError`.
225
+ * rejected Session throws `AuthoringError`.
226
226
  * A move whose destination equals its source is a no-op, never a collision
227
227
  * (ADR-0017 self-move amendment).
228
228
  *
@@ -236,7 +236,7 @@ export declare function move(path: string, toDir: string, opts?: {
236
236
  * Schedules a file copy to a new path and returns a `WritableHandle` for the destination.
237
237
  * Copying onto an existing destination is rejected at the engine seam unless
238
238
  * `{ force: true }` is passed (overwrite-on-collision, ADR-0017 fail-closed) — a
239
- * rejected run throws `AuthoringError`.
239
+ * rejected Session throws `AuthoringError`.
240
240
  *
241
241
  * @example
242
242
  * copy("src/template.ts", "src/generated/output.ts");
@@ -244,15 +244,15 @@ export declare function move(path: string, toDir: string, opts?: {
244
244
  export declare function copy(from: string, to: string, opts?: {
245
245
  force?: boolean;
246
246
  }): WritableHandle;
247
- import type { DryRunEntry, DryRunVerb } from "../dry-run/plan.ts";
248
- export type { DryRunEntry, DryRunVerb };
247
+ import type { PendingDirective } from "../pending-directives/render.ts";
248
+ export type { PendingDirective };
249
249
  /**
250
- * Returns the plan of directives still pending in the active run's buffer, rendered
251
- * in author vocabulary.
250
+ * Returns the Directives still pending in the active Session's buffer, rendered in
251
+ * author vocabulary.
252
252
  *
253
- * The plan reflects only what is still pending — the honest answer to "what will this
254
- * run still emit", not "what has this run emitted in total." A `read()` (or any flush)
255
- * empties the pending buffer, so directives already flushed no longer appear.
253
+ * Only what is still pending appears — the honest answer to "what will this Session
254
+ * still emit", not "what has this Session emitted in total." A `read()` (or any flush)
255
+ * drains the pending buffer, so Directives already sent no longer appear.
256
256
  *
257
257
  * Entries carry verb and path — no content or byte preview — plus an optional `kind`
258
258
  * (`"rendered" | "copied"`) present only on the package-local-read verbs whose transport
@@ -260,19 +260,19 @@ export type { DryRunEntry, DryRunVerb };
260
260
  * (`kind: "copied"`). The tree→tree `copy` verb also materializes content but predates
261
261
  * this axis and is never package-local-read/classified, so it carries no `kind`.
262
262
  *
263
- * Call it inside an active factory run, like every other `./commons` verb.
263
+ * Call it inside an active factory invocation, like every other `./commons` verb.
264
264
  *
265
265
  * @example
266
266
  * const run = () => {
267
267
  * create("src/index.ts", { template: "export const version = '1.0.0';", options: {} });
268
268
  * find("src/legacy.ts").remove();
269
- * for (const entry of dryRun()) {
269
+ * for (const entry of pendingDirectives()) {
270
270
  * console.log(entry.verb, entry.path); // "create src/index.ts", then "remove src/legacy.ts"
271
271
  * }
272
272
  * };
273
273
  *
274
- * @throws When called outside an active factory run, propagates the standard
274
+ * @throws When called outside an active factory invocation, propagates the standard
275
275
  * error — authoring verbs "can only be used while a schematic is running" (ADR-0026: the
276
- * message no longer enumerates individual verbs, so it covers `dryRun` too).
276
+ * message no longer enumerates individual verbs, so it covers `pendingDirectives` too).
277
277
  */
278
- export declare function dryRun(): DryRunEntry[];
278
+ export declare function pendingDirectives(): PendingDirective[];
@@ -98,17 +98,20 @@ export function find(path) {
98
98
  }
99
99
  export function create(path, opts) {
100
100
  const { session, factory } = currentContext();
101
- const template = "templateFile" in opts ? readTemplateFile(opts.templateFile, path, opts.options, opts.force) : opts.template;
101
+ // The wire requires `options`, and an omitted bag (untyped callers) would vanish in JSON and
102
+ // fail the batch's round-trip check as unrepresentable content.
103
+ const options = opts.options === undefined ? {} : opts.options;
104
+ const template = "templateFile" in opts ? readTemplateFile(opts.templateFile, path, options, opts.force) : opts.template;
102
105
  session.buffer(factory.create({
103
106
  pathTemplate: path,
104
107
  template,
105
- options: opts.options,
108
+ options,
106
109
  ...forceEntry(opts.force),
107
110
  }));
108
111
  return buildWritableHandle(path);
109
112
  }
110
113
  /**
111
- * Walks a package-local folder (`from`, resolved against the active run's `packageDir`)
114
+ * Walks a package-local folder (`from`, resolved against the active Session's `packageDir`)
112
115
  * and mirrors every entry into `to`, applying the rename → filename-token-translation →
113
116
  * `.template`-strip pipeline (REQ-FSC-05) and include/exclude glob filtering (REQ-FSC-03,
114
117
  * `exclude` wins on overlap). Each source classifies by-value or by-reference
@@ -119,7 +122,7 @@ export function create(path, opts) {
119
122
  * `false`) passes through unchanged to every emitted directive, no per-file override
120
123
  * (REQ-FSC-06). Two or more sources collapsing to the same destination reject fail-loud,
121
124
  * naming every offending source (REQ-FSC-08). Only usable inside a
122
- * factory run started with packageDir — there is no resolution anchor to walk a
125
+ * factory invocation started with packageDir — there is no resolution anchor to walk a
123
126
  * package-local folder against otherwise (`invalid-input`, never a cwd fallback).
124
127
  *
125
128
  * `rename` is a static REMAP TABLE (`Record<originalSourceRelativePath,
@@ -165,7 +168,7 @@ export function scaffold(args) {
165
168
  * `from`/`to` are mandatory; `force` defaults `false`. A missing `from`/`to` rejects
166
169
  * fail-loud before any emission (REQ-FEH-04.1/.2). Collision without `force` rejects;
167
170
  * `force: true` overwrites (`by-reference-copy-wire` REQ-BRC-05). Only usable inside a
168
- * factory run started with packageDir — there is no resolution anchor to read a
171
+ * factory invocation started with packageDir — there is no resolution anchor to read a
169
172
  * package-local file against otherwise (`invalid-input`, never a cwd fallback).
170
173
  *
171
174
  * Returns `void` (REQ-FEH-04.3) — NOT a `WritableHandle`, unlike `copy`: a by-reference
@@ -182,7 +185,7 @@ export function copyIn(from, to, opts) {
182
185
  }
183
186
  /**
184
187
  * Schedules an in-place content replacement for an existing file and returns a `WritableHandle`.
185
- * A rejected run (e.g. the target does not exist) throws `AuthoringError`.
188
+ * A rejected Session (e.g. the target does not exist) throws `AuthoringError`.
186
189
  *
187
190
  * @example
188
191
  * replaceContent("src/config.json", '{ "version": "2.0.0" }');
@@ -206,7 +209,7 @@ export function remove(path) {
206
209
  * Schedules a file rename (basename only) and returns a `WritableHandle` for the new path.
207
210
  * Renaming onto an existing path is rejected at the engine seam unless
208
211
  * `{ force: true }` is passed (overwrite-on-collision, ADR-0017 fail-closed) — a
209
- * rejected run throws `AuthoringError`.
212
+ * rejected Session throws `AuthoringError`.
210
213
  *
211
214
  * @example
212
215
  * rename("src/foo.ts", "bar.ts");
@@ -221,7 +224,7 @@ export function rename(path, newName, opts) {
221
224
  * Schedules a file move to a different directory and returns a `WritableHandle`.
222
225
  * Moving onto an existing destination is rejected at the engine seam unless
223
226
  * `{ force: true }` is passed (overwrite-on-collision, ADR-0017 fail-closed) — a
224
- * rejected run throws `AuthoringError`.
227
+ * rejected Session throws `AuthoringError`.
225
228
  * A move whose destination equals its source is a no-op, never a collision
226
229
  * (ADR-0017 self-move amendment).
227
230
  *
@@ -237,7 +240,7 @@ export function move(path, toDir, opts) {
237
240
  * Schedules a file copy to a new path and returns a `WritableHandle` for the destination.
238
241
  * Copying onto an existing destination is rejected at the engine seam unless
239
242
  * `{ force: true }` is passed (overwrite-on-collision, ADR-0017 fail-closed) — a
240
- * rejected run throws `AuthoringError`.
243
+ * rejected Session throws `AuthoringError`.
241
244
  *
242
245
  * @example
243
246
  * copy("src/template.ts", "src/generated/output.ts");
@@ -247,15 +250,15 @@ export function copy(from, to, opts) {
247
250
  session.buffer(factory.copy({ from, to, ...forceEntry(opts?.force) }));
248
251
  return buildWritableHandle(to);
249
252
  }
250
- // --- Stage 3: dry-run plan exposure (REQ-DRE-01..04) ---
251
- import { dryRunPlan } from "../dry-run/index.js";
253
+ // --- Stage 3: pending Directives exposure (REQ-DRE-01..04) ---
254
+ import { renderPendingDirectives } from "../pending-directives/index.js";
252
255
  /**
253
- * Returns the plan of directives still pending in the active run's buffer, rendered
254
- * in author vocabulary.
256
+ * Returns the Directives still pending in the active Session's buffer, rendered in
257
+ * author vocabulary.
255
258
  *
256
- * The plan reflects only what is still pending — the honest answer to "what will this
257
- * run still emit", not "what has this run emitted in total." A `read()` (or any flush)
258
- * empties the pending buffer, so directives already flushed no longer appear.
259
+ * Only what is still pending appears — the honest answer to "what will this Session
260
+ * still emit", not "what has this Session emitted in total." A `read()` (or any flush)
261
+ * drains the pending buffer, so Directives already sent no longer appear.
259
262
  *
260
263
  * Entries carry verb and path — no content or byte preview — plus an optional `kind`
261
264
  * (`"rendered" | "copied"`) present only on the package-local-read verbs whose transport
@@ -263,21 +266,21 @@ import { dryRunPlan } from "../dry-run/index.js";
263
266
  * (`kind: "copied"`). The tree→tree `copy` verb also materializes content but predates
264
267
  * this axis and is never package-local-read/classified, so it carries no `kind`.
265
268
  *
266
- * Call it inside an active factory run, like every other `./commons` verb.
269
+ * Call it inside an active factory invocation, like every other `./commons` verb.
267
270
  *
268
271
  * @example
269
272
  * const run = () => {
270
273
  * create("src/index.ts", { template: "export const version = '1.0.0';", options: {} });
271
274
  * find("src/legacy.ts").remove();
272
- * for (const entry of dryRun()) {
275
+ * for (const entry of pendingDirectives()) {
273
276
  * console.log(entry.verb, entry.path); // "create src/index.ts", then "remove src/legacy.ts"
274
277
  * }
275
278
  * };
276
279
  *
277
- * @throws When called outside an active factory run, propagates the standard
280
+ * @throws When called outside an active factory invocation, propagates the standard
278
281
  * error — authoring verbs "can only be used while a schematic is running" (ADR-0026: the
279
- * message no longer enumerates individual verbs, so it covers `dryRun` too).
282
+ * message no longer enumerates individual verbs, so it covers `pendingDirectives` too).
280
283
  */
281
- export function dryRun() {
282
- return dryRunPlan(currentContext().session.pendingSnapshot());
284
+ export function pendingDirectives() {
285
+ return renderPendingDirectives(currentContext().session.pendingDirectives());
283
286
  }
@@ -120,7 +120,7 @@ export interface OpPackFixture {
120
120
  /**
121
121
  * Runs the conformance suite for a dialect: asserts parse/print no-op round-trip fidelity
122
122
  * (REQ-DC-01) — `print(parse(sample)) === sample` BYTE-EXACT, never AST-equal, for every
123
- * sample in `fixture.samples` PLUS the six mandatory adversarial samples the kit injects on
123
+ * sample in `fixture.samples` PLUS the four mandatory adversarial samples the kit injects on
124
124
  * every run (REQ-DC-06 — additive, not opt-out-able). Before each round-trip check, verifies
125
125
  * `fixture.dialect.ast.parse` is a REAL parser, not an identity/stub function (REQ-DC-08): a
126
126
  * `parse` returning `null`/`undefined`, or the input string unchanged, fails BEFORE the
@@ -137,7 +137,7 @@ export declare function testDialect<Library extends object>(fixture: DialectFixt
137
137
  * no-read run, seam-serializability (REQ-DC-04) over every emitted directive, and — for
138
138
  * every multi-op exercise — the read-boundary split (REQ-DC-05.2's live counterpart): a
139
139
  * mid-chain `read()` must force exactly TWO cumulative modify directives, never one. Finally,
140
- * asserts `fixture.baseDialect` survives the six mandatory adversarial samples' round-trip +
140
+ * asserts `fixture.baseDialect` survives the four mandatory adversarial samples' round-trip +
141
141
  * real-base probe (REQ-DC-06/REQ-DC-08 — additive, not opt-out-able, same mechanism
142
142
  * `testDialect` runs), unconditionally on every call whose exercises pass.
143
143
  *
@@ -68,20 +68,26 @@ async function runExercise(dialect, exercise, opts) {
68
68
  .map((d) => d.modify);
69
69
  return { modifies, directives };
70
70
  }
71
- // REQ-DC-06 (ADR-0012 amendment clause 1): six mandatory adversarial samples, injected
72
- // ADDITIVELY into every `testDialect` run — `DialectFixture` carries no field capable of
73
- // disabling this (compile-level guarantee, REQ-DC-06.2, see test/conformance/planted/
74
- // opt-out-attempt.test.ts). Each sample is independently verified to round-trip byte-exact
75
- // against the real TypeScript dialect (`ast.ts`'s parse/print pair) — a dialect that fails one
76
- // is a real conformance failure, not a fixture artefact.
77
- const MANDATORY_ADVERSARIAL_SAMPLES = [
78
- "", // empty file
79
- "// just a comment, no statements\n", // comment-only file
80
- `/*${"a".repeat(4 * 1024 * 1024)}*/\nconst x = 1;\n`, // 4 MiB serialized-boundary sample (REQ-TSD-03.7 precedent)
81
- "const x = 1;\r\nconst y = 2;\r\n", // CRLF
82
- "const x = 1;\n", // UTF-8 BOM
83
- 'import { a } from "m";\nimport { b } from "m";\n', // duplicate-target: two import statements sharing one module specifier
84
- ];
71
+ // REQ-DC-06 (ADR-0012 amendment clause 1): four mandatory adversarial samples, injected
72
+ // ADDITIVELY into every `testDialect`/`testOpPack` run — `DialectFixture` carries no field
73
+ // capable of disabling this (compile-level guarantee, REQ-DC-06.2, see test/conformance/planted/
74
+ // opt-out-attempt.test.ts). No source text is valid in every language, so the samples derive
75
+ // from a source the dialect itself declares valid (the library-exercise seed, or the first
76
+ // op-exercise seed): only the empty file, line endings, the BOM, and size are format-neutral.
77
+ // Language-specific adversarial samples belong in each dialect's own `fixture.samples`.
78
+ const BOM = "\uFEFF";
79
+ const LARGE_SAMPLE_BYTES = 4 * 1024 * 1024;
80
+ function mandatoryAdversarialSamples(validSource) {
81
+ const lf = validSource.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
82
+ const terminated = lf.endsWith("\n") ? lf : `${lf}\n`;
83
+ return [
84
+ "", // empty file
85
+ terminated.replace(/\n/g, "\r\n"), // CRLF
86
+ BOM + terminated, // UTF-8 BOM
87
+ terminated + "\n".repeat(LARGE_SAMPLE_BYTES), // 4 MiB serialized-boundary sample (REQ-TSD-03.7 precedent)
88
+ ];
89
+ }
90
+ const UNDECLARED_EXTENSION = ".pbuilder-undeclared";
85
91
  // Shared by `testDialect` and `testOpPack` (verify-in-loop-4 Finding #1): the round-trip +
86
92
  // real-base-probe loop is ONE mechanism, run against whichever dialect reference the caller
87
93
  // holds (`fixture.dialect` for testDialect, `fixture.baseDialect` for testOpPack) — REQ-DC-06's
@@ -109,7 +115,7 @@ function runRoundTripProbe(dialectAst, samples, label) {
109
115
  /**
110
116
  * Runs the conformance suite for a dialect: asserts parse/print no-op round-trip fidelity
111
117
  * (REQ-DC-01) — `print(parse(sample)) === sample` BYTE-EXACT, never AST-equal, for every
112
- * sample in `fixture.samples` PLUS the six mandatory adversarial samples the kit injects on
118
+ * sample in `fixture.samples` PLUS the four mandatory adversarial samples the kit injects on
113
119
  * every run (REQ-DC-06 — additive, not opt-out-able). Before each round-trip check, verifies
114
120
  * `fixture.dialect.ast.parse` is a REAL parser, not an identity/stub function (REQ-DC-08): a
115
121
  * `parse` returning `null`/`undefined`, or the input string unchanged, fails BEFORE the
@@ -136,14 +142,27 @@ export async function testDialect(fixture) {
136
142
  !Object.is(Reflect.get(module.astLibrary, key), Reflect.get(expected, key)))) {
137
143
  throw new Error("testDialect: astLibrary runtime library mismatch with adapter evidence");
138
144
  }
139
- const samples = [...fixture.samples, ...MANDATORY_ADVERSARIAL_SAMPLES];
145
+ const samples = [...fixture.samples, ...mandatoryAdversarialSamples(fixture.libraryExercise.seed)];
140
146
  runRoundTripProbe(fixture.dialect.ast, samples, "testDialect");
141
147
  const exercise = fixture.libraryExercise;
142
148
  const { client, emitted } = createRunVehicle({ [exercise.path]: exercise.seed });
149
+ // A-11: `find` must reject an extension the dialect does not declare. Probed inside the run,
150
+ // because outside a Session a conforming `find` would throw for the wrong reason.
151
+ const undeclaredPath = `conformance-probe${UNDECLARED_EXTENSION}`;
152
+ let acceptedUndeclared = !fixture.dialect.extensions.includes(UNDECLARED_EXTENSION);
143
153
  const run = defineFactory(async () => {
154
+ try {
155
+ module.find(undeclaredPath);
156
+ }
157
+ catch {
158
+ acceptedUndeclared = false;
159
+ }
144
160
  await module.find(exercise.path).modify((ast) => exercise.modify(ast, module.astLibrary));
145
161
  });
146
162
  await run(undefined, { client });
163
+ if (acceptedUndeclared) {
164
+ throw new Error(`testDialect: find accepted "${undeclaredPath}", an undeclared extension (A-11)`);
165
+ }
147
166
  const directives = emitted.flatMap((batch) => batch.instructions);
148
167
  if (!deepEqual(directives, [{ op: "modify", modify: { path: exercise.path, content: exercise.expect } }])) {
149
168
  throw new Error("testDialect: library exercise did not emit the expected byte-exact modify");
@@ -156,7 +175,7 @@ export async function testDialect(fixture) {
156
175
  * no-read run, seam-serializability (REQ-DC-04) over every emitted directive, and — for
157
176
  * every multi-op exercise — the read-boundary split (REQ-DC-05.2's live counterpart): a
158
177
  * mid-chain `read()` must force exactly TWO cumulative modify directives, never one. Finally,
159
- * asserts `fixture.baseDialect` survives the six mandatory adversarial samples' round-trip +
178
+ * asserts `fixture.baseDialect` survives the four mandatory adversarial samples' round-trip +
160
179
  * real-base probe (REQ-DC-06/REQ-DC-08 — additive, not opt-out-able, same mechanism
161
180
  * `testDialect` runs), unconditionally on every call whose exercises pass.
162
181
  *
@@ -228,7 +247,7 @@ export async function testOpPack(fixture) {
228
247
  }
229
248
  }
230
249
  }
231
- // REQ-DC-06/REQ-DC-08 (verify-in-loop-4 Finding #1): the six mandatory adversarial
250
+ // REQ-DC-06/REQ-DC-08 (verify-in-loop-4 Finding #1): the four mandatory adversarial
232
251
  // samples' round-trip + real-base probe, run against `fixture.baseDialect` — same
233
252
  // mechanism `testDialect` runs, independent of `fixture.exercises`. Deliberately LAST
234
253
  // (not first, unlike testDialect): a fixture's own exercises target ONE specific
@@ -238,5 +257,5 @@ export async function testOpPack(fixture) {
238
257
  // failure surface for its own reason first, while still running the probe unconditionally
239
258
  // on every call whose exercises pass, exactly as REQ-DC-06's "regardless of what samples
240
259
  // the contributor's own fixture supplies" demands.
241
- runRoundTripProbe(fixture.baseDialect.ast, MANDATORY_ADVERSARIAL_SAMPLES, "testOpPack");
260
+ runRoundTripProbe(fixture.baseDialect.ast, mandatoryAdversarialSamples(fixture.exercises[0].seed), "testOpPack");
242
261
  }
@@ -45,7 +45,7 @@ export type AuthoringVerb = "create" | "modify" | "remove" | "rename" | "move" |
45
45
  * case "path-not-found":
46
46
  * case "unrepresentable-content":
47
47
  * case "changes-too-large":
48
- * case "outside-run":
48
+ * case "outside-session":
49
49
  * case "unknown":
50
50
  * case "invalid-input":
51
51
  * case "reserved-name":
@@ -56,7 +56,7 @@ export type AuthoringVerb = "create" | "modify" | "remove" | "rename" | "move" |
56
56
  * break;
57
57
  * }
58
58
  */
59
- export type AuthoringReason = "path-collision" | "path-not-found" | "unrepresentable-content" | "changes-too-large" | "outside-run" | "unknown" | "invalid-input" | "reserved-name" | "source-not-found" | "source-not-regular-file" | "source-unreadable";
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
60
  /**
61
61
  * Distinguishes an engine-refused write from an SDK-side misuse (2.4, ADR-0021) —
62
62
  * DERIVED from `reason`, never producer-set.
@@ -95,7 +95,7 @@ export declare class AuthoringError extends Error {
95
95
  readonly origin: AuthoringOrigin;
96
96
  /**
97
97
  * Counts directives applied within the failing flush before the offender — a
98
- * diagnostic for locating progress, NOT a persistence promise (a rejected run
98
+ * diagnostic for locating progress, NOT a persistence promise (a rejected Session
99
99
  * discards everything, ADR-0015).
100
100
  */
101
101
  readonly appliedCount: number;
@@ -16,7 +16,7 @@ import { EmitRejection } from "./emit-rejection.js";
16
16
  // an unclassifiable rejection necessarily arrived through the emit/write seam (the only
17
17
  // place toAuthoringError runs), so the write side is the honest attribution (spec
18
18
  // cross-cutting note 7). `invalid-input`/`reserved-name` (V2 → V3 amendment, REQ-AEC-07/08)
19
- // are ALWAYS "authoring-rejected" — same rationale as outside-run: an SDK-side misuse
19
+ // are ALWAYS "authoring-rejected" — same rationale as outside-session: an SDK-side misuse
20
20
  // detection, not an engine round-trip refusal. The three surviving `source-*` reasons
21
21
  // (`schematic-local-files` S-002, REQ-AEC-10; `source-outside-package` retired by
22
22
  // `inline-collection-marker` S-002, ADR-0077) are likewise ALWAYS "authoring-rejected" —
@@ -30,7 +30,7 @@ function originFor(reason) {
30
30
  case "changes-too-large":
31
31
  case "unknown":
32
32
  return "write-rejected";
33
- case "outside-run":
33
+ case "outside-session":
34
34
  case "invalid-input":
35
35
  case "reserved-name":
36
36
  case "source-not-found":
@@ -81,7 +81,7 @@ function primaryPath(directive) {
81
81
  }
82
82
  }
83
83
  // REQ-AEC-06: message templates selected BY REASON, three-way — never by verb/path
84
- // presence. `outside-run` also has verb/path undefined but must NOT get the batch
84
+ // presence. `outside-session` also has verb/path undefined but must NOT get the batch
85
85
  // template (the context.test.ts:12 substring pin would break).
86
86
  //
87
87
  // REQ-AEC-09 (V2 → V3 amendment) adds two MORE families (invalid-input's two variants,
@@ -105,7 +105,7 @@ function messageFor(reason, verb, path) {
105
105
  case "path-collision":
106
106
  case "path-not-found":
107
107
  return `${verb} failed at ${path}: ${reason}`;
108
- case "outside-run":
108
+ case "outside-session":
109
109
  return ("@pbuilder/sdk: authoring verbs can only be used while a schematic is running — " +
110
110
  "call them inside your factory function, not at module load time.");
111
111
  case "unrepresentable-content":
@@ -159,7 +159,7 @@ export class AuthoringError extends Error {
159
159
  origin;
160
160
  /**
161
161
  * Counts directives applied within the failing flush before the offender — a
162
- * diagnostic for locating progress, NOT a persistence promise (a rejected run
162
+ * diagnostic for locating progress, NOT a persistence promise (a rejected Session
163
163
  * discards everything, ADR-0015).
164
164
  */
165
165
  appliedCount;