iii-sdk 0.8.3 → 0.10.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 (50) hide show
  1. package/README.md +15 -11
  2. package/dist/index.cjs +278 -142
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +177 -3
  5. package/dist/index.d.cts.map +1 -1
  6. package/dist/index.d.mts +177 -3
  7. package/dist/index.d.mts.map +1 -1
  8. package/dist/index.mjs +259 -125
  9. package/dist/index.mjs.map +1 -1
  10. package/dist/state.cjs +7 -5
  11. package/dist/state.cjs.map +1 -1
  12. package/dist/state.d.cts +38 -13
  13. package/dist/state.d.cts.map +1 -1
  14. package/dist/state.d.mts +38 -13
  15. package/dist/state.d.mts.map +1 -1
  16. package/dist/state.mjs +6 -5
  17. package/dist/state.mjs.map +1 -1
  18. package/dist/stream-C1zUjhzk.d.mts +145 -0
  19. package/dist/stream-C1zUjhzk.d.mts.map +1 -0
  20. package/dist/stream-lxenNA3s.d.cts +145 -0
  21. package/dist/stream-lxenNA3s.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 +6 -5
  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-BvWlFlLq.d.cts +839 -0
  31. package/dist/utils-BvWlFlLq.d.cts.map +1 -0
  32. package/dist/{utils-BJTjoUdq.cjs → utils-C6yTT4Js.cjs} +311 -282
  33. package/dist/utils-C6yTT4Js.cjs.map +1 -0
  34. package/dist/utils-_zSeatp1.d.mts +839 -0
  35. package/dist/utils-_zSeatp1.d.mts.map +1 -0
  36. package/dist/{utils-coGqiBHT.mjs → utils-xBUm8n1P.mjs} +246 -217
  37. package/dist/utils-xBUm8n1P.mjs.map +1 -0
  38. package/package.json +5 -3
  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 +0 -524
  47. package/dist/utils-BaGgUfjl.d.cts.map +0 -1
  48. package/dist/utils-CMrMD5Ij.d.mts +0 -524
  49. package/dist/utils-CMrMD5Ij.d.mts.map +0 -1
  50. package/dist/utils-coGqiBHT.mjs.map +0 -1
@@ -0,0 +1,839 @@
1
+ import { n as IStream } from "./stream-lxenNA3s.cjs";
2
+ import { Readable, Writable } from "node:stream";
3
+ import { Context, Meter as Meter$1, Span, SpanKind, SpanStatusCode, Tracer } from "@opentelemetry/api";
4
+ import { Logger, SeverityNumber } from "@opentelemetry/api-logs";
5
+ import { Instrumentation } from "@opentelemetry/instrumentation";
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. */url: string; /** HTTP method. Defaults to `POST`. */
64
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; /** Timeout in milliseconds. */
65
+ timeout_ms?: number; /** Custom headers to send with the request. */
66
+ headers?: Record<string, string>; /** Authentication configuration. */
67
+ auth?: HttpAuthConfig;
68
+ };
69
+ type RegisterFunctionFormat = {
70
+ /**
71
+ * The name of the parameter
72
+ */
73
+ name?: string;
74
+ /**
75
+ * The description of the parameter
76
+ */
77
+ description?: string;
78
+ /**
79
+ * The type of the parameter
80
+ */
81
+ type: 'string' | 'number' | 'boolean' | 'object' | 'array' | 'null' | 'map';
82
+ /**
83
+ * The body of the parameter
84
+ */
85
+ properties?: Record<string, RegisterFunctionFormat>;
86
+ /**
87
+ * The items of the parameter
88
+ */
89
+ items?: RegisterFunctionFormat;
90
+ /**
91
+ * Whether the parameter is required
92
+ */
93
+ required?: string[];
94
+ };
95
+ type RegisterFunctionMessage = {
96
+ message_type: MessageType.RegisterFunction;
97
+ /**
98
+ * The path of the function (use :: for namespacing, e.g. external::my_lambda)
99
+ */
100
+ id: string;
101
+ /**
102
+ * The description of the function
103
+ */
104
+ description?: string;
105
+ /**
106
+ * The request format of the function
107
+ */
108
+ request_format?: RegisterFunctionFormat;
109
+ /**
110
+ * The response format of the function
111
+ */
112
+ response_format?: RegisterFunctionFormat;
113
+ metadata?: Record<string, unknown>;
114
+ /**
115
+ * HTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.)
116
+ */
117
+ invocation?: HttpInvocationConfig;
118
+ };
119
+ /**
120
+ * Routing action for {@link TriggerRequest}. Determines how the engine
121
+ * handles the invocation.
122
+ *
123
+ * - `enqueue` -- Routes through a named queue for async processing.
124
+ * - `void` -- Fire-and-forget, no response.
125
+ */
126
+ type TriggerAction = {
127
+ type: 'enqueue';
128
+ queue: string;
129
+ } | {
130
+ type: 'void';
131
+ };
132
+ /**
133
+ * Result returned when a function is invoked with `TriggerAction.Enqueue`.
134
+ */
135
+ type EnqueueResult = {
136
+ /** Unique receipt ID for the enqueued message. */messageReceiptId: string;
137
+ };
138
+ /**
139
+ * Request object passed to {@link ISdk.trigger}.
140
+ *
141
+ * @typeParam TInput - Type of the payload.
142
+ */
143
+ type TriggerRequest<TInput = unknown> = {
144
+ /** ID of the function to invoke. */function_id: string; /** Payload to pass to the function. */
145
+ payload: TInput; /** Routing action. Omit for synchronous request/response. */
146
+ action?: TriggerAction; /** Override the default invocation timeout in milliseconds. */
147
+ timeoutMs?: number;
148
+ };
149
+ /**
150
+ * Metadata about a registered function, returned by `ISdk.listFunctions`.
151
+ */
152
+ type FunctionInfo = {
153
+ /** Unique function identifier. */function_id: string; /** Human-readable description. */
154
+ description?: string; /** Schema describing expected request format. */
155
+ request_format?: RegisterFunctionFormat; /** Schema describing expected response format. */
156
+ response_format?: RegisterFunctionFormat; /** Arbitrary metadata attached to the function. */
157
+ metadata?: Record<string, unknown>;
158
+ };
159
+ /**
160
+ * Information about a registered trigger.
161
+ */
162
+ type TriggerInfo = {
163
+ /** Unique trigger identifier. */id: string; /** Type of the trigger (e.g. `http`, `cron`, `queue`). */
164
+ trigger_type: string; /** ID of the function this trigger is bound to. */
165
+ function_id: string; /** Trigger-specific configuration. */
166
+ config?: unknown;
167
+ };
168
+ /** Worker connection status. */
169
+ type WorkerStatus = 'connected' | 'available' | 'busy' | 'disconnected';
170
+ /**
171
+ * Metadata about a connected worker, returned by `ISdk.listWorkers`.
172
+ */
173
+ type WorkerInfo = {
174
+ /** Unique worker identifier assigned by the engine. */id: string; /** Display name of the worker. */
175
+ name?: string; /** Runtime environment (e.g. `node`, `python`, `rust`). */
176
+ runtime?: string; /** SDK version. */
177
+ version?: string; /** Operating system info. */
178
+ os?: string; /** IP address of the worker. */
179
+ ip_address?: string; /** Current connection status. */
180
+ status: WorkerStatus; /** Timestamp (ms since epoch) when the worker connected. */
181
+ connected_at_ms: number; /** Number of functions registered by this worker. */
182
+ function_count: number; /** List of function IDs registered by this worker. */
183
+ functions: string[]; /** Number of currently active invocations. */
184
+ active_invocations: number;
185
+ };
186
+ /**
187
+ * Serializable reference to one end of a streaming channel. Can be included
188
+ * in invocation payloads to pass channel endpoints between workers.
189
+ */
190
+ type StreamChannelRef = {
191
+ /** Unique channel identifier. */channel_id: string; /** Access key for authentication. */
192
+ access_key: string; /** Whether this ref is for reading or writing. */
193
+ direction: 'read' | 'write';
194
+ };
195
+ //#endregion
196
+ //#region src/channels.d.ts
197
+ /**
198
+ * Write end of a streaming channel. Provides both a Node.js `Writable` stream
199
+ * and a `sendMessage` method for sending structured text messages.
200
+ *
201
+ * @example
202
+ * ```typescript
203
+ * const channel = await iii.createChannel()
204
+ *
205
+ * // Stream binary data
206
+ * channel.writer.stream.write(Buffer.from('hello'))
207
+ * channel.writer.stream.end()
208
+ *
209
+ * // Or send text messages
210
+ * channel.writer.sendMessage(JSON.stringify({ type: 'event', data: 'test' }))
211
+ * channel.writer.close()
212
+ * ```
213
+ */
214
+ declare class ChannelWriter {
215
+ private static readonly FRAME_SIZE;
216
+ private ws;
217
+ private wsReady;
218
+ private readonly pendingMessages;
219
+ /** Node.js Writable stream for binary data. */
220
+ readonly stream: Writable;
221
+ private readonly url;
222
+ constructor(engineWsBase: string, ref: StreamChannelRef);
223
+ private ensureConnected;
224
+ /** Send a text message through the channel. */
225
+ sendMessage(msg: string): void;
226
+ /** Close the channel writer. */
227
+ close(): void;
228
+ private sendChunked;
229
+ private sendRaw;
230
+ }
231
+ /**
232
+ * Read end of a streaming channel. Provides both a Node.js `Readable` stream
233
+ * for binary data and an `onMessage` callback for structured text messages.
234
+ *
235
+ * @example
236
+ * ```typescript
237
+ * const channel = await iii.createChannel()
238
+ *
239
+ * // Stream binary data
240
+ * channel.reader.stream.on('data', (chunk) => console.log(chunk))
241
+ *
242
+ * // Or receive text messages
243
+ * channel.reader.onMessage((msg) => console.log('Got:', msg))
244
+ * ```
245
+ */
246
+ declare class ChannelReader {
247
+ private ws;
248
+ private connected;
249
+ private readonly messageCallbacks;
250
+ /** Node.js Readable stream for binary data. */
251
+ readonly stream: Readable;
252
+ private readonly url;
253
+ constructor(engineWsBase: string, ref: StreamChannelRef);
254
+ private ensureConnected;
255
+ /** Register a callback to receive text messages from the channel. */
256
+ onMessage(callback: (msg: string) => void): void;
257
+ readAll(): Promise<Buffer>;
258
+ close(): void;
259
+ }
260
+ //#endregion
261
+ //#region src/iii-constants.d.ts
262
+ /**
263
+ * Constants for the III module.
264
+ */
265
+ /** Engine function paths for internal operations */
266
+ declare const EngineFunctions: {
267
+ readonly LIST_FUNCTIONS: "engine::functions::list";
268
+ readonly LIST_WORKERS: "engine::workers::list";
269
+ readonly LIST_TRIGGERS: "engine::triggers::list";
270
+ readonly REGISTER_WORKER: "engine::workers::register";
271
+ };
272
+ /** Engine trigger types */
273
+ declare const EngineTriggers: {
274
+ readonly FUNCTIONS_AVAILABLE: "engine::functions-available";
275
+ readonly LOG: "log";
276
+ };
277
+ /** Log function paths */
278
+ declare const LogFunctions: {
279
+ readonly INFO: "engine::log::info";
280
+ readonly WARN: "engine::log::warn";
281
+ readonly ERROR: "engine::log::error";
282
+ readonly DEBUG: "engine::log::debug";
283
+ };
284
+ /** Connection state for the III WebSocket */
285
+ type IIIConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'failed';
286
+ /** Configuration for WebSocket reconnection behavior */
287
+ interface IIIReconnectionConfig {
288
+ /** Starting delay in milliseconds (default: 1000ms) */
289
+ initialDelayMs: number;
290
+ /** Maximum delay cap in milliseconds (default: 30000ms) */
291
+ maxDelayMs: number;
292
+ /** Exponential backoff multiplier (default: 2) */
293
+ backoffMultiplier: number;
294
+ /** Random jitter factor 0-1 (default: 0.3) */
295
+ jitterFactor: number;
296
+ /** Maximum retry attempts, -1 for infinite (default: -1) */
297
+ maxRetries: number;
298
+ }
299
+ /** Default reconnection configuration */
300
+ declare const DEFAULT_BRIDGE_RECONNECTION_CONFIG: IIIReconnectionConfig;
301
+ /** Default invocation timeout in milliseconds */
302
+ declare const DEFAULT_INVOCATION_TIMEOUT_MS = 30000;
303
+ //#endregion
304
+ //#region src/telemetry-system/types.d.ts
305
+ /** Configuration for WebSocket reconnection behavior */
306
+ interface ReconnectionConfig {
307
+ /** Starting delay in milliseconds (default: 1000ms) */
308
+ initialDelayMs: number;
309
+ /** Maximum delay cap in milliseconds (default: 30000ms) */
310
+ maxDelayMs: number;
311
+ /** Exponential backoff multiplier (default: 2) */
312
+ backoffMultiplier: number;
313
+ /** Random jitter factor 0-1 (default: 0.3) */
314
+ jitterFactor: number;
315
+ /** Maximum retry attempts, -1 for infinite (default: -1) */
316
+ maxRetries: number;
317
+ }
318
+ /** Configuration for OpenTelemetry initialization. */
319
+ interface OtelConfig {
320
+ /** Whether OpenTelemetry export is enabled. Defaults to true. Set to false or OTEL_ENABLED=false/0/no/off to disable. */
321
+ enabled?: boolean;
322
+ /** The service name to report. Defaults to OTEL_SERVICE_NAME or "iii-node". */
323
+ serviceName?: string;
324
+ /** The service version to report. Defaults to SERVICE_VERSION env var or "unknown". */
325
+ serviceVersion?: string;
326
+ /** The service namespace to report. Defaults to SERVICE_NAMESPACE env var. */
327
+ serviceNamespace?: string;
328
+ /** The service instance ID to report. Defaults to SERVICE_INSTANCE_ID env var or auto-generated UUID. */
329
+ serviceInstanceId?: string;
330
+ /** III Engine WebSocket URL. Defaults to III_URL or "ws://localhost:49134". */
331
+ engineWsUrl?: string;
332
+ /** OpenTelemetry instrumentations to register (e.g., PrismaInstrumentation). */
333
+ instrumentations?: Instrumentation[];
334
+ /** Whether OpenTelemetry metrics export is enabled. Defaults to true. Set to false or OTEL_METRICS_ENABLED=false/0/no/off to disable. */
335
+ metricsEnabled?: boolean;
336
+ /** Metrics export interval in milliseconds. Defaults to 60000 (60 seconds). */
337
+ metricsExportIntervalMs?: number;
338
+ /** Log processor flush delay in milliseconds. Defaults to 100ms. */
339
+ logsFlushIntervalMs?: number;
340
+ /** Maximum number of log records exported per batch. Defaults to 1. */
341
+ logsBatchSize?: number;
342
+ /** Whether to auto-instrument globalThis.fetch calls. Defaults to true. Works on Node.js, Bun, and Deno. Set to false to disable. */
343
+ fetchInstrumentationEnabled?: boolean;
344
+ /** Optional reconnection configuration for the WebSocket connection. */
345
+ reconnectionConfig?: Partial<ReconnectionConfig>;
346
+ }
347
+ //#endregion
348
+ //#region src/telemetry-system/context.d.ts
349
+ /**
350
+ * Extract the current trace ID from the active span context.
351
+ */
352
+ declare function currentTraceId(): string | undefined;
353
+ /**
354
+ * Extract the current span ID from the active span context.
355
+ */
356
+ declare function currentSpanId(): string | undefined;
357
+ /**
358
+ * Inject the current trace context into a W3C traceparent header string.
359
+ */
360
+ declare function injectTraceparent(): string | undefined;
361
+ /**
362
+ * Extract a trace context from a W3C traceparent header string.
363
+ */
364
+ declare function extractTraceparent(traceparent: string): Context;
365
+ /**
366
+ * Inject the current baggage into a W3C baggage header string.
367
+ */
368
+ declare function injectBaggage(): string | undefined;
369
+ /**
370
+ * Extract baggage from a W3C baggage header string.
371
+ */
372
+ declare function extractBaggage(baggage: string): Context;
373
+ /**
374
+ * Extract both trace context and baggage from their respective headers.
375
+ */
376
+ declare function extractContext(traceparent?: string, baggage?: string): Context;
377
+ /**
378
+ * Get a baggage entry from the current context.
379
+ */
380
+ declare function getBaggageEntry(key: string): string | undefined;
381
+ /**
382
+ * Set a baggage entry in the current context.
383
+ */
384
+ declare function setBaggageEntry(key: string, value: string): Context;
385
+ /**
386
+ * Remove a baggage entry from the current context.
387
+ */
388
+ declare function removeBaggageEntry(key: string): Context;
389
+ /**
390
+ * Get all baggage entries from the current context.
391
+ */
392
+ declare function getAllBaggage(): Record<string, string>;
393
+ //#endregion
394
+ //#region src/telemetry-system/index.d.ts
395
+ /**
396
+ * Initialize OpenTelemetry with the given configuration.
397
+ * This should be called once at application startup.
398
+ */
399
+ declare function initOtel(config?: OtelConfig): void;
400
+ /**
401
+ * Shutdown OpenTelemetry, flushing any pending data.
402
+ */
403
+ declare function shutdownOtel(): Promise<void>;
404
+ /**
405
+ * Get the OpenTelemetry tracer instance.
406
+ */
407
+ declare function getTracer(): Tracer | null;
408
+ /**
409
+ * Get the OpenTelemetry meter instance.
410
+ */
411
+ declare function getMeter(): Meter$1 | null;
412
+ /**
413
+ * Get the OpenTelemetry logger instance.
414
+ */
415
+ declare function getLogger(): Logger | null;
416
+ /**
417
+ * Start a new span with the given name and run the callback within it.
418
+ */
419
+ declare function withSpan<T>(name: string, options: {
420
+ kind?: SpanKind;
421
+ traceparent?: string;
422
+ }, fn: (span: Span) => Promise<T>): Promise<T>;
423
+ //#endregion
424
+ //#region src/triggers.d.ts
425
+ /**
426
+ * Configuration passed to a trigger handler when a trigger instance is
427
+ * registered or unregistered.
428
+ *
429
+ * @typeParam TConfig - Type of the trigger-specific configuration.
430
+ */
431
+ type TriggerConfig<TConfig> = {
432
+ /** Trigger instance ID. */id: string; /** Function to invoke when the trigger fires. */
433
+ function_id: string; /** Trigger-specific configuration. */
434
+ config: TConfig;
435
+ };
436
+ /**
437
+ * Handler interface for custom trigger types. Passed to
438
+ * `ISdk.registerTriggerType`.
439
+ *
440
+ * @typeParam TConfig - Type of the trigger-specific configuration.
441
+ *
442
+ * @example
443
+ * ```typescript
444
+ * const handler: TriggerHandler<{ interval: number }> = {
445
+ * async registerTrigger({ id, function_id, config }) {
446
+ * // Set up periodic invocation
447
+ * },
448
+ * async unregisterTrigger({ id, function_id, config }) {
449
+ * // Clean up
450
+ * },
451
+ * }
452
+ * ```
453
+ */
454
+ type TriggerHandler<TConfig> = {
455
+ /** Called when a trigger instance is registered. */registerTrigger(config: TriggerConfig<TConfig>): Promise<void>; /** Called when a trigger instance is unregistered. */
456
+ unregisterTrigger(config: TriggerConfig<TConfig>): Promise<void>;
457
+ };
458
+ //#endregion
459
+ //#region src/types.d.ts
460
+ /**
461
+ * Async function handler for a registered function. Receives the invocation
462
+ * payload and returns the result.
463
+ *
464
+ * @typeParam TInput - Type of the invocation payload.
465
+ * @typeParam TOutput - Type of the return value.
466
+ *
467
+ * @example
468
+ * ```typescript
469
+ * const handler: RemoteFunctionHandler<{ name: string }, { message: string }> =
470
+ * async (data) => ({ message: `Hello, ${data.name}!` })
471
+ * ```
472
+ */
473
+ type RemoteFunctionHandler<TInput = any, TOutput = any> = (data: TInput) => Promise<TOutput>;
474
+ /** OTEL Log Event from the engine */
475
+ type OtelLogEvent = {
476
+ /** Timestamp in Unix nanoseconds */timestamp_unix_nano: number; /** Observed timestamp in Unix nanoseconds */
477
+ observed_timestamp_unix_nano: number; /** OTEL severity number (1-24): TRACE=1-4, DEBUG=5-8, INFO=9-12, WARN=13-16, ERROR=17-20, FATAL=21-24 */
478
+ severity_number: number; /** Severity text (e.g., "INFO", "WARN", "ERROR") */
479
+ severity_text: string; /** Log message body */
480
+ body: string; /** Structured attributes */
481
+ attributes: Record<string, unknown>; /** Trace ID for correlation (if available) */
482
+ trace_id?: string; /** Span ID for correlation (if available) */
483
+ span_id?: string; /** Resource attributes from the emitting service */
484
+ resource: Record<string, string>; /** Service name that emitted the log */
485
+ service_name: string; /** Instrumentation scope name (if available) */
486
+ instrumentation_scope_name?: string; /** Instrumentation scope version (if available) */
487
+ instrumentation_scope_version?: string;
488
+ };
489
+ type RegisterTriggerInput = Omit<RegisterTriggerMessage, 'message_type' | 'id'>;
490
+ type RegisterServiceInput = Omit<RegisterServiceMessage, 'message_type'>;
491
+ type RegisterFunctionInput = Omit<RegisterFunctionMessage, 'message_type'>;
492
+ type RegisterTriggerTypeInput = Omit<RegisterTriggerTypeMessage, 'message_type'>;
493
+ type FunctionsAvailableCallback = (functions: FunctionInfo[]) => void;
494
+ interface ISdk {
495
+ /**
496
+ * Registers a new trigger. A trigger is a way to invoke a function when a certain event occurs.
497
+ * @param trigger - The trigger to register
498
+ * @returns A trigger object that can be used to unregister the trigger
499
+ *
500
+ * @example
501
+ * ```typescript
502
+ * const trigger = iii.registerTrigger({
503
+ * type: 'cron',
504
+ * function_id: 'my-service::process-batch',
505
+ * config: { schedule: '*\/5 * * * *' },
506
+ * })
507
+ *
508
+ * // Later, remove the trigger
509
+ * trigger.unregister()
510
+ * ```
511
+ */
512
+ registerTrigger(trigger: RegisterTriggerInput): Trigger;
513
+ /**
514
+ * Registers a new function with a local handler.
515
+ * @param func - The function to register
516
+ * @param handler - The handler for local execution
517
+ * @returns A handle that can be used to unregister the function
518
+ *
519
+ * @example
520
+ * ```typescript
521
+ * const ref = iii.registerFunction(
522
+ * { id: 'greet', description: 'Returns a greeting' },
523
+ * async (data: { name: string }) => ({ message: `Hello, ${data.name}!` }),
524
+ * )
525
+ *
526
+ * // Later, remove the function
527
+ * ref.unregister()
528
+ * ```
529
+ */
530
+ /**
531
+ * Registers a new service.
532
+ * @param message - The service to register
533
+ */
534
+ registerService(message: RegisterServiceInput): void;
535
+ registerFunction(func: RegisterFunctionInput, handler: RemoteFunctionHandler): FunctionRef;
536
+ /**
537
+ * Registers a new function with an HTTP invocation config (Lambda, Cloudflare Workers, etc.).
538
+ * @param func - The function to register
539
+ * @param invocation - HTTP invocation config
540
+ * @returns A handle that can be used to unregister the function
541
+ *
542
+ * @example
543
+ * ```typescript
544
+ * const ref = iii.registerFunction(
545
+ * { id: 'external::my-lambda', description: 'Proxied Lambda function' },
546
+ * {
547
+ * url: 'https://abc123.lambda-url.us-east-1.on.aws',
548
+ * method: 'POST',
549
+ * timeout_ms: 30_000,
550
+ * auth: { type: 'bearer', token_key: 'LAMBDA_AUTH_TOKEN' },
551
+ * },
552
+ * )
553
+ * ```
554
+ */
555
+ registerFunction(func: RegisterFunctionInput, invocation: HttpInvocationConfig): FunctionRef;
556
+ /**
557
+ * Invokes a function using a request object.
558
+ *
559
+ * @param request - The trigger request containing function_id, payload, and optional action/timeout
560
+ * @returns The result of the function
561
+ *
562
+ * @example
563
+ * ```typescript
564
+ * // Synchronous invocation
565
+ * const result = await iii.trigger<{ name: string }, { message: string }>({
566
+ * function_id: 'greet',
567
+ * payload: { name: 'World' },
568
+ * timeoutMs: 5000,
569
+ * })
570
+ * console.log(result.message) // "Hello, World!"
571
+ *
572
+ * // Fire-and-forget
573
+ * await iii.trigger({
574
+ * function_id: 'send-email',
575
+ * payload: { to: 'user@example.com' },
576
+ * action: TriggerAction.Void(),
577
+ * })
578
+ *
579
+ * // Enqueue for async processing
580
+ * const receipt = await iii.trigger({
581
+ * function_id: 'process-order',
582
+ * payload: { orderId: '123' },
583
+ * action: TriggerAction.Enqueue({ queue: 'orders' }),
584
+ * })
585
+ * ```
586
+ */
587
+ trigger<TInput, TOutput>(request: TriggerRequest<TInput>): Promise<TOutput>;
588
+ /**
589
+ * Lists all registered functions.
590
+ *
591
+ * @example
592
+ * ```typescript
593
+ * const functions = await iii.listFunctions()
594
+ * for (const fn of functions) {
595
+ * console.log(`${fn.function_id}: ${fn.description}`)
596
+ * }
597
+ * ```
598
+ */
599
+ listFunctions(): Promise<FunctionInfo[]>;
600
+ /**
601
+ * Lists all registered triggers.
602
+ * @param includeInternal - Whether to include internal triggers (default: false)
603
+ */
604
+ listTriggers(includeInternal?: boolean): Promise<TriggerInfo[]>;
605
+ /**
606
+ * Registers a new trigger type. A trigger type is a way to invoke a function when a certain event occurs.
607
+ * @param triggerType - The trigger type to register
608
+ * @param handler - The handler for the trigger type
609
+ * @returns A trigger type object that can be used to unregister the trigger type
610
+ *
611
+ * @example
612
+ * ```typescript
613
+ * type CronConfig = { schedule: string }
614
+ *
615
+ * iii.registerTriggerType<CronConfig>(
616
+ * { id: 'cron', description: 'Fires on a cron schedule' },
617
+ * {
618
+ * async registerTrigger({ id, function_id, config }) {
619
+ * startCronJob(id, config.schedule, () =>
620
+ * iii.trigger({ function_id, payload: {} }),
621
+ * )
622
+ * },
623
+ * async unregisterTrigger({ id }) {
624
+ * stopCronJob(id)
625
+ * },
626
+ * },
627
+ * )
628
+ * ```
629
+ */
630
+ registerTriggerType<TConfig>(triggerType: RegisterTriggerTypeInput, handler: TriggerHandler<TConfig>): void;
631
+ /**
632
+ * Unregisters a trigger type.
633
+ * @param triggerType - The trigger type to unregister
634
+ *
635
+ * @example
636
+ * ```typescript
637
+ * iii.unregisterTriggerType({ id: 'cron', description: 'Fires on a cron schedule' })
638
+ * ```
639
+ */
640
+ unregisterTriggerType(triggerType: RegisterTriggerTypeInput): void;
641
+ /**
642
+ * Creates a streaming channel pair for worker-to-worker data transfer.
643
+ * Returns a Channel with a local writer/reader and serializable refs that
644
+ * can be passed as fields in the invocation data to other functions.
645
+ *
646
+ * @param bufferSize - Optional buffer size for the channel (default: 64)
647
+ * @returns A Channel with writer, reader, and their serializable refs
648
+ *
649
+ * @example
650
+ * ```typescript
651
+ * const channel = await iii.createChannel()
652
+ *
653
+ * // Pass the writer ref to another function
654
+ * await iii.trigger({
655
+ * function_id: 'stream-producer',
656
+ * payload: { outputChannel: channel.writerRef },
657
+ * })
658
+ *
659
+ * // Read data locally
660
+ * channel.reader.onMessage((msg) => {
661
+ * console.log('Received:', msg)
662
+ * })
663
+ * ```
664
+ */
665
+ createChannel(bufferSize?: number): Promise<Channel>;
666
+ /**
667
+ * Creates a new stream implementation.
668
+ *
669
+ * This overrides the default stream implementation.
670
+ *
671
+ * @param streamName - The name of the stream
672
+ * @param stream - The stream implementation
673
+ *
674
+ * @example
675
+ * ```typescript
676
+ * const redisStream: IStream<UserSession> = {
677
+ * async get({ group_id, item_id }) {
678
+ * return JSON.parse(await redis.get(`${group_id}:${item_id}`) ?? 'null')
679
+ * },
680
+ * async set({ group_id, item_id, data }) {
681
+ * const old = await this.get({ stream_name: 'sessions', group_id, item_id })
682
+ * await redis.set(`${group_id}:${item_id}`, JSON.stringify(data))
683
+ * return { old_value: old ?? undefined, new_value: data }
684
+ * },
685
+ * async delete({ group_id, item_id }) {
686
+ * const old = await this.get({ stream_name: 'sessions', group_id, item_id })
687
+ * await redis.del(`${group_id}:${item_id}`)
688
+ * return { old_value: old ?? undefined }
689
+ * },
690
+ * async list({ group_id }) { return [] },
691
+ * async listGroups() { return [] },
692
+ * async update({ group_id, item_id, ops }) { return { new_value: {} } },
693
+ * }
694
+ *
695
+ * iii.createStream('sessions', redisStream)
696
+ * ```
697
+ */
698
+ createStream<TData>(streamName: string, stream: IStream<TData>): void;
699
+ /**
700
+ * Registers a callback to receive the current functions list
701
+ * when the engine announces changes.
702
+ *
703
+ * @example
704
+ * ```typescript
705
+ * const unsubscribe = iii.onFunctionsAvailable((functions) => {
706
+ * console.log(`${functions.length} functions available:`)
707
+ * for (const fn of functions) {
708
+ * console.log(` - ${fn.function_id}`)
709
+ * }
710
+ * })
711
+ *
712
+ * // Later, stop listening
713
+ * unsubscribe()
714
+ * ```
715
+ */
716
+ onFunctionsAvailable(callback: FunctionsAvailableCallback): () => void;
717
+ /**
718
+ * Gracefully shutdown the iii, cleaning up all resources.
719
+ *
720
+ * @example
721
+ * ```typescript
722
+ * process.on('SIGTERM', async () => {
723
+ * await iii.shutdown()
724
+ * process.exit(0)
725
+ * })
726
+ * ```
727
+ */
728
+ shutdown(): Promise<void>;
729
+ }
730
+ /**
731
+ * Handle returned by {@link ISdk.registerTrigger}. Use `unregister()` to
732
+ * remove the trigger from the engine.
733
+ */
734
+ type Trigger = {
735
+ /** Removes this trigger from the engine. */unregister(): void;
736
+ };
737
+ /**
738
+ * Handle returned by {@link ISdk.registerFunction}. Contains the function's
739
+ * `id` and an `unregister()` method.
740
+ */
741
+ type FunctionRef = {
742
+ /** The unique function identifier. */id: string; /** Removes this function from the engine. */
743
+ unregister: () => void;
744
+ };
745
+ /**
746
+ * A streaming channel pair for worker-to-worker data transfer. Created via
747
+ * {@link ISdk.createChannel}.
748
+ */
749
+ type Channel = {
750
+ /** Writer end of the channel. */writer: ChannelWriter; /** Reader end of the channel. */
751
+ reader: ChannelReader; /** Serializable reference to the writer (can be sent to other workers). */
752
+ writerRef: StreamChannelRef; /** Serializable reference to the reader (can be sent to other workers). */
753
+ readerRef: StreamChannelRef;
754
+ };
755
+ type InternalHttpRequest<TBody = unknown> = {
756
+ path_params: Record<string, string>;
757
+ query_params: Record<string, string | string[]>;
758
+ body: TBody;
759
+ headers: Record<string, string | string[]>;
760
+ method: string;
761
+ response: ChannelWriter;
762
+ request_body: ChannelReader;
763
+ };
764
+ /**
765
+ * Response object passed to HTTP function handlers. Use `status()` and
766
+ * `headers()` to set response metadata, write to `stream` for streaming
767
+ * responses, and call `close()` when done.
768
+ */
769
+ type HttpResponse = {
770
+ /** Set the HTTP status code. */status: (statusCode: number) => void; /** Set response headers. */
771
+ headers: (headers: Record<string, string>) => void; /** Writable stream for the response body. */
772
+ stream: NodeJS.WritableStream; /** Close the response. */
773
+ close: () => void;
774
+ };
775
+ /**
776
+ * Incoming HTTP request received by a function registered with an HTTP trigger.
777
+ *
778
+ * @typeParam TBody - Type of the parsed request body.
779
+ */
780
+ type HttpRequest<TBody = unknown> = Omit<InternalHttpRequest<TBody>, 'response'>;
781
+ /**
782
+ * Alias for {@link HttpRequest}. Represents an incoming API request.
783
+ *
784
+ * @typeParam TBody - Type of the parsed request body.
785
+ */
786
+ type ApiRequest<TBody = unknown> = HttpRequest<TBody>;
787
+ /**
788
+ * Structured API response returned from HTTP function handlers.
789
+ *
790
+ * @typeParam TStatus - HTTP status code literal type.
791
+ * @typeParam TBody - Type of the response body.
792
+ *
793
+ * @example
794
+ * ```typescript
795
+ * const response: ApiResponse = {
796
+ * status_code: 200,
797
+ * headers: { 'content-type': 'application/json' },
798
+ * body: { message: 'ok' },
799
+ * }
800
+ * ```
801
+ */
802
+ type ApiResponse<TStatus extends number = number, TBody = string | Buffer | Record<string, unknown>> = {
803
+ /** HTTP status code. */status_code: TStatus; /** Response headers. */
804
+ headers?: Record<string, string>; /** Response body. */
805
+ body?: TBody;
806
+ };
807
+ //#endregion
808
+ //#region src/utils.d.ts
809
+ /**
810
+ * Safely stringify a value, handling circular references, BigInt, and other edge cases.
811
+ * Returns "[unserializable]" if serialization fails for any reason.
812
+ */
813
+ declare function safeStringify(value: unknown): string;
814
+ /**
815
+ * Helper that wraps an HTTP-style handler (with separate `req`/`res` arguments)
816
+ * into the function handler format expected by the SDK.
817
+ *
818
+ * @param callback - Async handler receiving an {@link HttpRequest} and {@link HttpResponse}.
819
+ * @returns A function handler compatible with {@link ISdk.registerFunction}.
820
+ *
821
+ * @example
822
+ * ```typescript
823
+ * import { http } from 'iii-sdk'
824
+ *
825
+ * iii.registerFunction(
826
+ * { id: 'my-api' },
827
+ * http(async (req, res) => {
828
+ * res.status(200)
829
+ * res.headers({ 'content-type': 'application/json' })
830
+ * res.stream.end(JSON.stringify({ hello: 'world' }))
831
+ * res.close()
832
+ * }),
833
+ * )
834
+ * ```
835
+ */
836
+ declare const http: (callback: (req: HttpRequest, res: HttpResponse) => Promise<void | ApiResponse>) => (req: InternalHttpRequest) => Promise<void | ApiResponse>;
837
+ //#endregion
838
+ export { ChannelWriter as $, shutdownOtel as A, injectTraceparent as B, SeverityNumber 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 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 };
839
+ //# sourceMappingURL=utils-BvWlFlLq.d.cts.map