@pbuilder/sdk 0.2.2 → 0.2.3

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.
package/README.md CHANGED
@@ -1,161 +1,624 @@
1
1
  # @pbuilder/sdk
2
2
 
3
- > The public TypeScript/Bun authoring layer for [Project Builder](https://github.com/Project-Builder-Schematics) schematics.
3
+ > The TypeScript/Bun authoring layer for [Project Builder](https://github.com/Project-Builder-Schematics) schematics.
4
+
5
+ Project Builder exists to give developers — **and the AI agents working alongside them** —
6
+ deterministic code generation. A prompt produces something different every run; a
7
+ **schematic** — a typed, testable file-mutation program — produces the same files, byte for
8
+ byte, every time. You (or your agent) encode the change once, and from then on generation
9
+ is a program you run, not an output you review.
10
+
11
+ Three pieces cooperate, each with a sharply drawn responsibility:
12
+
13
+ ```mermaid
14
+ sequenceDiagram
15
+ actor U as Developer / AI agent
16
+ participant CLI as builder CLI
17
+ participant E as engine
18
+ participant F as factory<br/>(@pbuilder/sdk, Bun sidecar)
19
+
20
+ U->>CLI: builder execute default:hello
21
+ CLI->>E: start engine
22
+ E->>E: raise staging tree
23
+ E->>F: start Bun sidecar, run factory
24
+ loop commit phase — the SDK ↔ engine conversation
25
+ F->>E: read a file (find().read())
26
+ E-->>F: content, answered from the staging tree
27
+ F->>E: IR directives (create, replaceContent, …)
28
+ E->>E: commit directive to the staging tree
29
+ end
30
+ F-->>E: factory returns
31
+ E->>E: apply phase — staged result written to disk
32
+ E-->>CLI: result
33
+ CLI-->>U: ✓ done
34
+ ```
35
+
36
+ - The **`builder` CLI** owns every user- and agent-facing interaction: initialising a
37
+ workspace, scaffolding schematics, executing them (`init` / `new` / `execute`), and the
38
+ AI skill it drops into your repo so agents can drive it too. It ships the engine and
39
+ starts it on every run.
40
+ - **This SDK** owns the developer experience — typed verbs, templates, dialects, the
41
+ testing harness — and lowers everything you author into a small, stable **IR**
42
+ (instruction records). It holds a conversation with the engine over framed stdio: reads
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** —
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.
48
+ The engine is the only component that ever writes — and a failed run writes nothing.
4
49
 
5
- **Status: early development.** Not yet published to a registry — see the
6
- [quickstart](./docs/quickstart.md) for the local-install path (`bun link` or a packed
7
- tarball). APIs are unstable and will change.
50
+ That staging tree is what makes a schematic a conversation rather than a one-shot: while
51
+ the factory runs, the SDK reads file contents back from it and emits mutations in
52
+ response — idempotent, content-aware edits instead of blind overwrites.
8
53
 
9
- Start with the [quickstart](./docs/quickstart.md), or the [full doc index](./docs/README.md)
10
- for the reference set — verbs, error contract, dry-run, and
11
- [authoring a dialect](./docs/authoring-a-dialect.md) (structured, AST-aware mutation for one
12
- file type, e.g. `@pbuilder/sdk/typescript`, `@pbuilder/sdk/react`).
54
+ ## Installation
13
55
 
14
- ## What it is
56
+ ### macOS / Linux
15
57
 
16
- `@pbuilder/sdk` is the developer-facing library for authoring Project Builder **schematics** —
17
- programmable file mutations (create, remove, move, rename, copy, replaceContent) plus
18
- package-local reads (`scaffold`, `copyIn`, `create({ templateFile })`). The SDK never touches
19
- the disk:
20
- it translates what you author into an **IR** (instruction record) and hands it to the Project Builder
21
- engine, which owns execution and is the only component that writes to disk.
58
+ With [Homebrew](https://brew.sh) installed, grab the CLI (the `builder` binary) from the
59
+ tap:
60
+
61
+ ```sh
62
+ brew install project-builder-schematics/tap/pbuilder
63
+ ```
22
64
 
23
- It's a conversation, not a one-shot: while a schematic runs, the SDK queries the engine for file
24
- contents and emits mutations; the engine applies them to a staging tree and answers back. The SDK
25
- proposes; the engine disposes.
65
+ On Linux/WSL2 this needs a recent Homebrew — the cask install is verified on Homebrew 6.x;
66
+ older versions refuse casks on Linux. No Homebrew at all? Download the per-platform
67
+ tarball from the
68
+ [tap's releases](https://github.com/Project-Builder-Schematics/homebrew-tap/releases)
69
+ (`pbuilder_<version>_linux_amd64.tar.gz` and friends) and put `builder` on your `PATH` —
70
+ no brew required.
26
71
 
27
- ## Anatomy of a schematic
72
+ Schematics execute through a [Bun](https://bun.sh) sidecar, so Bun must be installed too:
28
73
 
74
+ ```sh
75
+ brew install oven-sh/bun/bun # or: curl -fsSL https://bun.sh/install | bash
29
76
  ```
30
- collection
31
- ├── schema.json # typed inputs (the contract with the user)
32
- └── factory.ts # the authoring logic (written against @pbuilder/sdk)
77
+
78
+ Bun is only the schematics' runtime — your project itself keeps whatever package manager
79
+ and tooling it already uses (npm, pnpm, yarn, …).
80
+
81
+ This guide was verified against CLI **0.6.0** and SDK **0.2.x**.
82
+
83
+ ### Windows
84
+
85
+ > **Not yet supported.** Windows builds of the CLI are on the roadmap; in the meantime the
86
+ > supported path on Windows is WSL2 (Ubuntu), using the Linux instructions above.
87
+
88
+ ### The SDK itself
89
+
90
+ You normally don't install it by hand — `builder init` (below) adds `@pbuilder/sdk` to your
91
+ project's `devDependencies` automatically. To add it manually, use whichever package
92
+ manager your project already uses:
93
+
94
+ ```sh
95
+ npm install -D @pbuilder/sdk # or: pnpm add -D / yarn add -D / bun add -d
33
96
  ```
34
97
 
35
- ## Scaffolding a folder
98
+ ## Your first schematic in five minutes
36
99
 
37
- A schematic's own `collection` folder can hold static/templated files alongside
38
- `schema.json`/`factory.ts` — `scaffold` walks one of those folders and mirrors it into the
39
- target tree, without you writing a `create()` call per file:
100
+ Every step below is runnable exactly as written.
40
101
 
41
- ```ts
42
- import { scaffold } from "@pbuilder/sdk/commons";
102
+ **1. Initialise a workspace** (inside any project — new or existing):
103
+
104
+ ```sh
105
+ builder init
106
+ ```
107
+
108
+ This creates `project-builder.json` (the workspace config), a `schematics/` folder, and an
109
+ AI skill under `.claude/skills/pbuilder/` — a command reference your coding agent picks up
110
+ automatically, no wiring needed. It also installs `@pbuilder/sdk` as a dev dependency,
111
+ creating a `package.json` first if the folder doesn't have one.
112
+
113
+ **2. Scaffold a schematic:**
114
+
115
+ ```sh
116
+ builder new schematic hello
117
+ ```
118
+
119
+ You get a registered, ready-to-edit package:
120
+
121
+ ```
122
+ schematics/hello/
123
+ ├── schema.json # typed inputs — the contract with the user
124
+ ├── schema.generated.ts # generated from schema.json — never edit
125
+ └── factory.ts # your authoring logic
126
+ ```
127
+
128
+ `project-builder.json` now lists it under `collections.default.hello`.
43
129
 
44
- export const run = (input: { name: string }) => {
45
- scaffold({ from: "files", to: "src/generated", options: { name: input.name } });
130
+ **3. Declare the inputs** — replace the generated `schema.json`'s contents with the
131
+ following; every property needs a `label` (codegen fails without it):
132
+
133
+ ```json
134
+ {
135
+ "properties": {
136
+ "name": { "type": "string", "label": "Service name", "required": true }
137
+ }
138
+ }
139
+ ```
140
+
141
+ Property types are `string`, `number`, `boolean`, and `enum` (which requires a non-empty
142
+ `choices` array); `default` and `description` are optional.
143
+
144
+ **4. Regenerate the input types:**
145
+
146
+ ```sh
147
+ bunx pbuilder-codegen schematics/hello
148
+ ```
149
+
150
+ This rewrites `schema.generated.ts` with an `Input` type derived from your schema — your
151
+ factory is typed against the schema, never against a hand-written shape.
152
+
153
+ **5. Write the factory** (`schematics/hello/factory.ts`):
154
+
155
+ ```ts
156
+ import { create, find, replaceContent } from "@pbuilder/sdk/commons";
157
+ import type { Input } from "./schema.generated.ts";
158
+
159
+ export default async (input: Input) => {
160
+ // create a new file
161
+ create(`src/services/${input.name}.ts`, {
162
+ template: `export const serviceName = "${input.name}";`,
163
+ options: {},
164
+ });
165
+
166
+ // content-aware edit: read the tree, then create or update
167
+ const existing = await find("services.txt").read();
168
+ if (existing === undefined) {
169
+ create("services.txt", { template: input.name, options: {} });
170
+ } else {
171
+ replaceContent("services.txt", `${existing}\n${input.name}`);
172
+ }
46
173
  };
47
174
  ```
48
175
 
49
- Each source file is classified automatically — never author-declared: valid, in-budget text
50
- renders by-value (through the same IR `create()` uses, `{= =}` tokens included); anything
51
- else (binary content, or a file over the size budget) travels by-reference instead, verbatim.
176
+ The engine invokes the module's **default export** — that's the factory. (This one builds
177
+ its output strings in TypeScript; the template language below is the declarative
178
+ alternative. And if your editor flags the `.ts`-extension import or `bun:test`, that's
179
+ just missing tsconfig settings — the [quickstart](./docs/quickstart.md) ships one; Bun
180
+ itself runs fine without it.)
181
+
182
+ **6. Execute it** — `default:hello` is `<collection>:<schematic>` as registered in
183
+ `project-builder.json`; inputs are passed as CLI flags:
184
+
185
+ ```sh
186
+ builder execute default:hello --name=payments
187
+ ```
188
+
189
+ ```
190
+ ~ services.txt
191
+ ~ src/services/payments.ts
192
+ ✓ done — 2 modified
193
+ ```
52
194
 
53
- `scaffold`, `copyIn`, and `create({ templateFile })` all resolve package-local files, so the
54
- call that runs this factory needs `packageDir` passed to it — without it, these verbs have
55
- no package to resolve against.
195
+ (`~` marks a path the run wrote.) Now run it again **with a different input**:
56
196
 
57
- Two escape hatches handle the single-file cases `scaffold` doesn't:
197
+ ```sh
198
+ builder execute default:hello --name=orders
199
+ ```
58
200
 
59
- - **`create(path, { templateFile })`** — an explicit RENDER request for one package-local
60
- file; a binary or over-budget file rejects fail-loud (never silently falls back to a copy).
61
- - **`copyIn(from, to, { force? })`** — an explicit NEVER-RENDER copy of one package-local
62
- file, verbatim — the escape for a text asset that would otherwise be classified by-value
63
- (e.g. one containing `{= =}`-like sequences that must survive untouched).
201
+ `services.txt` grows by one line instead of being clobbered — that's the read-back loop
202
+ from step 5 doing its job. Re-running with the **same** name, on the other hand, rejects
203
+ with `path-collision`: `create` is fail-closed on an existing path (pass `force: true` to
204
+ overwrite deliberately), and since a failed run writes nothing, your tree is left exactly
205
+ as it was.
206
+
207
+ **7. Test it** without the CLI or a running engine — see
208
+ [Testing your factory](#testing-your-factory) below.
209
+
210
+ From here: [Authoring verbs](./docs/authoring-verbs.md) is the full reference for
211
+ everything you can do inside a factory, and the
212
+ [quickstart](./docs/quickstart.md) covers the standalone-package setup (tsconfig
213
+ included) in more depth.
214
+
215
+ ## The seven mutations
216
+
217
+ Everything a factory can do to the tree is one of seven mutation verbs, all imported from
218
+ `@pbuilder/sdk/commons`:
219
+
220
+ | Verb | What it schedules |
221
+ |---|---|
222
+ | [`create(path, opts)`](./docs/authoring-verbs.md#create) | A new file. `path` and `template` are template strings rendered against one `options` object; the `templateFile` overload renders a package-local file instead. |
223
+ | [`replaceContent(path, content)`](./docs/authoring-verbs.md#replacecontent) | Wholesale replacement of an existing file's content. |
224
+ | [`remove(path)`](./docs/authoring-verbs.md#remove) | A deletion. Idempotent on an absent path. |
225
+ | [`rename(path, newName)`](./docs/authoring-verbs.md#rename) | A basename-only rename in place. |
226
+ | [`move(path, toDir)`](./docs/authoring-verbs.md#move) | A move to a different directory. |
227
+ | [`copy(from, to)`](./docs/authoring-verbs.md#copy) | A tree-to-tree copy, chainable via the returned handle. |
228
+ | [`copyIn(from, to)`](./docs/authoring-verbs.md#copyin) | A package-local file copied into the tree **verbatim** — the never-render escape hatch. |
229
+
230
+ The verbs that write to a new path — `create`, `rename`, `move`, `copy`, `copyIn`, and
231
+ `scaffold` — are fail-closed on collision and accept `{ force: true }` for a deliberate
232
+ overwrite: `create` and `scaffold` inside their options/args object, the rest as a
233
+ trailing argument.
234
+
235
+ Three companions round out the surface:
236
+
237
+ - [`find(path).read()`](./docs/authoring-verbs.md#the-read-trichotomy-findpathread) — read
238
+ a file back from the staging tree.
239
+ - [`scaffold({ from, to, options })`](./docs/authoring-verbs.md#scaffold) — mirror an
240
+ entire package-local folder into the tree, with dynamic file names. The workhorse for
241
+ multi-file generators — see [Scaffolding a folder of templates](#scaffolding-a-folder-of-templates).
242
+ - [`dryRun()`](./docs/dry-run.md) — inspect the directives still **pending**. A `read()`
243
+ drains the buffer, so call it before reading if you want the full picture.
244
+
245
+ ### What to keep in mind
246
+
247
+ Rules that save you real debugging time — each one is a mistake we've watched happen:
248
+
249
+ - **Always pass `options: {}` to `create`**, even when the template has no tokens. The
250
+ type requires it — and in untyped call sites (plain JS, `any`) omitting it puts
251
+ `undefined` in the directive batch, rejecting the write as unrepresentable.
252
+ - **`find().read()` is a trichotomy**: `undefined` means the file is absent, `""` means it
253
+ exists and is empty. Branch on `=== undefined` — never `if (!content)`, which conflates
254
+ the two. (`classifyContent()`, from the same module, turns the result into a value you
255
+ can `switch` over exhaustively.)
256
+ - **Make mutations idempotent.** Factories re-run against already-generated projects; check
257
+ whether your marker/import/entry is already present before inserting it. The step-5
258
+ example shows the read-back mechanics — a production factory would also skip the append
259
+ when the name is already listed.
260
+ - **Nothing touches disk while your factory runs.** Verbs *schedule* directives; during the
261
+ run the engine commits them to the staging tree only (that's why reading a path you
262
+ created earlier in the same run sees the staged content). Disk writes happen in the apply
263
+ phase, after the factory returns — a thrown error before return means nothing is written
264
+ at all.
265
+ - **Errors are structured.** A rejected run surfaces an `AuthoringError` with
266
+ `verb`/`path`/`reason` fields telling you which directive failed and why (one label
267
+ quirk: content replacement reports `verb: "modify"` — including plain
268
+ `replaceContent()`) — see the [error contract](./docs/authoring-errors.md).
269
+
270
+ ## How templates work
271
+
272
+ `create`'s `path` and `template` are both **template strings**, rendered against the same
273
+ single `options` object — that's the core idea:
64
274
 
65
- Two things worth knowing before you rely on `scaffold`:
275
+ ```ts
276
+ create("src/{= .name | dasherize =}/{= .name | dasherize =}.component.ts", {
277
+ template:
278
+ "export class {= .name | classify =}Component {\n" +
279
+ "{= range .methods =} {= .name =}() {}\n{= end =}}\n",
280
+ options: {
281
+ name: "userProfile",
282
+ methods: [{ name: "load" }, { name: "save" }],
283
+ },
284
+ });
285
+ ```
66
286
 
67
- - **Packaging caveat**: an empty `from` folder scaffolds as a silent no-op — but npm tarball
68
- packaging commonly drops empty directories, so an empty folder may not even survive
69
- `npm publish`. Ship a placeholder file if the folder's presence matters.
70
- - **Symlinked directories are never traversed** (even when their target resolves inside the
71
- package), and a single `scaffold` call is capped at 10,000 enumerated entries.
287
+ renders the path `src/user-profile/user-profile.component.ts` with content:
72
288
 
73
- ## Design at a glance
289
+ ```ts
290
+ export class UserProfileComponent {
291
+ load() {}
292
+ save() {}
293
+ }
294
+ ```
74
295
 
75
- - **Surface ≠ contract** — the SDK gives you rich authoring verbs; they lower to a small, stable IR.
76
- - **AST-agnostic engine** — AST tooling (ts-morph, postcss, cheerio) lives in SDK dialect modules,
77
- never in the engine. New file types are new packages, not engine releases.
78
- - **Bun-native** — TypeScript runs directly, no transpile step.
79
- - **`dist/core/**` ships, documented, not stripped** — the published tarball intentionally
80
- includes `dist/core/**`, because `./testing`'s runtime code imports `../core/context.ts`
81
- at runtime and needs it physically present on disk. `@pbuilder/sdk/core` still stays
82
- unreachable via `package.json#exports` regardless — the boundary is advisory-by-convention
83
- (no import path resolves it), not enforced by tarball exclusion.
296
+ The essentials:
297
+
298
+ - **Delimiters are `{= =}`, not `{{ }}`.** Inside them you reference options with a leading
299
+ dot: `{= .name =}`, nested walks like `{= .user.address.city =}`, and `{= . =}` for the
300
+ current context inside a loop.
301
+ - **Rendering happens in the engine at `builder execute` time, never in the SDK.** Your
302
+ factory ships the template and options verbatim — so template errors (a typo'd option
303
+ name, a type mismatch) surface at run time, and the test harness stores the raw
304
+ `{= .name =}` text, not rendered output.
305
+ - **7 pipes transform string values**, chained left to right with `|`. From `"userProfile"`:
306
+ `upper` → `USERPROFILE`, `lower` → `userprofile`, `capitalize` → `UserProfile`,
307
+ `dasherize` → `user-profile`, `underscore` → `user_profile`, `camelize` → `userProfile`,
308
+ `classify` → `UserProfile`. There is **no pluralize**, and `classify` does **not**
309
+ singularize (`users` → `Users`, not `User`) — if you need the singular, pass it in your
310
+ options.
311
+
312
+ The syntax comes from Go's `text/template`, **not** JavaScript — two rules prevent most of
313
+ the surprises:
314
+
315
+ - **Blocks open with a keyword and close with `{= end =}`** — no braces. Loops are `range`
316
+ (the dot becomes the current element), conditionals are `if`/`else if`/`else`:
317
+
318
+ ```
319
+ {= range .methods =} {= .name =}() {}
320
+ {= end =}
321
+ {= if eq .kind "primary" =}main{= else =}other{= end =}
322
+ ```
323
+
324
+ - **Comparisons and logic are operator-first function calls**, never infix: `eq a b`,
325
+ `ne`, `lt`, `gt`, `and`, `or`, `not` — `a === b && c` does not exist; you write
326
+ `and (eq .a .b) .c`.
327
+
328
+ Two traps worth knowing before they bite: **empty arrays and objects are falsy** (so
329
+ `{= if .items =}` is the "has items" check — no `.length`), and **number literals must match
330
+ the numeric type** they're compared against (option numbers are decimals: `eq .count 2.0`,
331
+ never `eq .count 2`).
332
+
333
+ If templating gets in your way, the escape hatch is always available: build the final
334
+ strings in TypeScript and pass a token-free template — it renders verbatim. For the full
335
+ language — `with`, variables, whitespace rules, output-path templating, sandbox limits, and
336
+ the error taxonomy — see [Authoring `create` templates](./docs/create-templates.md).
337
+
338
+ ## Scaffolding a folder of templates
339
+
340
+ For anything bigger than a couple of files, don't write one `create()` per file — keep a
341
+ folder of template files inside your schematic package and mirror it with **`scaffold`**:
84
342
 
85
- ## Testing your factory
343
+ ```
344
+ schematics/service/
345
+ ├── schema.json
346
+ ├── schema.generated.ts
347
+ ├── factory.ts
348
+ └── files/ # your template folder
349
+ ├── __name@dasherize__.service.ts.template
350
+ ├── __name@dasherize__.spec.ts.template
351
+ └── config/
352
+ └── settings.json
353
+ ```
354
+
355
+ ```ts
356
+ import { scaffold } from "@pbuilder/sdk/commons";
357
+ import type { Input } from "./schema.generated.ts";
358
+
359
+ export default (input: Input) => {
360
+ scaffold({
361
+ from: "files",
362
+ to: "src/services/__name@dasherize__",
363
+ options: { name: input.name },
364
+ });
365
+ };
366
+ ```
367
+
368
+ With `name: "userProfile"` this emits `src/services/user-profile/user-profile.service.ts`,
369
+ `…/user-profile.spec.ts`, and `…/config/settings.json` — contents rendered against the same
370
+ `options`, using the template language above.
371
+
372
+ ### Dynamic file names
86
373
 
87
- `@pbuilder/sdk/testing` is the third audience surface — `author-testing` (ADR-0033) — the
88
- supported way to test a factory you're authoring, in-memory, without a running engine. It
89
- ships `0.x`, semver-exempt (mirroring the kit) until real use validates the result shape.
374
+ File and folder names carry dynamic values through **filename tokens**:
90
375
 
91
- This is distinct from `./conformance`: `./testing` tests **your own factory's** behaviour;
92
- `./conformance` conformance-tests a **dialect or op-pack** implementation (parse/print
93
- fidelity), not a factory.
376
+ - `__name__` becomes `{= .name =}` — the `name` option, rendered into the path.
377
+ - `__name@pipe__` becomes `{= .name | pipe =}` — same 7 pipes as templates, so
378
+ `__name@dasherize__.service.ts` with `name: "userProfile"` lands as
379
+ `user-profile.service.ts`.
380
+ - The `to` destination is translated the same way — that's how one `scaffold` call fans out
381
+ into a per-option directory (`to: "src/services/__name@dasherize__"` above).
382
+
383
+ `scaffold` only rewrites the marker syntax; the rendering itself happens in the engine,
384
+ exactly as for `create` templates.
385
+
386
+ Three more per-entry controls, applied in a pinned order (`rename` first, token translation
387
+ second, `.template` strip last):
388
+
389
+ - **`.template` suffix** — stripped from the destination name. Use it to keep template
390
+ files from looking like real source to your editor/tooling
391
+ (`user.service.ts.template` → `user.service.ts`).
392
+ - **`rename`** — a static remap table matched against the *original* source-relative path,
393
+ for the odd file whose destination doesn't follow the pattern.
394
+ - **`include` / `exclude`** — glob filters over the original paths (`*` within a segment,
395
+ `**` across segments; `exclude` wins).
396
+
397
+ Each surviving file is classified automatically: valid, in-budget text renders as a
398
+ template; binary or over-budget files travel verbatim (`copyIn`). Caveats: an empty `from`
399
+ folder is a silent no-op (and npm packaging commonly drops empty directories — ship a
400
+ placeholder if the folder's presence matters) while `include`/`exclude` filters that
401
+ eliminate every entry reject loudly, nested symlinked directories are skipped
402
+ silently while a symlinked `from` root rejects outright, and a single call caps at 10,000
403
+ entries. Full edge-and-error semantics:
404
+ [`scaffold` in Authoring verbs](./docs/authoring-verbs.md#scaffold).
405
+
406
+ `scaffold`, `copyIn`, and `create({ templateFile })` resolve **package-local** files
407
+ (relative to your schematic's folder), so the run must know where that package is — the CLI
408
+ passes this automatically; in tests you pass `packageDir` yourself (below).
409
+
410
+ ## Testing your factory
94
411
 
95
- Import `runFactoryForTest` from `@pbuilder/sdk/testing`, pass it a bare
96
- `(input) => void | Promise<void>` factory function, and assert on the result. Templates are
97
- stored **verbatim** — `{{...}}` interpolation is the engine's job, not the harness's:
412
+ `@pbuilder/sdk/testing` runs a factory in-memory — no CLI, no engine, no disk. Create
413
+ `schematics/hello/factory.test.ts` next to the factory:
98
414
 
99
415
  ```ts
416
+ import { test, expect } from "bun:test";
100
417
  import { runFactoryForTest } from "@pbuilder/sdk/testing";
101
418
  import { create } from "@pbuilder/sdk/commons";
102
- import { expect, test } from "bun:test";
103
419
 
104
- test("factory writes a greeting file", async () => {
105
- const run = (input: { name: string }) => {
106
- create("src/greeting.ts", {
107
- template: `export const greeting = '${input.name}';`,
108
- options: {},
109
- });
110
- };
420
+ // in your schematic this is `import run from "./factory.ts";`
421
+ const run = (input: { name: string }) => {
422
+ create(`src/services/${input.name}.ts`, {
423
+ template: `export const serviceName = "${input.name}";`,
424
+ options: {},
425
+ });
426
+ };
111
427
 
112
- const result = await runFactoryForTest(run, { name: "world" });
428
+ test("factory creates the service file", async () => {
429
+ const result = await runFactoryForTest(run, { name: "payments" });
113
430
 
114
431
  expect(result.error).toBeUndefined();
115
- expect(result.tree.get("src/greeting.ts")).toEqual("export const greeting = 'world';");
432
+ expect(result.tree.get("src/services/payments.ts"))
433
+ .toEqual(`export const serviceName = "payments";`);
116
434
  });
117
435
  ```
118
436
 
119
- `runFactoryForTest`'s third parameter is an options bag — `seed` pre-populates the
120
- in-memory tree so your factory can read existing files back before writing new ones:
437
+ ```sh
438
+ bun test schematics
439
+ ```
440
+
441
+ This runs only your schematic tests under Bun — your app's own test runner (Jest, Vitest,
442
+ whatever you use) stays untouched and the two coexist in one repo.
443
+
444
+ Two things to know:
445
+
446
+ - `result.tree` contains **committed writes only**. Files you pre-populate via the `seed`
447
+ option are readable by the factory but never appear in the tree — which is exactly how
448
+ you assert idempotence (an untouched seed is absent from the tree):
449
+
450
+ ```ts
451
+ import { test, expect } from "bun:test";
452
+ import { runFactoryForTest } from "@pbuilder/sdk/testing";
453
+ import { find, replaceContent } from "@pbuilder/sdk/commons";
454
+
455
+ test("a seeded file is readable; only the write is committed", async () => {
456
+ const run = async (input: { name: string }) => {
457
+ const existing = await find("services.txt").read();
458
+ replaceContent("services.txt", `${existing}\n${input.name}`);
459
+ };
460
+
461
+ const seed = { "services.txt": "payments" };
462
+ const result = await runFactoryForTest(run, { name: "orders" }, { seed });
463
+
464
+ expect(result.error).toBeUndefined();
465
+ expect(result.tree.get("services.txt")).toEqual("payments\norders");
466
+ });
467
+ ```
468
+
469
+ - The options bag's other field, `packageDir` (pass `import.meta.dir`), anchors the
470
+ package-local verbs (`scaffold`, `copyIn`, `create({ templateFile })`) and opts the run
471
+ into schema-derived input validation against the adjacent `schema.json`. Without it those
472
+ verbs have nothing to resolve against.
473
+
474
+ Templates are stored **verbatim** in the test tree — rendering is the engine's job, and the
475
+ harness doesn't fake it. `./testing` ships `0.x`, semver-exempt, until real use validates
476
+ the result shape. (It tests *your factory*; the separate `./conformance` surface
477
+ conformance-tests a *dialect or op-pack* implementation — not the same audience.)
478
+
479
+ ## Beyond the verbs: dialects
480
+
481
+ When string-level mutation isn't enough — "add an import to this module", "set a prop on
482
+ this JSX element" — **dialects** provide structured, AST-aware operations for one file
483
+ type: see [authoring a dialect](./docs/authoring-a-dialect.md) for the full story. Two
484
+ ship today: `@pbuilder/sdk/typescript` and `@pbuilder/sdk/react`.
485
+
486
+ A dialect's entry point is its own `find(path)`: it opens a **coalescing, awaitable
487
+ handle**. Every op you chain mutates the same live AST, and the handle serializes to
488
+ exactly **one** `replaceContent`-style directive when it flushes — chaining three ops does
489
+ not produce three writes.
490
+
491
+ ### `@pbuilder/sdk/typescript`
121
492
 
122
493
  ```ts
123
- import { runFactoryForTest } from "@pbuilder/sdk/testing";
124
- import { find, create } from "@pbuilder/sdk/commons";
125
- import { expect, test } from "bun:test";
494
+ import * as ts from "@pbuilder/sdk/typescript";
126
495
 
127
- test("factory derives a file from a seeded config", async () => {
128
- const run = async () => {
129
- const raw = await find("config.json").read();
130
- const { name } = JSON.parse(raw ?? "{}") as { name: string };
131
- create("src/greeting.ts", { template: `export const greeting = '${name}';`, options: {} });
132
- };
496
+ await ts.find("src/index.ts")
497
+ .addImport("readFileSync", "node:fs")
498
+ .addFunction("hi", "(): void {}", { export: true });
499
+ ```
133
500
 
134
- const seed = { "config.json": JSON.stringify({ name: "seeded" }) };
135
- const result = await runFactoryForTest(run, undefined, { seed });
501
+ | Op | What it does |
502
+ |---|---|
503
+ | `addImport(name, from)` | Adds `import { name } from "from"`, merging into an existing clause from the same module. Idempotent — calling it twice never duplicates the import. |
504
+ | `removeImport(name, from)` | Removes the named binding; deletes the whole statement when it was the last one. Idempotent on an absent binding. |
505
+ | `addFunction(name, source, opts?)` | Appends a top-level function. `source` **includes** the braces (`"(): void {}"`). |
506
+ | `addVariable(name, initializer, opts?)` | Appends a top-level variable (`kind` defaults to `const`). |
507
+ | `addClass(name, source, opts?)` | Appends a top-level class. `source` **excludes** the braces — the op adds them. |
508
+ | `.modify(fn)` | The universal escape hatch: direct [ts-morph](https://ts-morph.com) access to the file's AST for anything the named ops don't cover. |
136
509
 
137
- expect(result.error).toBeUndefined();
138
- expect(result.tree.get("src/greeting.ts")).toEqual("export const greeting = 'seeded';");
139
- // the seed itself is readable but never appears in the committed tree
140
- expect(result.tree.has("config.json")).toBe(false);
141
- });
510
+ The `add*` ops fail loud on a name collision with an existing value declaration or import
511
+ binding (two value declarations sharing a name is invalid TypeScript); a `type`/`interface`
512
+ sharing the name does not collide. `source`/`initializer` strings are inserted **verbatim**
513
+ — never validated or sanitized — so the author owns their syntax, and anything derived from
514
+ untrusted input is the author's responsibility to sanitize.
515
+
516
+ ### `@pbuilder/sdk/react`
517
+
518
+ Mutates `.tsx` files — `find()` requires the explicit `.tsx` extension (extensionless and
519
+ `.jsx` paths are rejected, never normalized). The v1 op-pack — a dialect's bundle of named
520
+ ops — is deliberately minimal: two structured ops, with `.modify(fn)` as the escape hatch
521
+ for everything else:
522
+
523
+ ```ts
524
+ import * as react from "@pbuilder/sdk/react";
525
+
526
+ // src/Button.tsx before: const el = <Button />;
527
+ await react
528
+ .find("src/Button.tsx")
529
+ .addImport("handleClick", "./handlers")
530
+ .setJsxProp("Button", "onClick", "{handleClick}");
531
+ // -> import { handleClick } from "./handlers";
532
+ // -> const el = <Button onClick={handleClick} />;
533
+ ```
534
+
535
+ | Op | What it does |
536
+ |---|---|
537
+ | `addImport(name, from)` | Same contract as the TypeScript dialect's — idempotent, named-binding-only (no default/namespace imports in v1). |
538
+ | `setJsxProp(element, prop, value?)` | Sets a prop on **the one** element with that tag name — zero or multiple matches reject loudly. `value` takes three forms: `'"hi"'` (string), `'{count}'` (expression), or omitted (boolean shorthand). |
539
+
540
+ `setJsxProp`'s `value` is emitted verbatim into executable code — same trust boundary as
541
+ the TypeScript `source` strings. One React-specific subtlety: an inserted prop lands after
542
+ a trailing `{...spread}`, so it **wins** at runtime under React's later-position precedence.
543
+
544
+ ### `.modify()` — the universal escape hatch
545
+
546
+ Every dialect handle carries one universal op alongside its named ops: `.modify(ast => …)`.
547
+ Your callback receives the **same live AST instance the named ops mutate** — a ts-morph
548
+ `SourceFile` — so anything a named op could do, `.modify()` can do too, without waiting for
549
+ a structured op to exist:
550
+
551
+ ```ts
552
+ import * as ts from "@pbuilder/sdk/typescript";
553
+
554
+ await ts.find("src/app.module.ts")
555
+ .addImport("BooksModule", "./books/books.module")
556
+ .modify((ast) => {
557
+ // full ts-morph surface available here — decorators, call args, anything
558
+ const imports = ast
559
+ .getClassOrThrow("AppModule")
560
+ .getDecoratorOrThrow("Module")
561
+ .getArguments()[0];
562
+ // …structured edits the named ops don't cover yet
563
+ });
142
564
  ```
143
565
 
144
- `packageDir` is the options bag's other field — pass `import.meta.dir` to opt a factory into
145
- schema-derived run-boundary validation against an adjacent `schema.json`. It's more than a
146
- validation toggle, though: it's also the mandatory resolution anchor for the package-local
147
- verb family (`scaffold`, `copyIn`, `create({ templateFile })`) — omit it and you keep the
148
- untyped, unvalidated escape hatch shown above, but those verbs have nothing to resolve
149
- against.
566
+ Because it joins the same coalescing chain, mixing named ops and `.modify()` on one handle
567
+ still flushes as a **single** write. Two things to respect:
568
+
569
+ - **Operate only on the `ast` the callback hands you.** If your schematic depends on
570
+ ts-morph directly, that is a *separate realm* from the SDK's internal ts-morph — a
571
+ `Node` or `SourceFile` from your own import is not interchangeable with the callback's
572
+ AST, even at the identical ts-morph version. Never pass ts-morph objects across that
573
+ boundary.
574
+ - **`.modify()` runs with full process privilege — it is not a sandbox.** Your own
575
+ callbacks are your own trust; before importing a *third-party* dialect or op-pack built
576
+ on it, read [SECURITY.md](./SECURITY.md).
577
+
578
+ ### Going deeper
579
+
580
+ Everything dialect-related lives in one reference page —
581
+ [Authoring a dialect](./docs/authoring-a-dialect.md): the complete method-by-method
582
+ contracts of both shipped dialects (collision rules, idempotency, rejection semantics),
583
+ how coalescing turns chained edits into one directive, async usage, and building a dialect
584
+ of your own with `defineDialect`/`defineOpPack`, validated by the conformance kit (the
585
+ `./conformance` suite that proves a dialect parses and prints files with full fidelity).
586
+ If a named op behaves in a way that surprises you, that page is where the exact contract
587
+ is written down.
588
+
589
+ ## Documentation
590
+
591
+ The full reading path lives in [`docs/`](./docs/README.md):
592
+
593
+ 1. [Quickstart](./docs/quickstart.md) — standalone factory package, tsconfig, codegen, test.
594
+ 2. [Authoring verbs](./docs/authoring-verbs.md) — the seven verbs + `find().read()` in full.
595
+ 3. [Authoring `create` templates](./docs/create-templates.md) — the template language.
596
+ 4. [Error contract](./docs/authoring-errors.md) — `AuthoringError` and recovery.
597
+ 5. [Dry-run](./docs/dry-run.md) — previewing planned changes.
598
+ 6. [Authoring a dialect](./docs/authoring-a-dialect.md) — AST-aware mutation per file type.
599
+
600
+ ## Design at a glance
601
+
602
+ - **Surface ≠ contract** — rich authoring verbs lower to a small, stable IR.
603
+ - **AST-agnostic engine** — AST tooling (ts-morph, …) lives in SDK dialect modules, never in
604
+ the engine. New file types are new packages, not engine releases.
605
+ - **Bun-native** — factories run as TypeScript directly, no transpile step.
150
606
 
151
607
  ## Development
152
608
 
609
+ Contributing to the SDK itself:
610
+
153
611
  ```sh
154
612
  bun install
155
613
  bun test
156
614
  bun run typecheck
157
615
  ```
158
616
 
617
+ Packaging note: `dist/core/**` ships in the tarball, documented, not stripped —
618
+ `./testing`'s runtime imports it, so it must be physically present; `@pbuilder/sdk/core`
619
+ stays unreachable via `package.json#exports` regardless (the boundary is
620
+ advisory-by-convention, not enforced by tarball exclusion).
621
+
159
622
  `conformance/` — SDK↔engine live conformance corpus, consumed by `project-builder-engine` as a
160
623
  pinned git submodule; see `conformance/README.md` and `CONFORMANCE-CORPUS-HANDOFF.md`.
161
624
 
@@ -169,7 +632,7 @@ locally instead of on first contact with a consumer.
169
632
  # terminal 1 — start the registry (runs in foreground)
170
633
  bun run registry:up
171
634
 
172
- # terminal 2 — build + publish a local prerelease (0.0.0-local.<timestamp>, dist-tag `local`)
635
+ # terminal 2 — build + publish the version in package.json under dist-tag `local`
173
636
  bun run publish:local
174
637
  ```
175
638
 
@@ -192,8 +655,8 @@ Notes:
192
655
 
193
656
  - The `@pbuilder/*` scope is local-authoritative (no npmjs proxy) — a local publish can never
194
657
  be shadowed by the public package. Everything else proxies through to npmjs with caching.
195
- - `publish:local` restores `package.json` via `git checkout` afterwards — run it with a clean
196
- `package.json`, or uncommitted changes to it will be lost.
658
+ - `publish:local` publishes the version currently in `package.json` — publishing the same
659
+ version twice fails, so bump the version or reset the registry storage between publishes.
197
660
  - To reset the registry, stop it and delete `tools/verdaccio/storage/` (git-ignored).
198
661
  - Registry config lives in `tools/verdaccio/config.yaml`.
199
662
 
@@ -13,7 +13,7 @@ export type { ContentState } from "./classify-content.ts";
13
13
  *
14
14
  * @example
15
15
  * const opts: CreateOptions = {
16
- * template: "export const {{name}} = '{{value}}';",
16
+ * template: "export const {= .name =} = '{= .value =}';",
17
17
  * options: { name: "greeting", value: "hello" },
18
18
  * };
19
19
  */
@@ -87,7 +87,7 @@ export declare function find(path: string): FoundHandle;
87
87
  *
88
88
  * @example
89
89
  * create("src/index.ts", {
90
- * template: "export const version = '{{version}}';",
90
+ * template: "export const version = '{= .version =}';",
91
91
  * options: { version: "1.0.0" },
92
92
  * });
93
93
  * @example
@@ -68,7 +68,7 @@ export declare function requirePackageAnchors(missingAnchorMessage: string): {
68
68
  * // 2. Internal: wrap a bare author fn into a client-driven runner:
69
69
  * const bareFactory = (input: Input) => {
70
70
  * create("server.config.ts", {
71
- * template: "export const port = {{port}};",
71
+ * template: "export const port = {= .port =};",
72
72
  * options: { port: input.port },
73
73
  * });
74
74
  * };
@@ -254,7 +254,7 @@ function checkReservedNames(packageDir) {
254
254
  * // 2. Internal: wrap a bare author fn into a client-driven runner:
255
255
  * const bareFactory = (input: Input) => {
256
256
  * create("server.config.ts", {
257
- * template: "export const port = {{port}};",
257
+ * template: "export const port = {= .port =};",
258
258
  * options: { port: input.port },
259
259
  * });
260
260
  * };
@@ -11,7 +11,7 @@ export type JsonValue = string | number | boolean | null | JsonValue[] | {
11
11
  * op: "create",
12
12
  * create: {
13
13
  * pathTemplate: "src/greeting.ts",
14
- * template: "export const greeting = '{{name}}';",
14
+ * template: "export const greeting = '{= .name =}';",
15
15
  * options: { name: "world" },
16
16
  * },
17
17
  * };
@@ -2,7 +2,7 @@
2
2
  "manifestVersion": 1,
3
3
  "algorithm": "sha256",
4
4
  "entry": "dist/bin/pbuilder-runner.js",
5
- "packageVersion": "0.2.2",
5
+ "packageVersion": "0.2.3",
6
6
  "files": [
7
7
  {
8
8
  "path": "dist/bin/pbuilder-runner.js",
@@ -14,7 +14,7 @@
14
14
  },
15
15
  {
16
16
  "path": "dist/core/context.js",
17
- "sha256": "4f9e5b221964e5e9538c4c34158737d667c2a3bbd97358c750c786e918f0a6e5"
17
+ "sha256": "5a8b416fbf4c715e320dc51892766285d1d1ecb3733cfd5c138596e6bd4f969b"
18
18
  },
19
19
  {
20
20
  "path": "dist/core/directive-factory.js",
@@ -98,7 +98,7 @@
98
98
  },
99
99
  {
100
100
  "path": "package.json",
101
- "sha256": "e67ee94357f6293c57df74c4f8501b9fb013737b7f0c950827d86976bc332a85"
101
+ "sha256": "a66ef4b611d45015cda1d3fa85e55d516adec5800225d803697796ef1452bf1e"
102
102
  }
103
103
  ]
104
104
  }
@@ -13,7 +13,7 @@ export interface RunResult {
13
13
  /**
14
14
  * The committed tree (`ContractFake.committedTree()`), path → content. Committed writes
15
15
  * ONLY — an unmodified seed path is never present here, even if the factory read it.
16
- * Content is stored verbatim — `{{...}}` template placeholders are never rendered here;
16
+ * Content is stored verbatim — `{= ... =}` template placeholders are never rendered here;
17
17
  * interpolation is the engine's job, not the harness's.
18
18
  */
19
19
  tree: ReadonlyMap<string, string>;
@@ -61,7 +61,7 @@ export type { Batch, Directive };
61
61
  * test("factory writes a greeting file", async () => {
62
62
  * const run = (input: { name: string }) => {
63
63
  * create("src/greeting.ts", {
64
- * template: "export const greeting = '{{name}}';",
64
+ * template: "export const greeting = '{= .name =}';",
65
65
  * options: { name: input.name },
66
66
  * });
67
67
  * };
@@ -75,7 +75,7 @@ export type { Batch, Directive };
75
75
  * throw result.error;
76
76
  * }
77
77
  *
78
- * expect(result.tree.get("src/greeting.ts")).toEqual("export const greeting = '{{name}}';");
78
+ * expect(result.tree.get("src/greeting.ts")).toEqual("export const greeting = '{= .name =}';");
79
79
  * });
80
80
  */
81
81
  export declare function runFactoryForTest<O>(fn: (input: O) => void | Promise<void>, input: O, options?: {
@@ -35,7 +35,7 @@ import { ContractFake } from "./contract-fake.js";
35
35
  * test("factory writes a greeting file", async () => {
36
36
  * const run = (input: { name: string }) => {
37
37
  * create("src/greeting.ts", {
38
- * template: "export const greeting = '{{name}}';",
38
+ * template: "export const greeting = '{= .name =}';",
39
39
  * options: { name: input.name },
40
40
  * });
41
41
  * };
@@ -49,7 +49,7 @@ import { ContractFake } from "./contract-fake.js";
49
49
  * throw result.error;
50
50
  * }
51
51
  *
52
- * expect(result.tree.get("src/greeting.ts")).toEqual("export const greeting = '{{name}}';");
52
+ * expect(result.tree.get("src/greeting.ts")).toEqual("export const greeting = '{= .name =}';");
53
53
  * });
54
54
  */
55
55
  export async function runFactoryForTest(fn, input, options) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@pbuilder/sdk",
3
- "version": "0.2.2",
4
- "description": "The public TypeScript/Bun authoring layer for Project Builder schematics. Authors file mutations (create, modify, remove, rename, move, copy, copyIn), lowers them to IR, and talks to the Project Builder engine over framed stdio (see docs/engine-sdk-wire-spec.md).",
3
+ "version": "0.2.3",
4
+ "description": "The public TypeScript/Bun authoring layer for Project Builder schematics. Authors file mutations (create, replaceContent, remove, rename, move, copy, copyIn), lowers them to IR, and talks to the Project Builder engine over framed stdio (see docs/engine-sdk-wire-spec.md).",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "private": false,