@sanoma-ai/workflows 0.0.0-stage → 0.1.0

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 (148) hide show
  1. package/LICENSE +105 -0
  2. package/README.md +493 -2
  3. package/dist/approvals.d.ts +46 -0
  4. package/dist/approvals.js +111 -0
  5. package/dist/approvals.js.map +1 -0
  6. package/dist/ast.d.ts +57 -0
  7. package/dist/ast.js +81 -0
  8. package/dist/ast.js.map +1 -0
  9. package/dist/call.d.ts +33 -0
  10. package/dist/call.js +402 -0
  11. package/dist/call.js.map +1 -0
  12. package/dist/client.d.ts +167 -0
  13. package/dist/client.js +400 -0
  14. package/dist/client.js.map +1 -0
  15. package/dist/config.d.ts +126 -0
  16. package/dist/config.js +247 -0
  17. package/dist/config.js.map +1 -0
  18. package/dist/credentials.d.ts +30 -0
  19. package/dist/credentials.js +193 -0
  20. package/dist/credentials.js.map +1 -0
  21. package/dist/cucumber.d.ts +64 -0
  22. package/dist/cucumber.js +158 -0
  23. package/dist/cucumber.js.map +1 -0
  24. package/dist/datafile.d.ts +62 -0
  25. package/dist/datafile.js +326 -0
  26. package/dist/datafile.js.map +1 -0
  27. package/dist/db.d.ts +58 -0
  28. package/dist/db.js +179 -0
  29. package/dist/db.js.map +1 -0
  30. package/dist/define.d.ts +205 -0
  31. package/dist/define.js +103 -0
  32. package/dist/define.js.map +1 -0
  33. package/dist/describe.d.ts +135 -0
  34. package/dist/describe.js +127 -0
  35. package/dist/describe.js.map +1 -0
  36. package/dist/drift.d.ts +75 -0
  37. package/dist/drift.js +90 -0
  38. package/dist/drift.js.map +1 -0
  39. package/dist/env.d.ts +49 -0
  40. package/dist/env.js +83 -0
  41. package/dist/env.js.map +1 -0
  42. package/dist/errors.d.ts +88 -0
  43. package/dist/errors.js +148 -0
  44. package/dist/errors.js.map +1 -0
  45. package/dist/expectations.d.ts +26 -0
  46. package/dist/expectations.js +137 -0
  47. package/dist/expectations.js.map +1 -0
  48. package/dist/fake.d.ts +55 -0
  49. package/dist/fake.js +87 -0
  50. package/dist/fake.js.map +1 -0
  51. package/dist/fill.d.ts +9 -0
  52. package/dist/fill.js +17 -0
  53. package/dist/fill.js.map +1 -0
  54. package/dist/index.d.ts +19 -0
  55. package/dist/index.js +25 -0
  56. package/dist/index.js.map +1 -0
  57. package/dist/ledger.d.ts +217 -0
  58. package/dist/ledger.js +251 -0
  59. package/dist/ledger.js.map +1 -0
  60. package/dist/lint.d.ts +32 -0
  61. package/dist/lint.js +168 -0
  62. package/dist/lint.js.map +1 -0
  63. package/dist/log.d.ts +24 -0
  64. package/dist/log.js +83 -0
  65. package/dist/log.js.map +1 -0
  66. package/dist/op.d.ts +257 -0
  67. package/dist/op.js +188 -0
  68. package/dist/op.js.map +1 -0
  69. package/dist/outline.d.ts +179 -0
  70. package/dist/outline.js +506 -0
  71. package/dist/outline.js.map +1 -0
  72. package/dist/paths.d.ts +11 -0
  73. package/dist/paths.js +30 -0
  74. package/dist/paths.js.map +1 -0
  75. package/dist/plugin.d.ts +28 -0
  76. package/dist/plugin.js +25 -0
  77. package/dist/plugin.js.map +1 -0
  78. package/dist/policy.d.ts +114 -0
  79. package/dist/policy.js +60 -0
  80. package/dist/policy.js.map +1 -0
  81. package/dist/resource.d.ts +212 -0
  82. package/dist/resource.js +285 -0
  83. package/dist/resource.js.map +1 -0
  84. package/dist/resources.d.ts +62 -0
  85. package/dist/resources.js +197 -0
  86. package/dist/resources.js.map +1 -0
  87. package/dist/run.d.ts +87 -0
  88. package/dist/run.js +2 -0
  89. package/dist/run.js.map +1 -0
  90. package/dist/sandbox.d.ts +33 -0
  91. package/dist/sandbox.js +123 -0
  92. package/dist/sandbox.js.map +1 -0
  93. package/dist/scenario.d.ts +212 -0
  94. package/dist/scenario.js +1079 -0
  95. package/dist/scenario.js.map +1 -0
  96. package/dist/scenarios.d.ts +55 -0
  97. package/dist/scenarios.js +71 -0
  98. package/dist/scenarios.js.map +1 -0
  99. package/dist/shared.d.ts +61 -0
  100. package/dist/shared.js +77 -0
  101. package/dist/shared.js.map +1 -0
  102. package/dist/steps.d.ts +76 -0
  103. package/dist/steps.js +23 -0
  104. package/dist/steps.js.map +1 -0
  105. package/dist/version.d.ts +29 -0
  106. package/dist/version.js +76 -0
  107. package/dist/version.js.map +1 -0
  108. package/dist/worker.d.ts +34 -0
  109. package/dist/worker.js +219 -0
  110. package/dist/worker.js.map +1 -0
  111. package/oxlint.json +128 -0
  112. package/package.json +91 -3
  113. package/src/approvals.ts +157 -0
  114. package/src/ast.ts +115 -0
  115. package/src/call.ts +468 -0
  116. package/src/client.ts +534 -0
  117. package/src/config.ts +381 -0
  118. package/src/credentials.ts +211 -0
  119. package/src/cucumber.ts +230 -0
  120. package/src/datafile.ts +409 -0
  121. package/src/db.ts +197 -0
  122. package/src/define.ts +285 -0
  123. package/src/describe.ts +262 -0
  124. package/src/drift.ts +149 -0
  125. package/src/env.ts +122 -0
  126. package/src/errors.ts +202 -0
  127. package/src/expectations.ts +165 -0
  128. package/src/fake.ts +156 -0
  129. package/src/fill.ts +24 -0
  130. package/src/index.ts +120 -0
  131. package/src/ledger.ts +419 -0
  132. package/src/lint.ts +208 -0
  133. package/src/log.ts +82 -0
  134. package/src/op.ts +399 -0
  135. package/src/outline.ts +620 -0
  136. package/src/paths.ts +32 -0
  137. package/src/plugin.ts +37 -0
  138. package/src/policy.ts +139 -0
  139. package/src/resource.ts +447 -0
  140. package/src/resources.ts +256 -0
  141. package/src/run.ts +91 -0
  142. package/src/sandbox.ts +157 -0
  143. package/src/scenario.ts +1328 -0
  144. package/src/scenarios.ts +111 -0
  145. package/src/shared.ts +116 -0
  146. package/src/steps.ts +90 -0
  147. package/src/version.ts +86 -0
  148. package/src/worker.ts +253 -0
package/src/log.ts ADDED
@@ -0,0 +1,82 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import type { DLogger } from "@dbos-inc/dbos-sdk";
3
+
4
+ // DBOS's levels (winston's), most severe first. A message shows when its level is at or above the
5
+ // last `startWorker`'s `logLevel`, as DBOS's own do: `warn` by default. One threshold for the
6
+ // process, as DBOS's own logger is one per process.
7
+ const LEVELS = ["error", "warn", "info", "http", "verbose", "debug", "silly"];
8
+ const levelsUpTo = (level: string) => new Set(LEVELS.slice(0, LEVELS.indexOf(level) + 1));
9
+ let visible = levelsUpTo("warn");
10
+
11
+ /** Shows the messages at `level` and above from now on; an unknown level as `warn`. */
12
+ export function setLogLevel(level = "warn") {
13
+ visible = levelsUpTo(LEVELS.includes(level) ? level : "warn");
14
+ }
15
+
16
+ const shows = (level: string) => visible.has(level);
17
+
18
+ /** Tells the operator what the runtime did, such as loading credentials (never their values); shown at `info`. */
19
+ export const info = (message: string) => {
20
+ if (shows("info")) console.info(`sanoma: ${message}`);
21
+ };
22
+
23
+ /** Tells the operator something went wrong or was skipped, without failing anything; shown at `warn`. */
24
+ export const warn = (message: string) => {
25
+ if (shows("warn")) console.warn(`sanoma: ${message}`);
26
+ };
27
+
28
+ /** Set while a sandbox run's body runs. */
29
+ const sandboxRun = new AsyncLocalStorage<true>();
30
+ /** What sandbox runs failed with: each a copy made for its run (`quietIfSandbox`). */
31
+ const sandboxErrors = new WeakSet<object>();
32
+
33
+ /**
34
+ * Runs a workflow's body, as a sandbox run's when `sandbox`: `dbosLogger` then shows none of DBOS's
35
+ * warnings from inside it (its steps' failed tries among them), nor the error it fails with. A
36
+ * scenario's fakes fail on purpose; the run's ledger and its status say what happened. The run
37
+ * fails with a copy of its error (same prototype and properties), made for it, so the same error
38
+ * object thrown by a live run is still shown.
39
+ */
40
+ export function quietIfSandbox<T>(sandbox: boolean, body: () => Promise<T>): Promise<T> {
41
+ if (!sandbox) return body();
42
+ return sandboxRun.run(true, body).catch((err: unknown) => {
43
+ if (typeof err !== "object" || err === null) throw err;
44
+ const copy = Object.create(Object.getPrototypeOf(err), Object.getOwnPropertyDescriptors(err)) as object;
45
+ // V8's `stack` accessor reads the original's internal slot, which the copy lacks.
46
+ if ("stack" in err) Object.defineProperty(copy, "stack", { value: err.stack, writable: true, configurable: true });
47
+ sandboxErrors.add(copy);
48
+ throw copy;
49
+ });
50
+ }
51
+
52
+ /**
53
+ * DBOS's logger (`DBOS.setConfig`'s `logger`): its lines at the last `startWorker`'s `logLevel`,
54
+ * printed as DBOS's own console logger (`DBOSConsoleLogger`) prints them, except a sandbox run's
55
+ * (`quietIfSandbox`). A live run's failed tries and failure show as they always did. Installed
56
+ * only while DBOS exports no logs over OTLP: a custom logger replaces that transport.
57
+ */
58
+ export const dbosLogger: DLogger = {
59
+ info: (entry) => void (shows("info") && console.log(entry)),
60
+ debug: (entry) => void (shows("debug") && console.debug(entry)),
61
+ warn(entry) {
62
+ if (shows("warn") && !sandboxRun.getStore()) console.warn(entry);
63
+ },
64
+ // DBOS's GlobalLogger passes a string, with the stack in `metadata.stack` and an error in `metadata.error`.
65
+ error(entry, metadata) {
66
+ const error = metadata?.error;
67
+ if (!shows("error") || (typeof error === "object" && error !== null && sandboxErrors.has(error))) return;
68
+ if (metadata?.stack) console.error(entry, "\n", metadata.stack);
69
+ else console.error(entry);
70
+ },
71
+ };
72
+
73
+ /** A value as JSON, or as a string when it isn't JSON, cut to `max` characters, for a message. */
74
+ export function shown(value: unknown, max = Number.POSITIVE_INFINITY): string {
75
+ let text: string;
76
+ try {
77
+ text = JSON.stringify(value) ?? String(value);
78
+ } catch {
79
+ text = String(value);
80
+ }
81
+ return text.length > max ? `${text.slice(0, max)}…` : text;
82
+ }
package/src/op.ts ADDED
@@ -0,0 +1,399 @@
1
+ import type { z } from "zod";
2
+ import type { Fake } from "./fake.ts";
3
+ import type { Steps } from "./steps.ts";
4
+
5
+ /**
6
+ * What an operation does to the outside world. It sets the badge a reviewer
7
+ * sees and, later, the Cedar action the call is checked against.
8
+ */
9
+ export type Effect = "read" | "write" | "publish" | "send" | "money" | "access";
10
+
11
+ export interface OpSpec<I extends z.ZodType = z.ZodType, O extends z.ZodType = z.ZodType> {
12
+ effect: Effect;
13
+ input: I;
14
+ output: O;
15
+ /** Safe to retry: the vendor dedupes repeated calls. Otherwise a failed call stops the run. */
16
+ idempotent?: boolean;
17
+ description?: string;
18
+ /**
19
+ * The resource instance a call acts on, from its parsed input, such as a post's id. The
20
+ * policy sees it as `target`, so it can decide per instance. Must be deterministic.
21
+ *
22
+ * Its input is typed `any` inside `defineConnector`: TypeScript gives an inline function the
23
+ * type `Specs` declares, not the one its own spec's schema implies. Annotate it to have it
24
+ * checked: `target: ({ id }: { id: string }) => \`post/${id}\``.
25
+ */
26
+ target?: (input: any) => string;
27
+ /**
28
+ * How a scenario says this operation was set up or called, in Gherkin steps: `given` seeds
29
+ * the fake through it, `expect` expects a call to it. Cucumber expressions whose parameters are
30
+ * fields of the input, such as `{ given: "a post titled {title} exists" }`.
31
+ */
32
+ phrases?: { given?: string; expect?: string };
33
+ /**
34
+ * Top-level fields of its input and output that are the driver's own data, not the vendor's
35
+ * (a resource type's `handle`): the ledger records each as `"<name>"`, never its value.
36
+ */
37
+ opaque?: readonly string[];
38
+ }
39
+
40
+ /** One vendor operation, such as `ghost.post.publish`. Declares the contract only; drivers implement it. */
41
+ export interface Op<V extends string = string, R extends string = string, N extends string = string, I = any, O = any> {
42
+ readonly kind: "op";
43
+ readonly id: `${V}.${R}.${N}`;
44
+ readonly vendor: V;
45
+ readonly resource: R;
46
+ readonly name: N;
47
+ readonly effect: Effect;
48
+ readonly idempotent: boolean;
49
+ readonly description?: string;
50
+ /** From the spec: the resource instance a call acts on. */
51
+ readonly target?: (input: any) => string;
52
+ /** From the spec: how a scenario's steps name it. */
53
+ readonly phrases?: { readonly given?: string; readonly expect?: string };
54
+ /** From the spec: fields the ledger records by name only. */
55
+ readonly opaque?: readonly string[];
56
+ readonly input: z.ZodType<any, I>;
57
+ readonly output: z.ZodType<O>;
58
+ }
59
+
60
+ /**
61
+ * Where a resource type keeps its brand. A symbol, so `defineConnector` tells a resource type
62
+ * (`defineResource`) from a group of operations; a registered one (`Symbol.for`), so a copy of
63
+ * this package reads what another copy made, as `VENDOR`.
64
+ */
65
+ export const RESOURCE: unique symbol = Symbol.for("sanoma.resource");
66
+
67
+ /** What `defineConnector` reads of a resource type; `defineResource` makes them. */
68
+ export interface ResourceGroup {
69
+ readonly [RESOURCE]: true;
70
+ readonly vendor: string;
71
+ readonly type: string;
72
+ readonly ops: Readonly<Record<string, OpSpec>>;
73
+ }
74
+
75
+ /** A connector's groups: operations by name, or a resource type, whose operations are `read` and `import`. */
76
+ export type Specs = Record<string, Record<string, OpSpec> | ResourceGroup>;
77
+
78
+ /** The operations of one group of `Specs`. */
79
+ export type GroupOps<G> = G extends ResourceGroup ? G["ops"] : G;
80
+ type InputOf<T> = T extends OpSpec<infer I, any> ? I : never;
81
+ type OutputOf<T> = T extends OpSpec<any, infer O> ? O : never;
82
+
83
+ /**
84
+ * Where a connector keeps its vendor. A symbol, so it names no resource: `Object.values` and
85
+ * `keyof` over a connector see its resources only. A registered one (`Symbol.for`): a process
86
+ * may load two copies of this package (a connector's peer linked into a sanoma checkout, the
87
+ * app's from its tarball), and each must read the connectors the other made.
88
+ */
89
+ export const VENDOR: unique symbol = Symbol.for("sanoma.vendor");
90
+
91
+ export type Connector<V extends string, S extends Specs> = {
92
+ readonly [R in keyof S & string]: {
93
+ readonly [N in keyof GroupOps<S[R]> & string]: Op<
94
+ V,
95
+ R,
96
+ N,
97
+ z.input<InputOf<GroupOps<S[R]>[N]>>,
98
+ z.output<OutputOf<GroupOps<S[R]>[N]>>
99
+ >;
100
+ };
101
+ } & { readonly [VENDOR]: ConnectorVendor<V> };
102
+
103
+ /**
104
+ * The shape of a connector's `[VENDOR]` record. A process may load two builds of this package,
105
+ * and `resolveConfig` reads only a record of its own shape (`checkConnector`): change it with
106
+ * the record, so a build refuses a connector another build made in another shape.
107
+ */
108
+ export const CONNECTOR_FORMAT = 1;
109
+
110
+ /**
111
+ * A connector's vendor: its id, who it is (`defineConnector`'s third argument, for a UI), its
112
+ * resource types, and the driver and fake its package attaches (`withSetup`).
113
+ */
114
+ export interface ConnectorVendor<V extends string = string> {
115
+ /** The record's shape (`CONNECTOR_FORMAT`). */
116
+ readonly format: typeof CONNECTOR_FORMAT;
117
+ readonly id: V;
118
+ readonly info?: VendorInfo;
119
+ /** The resource types among its groups, in the order given. */
120
+ readonly resources: readonly ResourceGroup[];
121
+ /** What `withSetup` attached: how the config's resolver makes its driver and its fake. */
122
+ readonly setup?: ConnectorSetup;
123
+ }
124
+
125
+ /**
126
+ * Who a connector's vendor is, and where the connector lives, for a UI to show beside its
127
+ * operations. `logo` is the vendor's mark as inline SVG markup (one `<svg>…</svg>` element), and
128
+ * `dark` its variant for dark backgrounds. The app shows a logo only as an image (a `data:` URL
129
+ * in an `<img>`), where an SVG's scripts and external references never run or load.
130
+ */
131
+ export interface VendorInfo {
132
+ /** The vendor's name as it writes it, such as "Resend". */
133
+ title?: string;
134
+ logo?: { svg: string; dark?: string };
135
+ /** The connector's npm package name, such as "@sanoma-ai/connector-resend". */
136
+ package?: string;
137
+ /** The connector package's `homepage` from its package.json: where its code and README are, as an https URL. */
138
+ homepage?: string;
139
+ }
140
+
141
+ /** One `<svg>` element, with nothing but whitespace around it. */
142
+ const SVG_ELEMENT = /^\s*<svg[\s>][\s\S]*<\/svg>\s*$/;
143
+
144
+ const isResourceGroup = (group: unknown): group is ResourceGroup =>
145
+ (typeof group === "function" || typeof group === "object") &&
146
+ group !== null &&
147
+ (group as Partial<ResourceGroup>)[RESOURCE] === true;
148
+
149
+ /**
150
+ * Declares a vendor's operations, grouped by resource: `defineConnector("ghost", { post: { create: {...} } })`.
151
+ * A group may be a resource type from `defineResource`, under its own `type`, for its `read` and
152
+ * `import`: `defineConnector("github", { repository }, { package: "@sanoma-ai/connector-github" })`;
153
+ * it must be of the same vendor, and the connector needs `info.package`, whose `/resources`
154
+ * entry exports the types for data files.
155
+ * `info` says who the vendor is and where the connector lives, for a UI:
156
+ * `{ title: "Resend", logo: { svg }, package: "@sanoma-ai/connector-resend", homepage: "https://…" }`.
157
+ */
158
+ export function defineConnector<const V extends string, const S extends Specs>(
159
+ vendor: V,
160
+ specs: S,
161
+ info?: VendorInfo,
162
+ ): Connector<V, S> {
163
+ // A copy, frozen once checked: changing the caller's object later cannot slip a logo past the check.
164
+ const logo =
165
+ info?.logo && Object.freeze(Object.fromEntries(Object.entries(info.logo).filter(([, v]) => v !== undefined)));
166
+ for (const [variant, svg] of Object.entries(logo ?? {})) {
167
+ if (typeof svg !== "string" || !SVG_ELEMENT.test(svg)) {
168
+ throw new Error(
169
+ `defineConnector("${vendor}"): logo.${variant} must be inline SVG markup, one <svg>…</svg> element`,
170
+ );
171
+ }
172
+ }
173
+ const vendorInfo = info && Object.freeze({ ...info, ...(logo && { logo: logo as VendorInfo["logo"] }) });
174
+ // It becomes a link's href: a whole https URL, so never a `javascript:` one. Checked on the copy kept.
175
+ const homepage: unknown = vendorInfo?.homepage;
176
+ if (homepage !== undefined && (typeof homepage !== "string" || URL.parse(homepage)?.protocol !== "https:"))
177
+ throw new Error(`defineConnector("${vendor}"): homepage must be an https URL`);
178
+ const out: Record<string, Record<string, Op>> = {};
179
+ const resources: ResourceGroup[] = [];
180
+ for (const [resource, group] of Object.entries(specs)) {
181
+ let ops: Readonly<Record<string, OpSpec>> = group as Record<string, OpSpec>;
182
+ if (isResourceGroup(group)) {
183
+ if (group.vendor !== vendor) {
184
+ throw new Error(`defineConnector("${vendor}"): ${resource} is a resource type of ${group.vendor}`);
185
+ }
186
+ if (group.type !== resource) {
187
+ throw new Error(`defineConnector("${vendor}"): the resource type ${group.type} is given as ${resource}`);
188
+ }
189
+ resources.push(group);
190
+ ops = group.ops;
191
+ }
192
+ out[resource] = {};
193
+ for (const [name, spec] of Object.entries(ops)) {
194
+ out[resource][name] = Object.freeze({
195
+ kind: "op",
196
+ id: `${vendor}.${resource}.${name}`,
197
+ vendor,
198
+ resource,
199
+ name,
200
+ effect: spec.effect,
201
+ idempotent: spec.idempotent ?? false,
202
+ description: spec.description,
203
+ target: spec.target,
204
+ phrases: spec.phrases,
205
+ ...(spec.opaque?.length ? { opaque: spec.opaque } : {}),
206
+ input: spec.input,
207
+ output: spec.output,
208
+ } satisfies Op);
209
+ }
210
+ }
211
+ // A data file imports the resource types from `<package>/resources`, which the reader matches exactly.
212
+ if (resources.length && !vendorInfo?.package) {
213
+ throw new Error(
214
+ `defineConnector("${vendor}"): a connector with resource types needs info.package, the npm package data files import them from (\`<package>/resources\`)`,
215
+ );
216
+ }
217
+ const owner: ConnectorVendor<V> = Object.freeze({
218
+ format: CONNECTOR_FORMAT,
219
+ id: vendor,
220
+ info: vendorInfo,
221
+ resources: Object.freeze(resources),
222
+ });
223
+ return { ...out, [VENDOR]: owner } as unknown as Connector<V, S>;
224
+ }
225
+
226
+ /**
227
+ * What the runtime tells a driver about the call it is making. `idempotencyKey` is the same
228
+ * on every replay and retry of one call (`<runId>:<seq>`), so a driver can hand it to the
229
+ * vendor, or dedupe on it, and a crash between the vendor's reply and the checkpoint does
230
+ * not repeat the side effect.
231
+ */
232
+ export interface CallContext {
233
+ idempotencyKey: string;
234
+ runId: string;
235
+ opId: string;
236
+ /** 1 on the first try; retries count up (idempotent operations only). */
237
+ attempt: number;
238
+ }
239
+
240
+ export type DriverFn<I = any, O = unknown> = (input: I, call: CallContext) => Promise<O>;
241
+
242
+ /**
243
+ * A vendor's answer that the driver understood. `retryable` tells the runtime whether to try
244
+ * again (an idempotent operation on a timeout or a 5xx) or to stop (a 4xx). `status` and
245
+ * `vendorCode` keep what the vendor said, so the ledger and the UI can show it.
246
+ */
247
+ export class DriverError extends Error {
248
+ readonly code = "driver_failed" as const;
249
+ readonly retryable: boolean;
250
+ readonly status?: number;
251
+ readonly vendorCode?: string;
252
+
253
+ constructor(message: string, options: { retryable: boolean; status?: number; vendorCode?: string; cause?: unknown }) {
254
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
255
+ this.name = "DriverError";
256
+ this.retryable = options.retryable;
257
+ if (options.status !== undefined) this.status = options.status;
258
+ if (options.vendorCode !== undefined) this.vendorCode = options.vendorCode;
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Whether a vendor's HTTP status is worth retrying: a request timeout (408), a rate limit (429)
264
+ * or a server error (5xx). It is the runtime's default rule; a driver adds its vendor's
265
+ * exceptions around it, such as a quota that does not lift in the seconds a retry waits.
266
+ */
267
+ export function retryableStatus(status: number): boolean {
268
+ return status === 408 || status === 429 || status >= 500;
269
+ }
270
+
271
+ /**
272
+ * The environment variables a driver reads, as a Zod object of string schemas keyed by variable
273
+ * name, such as `z.object({ ACME_API_KEY: z.string().describe("an API key, from Settings, API keys") })`:
274
+ * each `.describe()` is the variable's one-line manual (what to put there, where to get it),
275
+ * `.optional()` marks one that may be unset. `resolveConfig` checks it against `process.env` and
276
+ * never keeps a value. The driver still reads the raw environment when it is called, so a
277
+ * `.default()` or `.transform()` is not applied to what it reads (use `.optional()` and name the
278
+ * default in `.describe()`), and a `.refine()` or `.superRefine()` on the object is not evaluated,
279
+ * only its fields.
280
+ */
281
+ export type DriverEnv = z.ZodObject<Record<string, z.ZodType<string | undefined, string | undefined>>>;
282
+
283
+ /**
284
+ * Implements a vendor's operations, keyed `"resource.name"`. A driver reads its credentials
285
+ * from the environment when it is called, never from the config file; `env` declares them.
286
+ */
287
+ export interface Driver {
288
+ readonly vendor: string;
289
+ readonly ops: Readonly<Record<string, DriverFn>>;
290
+ readonly env?: DriverEnv;
291
+ }
292
+
293
+ /**
294
+ * What a connector package attaches to its connector (`withSetup`), for the config's resolver
295
+ * to call: the config then names the connector alone, and never a driver, a fake or steps. Any may
296
+ * be missing: a workflow using an operation of a connector with no driver is refused, and a
297
+ * connector with no fake has none for sandbox runs.
298
+ */
299
+ export interface ConnectorSetup {
300
+ /** Makes the live driver, which reads its credentials from the environment when called: once per resolved config. */
301
+ driver?: () => Driver;
302
+ /** Makes a fake of the vendor (`defineFake`): once per sandbox run, its own. */
303
+ fake?: () => Fake<any, any>;
304
+ /** The connector's steps for Gherkin tests (`defineSteps`): a config's scenarios and the connector's own features can use them. */
305
+ steps?: Steps;
306
+ }
307
+
308
+ /**
309
+ * The connector with `setup` laid over what it already carries, as a connector package exports
310
+ * it: `export const ghost = withSetup(ghostOps, { driver: ghostDriver, fake: fakeGhost, steps: ghostSteps })`. A
311
+ * config that needs a driver made otherwise (another bridge, other options) swaps that one and
312
+ * keeps the fake: `withSetup(github, { driver: () => githubDriver({ bridge }) })`. The operations
313
+ * are the same objects, and the type is the connector's. The setup is kept on the connector's
314
+ * vendor record (`[VENDOR]`), so a spread copy of the connector keeps it.
315
+ */
316
+ export function withSetup<C extends Connector<any, any>>(connector: C, setup: Partial<ConnectorSetup>): C {
317
+ const owner = connector[VENDOR];
318
+ return {
319
+ ...connector,
320
+ [VENDOR]: Object.freeze({ ...owner, setup: Object.freeze({ ...owner.setup, ...setup }) }),
321
+ };
322
+ }
323
+
324
+ /**
325
+ * Throws unless `value` is a connector this package can read: one `defineConnector` made, in this
326
+ * copy of the package or another of the same `CONNECTOR_FORMAT`. One an older build made (its
327
+ * `VENDOR` an unregistered symbol, or its record without a format) is refused as such.
328
+ */
329
+ export function checkConnector(value: unknown): asserts value is Connector<any, any> {
330
+ const record =
331
+ typeof value === "object" && value !== null ? (value as Partial<Connector<any, any>>)[VENDOR] : undefined;
332
+ if (record?.format === CONNECTOR_FORMAT) return;
333
+ const build = "install the sanoma packages and connectors from one build";
334
+ throw new Error(
335
+ record === undefined
336
+ ? `\`connectors\` holds something that is not a connector: list what the connector packages export (or one from an older build: ${build})`
337
+ : `The "${String(record.id)}" connector was made by another build of @sanoma-ai/workflows: ${build}`,
338
+ );
339
+ }
340
+
341
+ /** What `withSetup` attached to a connector: nothing when it attached nothing. */
342
+ export const setupOf = (connector: Connector<any, any>): ConnectorSetup => connector[VENDOR].setup ?? {};
343
+
344
+ export function isOp(x: unknown): x is Op {
345
+ return typeof x === "object" && x !== null && (x as Op).kind === "op";
346
+ }
347
+
348
+ /**
349
+ * What a driver for a connector must implement: every operation, by resource and name. Each
350
+ * function gets the input as the operation's schema parses it and returns what its output
351
+ * schema accepts.
352
+ */
353
+ export type DriverImpl<S extends Specs> = {
354
+ [R in keyof S & string]: {
355
+ [N in keyof GroupOps<S[R]> & string]: DriverFn<
356
+ z.output<InputOf<GroupOps<S[R]>[N]>>,
357
+ z.input<OutputOf<GroupOps<S[R]>[N]>>
358
+ >;
359
+ };
360
+ };
361
+
362
+ /** The ids of a connector's operations, such as `"ghost.post.create" | "ghost.post.publish"`. */
363
+ export type OpIdOf<V extends string, S extends Specs> = {
364
+ [R in keyof S & string]: { [N in keyof GroupOps<S[R]> & string]: `${V}.${R}.${N}` }[keyof GroupOps<S[R]> & string];
365
+ }[keyof S & string];
366
+
367
+ /**
368
+ * Implements a connector's operations, typed by its schemas. A driver must be complete: an
369
+ * operation the connector declares that `impl` leaves out, or one `impl` adds that the
370
+ * connector doesn't declare, is refused here rather than when a run calls it. `options.env`
371
+ * declares the environment variables it reads (see `DriverEnv`).
372
+ */
373
+ export function defineDriver<V extends string, S extends Specs>(
374
+ connector: Connector<V, S>,
375
+ impl: DriverImpl<S>,
376
+ options: { env?: DriverEnv } = {},
377
+ ): Driver {
378
+ const declared = new Map<string, Op>();
379
+ for (const resource of Object.values(connector as Record<string, Record<string, unknown>>)) {
380
+ for (const op of Object.values(resource)) if (isOp(op)) declared.set(`${op.resource}.${op.name}`, op);
381
+ }
382
+ const vendor = connector[VENDOR].id;
383
+ const ops: Record<string, DriverFn> = {};
384
+ const extra: string[] = [];
385
+ for (const [resource, fns] of Object.entries(impl as Record<string, Record<string, unknown>>)) {
386
+ for (const [name, fn] of Object.entries(fns ?? {})) {
387
+ const key = `${resource}.${name}`;
388
+ if (!declared.has(key)) extra.push(`${vendor}.${key}`);
389
+ else if (typeof fn === "function") ops[key] = fn as DriverFn;
390
+ }
391
+ }
392
+ const missing = [...declared.keys()].filter((key) => !Object.hasOwn(ops, key)).map((key) => `${vendor}.${key}`);
393
+ const problems = [
394
+ ...(missing.length ? [`it does not implement ${missing.join(", ")}`] : []),
395
+ ...(extra.length ? [`it implements ${extra.join(", ")}, which the connector does not declare`] : []),
396
+ ];
397
+ if (problems.length) throw new Error(`defineDriver("${vendor}"): ${problems.join("; ")}`);
398
+ return Object.freeze({ vendor, ops: Object.freeze(ops), ...(options.env && { env: options.env }) });
399
+ }