iii-sdk 0.20.0 → 0.21.1-next.1

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 (41) hide show
  1. package/dist/channel.cjs +1 -1
  2. package/dist/channel.d.cts +1 -1
  3. package/dist/channel.d.mts +1 -1
  4. package/dist/channel.mjs +1 -1
  5. package/dist/{channels-De8fNMyx.mjs → channels-D3WzAo7Z.mjs} +13 -3
  6. package/dist/channels-D3WzAo7Z.mjs.map +1 -0
  7. package/dist/{channels-ZbQzcwnN.cjs → channels-DfBRsGN1.cjs} +13 -3
  8. package/dist/channels-DfBRsGN1.cjs.map +1 -0
  9. package/dist/engine.d.cts +1 -1
  10. package/dist/engine.d.mts +1 -1
  11. package/dist/helpers.cjs +1 -1
  12. package/dist/helpers.d.cts +1 -1
  13. package/dist/helpers.d.mts +1 -1
  14. package/dist/helpers.mjs +1 -1
  15. package/dist/iii-types-6aHBgy7l.cjs.map +1 -1
  16. package/dist/iii-types-CRx2qAjB.mjs.map +1 -1
  17. package/dist/index.cjs +13 -11
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.d.cts +2 -2
  20. package/dist/index.d.cts.map +1 -1
  21. package/dist/index.d.mts +2 -2
  22. package/dist/index.d.mts.map +1 -1
  23. package/dist/index.mjs +13 -11
  24. package/dist/index.mjs.map +1 -1
  25. package/dist/internal.d.cts +1 -1
  26. package/dist/internal.d.mts +1 -1
  27. package/dist/protocol.d.cts +1 -1
  28. package/dist/protocol.d.mts +1 -1
  29. package/dist/runtime.d.cts +1 -1
  30. package/dist/runtime.d.mts +1 -1
  31. package/dist/trigger.d.cts +1 -1
  32. package/dist/trigger.d.mts +1 -1
  33. package/dist/{types-ChnmRit-.d.mts → types-BWAWo4sU.d.cts} +24 -5
  34. package/dist/types-BWAWo4sU.d.cts.map +1 -0
  35. package/dist/{types-pzKubHk_.d.cts → types-CsnoPSrN.d.mts} +24 -5
  36. package/dist/types-CsnoPSrN.d.mts.map +1 -0
  37. package/package.json +2 -2
  38. package/dist/channels-De8fNMyx.mjs.map +0 -1
  39. package/dist/channels-ZbQzcwnN.cjs.map +0 -1
  40. package/dist/types-ChnmRit-.d.mts.map +0 -1
  41. package/dist/types-pzKubHk_.d.cts.map +0 -1
package/dist/channel.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_channels = require('./channels-ZbQzcwnN.cjs');
2
+ const require_channels = require('./channels-DfBRsGN1.cjs');
3
3
 
4
4
  exports.ChannelReader = require_channels.ChannelReader;
5
5
  exports.ChannelWriter = require_channels.ChannelWriter;
@@ -1,2 +1,2 @@
1
- import { D as StreamChannelRef, t as Channel, v as ChannelReader, y as ChannelWriter } from "./types-pzKubHk_.cjs";
1
+ import { O as StreamChannelRef, t as Channel, v as ChannelReader, y as ChannelWriter } from "./types-BWAWo4sU.cjs";
2
2
  export { type Channel, ChannelReader, ChannelWriter, type StreamChannelRef };
@@ -1,2 +1,2 @@
1
- import { D as StreamChannelRef, t as Channel, v as ChannelReader, y as ChannelWriter } from "./types-ChnmRit-.mjs";
1
+ import { O as StreamChannelRef, t as Channel, v as ChannelReader, y as ChannelWriter } from "./types-CsnoPSrN.mjs";
2
2
  export { type Channel, ChannelReader, ChannelWriter, type StreamChannelRef };
package/dist/channel.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import { i as ChannelWriter, r as ChannelReader } from "./channels-De8fNMyx.mjs";
1
+ import { i as ChannelWriter, r as ChannelReader } from "./channels-D3WzAo7Z.mjs";
2
2
 
3
3
  export { ChannelReader, ChannelWriter };
@@ -76,7 +76,8 @@ var ChannelWriter = class ChannelWriter {
76
76
  });
77
77
  }
78
78
  ensureConnected() {
79
- if (this.ws) return;
79
+ if (this.ws && this.ws.readyState !== WebSocket.CLOSING && this.ws.readyState !== WebSocket.CLOSED) return;
80
+ this.wsReady = false;
80
81
  this.ws = new WebSocket(this.url);
81
82
  this.ws.on("open", () => {
82
83
  this.wsReady = true;
@@ -84,9 +85,11 @@ var ChannelWriter = class ChannelWriter {
84
85
  this.pendingMessages.length = 0;
85
86
  });
86
87
  this.ws.on("error", (err) => {
88
+ this.wsReady = false;
87
89
  this.stream.destroy(err);
88
90
  });
89
91
  this.ws.on("close", () => {
92
+ this.wsReady = false;
90
93
  if (!this.stream.destroyed) this.stream.destroy();
91
94
  });
92
95
  }
@@ -126,7 +129,14 @@ var ChannelWriter = class ChannelWriter {
126
129
  }
127
130
  sendRaw(data, callback) {
128
131
  this.ensureConnected();
129
- if (this.wsReady && this.ws) this.ws.send(data, (err) => callback(err ?? null));
132
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) try {
133
+ this.ws.send(data, (err) => callback(err ?? null));
134
+ } catch {
135
+ this.pendingMessages.push({
136
+ data,
137
+ callback
138
+ });
139
+ }
130
140
  else this.pendingMessages.push({
131
141
  data,
132
142
  callback
@@ -211,4 +221,4 @@ function buildChannelUrl(engineWsBase, channelId, accessKey, direction) {
211
221
 
212
222
  //#endregion
213
223
  export { ChannelWriter as i, ChannelItem as n, ChannelReader as r, ChannelDirection as t };
214
- //# sourceMappingURL=channels-De8fNMyx.mjs.map
224
+ //# sourceMappingURL=channels-D3WzAo7Z.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"channels-D3WzAo7Z.mjs","names":[],"sources":["../src/channels.ts"],"sourcesContent":["import { Readable, Writable } from 'node:stream'\nimport { WebSocket } from 'ws'\nimport type { StreamChannelRef } from './iii-types'\n\n/**\n * Direction of a streaming channel endpoint. Mirrors the Rust SDK's\n * `ChannelDirection` enum and matches the literal values used by\n * {@link StreamChannelRef.direction}.\n */\nexport const ChannelDirection = {\n Read: 'read',\n Write: 'write',\n} as const\nexport type ChannelDirection = (typeof ChannelDirection)[keyof typeof ChannelDirection]\n\n/**\n * Discriminated runtime tag for an item observed on a streaming channel.\n * Mirrors the Rust SDK's `ChannelItem` enum (`Text` / `Binary`). Carrier for\n * factory + type-guard helpers so callers can construct and discriminate\n * channel items without depending on Rust-specific shape.\n */\nexport type ChannelItem =\n | { type: 'text'; value: string }\n | { type: 'binary'; value: Uint8Array }\n\nexport const ChannelItem = {\n /** Construct a text channel item. */\n Text(value: string): ChannelItem {\n return { type: 'text', value }\n },\n /** Construct a binary channel item. */\n Binary(value: Uint8Array): ChannelItem {\n return { type: 'binary', value }\n },\n} as const\n\n/**\n * Write end of a streaming channel. Provides both a Node.js `Writable` stream\n * and a `sendMessage` method for sending structured text messages.\n *\n * @example\n * ```typescript\n * import { createChannel } from 'iii-sdk/helpers'\n * const channel = await createChannel(iii)\n *\n * // Stream binary data\n * channel.writer.stream.write(Buffer.from('hello'))\n * channel.writer.stream.end()\n *\n * // Or send text messages\n * channel.writer.sendMessage(JSON.stringify({ type: 'event', data: 'test' }))\n * channel.writer.close()\n * ```\n */\nexport class ChannelWriter {\n private static readonly FRAME_SIZE = 64 * 1024\n private ws: WebSocket | null = null\n private wsReady = false\n private readonly pendingMessages: {\n data: Buffer | string\n callback: (err?: Error | null) => void\n }[] = []\n /** Node.js Writable stream for binary data. */\n public readonly stream: Writable\n private readonly url: string\n\n constructor(engineWsBase: string, ref: StreamChannelRef) {\n this.url = buildChannelUrl(engineWsBase, ref.channel_id, ref.access_key, 'write')\n\n this.stream = new Writable({\n write: (chunk: Buffer, _encoding, callback) => {\n const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n this.sendChunked(buf, callback)\n },\n final: (callback) => {\n if (!this.ws) {\n callback()\n return\n }\n // Delay the close frame slightly to allow the TCP stack to flush\n // all buffered send() data. Without this, the close frame can arrive\n // at the engine before all data frames, causing data truncation.\n const doClose = () => {\n if (this.ws) {\n this.ws.close(1000, 'stream_complete')\n }\n callback()\n }\n if (this.wsReady) {\n setTimeout(doClose, 10)\n } else {\n this.ws.on('open', () => setTimeout(doClose, 10))\n }\n },\n destroy: (err, callback) => {\n if (this.ws) this.ws.terminate()\n callback(err)\n },\n })\n }\n\n private ensureConnected(): void {\n // A non-null socket is only reusable while it is still connecting or open.\n // A CLOSING/CLOSED socket is dead and must be replaced — guarding solely on\n // `this.ws` being non-null would pin a terminated socket forever, so every\n // subsequent send would target a connection that can never deliver it.\n if (\n this.ws &&\n this.ws.readyState !== WebSocket.CLOSING &&\n this.ws.readyState !== WebSocket.CLOSED\n ) {\n return\n }\n this.wsReady = false\n this.ws = new WebSocket(this.url)\n\n this.ws.on('open', () => {\n this.wsReady = true\n for (const { data, callback } of this.pendingMessages) {\n this.ws?.send(data, callback)\n }\n this.pendingMessages.length = 0\n })\n\n this.ws.on('error', (err) => {\n this.wsReady = false\n this.stream.destroy(err)\n })\n\n this.ws.on('close', () => {\n this.wsReady = false\n if (!this.stream.destroyed) {\n this.stream.destroy()\n }\n })\n }\n\n /** Send a text message through the channel. */\n sendMessage(msg: string): void {\n this.ensureConnected()\n this.sendRaw(msg, (err) => {\n if (err) this.stream.destroy(err)\n })\n }\n\n /** Close the channel writer. */\n close(): void {\n if (!this.ws) return\n const doClose = () => {\n if (this.ws) {\n this.ws.close(1000, 'channel_close')\n }\n }\n if (this.wsReady) {\n doClose()\n } else {\n this.ws.on('open', () => doClose())\n }\n }\n\n private sendChunked(data: Buffer, callback: (err?: Error | null) => void): void {\n let offset = 0\n const sendNext = (err?: Error | null): void => {\n if (err) {\n callback(err)\n return\n }\n\n if (offset >= data.length) {\n callback(null)\n return\n }\n\n const end = Math.min(offset + ChannelWriter.FRAME_SIZE, data.length)\n const part = data.subarray(offset, end)\n offset = end\n this.sendRaw(part, sendNext)\n }\n sendNext(null)\n }\n\n private sendRaw(data: Buffer | string, callback: (err?: Error | null) => void): void {\n this.ensureConnected()\n // Trust the socket's live readyState over the tracked `wsReady` flag, which\n // can stay true after a drop. Queue anything we cannot send right now — and\n // requeue a send() that throws because the socket died underneath us — so it\n // flushes on the next open instead of being lost or throwing to the caller.\n if (this.ws && this.ws.readyState === WebSocket.OPEN) {\n try {\n this.ws.send(data, (err) => callback(err ?? null))\n } catch {\n this.pendingMessages.push({ data, callback })\n }\n } else {\n this.pendingMessages.push({ data, callback })\n }\n }\n}\n\n/**\n * Read end of a streaming channel. Provides both a Node.js `Readable` stream\n * for binary data and an `onMessage` callback for structured text messages.\n *\n * @example\n * ```typescript\n * import { createChannel } from 'iii-sdk/helpers'\n * const channel = await createChannel(iii)\n *\n * // Stream binary data\n * channel.reader.stream.on('data', (chunk) => console.log(chunk))\n *\n * // Or receive text messages\n * channel.reader.onMessage((msg) => console.log('Got:', msg))\n * ```\n */\nexport class ChannelReader {\n private ws: WebSocket | null = null\n private connected = false\n private readonly messageCallbacks: Array<(msg: string) => void> = []\n /** Node.js Readable stream for binary data. */\n public readonly stream: Readable\n private readonly url: string\n\n constructor(engineWsBase: string, ref: StreamChannelRef) {\n this.url = buildChannelUrl(engineWsBase, ref.channel_id, ref.access_key, 'read')\n\n const self = this\n this.stream = new Readable({\n read() {\n self.ensureConnected()\n if (self.ws) self.ws.resume()\n },\n destroy(err, callback) {\n if (self.ws && self.ws.readyState !== WebSocket.CLOSED) {\n self.ws.terminate()\n }\n self.ws = null\n callback(err)\n },\n })\n }\n\n private ensureConnected(): void {\n if (this.connected) return\n this.connected = true\n this.ws = new WebSocket(this.url)\n\n this.ws.on('open', () => {\n ;(this.ws as unknown as { binaryType: string }).binaryType = 'nodebuffer'\n })\n\n this.ws.on('message', (data: Buffer, isBinary: boolean) => {\n if (isBinary) {\n if (!this.stream.push(data)) {\n this.ws?.pause()\n }\n } else {\n const msg = data.toString('utf-8')\n for (const cb of this.messageCallbacks) {\n cb(msg)\n }\n }\n })\n\n this.ws.on('close', () => {\n this.ws = null\n if (!this.stream.destroyed) this.stream.push(null)\n })\n\n this.ws.on('error', (err) => {\n this.stream.destroy(err)\n })\n }\n\n /** Register a callback to receive text messages from the channel. */\n onMessage(callback: (msg: string) => void): void {\n this.messageCallbacks.push(callback)\n }\n\n async readAll(): Promise<Buffer> {\n this.ensureConnected()\n const chunks: Buffer[] = []\n\n for await (const chunk of this.stream) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))\n }\n\n return Buffer.concat(chunks)\n }\n\n close(): void {\n if (this.ws && this.ws.readyState !== WebSocket.CLOSED) {\n this.ws.close(1000, 'channel_close')\n }\n }\n}\n\nfunction buildChannelUrl(\n engineWsBase: string,\n channelId: string,\n accessKey: string,\n direction: 'read' | 'write',\n): string {\n const base = engineWsBase.replace(/\\/$/, '')\n return `${base}/ws/channels/${channelId}?key=${encodeURIComponent(accessKey)}&dir=${direction}`\n}\n"],"mappings":";;;;;;;;;AASA,MAAa,mBAAmB;CAC9B,MAAM;CACN,OAAO;CACR;AAaD,MAAa,cAAc;CAEzB,KAAK,OAA4B;AAC/B,SAAO;GAAE,MAAM;GAAQ;GAAO;;CAGhC,OAAO,OAAgC;AACrC,SAAO;GAAE,MAAM;GAAU;GAAO;;CAEnC;;;;;;;;;;;;;;;;;;;AAoBD,IAAa,gBAAb,MAAa,cAAc;;oBACY,KAAK;;CAW1C,YAAY,cAAsB,KAAuB;YAV1B;iBACb;yBAIZ,EAAE;AAMN,OAAK,MAAM,gBAAgB,cAAc,IAAI,YAAY,IAAI,YAAY,QAAQ;AAEjF,OAAK,SAAS,IAAI,SAAS;GACzB,QAAQ,OAAe,WAAW,aAAa;IAC7C,MAAM,MAAM,OAAO,SAAS,MAAM,GAAG,QAAQ,OAAO,KAAK,MAAM;AAC/D,SAAK,YAAY,KAAK,SAAS;;GAEjC,QAAQ,aAAa;AACnB,QAAI,CAAC,KAAK,IAAI;AACZ,eAAU;AACV;;IAKF,MAAM,gBAAgB;AACpB,SAAI,KAAK,GACP,MAAK,GAAG,MAAM,KAAM,kBAAkB;AAExC,eAAU;;AAEZ,QAAI,KAAK,QACP,YAAW,SAAS,GAAG;QAEvB,MAAK,GAAG,GAAG,cAAc,WAAW,SAAS,GAAG,CAAC;;GAGrD,UAAU,KAAK,aAAa;AAC1B,QAAI,KAAK,GAAI,MAAK,GAAG,WAAW;AAChC,aAAS,IAAI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AG,GAAG,UAAU,QAAQ;AAC3B,QAAK,OAAO,QAAQ,IAAI;IACxB;;;CAIJ,UAAU,UAAuC;AAC/C,OAAK,iBAAiB,KAAK,SAAS;;CAGtC,MAAM,UAA2B;AAC/B,OAAK,iBAAiB;EACtB,MAAM,SAAmB,EAAE;AAE3B,aAAW,MAAM,SAAS,KAAK,OAC7B,QAAO,KAAK,OAAO,SAAS,MAAM,GAAG,QAAQ,OAAO,KAAK,MAAM,CAAC;AAGlE,SAAO,OAAO,OAAO,OAAO;;CAG9B,QAAc;AACZ,MAAI,KAAK,MAAM,KAAK,GAAG,eAAe,UAAU,OAC9C,MAAK,GAAG,MAAM,KAAM,gBAAgB;;;AAK1C,SAAS,gBACP,cACA,WACA,WACA,WACQ;AAER,QAAO,GADM,aAAa,QAAQ,OAAO,GAAG,CAC7B,eAAe,UAAU,OAAO,mBAAmB,UAAU,CAAC,OAAO"}
@@ -77,7 +77,8 @@ var ChannelWriter = class ChannelWriter {
77
77
  });
78
78
  }
79
79
  ensureConnected() {
80
- if (this.ws) return;
80
+ if (this.ws && this.ws.readyState !== ws.WebSocket.CLOSING && this.ws.readyState !== ws.WebSocket.CLOSED) return;
81
+ this.wsReady = false;
81
82
  this.ws = new ws.WebSocket(this.url);
82
83
  this.ws.on("open", () => {
83
84
  this.wsReady = true;
@@ -85,9 +86,11 @@ var ChannelWriter = class ChannelWriter {
85
86
  this.pendingMessages.length = 0;
86
87
  });
87
88
  this.ws.on("error", (err) => {
89
+ this.wsReady = false;
88
90
  this.stream.destroy(err);
89
91
  });
90
92
  this.ws.on("close", () => {
93
+ this.wsReady = false;
91
94
  if (!this.stream.destroyed) this.stream.destroy();
92
95
  });
93
96
  }
@@ -127,7 +130,14 @@ var ChannelWriter = class ChannelWriter {
127
130
  }
128
131
  sendRaw(data, callback) {
129
132
  this.ensureConnected();
130
- if (this.wsReady && this.ws) this.ws.send(data, (err) => callback(err ?? null));
133
+ if (this.ws && this.ws.readyState === ws.WebSocket.OPEN) try {
134
+ this.ws.send(data, (err) => callback(err ?? null));
135
+ } catch {
136
+ this.pendingMessages.push({
137
+ data,
138
+ callback
139
+ });
140
+ }
131
141
  else this.pendingMessages.push({
132
142
  data,
133
143
  callback
@@ -235,4 +245,4 @@ Object.defineProperty(exports, 'ChannelWriter', {
235
245
  return ChannelWriter;
236
246
  }
237
247
  });
238
- //# sourceMappingURL=channels-ZbQzcwnN.cjs.map
248
+ //# sourceMappingURL=channels-DfBRsGN1.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"channels-DfBRsGN1.cjs","names":["Writable","WebSocket","Readable"],"sources":["../src/channels.ts"],"sourcesContent":["import { Readable, Writable } from 'node:stream'\nimport { WebSocket } from 'ws'\nimport type { StreamChannelRef } from './iii-types'\n\n/**\n * Direction of a streaming channel endpoint. Mirrors the Rust SDK's\n * `ChannelDirection` enum and matches the literal values used by\n * {@link StreamChannelRef.direction}.\n */\nexport const ChannelDirection = {\n Read: 'read',\n Write: 'write',\n} as const\nexport type ChannelDirection = (typeof ChannelDirection)[keyof typeof ChannelDirection]\n\n/**\n * Discriminated runtime tag for an item observed on a streaming channel.\n * Mirrors the Rust SDK's `ChannelItem` enum (`Text` / `Binary`). Carrier for\n * factory + type-guard helpers so callers can construct and discriminate\n * channel items without depending on Rust-specific shape.\n */\nexport type ChannelItem =\n | { type: 'text'; value: string }\n | { type: 'binary'; value: Uint8Array }\n\nexport const ChannelItem = {\n /** Construct a text channel item. */\n Text(value: string): ChannelItem {\n return { type: 'text', value }\n },\n /** Construct a binary channel item. */\n Binary(value: Uint8Array): ChannelItem {\n return { type: 'binary', value }\n },\n} as const\n\n/**\n * Write end of a streaming channel. Provides both a Node.js `Writable` stream\n * and a `sendMessage` method for sending structured text messages.\n *\n * @example\n * ```typescript\n * import { createChannel } from 'iii-sdk/helpers'\n * const channel = await createChannel(iii)\n *\n * // Stream binary data\n * channel.writer.stream.write(Buffer.from('hello'))\n * channel.writer.stream.end()\n *\n * // Or send text messages\n * channel.writer.sendMessage(JSON.stringify({ type: 'event', data: 'test' }))\n * channel.writer.close()\n * ```\n */\nexport class ChannelWriter {\n private static readonly FRAME_SIZE = 64 * 1024\n private ws: WebSocket | null = null\n private wsReady = false\n private readonly pendingMessages: {\n data: Buffer | string\n callback: (err?: Error | null) => void\n }[] = []\n /** Node.js Writable stream for binary data. */\n public readonly stream: Writable\n private readonly url: string\n\n constructor(engineWsBase: string, ref: StreamChannelRef) {\n this.url = buildChannelUrl(engineWsBase, ref.channel_id, ref.access_key, 'write')\n\n this.stream = new Writable({\n write: (chunk: Buffer, _encoding, callback) => {\n const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n this.sendChunked(buf, callback)\n },\n final: (callback) => {\n if (!this.ws) {\n callback()\n return\n }\n // Delay the close frame slightly to allow the TCP stack to flush\n // all buffered send() data. Without this, the close frame can arrive\n // at the engine before all data frames, causing data truncation.\n const doClose = () => {\n if (this.ws) {\n this.ws.close(1000, 'stream_complete')\n }\n callback()\n }\n if (this.wsReady) {\n setTimeout(doClose, 10)\n } else {\n this.ws.on('open', () => setTimeout(doClose, 10))\n }\n },\n destroy: (err, callback) => {\n if (this.ws) this.ws.terminate()\n callback(err)\n },\n })\n }\n\n private ensureConnected(): void {\n // A non-null socket is only reusable while it is still connecting or open.\n // A CLOSING/CLOSED socket is dead and must be replaced — guarding solely on\n // `this.ws` being non-null would pin a terminated socket forever, so every\n // subsequent send would target a connection that can never deliver it.\n if (\n this.ws &&\n this.ws.readyState !== WebSocket.CLOSING &&\n this.ws.readyState !== WebSocket.CLOSED\n ) {\n return\n }\n this.wsReady = false\n this.ws = new WebSocket(this.url)\n\n this.ws.on('open', () => {\n this.wsReady = true\n for (const { data, callback } of this.pendingMessages) {\n this.ws?.send(data, callback)\n }\n this.pendingMessages.length = 0\n })\n\n this.ws.on('error', (err) => {\n this.wsReady = false\n this.stream.destroy(err)\n })\n\n this.ws.on('close', () => {\n this.wsReady = false\n if (!this.stream.destroyed) {\n this.stream.destroy()\n }\n })\n }\n\n /** Send a text message through the channel. */\n sendMessage(msg: string): void {\n this.ensureConnected()\n this.sendRaw(msg, (err) => {\n if (err) this.stream.destroy(err)\n })\n }\n\n /** Close the channel writer. */\n close(): void {\n if (!this.ws) return\n const doClose = () => {\n if (this.ws) {\n this.ws.close(1000, 'channel_close')\n }\n }\n if (this.wsReady) {\n doClose()\n } else {\n this.ws.on('open', () => doClose())\n }\n }\n\n private sendChunked(data: Buffer, callback: (err?: Error | null) => void): void {\n let offset = 0\n const sendNext = (err?: Error | null): void => {\n if (err) {\n callback(err)\n return\n }\n\n if (offset >= data.length) {\n callback(null)\n return\n }\n\n const end = Math.min(offset + ChannelWriter.FRAME_SIZE, data.length)\n const part = data.subarray(offset, end)\n offset = end\n this.sendRaw(part, sendNext)\n }\n sendNext(null)\n }\n\n private sendRaw(data: Buffer | string, callback: (err?: Error | null) => void): void {\n this.ensureConnected()\n // Trust the socket's live readyState over the tracked `wsReady` flag, which\n // can stay true after a drop. Queue anything we cannot send right now — and\n // requeue a send() that throws because the socket died underneath us — so it\n // flushes on the next open instead of being lost or throwing to the caller.\n if (this.ws && this.ws.readyState === WebSocket.OPEN) {\n try {\n this.ws.send(data, (err) => callback(err ?? null))\n } catch {\n this.pendingMessages.push({ data, callback })\n }\n } else {\n this.pendingMessages.push({ data, callback })\n }\n }\n}\n\n/**\n * Read end of a streaming channel. Provides both a Node.js `Readable` stream\n * for binary data and an `onMessage` callback for structured text messages.\n *\n * @example\n * ```typescript\n * import { createChannel } from 'iii-sdk/helpers'\n * const channel = await createChannel(iii)\n *\n * // Stream binary data\n * channel.reader.stream.on('data', (chunk) => console.log(chunk))\n *\n * // Or receive text messages\n * channel.reader.onMessage((msg) => console.log('Got:', msg))\n * ```\n */\nexport class ChannelReader {\n private ws: WebSocket | null = null\n private connected = false\n private readonly messageCallbacks: Array<(msg: string) => void> = []\n /** Node.js Readable stream for binary data. */\n public readonly stream: Readable\n private readonly url: string\n\n constructor(engineWsBase: string, ref: StreamChannelRef) {\n this.url = buildChannelUrl(engineWsBase, ref.channel_id, ref.access_key, 'read')\n\n const self = this\n this.stream = new Readable({\n read() {\n self.ensureConnected()\n if (self.ws) self.ws.resume()\n },\n destroy(err, callback) {\n if (self.ws && self.ws.readyState !== WebSocket.CLOSED) {\n self.ws.terminate()\n }\n self.ws = null\n callback(err)\n },\n })\n }\n\n private ensureConnected(): void {\n if (this.connected) return\n this.connected = true\n this.ws = new WebSocket(this.url)\n\n this.ws.on('open', () => {\n ;(this.ws as unknown as { binaryType: string }).binaryType = 'nodebuffer'\n })\n\n this.ws.on('message', (data: Buffer, isBinary: boolean) => {\n if (isBinary) {\n if (!this.stream.push(data)) {\n this.ws?.pause()\n }\n } else {\n const msg = data.toString('utf-8')\n for (const cb of this.messageCallbacks) {\n cb(msg)\n }\n }\n })\n\n this.ws.on('close', () => {\n this.ws = null\n if (!this.stream.destroyed) this.stream.push(null)\n })\n\n this.ws.on('error', (err) => {\n this.stream.destroy(err)\n })\n }\n\n /** Register a callback to receive text messages from the channel. */\n onMessage(callback: (msg: string) => void): void {\n this.messageCallbacks.push(callback)\n }\n\n async readAll(): Promise<Buffer> {\n this.ensureConnected()\n const chunks: Buffer[] = []\n\n for await (const chunk of this.stream) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))\n }\n\n return Buffer.concat(chunks)\n }\n\n close(): void {\n if (this.ws && this.ws.readyState !== WebSocket.CLOSED) {\n this.ws.close(1000, 'channel_close')\n }\n }\n}\n\nfunction buildChannelUrl(\n engineWsBase: string,\n channelId: string,\n accessKey: string,\n direction: 'read' | 'write',\n): string {\n const base = engineWsBase.replace(/\\/$/, '')\n return `${base}/ws/channels/${channelId}?key=${encodeURIComponent(accessKey)}&dir=${direction}`\n}\n"],"mappings":";;;;;;;;;;AASA,MAAa,mBAAmB;CAC9B,MAAM;CACN,OAAO;CACR;AAaD,MAAa,cAAc;CAEzB,KAAK,OAA4B;AAC/B,SAAO;GAAE,MAAM;G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cACA,WACA,WACA,WACQ;AAER,QAAO,GADM,aAAa,QAAQ,OAAO,GAAG,CAC7B,eAAe,UAAU,OAAO,mBAAmB,UAAU,CAAC,OAAO"}
package/dist/engine.d.cts CHANGED
@@ -1,3 +1,3 @@
1
- import { l as RemoteFunctionHandler } from "./types-pzKubHk_.cjs";
1
+ import { l as RemoteFunctionHandler } from "./types-BWAWo4sU.cjs";
2
2
  import { n as EngineTriggers, t as EngineFunctions } from "./iii-constants-BqXp8xSN.cjs";
3
3
  export { EngineFunctions, EngineTriggers, type RemoteFunctionHandler };
package/dist/engine.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { l as RemoteFunctionHandler } from "./types-ChnmRit-.mjs";
1
+ import { l as RemoteFunctionHandler } from "./types-CsnoPSrN.mjs";
2
2
  import { n as EngineTriggers, t as EngineFunctions } from "./iii-constants-Baptl8nm.mjs";
3
3
  export { EngineFunctions, EngineTriggers, type RemoteFunctionHandler };
package/dist/helpers.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_utils = require('./utils-63wxBJg-.cjs');
3
- const require_channels = require('./channels-ZbQzcwnN.cjs');
3
+ const require_channels = require('./channels-DfBRsGN1.cjs');
4
4
 
5
5
  //#region src/helpers.ts
6
6
  /**
@@ -1,4 +1,4 @@
1
- import { D as StreamChannelRef, _ as ChannelItem, g as ChannelDirection, r as IIIClient, t as Channel } from "./types-pzKubHk_.cjs";
1
+ import { O as StreamChannelRef, _ as ChannelItem, g as ChannelDirection, r as IIIClient, t as Channel } from "./types-BWAWo4sU.cjs";
2
2
  import { IStream } from "./stream.cjs";
3
3
 
4
4
  //#region src/utils.d.ts
@@ -1,4 +1,4 @@
1
- import { D as StreamChannelRef, _ as ChannelItem, g as ChannelDirection, r as IIIClient, t as Channel } from "./types-ChnmRit-.mjs";
1
+ import { O as StreamChannelRef, _ as ChannelItem, g as ChannelDirection, r as IIIClient, t as Channel } from "./types-CsnoPSrN.mjs";
2
2
  import { IStream } from "./stream.mjs";
3
3
 
4
4
  //#region src/utils.d.ts
package/dist/helpers.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { n as ChannelItem, t as ChannelDirection } from "./channels-De8fNMyx.mjs";
1
+ import { n as ChannelItem, t as ChannelDirection } from "./channels-D3WzAo7Z.mjs";
2
2
  import { n as extractChannelRefs, r as isChannelRef } from "./utils-8G4hHqvZ.mjs";
3
3
 
4
4
  //#region src/helpers.ts
@@ -1 +1 @@
1
- {"version":3,"file":"iii-types-6aHBgy7l.cjs","names":[],"sources":["../src/iii-types.ts"],"sourcesContent":["import type { HttpInvocationConfig } from '@iii-dev/helpers/http'\n\nexport enum MessageType {\n RegisterFunction = 'registerfunction',\n UnregisterFunction = 'unregisterfunction',\n InvokeFunction = 'invokefunction',\n InvocationResult = 'invocationresult',\n RegisterTriggerType = 'registertriggertype',\n RegisterTrigger = 'registertrigger',\n UnregisterTrigger = 'unregistertrigger',\n UnregisterTriggerType = 'unregistertriggertype',\n TriggerRegistrationResult = 'triggerregistrationresult',\n WorkerRegistered = 'workerregistered',\n}\n\nexport type RegisterTriggerTypeMessage = {\n message_type: MessageType.RegisterTriggerType\n id: string\n description: string\n}\n\nexport type UnregisterTriggerTypeMessage = {\n message_type: MessageType.UnregisterTriggerType\n id: string\n}\n\nexport type UnregisterTriggerMessage = {\n message_type: MessageType.UnregisterTrigger\n id: string\n type?: string\n}\n\nexport type ErrorBody = {\n code: string\n message: string\n stacktrace?: string\n}\n\nexport type TriggerRegistrationResultMessage = {\n message_type: MessageType.TriggerRegistrationResult\n id: string\n type: string\n function_id: string\n error?: ErrorBody\n}\n\nexport type RegisterTriggerMessage = {\n message_type: MessageType.RegisterTrigger\n id: string\n type: string\n function_id: string\n config: unknown\n metadata?: Record<string, unknown>\n}\n\nexport type RegisterFunctionFormat = {\n /**\n * The name of the parameter\n */\n name?: string\n /**\n * The description of the parameter\n */\n description?: string\n /**\n * The type of the parameter\n */\n type?: 'string' | 'number' | 'boolean' | 'object' | 'array' | 'null' | 'map' | 'integer'\n /**\n * The body of the parameter (for objects)\n */\n properties?: Record<string, unknown>\n /**\n * The items of the parameter (for arrays)\n */\n items?: unknown\n /**\n * Whether the parameter is required\n */\n required?: string[]\n [key: string]: unknown\n}\n\nexport type RegisterFunctionMessage = {\n message_type: MessageType.RegisterFunction\n /**\n * The path of the function (use :: for namespacing, e.g. external::my_lambda)\n */\n id: string\n /**\n * The description of the function\n */\n description?: string\n /**\n * The request format of the function\n */\n request_format?: RegisterFunctionFormat\n /**\n * The response format of the function\n */\n response_format?: RegisterFunctionFormat\n metadata?: Record<string, unknown>\n /**\n * HTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.)\n */\n invocation?: HttpInvocationConfig\n}\n\n/**\n * Routing action for {@link TriggerRequest}. Determines how the engine\n * handles the invocation.\n *\n * - `enqueue` -- Routes through a named queue for async processing.\n * - `void` -- Fire-and-forget, no response.\n */\nexport type TriggerAction = { type: 'enqueue'; queue: string } | { type: 'void' }\n\n/**\n * Input passed to the RBAC middleware function on every function invocation\n * through the RBAC port. The middleware can inspect, modify, or reject the\n * call before it reaches the target function.\n */\nexport type MiddlewareFunctionInput = {\n /** ID of the function being invoked. */\n function_id: string\n /** Payload sent by the caller. */\n payload: Record<string, unknown>\n /** Routing action, if any. */\n action?: TriggerAction\n /** Auth context returned by the auth function for this session. */\n context: Record<string, unknown>\n}\n\n/**\n * Request object passed to {@link IIIClient.trigger}.\n *\n * @typeParam TInput - Type of the payload.\n */\nexport type TriggerRequest<TInput = unknown> = {\n /** ID of the function to invoke. */\n function_id: string\n /** Payload to pass to the function. */\n payload: TInput\n /** Routing action. Omit for synchronous request/response. */\n action?: TriggerAction\n /** Override the default invocation timeout in milliseconds. */\n timeoutMs?: number\n}\n\nexport type InvokeFunctionMessage = {\n message_type: MessageType.InvokeFunction\n /**\n * This is optional for async invocations\n */\n invocation_id?: string\n /**\n * The path of the function\n */\n function_id: string\n /**\n * The data to pass to the function\n */\n data: unknown\n /**\n * W3C trace-context traceparent header for distributed tracing\n */\n traceparent?: string\n /**\n * W3C baggage header for cross-cutting context propagation\n */\n baggage?: string\n /**\n * Trigger action for queue routing or fire-and-forget\n */\n action?: TriggerAction\n}\n\nexport type InvocationResultMessage = {\n message_type: MessageType.InvocationResult\n /**\n * The id of the invocation\n */\n invocation_id: string\n /**\n * The path of the function\n */\n function_id: string\n result?: unknown\n error?: unknown\n /**\n * W3C trace-context traceparent header for distributed tracing\n */\n traceparent?: string\n /**\n * W3C baggage header for cross-cutting context propagation\n */\n baggage?: string\n}\n\nexport type WorkerRegisteredMessage = {\n message_type: MessageType.WorkerRegistered\n worker_id: string\n}\n\nexport type UnregisterFunctionMessage = {\n message_type: MessageType.UnregisterFunction\n id: string\n}\n\n/**\n * Serializable reference to one end of a streaming channel. Can be included\n * in invocation payloads to pass channel endpoints between workers.\n */\nexport type StreamChannelRef = {\n /** Unique channel identifier. */\n channel_id: string\n /** Access key for authentication. */\n access_key: string\n /** Whether this ref is for reading or writing. */\n direction: 'read' | 'write'\n}\n\nexport type IIIMessage =\n | RegisterFunctionMessage\n | UnregisterFunctionMessage\n | InvokeFunctionMessage\n | InvocationResultMessage\n | RegisterTriggerMessage\n | RegisterTriggerTypeMessage\n | UnregisterTriggerMessage\n | UnregisterTriggerTypeMessage\n | TriggerRegistrationResultMessage\n | WorkerRegisteredMessage\n"],"mappings":";;AAEA,IAAY,cAAL;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;KACD"}
1
+ {"version":3,"file":"iii-types-6aHBgy7l.cjs","names":[],"sources":["../src/iii-types.ts"],"sourcesContent":["import type { HttpInvocationConfig } from '@iii-dev/helpers/http'\n\n/**\n * Any JSON value: the TypeScript equivalent of the engine's arbitrary-JSON\n * wire values (Rust `serde_json::Value`). Used where the wire contract is\n * \"any JSON\", e.g. per-invocation `metadata`.\n */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue }\n\nexport enum MessageType {\n RegisterFunction = 'registerfunction',\n UnregisterFunction = 'unregisterfunction',\n InvokeFunction = 'invokefunction',\n InvocationResult = 'invocationresult',\n RegisterTriggerType = 'registertriggertype',\n RegisterTrigger = 'registertrigger',\n UnregisterTrigger = 'unregistertrigger',\n UnregisterTriggerType = 'unregistertriggertype',\n TriggerRegistrationResult = 'triggerregistrationresult',\n WorkerRegistered = 'workerregistered',\n}\n\nexport type RegisterTriggerTypeMessage = {\n message_type: MessageType.RegisterTriggerType\n id: string\n description: string\n}\n\nexport type UnregisterTriggerTypeMessage = {\n message_type: MessageType.UnregisterTriggerType\n id: string\n}\n\nexport type UnregisterTriggerMessage = {\n message_type: MessageType.UnregisterTrigger\n id: string\n type?: string\n}\n\nexport type ErrorBody = {\n code: string\n message: string\n stacktrace?: string\n}\n\nexport type TriggerRegistrationResultMessage = {\n message_type: MessageType.TriggerRegistrationResult\n id: string\n type: string\n function_id: string\n error?: ErrorBody\n}\n\nexport type RegisterTriggerMessage = {\n message_type: MessageType.RegisterTrigger\n id: string\n type: string\n function_id: string\n config: unknown\n metadata?: Record<string, unknown>\n}\n\nexport type RegisterFunctionFormat = {\n /**\n * The name of the parameter\n */\n name?: string\n /**\n * The description of the parameter\n */\n description?: string\n /**\n * The type of the parameter\n */\n type?: 'string' | 'number' | 'boolean' | 'object' | 'array' | 'null' | 'map' | 'integer'\n /**\n * The body of the parameter (for objects)\n */\n properties?: Record<string, unknown>\n /**\n * The items of the parameter (for arrays)\n */\n items?: unknown\n /**\n * Whether the parameter is required\n */\n required?: string[]\n [key: string]: unknown\n}\n\nexport type RegisterFunctionMessage = {\n message_type: MessageType.RegisterFunction\n /**\n * The path of the function (use :: for namespacing, e.g. external::my_lambda)\n */\n id: string\n /**\n * The description of the function\n */\n description?: string\n /**\n * The request format of the function\n */\n request_format?: RegisterFunctionFormat\n /**\n * The response format of the function\n */\n response_format?: RegisterFunctionFormat\n metadata?: Record<string, unknown>\n /**\n * HTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.)\n */\n invocation?: HttpInvocationConfig\n}\n\n/**\n * Routing action for {@link TriggerRequest}. Determines how the engine\n * handles the invocation.\n *\n * - `enqueue` -- Routes through a named queue for async processing.\n * - `void` -- Fire-and-forget, no response.\n */\nexport type TriggerAction = { type: 'enqueue'; queue: string } | { type: 'void' }\n\n/**\n * Input passed to the RBAC middleware function on every function invocation\n * through the RBAC port. The middleware can inspect, modify, or reject the\n * call before it reaches the target function.\n */\nexport type MiddlewareFunctionInput = {\n /** ID of the function being invoked. */\n function_id: string\n /** Payload sent by the caller. */\n payload: Record<string, unknown>\n /** Routing action, if any. */\n action?: TriggerAction\n /** Auth context returned by the auth function for this session. */\n context: Record<string, unknown>\n}\n\n/**\n * Request object passed to {@link IIIClient.trigger}.\n *\n * @typeParam TInput - Type of the payload.\n */\nexport type TriggerRequest<TInput = unknown> = {\n /** ID of the function to invoke. */\n function_id: string\n /** Payload to pass to the function. */\n payload: TInput\n /** Routing action. Omit for synchronous request/response. */\n action?: TriggerAction\n /** Override the default invocation timeout in milliseconds. */\n timeoutMs?: number\n /**\n * Optional per-invocation metadata (arbitrary JSON). Travels as a separate\n * channel from the payload and is surfaced to the target handler as a\n * dedicated argument. Omitted from the wire message when undefined.\n */\n metadata?: unknown\n}\n\nexport type InvokeFunctionMessage = {\n message_type: MessageType.InvokeFunction\n /**\n * This is optional for async invocations\n */\n invocation_id?: string\n /**\n * The path of the function\n */\n function_id: string\n /**\n * The data to pass to the function\n */\n data: unknown\n /**\n * W3C trace-context traceparent header for distributed tracing\n */\n traceparent?: string\n /**\n * W3C baggage header for cross-cutting context propagation\n */\n baggage?: string\n /**\n * Trigger action for queue routing or fire-and-forget\n */\n action?: TriggerAction\n /**\n * Optional per-invocation metadata (arbitrary JSON). Travels as a separate\n * channel from `data`. Omitted from the JSON when undefined; absence on\n * inbound means \"no metadata\" (backward compatible with older engines).\n */\n metadata?: JsonValue\n}\n\nexport type InvocationResultMessage = {\n message_type: MessageType.InvocationResult\n /**\n * The id of the invocation\n */\n invocation_id: string\n /**\n * The path of the function\n */\n function_id: string\n result?: unknown\n error?: unknown\n /**\n * W3C trace-context traceparent header for distributed tracing\n */\n traceparent?: string\n /**\n * W3C baggage header for cross-cutting context propagation\n */\n baggage?: string\n}\n\nexport type WorkerRegisteredMessage = {\n message_type: MessageType.WorkerRegistered\n worker_id: string\n}\n\nexport type UnregisterFunctionMessage = {\n message_type: MessageType.UnregisterFunction\n id: string\n}\n\n/**\n * Serializable reference to one end of a streaming channel. Can be included\n * in invocation payloads to pass channel endpoints between workers.\n */\nexport type StreamChannelRef = {\n /** Unique channel identifier. */\n channel_id: string\n /** Access key for authentication. */\n access_key: string\n /** Whether this ref is for reading or writing. */\n direction: 'read' | 'write'\n}\n\nexport type IIIMessage =\n | RegisterFunctionMessage\n | UnregisterFunctionMessage\n | InvokeFunctionMessage\n | InvocationResultMessage\n | RegisterTriggerMessage\n | RegisterTriggerTypeMessage\n | UnregisterTriggerMessage\n | UnregisterTriggerTypeMessage\n | TriggerRegistrationResultMessage\n | WorkerRegisteredMessage\n"],"mappings":";;AAeA,IAAY,cAAL;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;KACD"}
@@ -1 +1 @@
1
- {"version":3,"file":"iii-types-CRx2qAjB.mjs","names":[],"sources":["../src/iii-types.ts"],"sourcesContent":["import type { HttpInvocationConfig } from '@iii-dev/helpers/http'\n\nexport enum MessageType {\n RegisterFunction = 'registerfunction',\n UnregisterFunction = 'unregisterfunction',\n InvokeFunction = 'invokefunction',\n InvocationResult = 'invocationresult',\n RegisterTriggerType = 'registertriggertype',\n RegisterTrigger = 'registertrigger',\n UnregisterTrigger = 'unregistertrigger',\n UnregisterTriggerType = 'unregistertriggertype',\n TriggerRegistrationResult = 'triggerregistrationresult',\n WorkerRegistered = 'workerregistered',\n}\n\nexport type RegisterTriggerTypeMessage = {\n message_type: MessageType.RegisterTriggerType\n id: string\n description: string\n}\n\nexport type UnregisterTriggerTypeMessage = {\n message_type: MessageType.UnregisterTriggerType\n id: string\n}\n\nexport type UnregisterTriggerMessage = {\n message_type: MessageType.UnregisterTrigger\n id: string\n type?: string\n}\n\nexport type ErrorBody = {\n code: string\n message: string\n stacktrace?: string\n}\n\nexport type TriggerRegistrationResultMessage = {\n message_type: MessageType.TriggerRegistrationResult\n id: string\n type: string\n function_id: string\n error?: ErrorBody\n}\n\nexport type RegisterTriggerMessage = {\n message_type: MessageType.RegisterTrigger\n id: string\n type: string\n function_id: string\n config: unknown\n metadata?: Record<string, unknown>\n}\n\nexport type RegisterFunctionFormat = {\n /**\n * The name of the parameter\n */\n name?: string\n /**\n * The description of the parameter\n */\n description?: string\n /**\n * The type of the parameter\n */\n type?: 'string' | 'number' | 'boolean' | 'object' | 'array' | 'null' | 'map' | 'integer'\n /**\n * The body of the parameter (for objects)\n */\n properties?: Record<string, unknown>\n /**\n * The items of the parameter (for arrays)\n */\n items?: unknown\n /**\n * Whether the parameter is required\n */\n required?: string[]\n [key: string]: unknown\n}\n\nexport type RegisterFunctionMessage = {\n message_type: MessageType.RegisterFunction\n /**\n * The path of the function (use :: for namespacing, e.g. external::my_lambda)\n */\n id: string\n /**\n * The description of the function\n */\n description?: string\n /**\n * The request format of the function\n */\n request_format?: RegisterFunctionFormat\n /**\n * The response format of the function\n */\n response_format?: RegisterFunctionFormat\n metadata?: Record<string, unknown>\n /**\n * HTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.)\n */\n invocation?: HttpInvocationConfig\n}\n\n/**\n * Routing action for {@link TriggerRequest}. Determines how the engine\n * handles the invocation.\n *\n * - `enqueue` -- Routes through a named queue for async processing.\n * - `void` -- Fire-and-forget, no response.\n */\nexport type TriggerAction = { type: 'enqueue'; queue: string } | { type: 'void' }\n\n/**\n * Input passed to the RBAC middleware function on every function invocation\n * through the RBAC port. The middleware can inspect, modify, or reject the\n * call before it reaches the target function.\n */\nexport type MiddlewareFunctionInput = {\n /** ID of the function being invoked. */\n function_id: string\n /** Payload sent by the caller. */\n payload: Record<string, unknown>\n /** Routing action, if any. */\n action?: TriggerAction\n /** Auth context returned by the auth function for this session. */\n context: Record<string, unknown>\n}\n\n/**\n * Request object passed to {@link IIIClient.trigger}.\n *\n * @typeParam TInput - Type of the payload.\n */\nexport type TriggerRequest<TInput = unknown> = {\n /** ID of the function to invoke. */\n function_id: string\n /** Payload to pass to the function. */\n payload: TInput\n /** Routing action. Omit for synchronous request/response. */\n action?: TriggerAction\n /** Override the default invocation timeout in milliseconds. */\n timeoutMs?: number\n}\n\nexport type InvokeFunctionMessage = {\n message_type: MessageType.InvokeFunction\n /**\n * This is optional for async invocations\n */\n invocation_id?: string\n /**\n * The path of the function\n */\n function_id: string\n /**\n * The data to pass to the function\n */\n data: unknown\n /**\n * W3C trace-context traceparent header for distributed tracing\n */\n traceparent?: string\n /**\n * W3C baggage header for cross-cutting context propagation\n */\n baggage?: string\n /**\n * Trigger action for queue routing or fire-and-forget\n */\n action?: TriggerAction\n}\n\nexport type InvocationResultMessage = {\n message_type: MessageType.InvocationResult\n /**\n * The id of the invocation\n */\n invocation_id: string\n /**\n * The path of the function\n */\n function_id: string\n result?: unknown\n error?: unknown\n /**\n * W3C trace-context traceparent header for distributed tracing\n */\n traceparent?: string\n /**\n * W3C baggage header for cross-cutting context propagation\n */\n baggage?: string\n}\n\nexport type WorkerRegisteredMessage = {\n message_type: MessageType.WorkerRegistered\n worker_id: string\n}\n\nexport type UnregisterFunctionMessage = {\n message_type: MessageType.UnregisterFunction\n id: string\n}\n\n/**\n * Serializable reference to one end of a streaming channel. Can be included\n * in invocation payloads to pass channel endpoints between workers.\n */\nexport type StreamChannelRef = {\n /** Unique channel identifier. */\n channel_id: string\n /** Access key for authentication. */\n access_key: string\n /** Whether this ref is for reading or writing. */\n direction: 'read' | 'write'\n}\n\nexport type IIIMessage =\n | RegisterFunctionMessage\n | UnregisterFunctionMessage\n | InvokeFunctionMessage\n | InvocationResultMessage\n | RegisterTriggerMessage\n | RegisterTriggerTypeMessage\n | UnregisterTriggerMessage\n | UnregisterTriggerTypeMessage\n | TriggerRegistrationResultMessage\n | WorkerRegisteredMessage\n"],"mappings":";AAEA,IAAY,cAAL;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;KACD"}
1
+ {"version":3,"file":"iii-types-CRx2qAjB.mjs","names":[],"sources":["../src/iii-types.ts"],"sourcesContent":["import type { HttpInvocationConfig } from '@iii-dev/helpers/http'\n\n/**\n * Any JSON value: the TypeScript equivalent of the engine's arbitrary-JSON\n * wire values (Rust `serde_json::Value`). Used where the wire contract is\n * \"any JSON\", e.g. per-invocation `metadata`.\n */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue }\n\nexport enum MessageType {\n RegisterFunction = 'registerfunction',\n UnregisterFunction = 'unregisterfunction',\n InvokeFunction = 'invokefunction',\n InvocationResult = 'invocationresult',\n RegisterTriggerType = 'registertriggertype',\n RegisterTrigger = 'registertrigger',\n UnregisterTrigger = 'unregistertrigger',\n UnregisterTriggerType = 'unregistertriggertype',\n TriggerRegistrationResult = 'triggerregistrationresult',\n WorkerRegistered = 'workerregistered',\n}\n\nexport type RegisterTriggerTypeMessage = {\n message_type: MessageType.RegisterTriggerType\n id: string\n description: string\n}\n\nexport type UnregisterTriggerTypeMessage = {\n message_type: MessageType.UnregisterTriggerType\n id: string\n}\n\nexport type UnregisterTriggerMessage = {\n message_type: MessageType.UnregisterTrigger\n id: string\n type?: string\n}\n\nexport type ErrorBody = {\n code: string\n message: string\n stacktrace?: string\n}\n\nexport type TriggerRegistrationResultMessage = {\n message_type: MessageType.TriggerRegistrationResult\n id: string\n type: string\n function_id: string\n error?: ErrorBody\n}\n\nexport type RegisterTriggerMessage = {\n message_type: MessageType.RegisterTrigger\n id: string\n type: string\n function_id: string\n config: unknown\n metadata?: Record<string, unknown>\n}\n\nexport type RegisterFunctionFormat = {\n /**\n * The name of the parameter\n */\n name?: string\n /**\n * The description of the parameter\n */\n description?: string\n /**\n * The type of the parameter\n */\n type?: 'string' | 'number' | 'boolean' | 'object' | 'array' | 'null' | 'map' | 'integer'\n /**\n * The body of the parameter (for objects)\n */\n properties?: Record<string, unknown>\n /**\n * The items of the parameter (for arrays)\n */\n items?: unknown\n /**\n * Whether the parameter is required\n */\n required?: string[]\n [key: string]: unknown\n}\n\nexport type RegisterFunctionMessage = {\n message_type: MessageType.RegisterFunction\n /**\n * The path of the function (use :: for namespacing, e.g. external::my_lambda)\n */\n id: string\n /**\n * The description of the function\n */\n description?: string\n /**\n * The request format of the function\n */\n request_format?: RegisterFunctionFormat\n /**\n * The response format of the function\n */\n response_format?: RegisterFunctionFormat\n metadata?: Record<string, unknown>\n /**\n * HTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.)\n */\n invocation?: HttpInvocationConfig\n}\n\n/**\n * Routing action for {@link TriggerRequest}. Determines how the engine\n * handles the invocation.\n *\n * - `enqueue` -- Routes through a named queue for async processing.\n * - `void` -- Fire-and-forget, no response.\n */\nexport type TriggerAction = { type: 'enqueue'; queue: string } | { type: 'void' }\n\n/**\n * Input passed to the RBAC middleware function on every function invocation\n * through the RBAC port. The middleware can inspect, modify, or reject the\n * call before it reaches the target function.\n */\nexport type MiddlewareFunctionInput = {\n /** ID of the function being invoked. */\n function_id: string\n /** Payload sent by the caller. */\n payload: Record<string, unknown>\n /** Routing action, if any. */\n action?: TriggerAction\n /** Auth context returned by the auth function for this session. */\n context: Record<string, unknown>\n}\n\n/**\n * Request object passed to {@link IIIClient.trigger}.\n *\n * @typeParam TInput - Type of the payload.\n */\nexport type TriggerRequest<TInput = unknown> = {\n /** ID of the function to invoke. */\n function_id: string\n /** Payload to pass to the function. */\n payload: TInput\n /** Routing action. Omit for synchronous request/response. */\n action?: TriggerAction\n /** Override the default invocation timeout in milliseconds. */\n timeoutMs?: number\n /**\n * Optional per-invocation metadata (arbitrary JSON). Travels as a separate\n * channel from the payload and is surfaced to the target handler as a\n * dedicated argument. Omitted from the wire message when undefined.\n */\n metadata?: unknown\n}\n\nexport type InvokeFunctionMessage = {\n message_type: MessageType.InvokeFunction\n /**\n * This is optional for async invocations\n */\n invocation_id?: string\n /**\n * The path of the function\n */\n function_id: string\n /**\n * The data to pass to the function\n */\n data: unknown\n /**\n * W3C trace-context traceparent header for distributed tracing\n */\n traceparent?: string\n /**\n * W3C baggage header for cross-cutting context propagation\n */\n baggage?: string\n /**\n * Trigger action for queue routing or fire-and-forget\n */\n action?: TriggerAction\n /**\n * Optional per-invocation metadata (arbitrary JSON). Travels as a separate\n * channel from `data`. Omitted from the JSON when undefined; absence on\n * inbound means \"no metadata\" (backward compatible with older engines).\n */\n metadata?: JsonValue\n}\n\nexport type InvocationResultMessage = {\n message_type: MessageType.InvocationResult\n /**\n * The id of the invocation\n */\n invocation_id: string\n /**\n * The path of the function\n */\n function_id: string\n result?: unknown\n error?: unknown\n /**\n * W3C trace-context traceparent header for distributed tracing\n */\n traceparent?: string\n /**\n * W3C baggage header for cross-cutting context propagation\n */\n baggage?: string\n}\n\nexport type WorkerRegisteredMessage = {\n message_type: MessageType.WorkerRegistered\n worker_id: string\n}\n\nexport type UnregisterFunctionMessage = {\n message_type: MessageType.UnregisterFunction\n id: string\n}\n\n/**\n * Serializable reference to one end of a streaming channel. Can be included\n * in invocation payloads to pass channel endpoints between workers.\n */\nexport type StreamChannelRef = {\n /** Unique channel identifier. */\n channel_id: string\n /** Access key for authentication. */\n access_key: string\n /** Whether this ref is for reading or writing. */\n direction: 'read' | 'write'\n}\n\nexport type IIIMessage =\n | RegisterFunctionMessage\n | UnregisterFunctionMessage\n | InvokeFunctionMessage\n | InvocationResultMessage\n | RegisterTriggerMessage\n | RegisterTriggerTypeMessage\n | UnregisterTriggerMessage\n | UnregisterTriggerTypeMessage\n | TriggerRegistrationResultMessage\n | WorkerRegisteredMessage\n"],"mappings":";AAeA,IAAY,cAAL;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;KACD"}
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_utils = require('./utils-63wxBJg-.cjs');
3
3
  const require_errors = require('./errors.cjs');
4
- const require_channels = require('./channels-ZbQzcwnN.cjs');
4
+ const require_channels = require('./channels-DfBRsGN1.cjs');
5
5
  const require_iii_constants = require('./iii-constants-Br94RUNi.cjs');
6
6
  const require_iii_types = require('./iii-types-6aHBgy7l.cjs');
7
7
  let _opentelemetry_api = require("@opentelemetry/api");
@@ -113,7 +113,7 @@ var Sdk = class {
113
113
  const handler = handlerOrInvocation;
114
114
  this.functions.set(functionId, {
115
115
  message: fullMessage,
116
- handler: async (input, traceparent, baggage) => {
116
+ handler: async (input, metadata, traceparent, baggage) => {
117
117
  const tracePayloads = !(process.env.III_DISABLE_TRACE_PAYLOADS === "1" || process.env.III_DISABLE_TRACE_PAYLOADS?.toLowerCase() === "true");
118
118
  const payloadMaxBytes = (0, _iii_dev_helpers_observability.resolveMaxBytesFromEnv)();
119
119
  const runHandler = async () => {
@@ -125,7 +125,7 @@ var Sdk = class {
125
125
  });
126
126
  }
127
127
  try {
128
- const result = await handler(input);
128
+ const result = await handler(input, metadata);
129
129
  if (tracePayloads) {
130
130
  const { json, truncated } = (0, _iii_dev_helpers_observability.redactAndTruncate)(result, payloadMaxBytes);
131
131
  (0, _iii_dev_helpers_observability.recordSpanEvent)("iii.invocation.output", {
@@ -183,7 +183,7 @@ var Sdk = class {
183
183
  };
184
184
  };
185
185
  this.trigger = async (request) => {
186
- const { function_id, payload, action, timeoutMs } = request;
186
+ const { function_id, payload, action, timeoutMs, metadata } = request;
187
187
  const effectiveTimeout = timeoutMs ?? this.invocationTimeoutMs;
188
188
  if (action?.type === "void") {
189
189
  const traceparent = (0, _iii_dev_helpers_observability.injectTraceparent)();
@@ -193,7 +193,8 @@ var Sdk = class {
193
193
  data: payload,
194
194
  traceparent,
195
195
  baggage,
196
- action
196
+ action,
197
+ metadata
197
198
  });
198
199
  return;
199
200
  }
@@ -229,7 +230,8 @@ var Sdk = class {
229
230
  data: payload,
230
231
  traceparent,
231
232
  baggage,
232
- action
233
+ action,
234
+ metadata
233
235
  });
234
236
  });
235
237
  };
@@ -480,7 +482,7 @@ var Sdk = class {
480
482
  }
481
483
  return value;
482
484
  }
483
- async onInvokeFunction(invocation_id, function_id, input, traceparent, baggage) {
485
+ async onInvokeFunction(invocation_id, function_id, input, metadata, traceparent, baggage) {
484
486
  const fn = this.functions.get(function_id);
485
487
  const getResponseTraceparent = () => (0, _iii_dev_helpers_observability.injectTraceparent)() ?? traceparent;
486
488
  const getResponseBaggage = () => (0, _iii_dev_helpers_observability.injectBaggage)() ?? baggage;
@@ -488,14 +490,14 @@ var Sdk = class {
488
490
  if (fn?.handler) {
489
491
  if (!invocation_id) {
490
492
  try {
491
- await fn.handler(resolvedInput, traceparent, baggage);
493
+ await fn.handler(resolvedInput, metadata, traceparent, baggage);
492
494
  } catch (error) {
493
495
  this.logError(`Error invoking function ${function_id}`, error);
494
496
  }
495
497
  return;
496
498
  }
497
499
  try {
498
- const result = await fn.handler(resolvedInput, traceparent, baggage);
500
+ const result = await fn.handler(resolvedInput, metadata, traceparent, baggage);
499
501
  this.sendMessage(require_iii_types.MessageType.InvocationResult, {
500
502
  invocation_id,
501
503
  function_id,
@@ -609,8 +611,8 @@ var Sdk = class {
609
611
  const { invocation_id, result, error } = message;
610
612
  this.onInvocationResult(invocation_id, result, error);
611
613
  } else if (msgType === require_iii_types.MessageType.InvokeFunction) {
612
- const { invocation_id, function_id, data, traceparent, baggage } = message;
613
- this.onInvokeFunction(invocation_id, function_id, data, traceparent, baggage);
614
+ const { invocation_id, function_id, data, metadata, traceparent, baggage } = message;
615
+ this.onInvokeFunction(invocation_id, function_id, data, metadata, traceparent, baggage);
614
616
  } else if (msgType === require_iii_types.MessageType.RegisterTrigger) this.onRegisterTrigger(message);
615
617
  else if (msgType === require_iii_types.MessageType.UnregisterTrigger) this.onUnregisterTrigger(message);
616
618
  else if (msgType === require_iii_types.MessageType.TriggerRegistrationResult) this.onTriggerRegistrationResult(message);