@powerhousedao/switchboard 6.2.3-dev.7 → 6.2.3-dev.70

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 (180) hide show
  1. package/.tsbuild/test/attachments/byte-grants.test.d.ts +2 -0
  2. package/.tsbuild/test/attachments/byte-grants.test.d.ts.map +1 -0
  3. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts +2 -0
  4. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts.map +1 -0
  5. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts +2 -0
  6. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts.map +1 -0
  7. package/.tsbuild/test/attachments/url-signer.test.d.ts +2 -0
  8. package/.tsbuild/test/attachments/url-signer.test.d.ts.map +1 -0
  9. package/.tsbuild/test/boot-create-signature-policy.test.d.ts +2 -0
  10. package/.tsbuild/test/boot-create-signature-policy.test.d.ts.map +1 -0
  11. package/.tsbuild/test/boot-inspection-enabled.test.d.ts +2 -0
  12. package/.tsbuild/test/boot-inspection-enabled.test.d.ts.map +1 -0
  13. package/.tsbuild/test/boot-mcp-enabled.test.d.ts +2 -0
  14. package/.tsbuild/test/boot-mcp-enabled.test.d.ts.map +1 -0
  15. package/.tsbuild/test/boot-privacy.test.d.ts +2 -0
  16. package/.tsbuild/test/boot-privacy.test.d.ts.map +1 -0
  17. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts +2 -0
  18. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts.map +1 -0
  19. package/.tsbuild/test/boot-without-renown.test.d.ts +2 -0
  20. package/.tsbuild/test/boot-without-renown.test.d.ts.map +1 -0
  21. package/.tsbuild/test/boot-without-require-signatures.test.d.ts +2 -0
  22. package/.tsbuild/test/boot-without-require-signatures.test.d.ts.map +1 -0
  23. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts +2 -0
  24. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts.map +1 -0
  25. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts +2 -0
  26. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts.map +1 -0
  27. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts +2 -0
  28. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts.map +1 -0
  29. package/.tsbuild/test/builder-defaults.test.d.ts +2 -0
  30. package/.tsbuild/test/builder-defaults.test.d.ts.map +1 -0
  31. package/.tsbuild/test/create-signature-policy.test.d.ts +2 -0
  32. package/.tsbuild/test/create-signature-policy.test.d.ts.map +1 -0
  33. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts +2 -0
  34. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts.map +1 -0
  35. package/.tsbuild/test/fatal-shutdown.test.d.ts +2 -0
  36. package/.tsbuild/test/fatal-shutdown.test.d.ts.map +1 -0
  37. package/.tsbuild/test/inspection-flag.test.d.ts +2 -0
  38. package/.tsbuild/test/inspection-flag.test.d.ts.map +1 -0
  39. package/.tsbuild/test/inspection-throttle.test.d.ts +2 -0
  40. package/.tsbuild/test/inspection-throttle.test.d.ts.map +1 -0
  41. package/.tsbuild/test/mcp-flag.test.d.ts +2 -0
  42. package/.tsbuild/test/mcp-flag.test.d.ts.map +1 -0
  43. package/.tsbuild/test/observability-signals.test.d.ts +2 -0
  44. package/.tsbuild/test/observability-signals.test.d.ts.map +1 -0
  45. package/.tsbuild/test/pglite-preflight.test.d.ts +2 -0
  46. package/.tsbuild/test/pglite-preflight.test.d.ts.map +1 -0
  47. package/.tsbuild/test/pglite-storage-dirs.test.d.ts +2 -0
  48. package/.tsbuild/test/pglite-storage-dirs.test.d.ts.map +1 -0
  49. package/.tsbuild/test/plugin-presence.test.d.ts +2 -0
  50. package/.tsbuild/test/plugin-presence.test.d.ts.map +1 -0
  51. package/.tsbuild/test/renown-trust-policy.test.d.ts +2 -0
  52. package/.tsbuild/test/renown-trust-policy.test.d.ts.map +1 -0
  53. package/.tsbuild/test/snapshot-writer.d.ts +18 -0
  54. package/.tsbuild/test/snapshot-writer.d.ts.map +1 -0
  55. package/.tsbuild/test/unsupported-stored-documents.test.d.ts +2 -0
  56. package/.tsbuild/test/unsupported-stored-documents.test.d.ts.map +1 -0
  57. package/.tsbuild/test/workflow/harness.d.ts +56 -0
  58. package/.tsbuild/test/workflow/harness.d.ts.map +1 -0
  59. package/.tsbuild/test/workflow/oauth.test.d.ts +2 -0
  60. package/.tsbuild/test/workflow/oauth.test.d.ts.map +1 -0
  61. package/.tsbuild/test/workflow/resolvers.test.d.ts +2 -0
  62. package/.tsbuild/test/workflow/resolvers.test.d.ts.map +1 -0
  63. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts +2 -0
  64. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts.map +1 -0
  65. package/.tsbuild/test/workflow/webhook-signed.test.d.ts +2 -0
  66. package/.tsbuild/test/workflow/webhook-signed.test.d.ts.map +1 -0
  67. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts +2 -0
  68. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts.map +1 -0
  69. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts +2 -0
  70. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts.map +1 -0
  71. package/.tsbuild/test/workflow-reactor-access.test.d.ts +2 -0
  72. package/.tsbuild/test/workflow-reactor-access.test.d.ts.map +1 -0
  73. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts +2 -0
  74. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts.map +1 -0
  75. package/.tsbuild/test/workflow-read-gate.test.d.ts +2 -0
  76. package/.tsbuild/test/workflow-read-gate.test.d.ts.map +1 -0
  77. package/.tsbuild/test/workflow-runtime.test.d.ts +2 -0
  78. package/.tsbuild/test/workflow-runtime.test.d.ts.map +1 -0
  79. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  80. package/.tsbuild/tsdown.config.d.ts.map +1 -1
  81. package/.tsbuild/vitest.config.d.ts.map +1 -1
  82. package/Auth.md +144 -2
  83. package/CHANGELOG.md +842 -0
  84. package/README.md +47 -10
  85. package/dist/index.d.mts +2 -1
  86. package/dist/index.mjs +50 -50
  87. package/dist/index.mjs.map +1 -1
  88. package/dist/install-packages.d.mts +2 -1
  89. package/dist/install-packages.mjs +2 -2
  90. package/dist/install-packages.mjs.map +1 -1
  91. package/dist/mcp-cNWW82NH.mjs +27 -0
  92. package/dist/mcp-cNWW82NH.mjs.map +1 -0
  93. package/dist/migrate.d.mts +2 -1
  94. package/dist/migrate.mjs +4 -3
  95. package/dist/migrate.mjs.map +1 -1
  96. package/dist/plugin-host-CGO4XZzK.d.mts +38 -0
  97. package/dist/plugin-host-CGO4XZzK.d.mts.map +1 -0
  98. package/dist/plugins/attachments.d.mts +23 -0
  99. package/dist/plugins/attachments.d.mts.map +1 -0
  100. package/dist/plugins/attachments.mjs +4 -0
  101. package/dist/plugins/mcp.d.mts +21 -0
  102. package/dist/plugins/mcp.d.mts.map +1 -0
  103. package/dist/plugins/mcp.mjs +4 -0
  104. package/dist/plugins/privacy.d.mts +12 -0
  105. package/dist/plugins/privacy.d.mts.map +1 -0
  106. package/dist/plugins/privacy.mjs +4 -0
  107. package/dist/plugins/workflows.d.mts +36 -0
  108. package/dist/plugins/workflows.d.mts.map +1 -0
  109. package/dist/plugins/workflows.mjs +4 -0
  110. package/dist/privacy-C8KVimKF.mjs +113 -0
  111. package/dist/privacy-C8KVimKF.mjs.map +1 -0
  112. package/dist/{server-CiKkVE6g.mjs → server-CF_mjyJi.mjs} +1170 -228
  113. package/dist/server-CF_mjyJi.mjs.map +1 -0
  114. package/dist/server.d.mts +190 -30
  115. package/dist/server.d.mts.map +1 -1
  116. package/dist/server.mjs +4 -5
  117. package/dist/{utils-Baw7rThP.mjs → utils-uaBlzyjS.mjs} +15 -9
  118. package/dist/utils-uaBlzyjS.mjs.map +1 -0
  119. package/dist/utils.d.mts +4 -5
  120. package/dist/utils.d.mts.map +1 -1
  121. package/dist/utils.mjs +3 -3
  122. package/dist/workflow-runtime-7GaJ13c9.d.mts +30 -0
  123. package/dist/workflow-runtime-7GaJ13c9.d.mts.map +1 -0
  124. package/dist/workflows-qKtqZhn3.mjs +1338 -0
  125. package/dist/workflows-qKtqZhn3.mjs.map +1 -0
  126. package/package.json +49 -20
  127. package/scripts/install-packages.sh +0 -0
  128. package/test/attachment-reference-read-model.test.ts +6 -1
  129. package/test/attachments/auth.test.ts +85 -0
  130. package/test/attachments/byte-grants.test.ts +290 -0
  131. package/test/attachments/byte-routes-read-gate.integration.test.ts +314 -0
  132. package/test/attachments/download-target.test.ts +201 -32
  133. package/test/attachments/index.test.ts +47 -4
  134. package/test/attachments/reserve-metadata-parity.test.ts +96 -0
  135. package/test/attachments/routes-integration.test.ts +60 -4
  136. package/test/attachments/routes.test.ts +271 -24
  137. package/test/attachments/service-config.test.ts +13 -3
  138. package/test/attachments/url-signer.test.ts +105 -0
  139. package/test/boot-create-signature-policy.test.ts +108 -0
  140. package/test/boot-inspection-enabled.test.ts +150 -0
  141. package/test/boot-mcp-enabled.test.ts +130 -0
  142. package/test/boot-privacy.test.ts +243 -0
  143. package/test/boot-unsupported-stored-documents.test.ts +213 -0
  144. package/test/boot-without-renown.test.ts +81 -0
  145. package/test/boot-without-require-signatures.test.ts +74 -0
  146. package/test/boot-worker-trust-policy.test.ts +90 -0
  147. package/test/boot-workflow-singleton-conflict.test.ts +107 -0
  148. package/test/boot-workflow-singleton-retry.test.ts +133 -0
  149. package/test/builder-defaults.test.ts +80 -0
  150. package/test/create-signature-policy.test.ts +69 -0
  151. package/test/durable-node-fs-pg16.test.ts +80 -0
  152. package/test/fatal-shutdown.test.ts +165 -0
  153. package/test/inspection-flag.test.ts +62 -0
  154. package/test/inspection-throttle.test.ts +23 -0
  155. package/test/mcp-flag.test.ts +56 -0
  156. package/test/observability-signals.test.ts +131 -0
  157. package/test/pglite-dialect.test.ts +217 -2
  158. package/test/pglite-preflight.test.ts +313 -0
  159. package/test/pglite-storage-dirs.test.ts +103 -0
  160. package/test/pglite-version.test.ts +9 -1
  161. package/test/plugin-presence.test.ts +269 -0
  162. package/test/renown-trust-policy.test.ts +315 -0
  163. package/test/snapshot-writer.ts +94 -0
  164. package/test/unsupported-stored-documents.test.ts +72 -0
  165. package/test/worker-pool.test.ts +27 -1
  166. package/test/workflow/harness.ts +289 -0
  167. package/test/workflow/oauth.test.ts +214 -0
  168. package/test/workflow/resolvers.test.ts +357 -0
  169. package/test/workflow/webhook-dedupe.test.ts +295 -0
  170. package/test/workflow/webhook-signed.test.ts +509 -0
  171. package/test/workflow/webhook-trigger-test.test.ts +82 -0
  172. package/test/workflow/webhook-unsigned.test.ts +345 -0
  173. package/test/workflow-reactor-access.test.ts +384 -0
  174. package/test/workflow-reactor-enforcement.test.ts +808 -0
  175. package/test/workflow-read-gate.test.ts +213 -0
  176. package/test/workflow-runtime.test.ts +1122 -0
  177. package/tsconfig.json +11 -2
  178. package/tsdown.config.ts +9 -1
  179. package/dist/server-CiKkVE6g.mjs.map +0 -1
  180. package/dist/utils-Baw7rThP.mjs.map +0 -1
@@ -0,0 +1,1338 @@
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]="3ac978b6-5ddf-546e-848d-1557f6ab7aeb")}catch(e){}}();
3
+ import { REACTOR_SCHEMA, supportsLiveReadModelRegistration } from "@powerhousedao/reactor";
4
+ import { AuthorizationPolicy, BaseSubgraph, ForbiddenError, callerSubject, createCanonicalDocumentIdResolver } from "@powerhousedao/reactor-api";
5
+ import { parseRef } from "@powerhousedao/reactor-attachments";
6
+ import { GraphQLError, Kind } from "graphql";
7
+ import { gql } from "graphql-tag";
8
+ //#region src/fatal-shutdown.mts
9
+ const FORCED_EXIT_MS = 15e3;
10
+ const fatalHandlers = /* @__PURE__ */ new WeakMap();
11
+ /**
12
+ * Sends an uncaught exception or unhandled rejection through the SIGTERM
13
+ * shutdown that `withSignalHandlers()` installs, so the reactor and read-model
14
+ * PGlite stores close with a shutdown checkpoint before the process exits
15
+ * with code 1. Node's default is to exit at once, which leaves both stores
16
+ * to WAL recovery on the next open. A store whose wasm runtime aborted
17
+ * (ENOSPC) rejects its close; the builder logs that and still exits. A
18
+ * shutdown that hangs is cut off after FORCED_EXIT_MS.
19
+ *
20
+ * A rejection is fatal only when this is its sole listener: Node exits on an
21
+ * unhandled rejection only when nothing listens for it, and Sentry's
22
+ * listener deliberately keeps the process running.
23
+ */
24
+ function installFatalErrorShutdown(logger, proc = process) {
25
+ if (fatalHandlers.has(proc)) return;
26
+ const realExit = proc.exit.bind(proc);
27
+ let shuttingDown = false;
28
+ /**
29
+ * Logs without ever throwing. onFatal runs inside the uncaughtException
30
+ * handler, so a logger whose transport is gone (EPIPE on a closed stdout)
31
+ * would otherwise throw from the handler that reports throws, killing the
32
+ * process before the shutdown it is supposed to run. A logging failure is
33
+ * swallowed: there is nowhere left to report it.
34
+ */
35
+ const logFatal = (message, err) => {
36
+ try {
37
+ if (err === void 0) logger.error(message);
38
+ else logger.error(message, err);
39
+ } catch {}
40
+ };
41
+ const onFatal = (kind, err) => {
42
+ logFatal(`${kind}: @error`, err);
43
+ if (shuttingDown) return;
44
+ shuttingDown = true;
45
+ proc.exitCode = 1;
46
+ setTimeout(() => {
47
+ logFatal("Shutdown after fatal error timed out; exiting");
48
+ realExit(1);
49
+ }, FORCED_EXIT_MS).unref();
50
+ proc.kill(proc.pid, "SIGTERM");
51
+ };
52
+ fatalHandlers.set(proc, onFatal);
53
+ proc.on("uncaughtException", (err) => onFatal("Uncaught exception", err));
54
+ proc.on("unhandledRejection", (reason) => {
55
+ if (proc.listenerCount("unhandledRejection") > 1) return;
56
+ onFatal("Unhandled rejection", reason);
57
+ });
58
+ }
59
+ /**
60
+ * Routes a fatal condition the caller detected through the same shutdown as an
61
+ * uncaught error. Returns false, and does nothing, when
62
+ * `installFatalErrorShutdown` has not run for `proc`.
63
+ */
64
+ function triggerFatalShutdown(kind, err, proc = process) {
65
+ const onFatal = fatalHandlers.get(proc);
66
+ if (!onFatal) return false;
67
+ onFatal(kind, err);
68
+ return true;
69
+ }
70
+ //#endregion
71
+ //#region src/workflow/oauth-callback.ts
72
+ const OAUTH_CALLBACK_PATH = "oauth/callback";
73
+ function escapeHtml(text) {
74
+ return text.replace(/[&<>"']/g, (char) => ({
75
+ "&": "&amp;",
76
+ "<": "&lt;",
77
+ ">": "&gt;",
78
+ "\"": "&quot;",
79
+ "'": "&#39;"
80
+ })[char]);
81
+ }
82
+ function resultPage(ok, detail) {
83
+ const title = ok ? "Connected" : "Sign-in failed";
84
+ return `<!doctype html>
85
+ <html><head><meta charset="utf-8"><title>${title}</title>
86
+ <meta name="viewport" content="width=device-width, initial-scale=1">
87
+ <style>body{font:15px system-ui,sans-serif;margin:0;display:grid;place-items:center;min-height:100vh;background:#fafafa;color:#222}main{max-width:28rem;padding:1.5rem;text-align:center}h1{font-size:1.1rem}</style>
88
+ </head><body><main><h1>${title}</h1><p>${ok ? "You can close this window." : escapeHtml(detail ?? "The sign-in did not finish.")}</p></main>
89
+ ${ok ? "<script>setTimeout(function(){window.close()},600)<\/script>" : ""}
90
+ </body></html>`;
91
+ }
92
+ function registerOAuthCallback(http, runtime) {
93
+ return http.get(OAUTH_CALLBACK_PATH, { auth: "public" }, async (request) => {
94
+ const params = new URL(request.url).searchParams;
95
+ const state = params.get("state");
96
+ const result = state ? await runtime.completeOAuth({
97
+ state,
98
+ code: params.get("code") ?? void 0,
99
+ error: params.get("error") ?? void 0,
100
+ errorDescription: params.get("error_description") ?? void 0
101
+ }) : {
102
+ ok: false,
103
+ detail: "The provider sent no state",
104
+ returnUrl: null
105
+ };
106
+ if (result.returnUrl && state) {
107
+ const back = new URL(result.returnUrl);
108
+ back.searchParams.set("ph_oauth", state);
109
+ return new Response(null, {
110
+ status: 303,
111
+ headers: {
112
+ location: back.href,
113
+ "cache-control": "no-store"
114
+ }
115
+ });
116
+ }
117
+ return new Response(resultPage(result.ok, result.detail), {
118
+ status: result.ok ? 200 : 400,
119
+ headers: {
120
+ "content-type": "text/html; charset=utf-8",
121
+ "cache-control": "no-store",
122
+ "referrer-policy": "no-referrer"
123
+ }
124
+ });
125
+ });
126
+ }
127
+ function callbackUrlOf(http) {
128
+ return `${http.baseUrl.replace(/\/+$/, "")}/${OAUTH_CALLBACK_PATH}`;
129
+ }
130
+ //#endregion
131
+ //#region src/workflow/resolvers.ts
132
+ const PIECE_SOURCES = [
133
+ "local",
134
+ "registry",
135
+ "activepieces"
136
+ ];
137
+ function isPieceSource(value) {
138
+ return PIECE_SOURCES.includes(value);
139
+ }
140
+ function blockRef(input) {
141
+ if (input.kind !== "action" && input.kind !== "trigger") throw new GraphQLError(`A block's kind is "action" or "trigger", got "${input.kind}"`);
142
+ return {
143
+ pieceName: input.pieceName,
144
+ pieceVersion: input.pieceVersion,
145
+ name: input.name,
146
+ kind: input.kind
147
+ };
148
+ }
149
+ async function cursorAware(call) {
150
+ try {
151
+ return await call();
152
+ } catch (error) {
153
+ if (error instanceof Error && error.name === "InvalidRunCursorError") throw new GraphQLError(error.message, { extensions: { code: "BAD_USER_INPUT" } });
154
+ throw error;
155
+ }
156
+ }
157
+ function selectsStepData(selections, path) {
158
+ let level = selections;
159
+ for (const name of [...path, "steps"]) {
160
+ const next = [];
161
+ for (const set of level) for (const selection of set.selections) {
162
+ if (selection.kind !== Kind.FIELD) return true;
163
+ if (selection.name.value === name && selection.selectionSet) next.push(selection.selectionSet);
164
+ }
165
+ if (next.length === 0) return false;
166
+ level = next;
167
+ }
168
+ return level.some((set) => set.selections.some((selection) => selection.kind !== Kind.FIELD || selection.name.value === "input" || selection.name.value === "output"));
169
+ }
170
+ function readsStepData(info, path) {
171
+ if (!info) return true;
172
+ return selectsStepData(info.fieldNodes.flatMap((node) => node.selectionSet ? [node.selectionSet] : []), path);
173
+ }
174
+ function requireAdmin(authorizationService, ctx) {
175
+ if (!authorizationService.isSupremeAdmin(ctx.user?.address)) throw new GraphQLError("Admin access required");
176
+ }
177
+ async function syncAware(call) {
178
+ try {
179
+ return await call();
180
+ } catch (error) {
181
+ if (error instanceof Error && error.name === "WorkflowSyncingError") throw new GraphQLError(error.message, { extensions: {
182
+ code: "WORKFLOW_SYNCING",
183
+ retryable: true
184
+ } });
185
+ throw error;
186
+ }
187
+ }
188
+ function parseJson(value) {
189
+ if (value === null) return null;
190
+ try {
191
+ return JSON.parse(value);
192
+ } catch {
193
+ return value;
194
+ }
195
+ }
196
+ function toStepRecord(row) {
197
+ return {
198
+ stepId: row.step_id,
199
+ stepKey: row.step_key,
200
+ pieceName: row.piece_name,
201
+ blockName: row.block_name,
202
+ status: row.status,
203
+ input: parseJson(row.input),
204
+ output: parseJson(row.output),
205
+ port: row.port,
206
+ error: row.error,
207
+ errorName: row.error_name,
208
+ startedAt: row.started_at,
209
+ endedAt: row.ended_at,
210
+ pieceVersion: row.piece_version,
211
+ pieceSource: row.piece_source,
212
+ versionMatch: row.version_match,
213
+ versionNote: row.version_note
214
+ };
215
+ }
216
+ function toRunRecord(row, steps) {
217
+ return {
218
+ id: row.id,
219
+ workflowId: row.workflow_id,
220
+ workflowName: row.workflow_name,
221
+ workflowVersion: row.workflow_version,
222
+ triggerKind: row.trigger_kind,
223
+ triggerPayload: parseJson(row.trigger_payload),
224
+ status: row.status,
225
+ error: row.error,
226
+ errorName: row.error_name,
227
+ startedAt: row.started_at,
228
+ endedAt: row.ended_at,
229
+ rerunOf: row.rerun_of,
230
+ warnings: row.warnings,
231
+ warningNotes: parseJson(row.warning_notes) ?? [],
232
+ steps: steps.map(toStepRecord)
233
+ };
234
+ }
235
+ const UNKNOWN_ACCESS = {
236
+ authEnforcement: true,
237
+ authConditions: false,
238
+ identity: null
239
+ };
240
+ function signedIn(ctx) {
241
+ return Boolean(ctx.user?.address);
242
+ }
243
+ function isAbsolute(url) {
244
+ return /^https?:\/\//i.test(url);
245
+ }
246
+ function redirectUriFor(routing, requested) {
247
+ if (!routing) throw new GraphQLError("This host serves no OAuth2 callback");
248
+ if (isAbsolute(routing.callbackUrl)) return routing.callbackUrl;
249
+ if (!requested) throw new GraphQLError("This host does not know its public URL; pass redirectUri");
250
+ let url;
251
+ try {
252
+ url = new URL(requested);
253
+ } catch {
254
+ throw new GraphQLError(`"${requested}" is not a URL`);
255
+ }
256
+ if (url.protocol !== "https:" && url.protocol !== "http:" || url.pathname !== routing.callbackUrl || url.search !== "" || url.hash !== "") throw new GraphQLError(`redirectUri must be this host's ${routing.callbackUrl}`);
257
+ return url.href;
258
+ }
259
+ function returnUrlFor(requested, ctx) {
260
+ if (!requested) return void 0;
261
+ const origin = ctx.headers.origin;
262
+ let url;
263
+ try {
264
+ url = new URL(requested);
265
+ } catch {
266
+ url = void 0;
267
+ }
268
+ if (!url || !origin || url.origin !== origin) throw new GraphQLError("returnUrl must be on the requesting page's origin");
269
+ return url.href;
270
+ }
271
+ const getResolvers = (runtime, authorizationService, oauth, access = UNKNOWN_ACCESS, assertCanRead) => {
272
+ return {
273
+ Query: { workflowRuntime: () => ({}) },
274
+ WorkflowRuntimeQueries: {
275
+ health: () => "ok",
276
+ authEnforcement: () => access.authEnforcement,
277
+ reactorIdentity: (_parent, _args, ctx) => signedIn(ctx) ? access.identity : null,
278
+ authConditions: (_parent, _args, ctx) => signedIn(ctx) ? access.authConditions : null,
279
+ reactorAccessDenial: async (_parent, args, ctx) => {
280
+ if (!assertCanRead) throw new GraphQLError("No read check configured");
281
+ await assertCanRead(args.workflowId, ctx);
282
+ return runtime.reactorAccessDenial(args.workflowId) ?? null;
283
+ },
284
+ blockDescriptor: (_parent, args) => runtime.blockDescriptor(blockRef(args.block)),
285
+ blockOptions: (_parent, args, ctx) => runtime.blockOptions(blockRef(args.block), args.propName, args.input, args.connectionId ?? void 0, ctx, args.searchValue ?? void 0, args.reactorConnectionId ?? void 0),
286
+ pieceCatalog: () => runtime.pieceCatalog(),
287
+ pieceActions: (_parent, args) => runtime.pieceActions(args.packageName, args.version ?? void 0),
288
+ pieceTriggers: (_parent, args) => runtime.pieceTriggers(args.packageName, args.version ?? void 0),
289
+ blockOutputTree: (_parent, args) => runtime.blockOutputTree(blockRef(args.block), args.config),
290
+ stepOutputTree: (_parent, args, ctx) => runtime.stepOutputTree(args.workflowId, args.stepId, ctx),
291
+ blockResolutions: (_parent, args, ctx) => runtime.blockResolutions(args.workflowId, ctx),
292
+ pieceDetail: (_parent, args) => runtime.pieceDetail(args.packageName, args.version ?? void 0),
293
+ searchPieces: (_parent, args) => {
294
+ if (args.kind !== "action" && args.kind !== "trigger") throw new GraphQLError(`A search's kind is "action" or "trigger", got "${args.kind}"`);
295
+ const unknown = (args.sources ?? []).filter((source) => !isPieceSource(source));
296
+ if (unknown.length > 0) throw new GraphQLError(`A search's sources are ${PIECE_SOURCES.join(", ")}, got ${unknown.join(", ")}`);
297
+ return runtime.searchPieces(args.query, {
298
+ kind: args.kind,
299
+ sources: (args.sources ?? []).filter(isPieceSource),
300
+ categories: args.categories ?? void 0,
301
+ limit: args.limit ?? void 0
302
+ });
303
+ },
304
+ connections: (_parent, _args, ctx) => runtime.connections(ctx),
305
+ webhookEndpoint: (_parent, args, ctx) => syncAware(() => runtime.webhookEndpoint(args.workflowId, ctx, { driveId: args.driveId ?? void 0 })),
306
+ secret: async (_parent, args) => {
307
+ try {
308
+ return await (await runtime.secrets()).stat(args.ref);
309
+ } catch {
310
+ return null;
311
+ }
312
+ },
313
+ secrets: async () => (await runtime.secrets()).list(),
314
+ oauthRedirectUri: () => oauth?.callbackUrl ?? null,
315
+ oauthAttempt: (_parent, args, ctx) => runtime.oauthAttempt(args.state, ctx),
316
+ triggerStates: async (_parent, _args, ctx) => (await runtime.triggerStates(ctx)).map((row) => ({
317
+ workflowId: row.workflow_id,
318
+ pieceName: row.piece_name,
319
+ triggerName: row.trigger_name,
320
+ status: row.status,
321
+ intervalMs: row.interval_ms,
322
+ nextPollAt: row.next_poll_at,
323
+ lastPollAt: row.last_poll_at,
324
+ lastError: row.last_error,
325
+ consecutiveFailures: row.consecutive_failures,
326
+ nextRenewAt: row.next_renew_at,
327
+ renewError: row.renew_error,
328
+ renewFailures: row.renew_failures,
329
+ pieceVersion: row.piece_version,
330
+ pieceSource: row.piece_source,
331
+ versionMatch: row.version_match,
332
+ versionNote: row.version_note
333
+ })),
334
+ runs: async (_parent, args, ctx, info) => (await runtime.runs({
335
+ ...args,
336
+ withStepData: readsStepData(info, [])
337
+ }, ctx)).map((record) => toRunRecord(record.row, record.steps)),
338
+ runsPage: async (_parent, args, ctx, info) => {
339
+ const { paging, ...scope } = args;
340
+ const page = await cursorAware(() => runtime.runsPage({
341
+ ...scope,
342
+ limit: paging?.limit ?? void 0,
343
+ cursor: paging?.cursor ?? null,
344
+ withStepData: readsStepData(info, ["items"])
345
+ }, ctx));
346
+ return {
347
+ items: page.records.map((record) => toRunRecord(record.row, record.steps)),
348
+ hasNextPage: page.hasNextPage,
349
+ hasPreviousPage: Boolean(paging?.cursor),
350
+ cursor: page.cursor
351
+ };
352
+ },
353
+ run: async (_parent, args, ctx) => {
354
+ const record = await runtime.run(args.id, ctx);
355
+ return record ? toRunRecord(record.row, record.steps) : null;
356
+ }
357
+ },
358
+ Mutation: { workflowRuntime: () => ({}) },
359
+ WorkflowRuntimeMutations: {
360
+ fire: (_parent, args, ctx) => runtime.fire(args.workflowId, args.payload, "manual", void 0, ctx),
361
+ testTrigger: (_parent, args, ctx) => syncAware(() => runtime.testTrigger(args.workflowId, ctx, {
362
+ ...args.payload !== void 0 ? { payload: args.payload } : {},
363
+ ...typeof args.timeoutSeconds === "number" ? { timeoutMs: args.timeoutSeconds * 1e3 } : {},
364
+ driveId: args.driveId ?? void 0
365
+ })),
366
+ cancelTriggerTest: (_parent, args, ctx) => runtime.cancelTriggerTestFor(args.workflowId, ctx),
367
+ testStep: (_parent, args, ctx) => syncAware(() => runtime.testStep(args.workflowId, args.stepId, ctx, { driveId: args.driveId ?? void 0 })),
368
+ rerun: (_parent, args, ctx) => runtime.rerun(args.runId, ctx),
369
+ createSecret: async (_parent, args, ctx) => {
370
+ requireAdmin(authorizationService, ctx);
371
+ return (await runtime.secrets()).create({
372
+ value: args.value,
373
+ label: args.label ?? void 0
374
+ });
375
+ },
376
+ rotateSecret: async (_parent, args, ctx) => {
377
+ requireAdmin(authorizationService, ctx);
378
+ return (await runtime.secrets()).rotate(args.ref, args.value);
379
+ },
380
+ deleteSecret: async (_parent, args, ctx) => {
381
+ requireAdmin(authorizationService, ctx);
382
+ await (await runtime.secrets()).delete(args.ref);
383
+ return true;
384
+ },
385
+ checkConnection: (_parent, args, ctx) => runtime.checkConnection(args.connectionId, ctx),
386
+ startOAuth: (_parent, args, ctx) => {
387
+ requireAdmin(authorizationService, ctx);
388
+ const returnUrl = returnUrlFor(args.returnUrl, ctx);
389
+ return runtime.startOAuth(args.connectionId, ctx, {
390
+ redirectUri: redirectUriFor(oauth, args.redirectUri),
391
+ ...returnUrl ? { returnUrl } : {}
392
+ });
393
+ }
394
+ }
395
+ };
396
+ };
397
+ //#endregion
398
+ //#region src/workflow/schema.ts
399
+ const schema = gql`
400
+ """
401
+ WorkflowRuntime Queries
402
+ """
403
+ type WorkflowRuntimeQueries {
404
+ health: String!
405
+ """
406
+ Whether this reactor enforces document auth (REACTOR_AUTH_ENFORCEMENT).
407
+ On, a workflow needs a signed publish, and the host grants, to reach
408
+ documents. Answered to any caller.
409
+ """
410
+ authEnforcement: Boolean!
411
+ """
412
+ Who this host signs as: grant it on each document a step writes. Null for
413
+ a caller who is not signed in, or a host with no signer.
414
+ """
415
+ reactorIdentity: ReactorIdentity
416
+ """
417
+ REACTOR_AUTH_CONDITIONS. True: grant the host by key, with
418
+ { match: subject.key == key }; false: by address. Null for a caller who
419
+ is not signed in.
420
+ """
421
+ authConditions: Boolean
422
+ """
423
+ Why the workflow's last publish or enable got no reactor access, naming
424
+ the publisher and the connection; null when the check passed.
425
+ """
426
+ reactorAccessDenial(workflowId: String!): String
427
+ """
428
+ Persisted runs, newest first. Scope them to one workflow, or to every
429
+ workflow a drive holds; workflowId wins when both are given.
430
+ """
431
+ runs(
432
+ workflowId: String
433
+ driveId: String
434
+ limit: Int
435
+ "Trigger kinds to leave out, e.g. test."
436
+ excludeTriggerKinds: [String!]
437
+ ): [WorkflowRunRecord!]!
438
+ """
439
+ The same listing a page at a time, newest journaled first. Pass a page's
440
+ cursor back in paging to read the next; a page is short only when
441
+ hasNextPage is false, or when the caller could read none of a long
442
+ stretch of runs. A run that starts between pages keeps its place.
443
+ """
444
+ runsPage(
445
+ workflowId: String
446
+ driveId: String
447
+ excludeTriggerKinds: [String!]
448
+ paging: WorkflowRunsPagingInput
449
+ ): WorkflowRunResultPage!
450
+ run(id: String!): WorkflowRunRecord
451
+ """
452
+ The descriptor (props, auth, ports) of one action or trigger, as the
453
+ version that runs it describes it; triggers come back under "trigger".
454
+ """
455
+ blockDescriptor(block: BlockInput!): Unknown
456
+ """
457
+ Resolves a dynamic prop against the current config values: a DROPDOWN
458
+ yields { options, placeholder, disabled }, a DYNAMIC prop yields the
459
+ resolved sub-property descriptor list.
460
+ """
461
+ blockOptions(
462
+ block: BlockInput!
463
+ propName: String!
464
+ input: Unknown
465
+ connectionId: String
466
+ "What the author typed, for a DROPDOWN declared with refreshOnSearch."
467
+ searchValue: String
468
+ "The step's reactor connection; its filter narrows what the resolver reads."
469
+ reactorConnectionId: String
470
+ ): Unknown
471
+ """
472
+ Every piece this reactor offers: the core piece, its package pieces, and
473
+ the pieces the registry and Activepieces publish.
474
+ """
475
+ pieceCatalog: Unknown
476
+ """
477
+ A piece's actions at one version; pin a step to that version.
478
+ """
479
+ pieceActions(
480
+ packageName: String!
481
+ "That version; the installed or latest one when omitted."
482
+ version: String
483
+ ): Unknown
484
+ """
485
+ A piece's triggers at one version; pin a trigger to that version.
486
+ """
487
+ pieceTriggers(
488
+ packageName: String!
489
+ "That version; the installed or latest one when omitted."
490
+ version: String
491
+ ): Unknown
492
+ """
493
+ Full piece detail (PieceMetadataModel-shaped), verbatim from the cloud API.
494
+ """
495
+ pieceDetail(
496
+ packageName: String!
497
+ "That version; the installed or latest one when omitted."
498
+ version: String
499
+ ): Unknown
500
+ """
501
+ Piece and block search across the catalog, grouped by piece. The index
502
+ builds lazily on first use; poll while status is "indexing".
503
+ """
504
+ searchPieces(
505
+ query: String!
506
+ "action | trigger"
507
+ kind: String!
508
+ "local | registry | activepieces; all when omitted."
509
+ sources: [String!]
510
+ "Category ids, any of; all when omitted."
511
+ categories: [String!]
512
+ "Pieces returned."
513
+ limit: Int
514
+ ): PieceSearchResult!
515
+ """
516
+ Health of every registered piece trigger (poll schedule, errors).
517
+ """
518
+ triggerStates: [TriggerStateRecord!]!
519
+ """
520
+ Authored output shape of a block (SDL / outputSchema / sampleData).
521
+ """
522
+ blockOutputTree(block: BlockInput!, config: Unknown): Unknown
523
+ """
524
+ Output shape of a draft step or trigger: its latest test output
525
+ (source "test", with sample and testedAt) when tested, else as blockOutputTree.
526
+ """
527
+ stepOutputTree(workflowId: String!, stepId: String!): Unknown
528
+ """
529
+ Every block of the draft (trigger first) as this reactor resolves it:
530
+ which piece version runs, from where, and how it matches the pin.
531
+ """
532
+ blockResolutions(workflowId: String!): [BlockResolutionRecord!]!
533
+ """
534
+ Every powerhouse/connection document, for connection pickers.
535
+ """
536
+ connections: [ConnectionRecord!]!
537
+ """
538
+ The webhook endpoint for a workflow: the URL to hand the provider. Minted
539
+ on first ask, whether or not the workflow is armed — an author needs the
540
+ URL before enabling, and the armed field carries that difference. Null
541
+ only when the host has no webhook service. With driveId, a workflow not
542
+ synced here yet is waited for briefly, then fails as WORKFLOW_SYNCING.
543
+ """
544
+ webhookEndpoint(workflowId: String!, driveId: String): WebhookEndpointRecord
545
+ """
546
+ Secret metadata (label, version, status). Never the value.
547
+ """
548
+ secret(ref: String!): SecretRecord
549
+ secrets: [SecretRecord!]!
550
+ """
551
+ The URL an OAuth2 app must register as its redirect. A bare path when
552
+ this host does not know its public origin; resolve it against the URL
553
+ this API is reached at. Null when the host serves no HTTP routes.
554
+ """
555
+ oauthRedirectUri: String
556
+ """
557
+ How an OAuth2 sign-in opened by startOAuth stands; null when unknown.
558
+ """
559
+ oauthAttempt(state: String!): OAuthAttempt
560
+ }
561
+
562
+ type OAuthAttempt {
563
+ connectionId: String!
564
+ "PENDING | EXCHANGING | OK | ERROR"
565
+ status: String!
566
+ error: String
567
+ }
568
+
569
+ type OAuthStart {
570
+ state: String!
571
+ "Where to send the user to sign in."
572
+ authorizationUrl: String!
573
+ redirectUri: String!
574
+ expiresAt: String!
575
+ }
576
+
577
+ """
578
+ One action or trigger of a piece, as a workflow pins it. The engine's own
579
+ blocks are the piece @powerhousedao/piece-core.
580
+ """
581
+ input BlockInput {
582
+ pieceName: String!
583
+ "Exact semver."
584
+ pieceVersion: String!
585
+ "The action or trigger name."
586
+ name: String!
587
+ "action | trigger"
588
+ kind: String!
589
+ }
590
+
591
+ type BlockSearchHit {
592
+ pieceName: String!
593
+ "The version the hit is listed at; pin to it when picking the block."
594
+ pieceVersion: String!
595
+ "The action or trigger name."
596
+ name: String!
597
+ pieceDisplayName: String!
598
+ logoUrl: String!
599
+ displayName: String!
600
+ description: String!
601
+ "action | trigger"
602
+ kind: String!
603
+ "Triggers only: POLLING | WEBHOOK | APP_WEBHOOK | MANUAL"
604
+ strategy: String
605
+ "Why this block cannot run on this reactor; null when it can."
606
+ unsupported: String
607
+ }
608
+
609
+ type BlockResolutionRecord {
610
+ "The trigger's or step's id."
611
+ stepId: String!
612
+ pieceName: String!
613
+ "The version the block pins."
614
+ pieceVersion: String!
615
+ "The action or trigger name."
616
+ name: String!
617
+ "action | trigger"
618
+ kind: String!
619
+ "The version that runs; null when nothing resolves."
620
+ resolvedVersion: String
621
+ "local | registry | activepieces | npm; null when nothing resolves."
622
+ source: String
623
+ "exact | compatible | fallback | installed | missing"
624
+ match: String!
625
+ "Why the version that runs differs from the pin, or why nothing resolves."
626
+ note: String
627
+ "The newest version any source offers."
628
+ latestVersion: String
629
+ }
630
+
631
+ type PieceSearchMatch {
632
+ pieceName: String!
633
+ pieceVersion: String!
634
+ displayName: String!
635
+ description: String!
636
+ logoUrl: String!
637
+ categories: [String!]!
638
+ "local | registry | activepieces"
639
+ source: String!
640
+ deprecated: Boolean
641
+ "Why no block of the piece can run on this reactor."
642
+ unsupported: String
643
+ "Every query token matched the piece's own name."
644
+ namedPiece: Boolean!
645
+ "Matching blocks of the kind asked for, best first."
646
+ blocks: [BlockSearchHit!]!
647
+ }
648
+
649
+ type PieceSearchResult {
650
+ "ready | indexing | error"
651
+ status: String!
652
+ pieces: [PieceSearchMatch!]!
653
+ indexedPieces: Int!
654
+ error: String
655
+ }
656
+
657
+ type SecretRecord {
658
+ ref: String!
659
+ label: String
660
+ version: Int!
661
+ status: String!
662
+ createdAt: String!
663
+ updatedAt: String!
664
+ }
665
+
666
+ type ConnectionRecord {
667
+ id: String!
668
+ name: String!
669
+ connectorId: String!
670
+ authType: String!
671
+ status: String!
672
+ accountLabel: String
673
+ }
674
+
675
+ type ReactorIdentity {
676
+ "The address the host signs as; null without a signed-in identity."
677
+ address: String
678
+ "The did:key that signs the host's operations."
679
+ key: String!
680
+ }
681
+
682
+ type ConnectionCheckResult {
683
+ ok: Boolean!
684
+ detail: String
685
+ """
686
+ From auth.getConnectionIdentifier when the check passes; otherwise the
687
+ label the connection already holds.
688
+ """
689
+ accountLabel: String
690
+ }
691
+
692
+ type WebhookEndpointRecord {
693
+ workflowId: String!
694
+ url: String!
695
+ """
696
+ False when the host gave the webhook service no public origin, so the url
697
+ above is a bare path. Switchboard always gives one, falling back to
698
+ http://localhost:<port> when PUBLIC_URL is unset.
699
+ """
700
+ absoluteUrl: Boolean!
701
+ "True while the workflow is ENABLED with a valid webhook trigger"
702
+ armed: Boolean!
703
+ createdAt: String!
704
+ }
705
+
706
+ type TriggerStateRecord {
707
+ workflowId: String!
708
+ pieceName: String!
709
+ triggerName: String!
710
+ status: String!
711
+ intervalMs: Int!
712
+ nextPollAt: String
713
+ lastPollAt: String
714
+ lastError: String
715
+ consecutiveFailures: Int!
716
+ "When a webhook trigger next renews its subscription; null if it never does."
717
+ nextRenewAt: String
718
+ "The last failed renewal, kept apart from lastError, the poll's."
719
+ renewError: String
720
+ renewFailures: Int!
721
+ "The piece version the trigger armed with; null for a host-fed trigger."
722
+ pieceVersion: String
723
+ pieceSource: String
724
+ versionMatch: String
725
+ versionNote: String
726
+ }
727
+
728
+ type Query {
729
+ workflowRuntime: WorkflowRuntimeQueries!
730
+ }
731
+
732
+ type WorkflowStepRunRecord {
733
+ stepId: String!
734
+ stepKey: String!
735
+ pieceName: String!
736
+ "The action the step ran, or the trigger a trigger test sampled."
737
+ blockName: String!
738
+ status: String!
739
+ input: Unknown
740
+ output: Unknown
741
+ port: String
742
+ error: String
743
+ "The thrown error's name, e.g. ReactorAccessDeniedError."
744
+ errorName: String
745
+ startedAt: String
746
+ endedAt: String
747
+ "The piece version that ran; null for an unresolved block."
748
+ pieceVersion: String
749
+ "local | registry | activepieces | npm"
750
+ pieceSource: String
751
+ "exact | compatible | fallback | installed | missing"
752
+ versionMatch: String
753
+ "Why the version that ran differs from the pin."
754
+ versionNote: String
755
+ }
756
+
757
+ type WorkflowRunRecord {
758
+ id: String!
759
+ workflowId: String!
760
+ workflowName: String!
761
+ workflowVersion: Int!
762
+ triggerKind: String!
763
+ triggerPayload: Unknown
764
+ status: String!
765
+ error: String
766
+ errorName: String
767
+ "When the run began executing; a PENDING run's is when it was journaled."
768
+ startedAt: String!
769
+ endedAt: String
770
+ rerunOf: String
771
+ "How many warningNotes the run has; a run with any is not a plain success."
772
+ warnings: Int!
773
+ "Steps that ran a fallback piece version, edges on ports nothing emits."
774
+ warningNotes: [String!]!
775
+ steps: [WorkflowStepRunRecord!]!
776
+ }
777
+
778
+ input WorkflowRunsPagingInput {
779
+ "Page size; default 25, at most 100."
780
+ limit: Int
781
+ "The cursor of the previous page."
782
+ cursor: String
783
+ }
784
+
785
+ type WorkflowRunResultPage {
786
+ items: [WorkflowRunRecord!]!
787
+ hasNextPage: Boolean!
788
+ "True when the page was read after a cursor."
789
+ hasPreviousPage: Boolean!
790
+ "Resumes after this page's last run; null for an empty page."
791
+ cursor: String
792
+ }
793
+
794
+ type WorkflowStepRun {
795
+ stepId: String!
796
+ key: String!
797
+ pieceName: String!
798
+ blockName: String!
799
+ status: String!
800
+ input: Unknown
801
+ output: Unknown
802
+ port: String
803
+ error: String
804
+ errorName: String
805
+ }
806
+
807
+ type WorkflowRunPayload {
808
+ runId: String
809
+ status: String!
810
+ error: String
811
+ errorName: String
812
+ steps: [WorkflowStepRun!]!
813
+ }
814
+
815
+ type WorkflowStepTestResult {
816
+ "Null when the test never started, e.g. an upstream block is untested."
817
+ runId: String
818
+ """
819
+ SUCCEEDED | FAILED | INDETERMINATE. INDETERMINATE is neither: a host call
820
+ the block made timed out, so a write it asked for may well have landed.
821
+ Show it distinctly - it is not a confirmed pass.
822
+ """
823
+ status: String!
824
+ output: Unknown
825
+ error: String
826
+ errorName: String
827
+ durationMs: Int!
828
+ }
829
+
830
+ """
831
+ WorkflowRuntime Mutations
832
+ """
833
+ type WorkflowRuntimeMutations {
834
+ """
835
+ Fires a workflow's manual trigger (the core piece's) and runs it to completion.
836
+ """
837
+ fire(workflowId: String!, payload: Unknown): WorkflowRunPayload!
838
+ """
839
+ Samples the draft trigger and saves it as the trigger's last test. A piece
840
+ trigger runs its test hook (no cursor changes). Of the core piece's
841
+ triggers, manual takes payload, schedule samples a fire now, and webhook
842
+ waits for the next delivery to the workflow's endpoint, up to
843
+ timeoutSeconds (default and cap 300), and that delivery runs nothing.
844
+ """
845
+ testTrigger(
846
+ workflowId: String!
847
+ payload: Unknown
848
+ timeoutSeconds: Int
849
+ driveId: String
850
+ ): Unknown
851
+ """
852
+ Stops a webhook trigger test that is waiting; false when none was.
853
+ """
854
+ cancelTriggerTest(workflowId: String!): Boolean!
855
+ """
856
+ Runs one draft step against the latest test outputs of the blocks it
857
+ reads, journaled as a "test" run and noted as the step's lastTest.
858
+ driveId waits for an unsynced workflow, as for webhookEndpoint.
859
+ """
860
+ testStep(
861
+ workflowId: String!
862
+ stepId: String!
863
+ driveId: String
864
+ ): WorkflowStepTestResult!
865
+ """
866
+ Resumes a FAILED run: succeeded steps replay from the journal,
867
+ execution restarts at the failure. Produces a new run.
868
+ """
869
+ rerun(runId: String!): WorkflowRunPayload!
870
+ """
871
+ Mints a managed secret and returns its ref; the value is stored
872
+ encrypted and is never readable back over any API.
873
+ """
874
+ createSecret(value: String!, label: String): SecretRecord!
875
+ """
876
+ Replaces the value behind an existing ref; documents stay untouched.
877
+ """
878
+ rotateSecret(ref: String!, value: String!): SecretRecord!
879
+ """
880
+ Tombstones a secret; its value becomes unrecoverable.
881
+ """
882
+ deleteSecret(ref: String!): Boolean!
883
+ """
884
+ Runs the piece's auth.validate against the connection's credentials,
885
+ then auth.getConnectionIdentifier for the account label, and records the
886
+ outcome on the connection document.
887
+ """
888
+ checkConnection(connectionId: String!): ConnectionCheckResult!
889
+ """
890
+ Opens an OAuth2 sign-in with the connection's own app (client_id in its
891
+ config, client_secret in its secretRefs). redirectUri is needed only when
892
+ oauthRedirectUri is a bare path. With returnUrl, which must be on the
893
+ caller's origin, the callback sends the browser back there with
894
+ ?ph_oauth=<state> instead of closing the window.
895
+ """
896
+ startOAuth(
897
+ connectionId: String!
898
+ redirectUri: String
899
+ returnUrl: String
900
+ ): OAuthStart!
901
+ }
902
+
903
+ type Mutation {
904
+ workflowRuntime: WorkflowRuntimeMutations!
905
+ }
906
+ `;
907
+ //#endregion
908
+ //#region src/workflow/subgraph.ts
909
+ /** The runtime's read/write surface. The runtime itself is composed by the
910
+ * host, so the subgraph only serves what it is handed. */
911
+ function createWorkflowRuntimeSubgraph(runtime, oauth, access) {
912
+ return class WorkflowRuntimeSubgraph extends BaseSubgraph {
913
+ name = "workflow-runtime";
914
+ typeDefs = schema;
915
+ resolvers = getResolvers(runtime, this.authorizationService, oauth, access, (documentId, ctx) => this.assertCanRead(documentId, ctx));
916
+ additionalContextFields = {};
917
+ };
918
+ }
919
+ //#endregion
920
+ //#region src/workflow-runtime.mts
921
+ /** The npm name the workflow package owns: its HTTP namespace and its models. */
922
+ const WORKFLOW_PACKAGE_NAME = "@powerhousedao/workflow";
923
+ const WORKFLOW_TELEMETRY_SCOPE = "@powerhousedao/reactor-workflow";
924
+ /** The env var and OpenFeature flag key that turns workflows on. */
925
+ const PH_WORKFLOWS_ENABLED = "PH_WORKFLOWS_ENABLED";
926
+ const SINGLETON_LOST = {
927
+ status: "unavailable",
928
+ reason: "workflow-singleton-lost"
929
+ };
930
+ /** Precedence, unchanged from the reactor-api resolver this replaces: the
931
+ * host's option, then PH_WORKFLOWS_ENABLED, then the config file, then off. */
932
+ async function resolveWorkflowsEnabled({ featureFlags, override, configEnabled = false, env = process.env }) {
933
+ if (override !== void 0) return override;
934
+ const raw = env[PH_WORKFLOWS_ENABLED]?.trim();
935
+ if (raw === "1") return true;
936
+ if (raw === "0") return false;
937
+ return featureFlags.getBooleanValue(PH_WORKFLOWS_ENABLED, configEnabled);
938
+ }
939
+ async function assertWorkflowPackageLoadable(load = () => import("@powerhousedao/workflow/document-models")) {
940
+ try {
941
+ await load();
942
+ } catch (error) {
943
+ throw new Error(`Workflows are enabled but ${WORKFLOW_PACKAGE_NAME} could not be loaded`, { cause: error });
944
+ }
945
+ }
946
+ /**
947
+ * Whether a composition failure was the workflow singleton refusing this
948
+ * process, rather than something that should take the boot down.
949
+ *
950
+ * Matched by NAME: the engine loads lazily, and importing it here for the
951
+ * constructor would defeat that. The fields the engine's error carries are
952
+ * typed optional for the same reason.
953
+ */
954
+ function isWorkflowSingletonConflict(error) {
955
+ return error instanceof Error && error.name === "WorkflowSingletonConflictError";
956
+ }
957
+ /**
958
+ * Retries the singleton claim for a host that booted without it, and hands
959
+ * the runtime over once a claim succeeds.
960
+ *
961
+ * Without it a rolling deploy whose slots have different owner names ends
962
+ * with nobody running workflows: the new pod is refused while the old one
963
+ * still holds the lease, and nothing retries once the old pod releases it.
964
+ * Only for a host that never composed; one that lost the lease after
965
+ * composing stays without workflows until it restarts.
966
+ */
967
+ function retryWorkflowSingleton(options) {
968
+ const intervalMs = options.intervalMs ?? 2e4;
969
+ let stopped = false;
970
+ let timer;
971
+ let attempt;
972
+ const run = async () => {
973
+ let workflows;
974
+ try {
975
+ workflows = await options.compose();
976
+ } catch (error) {
977
+ if (!isWorkflowSingletonConflict(error)) options.logger.error("Composing the workflow runtime after the singleton came free failed: @error", error);
978
+ schedule();
979
+ return;
980
+ }
981
+ if (stopped) {
982
+ await workflows.stop();
983
+ return;
984
+ }
985
+ options.logger.info("Claimed the workflow singleton after boot; starting the workflow runtime");
986
+ try {
987
+ await options.onComposed(workflows);
988
+ } catch (error) {
989
+ options.logger.error("Starting the workflow runtime after the singleton came free failed: @error", error);
990
+ schedule();
991
+ }
992
+ };
993
+ const schedule = () => {
994
+ if (stopped) return;
995
+ timer = setTimeout(() => {
996
+ timer = void 0;
997
+ attempt = run().finally(() => {
998
+ attempt = void 0;
999
+ });
1000
+ }, intervalMs);
1001
+ timer.unref();
1002
+ };
1003
+ schedule();
1004
+ return { async stop() {
1005
+ stopped = true;
1006
+ if (timer) clearTimeout(timer);
1007
+ timer = void 0;
1008
+ await attempt?.catch(() => void 0);
1009
+ } };
1010
+ }
1011
+ /**
1012
+ * What a host does once its composed runtime has shut down for losing the
1013
+ * workflow singleton.
1014
+ *
1015
+ * Taken over by another claim: that process runs workflows now, so this one
1016
+ * stays without them until it restarts. Unrenewable with no takeover seen (a
1017
+ * database blip): nothing else runs them, so the process goes down through
1018
+ * the fatal shutdown and its supervisor restarts it, which re-claims at boot.
1019
+ * A host with no fatal shutdown installed (embedded) stays without workflows
1020
+ * and says a restart is needed.
1021
+ */
1022
+ function workflowSingletonLossHandler(logger, fatal = triggerFatalShutdown) {
1023
+ return (loss) => {
1024
+ if (loss.reason === "taken") {
1025
+ logger.error(`Another process ("${loss.heldBy ?? "unknown"}") took the workflow singleton. This Switchboard has stopped its workflow runtime and runs no workflows until it is restarted; everything else serves normally.`);
1026
+ return;
1027
+ }
1028
+ const error = /* @__PURE__ */ new Error(`The workflow singleton lease could not be renewed for ${Math.round(loss.silentMs)}ms; no other process was seen taking it over`);
1029
+ if (fatal("Workflow singleton lease unrenewable", error)) return;
1030
+ logger.error(`${error.message}. This Switchboard has stopped its workflow runtime and runs no workflows until it is restarted.`);
1031
+ };
1032
+ }
1033
+ function modelManifestSource(builder) {
1034
+ return {
1035
+ modelManifest: () => builder.getResolvedModelManifest() ?? [],
1036
+ modelEntries: (documentType) => builder.getImportableEntries(documentType)
1037
+ };
1038
+ }
1039
+ function readAssertion(authorizationService, reactorClient) {
1040
+ const resolveCanonical = createCanonicalDocumentIdResolver(reactorClient);
1041
+ const hostCanRead = async (identifier, ctx) => {
1042
+ if (authorizationService.isSupremeAdmin(ctx.user?.address)) return;
1043
+ if (authorizationService.config.policy !== AuthorizationPolicy.DOCUMENT_PERMISSIONS) throw new ForbiddenError();
1044
+ let documentId;
1045
+ try {
1046
+ documentId = await resolveCanonical(identifier);
1047
+ } catch {
1048
+ throw new ForbiddenError();
1049
+ }
1050
+ if (!await authorizationService.canRead(documentId, ctx.user?.address)) throw new ForbiddenError("to read this document");
1051
+ };
1052
+ return async (identifier, caller) => {
1053
+ const ctx = caller;
1054
+ await hostCanRead(identifier, ctx);
1055
+ let served;
1056
+ try {
1057
+ served = await reactorClient.isServed(identifier, { subject: callerSubject(ctx.user) });
1058
+ } catch {
1059
+ throw new ForbiddenError();
1060
+ }
1061
+ if (!served) throw new ForbiddenError("to read this document");
1062
+ };
1063
+ }
1064
+ /** The same, for a design-time call that writes what it names. */
1065
+ function writeAssertion(authorizationService, reactorClient) {
1066
+ const resolveCanonical = createCanonicalDocumentIdResolver(reactorClient);
1067
+ return async (identifier, caller) => {
1068
+ const ctx = caller;
1069
+ if (authorizationService.isSupremeAdmin(ctx.user?.address)) return;
1070
+ if (authorizationService.config.policy !== AuthorizationPolicy.DOCUMENT_PERMISSIONS) throw new ForbiddenError();
1071
+ let documentId;
1072
+ try {
1073
+ documentId = await resolveCanonical(identifier);
1074
+ } catch {
1075
+ throw new ForbiddenError();
1076
+ }
1077
+ if (!await authorizationService.canWrite(documentId, ctx.user?.address)) throw new ForbiddenError("to write this document");
1078
+ };
1079
+ }
1080
+ /** What the reactor enforces and who it signs as; unknown counts as enforced. */
1081
+ function reactorAccessOf(clientModule) {
1082
+ const flags = clientModule?.reactorModule?.featureFlags;
1083
+ const signer = clientModule?.signer;
1084
+ const key = signer?.app?.key;
1085
+ const identity = key ? {
1086
+ address: signer.user?.address ?? null,
1087
+ key
1088
+ } : null;
1089
+ return {
1090
+ authEnforcement: flags ? flags.authEnforcement : true,
1091
+ authConditions: flags?.authConditions === true,
1092
+ identity
1093
+ };
1094
+ }
1095
+ /** Whom a run's created documents also grant: the host, as §8 grants it. */
1096
+ function hostPrincipalOf(access) {
1097
+ const identity = access.identity;
1098
+ if (!identity) return void 0;
1099
+ if (access.authConditions) return { match: { eq: [{ attr: "subject.key" }, { lit: identity.key }] } };
1100
+ return identity.address ? { address: identity.address } : void 0;
1101
+ }
1102
+ /** Who the host signs as, so a publish it signs makes no run user. */
1103
+ function hostIdentityOf(access) {
1104
+ const identity = access.identity;
1105
+ if (!identity) return void 0;
1106
+ return identity.address ? {
1107
+ address: identity.address,
1108
+ key: identity.key
1109
+ } : { key: identity.key };
1110
+ }
1111
+ const REFERENCE_INDEX_RETRIES = 8;
1112
+ const REFERENCE_INDEX_RETRY_MS = 250;
1113
+ /** A step reads an attachment the way the download route serves one: when the
1114
+ * run's user may read a document that references it. The candidates are the
1115
+ * documents the run was handed; the reference index can trail the operation
1116
+ * that fired the trigger, so a denial is retried briefly. */
1117
+ function attachmentReadPolicy(access, retryMs = REFERENCE_INDEX_RETRY_MS) {
1118
+ return async (request) => {
1119
+ try {
1120
+ if (parseRef(request.ref).version !== 1) return false;
1121
+ } catch {
1122
+ return false;
1123
+ }
1124
+ if (!access || request.documentIds.length === 0) return false;
1125
+ const subject = request.runUser?.subject;
1126
+ const caller = {
1127
+ ...subject?.address ? { userAddress: subject.address } : {},
1128
+ ...subject?.key ? { appKey: subject.key } : {}
1129
+ };
1130
+ for (let attempt = 0; attempt <= REFERENCE_INDEX_RETRIES; attempt++) {
1131
+ for (const documentId of request.documentIds) if ((await access.canReadAttachment({
1132
+ documentId,
1133
+ attachmentRef: request.ref,
1134
+ ...caller
1135
+ })).kind === "allowed") return true;
1136
+ if (attempt < REFERENCE_INDEX_RETRIES) await new Promise((resolve) => setTimeout(resolve, retryMs));
1137
+ }
1138
+ return false;
1139
+ };
1140
+ }
1141
+ async function registerWorkflowTriggersReadModel(engine, runtime, clientModule, registration) {
1142
+ const reactorModule = clientModule?.reactorModule;
1143
+ if (!reactorModule) return {
1144
+ status: "unavailable",
1145
+ reason: "in-process-reactor-module-unavailable"
1146
+ };
1147
+ const coordinator = reactorModule.readModelCoordinator;
1148
+ if (!supportsLiveReadModelRegistration(coordinator)) return {
1149
+ status: "unavailable",
1150
+ reason: "live-read-model-registration-unsupported"
1151
+ };
1152
+ const readModel = new engine.WorkflowTriggersReadModel(reactorModule.database.withSchema(REACTOR_SCHEMA), reactorModule.operationIndex, reactorModule.writeCache, reactorModule.processorManagerConsistencyTracker, runtime);
1153
+ await readModel.init();
1154
+ if (registration.tornDown) return SINGLETON_LOST;
1155
+ coordinator.addReadModel(readModel, engine.WORKFLOW_TRIGGERS_READ_MODEL_STAGE);
1156
+ registration.detach = () => coordinator.removeReadModel(readModel);
1157
+ return { status: "available" };
1158
+ }
1159
+ function bindPackagePieces(registry, source) {
1160
+ const apply = (byPackage) => {
1161
+ registry.setPieces([...byPackage.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).flatMap(([, pieces]) => pieces));
1162
+ };
1163
+ apply(source.getPieces());
1164
+ source.onPiecesChange(apply);
1165
+ }
1166
+ async function composeWorkflowRuntime(deps) {
1167
+ const load = deps.load ?? (() => import("@powerhousedao/reactor-workflow"));
1168
+ let engine;
1169
+ try {
1170
+ engine = await load();
1171
+ } catch (error) {
1172
+ throw new Error("Workflows are enabled but @powerhousedao/reactor-workflow could not be loaded", { cause: error });
1173
+ }
1174
+ const loss = { lost: false };
1175
+ const lease = deps.singletonLease === false ? void 0 : await engine.acquireWorkflowSingletonLease({
1176
+ relationalDb: deps.relationalDb,
1177
+ logger: deps.logger,
1178
+ ...deps.storageId ? { storageId: deps.storageId } : {},
1179
+ selfFence: deps.exclusiveJournal !== true,
1180
+ onLost: (lost) => {
1181
+ loss.lost = true;
1182
+ if (lost.reason === "taken") loss.heldBy = lost.heldBy;
1183
+ loss.tearDown?.();
1184
+ if (loss.composed) deps.onSingletonLost?.(lost);
1185
+ }
1186
+ });
1187
+ try {
1188
+ const composed = await composeClaimed(engine, deps, lease, loss);
1189
+ if (loss.lost) throw singletonLostError(engine, loss, lease);
1190
+ loss.composed = true;
1191
+ return composed;
1192
+ } catch (error) {
1193
+ loss.tearDown?.();
1194
+ await lease?.release();
1195
+ throw error;
1196
+ }
1197
+ }
1198
+ function singletonLostError(engine, loss, lease) {
1199
+ return new engine.WorkflowSingletonConflictError(loss.heldBy ?? "unknown", "unknown", lease?.owner ?? "unknown");
1200
+ }
1201
+ async function composeClaimed(engine, deps, lease, loss) {
1202
+ engine.setPieceRegistryUrl(deps.pieceRegistryUrl);
1203
+ if (deps.pieces) bindPackagePieces(engine.packagePieces, deps.pieces);
1204
+ if (loss.lost) throw singletonLostError(engine, loss, lease);
1205
+ const access = reactorAccessOf(deps.clientModule);
1206
+ const models = deps.models;
1207
+ const runtime = engine.createWorkflowRuntime({
1208
+ relationalDb: deps.relationalDb,
1209
+ secretsKeyFile: deps.secretsKeyFile,
1210
+ reactorClient: deps.reactorClient,
1211
+ assertCanRead: readAssertion(deps.authorizationService, deps.reactorClient),
1212
+ subjectOf: (caller) => callerSubject(caller.user),
1213
+ assertCanWrite: writeAssertion(deps.authorizationService, deps.reactorClient),
1214
+ ...deps.clientModule?.reactorModule ? { authEnforcement: access.authEnforcement } : {},
1215
+ hostPrincipal: hostPrincipalOf(access),
1216
+ hostIdentity: hostIdentityOf(access),
1217
+ ...models ? {
1218
+ modelManifest: () => models.modelManifest(),
1219
+ modelEntries: (documentType) => models.modelEntries(documentType)
1220
+ } : {},
1221
+ webhooks: deps.webhooks,
1222
+ attachments: deps.attachments,
1223
+ canReadAttachmentRef: attachmentReadPolicy(deps.attachmentAccess),
1224
+ logger: deps.logger,
1225
+ ...deps.reactorThreads ? { reactorThreads: deps.reactorThreads } : {},
1226
+ ...deps.telemetry ? { telemetry: deps.telemetry } : {}
1227
+ });
1228
+ const routes = {};
1229
+ const registration = { tornDown: false };
1230
+ const tearDown = () => {
1231
+ if (registration.tornDown) return;
1232
+ registration.tornDown = true;
1233
+ routes.oauthCallback?.dispose();
1234
+ runtime.shutdown();
1235
+ registration.detach?.();
1236
+ };
1237
+ loss.tearDown = tearDown;
1238
+ const triggers = await registerWorkflowTriggersReadModel(engine, runtime, deps.clientModule, registration);
1239
+ if (registration.tornDown) throw singletonLostError(engine, loss, lease);
1240
+ if (triggers.status === "available") deps.logger.info(`Workflow trigger read model registered (${engine.WORKFLOW_TRIGGERS_READ_MODEL}, ${engine.WORKFLOW_TRIGGERS_READ_MODEL_STAGE})`);
1241
+ else deps.logger.error("Workflow document triggers are NOT armed (@reason): this reactor's read-model coordinator takes no live registration, so no document operation reaches the runtime. Webhook and schedule triggers are unaffected.", triggers.reason);
1242
+ let stopped = false;
1243
+ if (deps.http) routes.oauthCallback = registerOAuthCallback(deps.http, runtime);
1244
+ return {
1245
+ subgraph: createWorkflowRuntimeSubgraph(runtime, deps.http ? { callbackUrl: callbackUrlOf(deps.http) } : void 0, access),
1246
+ get triggers() {
1247
+ return loss.lost ? SINGLETON_LOST : triggers;
1248
+ },
1249
+ ...lease ? { singletonOwner: lease.owner } : {},
1250
+ async start() {
1251
+ if (registration.tornDown) return;
1252
+ await runtime.registerWebhookEndpoint();
1253
+ if (loss.lost || stopped) return;
1254
+ runtime.startTriggerSupervisor();
1255
+ runtime.warmPieceSearch();
1256
+ },
1257
+ async stop() {
1258
+ if (stopped) return;
1259
+ stopped = true;
1260
+ tearDown();
1261
+ await lease?.release();
1262
+ }
1263
+ };
1264
+ }
1265
+ //#endregion
1266
+ //#region src/plugins/workflows.mts
1267
+ const workflowsPlugin = {
1268
+ name: "switchboard-workflows",
1269
+ appliesTo: "switchboard",
1270
+ hooks: {
1271
+ transformServerOptions: (options) => {
1272
+ const current = options.workflows;
1273
+ if (current?.enabled === false) return options;
1274
+ return {
1275
+ ...options,
1276
+ workflows: {
1277
+ ...current,
1278
+ enabled: true
1279
+ }
1280
+ };
1281
+ },
1282
+ onSubgraphsRegistering: async (ctx) => {
1283
+ const orchestration = ctx.workflowsOrchestration;
1284
+ if (!orchestration?.enabled) return;
1285
+ const logger = ctx.logger;
1286
+ const lateSubgraphs = ctx.lateSubgraphs;
1287
+ let workflows;
1288
+ let workflowsRetry;
1289
+ try {
1290
+ workflows = await orchestration.composeWorkflows();
1291
+ } catch (error) {
1292
+ if (!isWorkflowSingletonConflict(error)) throw error;
1293
+ 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.`);
1294
+ workflowsRetry = retryWorkflowSingleton({
1295
+ compose: orchestration.composeWorkflows,
1296
+ onComposed: async (composed) => {
1297
+ try {
1298
+ await composed.start();
1299
+ } catch (error) {
1300
+ try {
1301
+ await composed.stop();
1302
+ } catch (stopError) {
1303
+ logger.error("Stopping the late workflow runtime failed: @error", stopError);
1304
+ }
1305
+ throw error;
1306
+ }
1307
+ logger.info("Workflow runtime started");
1308
+ ctx.workflows = composed;
1309
+ await orchestration.registerWorkflowSubgraph(composed);
1310
+ try {
1311
+ await orchestration.updateRouter();
1312
+ } catch (error) {
1313
+ orchestration.reportMountFailure(error);
1314
+ }
1315
+ },
1316
+ logger
1317
+ });
1318
+ }
1319
+ ctx.workflowsRetry = workflowsRetry;
1320
+ if (workflows) {
1321
+ ctx.workflows = workflows;
1322
+ lateSubgraphs.push(orchestration.registerWorkflowSubgraph(workflows));
1323
+ await workflows.start();
1324
+ logger.info("Workflow runtime started");
1325
+ orchestration.setWorkflowsFact();
1326
+ }
1327
+ },
1328
+ onShutdown: async (ctx) => {
1329
+ await ctx.workflowsRetry?.stop();
1330
+ await ctx.workflows?.stop();
1331
+ }
1332
+ }
1333
+ };
1334
+ //#endregion
1335
+ export { composeWorkflowRuntime as a, resolveWorkflowsEnabled as c, installFatalErrorShutdown as d, triggerFatalShutdown as f, assertWorkflowPackageLoadable as i, retryWorkflowSingleton as l, WORKFLOW_PACKAGE_NAME as n, isWorkflowSingletonConflict as o, WORKFLOW_TELEMETRY_SCOPE as r, modelManifestSource as s, workflowsPlugin as t, workflowSingletonLossHandler as u };
1336
+
1337
+ //# sourceMappingURL=workflows-qKtqZhn3.mjs.map
1338
+ //# debugId=3ac978b6-5ddf-546e-848d-1557f6ab7aeb