@powerhousedao/reactor-workflow 6.2.3 → 6.3.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2466 +0,0 @@
1
- import { A as REACTOR_CREATE, D as jsonSafe, F as REACTOR_MODELS, I as STORE_DELETE, J as getActions, L as STORE_GET, M as REACTOR_FIND, N as REACTOR_GET, O as LOG_WRITE, P as REACTOR_MODEL, R as STORE_PUT, a as redactMessage, c as DEFAULT_EGRESS_POLICY, i as redactError, j as REACTOR_EXECUTE, k as OUTPUT_UPDATE, n as containsRedactedMarker, o as rememberSecrets, r as redact, s as secretsFor, t as collectSecretValues, v as rewriteFileRefs, x as configuredMaxFileBytes, z as buildDescriptor } from "./redact-LRWHJGW9.js";
2
- import { AppConnectionType, PieceCategory, Property, TriggerStrategy, createAction, createPiece, createTrigger } from "@powerhousedao/pieces-framework";
3
- import { execFile, fork } from "node:child_process";
4
- import { existsSync } from "node:fs";
5
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
6
- import path from "node:path";
7
- import { promisify } from "node:util";
8
- import { gunzip } from "node:zlib";
9
- import { childLogger } from "document-model";
10
- import { fileURLToPath } from "node:url";
11
- import { BRANCH_PORTS, CORE_PIECE_NAME, CORE_PIECE_NAME as CORE_PIECE_NAME$1, NEXT_PORT, PIECE_ACTION_PORTS, SCHEDULE_MODES, SCHEDULE_UNIT_MS, TRIGGER_PORTS, undeclaredPortEdges } from "@powerhousedao/pieces-framework/workflow";
12
- import { createHash, randomUUID } from "node:crypto";
13
- import { blockKey, isExactVersion } from "@powerhousedao/pieces-framework/block-type";
14
- //#region src/pieces/activepieces/registry-source.ts
15
- const logger$2 = childLogger(["workflow", "piece-registry"]);
16
- function source(baseUrl) {
17
- return {
18
- baseUrl,
19
- catalogUrl: (suggestions) => suggestions ? `${baseUrl}/pieces?suggestionType=ACTION_AND_TRIGGER` : `${baseUrl}/pieces`,
20
- pieceUrl: (name) => `${baseUrl}/pieces/${encodeURIComponent(name)}`,
21
- tarballUrl: (name, version) => `${baseUrl}/-/pieces/bundled/${name.replace("/", "-")}-${version}.tgz`
22
- };
23
- }
24
- let configured;
25
- function setPieceRegistryUrl(url) {
26
- const trimmed = url?.trim().replace(/\/+$/, "") ?? "";
27
- if (trimmed === "") {
28
- configured = void 0;
29
- return;
30
- }
31
- if (configured?.baseUrl === trimmed) return;
32
- configured = source(trimmed);
33
- logger$2.info(`Pieces may be fetched from ${configured.baseUrl}`);
34
- }
35
- function pieceRegistrySource() {
36
- return configured;
37
- }
38
- //#endregion
39
- //#region src/pieces/activepieces/fetch.ts
40
- const gunzip$1 = promisify(gunzip);
41
- const DEFAULT_CDN_PIECES_URL = "https://cdn.activepieces.com/pieces/bundled";
42
- const DEFAULT_NPM_REGISTRY_URL = "https://registry.npmjs.org";
43
- let cdnPiecesUrl = DEFAULT_CDN_PIECES_URL;
44
- let npmRegistryUrl = DEFAULT_NPM_REGISTRY_URL;
45
- function npmRegistryBaseUrl() {
46
- return npmRegistryUrl;
47
- }
48
- function cdnTarballUrl(name, version) {
49
- return `${cdnPiecesUrl}/${name.replace("/", "-")}-${version}.tgz`;
50
- }
51
- function npmTarballUrl(name, version) {
52
- const unscoped = name.startsWith("@") ? name.split("/")[1] : name;
53
- return `${npmRegistryUrl}/${name}/-/${unscoped}-${version}.tgz`;
54
- }
55
- const NPM_NAME_RE = /^(@[a-z0-9][a-z0-9-_.]*\/)?[a-z0-9][a-z0-9-_.]*$/;
56
- const NPM_VERSION_RE = /^[A-Za-z0-9][A-Za-z0-9.+-]*$/;
57
- function assertValidPackageCoordinate(name, version) {
58
- if (!NPM_NAME_RE.test(name)) throw new Error(`Invalid piece package name: ${name}`);
59
- if (!NPM_VERSION_RE.test(version)) throw new Error(`Invalid piece package version: ${version}`);
60
- }
61
- function assertWithinCacheDir(dir, cacheDir) {
62
- const root = path.resolve(cacheDir);
63
- const resolved = path.resolve(dir);
64
- if (resolved !== root && !resolved.startsWith(root + path.sep)) throw new Error(`Resolved piece cache path escapes cacheDir: ${dir}`);
65
- }
66
- function readString(header, offset, length) {
67
- const slice = header.subarray(offset, offset + length);
68
- const nul = slice.indexOf(0);
69
- return slice.subarray(0, nul === -1 ? length : nul).toString("utf8");
70
- }
71
- const MAX_EXTRACTED_BYTES = 67108864;
72
- const MAX_COMPRESSED_BYTES = 67108864;
73
- async function extractTarball(tgz, dest) {
74
- const tar = await gunzip$1(tgz, { maxOutputLength: MAX_EXTRACTED_BYTES }).catch((error) => {
75
- throw new Error(`Failed to decompress piece bundle: ${String(error)}`);
76
- });
77
- let offset = 0;
78
- while (offset + 512 <= tar.length) {
79
- const header = tar.subarray(offset, offset + 512);
80
- if (header.every((byte) => byte === 0)) break;
81
- const name = readString(header, 0, 100);
82
- const prefix = readString(header, 345, 155);
83
- const size = parseInt(readString(header, 124, 12).trim() || "0", 8);
84
- const type = String.fromCharCode(header[156]);
85
- offset += 512;
86
- if ((type === "0" || type === "\0" || type === "") && size >= 0) {
87
- const rel = (prefix ? `${prefix}/${name}` : name).replace(/^[^/]+\//, "");
88
- const target = path.resolve(dest, rel);
89
- if (rel && target.startsWith(path.resolve(dest) + path.sep)) {
90
- await mkdir(path.dirname(target), { recursive: true });
91
- await writeFile(target, tar.subarray(offset, offset + size));
92
- }
93
- }
94
- offset += Math.ceil(size / 512) * 512;
95
- }
96
- }
97
- async function readBoundedBody(response, url) {
98
- const declared = response.headers.get("content-length");
99
- if (declared && Number(declared) > MAX_COMPRESSED_BYTES) throw new Error(`${url} exceeds the ${MAX_COMPRESSED_BYTES}-byte compressed size cap (Content-Length: ${declared})`);
100
- if (!response.body) return Buffer.from(await response.arrayBuffer());
101
- const reader = response.body.getReader();
102
- const chunks = [];
103
- let total = 0;
104
- for (;;) {
105
- const { done, value } = await reader.read();
106
- if (done) break;
107
- total += value.byteLength;
108
- if (total > MAX_COMPRESSED_BYTES) {
109
- await reader.cancel();
110
- throw new Error(`${url} exceeds the ${MAX_COMPRESSED_BYTES}-byte compressed size cap`);
111
- }
112
- chunks.push(value);
113
- }
114
- return Buffer.concat(chunks);
115
- }
116
- function tarballSources(name, version, only) {
117
- const all = allTarballSources(name, version);
118
- return only ? all.filter(({ source }) => only.includes(source)) : all;
119
- }
120
- function allTarballSources(name, version) {
121
- const registry = pieceRegistrySource();
122
- return [
123
- ...registry ? [{
124
- source: "registry",
125
- url: registry.tarballUrl(name, version)
126
- }] : [],
127
- {
128
- source: "cdn",
129
- url: cdnTarballUrl(name, version)
130
- },
131
- {
132
- source: "npm",
133
- url: npmTarballUrl(name, version)
134
- }
135
- ];
136
- }
137
- async function downloadTarball(name, version, timeoutMs, only) {
138
- const sources = tarballSources(name, version, only);
139
- let lastError;
140
- for (const { source, url } of sources) try {
141
- const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
142
- if (!response.ok) {
143
- lastError = /* @__PURE__ */ new Error(`${url} responded ${response.status}`);
144
- continue;
145
- }
146
- return {
147
- tgz: await readBoundedBody(response, url),
148
- source
149
- };
150
- } catch (error) {
151
- lastError = error;
152
- }
153
- throw new Error(`Failed to fetch piece bundle ${name}@${version}: ${String(lastError)}`);
154
- }
155
- async function extractDownloadedTarball(name, version, timeoutMs, staging, only) {
156
- const { tgz, source } = await downloadTarball(name, version, timeoutMs, only);
157
- await extractTarball(tgz, staging);
158
- return source;
159
- }
160
- async function downloadPackagePiece(entryUrl, staging, timeoutMs) {
161
- const base = entryUrl.slice(0, entryUrl.lastIndexOf("/") + 1);
162
- const fetchInto = async (url, name) => {
163
- const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
164
- if (!response.ok) throw new Error(`${url} responded ${response.status}`);
165
- const body = await readBoundedBody(response, url);
166
- await writeFile(path.join(staging, name), body);
167
- return body;
168
- };
169
- await mkdir(staging, { recursive: true });
170
- const manifest = await fetchInto(`${base}package.json`, "package.json");
171
- const main = JSON.parse(manifest.toString("utf8")).main;
172
- const entry = typeof main === "string" && main !== "" ? main : entryUrl.slice(base.length);
173
- if (entry.includes("/") || entry.includes("\\") || entry.startsWith(".")) throw new Error(`Piece manifest at ${base} names an unusable main: ${entry}`);
174
- await fetchInto(`${base}${entry}`, entry);
175
- return "package";
176
- }
177
- function bundleDirFor(options) {
178
- const leaf = `${options.name.replace("/", "-")}-${options.version}`;
179
- return options.cacheScope ? path.join(options.cacheDir, options.cacheScope, leaf) : path.join(options.cacheDir, leaf);
180
- }
181
- async function fetchPieceBundle(options) {
182
- const { name, version, cacheDir, timeoutMs = 3e4 } = options;
183
- assertValidPackageCoordinate(name, version);
184
- const dir = bundleDirFor(options);
185
- assertWithinCacheDir(dir, cacheDir);
186
- if (existsSync(path.join(dir, "package.json"))) return {
187
- dir,
188
- source: "cache",
189
- dependencies: await readDependencies(dir),
190
- installed: false
191
- };
192
- const staging = `${dir}.tmp-${process.pid}`;
193
- await rm(staging, {
194
- recursive: true,
195
- force: true
196
- });
197
- const source = options.entryUrl ? await downloadPackagePiece(options.entryUrl, staging, timeoutMs) : await extractDownloadedTarball(name, version, timeoutMs, staging, options.sources);
198
- await rm(dir, {
199
- recursive: true,
200
- force: true
201
- });
202
- try {
203
- await rename(staging, dir);
204
- } catch (error) {
205
- await rm(staging, {
206
- recursive: true,
207
- force: true
208
- });
209
- if (!existsSync(path.join(dir, "package.json"))) throw error;
210
- }
211
- return {
212
- dir,
213
- source,
214
- dependencies: await readDependencies(dir),
215
- installed: false
216
- };
217
- }
218
- const inFlight = /* @__PURE__ */ new Map();
219
- async function ensurePieceBundle(options) {
220
- const key = bundleDirFor(options);
221
- const pending = inFlight.get(key);
222
- if (pending) return pending;
223
- const started = resolveBundle(options).finally(() => inFlight.delete(key));
224
- inFlight.set(key, started);
225
- return started;
226
- }
227
- async function resolveBundle(options) {
228
- const fetched = await fetchPieceBundle(options);
229
- if (Object.keys(fetched.dependencies).length === 0) return fetched;
230
- return installPieceBundle(options, fetched);
231
- }
232
- async function installPieceBundle(options, fetched) {
233
- const { name, version, cacheDir } = options;
234
- const timeoutMs = options.installTimeoutMs ?? INSTALL_TIMEOUT_MS;
235
- const workspace = `${bundleDirFor(options)}.install`;
236
- assertWithinCacheDir(workspace, cacheDir);
237
- const dir = path.join(workspace, "node_modules", name);
238
- if (existsSync(path.join(workspace, INSTALL_READY_MARKER)) && existsSync(path.join(dir, "package.json"))) return {
239
- dir,
240
- source: "cache",
241
- dependencies: fetched.dependencies,
242
- installed: true
243
- };
244
- try {
245
- await stageInstallWorkspace(workspace, options);
246
- await runInstall(workspace, timeoutMs);
247
- await writeFile(path.join(workspace, INSTALL_READY_MARKER), "true");
248
- } catch (error) {
249
- await rm(workspace, {
250
- recursive: true,
251
- force: true
252
- }).catch(() => void 0);
253
- throw notInstallable(name, version, fetched.dependencies, error);
254
- }
255
- return {
256
- dir,
257
- source: fetched.source,
258
- dependencies: fetched.dependencies,
259
- installed: true
260
- };
261
- }
262
- async function stageInstallWorkspace(workspace, options) {
263
- const { tgz } = await downloadTarball(options.name, options.version, options.timeoutMs ?? 3e4, options.sources);
264
- await rm(workspace, {
265
- recursive: true,
266
- force: true
267
- });
268
- await mkdir(workspace, { recursive: true });
269
- await writeFile(path.join(workspace, "bundle.tgz"), tgz);
270
- await writeFile(path.join(workspace, "package.json"), JSON.stringify({
271
- name: "piece-workspace",
272
- version: "1.0.0",
273
- private: true,
274
- dependencies: { [options.name]: "file:./bundle.tgz" }
275
- }));
276
- }
277
- const MAX_LISTED_DEPENDENCIES = 5;
278
- const INSTALL_READY_MARKER = "ready";
279
- const INSTALL_TIMEOUT_MS = Number(process.env.PH_WORKFLOWS_PIECE_INSTALL_TIMEOUT_MS) || 12e4;
280
- function installCommand() {
281
- const windows = process.platform === "win32";
282
- return {
283
- file: windows ? "npm.cmd" : "npm",
284
- args: [
285
- "install",
286
- "--ignore-scripts",
287
- "--no-audit",
288
- "--no-fund",
289
- "--omit=dev",
290
- "--loglevel=error"
291
- ],
292
- shell: windows
293
- };
294
- }
295
- async function runInstall(cwd, timeoutMs) {
296
- const { file, args, shell } = installCommand();
297
- await new Promise((resolve, reject) => {
298
- execFile(file, args, {
299
- cwd,
300
- timeout: timeoutMs,
301
- shell,
302
- windowsHide: true
303
- }, (error, _stdout, stderr) => {
304
- if (!error) return resolve();
305
- const killed = error.killed === true;
306
- const reported = stderr.split("\n").filter((line) => !line.includes("A complete log of this run")).join("\n").trim();
307
- reject(new Error(killed ? `timed out after ${timeoutMs}ms` : reported || error.message));
308
- });
309
- });
310
- }
311
- var PieceNotInstallableError = class extends Error {
312
- packageName;
313
- version;
314
- dependencies;
315
- cause;
316
- constructor(packageName, version, dependencies, cause) {
317
- const declared = Object.keys(dependencies);
318
- const listed = declared.slice(0, MAX_LISTED_DEPENDENCIES).map((dep) => `${dep}@${dependencies[dep]}`);
319
- const rest = declared.length - listed.length;
320
- const count = declared.length === 1 ? "a dependency" : `${declared.length} dependencies`;
321
- super(`Piece bundle ${packageName}@${version} carries ${count} it does not bundle (${listed.join(", ")}${rest > 0 ? `, and ${rest} more` : ""}), and installing them here failed: ${reasonOf(cause)}. The install runs once per version, with lifecycle scripts disabled, so a dependency that builds or downloads on install cannot be prepared this way. Check that this reactor can reach an npm registry, or run a piece whose bundle inlines what it needs.`);
322
- this.packageName = packageName;
323
- this.version = version;
324
- this.dependencies = dependencies;
325
- this.cause = cause;
326
- this.name = "PieceNotInstallableError";
327
- }
328
- };
329
- function reasonOf(cause) {
330
- return cause instanceof Error ? cause.message : String(cause);
331
- }
332
- function notInstallable(name, version, dependencies, cause) {
333
- return new PieceNotInstallableError(name, version, dependencies, cause);
334
- }
335
- async function readDependencies(dir) {
336
- const raw = await readFile(path.join(dir, "package.json"), "utf8");
337
- return JSON.parse(raw).dependencies ?? {};
338
- }
339
- //#endregion
340
- //#region src/pieces/activepieces/resolver.ts
341
- const DOWNLOADS = {
342
- registry: ["registry"],
343
- activepieces: ["cdn", "npm"],
344
- npm: ["npm"]
345
- };
346
- var PieceNotInstalledError = class extends Error {
347
- constructor(name, version) {
348
- super(`Piece ${name}@${version} is not installed on this reactor`);
349
- this.name = "PieceNotInstalledError";
350
- }
351
- };
352
- function sourcedResolver(options) {
353
- const fetch = (target, extra) => ensurePieceBundle({
354
- name: target.name,
355
- version: target.version,
356
- cacheDir: options.cacheDir,
357
- ...extra.entryUrl ? { entryUrl: extra.entryUrl } : {},
358
- ...extra.sources ? { sources: extra.sources } : {},
359
- ...extra.scope ? { cacheScope: extra.scope } : {},
360
- ...options.timeoutMs ? { timeoutMs: options.timeoutMs } : {}
361
- });
362
- return { async resolve(target) {
363
- const { name, version, source } = target;
364
- if (source === "local") {
365
- const local = await options.lookup?.(name);
366
- if (!local || local.version !== version) throw new PieceNotInstalledError(name, version);
367
- if (local.entryPath || local.bundleDir) return {
368
- name,
369
- version,
370
- ...local.entryPath ? { entryPath: local.entryPath } : {},
371
- ...local.bundleDir ? { bundleDir: local.bundleDir } : {},
372
- local: true
373
- };
374
- if (!local.entryUrl) throw new PieceNotInstalledError(name, version);
375
- return {
376
- name,
377
- version,
378
- bundleDir: (await fetch(target, {
379
- entryUrl: local.entryUrl,
380
- scope: "local"
381
- })).dir,
382
- local: true
383
- };
384
- }
385
- return {
386
- name,
387
- version,
388
- bundleDir: (await fetch(target, source ? {
389
- sources: DOWNLOADS[source],
390
- scope: source
391
- } : {})).dir,
392
- local: false
393
- };
394
- } };
395
- }
396
- function bundleResolver(options) {
397
- return sourcedResolver(options);
398
- }
399
- function pieceModuleRef(piece) {
400
- return piece.entryPath ? { entryPath: piece.entryPath } : { bundleDir: piece.bundleDir };
401
- }
402
- //#endregion
403
- //#region src/pieces/activepieces/worker/transport.ts
404
- function defaultEntryPath() {
405
- let dir = path.dirname(fileURLToPath(import.meta.url));
406
- while (!existsSync(path.join(dir, "package.json"))) {
407
- const parent = path.dirname(dir);
408
- if (parent === dir) throw new Error("Could not locate package root");
409
- dir = parent;
410
- }
411
- const entry = path.join(dir, "dist", "worker-entry.js");
412
- if (!existsSync(entry)) throw new Error(`Worker entry not built at ${entry} — run pnpm build`);
413
- return entry;
414
- }
415
- function createForkTransport(entryPath) {
416
- const child = fork(entryPath, [], {
417
- env: {},
418
- execArgv: [],
419
- serialization: "advanced",
420
- stdio: [
421
- "ignore",
422
- "ignore",
423
- "ignore",
424
- "ipc"
425
- ]
426
- });
427
- const exitListeners = /* @__PURE__ */ new Map();
428
- return {
429
- get connected() {
430
- return child.connected;
431
- },
432
- send(message) {
433
- child.send(message);
434
- },
435
- on(event, listener) {
436
- if (event === "exit") {
437
- const adapted = (code, signal) => listener({
438
- code,
439
- signal
440
- });
441
- exitListeners.set(listener, adapted);
442
- child.on("exit", adapted);
443
- return;
444
- }
445
- child.on("message", listener);
446
- },
447
- off(event, listener) {
448
- if (event === "exit") {
449
- const adapted = exitListeners.get(listener);
450
- if (adapted) {
451
- child.off("exit", adapted);
452
- exitListeners.delete(listener);
453
- }
454
- return;
455
- }
456
- child.off("message", listener);
457
- },
458
- kill() {
459
- child.kill("SIGKILL");
460
- }
461
- };
462
- }
463
- //#endregion
464
- //#region src/pieces/activepieces/worker/host.ts
465
- var PieceWorkerError = class extends Error {
466
- serialized;
467
- constructor(serialized) {
468
- super(`${serialized.name}: ${serialized.message}`);
469
- this.name = "PieceWorkerError";
470
- this.serialized = serialized;
471
- }
472
- };
473
- var PieceWorkerTimeoutError = class extends Error {
474
- constructor(timeoutMs) {
475
- super(`Piece action timed out after ${timeoutMs}ms; worker was replaced`);
476
- this.name = "PieceWorkerTimeoutError";
477
- }
478
- };
479
- var PieceWorkerExitError = class extends Error {
480
- constructor(code, signal) {
481
- super(`Piece worker exited unexpectedly (code=${code}, signal=${signal})`);
482
- this.name = "PieceWorkerExitError";
483
- }
484
- };
485
- function serveNotify(message, handlers) {
486
- const handler = handlers?.[message.method];
487
- if (!handler) return;
488
- try {
489
- Promise.resolve(handler(message.payload)).catch(() => void 0);
490
- } catch {}
491
- }
492
- var PieceWorker = class {
493
- connect;
494
- defaultTimeoutMs;
495
- worker;
496
- queue = Promise.resolve();
497
- nextId = 1;
498
- constructor(options = {}) {
499
- const entryPath = options.entryPath;
500
- this.connect = options.transport ?? (() => createForkTransport(entryPath ?? defaultEntryPath()));
501
- this.defaultTimeoutMs = options.defaultTimeoutMs ?? 3e4;
502
- }
503
- runAction(request, options = {}) {
504
- return this.enqueue("run", request, options.timeoutMs, options);
505
- }
506
- resolveOptions(request, options = {}) {
507
- return this.enqueue("resolve-options", request, options.timeoutMs, options);
508
- }
509
- checkConnection(request, options = {}) {
510
- return this.enqueue("check-connection", request, options.timeoutMs);
511
- }
512
- describePiece(request, options = {}) {
513
- return this.enqueue("describe", request, options.timeoutMs);
514
- }
515
- runTriggerHook(request, options = {}) {
516
- return this.enqueue("trigger-hook", request, options.timeoutMs, options);
517
- }
518
- enqueue(type, request, timeoutMs, taps = {}) {
519
- const run = this.queue.then(() => this.execute(type, request, timeoutMs ?? this.defaultTimeoutMs, taps));
520
- this.queue = run.catch(() => void 0);
521
- return run;
522
- }
523
- dispose() {
524
- this.worker?.kill();
525
- this.worker = void 0;
526
- }
527
- spawn() {
528
- if (this.worker) return this.worker;
529
- const worker = this.connect();
530
- const forget = () => {
531
- if (this.worker === worker) this.worker = void 0;
532
- worker.off("exit", forget);
533
- };
534
- worker.on("exit", forget);
535
- this.worker = worker;
536
- return worker;
537
- }
538
- execute(type, request, timeoutMs, taps) {
539
- const worker = this.spawn();
540
- const id = this.nextId++;
541
- return new Promise((resolve, reject) => {
542
- const timer = setTimeout(() => {
543
- cleanup();
544
- worker.kill();
545
- this.worker = void 0;
546
- reject(new PieceWorkerTimeoutError(timeoutMs));
547
- }, timeoutMs);
548
- const onMessage = (value) => {
549
- const response = value;
550
- if (response.type === "host-call" || response.type === "host-notify") return;
551
- if (response.id !== id) return;
552
- cleanup();
553
- if (response.type === "result") resolve({
554
- output: response.output,
555
- touched: response.touched,
556
- tlsPoisoned: response.tlsPoisoned,
557
- files: response.files,
558
- storeState: response.storeState,
559
- schedules: response.schedules,
560
- listeners: response.listeners
561
- });
562
- else reject(new PieceWorkerError(response.error));
563
- };
564
- const onExit = ({ code, signal }) => {
565
- cleanup();
566
- reject(new PieceWorkerExitError(code, signal));
567
- };
568
- const onHostCall = (value) => {
569
- const message = value;
570
- if (message.type === "host-call") {
571
- this.serveHostCall(worker, message, taps.hostCalls);
572
- return;
573
- }
574
- if (message.type === "host-notify") serveNotify(message, taps.notifications);
575
- };
576
- const cleanup = () => {
577
- clearTimeout(timer);
578
- worker.off("message", onMessage);
579
- worker.off("message", onHostCall);
580
- worker.off("exit", onExit);
581
- };
582
- worker.on("message", onMessage);
583
- worker.on("message", onHostCall);
584
- worker.on("exit", onExit);
585
- worker.send(jsonSafe({
586
- id,
587
- type,
588
- request: {
589
- maxFileBytes: configuredMaxFileBytes(),
590
- ...request
591
- }
592
- }));
593
- });
594
- }
595
- async serveHostCall(worker, message, handlers) {
596
- let response;
597
- try {
598
- const handler = handlers?.[message.method];
599
- if (!handler) throw new Error(`No host handler for "${message.method}"`);
600
- response = {
601
- id: message.id,
602
- type: "host-result",
603
- value: await handler(message.payload)
604
- };
605
- } catch (error) {
606
- response = {
607
- id: message.id,
608
- type: "host-result",
609
- error: error instanceof Error ? error.message : String(error)
610
- };
611
- }
612
- if (worker.connected) worker.send(response);
613
- }
614
- };
615
- //#endregion
616
- //#region src/pieces/activepieces/worker/pool.ts
617
- var PieceWorkerPoolBusyError = class extends Error {
618
- constructor(size, waiting) {
619
- super(`All ${size} piece workers are busy and ${waiting} runs are already waiting`);
620
- this.name = "PieceWorkerPoolBusyError";
621
- }
622
- };
623
- var PieceWorkerSessionClosedError = class extends Error {
624
- constructor() {
625
- super("This piece worker session is closed");
626
- this.name = "PieceWorkerSessionClosedError";
627
- }
628
- };
629
- const DEFAULT_SIZE = 4;
630
- var PieceWorkerSession = class {
631
- pool;
632
- worker;
633
- taking;
634
- held = false;
635
- closed = false;
636
- constructor(pool) {
637
- this.pool = pool;
638
- }
639
- runAction(request, options) {
640
- return this.request((worker) => worker.runAction(request, options));
641
- }
642
- resolveOptions(request, options) {
643
- return this.request((worker) => worker.resolveOptions(request, options));
644
- }
645
- checkConnection(request, options) {
646
- return this.request((worker) => worker.checkConnection(request, options));
647
- }
648
- describePiece(request, options) {
649
- return this.request((worker) => worker.describePiece(request, options));
650
- }
651
- runTriggerHook(request, options) {
652
- return this.request((worker) => worker.runTriggerHook(request, options));
653
- }
654
- close() {
655
- if (this.closed) return;
656
- this.closed = true;
657
- this.pool.cancel(this);
658
- this.worker?.dispose();
659
- this.worker = void 0;
660
- this.pool.forget(this);
661
- this.giveBack();
662
- }
663
- dispose() {
664
- this.close();
665
- }
666
- async request(fn) {
667
- const worker = await this.take();
668
- if (this.closed) throw new PieceWorkerSessionClosedError();
669
- return fn(worker);
670
- }
671
- take() {
672
- if (this.closed) return Promise.reject(new PieceWorkerSessionClosedError());
673
- if (this.worker) return Promise.resolve(this.worker);
674
- this.taking ??= this.acquire();
675
- return this.taking;
676
- }
677
- async acquire() {
678
- await this.pool.acquire(this);
679
- this.held = true;
680
- if (this.closed) {
681
- this.giveBack();
682
- throw new PieceWorkerSessionClosedError();
683
- }
684
- this.worker = this.pool.build();
685
- return this.worker;
686
- }
687
- giveBack() {
688
- if (!this.held) return;
689
- this.held = false;
690
- this.pool.release();
691
- }
692
- };
693
- var PieceWorkerPool = class {
694
- size;
695
- maxQueueDepth;
696
- createWorker;
697
- workerOptions;
698
- sessions = /* @__PURE__ */ new Set();
699
- waiters = [];
700
- inUse = 0;
701
- disposed = false;
702
- constructor(options = {}) {
703
- const { size, maxQueueDepth, createWorker, ...workerOptions } = options;
704
- this.size = Math.max(1, Math.trunc(size ?? DEFAULT_SIZE));
705
- this.maxQueueDepth = Math.max(0, Math.trunc(maxQueueDepth ?? 0));
706
- this.createWorker = createWorker ?? ((o) => new PieceWorker(o));
707
- this.workerOptions = workerOptions;
708
- }
709
- session() {
710
- if (this.disposed) throw new Error("Piece worker pool is disposed");
711
- const session = new PieceWorkerSession(this);
712
- this.sessions.add(session);
713
- return session;
714
- }
715
- stats() {
716
- return {
717
- size: this.size,
718
- active: this.inUse,
719
- waiting: this.waiters.length
720
- };
721
- }
722
- dispose() {
723
- this.disposed = true;
724
- for (const waiter of this.waiters.splice(0)) waiter.reject(/* @__PURE__ */ new Error("Piece worker pool is disposed"));
725
- for (const session of [...this.sessions]) session.close();
726
- this.sessions.clear();
727
- }
728
- /** @internal — a session taking its slot. */
729
- acquire(session) {
730
- if (this.disposed) return Promise.reject(/* @__PURE__ */ new Error("Piece worker pool is disposed"));
731
- if (this.inUse < this.size) {
732
- this.inUse++;
733
- return Promise.resolve();
734
- }
735
- if (this.maxQueueDepth > 0 && this.waiters.length >= this.maxQueueDepth) return Promise.reject(new PieceWorkerPoolBusyError(this.size, this.waiters.length));
736
- return new Promise((resolve, reject) => {
737
- this.waiters.push({
738
- session,
739
- resolve,
740
- reject
741
- });
742
- });
743
- }
744
- /** @internal — a session that closed while queueing. */
745
- cancel(session) {
746
- const index = this.waiters.findIndex((w) => w.session === session);
747
- if (index < 0) return;
748
- const [waiter] = this.waiters.splice(index, 1);
749
- waiter.reject(new PieceWorkerSessionClosedError());
750
- }
751
- /** @internal — a session giving its slot back. */
752
- release() {
753
- const next = this.waiters.shift();
754
- if (next) {
755
- next.resolve();
756
- return;
757
- }
758
- this.inUse = Math.max(0, this.inUse - 1);
759
- }
760
- /** @internal — one child for one session. */
761
- build() {
762
- return this.createWorker(this.workerOptions);
763
- }
764
- /** @internal — a session that closed itself. */
765
- forget(session) {
766
- this.sessions.delete(session);
767
- }
768
- };
769
- //#endregion
770
- //#region src/pieces/engine/types.ts
771
- function stepBlock(step) {
772
- return {
773
- pieceName: step.pieceName,
774
- pieceVersion: step.pieceVersion,
775
- kind: "action",
776
- name: step.actionName
777
- };
778
- }
779
- function triggerBlock(trigger) {
780
- return {
781
- pieceName: trigger.pieceName,
782
- pieceVersion: trigger.pieceVersion,
783
- kind: "trigger",
784
- name: trigger.triggerName
785
- };
786
- }
787
- //#endregion
788
- //#region src/pieces/engine/secrets.ts
789
- const SECRET_REF_PREFIX = "secret://v1:";
790
- const SECRET_ID_PATTERN = /^[0-9a-f]{32}$/;
791
- var SecretNotFoundError = class extends Error {
792
- constructor(ref) {
793
- super(`No secret found for ref "${ref}"`);
794
- this.name = "SecretNotFoundError";
795
- }
796
- };
797
- var SecretDeletedError = class extends Error {
798
- constructor(ref) {
799
- super(`Secret "${ref}" has been deleted`);
800
- this.name = "SecretDeletedError";
801
- }
802
- };
803
- var InvalidSecretRefError = class extends Error {
804
- constructor(ref) {
805
- super(`Invalid secret ref "${ref}"; expected ${SECRET_REF_PREFIX}<32 hex chars>`);
806
- this.name = "InvalidSecretRefError";
807
- }
808
- };
809
- function isSecretRef(ref) {
810
- return ref.startsWith("secret://v1:") && SECRET_ID_PATTERN.test(ref.slice(12));
811
- }
812
- function parseSecretRef(ref) {
813
- if (!isSecretRef(ref)) throw new InvalidSecretRefError(ref);
814
- return ref.slice(12);
815
- }
816
- function secretRefFromId(id) {
817
- if (!SECRET_ID_PATTERN.test(id)) throw new InvalidSecretRefError(id);
818
- return `${SECRET_REF_PREFIX}${id}`;
819
- }
820
- var InMemorySecretProvider = class {
821
- secrets;
822
- constructor(secrets) {
823
- this.secrets = new Map(Object.entries(secrets));
824
- }
825
- get(ref) {
826
- const value = this.secrets.get(ref);
827
- if (value === void 0) return Promise.reject(new SecretNotFoundError(ref));
828
- return Promise.resolve(value);
829
- }
830
- };
831
- //#endregion
832
- //#region src/pieces/engine/expressions.ts
833
- var ExpressionSyntaxError = class extends Error {
834
- constructor(source, detail) {
835
- super(`Invalid expression {{${source}}}: ${detail}`);
836
- this.name = "ExpressionSyntaxError";
837
- }
838
- };
839
- var UnresolvedReferenceError = class extends Error {
840
- reference;
841
- constructor(reference) {
842
- super(`Unresolved reference {{${reference}}}`);
843
- this.reference = reference;
844
- this.name = "UnresolvedReferenceError";
845
- }
846
- };
847
- const IDENT = /[A-Za-z0-9_$-]/;
848
- function parseExpression(source) {
849
- let i = 0;
850
- const fail = (detail) => {
851
- throw new ExpressionSyntaxError(source, detail);
852
- };
853
- const skipSpace = () => {
854
- while (i < source.length && /\s/.test(source[i])) i++;
855
- };
856
- const readString = () => {
857
- const quote = source[i++];
858
- let out = "";
859
- while (i < source.length && source[i] !== quote) {
860
- if (source[i] === "\\" && i + 1 < source.length) {
861
- out += source[i + 1];
862
- i += 2;
863
- continue;
864
- }
865
- out += source[i++];
866
- }
867
- if (source[i] !== quote) fail("unterminated string");
868
- i++;
869
- return out;
870
- };
871
- const readIdent = () => {
872
- const start = i;
873
- while (i < source.length && IDENT.test(source[i])) i++;
874
- if (i === start) fail(`expected a name at position ${start}`);
875
- return source.slice(start, i);
876
- };
877
- const readTerm = () => {
878
- skipSpace();
879
- const start = i;
880
- if (source[i] === "'" || source[i] === "\"") return {
881
- kind: "literal",
882
- value: readString()
883
- };
884
- const segments = [readIdent()];
885
- for (;;) {
886
- if (source[i] === ".") {
887
- i++;
888
- segments.push(readIdent());
889
- continue;
890
- }
891
- if (source[i] === "[") {
892
- i++;
893
- skipSpace();
894
- if (source[i] === "'" || source[i] === "\"") segments.push(readString());
895
- else {
896
- const digits = /^\d+/.exec(source.slice(i));
897
- if (!digits) fail("a bracket takes a quoted key or an index");
898
- segments.push(Number(digits[0]));
899
- i += digits[0].length;
900
- }
901
- skipSpace();
902
- if (source[i] !== "]") fail("expected ]");
903
- i++;
904
- continue;
905
- }
906
- break;
907
- }
908
- const optional = source[i] === "?";
909
- if (optional) i++;
910
- return {
911
- kind: "path",
912
- segments,
913
- optional,
914
- source: source.slice(start, i)
915
- };
916
- };
917
- const terms = [readTerm()];
918
- for (;;) {
919
- skipSpace();
920
- if (i >= source.length) break;
921
- if (source.startsWith("||", i)) {
922
- i += 2;
923
- terms.push(readTerm());
924
- continue;
925
- }
926
- fail(`unexpected "${source[i]}" at position ${i}`);
927
- }
928
- return {
929
- terms,
930
- source: source.trim()
931
- };
932
- }
933
- function splitTemplate(text) {
934
- const out = [];
935
- let pending = "";
936
- let cursor = 0;
937
- const flush = () => {
938
- if (pending) out.push({
939
- kind: "text",
940
- text: pending
941
- });
942
- pending = "";
943
- };
944
- for (;;) {
945
- const open = text.indexOf("{{", cursor);
946
- if (open < 0) break;
947
- if (open > 0 && text[open - 1] === "\\") {
948
- pending += text.slice(cursor, open - 1) + "{{";
949
- cursor = open + 2;
950
- continue;
951
- }
952
- let i = open + 2;
953
- let quote;
954
- let close = -1;
955
- for (; i < text.length; i++) {
956
- const char = text[i];
957
- if (quote) {
958
- if (char === "\\") i++;
959
- else if (char === quote) quote = void 0;
960
- continue;
961
- }
962
- if (char === "'" || char === "\"") quote = char;
963
- else if (text.startsWith("}}", i)) {
964
- close = i;
965
- break;
966
- }
967
- }
968
- if (close < 0) break;
969
- pending += text.slice(cursor, open);
970
- flush();
971
- out.push({
972
- kind: "expression",
973
- text: text.slice(open + 2, close)
974
- });
975
- cursor = close + 2;
976
- }
977
- pending += text.slice(cursor);
978
- flush();
979
- return out;
980
- }
981
- /** Every expression a string holds, parsed. */
982
- function expressionsIn(text) {
983
- return splitTemplate(text).filter((segment) => segment.kind === "expression").map((segment) => parseExpression(segment.text));
984
- }
985
- const MISSING = Symbol("missing");
986
- function lookupPath(scope, segments) {
987
- let current = scope;
988
- for (const segment of segments) {
989
- if (current === null || typeof current !== "object") return MISSING;
990
- const record = current;
991
- if (!Object.prototype.hasOwnProperty.call(record, segment)) return MISSING;
992
- current = record[segment];
993
- }
994
- return current === void 0 ? MISSING : current;
995
- }
996
- const isEmpty = (value) => value === null || value === "";
997
- function evaluateExpression(expression, scope) {
998
- const last = expression.terms.length - 1;
999
- let value = null;
1000
- for (const [index, term] of expression.terms.entries()) {
1001
- if (term.kind === "literal") value = term.value;
1002
- else {
1003
- const found = lookupPath(scope, term.segments);
1004
- if (found === MISSING) {
1005
- if (term.optional) value = null;
1006
- else if (index === last) throw new UnresolvedReferenceError(term.source);
1007
- else continue;
1008
- } else value = found;
1009
- }
1010
- if (!isEmpty(value)) return value;
1011
- }
1012
- return value;
1013
- }
1014
- function interpolate(value) {
1015
- if (value === void 0 || value === null) return "";
1016
- if (typeof value === "object") return JSON.stringify(value);
1017
- return String(value);
1018
- }
1019
- function resolveTemplate(text, scope) {
1020
- const segments = splitTemplate(text);
1021
- if (!segments.some((segment) => segment.kind === "expression")) return segments.map((segment) => segment.text).join("");
1022
- const meaningful = segments.filter((segment) => segment.kind === "expression" || segment.text.trim() !== "");
1023
- if (meaningful.length === 1) return evaluateExpression(parseExpression(meaningful[0].text), scope);
1024
- return segments.map((segment) => segment.kind === "text" ? segment.text : interpolate(evaluateExpression(parseExpression(segment.text), scope))).join("");
1025
- }
1026
- /** Evaluates every string in a value, nested ones included. */
1027
- function resolveExpressions(value, scope) {
1028
- if (typeof value === "string") return resolveTemplate(value, scope);
1029
- if (Array.isArray(value)) return value.map((item) => resolveExpressions(item, scope));
1030
- if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, resolveExpressions(entry, scope)]));
1031
- return value;
1032
- }
1033
- function evaluateCondition(condition, scope) {
1034
- const resolved = resolveTemplate(condition, scope);
1035
- if (resolved === "false" || resolved === "0") return false;
1036
- return Boolean(resolved);
1037
- }
1038
- //#endregion
1039
- //#region src/pieces/core/branch-operators.ts
1040
- var BranchConfigError = class extends Error {
1041
- constructor(message) {
1042
- super(`Branch: ${message}`);
1043
- this.name = "BranchConfigError";
1044
- }
1045
- };
1046
- function describe(value) {
1047
- if (value === void 0) return "nothing";
1048
- const text = JSON.stringify(value);
1049
- return text.length > 60 ? `${text.slice(0, 57)}...` : text;
1050
- }
1051
- function asText(value, side, caseSensitive) {
1052
- if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") throw new BranchConfigError(`${side} must be text, got ${describe(value)}`);
1053
- const text = String(value);
1054
- return caseSensitive ? text : text.toLowerCase();
1055
- }
1056
- const DECIMAL = /^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?$/;
1057
- function asNumber(value, side) {
1058
- if (typeof value === "number" && Number.isFinite(value)) return value;
1059
- if (typeof value === "string" && DECIMAL.test(value.trim())) return Number(value.trim());
1060
- throw new BranchConfigError(`${side} must be a number, got ${describe(value)}`);
1061
- }
1062
- function asBoolean(value, side) {
1063
- if (typeof value === "boolean") return value;
1064
- if (value === "true") return true;
1065
- if (value === "false") return false;
1066
- throw new BranchConfigError(`${side} must be true or false, got ${describe(value)}`);
1067
- }
1068
- function asDate(value, side) {
1069
- const time = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Date.parse(value) : NaN;
1070
- if (!Number.isFinite(time)) throw new BranchConfigError(`${side} must be a date, got ${describe(value)}`);
1071
- return time;
1072
- }
1073
- function asList(value, side) {
1074
- if (Array.isArray(value)) return value;
1075
- throw new BranchConfigError(`${side} must be a list, got ${describe(value)}`);
1076
- }
1077
- const blank = (value) => value === void 0 || value === null || value === "";
1078
- function textOp(label, test) {
1079
- return {
1080
- label,
1081
- left: "text",
1082
- binary: true,
1083
- text: true,
1084
- test: (left, right, caseSensitive) => test(asText(left, "left", caseSensitive), asText(right, "right", caseSensitive))
1085
- };
1086
- }
1087
- function numberOp(label, test) {
1088
- return {
1089
- label,
1090
- left: "number",
1091
- binary: true,
1092
- text: false,
1093
- test: (left, right) => test(asNumber(left, "left"), asNumber(right, "right"))
1094
- };
1095
- }
1096
- function dateOp(label, test) {
1097
- return {
1098
- label,
1099
- left: "date",
1100
- binary: true,
1101
- text: false,
1102
- test: (left, right) => test(asDate(left, "left"), asDate(right, "right"))
1103
- };
1104
- }
1105
- function unary(label, left, test) {
1106
- return {
1107
- label,
1108
- left,
1109
- binary: false,
1110
- text: false,
1111
- test
1112
- };
1113
- }
1114
- function listHas(left, right, caseSensitive) {
1115
- const wanted = asText(right, "right", caseSensitive);
1116
- return asList(left, "left").some((item) => {
1117
- if (typeof item === "object" && item !== null) return false;
1118
- const text = String(item);
1119
- return (caseSensitive ? text : text.toLowerCase()) === wanted;
1120
- });
1121
- }
1122
- const BRANCH_OPERATORS = {
1123
- TEXT_EXACTLY_MATCHES: textOp("Text is exactly", (a, b) => a === b),
1124
- TEXT_DOES_NOT_EXACTLY_MATCH: textOp("Text is not exactly", (a, b) => a !== b),
1125
- TEXT_CONTAINS: textOp("Text contains", (a, b) => a.includes(b)),
1126
- TEXT_DOES_NOT_CONTAIN: textOp("Text does not contain", (a, b) => !a.includes(b)),
1127
- TEXT_STARTS_WITH: textOp("Text starts with", (a, b) => a.startsWith(b)),
1128
- TEXT_DOES_NOT_START_WITH: textOp("Text does not start with", (a, b) => !a.startsWith(b)),
1129
- TEXT_ENDS_WITH: textOp("Text ends with", (a, b) => a.endsWith(b)),
1130
- TEXT_DOES_NOT_END_WITH: textOp("Text does not end with", (a, b) => !a.endsWith(b)),
1131
- NUMBER_IS_EQUAL_TO: numberOp("Number equals", (a, b) => a === b),
1132
- NUMBER_IS_GREATER_THAN: numberOp("Number is greater than", (a, b) => a > b),
1133
- NUMBER_IS_LESS_THAN: numberOp("Number is less than", (a, b) => a < b),
1134
- DATE_IS_EQUAL: dateOp("Date is", (a, b) => a === b),
1135
- DATE_IS_BEFORE: dateOp("Date is before", (a, b) => a < b),
1136
- DATE_IS_AFTER: dateOp("Date is after", (a, b) => a > b),
1137
- BOOLEAN_IS_TRUE: unary("Is true", "boolean", (v) => asBoolean(v, "left")),
1138
- BOOLEAN_IS_FALSE: unary("Is false", "boolean", (v) => !asBoolean(v, "left")),
1139
- LIST_CONTAINS: {
1140
- label: "List contains",
1141
- left: "list",
1142
- binary: true,
1143
- text: true,
1144
- test: listHas
1145
- },
1146
- LIST_DOES_NOT_CONTAIN: {
1147
- label: "List does not contain",
1148
- left: "list",
1149
- binary: true,
1150
- text: true,
1151
- test: (left, right, caseSensitive) => !listHas(left, right, caseSensitive)
1152
- },
1153
- LIST_IS_EMPTY: unary("List is empty", "list", (v) => asList(v, "left").length === 0),
1154
- LIST_IS_NOT_EMPTY: unary("List is not empty", "list", (v) => asList(v, "left").length > 0),
1155
- EXISTS: unary("Exists", "any", (v) => !blank(v)),
1156
- DOES_NOT_EXIST: unary("Does not exist", "any", blank)
1157
- };
1158
- const EXISTENCE_OPERATORS = /* @__PURE__ */ new Set(["EXISTS", "DOES_NOT_EXIST"]);
1159
- const OPERATORS = BRANCH_OPERATORS;
1160
- const DEFAULT_BRANCH_OPERATOR = "TEXT_EXACTLY_MATCHES";
1161
- function evaluateBranch(config) {
1162
- if (config === null || typeof config !== "object" || Array.isArray(config)) throw new BranchConfigError("the config must be an object");
1163
- const { operator, left, right, caseSensitive } = config;
1164
- if (operator === void 0 || operator === null || operator === "") throw new BranchConfigError("an operator is required");
1165
- if (typeof operator !== "string" || !Object.hasOwn(OPERATORS, operator)) throw new BranchConfigError(`unknown operator ${describe(operator)}`);
1166
- if (caseSensitive !== void 0 && typeof caseSensitive !== "boolean") throw new BranchConfigError("caseSensitive must be true or false");
1167
- const spec = OPERATORS[operator];
1168
- const result = spec.test(left, right, caseSensitive === true);
1169
- return {
1170
- operator,
1171
- left,
1172
- ...spec.binary ? { right } : {},
1173
- result
1174
- };
1175
- }
1176
- //#endregion
1177
- //#region src/pieces/engine/step-input.ts
1178
- function resolveStepInput(step, scope) {
1179
- const { config } = step;
1180
- if (step.pieceName !== CORE_PIECE_NAME || step.actionName !== "branch" || config === null || typeof config !== "object" || Array.isArray(config) || !Object.hasOwn(config, "left")) return resolveExpressions(config, scope);
1181
- const record = config;
1182
- const operator = resolveExpressions(record.operator, scope);
1183
- if (typeof operator !== "string" || !EXISTENCE_OPERATORS.has(operator)) return resolveExpressions(config, scope);
1184
- return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, key === "left" ? resolveOrMissing(value, scope) : resolveExpressions(value, scope)]));
1185
- }
1186
- function resolveOrMissing(value, scope) {
1187
- try {
1188
- return resolveExpressions(value, scope);
1189
- } catch (error) {
1190
- if (error instanceof UnresolvedReferenceError) return void 0;
1191
- throw error;
1192
- }
1193
- }
1194
- //#endregion
1195
- //#region src/pieces/engine/connections.ts
1196
- var ConnectionNotFoundError = class extends Error {
1197
- constructor(connectionId) {
1198
- super(`No connection registered for id "${connectionId}"`);
1199
- this.name = "ConnectionNotFoundError";
1200
- }
1201
- };
1202
- var ConnectionNotBoundError = class extends Error {
1203
- constructor(connectionId) {
1204
- super(`Connection "${connectionId}" is not bound to this workflow`);
1205
- this.name = "ConnectionNotBoundError";
1206
- }
1207
- };
1208
- var UnsupportedAuthTypeError = class extends Error {
1209
- constructor(authType) {
1210
- super(`Auth type "${authType}" is not supported yet`);
1211
- this.name = "UnsupportedAuthTypeError";
1212
- }
1213
- };
1214
- async function resolveSecrets(source, secrets) {
1215
- const entries = await Promise.all((source.secretRefs ?? []).map(async ({ name, ref }) => [name, await secrets.get(ref)]));
1216
- return Object.fromEntries(entries);
1217
- }
1218
- async function shapeConnection(source, secrets) {
1219
- const resolved = await resolveSecrets(source, secrets);
1220
- if (source.authType === "OAUTH2") return shapeOAuth2(source, resolved);
1221
- return {
1222
- auth: shapeAuth(source, resolved),
1223
- secretValues: Object.values(resolved)
1224
- };
1225
- }
1226
- function shapeOAuth2(source, resolved) {
1227
- const { client_secret: clientSecret, token, ...secretProps } = resolved;
1228
- const { client_id: clientId, ...configProps } = source.config ?? {};
1229
- if (!token) throw new Error("This OAuth2 connection is not signed in; connect it first");
1230
- let tokens;
1231
- try {
1232
- tokens = JSON.parse(token);
1233
- } catch {
1234
- throw new Error("Stored OAuth2 token is malformed; reconnect");
1235
- }
1236
- const text = (value, fallback = "") => typeof value === "string" ? value : fallback;
1237
- const auth = {
1238
- type: AppConnectionType.OAUTH2,
1239
- client_id: text(clientId),
1240
- client_secret: text(clientSecret),
1241
- redirect_url: text(tokens.redirect_url),
1242
- access_token: text(tokens.access_token),
1243
- refresh_token: text(tokens.refresh_token),
1244
- token_type: text(tokens.token_type, "Bearer"),
1245
- claimed_at: Number(tokens.claimed_at ?? 0),
1246
- scope: text(tokens.scope),
1247
- token_url: text(tokens.token_url),
1248
- ...typeof tokens.expires_in === "number" ? { expires_in: tokens.expires_in } : {},
1249
- data: tokens.data ?? {},
1250
- props: {
1251
- ...configProps,
1252
- ...secretProps
1253
- }
1254
- };
1255
- const secretValues = [
1256
- clientSecret,
1257
- auth.access_token,
1258
- auth.refresh_token,
1259
- ...Object.values(secretProps),
1260
- ...tokenLikeValues(auth.data)
1261
- ].filter((value) => Boolean(value));
1262
- return {
1263
- auth,
1264
- secretValues: [...new Set(secretValues)]
1265
- };
1266
- }
1267
- const TOKEN_KEY = /(token|secret)$/i;
1268
- function tokenLikeValues(value, key = "") {
1269
- if (typeof value === "string") return TOKEN_KEY.test(key) ? [value] : [];
1270
- if (Array.isArray(value)) return value.flatMap((item) => tokenLikeValues(item, key));
1271
- if (value !== null && typeof value === "object") return Object.entries(value).flatMap(([name, item]) => tokenLikeValues(item, name));
1272
- return [];
1273
- }
1274
- function shapeAuth(source, resolved) {
1275
- switch (source.authType) {
1276
- case "NONE": return;
1277
- case "SECRET_TEXT": {
1278
- const values = Object.values(resolved);
1279
- if (values.length !== 1) throw new Error(`SECRET_TEXT connection must have exactly one secret ref, got ${values.length}`);
1280
- return {
1281
- type: AppConnectionType.SECRET_TEXT,
1282
- secret_text: values[0]
1283
- };
1284
- }
1285
- case "BASIC_AUTH": {
1286
- const props = {
1287
- ...source.config,
1288
- ...resolved
1289
- };
1290
- return {
1291
- type: AppConnectionType.BASIC_AUTH,
1292
- username: props.username,
1293
- password: props.password
1294
- };
1295
- }
1296
- case "CUSTOM_AUTH": return {
1297
- type: AppConnectionType.CUSTOM_AUTH,
1298
- props: {
1299
- ...source.config,
1300
- ...resolved
1301
- }
1302
- };
1303
- default: throw new UnsupportedAuthTypeError(source.authType);
1304
- }
1305
- }
1306
- var StaticConnectionResolver = class {
1307
- secrets;
1308
- connections;
1309
- constructor(connections, secrets) {
1310
- this.secrets = secrets;
1311
- this.connections = new Map(Object.entries(connections));
1312
- }
1313
- resolve(connectionId) {
1314
- return this.resolveWithSecrets(connectionId).then((resolved) => resolved.auth);
1315
- }
1316
- resolveWithSecrets(connectionId) {
1317
- const source = this.connections.get(connectionId);
1318
- if (!source) return Promise.reject(new ConnectionNotFoundError(connectionId));
1319
- return shapeConnection(source, this.secrets);
1320
- }
1321
- };
1322
- function declaredConnectionIds(definition) {
1323
- const declared = /* @__PURE__ */ new Set();
1324
- const declare = (connectionId) => {
1325
- if (connectionId && !connectionId.includes("{{")) declared.add(connectionId);
1326
- };
1327
- declare(definition.trigger?.connectionId);
1328
- for (const step of definition.steps) declare(step.connectionId);
1329
- return declared;
1330
- }
1331
- var BoundConnectionResolver = class {
1332
- inner;
1333
- binding;
1334
- onRefused;
1335
- resolveWithSecrets;
1336
- constructor(inner, binding, onRefused) {
1337
- this.inner = inner;
1338
- this.binding = binding;
1339
- this.onRefused = onRefused;
1340
- const withSecrets = inner.resolveWithSecrets?.bind(inner);
1341
- if (!withSecrets) return;
1342
- this.resolveWithSecrets = (connectionId, request) => this.bound(connectionId, request) ? withSecrets(connectionId, request) : Promise.reject(new ConnectionNotBoundError(connectionId));
1343
- }
1344
- resolve(connectionId, request) {
1345
- if (!this.bound(connectionId, request)) return Promise.reject(new ConnectionNotBoundError(connectionId));
1346
- return this.inner.resolve(connectionId, request);
1347
- }
1348
- bound(connectionId, request) {
1349
- if (this.binding()?.has(connectionId)) return true;
1350
- this.onRefused?.(connectionId, request);
1351
- return false;
1352
- }
1353
- };
1354
- //#endregion
1355
- //#region src/pieces/core/hints.ts
1356
- function withHints(property, hints) {
1357
- return {
1358
- ...property,
1359
- ...hints
1360
- };
1361
- }
1362
- const shownWhen = (prop, oneOf) => ({ showWhen: {
1363
- prop,
1364
- oneOf
1365
- } });
1366
- function withPorts(action, ported) {
1367
- return Object.assign(action, ported);
1368
- }
1369
- function isPorted(action) {
1370
- const candidate = action;
1371
- return typeof candidate?.portOf === "function" && Array.isArray(candidate.ports);
1372
- }
1373
- function withDisplay(trigger, display) {
1374
- return Object.assign(trigger, { display });
1375
- }
1376
- //#endregion
1377
- //#region src/pieces/core/actions.ts
1378
- const operators = Object.entries(BRANCH_OPERATORS);
1379
- const BINARY_OPERATORS = operators.filter(([, spec]) => spec.binary).map(([name]) => name);
1380
- const TEXT_OPERATORS = operators.filter(([, spec]) => spec.text).map(([name]) => name);
1381
- const branchAction = withPorts(createAction({
1382
- name: "branch",
1383
- displayName: "Branch",
1384
- description: "Takes the true port when the operator holds for its operands, else the false port. An operand of the wrong type (a number operator on text, a list operator on something that is not a list) fails the step.",
1385
- requireAuth: false,
1386
- props: {
1387
- left: Property.ShortText({
1388
- displayName: "Value",
1389
- description: "What to test, usually an expression.",
1390
- required: true,
1391
- placeholder: "{{steps.fetch.output.status}}"
1392
- }),
1393
- operator: Property.StaticDropdown({
1394
- displayName: "Condition",
1395
- description: "How the value is tested.",
1396
- required: true,
1397
- defaultValue: DEFAULT_BRANCH_OPERATOR,
1398
- options: { options: operators.map(([value, spec]) => ({
1399
- value,
1400
- label: spec.label
1401
- })) }
1402
- }),
1403
- right: withHints(Property.ShortText({
1404
- displayName: "Compared with",
1405
- description: "The value the condition compares to.",
1406
- required: true
1407
- }), shownWhen("operator", BINARY_OPERATORS)),
1408
- caseSensitive: withHints(Property.Checkbox({
1409
- displayName: "Case sensitive",
1410
- description: "Match letter case exactly.",
1411
- required: false
1412
- }), shownWhen("operator", TEXT_OPERATORS))
1413
- },
1414
- run: (ctx) => Promise.resolve(evaluateBranch(ctx.propsValue))
1415
- }), {
1416
- ports: BRANCH_PORTS,
1417
- portOf: (output) => output.result ? "true" : "false"
1418
- });
1419
- function assertionText(value) {
1420
- if (typeof value === "string") return value;
1421
- if (value === void 0 || value === null) return "";
1422
- return JSON.stringify(value);
1423
- }
1424
- function normalizedList(entries) {
1425
- return (typeof entries === "string" ? [entries] : Array.isArray(entries) ? entries : []).map((entry) => String(entry).trim().toLowerCase()).filter(Boolean);
1426
- }
1427
- const assertAction = withPorts(createAction({
1428
- name: "assert",
1429
- displayName: "Assert",
1430
- description: "Fails the step when its value is blank or rejected, so a bad value stops the run instead of reaching a step with a side effect.",
1431
- requireAuth: false,
1432
- props: {
1433
- value: Property.ShortText({
1434
- displayName: "Value",
1435
- description: "e.g. {{steps.describe.output}} - the run fails when it is blank.",
1436
- required: true
1437
- }),
1438
- rejectValues: Property.Array({
1439
- displayName: "Rejected values",
1440
- description: "One per line; the run fails when the value matches any of them.",
1441
- required: false
1442
- }),
1443
- allowValues: Property.Array({
1444
- displayName: "Allowed values",
1445
- description: "One per line; when set, anything else fails. Safer than a reject list for model output.",
1446
- required: false
1447
- }),
1448
- allowEmpty: Property.Checkbox({
1449
- displayName: "Allow empty",
1450
- description: "Accept a blank value instead of failing.",
1451
- required: false
1452
- }),
1453
- message: Property.ShortText({
1454
- displayName: "Failure message",
1455
- description: "Replaces the default error.",
1456
- required: false
1457
- })
1458
- },
1459
- run: (ctx) => {
1460
- const { value, rejectValues, allowValues, allowEmpty, message } = ctx.propsValue;
1461
- const trimmed = assertionText(value).trim();
1462
- const fail = (reason) => Promise.reject(new Error(typeof message === "string" && message ? message : `Assert: ${reason}`));
1463
- if (!trimmed && allowEmpty !== true) return fail("value is empty");
1464
- if (normalizedList(rejectValues).includes(trimmed.toLowerCase())) return fail(`value is a rejected value ("${trimmed}")`);
1465
- const allowed = normalizedList(allowValues);
1466
- if (allowed.length > 0 && !allowed.includes(trimmed.toLowerCase())) return fail(`value "${trimmed}" is not one of the allowed values (${allowed.join(", ")})`);
1467
- return Promise.resolve({ value });
1468
- }
1469
- }), {
1470
- ports: PIECE_ACTION_PORTS,
1471
- portOf: () => NEXT_PORT
1472
- });
1473
- //#endregion
1474
- //#region src/pieces/core/triggers.ts
1475
- function hostFed(name) {
1476
- return () => Promise.reject(/* @__PURE__ */ new Error(`The "${name}" trigger is fired by the host, not by its hooks`));
1477
- }
1478
- const hooks = (name) => ({
1479
- onEnable: hostFed(name),
1480
- onDisable: hostFed(name),
1481
- run: hostFed(name)
1482
- });
1483
- const options = (entries) => ({ options: entries.map(([value, label]) => ({
1484
- value,
1485
- label
1486
- })) });
1487
- const scheduleTrigger = withDisplay(createTrigger({
1488
- name: "schedule",
1489
- displayName: "Schedule",
1490
- description: "Fires on a five-field cron expression, or every so many minutes, hours or days.",
1491
- type: TriggerStrategy.POLLING,
1492
- requireAuth: false,
1493
- props: {
1494
- mode: Property.StaticDropdown({
1495
- displayName: "Runs",
1496
- description: "cron or interval.",
1497
- required: true,
1498
- defaultValue: "cron",
1499
- options: options([[SCHEDULE_MODES[0], "On a cron schedule"], [SCHEDULE_MODES[1], "At a fixed interval"]])
1500
- }),
1501
- cron: withHints(Property.ShortText({
1502
- displayName: "Cron expression",
1503
- description: "Five fields, e.g. 0 9 * * 1-5 runs at 09:00 on weekdays.",
1504
- required: true,
1505
- defaultValue: "0 9 * * 1-5"
1506
- }), shownWhen("mode", ["cron"])),
1507
- every: withHints(Property.Number({
1508
- displayName: "Every",
1509
- description: "A whole number of units, at least 1.",
1510
- required: true,
1511
- defaultValue: 15
1512
- }), shownWhen("mode", ["interval"])),
1513
- unit: withHints(Property.StaticDropdown({
1514
- displayName: "Unit",
1515
- description: "minutes, hours or days.",
1516
- required: true,
1517
- defaultValue: "minutes",
1518
- options: { options: Object.keys(SCHEDULE_UNIT_MS).map((unit) => ({
1519
- value: unit,
1520
- label: unit.charAt(0).toUpperCase() + unit.slice(1)
1521
- })) }
1522
- }), shownWhen("mode", ["interval"])),
1523
- timezone: Property.ShortText({
1524
- displayName: "Timezone",
1525
- description: "An IANA name such as Europe/Lisbon. Defaults to UTC.",
1526
- required: false,
1527
- defaultValue: "UTC"
1528
- })
1529
- },
1530
- sampleData: {
1531
- scheduledFor: "2026-09-28T09:00:00.000Z",
1532
- firedAt: "2026-09-28T09:00:00.120Z",
1533
- timezone: "UTC",
1534
- cron: "0 9 * * 1-5"
1535
- },
1536
- ...hooks("schedule")
1537
- }), "schedule");
1538
- const SIGNED_SCHEMES = [
1539
- "token",
1540
- "hmac",
1541
- "hmac-prefixed",
1542
- "hmac-timestamped"
1543
- ];
1544
- const HMAC_SCHEMES = [
1545
- "hmac",
1546
- "hmac-prefixed",
1547
- "hmac-timestamped"
1548
- ];
1549
- const SECRET_REF_TYPE = "PH_SECRET_REF";
1550
- const webhookTrigger = createTrigger({
1551
- name: "webhook",
1552
- displayName: "Webhook",
1553
- description: "Fires on an HTTP delivery to the workflow's endpoint. Ask for the URL with the webhookEndpoint query rather than constructing it.",
1554
- type: TriggerStrategy.WEBHOOK,
1555
- requireAuth: false,
1556
- props: {
1557
- methods: Property.StaticDropdown({
1558
- displayName: "Method",
1559
- description: "The HTTP method a delivery must use.",
1560
- required: true,
1561
- defaultValue: "POST",
1562
- options: options([
1563
- ["POST", "POST"],
1564
- ["ANY", "Any"],
1565
- ["GET", "GET"],
1566
- ["PUT", "PUT"],
1567
- ["PATCH", "PATCH"],
1568
- ["DELETE", "DELETE"]
1569
- ])
1570
- }),
1571
- scheme: Property.StaticDropdown({
1572
- displayName: "Verification",
1573
- description: "How a delivery proves its sender.",
1574
- required: true,
1575
- defaultValue: "none",
1576
- options: options([
1577
- ["none", "None — the URL's token only"],
1578
- ["token", "Shared token in a header"],
1579
- ["hmac", "HMAC digest"],
1580
- ["hmac-prefixed", "HMAC digest with a label (sha256=…)"],
1581
- ["hmac-timestamped", "HMAC digest, timestamped (t=…,v1=…)"]
1582
- ])
1583
- }),
1584
- secretRef: withHints({
1585
- ...Property.ShortText({
1586
- displayName: "Secret",
1587
- description: "The shared secret: the value the header must equal, or the key the sender signs with",
1588
- required: true
1589
- }),
1590
- type: SECRET_REF_TYPE
1591
- }, shownWhen("scheme", SIGNED_SCHEMES)),
1592
- header: withHints(Property.ShortText({
1593
- displayName: "Header",
1594
- description: "Where the token or signature is read from. Defaults to the header the chosen scheme conventionally uses; set it only if the sender differs",
1595
- required: false,
1596
- advanced: true
1597
- }), shownWhen("scheme", SIGNED_SCHEMES)),
1598
- toleranceSeconds: withHints(Property.Number({
1599
- displayName: "Replay window (seconds)",
1600
- description: "Rejects a delivery signed longer ago than this, so a captured request expires. Default 300",
1601
- required: false,
1602
- advanced: true
1603
- }), shownWhen("scheme", ["hmac-timestamped"])),
1604
- algorithm: withHints(Property.StaticDropdown({
1605
- displayName: "Hash",
1606
- description: "How the digest was computed.",
1607
- required: false,
1608
- advanced: true,
1609
- options: options([
1610
- ["sha256", "SHA-256 (default)"],
1611
- ["sha1", "SHA-1"],
1612
- ["sha512", "SHA-512"]
1613
- ])
1614
- }), shownWhen("scheme", HMAC_SCHEMES)),
1615
- encoding: withHints(Property.StaticDropdown({
1616
- displayName: "Digest encoding",
1617
- description: "How the digest is written.",
1618
- required: false,
1619
- advanced: true,
1620
- options: options([["hex", "Hexadecimal (default)"], ["base64", "Base64"]])
1621
- }), shownWhen("scheme", HMAC_SCHEMES)),
1622
- prefix: withHints(Property.ShortText({
1623
- displayName: "Signature label",
1624
- description: "The text before the digest. Left empty it is the hash name and an equals sign, e.g. sha256=. Tick No label when the sender sends the digest alone",
1625
- required: false,
1626
- advanced: true
1627
- }), {
1628
- emptyChoice: "No label",
1629
- ...shownWhen("scheme", ["hmac-prefixed"])
1630
- }),
1631
- dedupeField: Property.ShortText({
1632
- displayName: "Event id field",
1633
- description: "Where the sender puts its own event id, so a redelivery is accepted without a second run. A bare name reads a query param or a top-level body field; prefix with header: or body: to read a header or a nested path (header:x-delivery-id, body:data.object.id)",
1634
- required: false,
1635
- advanced: true
1636
- }),
1637
- dedupeTtlSeconds: Property.Number({
1638
- displayName: "Dedupe window (seconds)",
1639
- description: "How long an event id is remembered. Default 300",
1640
- required: false,
1641
- advanced: true
1642
- }),
1643
- challengeField: Property.ShortText({
1644
- displayName: "Challenge field",
1645
- description: "Echo this field back instead of running, for senders that verify the endpoint before registering it. Same header:/body: prefixes as the event id field",
1646
- required: false,
1647
- advanced: true
1648
- }),
1649
- responseMode: Property.StaticDropdown({
1650
- displayName: "Response",
1651
- description: "Waiting holds the sender's socket open for the whole run",
1652
- required: false,
1653
- advanced: true,
1654
- defaultValue: "async",
1655
- options: options([["async", "Answer immediately (202)"], ["sync", "Wait for the run (200)"]])
1656
- }),
1657
- responseStatus: Property.Number({
1658
- displayName: "Success status",
1659
- description: "Status returned on acceptance. Default 202 async, 200 sync",
1660
- required: false,
1661
- advanced: true
1662
- })
1663
- },
1664
- sampleData: {
1665
- method: "POST",
1666
- path: "/",
1667
- headers: { "content-type": "application/json" },
1668
- queryParams: {},
1669
- body: { event: "ping" }
1670
- },
1671
- ...hooks("webhook")
1672
- });
1673
- const manualTrigger = createTrigger({
1674
- name: "manual",
1675
- displayName: "Manual",
1676
- description: "Fires only when something asks it to, with the fire mutation. The trigger to use for a workflow driven by a test or a script.",
1677
- type: TriggerStrategy.MANUAL,
1678
- requireAuth: false,
1679
- props: {},
1680
- sampleData: null,
1681
- ...hooks("manual")
1682
- });
1683
- //#endregion
1684
- //#region src/pieces/core/version.ts
1685
- const CORE_PIECE_VERSION = "6.2.3";
1686
- //#endregion
1687
- //#region src/pieces/core/index.ts
1688
- const corePiece = createPiece({
1689
- displayName: "Core",
1690
- description: "The engine's own blocks: branching, assertions, and the triggers that belong to no service.",
1691
- logoUrl: "",
1692
- authors: ["powerhouse"],
1693
- auth: void 0,
1694
- categories: [PieceCategory.CORE],
1695
- actions: [branchAction, assertAction],
1696
- triggers: [
1697
- scheduleTrigger,
1698
- webhookTrigger,
1699
- manualTrigger
1700
- ]
1701
- });
1702
- //#endregion
1703
- //#region src/pieces/builtin.ts
1704
- const BUILTIN_PIECES = [{
1705
- name: CORE_PIECE_NAME$1,
1706
- version: CORE_PIECE_VERSION,
1707
- piece: corePiece
1708
- }];
1709
- function builtinPiece(name) {
1710
- return BUILTIN_PIECES.find((entry) => entry.name === name);
1711
- }
1712
- function isBuiltinPiece(name) {
1713
- return builtinPiece(name) !== void 0;
1714
- }
1715
- function builtinLocalPieces() {
1716
- return BUILTIN_PIECES.map(({ name, version }) => ({
1717
- name,
1718
- version
1719
- }));
1720
- }
1721
- const descriptors = /* @__PURE__ */ new Map();
1722
- function describeBuiltinPiece(builtin) {
1723
- let descriptor = descriptors.get(builtin.name);
1724
- if (!descriptor) {
1725
- descriptor = buildDescriptor(builtin.piece, {
1726
- packageName: builtin.name,
1727
- version: builtin.version
1728
- }, {
1729
- routed: true,
1730
- hostFed: true
1731
- });
1732
- descriptors.set(builtin.name, descriptor);
1733
- }
1734
- return descriptor;
1735
- }
1736
- function blockPorts(block) {
1737
- const builtin = builtinPiece(block.pieceName);
1738
- if (builtin) {
1739
- const descriptor = describeBuiltinPiece(builtin);
1740
- return (block.kind === "trigger" ? descriptor.triggers : descriptor.actions).find((entry) => entry.name === block.name)?.ports;
1741
- }
1742
- return block.kind === "trigger" ? TRIGGER_PORTS : PIECE_ACTION_PORTS;
1743
- }
1744
- var UnknownBuiltinActionError = class extends Error {
1745
- constructor(piece, action) {
1746
- super(`${piece} has no action "${action}"`);
1747
- this.name = "UnknownBuiltinActionError";
1748
- }
1749
- };
1750
- async function runBuiltinAction(builtin, actionName, propsValue) {
1751
- const action = getActions(builtin.piece)[actionName];
1752
- if (!action || typeof action.run !== "function") throw new UnknownBuiltinActionError(builtin.name, actionName);
1753
- const output = await action.run({ propsValue });
1754
- return {
1755
- output,
1756
- ...isPorted(action) ? { port: action.portOf(output) } : {}
1757
- };
1758
- }
1759
- //#endregion
1760
- //#region src/pieces/engine/resolution.ts
1761
- function pieceRecord(resolution) {
1762
- if (!resolution?.resolved) return void 0;
1763
- return {
1764
- version: resolution.resolved.version,
1765
- ...resolution.resolved.source ? { source: resolution.resolved.source } : {},
1766
- match: resolution.match,
1767
- ...resolution.note ? { note: resolution.note } : {}
1768
- };
1769
- }
1770
- function blockLabel(block) {
1771
- const version = "pieceVersion" in block ? `@${block.pieceVersion}` : "";
1772
- return `${block.pieceName}${version} ${block.kind} "${block.name}"`;
1773
- }
1774
- var UnknownBlockError = class extends Error {
1775
- constructor(block, detail = `No executor registered for ${blockLabel(block)}`) {
1776
- super(detail);
1777
- this.name = "UnknownBlockError";
1778
- }
1779
- };
1780
- function unpinnedNote(block) {
1781
- return `${block.pieceName} ${block.kind} "${block.name}" pins "${block.pieceVersion}", which is not an exact semver version`;
1782
- }
1783
- function missingError(resolution) {
1784
- return new UnknownBlockError(resolution.requested, resolution.note);
1785
- }
1786
- const RESOLUTION = Symbol.for("reactor-workflow.block-resolution");
1787
- function withResolution(error, resolution) {
1788
- if (resolution && error !== null && typeof error === "object") error[RESOLUTION] = resolution;
1789
- return error;
1790
- }
1791
- function resolutionOf(error) {
1792
- if (error === null || typeof error !== "object") return void 0;
1793
- return error[RESOLUTION];
1794
- }
1795
- //#endregion
1796
- //#region src/pieces/engine/blocks.ts
1797
- var TriggerBlockAsStepError = class extends Error {
1798
- constructor(block) {
1799
- super(`${blockLabel(block)} is a trigger and cannot run as a workflow step`);
1800
- this.name = "TriggerBlockAsStepError";
1801
- }
1802
- };
1803
- const ATTACHMENT_REF = /^attachment:\/\//i;
1804
- function collectRefs(value, found) {
1805
- if (typeof value === "string") {
1806
- if (ATTACHMENT_REF.test(value)) found.add(value);
1807
- return;
1808
- }
1809
- if (Array.isArray(value)) {
1810
- for (const entry of value) collectRefs(entry, found);
1811
- return;
1812
- }
1813
- if (typeof value === "object" && value !== null) for (const entry of Object.values(value)) collectRefs(entry, found);
1814
- }
1815
- function storeScopeOf(payload) {
1816
- return payload?.scope === "PROJECT" ? "PROJECT" : "FLOW";
1817
- }
1818
- function storeKeyOf(payload) {
1819
- const key = payload?.key;
1820
- if (typeof key !== "string" || key === "") throw new Error("Store call carried no key");
1821
- return key;
1822
- }
1823
- function reactorInput(payload) {
1824
- if (typeof payload !== "object" || payload === null || Array.isArray(payload)) throw new Error("Reactor call carried no input object");
1825
- return payload;
1826
- }
1827
- function requiredString(payload, field) {
1828
- const value = payload[field];
1829
- if (typeof value !== "string" || value === "") throw new Error(`Reactor call carried no "${field}"`);
1830
- return value;
1831
- }
1832
- function optionalString(payload, field) {
1833
- const value = payload[field];
1834
- return typeof value === "string" && value !== "" ? value : void 0;
1835
- }
1836
- function reactorActions(payload) {
1837
- const actions = payload.actions;
1838
- if (!Array.isArray(actions) || actions.length === 0) throw new Error("Reactor call carried no actions");
1839
- return actions.map((entry, index) => {
1840
- const action = entry;
1841
- if (!action || typeof action.type !== "string") throw new Error(`Reactor call: actions[${index}] needs a string "type"`);
1842
- return {
1843
- type: action.type,
1844
- input: action.input,
1845
- ...typeof action.scope === "string" ? { scope: action.scope } : {}
1846
- };
1847
- });
1848
- }
1849
- const MAX_FIND_LIMIT = 100;
1850
- function findLimit(value) {
1851
- if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
1852
- return Math.min(Math.max(Math.floor(value), 1), MAX_FIND_LIMIT);
1853
- }
1854
- function findMatch(value) {
1855
- if (typeof value !== "object" || value === null) return void 0;
1856
- const record = value;
1857
- const path = record.path;
1858
- const wanted = record.value;
1859
- if (typeof path !== "string" || path.trim() === "") return void 0;
1860
- if (typeof wanted !== "string") return void 0;
1861
- return {
1862
- path: path.trim(),
1863
- value: wanted
1864
- };
1865
- }
1866
- function reactorHandlers(port) {
1867
- return {
1868
- [REACTOR_MODELS]: () => port.models(),
1869
- [REACTOR_MODEL]: (payload) => port.model(requiredString(reactorInput(payload), "documentType")),
1870
- [REACTOR_GET]: (payload) => {
1871
- const input = reactorInput(payload);
1872
- return port.get({
1873
- documentId: requiredString(input, "documentId"),
1874
- ...optionalString(input, "branch") ? { branch: optionalString(input, "branch") } : {}
1875
- });
1876
- },
1877
- [REACTOR_FIND]: (payload) => {
1878
- const input = reactorInput(payload);
1879
- return port.find({
1880
- ...optionalString(input, "documentType") ? { documentType: optionalString(input, "documentType") } : {},
1881
- ...optionalString(input, "parentId") ? { parentId: optionalString(input, "parentId") } : {},
1882
- ...findLimit(input.limit) !== void 0 ? { limit: findLimit(input.limit) } : {},
1883
- ...findMatch(input.match) ? { match: findMatch(input.match) } : {},
1884
- ...input.withState === true ? { withState: true } : {}
1885
- });
1886
- },
1887
- [REACTOR_CREATE]: (payload) => {
1888
- const input = reactorInput(payload);
1889
- return port.create({
1890
- documentType: requiredString(input, "documentType"),
1891
- ...optionalString(input, "name") ? { name: optionalString(input, "name") } : {},
1892
- ...optionalString(input, "parentId") ? { parentId: optionalString(input, "parentId") } : {}
1893
- });
1894
- },
1895
- [REACTOR_EXECUTE]: (payload) => {
1896
- const input = reactorInput(payload);
1897
- return port.execute({
1898
- documentId: requiredString(input, "documentId"),
1899
- ...optionalString(input, "branch") ? { branch: optionalString(input, "branch") } : {},
1900
- actions: reactorActions(input)
1901
- });
1902
- }
1903
- };
1904
- }
1905
- function storeHandlers(port) {
1906
- return {
1907
- [STORE_GET]: (payload) => port.get(storeKeyOf(payload), storeScopeOf(payload)),
1908
- [STORE_PUT]: async (payload) => {
1909
- await port.put(storeKeyOf(payload), payload.value, storeScopeOf(payload));
1910
- return null;
1911
- },
1912
- [STORE_DELETE]: async (payload) => {
1913
- await port.delete(storeKeyOf(payload), storeScopeOf(payload));
1914
- return null;
1915
- }
1916
- };
1917
- }
1918
- const logger$1 = childLogger(["workflow", "piece-staging"]);
1919
- function stepTaps(options, execution, values) {
1920
- const { onPieceLog, onPartialOutput } = options;
1921
- if (!onPieceLog && !onPartialOutput) return void 0;
1922
- const handlers = {};
1923
- if (onPieceLog) handlers[LOG_WRITE] = (payload) => {
1924
- const entry = payload;
1925
- return onPieceLog({
1926
- ...entry,
1927
- message: redactMessage(entry.message, { values })
1928
- }, execution);
1929
- };
1930
- if (onPartialOutput) handlers[OUTPUT_UPDATE] = (payload) => onPartialOutput(payload, execution);
1931
- return handlers;
1932
- }
1933
- function redactThrown(error, values) {
1934
- if (error instanceof Error) {
1935
- error.message = redactMessage(error.message, { values });
1936
- if (error.stack) error.stack = redactMessage(error.stack, { values });
1937
- return rememberSecrets(error, values);
1938
- }
1939
- return rememberSecrets(redactError(error, { values }), values);
1940
- }
1941
- const REACTOR_PORT_PIECE = "@powerhousedao/piece-reactor";
1942
- function servesReactorPort(packageName) {
1943
- return packageName === REACTOR_PORT_PIECE;
1944
- }
1945
- function isHostBound(packageName) {
1946
- return servesReactorPort(packageName) || isBuiltinPiece(packageName);
1947
- }
1948
- function resolvedBlock(resolution) {
1949
- const { requested, resolved } = resolution;
1950
- if (!resolved || resolution.match === "missing") return void 0;
1951
- return {
1952
- packageName: requested.pieceName,
1953
- version: resolved.version,
1954
- ...resolved.source ? { source: resolved.source } : {},
1955
- kind: requested.kind,
1956
- name: requested.name
1957
- };
1958
- }
1959
- function pinnedResolution(block) {
1960
- if (!isExactVersion(block.pieceVersion)) return {
1961
- requested: block,
1962
- match: "missing",
1963
- note: unpinnedNote(block)
1964
- };
1965
- return {
1966
- requested: block,
1967
- resolved: { version: block.pieceVersion },
1968
- match: "exact"
1969
- };
1970
- }
1971
- var ActivepiecesBlockExecutor = class {
1972
- options;
1973
- own;
1974
- resolver;
1975
- constructor(options) {
1976
- this.options = options;
1977
- this.resolver = options.resolver ?? bundleResolver({ cacheDir: options.cacheDir });
1978
- }
1979
- worker() {
1980
- const supplied = this.options.worker;
1981
- if (typeof supplied === "function") {
1982
- const worker = supplied();
1983
- if (worker) return worker;
1984
- } else if (supplied) return supplied;
1985
- return this.own ??= new PieceWorker();
1986
- }
1987
- async execute(execution) {
1988
- const resolution = this.options.resolveBlock ? await this.options.resolveBlock(execution.block) : pinnedResolution(execution.block);
1989
- const parsed = resolvedBlock(resolution);
1990
- if (!parsed) throw missingError(resolution);
1991
- if (parsed.kind !== "action") throw new TriggerBlockAsStepError(execution.block);
1992
- try {
1993
- const builtin = builtinPiece(parsed.packageName);
1994
- return {
1995
- ...builtin ? await runBuiltinAction(builtin, parsed.name, execution.config) : await this.run(execution, parsed),
1996
- resolution
1997
- };
1998
- } catch (error) {
1999
- throw withResolution(error, resolution);
2000
- }
2001
- }
2002
- async run(execution, parsed) {
2003
- const stagingDir = this.options.stagingRoot ? path.join(this.options.stagingRoot, randomUUID()) : void 0;
2004
- const runSecrets = execution.redactValues ?? [];
2005
- let redactValues = [...runSecrets];
2006
- try {
2007
- const piece = await this.resolver.resolve({
2008
- name: parsed.packageName,
2009
- version: parsed.version,
2010
- ...parsed.source ? { source: parsed.source } : {}
2011
- });
2012
- const connection = await this.resolveConnection(execution.connectionId, {
2013
- piecePackage: parsed.packageName,
2014
- stepId: execution.step.id,
2015
- stepKey: execution.step.key
2016
- });
2017
- const auth = connection?.auth;
2018
- redactValues = [...runSecrets, ...connection?.secretValues ?? []];
2019
- const timeoutMs = execution.step.timeoutSeconds ? execution.step.timeoutSeconds * 1e3 : this.options.defaultTimeoutMs;
2020
- const stagedInputs = await this.stageInputs(execution.config, stagingDir);
2021
- const pieceStore = this.options.pieceStore;
2022
- const notifications = stepTaps(this.options, execution, redactValues);
2023
- const egress = this.options.egress === void 0 ? DEFAULT_EGRESS_POLICY : this.options.egress;
2024
- const reactor = servesReactorPort(parsed.packageName) ? this.options.reactor : void 0;
2025
- const result = await this.worker().runAction({
2026
- ...pieceModuleRef(piece),
2027
- actionName: parsed.name,
2028
- propsValue: execution.config,
2029
- auth,
2030
- identity: {
2031
- ...this.options.identity?.(),
2032
- stepName: execution.step.key
2033
- },
2034
- ...redactValues.length > 0 ? { redactValues } : {},
2035
- ...this.options.stepTest?.() ? { stepTest: true } : {},
2036
- ...stagingDir ? { stagingDir } : {},
2037
- ...stagedInputs ? { stagedInputs } : {},
2038
- ...pieceStore ? { durableStore: true } : {},
2039
- ...reactor ? { reactorAccess: true } : {},
2040
- ...this.options.onPieceLog ? { captureLogs: true } : {},
2041
- ...this.options.onPartialOutput ? { liveOutput: true } : {},
2042
- ...egress ? { egress } : {}
2043
- }, {
2044
- ...timeoutMs ? { timeoutMs } : {},
2045
- ...pieceStore || reactor ? { hostCalls: {
2046
- ...pieceStore ? storeHandlers(pieceStore) : {},
2047
- ...reactor ? reactorHandlers(reactor) : {}
2048
- } } : {},
2049
- ...notifications ? { notifications } : {}
2050
- });
2051
- return {
2052
- output: await this.ingestFiles(result.output, result.files),
2053
- redactValues
2054
- };
2055
- } catch (error) {
2056
- throw redactThrown(error, redactValues);
2057
- } finally {
2058
- if (stagingDir) await rm(stagingDir, {
2059
- recursive: true,
2060
- force: true
2061
- });
2062
- }
2063
- }
2064
- async resolveConnection(connectionId, request) {
2065
- const connections = this.options.connections;
2066
- if (!connectionId || !connections) return void 0;
2067
- if (connections.resolveWithSecrets) return connections.resolveWithSecrets(connectionId, request);
2068
- const auth = await connections.resolve(connectionId, request);
2069
- return {
2070
- auth,
2071
- secretValues: [...collectSecretValues(auth)]
2072
- };
2073
- }
2074
- async stageInputs(config, stagingDir) {
2075
- const port = this.options.attachments;
2076
- if (!stagingDir || !port) return void 0;
2077
- const refs = /* @__PURE__ */ new Set();
2078
- collectRefs(config, refs);
2079
- if (refs.size === 0) return void 0;
2080
- await mkdir(stagingDir, { recursive: true });
2081
- const staged = [];
2082
- let index = 0;
2083
- for (const ref of refs) {
2084
- const destPath = path.join(stagingDir, `in-${index++}`);
2085
- try {
2086
- const meta = await port.read(ref, destPath);
2087
- staged.push({
2088
- ref,
2089
- path: destPath,
2090
- ...meta
2091
- });
2092
- } catch (error) {
2093
- logger$1.debug(`Left ${ref} unstaged: ${error instanceof Error ? error.message : String(error)}`);
2094
- }
2095
- }
2096
- return staged;
2097
- }
2098
- async ingestFiles(output, files) {
2099
- if (!files || files.length === 0) return output;
2100
- const port = this.options.attachments;
2101
- if (!port) throw new Error(`The action wrote ${files.length} file(s) through ctx.files, but no attachment store is configured for this reactor`);
2102
- const refs = /* @__PURE__ */ new Map();
2103
- for (const file of files) refs.set(file.token, await port.write({
2104
- path: file.path,
2105
- fileName: file.fileName,
2106
- size: file.size,
2107
- contentType: file.contentType
2108
- }));
2109
- return rewriteFileRefs(output, refs);
2110
- }
2111
- dispose() {
2112
- this.own?.dispose();
2113
- this.own = void 0;
2114
- }
2115
- };
2116
- var CompositeBlockExecutor = class {
2117
- pieces;
2118
- handlers;
2119
- constructor(pieces, handlers = {}) {
2120
- this.pieces = pieces;
2121
- this.handlers = handlers;
2122
- }
2123
- execute(execution) {
2124
- const handler = this.handlers[blockKey(execution.block)];
2125
- if (handler) return handler.execute(execution);
2126
- return this.pieces.execute(execution);
2127
- }
2128
- };
2129
- //#endregion
2130
- //#region src/pieces/engine/dynamic-props.ts
2131
- var DynamicPropertiesError = class extends Error {
2132
- prop;
2133
- missing;
2134
- constructor(message, prop, missing) {
2135
- super(message);
2136
- this.prop = prop;
2137
- this.missing = missing;
2138
- this.name = "DynamicPropertiesError";
2139
- }
2140
- };
2141
- function isRecord(value) {
2142
- return typeof value === "object" && value !== null && !Array.isArray(value);
2143
- }
2144
- function requiredChildren(schema) {
2145
- return (Array.isArray(schema) ? schema.filter(isRecord).filter((entry) => typeof entry.name === "string").map((entry) => [entry.name, entry]) : isRecord(schema) ? Object.entries(schema) : []).filter(([, prop]) => isRecord(prop) && prop.required === true).map(([name, prop]) => {
2146
- const displayName = prop.displayName;
2147
- return {
2148
- name,
2149
- label: typeof displayName === "string" && displayName !== "" ? `${displayName} (${name})` : name
2150
- };
2151
- });
2152
- }
2153
- function isBlank(value) {
2154
- return value === void 0 || value === null || value === "";
2155
- }
2156
- /** Throws a DynamicPropertiesError naming the first prop whose value does not
2157
- * satisfy its resolved children. Settings without a schema are ignored. */
2158
- function checkDynamicProperties(config, settings) {
2159
- if (!settings || settings.length === 0) return;
2160
- const values = isRecord(config) ? config : {};
2161
- for (const setting of settings) {
2162
- if (setting.schema === void 0 || setting.schema === null) continue;
2163
- const raw = values[setting.prop];
2164
- if (!isBlank(raw) && !isRecord(raw)) throw new DynamicPropertiesError(`Property "${setting.prop}" must be an object of fields, received ${Array.isArray(raw) ? "array" : typeof raw}`, setting.prop, []);
2165
- const value = isRecord(raw) ? raw : {};
2166
- const missing = requiredChildren(setting.schema).filter((child) => isBlank(value[child.name]));
2167
- if (missing.length > 0) throw new DynamicPropertiesError(`Property "${setting.prop}" is missing required fields: ${missing.map((child) => child.label).join(", ")}`, setting.prop, missing.map((child) => child.name));
2168
- }
2169
- }
2170
- //#endregion
2171
- //#region src/pieces/engine/canonical.ts
2172
- function canonicalJson(value) {
2173
- return JSON.stringify(sortKeys(value) ?? null);
2174
- }
2175
- function sortKeys(value) {
2176
- if (Array.isArray(value)) return value.map(sortKeys);
2177
- if (value === null || typeof value !== "object") return value;
2178
- const record = value;
2179
- return Object.fromEntries(Object.keys(record).sort().filter((key) => record[key] !== void 0).map((key) => [key, sortKeys(record[key])]));
2180
- }
2181
- function hashOf(...parts) {
2182
- const hash = createHash("sha256");
2183
- for (const part of parts) hash.update(part).update("\0");
2184
- return hash.digest("hex").slice(0, 16);
2185
- }
2186
- function stepConfigHash(step) {
2187
- const schemas = (step.propertySettings ?? []).filter((setting) => setting.schema !== null && setting.schema !== void 0).map((setting) => ({
2188
- prop: setting.prop,
2189
- schema: setting.schema
2190
- }));
2191
- return hashOf(step.pieceName, step.pieceVersion, step.actionName, canonicalJson({
2192
- config: step.config ?? {},
2193
- connectionId: step.connectionId ?? null,
2194
- propertySettings: schemas
2195
- }));
2196
- }
2197
- //#endregion
2198
- //#region src/pieces/engine/coordinator.ts
2199
- function deadPortWarnings(definition, declaredPorts) {
2200
- const blocks = new Map(definition.steps.map((step) => [step.id, {
2201
- key: step.key,
2202
- block: stepBlock(step)
2203
- }]));
2204
- if (definition.trigger) blocks.set(definition.trigger.id, {
2205
- key: "trigger",
2206
- block: triggerBlock(definition.trigger)
2207
- });
2208
- return undeclaredPortEdges(definition.edges, (id) => {
2209
- const source = blocks.get(id);
2210
- return source ? declaredPorts(source.block) : void 0;
2211
- }).map((edge) => {
2212
- const source = blocks.get(edge.from);
2213
- const target = blocks.get(edge.to)?.key ?? edge.to;
2214
- return `Edge from "${source.key}" to "${target}" leaves on port "${edge.port}", which ${blockLabel(source.block)} never takes`;
2215
- });
2216
- }
2217
- function withPiece(piece) {
2218
- return piece ? { piece } : {};
2219
- }
2220
- function errorMessage(error) {
2221
- if (error instanceof Error) return error.message;
2222
- return String(error);
2223
- }
2224
- function journaled(value, values) {
2225
- return value === void 0 ? void 0 : redact(value, { values });
2226
- }
2227
- async function runWorkflow(options) {
2228
- const { definition, executor } = options;
2229
- const runSecrets = options.redactValues ?? [];
2230
- const scope = {
2231
- trigger: { payload: options.triggerPayload },
2232
- steps: { ...options.priorSteps },
2233
- variables: Object.fromEntries((definition.variables ?? []).map((v) => [v.key, v.value ?? null]))
2234
- };
2235
- const records = /* @__PURE__ */ new Map();
2236
- const edgeDecisions = /* @__PURE__ */ new Map();
2237
- let runFailed;
2238
- let executedCount = 0;
2239
- const journal = async (record) => {
2240
- if (!options.onStep) return;
2241
- const ordinal = executedCount++;
2242
- try {
2243
- await options.onStep(record, ordinal);
2244
- } catch {}
2245
- };
2246
- const decideOutgoing = (sourceId, port) => {
2247
- for (const edge of definition.edges) {
2248
- if (edge.from !== sourceId) continue;
2249
- let taken = port !== void 0 && edge.port === port;
2250
- if (taken && edge.condition) try {
2251
- taken = evaluateCondition(edge.condition, scope);
2252
- } catch (error) {
2253
- taken = false;
2254
- runFailed ??= `Condition of edge "${edge.id}": ${errorMessage(error)}`;
2255
- }
2256
- edgeDecisions.set(edge.id, taken);
2257
- }
2258
- };
2259
- if (definition.trigger) decideOutgoing(definition.trigger.id, "next");
2260
- const inboundEdges = (step) => definition.edges.filter((edge) => edge.to === step.id);
2261
- const isEntryStep = (step) => !definition.trigger && inboundEdges(step).length === 0;
2262
- const skipStep = (step) => {
2263
- records.set(step.id, {
2264
- stepId: step.id,
2265
- key: step.key,
2266
- pieceName: step.pieceName,
2267
- blockName: step.actionName,
2268
- status: "SKIPPED"
2269
- });
2270
- decideOutgoing(step.id, void 0);
2271
- };
2272
- const refuseReplay = (step) => {
2273
- const error = `Journaled output of step "${step.key}" was redacted and cannot be replayed; fire the workflow again instead of rerunning it`;
2274
- records.set(step.id, {
2275
- stepId: step.id,
2276
- key: step.key,
2277
- pieceName: step.pieceName,
2278
- blockName: step.actionName,
2279
- status: "FAILED",
2280
- error
2281
- });
2282
- runFailed = error;
2283
- };
2284
- const passStep = async (step) => {
2285
- const record = {
2286
- stepId: step.id,
2287
- key: step.key,
2288
- pieceName: step.pieceName,
2289
- blockName: step.actionName,
2290
- status: "SKIPPED",
2291
- output: null,
2292
- port: "next"
2293
- };
2294
- records.set(step.id, record);
2295
- await journal(record);
2296
- scope.steps[step.key] = { output: null };
2297
- decideOutgoing(step.id, "next");
2298
- };
2299
- const executeStep = async (step) => {
2300
- if (step.skip === true) {
2301
- await passStep(step);
2302
- return;
2303
- }
2304
- const replay = options.completedSteps?.get(step.id);
2305
- if (replay) {
2306
- if (containsRedactedMarker(replay.output)) {
2307
- refuseReplay(step);
2308
- return;
2309
- }
2310
- const port = replay.port ?? "next";
2311
- const record = {
2312
- stepId: step.id,
2313
- key: step.key,
2314
- pieceName: step.pieceName,
2315
- blockName: step.actionName,
2316
- status: "REPLAYED",
2317
- output: replay.output,
2318
- port,
2319
- configHash: stepConfigHash(step)
2320
- };
2321
- records.set(step.id, record);
2322
- await journal(record);
2323
- scope.steps[step.key] = { output: replay.output };
2324
- decideOutgoing(step.id, port);
2325
- return;
2326
- }
2327
- const startedAt = (/* @__PURE__ */ new Date()).toISOString();
2328
- let input;
2329
- try {
2330
- input = resolveStepInput(step, scope);
2331
- checkDynamicProperties(input, step.propertySettings);
2332
- const result = await executor.execute({
2333
- block: stepBlock(step),
2334
- config: input,
2335
- connectionId: step.connectionId,
2336
- step,
2337
- ...runSecrets.length > 0 ? { redactValues: runSecrets } : {}
2338
- });
2339
- const port = result.port ?? "next";
2340
- const values = [...runSecrets, ...result.redactValues ?? []];
2341
- const record = {
2342
- stepId: step.id,
2343
- key: step.key,
2344
- pieceName: step.pieceName,
2345
- blockName: step.actionName,
2346
- status: "SUCCEEDED",
2347
- input: journaled(input, values),
2348
- output: journaled(result.output, values),
2349
- port,
2350
- startedAt,
2351
- endedAt: (/* @__PURE__ */ new Date()).toISOString(),
2352
- ...withPiece(pieceRecord(result.resolution)),
2353
- configHash: stepConfigHash(step)
2354
- };
2355
- records.set(step.id, record);
2356
- await journal(record);
2357
- scope.steps[step.key] = { output: result.output };
2358
- decideOutgoing(step.id, port);
2359
- } catch (error) {
2360
- const values = [...runSecrets, ...secretsFor(error)];
2361
- const detail = redactMessage(errorMessage(error), { values });
2362
- const record = {
2363
- stepId: step.id,
2364
- key: step.key,
2365
- pieceName: step.pieceName,
2366
- blockName: step.actionName,
2367
- status: "FAILED",
2368
- input: journaled(input, values),
2369
- error: detail,
2370
- startedAt,
2371
- endedAt: (/* @__PURE__ */ new Date()).toISOString(),
2372
- ...withPiece(pieceRecord(resolutionOf(error))),
2373
- configHash: stepConfigHash(step)
2374
- };
2375
- records.set(step.id, record);
2376
- await journal(record);
2377
- scope.steps[step.key] = { error: detail };
2378
- decideOutgoing(step.id, "error");
2379
- if (!definition.edges.some((edge) => edge.from === step.id && edgeDecisions.get(edge.id))) runFailed = `Step "${step.key}" failed: ${detail}`;
2380
- }
2381
- };
2382
- let progressed = true;
2383
- while (progressed && !runFailed) {
2384
- progressed = false;
2385
- for (const step of definition.steps) {
2386
- if (records.has(step.id)) continue;
2387
- const inbound = inboundEdges(step);
2388
- if (isEntryStep(step)) {
2389
- await executeStep(step);
2390
- progressed = true;
2391
- if (runFailed) break;
2392
- continue;
2393
- }
2394
- if (inbound.length === 0) continue;
2395
- if (!inbound.every((edge) => edgeDecisions.has(edge.id))) continue;
2396
- if (inbound.some((edge) => edgeDecisions.get(edge.id))) await executeStep(step);
2397
- else skipStep(step);
2398
- progressed = true;
2399
- if (runFailed) break;
2400
- }
2401
- }
2402
- for (const step of definition.steps) if (!records.has(step.id)) skipStep(step);
2403
- const steps = definition.steps.map((step) => records.get(step.id));
2404
- const warnings = options.declaredPorts ? deadPortWarnings(definition, options.declaredPorts) : [];
2405
- const noted = warnings.length > 0 ? { warnings } : {};
2406
- return runFailed ? {
2407
- status: "FAILED",
2408
- steps,
2409
- error: runFailed,
2410
- ...noted
2411
- } : {
2412
- status: "SUCCEEDED",
2413
- steps,
2414
- ...noted
2415
- };
2416
- }
2417
- //#endregion
2418
- //#region src/reactor/piece-registry.ts
2419
- const logger = childLogger(["workflow", "piece-registry"]);
2420
- function pieceLocation(piece) {
2421
- return piece.entryPath ?? piece.bundleDir ?? piece.entryUrl ?? "?";
2422
- }
2423
- var PieceRegistry = class {
2424
- byName = /* @__PURE__ */ new Map();
2425
- setPieces(pieces) {
2426
- const found = /* @__PURE__ */ new Map();
2427
- for (const piece of pieces) {
2428
- const held = found.get(piece.name);
2429
- if (!held) {
2430
- found.set(piece.name, piece);
2431
- continue;
2432
- }
2433
- logger.warn("Piece @name is shipped twice; keeping @kept, ignoring @ignored", piece.name, `${held.version} (${pieceLocation(held)})`, `${piece.version} (${pieceLocation(piece)})`);
2434
- }
2435
- this.byName = found;
2436
- const names = [...found.keys()].join(", ");
2437
- const held = [...found.values()].filter((piece) => piece.entryPath ?? piece.bundleDir).length;
2438
- const served = found.size - held;
2439
- if (found.size > 0) {
2440
- const what = served === 0 ? `${held} package piece(s) on disk` : held === 0 ? `${served} package piece(s), fetched when first run` : `${held} on disk and ${served} fetched when first run`;
2441
- logger.info(`Holding ${what}: @names`, names);
2442
- } else logger.debug("Holding no package pieces");
2443
- }
2444
- lookup = (name) => this.byName.get(name);
2445
- entries() {
2446
- return [...this.byName.values()];
2447
- }
2448
- versions() {
2449
- return Object.fromEntries([...this.byName.values()].map((piece) => [piece.name, piece.version]));
2450
- }
2451
- /** Test seam: a suite that filled the registry starts the next from nothing. */
2452
- reset() {
2453
- this.byName = /* @__PURE__ */ new Map();
2454
- }
2455
- };
2456
- const packagePieces = new PieceRegistry();
2457
- function installedPiece(name) {
2458
- return builtinLocalPieces().find((piece) => piece.name === name) ?? packagePieces.lookup(name);
2459
- }
2460
- function installedPieces() {
2461
- return [...builtinLocalPieces(), ...packagePieces.entries().filter((piece) => !isBuiltinPiece(piece.name))];
2462
- }
2463
- //#endregion
2464
- export { resolveStepInput as A, PieceWorker as B, describeBuiltinPiece as C, StaticConnectionResolver as D, BoundConnectionResolver as E, parseSecretRef as F, sourcedResolver as G, PieceWorkerTimeoutError as H, secretRefFromId as I, npmRegistryBaseUrl as J, ensurePieceBundle as K, stepBlock as L, InMemorySecretProvider as M, SecretDeletedError as N, declaredConnectionIds as O, SecretNotFoundError as P, triggerBlock as R, builtinPiece as S, CORE_PIECE_VERSION as T, bundleResolver as U, PieceWorkerError as V, pieceModuleRef as W, setPieceRegistryUrl as X, pieceRegistrySource as Y, servesReactorPort as _, runWorkflow as a, unpinnedNote as b, stepConfigHash as c, ActivepiecesBlockExecutor as d, CompositeBlockExecutor as f, resolvedBlock as g, reactorHandlers as h, packagePieces as i, expressionsIn as j, shapeConnection as k, DynamicPropertiesError as l, isHostBound as m, installedPiece as n, canonicalJson as o, REACTOR_PORT_PIECE as p, fetchPieceBundle as q, installedPieces as r, hashOf as s, PieceRegistry as t, checkDynamicProperties as u, storeHandlers as v, CORE_PIECE_NAME$1 as w, blockPorts as x, blockLabel as y, PieceWorkerPool as z };
2465
-
2466
- //# sourceMappingURL=piece-registry-CHN0198d.js.map