@pbuilder/sdk 0.2.4 → 0.3.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.
package/README.md CHANGED
@@ -150,6 +150,11 @@ bunx pbuilder-codegen schematics/hello
150
150
  This rewrites `schema.generated.ts` with an `Input` type derived from your schema — your
151
151
  factory is typed against the schema, never against a hand-written shape.
152
152
 
153
+ To regenerate every registered schematic instead, run `bunx pbuilder-codegen` from the
154
+ workspace or a descendant, or `bunx pbuilder-codegen --project ./workspace` from any
155
+ directory. See [Project-wide type generation](#project-wide-type-generation) for the
156
+ accepted registrations and failure behavior.
157
+
153
158
  **5. Write the factory** (`schematics/hello/factory.ts`):
154
159
 
155
160
  ```ts
@@ -212,6 +217,80 @@ everything you can do inside a factory, and the
212
217
  [quickstart](./docs/quickstart.md) covers the standalone-package setup (tsconfig
213
218
  included) in more depth.
214
219
 
220
+ ## Project-wide type generation
221
+
222
+ ```sh
223
+ bunx pbuilder-codegen # nearest project-builder.json, walking upward
224
+ bunx pbuilder-codegen --project ./workspace # exactly this directory's project-builder.json
225
+ bunx pbuilder-codegen ./schematics/hello # existing single-directory mode
226
+ ```
227
+
228
+ Project mode processes **all collections**, not only `default`. The first marker found
229
+ owns discovery: malformed, unreadable, directory-shaped, or dangling markers fail without
230
+ falling back to a parent. Missing configuration or malformed top-level configuration fails
231
+ before generation. Absent or empty `collections` succeeds with zero work. A configuration
232
+ symlink does not transfer write authority to its target's directory.
233
+
234
+ Two registration forms are supported:
235
+
236
+ ```json
237
+ {
238
+ "collections": {
239
+ "local": { "hello": { "path": "./schematics/hello" } },
240
+ "shared": { "path": "./schematics/collection.json" }
241
+ }
242
+ }
243
+ ```
244
+
245
+ Both `path` values are relative to the selected project root (absolute filesystem paths
246
+ are also accepted, subject to write containment). A direct directory must contain exactly
247
+ one regular `factory.ts` or `factory.js`. The collection manifest uses:
248
+
249
+ ```json
250
+ {
251
+ "schematics": {
252
+ "widget": { "factory": "./dist/widget.js#createWidget" }
253
+ }
254
+ }
255
+ ```
256
+
257
+ Manifest module paths are relative to the manifest's directory. An explicit export is
258
+ required: split at the **last `#`**, with a nonempty module path and an identifier-shaped
259
+ export (`default` is valid). Factories are never imported or executed, and exports are
260
+ not inspected. Compiled pointers use `schema.json` beside the actual compiled module,
261
+ not an inferred source directory. JSON configuration and manifests tolerate a leading BOM.
262
+ Inline-input registrations have no file target and fail individually; conflicting direct
263
+ and inline names also fail. Package lookup, extension inference, inheritance, URL decoding,
264
+ and recursive discovery of unregistered schematics are not supported.
265
+
266
+ Each authorized destination receives the existing fixed `schema.generated.ts`. Canonical
267
+ directory aliases are deduplicated, including failed generation attempts; distinct hardlinked
268
+ filenames are not. Output links are refused, not treated as aliases. Both the canonical
269
+ directory and output must stay inside the selected canonical project root. Positional mode
270
+ retains its existing cwd/package-root authorization and messages.
271
+
272
+ Independent entries continue after failures. Warnings go to stderr; stdout reports:
273
+
274
+ ```text
275
+ pbuilder-codegen: generated 3, failed 1, duplicates 2
276
+ ```
277
+
278
+ Exit status is `1` if any entry failed, otherwise `0` (including zero work). Unresolved or
279
+ refused registrations count individually; a duplicate of an attempted destination only
280
+ increments `duplicates`. Validation failures preserve prior generated output. This is not
281
+ a transaction: successful files remain changed if another entry fails.
282
+
283
+ New JSON reads reject static nonregular inputs. Linux/macOS retain descriptor-bound output
284
+ leaf checks; other platforms retain the existing writer after project-mode leaf validation.
285
+ These checks do not promise protection against parent-directory substitution races or a
286
+ universal filesystem sandbox. Native Windows and packaged-distribution verification remain
287
+ separate from source-test evidence.
288
+
289
+ Registration fixtures follow the observed CLI **v0.9.5** contract at
290
+ `e1280b4486d24ca0eb458471f26b0226523ae774`. That access-controlled compatibility evidence
291
+ is not a public configuration specification or a guarantee about future CLI versions;
292
+ older optional-export pointer examples do not describe this project-mode contract.
293
+
215
294
  ## The seven mutations
216
295
 
217
296
  Everything a factory can do to the tree is one of seven mutation verbs, all imported from
@@ -3,8 +3,20 @@ import { createRequire } from "node:module";
3
3
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
4
4
 
5
5
  // bin/pbuilder-codegen.ts
6
- import { readFileSync, writeFileSync, existsSync, realpathSync } from "node:fs";
7
- import { join as join2, dirname, basename, resolve, sep } from "node:path";
6
+ import {
7
+ readFileSync as readFileSync2,
8
+ writeFileSync,
9
+ existsSync,
10
+ realpathSync as realpathSync2,
11
+ lstatSync as lstatSync2,
12
+ statSync as statSync2,
13
+ openSync,
14
+ fstatSync,
15
+ ftruncateSync,
16
+ closeSync,
17
+ constants
18
+ } from "node:fs";
19
+ import { join as join3, dirname as dirname2, basename, resolve as resolve2, sep } from "node:path";
8
20
 
9
21
  // src/core/schema/schema-model.ts
10
22
  var FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
@@ -350,6 +362,130 @@ function emitInputType(schema, digest) {
350
362
  `);
351
363
  }
352
364
 
365
+ // bin/project-codegen.ts
366
+ import { lstatSync, statSync, readFileSync, realpathSync } from "node:fs";
367
+ import { dirname, join as join2, resolve } from "node:path";
368
+ function readObject(path) {
369
+ if (!statSync(path).isFile())
370
+ throw new Error("nonregular input");
371
+ const value = JSON.parse(readFileSync(path, "utf8").replace(/^\uFEFF/, ""));
372
+ if (!isPlainObject(value))
373
+ throw new Error("invalid object");
374
+ return value;
375
+ }
376
+ function discoverProject(directory) {
377
+ let selected = resolve(directory ?? process.cwd());
378
+ if (directory === undefined) {
379
+ for (;; ) {
380
+ try {
381
+ lstatSync(join2(selected, "project-builder.json"));
382
+ break;
383
+ } catch (error) {
384
+ if (!isErrnoException(error) || error.code !== "ENOENT") {
385
+ return { ok: false, diagnostic: `cannot load project configuration at ${JSON.stringify(selected)}` };
386
+ }
387
+ }
388
+ const parent = dirname(selected);
389
+ if (parent === selected)
390
+ return { ok: false, diagnostic: "project-builder.json not found" };
391
+ selected = parent;
392
+ }
393
+ }
394
+ let root;
395
+ let collections;
396
+ try {
397
+ root = realpathSync(selected);
398
+ const config = readObject(join2(root, "project-builder.json"));
399
+ const value = Object.hasOwn(config, "collections") ? config.collections : {};
400
+ if (!isPlainObject(value))
401
+ throw new Error("invalid collections");
402
+ collections = value;
403
+ } catch {
404
+ return { ok: false, diagnostic: `cannot load project configuration at ${JSON.stringify(selected)}` };
405
+ }
406
+ const entries = [];
407
+ for (const name of Object.keys(collections).sort()) {
408
+ const collection = collections[name];
409
+ if (!isPlainObject(collection)) {
410
+ entries.push({ kind: "failure", label: name, diagnostic: "collection must be an object" });
411
+ continue;
412
+ }
413
+ if (typeof collection.path === "string") {
414
+ let manifest;
415
+ const path = resolve(root, collection.path);
416
+ try {
417
+ const value = readObject(path);
418
+ const schematics = Object.hasOwn(value, "schematics") ? value.schematics : {};
419
+ if (!isPlainObject(schematics))
420
+ throw new Error("invalid schematics");
421
+ manifest = schematics;
422
+ } catch {
423
+ entries.push({ kind: "failure", label: name, diagnostic: `cannot load collection manifest ${JSON.stringify(path)}` });
424
+ continue;
425
+ }
426
+ for (const key of Object.keys(manifest).sort()) {
427
+ const label = `${name}/${key}`;
428
+ const registration = manifest[key];
429
+ const pointer = isPlainObject(registration) ? registration.factory : undefined;
430
+ const split = typeof pointer === "string" ? pointer.lastIndexOf("#") : -1;
431
+ if (typeof pointer !== "string" || split <= 0 || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(pointer.slice(split + 1))) {
432
+ entries.push({ kind: "failure", label, diagnostic: "factory must name a module and explicit export (module#export)" });
433
+ continue;
434
+ }
435
+ const module = resolve(dirname(path), pointer.slice(0, split));
436
+ try {
437
+ if (!statSync(module).isFile())
438
+ throw new Error("nonregular module");
439
+ entries.push({ kind: "target", label, directory: dirname(realpathSync(module)) });
440
+ } catch {
441
+ entries.push({ kind: "failure", label, diagnostic: `cannot resolve factory module ${JSON.stringify(module)}` });
442
+ }
443
+ }
444
+ continue;
445
+ }
446
+ const inline = Object.hasOwn(collection, "schematics") ? collection.schematics : {};
447
+ if (!isPlainObject(inline)) {
448
+ entries.push({ kind: "failure", label: name, diagnostic: "inline schematics must be an object" });
449
+ continue;
450
+ }
451
+ const directKeys = Object.keys(collection).filter((key) => key !== "schematics");
452
+ for (const key of [...new Set([...directKeys, ...Object.keys(inline)])].sort()) {
453
+ const label = `${name}/${key}`;
454
+ if (Object.hasOwn(inline, key)) {
455
+ entries.push({ kind: "failure", label, diagnostic: Object.hasOwn(collection, key) ? "ambiguous direct and inline registration" : "inline inputs have no file target" });
456
+ continue;
457
+ }
458
+ const registration = collection[key];
459
+ if (!isPlainObject(registration) || typeof registration.path !== "string" || registration.path.length === 0) {
460
+ entries.push({ kind: "failure", label, diagnostic: "schematic must name a directory path" });
461
+ continue;
462
+ }
463
+ const path = resolve(root, registration.path);
464
+ try {
465
+ if (!statSync(path).isDirectory())
466
+ throw new Error("not a directory");
467
+ let factories = 0;
468
+ for (const leaf of ["factory.ts", "factory.js"]) {
469
+ try {
470
+ if (!statSync(join2(path, leaf)).isFile())
471
+ throw new Error("nonregular factory");
472
+ factories++;
473
+ } catch (error) {
474
+ if (!isErrnoException(error) || error.code !== "ENOENT")
475
+ throw error;
476
+ }
477
+ }
478
+ if (factories !== 1)
479
+ throw new Error("ambiguous or missing factory");
480
+ entries.push({ kind: "target", label, directory: realpathSync(path) });
481
+ } catch {
482
+ entries.push({ kind: "failure", label, diagnostic: `directory requires exactly one regular factory.ts or factory.js: ${JSON.stringify(path)}` });
483
+ }
484
+ }
485
+ }
486
+ return { ok: true, root, entries };
487
+ }
488
+
353
489
  // bin/pbuilder-codegen.ts
354
490
  var GENERATED_FILENAME = "schema.generated.ts";
355
491
  var SUCCESS_LINE = "pbuilder-codegen: wrote schema.generated.ts";
@@ -368,9 +504,32 @@ class SchemaSufficiencyFailure extends Error {
368
504
  this.findings = findings;
369
505
  }
370
506
  }
507
+
508
+ class OutputWriteFailure extends Error {
509
+ constructor(outputPath, cause, reason) {
510
+ const code = isErrnoException(cause) ? cause.code : undefined;
511
+ super(`pbuilder-codegen: ${outputPath}: ${reason ?? (code === "ELOOP" ? "refusing symbolic-link output" : `cannot write output (${code ?? "unknown"})`)}`, { cause });
512
+ this.name = "OutputWriteFailure";
513
+ }
514
+ }
515
+ function assertOutputLeaf(outputPath) {
516
+ try {
517
+ const leaf = lstatSync2(outputPath);
518
+ if (leaf.isSymbolicLink()) {
519
+ throw new OutputWriteFailure(outputPath, undefined, "refusing symbolic-link output");
520
+ }
521
+ if (!leaf.isFile()) {
522
+ throw new OutputWriteFailure(outputPath, undefined, "output is not a regular file");
523
+ }
524
+ } catch (err) {
525
+ if (isErrnoException(err) && err.code === "ENOENT")
526
+ return;
527
+ throw err instanceof OutputWriteFailure ? err : new OutputWriteFailure(outputPath, err);
528
+ }
529
+ }
371
530
  function generateSchema(packageDir) {
372
531
  const schemaPath = schemaPathFor(packageDir);
373
- const raw = readFileSync(schemaPath, "utf-8");
532
+ const raw = readFileSync2(schemaPath, "utf-8");
374
533
  const schema = parseSchema(raw);
375
534
  const sufficiencyFindings = checkSufficiency(raw);
376
535
  if (sufficiencyFindings.length > 0) {
@@ -378,8 +537,38 @@ function generateSchema(packageDir) {
378
537
  }
379
538
  const digest = computeSchemaDigest(raw);
380
539
  const output = emitInputType(schema, digest);
381
- const outputPath = join2(packageDir, GENERATED_FILENAME);
382
- writeFileSync(outputPath, output, "utf-8");
540
+ const outputPath = join3(packageDir, GENERATED_FILENAME);
541
+ try {
542
+ if (process.platform === "linux" || process.platform === "darwin") {
543
+ assertOutputLeaf(outputPath);
544
+ if (!constants.O_NOFOLLOW || !constants.O_NONBLOCK) {
545
+ throw new OutputWriteFailure(outputPath, undefined, "safe output opening is unavailable");
546
+ }
547
+ const fd = openSync(outputPath, constants.O_WRONLY | constants.O_CREAT | constants.O_NOFOLLOW | constants.O_NONBLOCK, 438);
548
+ let failed = false;
549
+ try {
550
+ if (!fstatSync(fd).isFile()) {
551
+ throw new OutputWriteFailure(outputPath, undefined, "output is not a regular file");
552
+ }
553
+ ftruncateSync(fd, 0);
554
+ writeFileSync(fd, output, "utf-8");
555
+ } catch (err) {
556
+ failed = true;
557
+ throw err;
558
+ } finally {
559
+ try {
560
+ closeSync(fd);
561
+ } catch (err) {
562
+ if (!failed)
563
+ throw err;
564
+ }
565
+ }
566
+ } else {
567
+ writeFileSync(outputPath, output, "utf-8");
568
+ }
569
+ } catch (err) {
570
+ throw err instanceof OutputWriteFailure ? err : new OutputWriteFailure(outputPath, err);
571
+ }
383
572
  return { outputPath, digest };
384
573
  }
385
574
 
@@ -392,9 +581,9 @@ class WriteContainmentRefusal extends Error {
392
581
  function findProjectRoot(startDir) {
393
582
  let dir = startDir;
394
583
  for (;; ) {
395
- if (existsSync(join2(dir, "package.json")))
584
+ if (existsSync(join3(dir, "package.json")))
396
585
  return dir;
397
- const parent = dirname(dir);
586
+ const parent = dirname2(dir);
398
587
  if (parent === dir)
399
588
  return startDir;
400
589
  dir = parent;
@@ -404,22 +593,24 @@ function realpathNearestExisting(p) {
404
593
  let current = p;
405
594
  const suffix = [];
406
595
  while (!existsSync(current)) {
407
- const parent = dirname(current);
596
+ const parent = dirname2(current);
408
597
  if (parent === current)
409
598
  break;
410
599
  suffix.unshift(basename(current));
411
600
  current = parent;
412
601
  }
413
- const real = realpathSync(current);
414
- return suffix.length > 0 ? join2(real, ...suffix) : real;
602
+ const real = realpathSync2(current);
603
+ return suffix.length > 0 ? join3(real, ...suffix) : real;
415
604
  }
416
605
  function isWithin(anchor, target) {
417
- return target === anchor || target.startsWith(anchor + sep);
418
- }
419
- function assertWriteContained(packageDirArg, outputPath) {
420
- const anchor = realpathSync(findProjectRoot(process.cwd()));
421
- const resolvedPackageDir = realpathNearestExisting(resolve(packageDirArg));
422
- const resolvedOutputPath = realpathNearestExisting(resolve(outputPath));
606
+ return target === anchor || target.startsWith(anchor.endsWith(sep) ? anchor : anchor + sep);
607
+ }
608
+ function assertWriteContained(packageDirArg, outputPath, selectedRoot) {
609
+ const anchor = selectedRoot ?? realpathSync2(findProjectRoot(process.cwd()));
610
+ const resolvedPackageDir = realpathNearestExisting(resolve2(packageDirArg));
611
+ if (selectedRoot !== undefined || process.platform === "linux" || process.platform === "darwin")
612
+ assertOutputLeaf(outputPath);
613
+ const resolvedOutputPath = realpathNearestExisting(resolve2(outputPath));
423
614
  if (!isWithin(anchor, resolvedPackageDir) || !isWithin(anchor, resolvedOutputPath)) {
424
615
  throw new WriteContainmentRefusal(`pbuilder-codegen: refusing to write outside the project root: "${packageDirArg}"`);
425
616
  }
@@ -447,9 +638,12 @@ function formatSufficiencyError(schemaPath, err) {
447
638
  }
448
639
  function runCli(argv) {
449
640
  const [first] = argv;
450
- if (first === undefined) {
451
- console.error(USAGE);
452
- return 1;
641
+ if (first === undefined || first === "--project") {
642
+ if (first === "--project" && (!argv[1] || argv[1].startsWith("-") || argv.length !== 2)) {
643
+ console.error(USAGE);
644
+ return 1;
645
+ }
646
+ return runProject(argv[1]);
453
647
  }
454
648
  if (first === "--help" || first === "-h") {
455
649
  console.log(USAGE);
@@ -460,7 +654,7 @@ function runCli(argv) {
460
654
  return 1;
461
655
  }
462
656
  const packageDir = first;
463
- const outputPath = join2(packageDir, GENERATED_FILENAME);
657
+ const outputPath = join3(packageDir, GENERATED_FILENAME);
464
658
  const schemaPath = schemaPathFor(packageDir);
465
659
  try {
466
660
  assertWriteContained(packageDir, outputPath);
@@ -471,6 +665,10 @@ function runCli(argv) {
471
665
  try {
472
666
  generateSchema(packageDir);
473
667
  } catch (err) {
668
+ if (err instanceof OutputWriteFailure) {
669
+ console.error(err.message);
670
+ return 1;
671
+ }
474
672
  if (err instanceof SchemaParseFailure) {
475
673
  console.error(formatParseError(schemaPath, err));
476
674
  return 1;
@@ -492,6 +690,44 @@ function runCli(argv) {
492
690
  console.log(SUCCESS_LINE);
493
691
  return 0;
494
692
  }
693
+ function runProject(directory) {
694
+ const project = discoverProject(directory);
695
+ if (!project.ok) {
696
+ console.error(`pbuilder-codegen: ${project.diagnostic}`);
697
+ return 1;
698
+ }
699
+ const seen = new Set;
700
+ let generated = 0;
701
+ let failed = 0;
702
+ let duplicates = 0;
703
+ for (const entry of project.entries) {
704
+ if (entry.kind === "failure") {
705
+ failed++;
706
+ console.error(`pbuilder-codegen: ${JSON.stringify(entry.label)}: ${entry.diagnostic}`);
707
+ continue;
708
+ }
709
+ const output = join3(entry.directory, GENERATED_FILENAME);
710
+ const schemaPath = schemaPathFor(entry.directory);
711
+ try {
712
+ assertWriteContained(entry.directory, output, project.root);
713
+ if (seen.has(output)) {
714
+ duplicates++;
715
+ continue;
716
+ }
717
+ seen.add(output);
718
+ if (!statSync2(schemaPath).isFile())
719
+ throw new Error("nonregular schema");
720
+ generateSchema(entry.directory);
721
+ generated++;
722
+ } catch (error) {
723
+ failed++;
724
+ 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";
725
+ console.error(`pbuilder-codegen: ${JSON.stringify(entry.label)} (${JSON.stringify(entry.directory)}): ${JSON.stringify(diagnostic)}`);
726
+ }
727
+ }
728
+ console.log(`pbuilder-codegen: generated ${generated}, failed ${failed}, duplicates ${duplicates}`);
729
+ return failed > 0 ? 1 : 0;
730
+ }
495
731
  if (__require.main == __require.module) {
496
732
  process.exitCode = runCli(process.argv.slice(2));
497
733
  }
@@ -1,19 +1,64 @@
1
- import type { Dialect, OpPack } from "../core/define-dialect.ts";
1
+ import type { Dialect, Handle, OpPack } from "../core/define-dialect.ts";
2
2
  /**
3
- * Fixture passed to `testDialect` to drive the conformance suite.
4
- * The fixture supplies the dialect under test plus representative source samples.
3
+ * Runtime module contract; native namespace exports also preserve upstream types.
5
4
  *
6
5
  * @example
7
- * const fixture: DialectFixture = {
8
- * dialect: myTypeScriptDialect,
9
- * samples: ["const x = 1;", "export default {};"],
6
+ * import type { DialectModule } from "@pbuilder/sdk/conformance";
7
+ * import * as typescript from "@pbuilder/sdk/typescript";
8
+ *
9
+ * const module: DialectModule<typeof typescript.astLibrary> = typescript;
10
+ * const project = new module.astLibrary.Project({ useInMemoryFileSystem: true });
11
+ * const ast = project.createSourceFile("example.ts", "const answer = 1;\n");
12
+ * console.assert(module.astLibrary.Node.isSourceFile(ast));
13
+ */
14
+ export interface DialectModule<Library extends object = object> {
15
+ readonly find: (path: string) => Handle<"found", unknown, {}>;
16
+ readonly astLibrary: Library;
17
+ }
18
+ /**
19
+ * Actual entrypoint, independent adapter-library evidence, and a byte-exact editing exercise.
20
+ * The library exercise receives two arguments; public handle callbacks still receive only the AST.
21
+ *
22
+ * @example
23
+ * // In this repository's test/conformance/ directory:
24
+ * import { testDialect, type DialectFixture } from "@pbuilder/sdk/conformance";
25
+ * import * as module from "@pbuilder/sdk/typescript";
26
+ * import * as expectedAstLibrary from "ts-morph";
27
+ * import { defineDialect } from "../../src/core/define-dialect.ts";
28
+ * import { parse, print } from "../../src/dialects/typescript/ast.ts";
29
+ *
30
+ * const exerciseLibrary: DialectFixture<typeof expectedAstLibrary>["libraryExercise"]["modify"] = (ast, library) => {
31
+ * if (!(ast instanceof library.SourceFile) || !library.Node.isSourceFile(ast)) {
32
+ * throw new Error("incompatible adapter library");
33
+ * }
34
+ * ast.getVariableStatements()[0]!.setDeclarationKind(library.VariableDeclarationKind.Const);
35
+ * };
36
+ * const fixture: DialectFixture<typeof expectedAstLibrary> = {
37
+ * dialect: defineDialect({ extensions: [".ts"], ast: { parse, print }, ops: {} }),
38
+ * samples: ["const x = 1;\n"],
39
+ * module,
40
+ * expectedAstLibrary,
41
+ * libraryExercise: {
42
+ * path: "example.ts", seed: "let answer = 1;\n", expect: "const answer = 1;\n",
43
+ * modify: exerciseLibrary,
44
+ * },
10
45
  * };
46
+ * await testDialect(fixture);
11
47
  */
12
- export interface DialectFixture {
48
+ export interface DialectFixture<Library extends object = object> {
13
49
  /** The dialect instance to exercise. */
14
50
  dialect: Dialect;
15
51
  /** Representative source strings the dialect's parse/print round-trip must survive byte-exact. */
16
52
  samples: string[];
53
+ module: DialectModule<Library>;
54
+ /** Independent evidence from the adapter's library dependency, not the tested export. */
55
+ expectedAstLibrary: Library;
56
+ libraryExercise: {
57
+ path: string;
58
+ seed: string;
59
+ expect: string;
60
+ modify: (ast: unknown, library: Library) => void;
61
+ };
17
62
  }
18
63
  /**
19
64
  * One op-invocation recipe `testOpPack` applies to a seeded target: seed the file, run the
@@ -81,13 +126,10 @@ export interface OpPackFixture {
81
126
  * `parse` returning `null`/`undefined`, or the input string unchanged, fails BEFORE the
82
127
  * round-trip assertion could vacuously pass.
83
128
  *
84
- * @example
85
- * await testDialect({
86
- * dialect: myTypeScriptDialect,
87
- * samples: ["const x = 1;"],
88
- * });
129
+ * Requires runtime library exports matching independent adapter evidence, then exercises
130
+ * the actual module's `find().modify()` through a real run with byte-exact emitted output.
89
131
  */
90
- export declare function testDialect(fixture: DialectFixture): Promise<void>;
132
+ export declare function testDialect<Library extends object>(fixture: DialectFixture<Library>): Promise<void>;
91
133
  /**
92
134
  * Runs the conformance suite for an op-pack against a REAL base dialect (never a mock,
93
135
  * ADR-0012): for each of `fixture.exercises`, asserts single-op fidelity +
@@ -115,15 +115,39 @@ function runRoundTripProbe(dialectAst, samples, label) {
115
115
  * `parse` returning `null`/`undefined`, or the input string unchanged, fails BEFORE the
116
116
  * round-trip assertion could vacuously pass.
117
117
  *
118
- * @example
119
- * await testDialect({
120
- * dialect: myTypeScriptDialect,
121
- * samples: ["const x = 1;"],
122
- * });
118
+ * Requires runtime library exports matching independent adapter evidence, then exercises
119
+ * the actual module's `find().modify()` through a real run with byte-exact emitted output.
123
120
  */
124
121
  export async function testDialect(fixture) {
122
+ const module = fixture.module;
123
+ if (!module || typeof module.find !== "function") {
124
+ throw new Error("testDialect: module must expose callable find");
125
+ }
126
+ if (!module.astLibrary || typeof module.astLibrary !== "object") {
127
+ throw new Error("testDialect: module must expose runtime astLibrary");
128
+ }
129
+ const expected = fixture.expectedAstLibrary;
130
+ if (!expected || typeof expected !== "object") {
131
+ throw new Error("testDialect: independent expectedAstLibrary evidence is required");
132
+ }
133
+ const keys = Object.keys(expected);
134
+ if (keys.length === 0 || keys.length !== Object.keys(module.astLibrary).length ||
135
+ keys.some((key) => !Object.hasOwn(module.astLibrary, key) ||
136
+ !Object.is(Reflect.get(module.astLibrary, key), Reflect.get(expected, key)))) {
137
+ throw new Error("testDialect: astLibrary runtime library mismatch with adapter evidence");
138
+ }
125
139
  const samples = [...fixture.samples, ...MANDATORY_ADVERSARIAL_SAMPLES];
126
140
  runRoundTripProbe(fixture.dialect.ast, samples, "testDialect");
141
+ const exercise = fixture.libraryExercise;
142
+ const { client, emitted } = createRunVehicle({ [exercise.path]: exercise.seed });
143
+ const run = defineFactory(async () => {
144
+ await module.find(exercise.path).modify((ast) => exercise.modify(ast, module.astLibrary));
145
+ });
146
+ await run(undefined, { client });
147
+ const directives = emitted.flatMap((batch) => batch.instructions);
148
+ if (!deepEqual(directives, [{ op: "modify", modify: { path: exercise.path, content: exercise.expect } }])) {
149
+ throw new Error("testDialect: library exercise did not emit the expected byte-exact modify");
150
+ }
127
151
  }
128
152
  /**
129
153
  * Runs the conformance suite for an op-pack against a REAL base dialect (never a mock,
@@ -1,5 +1,6 @@
1
1
  import type { SourceFile } from "ts-morph";
2
2
  import { type Handle } from "../../core/define-dialect.ts";
3
+ export * as astLibrary from "ts-morph";
3
4
  type ReactOps = {
4
5
  setJsxProp: (ast: SourceFile, elementName: string, propName: string, value?: string) => void;
5
6
  addImport: (ast: SourceFile, name: string, from: string) => void;
@@ -36,4 +37,3 @@ type ReactOps = {
36
37
  * // -> const el = <Button onClick={handleClick} />;
37
38
  */
38
39
  export declare function find(path: string): Handle<"found", SourceFile, ReactOps>;
39
- export {};
@@ -9,6 +9,7 @@ import { defineDialect, defineOpPack, withOps } from "../../core/define-dialect.
9
9
  import { dialectError } from "../../core/dialect-error.js";
10
10
  import { parse, print } from "./ast.js";
11
11
  import { addImport, setJsxProp } from "./ops.js";
12
+ export * as astLibrary from "ts-morph";
12
13
  const opsPack = defineOpPack({ setJsxProp, addImport });
13
14
  const baseDialect = defineDialect({
14
15
  extensions: [".tsx"],
@@ -1,5 +1,6 @@
1
1
  import type { SourceFile } from "ts-morph";
2
2
  import { type Handle } from "../../core/define-dialect.ts";
3
+ export * as astLibrary from "ts-morph";
3
4
  type TypeScriptOps = {
4
5
  addImport: (ast: SourceFile, name: string, from: string) => void;
5
6
  addFunction: (ast: SourceFile, name: string, source: string, options?: {
@@ -29,4 +30,3 @@ type TypeScriptOps = {
29
30
  * };
30
31
  */
31
32
  export declare function find(path: string): Handle<"found", SourceFile, TypeScriptOps>;
32
- export {};
@@ -8,6 +8,7 @@
8
8
  import { defineDialect, defineOpPack, withOps } from "../../core/define-dialect.js";
9
9
  import { parse, print } from "./ast.js";
10
10
  import { addImport, addFunction, addVariable, addClass, removeImport } from "./ops.js";
11
+ export * as astLibrary from "ts-morph";
11
12
  const opsPack = defineOpPack({
12
13
  addImport,
13
14
  addFunction,
@@ -2,7 +2,7 @@
2
2
  "manifestVersion": 1,
3
3
  "algorithm": "sha256",
4
4
  "entry": "dist/bin/pbuilder-runner.js",
5
- "packageVersion": "0.2.4",
5
+ "packageVersion": "0.3.0",
6
6
  "files": [
7
7
  {
8
8
  "path": "dist/bin/pbuilder-runner.js",
@@ -82,7 +82,7 @@
82
82
  },
83
83
  {
84
84
  "path": "dist/transport/runner.js",
85
- "sha256": "fb06fea6d3427f97189ce2f269d5f392ada09fad99c10bb039419bc827e561a2"
85
+ "sha256": "771faddcf2f97bc3ade5fb617ef15992be46155b840d614838acb18feda99bda"
86
86
  },
87
87
  {
88
88
  "path": "dist/transport/single-instance-probe.js",
@@ -98,7 +98,7 @@
98
98
  },
99
99
  {
100
100
  "path": "package.json",
101
- "sha256": "5b83a3462c5984431b656a101da8090dfb841c3df230c6f5dbb4a56843a69970"
101
+ "sha256": "00d3d83021625e065c04cf4018aeae9ac360f2173d472258a4851a35bdbebf74"
102
102
  }
103
103
  ]
104
104
  }
@@ -94,7 +94,10 @@ function resolveInput(input) {
94
94
  });
95
95
  let size;
96
96
  try {
97
- size = statSync(input.path).size;
97
+ const stat = statSync(input.path);
98
+ if (!stat.isFile())
99
+ return unreadable();
100
+ size = stat.size;
98
101
  }
99
102
  catch {
100
103
  return unreadable();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pbuilder/sdk",
3
- "version": "0.2.4",
3
+ "version": "0.3.0",
4
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",
@@ -78,14 +78,15 @@
78
78
  "regen:closure-baseline": "bun scripts/regen-closure-baseline.ts",
79
79
  "prepublishOnly": "bun run build",
80
80
  "publish:dry": "npm publish --dry-run",
81
- "registry:up": "bunx verdaccio --config tools/verdaccio/config.yaml --listen 4873",
82
- "publish:local": "npm publish --registry http://localhost:4873 --tag local",
81
+ "registry:up": "verdaccio --config tools/verdaccio/config.yaml --listen 4873",
82
+ "publish:local": "npm publish --userconfig tools/verdaccio/npmrc --registry http://localhost:4873 --tag local",
83
83
  "link:sdk": "bun run build && bun link"
84
84
  },
85
85
  "devDependencies": {
86
86
  "@types/bun": "^1.3.14",
87
87
  "expect-type": "^1.3.0",
88
- "typescript": "^7.0.2"
88
+ "typescript": "^7.0.2",
89
+ "verdaccio": "6.10.3"
89
90
  },
90
91
  "dependencies": {
91
92
  "ts-morph": "28.0.0"