iii-sdk 0.4.1 → 0.8.2

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.
package/LICENSE.spdx ADDED
@@ -0,0 +1,22 @@
1
+ SPDXVersion: SPDX-2.1
2
+ DataLicense: CC0-1.0
3
+ PackageName: iii
4
+ DataFormat: SPDXRef-1
5
+ PackageSupplier: Organization: Motia LLC
6
+ PackageHomePage: https://iii.dev
7
+ PackageLicenseDeclared: Elastic-2.0
8
+ PackageLicenseDeclared: Apache-2.0
9
+ PackageCopyrightText: 2024-present, Motia LLC
10
+ PackageSummary: <text>iii is a single engine with three primitives (Function, Trigger, Discovery)
11
+ that replaces API frameworks, task queues, cron schedulers, pub/sub, state stores,
12
+ and observability pipelines.
13
+ </text>
14
+ PackageComment: <text>The engine runtime (engine/) is licensed under Elastic License 2.0.
15
+ All other components (sdk/, cli/, console/, frameworks/, docs/, website/)
16
+ are licensed under Apache License 2.0.
17
+ </text>
18
+ Created: 2024-01-01T00:00:00Z
19
+ PackageDownloadLocation: git://github.com/iii-hq/iii
20
+ PackageDownloadLocation: git+https://github.com/iii-hq/iii.git
21
+ PackageDownloadLocation: git+ssh://github.com/iii-hq/iii.git
22
+ Creator: Organization: Motia LLC
package/README.md CHANGED
@@ -1,100 +1,87 @@
1
- # III SDK for Node.js
1
+ # iii-sdk
2
2
 
3
- ## Installation
3
+ Node.js / TypeScript SDK for the [iii engine](https://github.com/iii-hq/iii).
4
+
5
+ [![npm](https://img.shields.io/npm/v/iii-sdk)](https://www.npmjs.com/package/iii-sdk)
6
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](../../../LICENSE)
7
+
8
+ ## Install
4
9
 
5
10
  ```bash
6
11
  npm install iii-sdk
7
12
  ```
8
13
 
9
- ## Usage
14
+ ## Hello World
10
15
 
11
16
  ```javascript
12
- import { III } from 'iii-sdk'
17
+ import { init } from 'iii-sdk'
13
18
 
14
- /**
15
- * Make sure the III Core Instance is up and Running on the given URL.
16
- */
17
- const iii = new III(process.env.III_BRIDGE_URL ?? 'ws://localhost:49134')
19
+ const iii = init('ws://localhost:49134')
18
20
 
19
- iii.registerFunction({ id: 'myFunction' }, (req) => {
20
- return { status_code: 200, body: { message: 'Hello, world!' } }
21
+ iii.registerFunction({ id: 'greet' }, async (input) => {
22
+ return { message: `Hello, ${input.name}!` }
21
23
  })
22
24
 
23
25
  iii.registerTrigger({
24
26
  type: 'http',
25
- function_id: 'myFunction',
26
- config: { api_path: 'myApiPath', http_method: 'POST' },
27
+ function_id: 'greet',
28
+ config: { api_path: '/greet', http_method: 'POST' },
27
29
  })
30
+
31
+ const result = await iii.trigger('greet', { name: 'world' })
28
32
  ```
29
33
 
30
- ### Registering Functions
34
+ ## API
31
35
 
32
- III Allows you to register functions that can be invoked by other services.
36
+ | Operation | Signature | Description |
37
+ | ------------------------ | ---------------------------------------------------- | ------------------------------------------------------------ |
38
+ | Initialize | `init(url, options?)` | Create and connect to the engine. Returns an `ISdk` instance |
39
+ | Register function | `iii.registerFunction({ id }, handler)` | Register a function that can be invoked by name |
40
+ | Register trigger | `iii.registerTrigger({ type, function_id, config })` | Bind a trigger (HTTP, cron, queue, etc.) to a function |
41
+ | Invoke (await) | `await iii.trigger(id, data, timeoutMs?)` | Invoke a function and wait for the result |
42
+ | Invoke (fire-and-forget) | `iii.triggerVoid(id, data)` | Invoke a function without waiting (fire-and-forget) |
43
+
44
+ ### Registering Functions
33
45
 
34
46
  ```javascript
35
- iii.registerFunction({ id: 'myFunction' }, (req) => {
36
- // ... do something
37
- return { status_code: 200, body: { message: 'Hello, world!' } }
47
+ iii.registerFunction({ id: 'orders.create' }, async (input) => {
48
+ return { status_code: 201, body: { id: '123', item: input.body.item } }
38
49
  })
39
50
  ```
40
51
 
41
52
  ### Registering Triggers
42
53
 
43
- III Allows you to register triggers that can be invoked by other services.
44
-
45
54
  ```javascript
46
55
  iii.registerTrigger({
47
56
  type: 'http',
48
- function_id: 'myFunction',
49
- config: { api_path: 'myApiPath', http_method: 'POST' },
57
+ function_id: 'orders.create',
58
+ config: { api_path: '/orders', http_method: 'POST' },
50
59
  })
51
60
  ```
52
61
 
53
- ### Registering Trigger Types
54
-
55
- Triggers are mostly created by III Core Modules, but you can also create your own triggers
62
+ ### Invoking Functions
56
63
 
57
64
  ```javascript
58
- iii.registerTrigger_type(
59
- {
60
- /**
61
- * This is the id of the trigger type, it's unique.
62
- * Then, you can register a trigger by calling the registerTrigger method.
63
- */
64
- id: 'myTrigger_type',
65
- description: 'My trigger type',
66
- },
67
- {
68
- /**
69
- * Trigger config has: id, function_id, and config.
70
- * Your logic should know what to do with the config.
71
- */
72
- registerTrigger: async (config) => {
73
- // ... do something
74
- },
75
- unregisterTrigger: async (config) => {
76
- // ... do something
77
- },
78
- },
79
- )
80
- ```
65
+ const result = await iii.trigger('orders.create', { item: 'widget' })
81
66
 
82
- ### Invoking Functions
67
+ iii.triggerVoid('analytics.track', { event: 'page_view' })
68
+ ```
83
69
 
84
- III Allows you to invoke functions, they can be functions from the Core Modules or
85
- functions registered by workers.
70
+ ## Node Modules
86
71
 
87
- ```javascript
88
- const result = await iii.call('myFunction', { param1: 'value1' })
89
- console.log(result)
90
- ```
72
+ | Import | What it provides |
73
+ | ------------------- | ------------------------------------- |
74
+ | `iii-sdk` | Core SDK (`init`, types) |
75
+ | `iii-sdk/stream` | Stream client for real-time state |
76
+ | `iii-sdk/state` | State client for key-value operations |
77
+ | `iii-sdk/telemetry` | OpenTelemetry integration |
91
78
 
92
- ### Invoking Functions Async
79
+ ## Deprecated
93
80
 
94
- III Allows you to invoke functions asynchronously, they can be functions from the Core Modules or functions registered by workers.
81
+ `call()` and `callVoid()` are deprecated aliases for `trigger()` and `triggerVoid()`. They still work but will be removed in a future release.
95
82
 
96
- ```javascript
97
- iii.callVoid('myFunction', { param1: 'value1' })
98
- ```
83
+ ## Resources
99
84
 
100
- This means the Engine won't hold the execution of the function, it will return immediately. Which means the function will be executed in the background.
85
+ - [Documentation](https://iii.dev/docs)
86
+ - [iii Engine](https://github.com/iii-hq/iii)
87
+ - [Examples](https://github.com/iii-hq/iii-examples)
package/dist/index.cjs CHANGED
@@ -25,14 +25,13 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
25
25
  }) : target, mod));
26
26
 
27
27
  //#endregion
28
- const require_otel_worker_gauges = require('./otel-worker-gauges-wK5b_eLY.cjs');
28
+ const require_utils = require('./utils-BJTjoUdq.cjs');
29
29
  let __opentelemetry_api = require("@opentelemetry/api");
30
30
  let node_module = require("node:module");
31
31
  let node_os = require("node:os");
32
32
  node_os = __toESM(node_os);
33
33
  let ws = require("ws");
34
34
  let node_stream = require("node:stream");
35
- let node_async_hooks = require("node:async_hooks");
36
35
  let __opentelemetry_api_logs = require("@opentelemetry/api-logs");
37
36
 
38
37
  //#region src/channels.ts
@@ -185,75 +184,6 @@ let MessageType = /* @__PURE__ */ function(MessageType$1) {
185
184
  return MessageType$1;
186
185
  }({});
187
186
 
188
- //#endregion
189
- //#region src/logger.ts
190
- var Logger = class {
191
- get otelLogger() {
192
- if (!this._otelLogger) this._otelLogger = require_otel_worker_gauges.getLogger();
193
- return this._otelLogger;
194
- }
195
- constructor(traceId, serviceName, spanId) {
196
- this.traceId = traceId;
197
- this.serviceName = serviceName;
198
- this.spanId = spanId;
199
- this._otelLogger = null;
200
- }
201
- emit(message, severity, data) {
202
- const attributes = {};
203
- if (this.traceId) attributes.trace_id = this.traceId;
204
- if (this.spanId) attributes.span_id = this.spanId;
205
- if (this.serviceName) attributes["service.name"] = this.serviceName;
206
- if (data !== void 0) attributes["log.data"] = typeof data === "string" ? data : require_otel_worker_gauges.safeStringify(data);
207
- if (this.otelLogger) this.otelLogger.emit({
208
- severityNumber: severity,
209
- body: message,
210
- attributes: Object.keys(attributes).length > 0 ? attributes : void 0
211
- });
212
- else switch (severity) {
213
- case __opentelemetry_api_logs.SeverityNumber.DEBUG:
214
- console.debug(message, data);
215
- break;
216
- case __opentelemetry_api_logs.SeverityNumber.INFO:
217
- console.info(message, data);
218
- break;
219
- case __opentelemetry_api_logs.SeverityNumber.WARN:
220
- console.warn(message, data);
221
- break;
222
- case __opentelemetry_api_logs.SeverityNumber.ERROR:
223
- console.error(message, data);
224
- break;
225
- default: console.log(message, data);
226
- }
227
- }
228
- info(message, data) {
229
- this.emit(message, __opentelemetry_api_logs.SeverityNumber.INFO, data);
230
- }
231
- warn(message, data) {
232
- this.emit(message, __opentelemetry_api_logs.SeverityNumber.WARN, data);
233
- }
234
- error(message, data) {
235
- this.emit(message, __opentelemetry_api_logs.SeverityNumber.ERROR, data);
236
- }
237
- debug(message, data) {
238
- this.emit(message, __opentelemetry_api_logs.SeverityNumber.DEBUG, data);
239
- }
240
- };
241
-
242
- //#endregion
243
- //#region src/context.ts
244
- const globalStorage = new node_async_hooks.AsyncLocalStorage();
245
- const withContext = async (fn, ctx) => {
246
- const currentOtelContext = __opentelemetry_api.context.active();
247
- return globalStorage.run(ctx, async () => {
248
- return __opentelemetry_api.context.with(currentOtelContext, async () => await fn(ctx));
249
- });
250
- };
251
- const getContext = () => {
252
- const store = globalStorage.getStore();
253
- if (store) return store;
254
- return { logger: new Logger() };
255
- };
256
-
257
187
  //#endregion
258
188
  //#region src/iii.ts
259
189
  const { version: SDK_VERSION } = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href)("../package.json");
@@ -268,7 +198,6 @@ var Sdk = class {
268
198
  this.address = address;
269
199
  this.options = options;
270
200
  this.functions = /* @__PURE__ */ new Map();
271
- this.httpFunctions = /* @__PURE__ */ new Map();
272
201
  this.services = /* @__PURE__ */ new Map();
273
202
  this.invocations = /* @__PURE__ */ new Map();
274
203
  this.triggers = /* @__PURE__ */ new Map();
@@ -315,59 +244,50 @@ var Sdk = class {
315
244
  this.triggers.delete(id);
316
245
  } };
317
246
  };
318
- this.registerFunction = (message, handler) => {
247
+ this.registerFunction = (message, handlerOrInvocation) => {
319
248
  if (!message.id || message.id.trim() === "") throw new Error("id is required");
320
- if (this.httpFunctions.has(message.id)) throw new Error(`function id already registered: ${message.id}`);
321
- this.sendMessage(MessageType.RegisterFunction, message, true);
322
- this.functions.set(message.id, {
323
- message: {
324
- ...message,
325
- message_type: MessageType.RegisterFunction
326
- },
327
- handler: async (input, traceparent, baggage) => {
328
- if (require_otel_worker_gauges.getTracer()) {
329
- const parentContext = require_otel_worker_gauges.extractContext(traceparent, baggage);
330
- return __opentelemetry_api.context.with(parentContext, () => require_otel_worker_gauges.withSpan(`call ${message.id}`, { kind: __opentelemetry_api.SpanKind.SERVER }, async (span) => {
331
- const traceId = require_otel_worker_gauges.currentTraceId() ?? crypto.randomUUID();
332
- const spanId = require_otel_worker_gauges.currentSpanId();
333
- return withContext(async () => await handler(input), {
334
- logger: new Logger(traceId, message.id, spanId),
335
- trace: span
336
- });
337
- }));
338
- }
339
- return withContext(async () => await handler(input), { logger: new Logger(crypto.randomUUID(), message.id) });
340
- }
341
- });
342
- return {
343
- id: message.id,
344
- unregister: () => {
345
- this.sendMessage(MessageType.UnregisterFunction, { id: message.id }, true);
346
- this.functions.delete(message.id);
347
- }
348
- };
349
- };
350
- this.registerHttpFunction = (id, config) => {
351
- if (!id || id.trim() === "") throw new Error("id is required");
352
- if (this.functions.has(id) || this.httpFunctions.has(id)) throw new Error(`function id already registered: ${id}`);
353
- const message = {
249
+ if (this.functions.has(message.id)) throw new Error(`function id already registered: ${message.id}`);
250
+ const isHandler = typeof handlerOrInvocation === "function";
251
+ const fullMessage = isHandler ? {
252
+ ...message,
253
+ message_type: MessageType.RegisterFunction
254
+ } : {
255
+ ...message,
354
256
  message_type: MessageType.RegisterFunction,
355
- id,
356
257
  invocation: {
357
- url: config.url,
358
- method: config.method ?? "POST",
359
- timeout_ms: config.timeout_ms,
360
- headers: config.headers,
361
- auth: config.auth
258
+ url: handlerOrInvocation.url,
259
+ method: handlerOrInvocation.method ?? "POST",
260
+ timeout_ms: handlerOrInvocation.timeout_ms,
261
+ headers: handlerOrInvocation.headers,
262
+ auth: handlerOrInvocation.auth
362
263
  }
363
264
  };
364
- this.sendMessage(MessageType.RegisterFunction, message, true);
365
- this.httpFunctions.set(id, message);
265
+ this.sendMessage(MessageType.RegisterFunction, fullMessage, true);
266
+ if (isHandler) {
267
+ const handler = handlerOrInvocation;
268
+ this.functions.set(message.id, {
269
+ message: fullMessage,
270
+ handler: async (input, traceparent, baggage) => {
271
+ if (require_utils.getTracer()) {
272
+ const parentContext = require_utils.extractContext(traceparent, baggage);
273
+ return __opentelemetry_api.context.with(parentContext, () => require_utils.withSpan(`call ${message.id}`, { kind: __opentelemetry_api.SpanKind.SERVER }, async () => await handler(input)));
274
+ }
275
+ const traceId = crypto.randomUUID().replace(/-/g, "");
276
+ const spanId = crypto.randomUUID().replace(/-/g, "").slice(0, 16);
277
+ const syntheticSpan = __opentelemetry_api.trace.wrapSpanContext({
278
+ traceId,
279
+ spanId,
280
+ traceFlags: 1
281
+ });
282
+ return __opentelemetry_api.context.with(__opentelemetry_api.trace.setSpan(__opentelemetry_api.context.active(), syntheticSpan), async () => await handler(input));
283
+ }
284
+ });
285
+ } else this.functions.set(message.id, { message: fullMessage });
366
286
  return {
367
- id,
287
+ id: message.id,
368
288
  unregister: () => {
369
- this.sendMessage(MessageType.UnregisterFunction, { id }, true);
370
- this.httpFunctions.delete(id);
289
+ this.sendMessage(MessageType.UnregisterFunction, { id: message.id }, true);
290
+ this.functions.delete(message.id);
371
291
  }
372
292
  };
373
293
  };
@@ -389,8 +309,8 @@ var Sdk = class {
389
309
  };
390
310
  this.trigger = async (function_id, data, timeoutMs) => {
391
311
  const invocation_id = crypto.randomUUID();
392
- const traceparent = require_otel_worker_gauges.injectTraceparent();
393
- const baggage = require_otel_worker_gauges.injectBaggage();
312
+ const traceparent = require_utils.injectTraceparent();
313
+ const baggage = require_utils.injectBaggage();
394
314
  const effectiveTimeout = timeoutMs ?? this.invocationTimeoutMs;
395
315
  return new Promise((resolve, reject) => {
396
316
  const timeout = setTimeout(() => {
@@ -420,8 +340,8 @@ var Sdk = class {
420
340
  });
421
341
  };
422
342
  this.triggerVoid = (function_id, data) => {
423
- const traceparent = require_otel_worker_gauges.injectTraceparent();
424
- const baggage = require_otel_worker_gauges.injectBaggage();
343
+ const traceparent = require_utils.injectTraceparent();
344
+ const baggage = require_utils.injectBaggage();
425
345
  this.sendMessage(MessageType.InvokeFunction, {
426
346
  function_id,
427
347
  data,
@@ -432,10 +352,10 @@ var Sdk = class {
432
352
  this.call = async (function_id, data, timeoutMs) => this.trigger(function_id, data, timeoutMs);
433
353
  this.callVoid = (function_id, data) => this.triggerVoid(function_id, data);
434
354
  this.listFunctions = async () => {
435
- return (await this.trigger(require_otel_worker_gauges.EngineFunctions.LIST_FUNCTIONS, {})).functions;
355
+ return (await this.trigger(require_utils.EngineFunctions.LIST_FUNCTIONS, {})).functions;
436
356
  };
437
357
  this.listWorkers = async () => {
438
- return (await this.trigger(require_otel_worker_gauges.EngineFunctions.LIST_WORKERS, {})).workers;
358
+ return (await this.trigger(require_utils.EngineFunctions.LIST_WORKERS, {})).workers;
439
359
  };
440
360
  this.createStream = (streamName, stream) => {
441
361
  this.registerFunction({ id: `stream::get(${streamName})` }, stream.get.bind(stream));
@@ -456,7 +376,7 @@ var Sdk = class {
456
376
  return null;
457
377
  });
458
378
  this.functionsAvailableTrigger = this.registerTrigger({
459
- type: require_otel_worker_gauges.EngineTriggers.FUNCTIONS_AVAILABLE,
379
+ type: require_utils.EngineTriggers.FUNCTIONS_AVAILABLE,
460
380
  function_id,
461
381
  config: {}
462
382
  });
@@ -487,7 +407,7 @@ var Sdk = class {
487
407
  return null;
488
408
  });
489
409
  this.logTrigger = this.registerTrigger({
490
- type: require_otel_worker_gauges.EngineTriggers.LOG,
410
+ type: require_utils.EngineTriggers.LOG,
491
411
  function_id,
492
412
  config: {
493
413
  level: "all",
@@ -514,7 +434,7 @@ var Sdk = class {
514
434
  this.shutdown = async () => {
515
435
  this.isShuttingDown = true;
516
436
  this.stopMetricsReporting();
517
- await require_otel_worker_gauges.shutdownOtel();
437
+ await require_utils.shutdownOtel();
518
438
  this.clearReconnectTimeout();
519
439
  for (const [_id, invocation] of this.invocations) {
520
440
  if (invocation.timeout) clearTimeout(invocation.timeout);
@@ -531,12 +451,12 @@ var Sdk = class {
531
451
  };
532
452
  this.workerName = options?.workerName ?? getDefaultWorkerName();
533
453
  this.metricsReportingEnabled = options?.enableMetricsReporting ?? true;
534
- this.invocationTimeoutMs = options?.invocationTimeoutMs ?? require_otel_worker_gauges.DEFAULT_INVOCATION_TIMEOUT_MS;
454
+ this.invocationTimeoutMs = options?.invocationTimeoutMs ?? require_utils.DEFAULT_INVOCATION_TIMEOUT_MS;
535
455
  this.reconnectionConfig = {
536
- ...require_otel_worker_gauges.DEFAULT_BRIDGE_RECONNECTION_CONFIG,
456
+ ...require_utils.DEFAULT_BRIDGE_RECONNECTION_CONFIG,
537
457
  ...options?.reconnectionConfig
538
458
  };
539
- require_otel_worker_gauges.initOtel({
459
+ require_utils.initOtel({
540
460
  ...options?.otel,
541
461
  engineWsUrl: this.address
542
462
  });
@@ -545,11 +465,12 @@ var Sdk = class {
545
465
  registerWorkerMetadata() {
546
466
  const telemetryOpts = this.options?.telemetry;
547
467
  const language = telemetryOpts?.language ?? Intl.DateTimeFormat().resolvedOptions().locale ?? process.env.LANG?.split(".")[0];
548
- this.triggerVoid(require_otel_worker_gauges.EngineFunctions.REGISTER_WORKER, {
468
+ this.triggerVoid(require_utils.EngineFunctions.REGISTER_WORKER, {
549
469
  runtime: "node",
550
470
  version: SDK_VERSION,
551
471
  name: this.workerName,
552
472
  os: getOsInfo(),
473
+ pid: process.pid,
553
474
  telemetry: {
554
475
  language,
555
476
  project_name: telemetryOpts?.project_name,
@@ -608,18 +529,18 @@ var Sdk = class {
608
529
  }
609
530
  startMetricsReporting() {
610
531
  if (!this.metricsReportingEnabled || !this.workerId) return;
611
- const meter = require_otel_worker_gauges.getMeter();
532
+ const meter = require_utils.getMeter();
612
533
  if (!meter) {
613
534
  console.warn("[iii] Worker metrics disabled: OpenTelemetry not initialized. Call initOtel() with metricsEnabled: true before creating the iii.");
614
535
  return;
615
536
  }
616
- require_otel_worker_gauges.registerWorkerGauges(meter, {
537
+ require_utils.registerWorkerGauges(meter, {
617
538
  workerId: this.workerId,
618
539
  workerName: this.workerName
619
540
  });
620
541
  }
621
542
  stopMetricsReporting() {
622
- require_otel_worker_gauges.stopWorkerGauges();
543
+ require_utils.stopWorkerGauges();
623
544
  }
624
545
  onSocketClose() {
625
546
  this.ws?.removeAllListeners();
@@ -643,9 +564,6 @@ var Sdk = class {
643
564
  this.functions.forEach(({ message }) => {
644
565
  this.sendMessage(MessageType.RegisterFunction, message, true);
645
566
  });
646
- this.httpFunctions.forEach((message) => {
647
- this.sendMessage(MessageType.RegisterFunction, message, true);
648
- });
649
567
  this.triggers.forEach((trigger) => {
650
568
  this.sendMessage(MessageType.RegisterTrigger, trigger, true);
651
569
  });
@@ -706,7 +624,7 @@ var Sdk = class {
706
624
  else if (!skipIfClosed) this.messagesToSend.push(wireMessage);
707
625
  }
708
626
  logError(message, error) {
709
- const otelLogger = require_otel_worker_gauges.getLogger();
627
+ const otelLogger = require_utils.getLogger();
710
628
  const errorMessage = error instanceof Error ? error.message : String(error ?? "");
711
629
  if (otelLogger) otelLogger.emit({
712
630
  severityNumber: __opentelemetry_api_logs.SeverityNumber.ERROR,
@@ -735,7 +653,7 @@ var Sdk = class {
735
653
  this.invocations.delete(invocation_id);
736
654
  }
737
655
  resolveChannelValue(value) {
738
- if (require_otel_worker_gauges.isChannelRef(value)) return value.direction === "read" ? new ChannelReader(this.address, value) : new ChannelWriter(this.address, value);
656
+ if (require_utils.isChannelRef(value)) return value.direction === "read" ? new ChannelReader(this.address, value) : new ChannelWriter(this.address, value);
739
657
  if (Array.isArray(value)) return value.map((item) => this.resolveChannelValue(item));
740
658
  if (value !== null && typeof value === "object") {
741
659
  const out = {};
@@ -746,10 +664,10 @@ var Sdk = class {
746
664
  }
747
665
  async onInvokeFunction(invocation_id, function_id, input, traceparent, baggage) {
748
666
  const fn = this.functions.get(function_id);
749
- const getResponseTraceparent = () => require_otel_worker_gauges.injectTraceparent() ?? traceparent;
750
- const getResponseBaggage = () => require_otel_worker_gauges.injectBaggage() ?? baggage;
667
+ const getResponseTraceparent = () => require_utils.injectTraceparent() ?? traceparent;
668
+ const getResponseBaggage = () => require_utils.injectBaggage() ?? baggage;
751
669
  const resolvedInput = this.resolveChannelValue(input);
752
- if (fn) {
670
+ if (fn?.handler) {
753
671
  if (!invocation_id) {
754
672
  try {
755
673
  await fn.handler(resolvedInput, traceparent, baggage);
@@ -779,16 +697,20 @@ var Sdk = class {
779
697
  baggage: getResponseBaggage()
780
698
  });
781
699
  }
782
- } else this.sendMessage(MessageType.InvocationResult, {
783
- invocation_id,
784
- function_id,
785
- error: {
786
- code: "function_not_found",
787
- message: "Function not found"
788
- },
789
- traceparent,
790
- baggage
791
- });
700
+ } else {
701
+ const errorCode = fn ? "function_not_invokable" : "function_not_found";
702
+ const errorMessage = fn ? "Function is HTTP-invoked and cannot be invoked locally" : "Function not found";
703
+ if (invocation_id) this.sendMessage(MessageType.InvocationResult, {
704
+ invocation_id,
705
+ function_id,
706
+ error: {
707
+ code: errorCode,
708
+ message: errorMessage
709
+ },
710
+ traceparent,
711
+ baggage
712
+ });
713
+ }
792
714
  }
793
715
  async onRegisterTrigger(message) {
794
716
  const { trigger_type, id, function_id, config } = message;
@@ -855,15 +777,69 @@ var Sdk = class {
855
777
  }
856
778
  }
857
779
  };
858
- const init = (address, options) => new Sdk(address, options);
780
+ const registerWorker = (address, options) => new Sdk(address, options);
781
+
782
+ //#endregion
783
+ //#region src/logger.ts
784
+ var Logger = class {
785
+ get otelLogger() {
786
+ if (!this._otelLogger) this._otelLogger = require_utils.getLogger();
787
+ return this._otelLogger;
788
+ }
789
+ constructor(traceId, serviceName, spanId) {
790
+ this.traceId = traceId;
791
+ this.serviceName = serviceName;
792
+ this.spanId = spanId;
793
+ this._otelLogger = null;
794
+ }
795
+ emit(message, severity, data) {
796
+ const attributes = {};
797
+ const traceId = this.traceId ?? require_utils.currentTraceId();
798
+ const spanId = this.spanId ?? require_utils.currentSpanId();
799
+ if (traceId) attributes.trace_id = traceId;
800
+ if (spanId) attributes.span_id = spanId;
801
+ if (this.serviceName) attributes["service.name"] = this.serviceName;
802
+ if (data !== void 0) attributes["log.data"] = data;
803
+ if (this.otelLogger) this.otelLogger.emit({
804
+ severityNumber: severity,
805
+ body: message,
806
+ attributes: Object.keys(attributes).length > 0 ? attributes : void 0
807
+ });
808
+ else switch (severity) {
809
+ case __opentelemetry_api_logs.SeverityNumber.DEBUG:
810
+ console.debug(message, data);
811
+ break;
812
+ case __opentelemetry_api_logs.SeverityNumber.INFO:
813
+ console.info(message, data);
814
+ break;
815
+ case __opentelemetry_api_logs.SeverityNumber.WARN:
816
+ console.warn(message, data);
817
+ break;
818
+ case __opentelemetry_api_logs.SeverityNumber.ERROR:
819
+ console.error(message, data);
820
+ break;
821
+ default: console.log(message, data);
822
+ }
823
+ }
824
+ info(message, data) {
825
+ this.emit(message, __opentelemetry_api_logs.SeverityNumber.INFO, data);
826
+ }
827
+ warn(message, data) {
828
+ this.emit(message, __opentelemetry_api_logs.SeverityNumber.WARN, data);
829
+ }
830
+ error(message, data) {
831
+ this.emit(message, __opentelemetry_api_logs.SeverityNumber.ERROR, data);
832
+ }
833
+ debug(message, data) {
834
+ this.emit(message, __opentelemetry_api_logs.SeverityNumber.DEBUG, data);
835
+ }
836
+ };
859
837
 
860
838
  //#endregion
861
839
  exports.ChannelReader = ChannelReader;
862
840
  exports.ChannelWriter = ChannelWriter;
863
841
  exports.Logger = Logger;
864
842
  exports.__toESM = __toESM;
865
- exports.getContext = getContext;
866
- exports.http = require_otel_worker_gauges.http;
867
- exports.init = init;
868
- exports.withContext = withContext;
843
+ exports.http = require_utils.http;
844
+ exports.registerWorker = registerWorker;
869
845
  //# sourceMappingURL=index.cjs.map