stitchkit 0.133.0 → 0.133.1

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/CHANGELOG.md CHANGED
@@ -15,6 +15,12 @@ additive**; the first breaking change landed in 0.10.0. Grep the file for
15
15
 
16
16
  ## [Unreleased]
17
17
 
18
+ ## [0.133.1] - 2026-11-27
19
+
20
+ ### Added
21
+
22
+ - `stitchkit/files/packaging` — `buildClientPackage` takes `exportedFiles` and `replaceModules`, so a client package that publishes its own manifest, a data file or a version read from the project's `package.json` can be built by it. `exportedFiles: ['./package.json', './native-stream.json']` writes the archive's own manifest and paths from `files` into `exports`; the proof resolves each by the package name to its packed file in every runtime, imports a `.json` one as JSON and typechecks `import pkg from '<name>/package.json' with { type: 'json' }` under Bundler and NodeNext, and `ClientPackage.proof.exportedFiles` lists them. `replaceModules: { 'package.json': JSON.stringify({ version }) }` builds every import of that file from the given contents, so the client ships one field instead of the project's `scripts` and `devDependencies`; a replacement no bundled module imports is refused with the new reason `replacement-unused`. The entries are now built by `Bun.build` from a script the build writes and runs in the same bounded `bun`, as the command line takes no plugin; the options it passes are the ones the command line spelled. → ADR 0335
23
+
18
24
  ## [0.133.0] - 2026-11-27
19
25
 
20
26
  ### ⚠️ Breaking changes
package/README.md CHANGED
@@ -1,3 +1,7 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/max-listov/stitchkit/master/assets/avatar.png" alt="Stitchkit — a blue ball of yarn with a golden needle" width="128" height="128" />
3
+ </p>
4
+
1
5
  <p align="center">
2
6
  <strong>Contract-first backend framework for Bun and Node.</strong><br/>
3
7
  Define your API once — get an HTTP API, MCP tools, AI-agent tools, a CLI and a typed client.
@@ -157,9 +157,9 @@ async function buildClientArtifact(options) {
157
157
  // src/files/client-package.ts
158
158
  import { createHash as createHash3 } from "node:crypto";
159
159
  import { existsSync as existsSync3 } from "node:fs";
160
- import { copyFile as copyFile2, mkdir as mkdir3, mkdtemp as mkdtemp2, readFile as readFile4, realpath as realpath2, rm as rm3, writeFile as writeFile4 } from "node:fs/promises";
160
+ import { copyFile as copyFile2, mkdir as mkdir3, mkdtemp as mkdtemp2, readFile as readFile4, realpath as realpath3, rm as rm3, writeFile as writeFile5 } from "node:fs/promises";
161
161
  import { tmpdir as tmpdir2 } from "node:os";
162
- import { dirname as dirname5, isAbsolute, join as join5, normalize, relative as relative3, resolve as resolve4 } from "node:path";
162
+ import { dirname as dirname5, extname, isAbsolute, join as join6, normalize, relative as relative3, resolve as resolve4 } from "node:path";
163
163
 
164
164
  // src/files/client-declarations.ts
165
165
  import { randomUUID } from "node:crypto";
@@ -200,6 +200,7 @@ var CLIENT_PACKAGE_OWNED_FIELDS = [
200
200
  ];
201
201
  var ClientPackageRefusalSchema = z2.enum([
202
202
  "build",
203
+ "replacement-unused",
203
204
  "declarations",
204
205
  "declaration-unresolved",
205
206
  "declaration-dependency",
@@ -478,19 +479,111 @@ function undeclared(file, specifier, name) {
478
479
  return new ClientPackageError("declaration-dependency", `Client package declaration ${file} names ${JSON.stringify(specifier)}, but "${name}" ` + "is neither a peer dependency nor a dependency of the package", { file, specifier, package: name });
479
480
  }
480
481
 
482
+ // src/files/client-package-bundle.ts
483
+ import { realpathSync } from "node:fs";
484
+ import { realpath, writeFile as writeFile3 } from "node:fs/promises";
485
+ import { join as join4 } from "node:path";
486
+ var REPLACEMENT_LOADERS = {
487
+ ".json": "json",
488
+ ".ts": "ts",
489
+ ".tsx": "tsx",
490
+ ".js": "js",
491
+ ".mjs": "js",
492
+ ".cjs": "js",
493
+ ".jsx": "jsx"
494
+ };
495
+ var BUNDLE_SCRIPT = `const config = JSON.parse(await Bun.file(process.argv[2]).text());
496
+ const replacements = new Map(Object.entries(config.replacements));
497
+ const escape = (text) => text.replace(/[.*+?^\${}()|[\\]\\\\]/g, '\\\\$&');
498
+ const loaderOf = (path) => config.loaders[path.slice(path.lastIndexOf('.'))];
499
+ const plugins =
500
+ replacements.size === 0
501
+ ? []
502
+ : [
503
+ {
504
+ name: 'stitchkit-replace-modules',
505
+ setup(build) {
506
+ const filter = new RegExp(\`^(?:\${[...replacements.keys()].map(escape).join('|')})$\`);
507
+ build.onLoad({ filter }, (args) => ({
508
+ contents: replacements.get(args.path),
509
+ loader: loaderOf(args.path),
510
+ }));
511
+ },
512
+ },
513
+ ];
514
+ try {
515
+ const result = await Bun.build({
516
+ entrypoints: config.entries,
517
+ root: config.root,
518
+ outdir: config.outdir,
519
+ target: config.target,
520
+ format: 'esm',
521
+ splitting: true,
522
+ external: config.external,
523
+ naming: { entry: '[dir]/[name].[ext]', chunk: 'chunks/[name]-[hash].[ext]' },
524
+ tsconfig: config.tsconfig,
525
+ metafile: true,
526
+ plugins,
527
+ throw: false,
528
+ });
529
+ if (!result.success) {
530
+ for (const log of result.logs) console.error(String(log));
531
+ process.exit(1);
532
+ }
533
+ await Bun.write(config.metafile, JSON.stringify(result.metafile));
534
+ } catch (error) {
535
+ console.error(String(error?.stack ?? error));
536
+ process.exit(1);
537
+ }
538
+ `;
539
+ async function bundleClientPackage(input) {
540
+ const script = join4(input.work, "bundle.mjs");
541
+ const config = join4(input.work, "bundle.json");
542
+ const metafile = join4(input.work, "meta.json");
543
+ await writeFile3(script, BUNDLE_SCRIPT);
544
+ await writeFile3(config, JSON.stringify({
545
+ entries: input.entries,
546
+ root: input.root,
547
+ outdir: input.outdir,
548
+ target: input.runtime,
549
+ external: input.external,
550
+ tsconfig: input.tsconfig,
551
+ metafile,
552
+ replacements: Object.fromEntries([...input.replacements].flatMap(([path, contents]) => [
553
+ [path, contents],
554
+ [realpathSync(path), contents]
555
+ ])),
556
+ loaders: REPLACEMENT_LOADERS
557
+ }));
558
+ const built = await runClientTool(input.step, input.bun, [script, config], input.root);
559
+ if (!built.ok) {
560
+ throw new ClientPackageError("build", `Client package build failed (exit ${built.exit}): ${built.output}`, { output: built.output });
561
+ }
562
+ const graph = await readClientBuildGraph(metafile, input.root);
563
+ const bundled = new Set;
564
+ for (const module of graph.modules.keys())
565
+ bundled.add(await realpath(module).catch(() => module));
566
+ for (const module of input.replacements.keys()) {
567
+ if (bundled.has(realpathSync(module)))
568
+ continue;
569
+ throw new ClientPackageError("replacement-unused", `Client package replaces ${module}, which no bundled module imports`, { module });
570
+ }
571
+ return graph;
572
+ }
573
+
481
574
  // src/files/client-package-proof.ts
482
575
  import { createHash as createHash2 } from "node:crypto";
483
576
  import { existsSync as existsSync2 } from "node:fs";
484
- import { copyFile, mkdir as mkdir2, readdir, readFile as readFile3, realpath, writeFile as writeFile3 } from "node:fs/promises";
485
- import { basename as basename2, dirname as dirname4, join as join4, relative as relative2 } from "node:path";
577
+ import { copyFile, mkdir as mkdir2, readdir, readFile as readFile3, realpath as realpath2, writeFile as writeFile4 } from "node:fs/promises";
578
+ import { basename as basename2, dirname as dirname4, join as join5, relative as relative2 } from "node:path";
486
579
  import { z as z3 } from "zod";
487
580
  var InstalledManifestSchema = z3.object({ version: z3.string() });
488
581
  async function resolveExternalPackage(from, name) {
489
582
  for (let directory = from;; directory = dirname4(directory)) {
490
- const candidate = join4(directory, "node_modules", name);
491
- if (existsSync2(join4(candidate, "package.json"))) {
492
- const real = await realpath(candidate);
493
- const manifest = InstalledManifestSchema.parse(safeJsonParse(await readFile3(join4(real, "package.json"), "utf8")));
583
+ const candidate = join5(directory, "node_modules", name);
584
+ if (existsSync2(join5(candidate, "package.json"))) {
585
+ const real = await realpath2(candidate);
586
+ const manifest = InstalledManifestSchema.parse(safeJsonParse(await readFile3(join5(real, "package.json"), "utf8")));
494
587
  return { directory: real, version: manifest.version };
495
588
  }
496
589
  if (dirname4(directory) === directory) {
@@ -501,7 +594,7 @@ async function resolveExternalPackage(from, name) {
501
594
  async function filesUnder(directory, base = directory) {
502
595
  const files = [];
503
596
  for (const entry of await readdir(directory, { withFileTypes: true })) {
504
- const path = join4(directory, entry.name);
597
+ const path = join5(directory, entry.name);
505
598
  if (entry.isDirectory()) {
506
599
  if (entry.name !== "node_modules")
507
600
  files.push(...await filesUnder(path, base));
@@ -514,16 +607,28 @@ async function filesUnder(directory, base = directory) {
514
607
  var IdentityReportSchema = z3.object({
515
608
  exports: z3.record(z3.string(), z3.array(z3.string())),
516
609
  shared: z3.array(z3.string()),
517
- split: z3.array(z3.string())
610
+ split: z3.array(z3.string()),
611
+ unresolved: z3.array(z3.string())
518
612
  });
519
- function identityScript(name, subpaths) {
520
- return `const name = ${JSON.stringify(name)};
613
+ function identityScript(name, subpaths, files) {
614
+ return `import { fileURLToPath } from 'node:url';
615
+ const name = ${JSON.stringify(name)};
521
616
  const subpaths = ${JSON.stringify(subpaths)};
617
+ const files = ${JSON.stringify(files)};
522
618
  const namespaces = {};
523
619
  for (const subpath of subpaths) {
524
620
  namespaces[subpath] = await import(subpath === '.' ? name : name + subpath.slice(1));
525
621
  }
526
622
  const exported = {};
623
+ const unresolved = [];
624
+ for (const [subpath, path] of Object.entries(files)) {
625
+ const specifier = name + subpath.slice(1);
626
+ const resolved = fileURLToPath(import.meta.resolve(specifier)).replaceAll('\\\\', '/');
627
+ if (!resolved.endsWith('/node_modules/' + name + path.slice(1))) unresolved.push(subpath);
628
+ else if (path.endsWith('.json')) {
629
+ exported[subpath] = Object.keys(await import(specifier, { with: { type: 'json' } })).sort();
630
+ }
631
+ }
527
632
  const owners = new Map();
528
633
  for (const subpath of subpaths) {
529
634
  exported[subpath] = Object.keys(namespaces[subpath]).sort();
@@ -536,7 +641,9 @@ for (const [key, list] of owners) {
536
641
  const first = namespaces[list[0]][key];
537
642
  (list.every((subpath) => Object.is(namespaces[subpath][key], first)) ? shared : split).push(key);
538
643
  }
539
- process.stdout.write(JSON.stringify({ exports: exported, shared: shared.sort(), split: split.sort() }));
644
+ process.stdout.write(
645
+ JSON.stringify({ exports: exported, shared: shared.sort(), split: split.sort(), unresolved }),
646
+ );
540
647
  `;
541
648
  }
542
649
  var RangeReportSchema = z3.array(z3.object({ package: z3.string(), range: z3.string(), installed: z3.string() }));
@@ -557,7 +664,7 @@ async function install(input) {
557
664
  for (const name of options.proof?.types ?? []) {
558
665
  types[name] = `file:${(await resolveExternalPackage(input.root, name)).directory}`;
559
666
  }
560
- await writeFile3(join4(consumer, "package.json"), `${JSON.stringify({
667
+ await writeFile4(join5(consumer, "package.json"), `${JSON.stringify({
561
668
  name: "client-package-consumer",
562
669
  private: true,
563
670
  type: "module",
@@ -570,17 +677,17 @@ async function install(input) {
570
677
  }, null, 2)}
571
678
  `);
572
679
  ranOrRefuse(await runClientTool(input.step, input.tools.bun, ["install", "--ignore-scripts"], consumer), "install", "install");
573
- const installed = join4(consumer, "node_modules", options.name);
680
+ const installed = join5(consumer, "node_modules", options.name);
574
681
  for (const peer of peers) {
575
- if (!existsSync2(join4(installed, "node_modules", peer)))
682
+ if (!existsSync2(join5(installed, "node_modules", peer)))
576
683
  continue;
577
684
  throw new ClientPackageError("bundled-peer", `Client package installs its own copy of peer "${peer}" instead of sharing the consumer's`, { package: peer });
578
685
  }
579
686
  const files = [];
580
687
  for (const path of await filesUnder(input.staged)) {
581
- const packed = await readFile3(join4(input.staged, path));
688
+ const packed = await readFile3(join5(input.staged, path));
582
689
  const digest = createHash2("sha256").update(packed).digest("hex");
583
- const unpacked = existsSync2(join4(installed, path)) ? createHash2("sha256").update(await readFile3(join4(installed, path))).digest("hex") : undefined;
690
+ const unpacked = existsSync2(join5(installed, path)) ? createHash2("sha256").update(await readFile3(join5(installed, path))).digest("hex") : undefined;
584
691
  if (unpacked !== digest) {
585
692
  throw new ClientPackageError("install", `Client package file ${path} is not in the installed archive as it was built`, { file: path });
586
693
  }
@@ -593,18 +700,18 @@ async function proveRanges(input) {
593
700
  const declared = { ...options.dependencies, ...options.peerDependencies };
594
701
  const installedVersions = {};
595
702
  for (const name of Object.keys(declared)) {
596
- const manifest = [join4(options.name, "node_modules", name), name].map((path) => join4(consumer, "node_modules", path, "package.json")).find((path) => existsSync2(path));
703
+ const manifest = [join5(options.name, "node_modules", name), name].map((path) => join5(consumer, "node_modules", path, "package.json")).find((path) => existsSync2(path));
597
704
  if (manifest === undefined) {
598
705
  throw new ClientPackageError("install", `Client package was installed without "${name}"`, { package: name });
599
706
  }
600
707
  installedVersions[name] = InstalledManifestSchema.parse(safeJsonParse(await readFile3(manifest, "utf8"))).version;
601
708
  }
602
- await writeFile3(join4(consumer, "ranges.json"), JSON.stringify(Object.entries(declared).map(([name, range]) => ({
709
+ await writeFile4(join5(consumer, "ranges.json"), JSON.stringify(Object.entries(declared).map(([name, range]) => ({
603
710
  package: name,
604
711
  range,
605
712
  installed: installedVersions[name] ?? ""
606
713
  }))));
607
- await writeFile3(join4(consumer, "ranges.mjs"), RANGE_SCRIPT);
714
+ await writeFile4(join5(consumer, "ranges.mjs"), RANGE_SCRIPT);
608
715
  const ran = ranOrRefuse(await runClientTool(input.step, input.tools.bun, ["ranges.mjs"], consumer), "install", "range check");
609
716
  const [outside] = RangeReportSchema.parse(safeJsonParse(ran.stdout));
610
717
  if (outside !== undefined) {
@@ -615,13 +722,17 @@ async function proveRanges(input) {
615
722
  async function proveIdentity(input) {
616
723
  const { options, consumer } = input;
617
724
  const subpaths = Object.keys(options.entries);
618
- await writeFile3(join4(consumer, "identity.mjs"), identityScript(options.name, subpaths));
725
+ await writeFile4(join5(consumer, "identity.mjs"), identityScript(options.name, subpaths, Object.fromEntries(input.exportedFiles)));
619
726
  const runtimes = (options.runtime ?? "node") === "node" ? ["node", "bun"] : ["bun"];
620
727
  const distinct = new Set(options.proof?.distinctExports ?? []);
621
728
  let first;
622
729
  for (const runtime of runtimes) {
623
730
  const ran = ranOrRefuse(await runClientTool(input.step, input.tools[runtime], ["identity.mjs"], consumer), "install", `import in ${runtime}`, { runtime });
624
731
  const report = IdentityReportSchema.parse(safeJsonParse(ran.stdout));
732
+ const [unresolved] = report.unresolved;
733
+ if (unresolved !== undefined) {
734
+ throw new ClientPackageError("missing-export", `Client package subpath "${unresolved}" does not resolve to its packed file in ${runtime}`, { subpath: unresolved, runtime });
735
+ }
625
736
  for (const [subpath, required] of Object.entries(options.proof?.exports ?? {})) {
626
737
  const names = required.filter((name) => !report.exports[subpath]?.includes(name));
627
738
  if (names.length === 0)
@@ -643,22 +754,28 @@ var RESOLUTIONS = [
643
754
  async function proveTypes(input) {
644
755
  const { options, consumer } = input;
645
756
  const sources = ["exports.ts"];
646
- await writeFile3(join4(consumer, "exports.ts"), Object.keys(options.entries).map((subpath, index) => {
757
+ const json = [...input.exportedFiles].filter(([, path]) => path.endsWith(".json"));
758
+ await writeFile4(join5(consumer, "exports.ts"), Object.keys(options.entries).map((subpath, index) => {
647
759
  const specifier = subpath === "." ? options.name : options.name + subpath.slice(1);
648
760
  return `export * as E${index} from ${JSON.stringify(specifier)};
649
761
  `;
650
- }).join(""));
651
- await mkdir2(join4(consumer, "typecheck"));
762
+ }).concat(json.map(([subpath], index) => {
763
+ const specifier = JSON.stringify(options.name + subpath.slice(1));
764
+ return `import J${index} from ${specifier} with { type: 'json' };
765
+ export { J${index} };
766
+ `;
767
+ })).join(""));
768
+ await mkdir2(join5(consumer, "typecheck"));
652
769
  for (const [index, source] of (options.proof?.typecheck ?? []).entries()) {
653
770
  const copy = `typecheck/${index}-${basename2(source)}`;
654
- await copyFile(source, join4(consumer, copy));
771
+ await copyFile(source, join5(consumer, copy));
655
772
  sources.push(copy);
656
773
  }
657
774
  const [compiler, ...leading] = input.tools.tsc;
658
775
  const version = ranOrRefuse(await runClientTool(input.step, compiler, [...leading, "--version"], consumer), "typecheck", "compiler").stdout.replace(/^Version\s+/, "");
659
776
  for (const { resolution, module } of RESOLUTIONS) {
660
777
  const config = `tsconfig.${resolution.toLowerCase()}.json`;
661
- await writeFile3(join4(consumer, config), JSON.stringify({
778
+ await writeFile4(join5(consumer, config), JSON.stringify({
662
779
  compilerOptions: {
663
780
  strict: true,
664
781
  noEmit: true,
@@ -667,7 +784,8 @@ async function proveTypes(input) {
667
784
  module,
668
785
  moduleResolution: resolution,
669
786
  lib: ["ES2023", "DOM"],
670
- types: (options.proof?.types ?? []).map((name) => name.replace(/^@types\//, ""))
787
+ types: (options.proof?.types ?? []).map((name) => name.replace(/^@types\//, "")),
788
+ ...json.length > 0 ? { resolveJsonModule: true } : {}
671
789
  },
672
790
  files: sources
673
791
  }));
@@ -688,7 +806,8 @@ async function proveClientPackage(input) {
688
806
  runtimes: identity.runtimes,
689
807
  resolutions: RESOLUTIONS.map(({ resolution }) => resolution),
690
808
  typescript,
691
- externals
809
+ externals,
810
+ exportedFiles: [...input.exportedFiles.keys()]
692
811
  }
693
812
  };
694
813
  }
@@ -744,33 +863,39 @@ function plan(options) {
744
863
  external: [...peers, ...dependencies],
745
864
  manifest,
746
865
  files,
747
- tarball: join5(resolve4(options.outDir), `${options.name.replace(/^@/, "").replaceAll("/", "-")}-${options.version}.tgz`)
866
+ exportedFiles: planExportedFiles(options, entries, files),
867
+ replacements: planReplacements(options),
868
+ tarball: join6(resolve4(options.outDir), `${options.name.replace(/^@/, "").replaceAll("/", "-")}-${options.version}.tgz`)
748
869
  };
749
870
  }
750
- async function bundle(options, planned, step, bun, work) {
751
- const metafile = join5(work, "meta.json");
752
- const built = await runClientTool(step, bun, [
753
- "build",
754
- ...planned.entries.values(),
755
- `--root=${planned.root}`,
756
- `--outdir=${join5(work, "package", "dist")}`,
757
- `--target=${options.runtime ?? "node"}`,
758
- "--format=esm",
759
- "--splitting",
760
- ...planned.external.map((name) => `--external=${name}`),
761
- "--entry-naming=[dir]/[name].[ext]",
762
- "--chunk-naming=chunks/[name]-[hash].[ext]",
763
- `--tsconfig-override=${planned.tsconfig}`,
764
- `--metafile=${metafile}`
765
- ], planned.root);
766
- if (!built.ok) {
767
- throw new ClientPackageError("build", `Client package build failed (exit ${built.exit}): ${built.output}`, { output: built.output });
871
+ function planExportedFiles(options, entries, files) {
872
+ const exported = new Map;
873
+ for (const subpath of options.exportedFiles ?? []) {
874
+ const path = normalize(subpath.slice(2)).replaceAll("\\", "/");
875
+ if (!subpath.startsWith("./") || path !== "package.json" && !files.has(path)) {
876
+ throw new TypeError(`Client package exported file ${JSON.stringify(subpath)} is neither "./package.json" nor "./" and a path in files`);
877
+ }
878
+ if (entries.has(subpath) || exported.has(subpath)) {
879
+ throw new TypeError(`Client package subpath ${JSON.stringify(subpath)} is exported twice`);
880
+ }
881
+ exported.set(subpath, `./${path}`);
768
882
  }
769
- return readClientBuildGraph(metafile, planned.root);
883
+ return exported;
884
+ }
885
+ function planReplacements(options) {
886
+ const replacements = new Map;
887
+ for (const [module, contents] of Object.entries(options.replaceModules ?? {})) {
888
+ const path = resolve4(module);
889
+ if (!existsSync3(path) || REPLACEMENT_LOADERS[extname(path)] === undefined) {
890
+ throw new TypeError(`Client package replaces ${module}, which is not an existing ${Object.keys(REPLACEMENT_LOADERS).join(", ")} file`);
891
+ }
892
+ replacements.set(path, contents);
893
+ }
894
+ return replacements;
770
895
  }
771
896
  async function refuseBundledExternals(graph, externals) {
772
897
  for (const module of graph.modules.keys()) {
773
- const real = await realpath2(module);
898
+ const real = await realpath3(module);
774
899
  for (const [name, external] of externals) {
775
900
  if (!real.startsWith(`${external.directory}/`))
776
901
  continue;
@@ -783,17 +908,19 @@ async function stage(options, planned, graph, staged) {
783
908
  for (const [subpath, entry] of planned.entries) {
784
909
  const output = graph.entryOutputs.get(entry);
785
910
  const types = output?.replace(/\.js$/, ".d.ts");
786
- if (output === undefined || types === undefined || !existsSync3(join5(staged, "dist", types))) {
911
+ if (output === undefined || types === undefined || !existsSync3(join6(staged, "dist", types))) {
787
912
  throw new ClientPackageError("declarations", `Client package entry ${entry} has no built module with a declaration beside it`, { entry, subpath });
788
913
  }
789
914
  exported[subpath] = { types: `./dist/${types}`, import: `./dist/${output}` };
790
915
  }
916
+ for (const [subpath, path] of planned.exportedFiles)
917
+ exported[subpath] = path;
791
918
  for (const [target, source] of planned.files) {
792
- await mkdir3(dirname5(join5(staged, target)), { recursive: true });
793
- await copyFile2(source, join5(staged, target));
919
+ await mkdir3(dirname5(join6(staged, target)), { recursive: true });
920
+ await copyFile2(source, join6(staged, target));
794
921
  }
795
922
  const present = (record) => record !== undefined && Object.keys(record).length > 0 ? record : undefined;
796
- await writeFile4(join5(staged, "package.json"), `${JSON.stringify({
923
+ await writeFile5(join6(staged, "package.json"), `${JSON.stringify({
797
924
  name: options.name,
798
925
  version: options.version,
799
926
  ...planned.manifest,
@@ -812,7 +939,7 @@ async function buildClientPackage(options) {
812
939
  signal: options.signal
813
940
  };
814
941
  const bun = options.executables?.bun ?? "bun";
815
- const work = await mkdtemp2(join5(tmpdir2(), "stitchkit-client-package-"));
942
+ const work = await mkdtemp2(join6(tmpdir2(), "stitchkit-client-package-"));
816
943
  await rm3(planned.tarball, { force: true });
817
944
  try {
818
945
  const externals = new Map;
@@ -821,10 +948,21 @@ async function buildClientPackage(options) {
821
948
  }
822
949
  const tsc = options.executables?.tsc !== undefined ? [options.executables.tsc] : [
823
950
  process.execPath,
824
- join5((await resolveExternalPackage(planned.root, "typescript")).directory, "bin", "tsc")
951
+ join6((await resolveExternalPackage(planned.root, "typescript")).directory, "bin", "tsc")
825
952
  ];
826
- const staged = join5(work, "package");
827
- const graph = await bundle(options, planned, step, bun, work);
953
+ const staged = join6(work, "package");
954
+ const graph = await bundleClientPackage({
955
+ step,
956
+ bun,
957
+ root: planned.root,
958
+ tsconfig: planned.tsconfig,
959
+ entries: [...planned.entries.values()],
960
+ external: planned.external,
961
+ runtime: options.runtime ?? "node",
962
+ replacements: planned.replacements,
963
+ work,
964
+ outdir: join6(staged, "dist")
965
+ });
828
966
  refuseForbiddenModules(graph, options.forbiddenModules ?? []);
829
967
  await refuseBundledExternals(graph, externals);
830
968
  await emitClientDeclarations({
@@ -832,9 +970,9 @@ async function buildClientPackage(options) {
832
970
  tsc,
833
971
  tsconfig: planned.tsconfig,
834
972
  entries: [...planned.entries.values()],
835
- outDir: join5(staged, "dist")
973
+ outDir: join6(staged, "dist")
836
974
  });
837
- normalizeClientDeclarations(join5(staged, "dist"), {
975
+ normalizeClientDeclarations(join6(staged, "dist"), {
838
976
  packages: new Set(planned.external),
839
977
  runtime: options.runtime ?? "node"
840
978
  });
@@ -844,7 +982,7 @@ async function buildClientPackage(options) {
844
982
  if (!packed.ok) {
845
983
  throw new ClientPackageError("install", `Client package pack failed (exit ${packed.exit}): ${packed.output}`, { output: packed.output });
846
984
  }
847
- const consumer = join5(work, "consumer");
985
+ const consumer = join6(work, "consumer");
848
986
  await mkdir3(consumer);
849
987
  const proven = await proveClientPackage({
850
988
  options,
@@ -854,7 +992,8 @@ async function buildClientPackage(options) {
854
992
  staged,
855
993
  tarball: planned.tarball,
856
994
  externals,
857
- root: planned.root
995
+ root: planned.root,
996
+ exportedFiles: planned.exportedFiles
858
997
  });
859
998
  const archive = await readFile4(planned.tarball);
860
999
  return {
@@ -960,11 +1099,11 @@ import { fileURLToPath } from "node:url";
960
1099
  import { z as z5 } from "zod";
961
1100
 
962
1101
  // src/files/native-packaging-plugin.ts
963
- import { existsSync as existsSync4, readFileSync as readFileSync2, realpathSync } from "node:fs";
964
- import { basename as basename3, join as join6 } from "node:path";
965
- var realpath3 = (path) => {
1102
+ import { existsSync as existsSync4, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
1103
+ import { basename as basename3, join as join7 } from "node:path";
1104
+ var realpath4 = (path) => {
966
1105
  try {
967
- return realpathSync(path);
1106
+ return realpathSync2(path);
968
1107
  } catch {
969
1108
  return path;
970
1109
  }
@@ -974,7 +1113,7 @@ function loaderInstallation(path, loaderName) {
974
1113
  if (!path.endsWith(suffix))
975
1114
  return;
976
1115
  const root = path.slice(0, -suffix.length);
977
- const manifest = join6(root, "package.json");
1116
+ const manifest = join7(root, "package.json");
978
1117
  if (!existsSync4(manifest))
979
1118
  return;
980
1119
  try {
@@ -993,7 +1132,7 @@ function loaderInstallation(path, loaderName) {
993
1132
  function nativePlugin(owner, specifiers, embedded, companionEntry) {
994
1133
  const contents = nativeLoaderSource(specifiers, "static");
995
1134
  const external = new Set(Object.values(specifiers));
996
- const ownLoader = realpath3(owner.loaderPath);
1135
+ const ownLoader = realpath4(owner.loaderPath);
997
1136
  const loaderFile = basename3(owner.loaderName);
998
1137
  return {
999
1138
  name: "stitchkit-native-packaging",
@@ -1013,7 +1152,7 @@ function nativePlugin(owner, specifiers, embedded, companionEntry) {
1013
1152
  return { contents, loader: "js" };
1014
1153
  if (basename3(args.path) !== loaderFile)
1015
1154
  return;
1016
- if (realpath3(args.path) === ownLoader)
1155
+ if (realpath4(args.path) === ownLoader)
1017
1156
  return { contents, loader: "js" };
1018
1157
  const foreign = loaderInstallation(args.path, owner.loaderName);
1019
1158
  if (!foreign)
@@ -1026,7 +1165,7 @@ function nativePlugin(owner, specifiers, embedded, companionEntry) {
1026
1165
  return bytes ? { contents: bytes, loader: "napi" } : undefined;
1027
1166
  });
1028
1167
  if (companionEntry !== undefined)
1029
- build.onResolve({ filter: /./ }, (args) => (args.importer === owner.loaderPath || realpath3(args.importer) === ownLoader) && external.has(args.path) ? { path: args.path, external: true } : undefined);
1168
+ build.onResolve({ filter: /./ }, (args) => (args.importer === owner.loaderPath || realpath4(args.importer) === ownLoader) && external.has(args.path) ? { path: args.path, external: true } : undefined);
1030
1169
  }
1031
1170
  };
1032
1171
  }
@@ -0,0 +1,25 @@
1
+ import { type ClientBuildGraph, type ClientBuildStep } from './client-build.js';
2
+ /** Extension of a replaced module → the loader its replacement contents are read with. */
3
+ export declare const REPLACEMENT_LOADERS: Readonly<Record<string, string>>;
4
+ /** What one build of a client package needs. */
5
+ export interface ClientPackageBundleInput {
6
+ step: ClientBuildStep;
7
+ bun: string;
8
+ /** The build root: the tsconfig's directory, where the bundler runs. */
9
+ root: string;
10
+ tsconfig: string;
11
+ entries: readonly string[];
12
+ external: readonly string[];
13
+ runtime: 'node' | 'bun' | 'browser';
14
+ /** Absolute path of a replaced module → its contents. */
15
+ replacements: ReadonlyMap<string, string>;
16
+ /** The temporary directory the script, its config and the metafile go to. */
17
+ work: string;
18
+ outdir: string;
19
+ }
20
+ /**
21
+ * Build every entry in one pass, so a module two of them import is emitted
22
+ * once, and refuse a replacement that no bundled module imports.
23
+ */
24
+ export declare function bundleClientPackage(input: ClientPackageBundleInput): Promise<ClientBuildGraph>;
25
+ //# sourceMappingURL=client-package-bundle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-package-bundle.d.ts","sourceRoot":"","sources":["../../src/files/client-package-bundle.ts"],"names":[],"mappings":"AAYA,OAAO,EACL,KAAK,gBAAgB,EACrB,KAAK,eAAe,EAGrB,MAAM,gBAAgB,CAAC;AAGxB,0FAA0F;AAC1F,eAAO,MAAM,mBAAmB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQhE,CAAC;AAEF,gDAAgD;AAChD,MAAM,WAAW,wBAAwB;IACvC,IAAI,EAAE,eAAe,CAAC;IACtB,GAAG,EAAE,MAAM,CAAC;IACZ,wEAAwE;IACxE,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3B,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B,OAAO,EAAE,MAAM,GAAG,KAAK,GAAG,SAAS,CAAC;IACpC,yDAAyD;IACzD,YAAY,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC1C,6EAA6E;IAC7E,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CAChB;AAmDD;;;GAGG;AACH,wBAAsB,mBAAmB,CACvC,KAAK,EAAE,wBAAwB,GAC9B,OAAO,CAAC,gBAAgB,CAAC,CA8C3B"}
@@ -71,6 +71,24 @@ export interface ClientPackageOptions {
71
71
  manifest?: ClientPackageManifest;
72
72
  /** Extra files of the package: path inside the package → source file. */
73
73
  files?: Readonly<Record<string, string>>;
74
+ /**
75
+ * Files a consumer imports by subpath, written to `exports` beside the
76
+ * entries: `'./package.json'` is the archive's own manifest, any other names
77
+ * a path in `files` (`'./native-stream.json'` for `files['native-stream.json']`).
78
+ * The proof resolves each by the package name in every runtime, imports a
79
+ * `.json` file with `with { type: 'json' }` and typechecks that import.
80
+ */
81
+ exportedFiles?: readonly `./${string}`[];
82
+ /**
83
+ * Modules the bundle takes as other contents: source file → the contents it
84
+ * is built from instead, in that file's own format (`.json`, `.ts`, `.tsx`,
85
+ * `.js`, `.jsx`). A key is resolved like an entry and replaces every import
86
+ * that reaches that file, so `{ 'package.json': JSON.stringify({ version }) }`
87
+ * ships one field of the project manifest instead of its scripts. A
88
+ * replacement no bundled module imports is refused. Declarations are still
89
+ * emitted from the files themselves.
90
+ */
91
+ replaceModules?: Readonly<Record<string, string>>;
74
92
  /** What the installed archive must additionally satisfy. */
75
93
  proof?: {
76
94
  /**
@@ -118,7 +136,7 @@ export interface ClientPackage {
118
136
  }[];
119
137
  /** Absolute path of every source module bundled into the package. */
120
138
  modules: readonly string[];
121
- /** Per subpath: the names the installed package exports at runtime. */
139
+ /** Per subpath: the names the installed package exports at runtime; a `.json` file exports `default`. */
122
140
  exports: Readonly<Record<string, readonly string[]>>;
123
141
  /** Names more than one subpath exports, each proven to be one value across them. */
124
142
  sharedExports: readonly string[];
@@ -131,6 +149,8 @@ export interface ClientPackage {
131
149
  typescript: string;
132
150
  /** Each peer and dependency the proof installed → its version. */
133
151
  externals: Readonly<Record<string, string>>;
152
+ /** Each of `exportedFiles`, resolved by the package name to the packed file in every runtime. */
153
+ exportedFiles: readonly string[];
134
154
  };
135
155
  }
136
156
  /** Every reason `buildClientPackage` refuses with. */
@@ -144,6 +164,7 @@ export declare const ClientPackageRefusalSchema: z.ZodEnum<{
144
164
  "manifest-owned-field": "manifest-owned-field";
145
165
  "missing-export": "missing-export";
146
166
  "peer-range": "peer-range";
167
+ "replacement-unused": "replacement-unused";
147
168
  "shared-export-split": "shared-export-split";
148
169
  typecheck: "typecheck";
149
170
  }>;
@@ -1 +1 @@
1
- {"version":3,"file":"client-package-contract.d.ts","sourceRoot":"","sources":["../../src/files/client-package-contract.ts"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AC;KAClC,CAAC;CACH;AAED,sDAAsD;AACtD,eAAO,MAAM,0BAA0B;;;;;;;;;;;;;EAyBrC,CAAC;AAEH,iFAAiF;AACjF,qBAAa,kBAAmB,SAAQ,KAAK;IAEzC,mEAAmE;IACnE,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,0BAA0B,CAAC;IAE3D,6FAA6F;IAC7F,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IALrD;IACE,mEAAmE;IAC1D,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,0BAA0B,CAAC,EAC3D,OAAO,EAAE,MAAM;IACf,6FAA6F;IACpF,OAAO,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAM,EACxD,OAAO,CAAC,EAAE,YAAY,EAIvB;CACF"}
@@ -30,6 +30,8 @@ export interface ClientPackageProofInput {
30
30
  externals: ReadonlyMap<string, ExternalPackage>;
31
31
  /** The project directory type packages are resolved from. */
32
32
  root: string;
33
+ /** Exported file subpath → the packed file it names, `./`-relative. */
34
+ exportedFiles: ReadonlyMap<string, string>;
33
35
  }
34
36
  type ProvenPackage = Pick<ClientPackage, 'files' | 'exports' | 'sharedExports' | 'proof'>;
35
37
  /** Prove the packed archive; every refusal is a `ClientPackageError`. */
@@ -1 +1 @@
1
- {"version":3,"file":"client-package-proof.d.ts","sourceRoot":"","sources":["../../src/files/client-package-proof.ts"],"names":[],"mappings":"AAiBA,OAAO,EACL,KAAK,eAAe,EACpB,KAAK,iBAAiB,EAGvB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,KAAK,aAAa,EAElB,KAAK,oBAAoB,EAC1B,MAAM,2BAA2B,CAAC;AAEnC,wFAAwF;AACxF,MAAM,WAAW,eAAe;IAC9B,0CAA0C;IAC1C,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;CAC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EACZ,IAAI,EAAE,MAAM,GACX,OAAO,CAAC,eAAe,CAAC,CAkB1B;AAgFD,2CAA2C;AAC3C,MAAM,WAAW,uBAAuB;IACtC,OAAO,EAAE,oBAAoB,CAAC;IAC9B,IAAI,EAAE,eAAe,CAAC;IACtB,KAAK,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,iBAAiB,CAAA;KAAE,CAAC;IAC7D,qDAAqD;IACrD,QAAQ,EAAE,MAAM,CAAC;IACjB,gEAAgE;IAChE,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,+DAA+D;IAC/D,SAAS,EAAE,WAAW,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IAChD,6DAA6D;IAC7D,IAAI,EAAE,MAAM,CAAC;IACb,uEAAuE;IACvE,aAAa,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC5C;AAED,KAAK,aAAa,GAAG,IAAI,CAAC,aAAa,EAAE,OAAO,GAAG,SAAS,GAAG,eAAe,GAAG,OAAO,CAAC,CAAC;AAkQ1F,yEAAyE;AACzE,wBAAsB,kBAAkB,CACtC,KAAK,EAAE,uBAAuB,GAC7B,OAAO,CAAC,aAAa,CAAC,CAiBxB"}
@@ -1 +1 @@
1
- {"version":3,"file":"client-package.d.ts","sourceRoot":"","sources":["../../src/files/client-package.ts"],"names":[],"mappings":"AA8BA,OAAO,EAEL,KAAK,aAAa,EAGlB,KAAK,oBAAoB,EAC1B,MAAM,2BAA2B,CAAC;AAgNnC;;;;;;;;;;;;;GAaG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,oBAAoB,GAC5B,OAAO,CAAC,aAAa,CAAC,CAsFxB"}
1
+ {"version":3,"file":"client-package.d.ts","sourceRoot":"","sources":["../../src/files/client-package.ts"],"names":[],"mappings":"AA8BA,OAAO,EAEL,KAAK,aAAa,EAGlB,KAAK,oBAAoB,EAC1B,MAAM,2BAA2B,CAAC;AAwNnC;;;;;;;;;;;;;GAaG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,oBAAoB,GAC5B,OAAO,CAAC,aAAa,CAAC,CAkGxB"}
@@ -58,9 +58,9 @@ It also owns the two builds of a client — one self-contained file, and a typed
58
58
  | `ClientArtifactOptions` | _type_ | entry, output file, runtime, forbidden modules, `executables.bun`, deadline and signal |
59
59
  | `ClientArtifact` | _type_ | the built file, its SHA-256 and size, and the bundled modules |
60
60
  | `buildClientPackage` | function | build several entries of a typed client into one npm archive over one module graph, with peers and dependencies outside and declarations that resolve under Bundler and NodeNext, and return it only after the archive was installed, imported in Node and Bun and typechecked by a strict consumer — [guide](../guide/native-io.md#a-typed-client-as-an-npm-package), [ADR 0331](../decisions/0331-a-client-package-is-one-module-graph-proven-installed.md) |
61
- | `ClientPackageOptions` | _type_ | name, version, `entries` by subpath, `tsconfig`, peers and dependencies, forbidden modules, runtime, output directory, `manifest`, extra `files`, `proof` (consumer sources, required and distinct exports, type packages), `executables`, deadline and signal |
61
+ | `ClientPackageOptions` | _type_ | name, version, `entries` by subpath, `tsconfig`, peers and dependencies, forbidden modules, runtime, output directory, `manifest`, extra `files`, `exportedFiles` (`./package.json` and packed files a consumer imports by subpath), `replaceModules` (a module built from given contents), `proof` (consumer sources, required and distinct exports, type packages), `executables`, deadline and signal |
62
62
  | `ClientPackageManifest` | _type_ | descriptive `package.json` fields of the package; a field the build writes itself is refused |
63
- | `ClientPackage` | _type_ | the archive with its SHA-256 and size, every packed file with its digest, the bundled modules, exports per subpath, the names proven shared across subpaths, and what the proof ran |
63
+ | `ClientPackage` | _type_ | the archive with its SHA-256 and size, every packed file with its digest, the bundled modules, exports per subpath, the names proven shared across subpaths, and what the proof ran, the exported files it resolved included |
64
64
  | `ClientPackageError` | class | the refusal of a client package: a closed `reason` and `details` naming the file, specifier, package or names |
65
65
  | `ForbiddenModule` | _type_ | a package name or subpath, a source path fragment or a `RegExp` over module paths |
66
66
  | `ForbiddenModuleError` | class | the refusal of a client that reaches a forbidden module, bundled or left external: `module` and `importedBy` |
@@ -330,13 +330,45 @@ rewrites every relative specifier to the `.js` file it stands for, whether the s
330
330
  | `declaration-unresolved` | a relative module with no declaration in the package — a hand-written `.d.ts` beside the sources, or a `/// <reference path>` | move the types into a `.ts` module |
331
331
  | `declaration-dependency` | a package that is neither a peer nor a dependency — including a tsconfig path alias such as `@/schema` | declare the package, or keep its types out of the public surface; import own modules relatively |
332
332
 
333
+ ### Files imported by subpath, and modules built from other contents
334
+
335
+ `exportedFiles` puts files a consumer imports by name into `exports`, beside the entries:
336
+ `'./package.json'` is the archive's own manifest — a consumer reads the client's version from it —
337
+ and any other names a path in `files`:
338
+
339
+ ```ts
340
+ files: { 'native-stream.json': 'config/native-stream.json' },
341
+ exportedFiles: ['./package.json', './native-stream.json'],
342
+ // consumer: import pkg from '@acme/api-client/package.json' with { type: 'json' }
343
+ ```
344
+
345
+ The proof resolves each by the package name to its packed file in every runtime it imports the
346
+ entries in, imports a `.json` file as JSON (`client.exports` lists its `default`), and the strict
347
+ consumer imports it with `with { type: 'json' }` under both resolutions. A file that is in `files`
348
+ but not in `exportedFiles` is packed and not importable by name.
349
+
350
+ `replaceModules` builds a module from contents you give instead of its file. The key is a path,
351
+ resolved like an entry; the contents are in that file's own format (`.json`, `.ts`, `.tsx`, `.js`,
352
+ `.jsx`), and every import that reaches the file gets them. A client that imports the project's
353
+ `package.json` for its version otherwise ships the whole manifest, `scripts` and
354
+ `devDependencies` included:
355
+
356
+ ```ts
357
+ replaceModules: { 'package.json': JSON.stringify({ version }) },
358
+ ```
359
+
360
+ A replacement no bundled module imports is refused as `replacement-unused`: it would say the
361
+ package was built from something it was not. Declarations are still emitted from the files
362
+ themselves, so a replacement keeps the shape the types describe.
363
+
333
364
  ### What the proof runs
334
365
 
335
366
  The archive is installed into an empty directory beside its peers. There the build:
336
367
 
337
368
  1. compares every installed file with the one it built;
338
369
  2. imports every subpath by the package name — in Node and Bun for `runtime: 'node'` (the
339
- default), in Bun for `'bun'` and `'browser'` — and checks `proof.exports` and shared names;
370
+ default), in Bun for `'bun'` and `'browser'` — and checks `proof.exports` and shared names,
371
+ and resolves every exported file;
340
372
  3. typechecks a strict consumer (`strict`, `skipLibCheck: false`) that re-exports every subpath,
341
373
  under `moduleResolution: bundler` and under `NodeNext`.
342
374
 
@@ -364,13 +396,14 @@ A refusal is a `ClientPackageError`: switch on `reason`, read `details`. A forbi
364
396
  | `reason` | When | `details` |
365
397
  |---|---|---|
366
398
  | `build` | the bundler failed | `output` |
399
+ | `replacement-unused` | a module in `replaceModules` is imported by no bundled module | `module` |
367
400
  | `declarations` | the compiler reported an error in the client's graph | `output` |
368
401
  | `declaration-unresolved`, `declaration-dependency` | see above | `file`, `specifier`, `package` |
369
402
  | `bundled-peer` | code of a peer or dependency is in the package | `package`, `module` |
370
403
  | `manifest-owned-field` | `manifest` sets a field the build writes | `field` |
371
404
  | `install` | a peer is not installed for the build, or packing, installing or importing the archive failed | `package` or `output`, `runtime` |
372
405
  | `peer-range` | an installed peer or dependency is outside its declared range | `package`, `range`, `installed` |
373
- | `missing-export` | a subpath lacks a name from `proof.exports` | `subpath`, `names`, `runtime` |
406
+ | `missing-export` | a subpath lacks a name from `proof.exports`, or an exported file does not resolve to its packed path | `subpath`, `names`, `runtime` |
374
407
  | `shared-export-split` | several subpaths export one name as different values | `names`, `runtime` |
375
408
  | `typecheck` | the strict consumer did not typecheck | `resolution`, `output` |
376
409
 
package/llms-full.txt CHANGED
@@ -10958,13 +10958,45 @@ rewrites every relative specifier to the `.js` file it stands for, whether the s
10958
10958
  | `declaration-unresolved` | a relative module with no declaration in the package — a hand-written `.d.ts` beside the sources, or a `/// <reference path>` | move the types into a `.ts` module |
10959
10959
  | `declaration-dependency` | a package that is neither a peer nor a dependency — including a tsconfig path alias such as `@/schema` | declare the package, or keep its types out of the public surface; import own modules relatively |
10960
10960
 
10961
+ ### Files imported by subpath, and modules built from other contents
10962
+
10963
+ `exportedFiles` puts files a consumer imports by name into `exports`, beside the entries:
10964
+ `'./package.json'` is the archive's own manifest — a consumer reads the client's version from it —
10965
+ and any other names a path in `files`:
10966
+
10967
+ ```ts
10968
+ files: { 'native-stream.json': 'config/native-stream.json' },
10969
+ exportedFiles: ['./package.json', './native-stream.json'],
10970
+ // consumer: import pkg from '@acme/api-client/package.json' with { type: 'json' }
10971
+ ```
10972
+
10973
+ The proof resolves each by the package name to its packed file in every runtime it imports the
10974
+ entries in, imports a `.json` file as JSON (`client.exports` lists its `default`), and the strict
10975
+ consumer imports it with `with { type: 'json' }` under both resolutions. A file that is in `files`
10976
+ but not in `exportedFiles` is packed and not importable by name.
10977
+
10978
+ `replaceModules` builds a module from contents you give instead of its file. The key is a path,
10979
+ resolved like an entry; the contents are in that file's own format (`.json`, `.ts`, `.tsx`, `.js`,
10980
+ `.jsx`), and every import that reaches the file gets them. A client that imports the project's
10981
+ `package.json` for its version otherwise ships the whole manifest, `scripts` and
10982
+ `devDependencies` included:
10983
+
10984
+ ```ts
10985
+ replaceModules: { 'package.json': JSON.stringify({ version }) },
10986
+ ```
10987
+
10988
+ A replacement no bundled module imports is refused as `replacement-unused`: it would say the
10989
+ package was built from something it was not. Declarations are still emitted from the files
10990
+ themselves, so a replacement keeps the shape the types describe.
10991
+
10961
10992
  ### What the proof runs
10962
10993
 
10963
10994
  The archive is installed into an empty directory beside its peers. There the build:
10964
10995
 
10965
10996
  1. compares every installed file with the one it built;
10966
10997
  2. imports every subpath by the package name — in Node and Bun for `runtime: 'node'` (the
10967
- default), in Bun for `'bun'` and `'browser'` — and checks `proof.exports` and shared names;
10998
+ default), in Bun for `'bun'` and `'browser'` — and checks `proof.exports` and shared names,
10999
+ and resolves every exported file;
10968
11000
  3. typechecks a strict consumer (`strict`, `skipLibCheck: false`) that re-exports every subpath,
10969
11001
  under `moduleResolution: bundler` and under `NodeNext`.
10970
11002
 
@@ -10992,13 +11024,14 @@ A refusal is a `ClientPackageError`: switch on `reason`, read `details`. A forbi
10992
11024
  | `reason` | When | `details` |
10993
11025
  |---|---|---|
10994
11026
  | `build` | the bundler failed | `output` |
11027
+ | `replacement-unused` | a module in `replaceModules` is imported by no bundled module | `module` |
10995
11028
  | `declarations` | the compiler reported an error in the client's graph | `output` |
10996
11029
  | `declaration-unresolved`, `declaration-dependency` | see above | `file`, `specifier`, `package` |
10997
11030
  | `bundled-peer` | code of a peer or dependency is in the package | `package`, `module` |
10998
11031
  | `manifest-owned-field` | `manifest` sets a field the build writes | `field` |
10999
11032
  | `install` | a peer is not installed for the build, or packing, installing or importing the archive failed | `package` or `output`, `runtime` |
11000
11033
  | `peer-range` | an installed peer or dependency is outside its declared range | `package`, `range`, `installed` |
11001
- | `missing-export` | a subpath lacks a name from `proof.exports` | `subpath`, `names`, `runtime` |
11034
+ | `missing-export` | a subpath lacks a name from `proof.exports`, or an exported file does not resolve to its packed path | `subpath`, `names`, `runtime` |
11002
11035
  | `shared-export-split` | several subpaths export one name as different values | `names`, `runtime` |
11003
11036
  | `typecheck` | the strict consumer did not typecheck | `resolution`, `output` |
11004
11037
 
@@ -30416,9 +30449,9 @@ It also owns the two builds of a client — one self-contained file, and a typed
30416
30449
  | `ClientArtifactOptions` | _type_ | entry, output file, runtime, forbidden modules, `executables.bun`, deadline and signal |
30417
30450
  | `ClientArtifact` | _type_ | the built file, its SHA-256 and size, and the bundled modules |
30418
30451
  | `buildClientPackage` | function | build several entries of a typed client into one npm archive over one module graph, with peers and dependencies outside and declarations that resolve under Bundler and NodeNext, and return it only after the archive was installed, imported in Node and Bun and typechecked by a strict consumer — [guide](../guide/native-io.md#a-typed-client-as-an-npm-package), [ADR 0331](../decisions/0331-a-client-package-is-one-module-graph-proven-installed.md) |
30419
- | `ClientPackageOptions` | _type_ | name, version, `entries` by subpath, `tsconfig`, peers and dependencies, forbidden modules, runtime, output directory, `manifest`, extra `files`, `proof` (consumer sources, required and distinct exports, type packages), `executables`, deadline and signal |
30452
+ | `ClientPackageOptions` | _type_ | name, version, `entries` by subpath, `tsconfig`, peers and dependencies, forbidden modules, runtime, output directory, `manifest`, extra `files`, `exportedFiles` (`./package.json` and packed files a consumer imports by subpath), `replaceModules` (a module built from given contents), `proof` (consumer sources, required and distinct exports, type packages), `executables`, deadline and signal |
30420
30453
  | `ClientPackageManifest` | _type_ | descriptive `package.json` fields of the package; a field the build writes itself is refused |
30421
- | `ClientPackage` | _type_ | the archive with its SHA-256 and size, every packed file with its digest, the bundled modules, exports per subpath, the names proven shared across subpaths, and what the proof ran |
30454
+ | `ClientPackage` | _type_ | the archive with its SHA-256 and size, every packed file with its digest, the bundled modules, exports per subpath, the names proven shared across subpaths, and what the proof ran, the exported files it resolved included |
30422
30455
  | `ClientPackageError` | class | the refusal of a client package: a closed `reason` and `details` naming the file, specifier, package or names |
30423
30456
  | `ForbiddenModule` | _type_ | a package name or subpath, a source path fragment or a `RegExp` over module paths |
30424
30457
  | `ForbiddenModuleError` | class | the refusal of a client that reaches a forbidden module, bundled or left external: `module` and `importedBy` |
package/llms.txt CHANGED
@@ -80,9 +80,9 @@ Load the slice for each entrypoint your code imports — `import … from 'stitc
80
80
  - **stitchkit/node**: [llms/node.txt](llms/node.txt) 3.3 KB
81
81
  - **stitchkit/agent-runtime/react**: [llms/agent-runtime-react.txt](llms/agent-runtime-react.txt) 1.0 KB
82
82
  - **stitchkit/agent-runtime/realtime**: [llms/agent-runtime-realtime.txt](llms/agent-runtime-realtime.txt) 2.6 KB
83
- - **stitchkit/process**: [llms/process.txt](llms/process.txt) 42.0 KB → [llms/process.2.txt](llms/process.2.txt) 29.3 KB
83
+ - **stitchkit/process**: [llms/process.txt](llms/process.txt) 42.0 KB → [llms/process.2.txt](llms/process.2.txt) 31.1 KB
84
84
  - **stitchkit/process/bootstrap**: [llms/process-bootstrap.txt](llms/process-bootstrap.txt) 1.0 KB
85
- - **stitchkit/files/packaging**: [llms/files-packaging.txt](llms/files-packaging.txt) 5.5 KB
85
+ - **stitchkit/files/packaging**: [llms/files-packaging.txt](llms/files-packaging.txt) 5.7 KB
86
86
  - **stitchkit/http**: [llms/http.txt](llms/http.txt) 2.9 KB
87
87
  - **stitchkit/realtime**: [llms/realtime.txt](llms/realtime.txt) 2.0 KB
88
88
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stitchkit",
3
- "version": "0.133.0",
3
+ "version": "0.133.1",
4
4
  "description": "Contract-first backend framework — one defineContract() into an HTTP API, MCP tools, AI-agent tools and a typed client. Bun and Node.",
5
5
  "keywords": [
6
6
  "bun",