@powerhousedao/switchboard 6.2.3-dev.10 → 6.2.3-dev.101

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 (310) hide show
  1. package/.tsbuild/test/ai-gateway.test.d.ts +2 -0
  2. package/.tsbuild/test/ai-gateway.test.d.ts.map +1 -0
  3. package/.tsbuild/test/attachments/byte-grants.test.d.ts +2 -0
  4. package/.tsbuild/test/attachments/byte-grants.test.d.ts.map +1 -0
  5. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts +2 -0
  6. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts.map +1 -0
  7. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts +2 -0
  8. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts.map +1 -0
  9. package/.tsbuild/test/attachments/url-signer.test.d.ts +2 -0
  10. package/.tsbuild/test/attachments/url-signer.test.d.ts.map +1 -0
  11. package/.tsbuild/test/boot-auth-config.test.d.ts +2 -0
  12. package/.tsbuild/test/boot-auth-config.test.d.ts.map +1 -0
  13. package/.tsbuild/test/boot-create-signature-policy.test.d.ts +2 -0
  14. package/.tsbuild/test/boot-create-signature-policy.test.d.ts.map +1 -0
  15. package/.tsbuild/test/boot-desktop-auth.test.d.ts +2 -0
  16. package/.tsbuild/test/boot-desktop-auth.test.d.ts.map +1 -0
  17. package/.tsbuild/test/boot-env-isolation.test.d.ts +2 -0
  18. package/.tsbuild/test/boot-env-isolation.test.d.ts.map +1 -0
  19. package/.tsbuild/test/boot-helpers.d.ts +5 -0
  20. package/.tsbuild/test/boot-helpers.d.ts.map +1 -0
  21. package/.tsbuild/test/boot-inspection-enabled.test.d.ts +2 -0
  22. package/.tsbuild/test/boot-inspection-enabled.test.d.ts.map +1 -0
  23. package/.tsbuild/test/boot-mcp-auth.test.d.ts +2 -0
  24. package/.tsbuild/test/boot-mcp-auth.test.d.ts.map +1 -0
  25. package/.tsbuild/test/boot-mcp-enabled.test.d.ts +2 -0
  26. package/.tsbuild/test/boot-mcp-enabled.test.d.ts.map +1 -0
  27. package/.tsbuild/test/boot-port-zero.test.d.ts +2 -0
  28. package/.tsbuild/test/boot-port-zero.test.d.ts.map +1 -0
  29. package/.tsbuild/test/boot-preconditions.test.d.ts +2 -0
  30. package/.tsbuild/test/boot-preconditions.test.d.ts.map +1 -0
  31. package/.tsbuild/test/boot-privacy.test.d.ts +2 -0
  32. package/.tsbuild/test/boot-privacy.test.d.ts.map +1 -0
  33. package/.tsbuild/test/boot-ready-drives.test.d.ts +2 -0
  34. package/.tsbuild/test/boot-ready-drives.test.d.ts.map +1 -0
  35. package/.tsbuild/test/boot-undo-v3-flag.test.d.ts +2 -0
  36. package/.tsbuild/test/boot-undo-v3-flag.test.d.ts.map +1 -0
  37. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts +2 -0
  38. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts.map +1 -0
  39. package/.tsbuild/test/boot-without-renown.test.d.ts +2 -0
  40. package/.tsbuild/test/boot-without-renown.test.d.ts.map +1 -0
  41. package/.tsbuild/test/boot-without-require-signatures.test.d.ts +2 -0
  42. package/.tsbuild/test/boot-without-require-signatures.test.d.ts.map +1 -0
  43. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts +2 -0
  44. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts.map +1 -0
  45. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts +2 -0
  46. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts.map +1 -0
  47. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts +2 -0
  48. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts.map +1 -0
  49. package/.tsbuild/test/builder-defaults.test.d.ts +2 -0
  50. package/.tsbuild/test/builder-defaults.test.d.ts.map +1 -0
  51. package/.tsbuild/test/config-from-env.test.d.ts +2 -0
  52. package/.tsbuild/test/config-from-env.test.d.ts.map +1 -0
  53. package/.tsbuild/test/config-merge.test.d.ts +2 -0
  54. package/.tsbuild/test/config-merge.test.d.ts.map +1 -0
  55. package/.tsbuild/test/config-schema.test.d.ts +2 -0
  56. package/.tsbuild/test/config-schema.test.d.ts.map +1 -0
  57. package/.tsbuild/test/create-signature-policy.test.d.ts +2 -0
  58. package/.tsbuild/test/create-signature-policy.test.d.ts.map +1 -0
  59. package/.tsbuild/test/default-drive-protocol-versions.test.d.ts +2 -0
  60. package/.tsbuild/test/default-drive-protocol-versions.test.d.ts.map +1 -0
  61. package/.tsbuild/test/default-drive-slug.test.d.ts +2 -0
  62. package/.tsbuild/test/default-drive-slug.test.d.ts.map +1 -0
  63. package/.tsbuild/test/delegated-publish.test.d.ts +2 -0
  64. package/.tsbuild/test/delegated-publish.test.d.ts.map +1 -0
  65. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts +2 -0
  66. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts.map +1 -0
  67. package/.tsbuild/test/fatal-shutdown.test.d.ts +2 -0
  68. package/.tsbuild/test/fatal-shutdown.test.d.ts.map +1 -0
  69. package/.tsbuild/test/inspection-throttle.test.d.ts +2 -0
  70. package/.tsbuild/test/inspection-throttle.test.d.ts.map +1 -0
  71. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts +2 -0
  72. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts.map +1 -0
  73. package/.tsbuild/test/observability-signals.test.d.ts +2 -0
  74. package/.tsbuild/test/observability-signals.test.d.ts.map +1 -0
  75. package/.tsbuild/test/permissions-backfill.test.d.ts +2 -0
  76. package/.tsbuild/test/permissions-backfill.test.d.ts.map +1 -0
  77. package/.tsbuild/test/pglite-preflight.test.d.ts +2 -0
  78. package/.tsbuild/test/pglite-preflight.test.d.ts.map +1 -0
  79. package/.tsbuild/test/pglite-storage-dirs.test.d.ts +2 -0
  80. package/.tsbuild/test/pglite-storage-dirs.test.d.ts.map +1 -0
  81. package/.tsbuild/test/pglite-store.test.d.ts +2 -0
  82. package/.tsbuild/test/pglite-store.test.d.ts.map +1 -0
  83. package/.tsbuild/test/plugin-config-schemas.test.d.ts +2 -0
  84. package/.tsbuild/test/plugin-config-schemas.test.d.ts.map +1 -0
  85. package/.tsbuild/test/plugin-presence.test.d.ts +2 -0
  86. package/.tsbuild/test/plugin-presence.test.d.ts.map +1 -0
  87. package/.tsbuild/test/port-probe.test.d.ts +2 -0
  88. package/.tsbuild/test/port-probe.test.d.ts.map +1 -0
  89. package/.tsbuild/test/processor-timing-log.test.d.ts +2 -0
  90. package/.tsbuild/test/processor-timing-log.test.d.ts.map +1 -0
  91. package/.tsbuild/test/renown-storage-path.test.d.ts +2 -0
  92. package/.tsbuild/test/renown-storage-path.test.d.ts.map +1 -0
  93. package/.tsbuild/test/renown-trust-policy.test.d.ts +2 -0
  94. package/.tsbuild/test/renown-trust-policy.test.d.ts.map +1 -0
  95. package/.tsbuild/test/served-schemas.test.d.ts +2 -0
  96. package/.tsbuild/test/served-schemas.test.d.ts.map +1 -0
  97. package/.tsbuild/test/shutdown.test.d.ts +2 -0
  98. package/.tsbuild/test/shutdown.test.d.ts.map +1 -0
  99. package/.tsbuild/test/snapshot-writer.d.ts +18 -0
  100. package/.tsbuild/test/snapshot-writer.d.ts.map +1 -0
  101. package/.tsbuild/test/store-lock.test.d.ts +2 -0
  102. package/.tsbuild/test/store-lock.test.d.ts.map +1 -0
  103. package/.tsbuild/test/two-switchboards.test.d.ts +2 -0
  104. package/.tsbuild/test/two-switchboards.test.d.ts.map +1 -0
  105. package/.tsbuild/test/unsupported-stored-documents.test.d.ts +2 -0
  106. package/.tsbuild/test/unsupported-stored-documents.test.d.ts.map +1 -0
  107. package/.tsbuild/test/workflow/harness.d.ts +56 -0
  108. package/.tsbuild/test/workflow/harness.d.ts.map +1 -0
  109. package/.tsbuild/test/workflow/oauth-apps-config.test.d.ts +2 -0
  110. package/.tsbuild/test/workflow/oauth-apps-config.test.d.ts.map +1 -0
  111. package/.tsbuild/test/workflow/oauth.test.d.ts +2 -0
  112. package/.tsbuild/test/workflow/oauth.test.d.ts.map +1 -0
  113. package/.tsbuild/test/workflow/resolvers.test.d.ts +2 -0
  114. package/.tsbuild/test/workflow/resolvers.test.d.ts.map +1 -0
  115. package/.tsbuild/test/workflow/runtime-host.test.d.ts +2 -0
  116. package/.tsbuild/test/workflow/runtime-host.test.d.ts.map +1 -0
  117. package/.tsbuild/test/workflow/waitpoint-routes.test.d.ts +2 -0
  118. package/.tsbuild/test/workflow/waitpoint-routes.test.d.ts.map +1 -0
  119. package/.tsbuild/test/workflow/waitpoint-runtime.test.d.ts +2 -0
  120. package/.tsbuild/test/workflow/waitpoint-runtime.test.d.ts.map +1 -0
  121. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts +2 -0
  122. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts.map +1 -0
  123. package/.tsbuild/test/workflow/webhook-signed.test.d.ts +2 -0
  124. package/.tsbuild/test/workflow/webhook-signed.test.d.ts.map +1 -0
  125. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts +2 -0
  126. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts.map +1 -0
  127. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts +2 -0
  128. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts.map +1 -0
  129. package/.tsbuild/test/workflow-reactor-access.test.d.ts +2 -0
  130. package/.tsbuild/test/workflow-reactor-access.test.d.ts.map +1 -0
  131. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts +2 -0
  132. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts.map +1 -0
  133. package/.tsbuild/test/workflow-read-gate.test.d.ts +2 -0
  134. package/.tsbuild/test/workflow-read-gate.test.d.ts.map +1 -0
  135. package/.tsbuild/test/workflow-runtime.test.d.ts +2 -0
  136. package/.tsbuild/test/workflow-runtime.test.d.ts.map +1 -0
  137. package/.tsbuild/test/workflows-plugin-config.test.d.ts +2 -0
  138. package/.tsbuild/test/workflows-plugin-config.test.d.ts.map +1 -0
  139. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  140. package/.tsbuild/tsdown.config.d.ts.map +1 -1
  141. package/.tsbuild/vitest.config.d.ts.map +1 -1
  142. package/Auth.md +144 -2
  143. package/CHANGELOG.md +1299 -0
  144. package/README.md +102 -22
  145. package/dist/boot.d.mts +46 -0
  146. package/dist/boot.d.mts.map +1 -0
  147. package/dist/boot.mjs +67 -0
  148. package/dist/boot.mjs.map +1 -0
  149. package/dist/config/from-env.d.mts +15 -0
  150. package/dist/config/from-env.d.mts.map +1 -0
  151. package/dist/config/from-env.mjs +4 -0
  152. package/dist/config/schema.d.mts +3 -0
  153. package/dist/config/schema.mjs +4 -0
  154. package/dist/from-env-FH4fPeIE.mjs +481 -0
  155. package/dist/from-env-FH4fPeIE.mjs.map +1 -0
  156. package/dist/index.d.mts +2 -1
  157. package/dist/index.mjs +84 -84
  158. package/dist/index.mjs.map +1 -1
  159. package/dist/install-packages.d.mts +2 -1
  160. package/dist/install-packages.mjs +2 -2
  161. package/dist/install-packages.mjs.map +1 -1
  162. package/dist/mcp-SsBK14Jm.mjs +32 -0
  163. package/dist/mcp-SsBK14Jm.mjs.map +1 -0
  164. package/dist/migrate.d.mts +2 -1
  165. package/dist/migrate.mjs +7 -5
  166. package/dist/migrate.mjs.map +1 -1
  167. package/dist/plugin-host-CK9_tVak.d.mts +46 -0
  168. package/dist/plugin-host-CK9_tVak.d.mts.map +1 -0
  169. package/dist/plugins/ai.d.mts +37 -0
  170. package/dist/plugins/ai.d.mts.map +1 -0
  171. package/dist/plugins/ai.mjs +400 -0
  172. package/dist/plugins/ai.mjs.map +1 -0
  173. package/dist/plugins/attachments.d.mts +33 -0
  174. package/dist/plugins/attachments.d.mts.map +1 -0
  175. package/dist/plugins/attachments.mjs +4 -0
  176. package/dist/plugins/mcp.d.mts +31 -0
  177. package/dist/plugins/mcp.d.mts.map +1 -0
  178. package/dist/plugins/mcp.mjs +4 -0
  179. package/dist/plugins/privacy.d.mts +22 -0
  180. package/dist/plugins/privacy.d.mts.map +1 -0
  181. package/dist/plugins/privacy.mjs +4 -0
  182. package/dist/plugins/workflows.d.mts +79 -0
  183. package/dist/plugins/workflows.d.mts.map +1 -0
  184. package/dist/plugins/workflows.mjs +4 -0
  185. package/dist/postgres-url-DTDhBjXX.mjs +11 -0
  186. package/dist/postgres-url-DTDhBjXX.mjs.map +1 -0
  187. package/dist/privacy-BO8Q25xI.mjs +44 -0
  188. package/dist/privacy-BO8Q25xI.mjs.map +1 -0
  189. package/dist/privacy-DxIJGH4P.mjs +91 -0
  190. package/dist/privacy-DxIJGH4P.mjs.map +1 -0
  191. package/dist/renown-layers-DmbWLt46.mjs +42 -0
  192. package/dist/renown-layers-DmbWLt46.mjs.map +1 -0
  193. package/dist/schema-CsY8bjsu.mjs +329 -0
  194. package/dist/schema-CsY8bjsu.mjs.map +1 -0
  195. package/dist/schema-MAUTnmj1.d.mts +251 -0
  196. package/dist/schema-MAUTnmj1.d.mts.map +1 -0
  197. package/dist/server-CirQ9hyu.mjs +2732 -0
  198. package/dist/server-CirQ9hyu.mjs.map +1 -0
  199. package/dist/server.d.mts +129 -189
  200. package/dist/server.d.mts.map +1 -1
  201. package/dist/server.mjs +5 -5
  202. package/dist/types-CidZdkhU.d.mts +314 -0
  203. package/dist/types-CidZdkhU.d.mts.map +1 -0
  204. package/dist/utils-Cm0TE6dP.mjs +148 -0
  205. package/dist/utils-Cm0TE6dP.mjs.map +1 -0
  206. package/dist/utils.d.mts +30 -5
  207. package/dist/utils.d.mts.map +1 -1
  208. package/dist/utils.mjs +5 -4
  209. package/dist/worker-pool-gyxJnCxA.mjs +304 -0
  210. package/dist/worker-pool-gyxJnCxA.mjs.map +1 -0
  211. package/dist/workflow-runtime-CF5pc8mt.d.mts +33 -0
  212. package/dist/workflow-runtime-CF5pc8mt.d.mts.map +1 -0
  213. package/dist/workflows-C9BQlyT0.mjs +1943 -0
  214. package/dist/workflows-C9BQlyT0.mjs.map +1 -0
  215. package/package.json +85 -24
  216. package/scripts/install-packages.sh +0 -0
  217. package/test/ai-gateway.test.ts +612 -0
  218. package/test/attachment-reference-read-model.test.ts +28 -20
  219. package/test/attachments/auth.test.ts +85 -0
  220. package/test/attachments/byte-grants.test.ts +290 -0
  221. package/test/attachments/byte-routes-read-gate.integration.test.ts +314 -0
  222. package/test/attachments/download-target.test.ts +211 -32
  223. package/test/attachments/index.test.ts +47 -4
  224. package/test/attachments/reserve-metadata-parity.test.ts +96 -0
  225. package/test/attachments/routes-integration.test.ts +60 -4
  226. package/test/attachments/routes.test.ts +297 -35
  227. package/test/attachments/service-config.test.ts +41 -19
  228. package/test/attachments/url-signer.test.ts +105 -0
  229. package/test/boot-auth-config.test.ts +109 -0
  230. package/test/boot-create-signature-policy.test.ts +110 -0
  231. package/test/boot-desktop-auth.test.ts +278 -0
  232. package/test/boot-env-isolation.test.ts +26 -0
  233. package/test/boot-helpers.ts +19 -0
  234. package/test/boot-inspection-enabled.test.ts +140 -0
  235. package/test/boot-mcp-auth.test.ts +449 -0
  236. package/test/boot-mcp-enabled.test.ts +119 -0
  237. package/test/boot-port-zero.test.ts +101 -0
  238. package/test/boot-preconditions.test.ts +213 -0
  239. package/test/boot-privacy.test.ts +232 -0
  240. package/test/boot-ready-drives.test.ts +141 -0
  241. package/test/boot-undo-v3-flag.test.ts +120 -0
  242. package/test/boot-unsupported-stored-documents.test.ts +214 -0
  243. package/test/boot-without-renown.test.ts +83 -0
  244. package/test/boot-without-require-signatures.test.ts +76 -0
  245. package/test/boot-worker-trust-policy.test.ts +91 -0
  246. package/test/boot-workflow-singleton-conflict.test.ts +109 -0
  247. package/test/boot-workflow-singleton-retry.test.ts +122 -0
  248. package/test/builder-defaults.test.ts +80 -0
  249. package/test/config-from-env.test.ts +963 -0
  250. package/test/config-merge.test.ts +248 -0
  251. package/test/config-schema.test.ts +167 -0
  252. package/test/create-signature-policy.test.ts +69 -0
  253. package/test/default-drive-protocol-versions.test.ts +79 -0
  254. package/test/default-drive-slug.test.ts +265 -0
  255. package/test/delegated-publish.test.ts +435 -0
  256. package/test/durable-node-fs-pg16.test.ts +80 -0
  257. package/test/fatal-shutdown.test.ts +205 -0
  258. package/test/goldens/packages.graphql +797 -0
  259. package/test/goldens/privacy.graphql +853 -0
  260. package/test/goldens/reactor-drive-nodes.graphql +827 -0
  261. package/test/goldens/resolvers.json +327 -0
  262. package/test/goldens/supergraph.graphql +5918 -0
  263. package/test/goldens/workflow-runtime.graphql +1548 -0
  264. package/test/inspection-throttle.test.ts +23 -0
  265. package/test/keyframe-reclaim-store.test.ts +156 -0
  266. package/test/observability-signals.test.ts +131 -0
  267. package/test/permissions-backfill.test.ts +486 -0
  268. package/test/pglite-dialect.test.ts +237 -2
  269. package/test/pglite-preflight.test.ts +313 -0
  270. package/test/pglite-storage-dirs.test.ts +113 -0
  271. package/test/pglite-store.test.ts +441 -0
  272. package/test/pglite-version.test.ts +9 -1
  273. package/test/plugin-config-schemas.test.ts +83 -0
  274. package/test/plugin-presence.test.ts +262 -0
  275. package/test/port-probe.test.ts +45 -0
  276. package/test/processor-timing-log.test.ts +109 -0
  277. package/test/reactor-feature-flags.test.ts +20 -0
  278. package/test/redact-webhook-path.test.ts +9 -0
  279. package/test/renown-storage-path.test.ts +40 -0
  280. package/test/renown-trust-policy.test.ts +313 -0
  281. package/test/served-schemas.test.ts +134 -0
  282. package/test/shutdown.test.ts +278 -0
  283. package/test/snapshot-writer.ts +94 -0
  284. package/test/store-lock.test.ts +65 -0
  285. package/test/two-switchboards.test.ts +146 -0
  286. package/test/unsupported-stored-documents.test.ts +72 -0
  287. package/test/worker-pool.test.ts +27 -1
  288. package/test/workflow/harness.ts +289 -0
  289. package/test/workflow/oauth-apps-config.test.ts +66 -0
  290. package/test/workflow/oauth.test.ts +286 -0
  291. package/test/workflow/resolvers.test.ts +488 -0
  292. package/test/workflow/runtime-host.test.ts +19 -0
  293. package/test/workflow/waitpoint-routes.test.ts +306 -0
  294. package/test/workflow/waitpoint-runtime.test.ts +204 -0
  295. package/test/workflow/webhook-dedupe.test.ts +295 -0
  296. package/test/workflow/webhook-signed.test.ts +509 -0
  297. package/test/workflow/webhook-trigger-test.test.ts +82 -0
  298. package/test/workflow/webhook-unsigned.test.ts +345 -0
  299. package/test/workflow-reactor-access.test.ts +384 -0
  300. package/test/workflow-reactor-enforcement.test.ts +808 -0
  301. package/test/workflow-read-gate.test.ts +213 -0
  302. package/test/workflow-runtime.test.ts +1254 -0
  303. package/test/workflows-plugin-config.test.ts +77 -0
  304. package/tsconfig.json +11 -2
  305. package/tsdown.config.ts +13 -1
  306. package/vitest.config.ts +66 -1
  307. package/dist/server-CiKkVE6g.mjs +0 -1555
  308. package/dist/server-CiKkVE6g.mjs.map +0 -1
  309. package/dist/utils-Baw7rThP.mjs +0 -80
  310. package/dist/utils-Baw7rThP.mjs.map +0 -1
@@ -0,0 +1,2732 @@
1
+
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4384c5e3-87ee-52b5-bdec-eaf98e7a2b57")}catch(e){}}();
3
+ import { a as loadNodeFsClass, c as openForVerify, d as ATTACHMENT_URL_SIGNING_SECRET_ENV, f as resolveAttachmentUrlSigning, i as isSupportedMajor, l as pgliteModuleSpec, n as StoredDocumentsRefusedError, o as loadPGliteModule, r as resolveUnsupportedStoredDocuments, s as loadPgDump, t as switchboardConfigFromEnv, u as readPgVersionFile } from "./from-env-FH4fPeIE.mjs";
4
+ import { a as resolveWorkerModelSources, l as resolveProjectionWorkerOptions, n as keepImportableSources, o as resolveWorkerPoolOptions, p as workerPoolIssues, s as assertProjectionWorkerSupported, t as buildWorkerDbConfig } from "./worker-pool-gyxJnCxA.mjs";
5
+ import { t as isPostgresUrl } from "./postgres-url-DTDhBjXX.mjs";
6
+ import { n as resolvePrivacy, r as startPrivacy } from "./privacy-DxIJGH4P.mjs";
7
+ import { i as switchboardConfigSchema, o as mergeSwitchboardConfig } from "./schema-CsY8bjsu.mjs";
8
+ import { _ as triggerFatalShutdown, a as workflowsPlugin, c as WORKFLOW_TELEMETRY_SCOPE, d as isWorkflowSingletonConflict, f as modelManifestSource, g as raiseSigterm, h as installFatalErrorShutdown, l as assertWorkflowPackageLoadable, m as workflowSingletonLossHandler, p as retryWorkflowSingleton, s as WORKFLOW_PACKAGE_NAME, u as composeWorkflowRuntime } from "./workflows-C9BQlyT0.mjs";
9
+ import { t as privacyPlugin } from "./privacy-BO8Q25xI.mjs";
10
+ import { t as mcpPlugin } from "./mcp-SsBK14Jm.mjs";
11
+ import { n as reactorFeatureFlagsOf, t as renownLayers } from "./renown-layers-DmbWLt46.mjs";
12
+ import { r as ensureDrive } from "./utils-Cm0TE6dP.mjs";
13
+ import { createRequire, register } from "node:module";
14
+ import { metrics, trace } from "@opentelemetry/api";
15
+ import { ReactorInstrumentation } from "@powerhousedao/opentelemetry-instrumentation-reactor";
16
+ import { childLogger, setLogLevel } from "document-model";
17
+ import { getConfig } from "@powerhousedao/config/node";
18
+ import { CatchUpPriority, ChannelScheme, DriveCollectionId, EventBus, HardenedPGliteDialect, IN_MEMORY_PGLITE_STORAGE_FACTS, MemoryTelemetry, PGLITE_PATH_STORAGE_FACTS, POSTGRES_STORAGE_FACTS, ProcessorTimingSettings, REACTOR_SCHEMA, ReactorBuilder, ReactorClientBuilder, UnsupportedStoredProtocolError, computeProcessorTiming, createHybridProjectionCoordinatorFactory, instrumentPgPool, isCatchingUp, parseDriveUrl, parseKeyframeSettings, rankSlowest, renderDoneSummary, renderSlowLine, startProgressHeartbeat, supportsLiveReadModelRegistration, withProgressHeartbeat } from "@powerhousedao/reactor";
19
+ import { HttpPackageLoader, ImportPackageLoader, NodeEventLoopDelay, NodeMemorySampler, PackageManagementService, PackagesSubgraph, RequestLoadRecorder, baseDocumentModels, createHeapSnapshotWriter, getUniqueDocumentModels, initializeAndStartAPI, memoryFileSink, reportFailure, resolveRenownConfig, runDetached, telemetryDir } from "@powerhousedao/reactor-api";
20
+ import { DEFAULT_PGLITE_WORKER_MEMORY_MB, PGLITE_UTC_PARSERS, ThreadedPGlite, createDurableNodeFs, disableWasmWrapperTiering, maintenanceOf, pgliteWorkerEntryPath, preparePgliteDataDir, removeStalePgliteFiles, resolvePgliteMaintenance, syncTree } from "@powerhousedao/reactor-api/pglite-node";
21
+ import "@powerhousedao/shared/document-model";
22
+ import fs, { promises } from "node:fs";
23
+ import path, { join, resolve } from "node:path";
24
+ import { z } from "zod";
25
+ import { httpsHooksPath } from "@powerhousedao/reactor-api/https-hooks";
26
+ import { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentReferenceReadModel, AttachmentSchemaCompiler, HashMismatch, InvalidAttachmentMetadata, InvalidAttachmentRef, ReservationNotFound, SizeMismatch, UploadTooLarge, createRef, createRemoteAttachmentService, parseAttachmentDownloadTarget, validateReserveMetadata } from "@powerhousedao/reactor-attachments";
27
+ import { createAttachmentClient } from "@powerhousedao/reactor-attachments/client";
28
+ import { DriveNodeView, NodeProcessor, REACTOR_DRIVE_DOCUMENT_TYPE, ReactorDriveClient, createReactorDriveWriteStrategy } from "@powerhousedao/reactor-drive";
29
+ import { REACTOR_DRIVE_SUBGRAPH_NAME, createReactorDriveResolvers, reactorDriveSubgraphTypeDefs } from "@powerhousedao/reactor-drive/subgraph";
30
+ import { DEFAULT_KEYPAIR_PATH, DEFAULT_RENOWN_URL, NodeKeyStorage, RENOWN_READ_MODEL_SUBGRAPH, RenownBuilder, RenownCryptoBuilder, createLocalCredentialVerifier, createRenownTrustPolicy, resolveSwitchboardEndpoint } from "@renown/sdk/node";
31
+ import dotenv from "dotenv";
32
+ import { Kysely, PostgresDialect, sql } from "kysely";
33
+ import net from "node:net";
34
+ import path$1 from "path";
35
+ import { Pool } from "pg";
36
+ import { Readable } from "node:stream";
37
+ import { mergeContributions, resolveOrder, runObserveHook, runObserveHookSequential, runTransformHook } from "@powerhousedao/host-core";
38
+ import { defaultStoreDirs, resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
39
+ import { isDotenvDisabled } from "@powerhousedao/shared/clis/project-env";
40
+ //#region src/profiler.ts
41
+ let started = false;
42
+ async function initProfilerFromEnv(env) {
43
+ if (started || !env.PYROSCOPE_SERVER_ADDRESS) return;
44
+ started = true;
45
+ const { PYROSCOPE_SERVER_ADDRESS: serverAddress, PYROSCOPE_APPLICATION_NAME: appName, PYROSCOPE_USER: basicAuthUser, PYROSCOPE_PASSWORD: basicAuthPassword, PYROSCOPE_WALL_ENABLED: wallEnabled, PYROSCOPE_HEAP_ENABLED: heapEnabled } = env;
46
+ return initProfiler({
47
+ serverAddress,
48
+ appName,
49
+ basicAuthUser,
50
+ basicAuthPassword,
51
+ wall: {
52
+ samplingDurationMs: 1e4,
53
+ samplingIntervalMicros: 1e4,
54
+ collectCpuTime: true
55
+ },
56
+ heap: {
57
+ samplingIntervalBytes: 524288,
58
+ stackDepth: 64
59
+ }
60
+ }, {
61
+ wallEnabled: wallEnabled !== "false",
62
+ heapEnabled: heapEnabled === "true"
63
+ });
64
+ }
65
+ async function initProfiler(options, flags = {
66
+ wallEnabled: true,
67
+ heapEnabled: false
68
+ }) {
69
+ console.log("Initializing Pyroscope profiler at:", options?.serverAddress);
70
+ console.log(" Wall profiling:", flags.wallEnabled ? "enabled" : "disabled");
71
+ console.log(" Heap profiling:", flags.heapEnabled ? "enabled" : "disabled");
72
+ const { default: Pyroscope } = await import("@pyroscope/nodejs");
73
+ Pyroscope.init(options);
74
+ if (flags.wallEnabled) Pyroscope.startWallProfiling();
75
+ Pyroscope.startCpuProfiling();
76
+ if (flags.heapEnabled) Pyroscope.startHeapProfiling();
77
+ }
78
+ //#endregion
79
+ //#region src/permissions-backfill.mts
80
+ /** The permission tables, as reactor-api once kept them on the read-model store. */
81
+ const PERMISSION_TABLES = [
82
+ "DocumentPermission",
83
+ "OperationUserPermission",
84
+ "DocumentProtection"
85
+ ];
86
+ /** What a read-model table is renamed to once its rows live in the reactor store. */
87
+ const MIGRATED_TABLE_SUFFIX = "_migrated_2026_10_25";
88
+ const INSERT_BATCH_SIZE = 500;
89
+ /**
90
+ * Moves the document permission rows from the read-model store into the
91
+ * reactor store, once.
92
+ *
93
+ * Runs at boot after the reactor's migrations (029 creates the target tables)
94
+ * and before the permission service serves a check. When the read-model
95
+ * store still has the legacy tables and the reactor store's are empty, every
96
+ * row is copied in one reactor-store transaction (ids are not carried: no
97
+ * table references them, and the target's serial assigns fresh ones), then
98
+ * the legacy tables are renamed to `<name>_migrated_2026_10_25` so the copy
99
+ * cannot run again. The renamed tables are kept for a release.
100
+ *
101
+ * Idempotent across crashes: when the copy committed but the rename did not,
102
+ * the next boot finds equal row counts on both sides and only renames. Any
103
+ * other mix of rows on both sides is refused with a warning and both stores
104
+ * are left as they are. Plain SQL throughout, so a PGlite or Postgres read
105
+ * store behaves the same.
106
+ */
107
+ async function backfillPermissionTables(readModelDb, reactorDb, logger) {
108
+ const source = readModelDb;
109
+ const target = reactorDb;
110
+ const present = await existingTables(source);
111
+ const legacy = PERMISSION_TABLES.filter((table) => present.has(table));
112
+ if (legacy.length === 0) {
113
+ if (PERMISSION_TABLES.some((table) => present.has(migratedName(table)))) {
114
+ logger.debug("Permission tables backfill: already done; the read-model tables carry the _migrated_2026_10_25 suffix");
115
+ return { status: "already-backfilled" };
116
+ }
117
+ logger.debug("Permission tables backfill: the read-model store has no permission tables; nothing to copy");
118
+ return { status: "fresh-install" };
119
+ }
120
+ const blocked = legacy.filter((table) => present.has(migratedName(table)));
121
+ if (blocked.length > 0) return refuse(logger, `the read-model store has both ${blocked.join(", ")} and ${blocked.map(migratedName).join(", ")}; drop or rename one of each pair`);
122
+ const legacyCounts = await countRows(source, present);
123
+ const reactorCounts = await countRows(target, new Set(PERMISSION_TABLES));
124
+ if (PERMISSION_TABLES.reduce((sum, table) => sum + reactorCounts[table], 0) > 0) {
125
+ if (!countsEqual(legacyCounts, reactorCounts)) return refuse(logger, `the reactor store already has permission rows (${formatCounts(reactorCounts)}) that differ from the read-model store's (${formatCounts(legacyCounts)})`);
126
+ await renameLegacyTables(source, legacy);
127
+ logger.info(`Permission tables backfill: rows were copied by an earlier boot (${formatCounts(legacyCounts)}); renamed the read-model tables to *${MIGRATED_TABLE_SUFFIX}`);
128
+ return {
129
+ status: "rename-completed",
130
+ counts: legacyCounts
131
+ };
132
+ }
133
+ await target.transaction().execute(async (trx) => {
134
+ if (present.has("DocumentPermission")) await copyDocumentPermissions(source, trx);
135
+ if (present.has("OperationUserPermission")) await copyOperationUserPermissions(source, trx);
136
+ if (present.has("DocumentProtection")) await copyDocumentProtections(source, trx);
137
+ const copied = await countRows(trx, new Set(PERMISSION_TABLES));
138
+ if (!countsEqual(copied, legacyCounts)) throw new Error(`Permission tables backfill copied ${formatCounts(copied)} but the read-model store has ${formatCounts(legacyCounts)}; rolled back`);
139
+ });
140
+ await renameLegacyTables(source, legacy);
141
+ logger.info(`Permission tables backfill: copied ${formatCounts(legacyCounts)} from the read-model store to the reactor store; renamed the read-model tables to *${MIGRATED_TABLE_SUFFIX}`);
142
+ return {
143
+ status: "copied",
144
+ counts: legacyCounts
145
+ };
146
+ }
147
+ function migratedName(table) {
148
+ return `${table}${MIGRATED_TABLE_SUFFIX}`;
149
+ }
150
+ function refuse(logger, reason) {
151
+ logger.warn(`Permission tables backfill refused: ${reason}. Permission checks read the reactor store; both stores were left unchanged.`);
152
+ return {
153
+ status: "refused",
154
+ reason
155
+ };
156
+ }
157
+ /** The permission tables, legacy or renamed, in the read-model store's own schema. */
158
+ async function existingTables(db) {
159
+ const names = PERMISSION_TABLES.flatMap((table) => [table, migratedName(table)]);
160
+ const result = await sql`
161
+ select table_name from information_schema.tables
162
+ where table_schema = current_schema()
163
+ and table_name in (${sql.join(names)})
164
+ `.execute(db);
165
+ return new Set(result.rows.map((row) => row.table_name));
166
+ }
167
+ async function countRows(db, tables) {
168
+ const counts = {
169
+ DocumentPermission: 0,
170
+ OperationUserPermission: 0,
171
+ DocumentProtection: 0
172
+ };
173
+ for (const table of PERMISSION_TABLES) {
174
+ if (!tables.has(table)) continue;
175
+ const row = await db.selectFrom(table).select((eb) => eb.fn.countAll().as("count")).executeTakeFirstOrThrow();
176
+ counts[table] = Number(row.count);
177
+ }
178
+ return counts;
179
+ }
180
+ function countsEqual(a, b) {
181
+ return PERMISSION_TABLES.every((table) => a[table] === b[table]);
182
+ }
183
+ function formatCounts(counts) {
184
+ return PERMISSION_TABLES.map((table) => `${table}=${counts[table]}`).join(", ");
185
+ }
186
+ async function copyDocumentPermissions(source, trx) {
187
+ const rows = await source.selectFrom("DocumentPermission").select([
188
+ "documentId",
189
+ "userAddress",
190
+ "permission",
191
+ "grantedBy",
192
+ "createdAt",
193
+ "updatedAt"
194
+ ]).orderBy("id").execute();
195
+ for (const batch of batches(rows)) await trx.insertInto("DocumentPermission").values(batch).execute();
196
+ }
197
+ async function copyOperationUserPermissions(source, trx) {
198
+ const rows = await source.selectFrom("OperationUserPermission").select([
199
+ "documentId",
200
+ "operationType",
201
+ "userAddress",
202
+ "grantedBy",
203
+ "createdAt"
204
+ ]).orderBy("id").execute();
205
+ for (const batch of batches(rows)) await trx.insertInto("OperationUserPermission").values(batch).execute();
206
+ }
207
+ async function copyDocumentProtections(source, trx) {
208
+ const rows = await source.selectFrom("DocumentProtection").select([
209
+ "documentId",
210
+ "protected",
211
+ "ownerAddress",
212
+ "createdAt",
213
+ "updatedAt"
214
+ ]).orderBy("documentId").execute();
215
+ for (const batch of batches(rows)) await trx.insertInto("DocumentProtection").values(batch).execute();
216
+ }
217
+ function* batches(rows) {
218
+ for (let start = 0; start < rows.length; start += INSERT_BATCH_SIZE) yield rows.slice(start, start + INSERT_BATCH_SIZE);
219
+ }
220
+ async function renameLegacyTables(db, tables) {
221
+ await db.transaction().execute(async (trx) => {
222
+ for (const table of tables) await sql`ALTER TABLE ${sql.id(table)} RENAME TO ${sql.id(migratedName(table))}`.execute(trx);
223
+ });
224
+ }
225
+ //#endregion
226
+ //#region src/attachments/auth.ts
227
+ const ANONYMOUS_ACTOR = {
228
+ user: void 0,
229
+ authEnabled: false
230
+ };
231
+ /**
232
+ * Wrap a Node-style handler so that, when `authService` is provided and auth is
233
+ * enabled, the request must carry a verifiable Bearer token. The handler always
234
+ * receives an actor context: the verified bearer user when auth is enabled, or
235
+ * the anonymous context when it is disabled. With `allowAnonymous`, a missing
236
+ * bearer yields an anonymous actor with `authEnabled: true` instead of a 401 —
237
+ * unless `requireAuthenticatedCaller` says the deployment refuses anonymous
238
+ * callers outright, which overrides it.
239
+ *
240
+ * With no `authService` there is no bearer to read and every caller is
241
+ * anonymous, so nothing is refused here. That combination cannot carry the
242
+ * floor: `assertRequireAuthenticatedCallerAllowed` refuses to boot with
243
+ * `REQUIRE_AUTHENTICATED_CALLER` set and no identity resolution, and identity
244
+ * resolution is what builds the service.
245
+ */
246
+ function requireAuth(authService, handler, options) {
247
+ if (!authService) return (req, res, body) => handler(req, res, body, ANONYMOUS_ACTOR);
248
+ return async (req, res, body) => {
249
+ let result;
250
+ try {
251
+ result = await authService.verifyBearer(req.headers.authorization);
252
+ } catch {
253
+ res.statusCode = 500;
254
+ res.setHeader("Content-Type", "application/json");
255
+ res.end(JSON.stringify({ error: "Internal authentication error" }));
256
+ return;
257
+ }
258
+ if (result instanceof Response) {
259
+ const body = await result.text();
260
+ res.statusCode = result.status;
261
+ const contentType = result.headers.get("content-type");
262
+ if (contentType) res.setHeader("Content-Type", contentType);
263
+ res.end(body);
264
+ return;
265
+ }
266
+ if (!result.user) {
267
+ if (options?.requireAuthenticatedCaller === true || result.auth_enabled && !options?.allowAnonymous) {
268
+ res.statusCode = 401;
269
+ res.setHeader("Content-Type", "application/json");
270
+ res.end(JSON.stringify({ error: "Authentication required" }));
271
+ return;
272
+ }
273
+ }
274
+ await handler(req, res, body, {
275
+ user: result.user,
276
+ authEnabled: result.auth_enabled
277
+ });
278
+ };
279
+ }
280
+ //#endregion
281
+ //#region src/attachments/mount-auth.ts
282
+ /**
283
+ * Mount a Node-style attachment route with `requireAuth` applied unconditionally.
284
+ * When `api.authService` is undefined (auth disabled), the handler still runs
285
+ * through `requireAuth` and receives the anonymous actor context — that is the
286
+ * only way to opt out of bearer verification. To register a route without auth
287
+ * wrapping you must call `api.httpAdapter.mountNodeRoute` directly.
288
+ *
289
+ * `allowAnonymous` is reserved for routes whose handlers make a per-document
290
+ * authorization decision themselves; identity-only routes must not use it. It
291
+ * is also not the last word: a deployment that refuses anonymous callers
292
+ * (`REQUIRE_AUTHENTICATED_CALLER`) refuses them here too, because these routes
293
+ * are mounted on the HTTP adapter and never reach the fetch chain that carries
294
+ * that floor for GraphQL. The flag is read from the API, so every route
295
+ * mounted through here inherits it without each one remembering to.
296
+ */
297
+ function mountAuthenticatedNodeRoute(api, method, path, handler, options) {
298
+ const { rawBody, ...authOptions } = options ?? {};
299
+ api.httpAdapter.mountNodeRoute(method, path, requireAuth(api.authService, handler, {
300
+ ...authOptions,
301
+ requireAuthenticatedCaller: api.requireAuthenticatedCaller
302
+ }), { rawBody: rawBody ?? false });
303
+ }
304
+ //#endregion
305
+ //#region src/attachments/routes.ts
306
+ const logger$2 = childLogger(["switchboard", "attachments"]);
307
+ const RETRY_AFTER_SECONDS = 5;
308
+ const HASH_PATTERN = /^[a-f0-9]{64}$/i;
309
+ function sendJson(res, status, body) {
310
+ res.statusCode = status;
311
+ res.setHeader("Content-Type", "application/json");
312
+ res.end(JSON.stringify(body));
313
+ }
314
+ function sendError(res, status, message) {
315
+ sendJson(res, status, { error: message });
316
+ }
317
+ function statusForError(err) {
318
+ if (err instanceof AttachmentNotFound) return 404;
319
+ if (err instanceof ReservationNotFound) return 404;
320
+ if (err instanceof InvalidAttachmentRef) return 400;
321
+ if (err instanceof UploadTooLarge) return 413;
322
+ return 500;
323
+ }
324
+ function sendErrorFromException(res, err) {
325
+ const status = statusForError(err);
326
+ if (status >= 500) {
327
+ logger$2.error("Attachment route error: @error", err);
328
+ sendError(res, status, "Internal error");
329
+ return;
330
+ }
331
+ sendError(res, status, err instanceof Error ? err.message : String(err));
332
+ }
333
+ async function readJsonBody(req, body) {
334
+ if (body !== void 0 && body !== null && typeof body === "object") return body;
335
+ const chunks = [];
336
+ for await (const chunk of req) chunks.push(chunk);
337
+ if (chunks.length === 0) return void 0;
338
+ const text = Buffer.concat(chunks).toString("utf8");
339
+ if (text.length === 0) return void 0;
340
+ return JSON.parse(text);
341
+ }
342
+ function parseReserveOptions(input) {
343
+ if (input === null || typeof input !== "object") return null;
344
+ const obj = input;
345
+ const { mimeType, fileName } = obj;
346
+ const extension = obj.extension ?? null;
347
+ try {
348
+ validateReserveMetadata({
349
+ mimeType,
350
+ fileName,
351
+ extension
352
+ });
353
+ } catch (err) {
354
+ if (err instanceof InvalidAttachmentMetadata) return null;
355
+ throw err;
356
+ }
357
+ if (typeof mimeType !== "string" || typeof fileName !== "string") return null;
358
+ if (extension !== null && typeof extension !== "string") return null;
359
+ if (obj.clientHash !== void 0) {
360
+ if (typeof obj.clientHash !== "string" || !HASH_PATTERN.test(obj.clientHash)) return null;
361
+ if (typeof obj.sizeBytes !== "number" || !Number.isSafeInteger(obj.sizeBytes) || obj.sizeBytes < 0) return null;
362
+ return {
363
+ mimeType,
364
+ fileName,
365
+ extension,
366
+ clientHash: obj.clientHash.toLowerCase(),
367
+ sizeBytes: obj.sizeBytes
368
+ };
369
+ }
370
+ return {
371
+ mimeType,
372
+ fileName,
373
+ extension
374
+ };
375
+ }
376
+ function quoteFilename(name) {
377
+ return `"${name.replace(/[\\"]/g, "\\$&")}"`;
378
+ }
379
+ function buildContentDisposition(fileName) {
380
+ const ascii = fileName.replace(/[^\x20-\x21\x23-\x5b\x5d-\x7e]/g, "_");
381
+ const encoded = encodeURIComponent(fileName).replace(/['()*!]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
382
+ return `attachment; filename=${quoteFilename(ascii)}; filename*=UTF-8''${encoded}`;
383
+ }
384
+ function makeReserveHandler(attachments) {
385
+ return async (req, res, body) => {
386
+ let parsed;
387
+ try {
388
+ parsed = await readJsonBody(req, body);
389
+ } catch {
390
+ sendError(res, 400, "Invalid JSON body");
391
+ return;
392
+ }
393
+ const opts = parseReserveOptions(parsed);
394
+ if (!opts) {
395
+ sendError(res, 400, "Body must be { mimeType: string (type/subtype), fileName: string (no control characters, max 255 chars), extension?: string|null, clientHash?: string (64 hex chars), sizeBytes?: number (required with clientHash) }");
396
+ return;
397
+ }
398
+ let upload;
399
+ try {
400
+ upload = await attachments.service.reserve(opts);
401
+ } catch (err) {
402
+ if (err instanceof AttachmentAlreadyExists) {
403
+ sendJson(res, 409, {
404
+ error: "already_exists",
405
+ ref: err.ref
406
+ });
407
+ return;
408
+ }
409
+ sendErrorFromException(res, err);
410
+ return;
411
+ }
412
+ sendJson(res, 201, {
413
+ reservationId: upload.reservationId,
414
+ ref: upload.ref,
415
+ expiresAtUtc: upload.expiresAtUtc,
416
+ ...upload.uploadTarget ? { uploadTarget: upload.uploadTarget } : {}
417
+ });
418
+ };
419
+ }
420
+ function makeUploadHandler(attachments) {
421
+ return async (req, res) => {
422
+ const reservationId = extractParam(req, "reservationId");
423
+ if (!reservationId) {
424
+ sendError(res, 400, "Missing reservationId");
425
+ return;
426
+ }
427
+ if (attachments.backend?.kind === "s3") {
428
+ sendError(res, 405, "Use the reservation uploadTarget for S3 uploads");
429
+ return;
430
+ }
431
+ let reservation;
432
+ try {
433
+ reservation = await attachments.reservations.get(reservationId);
434
+ } catch (err) {
435
+ sendErrorFromException(res, err);
436
+ return;
437
+ }
438
+ const upload = attachments.uploadFactory.createUpload(reservation);
439
+ const webStream = Readable.toWeb(req);
440
+ try {
441
+ sendJson(res, 200, await upload.send(webStream));
442
+ } catch (err) {
443
+ if (err instanceof HashMismatch) {
444
+ sendJson(res, 422, {
445
+ error: "hash_mismatch",
446
+ claimed: err.claimed,
447
+ actual: err.actual
448
+ });
449
+ return;
450
+ }
451
+ if (err instanceof SizeMismatch) {
452
+ sendJson(res, 422, {
453
+ error: "size_mismatch",
454
+ declared: err.declared,
455
+ actual: err.actual
456
+ });
457
+ return;
458
+ }
459
+ sendErrorFromException(res, err);
460
+ }
461
+ };
462
+ }
463
+ function makeDownloadHandler(attachments, attachmentAccess, urlSigner) {
464
+ return async (req, res, _body, actor) => {
465
+ const hash = extractParam(req, "hash");
466
+ if (!hash || !HASH_PATTERN.test(hash)) {
467
+ sendError(res, 400, "Invalid attachment hash");
468
+ return;
469
+ }
470
+ const canonicalHash = hash.toLowerCase();
471
+ const grant = await resolveByteGrant(req, canonicalHash, actor, attachmentAccess, urlSigner);
472
+ if (!admitGrant(res, grant)) return;
473
+ const controller = new AbortController();
474
+ req.once("close", () => controller.abort());
475
+ let response;
476
+ try {
477
+ response = await attachments.store.get(canonicalHash, controller.signal, grant.documentId);
478
+ } catch (err) {
479
+ if (err instanceof AttachmentPending) {
480
+ res.statusCode = 202;
481
+ res.setHeader("Cache-Control", "private");
482
+ res.setHeader("Retry-After", String(RETRY_AFTER_SECONDS));
483
+ res.setHeader("Attachment-Pending", buildPendingHeader({
484
+ expiresAtUtc: err.expiresAtUtc,
485
+ ...err.metadata ?? {}
486
+ }));
487
+ res.end();
488
+ return;
489
+ }
490
+ sendErrorFromException(res, err);
491
+ return;
492
+ }
493
+ const { header, body } = response;
494
+ res.statusCode = 200;
495
+ res.setHeader("Cache-Control", "private");
496
+ res.setHeader("Content-Type", header.mimeType);
497
+ res.setHeader("Content-Length", String(header.sizeBytes));
498
+ res.setHeader("Content-Disposition", buildContentDisposition(header.fileName));
499
+ res.setHeader("Attachment-Metadata", buildMetadataHeader(header));
500
+ const source = Readable.fromWeb(body);
501
+ source.once("error", (err) => handleDownloadStreamError(res, hash, err));
502
+ source.pipe(res);
503
+ };
504
+ }
505
+ function handleDownloadStreamError(res, hash, err) {
506
+ if (res.headersSent) {
507
+ logger$2.error("Attachment stream failed mid-download: @error", err);
508
+ res.destroy();
509
+ return;
510
+ }
511
+ res.removeHeader("Content-Length");
512
+ res.removeHeader("Content-Disposition");
513
+ res.removeHeader("Attachment-Metadata");
514
+ if (err?.code === "ENOENT") {
515
+ logger$2.warn("Attachment @hash is recorded as available but its blob is missing", hash);
516
+ sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
517
+ return;
518
+ }
519
+ logger$2.error("Attachment stream failed before sending: @error", err);
520
+ sendError(res, 500, "Internal error");
521
+ }
522
+ function toAsciiJson(value) {
523
+ return JSON.stringify(value).replace(/[\u007f-\uffff]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
524
+ }
525
+ function buildPendingHeader(pending) {
526
+ return toAsciiJson(pending);
527
+ }
528
+ function buildMetadataHeader(header) {
529
+ return toAsciiJson({
530
+ mimeType: header.mimeType,
531
+ fileName: header.fileName,
532
+ sizeBytes: header.sizeBytes,
533
+ extension: header.extension,
534
+ createdAtUtc: header.createdAtUtc,
535
+ lastAccessedAtUtc: header.lastAccessedAtUtc
536
+ });
537
+ }
538
+ function makeStatHandler(attachments, attachmentAccess, urlSigner) {
539
+ return async (req, res, _body, actor) => {
540
+ const hash = extractParam(req, "hash");
541
+ if (!hash || !HASH_PATTERN.test(hash)) {
542
+ sendError(res, 400, "Invalid attachment hash");
543
+ return;
544
+ }
545
+ const canonicalHash = hash.toLowerCase();
546
+ if (!admitGrant(res, await resolveByteGrant(req, canonicalHash, actor, attachmentAccess, urlSigner))) return;
547
+ let header;
548
+ try {
549
+ header = await attachments.store.stat(canonicalHash);
550
+ } catch (err) {
551
+ sendErrorFromException(res, err);
552
+ return;
553
+ }
554
+ res.setHeader("Cache-Control", "private");
555
+ if (header.status === "pending") {
556
+ res.statusCode = 202;
557
+ res.setHeader("Retry-After", String(RETRY_AFTER_SECONDS));
558
+ res.setHeader("Attachment-Pending", buildPendingHeader({
559
+ expiresAtUtc: header.expiresAtUtc,
560
+ mimeType: header.mimeType,
561
+ fileName: header.fileName,
562
+ sizeBytes: header.sizeBytes
563
+ }));
564
+ res.end();
565
+ return;
566
+ }
567
+ res.statusCode = 200;
568
+ res.setHeader("Content-Type", header.mimeType);
569
+ res.setHeader("Content-Length", String(header.sizeBytes));
570
+ res.setHeader("Content-Disposition", buildContentDisposition(header.fileName));
571
+ res.setHeader("Attachment-Metadata", buildMetadataHeader(header));
572
+ res.end();
573
+ };
574
+ }
575
+ function makeGetReservationHandler(attachments) {
576
+ return async (req, res) => {
577
+ const reservationId = extractParam(req, "reservationId");
578
+ if (!reservationId) {
579
+ sendError(res, 400, "Missing reservationId");
580
+ return;
581
+ }
582
+ try {
583
+ sendJson(res, 200, await attachments.reservations.get(reservationId));
584
+ } catch (err) {
585
+ sendErrorFromException(res, err);
586
+ }
587
+ };
588
+ }
589
+ function makeDeleteReservationHandler(attachments) {
590
+ return async (req, res) => {
591
+ const reservationId = extractParam(req, "reservationId");
592
+ if (!reservationId) {
593
+ sendError(res, 400, "Missing reservationId");
594
+ return;
595
+ }
596
+ try {
597
+ await attachments.reservations.delete(reservationId);
598
+ res.statusCode = 204;
599
+ res.end();
600
+ } catch (err) {
601
+ sendErrorFromException(res, err);
602
+ }
603
+ };
604
+ }
605
+ function extractParam(req, name) {
606
+ return req.params?.[name];
607
+ }
608
+ const MAX_DOCUMENT_ID_LEN = 512;
609
+ const ATTACHMENT_NOT_FOUND_BODY = { error: "Attachment not found" };
610
+ const MAX_DOWNLOAD_TARGET_TTL_SECONDS = 604800;
611
+ /**
612
+ * How long a download target may live, by default.
613
+ *
614
+ * The authorization behind a presigned URL is decided once, when it is issued,
615
+ * and the URL keeps working until it expires however the document's policy
616
+ * changes in between. A week of that is a revocation that does not revoke: an
617
+ * account deactivated, a company reassigned or a group left, and the bytes stay
618
+ * fetchable by anyone holding the link. Minutes are enough to open a file;
619
+ * days are only enough to lose control of it.
620
+ *
621
+ * A deployment that needs longer sets `attachments.downloadTargetMaxTtlSeconds`
622
+ * (ATTACHMENT_DOWNLOAD_TARGET_MAX_TTL_SECONDS at the edge), still bounded by the
623
+ * signing ceiling above.
624
+ */
625
+ const DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS = 300;
626
+ /** A configured ceiling, bounded by the signing maximum; unset is the default. */
627
+ function downloadTargetTtlCapSeconds(configured) {
628
+ return configured === void 0 ? DEFAULT_DOWNLOAD_TARGET_TTL_SECONDS : Math.min(configured, MAX_DOWNLOAD_TARGET_TTL_SECONDS);
629
+ }
630
+ /**
631
+ * Returns the single `documentId` query value, or null when it is missing,
632
+ * duplicated, blank, or oversized. Validation happens before authorization so
633
+ * malformed requests never reach the access service.
634
+ */
635
+ function extractSingleDocumentId(req) {
636
+ if (!req.url) return null;
637
+ let url;
638
+ try {
639
+ url = new URL(req.url, "http://switchboard.invalid");
640
+ } catch {
641
+ return null;
642
+ }
643
+ const values = url.searchParams.getAll("documentId");
644
+ if (values.length !== 1) return null;
645
+ const value = values[0];
646
+ if (value.trim().length === 0 || value.length > MAX_DOCUMENT_ID_LEN) return null;
647
+ return value;
648
+ }
649
+ /**
650
+ * Returns the target TTL in seconds, or "invalid" when the caller's own value
651
+ * is malformed (duplicated, non-integer, or non-positive).
652
+ *
653
+ * The cap applies whether or not the caller asked for a lifetime: omitting
654
+ * `expiresIn` used to fall through to whatever the storage backend was
655
+ * configured with, which would make the ceiling something a client opts out of
656
+ * by saying nothing.
657
+ */
658
+ function extractExpiresIn(req, cap) {
659
+ if (!req.url) return cap;
660
+ let url;
661
+ try {
662
+ url = new URL(req.url, "http://switchboard.invalid");
663
+ } catch {
664
+ return cap;
665
+ }
666
+ const values = url.searchParams.getAll("expiresIn");
667
+ if (values.length === 0) return cap;
668
+ if (values.length > 1) return "invalid";
669
+ const parsed = Number(values[0]);
670
+ if (!Number.isInteger(parsed) || parsed <= 0) return "invalid";
671
+ return Math.min(parsed, cap);
672
+ }
673
+ function singleQueryValue(params, name) {
674
+ const values = params.getAll(name);
675
+ return values.length === 1 ? values[0] : null;
676
+ }
677
+ /**
678
+ * Byte routes serve only under a grant: a signed URL minted by the
679
+ * download-target route, or a documentId the caller may read the attachment
680
+ * through. A signed request is judged by its signature alone.
681
+ */
682
+ async function resolveByteGrant(req, hash, actor, attachmentAccess, urlSigner) {
683
+ let params;
684
+ try {
685
+ params = new URL(req.url ?? "", "http://switchboard.invalid").searchParams;
686
+ } catch {
687
+ return { kind: "denied" };
688
+ }
689
+ const documentId = extractSingleDocumentId(req);
690
+ if (documentId === null) return { kind: "denied" };
691
+ if (params.has("signature") || params.has("expires")) {
692
+ const signature = singleQueryValue(params, "signature");
693
+ const expires = singleQueryValue(params, "expires");
694
+ if (!urlSigner || signature === null || expires === null) return { kind: "denied" };
695
+ return urlSigner.verify(hash, documentId, expires, signature) ? {
696
+ kind: "granted",
697
+ documentId
698
+ } : { kind: "denied" };
699
+ }
700
+ let decision;
701
+ try {
702
+ decision = await attachmentAccess.canReadAttachment({
703
+ documentId,
704
+ attachmentRef: createRef(hash),
705
+ userAddress: actor?.user?.address,
706
+ appKey: actor?.user?.appKey
707
+ });
708
+ } catch (err) {
709
+ logger$2.error("Attachment access decision failed: @error", err);
710
+ return { kind: "error" };
711
+ }
712
+ if (decision.kind === "projection-unavailable") return { kind: "unavailable" };
713
+ if (decision.kind === "denied") return { kind: "denied" };
714
+ return {
715
+ kind: "granted",
716
+ documentId: decision.documentId
717
+ };
718
+ }
719
+ /** Answers a refused grant; true when the request may proceed. */
720
+ function admitGrant(res, grant) {
721
+ switch (grant.kind) {
722
+ case "granted": return true;
723
+ case "denied":
724
+ sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
725
+ return false;
726
+ case "unavailable":
727
+ sendError(res, 503, "Attachment downloads are temporarily unavailable");
728
+ return false;
729
+ case "error":
730
+ sendError(res, 500, "Internal error");
731
+ return false;
732
+ }
733
+ }
734
+ /**
735
+ * Base URL of this Switchboard as seen by the caller, used to build
736
+ * filesystem `switchboard` download targets that point back at the signed
737
+ * byte route.
738
+ */
739
+ function requestBaseUrl(req) {
740
+ const forwardedProto = req.headers["x-forwarded-proto"];
741
+ const proto = (Array.isArray(forwardedProto) ? forwardedProto[0] : forwardedProto)?.split(",")[0]?.trim() || (req.socket.encrypted ? "https" : "http");
742
+ const forwardedHost = req.headers["x-forwarded-host"];
743
+ const host = (Array.isArray(forwardedHost) ? forwardedHost[0] : forwardedHost) ?? req.headers.host;
744
+ if (!host) return null;
745
+ return `${proto}://${host}`;
746
+ }
747
+ function makeDownloadTargetHandler(attachments, attachmentAccess, urlSigner, ttlCapSeconds = downloadTargetTtlCapSeconds(void 0)) {
748
+ return async (req, res, _body, actor) => {
749
+ res.setHeader("Cache-Control", "no-store");
750
+ const hash = extractParam(req, "hash");
751
+ if (!hash || !HASH_PATTERN.test(hash)) {
752
+ sendError(res, 400, "Invalid attachment hash");
753
+ return;
754
+ }
755
+ const documentId = extractSingleDocumentId(req);
756
+ if (documentId === null) {
757
+ sendError(res, 400, "documentId is required exactly once as a non-empty query parameter");
758
+ return;
759
+ }
760
+ const expiresIn = extractExpiresIn(req, ttlCapSeconds);
761
+ if (expiresIn === "invalid") {
762
+ sendError(res, 400, "expiresIn must be a single positive integer number of seconds");
763
+ return;
764
+ }
765
+ const canonicalHash = hash.toLowerCase();
766
+ let decision;
767
+ try {
768
+ decision = await attachmentAccess.canReadAttachment({
769
+ documentId,
770
+ attachmentRef: createRef(canonicalHash),
771
+ userAddress: actor?.user?.address,
772
+ appKey: actor?.user?.appKey
773
+ });
774
+ } catch (err) {
775
+ logger$2.error("Attachment access decision failed: @error", err);
776
+ sendError(res, 500, "Internal error");
777
+ return;
778
+ }
779
+ if (decision.kind === "projection-unavailable") {
780
+ sendError(res, 503, "Attachment downloads are temporarily unavailable");
781
+ return;
782
+ }
783
+ if (decision.kind === "denied") {
784
+ sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
785
+ return;
786
+ }
787
+ let header;
788
+ try {
789
+ header = await attachments.store.stat(canonicalHash);
790
+ } catch (err) {
791
+ if (err instanceof AttachmentNotFound) {
792
+ sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
793
+ return;
794
+ }
795
+ logger$2.error("Attachment metadata lookup failed: @error", err);
796
+ sendError(res, 500, "Internal error");
797
+ return;
798
+ }
799
+ if (header.status !== "available") {
800
+ sendJson(res, 404, ATTACHMENT_NOT_FOUND_BODY);
801
+ return;
802
+ }
803
+ let target;
804
+ if (attachments.backend && attachments.backend.kind !== "filesystem") try {
805
+ target = await attachments.backend.prepareDownloadTarget(canonicalHash, expiresIn);
806
+ } catch {
807
+ sendError(res, 502, "Attachment download target unavailable");
808
+ return;
809
+ }
810
+ else {
811
+ if (!urlSigner) {
812
+ sendError(res, 503, "Attachment download signing is not configured");
813
+ return;
814
+ }
815
+ const base = requestBaseUrl(req);
816
+ if (!base) {
817
+ sendError(res, 500, "Internal error");
818
+ return;
819
+ }
820
+ const signed = urlSigner.sign(canonicalHash, decision.documentId, expiresIn);
821
+ try {
822
+ target = parseAttachmentDownloadTarget({
823
+ kind: "switchboard",
824
+ method: "GET",
825
+ url: `${base}/attachments/${canonicalHash}?${signed.query}`,
826
+ headers: {},
827
+ expiresAtUtc: signed.expiresAtUtc
828
+ });
829
+ } catch {
830
+ sendError(res, 500, "Internal error");
831
+ return;
832
+ }
833
+ }
834
+ sendJson(res, 200, target);
835
+ };
836
+ }
837
+ //#endregion
838
+ //#region src/attachments/index.ts
839
+ const logger$1 = childLogger(["switchboard", "attachments"]);
840
+ function registerAttachmentRoutes(api, options = {}) {
841
+ const { attachments, attachmentAccess } = api;
842
+ const { config } = options;
843
+ const urlSigner = options.urlSigner === void 0 ? signerFromEnvironment(attachments.backend?.kind ?? "filesystem", {
844
+ [ATTACHMENT_URL_SIGNING_SECRET_ENV]: config?.urlSigningSecret,
845
+ NODE_ENV: process.env.NODE_ENV
846
+ }) : options.urlSigner;
847
+ const ttlCapSeconds = downloadTargetTtlCapSeconds(config?.downloadTargetMaxTtlSeconds);
848
+ mountAuthenticatedNodeRoute(api, "POST", "/attachments/reservations", makeReserveHandler(attachments));
849
+ mountAuthenticatedNodeRoute(api, "GET", "/attachments/reservations/:reservationId", makeGetReservationHandler(attachments));
850
+ mountAuthenticatedNodeRoute(api, "DELETE", "/attachments/reservations/:reservationId", makeDeleteReservationHandler(attachments));
851
+ mountAuthenticatedNodeRoute(api, "PUT", "/attachments/reservations/:reservationId", makeUploadHandler(attachments), { rawBody: true });
852
+ mountAuthenticatedNodeRoute(api, "HEAD", "/attachments/:hash", makeStatHandler(attachments, attachmentAccess, urlSigner), { allowAnonymous: true });
853
+ mountAuthenticatedNodeRoute(api, "GET", "/attachments/:hash/download-target", makeDownloadTargetHandler(attachments, attachmentAccess, urlSigner, ttlCapSeconds), { allowAnonymous: true });
854
+ mountAuthenticatedNodeRoute(api, "GET", "/attachments/:hash", makeDownloadHandler(attachments, attachmentAccess, urlSigner), { allowAnonymous: true });
855
+ }
856
+ function signerFromEnvironment(backend, env) {
857
+ const signing = resolveAttachmentUrlSigning(env);
858
+ if (signing.status === "unconfigured") {
859
+ if (backend === "filesystem") logger$1.error(`${ATTACHMENT_URL_SIGNING_SECRET_ENV} is not set: filesystem attachment download targets are refused until it is`);
860
+ return null;
861
+ }
862
+ if (signing.status === "ephemeral" && backend === "filesystem") logger$1.warn(`${ATTACHMENT_URL_SIGNING_SECRET_ENV} is not set: signing attachment download URLs with a per-process secret`);
863
+ return signing.signer;
864
+ }
865
+ //#endregion
866
+ //#region src/workflow/oauth-apps-config.ts
867
+ /**
868
+ * The config file's `workflows.oauthApps`, client file paths made absolute
869
+ * from `dir`, the config file's folder. A malformed entry is left out; a
870
+ * relay that is not an object is dropped and reported, the app kept without
871
+ * it. The relay's fields are checked by the runtime, as for apps a host
872
+ * passes itself.
873
+ */
874
+ function parseOAuthApps(raw, dir, onDroppedRelay) {
875
+ if (!Array.isArray(raw)) return [];
876
+ const at = (p) => typeof p === "string" && p ? path.resolve(dir, p) : void 0;
877
+ return raw.flatMap((entry) => {
878
+ const app = entry ?? {};
879
+ if (typeof app.id !== "string" || !app.id) return [];
880
+ const desktop = at(app.clients?.desktop);
881
+ const web = at(app.clients?.web);
882
+ let relay;
883
+ if (app.relay !== void 0) {
884
+ if (typeof app.relay === "object" && app.relay !== null && !Array.isArray(app.relay)) relay = app.relay;
885
+ else onDroppedRelay?.(app.id, app.relay);
886
+ }
887
+ return [{
888
+ id: app.id,
889
+ clients: {
890
+ ...desktop ? { desktop } : {},
891
+ ...web ? { web } : {}
892
+ },
893
+ ...relay ? { relay } : {}
894
+ }];
895
+ });
896
+ }
897
+ //#endregion
898
+ //#region src/attachment-reference-read-model.mts
899
+ const attachmentSchemaCompiler = new AttachmentSchemaCompiler();
900
+ function createAttachmentReferenceReadModel(baseKysely, dependencies, attachmentReferenceWriter) {
901
+ return new AttachmentReferenceReadModel(baseKysely.withSchema(REACTOR_SCHEMA), dependencies.operationIndex, dependencies.writeCache, dependencies.processorManagerConsistencyTracker, dependencies.documentModelRegistry, attachmentSchemaCompiler, attachmentReferenceWriter);
902
+ }
903
+ function registerAttachmentReferenceReadModel(reactorBuilder, registration) {
904
+ reactorBuilder.withReadModelFactory(async ({ documentModelRegistry, operationIndex, writeCache, processorManagerConsistencyTracker }) => {
905
+ const readModel = createAttachmentReferenceReadModel(registration.baseKysely, {
906
+ operationIndex,
907
+ writeCache,
908
+ processorManagerConsistencyTracker,
909
+ documentModelRegistry
910
+ }, registration.attachmentReferenceWriter);
911
+ await readModel.init();
912
+ return readModel;
913
+ });
914
+ }
915
+ async function registerAttachmentReferenceReadModelOnModule(clientModule, attachmentReferenceWriter) {
916
+ const reactorModule = clientModule.reactorModule;
917
+ if (!reactorModule) return {
918
+ status: "unavailable",
919
+ reason: "in-process-reactor-module-unavailable"
920
+ };
921
+ const coordinator = reactorModule.readModelCoordinator;
922
+ if (!supportsLiveReadModelRegistration(coordinator)) return {
923
+ status: "unavailable",
924
+ reason: "live-read-model-registration-unsupported"
925
+ };
926
+ const readModel = createAttachmentReferenceReadModel(reactorModule.database, {
927
+ operationIndex: reactorModule.operationIndex,
928
+ writeCache: reactorModule.writeCache,
929
+ processorManagerConsistencyTracker: reactorModule.processorManagerConsistencyTracker,
930
+ documentModelRegistry: reactorModule.documentModelRegistry
931
+ }, attachmentReferenceWriter);
932
+ await readModel.init();
933
+ coordinator.addReadModel(readModel, "pre_ready");
934
+ await readModel.init();
935
+ return { status: "available" };
936
+ }
937
+ //#endregion
938
+ //#region src/builder-defaults.mts
939
+ /**
940
+ * Apply switchboard's standard configuration to a reactor + client builder
941
+ * pair. Each piece is opt-out via the options object; defaults mirror what
942
+ * `startSwitchboard` does when building a reactor itself. Mutates both
943
+ * builders in place.
944
+ *
945
+ * Does NOT touch kysely or read models — callers wire those themselves
946
+ * (see `withKysely` / `withReadModelFactory` on the reactor builder).
947
+ */
948
+ /** The models switchboard always registers alongside package models. */
949
+ function switchboardBaseDocumentModels() {
950
+ return baseDocumentModels.map(([, model]) => model);
951
+ }
952
+ function applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, options = {}) {
953
+ const baseModels = options.includeBaseModels !== false ? switchboardBaseDocumentModels() : [];
954
+ const extra = options.documentModels ?? [];
955
+ if (baseModels.length || extra.length) reactorBuilder.withDocumentModelSources(getUniqueDocumentModels(baseModels, extra));
956
+ if (options.upgradeManifests?.length) reactorBuilder.withUpgradeManifests(options.upgradeManifests);
957
+ const scheme = options.channelScheme === void 0 ? ChannelScheme.SWITCHBOARD : options.channelScheme;
958
+ if (scheme !== false) reactorBuilder.withChannelScheme(scheme);
959
+ if (options.signalHandlers !== false) reactorBuilder.withSignalHandlers();
960
+ if (options.executorConfig?.maxSkipThreshold !== void 0 || options.executorConfig?.featureFlags !== void 0) reactorBuilder.withExecutorConfig({
961
+ ...options.executorConfig.maxSkipThreshold !== void 0 ? { maxSkipThreshold: options.executorConfig.maxSkipThreshold } : {},
962
+ ...options.executorConfig.featureFlags !== void 0 ? { featureFlags: options.executorConfig.featureFlags } : {}
963
+ });
964
+ if (options.documentModelLoader) reactorBuilder.withDocumentModelLoader(options.documentModelLoader);
965
+ if (options.logger) reactorBuilder.withLogger(options.logger);
966
+ if (options.signer) {
967
+ clientBuilder.withSigner(options.signer);
968
+ reactorBuilder.withSigner(options.signer.signer, options.signer.workerSigner);
969
+ }
970
+ if (options.createSignaturePolicy) clientBuilder.withCreateSignaturePolicy(options.createSignaturePolicy);
971
+ const trust = options.trustPolicy ?? options.signer;
972
+ if (trust?.trustPolicy) reactorBuilder.withTrustPolicy(trust.trustPolicy, trust.workerTrustPolicy);
973
+ }
974
+ //#endregion
975
+ //#region src/plugins/attachments.mts
976
+ /** No entry config: presence is the whole activation. A typo'd config key
977
+ * fails at resolution instead of being silently ignored. */
978
+ const attachmentsPluginConfigSchema = z.strictObject({});
979
+ /**
980
+ * R2.3 — the attachments subsystem as a built-in plugin: the six /attachments
981
+ * routes mount at onHttpMounting and the remote attachment service is created
982
+ * for the returned handle. Presence is activation — removed from the
983
+ * composition, the routes and service do not exist. NOT yet carved: the
984
+ * attachment-reference read model registered inside reactor construction
985
+ * (carve map: server.mts initializeClient) — it follows with the
986
+ * onReadModelsRegistering step in R2 step 2; until then it registers on both
987
+ * paths (a dormant read model when the plugin is absent, harmless).
988
+ *
989
+ * Inputs (carve map): api (routes), config.attachments (signing, TTL),
990
+ * options.attachmentServiceUrl / https + serverPort + renown (service config).
991
+ */
992
+ const attachmentsPlugin = {
993
+ name: "switchboard-attachments",
994
+ appliesTo: "switchboard",
995
+ configSchema: attachmentsPluginConfigSchema,
996
+ hooks: { onHttpMounting: (ctx) => {
997
+ registerAttachmentRoutes(ctx.api, { config: ctx.config?.attachments });
998
+ ctx.attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(ctx.options, ctx.serverPort, ctx.renown));
999
+ } }
1000
+ };
1001
+ //#endregion
1002
+ //#region src/plugin-host.mts
1003
+ /** Built-in plugins, pre-listed (the default composition until host.js
1004
+ * entries map in R2 step 2). Subsystems join as R2 carves them. */
1005
+ function builtinSwitchboardPlugins() {
1006
+ const entry = {
1007
+ enabled: true,
1008
+ verbs: "*",
1009
+ config: {}
1010
+ };
1011
+ return [
1012
+ {
1013
+ plugin: mcpPlugin,
1014
+ provenance: "built-in",
1015
+ entry: {
1016
+ ...entry,
1017
+ module: "@powerhousedao/switchboard/plugins/mcp"
1018
+ }
1019
+ },
1020
+ {
1021
+ plugin: attachmentsPlugin,
1022
+ provenance: "built-in",
1023
+ entry: {
1024
+ ...entry,
1025
+ module: "@powerhousedao/switchboard/plugins/attachments"
1026
+ }
1027
+ },
1028
+ {
1029
+ plugin: privacyPlugin,
1030
+ provenance: "built-in",
1031
+ entry: {
1032
+ ...entry,
1033
+ module: "@powerhousedao/switchboard/plugins/privacy"
1034
+ }
1035
+ },
1036
+ {
1037
+ plugin: workflowsPlugin,
1038
+ provenance: "built-in",
1039
+ entry: {
1040
+ ...entry,
1041
+ module: "@powerhousedao/switchboard/plugins/workflows"
1042
+ }
1043
+ }
1044
+ ];
1045
+ }
1046
+ function createSwitchboardPluginHost(ctx, resolved) {
1047
+ resolved ??= builtinSwitchboardPlugins();
1048
+ const ordered = resolveOrder(resolved.map((r) => r.plugin));
1049
+ const contributions = mergeContributions(resolved.map((r) => ({
1050
+ plugin: r.plugin,
1051
+ provenance: r.provenance
1052
+ })));
1053
+ const fullCtx = {
1054
+ ...ctx,
1055
+ contributions
1056
+ };
1057
+ const LOG = "[switchboard:plugins]";
1058
+ console.log(`${LOG} composition: ${ordered.length} plugin(s) in order — ${ordered.map((p) => p.name).join(", ") || "(none)"}`);
1059
+ for (const r of resolved) {
1060
+ const cfg = Object.keys(r.entry.config ?? {});
1061
+ console.log(`${LOG} • ${r.plugin.name} [${r.provenance}] (${r.entry.module})` + (cfg.length ? ` config: {${cfg.join(", ")}}` : ""));
1062
+ }
1063
+ const ranBy = (hook) => ordered.filter((p) => p.hooks?.[hook]);
1064
+ const logHook = (hook) => {
1065
+ const names = ranBy(hook).map((p) => p.name);
1066
+ console.log(`${LOG} hook ${hook} → ${names.length ? names.join(", ") : "(no implementers)"}`);
1067
+ };
1068
+ return {
1069
+ plugins: ordered,
1070
+ ctx: fullCtx,
1071
+ transformOptions: (seed) => {
1072
+ logHook("transformServerOptions");
1073
+ return runTransformHook("transformServerOptions", ordered, fullCtx, seed);
1074
+ },
1075
+ observe: (hook) => {
1076
+ logHook(hook);
1077
+ return hook === "onShutdown" ? runObserveHookSequential(hook, ordered, fullCtx) : runObserveHook(hook, ordered, fullCtx);
1078
+ }
1079
+ };
1080
+ }
1081
+ //#endregion
1082
+ //#region src/processor-timing-log.mts
1083
+ const TOP = 5;
1084
+ /**
1085
+ * The console's `catch-up slowest` line for a host without the ph-cli display:
1086
+ * one every interval while catching up, and one summary when it ends. Silent
1087
+ * while timing is off or nothing is catching up. Returns the stop.
1088
+ */
1089
+ function startProcessorTimingLog(options) {
1090
+ const now = options.now ?? (() => Date.now());
1091
+ let busySince;
1092
+ const tick = () => {
1093
+ const report = options.read();
1094
+ if (report.level === "off") return;
1095
+ if (isCatchingUp(report)) {
1096
+ busySince ??= now();
1097
+ const rows = rankSlowest(report, TOP, "window");
1098
+ if (rows.length > 0) options.log(renderSlowLine(rows, report.windowMs));
1099
+ return;
1100
+ }
1101
+ if (busySince === void 0) return;
1102
+ const wallMs = now() - busySince;
1103
+ busySince = void 0;
1104
+ options.log(renderDoneSummary(rankSlowest(report, TOP, "total"), wallMs));
1105
+ };
1106
+ const timer = setInterval(tick, options.intervalMs);
1107
+ timer.unref();
1108
+ return () => clearInterval(timer);
1109
+ }
1110
+ //#endregion
1111
+ //#region src/pglite-dialect.ts
1112
+ /** A poisoned store cannot recover in process, so it takes the fatal shutdown and a supervisor restart. */
1113
+ function reactorPgliteDialectOptions(logger, proc) {
1114
+ return {
1115
+ onDiagnostic: (message, error) => logger.error(`[pglite-dialect] ${message}: @error`, error),
1116
+ onPoisoned: (cause) => {
1117
+ if (!triggerFatalShutdown("PGlite session poisoned", cause, proc)) logger.error("PGlite session poisoned: @error", cause);
1118
+ }
1119
+ };
1120
+ }
1121
+ var ClosablePGliteDialect = class {
1122
+ #inner;
1123
+ #pglite;
1124
+ constructor(pglite, options = {}) {
1125
+ this.#pglite = pglite;
1126
+ this.#inner = new HardenedPGliteDialect(pglite, options);
1127
+ }
1128
+ createAdapter() {
1129
+ return this.#inner.createAdapter();
1130
+ }
1131
+ createDriver() {
1132
+ const driver = this.#inner.createDriver();
1133
+ const pglite = this.#pglite;
1134
+ const innerDestroy = driver.destroy.bind(driver);
1135
+ driver.destroy = async () => {
1136
+ await innerDestroy();
1137
+ if (pglite.closed) return;
1138
+ try {
1139
+ await pglite.close();
1140
+ } catch (err) {
1141
+ if (!/PGlite aborted/.test(String(err))) throw err;
1142
+ }
1143
+ };
1144
+ return driver;
1145
+ }
1146
+ createQueryCompiler() {
1147
+ return this.#inner.createQueryCompiler();
1148
+ }
1149
+ createIntrospector(db) {
1150
+ return this.#inner.createIntrospector(db);
1151
+ }
1152
+ };
1153
+ //#endregion
1154
+ //#region src/pglite-migration.ts
1155
+ function backupPath(dataDir, major) {
1156
+ return `${dataDir}.backup-pg${major}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`;
1157
+ }
1158
+ async function pathExists(p) {
1159
+ try {
1160
+ await promises.stat(p);
1161
+ return true;
1162
+ } catch {
1163
+ return false;
1164
+ }
1165
+ }
1166
+ function logRestoreFailure(dataDir, sql, err, logger) {
1167
+ const errObj = err;
1168
+ const position = typeof errObj.position === "string" ? parseInt(errObj.position, 10) : typeof errObj.position === "number" ? errObj.position : NaN;
1169
+ logger.error(`[pglite-migration] Restore failed for ${dataDir}: code=${errObj.code ?? ""} severity=${errObj.severity ?? ""} message=${errObj.message ?? ""} sqlLength=${sql.length}`);
1170
+ if (Number.isFinite(position) && position > 0) {
1171
+ const zeroBased = position - 1;
1172
+ const start = Math.max(0, zeroBased - 200);
1173
+ const end = Math.min(sql.length, zeroBased + 200);
1174
+ const before = sql.slice(start, zeroBased);
1175
+ const at = sql.slice(zeroBased, zeroBased + 1);
1176
+ const after = sql.slice(zeroBased + 1, end);
1177
+ logger.error(`[pglite-migration] SQL context around position ${position}:\n${before}»${at}«${after}`);
1178
+ } else logger.error(`[pglite-migration] No position info. First 2000 chars of dump:\n${sql.slice(0, 2e3)}`);
1179
+ }
1180
+ /**
1181
+ * Migrate a filesystem PGLite data directory from a legacy PG major to the
1182
+ * current one. Renames the existing dir to a timestamped backup, dumps via the
1183
+ * matching legacy `pg_dump`, restores into a fresh current-version PGLite at
1184
+ * the original path. On failure, the original dir is restored from the backup.
1185
+ *
1186
+ * No-op when the dir is missing or already at the current major.
1187
+ */
1188
+ async function migratePgliteDir(dataDir, logger) {
1189
+ const major = await readPgVersionFile(dataDir);
1190
+ if (major === null) {
1191
+ logger.info(`[pglite-migration] No PG_VERSION at ${dataDir}; skipping migration`);
1192
+ return;
1193
+ }
1194
+ if (major === 17) return;
1195
+ if (!isSupportedMajor(major)) throw new Error(`Unsupported legacy PGlite data dir: PG_VERSION=${major} for ${dataDir}`);
1196
+ const backupDir = backupPath(dataDir, major);
1197
+ logger.info(`[pglite-migration] Migrating ${dataDir} from PG${major} to PG17; backup: ${backupDir}`);
1198
+ await promises.rename(dataDir, backupDir);
1199
+ let sql;
1200
+ try {
1201
+ const [legacyMod, pgDump] = await Promise.all([loadPGliteModule(major), loadPgDump(major)]);
1202
+ const LegacyPGlite = legacyMod.PGlite;
1203
+ const onDisk = new LegacyPGlite(backupDir);
1204
+ let tar;
1205
+ try {
1206
+ await onDisk.waitReady;
1207
+ tar = await onDisk.dumpDataDir("none");
1208
+ } finally {
1209
+ await onDisk.close();
1210
+ }
1211
+ const pg = new LegacyPGlite({ loadDataDir: tar });
1212
+ try {
1213
+ await pg.waitReady;
1214
+ sql = await (await pgDump({ pg })).text();
1215
+ } finally {
1216
+ await pg.close();
1217
+ }
1218
+ } catch (err) {
1219
+ await rollback(dataDir, backupDir, err, logger);
1220
+ throw err;
1221
+ }
1222
+ try {
1223
+ const CurrentPGlite = (await loadPGliteModule(17)).PGlite;
1224
+ const pg = new CurrentPGlite(dataDir, { relaxedDurability: false });
1225
+ try {
1226
+ await pg.waitReady;
1227
+ try {
1228
+ await pg.exec("SET standard_conforming_strings = off;");
1229
+ } catch (gucErr) {
1230
+ logger.warn(`[pglite-migration] Could not force standard_conforming_strings=off: ${String(gucErr)}`);
1231
+ }
1232
+ try {
1233
+ await pg.exec(sql);
1234
+ } catch (execErr) {
1235
+ logRestoreFailure(dataDir, sql, execErr, logger);
1236
+ throw execErr;
1237
+ }
1238
+ } finally {
1239
+ await pg.close();
1240
+ }
1241
+ syncTree(dataDir);
1242
+ } catch (err) {
1243
+ await rollback(dataDir, backupDir, err, logger);
1244
+ throw err;
1245
+ }
1246
+ logger.info(`[pglite-migration] Migration of ${dataDir} complete. Backup retained at ${backupDir}; remove it manually once you have verified the upgrade.`);
1247
+ }
1248
+ async function rollback(dataDir, backupDir, originalError, logger) {
1249
+ try {
1250
+ if (await pathExists(dataDir)) await promises.rm(dataDir, {
1251
+ recursive: true,
1252
+ force: true
1253
+ });
1254
+ if (await pathExists(backupDir)) await promises.rename(backupDir, dataDir);
1255
+ } catch (rollbackErr) {
1256
+ logger.error(`[pglite-migration] Migration AND rollback failed for ${dataDir}. Original error: ${String(originalError)}; rollback error: ${String(rollbackErr)}; backup may still exist at ${backupDir}.`);
1257
+ return;
1258
+ }
1259
+ logger.error(`[pglite-migration] Migration failed for ${dataDir}; rolled back from ${backupDir}. Original error: ${String(originalError)}`);
1260
+ }
1261
+ //#endregion
1262
+ //#region src/pglite-preflight.ts
1263
+ const RM_OPTIONS = {
1264
+ recursive: true,
1265
+ force: true,
1266
+ maxRetries: 10,
1267
+ retryDelay: 100
1268
+ };
1269
+ /**
1270
+ * Prepares every local PGlite dir before the first open and returns the
1271
+ * PG major detected on disk per dir. Conversion of an AtomicNodeFs snapshot
1272
+ * runs for every dir, before the major is read, so a pure-snapshot PG16 dir
1273
+ * is converted and then migrated.
1274
+ */
1275
+ async function runPglitePreflight(options) {
1276
+ const { dirs, logger } = options;
1277
+ const detectedMajors = /* @__PURE__ */ new Map();
1278
+ if (options.inMemory || dirs.length === 0) return detectedMajors;
1279
+ if (options.forcePgVersion !== void 0) {
1280
+ if (options.migratePglite) logger.warn("PH_FORCE_PG_VERSION is set; ignoring --migrate-pglite/PH_MIGRATE_PGLITE because the data dirs will be wiped.");
1281
+ logger.warn(`PH_FORCE_PG_VERSION=${options.forcePgVersion} set; wiping PGLite data dirs and re-initializing at PG${options.forcePgVersion}.`);
1282
+ for (const dir of dirs) {
1283
+ for (const p of [
1284
+ dir,
1285
+ `${dir}.converting`,
1286
+ `${dir}.old`
1287
+ ]) await promises.rm(p, RM_OPTIONS);
1288
+ logger.info(`Wiped PGLite data dir ${dir}`);
1289
+ }
1290
+ return detectedMajors;
1291
+ }
1292
+ const deps = {
1293
+ openForVerify: options.openForVerify ?? openForVerify,
1294
+ logger
1295
+ };
1296
+ for (const dir of dirs) {
1297
+ await preparePgliteDataDir(dir, deps);
1298
+ const major = await readPgVersionFile(dir);
1299
+ if (major !== null) detectedMajors.set(dir, major);
1300
+ }
1301
+ if (options.migratePglite) for (const [dir, major] of detectedMajors) {
1302
+ if (major === 17) continue;
1303
+ await migratePgliteDir(dir, logger);
1304
+ await removeStalePgliteFiles(dir, logger);
1305
+ const after = await readPgVersionFile(dir);
1306
+ if (after !== null) detectedMajors.set(dir, after);
1307
+ }
1308
+ else for (const [dir, major] of detectedMajors) {
1309
+ if (major === 17) continue;
1310
+ logger.warn(`PGLite data dir at ${dir} was created with PG${major} but Switchboard ships PG17. Running on legacy PGLite. Re-start with --migrate-pglite (or PH_MIGRATE_PGLITE=true) to upgrade.`);
1311
+ }
1312
+ return detectedMajors;
1313
+ }
1314
+ //#endregion
1315
+ //#region src/pglite-store.mts
1316
+ function onPgliteAbort(logger, what, proc) {
1317
+ if (!triggerFatalShutdown("PGlite aborted", what, proc)) logger.error("PGlite aborted: @error", what);
1318
+ }
1319
+ /** A store's worker thread died: every later query would fail, so the process shuts down. */
1320
+ function onPgliteWorkerExit(logger, error, proc) {
1321
+ if (!triggerFatalShutdown("PGlite worker exited", error, proc)) logger.error("PGlite worker exited: @error", error);
1322
+ }
1323
+ /** Sends a worker's abort and its unexpected exit to the fatal shutdown. */
1324
+ function routePgliteWorkerFailures(store, logger, proc) {
1325
+ store.onAbort((reason) => onPgliteAbort(logger, reason, proc));
1326
+ store.onExit((error) => {
1327
+ if (error !== null) onPgliteWorkerExit(logger, error, proc);
1328
+ });
1329
+ }
1330
+ /**
1331
+ * Adds a terminate of the store's worker to the dialect's `onPoisoned`: a
1332
+ * statement that never settled holds the worker's only connection, and the
1333
+ * fatal shutdown's close would otherwise queue behind it until its grace ran
1334
+ * out.
1335
+ */
1336
+ function terminateOnPoisoned(options, store) {
1337
+ const reportPoisoned = options.onPoisoned;
1338
+ return {
1339
+ ...options,
1340
+ onPoisoned: (cause) => {
1341
+ reportPoisoned?.(cause);
1342
+ store.terminate();
1343
+ }
1344
+ };
1345
+ }
1346
+ function pgliteFsyncFor(wanted, major, dir, logger) {
1347
+ if (wanted && major === 16) logger.warn(`PGlite data dir ${dir} is PG16 on pglite-legacy-02, which does not sync commits to disk; only checkpoints are synced until --migrate-pglite upgrades it.`);
1348
+ return wanted;
1349
+ }
1350
+ /** The VACUUM FULL settings a config asks for, with the env parser's rules. */
1351
+ function vacuumFullTimingOf(vacuumFull) {
1352
+ return resolvePgliteMaintenance({
1353
+ PH_PGLITE_VACUUM_FULL: vacuumFull.mode,
1354
+ PH_PGLITE_VACUUM_FULL_ABOVE_MB: vacuumFull.aboveMb?.toString(),
1355
+ PH_PGLITE_VACUUM_FULL_QUIET_MS: vacuumFull.quietMs?.toString(),
1356
+ PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS: vacuumFull.maxDeferMs?.toString()
1357
+ });
1358
+ }
1359
+ const DEFAULT_MAINTENANCE = { vacuumFullAboveBytes: 0 };
1360
+ /** Preloads the module's NodeFS so the returned factory can be synchronous. */
1361
+ async function loadDurableFsFactory(major, logger, proc, settings = {}) {
1362
+ const NodeFS = await loadNodeFsClass(major);
1363
+ const timing = settings.maintenance ?? DEFAULT_MAINTENANCE;
1364
+ return (dir) => createDurableNodeFs(NodeFS, dir, {
1365
+ fsync: pgliteFsyncFor(settings.fsync ?? true, major, dir, logger),
1366
+ ...timing,
1367
+ logger,
1368
+ onAbort: (what) => onPgliteAbort(logger, what, proc)
1369
+ });
1370
+ }
1371
+ const REACTOR_STORE = {
1372
+ label: "reactor-storage",
1373
+ parsers: "none"
1374
+ };
1375
+ const READ_STORE = {
1376
+ label: "read-storage",
1377
+ parsers: "utc-timestamps"
1378
+ };
1379
+ /**
1380
+ * Starts both stores at once, so the wait is the slower of the two rather than
1381
+ * their sum. A store left by a crash spends seconds recovering in its thread.
1382
+ * If one can't open, the other is closed, not left recovering for nobody.
1383
+ */
1384
+ function openStoresTogether(openReactor, openReadModel) {
1385
+ const reactor = openReactor();
1386
+ let readModel;
1387
+ try {
1388
+ readModel = openReadModel();
1389
+ } catch (error) {
1390
+ reactor.close().catch(() => void 0);
1391
+ throw error;
1392
+ }
1393
+ const close = async () => {
1394
+ await Promise.allSettled([reactor.close(), readModel.close()]);
1395
+ };
1396
+ const stays = () => new Promise(() => void 0);
1397
+ const failed = Promise.race([reactor.waitReady.then(stays), readModel.waitReady.then(stays)]).catch(async (error) => {
1398
+ await close();
1399
+ throw error;
1400
+ });
1401
+ failed.catch(() => void 0);
1402
+ return {
1403
+ reactor,
1404
+ readModel,
1405
+ failed,
1406
+ close
1407
+ };
1408
+ }
1409
+ /**
1410
+ * The factory for one PGlite store: in a worker thread when `threaded` (and a
1411
+ * worker script exists here), else in the main thread as before. Either way
1412
+ * the store runs DurableNodeFs over its dir with the same fsync choice, and a
1413
+ * wasm abort takes the fatal shutdown.
1414
+ */
1415
+ async function createPgliteStoreFactory(options) {
1416
+ if (options.threaded) {
1417
+ if (pgliteWorkerEntryPath !== null) return threadedStoreFactory(options);
1418
+ options.logger.warn(`${options.label}: no PGlite worker script is available (unbuilt @powerhousedao/reactor-api); PGlite runs in the main thread`);
1419
+ }
1420
+ return mainThreadStoreFactory(options);
1421
+ }
1422
+ function threadedStoreFactory(options) {
1423
+ const { label, major, parsers, inMemory, logger, proc } = options;
1424
+ const settings = options.settings ?? {};
1425
+ const memoryLimitMb = settings.workerMemoryMb ?? DEFAULT_PGLITE_WORKER_MEMORY_MB;
1426
+ const module = pgliteModuleSpec(major);
1427
+ return (dir) => {
1428
+ const store = new ThreadedPGlite({
1429
+ store: {
1430
+ label,
1431
+ dataDir: inMemory ? null : dir,
1432
+ module,
1433
+ durableFs: inMemory ? null : {
1434
+ fsync: pgliteFsyncFor(settings.fsync ?? true, major, dir, logger),
1435
+ ...settings.maintenance ?? DEFAULT_MAINTENANCE
1436
+ },
1437
+ parsers
1438
+ },
1439
+ memoryLimitMb,
1440
+ logger
1441
+ });
1442
+ routePgliteWorkerFailures(store, logger, proc);
1443
+ logger.info(`${label}: PGlite (PG${major}) in a worker thread (memory limit ${memoryLimitMb} MB)${where(inMemory, dir)}`);
1444
+ const opening = startProgressHeartbeat({
1445
+ logger,
1446
+ label: `${label}: opening the store`
1447
+ });
1448
+ store.waitReady.then(() => opening.stop(), () => opening.stop("failed"));
1449
+ return store;
1450
+ };
1451
+ }
1452
+ async function mainThreadStoreFactory(options) {
1453
+ const { label, major, inMemory, logger, proc } = options;
1454
+ const { PGlite } = await loadPGliteModule(major);
1455
+ const durableFs = inMemory ? null : await loadDurableFsFactory(major, logger, proc, options.settings);
1456
+ const base = options.parsers === "utc-timestamps" ? { parsers: PGLITE_UTC_PARSERS } : {};
1457
+ return (dir) => {
1458
+ logger.info(`${label}: PGlite (PG${major}) in the main thread${where(inMemory, dir)}`);
1459
+ return durableFs === null ? new PGlite(base) : new PGlite({
1460
+ ...base,
1461
+ fs: durableFs(dir)
1462
+ });
1463
+ };
1464
+ }
1465
+ function where(inMemory, dir) {
1466
+ return inMemory ? ", in memory [PH_PGLITE_IN_MEMORY=1]" : ` at ${dir}`;
1467
+ }
1468
+ //#endregion
1469
+ //#region src/create-signature-policy.mts
1470
+ /** The requested policy, or legacy when it needs a signer this switchboard lacks. */
1471
+ function createSignaturePolicyFor(policy, options) {
1472
+ if (policy === "v2-required" && !options.hasSigner) {
1473
+ options.logger?.warn("No signer is configured, so new documents are created legacy: a v2-required document refuses the unsigned operations this switchboard would write. Set up an identity (ph login) to create v2-required documents.");
1474
+ return "legacy";
1475
+ }
1476
+ return policy;
1477
+ }
1478
+ //#endregion
1479
+ //#region src/renown.ts
1480
+ const logger = childLogger(["switchboard", "renown"]);
1481
+ /**
1482
+ * Initialize Renown for the Switchboard instance.
1483
+ * This allows Switchboard to authenticate with remote services
1484
+ * using the same identity established during `ph login`.
1485
+ */
1486
+ async function initRenown(options = {}) {
1487
+ const { keypairPath, requireExisting = false, baseUrl = DEFAULT_RENOWN_URL, userDataDir, storagePath = userDataDir ? join(resolvePhDir(void 0, { PH_USER_DATA_DIR: userDataDir }), ".renown.json") : void 0 } = options;
1488
+ const keyStorage = new NodeKeyStorage(keypairPath, { logger });
1489
+ const existingKeyPair = await keyStorage.loadKeyPair();
1490
+ if (!existingKeyPair && requireExisting) throw new Error("No existing keypair found and requireExisting is true. Run \"ph login\" to create one.");
1491
+ if (!existingKeyPair) logger.info("No existing keypair found. A new one will be generated.");
1492
+ const renownCrypto = await new RenownCryptoBuilder().withKeyPairStorage(keyStorage).build();
1493
+ const renown = await new RenownBuilder("switchboard", {
1494
+ ...storagePath ? { storagePath } : {},
1495
+ ...keypairPath ? { keyPath: keypairPath } : {}
1496
+ }).withCrypto(renownCrypto).withBaseUrl(baseUrl).build();
1497
+ logger.info("Switchboard identity initialized: @did", renownCrypto.did);
1498
+ return renown;
1499
+ }
1500
+ /**
1501
+ * Get the signer config for the given renown instance.
1502
+ *
1503
+ * @param renown - The renown instance
1504
+ * @param keypairPath - Where `initRenown` loaded the key from
1505
+ */
1506
+ function getRenownSignerConfig(renown, keypairPath) {
1507
+ return {
1508
+ signer: renown.signer,
1509
+ workerSigner: getRenownWorkerSignerSpec(renown, keypairPath)
1510
+ };
1511
+ }
1512
+ /**
1513
+ * What a pooled executor worker imports to sign as this switchboard: it
1514
+ * reloads the key `initRenown` stored, and takes the user known at boot.
1515
+ */
1516
+ function getRenownWorkerSignerSpec(renown, keypairPath) {
1517
+ const { signer } = renown;
1518
+ const user = signer.user;
1519
+ return {
1520
+ module: {
1521
+ filePath: createRequire(import.meta.url).resolve("@renown/sdk/node"),
1522
+ exportName: "createNodeRenownSigner"
1523
+ },
1524
+ initArgs: {
1525
+ appName: signer.app?.name ?? "switchboard",
1526
+ keypairPath: resolve(keypairPath ?? DEFAULT_KEYPAIR_PATH),
1527
+ ...signer.app?.key ? { did: signer.app.key } : {},
1528
+ ...user ? { user: {
1529
+ address: user.address,
1530
+ networkId: user.networkId,
1531
+ chainId: user.chainId
1532
+ } } : {}
1533
+ }
1534
+ };
1535
+ }
1536
+ /**
1537
+ * What a host with `authEnforcement` off installs: a delegated signer is
1538
+ * verified from what it carries, and every other signer is accepted as the
1539
+ * default would. No lookup, so it needs no network, at boot or after.
1540
+ */
1541
+ function getDelegationTrustPolicyConfig(renown) {
1542
+ const ownSigner = renown?.signer;
1543
+ const self = ownIdentity(renown);
1544
+ return {
1545
+ trustPolicy: createRenownTrustPolicy({
1546
+ delegationOnly: true,
1547
+ ownSigner
1548
+ }),
1549
+ workerTrustPolicy: {
1550
+ module: {
1551
+ filePath: createRequire(import.meta.url).resolve("@renown/sdk/node"),
1552
+ exportName: "createRenownTrustPolicy"
1553
+ },
1554
+ initArgs: {
1555
+ delegationOnly: true,
1556
+ ...self ? { self } : {}
1557
+ }
1558
+ }
1559
+ };
1560
+ }
1561
+ /**
1562
+ * Admits a key as a signer for an address a Renown credential binds it to; a
1563
+ * `self` source has no worker spec. In process, the switchboard's own key is
1564
+ * matched against its current user; the worker spec carries the user known now.
1565
+ */
1566
+ async function getRenownTrustPolicyConfig(trustSource, renown) {
1567
+ const ownSigner = renown?.signer;
1568
+ if (trustSource.source === "self") return { trustPolicy: createRenownTrustPolicy({
1569
+ switchboard: trustSource.request,
1570
+ ownSigner
1571
+ }) };
1572
+ const switchboardUrl = await resolveSwitchboardEndpoint({
1573
+ switchboardUrl: trustSource.switchboardUrl,
1574
+ baseUrl: trustSource.renownUrl
1575
+ });
1576
+ const options = {
1577
+ ...switchboardUrl ? { switchboard: switchboardUrl } : {},
1578
+ ...trustSource.renownUrl ? { renownUrl: trustSource.renownUrl } : {}
1579
+ };
1580
+ const self = ownIdentity(renown);
1581
+ return {
1582
+ trustPolicy: createRenownTrustPolicy({
1583
+ ...options,
1584
+ ownSigner
1585
+ }),
1586
+ workerTrustPolicy: {
1587
+ module: {
1588
+ filePath: createRequire(import.meta.url).resolve("@renown/sdk/node"),
1589
+ exportName: "createRenownTrustPolicy"
1590
+ },
1591
+ initArgs: {
1592
+ ...options,
1593
+ ...self ? { self } : {}
1594
+ }
1595
+ }
1596
+ };
1597
+ }
1598
+ function ownIdentity(renown) {
1599
+ const key = renown?.signer.app?.key;
1600
+ if (!key) return;
1601
+ const user = renown.signer.user;
1602
+ return {
1603
+ key,
1604
+ user: {
1605
+ address: user?.address ?? "",
1606
+ networkId: user?.networkId ?? "",
1607
+ chainId: user?.chainId ?? 0
1608
+ }
1609
+ };
1610
+ }
1611
+ //#endregion
1612
+ //#region src/store-lock.mts
1613
+ var StoreInUseError = class extends Error {
1614
+ dir;
1615
+ owner;
1616
+ constructor(dir, owner) {
1617
+ super(`The PGlite store ${dir} is in use by another process (pid ${owner.pid}, since ${owner.startedAt}: ${owner.command}). Two processes on one PGlite store corrupt it. Stop that process first, or point this one at a different store.`);
1618
+ this.dir = dir;
1619
+ this.owner = owner;
1620
+ this.name = "StoreInUseError";
1621
+ }
1622
+ };
1623
+ const lockPathOf = (dir) => `${path.resolve(dir)}.lock`;
1624
+ function isAlive(pid) {
1625
+ try {
1626
+ process.kill(pid, 0);
1627
+ return true;
1628
+ } catch (error) {
1629
+ return error.code === "EPERM";
1630
+ }
1631
+ }
1632
+ function readOwner(file) {
1633
+ try {
1634
+ return JSON.parse(fs.readFileSync(file, "utf8"));
1635
+ } catch {
1636
+ return;
1637
+ }
1638
+ }
1639
+ const held = /* @__PURE__ */ new Set();
1640
+ let exitHookInstalled = false;
1641
+ function releaseAll() {
1642
+ for (const file of held) if (readOwner(file)?.pid === process.pid) try {
1643
+ fs.rmSync(file);
1644
+ } catch {}
1645
+ held.clear();
1646
+ }
1647
+ /** Take the lock for each store dir, or throw StoreInUseError naming the
1648
+ * live owner. Idempotent within one process. */
1649
+ function acquireStoreLocks(dirs, isPidAlive = isAlive) {
1650
+ const mine = {
1651
+ pid: process.pid,
1652
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1653
+ command: process.argv.slice(1).join(" ").slice(0, 200)
1654
+ };
1655
+ for (const dir of new Set(dirs.map((d) => path.resolve(d)))) {
1656
+ const file = lockPathOf(dir);
1657
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1658
+ const owner = readOwner(file);
1659
+ if (owner && owner.pid !== process.pid && isPidAlive(owner.pid)) throw new StoreInUseError(dir, owner);
1660
+ fs.writeFileSync(file, `${JSON.stringify(mine)}\n`);
1661
+ held.add(file);
1662
+ }
1663
+ if (!exitHookInstalled) {
1664
+ exitHookInstalled = true;
1665
+ process.on("exit", releaseAll);
1666
+ }
1667
+ }
1668
+ //#endregion
1669
+ //#region src/server.mts
1670
+ const defaultLogger = childLogger(["switchboard"]);
1671
+ if (!isDotenvDisabled()) dotenv.config();
1672
+ /** Process-wide settings an edge applies once, before its first `startSwitchboard`. */
1673
+ function initSwitchboardProcess(options = {}) {
1674
+ setLogLevel(options.logLevel ?? "info");
1675
+ }
1676
+ let httpsHooksRegistered = false;
1677
+ function registerHttpsHooks() {
1678
+ if (httpsHooksRegistered) return;
1679
+ httpsHooksRegistered = true;
1680
+ register(httpsHooksPath, import.meta.url);
1681
+ }
1682
+ const PORT_FALLBACK_ATTEMPTS = 20;
1683
+ let flushIntervalWarned = false;
1684
+ function warnIgnoredFlushInterval(logger) {
1685
+ if (flushIntervalWarned) return;
1686
+ if (process.env.PGLITE_FLUSH_INTERVAL_MS === void 0) return;
1687
+ flushIntervalWarned = true;
1688
+ logger.warn("PGLITE_FLUSH_INTERVAL_MS is set but ignored: PGlite stores no longer snapshot on a timer.");
1689
+ }
1690
+ /**
1691
+ * Attempt to bind a throwaway TCP server to the given port. Resolves true if
1692
+ * the port is free, false if the OS reports it in use. Any other error is
1693
+ * surfaced so we don't silently mask real issues (permissions, bad host, …).
1694
+ */
1695
+ async function isPortAvailable(port) {
1696
+ try {
1697
+ return await probePort(port, "::");
1698
+ } catch (error) {
1699
+ if (!isNoIpv6Error(error)) throw portProbeError(port, error);
1700
+ try {
1701
+ return await probePort(port, "0.0.0.0");
1702
+ } catch (ipv4Error) {
1703
+ throw portProbeError(port, ipv4Error);
1704
+ }
1705
+ }
1706
+ }
1707
+ const isNoIpv6Error = (error) => ["EAFNOSUPPORT", "EADDRNOTAVAIL"].includes(error.code ?? "");
1708
+ const portProbeError = (port, error) => new Error(`Could not check whether port ${port} is free: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1709
+ function probePort(port, host) {
1710
+ return new Promise((resolve, reject) => {
1711
+ const tester = net.createServer();
1712
+ tester.once("error", (err) => {
1713
+ if (err.code === "EADDRINUSE" || err.code === "EACCES") resolve(false);
1714
+ else reject(err);
1715
+ });
1716
+ tester.once("listening", () => {
1717
+ tester.close(() => resolve(true));
1718
+ });
1719
+ tester.listen({
1720
+ port,
1721
+ host
1722
+ });
1723
+ });
1724
+ }
1725
+ /** The powerhouse.config.json this run reads, defaulting to the cwd copy. */
1726
+ function resolveConfigPath(configFile) {
1727
+ return configFile ?? path$1.join(process.cwd(), "powerhouse.config.json");
1728
+ }
1729
+ /**
1730
+ * The config file's `workflows.oauthApps`, client file paths made absolute
1731
+ * from the config file's folder. An unreadable file or a malformed entry
1732
+ * means none: a missing app is reported when a sign-in asks for it.
1733
+ */
1734
+ function readConfigOAuthApps(configPath, logger) {
1735
+ let raw;
1736
+ try {
1737
+ raw = getConfig(configPath).workflows?.oauthApps;
1738
+ } catch {
1739
+ return [];
1740
+ }
1741
+ return parseOAuthApps(raw, path$1.dirname(path$1.resolve(configPath)), (id, relay) => logger.warn(`workflows.oauthApps "${id}": relay ${JSON.stringify(relay)} is not an object with clientId, redirectUri and tokenUrl; ignored`));
1742
+ }
1743
+ /** `PH_KEYFRAMES` (or a caller's layer) wins whole over the project config. */
1744
+ function resolveKeyframes(configured, fromFile, configPath) {
1745
+ if (configured) return configured;
1746
+ return fromFile === void 0 ? void 0 : parseKeyframeSettings(fromFile, `${configPath} reactor.keyframes`);
1747
+ }
1748
+ function readConfigWorkflowsEnabled(configPath) {
1749
+ try {
1750
+ return getConfig(configPath).workflows?.enabled ?? false;
1751
+ } catch {
1752
+ return false;
1753
+ }
1754
+ }
1755
+ async function resolveServerPort(requested, strictPort, logger) {
1756
+ if (requested === 0 || strictPort) return requested;
1757
+ for (let i = 0; i < PORT_FALLBACK_ATTEMPTS; i++) {
1758
+ const candidate = requested + i;
1759
+ if (await isPortAvailable(candidate)) {
1760
+ if (candidate !== requested) logger.info(`Port ${requested} is in use. Falling back to port ${candidate}.`);
1761
+ return candidate;
1762
+ }
1763
+ }
1764
+ return requested;
1765
+ }
1766
+ async function createReactorKysely(opts) {
1767
+ const { reactorDbUrl, reactorPgliteDir, reactorPgliteMajor, inMemory, hostPoolSize, pgliteWorkers, pgliteSettings, openingStore, logger } = opts;
1768
+ if (reactorDbUrl && isPostgresUrl(reactorDbUrl)) {
1769
+ const connectionString = reactorDbUrl.includes("?") ? reactorDbUrl : `${reactorDbUrl}?sslmode=disable`;
1770
+ const poolSize = hostPoolSize();
1771
+ const pool = new Pool({
1772
+ connectionString,
1773
+ max: poolSize
1774
+ });
1775
+ const poolInstrumentation = instrumentPgPool(pool, "reactor-host");
1776
+ logger.info(`Using PostgreSQL for reactor storage (host pool max ${poolSize})`);
1777
+ return {
1778
+ kysely: new Kysely({ dialect: new PostgresDialect({ pool }) }),
1779
+ poolInstrumentation,
1780
+ storageFacts: POSTGRES_STORAGE_FACTS
1781
+ };
1782
+ }
1783
+ if (!reactorPgliteDir || reactorPgliteMajor === null) throw new Error("Reactor PGLite directory not resolved");
1784
+ const pglite = openingStore ?? (await createPgliteStoreFactory({
1785
+ ...REACTOR_STORE,
1786
+ major: reactorPgliteMajor,
1787
+ inMemory,
1788
+ threaded: pgliteWorkers,
1789
+ settings: pgliteSettings,
1790
+ logger
1791
+ }))(reactorPgliteDir);
1792
+ const dialectOptions = pglite instanceof ThreadedPGlite ? terminateOnPoisoned(reactorPgliteDialectOptions(logger), pglite) : reactorPgliteDialectOptions(logger);
1793
+ return {
1794
+ kysely: new Kysely({ dialect: new ClosablePGliteDialect(pglite, dialectOptions) }),
1795
+ poolInstrumentation: void 0,
1796
+ storageFacts: inMemory ? IN_MEMORY_PGLITE_STORAGE_FACTS : PGLITE_PATH_STORAGE_FACTS,
1797
+ storeMaintenance: pglite instanceof ThreadedPGlite ? pglite : maintenanceOf(pglite)
1798
+ };
1799
+ }
1800
+ /**
1801
+ * Where the two stores live — the classic resolution, relocated verbatim.
1802
+ * Classic layout: `./.ph/reactor-storage` for the reactor and
1803
+ * `.ph/read-storage` for the read model (the same names inside
1804
+ * `${userData}/.ph` under a shell's PH_USER_DATA_DIR). `dbPath` also names
1805
+ * the reactor store unless PH_REACTOR_DATABASE_URL does: with `dbPath` alone
1806
+ * both stores share one location. That is the long-standing contract of
1807
+ * `--db-path` and fine for one Postgres database, but for PGlite it is two
1808
+ * postmasters on one data dir — reported via `sharedPgliteDir` so the caller
1809
+ * warns. Not refused: changing that contract is a separate decision.
1810
+ */
1811
+ function resolvePgliteStorageDirs(opts) {
1812
+ const { dbPath, reactorDbUrl, callerReactor } = opts;
1813
+ const defaults = defaultStoreDirs({ PH_USER_DATA_DIR: opts.userDataDir }, opts.phDir);
1814
+ const readModelPath = dbPath || defaults.readModel;
1815
+ const reactorPath = reactorDbUrl || defaults.reactor;
1816
+ const reactorPgliteDir = callerReactor ? null : !reactorDbUrl || !isPostgresUrl(reactorDbUrl) ? reactorPath : null;
1817
+ const readModelPgliteDir = !dbPath || !isPostgresUrl(dbPath) ? readModelPath : null;
1818
+ const sharedPgliteDir = reactorPgliteDir !== null && readModelPgliteDir !== null && path$1.resolve(reactorPgliteDir) === path$1.resolve(readModelPgliteDir) ? path$1.resolve(reactorPgliteDir) : null;
1819
+ return {
1820
+ readModelPath,
1821
+ reactorPath,
1822
+ reactorPgliteDir,
1823
+ readModelPgliteDir,
1824
+ pgliteDirs: [reactorPgliteDir, readModelPgliteDir].filter((d) => d !== null),
1825
+ sharedPgliteDir
1826
+ };
1827
+ }
1828
+ /** The remote attachment service config for switchboard's own `/attachments/*` API; `attachments.serviceUrl` carries PH_SWITCHBOARD_PUBLIC_URL. */
1829
+ function deriveAttachmentServiceConfig(options, serverPort, renown) {
1830
+ const protocol = options.https ? "https" : "http";
1831
+ return {
1832
+ remoteUrl: options.attachmentServiceUrl ?? `${protocol}://localhost:${serverPort}`,
1833
+ jwtHandler: renown ? async (url) => renown.user ? renown.getBearerToken({
1834
+ expiresIn: 10,
1835
+ aud: url
1836
+ }) : void 0 : void 0
1837
+ };
1838
+ }
1839
+ /** Sentry starts only under SENTRY_DSN (observability.mts), and is a lot to load. */
1840
+ async function captureInSentry(error) {
1841
+ if (!process.env.SENTRY_DSN) return;
1842
+ (await import("@sentry/node")).captureException(error);
1843
+ }
1844
+ async function initServer(requestedPort, options, config, renown, renownConfig, reportError, opening) {
1845
+ const { dev, packages = [], remoteDrives = [], logger = defaultLogger } = options;
1846
+ const pluginHost = config.features.pluginHost ? createSwitchboardPluginHost({
1847
+ logger,
1848
+ options,
1849
+ config,
1850
+ renown
1851
+ }, options.pluginComposition) : null;
1852
+ if (pluginHost) {
1853
+ options = await pluginHost.transformOptions(options);
1854
+ options.mcp ??= false;
1855
+ options.workflows = {
1856
+ ...options.workflows,
1857
+ enabled: options.workflows?.enabled === true
1858
+ };
1859
+ }
1860
+ logger.level = config.logLevel;
1861
+ const dbPath = config.storage.readModel.url;
1862
+ const reactorDbUrl = config.storage.reactor.url;
1863
+ const inMemory = config.storage.inMemory;
1864
+ const pgliteSettings = {
1865
+ fsync: config.storage.pglite.fsync,
1866
+ maintenance: vacuumFullTimingOf(config.storage.pglite.vacuumFull),
1867
+ workerMemoryMb: config.storage.pglite.workerMemoryMb
1868
+ };
1869
+ const { readModelPath, reactorPgliteDir, readModelPgliteDir, pgliteDirs, sharedPgliteDir } = resolvePgliteStorageDirs({
1870
+ dbPath,
1871
+ reactorDbUrl,
1872
+ callerReactor: options.reactor !== void 0,
1873
+ userDataDir: config.storage.userDataDir
1874
+ });
1875
+ if (sharedPgliteDir !== null) logger.warn(`The reactor and read-model PGlite stores share one directory (${sharedPgliteDir}): two PGlite instances on one data dir can abort at the first checkpoint and leave the store unopenable. Set PH_REACTOR_DATABASE_URL to a separate directory, or leave dbPath unset for the classic ./.ph/reactor-storage + .ph/read-storage layout.`);
1876
+ if (!inMemory) acquireStoreLocks(pgliteDirs);
1877
+ warnIgnoredFlushInterval(logger);
1878
+ const detectedMajors = await runPglitePreflight({
1879
+ dirs: pgliteDirs,
1880
+ forcePgVersion: options.forcePgVersion,
1881
+ migratePglite: options.migratePglite,
1882
+ inMemory,
1883
+ logger
1884
+ });
1885
+ function resolvePgliteMajorForDir(dir) {
1886
+ if (options.forcePgVersion !== void 0) return options.forcePgVersion;
1887
+ const detected = detectedMajors.get(dir);
1888
+ if (detected === void 0) return 17;
1889
+ if (!isSupportedMajor(detected)) throw new Error(`Unsupported PGLite data dir at ${dir}: PG_VERSION=${detected}`);
1890
+ return detected;
1891
+ }
1892
+ const reactorPgliteMajor = reactorPgliteDir ? resolvePgliteMajorForDir(reactorPgliteDir) : null;
1893
+ const readModelPgliteMajor = readModelPgliteDir ? resolvePgliteMajorForDir(readModelPgliteDir) : null;
1894
+ const inspectionThrottle = config.inspection.callsPerMinute === void 0 ? {} : { callsPerMinute: config.inspection.callsPerMinute };
1895
+ let workerPool = resolveWorkerPoolOptions(options.workerPool, {});
1896
+ if (workerPool && options.reactor) {
1897
+ logger.warn("Worker pool configuration ignored: the caller-provided reactor owns its own executor");
1898
+ workerPool = null;
1899
+ }
1900
+ if (workerPool) {
1901
+ const issue = workerPoolIssues({
1902
+ dev: dev === true,
1903
+ workers: workerPool.numWorkers,
1904
+ projectionWorker: false,
1905
+ reactorDbUrl,
1906
+ authEnforcement: config.protocol.featureFlags.authEnforcement,
1907
+ renownSource: renownConfig.source
1908
+ }).at(0);
1909
+ if (issue) throw new Error(issue);
1910
+ }
1911
+ const unsupportedStoredDocuments = resolveUnsupportedStoredDocuments(options.unsupportedStoredDocuments, {});
1912
+ let projectionWorker = resolveProjectionWorkerOptions(options.projectionWorker, {});
1913
+ if (projectionWorker && options.reactor) {
1914
+ logger.warn("Projection worker configuration ignored: the caller-provided reactor owns its own read-model coordinator");
1915
+ projectionWorker = null;
1916
+ }
1917
+ if (projectionWorker) assertProjectionWorkerSupported({
1918
+ dev: dev === true,
1919
+ reactorDbUrl
1920
+ });
1921
+ const apiRef = { current: void 0 };
1922
+ let driveNodeView;
1923
+ const configPath = resolveConfigPath(options.configFile);
1924
+ const fileConfig = getConfig(configPath);
1925
+ const registryUrl = options.registryUrl ?? fileConfig.packageRegistryUrl;
1926
+ const registryPackages = config.packages.registryPackages;
1927
+ const dynamicModelLoading = options.dynamicModelLoading === true;
1928
+ let httpLoader;
1929
+ if (registryUrl) {
1930
+ registerHttpsHooks();
1931
+ httpLoader = new HttpPackageLoader({
1932
+ registryUrl,
1933
+ cacheDir: path$1.join(resolvePhDir(void 0, { PH_USER_DATA_DIR: config.storage.userDataDir }), "registry-packages")
1934
+ });
1935
+ for (const name of registryPackages) if (!packages.includes(name)) packages.push(name);
1936
+ }
1937
+ const registryPackageNames = new Set(registryPackages.filter(Boolean));
1938
+ const resolveRegistryModels = async (identifier) => httpLoader && registryPackageNames.has(identifier) ? (await httpLoader.cachePackage(identifier)).entries.documentModels ?? null : null;
1939
+ const reactorLogger = logger.child(["reactor"]);
1940
+ let projectionWorkerFatalFired = false;
1941
+ const onProjectionWorkerFatal = (shardId, reason) => {
1942
+ if (projectionWorkerFatalFired) return;
1943
+ projectionWorkerFatalFired = true;
1944
+ reactorLogger.error(`Projection worker ${shardId} died; shutting down so the supervisor restarts a healthy process`, reason);
1945
+ raiseSigterm();
1946
+ };
1947
+ const workflowsEnabled = options.workflows?.enabled === true;
1948
+ const privacyConfig = pluginHost ? { enabled: false } : resolvePrivacy(options.privacy, {});
1949
+ if (workflowsEnabled) {
1950
+ await assertWorkflowPackageLoadable();
1951
+ if (!packages.includes("@powerhousedao/workflow")) packages.push(WORKFLOW_PACKAGE_NAME);
1952
+ }
1953
+ let ownedReactorModule;
1954
+ const catchUpPriority = new CatchUpPriority(config.protocol.catchUpPriority === "dynamic" ? { mode: "dynamic" } : {
1955
+ mode: "fixed",
1956
+ level: config.protocol.catchUpPriority
1957
+ });
1958
+ const processorTiming = new ProcessorTimingSettings({
1959
+ level: config.protocol.processorTiming,
1960
+ windowMs: config.protocol.processorTimingWindowMs,
1961
+ slowBatchMs: config.protocol.processorSlowBatchMs
1962
+ });
1963
+ const memoryTelemetry = createMemoryTelemetry(config, reactorLogger);
1964
+ let workerModels;
1965
+ let localRenownRequest;
1966
+ const initializeClient = async (documentModels, { attachmentReferenceWriter, upgradeManifests, readModelDb }) => {
1967
+ if (options.reactor) {
1968
+ const attachmentReferenceProjection = await registerAttachmentReferenceReadModelOnModule(options.reactor, attachmentReferenceWriter);
1969
+ if (options.reactor.reactorModule) {
1970
+ new ReactorInstrumentation(options.reactor.reactorModule).start();
1971
+ reactorLogger.info("Reactor metrics instrumentation started (using caller-provided reactor)");
1972
+ }
1973
+ return {
1974
+ module: options.reactor,
1975
+ attachmentReferenceProjection
1976
+ };
1977
+ }
1978
+ const { kysely: baseKysely, poolInstrumentation, storageFacts, storeMaintenance } = await createReactorKysely({
1979
+ reactorDbUrl,
1980
+ reactorPgliteDir,
1981
+ reactorPgliteMajor,
1982
+ inMemory,
1983
+ hostPoolSize: () => config.workers.hostPoolSize,
1984
+ pgliteWorkers: options.pgliteWorkers === true,
1985
+ pgliteSettings,
1986
+ openingStore: opening.stores?.reactor,
1987
+ logger
1988
+ });
1989
+ const maxSkipThreshold = config.protocol.maxSkipThreshold;
1990
+ const hasSkipThreshold = maxSkipThreshold !== void 0;
1991
+ if (hasSkipThreshold) logger.info(`Reactor maxSkipThreshold set to ${maxSkipThreshold}`);
1992
+ const { flags: reactorFeatureFlags, enabled: enabledFeatureFlags } = reactorFeatureFlagsOf(config.protocol.featureFlags);
1993
+ if (enabledFeatureFlags.length > 0) logger.info(`Reactor feature flags enabled: ${enabledFeatureFlags.join(", ")}`);
1994
+ if (reactorFeatureFlags.undoV3 === false) logger.info("Reactor undoV3 is off: new documents take base-reducer 2");
1995
+ const reactorBuilder = new ReactorBuilder().withEventBus(new EventBus()).withKysely(baseKysely).withStorageFacts(storageFacts).withFeatures({ legacyProcessorIds: config.protocol.legacyProcessorIds }).withUnsupportedStoredDocuments(unsupportedStoredDocuments).withCatchUpPriority(catchUpPriority).withProcessorTiming(processorTiming).withMemoryTelemetry(memoryTelemetry);
1996
+ const keyframes = resolveKeyframes(config.storage.keyframes, fileConfig.reactor?.keyframes, configPath);
1997
+ if (keyframes) {
1998
+ logger.info(`Keyframes: default ${JSON.stringify(keyframes.default ?? {})}, ${Object.keys(keyframes.types ?? {}).length} document type(s) with their own rule`);
1999
+ reactorBuilder.withKeyframes(keyframes);
2000
+ }
2001
+ if (storeMaintenance) reactorBuilder.withStoreMaintenance(storeMaintenance);
2002
+ if (poolInstrumentation) reactorBuilder.withInstrumentedPool(poolInstrumentation);
2003
+ const clientBuilder = new ReactorClientBuilder().withReactorBuilder(reactorBuilder);
2004
+ const vetraDocumentModels = dev ? Object.values(await import("@powerhousedao/vetra/document-models")).filter((m) => typeof m === "object" && m !== null && "documentModel" in m && "reducer" in m) : [];
2005
+ applySwitchboardReactorDefaults(reactorBuilder, clientBuilder, {
2006
+ signalHandlers: options.signalHandlers,
2007
+ documentModels: [...documentModels, ...vetraDocumentModels],
2008
+ upgradeManifests,
2009
+ executorConfig: {
2010
+ ...hasSkipThreshold ? { maxSkipThreshold } : {},
2011
+ featureFlags: reactorFeatureFlags
2012
+ },
2013
+ documentModelLoader: httpLoader && dynamicModelLoading ? httpLoader.documentModelLoader : void 0,
2014
+ logger: reactorLogger,
2015
+ signer: renown ? getRenownSignerConfig(renown, options.identity?.keypairPath) : void 0,
2016
+ createSignaturePolicy: createSignaturePolicyFor(config.protocol.createSignaturePolicy, {
2017
+ hasSigner: renown !== null,
2018
+ logger
2019
+ }),
2020
+ trustPolicy: reactorFeatureFlags.authEnforcement ? await getRenownTrustPolicyConfig(renownConfig.source === "self" ? {
2021
+ source: "self",
2022
+ request: (query, variables) => localRenownRequest ? localRenownRequest(query, variables) : Promise.reject(/* @__PURE__ */ new Error("The local renown read model is not bound yet"))
2023
+ } : {
2024
+ source: "remote",
2025
+ renownUrl: renownConfig.url,
2026
+ switchboardUrl: renownConfig.switchboardUrl
2027
+ }, renown) : getDelegationTrustPolicyConfig(renown)
2028
+ });
2029
+ if (workerPool || projectionWorker || workflowsEnabled) {
2030
+ const sources = await resolveWorkerModelSources(packages, reactorLogger, { resolveRemote: resolveRegistryModels });
2031
+ reactorBuilder.withDocumentModelSources(workerPool || projectionWorker ? sources : await keepImportableSources(sources, reactorLogger));
2032
+ }
2033
+ workerModels = modelManifestSource(reactorBuilder);
2034
+ if (workerPool) {
2035
+ if (!reactorDbUrl) throw new Error("unreachable: worker pool enabled without a reactor database URL");
2036
+ reactorBuilder.withWorkerPool({
2037
+ numWorkers: workerPool.numWorkers,
2038
+ db: buildWorkerDbConfig(reactorDbUrl, workerPool)
2039
+ });
2040
+ reactorLogger.info(`Executor worker pool enabled: ${workerPool.numWorkers} worker threads${workerPool.mode === "auto" ? " (auto-sized from cores)" : ""}`);
2041
+ }
2042
+ reactorBuilder.withReadModelFactory(async ({ operationIndex, writeCache, processorManagerConsistencyTracker }) => {
2043
+ const nodeProcessor = new NodeProcessor(baseKysely, REACTOR_SCHEMA, operationIndex, writeCache, processorManagerConsistencyTracker);
2044
+ await nodeProcessor.init();
2045
+ return nodeProcessor;
2046
+ });
2047
+ registerAttachmentReferenceReadModel(reactorBuilder, {
2048
+ baseKysely,
2049
+ attachmentReferenceWriter
2050
+ });
2051
+ if (projectionWorker) {
2052
+ if (!reactorDbUrl) throw new Error("unreachable: projection worker enabled without a reactor database URL");
2053
+ const db = {
2054
+ ...buildWorkerDbConfig(reactorDbUrl, {
2055
+ dbPoolSizePerWorker: projectionWorker.dbPoolSize,
2056
+ acquireTimeoutMs: workerPool?.acquireTimeoutMs ?? 5e3
2057
+ }),
2058
+ applicationName: "switchboard-projection"
2059
+ };
2060
+ reactorBuilder.withReadModelCoordinatorFactory(createHybridProjectionCoordinatorFactory({
2061
+ shardCount: 1,
2062
+ poolSize: projectionWorker.dbPoolSize,
2063
+ db,
2064
+ onFatal: onProjectionWorkerFatal
2065
+ }));
2066
+ reactorLogger.info(`Projection worker enabled: 1 worker thread, pool size ${projectionWorker.dbPoolSize}`);
2067
+ }
2068
+ reactorBuilder.withShutdownHook(async () => {
2069
+ if (apiRef.current) await apiRef.current.dispose();
2070
+ });
2071
+ const reactorDriveSchemaDb = baseKysely.withSchema(REACTOR_SCHEMA);
2072
+ const nodeView = new DriveNodeView(reactorDriveSchemaDb);
2073
+ driveNodeView = nodeView;
2074
+ clientBuilder.withDriveNodeSource(nodeView).withDriveWriteStrategy(REACTOR_DRIVE_DOCUMENT_TYPE, createReactorDriveWriteStrategy);
2075
+ let module;
2076
+ try {
2077
+ module = await withProgressHeartbeat({
2078
+ logger,
2079
+ label: "Starting the reactor (migrations, document view, indexer, processors)"
2080
+ }, () => clientBuilder.buildModule());
2081
+ } catch (error) {
2082
+ try {
2083
+ await baseKysely.destroy();
2084
+ } catch (destroyError) {
2085
+ logger.error("Aborting boot: reactor database destroy failed: @error", destroyError);
2086
+ }
2087
+ if (UnsupportedStoredProtocolError.isError(error)) throw new StoredDocumentsRefusedError(error);
2088
+ throw error;
2089
+ }
2090
+ if (module.reactorModule) {
2091
+ const instrumentation = new ReactorInstrumentation(module.reactorModule);
2092
+ instrumentation.start();
2093
+ reactorLogger.info("Reactor metrics instrumentation started");
2094
+ memoryTelemetry.addGauge("otel", () => instrumentation.stats());
2095
+ }
2096
+ const reactorDriveClient = new ReactorDriveClient({
2097
+ read: module.read,
2098
+ write: module.write,
2099
+ readModel: nodeView
2100
+ });
2101
+ ownedReactorModule = module;
2102
+ if (options.fatalErrorShutdown) installFatalErrorShutdown(logger);
2103
+ const permissionsDb = baseKysely.withSchema(REACTOR_SCHEMA);
2104
+ try {
2105
+ if (readModelDb) await withProgressHeartbeat({
2106
+ logger,
2107
+ label: "Moving the permission tables"
2108
+ }, () => backfillPermissionTables(readModelDb, permissionsDb, logger));
2109
+ } catch (error) {
2110
+ logger.error("Aborting boot: permission tables backfill failed: @error", error);
2111
+ try {
2112
+ await module.reactorModule?.shutdown();
2113
+ } catch (shutdownError) {
2114
+ logger.error("Aborting boot: reactor shutdown failed: @error", shutdownError);
2115
+ }
2116
+ throw error;
2117
+ }
2118
+ return {
2119
+ module,
2120
+ reactorDriveClient,
2121
+ driveNodes: nodeView,
2122
+ attachmentReferenceProjection: { status: "available" },
2123
+ permissionsDb
2124
+ };
2125
+ };
2126
+ const abortBoot = async (api) => {
2127
+ let disposed;
2128
+ const disposeApi = () => disposed ??= api.dispose();
2129
+ apiRef.current = { dispose: disposeApi };
2130
+ const owned = ownedReactorModule;
2131
+ if (owned?.reactorModule) try {
2132
+ await owned.reactorModule.shutdown();
2133
+ } catch (error) {
2134
+ logger.error("Aborting boot: reactor shutdown failed: @error", error);
2135
+ }
2136
+ else if (owned) try {
2137
+ await owned.reactor.kill().completed;
2138
+ } catch (error) {
2139
+ logger.error("Aborting boot: reactor shutdown failed: @error", error);
2140
+ }
2141
+ try {
2142
+ await disposeApi();
2143
+ } catch (error) {
2144
+ logger.error("Aborting boot: api dispose failed: @error", error);
2145
+ }
2146
+ };
2147
+ let localCredentialCheck;
2148
+ const verifyCredential = renownConfig.source === "self" ? (params) => localCredentialCheck ? localCredentialCheck(params) : Promise.reject(/* @__PURE__ */ new Error("The local renown read model is not bound yet")) : void 0;
2149
+ let defaultDriveUrl = void 0;
2150
+ const basePath = process.cwd();
2151
+ const reporting = {
2152
+ logger,
2153
+ report: reportError
2154
+ };
2155
+ let vite;
2156
+ let viteLoader;
2157
+ if (dev) {
2158
+ const { VitePackageLoader, createViteLogger, startViteServer } = await import("@powerhousedao/reactor-api/vite");
2159
+ vite = await startViteServer(process.cwd(), createViteLogger(logger));
2160
+ viteLoader = VitePackageLoader.build(vite, {
2161
+ resolveFrom: [import.meta.url],
2162
+ reportError
2163
+ });
2164
+ }
2165
+ const vetraProcessorFactory = dev ? (await import("@powerhousedao/vetra/processors")).processorFactory : void 0;
2166
+ if (!options.disableLocalPackages) packages.push(basePath);
2167
+ const packageLoaders = [];
2168
+ if (viteLoader) packageLoaders.push(viteLoader);
2169
+ else packageLoaders.push(new ImportPackageLoader());
2170
+ if (httpLoader) {
2171
+ packageLoaders.push(httpLoader);
2172
+ for (const name of registryPackages) if (!packages.includes(name)) packages.push(name);
2173
+ }
2174
+ const apiLogger = logger.child(["reactor-api"]);
2175
+ let pgliteFactory;
2176
+ let storeFailed = () => void 0;
2177
+ const storesFailed = new Promise((_, reject) => {
2178
+ storeFailed = reject;
2179
+ });
2180
+ storesFailed.catch(() => void 0);
2181
+ if (readModelPgliteDir && readModelPgliteMajor !== null) {
2182
+ const storeOptions = {
2183
+ inMemory,
2184
+ threaded: options.pgliteWorkers === true,
2185
+ settings: pgliteSettings,
2186
+ logger
2187
+ };
2188
+ const openReadStore = await createPgliteStoreFactory({
2189
+ ...storeOptions,
2190
+ ...READ_STORE,
2191
+ major: readModelPgliteMajor
2192
+ });
2193
+ const openReactorStore = storeOptions.threaded && pgliteWorkerEntryPath !== null && sharedPgliteDir === null && reactorPgliteDir && reactorPgliteMajor !== null ? await createPgliteStoreFactory({
2194
+ ...storeOptions,
2195
+ ...REACTOR_STORE,
2196
+ major: reactorPgliteMajor
2197
+ }) : void 0;
2198
+ pgliteFactory = (connectionString) => {
2199
+ const dir = connectionString ?? readModelPgliteDir;
2200
+ if (!openReactorStore || !reactorPgliteDir || dir !== readModelPgliteDir) return openReadStore(dir);
2201
+ opening.stores ??= openStoresTogether(() => openReactorStore(reactorPgliteDir), () => openReadStore(dir));
2202
+ opening.stores.failed.catch(storeFailed);
2203
+ return opening.stores.readModel;
2204
+ };
2205
+ }
2206
+ const startingApi = initializeAndStartAPI(initializeClient, {
2207
+ port: requestedPort,
2208
+ dbPath: readModelPath,
2209
+ pgliteFactory,
2210
+ https: options.https,
2211
+ packageLoaders: packageLoaders.length > 0 ? packageLoaders : void 0,
2212
+ packages,
2213
+ processorConfig: options.processorConfig,
2214
+ ...renown ? { hostSigner: renown.signer } : {},
2215
+ processors: vetraProcessorFactory ? { "@powerhousedao/vetra": [vetraProcessorFactory] } : {},
2216
+ configFile: configPath,
2217
+ server: {
2218
+ basePath: config.server.basePath,
2219
+ gatewayAdapter: config.server.gatewayAdapter,
2220
+ publicUrl: config.server.publicUrl,
2221
+ host: config.server.host
2222
+ },
2223
+ auth: {
2224
+ ...authSectionOf(config.auth),
2225
+ stateDir: resolvePhDir(void 0, config.storage.userDataDir ? { PH_USER_DATA_DIR: config.storage.userDataDir } : process.env)
2226
+ },
2227
+ attachments: { storage: config.attachments.storage },
2228
+ mcp: options.mcp ?? true,
2229
+ inspection: options.inspection === false ? false : {
2230
+ throttle: inspectionThrottle,
2231
+ admin: config.inspection.admin
2232
+ },
2233
+ logger: apiLogger,
2234
+ reportError,
2235
+ enableDocumentModelSubgraphs: options.enableDocumentModelSubgraphs,
2236
+ hostValidation: options.hostValidation,
2237
+ hostRefreshesSupergraph: true,
2238
+ renown: renownConfig,
2239
+ verifyCredential
2240
+ }, "switchboard");
2241
+ const api = await Promise.race([startingApi, storesFailed]);
2242
+ apiRef.current = api;
2243
+ const serverPort = api.port;
2244
+ if (renownConfig.source === "self") {
2245
+ const { graphqlManager: manager } = api;
2246
+ if (!manager.hasSubgraphHandler(RENOWN_READ_MODEL_SUBGRAPH) && manager.getSubgraphByName(RENOWN_READ_MODEL_SUBGRAPH)) try {
2247
+ await manager.updateRouter(true);
2248
+ } catch (error) {
2249
+ await abortBoot(api);
2250
+ throw error;
2251
+ }
2252
+ if (!manager.hasSubgraphHandler(RENOWN_READ_MODEL_SUBGRAPH)) {
2253
+ await abortBoot(api);
2254
+ throw new Error(`Renown credential verification is set to "self" (auth.renown.source or RENOWN_SOURCE) but no loaded package serves the "${RENOWN_READ_MODEL_SUBGRAPH}" subgraph. Install one (@powerhousedao/renown-package) or set RENOWN_SOURCE=remote.`);
2255
+ }
2256
+ localRenownRequest = (query, variables) => manager.executeSubgraphQuery(RENOWN_READ_MODEL_SUBGRAPH, query, variables);
2257
+ localCredentialCheck = createLocalCredentialVerifier(localRenownRequest, { onError: (error) => logger.error("Renown read model query failed: @error", error) });
2258
+ logger.info("Renown credentials will be verified against this switchboard's own renown read model");
2259
+ }
2260
+ let attachmentService;
2261
+ if (pluginHost) {
2262
+ pluginHost.ctx.api = api;
2263
+ pluginHost.ctx.serverPort = serverPort;
2264
+ await pluginHost.observe("onHttpMounting");
2265
+ attachmentService = pluginHost.ctx.attachmentService;
2266
+ } else {
2267
+ registerAttachmentRoutes(api, { config: config.attachments });
2268
+ attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(options, serverPort, renown));
2269
+ }
2270
+ if (process.env.SENTRY_DSN) api.httpAdapter.setupSentryErrorHandler(await import("@sentry/node"));
2271
+ const { client, read, write, graphqlManager, documentModelRegistry } = api;
2272
+ const lateSubgraphs = [];
2273
+ if (pluginHost) {
2274
+ pluginHost.ctx.client = client;
2275
+ pluginHost.ctx.read = read;
2276
+ pluginHost.ctx.write = write;
2277
+ pluginHost.ctx.graphqlManager = graphqlManager;
2278
+ pluginHost.ctx.lateSubgraphs = lateSubgraphs;
2279
+ pluginHost.ctx.reactorClientModule = options.reactor ?? ownedReactorModule;
2280
+ await pluginHost.observe("onReactorReady");
2281
+ }
2282
+ let workflows;
2283
+ let workflowsRetry;
2284
+ const composeWorkflows = () => composeWorkflowRuntime({
2285
+ reactorClient: client,
2286
+ clientModule: options.reactor ?? ownedReactorModule,
2287
+ relationalDb: api.relationalDb,
2288
+ secretsKeyFile: readModelPgliteDir === null ? false : void 0,
2289
+ storageId: readModelPgliteDir === null ? readModelPath : path$1.resolve(readModelPath),
2290
+ attachments: createAttachmentClient(api.attachments.service),
2291
+ attachmentAccess: api.attachmentAccess,
2292
+ webhooks: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME).webhooks,
2293
+ http: api.httpRoutes.scopeFor(WORKFLOW_PACKAGE_NAME),
2294
+ oauthApps: options.workflows?.oauthApps ?? readConfigOAuthApps(resolveConfigPath(options.configFile), logger),
2295
+ authorizationService: api.authorizationService,
2296
+ indexQueries: api.graphqlManager,
2297
+ pieces: api.packageManager,
2298
+ pieceRegistryUrl: registryUrl,
2299
+ models: workerModels,
2300
+ reactorThreads: (workerPool?.numWorkers ?? 0) + (projectionWorker ? 1 : 0),
2301
+ logger: logger.child(["workflow-runtime"]),
2302
+ exclusiveJournal: readModelPgliteDir !== null,
2303
+ onSingletonLost: workflowSingletonLossHandler(logger),
2304
+ telemetry: {
2305
+ tracer: trace.getTracer(WORKFLOW_TELEMETRY_SCOPE),
2306
+ meter: metrics.getMeter(WORKFLOW_TELEMETRY_SCOPE)
2307
+ }
2308
+ });
2309
+ const registerWorkflowSubgraph = (composed) => {
2310
+ const WorkflowRuntimeSubgraph = composed.subgraph;
2311
+ const workflowSubgraph = new WorkflowRuntimeSubgraph({
2312
+ readClient: read,
2313
+ reactorClient: client,
2314
+ http: graphqlManager.scopeForPackage(WORKFLOW_PACKAGE_NAME),
2315
+ relationalDb: api.relationalDb,
2316
+ analyticsStore: void 0,
2317
+ graphqlManager,
2318
+ syncManager: api.syncManager,
2319
+ authorizationService: graphqlManager.getAuthorizationService(),
2320
+ path: graphqlManager.getBasePath(),
2321
+ attachments: api.attachmentClientProvider
2322
+ });
2323
+ return graphqlManager.registerSubgraphInstance(workflowSubgraph, "graphql", false).catch((error) => {
2324
+ reportFailure(reporting, error, "Failed to register workflow-runtime subgraph: @error");
2325
+ });
2326
+ };
2327
+ if (!pluginHost && workflowsEnabled) try {
2328
+ workflows = await composeWorkflows();
2329
+ } catch (error) {
2330
+ if (!isWorkflowSingletonConflict(error)) throw error;
2331
+ logger.warn(`Workflows are enabled but another live process ("${error.owner ?? "unknown"}") holds the workflow singleton until ${error.expiresAt ?? "unknown"}. This Switchboard has booted WITHOUT the workflow runtime: no trigger of any kind fires here, and the workflow GraphQL face is absent. Everything else serves normally. Stop the other owner, or set PH_WORKFLOWS_SINGLETON_OWNER to the same stable name on the slot that owns workflows. This Switchboard retries the claim and starts workflows once the lease comes free.`);
2332
+ workflowsRetry = retryWorkflowSingleton({
2333
+ compose: composeWorkflows,
2334
+ onComposed: async (composed) => {
2335
+ try {
2336
+ await composed.start();
2337
+ } catch (error) {
2338
+ try {
2339
+ await composed.stop();
2340
+ } catch (stopError) {
2341
+ logger.error("Stopping the late workflow runtime failed: @error", stopError);
2342
+ }
2343
+ throw error;
2344
+ }
2345
+ logger.info("Workflow runtime started");
2346
+ workflows = composed;
2347
+ await registerWorkflowSubgraph(composed);
2348
+ try {
2349
+ await graphqlManager.updateRouter(true);
2350
+ } catch (error) {
2351
+ reportFailure(reporting, error, "Mounting the late workflow-runtime subgraph failed: @error");
2352
+ }
2353
+ },
2354
+ logger
2355
+ });
2356
+ }
2357
+ if (workflows) {
2358
+ lateSubgraphs.push(registerWorkflowSubgraph(workflows));
2359
+ const runtime = workflows;
2360
+ await withProgressHeartbeat({
2361
+ logger,
2362
+ label: "Starting the workflow runtime"
2363
+ }, () => runtime.start());
2364
+ logger.info("Workflow runtime started");
2365
+ api.inspection?.facts.setWorkflows(true);
2366
+ }
2367
+ if (pluginHost) {
2368
+ pluginHost.ctx.workflowsOrchestration = {
2369
+ enabled: options.workflows?.enabled === true,
2370
+ composeWorkflows,
2371
+ registerWorkflowSubgraph,
2372
+ updateRouter: () => graphqlManager.updateRouter(true),
2373
+ reportMountFailure: (error) => reportFailure(reporting, error, "Mounting the late workflow-runtime subgraph failed: @error"),
2374
+ setWorkflowsFact: () => api.inspection?.facts.setWorkflows(true)
2375
+ };
2376
+ try {
2377
+ await pluginHost.observe("onSubgraphsRegistering");
2378
+ } catch (error) {
2379
+ await pluginHost.ctx.workflowsRetry?.stop();
2380
+ await pluginHost.ctx.workflows?.stop();
2381
+ await abortBoot(api);
2382
+ throw error;
2383
+ }
2384
+ }
2385
+ let privacy;
2386
+ if (!pluginHost && privacyConfig.enabled) {
2387
+ const signer = options.reactor ? options.privacy?.signer : options.privacy?.signer ?? renown?.signer;
2388
+ try {
2389
+ privacy = await startPrivacy({
2390
+ config: privacyConfig,
2391
+ reactorModule: (options.reactor ?? ownedReactorModule)?.reactorModule,
2392
+ signer,
2393
+ authorizationService: api.authorizationService,
2394
+ documentPermissionService: api.documentPermissionService,
2395
+ graphqlManager,
2396
+ reactorClient: client,
2397
+ logger: logger.child(["privacy"])
2398
+ });
2399
+ } catch (error) {
2400
+ await workflowsRetry?.stop();
2401
+ await workflows?.stop();
2402
+ await abortBoot(api);
2403
+ throw error;
2404
+ }
2405
+ }
2406
+ const stopCatchUpLoad = ownedReactorModule ? feedCatchUpPriority(catchUpPriority, api.httpServer) : () => {};
2407
+ const stopTimingLog = startOwnedTimingLog(ownedReactorModule?.reactorModule, processorTiming, config.protocol.processorTimingLogMs, reactorLogger);
2408
+ if (ownedReactorModule?.reactorModule && config.telemetry.memory.enabled) memoryTelemetry.start();
2409
+ let apiDrained;
2410
+ const drainApi = () => apiDrained ??= (async () => {
2411
+ stopCatchUpLoad();
2412
+ stopTimingLog();
2413
+ memoryTelemetry.stop();
2414
+ if (pluginHost) await pluginHost.observe("onShutdown");
2415
+ await privacy?.stop();
2416
+ await workflowsRetry?.stop();
2417
+ await workflows?.stop();
2418
+ await api.dispose();
2419
+ })();
2420
+ apiRef.current = { dispose: drainApi };
2421
+ const ownedReactor = ownedReactorModule?.reactorModule;
2422
+ const shutdown = ownedReactor ? () => ownedReactor.shutdown() : drainApi;
2423
+ if (httpLoader) {
2424
+ const packageManagementService = new PackageManagementService({
2425
+ defaultRegistryUrl: registryUrl,
2426
+ httpLoader,
2427
+ documentModelRegistry,
2428
+ packageManager: api.packageManager
2429
+ });
2430
+ packageManagementService.setOnModelsChanged(() => {
2431
+ graphqlManager.regenerateDocumentModelSubgraphs().catch((error) => {
2432
+ reportFailure(reporting, error, "Failed to regenerate document model subgraphs: @error");
2433
+ });
2434
+ });
2435
+ const packagesSubgraph = new PackagesSubgraph({
2436
+ relationalDb: void 0,
2437
+ analyticsStore: void 0,
2438
+ readClient: read,
2439
+ reactorClient: client,
2440
+ graphqlManager,
2441
+ syncManager: api.syncManager,
2442
+ path: graphqlManager.getBasePath(),
2443
+ authorizationService: graphqlManager.getAuthorizationService(),
2444
+ packageManagementService,
2445
+ http: graphqlManager.scopeForPackage("@powerhousedao/switchboard"),
2446
+ attachments: api.attachmentClientProvider
2447
+ });
2448
+ lateSubgraphs.push(graphqlManager.registerSubgraphInstance(packagesSubgraph, "graphql", false).catch((error) => {
2449
+ reportFailure(reporting, error, "Failed to register packages subgraph: @error");
2450
+ }));
2451
+ }
2452
+ if (driveNodeView) {
2453
+ graphqlManager.setAdditionalContextFields({ readModel: driveNodeView });
2454
+ const authorizationService = graphqlManager.getAuthorizationService();
2455
+ const reactorDriveSubgraph = {
2456
+ name: REACTOR_DRIVE_SUBGRAPH_NAME,
2457
+ path: graphqlManager.getBasePath(),
2458
+ resolvers: createReactorDriveResolvers({
2459
+ reactorClient: client,
2460
+ readModel: driveNodeView,
2461
+ hostCanRead: (documentId, address) => authorizationService.canRead(documentId, address)
2462
+ }),
2463
+ typeDefs: reactorDriveSubgraphTypeDefs,
2464
+ readClient: read,
2465
+ reactorClient: client,
2466
+ relationalDb: void 0
2467
+ };
2468
+ lateSubgraphs.push(graphqlManager.registerSubgraphInstance(reactorDriveSubgraph, "graphql", false).catch((error) => {
2469
+ reportFailure(reporting, error, "Failed to register reactor-drive subgraph: @error");
2470
+ }));
2471
+ }
2472
+ if (options.drive) {
2473
+ if (!renown) throw new Error("Cannot create default drive without Renown identity");
2474
+ defaultDriveUrl = await ensureDrive(client, options.drive, serverPort, logger);
2475
+ }
2476
+ runDetached("Marking the API ready", async () => {
2477
+ await Promise.allSettled(lateSubgraphs);
2478
+ try {
2479
+ await graphqlManager.updateRouter(true);
2480
+ } catch (error) {
2481
+ reportFailure(reporting, error, "Final router update before readiness failed: @error");
2482
+ }
2483
+ try {
2484
+ await options.readyAfter;
2485
+ } catch (error) {
2486
+ reportFailure(reporting, error, "Not ready: the drives seeded after start failed: @error");
2487
+ return;
2488
+ }
2489
+ api.readiness.markReady();
2490
+ }, reporting);
2491
+ if (vite) api.httpAdapter.mountRawMiddleware(vite.middlewares);
2492
+ if (remoteDrives.length > 0) for (const remoteDriveUrl of remoteDrives) {
2493
+ let driveId;
2494
+ try {
2495
+ const { syncManager } = api;
2496
+ const parsed = parseDriveUrl(remoteDriveUrl);
2497
+ driveId = parsed.driveId;
2498
+ const remoteName = `remote-drive-${driveId}-${crypto.randomUUID()}`;
2499
+ await syncManager.add(remoteName, DriveCollectionId.forDrive(driveId), {
2500
+ type: "gql",
2501
+ parameters: { url: parsed.graphqlEndpoint }
2502
+ });
2503
+ logger.debug("Remote drive @remoteDriveUrl synced", remoteDriveUrl);
2504
+ } catch (error) {
2505
+ if (error instanceof Error && error.message.includes("already exists")) {
2506
+ logger.debug("Remote drive already added: @remoteDriveUrl", remoteDriveUrl);
2507
+ driveId = remoteDriveUrl.split("/").pop();
2508
+ } else logger.error("Failed to connect to remote drive @remoteDriveUrl: @error", remoteDriveUrl, error);
2509
+ } finally {
2510
+ if (!defaultDriveUrl && driveId) defaultDriveUrl = `${options.https ? "https" : "http"}://localhost:${serverPort}/d/${driveId}`;
2511
+ }
2512
+ }
2513
+ if (pluginHost) await pluginHost.observe("onDrivesReady");
2514
+ return {
2515
+ defaultDriveUrl,
2516
+ api,
2517
+ reactor: client,
2518
+ attachmentService,
2519
+ attachmentReferenceProjection: api.attachmentReferenceProjection,
2520
+ get workflowTriggers() {
2521
+ return (workflows ?? pluginHost?.ctx.workflows)?.triggers;
2522
+ },
2523
+ workflowsEnabled,
2524
+ modelManifest: () => workerModels?.modelManifest() ?? [],
2525
+ privacy: (() => {
2526
+ const running = privacy ?? pluginHost?.ctx.privacy;
2527
+ return running ? { erasure: running.erasure } : void 0;
2528
+ })(),
2529
+ mcpEnabled: options.mcp !== false,
2530
+ inspectionEnabled: options.inspection !== false,
2531
+ inspector: api.inspection?.inspector,
2532
+ renown,
2533
+ port: serverPort,
2534
+ shutdown
2535
+ };
2536
+ }
2537
+ /**
2538
+ * Boot the switchboard HTTP/GraphQL/MCP stack on top of a reactor.
2539
+ *
2540
+ * If `options.reactor` is provided, the switchboard reuses it instead of
2541
+ * building its own — the caller then owns the reactor's lifecycle and is
2542
+ * responsible for invoking `SwitchboardReactor.shutdown()` from their own
2543
+ * teardown / SIGINT path. The switchboard will not reach into the caller's
2544
+ * reactor; killing the reactor alone leaves the api/GraphQL/MCP resources
2545
+ * dangling until the process exits.
2546
+ *
2547
+ * When `options.reactor` is omitted, the switchboard builds and owns the
2548
+ * reactor. `shutdown()` on the returned handle then runs the reactor
2549
+ * module's `shutdown()`: `kill()`, the `withShutdownHook` chain that drains
2550
+ * the api (HTTP server, GraphQL, MCP, attachments, read-model db), then the
2551
+ * reactor database. It does not exit the process. It is the same memoized
2552
+ * teardown the SIGINT/SIGTERM handlers (`withSignalHandlers`) run, so calling
2553
+ * it twice, or receiving a signal around it, tears down once.
2554
+ */
2555
+ const startSwitchboard = async (input = {}, deps = {}) => {
2556
+ assertConfigShape(input);
2557
+ const configPath = resolveConfigPath(input.configFile);
2558
+ const fileConfig = getConfig(configPath);
2559
+ const config = switchboardConfigSchema.parse(mergeSwitchboardConfig({ auth: {
2560
+ enabled: fileConfig.auth?.enabled,
2561
+ admins: fileConfig.auth?.admins
2562
+ } }, input));
2563
+ const logger = deps.logger ?? defaultLogger;
2564
+ if (disableWasmWrapperTiering()) logger.info("Wasm wrapper tier-up off on Node 24 (nodejs/node#66366)");
2565
+ if (process.env.PYROSCOPE_SERVER_ADDRESS) await initProfilerFromEnv(process.env).catch((error) => logger.error("Error starting profiler: @error", error));
2566
+ const serverPort = await resolveServerPort(config.server.port, config.server.strictPort, logger);
2567
+ const options = serverOptionsOf(config, deps);
2568
+ if (!config.features.pluginHost) {
2569
+ options.mcp = config.features.mcp ?? true;
2570
+ options.workflows = { enabled: config.features.workflows ?? readConfigWorkflowsEnabled(configPath) };
2571
+ }
2572
+ const renownConfig = resolveRenownConfig(renownLayers(fileConfig.auth?.renown, config.auth.renown), {}, logger);
2573
+ const userDataDir = config.storage.userDataDir;
2574
+ options.identity = {
2575
+ ...options.identity,
2576
+ baseUrl: options.identity?.baseUrl ?? renownConfig.url,
2577
+ keypairPath: options.identity?.keypairPath ?? (userDataDir ? path$1.join(resolvePhDir(void 0, { PH_USER_DATA_DIR: userDataDir }), ".keypair.json") : void 0)
2578
+ };
2579
+ logger.info("Feature flags: @flags", JSON.stringify({
2580
+ DOCUMENT_MODEL_SUBGRAPHS_ENABLED: options.enableDocumentModelSubgraphs,
2581
+ MCP_ENABLED: options.mcp,
2582
+ INSPECTION_ENABLED: options.inspection,
2583
+ PH_PGLITE_WORKERS: options.pgliteWorkers,
2584
+ PH_WORKFLOWS_ENABLED: options.workflows?.enabled
2585
+ }, null, 2));
2586
+ let renown = null;
2587
+ try {
2588
+ renown = await initRenown({
2589
+ ...options.identity,
2590
+ userDataDir
2591
+ });
2592
+ } catch (e) {
2593
+ logger.warn("Failed to initialize ConnectCrypto: @error", e);
2594
+ if (options.identity.requireExisting) throw new Error("Identity required but failed to initialize. Run \"ph login\" first.", { cause: e });
2595
+ }
2596
+ const reportError = deps.reportError ?? ((error) => {
2597
+ captureInSentry(error);
2598
+ });
2599
+ const opening = {};
2600
+ try {
2601
+ return await initServer(serverPort, options, config, renown, renownConfig, reportError, opening);
2602
+ } catch (e) {
2603
+ await opening.stores?.close();
2604
+ await captureInSentry(e);
2605
+ if (StoredDocumentsRefusedError.isError(e)) logger.error(e.message);
2606
+ else logger.error("App crashed: @error", e);
2607
+ throw e;
2608
+ }
2609
+ };
2610
+ function assertConfigShape(input) {
2611
+ const unknown = Object.keys(input).filter((key) => !(key in switchboardConfigSchema.shape));
2612
+ if (unknown.length > 0) throw new Error(`startSwitchboard(config, deps) got unknown config keys: ${unknown.join(", ")}. It takes the @powerhousedao/switchboard/config shape; runtime objects go in deps.`);
2613
+ }
2614
+ /** The options view plugins transform, from the config and deps. */
2615
+ function serverOptionsOf(config, deps) {
2616
+ const { executor, projection } = config.workers;
2617
+ return {
2618
+ reactor: deps.reactor,
2619
+ fatalErrorShutdown: deps.fatalErrorShutdown,
2620
+ signalHandlers: deps.signalHandlers,
2621
+ readyAfter: deps.readyAfter,
2622
+ pluginComposition: deps.pluginComposition,
2623
+ logger: deps.logger,
2624
+ registryUrl: config.packages.registryUrl,
2625
+ configFile: config.configFile,
2626
+ port: config.server.port,
2627
+ strictPort: config.server.strictPort,
2628
+ dev: config.server.dev,
2629
+ dbPath: config.storage.readModel.url,
2630
+ drive: config.drive,
2631
+ packages: [...config.packages.list],
2632
+ remoteDrives: [...config.remoteDrives],
2633
+ https: config.server.https,
2634
+ identity: config.identity,
2635
+ attachmentServiceUrl: config.attachments.serviceUrl,
2636
+ mcp: config.features.mcp,
2637
+ inspection: config.inspection.enabled,
2638
+ pgliteWorkers: config.storage.pglite.workers,
2639
+ workflows: config.features.workflows === void 0 ? void 0 : { enabled: config.features.workflows },
2640
+ privacy: {
2641
+ enabled: config.features.privacy.enabled,
2642
+ deploymentSecret: config.features.privacy.deploymentSecret,
2643
+ intervalMs: config.features.privacy.intervalMs,
2644
+ deadlineMs: config.features.privacy.deadlineMs,
2645
+ markerGraceMs: config.features.privacy.markerGraceMs,
2646
+ purgeTimeoutMs: config.features.privacy.purgeTimeoutMs,
2647
+ signer: deps.privacySigner
2648
+ },
2649
+ processorConfig: config.processorConfig,
2650
+ disableLocalPackages: config.packages.disableLocal,
2651
+ enableDocumentModelSubgraphs: config.features.documentModelSubgraphs,
2652
+ dynamicModelLoading: config.packages.dynamic,
2653
+ hostValidation: config.packages.hostValidation,
2654
+ migratePglite: config.storage.migratePglite,
2655
+ forcePgVersion: config.storage.forcePgVersion,
2656
+ workerPool: {
2657
+ numWorkers: executor.count,
2658
+ dbPoolSizePerWorker: executor.poolSize,
2659
+ acquireTimeoutMs: executor.acquireTimeoutMs
2660
+ },
2661
+ projectionWorker: {
2662
+ enabled: projection.enabled,
2663
+ dbPoolSize: projection.poolSize
2664
+ },
2665
+ unsupportedStoredDocuments: config.protocol.unsupportedStoredDocuments
2666
+ };
2667
+ }
2668
+ /** reactor-api's auth section; renown is resolved here, not there. */
2669
+ function authSectionOf(auth) {
2670
+ const { renown: _renown, ...section } = auth;
2671
+ return section;
2672
+ }
2673
+ if (import.meta.main) {
2674
+ const config = switchboardConfigFromEnv(process.env);
2675
+ initSwitchboardProcess(config);
2676
+ await startSwitchboard(config, { fatalErrorShutdown: true });
2677
+ }
2678
+ /** Off in config, no timers or observers exist; a lever can still start it. */
2679
+ function createMemoryTelemetry(config, logger) {
2680
+ const { memory, dir, heapSnapshotDir } = config.telemetry;
2681
+ const directory = dir ?? telemetryDir();
2682
+ return new MemoryTelemetry({
2683
+ sampler: new NodeMemorySampler(),
2684
+ config: {
2685
+ enabled: memory.enabled,
2686
+ intervalMs: memory.intervalMs,
2687
+ outputs: memory.outputs,
2688
+ filePath: memory.file.path,
2689
+ fileMaxMb: memory.file.maxMb,
2690
+ fileKeep: memory.file.keep,
2691
+ ringSize: memory.ringSize,
2692
+ consoleIntervalMs: memory.consoleIntervalMs,
2693
+ workers: memory.workers,
2694
+ windowMin: memory.windowMin
2695
+ },
2696
+ fileSink: (settings) => memoryFileSink(settings, {
2697
+ dir: directory,
2698
+ logger
2699
+ }),
2700
+ heapSnapshot: createHeapSnapshotWriter({ dir: heapSnapshotDir ?? directory }),
2701
+ logger
2702
+ });
2703
+ }
2704
+ /** For a host with no ph-cli display: the slowest processors, through the log. */
2705
+ function startOwnedTimingLog(module, settings, intervalMs, logger) {
2706
+ if (!module || intervalMs <= 0) return () => {};
2707
+ return startProcessorTimingLog({
2708
+ intervalMs,
2709
+ read: () => computeProcessorTiming(module.processorManager.getAll(), module.catchUp.status(), settings.level, settings.windowMs),
2710
+ log: (line) => logger.info("@Line", line)
2711
+ });
2712
+ }
2713
+ /**
2714
+ * Feeds the priority this server's request load and main-thread event-loop
2715
+ * delay, and ticks its controller every second. Returns the stop.
2716
+ */
2717
+ function feedCatchUpPriority(priority, server) {
2718
+ const recorder = new RequestLoadRecorder({ eventLoopDelay: new NodeEventLoopDelay() });
2719
+ recorder.attach(server);
2720
+ priority.setLoadSource(recorder);
2721
+ const stopTicking = priority.startTicking();
2722
+ return () => {
2723
+ stopTicking();
2724
+ priority.setLoadSource(void 0);
2725
+ recorder.stop();
2726
+ };
2727
+ }
2728
+ //#endregion
2729
+ export { resolveKeyframes as a, attachmentsPlugin as c, initProfilerFromEnv as d, isPortAvailable as i, attachmentsPluginConfigSchema as l, deriveAttachmentServiceConfig as n, resolvePgliteStorageDirs as o, initSwitchboardProcess as r, startSwitchboard as s, createReactorKysely as t, applySwitchboardReactorDefaults as u };
2730
+
2731
+ //# sourceMappingURL=server-CirQ9hyu.mjs.map
2732
+ //# debugId=4384c5e3-87ee-52b5-bdec-eaf98e7a2b57