@plitzi/sdk-actions 0.0.0-stage → 0.39.3

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 +18 -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
@@ -0,0 +1,160 @@
1
+ import { n as stateOf, t as documentOf } from "../chunks/queueDocument-xYz-KZ5V.mjs";
2
+ import { a as emptyState, c as queueRules, i as changedBy, r as applyRule, s as queueOver } from "../chunks/queueRules-BCCVgeUE.mjs";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { DatabaseSync } from "node:sqlite";
6
+ // src/sqlite/open.ts
7
+ /** A SQLite file opened for the stores that share it — its folder made when it is not there. */
8
+ var openDatabase = (file) => {
9
+ fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true });
10
+ const db = new DatabaseSync(file);
11
+ db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000; PRAGMA synchronous = NORMAL;");
12
+ return db;
13
+ };
14
+ // src/sqlite/jobQueue.ts
15
+ /**
16
+ * The job queue in a SQLite file, over Node's own `node:sqlite`: what `ctx.later`, a schedule's fires and a function's
17
+ * jobs wait in, surviving a restart AND shared — every process on the file (replicas on one machine, a server started
18
+ * with `workers`) claims from the same queue, each job by one of them.
19
+ *
20
+ * ```ts
21
+ * import { createSqliteJobQueue, createSqliteKv } from '@plitzi/sdk-actions/sqlite';
22
+ *
23
+ * createServer({ action: { kv: createSqliteKv({ db }), jobs: { queue: createSqliteJobQueue({ db }) } } });
24
+ * ```
25
+ *
26
+ * The rules are the in-process queue's, to the letter (`queueRules`), run on the state as the table holds it, inside
27
+ * one `BEGIN IMMEDIATE` transaction a call: two processes never claim one job, nor write over each other's change. The
28
+ * state is one row, read whole each call — right for what a project's queue holds (its jobs waiting and the last
29
+ * `retainFinished` done); a deployment of thousands a minute keeps its queue in a database (`JobQueue`).
30
+ */
31
+ var createSqliteJobQueue = (options) => {
32
+ const table = options.table ?? "action_jobs";
33
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) throw new Error(`createSqliteJobQueue: "${table}" is not a table name (letters, digits and _, not starting with a digit).`);
34
+ const db = options.db ?? openDatabase(options.file);
35
+ db.exec(`CREATE TABLE IF NOT EXISTS ${table} (id INTEGER PRIMARY KEY CHECK (id = 1), document TEXT NOT NULL)`);
36
+ const statements = {
37
+ read: db.prepare(`SELECT document FROM ${table} WHERE id = 1`),
38
+ write: db.prepare(`INSERT INTO ${table} (id, document) VALUES (1, ?) ON CONFLICT (id) DO UPDATE SET document = excluded.document`)
39
+ };
40
+ const rulesOptions = {
41
+ retainFinished: options.retainFinished ?? 500,
42
+ clock: options.clock ?? Date.now
43
+ };
44
+ const read = () => {
45
+ const row = statements.read.get();
46
+ if (typeof row?.document !== "string") return emptyState();
47
+ const state = stateOf(JSON.parse(row.document));
48
+ if (typeof state === "string") throw new Error(`createSqliteJobQueue: the table ${table} holds no queue it wrote (${state}). Point \`table\` elsewhere.`);
49
+ return state;
50
+ };
51
+ return queueOver((method, args) => {
52
+ db.exec("BEGIN IMMEDIATE");
53
+ try {
54
+ const state = read();
55
+ const unanswered = { changed: false };
56
+ const rules = queueRules(state, {
57
+ ...rulesOptions,
58
+ onUnansweredChange: () => {
59
+ unanswered.changed = true;
60
+ }
61
+ });
62
+ const answer = applyRule(rules, method, args);
63
+ if (unanswered.changed || changedBy(method, answer)) statements.write.run(JSON.stringify(documentOf(state)));
64
+ db.exec("COMMIT");
65
+ return Promise.resolve(answer);
66
+ } catch (error) {
67
+ db.exec("ROLLBACK");
68
+ return Promise.reject(error instanceof Error ? error : new Error(String(error)));
69
+ }
70
+ });
71
+ };
72
+ // src/sqlite/kv.ts
73
+ /**
74
+ * The STORE's clock in epoch ms, read inside each statement: every process on the file agrees on what "now" is.
75
+ * `julianday()` with no argument is the current instant.
76
+ */
77
+ var NOW_MS = "CAST((julianday() - 2440587.5) * 86400000 AS INTEGER)";
78
+ /**
79
+ * A key/value store in a SQLite file, over Node's own `node:sqlite` — nothing to install, nothing to run beside the
80
+ * server. For a deployment with no database that wants what `kv` keeps to survive a restart AND to be shared: every
81
+ * process pointed at the same file — replicas on one machine, a server started with `workers` — sees the same keys,
82
+ * the same counters and the same single-flight keys.
83
+ *
84
+ * ```ts
85
+ * import { createSqliteKv } from '@plitzi/sdk-actions/sqlite';
86
+ *
87
+ * createServer({ action: { kv: createSqliteKv({ file: 'data/kv.sqlite' }) } });
88
+ * ```
89
+ *
90
+ * Every operation is ONE statement, so it is atomic without a transaction: an increment is an upsert that adds in
91
+ * place, a swap is an update whose `WHERE` names the value it expects. Lifetimes are instants on the store's clock,
92
+ * enforced on every read, and expired rows are swept as writes go by.
93
+ *
94
+ * Needs a Node with `node:sqlite` unflagged (22.13 and later), which still prints an `ExperimentalWarning` once when
95
+ * it loads — the reason this is its own entry rather than the default.
96
+ */
97
+ var createSqliteKv = (options) => {
98
+ const table = options.table ?? "action_kv";
99
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) throw new Error(`createSqliteKv: "${table}" is not a table name (letters, digits and _, not starting with a digit).`);
100
+ const db = options.db ?? openDatabase(options.file);
101
+ db.exec(`CREATE TABLE IF NOT EXISTS ${table} (key TEXT PRIMARY KEY, value TEXT NOT NULL, expires_at INTEGER)`);
102
+ const live = `(expires_at IS NULL OR expires_at > ${NOW_MS})`;
103
+ const expiry = (ttlSeconds) => ttlSeconds === void 0 ? null : ttlSeconds * 1e3;
104
+ const expiresAt = `CASE WHEN ? IS NULL THEN NULL ELSE ${NOW_MS} + ? END`;
105
+ const statements = {
106
+ get: db.prepare(`SELECT value FROM ${table} WHERE key = ? AND ${live}`),
107
+ set: db.prepare(`INSERT INTO ${table} (key, value, expires_at) VALUES (?, ?, ${expiresAt})
108
+ ON CONFLICT (key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at`),
109
+ delete: db.prepare(`DELETE FROM ${table} WHERE key = ?`),
110
+ increment: db.prepare(`INSERT INTO ${table} (key, value, expires_at) VALUES (?, ?, NULL)
111
+ ON CONFLICT (key) DO UPDATE SET
112
+ value = CASE WHEN ${table}.expires_at IS NOT NULL AND ${table}.expires_at <= ${NOW_MS}
113
+ THEN excluded.value ELSE CAST(${table}.value + ? AS TEXT) END,
114
+ expires_at = CASE WHEN ${table}.expires_at IS NOT NULL AND ${table}.expires_at <= ${NOW_MS}
115
+ THEN NULL ELSE ${table}.expires_at END
116
+ RETURNING value`),
117
+ expire: db.prepare(`UPDATE ${table} SET expires_at = ${expiresAt} WHERE key = ? AND ${live}`),
118
+ claim: db.prepare(`INSERT INTO ${table} (key, value, expires_at) VALUES (?, ?, ${expiresAt})
119
+ ON CONFLICT (key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at
120
+ WHERE ${table}.expires_at IS NOT NULL AND ${table}.expires_at <= ${NOW_MS}`),
121
+ replace: db.prepare(`UPDATE ${table} SET value = ?, expires_at = ${expiresAt} WHERE key = ? AND value = ? AND ${live}`),
122
+ sweep: db.prepare(`DELETE FROM ${table} WHERE expires_at IS NOT NULL AND expires_at <= ${NOW_MS}`)
123
+ };
124
+ /** Used-once keys (a delivery's idempotency key, a caller's window) expire and stay until swept: once a minute. */
125
+ let sweptAt = 0;
126
+ const sweep = () => {
127
+ if (Date.now() - sweptAt < 6e4) return;
128
+ sweptAt = Date.now();
129
+ statements.sweep.run();
130
+ };
131
+ const text = (row) => typeof row?.value === "string" ? row.value : void 0;
132
+ return {
133
+ get: (key) => Promise.resolve(text(statements.get.get(key))),
134
+ set: (key, value, ttlSeconds) => {
135
+ statements.set.run(key, value, expiry(ttlSeconds), expiry(ttlSeconds));
136
+ sweep();
137
+ return Promise.resolve();
138
+ },
139
+ delete: (key) => {
140
+ statements.delete.run(key);
141
+ return Promise.resolve();
142
+ },
143
+ increment: (key, amount) => {
144
+ const step = Number.isInteger(amount) ? BigInt(amount) : amount;
145
+ const value = text(statements.increment.get(key, String(amount), step));
146
+ sweep();
147
+ return Promise.resolve(Number(value ?? amount));
148
+ },
149
+ expire: (key, ttlSeconds) => {
150
+ statements.expire.run(expiry(ttlSeconds), expiry(ttlSeconds), key);
151
+ return Promise.resolve();
152
+ },
153
+ swap: (key, expected, next, ttlSeconds) => {
154
+ const written = expected === void 0 ? statements.claim.run(key, next, expiry(ttlSeconds), expiry(ttlSeconds)) : statements.replace.run(next, expiry(ttlSeconds), expiry(ttlSeconds), key, expected);
155
+ sweep();
156
+ return Promise.resolve(written.changes === 1);
157
+ }
158
+ };
159
+ };
160
+ export { createSqliteJobQueue, createSqliteKv };
@@ -0,0 +1,35 @@
1
+ import { JobQueue } from '../types';
2
+ import { DatabaseSync } from 'node:sqlite';
3
+ export type SqliteJobQueueOptions = ({
4
+ /** The database file — created, with its folder, when it is not there. Opened in WAL mode. */
5
+ file: string;
6
+ db?: never;
7
+ } | {
8
+ /** A database the deployment opened and shares with its own tables — its `kv` (`createSqliteKv`) among them. */
9
+ db: DatabaseSync;
10
+ file?: never;
11
+ }) & {
12
+ /** The table the queue lives in, created when it is not there. Default `action_jobs`. */
13
+ table?: string;
14
+ /** How many finished jobs to keep before the oldest are dropped. Default 500. */
15
+ retainFinished?: number;
16
+ /** What the queue calls now, in epoch ms: every process on the file reads the machine's clock. */
17
+ clock?: () => number;
18
+ };
19
+ /**
20
+ * The job queue in a SQLite file, over Node's own `node:sqlite`: what `ctx.later`, a schedule's fires and a function's
21
+ * jobs wait in, surviving a restart AND shared — every process on the file (replicas on one machine, a server started
22
+ * with `workers`) claims from the same queue, each job by one of them.
23
+ *
24
+ * ```ts
25
+ * import { createSqliteJobQueue, createSqliteKv } from '@plitzi/sdk-actions/sqlite';
26
+ *
27
+ * createServer({ action: { kv: createSqliteKv({ db }), jobs: { queue: createSqliteJobQueue({ db }) } } });
28
+ * ```
29
+ *
30
+ * The rules are the in-process queue's, to the letter (`queueRules`), run on the state as the table holds it, inside
31
+ * one `BEGIN IMMEDIATE` transaction a call: two processes never claim one job, nor write over each other's change. The
32
+ * state is one row, read whole each call — right for what a project's queue holds (its jobs waiting and the last
33
+ * `retainFinished` done); a deployment of thousands a minute keeps its queue in a database (`JobQueue`).
34
+ */
35
+ export declare const createSqliteJobQueue: (options: SqliteJobQueueOptions) => JobQueue;
@@ -0,0 +1,34 @@
1
+ import { ActionKvAdapter } from '../engine/types';
2
+ import { DatabaseSync } from 'node:sqlite';
3
+ export type SqliteKvOptions = ({
4
+ /** The database file — created, with its folder, when it is not there. Opened in WAL mode. */
5
+ file: string;
6
+ db?: never;
7
+ } | {
8
+ /** A database the deployment opened and shares with its own tables (a job queue, an activity log). */
9
+ db: DatabaseSync;
10
+ file?: never;
11
+ }) & {
12
+ /** The table the keys live in, created when it is not there. Default `action_kv`. */
13
+ table?: string;
14
+ };
15
+ /**
16
+ * A key/value store in a SQLite file, over Node's own `node:sqlite` — nothing to install, nothing to run beside the
17
+ * server. For a deployment with no database that wants what `kv` keeps to survive a restart AND to be shared: every
18
+ * process pointed at the same file — replicas on one machine, a server started with `workers` — sees the same keys,
19
+ * the same counters and the same single-flight keys.
20
+ *
21
+ * ```ts
22
+ * import { createSqliteKv } from '@plitzi/sdk-actions/sqlite';
23
+ *
24
+ * createServer({ action: { kv: createSqliteKv({ file: 'data/kv.sqlite' }) } });
25
+ * ```
26
+ *
27
+ * Every operation is ONE statement, so it is atomic without a transaction: an increment is an upsert that adds in
28
+ * place, a swap is an update whose `WHERE` names the value it expects. Lifetimes are instants on the store's clock,
29
+ * enforced on every read, and expired rows are swept as writes go by.
30
+ *
31
+ * Needs a Node with `node:sqlite` unflagged (22.13 and later), which still prints an `ExperimentalWarning` once when
32
+ * it loads — the reason this is its own entry rather than the default.
33
+ */
34
+ export declare const createSqliteKv: (options: SqliteKvOptions) => ActionKvAdapter;
@@ -0,0 +1,3 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ /** A SQLite file opened for the stores that share it — its folder made when it is not there. */
3
+ export declare const openDatabase: (file: string) => DatabaseSync;
@@ -0,0 +1,293 @@
1
+ import { JobClaimMemory, JobQueue, JobSpaces, JobWake } from './jobs';
2
+ import { SSRPageAdapters, ServerBaseConfig } from '@plitzi/sdk-kernel/types';
3
+ import { ActionEmailConfig, ActionLimits, ActionRejectRecord, ActionRunRecord, Environment, SSRRealtimeConfig, Schema, SpaceRevision } from '@plitzi/sdk-shared';
4
+ /** The actions engine's own configuration: its actions, its functions, its connectors and its realtime channels. */
5
+ export type EngineOptions = {
6
+ /** Write endpoint for server-driven providers. Absent means the server serves reads only. */
7
+ action?: SSRActionConfig;
8
+ /**
9
+ * The server's code: its own (`native`), the server halves of the plugins it ships (`plugins`, by plugin type), the
10
+ * runner the spaces' code runs on, and the ceilings. Built by `@plitzi/sdk-actions/functions` (`loadFunctions`), and
11
+ * checked as the server starts.
12
+ */
13
+ functions?: {
14
+ native?: unknown[];
15
+ /** Say an invocation of `native` that spends more than a sandbox would let it (sdk-server's `FunctionsConfig`). */
16
+ measureNative?: boolean;
17
+ plugins?: Record<string, unknown>;
18
+ runner?: unknown;
19
+ limits?: Record<string, number>;
20
+ /** What the spaces' jobs may spend, per space (its plan): see `FunctionJobLimits` in `@plitzi/sdk-actions/functions`. */
21
+ jobs?: {
22
+ limitsFor?: (spaceId: number) => Promise<Record<string, unknown> | undefined>;
23
+ };
24
+ /** `ctx.oauth`: where providers send a visitor back — see `FunctionsConfig` in `@plitzi/sdk-actions/functions`. */
25
+ oauth?: {
26
+ callbackOrigin?: string;
27
+ };
28
+ };
29
+ /** Realtime channels the spaces declare — see {@link SSRRealtimeConfig}. On, in memory, when absent. */
30
+ realtime?: SSRRealtimeConfig;
31
+ /** Connector manifest and credential lookups — see {@link ConnectorLookupsConfig}. They serve the RSC read path
32
+ * and the `/_action` write endpoint alike; without them neither can reach a connector. */
33
+ connectors?: ConnectorLookupsConfig;
34
+ };
35
+ /** The actions engine's configuration: the server's, and the engine's own. */
36
+ export type EngineConfig = ServerBaseConfig & EngineOptions;
37
+ /** The engine's configuration where it answers for a space's host: the adapters that read a space are required. */
38
+ export type EngineServerConfig = EngineConfig & {
39
+ adapters: SSRPageAdapters;
40
+ };
41
+ /**
42
+ * How the server reaches a space's actions, and what it may run.
43
+ *
44
+ * Typed loosely for the same reason `ConnectorLookupsConfig` is — the document is executed by
45
+ * `@plitzi/sdk-server`'s actions module and the shared types stay free of its internals. Shaped as `ActionLookups`
46
+ * there.
47
+ */
48
+ export type ActionLookupsConfig = {
49
+ getAction: (spaceId: number, actionId: string, at?: SpaceRevision) => Promise<unknown>;
50
+ listActions?: (spaceId: number, at?: SpaceRevision) => Promise<unknown[]>;
51
+ /** Which spaces have something scheduled — the periodic reconcile's safety net. See `ActionLookups`. */
52
+ listScheduledSpaces?: () => Promise<number[]>;
53
+ getCredential?: (spaceId: number, identifier: string) => Promise<Record<string, string> | undefined>;
54
+ getConnector?: (spaceId: number, connectorId: string, at?: SpaceRevision) => Promise<unknown>;
55
+ /** The space's own functions as of that revision — `SpaceFunctions` in `@plitzi/sdk-actions/functions`. */
56
+ getFunctions?: (spaceId: number, at?: SpaceRevision) => Promise<unknown>;
57
+ /** The server halves of the plugins the space uses, by plugin type — a `SpaceFunctions` each. */
58
+ getPluginFunctions?: (spaceId: number, at?: SpaceRevision) => Promise<unknown>;
59
+ /**
60
+ * The space's own data as of that revision — what a project keeps in `src/data/`, kept privately and frozen with each
61
+ * publish — as its files' text by path (`products.json`). A provider resolved on the server whose `query` is
62
+ * `/data/<file>` reads it, and a function's `ctx.data`; no browser is answered it. Given none, `dataDir` is read.
63
+ */
64
+ getData?: (spaceId: number, at?: SpaceRevision) => Promise<unknown>;
65
+ /** The feature flags the space declares as of that revision — what a flow reads as `{{ flags.<name> }}`. */
66
+ getFlags?: (spaceId: number, at?: SpaceRevision) => Promise<Schema['flags']>;
67
+ /**
68
+ * One person of the space by username or id — `{ id, username, name?, avatar? }`, only of someone who belongs to it
69
+ * (its visitors and members, as the deployment knows them): a function's `ctx.visitors.get`. Whatever else is
70
+ * answered is dropped before code sees it. Given none, a server with an `auth` answers its own accounts.
71
+ */
72
+ getVisitor?: (spaceId: number, environment: string, who: string | number) => Promise<unknown>;
73
+ };
74
+ export type SSRActionConfig = {
75
+ /** URL path for the write endpoint, and the base for the action-addressed routes. Defaults to '/_action'. */
76
+ path?: string;
77
+ /**
78
+ * The origin a page calls its actions on, when it is not the page's own — `https://actions.example.com`: what the
79
+ * pages are told is `origin` + `path`, and they call it with their cookies. Absent, a page calls its own origin, and a
80
+ * gateway sends the path to the worker (the recommended way: one origin, the session and CSRF unchanged).
81
+ *
82
+ * Set, the worker answers the pages of `pageOrigins` alone (CORS with credentials), and it must read the visitor's
83
+ * session: a cookie scoped to a parent domain both share (`authCookie.domain`). It resolves the space with its own
84
+ * `getSpaceDeployment`, which sees this origin's host. A page's `/fn/` routes and channels stay on its own origin.
85
+ */
86
+ origin?: string;
87
+ /**
88
+ * The origins whose pages call the actions on `origin`, exactly as a browser sends them — `https://www.example.com`.
89
+ * Its CORS answers them with credentials and its cross-site check takes them as its own; any other page is refused.
90
+ * Required with `origin`: a worker started without them refuses to start.
91
+ */
92
+ pageOrigins?: string[];
93
+ /**
94
+ * Supplying these is what turns server actions on: without a way to read a document there is nothing to run, and
95
+ * the endpoint keeps answering element-addressed connector writes alone.
96
+ */
97
+ lookups?: ActionLookupsConfig;
98
+ /**
99
+ * Ceilings for every run this server accepts. A space's plan (`limitsFor`) and a document may tighten them, never
100
+ * widen them.
101
+ */
102
+ limits?: ActionLimits;
103
+ /**
104
+ * What one run of that space's actions may spend — its plan's, each at most `limits`; an unset one is `limits`'. Read
105
+ * on every run, so a deployment caches what it answers. Absent, every space gets `limits`.
106
+ */
107
+ limitsFor?: (spaceId: number) => Promise<ActionLimits | undefined>;
108
+ /**
109
+ * Whether that space may start a run now — its plan's allowance of runs for the period not spent — or why not, asked
110
+ * before every run but a page's render (which its page view already pays for). A refusal is the run's, `quota`: a
111
+ * call answered 402, a job set aside. Absent, every run may start.
112
+ */
113
+ admitRun?: (spaceId: number) => Promise<string | undefined>;
114
+ /**
115
+ * Concurrency ceilings.
116
+ *
117
+ * `perSpace`/`perProcess` count CALLS — a click, a webhook, a schedule — where one run is somebody asking for
118
+ * work and one space's callers must not starve another's. A `render` is counted only by `renderPerProcess`,
119
+ * because it arrives because people are reading the page: a ceiling per space there would refuse the five
120
+ * hundredth visitor of a page that is simply doing well.
121
+ *
122
+ * `memoryShare` is the share of this process's memory limit (its container's, else V8's heap limit) past which it
123
+ * takes no new run, of either kind: 0.85 by default. A slot ceiling counts runs, not what they hold, and runs reading
124
+ * large answers can fill a process long before its slots — refusing the next one (`over_capacity`, with a retry) is
125
+ * what keeps the process alive for the runs already in it.
126
+ *
127
+ * `perSpace` is 10 by default and `perProcess` 100, plus the job workers of a process that runs jobs (`jobs.workers`):
128
+ * its jobs are calls too. A job worker claims only what these leave room for — never a job of a space at its ceiling.
129
+ */
130
+ concurrency?: {
131
+ perSpace?: number;
132
+ perProcess?: number;
133
+ renderPerProcess?: number;
134
+ memoryShare?: number;
135
+ };
136
+ /** Inbound webhooks are public by construction, so they are counted per caller per minute. Default 60. */
137
+ rateLimit?: {
138
+ webhookPerMinute?: number;
139
+ };
140
+ /**
141
+ * Database engines a flow may reach, shaped as `ActionDbDriver` in `@plitzi/sdk-actions`.
142
+ *
143
+ * Omitted leaves the `db.query` task unregistered entirely. What a driver connects to is always a database the
144
+ * SPACE declared as a credential — never this deployment's own, which no credential a space holds can name.
145
+ */
146
+ dbDrivers?: unknown[];
147
+ /**
148
+ * The limits on `email.send`, which sends through the SMTP credential a step names, and optionally how a message
149
+ * leaves. Omitted keeps the defaults: 200 messages per space per day, no SMTP host on a private network, and the
150
+ * server's own SMTP connection. See {@link ActionEmailConfig}.
151
+ */
152
+ email?: ActionEmailConfig;
153
+ /**
154
+ * Called once per run that STARTED — completed, failed or aborted — for a deployment that keeps a record.
155
+ * Shaped as `ActionRunRecord` in `@plitzi/sdk-actions`.
156
+ *
157
+ * A refused request is not a run and is not reported here; it goes to {@link SSRActionConfig.onReject}.
158
+ */
159
+ onRun?: (record: ActionRunRecord) => void | Promise<void>;
160
+ /**
161
+ * Called once per request that was REFUSED before it became a run — a webhook whose signature did not verify, a
162
+ * caller over the rate limit, an action nobody may start. Shaped as `ActionRejectRecord`.
163
+ *
164
+ * Its own hook because it answers a different question from `onRun`: runs are history, refusals are a fault
165
+ * report, and the one that matters most — a signature that does not match — is otherwise indistinguishable
166
+ * from the integration simply never firing. Everything is reported; which refusals are worth keeping (a
167
+ * duplicate delivery is a polite retry, not a fault) is the deployment's to decide.
168
+ */
169
+ onReject?: (record: ActionRejectRecord) => void | Promise<void>;
170
+ /**
171
+ * Replaying a finished run's answer to a caller that asks again with the same key, for this many milliseconds.
172
+ *
173
+ * Off unless set, and it only ever applies to a key the CALLER named — an `idempotencyKey` on the call or the
174
+ * delivery id a webhook sender stamps. Single-flight already refuses a retry that arrives while the first run
175
+ * is going; this is for the one that arrives after it finished, which is how every provider retries.
176
+ */
177
+ idempotency?: {
178
+ replayTtlMs?: number;
179
+ };
180
+ /**
181
+ * What each space's functions sign with (`ctx.sign` / `ctx.verify`): at least 32 characters, the same on every
182
+ * replica. Each space and environment signs with a key derived from it. Absent, spaces sign nothing.
183
+ */
184
+ signingSecret?: string;
185
+ /**
186
+ * Where the `kv` tasks keep things — shaped as `ActionKvAdapter` in `@plitzi/sdk-actions`.
187
+ *
188
+ * Six operations over strings, with no rule to obey: Redis, Memcached, a table, whatever this deployment
189
+ * already runs. How a counter BEHAVES — the key prefixing, the JSON round trip, and the rule that a window's
190
+ * lifetime is set once by whoever created it — belongs to the server, not to the thing it writes into.
191
+ *
192
+ * Omitted leaves an in-process Map, which counts only its own replica. That is fine for one; for a cluster it is
193
+ * a rate limit that multiplies by the number of them, so a multi-replica deployment supplies a shared one.
194
+ */
195
+ kv?: {
196
+ get: (key: string) => Promise<string | undefined>;
197
+ set: (key: string, value: string, ttlSeconds?: number) => Promise<void>;
198
+ delete: (key: string) => Promise<void>;
199
+ increment: (key: string, amount: number) => Promise<number>;
200
+ expire: (key: string, ttlSeconds: number) => Promise<void>;
201
+ /** Writes `next` only if the key holds `expected` (nothing, when undefined); answers whether it wrote. Atomic. */
202
+ swap: (key: string, expected: string | undefined, next: string, ttlSeconds?: number) => Promise<boolean>;
203
+ };
204
+ /**
205
+ * Scheduled runs: the durable queue they wait in, how many this replica runs at once, and whether it produces.
206
+ *
207
+ * On wherever `lookups.listActions` is answerable — a `schedule` trigger the editor offers is a trigger the
208
+ * server honours, which before this it only did if the deployment wrote a timer and a distributed lock of its
209
+ * own. With no `queue` it runs over this process's memory: right for one replica, and wrong for two, because
210
+ * each then keeps its own schedules and the nightly email goes out once per replica.
211
+ *
212
+ * `false` turns it off for a replica that must only serve pages.
213
+ */
214
+ jobs?: ActionJobsConfig | false;
215
+ };
216
+ /**
217
+ * How this deployment runs what a clock starts.
218
+ *
219
+ * Every default here is a safe one for a single machine; the two a cluster has to think about are `queue` — which
220
+ * must be shared, or the replicas do not see each other's work — and `workers`, which is how fast a backlog
221
+ * drains. Nothing in this config is a clock: the queue's own is the only one the scheduling path reads, so
222
+ * replicas in different countries agree about what has run without agreeing about what time it is.
223
+ */
224
+ export type ActionJobsConfig = {
225
+ /** Shaped as `JobQueue`. Omitted → this process's memory. */
226
+ queue?: JobQueue;
227
+ /** Jobs this replica runs at once. Default 4; `0` produces without consuming. */
228
+ workers?: number;
229
+ /** Whether this replica sweeps due schedules into the queue. Default true. */
230
+ produce?: boolean;
231
+ /** Whether a space may have scheduled runs — its plan, say: why not, or nothing. Absent, every space may. */
232
+ admitSchedules?: (spaceId: number) => Promise<string | undefined>;
233
+ /** The spaces this server schedules for, when it serves a known few — the self-hosted shape. */
234
+ spaces?: number[];
235
+ /** How often a free worker looks for a job. Default 1s. */
236
+ pollMs?: number;
237
+ /**
238
+ * How replicas tell each other a job is due now (`JobWake`): a worker then takes one as it is enqueued, not on its next
239
+ * look. Absent, every worker finds new jobs by looking, up to `pollMs` late.
240
+ */
241
+ wake?: JobWake;
242
+ /**
243
+ * Which spaces' jobs this replica takes, asked on every claim (`JobSpaces`): a worker kept for some spaces takes
244
+ * theirs alone, the others every space but those. Absent, every space's. Not `spaces`, which is what it schedules.
245
+ */
246
+ claims?: () => JobSpaces | undefined;
247
+ /**
248
+ * What this replica may hold, and the most any of the deployment's may (`JobClaimMemory`), asked on every claim: a
249
+ * job a worker died running then needs more than that one could, runs on a replica that may hold it, and is set aside
250
+ * (`paused`) when none may. Absent, a job whose worker died runs again on whichever claims it.
251
+ */
252
+ claimMemory?: () => JobClaimMemory | undefined;
253
+ /**
254
+ * Whose jobs this replica takes besides its own while it has more than one slot free (`JobSpaces`): a larger worker
255
+ * kept for the heavy jobs helps the others while it is idle, and keeps a slot for what only it may run.
256
+ */
257
+ helps?: () => JobSpaces | undefined;
258
+ /** How often this replica looks for due schedules. Default 15s. */
259
+ schedulePollMs?: number;
260
+ /** How long a claim is held before another replica may take the job over — the failover window. Default 30s. */
261
+ leaseMs?: number;
262
+ /** Attempts a job gets before it is left for an operator as `dead`. Default 3. */
263
+ maxAttempts?: number;
264
+ /** First retry delay, doubling per attempt, up to `maxMs`. Defaults to 30s and 15 minutes. */
265
+ backoff?: {
266
+ baseMs?: number;
267
+ maxMs?: number;
268
+ };
269
+ /** Which environment scheduled runs execute in. Default `main`. */
270
+ environment?: Environment;
271
+ /** How often schedules are re-derived from documents. Default 15 minutes. */
272
+ reconcileMs?: number;
273
+ /** Names this replica in the job history. Defaults to the pid and a random suffix. */
274
+ workerId?: string;
275
+ onError?: (error: unknown) => void;
276
+ };
277
+ /**
278
+ * How the server reaches a space's connectors: the manifest that describes one, and the credential it authenticates
279
+ * with. Shaped as `ConnectorLookups` in `@plitzi/sdk-server`; typed loosely here so the shared types stay free of the
280
+ * server's internals.
281
+ *
282
+ * Top-level, and not under `action`, because BOTH directions need them. Supplying them is what makes the write
283
+ * endpoint able to authorize a write — a write can only be checked against a manifest — and it is also all the server
284
+ * needs to answer a server-driven element's READ, so `adapters.getRscData` is derived from them unless a deployment
285
+ * supplies its own. They lived under `action` when writes were the only caller, which left every deployment building
286
+ * that read half by hand out of `createConnectorResolver` and `resolveRscData` — from these very lookups, passed a
287
+ * second time.
288
+ */
289
+ export type ConnectorLookupsConfig = {
290
+ getConnector: (spaceId: number, connectorId: string, at?: SpaceRevision) => Promise<unknown>;
291
+ getCredential?: (spaceId: number, identifier: string) => Promise<Record<string, string> | undefined>;
292
+ fetchImpl?: typeof fetch;
293
+ };
@@ -0,0 +1,2 @@
1
+ export type { ActionLookupsConfig, ConnectorLookupsConfig, EngineConfig, EngineOptions, EngineServerConfig, SSRActionConfig, ActionJobsConfig } from './config';
2
+ export type { ActionSchedule, ActionScheduleInput, JobClaimMemory, JobQuery, JobQueue, JobFlowMinute, JobQueueSummary, JobSettlement, JobsNeedingMemory, JobSpaces, JobStop, JobTake, JobWake, JobWrite, WaitingJobs } from './jobs';
@@ -0,0 +1 @@
1
+ export {};