iii-sdk 0.8.3 → 0.9.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 (48) hide show
  1. package/README.md +15 -11
  2. package/dist/index.cjs +234 -105
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +182 -3
  5. package/dist/index.d.cts.map +1 -1
  6. package/dist/index.d.mts +182 -3
  7. package/dist/index.d.mts.map +1 -1
  8. package/dist/index.mjs +234 -106
  9. package/dist/index.mjs.map +1 -1
  10. package/dist/state.cjs +1 -0
  11. package/dist/state.cjs.map +1 -1
  12. package/dist/state.d.cts +43 -1
  13. package/dist/state.d.cts.map +1 -1
  14. package/dist/state.d.mts +43 -1
  15. package/dist/state.d.mts.map +1 -1
  16. package/dist/state.mjs +1 -0
  17. package/dist/state.mjs.map +1 -1
  18. package/dist/stream-BAjVneSg.d.mts +176 -0
  19. package/dist/stream-BAjVneSg.d.mts.map +1 -0
  20. package/dist/stream-DUNsytJU.d.cts +176 -0
  21. package/dist/stream-DUNsytJU.d.cts.map +1 -0
  22. package/dist/stream.d.cts +1 -1
  23. package/dist/stream.d.mts +1 -1
  24. package/dist/telemetry.cjs +1 -1
  25. package/dist/telemetry.d.cts +10 -11
  26. package/dist/telemetry.d.cts.map +1 -1
  27. package/dist/telemetry.d.mts +10 -11
  28. package/dist/telemetry.d.mts.map +1 -1
  29. package/dist/telemetry.mjs +1 -1
  30. package/dist/{utils-coGqiBHT.mjs → utils-5jD8F3OE.mjs} +241 -212
  31. package/dist/utils-5jD8F3OE.mjs.map +1 -0
  32. package/dist/{utils-CMrMD5Ij.d.mts → utils-BRn3Iff5.d.mts} +586 -210
  33. package/dist/utils-BRn3Iff5.d.mts.map +1 -0
  34. package/dist/{utils-BaGgUfjl.d.cts → utils-D6RPYBhs.d.cts} +586 -210
  35. package/dist/utils-D6RPYBhs.d.cts.map +1 -0
  36. package/dist/{utils-BJTjoUdq.cjs → utils-bsZVduQi.cjs} +240 -211
  37. package/dist/utils-bsZVduQi.cjs.map +1 -0
  38. package/package.json +4 -2
  39. package/typedoc.json +8 -0
  40. package/vitest.config.ts +4 -4
  41. package/dist/stream-BEp3rjfm.d.cts +0 -97
  42. package/dist/stream-BEp3rjfm.d.cts.map +0 -1
  43. package/dist/stream-Bzpo5JNV.d.mts +0 -97
  44. package/dist/stream-Bzpo5JNV.d.mts.map +0 -1
  45. package/dist/utils-BJTjoUdq.cjs.map +0 -1
  46. package/dist/utils-BaGgUfjl.d.cts.map +0 -1
  47. package/dist/utils-CMrMD5Ij.d.mts.map +0 -1
  48. package/dist/utils-coGqiBHT.mjs.map +0 -1
@@ -1,9 +1,293 @@
1
- import { n as IStream } from "./stream-Bzpo5JNV.mjs";
2
- import { Context, Meter as Meter$1, Span, SpanKind as SpanKind$1, SpanStatusCode as SpanStatusCode$1, Tracer } from "@opentelemetry/api";
1
+ import { n as IStream } from "./stream-BAjVneSg.mjs";
3
2
  import { Readable, Writable } from "node:stream";
3
+ import { Context, Meter as Meter$1, Span, SpanKind as SpanKind$1, SpanStatusCode as SpanStatusCode$1, Tracer } from "@opentelemetry/api";
4
4
  import { Instrumentation } from "@opentelemetry/instrumentation";
5
5
  import { Logger, SeverityNumber as SeverityNumber$1 } from "@opentelemetry/api-logs";
6
6
 
7
+ //#region src/iii-types.d.ts
8
+ declare enum MessageType {
9
+ RegisterFunction = "registerfunction",
10
+ UnregisterFunction = "unregisterfunction",
11
+ RegisterService = "registerservice",
12
+ InvokeFunction = "invokefunction",
13
+ InvocationResult = "invocationresult",
14
+ RegisterTriggerType = "registertriggertype",
15
+ RegisterTrigger = "registertrigger",
16
+ UnregisterTrigger = "unregistertrigger",
17
+ UnregisterTriggerType = "unregistertriggertype",
18
+ TriggerRegistrationResult = "triggerregistrationresult",
19
+ WorkerRegistered = "workerregistered",
20
+ }
21
+ type RegisterTriggerTypeMessage = {
22
+ message_type: MessageType.RegisterTriggerType;
23
+ id: string;
24
+ description: string;
25
+ };
26
+ type RegisterTriggerMessage = {
27
+ message_type: MessageType.RegisterTrigger;
28
+ id: string;
29
+ type: string;
30
+ function_id: string;
31
+ config: unknown;
32
+ };
33
+ type RegisterServiceMessage = {
34
+ message_type: MessageType.RegisterService;
35
+ id: string;
36
+ name?: string;
37
+ description?: string;
38
+ parent_service_id?: string;
39
+ };
40
+ /**
41
+ * Authentication configuration for HTTP-invoked functions.
42
+ *
43
+ * - `hmac` -- HMAC signature verification using a shared secret.
44
+ * - `bearer` -- Bearer token authentication.
45
+ * - `api_key` -- API key sent via a custom header.
46
+ */
47
+ type HttpAuthConfig = {
48
+ type: 'hmac';
49
+ secret_key: string;
50
+ } | {
51
+ type: 'bearer';
52
+ token_key: string;
53
+ } | {
54
+ type: 'api_key';
55
+ header: string;
56
+ value_key: string;
57
+ };
58
+ /**
59
+ * Configuration for registering an HTTP-invoked function (Lambda, Cloudflare
60
+ * Workers, etc.) instead of a local handler.
61
+ */
62
+ type HttpInvocationConfig = {
63
+ /** URL to invoke. */
64
+ url: string;
65
+ /** HTTP method. Defaults to `POST`. */
66
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
67
+ /** Timeout in milliseconds. */
68
+ timeout_ms?: number;
69
+ /** Custom headers to send with the request. */
70
+ headers?: Record<string, string>;
71
+ /** Authentication configuration. */
72
+ auth?: HttpAuthConfig;
73
+ };
74
+ type RegisterFunctionFormat = {
75
+ name: string;
76
+ /**
77
+ * The description of the parameter
78
+ */
79
+ description?: string;
80
+ /**
81
+ * The type of the parameter
82
+ */
83
+ type: 'string' | 'number' | 'boolean' | 'object' | 'array' | 'null' | 'map';
84
+ /**
85
+ * The body of the parameter
86
+ */
87
+ body?: RegisterFunctionFormat[];
88
+ /**
89
+ * The items of the parameter
90
+ */
91
+ items?: RegisterFunctionFormat;
92
+ /**
93
+ * Whether the parameter is required
94
+ */
95
+ required?: boolean;
96
+ };
97
+ type RegisterFunctionMessage = {
98
+ message_type: MessageType.RegisterFunction;
99
+ /**
100
+ * The path of the function (use :: for namespacing, e.g. external::my_lambda)
101
+ */
102
+ id: string;
103
+ /**
104
+ * The description of the function
105
+ */
106
+ description?: string;
107
+ /**
108
+ * The request format of the function
109
+ */
110
+ request_format?: RegisterFunctionFormat;
111
+ /**
112
+ * The response format of the function
113
+ */
114
+ response_format?: RegisterFunctionFormat;
115
+ metadata?: Record<string, unknown>;
116
+ /**
117
+ * HTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.)
118
+ */
119
+ invocation?: HttpInvocationConfig;
120
+ };
121
+ /**
122
+ * Routing action for {@link TriggerRequest}. Determines how the engine
123
+ * handles the invocation.
124
+ *
125
+ * - `enqueue` -- Routes through a named queue for async processing.
126
+ * - `void` -- Fire-and-forget, no response.
127
+ */
128
+ type TriggerAction = {
129
+ type: 'enqueue';
130
+ queue: string;
131
+ } | {
132
+ type: 'void';
133
+ };
134
+ /**
135
+ * Result returned when a function is invoked with `TriggerAction.Enqueue`.
136
+ */
137
+ type EnqueueResult = {
138
+ /** Unique receipt ID for the enqueued message. */
139
+ messageReceiptId: string;
140
+ };
141
+ /**
142
+ * Request object passed to {@link ISdk.trigger}.
143
+ *
144
+ * @typeParam TInput - Type of the payload.
145
+ */
146
+ type TriggerRequest<TInput = unknown> = {
147
+ /** ID of the function to invoke. */
148
+ function_id: string;
149
+ /** Payload to pass to the function. */
150
+ payload: TInput;
151
+ /** Routing action. Omit for synchronous request/response. */
152
+ action?: TriggerAction;
153
+ /** Override the default invocation timeout in milliseconds. */
154
+ timeoutMs?: number;
155
+ };
156
+ /**
157
+ * Metadata about a registered function, returned by `ISdk.listFunctions`.
158
+ */
159
+ type FunctionInfo = {
160
+ /** Unique function identifier. */
161
+ function_id: string;
162
+ /** Human-readable description. */
163
+ description?: string;
164
+ /** Schema describing expected request format. */
165
+ request_format?: RegisterFunctionFormat;
166
+ /** Schema describing expected response format. */
167
+ response_format?: RegisterFunctionFormat;
168
+ /** Arbitrary metadata attached to the function. */
169
+ metadata?: Record<string, unknown>;
170
+ };
171
+ /**
172
+ * Information about a registered trigger.
173
+ */
174
+ type TriggerInfo = {
175
+ /** Unique trigger identifier. */
176
+ id: string;
177
+ /** Type of the trigger (e.g. `http`, `cron`, `queue`). */
178
+ trigger_type: string;
179
+ /** ID of the function this trigger is bound to. */
180
+ function_id: string;
181
+ /** Trigger-specific configuration. */
182
+ config?: unknown;
183
+ };
184
+ /** Worker connection status. */
185
+ type WorkerStatus = 'connected' | 'available' | 'busy' | 'disconnected';
186
+ /**
187
+ * Metadata about a connected worker, returned by `ISdk.listWorkers`.
188
+ */
189
+ type WorkerInfo = {
190
+ /** Unique worker identifier assigned by the engine. */
191
+ id: string;
192
+ /** Display name of the worker. */
193
+ name?: string;
194
+ /** Runtime environment (e.g. `node`, `python`, `rust`). */
195
+ runtime?: string;
196
+ /** SDK version. */
197
+ version?: string;
198
+ /** Operating system info. */
199
+ os?: string;
200
+ /** IP address of the worker. */
201
+ ip_address?: string;
202
+ /** Current connection status. */
203
+ status: WorkerStatus;
204
+ /** Timestamp (ms since epoch) when the worker connected. */
205
+ connected_at_ms: number;
206
+ /** Number of functions registered by this worker. */
207
+ function_count: number;
208
+ /** List of function IDs registered by this worker. */
209
+ functions: string[];
210
+ /** Number of currently active invocations. */
211
+ active_invocations: number;
212
+ };
213
+ /**
214
+ * Serializable reference to one end of a streaming channel. Can be included
215
+ * in invocation payloads to pass channel endpoints between workers.
216
+ */
217
+ type StreamChannelRef = {
218
+ /** Unique channel identifier. */
219
+ channel_id: string;
220
+ /** Access key for authentication. */
221
+ access_key: string;
222
+ /** Whether this ref is for reading or writing. */
223
+ direction: 'read' | 'write';
224
+ };
225
+ //#endregion
226
+ //#region src/channels.d.ts
227
+ /**
228
+ * Write end of a streaming channel. Provides both a Node.js `Writable` stream
229
+ * and a `sendMessage` method for sending structured text messages.
230
+ *
231
+ * @example
232
+ * ```typescript
233
+ * const channel = await iii.createChannel()
234
+ *
235
+ * // Stream binary data
236
+ * channel.writer.stream.write(Buffer.from('hello'))
237
+ * channel.writer.stream.end()
238
+ *
239
+ * // Or send text messages
240
+ * channel.writer.sendMessage(JSON.stringify({ type: 'event', data: 'test' }))
241
+ * channel.writer.close()
242
+ * ```
243
+ */
244
+ declare class ChannelWriter {
245
+ private static readonly FRAME_SIZE;
246
+ private ws;
247
+ private wsReady;
248
+ private readonly pendingMessages;
249
+ /** Node.js Writable stream for binary data. */
250
+ readonly stream: Writable;
251
+ private readonly url;
252
+ constructor(engineWsBase: string, ref: StreamChannelRef);
253
+ private ensureConnected;
254
+ /** Send a text message through the channel. */
255
+ sendMessage(msg: string): void;
256
+ /** Close the channel writer. */
257
+ close(): void;
258
+ private sendChunked;
259
+ private sendRaw;
260
+ }
261
+ /**
262
+ * Read end of a streaming channel. Provides both a Node.js `Readable` stream
263
+ * for binary data and an `onMessage` callback for structured text messages.
264
+ *
265
+ * @example
266
+ * ```typescript
267
+ * const channel = await iii.createChannel()
268
+ *
269
+ * // Stream binary data
270
+ * channel.reader.stream.on('data', (chunk) => console.log(chunk))
271
+ *
272
+ * // Or receive text messages
273
+ * channel.reader.onMessage((msg) => console.log('Got:', msg))
274
+ * ```
275
+ */
276
+ declare class ChannelReader {
277
+ private ws;
278
+ private connected;
279
+ private readonly messageCallbacks;
280
+ /** Node.js Readable stream for binary data. */
281
+ readonly stream: Readable;
282
+ private readonly url;
283
+ constructor(engineWsBase: string, ref: StreamChannelRef);
284
+ private ensureConnected;
285
+ /** Register a callback to receive text messages from the channel. */
286
+ onMessage(callback: (msg: string) => void): void;
287
+ readAll(): Promise<Buffer>;
288
+ close(): void;
289
+ }
290
+ //#endregion
7
291
  //#region src/iii-constants.d.ts
8
292
  /**
9
293
  * Constants for the III module.
@@ -12,6 +296,7 @@ import { Logger, SeverityNumber as SeverityNumber$1 } from "@opentelemetry/api-l
12
296
  declare const EngineFunctions: {
13
297
  readonly LIST_FUNCTIONS: "engine::functions::list";
14
298
  readonly LIST_WORKERS: "engine::workers::list";
299
+ readonly LIST_TRIGGERS: "engine::triggers::list";
15
300
  readonly REGISTER_WORKER: "engine::workers::register";
16
301
  };
17
302
  /** Engine trigger types */
@@ -72,7 +357,7 @@ interface OtelConfig {
72
357
  serviceNamespace?: string;
73
358
  /** The service instance ID to report. Defaults to SERVICE_INSTANCE_ID env var or auto-generated UUID. */
74
359
  serviceInstanceId?: string;
75
- /** III Engine WebSocket URL. Defaults to III_BRIDGE_URL or "ws://localhost:49134". */
360
+ /** III Engine WebSocket URL. Defaults to III_URL or "ws://localhost:49134". */
76
361
  engineWsUrl?: string;
77
362
  /** OpenTelemetry instrumentations to register (e.g., PrismaInstrumentation). */
78
363
  instrumentations?: Instrumentation[];
@@ -166,162 +451,60 @@ declare function withSpan<T>(name: string, options: {
166
451
  traceparent?: string;
167
452
  }, fn: (span: Span) => Promise<T>): Promise<T>;
168
453
  //#endregion
169
- //#region src/iii-types.d.ts
170
- declare enum MessageType {
171
- RegisterFunction = "registerfunction",
172
- UnregisterFunction = "unregisterfunction",
173
- RegisterService = "registerservice",
174
- InvokeFunction = "invokefunction",
175
- InvocationResult = "invocationresult",
176
- RegisterTriggerType = "registertriggertype",
177
- RegisterTrigger = "registertrigger",
178
- UnregisterTrigger = "unregistertrigger",
179
- UnregisterTriggerType = "unregistertriggertype",
180
- TriggerRegistrationResult = "triggerregistrationresult",
181
- WorkerRegistered = "workerregistered",
182
- }
183
- type RegisterTriggerTypeMessage = {
184
- message_type: MessageType.RegisterTriggerType;
185
- id: string;
186
- description: string;
187
- };
188
- type RegisterTriggerMessage = {
189
- message_type: MessageType.RegisterTrigger;
190
- id: string;
191
- type: string;
192
- function_id: string;
193
- config: unknown;
194
- };
195
- type HttpAuthConfig = {
196
- type: 'hmac';
197
- secret_key: string;
198
- } | {
199
- type: 'bearer';
200
- token_key: string;
201
- } | {
202
- type: 'api_key';
203
- header: string;
204
- value_key: string;
205
- };
206
- type HttpInvocationConfig = {
207
- url: string;
208
- method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
209
- timeout_ms?: number;
210
- headers?: Record<string, string>;
211
- auth?: HttpAuthConfig;
212
- };
213
- type RegisterFunctionFormat = {
214
- name: string;
215
- /**
216
- * The description of the parameter
217
- */
218
- description?: string;
219
- /**
220
- * The type of the parameter
221
- */
222
- type: 'string' | 'number' | 'boolean' | 'object' | 'array' | 'null' | 'map';
223
- /**
224
- * The body of the parameter
225
- */
226
- body?: RegisterFunctionFormat[];
227
- /**
228
- * The items of the parameter
229
- */
230
- items?: RegisterFunctionFormat;
231
- /**
232
- * Whether the parameter is required
233
- */
234
- required?: boolean;
235
- };
236
- type RegisterFunctionMessage = {
237
- message_type: MessageType.RegisterFunction;
238
- /**
239
- * The path of the function (use :: for namespacing, e.g. external::my_lambda)
240
- */
241
- id: string;
242
- /**
243
- * The description of the function
244
- */
245
- description?: string;
246
- /**
247
- * The request format of the function
248
- */
249
- request_format?: RegisterFunctionFormat;
250
- /**
251
- * The response format of the function
252
- */
253
- response_format?: RegisterFunctionFormat;
254
- metadata?: Record<string, unknown>;
255
- /**
256
- * HTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.)
257
- */
258
- invocation?: HttpInvocationConfig;
259
- };
260
- type FunctionInfo = {
261
- function_id: string;
262
- description?: string;
263
- request_format?: RegisterFunctionFormat;
264
- response_format?: RegisterFunctionFormat;
265
- metadata?: Record<string, unknown>;
266
- };
267
- type WorkerStatus = 'connected' | 'available' | 'busy' | 'disconnected';
268
- type WorkerInfo = {
269
- id: string;
270
- name?: string;
271
- runtime?: string;
272
- version?: string;
273
- os?: string;
274
- ip_address?: string;
275
- status: WorkerStatus;
276
- connected_at_ms: number;
277
- function_count: number;
278
- functions: string[];
279
- active_invocations: number;
280
- };
281
- type StreamChannelRef = {
282
- channel_id: string;
283
- access_key: string;
284
- direction: 'read' | 'write';
285
- };
286
- //#endregion
287
454
  //#region src/triggers.d.ts
455
+ /**
456
+ * Configuration passed to a trigger handler when a trigger instance is
457
+ * registered or unregistered.
458
+ *
459
+ * @typeParam TConfig - Type of the trigger-specific configuration.
460
+ */
288
461
  type TriggerConfig<TConfig> = {
462
+ /** Trigger instance ID. */
289
463
  id: string;
464
+ /** Function to invoke when the trigger fires. */
290
465
  function_id: string;
466
+ /** Trigger-specific configuration. */
291
467
  config: TConfig;
292
468
  };
469
+ /**
470
+ * Handler interface for custom trigger types. Passed to
471
+ * `ISdk.registerTriggerType`.
472
+ *
473
+ * @typeParam TConfig - Type of the trigger-specific configuration.
474
+ *
475
+ * @example
476
+ * ```typescript
477
+ * const handler: TriggerHandler<{ interval: number }> = {
478
+ * async registerTrigger({ id, function_id, config }) {
479
+ * // Set up periodic invocation
480
+ * },
481
+ * async unregisterTrigger({ id, function_id, config }) {
482
+ * // Clean up
483
+ * },
484
+ * }
485
+ * ```
486
+ */
293
487
  type TriggerHandler<TConfig> = {
488
+ /** Called when a trigger instance is registered. */
294
489
  registerTrigger(config: TriggerConfig<TConfig>): Promise<void>;
490
+ /** Called when a trigger instance is unregistered. */
295
491
  unregisterTrigger(config: TriggerConfig<TConfig>): Promise<void>;
296
492
  };
297
493
  //#endregion
298
- //#region src/channels.d.ts
299
- declare class ChannelWriter {
300
- private static readonly FRAME_SIZE;
301
- private ws;
302
- private wsReady;
303
- private readonly pendingMessages;
304
- readonly stream: Writable;
305
- private readonly url;
306
- constructor(engineWsBase: string, ref: StreamChannelRef);
307
- private ensureConnected;
308
- sendMessage(msg: string): void;
309
- close(): void;
310
- private sendChunked;
311
- private sendRaw;
312
- }
313
- declare class ChannelReader {
314
- private ws;
315
- private connected;
316
- private readonly messageCallbacks;
317
- readonly stream: Readable;
318
- private readonly url;
319
- constructor(engineWsBase: string, ref: StreamChannelRef);
320
- private ensureConnected;
321
- onMessage(callback: (msg: string) => void): void;
322
- }
323
- //#endregion
324
494
  //#region src/types.d.ts
495
+ /**
496
+ * Async function handler for a registered function. Receives the invocation
497
+ * payload and returns the result.
498
+ *
499
+ * @typeParam TInput - Type of the invocation payload.
500
+ * @typeParam TOutput - Type of the return value.
501
+ *
502
+ * @example
503
+ * ```typescript
504
+ * const handler: RemoteFunctionHandler<{ name: string }, { message: string }> =
505
+ * async (data) => ({ message: `Hello, ${data.name}!` })
506
+ * ```
507
+ */
325
508
  type RemoteFunctionHandler<TInput = any, TOutput = any> = (data: TInput) => Promise<TOutput>;
326
509
  /** OTEL Log Event from the engine */
327
510
  type OtelLogEvent = {
@@ -350,16 +533,8 @@ type OtelLogEvent = {
350
533
  /** Instrumentation scope version (if available) */
351
534
  instrumentation_scope_version?: string;
352
535
  };
353
- /** Severity levels for log filtering */
354
- type LogSeverityLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | 'all';
355
- /** Optional configuration for onLog */
356
- type LogConfig = {
357
- /** Minimum severity level to receive (default: 'all') */
358
- level?: LogSeverityLevel;
359
- };
360
- /** Callback type for log events */
361
- type LogCallback = (log: OtelLogEvent) => void;
362
536
  type RegisterTriggerInput = Omit<RegisterTriggerMessage, 'message_type' | 'id'>;
537
+ type RegisterServiceInput = Omit<RegisterServiceMessage, 'message_type'>;
363
538
  type RegisterFunctionInput = Omit<RegisterFunctionMessage, 'message_type'>;
364
539
  type RegisterTriggerTypeInput = Omit<RegisterTriggerTypeMessage, 'message_type'>;
365
540
  type FunctionsAvailableCallback = (functions: FunctionInfo[]) => void;
@@ -368,55 +543,148 @@ interface ISdk {
368
543
  * Registers a new trigger. A trigger is a way to invoke a function when a certain event occurs.
369
544
  * @param trigger - The trigger to register
370
545
  * @returns A trigger object that can be used to unregister the trigger
546
+ *
547
+ * @example
548
+ * ```typescript
549
+ * const trigger = iii.registerTrigger({
550
+ * type: 'cron',
551
+ * function_id: 'my-service::process-batch',
552
+ * config: { schedule: '*\/5 * * * *' },
553
+ * })
554
+ *
555
+ * // Later, remove the trigger
556
+ * trigger.unregister()
557
+ * ```
371
558
  */
372
559
  registerTrigger(trigger: RegisterTriggerInput): Trigger;
373
560
  /**
374
- * Registers a new function. A function is a unit of work that can be invoked by other services.
375
- * Pass a handler for local execution, or an HttpInvocationConfig for HTTP-invoked functions.
561
+ * Registers a new function with a local handler.
376
562
  * @param func - The function to register
377
- * @param handlerOrInvocation - The handler for local execution, or HTTP invocation config
378
- * @returns A function object that can be used to unregister the function
563
+ * @param handler - The handler for local execution
564
+ * @returns A handle that can be used to unregister the function
565
+ *
566
+ * @example
567
+ * ```typescript
568
+ * const ref = iii.registerFunction(
569
+ * { id: 'greet', description: 'Returns a greeting' },
570
+ * async (data: { name: string }) => ({ message: `Hello, ${data.name}!` }),
571
+ * )
572
+ *
573
+ * // Later, remove the function
574
+ * ref.unregister()
575
+ * ```
576
+ */
577
+ /**
578
+ * Registers a new service.
579
+ * @param message - The service to register
379
580
  */
581
+ registerService(message: RegisterServiceInput): void;
380
582
  registerFunction(func: RegisterFunctionInput, handler: RemoteFunctionHandler): FunctionRef;
583
+ /**
584
+ * Registers a new function with an HTTP invocation config (Lambda, Cloudflare Workers, etc.).
585
+ * @param func - The function to register
586
+ * @param invocation - HTTP invocation config
587
+ * @returns A handle that can be used to unregister the function
588
+ *
589
+ * @example
590
+ * ```typescript
591
+ * const ref = iii.registerFunction(
592
+ * { id: 'external::my-lambda', description: 'Proxied Lambda function' },
593
+ * {
594
+ * url: 'https://abc123.lambda-url.us-east-1.on.aws',
595
+ * method: 'POST',
596
+ * timeout_ms: 30_000,
597
+ * auth: { type: 'bearer', token_key: 'LAMBDA_AUTH_TOKEN' },
598
+ * },
599
+ * )
600
+ * ```
601
+ */
381
602
  registerFunction(func: RegisterFunctionInput, invocation: HttpInvocationConfig): FunctionRef;
382
603
  /**
383
- * Invokes a function.
384
- * @param function_id - The path to the function
385
- * @param data - The data to pass to the function
386
- * @param timeoutMs - Optional timeout in milliseconds
604
+ * Invokes a function using a request object.
605
+ *
606
+ * @param request - The trigger request containing function_id, payload, and optional action/timeout
387
607
  * @returns The result of the function
608
+ *
609
+ * @example
610
+ * ```typescript
611
+ * // Synchronous invocation
612
+ * const result = await iii.trigger<{ name: string }, { message: string }>({
613
+ * function_id: 'greet',
614
+ * payload: { name: 'World' },
615
+ * timeoutMs: 5000,
616
+ * })
617
+ * console.log(result.message) // "Hello, World!"
618
+ *
619
+ * // Fire-and-forget
620
+ * await iii.trigger({
621
+ * function_id: 'send-email',
622
+ * payload: { to: 'user@example.com' },
623
+ * action: TriggerAction.Void(),
624
+ * })
625
+ *
626
+ * // Enqueue for async processing
627
+ * const receipt = await iii.trigger({
628
+ * function_id: 'process-order',
629
+ * payload: { orderId: '123' },
630
+ * action: TriggerAction.Enqueue({ queue: 'orders' }),
631
+ * })
632
+ * ```
388
633
  */
389
- trigger<TInput, TOutput>(function_id: string, data: TInput, timeoutMs?: number): Promise<TOutput>;
634
+ trigger<TInput, TOutput>(request: TriggerRequest<TInput>): Promise<TOutput>;
390
635
  /**
391
636
  * Lists all registered functions.
637
+ *
638
+ * @example
639
+ * ```typescript
640
+ * const functions = await iii.listFunctions()
641
+ * for (const fn of functions) {
642
+ * console.log(`${fn.function_id}: ${fn.description}`)
643
+ * }
644
+ * ```
392
645
  */
393
646
  listFunctions(): Promise<FunctionInfo[]>;
394
647
  /**
395
- * Invokes a function asynchronously.
396
- * @param function_id - The path to the function
397
- * @param data - The data to pass to the function
648
+ * Lists all registered triggers.
649
+ * @param includeInternal - Whether to include internal triggers (default: false)
398
650
  */
399
- triggerVoid<TInput>(function_id: string, data: TInput): void;
400
- call<TInput, TOutput>(function_id: string, data: TInput, timeoutMs?: number): Promise<TOutput>;
401
- callVoid<TInput>(function_id: string, data: TInput): void;
651
+ listTriggers(includeInternal?: boolean): Promise<TriggerInfo[]>;
402
652
  /**
403
653
  * Registers a new trigger type. A trigger type is a way to invoke a function when a certain event occurs.
404
654
  * @param triggerType - The trigger type to register
405
655
  * @param handler - The handler for the trigger type
406
656
  * @returns A trigger type object that can be used to unregister the trigger type
657
+ *
658
+ * @example
659
+ * ```typescript
660
+ * type CronConfig = { schedule: string }
661
+ *
662
+ * iii.registerTriggerType<CronConfig>(
663
+ * { id: 'cron', description: 'Fires on a cron schedule' },
664
+ * {
665
+ * async registerTrigger({ id, function_id, config }) {
666
+ * startCronJob(id, config.schedule, () =>
667
+ * iii.trigger({ function_id, payload: {} }),
668
+ * )
669
+ * },
670
+ * async unregisterTrigger({ id }) {
671
+ * stopCronJob(id)
672
+ * },
673
+ * },
674
+ * )
675
+ * ```
407
676
  */
408
677
  registerTriggerType<TConfig>(triggerType: RegisterTriggerTypeInput, handler: TriggerHandler<TConfig>): void;
409
678
  /**
410
679
  * Unregisters a trigger type.
411
680
  * @param triggerType - The trigger type to unregister
681
+ *
682
+ * @example
683
+ * ```typescript
684
+ * iii.unregisterTriggerType({ id: 'cron', description: 'Fires on a cron schedule' })
685
+ * ```
412
686
  */
413
687
  unregisterTriggerType(triggerType: RegisterTriggerTypeInput): void;
414
- /**
415
- * Registers a callback for a specific event.
416
- * @param event - The event to register the callback for
417
- * @param callback - The callback to register
418
- */
419
- on(event: string, callback: (arg?: unknown) => void): void;
420
688
  /**
421
689
  * Creates a streaming channel pair for worker-to-worker data transfer.
422
690
  * Returns a Channel with a local writer/reader and serializable refs that
@@ -424,6 +692,22 @@ interface ISdk {
424
692
  *
425
693
  * @param bufferSize - Optional buffer size for the channel (default: 64)
426
694
  * @returns A Channel with writer, reader, and their serializable refs
695
+ *
696
+ * @example
697
+ * ```typescript
698
+ * const channel = await iii.createChannel()
699
+ *
700
+ * // Pass the writer ref to another function
701
+ * await iii.trigger({
702
+ * function_id: 'stream-producer',
703
+ * payload: { outputChannel: channel.writerRef },
704
+ * })
705
+ *
706
+ * // Read data locally
707
+ * channel.reader.onMessage((msg) => {
708
+ * console.log('Received:', msg)
709
+ * })
710
+ * ```
427
711
  */
428
712
  createChannel(bufferSize?: number): Promise<Channel>;
429
713
  /**
@@ -433,36 +717,93 @@ interface ISdk {
433
717
  *
434
718
  * @param streamName - The name of the stream
435
719
  * @param stream - The stream implementation
720
+ *
721
+ * @example
722
+ * ```typescript
723
+ * const redisStream: IStream<UserSession> = {
724
+ * async get({ group_id, item_id }) {
725
+ * return JSON.parse(await redis.get(`${group_id}:${item_id}`) ?? 'null')
726
+ * },
727
+ * async set({ group_id, item_id, data }) {
728
+ * const old = await this.get({ stream_name: 'sessions', group_id, item_id })
729
+ * await redis.set(`${group_id}:${item_id}`, JSON.stringify(data))
730
+ * return { old_value: old ?? undefined, new_value: data }
731
+ * },
732
+ * async delete({ group_id, item_id }) {
733
+ * const old = await this.get({ stream_name: 'sessions', group_id, item_id })
734
+ * await redis.del(`${group_id}:${item_id}`)
735
+ * return { old_value: old ?? undefined }
736
+ * },
737
+ * async list({ group_id }) { return [] },
738
+ * async listGroups() { return [] },
739
+ * async update({ group_id, item_id, ops }) { return { new_value: {} } },
740
+ * }
741
+ *
742
+ * iii.createStream('sessions', redisStream)
743
+ * ```
436
744
  */
437
745
  createStream<TData>(streamName: string, stream: IStream<TData>): void;
438
746
  /**
439
747
  * Registers a callback to receive the current functions list
440
748
  * when the engine announces changes.
749
+ *
750
+ * @example
751
+ * ```typescript
752
+ * const unsubscribe = iii.onFunctionsAvailable((functions) => {
753
+ * console.log(`${functions.length} functions available:`)
754
+ * for (const fn of functions) {
755
+ * console.log(` - ${fn.function_id}`)
756
+ * }
757
+ * })
758
+ *
759
+ * // Later, stop listening
760
+ * unsubscribe()
761
+ * ```
441
762
  */
442
763
  onFunctionsAvailable(callback: FunctionsAvailableCallback): () => void;
443
- /**
444
- * Registers a callback to receive OTEL log events from the engine.
445
- * @param callback - The callback to invoke when a log event is received
446
- * @param config - Optional configuration for filtering logs by severity level
447
- * @returns A function to unregister the callback
448
- */
449
- onLog(callback: LogCallback, config?: LogConfig): () => void;
450
764
  /**
451
765
  * Gracefully shutdown the iii, cleaning up all resources.
766
+ *
767
+ * @example
768
+ * ```typescript
769
+ * process.on('SIGTERM', async () => {
770
+ * await iii.shutdown()
771
+ * process.exit(0)
772
+ * })
773
+ * ```
452
774
  */
453
775
  shutdown(): Promise<void>;
454
776
  }
777
+ /**
778
+ * Handle returned by {@link ISdk.registerTrigger}. Use `unregister()` to
779
+ * remove the trigger from the engine.
780
+ */
455
781
  type Trigger = {
782
+ /** Removes this trigger from the engine. */
456
783
  unregister(): void;
457
784
  };
785
+ /**
786
+ * Handle returned by {@link ISdk.registerFunction}. Contains the function's
787
+ * `id` and an `unregister()` method.
788
+ */
458
789
  type FunctionRef = {
790
+ /** The unique function identifier. */
459
791
  id: string;
792
+ /** Removes this function from the engine. */
460
793
  unregister: () => void;
461
794
  };
795
+ /**
796
+ * A streaming channel pair for worker-to-worker data transfer. Created via
797
+ * {@link ISdk.createChannel}.
798
+ */
462
799
  type Channel = {
800
+ /** Writer end of the channel. */
463
801
  writer: ChannelWriter;
802
+ /** Reader end of the channel. */
464
803
  reader: ChannelReader;
804
+ /** Serializable reference to the writer (can be sent to other workers). */
465
805
  writerRef: StreamChannelRef;
806
+ /** Serializable reference to the reader (can be sent to other workers). */
466
807
  readerRef: StreamChannelRef;
467
808
  };
468
809
  type InternalHttpRequest<TBody = unknown> = {
@@ -474,51 +815,86 @@ type InternalHttpRequest<TBody = unknown> = {
474
815
  response: ChannelWriter;
475
816
  request_body: ChannelReader;
476
817
  };
818
+ /**
819
+ * Response object passed to HTTP function handlers. Use `status()` and
820
+ * `headers()` to set response metadata, write to `stream` for streaming
821
+ * responses, and call `close()` when done.
822
+ */
477
823
  type HttpResponse = {
824
+ /** Set the HTTP status code. */
478
825
  status: (statusCode: number) => void;
826
+ /** Set response headers. */
479
827
  headers: (headers: Record<string, string>) => void;
828
+ /** Writable stream for the response body. */
480
829
  stream: NodeJS.WritableStream;
830
+ /** Close the response. */
481
831
  close: () => void;
482
832
  };
833
+ /**
834
+ * Incoming HTTP request received by a function registered with an HTTP trigger.
835
+ *
836
+ * @typeParam TBody - Type of the parsed request body.
837
+ */
483
838
  type HttpRequest<TBody = unknown> = Omit<InternalHttpRequest<TBody>, 'response'>;
839
+ /**
840
+ * Alias for {@link HttpRequest}. Represents an incoming API request.
841
+ *
842
+ * @typeParam TBody - Type of the parsed request body.
843
+ */
484
844
  type ApiRequest<TBody = unknown> = HttpRequest<TBody>;
845
+ /**
846
+ * Structured API response returned from HTTP function handlers.
847
+ *
848
+ * @typeParam TStatus - HTTP status code literal type.
849
+ * @typeParam TBody - Type of the response body.
850
+ *
851
+ * @example
852
+ * ```typescript
853
+ * const response: ApiResponse = {
854
+ * status_code: 200,
855
+ * headers: { 'content-type': 'application/json' },
856
+ * body: { message: 'ok' },
857
+ * }
858
+ * ```
859
+ */
485
860
  type ApiResponse<TStatus extends number = number, TBody = string | Buffer | Record<string, unknown>> = {
861
+ /** HTTP status code. */
486
862
  status_code: TStatus;
863
+ /** Response headers. */
487
864
  headers?: Record<string, string>;
865
+ /** Response body. */
488
866
  body?: TBody;
489
867
  };
490
868
  //#endregion
491
- //#region src/iii.d.ts
492
- /** Callback type for connection state changes */
493
- type ConnectionStateCallback = (state: IIIConnectionState) => void;
494
- type TelemetryOptions = {
495
- language?: string;
496
- project_name?: string;
497
- framework?: string;
498
- amplitude_api_key?: string;
499
- };
500
- type InitOptions = {
501
- workerName?: string;
502
- enableMetricsReporting?: boolean;
503
- /** Default timeout for function invocations in milliseconds */
504
- invocationTimeoutMs?: number;
505
- /** Configuration for WebSocket reconnection behavior */
506
- reconnectionConfig?: Partial<IIIReconnectionConfig>;
507
- /** OpenTelemetry configuration. OTel is initialized automatically by default.
508
- * Set `{ enabled: false }` or env `OTEL_ENABLED=false/0/no/off` to disable.
509
- * The engineWsUrl is set automatically from the III address. */
510
- otel?: Omit<OtelConfig, 'engineWsUrl'>;
511
- telemetry?: TelemetryOptions;
512
- };
513
- declare const registerWorker: (address: string, options?: InitOptions) => ISdk;
514
- //#endregion
515
869
  //#region src/utils.d.ts
516
870
  /**
517
871
  * Safely stringify a value, handling circular references, BigInt, and other edge cases.
518
872
  * Returns "[unserializable]" if serialization fails for any reason.
519
873
  */
520
874
  declare function safeStringify(value: unknown): string;
875
+ /**
876
+ * Helper that wraps an HTTP-style handler (with separate `req`/`res` arguments)
877
+ * into the function handler format expected by the SDK.
878
+ *
879
+ * @param callback - Async handler receiving an {@link HttpRequest} and {@link HttpResponse}.
880
+ * @returns A function handler compatible with {@link ISdk.registerFunction}.
881
+ *
882
+ * @example
883
+ * ```typescript
884
+ * import { http } from 'iii-sdk'
885
+ *
886
+ * iii.registerFunction(
887
+ * { id: 'my-api' },
888
+ * http(async (req, res) => {
889
+ * res.status(200)
890
+ * res.headers({ 'content-type': 'application/json' })
891
+ * res.stream.end(JSON.stringify({ hello: 'world' }))
892
+ * res.close()
893
+ * }),
894
+ * )
895
+ * ```
896
+ */
521
897
  declare const http: (callback: (req: HttpRequest, res: HttpResponse) => Promise<void | ApiResponse>) => (req: InternalHttpRequest) => Promise<void | ApiResponse>;
522
898
  //#endregion
523
- export { IIIReconnectionConfig as $, getLogger as A, extractTraceparent as B, WorkerInfo as C, SeverityNumber$1 as D, Meter$1 as E, withSpan as F, removeBaggageEntry as G, getBaggageEntry as H, currentSpanId as I, DEFAULT_BRIDGE_RECONNECTION_CONFIG as J, setBaggageEntry as K, currentTraceId as L, getTracer as M, initOtel as N, Span as O, shutdownOtel as P, IIIConnectionState as Q, extractBaggage as R, StreamChannelRef as S, Logger as T, injectBaggage as U, getAllBaggage as V, injectTraceparent as W, EngineFunctions as X, DEFAULT_INVOCATION_TIMEOUT_MS as Y, EngineTriggers as Z, ChannelReader as _, registerWorker as a, HttpAuthConfig as b, Channel as c, HttpResponse as d, LogFunctions as et, ISdk as f, OtelLogEvent as g, LogSeverityLevel as h, InitOptions as i, getMeter as j, SpanStatusCode$1 as k, FunctionsAvailableCallback as l, LogConfig as m, safeStringify as n, ApiRequest as o, LogCallback as p, OtelConfig as q, ConnectionStateCallback as r, ApiResponse as s, http as t, HttpRequest as u, ChannelWriter as v, WorkerStatus as w, HttpInvocationConfig as x, FunctionInfo as y, extractContext as z };
524
- //# sourceMappingURL=utils-CMrMD5Ij.d.mts.map
899
+ export { ChannelWriter as $, shutdownOtel as A, injectTraceparent as B, SeverityNumber$1 as C, getMeter as D, getLogger as E, extractContext as F, DEFAULT_BRIDGE_RECONNECTION_CONFIG as G, setBaggageEntry as H, extractTraceparent as I, EngineTriggers as J, DEFAULT_INVOCATION_TIMEOUT_MS as K, getAllBaggage as L, currentSpanId as M, currentTraceId as N, getTracer as O, extractBaggage as P, ChannelReader as Q, getBaggageEntry as R, Meter$1 as S, SpanStatusCode$1 as T, OtelConfig as U, removeBaggageEntry as V, ReconnectionConfig as W, IIIReconnectionConfig as X, IIIConnectionState as Y, LogFunctions as Z, RemoteFunctionHandler as _, Channel as a, RegisterFunctionFormat as at, TriggerHandler as b, HttpRequest as c, RegisterTriggerTypeMessage as ct, InternalHttpRequest as d, TriggerInfo as dt, EnqueueResult as et, OtelLogEvent as f, TriggerRequest as ft, RegisterTriggerTypeInput as g, RegisterTriggerInput as h, ApiResponse as i, MessageType as it, withSpan as j, initOtel as k, HttpResponse as l, StreamChannelRef as lt, RegisterServiceInput as m, WorkerStatus as mt, safeStringify as n, HttpAuthConfig as nt, FunctionRef as o, RegisterFunctionMessage as ot, RegisterFunctionInput as p, WorkerInfo as pt, EngineFunctions as q, ApiRequest as r, HttpInvocationConfig as rt, FunctionsAvailableCallback as s, RegisterTriggerMessage as st, http as t, FunctionInfo as tt, ISdk as u, TriggerAction as ut, Trigger as v, Span as w, Logger as x, TriggerConfig as y, injectBaggage as z };
900
+ //# sourceMappingURL=utils-BRn3Iff5.d.mts.map