@plitzi/sdk-actions 0.0.0-stage → 0.39.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +54 -2
  3. package/dist/chunks/credentials-DwxZeAvH.mjs +27 -0
  4. package/dist/chunks/errors-bCBfIe7c.mjs +54 -0
  5. package/dist/chunks/grants-BsD-WlLE.mjs +168 -0
  6. package/dist/chunks/load-DBWRZn7G.mjs +48 -0
  7. package/dist/chunks/module-WdDzbjHy.mjs +7032 -0
  8. package/dist/chunks/queueDocument-xYz-KZ5V.mjs +21 -0
  9. package/dist/chunks/queueRules-BCCVgeUE.mjs +487 -0
  10. package/dist/chunks/remote-DopPgCMK.mjs +404 -0
  11. package/dist/chunks/storeClock-Btm7EaVm.mjs +31 -0
  12. package/dist/chunks/taskCatalog-S1IozUTD.mjs +201 -0
  13. package/dist/connectors/connectors.d.ts +7 -0
  14. package/dist/connectors/engine.d.ts +47 -0
  15. package/dist/connectors/getByPath.d.ts +8 -0
  16. package/dist/connectors/projection.d.ts +18 -0
  17. package/dist/connectors/resolver.d.ts +27 -0
  18. package/dist/connectors/types.d.ts +19 -0
  19. package/dist/engine/configSeam.d.ts +10 -0
  20. package/dist/engine/connectorWrite.d.ts +12 -0
  21. package/dist/engine/fileStore.d.ts +60 -0
  22. package/dist/engine/fleet.d.ts +20 -0
  23. package/dist/engine/jobs/calls.d.ts +49 -0
  24. package/dist/engine/jobs/claimSpaces.d.ts +10 -0
  25. package/dist/engine/jobs/codeMarks.d.ts +10 -0
  26. package/dist/engine/jobs/endings.d.ts +42 -0
  27. package/dist/engine/jobs/failureStreak.d.ts +15 -0
  28. package/dist/engine/jobs/fileQueue.d.ts +34 -0
  29. package/dist/engine/jobs/flow.d.ts +11 -0
  30. package/dist/engine/jobs/jobs.d.ts +36 -0
  31. package/dist/engine/jobs/later.d.ts +27 -0
  32. package/dist/engine/jobs/memoryNeeds.d.ts +24 -0
  33. package/dist/engine/jobs/memoryQueue.d.ts +33 -0
  34. package/dist/engine/jobs/memoryWatch.d.ts +21 -0
  35. package/dist/engine/jobs/notNow.d.ts +39 -0
  36. package/dist/engine/jobs/queueDocument.d.ts +15 -0
  37. package/dist/engine/jobs/queueRules.d.ts +64 -0
  38. package/dist/engine/jobs/scheduler.d.ts +70 -0
  39. package/dist/engine/jobs/schedules.d.ts +24 -0
  40. package/dist/engine/jobs/storeClock.d.ts +16 -0
  41. package/dist/engine/jobs/wake.d.ts +6 -0
  42. package/dist/engine/jobs/worker.d.ts +99 -0
  43. package/dist/engine/module.d.ts +96 -0
  44. package/dist/engine/moduleFor.d.ts +3 -0
  45. package/dist/engine/runtime/check.d.ts +24 -0
  46. package/dist/engine/runtime/credentials.d.ts +8 -0
  47. package/dist/engine/runtime/deadline.d.ts +19 -0
  48. package/dist/engine/runtime/email.d.ts +38 -0
  49. package/dist/engine/runtime/errors.d.ts +28 -0
  50. package/dist/engine/runtime/fileKv.d.ts +35 -0
  51. package/dist/engine/runtime/flags.d.ts +16 -0
  52. package/dist/engine/runtime/guards.d.ts +190 -0
  53. package/dist/engine/runtime/kvList.d.ts +28 -0
  54. package/dist/engine/runtime/kvStore.d.ts +36 -0
  55. package/dist/engine/runtime/limits.d.ts +12 -0
  56. package/dist/engine/runtime/memoryKv.d.ts +28 -0
  57. package/dist/engine/runtime/namespaceKv.d.ts +9 -0
  58. package/dist/engine/runtime/precheck.d.ts +28 -0
  59. package/dist/engine/runtime/rateLimit.d.ts +9 -0
  60. package/dist/engine/runtime/redisKv.d.ts +27 -0
  61. package/dist/engine/runtime/renderFailure.d.ts +24 -0
  62. package/dist/engine/runtime/renderResolver.d.ts +16 -0
  63. package/dist/engine/runtime/renderShare.d.ts +12 -0
  64. package/dist/engine/runtime/report.d.ts +15 -0
  65. package/dist/engine/runtime/runAction.d.ts +26 -0
  66. package/dist/engine/runtime/runLogger.d.ts +37 -0
  67. package/dist/engine/runtime/runStats.d.ts +8 -0
  68. package/dist/engine/runtime/scope.d.ts +40 -0
  69. package/dist/engine/runtime/signing.d.ts +27 -0
  70. package/dist/engine/runtime/taskContext.d.ts +54 -0
  71. package/dist/engine/runtime/triggers.d.ts +12 -0
  72. package/dist/engine/taskCatalog.d.ts +28 -0
  73. package/dist/engine/tasks/auth.d.ts +2 -0
  74. package/dist/engine/tasks/builtins.d.ts +10 -0
  75. package/dist/engine/tasks/connector.d.ts +2 -0
  76. package/dist/engine/tasks/db.d.ts +2 -0
  77. package/dist/engine/tasks/email.d.ts +2 -0
  78. package/dist/engine/tasks/flow.d.ts +3 -0
  79. package/dist/engine/tasks/helpers.d.ts +16 -0
  80. package/dist/engine/tasks/http.d.ts +2 -0
  81. package/dist/engine/tasks/kv.d.ts +2 -0
  82. package/dist/engine/tasks/list.d.ts +2 -0
  83. package/dist/engine/tasks/names.d.ts +8 -0
  84. package/dist/engine/tasks/realtime.d.ts +3 -0
  85. package/dist/engine/tasks/registry.d.ts +19 -0
  86. package/dist/engine/tasks/transform.d.ts +2 -0
  87. package/dist/engine/transport/callHandler.d.ts +34 -0
  88. package/dist/engine/transport/cancelHandler.d.ts +23 -0
  89. package/dist/engine/transport/catalogHandler.d.ts +22 -0
  90. package/dist/engine/transport/stream.d.ts +22 -0
  91. package/dist/engine/transport/verifySignature.d.ts +16 -0
  92. package/dist/engine/transport/webhookHandler.d.ts +26 -0
  93. package/dist/engine/types.d.ts +442 -0
  94. package/dist/functions/build.d.ts +27 -0
  95. package/dist/functions/capabilities.d.ts +11 -0
  96. package/dist/functions/config.d.ts +111 -0
  97. package/dist/functions/context.d.ts +15 -0
  98. package/dist/functions/index.d.ts +17 -0
  99. package/dist/functions/index.mjs +461 -0
  100. package/dist/functions/jobControl.d.ts +22 -0
  101. package/dist/functions/jobs.d.ts +104 -0
  102. package/dist/functions/load.d.ts +22 -0
  103. package/dist/functions/local.d.ts +36 -0
  104. package/dist/functions/manifest.d.ts +32 -0
  105. package/dist/functions/native.d.ts +13 -0
  106. package/dist/functions/oauth.d.ts +33 -0
  107. package/dist/functions/routes.d.ts +50 -0
  108. package/dist/functions/runner/remote.d.ts +26 -0
  109. package/dist/functions/scope.d.ts +28 -0
  110. package/dist/functions/space.d.ts +41 -0
  111. package/dist/functions/tryEntry.d.ts +9 -0
  112. package/dist/index.d.ts +47 -0
  113. package/dist/index.mjs +545 -0
  114. package/dist/mongo/claimable.d.ts +5 -0
  115. package/dist/mongo/index.d.ts +4 -0
  116. package/dist/mongo/index.mjs +779 -0
  117. package/dist/mongo/jobQueue.d.ts +38 -0
  118. package/dist/mongo/kv.d.ts +15 -0
  119. package/dist/mysql/index.d.ts +5 -0
  120. package/dist/mysql/index.mjs +808 -0
  121. package/dist/mysql/jobQueue.d.ts +40 -0
  122. package/dist/mysql/kv.d.ts +18 -0
  123. package/dist/mysql/rows.d.ts +64 -0
  124. package/dist/mysql/schema.d.ts +28 -0
  125. package/dist/mysql/summary.d.ts +7 -0
  126. package/dist/realtime/declarations.d.ts +11 -0
  127. package/dist/realtime/failure.d.ts +6 -0
  128. package/dist/realtime/grants.d.ts +22 -0
  129. package/dist/realtime/handlers.d.ts +86 -0
  130. package/dist/realtime/hub.d.ts +71 -0
  131. package/dist/realtime/index.d.ts +105 -0
  132. package/dist/realtime/index.mjs +824 -0
  133. package/dist/realtime/jobs.d.ts +18 -0
  134. package/dist/realtime/message.d.ts +3 -0
  135. package/dist/realtime/presence.d.ts +33 -0
  136. package/dist/realtime/retained.d.ts +21 -0
  137. package/dist/realtime/socket.d.ts +30 -0
  138. package/dist/render/index.d.ts +10 -0
  139. package/dist/render/index.mjs +1 -0
  140. package/dist/render/protocol.d.ts +47 -0
  141. package/dist/render/remote.d.ts +16 -0
  142. package/dist/runtimes/bundle.d.ts +29 -0
  143. package/dist/runtimes/index.d.ts +3 -0
  144. package/dist/runtimes/index.mjs +229 -0
  145. package/dist/runtimes/stages.d.ts +52 -0
  146. package/dist/sqlite/index.d.ts +4 -0
  147. package/dist/sqlite/index.mjs +160 -0
  148. package/dist/sqlite/jobQueue.d.ts +35 -0
  149. package/dist/sqlite/kv.d.ts +34 -0
  150. package/dist/sqlite/open.d.ts +3 -0
  151. package/dist/types/config.d.ts +293 -0
  152. package/dist/types/index.d.ts +2 -0
  153. package/dist/types/index.mjs +1 -0
  154. package/dist/types/jobs.d.ts +317 -0
  155. package/dist/worker/elsewhere.d.ts +16 -0
  156. package/dist/worker/index.d.ts +5 -0
  157. package/dist/worker/index.mjs +1703 -0
  158. package/dist/worker/origin.d.ts +12 -0
  159. package/dist/worker/pageEngine.d.ts +11 -0
  160. package/dist/worker/stages/action.d.ts +24 -0
  161. package/dist/worker/stages/cors.d.ts +9 -0
  162. package/dist/worker/stages/forward.d.ts +12 -0
  163. package/dist/worker/stages/functionRoutes.d.ts +10 -0
  164. package/dist/worker/stages/queuedCalls.d.ts +15 -0
  165. package/dist/worker/stages/realtime.d.ts +9 -0
  166. package/dist/worker/stages/render.d.ts +9 -0
  167. package/dist/worker/worker.d.ts +39 -0
  168. package/package.json +76 -3
package/dist/index.mjs ADDED
@@ -0,0 +1,545 @@
1
+ import { A as schedulesFor, C as fleetJobQueue, D as DEFAULT_MAX_ATTEMPTS, E as createScheduler, I as fetchConnectorRecords, L as rebaseMedia, M as KEPT_CALLS_PER_SPACE, N as KEPT_CALL_MS, O as scheduleFor, R as writeConnectorRecord, T as createJobWorker, _ as DEFAULT_LIMITS, a as createTaskRegistry, b as MAX_LIST_ENTRIES, f as taskName, g as spaceKvPatterns, j as createMemoryJobQueue, k as scheduleJobId, m as createSigning, p as MIN_SIGNING_SECRET_LENGTH, s as jobViewOf, t as createActionsModule, v as createKvStore, w as fleetKv, x as createActionJobs, y as MAX_LIST_BYTES } from "./chunks/module-WdDzbjHy.mjs";
2
+ import { n as describeTask, r as createConnectorResolver, t as describeCatalog } from "./chunks/taskCatalog-S1IozUTD.mjs";
3
+ import { n as stateOf, t as documentOf } from "./chunks/queueDocument-xYz-KZ5V.mjs";
4
+ import { a as emptyState, c as queueRules, i as changedBy, r as applyRule, s as queueOver } from "./chunks/queueRules-BCCVgeUE.mjs";
5
+ import { a as triggerParams, t as ActionRunError } from "./chunks/errors-bCBfIe7c.mjs";
6
+ import { a as createMapKv, o as createMemoryKv } from "./chunks/grants-BsD-WlLE.mjs";
7
+ import { createActionRealtime, n as publishJobView, r as createRealtimeHub, t as createRealtimeRetained } from "./realtime/index.mjs";
8
+ import { t as credentialsFromEnv } from "./chunks/credentials-DwxZeAvH.mjs";
9
+ import { hasValidToken } from "@plitzi/sdk-shared/helpers/twigWrapper";
10
+ import fs from "node:fs";
11
+ import { parseCron, readSmtpCredential, triggerHasStaleVerify, triggerVerify } from "@plitzi/sdk-shared/actions";
12
+ import path from "node:path";
13
+ import { writeFileAtomic } from "@plitzi/sdk-kernel/files";
14
+ import { serverLog } from "@plitzi/sdk-kernel/log";
15
+ // src/engine/fileStore.ts
16
+ var holderIn = (lock) => {
17
+ try {
18
+ const parsed = JSON.parse(fs.readFileSync(lock, "utf8"));
19
+ return typeof parsed === "object" && parsed !== null && "pid" in parsed && typeof parsed.pid === "number" ? {
20
+ pid: parsed.pid,
21
+ since: "since" in parsed && typeof parsed.since === "string" ? parsed.since : "?",
22
+ ..."owner" in parsed && typeof parsed.owner === "string" ? { owner: parsed.owner } : {},
23
+ ..."serves" in parsed && typeof parsed.serves === "string" ? { serves: parsed.serves } : {}
24
+ } : void 0;
25
+ } catch {
26
+ return;
27
+ }
28
+ };
29
+ /** Whether a process is still running: signal 0 asks without sending anything, and `EPERM` is one that is not ours. */
30
+ var running = (pid) => {
31
+ try {
32
+ process.kill(pid, 0);
33
+ return true;
34
+ } catch (error) {
35
+ return error.code === "EPERM";
36
+ }
37
+ };
38
+ /**
39
+ * A file another running process holds: its message is the whole report — who holds it and how to stop it — said as it
40
+ * is when the server starts (`serveProject`). Thrown plain, it was a stack ending on its cause's `EEXIST`, and the agent
41
+ * reading the end of it found no word of what to do.
42
+ */
43
+ var FileInUseError = class extends Error {
44
+ /** The process that holds it: a server says where it answers, for the one refused to point there. */
45
+ holder;
46
+ constructor(message, holder, options) {
47
+ super(message, options);
48
+ this.name = "FileInUseError";
49
+ this.holder = holder;
50
+ }
51
+ };
52
+ /** The files this process holds, let go of together when it exits — however it does. */
53
+ var held = /* @__PURE__ */ new Set();
54
+ /** Lets go of a file this process holds. */
55
+ var letGo = (lock) => {
56
+ held.delete(lock);
57
+ if (holderIn(lock)?.pid === process.pid) fs.rmSync(lock, { force: true });
58
+ };
59
+ process.once("exit", () => held.forEach(letGo));
60
+ /**
61
+ * Takes the file for this process, or says who has it — `store` names the store in what is said (`createFileKv`).
62
+ *
63
+ * Two processes on one file each load it and then write their whole document over it: every change one makes, the
64
+ * other erases with its next write, and nothing anywhere says so — a second server started beside the first, a
65
+ * `--watch` left running after a restart. So a file has one holder: a second is refused, naming the first. A lock whose
66
+ * process is gone — killed, crashed — is taken over.
67
+ */
68
+ var holdFile = (file, { owner, serves }, store) => {
69
+ const lock = `${file}.lock`;
70
+ fs.mkdirSync(path.dirname(file), { recursive: true });
71
+ const mine = {
72
+ pid: process.pid,
73
+ since: (/* @__PURE__ */ new Date()).toISOString(),
74
+ ...owner ? { owner } : {},
75
+ ...serves ? { serves } : {}
76
+ };
77
+ for (let attempt = 0; attempt < 2; attempt += 1) try {
78
+ fs.writeFileSync(lock, JSON.stringify(mine), { flag: "wx" });
79
+ held.add(lock);
80
+ return lock;
81
+ } catch (error) {
82
+ if (error.code !== "EEXIST") throw error;
83
+ const holder = holderIn(lock);
84
+ if (holder && running(holder.pid)) throw new FileInUseError(`${store}: ${file} is in use by process ${String(holder.pid)}${holder.owner ? ` — ${holder.owner}` : ""}, since ${holder.since}. Two processes on one file write over each other's changes: stop that one first, or point \`file\` elsewhere.`, holder, { cause: error });
85
+ fs.rmSync(lock, { force: true });
86
+ }
87
+ throw new Error(`${store}: ${lock} could not be taken`);
88
+ };
89
+ /**
90
+ * Writes `document()` to `file` whole after each change, through a temporary file renamed over the old one — changes
91
+ * that arrive while a write is under way are written together right after it, so a crash loses at most the changes of
92
+ * that instant and never leaves half a file. A write that failed is said in the log and tried again by the next change
93
+ * or `flush`, never in a loop against a disk that keeps refusing.
94
+ */
95
+ var documentWriter = ({ file, document, store, what }) => {
96
+ let dirty = false;
97
+ let failed = false;
98
+ /** The write under way, resolving to whether everything it took on reached the disk. */
99
+ let writing;
100
+ const drain = async () => {
101
+ while (dirty) {
102
+ dirty = false;
103
+ try {
104
+ await fs.promises.mkdir(path.dirname(file), { recursive: true });
105
+ await writeFileAtomic(file, document());
106
+ } catch (error) {
107
+ dirty = true;
108
+ failed = true;
109
+ serverLog.error("Actions", `${what} ${file} could not be written`, error);
110
+ return false;
111
+ }
112
+ }
113
+ return true;
114
+ };
115
+ const write = () => {
116
+ writing ??= new Promise((resolve) => {
117
+ queueMicrotask(resolve);
118
+ }).then(drain).finally(() => {
119
+ writing = void 0;
120
+ if (dirty && !failed) write();
121
+ });
122
+ return writing;
123
+ };
124
+ return {
125
+ changed: () => {
126
+ dirty = true;
127
+ failed = false;
128
+ write();
129
+ },
130
+ flush: async () => {
131
+ failed = false;
132
+ while (writing !== void 0 || dirty) if (!await (writing ?? write())) throw new Error(`${store}: ${file} could not be written; the reason is in the log.`);
133
+ }
134
+ };
135
+ };
136
+ // src/engine/jobs/fileQueue.ts
137
+ var load$1 = (file) => {
138
+ if (!fs.existsSync(file)) return emptyState();
139
+ const refuse = (why) => /* @__PURE__ */ new Error(`createFileJobQueue: ${file} is not a queue it wrote (${why}). Move it aside, or point \`file\` elsewhere.`);
140
+ let parsed;
141
+ try {
142
+ parsed = JSON.parse(fs.readFileSync(file, "utf8"));
143
+ } catch (error) {
144
+ throw refuse(error instanceof Error ? error.message : String(error));
145
+ }
146
+ const state = stateOf(parsed);
147
+ if (typeof state === "string") throw refuse(state);
148
+ return state;
149
+ };
150
+ /**
151
+ * The job queue in one JSON file: what `ctx.later`, a schedule's fires and a function's jobs wait in, surviving a
152
+ * restart — for a deployment with no database. A job due while the server was down runs once it is back; one a worker
153
+ * held when it went down is taken again, its attempt written `lost`.
154
+ *
155
+ * ```ts
156
+ * createServer({ action: { jobs: { queue: createFileJobQueue({ file: 'state/jobs.json' }) } } });
157
+ * ```
158
+ *
159
+ * The rules are the in-process queue's, to the letter (`queueRules`): the file is only where its state is kept, written
160
+ * whole after each change that changed something, as `createFileKv` writes its own. ONE process holds the file
161
+ * (`<file>.lock`); the workers of one server reach the primary's through the fleet (`fleetJobQueue`); replicas share
162
+ * `createSqliteJobQueue` (`@plitzi/sdk-actions/sqlite`) or a database's queue.
163
+ */
164
+ var createFileJobQueue = ({ file, owner, serves, retainFinished = 500, clock = Date.now }) => {
165
+ const lock = holdFile(file, {
166
+ owner,
167
+ serves
168
+ }, "createFileJobQueue");
169
+ let state;
170
+ try {
171
+ state = load$1(file);
172
+ } catch (error) {
173
+ letGo(lock);
174
+ throw error;
175
+ }
176
+ const { changed, flush } = documentWriter({
177
+ file,
178
+ document: () => `${JSON.stringify(documentOf(state), null, 2)}\n`,
179
+ store: "createFileJobQueue",
180
+ what: "job queue file"
181
+ });
182
+ const rules = queueRules(state, {
183
+ retainFinished,
184
+ clock,
185
+ onUnansweredChange: changed
186
+ });
187
+ return {
188
+ ...queueOver((method, args) => {
189
+ const answer = applyRule(rules, method, args);
190
+ if (changedBy(method, answer)) changed();
191
+ return Promise.resolve(answer);
192
+ }),
193
+ flush,
194
+ close: async () => {
195
+ try {
196
+ await flush();
197
+ } finally {
198
+ letGo(lock);
199
+ }
200
+ }
201
+ };
202
+ };
203
+ // src/engine/runtime/check.ts
204
+ /** A value the check can reason about: a literal the author typed, not a template resolved at run time. */
205
+ var literal = (value) => {
206
+ const text = typeof value === "string" ? value.trim() : "";
207
+ return text && !hasValidToken(text) ? text : "";
208
+ };
209
+ /**
210
+ * What only THIS deployment can answer about an action.
211
+ *
212
+ * `validateActionDocument` reads the document and nothing else, so it catches a flow that contradicts itself — a
213
+ * step with no task, an output that names a step that does not exist. It cannot catch the other half, which is
214
+ * every way a correct document meets a server that cannot run it: a task this deployment never registered, a
215
+ * credential the space does not have, a key that is not in the credential it does have, a connector that was
216
+ * deleted, a database engine with no driver, a cron that will never fire.
217
+ *
218
+ * Those are the failures that surface at 3am on the first real delivery, and an author has no way to see them
219
+ * from the editor — which is why this runs on the server and answers in the same shape the validator does.
220
+ *
221
+ * It reads credentials to ask WHETHER they exist and whether they carry the key a step names. It never reports a
222
+ * value, and nothing here runs a step.
223
+ */
224
+ var checkAction = async (entry, deps) => {
225
+ const { spaceId, registry, lookups, dbDrivers = [] } = deps;
226
+ const issues = [];
227
+ const add = (level, path, message, hint) => issues.push({
228
+ level,
229
+ path,
230
+ message,
231
+ ...hint === void 0 ? {} : { hint }
232
+ });
233
+ /** Answers once per identifier: a flow naming the same credential in four steps is one lookup, not four. */
234
+ const credentials = /* @__PURE__ */ new Map();
235
+ const credentialOf = async (identifier) => {
236
+ if (!credentials.has(identifier)) credentials.set(identifier, await lookups.getCredential?.(spaceId, identifier));
237
+ return credentials.get(identifier);
238
+ };
239
+ const checkCredential = async (node, identifier, field) => {
240
+ const path = `nodes.${node.id}.params.credential`;
241
+ const credential = await credentialOf(identifier);
242
+ if (!credential) {
243
+ add("error", path, `This space has no credential called "${identifier}"`, "Add it in Credentials, or name one that exists");
244
+ return;
245
+ }
246
+ if (field && !(field in credential)) add("error", path, `The credential "${identifier}" has no key called "${field}"`, `It holds: ${Object.keys(credential).join(", ") || "nothing"}`);
247
+ return credential;
248
+ };
249
+ const checkTrigger = async (node) => {
250
+ const params = triggerParams(node);
251
+ if (node.action === "webhook") {
252
+ if (triggerHasStaleVerify(params)) {
253
+ add("error", `nodes.${node.id}.params.signatureCredential`, "The signature check is in a format nothing reads any more, so this endpoint is refused outright", "Name the signing credential on the trigger step");
254
+ return;
255
+ }
256
+ const verify = triggerVerify(params);
257
+ if (!verify) {
258
+ add("warning", `nodes.${node.id}.params.signatureCredential`, "This webhook verifies nothing: anyone who learns the URL can start it", "Name the credential holding the sender’s signing secret");
259
+ return;
260
+ }
261
+ const credential = await credentialOf(verify.credential);
262
+ const field = verify.secretField ?? "secret";
263
+ if (!credential) {
264
+ add("error", `nodes.${node.id}.params.signatureCredential`, `This space has no credential called "${verify.credential}"`);
265
+ return;
266
+ }
267
+ if (!(field in credential)) {
268
+ add("error", `nodes.${node.id}.params.signatureSecretField`, `The credential "${verify.credential}" has no key called "${field}"`, `It holds: ${Object.keys(credential).join(", ") || "nothing"}`);
269
+ return;
270
+ }
271
+ if (!credential[field]) add("error", `nodes.${node.id}.params.signatureSecretField`, `The key "${field}" of "${verify.credential}" is empty`);
272
+ }
273
+ if (node.action === "schedule" && !parseCron(params.cron ?? "")) add("error", `nodes.${node.id}.params.cron`, `"${params.cron ?? ""}" is not an expression this server can fire`, "Five fields, UTC — minute hour day-of-month month day-of-week");
274
+ };
275
+ const checkTask = async (node) => {
276
+ if (!registry.get(node.action)) {
277
+ add("error", `nodes.${node.id}.action`, `This server registers no task called "${node.action}"`, `It offers: ${registry.list().map((entry) => entry.name).join(", ")}`);
278
+ return;
279
+ }
280
+ const { params } = node;
281
+ const connector = literal(params.connector);
282
+ if (connector && !await lookups.getConnector?.(spaceId, connector)) add("error", `nodes.${node.id}.params.connector`, `This space has no connector called "${connector}"`, "Add it in Connectors, or name one that exists");
283
+ const identifier = literal(params.credential);
284
+ if (node.action === "email.send") {
285
+ const path = `nodes.${node.id}.params.credential`;
286
+ if (!identifier) {
287
+ add("error", path, "This step names no SMTP server to send through", "Add an SMTP credential and pick it here");
288
+ return;
289
+ }
290
+ const credential = await checkCredential(node, identifier);
291
+ if (!credential) return;
292
+ readSmtpCredential(credential).problems.forEach((problem) => add("error", path, `The credential "${identifier}" is not a usable SMTP server: ${problem.key} — ${problem.message}`));
293
+ return;
294
+ }
295
+ if (!identifier) return;
296
+ if (node.action === "db.query") {
297
+ const credential = await checkCredential(node, identifier, "dsn");
298
+ const engine = credential?.engine ?? "";
299
+ if (credential && !engine) {
300
+ add("error", `nodes.${node.id}.params.credential`, `The credential "${identifier}" declares no engine`, "Add an `engine` key naming the database, e.g. mysql");
301
+ return;
302
+ }
303
+ if (engine && !dbDrivers.some((driver) => driver.engine === engine)) add("error", `nodes.${node.id}.params.credential`, `This server has no driver for "${engine}"`, dbDrivers.length > 0 ? `It drives: ${dbDrivers.map((driver) => driver.engine).join(", ")}` : "It registers no database drivers at all");
304
+ return;
305
+ }
306
+ await checkCredential(node, identifier);
307
+ };
308
+ for (const node of Object.values(entry.document.nodes)) {
309
+ if (node.type === "trigger") {
310
+ await checkTrigger(node);
311
+ continue;
312
+ }
313
+ if (node.type === "task" && node.action) await checkTask(node);
314
+ }
315
+ return {
316
+ valid: !issues.some((issue) => issue.level === "error"),
317
+ issues
318
+ };
319
+ };
320
+ // src/engine/runtime/runLogger.ts
321
+ /**
322
+ * `onRun`, wired into the log stream the server already reports through.
323
+ *
324
+ * Without an `onRun` a deployment gets nothing at all about its flows: the request log says a call was answered,
325
+ * and a run started by a webhook or a schedule has no request to say anything about. This is the smallest useful
326
+ * answer to that, and it needs no store — whatever sink is already collecting `ServerLogEvent`s (a console, a
327
+ * file, a log shipper) starts carrying runs too, because a run is emitted as one more event on the same stream.
328
+ *
329
+ * What it reports is the SHAPE of the run — which steps ran and how each ended — and never what they held. A
330
+ * deployment that wants run HISTORY rather than run logs keeps its own `onRun` and writes rows; the two compose,
331
+ * since `onRun` is one function.
332
+ *
333
+ * Held to the server's `logLevel` like everything else on the stream: a run that completed is `debug` — or `warn` when it
334
+ * was slow (`SLOW_RUN_MS`) — and one that did not is `error`.
335
+ *
336
+ * Never throws: the runner treats the record as best-effort, and a logging outage must not take an action down.
337
+ */
338
+ var createRunLogger = (logger) => (record) => {
339
+ try {
340
+ serverLog.emit(logger, {
341
+ kind: "run",
342
+ name: record.actionId,
343
+ spaceId: record.spaceId,
344
+ environment: record.environment,
345
+ trigger: record.trigger,
346
+ status: record.status,
347
+ ...record.userId === void 0 ? {} : { userId: record.userId },
348
+ steps: record.steps.map((step) => `${step.action}:${step.status}`),
349
+ durationMs: record.durationMs,
350
+ ok: record.status === "completed",
351
+ ...record.error === void 0 ? {} : { error: record.error },
352
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
353
+ });
354
+ } catch {}
355
+ };
356
+ /**
357
+ * `onReject`, wired into the same log stream.
358
+ *
359
+ * The refusals are the half a deployment notices it is missing at the worst possible moment: an integration is
360
+ * being set up, every delivery is answered 401, and nothing anywhere says which check refused it. This puts them
361
+ * on the stream the server already reports through, as their own `kind` so a sink can route them somewhere
362
+ * louder than a run.
363
+ *
364
+ * It carries no body, no signature and no header — what went wrong is `reason`, and `detail` is the server's own
365
+ * words about it.
366
+ *
367
+ * A refusal is a `warn`: the caller was turned away, the server did not fail.
368
+ *
369
+ * Never throws, for the same reason the run logger does not: the caller was refused either way, and a sink's
370
+ * problem must not become the response's.
371
+ */
372
+ var createRejectLogger = (logger) => (record) => {
373
+ try {
374
+ serverLog.emit(logger, {
375
+ kind: "reject",
376
+ name: record.actionId,
377
+ spaceId: record.spaceId,
378
+ environment: record.environment,
379
+ trigger: record.trigger,
380
+ reason: record.reason,
381
+ ...record.callerId === void 0 ? {} : { callerId: record.callerId },
382
+ durationMs: 0,
383
+ ok: false,
384
+ ...record.detail === void 0 ? {} : { error: record.detail },
385
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
386
+ });
387
+ } catch {}
388
+ };
389
+ // src/engine/runtime/fileKv.ts
390
+ var isEntry = (value) => typeof value === "object" && value !== null && "value" in value && typeof value.value === "string" && (!("expiresAt" in value) || typeof value.expiresAt === "number");
391
+ var load = (file) => {
392
+ if (!fs.existsSync(file)) return /* @__PURE__ */ new Map();
393
+ const refuse = (why) => /* @__PURE__ */ new Error(`createFileKv: ${file} is not a store it wrote (${why}). Move it aside, or point \`file\` elsewhere.`);
394
+ let parsed;
395
+ try {
396
+ parsed = JSON.parse(fs.readFileSync(file, "utf8"));
397
+ } catch (error) {
398
+ throw refuse(error instanceof Error ? error.message : String(error));
399
+ }
400
+ if (typeof parsed !== "object" || parsed === null || !("format" in parsed) || parsed.format !== 1) throw refuse("no `format: 1`");
401
+ const entries = "entries" in parsed && typeof parsed.entries === "object" ? parsed.entries : null;
402
+ if (entries === null) throw refuse("no `entries`");
403
+ const now = Date.now();
404
+ const kept = Object.entries(entries).filter((pair) => isEntry(pair[1]) && (pair[1].expiresAt === void 0 || pair[1].expiresAt > now));
405
+ return new Map(kept);
406
+ };
407
+ /**
408
+ * A key/value store in one JSON file: the `kv` server actions keep — saved layouts, counters, a source's cached answer —
409
+ * surviving a restart, for a deployment with no database. Nothing to install, and a file anybody can read, back up or
410
+ * edit by hand while the server is stopped.
411
+ *
412
+ * ```ts
413
+ * createServer({ action: { kv: createFileKv({ file: 'state/kv.json' }) } });
414
+ * ```
415
+ *
416
+ * The rules are the in-process store's, to the letter (`createMapKv`): the file is only where the map is kept. Every
417
+ * change is written whole, through a temporary file renamed over the old one, as soon as the change is made — changes
418
+ * that arrive while a write is under way are written together right after it, so a crash loses at most the writes
419
+ * of that instant and never leaves half a file. Entries past their lifetime are not written.
420
+ *
421
+ * ONE process: it reads the file when it starts and holds it after (`<file>.lock`, with its pid) — a second process is
422
+ * refused, naming the first, because two would write over each other's changes. The workers of one server reach the
423
+ * primary's through the fleet (`fleetKv`); replicas use `createSqliteKv` (`@plitzi/sdk-actions/sqlite`) or a database.
424
+ * And a whole file per change: right for what a site keeps, not for a counter bumped thousands of times a second.
425
+ */
426
+ var createFileKv = ({ file, owner, serves }) => {
427
+ const lock = holdFile(file, {
428
+ owner,
429
+ serves
430
+ }, "createFileKv");
431
+ let entries;
432
+ try {
433
+ entries = load(file);
434
+ } catch (error) {
435
+ letGo(lock);
436
+ throw error;
437
+ }
438
+ const document = () => {
439
+ const now = Date.now();
440
+ const live = [...entries].filter(([, entry]) => entry.expiresAt === void 0 || entry.expiresAt > now);
441
+ const body = {
442
+ format: 1,
443
+ entries: Object.fromEntries(live)
444
+ };
445
+ return `${JSON.stringify(body, null, 2)}\n`;
446
+ };
447
+ const { changed, flush } = documentWriter({
448
+ file,
449
+ document,
450
+ store: "createFileKv",
451
+ what: "kv file"
452
+ });
453
+ return {
454
+ ...createMapKv(entries, changed),
455
+ flush,
456
+ close: async () => {
457
+ try {
458
+ await flush();
459
+ } finally {
460
+ letGo(lock);
461
+ }
462
+ }
463
+ };
464
+ };
465
+ // src/engine/runtime/redisKv.ts
466
+ /**
467
+ * Read and write as ONE step: Redis runs a script with nothing else in between, which is what makes it the
468
+ * compare-and-set it has no command for. `ARGV[1]` says whether a value is expected at all — an absent key and one
469
+ * holding the empty string are different things.
470
+ */
471
+ var SWAP = `
472
+ local current = redis.call('GET', KEYS[1])
473
+ if ARGV[1] == 'absent' then
474
+ if current then return 0 end
475
+ elseif current ~= ARGV[2] then
476
+ return 0
477
+ end
478
+ if ARGV[4] == '' then
479
+ redis.call('SET', KEYS[1], ARGV[3])
480
+ else
481
+ redis.call('SET', KEYS[1], ARGV[3], 'EX', tonumber(ARGV[4]))
482
+ end
483
+ return 1
484
+ `;
485
+ /**
486
+ * An {@link ActionKvAdapter} over Redis: each operation one command, and `swap` one script.
487
+ *
488
+ * `client` may be a function, for a deployment whose connection comes and goes — it is asked on every call, and a
489
+ * client it cannot give is its to refuse (throwing), never this adapter's to read as "no value".
490
+ */
491
+ var createRedisKv = (client, { prefix = "" } = {}) => {
492
+ const redis = typeof client === "function" ? client : () => client;
493
+ const key = (name) => `${prefix}${name}`;
494
+ return {
495
+ get: async (name) => await redis().get(key(name)) ?? void 0,
496
+ set: async (name, value, ttlSeconds) => {
497
+ await (ttlSeconds === void 0 ? redis().set(key(name), value) : redis().set(key(name), value, "EX", ttlSeconds));
498
+ },
499
+ delete: async (name) => {
500
+ await redis().del(key(name));
501
+ },
502
+ increment: (name, amount) => redis().incrby(key(name), amount),
503
+ expire: async (name, ttlSeconds) => {
504
+ await redis().expire(key(name), ttlSeconds);
505
+ },
506
+ swap: async (name, expected, next, ttlSeconds) => await redis().eval(SWAP, 1, key(name), expected === void 0 ? "absent" : "equals", expected ?? "", next, ttlSeconds === void 0 ? "" : ttlSeconds) === 1
507
+ };
508
+ };
509
+ // src/functions/jobControl.ts
510
+ /**
511
+ * An operator's hold on the jobs, from a process that serves no pages — a deployment's API behind its Queue panel: the
512
+ * queue's own `pause`, `resume`, `cancel` and `requeue`, each said on `$job:<id>` when it changed a job of the spaces'
513
+ * functions, as the page server says it when its code does the same.
514
+ */
515
+ var createJobControl = ({ queue, realtime }) => {
516
+ const said = realtime ? {
517
+ retained: createRealtimeRetained(realtime.kv),
518
+ pubsub: realtime.pubsub
519
+ } : void 0;
520
+ const hub = said ? createRealtimeHub(said.pubsub, said.retained) : void 0;
521
+ const announce = async (spaceIds, jobId) => {
522
+ if (!hub || !said) return;
523
+ try {
524
+ const job = await queue.getJob(spaceIds, jobId);
525
+ if (job?.target.kind === "function") await publishJobView(hub, said.retained, {
526
+ spaceId: job.spaceId,
527
+ environment: job.environment
528
+ }, jobId, jobViewOf(job));
529
+ } catch (error) {
530
+ serverLog.warn("Actions", `job ${jobId}: its watchers were not told what an operator did`, error);
531
+ }
532
+ };
533
+ const told = (change) => async (spaceIds, jobId, ...rest) => {
534
+ const changed = await change(spaceIds, jobId, ...rest);
535
+ if (changed) await announce(spaceIds, jobId);
536
+ return changed;
537
+ };
538
+ return {
539
+ pause: told((spaceIds, jobId) => queue.pause(spaceIds, jobId)),
540
+ resume: told((spaceIds, jobId) => queue.resume(spaceIds, jobId)),
541
+ cancel: told((spaceIds, jobId) => queue.cancel(spaceIds, jobId)),
542
+ requeue: told((spaceIds, jobId, options) => queue.requeue(spaceIds, jobId, options))
543
+ };
544
+ };
545
+ export { ActionRunError, DEFAULT_LIMITS, DEFAULT_MAX_ATTEMPTS, FileInUseError, KEPT_CALLS_PER_SPACE, KEPT_CALL_MS, MAX_LIST_BYTES, MAX_LIST_ENTRIES, MIN_SIGNING_SECRET_LENGTH, checkAction, createActionJobs, createActionRealtime, createActionsModule, createConnectorResolver, createFileJobQueue, createFileKv, createJobControl, createJobWorker, createKvStore, createMemoryJobQueue, createMemoryKv, createRedisKv, createRejectLogger, createRunLogger, createScheduler, createSigning, createTaskRegistry, credentialsFromEnv, describeCatalog, describeTask, fetchConnectorRecords, fleetJobQueue, fleetKv, rebaseMedia, scheduleFor, scheduleJobId, schedulesFor, spaceKvPatterns, taskName, writeConnectorRecord };
@@ -0,0 +1,5 @@
1
+ import { JobSpaces, JobTake } from '../types';
2
+ import { Document } from 'mongodb';
3
+ /** What a claim with these `spaces` and `memoryMb` takes at `at`: due and waiting, of its spaces — or a job a worker died
4
+ * running that this one may hold, whatever its spaces. */
5
+ export declare const claimable: (at: number, spaces: JobSpaces | undefined, memoryMb: number | undefined, takes?: JobTake) => Document;
@@ -0,0 +1,4 @@
1
+ export { createMongoJobQueue } from './jobQueue';
2
+ export { createMongoKv } from './kv';
3
+ export type { MongoDbSource, MongoJobQueue, MongoJobQueueOptions } from './jobQueue';
4
+ export type { MongoKvOptions } from './kv';