@powerhousedao/switchboard 6.2.3-dev.8 → 6.2.3-dev.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. package/.tsbuild/test/attachments/byte-grants.test.d.ts +2 -0
  2. package/.tsbuild/test/attachments/byte-grants.test.d.ts.map +1 -0
  3. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts +2 -0
  4. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts.map +1 -0
  5. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts +2 -0
  6. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts.map +1 -0
  7. package/.tsbuild/test/attachments/url-signer.test.d.ts +2 -0
  8. package/.tsbuild/test/attachments/url-signer.test.d.ts.map +1 -0
  9. package/.tsbuild/test/boot-auth-config.test.d.ts +2 -0
  10. package/.tsbuild/test/boot-auth-config.test.d.ts.map +1 -0
  11. package/.tsbuild/test/boot-create-signature-policy.test.d.ts +2 -0
  12. package/.tsbuild/test/boot-create-signature-policy.test.d.ts.map +1 -0
  13. package/.tsbuild/test/boot-env-isolation.test.d.ts +2 -0
  14. package/.tsbuild/test/boot-env-isolation.test.d.ts.map +1 -0
  15. package/.tsbuild/test/boot-helpers.d.ts +5 -0
  16. package/.tsbuild/test/boot-helpers.d.ts.map +1 -0
  17. package/.tsbuild/test/boot-inspection-enabled.test.d.ts +2 -0
  18. package/.tsbuild/test/boot-inspection-enabled.test.d.ts.map +1 -0
  19. package/.tsbuild/test/boot-mcp-auth.test.d.ts +2 -0
  20. package/.tsbuild/test/boot-mcp-auth.test.d.ts.map +1 -0
  21. package/.tsbuild/test/boot-mcp-enabled.test.d.ts +2 -0
  22. package/.tsbuild/test/boot-mcp-enabled.test.d.ts.map +1 -0
  23. package/.tsbuild/test/boot-port-zero.test.d.ts +2 -0
  24. package/.tsbuild/test/boot-port-zero.test.d.ts.map +1 -0
  25. package/.tsbuild/test/boot-preconditions.test.d.ts +2 -0
  26. package/.tsbuild/test/boot-preconditions.test.d.ts.map +1 -0
  27. package/.tsbuild/test/boot-privacy.test.d.ts +2 -0
  28. package/.tsbuild/test/boot-privacy.test.d.ts.map +1 -0
  29. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts +2 -0
  30. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts.map +1 -0
  31. package/.tsbuild/test/boot-without-renown.test.d.ts +2 -0
  32. package/.tsbuild/test/boot-without-renown.test.d.ts.map +1 -0
  33. package/.tsbuild/test/boot-without-require-signatures.test.d.ts +2 -0
  34. package/.tsbuild/test/boot-without-require-signatures.test.d.ts.map +1 -0
  35. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts +2 -0
  36. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts.map +1 -0
  37. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts +2 -0
  38. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts.map +1 -0
  39. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts +2 -0
  40. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts.map +1 -0
  41. package/.tsbuild/test/builder-defaults.test.d.ts +2 -0
  42. package/.tsbuild/test/builder-defaults.test.d.ts.map +1 -0
  43. package/.tsbuild/test/config-from-env.test.d.ts +2 -0
  44. package/.tsbuild/test/config-from-env.test.d.ts.map +1 -0
  45. package/.tsbuild/test/config-merge.test.d.ts +2 -0
  46. package/.tsbuild/test/config-merge.test.d.ts.map +1 -0
  47. package/.tsbuild/test/config-schema.test.d.ts +2 -0
  48. package/.tsbuild/test/config-schema.test.d.ts.map +1 -0
  49. package/.tsbuild/test/create-signature-policy.test.d.ts +2 -0
  50. package/.tsbuild/test/create-signature-policy.test.d.ts.map +1 -0
  51. package/.tsbuild/test/default-drive-protocol-versions.test.d.ts +2 -0
  52. package/.tsbuild/test/default-drive-protocol-versions.test.d.ts.map +1 -0
  53. package/.tsbuild/test/default-drive-slug.test.d.ts +2 -0
  54. package/.tsbuild/test/default-drive-slug.test.d.ts.map +1 -0
  55. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts +2 -0
  56. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts.map +1 -0
  57. package/.tsbuild/test/fatal-shutdown.test.d.ts +2 -0
  58. package/.tsbuild/test/fatal-shutdown.test.d.ts.map +1 -0
  59. package/.tsbuild/test/inspection-throttle.test.d.ts +2 -0
  60. package/.tsbuild/test/inspection-throttle.test.d.ts.map +1 -0
  61. package/.tsbuild/test/observability-signals.test.d.ts +2 -0
  62. package/.tsbuild/test/observability-signals.test.d.ts.map +1 -0
  63. package/.tsbuild/test/permissions-backfill.test.d.ts +2 -0
  64. package/.tsbuild/test/permissions-backfill.test.d.ts.map +1 -0
  65. package/.tsbuild/test/pglite-preflight.test.d.ts +2 -0
  66. package/.tsbuild/test/pglite-preflight.test.d.ts.map +1 -0
  67. package/.tsbuild/test/pglite-storage-dirs.test.d.ts +2 -0
  68. package/.tsbuild/test/pglite-storage-dirs.test.d.ts.map +1 -0
  69. package/.tsbuild/test/pglite-store.test.d.ts +2 -0
  70. package/.tsbuild/test/pglite-store.test.d.ts.map +1 -0
  71. package/.tsbuild/test/plugin-config-schemas.test.d.ts +2 -0
  72. package/.tsbuild/test/plugin-config-schemas.test.d.ts.map +1 -0
  73. package/.tsbuild/test/plugin-presence.test.d.ts +2 -0
  74. package/.tsbuild/test/plugin-presence.test.d.ts.map +1 -0
  75. package/.tsbuild/test/port-probe.test.d.ts +2 -0
  76. package/.tsbuild/test/port-probe.test.d.ts.map +1 -0
  77. package/.tsbuild/test/renown-storage-path.test.d.ts +2 -0
  78. package/.tsbuild/test/renown-storage-path.test.d.ts.map +1 -0
  79. package/.tsbuild/test/renown-trust-policy.test.d.ts +2 -0
  80. package/.tsbuild/test/renown-trust-policy.test.d.ts.map +1 -0
  81. package/.tsbuild/test/served-schemas.test.d.ts +2 -0
  82. package/.tsbuild/test/served-schemas.test.d.ts.map +1 -0
  83. package/.tsbuild/test/shutdown.test.d.ts +2 -0
  84. package/.tsbuild/test/shutdown.test.d.ts.map +1 -0
  85. package/.tsbuild/test/snapshot-writer.d.ts +18 -0
  86. package/.tsbuild/test/snapshot-writer.d.ts.map +1 -0
  87. package/.tsbuild/test/store-lock.test.d.ts +2 -0
  88. package/.tsbuild/test/store-lock.test.d.ts.map +1 -0
  89. package/.tsbuild/test/two-switchboards.test.d.ts +2 -0
  90. package/.tsbuild/test/two-switchboards.test.d.ts.map +1 -0
  91. package/.tsbuild/test/unsupported-stored-documents.test.d.ts +2 -0
  92. package/.tsbuild/test/unsupported-stored-documents.test.d.ts.map +1 -0
  93. package/.tsbuild/test/workflow/harness.d.ts +56 -0
  94. package/.tsbuild/test/workflow/harness.d.ts.map +1 -0
  95. package/.tsbuild/test/workflow/oauth.test.d.ts +2 -0
  96. package/.tsbuild/test/workflow/oauth.test.d.ts.map +1 -0
  97. package/.tsbuild/test/workflow/resolvers.test.d.ts +2 -0
  98. package/.tsbuild/test/workflow/resolvers.test.d.ts.map +1 -0
  99. package/.tsbuild/test/workflow/runtime-host.test.d.ts +2 -0
  100. package/.tsbuild/test/workflow/runtime-host.test.d.ts.map +1 -0
  101. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts +2 -0
  102. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts.map +1 -0
  103. package/.tsbuild/test/workflow/webhook-signed.test.d.ts +2 -0
  104. package/.tsbuild/test/workflow/webhook-signed.test.d.ts.map +1 -0
  105. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts +2 -0
  106. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts.map +1 -0
  107. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts +2 -0
  108. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts.map +1 -0
  109. package/.tsbuild/test/workflow-reactor-access.test.d.ts +2 -0
  110. package/.tsbuild/test/workflow-reactor-access.test.d.ts.map +1 -0
  111. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts +2 -0
  112. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts.map +1 -0
  113. package/.tsbuild/test/workflow-read-gate.test.d.ts +2 -0
  114. package/.tsbuild/test/workflow-read-gate.test.d.ts.map +1 -0
  115. package/.tsbuild/test/workflow-runtime.test.d.ts +2 -0
  116. package/.tsbuild/test/workflow-runtime.test.d.ts.map +1 -0
  117. package/.tsbuild/test/workflows-plugin-config.test.d.ts +2 -0
  118. package/.tsbuild/test/workflows-plugin-config.test.d.ts.map +1 -0
  119. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  120. package/.tsbuild/tsdown.config.d.ts.map +1 -1
  121. package/.tsbuild/vitest.config.d.ts.map +1 -1
  122. package/Auth.md +144 -2
  123. package/CHANGELOG.md +1074 -0
  124. package/README.md +55 -14
  125. package/dist/boot.d.mts +46 -0
  126. package/dist/boot.d.mts.map +1 -0
  127. package/dist/boot.mjs +67 -0
  128. package/dist/boot.mjs.map +1 -0
  129. package/dist/config/from-env.d.mts +15 -0
  130. package/dist/config/from-env.d.mts.map +1 -0
  131. package/dist/config/from-env.mjs +4 -0
  132. package/dist/config/schema.d.mts +3 -0
  133. package/dist/config/schema.mjs +4 -0
  134. package/dist/from-env-BO0n9R02.mjs +401 -0
  135. package/dist/from-env-BO0n9R02.mjs.map +1 -0
  136. package/dist/index.d.mts +2 -1
  137. package/dist/index.mjs +76 -79
  138. package/dist/index.mjs.map +1 -1
  139. package/dist/install-packages.d.mts +2 -1
  140. package/dist/install-packages.mjs +2 -2
  141. package/dist/install-packages.mjs.map +1 -1
  142. package/dist/mcp-SsBK14Jm.mjs +32 -0
  143. package/dist/mcp-SsBK14Jm.mjs.map +1 -0
  144. package/dist/migrate.d.mts +2 -1
  145. package/dist/migrate.mjs +7 -5
  146. package/dist/migrate.mjs.map +1 -1
  147. package/dist/plugin-host-C1sYEm8g.d.mts +46 -0
  148. package/dist/plugin-host-C1sYEm8g.d.mts.map +1 -0
  149. package/dist/plugins/attachments.d.mts +33 -0
  150. package/dist/plugins/attachments.d.mts.map +1 -0
  151. package/dist/plugins/attachments.mjs +4 -0
  152. package/dist/plugins/mcp.d.mts +31 -0
  153. package/dist/plugins/mcp.d.mts.map +1 -0
  154. package/dist/plugins/mcp.mjs +4 -0
  155. package/dist/plugins/privacy.d.mts +22 -0
  156. package/dist/plugins/privacy.d.mts.map +1 -0
  157. package/dist/plugins/privacy.mjs +4 -0
  158. package/dist/plugins/workflows.d.mts +79 -0
  159. package/dist/plugins/workflows.d.mts.map +1 -0
  160. package/dist/plugins/workflows.mjs +4 -0
  161. package/dist/postgres-url-DTDhBjXX.mjs +11 -0
  162. package/dist/postgres-url-DTDhBjXX.mjs.map +1 -0
  163. package/dist/privacy-BO8Q25xI.mjs +44 -0
  164. package/dist/privacy-BO8Q25xI.mjs.map +1 -0
  165. package/dist/privacy-DxIJGH4P.mjs +91 -0
  166. package/dist/privacy-DxIJGH4P.mjs.map +1 -0
  167. package/dist/renown-layers-COZsrGQT.mjs +40 -0
  168. package/dist/renown-layers-COZsrGQT.mjs.map +1 -0
  169. package/dist/schema-0g_QdOWn.mjs +267 -0
  170. package/dist/schema-0g_QdOWn.mjs.map +1 -0
  171. package/dist/schema-ivUWPQOn.d.mts +202 -0
  172. package/dist/schema-ivUWPQOn.d.mts.map +1 -0
  173. package/dist/server-cE1BWLQu.mjs +2518 -0
  174. package/dist/server-cE1BWLQu.mjs.map +1 -0
  175. package/dist/server.d.mts +270 -48
  176. package/dist/server.d.mts.map +1 -1
  177. package/dist/server.mjs +5 -5
  178. package/dist/utils-C6AIF38Z.mjs +133 -0
  179. package/dist/utils-C6AIF38Z.mjs.map +1 -0
  180. package/dist/utils.d.mts +12 -5
  181. package/dist/utils.d.mts.map +1 -1
  182. package/dist/utils.mjs +4 -3
  183. package/dist/worker-pool-BWHBLBJd.mjs +304 -0
  184. package/dist/worker-pool-BWHBLBJd.mjs.map +1 -0
  185. package/dist/workflow-runtime-7GaJ13c9.d.mts +30 -0
  186. package/dist/workflow-runtime-7GaJ13c9.d.mts.map +1 -0
  187. package/dist/workflows-COM3MKfD.mjs +1437 -0
  188. package/dist/workflows-COM3MKfD.mjs.map +1 -0
  189. package/package.json +68 -23
  190. package/scripts/install-packages.sh +0 -0
  191. package/test/attachment-reference-read-model.test.ts +28 -20
  192. package/test/attachments/auth.test.ts +85 -0
  193. package/test/attachments/byte-grants.test.ts +290 -0
  194. package/test/attachments/byte-routes-read-gate.integration.test.ts +314 -0
  195. package/test/attachments/download-target.test.ts +211 -32
  196. package/test/attachments/index.test.ts +47 -4
  197. package/test/attachments/reserve-metadata-parity.test.ts +96 -0
  198. package/test/attachments/routes-integration.test.ts +60 -4
  199. package/test/attachments/routes.test.ts +297 -35
  200. package/test/attachments/service-config.test.ts +41 -19
  201. package/test/attachments/url-signer.test.ts +105 -0
  202. package/test/boot-auth-config.test.ts +109 -0
  203. package/test/boot-create-signature-policy.test.ts +110 -0
  204. package/test/boot-env-isolation.test.ts +26 -0
  205. package/test/boot-helpers.ts +19 -0
  206. package/test/boot-inspection-enabled.test.ts +140 -0
  207. package/test/boot-mcp-auth.test.ts +449 -0
  208. package/test/boot-mcp-enabled.test.ts +119 -0
  209. package/test/boot-port-zero.test.ts +101 -0
  210. package/test/boot-preconditions.test.ts +200 -0
  211. package/test/boot-privacy.test.ts +232 -0
  212. package/test/boot-unsupported-stored-documents.test.ts +214 -0
  213. package/test/boot-without-renown.test.ts +83 -0
  214. package/test/boot-without-require-signatures.test.ts +76 -0
  215. package/test/boot-worker-trust-policy.test.ts +91 -0
  216. package/test/boot-workflow-singleton-conflict.test.ts +109 -0
  217. package/test/boot-workflow-singleton-retry.test.ts +122 -0
  218. package/test/builder-defaults.test.ts +80 -0
  219. package/test/config-from-env.test.ts +758 -0
  220. package/test/config-merge.test.ts +215 -0
  221. package/test/config-schema.test.ts +128 -0
  222. package/test/create-signature-policy.test.ts +69 -0
  223. package/test/default-drive-protocol-versions.test.ts +102 -0
  224. package/test/default-drive-slug.test.ts +97 -0
  225. package/test/durable-node-fs-pg16.test.ts +80 -0
  226. package/test/fatal-shutdown.test.ts +165 -0
  227. package/test/goldens/packages.graphql +797 -0
  228. package/test/goldens/privacy.graphql +853 -0
  229. package/test/goldens/reactor-drive-nodes.graphql +827 -0
  230. package/test/goldens/resolvers.json +322 -0
  231. package/test/goldens/supergraph.graphql +5652 -0
  232. package/test/goldens/workflow-runtime.graphql +1419 -0
  233. package/test/inspection-throttle.test.ts +23 -0
  234. package/test/observability-signals.test.ts +131 -0
  235. package/test/permissions-backfill.test.ts +486 -0
  236. package/test/pglite-dialect.test.ts +237 -2
  237. package/test/pglite-preflight.test.ts +313 -0
  238. package/test/pglite-storage-dirs.test.ts +113 -0
  239. package/test/pglite-store.test.ts +264 -0
  240. package/test/pglite-version.test.ts +9 -1
  241. package/test/plugin-config-schemas.test.ts +83 -0
  242. package/test/plugin-presence.test.ts +262 -0
  243. package/test/port-probe.test.ts +45 -0
  244. package/test/renown-storage-path.test.ts +40 -0
  245. package/test/renown-trust-policy.test.ts +313 -0
  246. package/test/served-schemas.test.ts +134 -0
  247. package/test/shutdown.test.ts +278 -0
  248. package/test/snapshot-writer.ts +94 -0
  249. package/test/store-lock.test.ts +65 -0
  250. package/test/two-switchboards.test.ts +146 -0
  251. package/test/unsupported-stored-documents.test.ts +72 -0
  252. package/test/worker-pool.test.ts +27 -1
  253. package/test/workflow/harness.ts +289 -0
  254. package/test/workflow/oauth.test.ts +205 -0
  255. package/test/workflow/resolvers.test.ts +369 -0
  256. package/test/workflow/runtime-host.test.ts +19 -0
  257. package/test/workflow/webhook-dedupe.test.ts +295 -0
  258. package/test/workflow/webhook-signed.test.ts +509 -0
  259. package/test/workflow/webhook-trigger-test.test.ts +82 -0
  260. package/test/workflow/webhook-unsigned.test.ts +345 -0
  261. package/test/workflow-reactor-access.test.ts +384 -0
  262. package/test/workflow-reactor-enforcement.test.ts +808 -0
  263. package/test/workflow-read-gate.test.ts +213 -0
  264. package/test/workflow-runtime.test.ts +1135 -0
  265. package/test/workflows-plugin-config.test.ts +77 -0
  266. package/tsconfig.json +11 -2
  267. package/tsdown.config.ts +12 -1
  268. package/vitest.config.ts +65 -0
  269. package/dist/server-CiKkVE6g.mjs +0 -1555
  270. package/dist/server-CiKkVE6g.mjs.map +0 -1
  271. package/dist/utils-Baw7rThP.mjs +0 -80
  272. package/dist/utils-Baw7rThP.mjs.map +0 -1
@@ -0,0 +1,278 @@
1
+ import { PGlite } from "@electric-sql/pglite";
2
+ import {
3
+ ReactorBuilder,
4
+ ReactorClientBuilder,
5
+ type Database,
6
+ type InProcessReactorClientModule,
7
+ } from "@powerhousedao/reactor";
8
+ import type { ILogger } from "document-model";
9
+ import { Kysely } from "kysely";
10
+ import { PGliteDialect } from "kysely-pglite-dialect";
11
+ import { mkdtemp, rm } from "node:fs/promises";
12
+ import { createServer } from "node:net";
13
+ import { tmpdir } from "node:os";
14
+ import { join } from "node:path";
15
+ import {
16
+ afterEach,
17
+ beforeEach,
18
+ describe,
19
+ expect,
20
+ it,
21
+ vi,
22
+ type MockInstance,
23
+ } from "vitest";
24
+ import { applySwitchboardReactorDefaults } from "../src/builder-defaults.mjs";
25
+ import type { startSwitchboard } from "../src/server.mjs";
26
+ import { bootSwitchboard } from "./boot-helpers.js";
27
+
28
+ type Switchboard = Awaited<ReturnType<typeof startSwitchboard>>;
29
+
30
+ async function freePort(): Promise<number> {
31
+ const server = createServer();
32
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
33
+ const address = server.address();
34
+ await new Promise<void>((resolve) => server.close(() => resolve()));
35
+ if (!address || typeof address === "string") throw new Error("no port");
36
+ return address.port;
37
+ }
38
+
39
+ /** True when nothing holds `port` any more. */
40
+ async function portIsFree(port: number): Promise<boolean> {
41
+ const server = createServer();
42
+ return new Promise((resolve) => {
43
+ server.once("error", () => resolve(false));
44
+ server.listen(port, () => server.close(() => resolve(true)));
45
+ });
46
+ }
47
+
48
+ /** initServer returns the reactor-api handle too; SwitchboardReactor does not
49
+ * type it. Spying on its dispose shows how often the api was drained. */
50
+ function apiOf(sb: object): { dispose: () => Promise<void> } {
51
+ const api: unknown = Reflect.get(sb, "api");
52
+ if (
53
+ typeof api !== "object" ||
54
+ api === null ||
55
+ typeof Reflect.get(api, "dispose") !== "function"
56
+ ) {
57
+ throw new Error("switchboard returned no api handle");
58
+ }
59
+ return api as { dispose: () => Promise<void> };
60
+ }
61
+
62
+ function stubLogger(): ILogger {
63
+ const logger = {
64
+ verbose: vi.fn(),
65
+ debug: vi.fn(),
66
+ info: vi.fn(),
67
+ warn: vi.fn(),
68
+ error: vi.fn(),
69
+ child: vi.fn(),
70
+ };
71
+ logger.child.mockReturnValue(logger);
72
+ return logger as unknown as ILogger;
73
+ }
74
+
75
+ describe("SwitchboardReactor.shutdown", () => {
76
+ let tempRoot: string;
77
+ let previousReactorDb: string | undefined;
78
+ let switchboard: Switchboard | undefined;
79
+ const signalsBefore = {
80
+ SIGINT: new Set<NodeJS.SignalsListener>(),
81
+ SIGTERM: new Set<NodeJS.SignalsListener>(),
82
+ };
83
+ const addedListeners = (signal: "SIGINT" | "SIGTERM") =>
84
+ (process.listeners(signal) as NodeJS.SignalsListener[]).filter(
85
+ (listener) => !signalsBefore[signal].has(listener),
86
+ );
87
+
88
+ beforeEach(async () => {
89
+ tempRoot = await mkdtemp(join(tmpdir(), "switchboard-shutdown-"));
90
+ previousReactorDb = process.env.PH_REACTOR_DATABASE_URL;
91
+ process.env.PH_REACTOR_DATABASE_URL = join(tempRoot, "reactor-storage");
92
+ for (const signal of ["SIGINT", "SIGTERM"] as const) {
93
+ signalsBefore[signal] = new Set(
94
+ process.listeners(signal) as NodeJS.SignalsListener[],
95
+ );
96
+ }
97
+ });
98
+
99
+ afterEach(async () => {
100
+ await switchboard?.shutdown().catch(() => undefined);
101
+ switchboard = undefined;
102
+ vi.restoreAllMocks();
103
+ // The owned reactor's withSignalHandlers() listeners outlive the test.
104
+ for (const signal of ["SIGINT", "SIGTERM"] as const) {
105
+ for (const listener of addedListeners(signal)) {
106
+ process.removeListener(signal, listener);
107
+ }
108
+ }
109
+ if (previousReactorDb === undefined) {
110
+ delete process.env.PH_REACTOR_DATABASE_URL;
111
+ } else {
112
+ process.env.PH_REACTOR_DATABASE_URL = previousReactorDb;
113
+ }
114
+ await rm(tempRoot, { recursive: true, force: true });
115
+ });
116
+
117
+ async function start(
118
+ reactor?: InProcessReactorClientModule,
119
+ ): Promise<Switchboard> {
120
+ switchboard = await bootSwitchboard(
121
+ {
122
+ server: { port: 0 },
123
+ storage: { readModel: { url: join(tempRoot, "read-model") } },
124
+ features: { workflows: false, mcp: false },
125
+ packages: { disableLocal: true },
126
+ identity: { keypairPath: join(tempRoot, "identity.json") },
127
+ },
128
+ { reactor, logger: stubLogger() },
129
+ );
130
+ return switchboard;
131
+ }
132
+
133
+ /**
134
+ * Spies on the reactor module the switchboard builds for itself, from the
135
+ * moment it is built (an aborted boot tears it down before returning).
136
+ */
137
+ function watchOwnedReactor() {
138
+ const realBuild = Object.getOwnPropertyDescriptor(
139
+ ReactorClientBuilder.prototype,
140
+ "buildModule",
141
+ )?.value as (
142
+ this: ReactorClientBuilder,
143
+ ) => Promise<InProcessReactorClientModule>;
144
+ const watched: {
145
+ kill?: MockInstance<() => unknown>;
146
+ destroy?: MockInstance<() => Promise<void>>;
147
+ } = {};
148
+ vi.spyOn(ReactorClientBuilder.prototype, "buildModule").mockImplementation(
149
+ async function (this: ReactorClientBuilder) {
150
+ const built = await realBuild.call(this);
151
+ if (!built.reactorModule) throw new Error("no reactor module built");
152
+ watched.kill = vi.spyOn(built.reactorModule.reactor, "kill");
153
+ watched.destroy = vi.spyOn(built.reactorModule.database, "destroy");
154
+ return built;
155
+ },
156
+ );
157
+ return watched;
158
+ }
159
+
160
+ /** Stubbed before boot: the signal handler binds process.exit when the
161
+ * reactor is built. */
162
+ function stubExit() {
163
+ const codes: Array<number | undefined> = [];
164
+ let resolveExit: (code: number | undefined) => void = () => undefined;
165
+ const exited = new Promise<number | undefined>((resolve) => {
166
+ resolveExit = resolve;
167
+ });
168
+ vi.spyOn(process, "exit").mockImplementation((code) => {
169
+ const value = code === undefined ? undefined : Number(code);
170
+ codes.push(value);
171
+ resolveExit(value);
172
+ return undefined as never;
173
+ });
174
+ return { codes, exited };
175
+ }
176
+
177
+ function raiseSigint(): void {
178
+ const sigint = addedListeners("SIGINT");
179
+ expect(sigint).toHaveLength(1);
180
+ sigint[0]!("SIGINT");
181
+ }
182
+
183
+ it("stops an owned reactor and frees the port once, however often it is called", async () => {
184
+ const reactor = watchOwnedReactor();
185
+ const exit = stubExit();
186
+
187
+ const sb = await start();
188
+ const dispose = vi.spyOn(apiOf(sb), "dispose");
189
+ expect(await portIsFree(sb.port)).toBe(false);
190
+
191
+ await Promise.all([sb.shutdown(), sb.shutdown()]);
192
+ await sb.shutdown();
193
+
194
+ expect(reactor.kill).toHaveBeenCalledTimes(1);
195
+ expect(dispose).toHaveBeenCalledTimes(1);
196
+ expect(reactor.destroy).toHaveBeenCalledTimes(1);
197
+ expect(await portIsFree(sb.port)).toBe(true);
198
+ expect(exit.codes).toEqual([]);
199
+
200
+ // A later SIGINT joins the finished teardown and only exits.
201
+ raiseSigint();
202
+ expect(await exit.exited).toBe(0);
203
+ expect(exit.codes).toEqual([0]);
204
+ expect(reactor.kill).toHaveBeenCalledTimes(1);
205
+ expect(dispose).toHaveBeenCalledTimes(1);
206
+ expect(reactor.destroy).toHaveBeenCalledTimes(1);
207
+ }, 60_000);
208
+
209
+ it("an aborted boot tears the owned reactor down once, through its shutdown", async () => {
210
+ const reactor = watchOwnedReactor();
211
+ const exit = stubExit();
212
+ const previousSource = process.env.RENOWN_SOURCE;
213
+ // No loaded package serves the renown read model: the boot aborts after
214
+ // the reactor and the api are up.
215
+ process.env.RENOWN_SOURCE = "self";
216
+ const port = await freePort();
217
+
218
+ try {
219
+ await expect(
220
+ bootSwitchboard(
221
+ {
222
+ server: { port: port, strictPort: true },
223
+ storage: { readModel: { url: join(tempRoot, "read-model") } },
224
+ features: { workflows: false, mcp: false },
225
+ packages: { disableLocal: true },
226
+ identity: { keypairPath: join(tempRoot, "identity.json") },
227
+ },
228
+ { logger: stubLogger() },
229
+ ),
230
+ ).rejects.toThrow(/no loaded package serves/);
231
+ } finally {
232
+ if (previousSource === undefined) {
233
+ delete process.env.RENOWN_SOURCE;
234
+ } else {
235
+ process.env.RENOWN_SOURCE = previousSource;
236
+ }
237
+ }
238
+
239
+ expect(reactor.kill).toHaveBeenCalledTimes(1);
240
+ expect(reactor.destroy).toHaveBeenCalledTimes(1);
241
+ expect(await portIsFree(port)).toBe(true);
242
+
243
+ raiseSigint();
244
+ expect(await exit.exited).toBe(0);
245
+ expect(reactor.kill).toHaveBeenCalledTimes(1);
246
+ expect(reactor.destroy).toHaveBeenCalledTimes(1);
247
+ }, 60_000);
248
+
249
+ it("drains the api once and leaves a caller-provided reactor running", async () => {
250
+ const database = new Kysely<Database>({
251
+ dialect: new PGliteDialect(new PGlite()),
252
+ });
253
+ const reactorBuilder = new ReactorBuilder().withKysely(database);
254
+ const clientBuilder = new ReactorClientBuilder().withReactorBuilder(
255
+ reactorBuilder,
256
+ );
257
+ applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, {
258
+ signalHandlers: false,
259
+ });
260
+ const caller = await clientBuilder.buildModule();
261
+ const callerModule = caller.reactorModule;
262
+ if (!callerModule) throw new Error("caller built no reactor module");
263
+
264
+ try {
265
+ const sb = await start(caller);
266
+ const kill = vi.spyOn(callerModule.reactor, "kill");
267
+ const dispose = vi.spyOn(apiOf(sb), "dispose");
268
+
269
+ await Promise.all([sb.shutdown(), sb.shutdown()]);
270
+
271
+ expect(dispose).toHaveBeenCalledTimes(1);
272
+ expect(kill).not.toHaveBeenCalled();
273
+ expect(await portIsFree(sb.port)).toBe(true);
274
+ } finally {
275
+ await callerModule.shutdown();
276
+ }
277
+ }, 60_000);
278
+ });
@@ -0,0 +1,94 @@
1
+ // Test-only v1 snapshot.bin writer over a loose on-disk tree.
2
+ import { promises as fs } from "node:fs";
3
+ import type { FileHandle } from "node:fs/promises";
4
+ import path from "node:path";
5
+
6
+ const MAGIC = new Uint8Array([0x50, 0x47, 0x4c, 0x41]);
7
+ const FORMAT_VERSION = 1;
8
+ const HEADER_SIZE = 12;
9
+ const ENTRY_PREFIX_SIZE = 9;
10
+ const DEFAULT_SKIP = ["snapshot.bin", "snapshot.bin.tmp"];
11
+
12
+ export interface SnapshotEntry {
13
+ type: 0 | 1;
14
+ mode: number;
15
+ relPath: string;
16
+ data?: Buffer;
17
+ }
18
+
19
+ export interface WriteSnapshotOptions {
20
+ /** Root-level names to leave out. Defaults to the snapshot files. */
21
+ skip?: string[];
22
+ }
23
+
24
+ export async function collectDiskEntries(
25
+ dataDir: string,
26
+ options: WriteSnapshotOptions = {},
27
+ ): Promise<SnapshotEntry[]> {
28
+ const skip = new Set(options.skip ?? DEFAULT_SKIP);
29
+ const entries: SnapshotEntry[] = [];
30
+ const walk = async (dir: string, rel: string) => {
31
+ const names = (await fs.readdir(dir)).sort();
32
+ for (const name of names) {
33
+ if (rel === "" && skip.has(name)) continue;
34
+ const full = path.join(dir, name);
35
+ const relPath = rel === "" ? name : `${rel}/${name}`;
36
+ const stat = await fs.lstat(full);
37
+ if (stat.isDirectory()) {
38
+ entries.push({ type: 0, mode: stat.mode & 0o7777, relPath });
39
+ await walk(full, relPath);
40
+ } else if (stat.isFile()) {
41
+ entries.push({
42
+ type: 1,
43
+ mode: stat.mode & 0o7777,
44
+ relPath,
45
+ data: await fs.readFile(full),
46
+ });
47
+ }
48
+ }
49
+ };
50
+ await walk(dataDir, "");
51
+ return entries;
52
+ }
53
+
54
+ export function encodeSnapshot(entries: SnapshotEntry[]): Buffer {
55
+ const encoder = new TextEncoder();
56
+ const parts: Buffer[] = [];
57
+ const header = Buffer.alloc(HEADER_SIZE);
58
+ header.set(MAGIC, 0);
59
+ header.writeUInt32LE(FORMAT_VERSION, 4);
60
+ header.writeUInt32LE(entries.length, 8);
61
+ parts.push(header);
62
+ for (const entry of entries) {
63
+ const pathBytes = encoder.encode(entry.relPath);
64
+ const dataLen = entry.data?.byteLength ?? 0;
65
+ const prefix = Buffer.alloc(ENTRY_PREFIX_SIZE + pathBytes.byteLength + 4);
66
+ prefix.writeUInt8(entry.type, 0);
67
+ prefix.writeUInt32LE(entry.mode, 1);
68
+ prefix.writeUInt32LE(pathBytes.byteLength, 5);
69
+ prefix.set(pathBytes, ENTRY_PREFIX_SIZE);
70
+ prefix.writeUInt32LE(dataLen, ENTRY_PREFIX_SIZE + pathBytes.byteLength);
71
+ parts.push(prefix);
72
+ if (entry.data && dataLen > 0) parts.push(entry.data);
73
+ }
74
+ return Buffer.concat(parts);
75
+ }
76
+
77
+ /** Serializes `dataDir` into `snapshotPath`. Returns the entry count and size. */
78
+ export async function writeSnapshotFromDir(
79
+ dataDir: string,
80
+ snapshotPath: string,
81
+ options: WriteSnapshotOptions = {},
82
+ ): Promise<{ entries: number; bytes: number }> {
83
+ const entries = await collectDiskEntries(dataDir, options);
84
+ const bytes = encodeSnapshot(entries);
85
+ let fh: FileHandle | undefined;
86
+ try {
87
+ fh = await fs.open(snapshotPath, "w");
88
+ await fh.writeFile(bytes);
89
+ await fh.sync();
90
+ } finally {
91
+ await fh?.close();
92
+ }
93
+ return { entries: entries.length, bytes: bytes.byteLength };
94
+ }
@@ -0,0 +1,65 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { afterEach, describe, expect, it } from "vitest";
5
+ import {
6
+ acquireStoreLocks,
7
+ releaseStoreLocks,
8
+ StoreInUseError,
9
+ } from "../src/store-lock.mjs";
10
+
11
+ const dirs: string[] = [];
12
+ function store(): string {
13
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "ph-store-lock-"));
14
+ dirs.push(root);
15
+ return path.join(root, "reactor-storage");
16
+ }
17
+ afterEach(() => {
18
+ releaseStoreLocks();
19
+ for (const d of dirs.splice(0))
20
+ fs.rmSync(d, { recursive: true, force: true });
21
+ });
22
+
23
+ const lockOf = (dir: string) => `${path.resolve(dir)}.lock`;
24
+ const lockPid = (dir: string) =>
25
+ (JSON.parse(fs.readFileSync(lockOf(dir), "utf8")) as { pid: number }).pid;
26
+ const claim = (dir: string, pid: number) =>
27
+ fs.writeFileSync(
28
+ lockOf(dir),
29
+ JSON.stringify({ pid, startedAt: "earlier", command: "ph run vetra" }),
30
+ );
31
+
32
+ describe("acquireStoreLocks", () => {
33
+ it("writes a sibling lock (never inside the data dir) and releases it", () => {
34
+ const dir = store();
35
+ acquireStoreLocks([dir]);
36
+ expect(lockPid(dir)).toBe(process.pid);
37
+ expect(fs.existsSync(dir)).toBe(false); // initdb still gets an empty dir
38
+ releaseStoreLocks();
39
+ expect(fs.existsSync(lockOf(dir))).toBe(false);
40
+ });
41
+
42
+ it("refuses a store held by another live process, naming it", () => {
43
+ const dir = store();
44
+ claim(dir, 4242);
45
+ expect(() => acquireStoreLocks([dir], (pid) => pid === 4242)).toThrow(
46
+ StoreInUseError,
47
+ );
48
+ expect(() => acquireStoreLocks([dir], (pid) => pid === 4242)).toThrow(
49
+ /pid 4242.*ph run vetra/,
50
+ );
51
+ });
52
+
53
+ it("takes over a stale lock from a dead (hard-killed) process", () => {
54
+ const dir = store();
55
+ claim(dir, 4242);
56
+ acquireStoreLocks([dir], () => false);
57
+ expect(lockPid(dir)).toBe(process.pid);
58
+ });
59
+
60
+ it("is re-entrant for the owning process (in-process restarts)", () => {
61
+ const dir = store();
62
+ acquireStoreLocks([dir]);
63
+ expect(() => acquireStoreLocks([dir])).not.toThrow();
64
+ });
65
+ });
@@ -0,0 +1,146 @@
1
+ import { signaturePolicyOf } from "@powerhousedao/shared/document-model";
2
+ import { mkdtemp, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import type { ILogger } from "document-model";
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
7
+ import type { SwitchboardConfigInput } from "../src/config/schema.js";
8
+ import { startSwitchboard, type SwitchboardReactor } from "../src/server.mjs";
9
+
10
+ type Info = ReturnType<typeof vi.fn>;
11
+
12
+ function stubLogger(): ILogger & { info: Info } {
13
+ const logger = {
14
+ verbose: vi.fn(),
15
+ debug: vi.fn(),
16
+ info: vi.fn(),
17
+ warn: vi.fn(),
18
+ error: vi.fn(),
19
+ child: vi.fn(),
20
+ };
21
+ logger.child.mockReturnValue(logger);
22
+ return logger as unknown as ILogger & { info: Info };
23
+ }
24
+
25
+ function messages(logger: { info: Info }): string[] {
26
+ return logger.info.mock.calls.map(([message]) => String(message));
27
+ }
28
+
29
+ /** The `[policy enforcement, caller identity]` reactor-api logged, if any. */
30
+ function authSetup(logger: { info: Info }): unknown[] | undefined {
31
+ return logger.info.mock.calls
32
+ .find(([message]) =>
33
+ String(message).startsWith("Setting up Auth middleware"),
34
+ )
35
+ ?.slice(1);
36
+ }
37
+
38
+ async function throttled(port: number): Promise<boolean> {
39
+ const response = await fetch(`http://localhost:${port}/graphql/inspection`, {
40
+ method: "POST",
41
+ headers: { "content-type": "application/json" },
42
+ body: JSON.stringify({
43
+ query:
44
+ '{ inspection { validateDocument(documentId: "missing") { documentId } } }',
45
+ }),
46
+ });
47
+ const body = (await response.json()) as {
48
+ errors?: { extensions?: { code?: string } }[];
49
+ };
50
+ return (body.errors ?? []).some(
51
+ (error) => error.extensions?.code === "TOO_MANY_REQUESTS",
52
+ );
53
+ }
54
+
55
+ // Env a direct caller does not map: nothing inside the server may read it.
56
+ const STRAY_ENV = { AUTH_ENABLED: "true", ADMINS: "0xenv" };
57
+
58
+ describe("two switchboards in one process", () => {
59
+ let root: string;
60
+ const started: SwitchboardReactor[] = [];
61
+ const previous = new Map<string, string | undefined>();
62
+
63
+ beforeEach(async () => {
64
+ root = await mkdtemp(join(tmpdir(), "switchboard-two-"));
65
+ for (const [name, value] of Object.entries(STRAY_ENV)) {
66
+ previous.set(name, process.env[name]);
67
+ process.env[name] = value;
68
+ }
69
+ });
70
+
71
+ afterEach(async () => {
72
+ for (const handle of started.splice(0)) await handle.shutdown();
73
+ for (const [name, value] of previous) {
74
+ if (value === undefined) delete process.env[name];
75
+ else process.env[name] = value;
76
+ }
77
+ previous.clear();
78
+ await rm(root, { recursive: true, force: true });
79
+ });
80
+
81
+ async function boot(name: string, config: SwitchboardConfigInput) {
82
+ const logger = stubLogger();
83
+ const handle = await startSwitchboard(
84
+ {
85
+ server: { port: 0 },
86
+ storage: { inMemory: true, userDataDir: join(root, name) },
87
+ features: { workflows: false, mcp: false },
88
+ packages: { disableLocal: true },
89
+ identity: { keypairPath: join(root, name, "identity.json") },
90
+ ...config,
91
+ },
92
+ { logger, signalHandlers: false, fatalErrorShutdown: false },
93
+ );
94
+ started.push(handle);
95
+ return { handle, logger };
96
+ }
97
+
98
+ it("runs each on its own config, not on the process env", async () => {
99
+ const a = await boot("a", {
100
+ protocol: {
101
+ featureFlags: { documentDecisions: true },
102
+ createSignaturePolicy: "legacy",
103
+ },
104
+ auth: { resolveIdentity: true },
105
+ inspection: { callsPerMinute: 1 },
106
+ });
107
+ const b = await boot("b", {
108
+ protocol: { featureFlags: { documentDecisions: false } },
109
+ inspection: { callsPerMinute: 3 },
110
+ });
111
+
112
+ expect(a.handle.port).toBeGreaterThan(0);
113
+ expect(b.handle.port).toBeGreaterThan(0);
114
+ expect(a.handle.port).not.toBe(b.handle.port);
115
+
116
+ const flagsOn = "Reactor feature flags enabled: documentDecisions";
117
+ expect(messages(a.logger)).toContain(flagsOn);
118
+ expect(messages(b.logger)).not.toContain(flagsOn);
119
+
120
+ // AUTH_ENABLED in process.env reaches neither.
121
+ expect(authSetup(a.logger)).toEqual([false, true]);
122
+ expect(authSetup(b.logger)).toBeUndefined();
123
+
124
+ const onA = await a.handle.reactor.createEmpty("powerhouse/document-model");
125
+ const onB = await b.handle.reactor.createEmpty("powerhouse/document-model");
126
+ expect(signaturePolicyOf(onA.header)).toBe("legacy");
127
+ expect(signaturePolicyOf(onB.header)).toBe("v2-required");
128
+ const exists = (handle: SwitchboardReactor, id: string) =>
129
+ handle.reactor.get(id).then(
130
+ () => true,
131
+ () => false,
132
+ );
133
+ expect(await exists(a.handle, onA.header.id)).toBe(true);
134
+ expect(await exists(b.handle, onA.header.id)).toBe(false);
135
+ expect(await exists(a.handle, onB.header.id)).toBe(false);
136
+
137
+ expect(a.handle.inspectionEnabled).toBe(true);
138
+ expect(b.handle.inspectionEnabled).toBe(true);
139
+ expect(await throttled(a.handle.port)).toBe(false);
140
+ expect(await throttled(a.handle.port)).toBe(true);
141
+ for (let call = 0; call < 3; call++) {
142
+ expect(await throttled(b.handle.port)).toBe(false);
143
+ }
144
+ expect(await throttled(b.handle.port)).toBe(true);
145
+ }, 120_000);
146
+ });
@@ -0,0 +1,72 @@
1
+ import { UnsupportedStoredProtocolError } from "@powerhousedao/reactor";
2
+ import { describe, expect, it } from "vitest";
3
+ import {
4
+ StoredDocumentsRefusedError,
5
+ resolveUnsupportedStoredDocuments,
6
+ } from "../src/unsupported-stored-documents.mjs";
7
+
8
+ describe("resolveUnsupportedStoredDocuments", () => {
9
+ it("refuses by default", () => {
10
+ expect(resolveUnsupportedStoredDocuments(undefined, {})).toBe("refuse");
11
+ expect(
12
+ resolveUnsupportedStoredDocuments(undefined, {
13
+ REACTOR_UNSUPPORTED_STORED_DOCUMENTS: " ",
14
+ }),
15
+ ).toBe("refuse");
16
+ });
17
+
18
+ it("reads REACTOR_UNSUPPORTED_STORED_DOCUMENTS", () => {
19
+ expect(
20
+ resolveUnsupportedStoredDocuments(undefined, {
21
+ REACTOR_UNSUPPORTED_STORED_DOCUMENTS: " read-only ",
22
+ }),
23
+ ).toBe("read-only");
24
+ expect(
25
+ resolveUnsupportedStoredDocuments(undefined, {
26
+ REACTOR_UNSUPPORTED_STORED_DOCUMENTS: "refuse",
27
+ }),
28
+ ).toBe("refuse");
29
+ });
30
+
31
+ it("lets the option win over the env var", () => {
32
+ expect(
33
+ resolveUnsupportedStoredDocuments("refuse", {
34
+ REACTOR_UNSUPPORTED_STORED_DOCUMENTS: "read-only",
35
+ }),
36
+ ).toBe("refuse");
37
+ });
38
+
39
+ it("refuses an unknown value", () => {
40
+ expect(() =>
41
+ resolveUnsupportedStoredDocuments(undefined, {
42
+ REACTOR_UNSUPPORTED_STORED_DOCUMENTS: "readonly",
43
+ }),
44
+ ).toThrow(
45
+ 'REACTOR_UNSUPPORTED_STORED_DOCUMENTS must be "refuse" or "read-only", got "readonly"',
46
+ );
47
+ });
48
+ });
49
+
50
+ describe("StoredDocumentsRefusedError", () => {
51
+ it("names the versions, the count and both ways forward", () => {
52
+ const cause = new UnsupportedStoredProtocolError(
53
+ [
54
+ { protocol: "base-reducer", version: 3 },
55
+ { protocol: "base-reducer", version: 7 },
56
+ ],
57
+ 4,
58
+ );
59
+
60
+ const error = new StoredDocumentsRefusedError(cause);
61
+
62
+ expect(error.message).toBe(
63
+ "Refusing to start: 4 stored document(s) require base-reducer 3, base-reducer 7, which this switchboard does not run. " +
64
+ "Either start a switchboard build that runs base-reducer 3, base-reducer 7, or set REACTOR_UNSUPPORTED_STORED_DOCUMENTS=read-only to start with those documents read-only.",
65
+ );
66
+ expect(error.documents).toBe(4);
67
+ expect(error.versions).toBe(cause.versions);
68
+ expect(error.cause).toBe(cause);
69
+ expect(StoredDocumentsRefusedError.isError(error)).toBe(true);
70
+ expect(StoredDocumentsRefusedError.isError(cause)).toBe(false);
71
+ });
72
+ });
@@ -1,9 +1,12 @@
1
1
  import type { ILogger } from "document-model";
2
- import { existsSync } from "node:fs";
2
+ import { existsSync, mkdtempSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
3
5
  import { describe, expect, it, vi } from "vitest";
4
6
  import {
5
7
  autoWorkerCount,
6
8
  buildWorkerDbConfig,
9
+ keepImportableSources,
7
10
  resolveHostPoolSize,
8
11
  resolveWorkerModelSources,
9
12
  resolveWorkerPoolOptions,
@@ -264,3 +267,26 @@ describe("resolveWorkerModelSources", () => {
264
267
  expect(logger.warn).toHaveBeenCalledTimes(1);
265
268
  });
266
269
  });
270
+
271
+ describe("keepImportableSources", () => {
272
+ it("keeps sources that export a model and drops one that throws or has none", async () => {
273
+ const dir = mkdtempSync(path.join(tmpdir(), "ph-model-sources-"));
274
+ const good = path.join(dir, "good.mjs");
275
+ const broken = path.join(dir, "broken.mjs");
276
+ const empty = path.join(dir, "empty.mjs");
277
+ writeFileSync(
278
+ good,
279
+ 'export const Model = { reducer: () => ({}), documentModel: { global: { id: "test/model" } } };',
280
+ );
281
+ writeFileSync(broken, 'throw new Error("stale dist");');
282
+ // What `ph init` builds for a project with no models yet.
283
+ writeFileSync(empty, "export {};");
284
+
285
+ const kept = await keepImportableSources(
286
+ [{ filePath: broken }, { filePath: good }, { filePath: empty }],
287
+ stubLogger(),
288
+ );
289
+
290
+ expect(kept).toEqual([{ filePath: good }]);
291
+ });
292
+ });