@engini/sdk 0.19.0 → 0.20.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.
@@ -0,0 +1,355 @@
1
+ import { type TriggerDestinationCreated, type TriggerDestinationStatusDto, type TriggerDestinationView, type TriggerEventDetailView, type TriggerEventView, type TriggerInstanceView, type TriggerScheduleDto, type TriggerTypeDetailDto, type TriggerTypeDto } from "@engini/client";
2
+ import { type Transport } from "../http.js";
3
+ /** Minimal client surface this resource needs (satisfied by `Engini`). */
4
+ export interface TriggersClient {
5
+ _transport: Transport;
6
+ }
7
+ /**
8
+ * The reconnect backoff, behind an indirection so tests can collapse it.
9
+ *
10
+ * Spying on the global timer instead would also collapse undici's own connection
11
+ * timeouts, which then fire against a torn-down parser. Python's tests monkeypatch
12
+ * `time.sleep` for exactly the same reason. Not public surface — `index.ts` does not
13
+ * re-export it.
14
+ */
15
+ export declare const backoffTimer: {
16
+ sleep: (ms: number) => Promise<void>;
17
+ };
18
+ /**
19
+ * The body Engini POSTs to a destination, as returned by `verifyWebhook`.
20
+ *
21
+ * Deliberately **not** `TriggerEventView`: the delivery body carries `trigger_slug` and
22
+ * `attempt`, which the SSE frame does not, and omits `delivery`, which the SSE frame
23
+ * always reports as `"pending"` anyway.
24
+ *
25
+ * Every member is optional because `verifyWebhook` authenticates the body but does not
26
+ * schema-check it — it returns what was delivered. Marking fields required would be a
27
+ * promise this SDK cannot keep, and would have callers treat a missing one as present.
28
+ * The generated view types are optional for the same reason.
29
+ */
30
+ export interface TriggerWebhookEvent {
31
+ id?: string;
32
+ trigger_id?: string;
33
+ trigger_slug?: string | null;
34
+ occurred_at?: string;
35
+ attempt?: number;
36
+ payload_truncated?: boolean;
37
+ payload_hash?: string;
38
+ payload?: unknown;
39
+ }
40
+ /**
41
+ * Verify a delivered trigger webhook and return its parsed event.
42
+ *
43
+ * Module-level on purpose: the process receiving webhooks is usually a bare HTTP
44
+ * handler with no Engini client, and requiring one to check a signature would be the
45
+ * wrong dependency.
46
+ *
47
+ * @param payload The **raw** request body, exactly as received. A body that was
48
+ * JSON-parsed and re-serialised will not verify — the signature covers the bytes on
49
+ * the wire, not an equivalent document.
50
+ * @param signatureHeader The `X-Engini-Signature` header value, `t=<unix>,v1=<lowercase hex>`.
51
+ * @param secret The destination's signing secret, the whole `esec_…` string.
52
+ * @param options.tolerance Replay window in seconds either side of `t`. Defaults to the
53
+ * server's recommended 300.
54
+ * @returns The parsed event body — so verifying and reading it is one call, not two.
55
+ * @throws EnginiWebhookSignatureError On *any* rejection: absent or malformed header,
56
+ * unknown scheme version, bad signature, or a timestamp outside the tolerance. It
57
+ * throws rather than returning `false` because a boolean is silently ignorable, and
58
+ * an ignored signature check is the one failure mode a webhook receiver cannot afford.
59
+ *
60
+ * Every delivery attempt is signed afresh, so a retry of the same event carries a
61
+ * different `t` and signature. Deduplicate on the `X-Engini-Event-Id` header, never on
62
+ * the signature.
63
+ */
64
+ export declare function verifyWebhook(payload: string | Uint8Array, signatureHeader: string | null | undefined, secret: string, options?: {
65
+ tolerance?: number;
66
+ }): TriggerWebhookEvent;
67
+ /** The catalog of what can be triggered. Accessed as `client.triggers.types`. */
68
+ declare class TriggerTypesResource {
69
+ private readonly client;
70
+ constructor(client: TriggersClient);
71
+ /**
72
+ * Every trigger type visible to the account, paginated.
73
+ *
74
+ * `connectionId` narrows the catalog to the types that connection can actually serve.
75
+ */
76
+ list(params?: {
77
+ applicationSlug?: string;
78
+ search?: string;
79
+ connectionId?: number;
80
+ }): Promise<TriggerTypeDto[]>;
81
+ /**
82
+ * One trigger type, with its `config_schema`, `payload_schema` and parameters.
83
+ *
84
+ * `parameters` says which knobs this type actually honours — whether it schedules,
85
+ * whether it takes listen columns, which event types it offers — so read it before
86
+ * building a `create` call rather than sending fields the type will reject.
87
+ */
88
+ get(triggerSlug: string, params?: {
89
+ applicationSlug?: string;
90
+ }): Promise<TriggerTypeDetailDto>;
91
+ }
92
+ /** Captured events and their delivery history. Accessed as `client.triggers.events`. */
93
+ declare class TriggerEventsResource {
94
+ private readonly client;
95
+ constructor(client: TriggersClient);
96
+ /**
97
+ * Every captured event for one trigger, newest first.
98
+ *
99
+ * With no `top`, drains the whole log, 100 events per page. Pass `top` to fetch a
100
+ * single bounded page instead — unlike `TriggersResource.list`'s `include: "workflow"`
101
+ * workaround, this endpoint's `top`/`offset` are not affected by server bug
102
+ * 13003703309, so one page of exactly `top` rows is a real cap, not a client-side
103
+ * slice of a fully-drained result (which would fetch everything just to throw most of
104
+ * it away).
105
+ */
106
+ list(triggerId: string, params?: {
107
+ top?: number;
108
+ }): Promise<TriggerEventView[]>;
109
+ /**
110
+ * One event plus its delivery attempts.
111
+ *
112
+ * The result is **nested** — `.event` and `.attempts` — not a flat event. This is
113
+ * also the only place a real delivery state can be read: the `delivery` field on a
114
+ * streamed event always reads `"pending"`.
115
+ */
116
+ get(eventId: string): Promise<TriggerEventDetailView>;
117
+ /**
118
+ * Re-deliver a captured event to its destination.
119
+ *
120
+ * Throws `EnginiConflictError` with `errorCode === "DESTINATION_DISABLED"` when the
121
+ * destination was auto-disabled by consecutive failures; re-enable it with
122
+ * `destinations.update(name, { status: "active" })` first.
123
+ */
124
+ replay(eventId: string): Promise<TriggerEventDetailView>;
125
+ }
126
+ /**
127
+ * Registered HTTPS delivery endpoints. Accessed as `client.triggers.destinations`.
128
+ *
129
+ * Distinct from `client.triggers.destination` (singular), which is the account default
130
+ * and a different pair of endpoints. Nested rather than flattened precisely so the two
131
+ * cannot be confused.
132
+ */
133
+ declare class TriggerDestinationsResource {
134
+ private readonly client;
135
+ constructor(client: TriggersClient);
136
+ /** Every destination on the account, the default first. Never includes secrets. */
137
+ list(): Promise<TriggerDestinationView[]>;
138
+ /** One destination by name, including its failure counters and status. */
139
+ get(name: string): Promise<TriggerDestinationView>;
140
+ /**
141
+ * Register a destination. **The response carries its signing secret.**
142
+ *
143
+ * The result is nested: `.destination` and `.signing_secret`. That secret is shown
144
+ * exactly once, with no overlap window — store it now and never log it. It is the key
145
+ * `verifyWebhook` needs.
146
+ */
147
+ create(params: {
148
+ name: string;
149
+ url: string;
150
+ isDefault?: boolean;
151
+ maxConsecutiveFailures?: number;
152
+ }): Promise<TriggerDestinationCreated>;
153
+ /**
154
+ * Change a destination's URL, default flag, status or failure budget.
155
+ *
156
+ * `status: "active"` is how an `"auto_disabled"` destination is brought back after it
157
+ * tripped its consecutive-failure budget.
158
+ */
159
+ update(name: string, params: {
160
+ url?: string;
161
+ isDefault?: boolean;
162
+ status?: TriggerDestinationStatusDto;
163
+ maxConsecutiveFailures?: number;
164
+ }): Promise<TriggerDestinationView>;
165
+ /**
166
+ * Delete a destination, optionally re-pointing its triggers at another.
167
+ *
168
+ * Without `reassignTo` a destination that triggers still reference is a 409
169
+ * `DESTINATION_IN_USE` rather than a silent orphaning.
170
+ *
171
+ * The query parameter really is `reassign_to`, snake_case — unlike every other query
172
+ * parameter on this surface.
173
+ */
174
+ delete(name: string, params?: {
175
+ reassignTo?: string;
176
+ }): Promise<void>;
177
+ /**
178
+ * Issue a new signing secret, invalidating the current one immediately.
179
+ *
180
+ * **There is no overlap window**: deliveries signed with the old secret stop verifying
181
+ * the moment this resolves, so deploy the new secret to the receiver first. Returns
182
+ * the same nested `.destination` / `.signing_secret` shape as `create`.
183
+ */
184
+ rotateSecret(name: string): Promise<TriggerDestinationCreated>;
185
+ }
186
+ /**
187
+ * The account's default destination. Accessed as `client.triggers.destination`.
188
+ *
189
+ * `/v1/triggers/destination` (singular) and `/v1/triggers/destinations` (plural) are
190
+ * different endpoints; these two methods are the singular pair.
191
+ */
192
+ declare class DefaultDestinationResource {
193
+ private readonly client;
194
+ constructor(client: TriggersClient);
195
+ /** The account's default destination, or a 404 when none is set. */
196
+ get(): Promise<TriggerDestinationView>;
197
+ /**
198
+ * Set (or re-point) the account default in one call.
199
+ *
200
+ * Creating a default returns the nested `.destination` / `.signing_secret` shape,
201
+ * secret included and shown once; re-pointing an existing one returns the destination
202
+ * alone, with no secret. Check for the secret rather than assuming which happened.
203
+ */
204
+ put(params: {
205
+ url: string;
206
+ name?: string;
207
+ maxConsecutiveFailures?: number;
208
+ }): Promise<TriggerDestinationCreated | TriggerDestinationView>;
209
+ }
210
+ /** The fields every trigger write accepts. Each is independently optional. */
211
+ interface TriggerWriteParams {
212
+ connectionId?: number;
213
+ connectionName?: string;
214
+ config?: unknown;
215
+ schedule?: TriggerScheduleDto;
216
+ pollIntervalMinutes?: number;
217
+ listenColumns?: string[];
218
+ destinationId?: number;
219
+ dedupeWindowHours?: number;
220
+ }
221
+ export declare class TriggersResource {
222
+ private readonly client;
223
+ readonly types: TriggerTypesResource;
224
+ readonly events: TriggerEventsResource;
225
+ readonly destinations: TriggerDestinationsResource;
226
+ readonly destination: DefaultDestinationResource;
227
+ constructor(client: TriggersClient);
228
+ /**
229
+ * Also reachable as `client.triggers.verifyWebhook`, for callers that happen to have
230
+ * a client to hand. The module-level export is the real one.
231
+ */
232
+ readonly verifyWebhook: typeof verifyWebhook;
233
+ /**
234
+ * Create a trigger instance from a trigger type.
235
+ *
236
+ * Pass `connectionId` or `connectionName`; with neither, the server uses the account's
237
+ * default connection for the application and answers `MISSING_DEFAULT_CONNECTION`
238
+ * (500) when there is none.
239
+ *
240
+ * Which of `schedule` / `pollIntervalMinutes` / `listenColumns` apply is per trigger
241
+ * type — read `types.get(slug).parameters` first.
242
+ */
243
+ create(params: {
244
+ triggerSlug: string;
245
+ applicationSlug?: string;
246
+ } & TriggerWriteParams): Promise<TriggerInstanceView>;
247
+ /**
248
+ * Every trigger instance on the account, paginated.
249
+ *
250
+ * `status` is one of `enabled`, `disabled` or `errored`.
251
+ *
252
+ * `include: "workflow"` additionally returns designer-built triggers — and **returns a
253
+ * single page of at most `top` rows instead of paginating.** That is a WORKAROUND for
254
+ * server bug 13003703309, not the contract: the server appends designer triggers with
255
+ * `Take(top)` and no `Skip(offset)`, so page 2 re-returns page 1's rows while
256
+ * `totalCount` keeps climbing — auto-pagination would duplicate rows and never
257
+ * terminate. When 13003703309 lands, delete this branch and let every call paginate.
258
+ */
259
+ list(params?: {
260
+ applicationSlug?: string;
261
+ connectionId?: number;
262
+ status?: string;
263
+ include?: string;
264
+ top?: number;
265
+ }): Promise<TriggerInstanceView[]>;
266
+ /** One trigger instance, with its status, schedule and last-error detail. */
267
+ get(triggerId: string): Promise<TriggerInstanceView>;
268
+ /**
269
+ * Change a trigger's connection, config, schedule or destination.
270
+ *
271
+ * Merges: anything omitted is left alone. `trigger_slug` is not changeable — the type
272
+ * a trigger was created from is fixed.
273
+ */
274
+ update(triggerId: string, params: TriggerWriteParams): Promise<TriggerInstanceView>;
275
+ /**
276
+ * Enable a trigger and clear its `status_reason`.
277
+ *
278
+ * Throws `EnginiTriggerSubscribeFailedError` (502) when Engini could not register the
279
+ * subscription with the provider — the trigger stays disabled.
280
+ */
281
+ enable(triggerId: string): Promise<TriggerInstanceView>;
282
+ /** Stop a trigger capturing events. Not a delete; its event history stays. */
283
+ disable(triggerId: string): Promise<TriggerInstanceView>;
284
+ /** Permanently delete a trigger instance and its hidden system workflow. */
285
+ delete(triggerId: string): Promise<void>;
286
+ /**
287
+ * Open the SSE response, throwing the mapped typed error on a non-2xx.
288
+ *
289
+ * Written by hand rather than through the generated op: hey-api emitted
290
+ * `triggersSubscribeTriggerEvents` as a plain `.get()` typed `unknown`, because the
291
+ * OpenAPI document declares no `content` block on this 200 at all. Its `.sse()` reader
292
+ * exists but is unreachable until the spec gains `text/event-stream`.
293
+ */
294
+ private openStream;
295
+ /**
296
+ * Yield `["event", …]` / `["control", …]` frames until the stream ends.
297
+ *
298
+ * Returning normally means the socket ended without a control frame. That is the
299
+ * *expected* case, not an error: the gateway caps every stream at exactly one hour of
300
+ * wall-clock time and the response headers were flushed at connect, so nothing can be
301
+ * written at the deadline — the body is simply truncated. It is indistinguishable from
302
+ * a network blip by design, and handled the same way.
303
+ */
304
+ private streamOnce;
305
+ /**
306
+ * Stream trigger events as they are captured, as an async iterator.
307
+ *
308
+ * This is a **second read path for local development**, not a delivery mechanism —
309
+ * production delivery is a destination plus `verifyWebhook`.
310
+ *
311
+ * Every stream ends, so this one resumes. The gateway caps each connection at exactly
312
+ * one hour of wall-clock time — an absolute cap, not an idle one, which the 20-second
313
+ * heartbeat does not defer — and the cut arrives as an abrupt truncation with no
314
+ * control frame. A pod draining sends `control{reason:"draining", reconnect:true}`
315
+ * instead. All three of those are the same thing here: reconnect with `?since=<last
316
+ * event id>`, which streams events strictly *after* that one, so the seam neither
317
+ * duplicates nor skips.
318
+ *
319
+ * Two endings are not resumable and stop hard:
320
+ *
321
+ * - `control{reason:"revoked", reconnect:false}` → `EnginiAuthError`.
322
+ * - `410 SINCE_PRUNED` on the resume → `EnginiTriggerGapError`. Never a silent restart
323
+ * from "now": the point of the cursor is that a gap is visible. Read the missed
324
+ * window with `events.list` and subscribe again.
325
+ *
326
+ * A `429 TRIGGER_STREAM_LIMIT_EXCEEDED` waits out its `Retry-After` (the server sends
327
+ * 30s) and resumes; the account allows 10 concurrent streams.
328
+ *
329
+ * Each yielded event is the parsed frame: `id`, `trigger_id`, `occurred_at`, `payload`,
330
+ * `payload_truncated`, `payload_hash`, `delivery`.
331
+ *
332
+ * **`delivery` is always the literal `"pending"` here** — the stream writer builds its
333
+ * view without querying delivery attempts, so the field is its default for every event,
334
+ * including ones already delivered, failed or dead-lettered. It is not a delivery
335
+ * state; call `events.get(id)` for the real one.
336
+ *
337
+ * @param params.autoResume Set `false` to stop at the first ending instead of
338
+ * reconnecting. The unrecoverable endings still throw.
339
+ * @param params.maxReconnects Consecutive failed reconnects before giving up. The
340
+ * counter resets on every event actually delivered, so a stream that is working never
341
+ * exhausts it.
342
+ * @param params.heartbeatTimeoutMs Milliseconds of total silence before the socket is
343
+ * treated as dead.
344
+ */
345
+ subscribe(params?: {
346
+ triggerId?: string;
347
+ triggerSlug?: string;
348
+ applicationSlug?: string;
349
+ since?: string;
350
+ autoResume?: boolean;
351
+ maxReconnects?: number;
352
+ heartbeatTimeoutMs?: number;
353
+ }): AsyncGenerator<TriggerEventView>;
354
+ }
355
+ export {};