iii-browser-sdk 0.24.6 → 0.25.0-alpha.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.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { n as isChannelRef, o as ChannelReader, r as randomUUID, s as ChannelWriter } from "./utils-nQQPFFRM.mjs";
1
+ import { a as utf8ByteLength, c as ChannelReader, i as unrefTimer, l as ChannelWriter, n as isChannelRef, r as randomUUID } from "./utils-CyT9CwWA.mjs";
2
2
 
3
3
  //#region src/errors.ts
4
4
  /**
@@ -17,6 +17,48 @@ var RegistrationRejectedError = class extends Error {
17
17
  this.owner_worker_id = init.owner_worker_id;
18
18
  }
19
19
  };
20
+ /**
21
+ * An error the SDK raises itself for an invocation, with a machine-readable
22
+ * `code`: observe delivery errors (`NOT_OWNER_DELIVERED`,
23
+ * `OBSERVER_NOT_ACTIVE`, `FILTERS_NOT_MATCHED`) and an invalid observe
24
+ * descriptor (`INVALID_OBSERVE_DESCRIPTOR`). Mirrors the Node SDK.
25
+ *
26
+ * A call the engine answers with an error still rejects with the engine's
27
+ * error body (`{ code, message, stacktrace? }`), as in earlier releases, and
28
+ * so does a locally dispatched call whose handler throws: both paths reject
29
+ * with the same value.
30
+ */
31
+ var InvocationError = class extends Error {
32
+ constructor(init) {
33
+ super(`${init.code}: ${init.message}`);
34
+ this.name = "InvocationError";
35
+ this.code = init.code;
36
+ this.function_id = init.function_id;
37
+ this.stacktrace = init.stacktrace;
38
+ }
39
+ };
40
+ /**
41
+ * Thrown by an `onObserverAdded` hook to reject an observer with a code of
42
+ * its own (`HTTP_ROUTE_CONFLICT`, `INVALID_CRON_EXPRESSION`, ...); any other
43
+ * error rejects it with `OBSERVE_REJECTED`. Also the error `ObserverHandle.ready()`
44
+ * rejects with when the observer turns `error` or `disposed`.
45
+ *
46
+ * @example
47
+ * ```typescript
48
+ * onObserverAdded(obs) {
49
+ * if (!isValidCron(obs.args.expression)) {
50
+ * throw new ObserveRejection('INVALID_CRON_EXPRESSION', 'invalid day-of-week field')
51
+ * }
52
+ * }
53
+ * ```
54
+ */
55
+ var ObserveRejection = class extends Error {
56
+ constructor(code, message) {
57
+ super(message);
58
+ this.name = "ObserveRejection";
59
+ this.code = code;
60
+ }
61
+ };
20
62
 
21
63
  //#endregion
22
64
  //#region src/iii-constants.ts
@@ -24,40 +66,2190 @@ var RegistrationRejectedError = class extends Error {
24
66
  * Constants for the III module.
25
67
  */
26
68
  /**
27
- * Engine function paths for internal operations.
28
- *
29
- * Naming note: `LIST_TRIGGERS` / `INFO_TRIGGERS` cover trigger TYPES
30
- * (templates). `LIST_REGISTERED_TRIGGERS` / `INFO_REGISTERED_TRIGGERS`
31
- * cover trigger INSTANCES (subscriber rows). The old
32
- * `engine::trigger-types::list` builtin has been removed and is now
33
- * served by `engine::triggers::list`.
69
+ * Engine function paths for internal operations.
70
+ *
71
+ * Naming note: `LIST_TRIGGERS` / `INFO_TRIGGERS` cover trigger TYPES
72
+ * (templates). `LIST_REGISTERED_TRIGGERS` / `INFO_REGISTERED_TRIGGERS`
73
+ * cover trigger INSTANCES (subscriber rows). The old
74
+ * `engine::trigger-types::list` builtin has been removed and is now
75
+ * served by `engine::triggers::list`.
76
+ */
77
+ const EngineFunctions = {
78
+ LIST_FUNCTIONS: "engine::functions::list",
79
+ INFO_FUNCTIONS: "engine::functions::info",
80
+ LIST_WORKERS: "engine::workers::list",
81
+ INFO_WORKERS: "engine::workers::info",
82
+ LIST_TRIGGERS: "engine::triggers::list",
83
+ INFO_TRIGGERS: "engine::triggers::info",
84
+ LIST_REGISTERED_TRIGGERS: "engine::registered-triggers::list",
85
+ INFO_REGISTERED_TRIGGERS: "engine::registered-triggers::info",
86
+ REGISTER_WORKER: "engine::workers::register"
87
+ };
88
+ /** Engine trigger types */
89
+ const EngineTriggers = { FUNCTIONS_AVAILABLE: "engine::functions-available" };
90
+ /** Default reconnection configuration */
91
+ const DEFAULT_BRIDGE_RECONNECTION_CONFIG = {
92
+ initialDelayMs: 1e3,
93
+ maxDelayMs: 3e4,
94
+ backoffMultiplier: 2,
95
+ jitterFactor: .3,
96
+ maxRetries: -1
97
+ };
98
+ /** Default invocation timeout in milliseconds */
99
+ const DEFAULT_INVOCATION_TIMEOUT_MS = 3e4;
100
+
101
+ //#endregion
102
+ //#region ../iii/src/filter/errors.ts
103
+ const MAX_ENCODED_BYTES = 8192;
104
+ /** Numeric literals in a filter must satisfy `|n| <= 2^53`. */
105
+ const MAX_SAFE_LITERAL = 2 ** 53;
106
+ /** A filter the language rejects. `code` is the protocol error code (protocol.md §4). */
107
+ var FilterError = class FilterError extends Error {
108
+ constructor(code, message) {
109
+ super(message);
110
+ this.name = "FilterError";
111
+ this.code = code;
112
+ }
113
+ static invalid(message) {
114
+ return new FilterError("INVALID_FILTER", message);
115
+ }
116
+ };
117
+
118
+ //#endregion
119
+ //#region ../iii/src/filter/json.ts
120
+ /**
121
+ * The filter as JSON. A filter written in JavaScript must already be JSON:
122
+ * `JSON.stringify` would silently drop or rewrite what is not (an `undefined`
123
+ * clause disappears, a `Map` or a class instance becomes `{}`, `NaN` becomes
124
+ * `null`), and a dropped clause turns a filter into one that matches more.
125
+ * So every value is checked first, and anything JSON would not carry as it is
126
+ * is `INVALID_FILTER`, naming where it is.
127
+ *
128
+ * Pure TypeScript with no Node.js APIs: the browser SDK uses this file too.
129
+ */
130
+ function where(at) {
131
+ return at === "" ? "the filter" : `\`${at}\``;
132
+ }
133
+ /** A string serde_json would refuse (a lone surrogate) is refused here too. */
134
+ function checkString(s, at, what) {
135
+ for (let i = 0; i < s.length; i++) {
136
+ const c = s.charCodeAt(i);
137
+ if (c < 55296 || c > 57343) continue;
138
+ const next = s.charCodeAt(i + 1);
139
+ if (c <= 56319 && next >= 56320 && next <= 57343) {
140
+ i++;
141
+ continue;
142
+ }
143
+ throw FilterError.invalid(`${where(at)}: ${what} holds a lone UTF-16 surrogate, which is not valid Unicode`);
144
+ }
145
+ }
146
+ /** An object JSON writes member by member: a prototype-less object or one whose prototype is a realm's `Object.prototype`. */
147
+ function isPlainObject(v) {
148
+ const proto = Object.getPrototypeOf(v);
149
+ return proto === null || Object.getPrototypeOf(proto) === null;
150
+ }
151
+ function describe(v) {
152
+ if (typeof v === "number") return String(v);
153
+ if (typeof v !== "object" || v === null) return typeof v;
154
+ const name = Object.getPrototypeOf(v)?.constructor?.name;
155
+ return typeof name === "string" && name !== "" ? `a ${name}` : "an object";
156
+ }
157
+ /**
158
+ * Checks that `src` is JSON as it stands: plain objects (own enumerable data
159
+ * properties, string keys) and dense arrays of strings, finite numbers within
160
+ * ±2^53, booleans and `null`, without cycles (a value shared by two members
161
+ * is fine), nested at most MAX_JSON_DEPTH arrays / objects. Iterative, and
162
+ * bounded by the encoded size limit (every JSON value takes at least one
163
+ * byte, so a value shared many times over is refused quickly).
164
+ */
165
+ function checkJson(src) {
166
+ const stack = [{
167
+ value: src,
168
+ at: "",
169
+ depth: 1
170
+ }];
171
+ const ancestors = /* @__PURE__ */ new Set();
172
+ let visited = 0;
173
+ while (stack.length > 0) {
174
+ const { value, at, depth, leave } = stack.pop();
175
+ if (leave) {
176
+ ancestors.delete(value);
177
+ continue;
178
+ }
179
+ if (++visited > 8192) throw FilterError.invalid(`the filter encodes to more than ${MAX_ENCODED_BYTES} bytes`);
180
+ switch (typeof value) {
181
+ case "boolean": continue;
182
+ case "string":
183
+ checkString(value, at, "a string");
184
+ continue;
185
+ case "number":
186
+ if (!Number.isFinite(value)) throw FilterError.invalid(`${where(at)}: ${value} is not a JSON number`);
187
+ if (Math.abs(value) > MAX_SAFE_LITERAL) throw FilterError.invalid(`${where(at)}: the number ${value} is outside ±2^53`);
188
+ continue;
189
+ case "object":
190
+ if (value === null) continue;
191
+ if (ancestors.has(value)) throw FilterError.invalid(`${where(at)}: a cycle (the value contains itself)`);
192
+ if (depth > 120) throw FilterError.invalid(`${where(at)}: the filter nests deeper than ${120} arrays / objects`);
193
+ ancestors.add(value);
194
+ stack.push({
195
+ value,
196
+ at,
197
+ depth,
198
+ leave: true
199
+ });
200
+ if (Array.isArray(value)) {
201
+ for (let i = 0; i < value.length; i++) {
202
+ if (!(i in value)) throw FilterError.invalid(`${where(at)}: the array has a hole at ${i}`);
203
+ stack.push({
204
+ value: value[i],
205
+ at: `${at}[${i}]`,
206
+ depth: depth + 1
207
+ });
208
+ }
209
+ continue;
210
+ }
211
+ if (!isPlainObject(value)) throw FilterError.invalid(`${where(at)}: ${describe(value)} is not a JSON object (use a plain object)`);
212
+ if (Object.getOwnPropertySymbols(value).length > 0) throw FilterError.invalid(`${where(at)}: symbol keys are not JSON`);
213
+ for (const key of Object.getOwnPropertyNames(value)) {
214
+ const member = at === "" ? key : `${at}.${key}`;
215
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
216
+ if (!descriptor?.enumerable) throw FilterError.invalid(`${where(member)}: a non-enumerable property is not JSON`);
217
+ if (!("value" in descriptor)) throw FilterError.invalid(`${where(member)}: an accessor property is not JSON`);
218
+ checkString(key, member, "the key");
219
+ stack.push({
220
+ value: descriptor.value,
221
+ at: member,
222
+ depth: depth + 1
223
+ });
224
+ }
225
+ continue;
226
+ default: throw FilterError.invalid(`${where(at)}: ${describe(value)} is not JSON`);
227
+ }
228
+ }
229
+ }
230
+ /** Freezes a parsed JSON value (iteratively): the closures compiled from it share its operands. */
231
+ function deepFreeze(value) {
232
+ const stack = [value];
233
+ while (stack.length > 0) {
234
+ const v = stack.pop();
235
+ if (v === null || typeof v !== "object" || Object.isFrozen(v)) continue;
236
+ Object.freeze(v);
237
+ for (const member of Object.values(v)) stack.push(member);
238
+ }
239
+ return value;
240
+ }
241
+
242
+ //#endregion
243
+ //#region ../iii/src/filter/value.ts
244
+ const hasEnumerable = Object.prototype.propertyIsEnumerable;
245
+ const toStringTag = Object.prototype.toString;
246
+ /** A `BigInt` read through its JSON encoding (its decimal digits) as a double; beyond the double range, `null`. */
247
+ function bigintView(b) {
248
+ const n = Number(b);
249
+ return Number.isFinite(n) ? n : null;
250
+ }
251
+ /**
252
+ * Unwraps a boxed primitive (`new Number(1)`), also one from another realm,
253
+ * by its internal slot rather than `instanceof`. Anything else is an object.
254
+ */
255
+ function unbox(v) {
256
+ try {
257
+ switch (toStringTag.call(v)) {
258
+ case "[object Number]": {
259
+ const n = Number.prototype.valueOf.call(v);
260
+ return Number.isFinite(n) ? n : null;
261
+ }
262
+ case "[object String]": return String.prototype.valueOf.call(v);
263
+ case "[object Boolean]": return Boolean.prototype.valueOf.call(v);
264
+ case "[object BigInt]": return bigintView(BigInt.prototype.valueOf.call(v));
265
+ }
266
+ } catch {}
267
+ return v;
268
+ }
269
+ /**
270
+ * One step of `JSON.stringify` (SerializeJSONProperty): `toJSON`, boxed
271
+ * primitives, non-finite numbers, and the values JSON drops. `BigInt` is read
272
+ * through its JSON encoding (its decimal digits), as a double, unless the
273
+ * program installed `BigInt.prototype.toJSON`. Objects and arrays are
274
+ * returned as they are; their members are mapped when a path steps into them.
275
+ *
276
+ * Host code runs here (`toJSON`, getters, Proxy traps) and may throw: the
277
+ * caller of the whole evaluation turns that into a non-match.
278
+ */
279
+ function jsonView(value, key) {
280
+ let v = value;
281
+ if (v !== null && (typeof v === "object" || typeof v === "function" || typeof v === "bigint")) {
282
+ const toJSON = v.toJSON;
283
+ if (typeof toJSON === "function") v = toJSON.call(v, key);
284
+ }
285
+ switch (typeof v) {
286
+ case "string":
287
+ case "boolean": return v;
288
+ case "number": return Number.isFinite(v) ? v : null;
289
+ case "bigint": return bigintView(v);
290
+ case "object": {
291
+ if (v === null) return null;
292
+ if (Array.isArray(v)) return v;
293
+ const proto = Object.getPrototypeOf(v);
294
+ if (proto === Object.prototype || proto === null) return v;
295
+ return unbox(v);
296
+ }
297
+ default: return;
298
+ }
299
+ }
300
+ /** Element `index` of an array, as JSON writes it: a member JSON drops is `null`. */
301
+ function arrayElement(array, index) {
302
+ const v = jsonView(array[index], String(index));
303
+ return v === void 0 ? null : v;
304
+ }
305
+ /** Own enumerable key `key` of an object; inherited properties do not exist. */
306
+ function objectMember(object, key) {
307
+ if (!hasEnumerable.call(object, key)) return void 0;
308
+ return jsonView(object[key], key);
309
+ }
310
+ function isObject(v) {
311
+ return v !== null && typeof v === "object" && !Array.isArray(v);
312
+ }
313
+ /**
314
+ * JSON deep equality between a mapped host value and a filter literal (plain
315
+ * JSON). Numbers compare as doubles (`1 == 1.0`, `-0 == 0`), object key order
316
+ * is ignored, array order is not, and there is no coercion between types.
317
+ * Iterative, so a deeply nested literal cannot overflow the stack.
318
+ */
319
+ function jsonEquals(host, literal) {
320
+ if (literal === null || typeof literal !== "object") return scalarEquals(host, literal);
321
+ const stack = [[host, literal]];
322
+ while (stack.length > 0) {
323
+ const [h, l] = stack.pop();
324
+ if (l === null || typeof l !== "object") {
325
+ if (!scalarEquals(h, l)) return false;
326
+ continue;
327
+ }
328
+ if (Array.isArray(l)) {
329
+ if (!Array.isArray(h) || h.length !== l.length) return false;
330
+ for (let i = 0; i < l.length; i++) stack.push([arrayElement(h, i), l[i]]);
331
+ continue;
332
+ }
333
+ if (!isObject(h)) return false;
334
+ const lit = l;
335
+ const keys = Object.keys(lit);
336
+ for (const k of keys) {
337
+ const member = objectMember(h, k);
338
+ if (member === void 0) return false;
339
+ stack.push([member, lit[k]]);
340
+ }
341
+ let present = 0;
342
+ for (const k of Object.keys(h)) if (jsonView(h[k], k) !== void 0) {
343
+ present++;
344
+ if (present > keys.length) return false;
345
+ }
346
+ if (present !== keys.length) return false;
347
+ }
348
+ return true;
349
+ }
350
+ function scalarEquals(host, literal) {
351
+ if (literal === null) return host === null;
352
+ switch (typeof literal) {
353
+ case "number":
354
+ case "string":
355
+ case "boolean": return host === literal;
356
+ default: return false;
357
+ }
358
+ }
359
+ /**
360
+ * Compares two strings by Unicode code point (UTF-8 byte order), not by
361
+ * UTF-16 code unit as `<` does: a surrogate pair (a code point above U+FFFF)
362
+ * sorts after every BMP character, including U+E000..U+FFFF.
363
+ */
364
+ function compareCodePoints(a, b) {
365
+ if (a === b) return 0;
366
+ const n = a.length < b.length ? a.length : b.length;
367
+ for (let i = 0; i < n; i++) {
368
+ let ca = a.charCodeAt(i);
369
+ let cb = b.charCodeAt(i);
370
+ if (ca !== cb) {
371
+ if (ca >= 55296 && cb >= 55296) {
372
+ ca = ca >= 57344 ? ca - 2048 : ca + 8192;
373
+ cb = cb >= 57344 ? cb - 2048 : cb + 8192;
374
+ }
375
+ return ca < cb ? -1 : 1;
376
+ }
377
+ }
378
+ return a.length < b.length ? -1 : a.length > b.length ? 1 : 0;
379
+ }
380
+ /** `$prefix`: code point by code point, so a prefix never ends inside a surrogate pair. */
381
+ function hasCodePointPrefix(s, prefix) {
382
+ if (!s.startsWith(prefix)) return false;
383
+ if (prefix.length === 0 || prefix.length === s.length) return true;
384
+ const last = prefix.charCodeAt(prefix.length - 1);
385
+ if (last < 55296 || last > 56319) return true;
386
+ const next = s.charCodeAt(prefix.length);
387
+ return next < 56320 || next > 57343;
388
+ }
389
+ /** UTF-8 byte length of a string, without `Buffer` or `TextEncoder`. */
390
+ function utf8Length(s) {
391
+ let bytes = 0;
392
+ for (let i = 0; i < s.length; i++) {
393
+ const c = s.charCodeAt(i);
394
+ if (c < 128) bytes += 1;
395
+ else if (c < 2048) bytes += 2;
396
+ else if (c >= 55296 && c <= 56319 && i + 1 < s.length) {
397
+ const d = s.charCodeAt(i + 1);
398
+ if (d >= 56320 && d <= 57343) {
399
+ bytes += 4;
400
+ i++;
401
+ } else bytes += 3;
402
+ } else bytes += 3;
403
+ }
404
+ return bytes;
405
+ }
406
+
407
+ //#endregion
408
+ //#region ../iii/src/filter/path.ts
409
+ const ROOTS = new Set([
410
+ "input",
411
+ "output",
412
+ "error",
413
+ "caller",
414
+ "metadata",
415
+ "@"
416
+ ]);
417
+ const CANONICAL_INDEX = /^(?:0|[1-9][0-9]*)$/;
418
+ function canonicalIndex(segment) {
419
+ if (segment.length > 15 || !CANONICAL_INDEX.test(segment)) return void 0;
420
+ return Number(segment);
421
+ }
422
+ function emptySegment(raw) {
423
+ return FilterError.invalid(raw === "" ? "empty path" : `path \`${raw}\`: empty segment`);
424
+ }
425
+ /**
426
+ * Parses `root ("." segment)*`. `\.` and `\\` escape inside keys; any other
427
+ * backslash sequence, an empty segment or an unknown root is
428
+ * `INVALID_FILTER`. `@` is a root only inside `$any`, where it is the only
429
+ * root allowed.
430
+ */
431
+ function parsePath(raw, inAny) {
432
+ const parts = [];
433
+ let current = "";
434
+ for (let i = 0; i < raw.length; i++) {
435
+ const c = raw[i];
436
+ if (c === "\\") {
437
+ const next = raw[i + 1];
438
+ if (next === "." || next === "\\") {
439
+ current += next;
440
+ i++;
441
+ } else if (next === void 0) throw FilterError.invalid(`path \`${raw}\`: dangling \`\\\` at the end`);
442
+ else throw FilterError.invalid(`path \`${raw}\`: invalid escape \`\\${next}\` (only \`\\.\` and \`\\\\\` are allowed)`);
443
+ } else if (c === ".") {
444
+ if (current === "") throw emptySegment(raw);
445
+ parts.push(current);
446
+ current = "";
447
+ } else current += c;
448
+ }
449
+ if (current === "") throw emptySegment(raw);
450
+ parts.push(current);
451
+ const first = parts[0];
452
+ if (!ROOTS.has(first)) throw FilterError.invalid(inAny ? `path \`${raw}\`: inside \`$any\` paths start at \`@\`, the current element` : `path \`${raw}\`: unknown root \`${first}\` (expected input, output, error, caller or metadata)`);
453
+ if (first === "@" && !inAny) throw FilterError.invalid(`path \`${raw}\`: \`@\` paths are only allowed inside \`$any\``);
454
+ if (first !== "@" && inAny) throw FilterError.invalid(`path \`${raw}\`: inside \`$any\` paths start at \`@\`, the current element`);
455
+ const segments = parts.slice(1).map((key) => ({
456
+ key,
457
+ index: canonicalIndex(key)
458
+ }));
459
+ if (segments.length > 16) throw FilterError.invalid(`path \`${raw}\`: ${segments.length} segments after the root (limit ${16})`);
460
+ return {
461
+ root: first,
462
+ segments
463
+ };
464
+ }
465
+ /** Compiles the path into a resolver; `undefined` means absent. */
466
+ function compilePath(path) {
467
+ const { root, segments } = path;
468
+ const step = (start) => {
469
+ let current = start;
470
+ for (let i = 0; i < segments.length; i++) {
471
+ if (current === void 0 || current === null || typeof current !== "object") return void 0;
472
+ const segment = segments[i];
473
+ if (Array.isArray(current)) {
474
+ const index = segment.index;
475
+ if (index === void 0 || index >= current.length) return void 0;
476
+ current = arrayElement(current, index);
477
+ } else current = objectMember(current, segment.key);
478
+ }
479
+ return current;
480
+ };
481
+ if (root === "@") return (_doc, element) => step(element);
482
+ return (doc) => step(objectMember(doc, root));
483
+ }
484
+
485
+ //#endregion
486
+ //#region ../iii/src/filter/compile.ts
487
+ /**
488
+ * Validation (filters.md §2, §4) and compilation into closures, in one pass.
489
+ *
490
+ * Mirrors `crates/iii-filter` (`parse.rs`, `eval.rs`): the same limits, the
491
+ * same error code (`INVALID_FILTER`) and the same semantics, so a filter
492
+ * evaluated here, in the engine or in another SDK answers the same. The
493
+ * filter must already be JSON (`checkJson`); it is then copied through
494
+ * `JSON.stringify` (also what the encoded size limit is measured on), so
495
+ * what is validated is exactly what travels on the wire.
496
+ *
497
+ * Limits, as the vectors define them:
498
+ * - depth: the top-level filter is at depth 1; the filters of a `$or`, the
499
+ * operand of `$not` and the operand of `$any` are one level deeper than the
500
+ * object holding them; the filters of a `$and` stay at the same level;
501
+ * - nodes: every operator (`$eq` ... `$any`) and every `$or` / `$not` counts
502
+ * one; paths and `$and` are free;
503
+ * - encoded size: the compact JSON of the filter as given, in UTF-8 bytes.
504
+ *
505
+ * Pure TypeScript with no Node.js APIs: the browser SDK uses this file too.
506
+ */
507
+ const VALUE_OPERATORS = new Set([
508
+ "$eq",
509
+ "$ne",
510
+ "$in",
511
+ "$nin",
512
+ "$gt",
513
+ "$gte",
514
+ "$lt",
515
+ "$lte",
516
+ "$exists",
517
+ "$prefix",
518
+ "$any"
519
+ ]);
520
+ var Budget = class {
521
+ constructor() {
522
+ this.used = 0;
523
+ }
524
+ take() {
525
+ this.used++;
526
+ if (this.used > 64) throw FilterError.invalid(`more than ${64} operator / clause nodes`);
527
+ }
528
+ };
529
+ function isJsonObject(v) {
530
+ return v !== null && typeof v === "object" && !Array.isArray(v);
531
+ }
532
+ function kind(v) {
533
+ if (v === null) return "null";
534
+ if (Array.isArray(v)) return "an array";
535
+ switch (typeof v) {
536
+ case "boolean": return "a boolean";
537
+ case "number": return "a number";
538
+ case "string": return "a string";
539
+ default: return "an object";
540
+ }
541
+ }
542
+ /**
543
+ * Validates `src` and compiles it. Throws {@link FilterError} with code
544
+ * `INVALID_FILTER` when the filter is not valid.
545
+ *
546
+ * `trusted` skips the encoded size limit, for filters the engine already
547
+ * validated (the normal form it pushes to owners): normalizing can make a
548
+ * filter a little longer than the one written, and JavaScript spells some
549
+ * numbers longer than serde_json, so near the limit the two measurements can
550
+ * disagree, and the engine's is the one that counts.
551
+ */
552
+ function compile(src, trusted = false) {
553
+ let text;
554
+ try {
555
+ if (src === null || typeof src !== "object" || Array.isArray(src)) throw FilterError.invalid(`a filter must be a JSON object, found ${src === void 0 ? "nothing" : kind(src)}`);
556
+ checkJson(src);
557
+ text = JSON.stringify(src);
558
+ } catch (error) {
559
+ if (error instanceof FilterError) throw error;
560
+ throw FilterError.invalid(`the filter cannot be read: ${error instanceof Error ? error.message : String(error)}`);
561
+ }
562
+ if (!trusted && utf8Length(text) > 8192) throw FilterError.invalid(`the filter encodes to more than ${MAX_ENCODED_BYTES} bytes`);
563
+ const json = deepFreeze(JSON.parse(text));
564
+ const roots = /* @__PURE__ */ new Set();
565
+ const clauses = [];
566
+ collectClauses(json, 1, false, new Budget(), roots, clauses);
567
+ return {
568
+ pred: and(clauses),
569
+ roots,
570
+ json,
571
+ matchAll: clauses.length === 0
572
+ };
573
+ }
574
+ function parseFilter(src, depth, inAny, budget, roots) {
575
+ const clauses = [];
576
+ collectClauses(src, depth, inAny, budget, roots, clauses);
577
+ return and(clauses);
578
+ }
579
+ function and(clauses) {
580
+ switch (clauses.length) {
581
+ case 0: return () => true;
582
+ case 1: return clauses[0];
583
+ case 2: {
584
+ const [a, b] = clauses;
585
+ return (doc, el) => a(doc, el) && b(doc, el);
586
+ }
587
+ default: return (doc, el) => {
588
+ for (let i = 0; i < clauses.length; i++) if (!clauses[i](doc, el)) return false;
589
+ return true;
590
+ };
591
+ }
592
+ }
593
+ /**
594
+ * Collects the clauses of `src` and of every filter its `$and`s hold. `$and`
595
+ * adds no depth, so it is walked with an explicit stack.
596
+ */
597
+ function collectClauses(src, depth, inAny, budget, roots, out) {
598
+ if (depth > 8) throw FilterError.invalid(`filters nested deeper than ${8} levels`);
599
+ const pending = [src];
600
+ while (pending.length > 0) {
601
+ const current = pending.pop();
602
+ if (!isJsonObject(current)) throw FilterError.invalid(`a filter must be a JSON object, found ${kind(current)}`);
603
+ for (const key of Object.keys(current)) {
604
+ const value = current[key];
605
+ if (key === "$and") {
606
+ const items = filterList("$and", value);
607
+ for (let i = items.length - 1; i >= 0; i--) pending.push(items[i]);
608
+ } else if (key === "$or") {
609
+ budget.take();
610
+ const children = filterList("$or", value).map((item) => parseFilter(item, depth + 1, inAny, budget, roots));
611
+ out.push((doc, el) => {
612
+ for (let i = 0; i < children.length; i++) if (children[i](doc, el)) return true;
613
+ return false;
614
+ });
615
+ } else if (key === "$not") {
616
+ budget.take();
617
+ if (!isJsonObject(value)) throw FilterError.invalid(`\`$not\` takes a filter object, found ${kind(value)}`);
618
+ const child = parseFilter(value, depth + 1, inAny, budget, roots);
619
+ out.push((doc, el) => !child(doc, el));
620
+ } else if (VALUE_OPERATORS.has(key)) throw FilterError.invalid(`\`${key}\` needs a path: write {"<path>": {"${key}": ...}}`);
621
+ else if (key.startsWith("$")) throw FilterError.invalid(`unknown operator \`${key}\` (a filter holds paths, \`$and\`, \`$or\` and \`$not\`)`);
622
+ else {
623
+ const path = parsePath(key, inAny);
624
+ if (path.root !== "@") roots.add(path.root);
625
+ const ops = parseOperatorObject(key, value, depth, budget);
626
+ const resolve = compilePath(path);
627
+ out.push(pathClause(resolve, ops));
628
+ }
629
+ }
630
+ }
631
+ }
632
+ function pathClause(resolve, ops) {
633
+ if (ops.length === 1) {
634
+ const op = ops[0];
635
+ return (doc, el) => op(resolve(doc, el), doc);
636
+ }
637
+ return (doc, el) => {
638
+ const value = resolve(doc, el);
639
+ for (let i = 0; i < ops.length; i++) if (!ops[i](value, doc)) return false;
640
+ return true;
641
+ };
642
+ }
643
+ function filterList(name, value) {
644
+ if (!Array.isArray(value)) throw FilterError.invalid(`\`${name}\` takes an array of filters, found ${kind(value)}`);
645
+ if (value.length === 0) throw FilterError.invalid(`\`${name}\` takes a non-empty array of filters`);
646
+ return value;
647
+ }
648
+ function parseOperatorObject(path, value, depth, budget) {
649
+ const shorthand = () => FilterError.invalid(`\`${path}\`: expected an operator object such as {"$eq": ...}; literal values are not allowed`);
650
+ if (!isJsonObject(value)) throw shorthand();
651
+ const names = Object.keys(value);
652
+ if (names.length === 0) throw FilterError.invalid(`\`${path}\`: empty operator object`);
653
+ if (names.some((k) => !k.startsWith("$"))) throw shorthand();
654
+ return parseOperators(path, value, depth, budget);
655
+ }
656
+ /** The operators of an operator object; `depth` is the level of the object holding them. */
657
+ function parseOperators(path, map, depth, budget) {
658
+ return Object.keys(map).map((name) => {
659
+ budget.take();
660
+ return parseOperator(path, name, map[name], depth, budget);
661
+ });
662
+ }
663
+ function parseOperator(path, name, operand, depth, budget) {
664
+ const wrong = (expected) => FilterError.invalid(`\`${path}\`: \`${name}\` takes ${expected}, found ${kind(operand)}`);
665
+ switch (name) {
666
+ case "$eq":
667
+ checkLiteralDepth(path, name, operand);
668
+ return (v) => v !== void 0 && jsonEquals(v, operand);
669
+ case "$ne":
670
+ checkLiteralDepth(path, name, operand);
671
+ return (v) => v === void 0 || !jsonEquals(v, operand);
672
+ case "$in":
673
+ case "$nin": {
674
+ if (!Array.isArray(operand)) throw wrong("an array");
675
+ if (operand.length > 256) throw FilterError.invalid(`\`${path}\`: \`${name}\` has ${operand.length} items (limit ${256})`);
676
+ for (const item of operand) checkLiteralDepth(path, name, item);
677
+ const items = operand;
678
+ const member = (v) => {
679
+ for (let i = 0; i < items.length; i++) if (jsonEquals(v, items[i])) return true;
680
+ return false;
681
+ };
682
+ return name === "$in" ? (v) => v !== void 0 && member(v) : (v) => v === void 0 || !member(v);
683
+ }
684
+ case "$gt":
685
+ case "$gte":
686
+ case "$lt":
687
+ case "$lte": {
688
+ const accept = name === "$gt" ? (c) => c > 0 : name === "$gte" ? (c) => c >= 0 : name === "$lt" ? (c) => c < 0 : (c) => c <= 0;
689
+ if (typeof operand === "number") {
690
+ const bound = operand;
691
+ return (v) => typeof v === "number" && accept(v < bound ? -1 : v > bound ? 1 : 0);
692
+ }
693
+ if (typeof operand === "string") {
694
+ const bound = operand;
695
+ return (v) => typeof v === "string" && accept(compareCodePoints(v, bound));
696
+ }
697
+ throw wrong("a number or a string");
698
+ }
699
+ case "$exists": {
700
+ if (typeof operand !== "boolean") throw wrong("a boolean");
701
+ const expected = operand;
702
+ return (v) => v !== void 0 === expected;
703
+ }
704
+ case "$prefix": {
705
+ if (typeof operand !== "string") throw wrong("a string");
706
+ const prefix = operand;
707
+ return (v) => typeof v === "string" && hasCodePointPrefix(v, prefix);
708
+ }
709
+ case "$any": return parseAny(path, operand, depth, budget);
710
+ case "$and":
711
+ case "$or":
712
+ case "$not": throw FilterError.invalid(`\`${path}\`: \`${name}\` combines filters and is not a value operator`);
713
+ default: throw FilterError.invalid(`\`${path}\`: unknown operator \`${name}\``);
714
+ }
715
+ }
716
+ /**
717
+ * `$any` takes an operator object (all keys are value operators) or a filter
718
+ * over the element (`@` paths, `$and`, `$or`, `$not`). `{}` is the empty
719
+ * filter: it matches any non-empty array.
720
+ */
721
+ function parseAny(path, operand, depth, budget) {
722
+ if (!isJsonObject(operand)) throw FilterError.invalid(`\`${path}\`: \`$any\` takes an operator object or a filter over \`@\`, found ${kind(operand)}`);
723
+ if (depth + 1 > 8) throw FilterError.invalid(`filters nested deeper than ${8} levels`);
724
+ const names = Object.keys(operand);
725
+ if (names.length > 0 && names.every((k) => VALUE_OPERATORS.has(k))) {
726
+ const ops = parseOperators(path, operand, depth + 1, budget);
727
+ return (v, doc) => {
728
+ if (!Array.isArray(v)) return false;
729
+ for (let i = 0; i < v.length; i++) {
730
+ const item = arrayElement(v, i);
731
+ let all = true;
732
+ for (let j = 0; j < ops.length; j++) if (!ops[j](item, doc)) {
733
+ all = false;
734
+ break;
735
+ }
736
+ if (all) return true;
737
+ }
738
+ return false;
739
+ };
740
+ }
741
+ const node = parseFilter(operand, depth + 1, true, budget, /* @__PURE__ */ new Set());
742
+ return (v, doc) => {
743
+ if (!Array.isArray(v)) return false;
744
+ for (let i = 0; i < v.length; i++) if (node(doc, arrayElement(v, i))) return true;
745
+ return false;
746
+ };
747
+ }
748
+ /**
749
+ * A literal (an `$eq` / `$ne` operand, an `$in` / `$nin` item) nests at most
750
+ * MAX_LITERAL_DEPTH arrays / objects: a scalar is 0, `[]` and `[1]` are 1.
751
+ */
752
+ function checkLiteralDepth(path, name, literal) {
753
+ const stack = [[literal, 1]];
754
+ while (stack.length > 0) {
755
+ const [value, level] = stack.pop();
756
+ if (value === null || typeof value !== "object") continue;
757
+ if (level > 32) throw FilterError.invalid(`\`${path}\`: \`${name}\` nests a literal deeper than ${32} arrays / objects`);
758
+ for (const member of Object.values(value)) stack.push([member, level + 1]);
759
+ }
760
+ }
761
+
762
+ //#endregion
763
+ //#region ../iii/src/filter/index.ts
764
+ /**
765
+ * The observer filter language (`iii-filter` v1, filters.md): validation and
766
+ * evaluation for the SDKs, with the same semantics as the engine's Rust
767
+ * evaluator (`crates/iii-filter`).
768
+ *
769
+ * Pure TypeScript with no Node.js APIs: the browser SDK uses these files too.
770
+ */
771
+ /**
772
+ * Validates and compiles a filter. Throws {@link FilterError}
773
+ * (`INVALID_FILTER`) when it is not valid.
774
+ *
775
+ * @example
776
+ * ```typescript
777
+ * const f = compileFilter({ 'input.amount': { $gte: 500 } })
778
+ * f.matches({ input: { amount: 750 } }) // true
779
+ * ```
780
+ */
781
+ function compileFilter(src, options) {
782
+ const { pred, roots, json, matchAll } = compile(src, options?.trusted === true);
783
+ return {
784
+ source: json,
785
+ matchAll,
786
+ roots,
787
+ matches: (doc) => {
788
+ try {
789
+ return pred(doc !== null && typeof doc === "object" ? doc : {}, void 0);
790
+ } catch {
791
+ return false;
792
+ }
793
+ }
794
+ };
795
+ }
796
+ /** The filter that matches every document (`{}`). */
797
+ const MATCH_ALL = compileFilter({});
798
+
799
+ //#endregion
800
+ //#region src/iii-types.ts
801
+ /**
802
+ * Protocol features (`WorkerRegistered.features` from the engine,
803
+ * `engine::workers::register` `features` from the SDK).
804
+ */
805
+ const FEATURE_OBSERVE_V1 = "observe.v1";
806
+ const FEATURE_LOCAL_DISPATCH_V1 = "local-dispatch.v1";
807
+ /**
808
+ * What this SDK declares in `engine::workers::register`. Not
809
+ * `large-messages.v1`, unlike the other SDKs: a browser receives one 16 MiB
810
+ * WebSocket frame at most.
811
+ */
812
+ const SDK_FEATURES = [FEATURE_OBSERVE_V1, FEATURE_LOCAL_DISPATCH_V1];
813
+
814
+ //#endregion
815
+ //#region src/invocation-context.ts
816
+ /**
817
+ * How long an invocation that came over the wire (and one re-entered with
818
+ * `withInvocation`) counts as running at most, when it never settles. An
819
+ * observer chain's hops may await far longer than this SDK's own call
820
+ * timeout, and their depth must still reach the calls they make afterwards
821
+ * (the engine's loop guard counts on it). A local call counts as running until
822
+ * its caller's timeout instead.
823
+ */
824
+ const MAX_RUNNING_INVOCATION_MS = 600 * 1e3;
825
+ /**
826
+ * Browsers have no `AsyncLocalStorage` (and `AsyncContext` is not shipped
827
+ * yet), so the context is a synchronous scope: {@link runInContext} sets it
828
+ * while `fn` runs and restores the previous one when `fn` returns. An async
829
+ * handler sees it up to its first `await`; the continuation after an `await`
830
+ * runs from the event loop, outside any scope, so it never sees another
831
+ * invocation's context, only none. `withInvocation` re-enters a captured one.
832
+ *
833
+ * One scope for the whole page, like the Node SDK's one `AsyncLocalStorage`
834
+ * per process: a handler of one worker that calls another worker's
835
+ * `trigger()` is that call's caller.
836
+ */
837
+ let current;
838
+ /** The public views handed out, so `withInvocation(view, fn)` restores everything (metadata included). */
839
+ const views = /* @__PURE__ */ new WeakMap();
840
+ function currentContext() {
841
+ return current;
842
+ }
843
+ /**
844
+ * Every invocation whose work is running on this page (handlers, remote and
845
+ * local, and the async `fn` of `withInvocation`), until it settles: one lease
846
+ * per piece of work, because an async `withInvocation` keeps an invocation
847
+ * running alongside its handler. A lease is forgotten at its deadline, so work
848
+ * that never settles does not lend its depth to every later call made on the
849
+ * page; settling one lease never ends another (a late one, after its deadline
850
+ * passed and the invocation was entered again, ends only itself).
851
+ */
852
+ const running = /* @__PURE__ */ new Map();
853
+ /**
854
+ * Marks `ctx` as running for at most `maxAgeMs`; call the returned function
855
+ * when the work settles.
856
+ */
857
+ function trackRunning(ctx, maxAgeMs) {
858
+ const lease = { deadline: Date.now() + maxAgeMs };
859
+ let leases = running.get(ctx);
860
+ if (!leases) {
861
+ leases = /* @__PURE__ */ new Set();
862
+ running.set(ctx, leases);
863
+ }
864
+ leases.add(lease);
865
+ return () => {
866
+ const current = running.get(ctx);
867
+ if (!current?.delete(lease)) return;
868
+ if (current.size === 0) running.delete(ctx);
869
+ };
870
+ }
871
+ /** The running invocations; leases past their deadline are forgotten here. */
872
+ function live() {
873
+ const now = Date.now();
874
+ const out = [];
875
+ for (const [ctx, leases] of running) {
876
+ for (const lease of leases) if (lease.deadline <= now) leases.delete(lease);
877
+ if (leases.size === 0) running.delete(ctx);
878
+ else out.push(ctx);
879
+ }
880
+ return out;
881
+ }
882
+ /** What a fallback attribution lends: the invocation without its metadata sidecar (one object per invocation). */
883
+ const lent = /* @__PURE__ */ new WeakMap();
884
+ function lend(ctx) {
885
+ let view = lent.get(ctx);
886
+ if (!view) {
887
+ const { metadata: _, ...rest } = ctx;
888
+ view = rest;
889
+ lent.set(ctx, view);
890
+ }
891
+ return view;
892
+ }
893
+ /**
894
+ * The invocation a call, an emit or a report made now belongs to. Inside a
895
+ * scope, the scope's. Outside any scope (code after an `await`), the running
896
+ * invocation when that is unambiguous: it is the only one running and it is
897
+ * an observe activation. It lends its ids, caller and trace context, never its
898
+ * metadata: filters on `metadata.*` see only what a real scope carries.
899
+ * Otherwise none, and the call carries no `caller`: the SDK cannot tell which
900
+ * handler, if any, made it.
901
+ */
902
+ function callContext() {
903
+ if (current) return current;
904
+ const all = live();
905
+ return all.length === 1 && all[0].activation ? lend(all[0]) : void 0;
906
+ }
907
+ /**
908
+ * The `observe_depth` a call, an emit or a report made now carries. Inside a
909
+ * scope, the scope's. Outside any scope, the deepest running invocation's:
910
+ * the engine's loop guard counts on this depth, so code after an `await`
911
+ * over-counts (a chain may stop earlier than `max_observe_depth`) rather than
912
+ * restart the chain at 0 (an observer cycle would never stop).
913
+ */
914
+ function callDepth() {
915
+ if (current) return current.observe_depth;
916
+ let depth = 0;
917
+ for (const ctx of live()) if (ctx.observe_depth > depth) depth = ctx.observe_depth;
918
+ return depth;
919
+ }
920
+ /**
921
+ * The local depth that calls started outside any scope in the current
922
+ * synchronous run share (see {@link callLocalDepth}); cleared on a microtask.
923
+ */
924
+ let unscopedLocalDepth;
925
+ /**
926
+ * How many local calls deep a local call made now is nested (decision 20,
927
+ * {@link MAX_LOCAL_DEPTH}). Inside a scope, the scope's. Outside any scope, the
928
+ * deepest running local call's, so a self-recursion that awaits before each
929
+ * call still reaches the engine at the limit. That value is taken once per
930
+ * synchronous run: calls started together outside any scope (a fan-out, from
931
+ * a loop or `Promise.all`) are siblings at one depth; only code after an
932
+ * `await`, which runs later, sees them running and goes one level deeper.
933
+ */
934
+ function callLocalDepth() {
935
+ if (current) return current.localDepth ?? 0;
936
+ if (unscopedLocalDepth === void 0) {
937
+ let depth = 0;
938
+ for (const ctx of live()) if ((ctx.localDepth ?? 0) > depth) depth = ctx.localDepth ?? 0;
939
+ unscopedLocalDepth = depth;
940
+ queueMicrotask(() => {
941
+ unscopedLocalDepth = void 0;
942
+ });
943
+ }
944
+ return unscopedLocalDepth;
945
+ }
946
+ /**
947
+ * `withInvocation`: runs `fn` inside `ctx`. When `fn` returns a promise, `ctx`
948
+ * counts as running until it settles (at most `maxAgeMs`), so `fn`'s code after
949
+ * its own `await`s falls back to it (see {@link callContext}, {@link callDepth}),
950
+ * and the caller gets a promise that settles the same way: a rejection the
951
+ * caller does not handle is still reported as unhandled.
952
+ */
953
+ function enterInvocation(ctx, fn, maxAgeMs) {
954
+ const result = runInContext(ctx, fn);
955
+ if (!ctx || result === null || typeof result?.then !== "function") return result;
956
+ const untrack = trackRunning(ctx, maxAgeMs);
957
+ return result.then((value) => {
958
+ untrack();
959
+ return value;
960
+ }, (error) => {
961
+ untrack();
962
+ throw error;
963
+ });
964
+ }
965
+ /** Runs `fn` synchronously inside `ctx` (`undefined`: outside any invocation). */
966
+ function runInContext(ctx, fn) {
967
+ const previous = current;
968
+ current = ctx;
969
+ try {
970
+ return fn();
971
+ } finally {
972
+ current = previous;
973
+ }
974
+ }
975
+ /** The public view of the current invocation (without the metadata sidecar). */
976
+ function publicContext(ctx) {
977
+ if (!ctx) return void 0;
978
+ const view = {
979
+ function_id: ctx.function_id,
980
+ invocation_id: ctx.invocation_id,
981
+ observe_depth: ctx.observe_depth
982
+ };
983
+ if (ctx.caller) view.caller = ctx.caller;
984
+ if (ctx.activation) view.activation = ctx.activation;
985
+ if (ctx.traceparent !== void 0) view.traceparent = ctx.traceparent;
986
+ if (ctx.baggage !== void 0) view.baggage = ctx.baggage;
987
+ views.set(view, ctx);
988
+ return view;
989
+ }
990
+ /**
991
+ * The context `withInvocation` re-enters: the one a view of
992
+ * `currentInvocation()` was taken from, or one built from a context the
993
+ * caller assembled itself or copied (at the local depth of the code entering it).
994
+ */
995
+ function contextFromView(view) {
996
+ if (view === void 0 || view === null) return void 0;
997
+ const known = views.get(view);
998
+ if (known) {
999
+ const depth = callLocalDepth();
1000
+ return depth > (known.localDepth ?? 0) ? {
1001
+ ...known,
1002
+ localDepth: depth
1003
+ } : known;
1004
+ }
1005
+ if (typeof view.function_id !== "string" || typeof view.invocation_id !== "string") throw new Error("withInvocation: expected the value iii.currentInvocation() returned");
1006
+ const ctx = {
1007
+ function_id: view.function_id,
1008
+ invocation_id: view.invocation_id,
1009
+ observe_depth: typeof view.observe_depth === "number" && view.observe_depth > 0 ? view.observe_depth : 0,
1010
+ localDepth: callLocalDepth()
1011
+ };
1012
+ if (view.caller) ctx.caller = view.caller;
1013
+ if (view.activation) ctx.activation = view.activation;
1014
+ if (typeof view.traceparent === "string") ctx.traceparent = view.traceparent;
1015
+ if (typeof view.baggage === "string") ctx.baggage = view.baggage;
1016
+ return ctx;
1017
+ }
1018
+
1019
+ //#endregion
1020
+ //#region src/observe-wire.ts
1021
+ /** CONTRACT D1: what an absent `capture` means. */
1022
+ const DEFAULT_CAPTURE = [
1023
+ "input",
1024
+ "output",
1025
+ "caller"
1026
+ ];
1027
+ function isRecord(v) {
1028
+ return v !== null && typeof v === "object" && !Array.isArray(v);
1029
+ }
1030
+ function str(v) {
1031
+ return typeof v === "string" ? v : void 0;
1032
+ }
1033
+ function num(v) {
1034
+ return typeof v === "number" ? v : void 0;
1035
+ }
1036
+ function errorBody(v) {
1037
+ if (!isRecord(v)) return void 0;
1038
+ const body = {
1039
+ code: String(v.code ?? ""),
1040
+ message: String(v.message ?? "")
1041
+ };
1042
+ if (typeof v.stacktrace === "string") body.stacktrace = v.stacktrace;
1043
+ return body;
1044
+ }
1045
+ /** Copies the wire caller, dropping `null`s and a `parent` inside `parent`. */
1046
+ function decodeCaller(v, depth = 0) {
1047
+ if (!isRecord(v)) return void 0;
1048
+ const caller = {};
1049
+ for (const key of [
1050
+ "worker_id",
1051
+ "worker_name",
1052
+ "function_id",
1053
+ "invocation_id"
1054
+ ]) {
1055
+ const value = str(v[key]);
1056
+ if (value !== void 0) caller[key] = value;
1057
+ }
1058
+ if (depth === 0) {
1059
+ const parent = decodeCaller(v.parent, 1);
1060
+ if (parent) caller.parent = parent;
1061
+ }
1062
+ return caller;
1063
+ }
1064
+ function decodeActivation(v) {
1065
+ if (!isRecord(v) || typeof v.observer_id !== "string") return void 0;
1066
+ const activation = { observer_id: v.observer_id };
1067
+ if (typeof v.activation_id === "string") activation.activation_id = v.activation_id;
1068
+ return activation;
1069
+ }
1070
+ /** An observer as the owner sees it (`observeradded.observer`, `functionregistered.observers[]`). */
1071
+ function decodeObserverInfo(v) {
1072
+ const raw = isRecord(v) ? v : {};
1073
+ const info = {
1074
+ id: String(raw.id ?? ""),
1075
+ args: isRecord(raw.args) ? raw.args : {},
1076
+ filters: raw.filters === void 0 ? {} : raw.filters,
1077
+ target: String(raw.target ?? ""),
1078
+ capture: Array.isArray(raw.capture) ? raw.capture.filter((c) => typeof c === "string") : [...DEFAULT_CAPTURE],
1079
+ on: str(raw.on) ?? "success"
1080
+ };
1081
+ if (isRecord(raw.legacy) && typeof raw.legacy.trigger_type === "string") info.legacy = {
1082
+ trigger_type: raw.legacy.trigger_type,
1083
+ config: raw.legacy.config ?? null
1084
+ };
1085
+ return info;
1086
+ }
1087
+ function decodeFunctionRegistered(v) {
1088
+ return {
1089
+ id: String(v.id ?? ""),
1090
+ namespace: String(v.namespace ?? ""),
1091
+ revision: num(v.revision) ?? 0,
1092
+ local_dispatch: v.local_dispatch === true,
1093
+ observers: Array.isArray(v.observers) ? v.observers.map(decodeObserverInfo) : []
1094
+ };
1095
+ }
1096
+ function decodeObserverAdded(v) {
1097
+ return {
1098
+ function_id: String(v.function_id ?? ""),
1099
+ namespace: String(v.namespace ?? ""),
1100
+ revision: num(v.revision) ?? 0,
1101
+ observer: decodeObserverInfo(v.observer)
1102
+ };
1103
+ }
1104
+ function decodeObserverRemoved(v) {
1105
+ return {
1106
+ function_id: String(v.function_id ?? ""),
1107
+ namespace: String(v.namespace ?? ""),
1108
+ revision: num(v.revision) ?? 0,
1109
+ id: String(v.id ?? "")
1110
+ };
1111
+ }
1112
+ function decodeObserveResult(v) {
1113
+ const msg = {
1114
+ id: String(v.id ?? ""),
1115
+ state: String(v.state ?? "")
1116
+ };
1117
+ const error = errorBody(v.error);
1118
+ if (error) msg.error = error;
1119
+ if (Array.isArray(v.warnings)) msg.warnings = v.warnings.filter((w) => typeof w === "string");
1120
+ return msg;
1121
+ }
1122
+ function decodeObserverStateChanged(v) {
1123
+ const msg = {
1124
+ id: String(v.id ?? ""),
1125
+ state: String(v.state ?? ""),
1126
+ fires: num(v.fires) ?? 0
1127
+ };
1128
+ const reason = errorBody(v.reason);
1129
+ if (reason) msg.reason = reason;
1130
+ return msg;
1131
+ }
1132
+ function decodeWorkerRegistered(v) {
1133
+ const msg = { worker_id: String(v.worker_id ?? "") };
1134
+ if (typeof v.reattach_token === "string") msg.reattach_token = v.reattach_token;
1135
+ if (Array.isArray(v.features)) msg.features = v.features.filter((f) => typeof f === "string");
1136
+ return msg;
1137
+ }
1138
+ /** The observe fields of an inbound `invokefunction` (`caller`, `observe_depth`, `activation`). */
1139
+ function decodeInvokeFunction(v) {
1140
+ const msg = {
1141
+ function_id: String(v.function_id ?? ""),
1142
+ data: v.data
1143
+ };
1144
+ if (typeof v.invocation_id === "string") msg.invocation_id = v.invocation_id;
1145
+ if (typeof v.traceparent === "string") msg.traceparent = v.traceparent;
1146
+ if (typeof v.baggage === "string") msg.baggage = v.baggage;
1147
+ if (isRecord(v.action)) msg.action = v.action;
1148
+ if (v.metadata !== void 0 && v.metadata !== null) msg.metadata = v.metadata;
1149
+ if (typeof v.namespace === "string") msg.namespace = v.namespace;
1150
+ const caller = decodeCaller(v.caller);
1151
+ if (caller) msg.caller = caller;
1152
+ const depth = num(v.observe_depth);
1153
+ if (depth !== void 0 && depth > 0) msg.observe_depth = depth;
1154
+ const activation = decodeActivation(v.activation);
1155
+ if (activation) msg.activation = activation;
1156
+ return msg;
1157
+ }
1158
+ /** Drops `parent` (one level only). */
1159
+ function stripCaller(caller) {
1160
+ if (!caller) return void 0;
1161
+ const { parent: _, ...rest } = caller;
1162
+ return rest;
1163
+ }
1164
+ /** JSON's view of a message: `undefined` fields left out, no caller-owned objects retained. */
1165
+ function snapshot(value) {
1166
+ return JSON.parse(JSON.stringify(value));
1167
+ }
1168
+ /**
1169
+ * `observe { id, source, target, ... }` from the three arguments of
1170
+ * `iii.observe`. Only what the caller set is sent; the engine applies the
1171
+ * defaults. `resolveNamespace` gives the namespace of an unqualified id (this
1172
+ * worker's, `default` for `engine::*`).
1173
+ */
1174
+ function buildObserveMessage(id, source, target, options, resolveNamespace) {
1175
+ const targetRef = typeof target === "string" ? { function_id: target } : target;
1176
+ const sourceNamespace = resolveNamespace(source.namespace, source.function_id, "ObserveSource.namespace");
1177
+ const targetNamespace = resolveNamespace(targetRef.namespace, targetRef.function_id, "Target.namespace");
1178
+ return snapshot({
1179
+ id,
1180
+ source: {
1181
+ function_id: source.function_id,
1182
+ namespace: sourceNamespace,
1183
+ args: source.args,
1184
+ filters: source.filters,
1185
+ capture: source.capture,
1186
+ on: source.on,
1187
+ deliver: source.deliver
1188
+ },
1189
+ target: {
1190
+ function_id: targetRef.function_id,
1191
+ namespace: targetNamespace
1192
+ },
1193
+ metadata: options?.metadata,
1194
+ max_fires: options?.max_fires,
1195
+ expires_in_ms: options?.expires_in_ms,
1196
+ max_in_flight: options?.max_in_flight
1197
+ });
1198
+ }
1199
+ /** `registerfunction.observe`: the four fields that travel, or `undefined` when none is set. */
1200
+ function observeDescriptor(hooks) {
1201
+ if (!hooks) return void 0;
1202
+ const descriptor = snapshot({
1203
+ delivery: hooks.delivery,
1204
+ args_format: hooks.args_format,
1205
+ legacy_trigger_type: hooks.legacy_trigger_type,
1206
+ allow: hooks.allow
1207
+ });
1208
+ return Object.keys(descriptor).length > 0 ? descriptor : void 0;
1209
+ }
1210
+ function buildObserverAck(ack) {
1211
+ const msg = {
1212
+ function_id: ack.function_id,
1213
+ id: ack.id,
1214
+ revision: ack.revision
1215
+ };
1216
+ if (ack.namespace !== void 0) msg.namespace = ack.namespace;
1217
+ if (ack.error) msg.error = {
1218
+ code: ack.error.code,
1219
+ message: ack.error.message
1220
+ };
1221
+ return msg;
1222
+ }
1223
+ /**
1224
+ * An outbound `invokefunction`. `observe_depth` is left out when 0, and every
1225
+ * optional field when unset.
1226
+ */
1227
+ function buildInvokeFunction(init) {
1228
+ const msg = {};
1229
+ if (init.invocation_id !== void 0) msg.invocation_id = init.invocation_id;
1230
+ msg.function_id = init.function_id;
1231
+ msg.data = init.data;
1232
+ if (init.traceparent !== void 0) msg.traceparent = init.traceparent;
1233
+ if (init.baggage !== void 0) msg.baggage = init.baggage;
1234
+ if (init.action !== void 0) msg.action = init.action;
1235
+ if (init.metadata !== void 0) msg.metadata = init.metadata;
1236
+ if (init.namespace !== void 0) msg.namespace = init.namespace;
1237
+ if (init.caller !== void 0) msg.caller = init.caller;
1238
+ if (init.observe_depth !== void 0 && init.observe_depth > 0) msg.observe_depth = init.observe_depth;
1239
+ if (init.activation !== void 0) msg.activation = init.activation;
1240
+ return msg;
1241
+ }
1242
+ /** The caller an outbound call asserts from inside a handler: that handler, and its own caller one level up. */
1243
+ function callerFor(ctx) {
1244
+ const caller = {
1245
+ function_id: ctx.function_id,
1246
+ invocation_id: ctx.invocation_id
1247
+ };
1248
+ const parent = stripCaller(ctx.caller);
1249
+ if (parent && Object.keys(parent).length > 0) caller.parent = parent;
1250
+ return caller;
1251
+ }
1252
+
1253
+ //#endregion
1254
+ //#region src/observable.ts
1255
+ /**
1256
+ * The owner side of observe (sdk.md §1, §4.1–§4.3): per-function observer
1257
+ * state, the observe hooks, the `Observer` object handed to them, and the
1258
+ * reports of local invocations and `obs.emit` events.
1259
+ */
1260
+ /** CONTRACT D11: `onObserverAdded` (and `onObserverRemoved`) still running after this is `OWNER_TIMEOUT`. */
1261
+ const OBSERVE_HOOK_TIMEOUT_MS = 3e4;
1262
+ function sameJson(a, b) {
1263
+ return JSON.stringify(a) === JSON.stringify(b);
1264
+ }
1265
+ function rejectionBody(error) {
1266
+ if (error instanceof ObserveRejection) return {
1267
+ code: error.code,
1268
+ message: error.message
1269
+ };
1270
+ return {
1271
+ code: "OBSERVE_REJECTED",
1272
+ message: error instanceof Error ? error.message : String(error)
1273
+ };
1274
+ }
1275
+ function onAccepts(on, ok) {
1276
+ return on === "complete" || (on === "success" ? ok : on === "error" ? !ok : false);
1277
+ }
1278
+ /** The `Observer` an owner receives. Its identity is stable while the observer lives. */
1279
+ var ObserverImpl = class {
1280
+ constructor(owner, info, filter, revision) {
1281
+ this.owner = owner;
1282
+ this.active = false;
1283
+ this.adding = false;
1284
+ this.id = info.id;
1285
+ this.function_id = owner.functionId;
1286
+ this.args = info.args;
1287
+ this.filters = info.filters;
1288
+ this.target = info.target;
1289
+ this.capture = info.capture;
1290
+ this.on = info.on;
1291
+ if (info.legacy) this.legacy = info.legacy;
1292
+ this.filter = filter;
1293
+ this.revision = revision;
1294
+ }
1295
+ /** @internal Takes the engine's current view of a kept observer. */
1296
+ update(info, filter) {
1297
+ this.filters = info.filters;
1298
+ this.filter = filter;
1299
+ this.target = info.target;
1300
+ this.capture = info.capture;
1301
+ this.on = info.on;
1302
+ }
1303
+ matches(doc) {
1304
+ return this.filter.matches(doc);
1305
+ }
1306
+ emit(event) {
1307
+ return this.owner.emit(this, event);
1308
+ }
1309
+ call(payload, opts) {
1310
+ return this.owner.call(this, payload, opts?.timeoutMs);
1311
+ }
1312
+ reject(code, message) {
1313
+ this.owner.reject(this, code, message);
1314
+ }
1315
+ toJSON() {
1316
+ return {
1317
+ id: this.id,
1318
+ function_id: this.function_id,
1319
+ args: this.args,
1320
+ filters: this.filters,
1321
+ target: this.target,
1322
+ capture: this.capture,
1323
+ on: this.on,
1324
+ ...this.legacy ? { legacy: this.legacy } : {}
1325
+ };
1326
+ }
1327
+ };
1328
+ /**
1329
+ * One registered function's observers, as the engine pushed them
1330
+ * (`functionregistered`, `observeradded`, `observerremoved`). Hooks run one
1331
+ * at a time, in revision order.
1332
+ */
1333
+ var FunctionObservers = class {
1334
+ constructor(functionId, hooks, localDispatchOption, hasHandler, host) {
1335
+ this.functionId = functionId;
1336
+ this.hooks = hooks;
1337
+ this.localDispatchOption = localDispatchOption;
1338
+ this.hasHandler = hasHandler;
1339
+ this.host = host;
1340
+ this.confirmed = false;
1341
+ this.confirmedEpoch = -1;
1342
+ this.localDispatch = false;
1343
+ this.revision = -1;
1344
+ this.known = /* @__PURE__ */ new Map();
1345
+ this.compiled = [];
1346
+ this.queue = Promise.resolve();
1347
+ this.disposed = false;
1348
+ this.releases = 0;
1349
+ this.delivery = hooks?.delivery === "owner" ? "owner" : "auto";
1350
+ }
1351
+ /** Callbacks or owner delivery: what needs `observe.v1` on both sides. */
1352
+ get needsObserve() {
1353
+ return this.delivery === "owner" || !!this.hooks?.onObserverAdded || !!this.hooks?.onObserverRemoved;
1354
+ }
1355
+ isObserved() {
1356
+ return this.compiled.length > 0;
1357
+ }
1358
+ observers() {
1359
+ return [...this.compiled];
1360
+ }
1361
+ /** `functionregistered`: always accepted; replaces the set (§4.2). */
1362
+ onFunctionRegistered(msg, epoch) {
1363
+ if (this.disposed) return;
1364
+ this.confirmed = true;
1365
+ this.releasedEpoch = void 0;
1366
+ this.localDispatch = msg.local_dispatch && this.localDispatchOption && this.hasHandler;
1367
+ this.namespace = msg.namespace;
1368
+ this.revision = msg.revision;
1369
+ this.enqueue(async () => {
1370
+ try {
1371
+ await this.applySet(msg.observers, msg.revision, msg.namespace);
1372
+ } finally {
1373
+ this.confirmedEpoch = epoch;
1374
+ this.host.reporter.flush();
1375
+ }
1376
+ });
1377
+ }
1378
+ onObserverAdded(msg) {
1379
+ if (this.disposed || msg.revision <= this.revision) return;
1380
+ this.revision = msg.revision;
1381
+ this.enqueue(async () => {
1382
+ if (this.known.get(msg.observer.id)?.rejection) await this.remove(msg.observer.id);
1383
+ await this.add(msg.observer, msg.revision, msg.namespace);
1384
+ });
1385
+ }
1386
+ onObserverRemoved(msg) {
1387
+ if (this.disposed || msg.revision <= this.revision) return;
1388
+ this.revision = msg.revision;
1389
+ this.enqueue(() => this.remove(msg.id));
1390
+ }
1391
+ /**
1392
+ * `RegistrationRejected{FUNCTION_NAMESPACE_CONFLICT}`: no local dispatch, no
1393
+ * observers, and its held reports are discarded (they could never be
1394
+ * confirmed, and would starve other functions of buffer).
1395
+ */
1396
+ onRegistrationRejected(epoch) {
1397
+ this.confirmed = false;
1398
+ this.confirmedEpoch = -1;
1399
+ this.localDispatch = false;
1400
+ this.releasedEpoch = epoch;
1401
+ this.releases++;
1402
+ this.host.reporter.discard(this.functionId);
1403
+ this.dropAll();
1404
+ }
1405
+ /** The function was unregistered. */
1406
+ dispose() {
1407
+ this.disposed = true;
1408
+ this.onRegistrationRejected(-1);
1409
+ }
1410
+ /**
1411
+ * Stops delivery at once, then removes every observer through the hook
1412
+ * queue, after the adds queued before it (which undo themselves: `add`).
1413
+ */
1414
+ dropAll() {
1415
+ for (const obs of this.compiled) obs.active = false;
1416
+ this.compiled = [];
1417
+ this.enqueue(async () => {
1418
+ for (const id of [...this.known.keys()]) await this.remove(id);
1419
+ });
1420
+ }
1421
+ enqueue(task) {
1422
+ this.queue = this.queue.then(task).catch((error) => {
1423
+ this.host.logError(`Observe hook failed for ${this.functionId}`, error);
1424
+ });
1425
+ }
1426
+ activate(obs) {
1427
+ if (obs.active) return;
1428
+ obs.active = true;
1429
+ this.compiled = [...this.compiled, obs];
1430
+ }
1431
+ deactivate(obs) {
1432
+ if (!obs.active) return;
1433
+ obs.active = false;
1434
+ this.compiled = this.compiled.filter((o) => o !== obs);
1435
+ }
1436
+ ack(info, revision, namespace, error) {
1437
+ this.host.sendAck({
1438
+ function_id: this.functionId,
1439
+ namespace,
1440
+ id: info.id,
1441
+ revision,
1442
+ ...error ? { error } : {}
1443
+ });
1444
+ }
1445
+ /** Diffs the engine's full set against what this SDK holds. */
1446
+ async applySet(list, revision, namespace) {
1447
+ const incoming = new Set(list.map((o) => o.id));
1448
+ for (const id of [...this.known.keys()]) if (!incoming.has(id)) await this.remove(id);
1449
+ for (const info of list) {
1450
+ const existing = this.known.get(info.id);
1451
+ if (existing && sameJson(existing.args, info.args) && sameJson(existing.legacy, info.legacy)) this.keep(existing, info, revision, namespace);
1452
+ else {
1453
+ if (existing) await this.remove(info.id);
1454
+ await this.add(info, revision, namespace);
1455
+ }
1456
+ }
1457
+ }
1458
+ /**
1459
+ * A kept observer: the hook already ran for it; take the engine's filters
1460
+ * and ack it again, or repeat the owner's late rejection of it.
1461
+ */
1462
+ keep(obs, info, revision, namespace) {
1463
+ if (obs.rejection) {
1464
+ obs.revision = revision;
1465
+ this.ack(info, revision, namespace, obs.rejection);
1466
+ return;
1467
+ }
1468
+ let filter = obs.filter;
1469
+ if (!sameJson(obs.filters, info.filters)) try {
1470
+ filter = compileFilter(info.filters, { trusted: true });
1471
+ } catch (error) {
1472
+ obs.revision = revision;
1473
+ this.deactivate(obs);
1474
+ this.ack(info, revision, namespace, {
1475
+ code: "INVALID_FILTER",
1476
+ message: error.message
1477
+ });
1478
+ return;
1479
+ }
1480
+ obs.update(info, filter);
1481
+ obs.revision = revision;
1482
+ this.activate(obs);
1483
+ this.ack(info, revision, namespace);
1484
+ }
1485
+ /** handleAdded (§4.2): hook, then the compiled set, then the ack. */
1486
+ async add(info, revision, namespace) {
1487
+ if (this.disposed || this.releasedEpoch !== void 0) return;
1488
+ const releases = this.releases;
1489
+ const existing = this.known.get(info.id);
1490
+ if (existing) {
1491
+ this.keep(existing, info, revision, namespace);
1492
+ return;
1493
+ }
1494
+ let filter;
1495
+ try {
1496
+ filter = compileFilter(info.filters, { trusted: true });
1497
+ } catch (error) {
1498
+ this.ack(info, revision, namespace, {
1499
+ code: "INVALID_FILTER",
1500
+ message: error.message
1501
+ });
1502
+ return;
1503
+ }
1504
+ const obs = new ObserverImpl(this, info, filter, revision);
1505
+ const onAdded = this.hooks?.onObserverAdded;
1506
+ if (onAdded) {
1507
+ obs.adding = true;
1508
+ const outcome = await this.runHook(() => onAdded.call(this.hooks, obs));
1509
+ obs.adding = false;
1510
+ if (!outcome.ok) {
1511
+ this.ack(info, revision, namespace, {
1512
+ code: outcome.code,
1513
+ message: outcome.message
1514
+ });
1515
+ if (outcome.timedOut) outcome.late.then(() => this.enqueue(() => this.callRemoved(obs)), () => void 0);
1516
+ return;
1517
+ }
1518
+ }
1519
+ if (this.disposed || this.releases !== releases) {
1520
+ await this.callRemoved(obs);
1521
+ return;
1522
+ }
1523
+ this.known.set(obs.id, obs);
1524
+ if (obs.rejection) {
1525
+ this.ack(info, revision, namespace, obs.rejection);
1526
+ return;
1527
+ }
1528
+ this.activate(obs);
1529
+ this.ack(info, revision, namespace);
1530
+ }
1531
+ async remove(id) {
1532
+ const obs = this.known.get(id);
1533
+ if (!obs) return;
1534
+ this.known.delete(id);
1535
+ this.deactivate(obs);
1536
+ await this.callRemoved(obs);
1537
+ }
1538
+ async callRemoved(obs) {
1539
+ const onRemoved = this.hooks?.onObserverRemoved;
1540
+ if (!onRemoved) return;
1541
+ const outcome = await this.runHook(() => onRemoved.call(this.hooks, obs));
1542
+ if (!outcome.ok) this.host.logError(`onObserverRemoved failed for observer ${obs.id} of ${this.functionId}: ${outcome.message}`);
1543
+ }
1544
+ async runHook(fn) {
1545
+ const run = Promise.resolve().then(fn);
1546
+ let timer;
1547
+ const timeoutMs = this.host.hookTimeoutMs();
1548
+ const timeout = new Promise((resolve) => {
1549
+ timer = setTimeout(() => resolve("timeout"), timeoutMs);
1550
+ unrefTimer(timer);
1551
+ });
1552
+ try {
1553
+ if (await Promise.race([run.then(() => "done"), timeout]) === "timeout") return {
1554
+ ok: false,
1555
+ code: "OWNER_TIMEOUT",
1556
+ message: `observe hook of ${this.functionId} still running after ${timeoutMs}ms`,
1557
+ timedOut: true,
1558
+ late: run
1559
+ };
1560
+ return { ok: true };
1561
+ } catch (error) {
1562
+ return {
1563
+ ok: false,
1564
+ ...rejectionBody(error),
1565
+ timedOut: false,
1566
+ late: run
1567
+ };
1568
+ } finally {
1569
+ if (timer) clearTimeout(timer);
1570
+ }
1571
+ }
1572
+ requireOwnerDelivery(what) {
1573
+ if (this.delivery !== "owner") throw new InvocationError({
1574
+ code: "NOT_OWNER_DELIVERED",
1575
+ message: `obs.${what}() needs an owner-delivered function; ${this.functionId} is auto-delivered (observe.delivery)`,
1576
+ function_id: this.functionId
1577
+ });
1578
+ }
1579
+ isActive(obs) {
1580
+ return obs.active && this.known.get(obs.id) === obs;
1581
+ }
1582
+ /**
1583
+ * The caller an event carries (sdk.md §1): inside the function's own
1584
+ * handler, that invocation's caller; inside another handler, that handler;
1585
+ * outside any handler, this worker only.
1586
+ */
1587
+ eventCaller(cur) {
1588
+ if (cur && cur.function_id === this.functionId) return {
1589
+ caller: cur.caller,
1590
+ own: true
1591
+ };
1592
+ const { worker_id, worker_name } = this.host.identity();
1593
+ const caller = worker_id !== void 0 ? {
1594
+ worker_id,
1595
+ worker_name
1596
+ } : { worker_name };
1597
+ if (cur) {
1598
+ caller.function_id = cur.function_id;
1599
+ caller.invocation_id = cur.invocation_id;
1600
+ const parent = stripCaller(cur.caller);
1601
+ if (parent && Object.keys(parent).length > 0) caller.parent = parent;
1602
+ }
1603
+ return {
1604
+ caller,
1605
+ own: false
1606
+ };
1607
+ }
1608
+ /**
1609
+ * Hands `event` to one observer. `false`, and nothing sent, when its
1610
+ * filters reject the event or it is no longer active (removed or rejected
1611
+ * meanwhile): an owner's fan-out loop must not stop for one observer.
1612
+ */
1613
+ emit(obs, event) {
1614
+ this.requireOwnerDelivery("emit");
1615
+ if (!this.isActive(obs)) return false;
1616
+ const cur = callContext();
1617
+ const { caller, own } = this.eventCaller(cur);
1618
+ const metadata = cur?.metadata;
1619
+ if (!obs.filter.matches({
1620
+ input: event,
1621
+ caller,
1622
+ metadata
1623
+ })) return false;
1624
+ const values = { input: event };
1625
+ if (caller !== void 0) values.caller = caller;
1626
+ if (metadata !== void 0) values.metadata = metadata;
1627
+ const trace = cur ? {
1628
+ traceparent: cur.traceparent,
1629
+ baggage: cur.baggage
1630
+ } : this.host.traceContext();
1631
+ this.host.reporter.pushEmit({
1632
+ function_id: this.functionId,
1633
+ namespace: this.namespace,
1634
+ invocation_id: own && cur ? cur.invocation_id : randomUUID(),
1635
+ status: "success",
1636
+ values,
1637
+ captures: obs.capture,
1638
+ started_at_ms: Date.now(),
1639
+ duration_ms: 0,
1640
+ observe_depth: cur ? cur.observe_depth : callDepth(),
1641
+ traceparent: trace.traceparent,
1642
+ baggage: trace.baggage,
1643
+ observer_id: obs.id,
1644
+ event,
1645
+ context: cur
1646
+ });
1647
+ return true;
1648
+ }
1649
+ async call(obs, payload, timeoutMs) {
1650
+ this.requireOwnerDelivery("call");
1651
+ if (!this.isActive(obs)) throw new InvocationError({
1652
+ code: "OBSERVER_NOT_ACTIVE",
1653
+ message: `observer ${obs.id} of ${this.functionId} is not active`,
1654
+ function_id: this.functionId
1655
+ });
1656
+ const cur = callContext();
1657
+ const { caller } = this.eventCaller(cur);
1658
+ if (!obs.filter.matches({
1659
+ input: payload,
1660
+ caller,
1661
+ metadata: cur?.metadata
1662
+ })) throw new InvocationError({
1663
+ code: "FILTERS_NOT_MATCHED",
1664
+ message: `the filters of observer ${obs.id} reject this payload`,
1665
+ function_id: this.functionId
1666
+ });
1667
+ return this.host.callTarget(obs.target, obs.id, payload, timeoutMs);
1668
+ }
1669
+ reject(obs, code, message) {
1670
+ if (obs.adding) {
1671
+ obs.rejection = {
1672
+ code,
1673
+ message
1674
+ };
1675
+ return;
1676
+ }
1677
+ if (this.known.get(obs.id) !== obs) return;
1678
+ obs.rejection = {
1679
+ code,
1680
+ message
1681
+ };
1682
+ this.deactivate(obs);
1683
+ this.host.sendAck({
1684
+ function_id: this.functionId,
1685
+ namespace: this.namespace,
1686
+ id: obs.id,
1687
+ revision: obs.revision,
1688
+ error: {
1689
+ code,
1690
+ message
1691
+ }
1692
+ });
1693
+ }
1694
+ /**
1695
+ * Evaluates `set` (the compiled set captured when the call started) on a
1696
+ * finished local invocation of an auto function, and reports it when an
1697
+ * observer matches. Never throws.
1698
+ */
1699
+ reportLocal(set, init) {
1700
+ if (this.delivery !== "auto" || set.length === 0) return;
1701
+ const doc = {
1702
+ input: init.input,
1703
+ caller: init.caller,
1704
+ metadata: init.metadata
1705
+ };
1706
+ if (init.ok) doc.output = init.output;
1707
+ else doc.error = init.error;
1708
+ const matched = [];
1709
+ const captures = /* @__PURE__ */ new Set();
1710
+ for (const obs of set) {
1711
+ if (!onAccepts(obs.on, init.ok)) continue;
1712
+ if (!obs.filter.matches(doc)) continue;
1713
+ matched.push(obs.id);
1714
+ for (const c of obs.capture) captures.add(c);
1715
+ }
1716
+ if (matched.length === 0) return;
1717
+ const values = { input: init.input };
1718
+ if (init.ok) values.output = init.output;
1719
+ else values.error = init.error;
1720
+ if (init.caller !== void 0) values.caller = init.caller;
1721
+ if (init.metadata !== void 0) values.metadata = init.metadata;
1722
+ this.host.reporter.push({
1723
+ function_id: this.functionId,
1724
+ namespace: this.namespace,
1725
+ invocation_id: init.invocation_id,
1726
+ matched,
1727
+ status: init.ok ? "success" : "error",
1728
+ values,
1729
+ captures,
1730
+ started_at_ms: init.started_at_ms,
1731
+ duration_ms: init.duration_ms,
1732
+ observe_depth: init.observe_depth,
1733
+ traceparent: init.traceparent,
1734
+ baggage: init.baggage
1735
+ });
1736
+ }
1737
+ };
1738
+
1739
+ //#endregion
1740
+ //#region src/observer-handle.ts
1741
+ /**
1742
+ * The observing side of observe (sdk.md §2): the handle `iii.observe`
1743
+ * returns, kept for replay until it is disposed.
1744
+ */
1745
+ /** Active → resolved; error / disposed → rejected; otherwise still waiting. */
1746
+ function settlement(id, state, reason) {
1747
+ if (state === "active") return Promise.resolve();
1748
+ if (state === "error" || state === "disposed") {
1749
+ const why = reason ?? {
1750
+ code: state === "error" ? "OBSERVE_FAILED" : "UNOBSERVED",
1751
+ message: `observer ${id} is ${state}`
1752
+ };
1753
+ return Promise.reject(new ObserveRejection(why.code, why.message));
1754
+ }
1755
+ }
1756
+ var ObserverHandleImpl = class {
1757
+ constructor(id, message, onDispose, logError) {
1758
+ this.id = id;
1759
+ this.message = message;
1760
+ this.onDispose = onDispose;
1761
+ this.logError = logError;
1762
+ this.currentState = "pending";
1763
+ this.listeners = /* @__PURE__ */ new Set();
1764
+ this.undelivered = [];
1765
+ this.delivering = false;
1766
+ this.sent = false;
1767
+ }
1768
+ get state() {
1769
+ return this.currentState;
1770
+ }
1771
+ get reason() {
1772
+ return this.currentReason;
1773
+ }
1774
+ ready() {
1775
+ const settled = settlement(this.id, this.currentState, this.currentReason);
1776
+ if (settled) return settled;
1777
+ return new Promise((resolve, reject) => {
1778
+ const off = this.onStateChange((state, reason) => {
1779
+ const result = settlement(this.id, state, reason);
1780
+ if (!result) return;
1781
+ off();
1782
+ result.then(resolve, reject);
1783
+ });
1784
+ });
1785
+ }
1786
+ onStateChange(listener) {
1787
+ this.listeners.add(listener);
1788
+ return () => {
1789
+ this.listeners.delete(listener);
1790
+ };
1791
+ }
1792
+ async dispose() {
1793
+ if (this.currentState === "disposed") return;
1794
+ this.onDispose(this);
1795
+ this.setState("disposed", {
1796
+ code: "UNOBSERVED",
1797
+ message: "disposed by the observing worker"
1798
+ });
1799
+ }
1800
+ /** @internal A state from the engine (`observeresult`, `observerstatechanged`) or the SDK. */
1801
+ setState(state, reason) {
1802
+ if (this.currentState === "disposed") return;
1803
+ const changed = state !== this.currentState || reason?.code !== this.currentReason?.code || reason?.message !== this.currentReason?.message;
1804
+ this.currentState = state;
1805
+ this.currentReason = reason;
1806
+ if (!changed) return;
1807
+ this.undelivered.push([state, reason]);
1808
+ if (this.delivering) return;
1809
+ this.delivering = true;
1810
+ queueMicrotask(() => this.deliver());
1811
+ }
1812
+ deliver() {
1813
+ for (let next = this.undelivered.shift(); next; next = this.undelivered.shift()) {
1814
+ const [state, reason] = next;
1815
+ for (const listener of [...this.listeners]) try {
1816
+ listener(state, reason);
1817
+ } catch (error) {
1818
+ this.logError(`Observer ${this.id} state listener threw`, error);
1819
+ }
1820
+ }
1821
+ this.delivering = false;
1822
+ }
1823
+ };
1824
+ const STATES = new Set([
1825
+ "pending",
1826
+ "active",
1827
+ "suspended",
1828
+ "error",
1829
+ "disposed"
1830
+ ]);
1831
+ /** A wire state this SDK does not know (a newer engine) reads as `pending`. */
1832
+ function toObserverState(state) {
1833
+ return STATES.has(state) ? state : "pending";
1834
+ }
1835
+
1836
+ //#endregion
1837
+ //#region src/reporter.ts
1838
+ const PART_ORDER = [
1839
+ "input",
1840
+ "output",
1841
+ "error",
1842
+ "caller",
1843
+ "metadata"
1844
+ ];
1845
+ const DEFAULT_REPORTER_LIMITS = {
1846
+ batchItems: 256,
1847
+ lingerMs: 5,
1848
+ maxItems: 1e4,
1849
+ maxBytes: 8 * 1024 * 1024,
1850
+ maxFrameBytes: 16 * 1024 * 1024,
1851
+ statsIntervalMs: 1e4
1852
+ };
1853
+ var ReportItem = class {
1854
+ constructor(init, emit, coalesceKey, context) {
1855
+ this.init = init;
1856
+ this.emit = emit;
1857
+ this.coalesceKey = coalesceKey;
1858
+ this.context = context;
1859
+ this.parts = /* @__PURE__ */ new Map();
1860
+ this.captured = /* @__PURE__ */ new Set();
1861
+ this.json = "";
1862
+ this.bytes = 0;
1863
+ }
1864
+ /** Adds the parts `captures` asks for that are not in the item yet. */
1865
+ capture(captures) {
1866
+ for (const c of captures) {
1867
+ if (this.captured.has(c)) continue;
1868
+ this.captured.add(c);
1869
+ if (!PART_ORDER.includes(c)) continue;
1870
+ const part = c;
1871
+ if (!(part in this.init.values)) continue;
1872
+ const encoded = encodeJson(this.init.values[part]);
1873
+ if (encoded !== void 0) this.parts.set(part, encoded);
1874
+ }
1875
+ }
1876
+ /** What a merge can change, to undo it. */
1877
+ save() {
1878
+ return {
1879
+ matched: this.init.matched.length,
1880
+ captured: [...this.captured],
1881
+ parts: [...this.parts],
1882
+ json: this.json,
1883
+ bytes: this.bytes
1884
+ };
1885
+ }
1886
+ restore(state) {
1887
+ this.init.matched.length = state.matched;
1888
+ this.captured.clear();
1889
+ for (const c of state.captured) this.captured.add(c);
1890
+ this.parts.clear();
1891
+ for (const [part, encoded] of state.parts) this.parts.set(part, encoded);
1892
+ this.json = state.json;
1893
+ this.bytes = state.bytes;
1894
+ }
1895
+ /** Assembles the wire JSON from the pre-encoded parts. */
1896
+ render() {
1897
+ const i = this.init;
1898
+ let s = `{"function_id":${JSON.stringify(i.function_id)}`;
1899
+ if (i.namespace !== void 0) s += `,"namespace":${JSON.stringify(i.namespace)}`;
1900
+ s += `,"invocation_id":${JSON.stringify(i.invocation_id)},"matched":${JSON.stringify(i.matched)}`;
1901
+ s += `,"status":${JSON.stringify(i.status)}`;
1902
+ for (const part of PART_ORDER) {
1903
+ const encoded = this.parts.get(part);
1904
+ if (encoded !== void 0) s += `,"${part}":${encoded}`;
1905
+ }
1906
+ s += `,"started_at_ms":${finite(i.started_at_ms)},"duration_ms":${finite(i.duration_ms)}`;
1907
+ s += `,"observe_depth":${finite(i.observe_depth)}`;
1908
+ if (i.traceparent !== void 0) s += `,"traceparent":${JSON.stringify(i.traceparent)}`;
1909
+ if (i.baggage !== void 0) s += `,"baggage":${JSON.stringify(i.baggage)}`;
1910
+ this.json = wellFormed(`${s}}`);
1911
+ this.bytes = byteLength(this.json);
1912
+ }
1913
+ };
1914
+ /**
1915
+ * Replaces lone surrogates with U+FFFD (CONTRACT parity 32): `JSON.stringify`
1916
+ * writes one as `\ud800`, which the engine's strict decoder refuses, and it
1917
+ * would take the whole batch down with it. `JSON.stringify` escapes nothing
1918
+ * else in that range (a valid pair is written as is), so every `\udXXX`
1919
+ * escape it produced is a lone surrogate. Fast path: no `\ud` at all.
34
1920
  */
35
- const EngineFunctions = {
36
- LIST_FUNCTIONS: "engine::functions::list",
37
- INFO_FUNCTIONS: "engine::functions::info",
38
- LIST_WORKERS: "engine::workers::list",
39
- INFO_WORKERS: "engine::workers::info",
40
- LIST_TRIGGERS: "engine::triggers::list",
41
- INFO_TRIGGERS: "engine::triggers::info",
42
- LIST_REGISTERED_TRIGGERS: "engine::registered-triggers::list",
43
- INFO_REGISTERED_TRIGGERS: "engine::registered-triggers::info",
44
- REGISTER_WORKER: "engine::workers::register"
45
- };
46
- /** Engine trigger types */
47
- const EngineTriggers = { FUNCTIONS_AVAILABLE: "engine::functions-available" };
48
- /** Default reconnection configuration */
49
- const DEFAULT_BRIDGE_RECONNECTION_CONFIG = {
50
- initialDelayMs: 1e3,
51
- maxDelayMs: 3e4,
52
- backoffMultiplier: 2,
53
- jitterFactor: .3,
54
- maxRetries: -1
1921
+ function wellFormed(json) {
1922
+ if (!json.includes("\\ud")) return json;
1923
+ return json.replace(/(\\+)u(d[89a-f][0-9a-f]{2})/g, (match, slashes) => slashes.length % 2 === 1 ? `${slashes.slice(0, -1)}\\ufffd` : match);
1924
+ }
1925
+ function finite(n) {
1926
+ return Number.isFinite(n) ? n : 0;
1927
+ }
1928
+ function byteLength(s) {
1929
+ return utf8ByteLength(s);
1930
+ }
1931
+ /** JSON text of a value as the remote path would send it; `BigInt` is written as its number. */
1932
+ function encodeJson(value) {
1933
+ try {
1934
+ return JSON.stringify(value);
1935
+ } catch (error) {
1936
+ if (!(error instanceof TypeError)) throw error;
1937
+ return JSON.stringify(value, (_k, v) => typeof v === "bigint" ? Number(v) : v);
1938
+ }
1939
+ }
1940
+ const FRAME_HEAD = `{"type":"${"invocationsobserved"}","items":[`;
1941
+ const FRAME_TAIL = "]}";
1942
+ const FRAME_OVERHEAD = byteLength(FRAME_HEAD) + byteLength(FRAME_TAIL);
1943
+ var Reporter = class {
1944
+ constructor(host, limits) {
1945
+ this.host = host;
1946
+ this.items = [];
1947
+ this.bytes = 0;
1948
+ this.perFunction = /* @__PURE__ */ new Map();
1949
+ this.openEmits = /* @__PURE__ */ new Map();
1950
+ this.stats = /* @__PURE__ */ new Map();
1951
+ this.drops = /* @__PURE__ */ new Map();
1952
+ this.windowStart = Date.now();
1953
+ this.unencodable = /* @__PURE__ */ new Set();
1954
+ this.limits = {
1955
+ ...DEFAULT_REPORTER_LIMITS,
1956
+ ...limits
1957
+ };
1958
+ }
1959
+ /** Starts the `localinvocationstats` timer. */
1960
+ start() {
1961
+ if (this.statsTimer) return;
1962
+ this.windowStart = Date.now();
1963
+ this.statsTimer = setInterval(() => this.sendStats(), this.limits.statsIntervalMs);
1964
+ unrefTimer(this.statsTimer);
1965
+ }
1966
+ stop() {
1967
+ if (this.statsTimer) clearInterval(this.statsTimer);
1968
+ this.statsTimer = void 0;
1969
+ if (this.lingerTimer) clearTimeout(this.lingerTimer);
1970
+ this.lingerTimer = void 0;
1971
+ }
1972
+ /** Buffered items (for tests and diagnostics). */
1973
+ get size() {
1974
+ return this.items.length;
1975
+ }
1976
+ /** A matched local invocation of an auto function. */
1977
+ push(init) {
1978
+ const { captures, ...rest } = init;
1979
+ const item = new ReportItem(rest, false, void 0, void 0);
1980
+ if (!this.build(item, captures)) return false;
1981
+ return this.enqueue(item);
1982
+ }
1983
+ /**
1984
+ * An `obs.emit` event. The same event value emitted to several observers
1985
+ * from the same invocation context, before the buffer is flushed, becomes
1986
+ * one item whose `matched` lists them all.
1987
+ */
1988
+ pushEmit(init) {
1989
+ const { observer_id, event, context, captures, ...rest } = init;
1990
+ const merge = this.openEmits.get(event)?.find((it) => it.init.function_id === rest.function_id && it.context === context && !it.init.matched.includes(observer_id));
1991
+ if (merge) return this.merge(merge, observer_id, captures);
1992
+ const item = new ReportItem({
1993
+ ...rest,
1994
+ matched: [observer_id]
1995
+ }, true, event, context);
1996
+ if (!this.build(item, captures)) return false;
1997
+ return this.enqueue(item);
1998
+ }
1999
+ /** Makes a buffered emit item a merge target. Only items in the buffer are: a flush re-indexes. */
2000
+ index(item) {
2001
+ if (!item.emit) return;
2002
+ const list = this.openEmits.get(item.coalesceKey);
2003
+ if (list) list.push(item);
2004
+ else this.openEmits.set(item.coalesceKey, [item]);
2005
+ }
2006
+ /** Adds an observer (and its captures) to a buffered emit item, within the same bounds as a new item. */
2007
+ merge(item, observerId, captures) {
2008
+ const fn = item.init.function_id;
2009
+ const before = item.save();
2010
+ try {
2011
+ item.init.matched.push(observerId);
2012
+ item.capture(captures);
2013
+ item.render();
2014
+ } catch (error) {
2015
+ item.restore(before);
2016
+ this.logUnencodable(fn, error);
2017
+ return false;
2018
+ }
2019
+ const growth = item.bytes - before.bytes;
2020
+ const reason = this.tooLarge(item) ? "TOO_LARGE" : growth > 0 && this.bytes + this.host.pendingBytes() + growth > this.limits.maxBytes ? "BUFFER_FULL" : void 0;
2021
+ if (reason) {
2022
+ item.restore(before);
2023
+ this.drop(fn, reason);
2024
+ return false;
2025
+ }
2026
+ this.bytes += growth;
2027
+ return true;
2028
+ }
2029
+ build(item, captures) {
2030
+ try {
2031
+ item.capture(captures);
2032
+ item.render();
2033
+ return true;
2034
+ } catch (error) {
2035
+ this.logUnencodable(item.init.function_id, error);
2036
+ return false;
2037
+ }
2038
+ }
2039
+ logUnencodable(functionId, error) {
2040
+ if (this.unencodable.has(functionId)) return;
2041
+ this.unencodable.add(functionId);
2042
+ this.host.logError(`Cannot encode an observed invocation of ${functionId} as JSON; it is not reported`, error);
2043
+ }
2044
+ /**
2045
+ * TOO_LARGE is measured against the buffer (8 MiB), the smaller of the two
2046
+ * limits: an item that can never be buffered. It also always fits a 16 MiB frame.
2047
+ */
2048
+ tooLarge(item) {
2049
+ return item.bytes > this.limits.maxBytes || item.bytes + FRAME_OVERHEAD > this.limits.maxFrameBytes;
2050
+ }
2051
+ enqueue(item) {
2052
+ const fn = item.init.function_id;
2053
+ if (this.tooLarge(item)) {
2054
+ this.drop(fn, "TOO_LARGE");
2055
+ return false;
2056
+ }
2057
+ if (this.items.length >= this.limits.maxItems || this.bytes + this.host.pendingBytes() + item.bytes > this.limits.maxBytes) {
2058
+ this.drop(fn, "BUFFER_FULL");
2059
+ return false;
2060
+ }
2061
+ this.items.push(item);
2062
+ this.bytes += item.bytes;
2063
+ this.perFunction.set(fn, (this.perFunction.get(fn) ?? 0) + 1);
2064
+ this.index(item);
2065
+ if (this.items.length >= this.limits.batchItems) this.flush();
2066
+ else this.arm(this.limits.lingerMs);
2067
+ return true;
2068
+ }
2069
+ arm(ms) {
2070
+ if (this.lingerTimer) return;
2071
+ this.lingerTimer = setTimeout(() => {
2072
+ this.lingerTimer = void 0;
2073
+ this.flush();
2074
+ }, ms);
2075
+ unrefTimer(this.lingerTimer);
2076
+ }
2077
+ /** Counts a report the SDK dropped (`BUFFER_FULL`, `TOO_LARGE`, `INACTIVE`). */
2078
+ drop(functionId, reason, count = 1) {
2079
+ let byReason = this.drops.get(functionId);
2080
+ if (!byReason) {
2081
+ byReason = /* @__PURE__ */ new Map();
2082
+ this.drops.set(functionId, byReason);
2083
+ }
2084
+ byReason.set(reason, (byReason.get(reason) ?? 0) + count);
2085
+ }
2086
+ /** Counts one local invocation (for `localinvocationstats`). */
2087
+ recordLocal(functionId, ok, durationMs) {
2088
+ let s = this.stats.get(functionId);
2089
+ if (!s) {
2090
+ s = {
2091
+ count: 0,
2092
+ errors: 0,
2093
+ duration_ms_sum: 0
2094
+ };
2095
+ this.stats.set(functionId, s);
2096
+ }
2097
+ s.count++;
2098
+ if (!ok) s.errors++;
2099
+ s.duration_ms_sum += durationMs;
2100
+ }
2101
+ /**
2102
+ * Discards a function's buffered items, counted as `INACTIVE`: the
2103
+ * function is unregistered, or the engine refused it
2104
+ * (`FUNCTION_NAMESPACE_CONFLICT`), so they could never be confirmed.
2105
+ */
2106
+ discard(functionId) {
2107
+ const count = this.perFunction.get(functionId);
2108
+ if (!count) return;
2109
+ this.drop(functionId, "INACTIVE", count);
2110
+ this.setItems(this.items.filter((it) => it.init.function_id !== functionId));
2111
+ }
2112
+ /**
2113
+ * Sends what can be sent: items whose function the engine confirmed on the
2114
+ * current connection, in frames under the frame limit, while the socket's
2115
+ * unwritten bytes stay within the buffer bound. The rest stays.
2116
+ */
2117
+ flush() {
2118
+ if (this.lingerTimer) {
2119
+ clearTimeout(this.lingerTimer);
2120
+ this.lingerTimer = void 0;
2121
+ }
2122
+ if (this.items.length === 0 || !this.host.online()) return;
2123
+ const status = /* @__PURE__ */ new Map();
2124
+ for (const fn of this.perFunction.keys()) status.set(fn, this.host.status(fn));
2125
+ if (![...status.values()].some((s) => s !== "wait")) return;
2126
+ const ready = [];
2127
+ const held = [];
2128
+ for (const item of this.items) {
2129
+ const st = status.get(item.init.function_id);
2130
+ if (st === "ready") ready.push(item);
2131
+ else if (st === "wait") held.push(item);
2132
+ else this.drop(item.init.function_id, "INACTIVE");
2133
+ }
2134
+ this.setItems(held);
2135
+ let frame = [];
2136
+ let frameBytes = FRAME_OVERHEAD;
2137
+ let blocked = false;
2138
+ const unsent = [];
2139
+ const send = () => {
2140
+ if (frame.length === 0) return;
2141
+ const data = `${FRAME_HEAD}${frame.map((it) => it.json).join(",")}${FRAME_TAIL}`;
2142
+ const pending = blocked ? 0 : this.host.pendingBytes();
2143
+ if (blocked || pending > 0 && pending + frameBytes > this.limits.maxBytes || !this.host.sendFrame(data)) {
2144
+ blocked = true;
2145
+ unsent.push(...frame);
2146
+ }
2147
+ frame = [];
2148
+ frameBytes = FRAME_OVERHEAD;
2149
+ };
2150
+ for (const item of ready) {
2151
+ if (item.bytes + FRAME_OVERHEAD > this.limits.maxFrameBytes) {
2152
+ this.drop(item.init.function_id, "TOO_LARGE");
2153
+ continue;
2154
+ }
2155
+ const separator = frame.length > 0 ? 1 : 0;
2156
+ if (frameBytes + separator + item.bytes > this.limits.maxFrameBytes) send();
2157
+ frameBytes += (frame.length > 0 ? 1 : 0) + item.bytes;
2158
+ frame.push(item);
2159
+ }
2160
+ send();
2161
+ if (unsent.length > 0) {
2162
+ this.requeue(unsent);
2163
+ if (this.host.online()) this.arm(this.limits.lingerMs * 20);
2164
+ }
2165
+ }
2166
+ /** Replaces the buffer, keeping the per-function counts and the emit coalescing index in step. */
2167
+ setItems(items) {
2168
+ this.items = items;
2169
+ this.bytes = 0;
2170
+ this.perFunction.clear();
2171
+ this.openEmits.clear();
2172
+ for (const item of items) {
2173
+ this.bytes += item.bytes;
2174
+ const fn = item.init.function_id;
2175
+ this.perFunction.set(fn, (this.perFunction.get(fn) ?? 0) + 1);
2176
+ this.index(item);
2177
+ }
2178
+ }
2179
+ /** Puts items back at the front of the buffer, within its bounds. */
2180
+ requeue(items) {
2181
+ const kept = [];
2182
+ let bytes = this.bytes;
2183
+ let count = this.items.length;
2184
+ for (const item of items) {
2185
+ if (count >= this.limits.maxItems || bytes + item.bytes > this.limits.maxBytes) {
2186
+ this.drop(item.init.function_id, "BUFFER_FULL");
2187
+ continue;
2188
+ }
2189
+ kept.push(item);
2190
+ bytes += item.bytes;
2191
+ count++;
2192
+ }
2193
+ this.setItems([...kept, ...this.items]);
2194
+ }
2195
+ /** Sends `localinvocationstats` when there is anything to report; keeps counting while offline. */
2196
+ sendStats(now = Date.now()) {
2197
+ if (this.stats.size === 0 && this.drops.size === 0) {
2198
+ this.windowStart = now;
2199
+ return false;
2200
+ }
2201
+ if (!this.host.online()) return false;
2202
+ const message = buildLocalInvocationStats(now - this.windowStart, this.stats, this.drops);
2203
+ if (!this.host.sendFrame(JSON.stringify({
2204
+ type: "localinvocationstats",
2205
+ ...message
2206
+ }))) return false;
2207
+ this.stats.clear();
2208
+ this.drops.clear();
2209
+ this.windowStart = now;
2210
+ return true;
2211
+ }
2212
+ /** Forgets everything buffered (the engine does not support observe). */
2213
+ clear() {
2214
+ this.setItems([]);
2215
+ }
55
2216
  };
56
- /** Default invocation timeout in milliseconds */
57
- const DEFAULT_INVOCATION_TIMEOUT_MS = 3e4;
2217
+ /** `localinvocationstats` from the counters, in insertion order. */
2218
+ function buildLocalInvocationStats(windowMs, stats, drops) {
2219
+ return {
2220
+ window_ms: Math.max(0, Math.round(windowMs)),
2221
+ functions: [...stats].map(([function_id, s]) => ({
2222
+ function_id,
2223
+ count: s.count,
2224
+ errors: s.errors,
2225
+ duration_ms_sum: s.duration_ms_sum
2226
+ })),
2227
+ dropped_reports: [...drops].flatMap(([function_id, byReason]) => [...byReason].map(([reason, count]) => ({
2228
+ function_id,
2229
+ reason,
2230
+ count
2231
+ })))
2232
+ };
2233
+ }
58
2234
 
59
2235
  //#endregion
60
2236
  //#region src/iii.ts
2237
+ const MAX_JSON_FRAME_BYTES = 16 * 1024 * 1024;
2238
+ const JSON_ENCODER = new TextEncoder();
2239
+ const PAYLOAD_SIZE_DOCS = "https://iii.dev/docs/creating-workers/channels#payload-size";
2240
+ function payloadTooLargeMessage(size) {
2241
+ return `Serialized JSON envelope is ${size} bytes; limit is ${MAX_JSON_FRAME_BYTES} bytes. Use channels for larger payloads: ${PAYLOAD_SIZE_DOCS}`;
2242
+ }
2243
+ function createPayloadTooLargeError(size, functionId) {
2244
+ return new InvocationError({
2245
+ code: "payload_too_large",
2246
+ message: payloadTooLargeMessage(size),
2247
+ function_id: functionId
2248
+ });
2249
+ }
2250
+ function isPayloadTooLargeError(error) {
2251
+ return error instanceof Error && "code" in error && error.code === "payload_too_large";
2252
+ }
61
2253
  /** Short random suffix; `crypto.randomUUID` is unavailable on insecure origins. */
62
2254
  function randomId() {
63
2255
  const c = globalThis.crypto;
@@ -92,10 +2284,120 @@ function callNamespace(explicit, worker, source) {
92
2284
  return explicit ?? worker;
93
2285
  }
94
2286
  /** Resolve one function invocation without leaking engine and configuration builtins into a worker namespace. */
95
- function invocationNamespace(explicit, worker, functionId) {
96
- const namespace = callNamespace(explicit, worker, "TriggerRequest.namespace");
2287
+ function invocationNamespace(explicit, worker, functionId, source = "TriggerRequest.namespace") {
2288
+ const namespace = callNamespace(explicit, worker, source);
97
2289
  return explicit === void 0 && (functionId.startsWith("engine::") || functionId.startsWith("configuration::")) ? "default" : namespace;
98
2290
  }
2291
+ const MIGRATION_GUIDE = "https://iii.dev/docs/upgrading/from-0-24-x";
2292
+ /** CONTRACT §5: one warning per page per deprecated API. */
2293
+ const DEPRECATIONS = {
2294
+ registerTrigger: `registerTrigger is deprecated and will be removed in a future release. Use iii.observe(source, target) instead. Migration guide: ${MIGRATION_GUIDE}`,
2295
+ registerTriggerType: `registerTriggerType is deprecated and will be removed in a future release. Register a function with an observe descriptor (registerFunction(id, handler, { observe: { ... } })) instead. Migration guide: ${MIGRATION_GUIDE}`
2296
+ };
2297
+ const deprecationsWarned = /* @__PURE__ */ new Set();
2298
+ /**
2299
+ * Local dispatch hands the handler a copy of the caller's payload and the
2300
+ * caller a copy of the result (value semantics, as over the wire):
2301
+ * `structuredClone`, or JSON for what it cannot clone (functions, class
2302
+ * instances with methods the clone would drop).
2303
+ */
2304
+ function cloneValue(value) {
2305
+ if (value === null || typeof value !== "object") return typeof value === "function" || typeof value === "symbol" ? void 0 : value;
2306
+ if (typeof structuredClone === "function") try {
2307
+ return structuredClone(value);
2308
+ } catch {}
2309
+ const text = JSON.stringify(value);
2310
+ return text === void 0 ? void 0 : JSON.parse(text);
2311
+ }
2312
+ const UNSUPPORTED_REASON = {
2313
+ code: "UNSUPPORTED",
2314
+ message: "the engine does not support observe (no observe.v1 in its features); upgrade it to 0.25 or later"
2315
+ };
2316
+ /** `args_format` needs `delivery: 'owner'`: an auto function's events are its invocations, offered to every observer. */
2317
+ function validateObserveHooks(functionId, hooks) {
2318
+ if (!hooks) return;
2319
+ const delivery = hooks.delivery;
2320
+ if (delivery !== void 0 && delivery !== "auto" && delivery !== "owner") throw new InvocationError({
2321
+ code: "INVALID_OBSERVE_DESCRIPTOR",
2322
+ message: `observe.delivery must be 'auto' or 'owner', got ${JSON.stringify(delivery)}`,
2323
+ function_id: functionId
2324
+ });
2325
+ if (hooks.args_format !== void 0 && delivery !== "owner") throw new InvocationError({
2326
+ code: "INVALID_OBSERVE_DESCRIPTOR",
2327
+ message: "observe.args_format requires delivery: 'owner' (an auto function takes no args)",
2328
+ function_id: functionId
2329
+ });
2330
+ }
2331
+ /**
2332
+ * The error a call that timed out rejects with, on the remote and the local
2333
+ * path: an `Error` (its message unchanged from earlier releases) that also
2334
+ * carries `code: 'TIMEOUT'` and the `function_id`, like the Node SDK's.
2335
+ */
2336
+ function timeoutError(ms, functionId) {
2337
+ return Object.assign(/* @__PURE__ */ new Error(`Invocation timeout after ${ms}ms: ${functionId}`), {
2338
+ code: "TIMEOUT",
2339
+ function_id: functionId
2340
+ });
2341
+ }
2342
+ /** What a handler failure reports when the thrown value cannot even be read (a getter or `toString` that throws). */
2343
+ const UNREADABLE_FAILURE = "the handler failed with a value that cannot be read";
2344
+ function safeString(value) {
2345
+ try {
2346
+ return String(value);
2347
+ } catch {
2348
+ return UNREADABLE_FAILURE;
2349
+ }
2350
+ }
2351
+ /**
2352
+ * An error body as the engine sends it, and as this SDK's own calls reject
2353
+ * with: a plain (JSON-parsed) object with a string `code`, a string `message`
2354
+ * and, optionally, a string `stacktrace`. A class instance or anything else
2355
+ * with such fields is not one: it is reported through `String()`.
2356
+ */
2357
+ function isEngineErrorBody(value) {
2358
+ if (value === null || typeof value !== "object") return false;
2359
+ const proto = Object.getPrototypeOf(value);
2360
+ if (proto !== Object.prototype && proto !== null) return false;
2361
+ const body = value;
2362
+ return typeof body.code === "string" && typeof body.message === "string" && (body.stacktrace === void 0 || typeof body.stacktrace === "string");
2363
+ }
2364
+ /**
2365
+ * The error a handler's failure becomes, the same on the local and the remote
2366
+ * path (code `invocation_failed`):
2367
+ * - an `Error`, from any realm (an iframe's too): its message and stack;
2368
+ * - an engine error body (a failed call's rejection, rethrown): its message and stacktrace;
2369
+ * - anything else: `String(value)`.
2370
+ * Never throws: when reading the value throws, a fixed message is reported, so
2371
+ * the caller always gets its answer.
2372
+ */
2373
+ function handlerErrorBody(error) {
2374
+ try {
2375
+ if (error instanceof Error || Object.prototype.toString.call(error) === "[object Error]") {
2376
+ const { message, stack } = error;
2377
+ return {
2378
+ code: "invocation_failed",
2379
+ message: typeof message === "string" ? message : safeString(message),
2380
+ stacktrace: typeof stack === "string" ? stack : void 0
2381
+ };
2382
+ }
2383
+ if (isEngineErrorBody(error)) return {
2384
+ code: "invocation_failed",
2385
+ message: error.message,
2386
+ stacktrace: error.stacktrace
2387
+ };
2388
+ return {
2389
+ code: "invocation_failed",
2390
+ message: String(error),
2391
+ stacktrace: void 0
2392
+ };
2393
+ } catch {
2394
+ return {
2395
+ code: "invocation_failed",
2396
+ message: safeString(error),
2397
+ stacktrace: void 0
2398
+ };
2399
+ }
2400
+ }
99
2401
  function resolveNamespace(optionNamespace) {
100
2402
  if (optionNamespace !== void 0 && optionNamespace.trim() === "") throw new Error(`namespace is empty: options.namespace was set to ${JSON.stringify(optionNamespace)}. Give it a name, or leave it unset to register in \`default\`.`);
101
2403
  return optionNamespace;
@@ -113,20 +2415,28 @@ var Sdk = class {
113
2415
  this.connectionState = "disconnected";
114
2416
  this.connectionListeners = /* @__PURE__ */ new Set();
115
2417
  this.isShuttingDown = false;
2418
+ this.observers = /* @__PURE__ */ new Map();
2419
+ this.engineFeatures = /* @__PURE__ */ new Set();
2420
+ this.registeredOnConnection = false;
2421
+ this.connectionEpoch = 0;
2422
+ this.hooksInactiveWarned = /* @__PURE__ */ new Set();
2423
+ this.observeQueue = [];
116
2424
  this.registerTriggerType = (triggerType, handler) => {
117
- this.sendMessage("registertriggertype", triggerType, true);
118
- this.triggerTypes.set(triggerType.id, {
119
- message: {
120
- ...triggerType,
121
- message_type: "registertriggertype"
122
- },
2425
+ this.warnDeprecated("registerTriggerType");
2426
+ const message = this.snapshotRegistration({
2427
+ ...triggerType,
2428
+ message_type: "registertriggertype"
2429
+ });
2430
+ this.sendMessage("registertriggertype", message, true);
2431
+ this.triggerTypes.set(message.id, {
2432
+ message,
123
2433
  handler
124
2434
  });
125
2435
  return {
126
- id: triggerType.id,
2436
+ id: message.id,
127
2437
  registerTrigger: (functionId, config) => {
128
2438
  return this.registerTrigger({
129
- type: triggerType.id,
2439
+ type: message.id,
130
2440
  function_id: functionId,
131
2441
  config,
132
2442
  namespace: this.namespace
@@ -135,7 +2445,7 @@ var Sdk = class {
135
2445
  registerFunction: (functionId, handler, config) => {
136
2446
  const ref = this.registerFunction(functionId, handler);
137
2447
  this.registerTrigger({
138
- type: triggerType.id,
2448
+ type: message.id,
139
2449
  function_id: functionId,
140
2450
  config,
141
2451
  namespace: this.namespace
@@ -143,17 +2453,22 @@ var Sdk = class {
143
2453
  return ref;
144
2454
  },
145
2455
  unregister: () => {
146
- this.unregisterTriggerType(triggerType);
2456
+ this.unregisterTriggerType(message);
147
2457
  }
148
2458
  };
149
2459
  };
150
2460
  this.unregisterTriggerType = (triggerType) => {
151
- this.sendMessage("unregistertriggertype", triggerType, true);
152
- this.triggerTypes.delete(triggerType.id);
2461
+ const { id, namespace } = triggerType;
2462
+ this.sendMessage("unregistertriggertype", namespace !== void 0 ? {
2463
+ id,
2464
+ namespace
2465
+ } : { id }, true);
2466
+ this.triggerTypes.delete(id);
153
2467
  };
154
2468
  this.registerTrigger = (trigger) => {
2469
+ this.warnDeprecated("registerTrigger");
155
2470
  const id = randomUUID();
156
- const fullTrigger = {
2471
+ const fullTrigger = this.snapshotRegistration({
157
2472
  ...trigger,
158
2473
  id,
159
2474
  message_type: "registertrigger",
@@ -161,7 +2476,7 @@ var Sdk = class {
161
2476
  const namespace = callNamespace(trigger.namespace, this.namespace, "RegisterTriggerInput.namespace");
162
2477
  return namespace !== void 0 ? { namespace } : {};
163
2478
  })()
164
- };
2479
+ });
165
2480
  this.sendMessage("registertrigger", fullTrigger, true);
166
2481
  this.triggers.set(id, fullTrigger);
167
2482
  return { unregister: () => {
@@ -176,27 +2491,82 @@ var Sdk = class {
176
2491
  this.registerFunction = (functionId, handlerOrInvocation, options) => {
177
2492
  if (!functionId || functionId.trim() === "") throw new Error("id is required");
178
2493
  if (this.functions.has(functionId)) throw new Error(`function id already registered: ${functionId}`);
179
- const fullMessage = {
180
- ...options,
2494
+ const { observe: hooks, localDispatch, ...wireOptions } = options ?? {};
2495
+ validateObserveHooks(functionId, hooks);
2496
+ const descriptor = observeDescriptor(hooks);
2497
+ const fullMessage = this.snapshotRegistration({
2498
+ ...wireOptions,
2499
+ ...descriptor ? { observe: descriptor } : {},
181
2500
  id: functionId,
182
2501
  message_type: "registerfunction"
183
- };
2502
+ });
184
2503
  this.sendMessage("registerfunction", fullMessage, true);
2504
+ const observe = new FunctionObservers(functionId, hooks, localDispatch !== false, true, this.observeHost);
2505
+ if (observe.needsObserve && this.registeredOnConnection && !this.engineFeatures.has("observe.v1")) this.warnHooksInactive(functionId);
185
2506
  const handler = handlerOrInvocation;
186
2507
  this.functions.set(functionId, {
187
2508
  message: fullMessage,
188
- handler: async (input, _traceparent, _baggage) => {
189
- return await handler(input);
2509
+ observe,
2510
+ handler: async (input, metadata) => {
2511
+ return await handler(input, metadata);
190
2512
  }
191
2513
  });
192
2514
  return {
193
2515
  id: functionId,
194
2516
  unregister: () => {
2517
+ if (this.functions.get(functionId)?.observe !== observe) return;
195
2518
  this.sendMessage("unregisterfunction", { id: functionId }, true);
196
2519
  this.functions.delete(functionId);
197
- }
2520
+ observe.dispose();
2521
+ },
2522
+ isObserved: () => observe.isObserved(),
2523
+ observers: () => observe.observers()
198
2524
  };
199
2525
  };
2526
+ this.observe = (source, target, options) => {
2527
+ if (!source || typeof source.function_id !== "string" || source.function_id.trim() === "") throw new Error("observe: source.function_id is required");
2528
+ const targetId = typeof target === "string" ? target : target?.function_id;
2529
+ if (typeof targetId !== "string" || targetId.trim() === "") throw new Error("observe: target is required (the id of a registered function)");
2530
+ const id = options?.id ?? randomUUID();
2531
+ if (this.observers.has(id)) throw new Error(`observe: observer id already in use: ${id}`);
2532
+ const onDispose = (h) => this.disposeObserver(h);
2533
+ const logError = (msg, error) => this.logError(msg, error);
2534
+ const refused = (reason) => {
2535
+ const handle = new ObserverHandleImpl(id, {
2536
+ id,
2537
+ source: { function_id: source.function_id },
2538
+ target: { function_id: targetId }
2539
+ }, onDispose, logError);
2540
+ handle.setState("error", reason);
2541
+ return handle;
2542
+ };
2543
+ if (source.filters !== void 0) try {
2544
+ compileFilter(source.filters);
2545
+ } catch (error) {
2546
+ if (!(error instanceof FilterError)) throw error;
2547
+ return refused({
2548
+ code: error.code,
2549
+ message: error.message
2550
+ });
2551
+ }
2552
+ let message;
2553
+ try {
2554
+ message = buildObserveMessage(id, source, target, options, (explicit, functionId, field) => invocationNamespace(explicit, this.namespace, functionId, field));
2555
+ } catch (error) {
2556
+ if (!(error instanceof TypeError)) throw error;
2557
+ return refused({
2558
+ code: "INVALID_ARGS",
2559
+ message: `observe: the source or options are not JSON: ${error.message}`
2560
+ });
2561
+ }
2562
+ const handle = new ObserverHandleImpl(id, message, onDispose, logError);
2563
+ this.observers.set(id, handle);
2564
+ if (this.registeredOnConnection && this.isOpen()) if (this.engineFeatures.has("observe.v1")) this.sendObserve(handle);
2565
+ else handle.setState("error", UNSUPPORTED_REASON);
2566
+ return handle;
2567
+ };
2568
+ this.currentInvocation = () => publicContext(currentContext());
2569
+ this.withInvocation = (invocation, fn) => enterInvocation(contextFromView(invocation), fn, MAX_RUNNING_INVOCATION_MS);
200
2570
  this.__helpers_create_channel = async (bufferSize) => {
201
2571
  const result = await this.trigger({
202
2572
  function_id: "engine::channels::create",
@@ -210,45 +2580,25 @@ var Sdk = class {
210
2580
  };
211
2581
  };
212
2582
  this.trigger = async (request) => {
213
- const { function_id, payload, action, timeoutMs } = request;
2583
+ const { function_id, action } = request;
214
2584
  const namespace = invocationNamespace(request.namespace, this.namespace, function_id);
215
- const effectiveTimeout = timeoutMs ?? this.invocationTimeoutMs;
216
- if (action?.type === "void") {
217
- this.sendMessage("invokefunction", {
218
- function_id,
219
- data: payload,
220
- action,
221
- ...namespace !== void 0 ? { namespace } : {}
222
- });
223
- return;
224
- }
225
- const invocation_id = randomUUID();
226
- return new Promise((resolve, reject) => {
227
- const timeout = setTimeout(() => {
228
- if (this.invocations.get(invocation_id)) {
229
- this.invocations.delete(invocation_id);
230
- reject(/* @__PURE__ */ new Error(`Invocation timeout after ${effectiveTimeout}ms: ${function_id}`));
2585
+ if (request.dispatch !== "remote" && action?.type !== "enqueue") {
2586
+ const fn = this.functions.get(function_id);
2587
+ const observe = fn?.observe;
2588
+ if (fn?.handler && observe?.localDispatch && (namespace === void 0 || namespace === observe.namespace)) {
2589
+ const depth = callLocalDepth();
2590
+ if (depth < 64) return this.invokeLocal(function_id, fn.handler, observe, request);
2591
+ if (!this.isOpen()) {
2592
+ if (depth < 256) return this.invokeLocal(function_id, fn.handler, observe, request);
2593
+ throw new InvocationError({
2594
+ code: "LOCAL_DEPTH_EXCEEDED",
2595
+ message: `${function_id} is called ${depth} local calls deep: past ${64} the call needs the engine, and the socket is closed`,
2596
+ function_id
2597
+ });
231
2598
  }
232
- }, effectiveTimeout);
233
- this.invocations.set(invocation_id, {
234
- resolve: (result) => {
235
- clearTimeout(timeout);
236
- resolve(result);
237
- },
238
- reject: (error) => {
239
- clearTimeout(timeout);
240
- reject(error);
241
- },
242
- timeout
243
- });
244
- this.sendMessage("invokefunction", {
245
- invocation_id,
246
- function_id,
247
- data: payload,
248
- action,
249
- ...namespace !== void 0 ? { namespace } : {}
250
- });
251
- });
2599
+ }
2600
+ }
2601
+ return this.invokeRemote(request, namespace);
252
2602
  };
253
2603
  this.__helpers_create_stream = (streamName, stream) => {
254
2604
  this.registerFunction(`stream::get(${streamName})`, stream.get.bind(stream));
@@ -260,6 +2610,13 @@ var Sdk = class {
260
2610
  this.getFatalError = () => this.fatalError;
261
2611
  this.shutdown = async () => {
262
2612
  this.isShuttingDown = true;
2613
+ try {
2614
+ this.reporter.flush();
2615
+ this.reporter.sendStats();
2616
+ } catch (error) {
2617
+ this.logError("Failed to flush observed invocations on shutdown", error);
2618
+ }
2619
+ this.reporter.stop();
263
2620
  this.clearReconnectTimeout();
264
2621
  for (const [_id, invocation] of this.invocations) {
265
2622
  if (invocation.timeout) clearTimeout(invocation.timeout);
@@ -269,9 +2626,11 @@ var Sdk = class {
269
2626
  if (this.ws) {
270
2627
  this.ws.onopen = null;
271
2628
  this.ws.onclose = null;
272
- this.ws.onerror = null;
2629
+ this.ws.onerror = () => void 0;
273
2630
  this.ws.onmessage = null;
274
- this.ws.close();
2631
+ try {
2632
+ this.ws.close();
2633
+ } catch {}
275
2634
  this.ws = void 0;
276
2635
  }
277
2636
  this.setConnectionState("disconnected");
@@ -294,8 +2653,258 @@ var Sdk = class {
294
2653
  ...DEFAULT_BRIDGE_RECONNECTION_CONFIG,
295
2654
  ...options?.reconnectionConfig
296
2655
  };
2656
+ this.reporter = new Reporter({
2657
+ online: () => this.observeOnline(),
2658
+ status: (functionId) => {
2659
+ const state = this.functions.get(functionId)?.observe;
2660
+ if (!state || state.releasedEpoch === this.connectionEpoch) return "gone";
2661
+ return state.confirmedEpoch === this.connectionEpoch ? "ready" : "wait";
2662
+ },
2663
+ sendFrame: (data) => {
2664
+ if (!this.isOpen()) return false;
2665
+ this.sendMessageRaw(data);
2666
+ return true;
2667
+ },
2668
+ pendingBytes: () => this.ws?.bufferedAmount ?? 0,
2669
+ logError: (message, error) => this.logError(message, error)
2670
+ }, options?.observe?.reporter);
2671
+ this.observeHost = {
2672
+ identity: () => this.workerId !== void 0 ? {
2673
+ worker_id: this.workerId,
2674
+ worker_name: this.workerName
2675
+ } : { worker_name: this.workerName },
2676
+ sendAck: (ack) => this.sendMessage("observerack", buildObserverAck(ack), true),
2677
+ reporter: this.reporter,
2678
+ callTarget: (target, observerId, payload, timeoutMs) => this.invokeRemote({
2679
+ function_id: target,
2680
+ payload,
2681
+ timeoutMs
2682
+ }, void 0, { observer_id: observerId }),
2683
+ logError: (message, error) => this.logError(message, error),
2684
+ hookTimeoutMs: () => options?.observe?.hookTimeoutMs ?? 3e4,
2685
+ traceContext: () => ({})
2686
+ };
2687
+ this.reporter.start();
297
2688
  this.connect();
298
2689
  }
2690
+ warnDeprecated(api) {
2691
+ if (deprecationsWarned.has(api)) return;
2692
+ deprecationsWarned.add(api);
2693
+ console.warn(`[iii] ${DEPRECATIONS[api]}`);
2694
+ }
2695
+ logError(message, error) {
2696
+ if (error === void 0) console.error(`[iii] ${message}`);
2697
+ else console.error(`[iii] ${message}`, error);
2698
+ }
2699
+ sendObserve(handle) {
2700
+ this.sendMessage("observe", handle.message, true);
2701
+ handle.sent = true;
2702
+ }
2703
+ disposeObserver(handle) {
2704
+ if (this.observers.get(handle.id) === handle) this.observers.delete(handle.id);
2705
+ if (!handle.sent) return;
2706
+ this.sendObserveFamily("unobserve", { id: handle.id });
2707
+ }
2708
+ /**
2709
+ * An observe-family frame that must not be lost to a disconnect (`unobserve`:
2710
+ * a reattach would otherwise keep the observer alive). Without a registered
2711
+ * connection it waits for the next `WorkerRegistered`, and goes out only if
2712
+ * that engine advertises `observe.v1`.
2713
+ */
2714
+ sendObserveFamily(type, message) {
2715
+ if (!this.isOpen() || !this.registeredOnConnection) this.observeQueue.push({
2716
+ type,
2717
+ ...message
2718
+ });
2719
+ else if (this.engineFeatures.has("observe.v1")) this.sendMessage(type, message, true);
2720
+ }
2721
+ warnHooksInactive(functionId) {
2722
+ if (this.hooksInactiveWarned.has(functionId)) return;
2723
+ this.hooksInactiveWarned.add(functionId);
2724
+ console.warn(`[iii] Function "${functionId}" declares observe hooks or owner delivery, but the engine does not support observe (observe.v1): it is registered as a plain function and its observe hooks are inactive.`);
2725
+ }
2726
+ /** Connected to an engine that advertised `observe.v1`. */
2727
+ observeOnline() {
2728
+ return this.isOpen() && this.registeredOnConnection && this.engineFeatures.has("observe.v1");
2729
+ }
2730
+ /**
2731
+ * What an outgoing call carries from the invocation it is made in: `caller`
2732
+ * and `observe_depth` (engines with `observe.v1` only), and the trace
2733
+ * context. The browser has no OpenTelemetry, so `traceparent` / `baggage`
2734
+ * are the request's own, else the invocation's (see `callContext`), else
2735
+ * none. Outside any scope `observe_depth` is the deepest running
2736
+ * invocation's (`callDepth`), so the loop guard holds after an `await`.
2737
+ */
2738
+ outgoingFields(request) {
2739
+ const cur = callContext();
2740
+ const fields = {
2741
+ traceparent: request.traceparent ?? cur?.traceparent,
2742
+ baggage: request.baggage ?? cur?.baggage
2743
+ };
2744
+ if (this.engineFeatures.has("observe.v1")) {
2745
+ if (cur) fields.caller = callerFor(cur);
2746
+ fields.observe_depth = cur ? cur.observe_depth : callDepth();
2747
+ }
2748
+ return fields;
2749
+ }
2750
+ /** The routed path: an `InvokeFunction` through the engine. */
2751
+ invokeRemote(request, namespace, activation) {
2752
+ const { function_id, payload, action, timeoutMs, metadata } = request;
2753
+ const effectiveTimeout = timeoutMs ?? this.invocationTimeoutMs;
2754
+ const outgoing = this.outgoingFields(request);
2755
+ if (action?.type === "void") {
2756
+ this.sendMessage("invokefunction", buildInvokeFunction({
2757
+ function_id,
2758
+ data: payload,
2759
+ action,
2760
+ metadata,
2761
+ namespace,
2762
+ ...outgoing,
2763
+ activation
2764
+ }));
2765
+ return Promise.resolve(void 0);
2766
+ }
2767
+ const invocation_id = randomUUID();
2768
+ return new Promise((resolve, reject) => {
2769
+ const timeout = setTimeout(() => {
2770
+ if (this.invocations.get(invocation_id)) {
2771
+ this.invocations.delete(invocation_id);
2772
+ reject(timeoutError(effectiveTimeout, function_id));
2773
+ }
2774
+ }, effectiveTimeout);
2775
+ this.invocations.set(invocation_id, {
2776
+ resolve: (result) => {
2777
+ clearTimeout(timeout);
2778
+ resolve(result);
2779
+ },
2780
+ reject: (error) => {
2781
+ clearTimeout(timeout);
2782
+ reject(error);
2783
+ },
2784
+ timeout
2785
+ });
2786
+ this.sendMessage("invokefunction", buildInvokeFunction({
2787
+ invocation_id,
2788
+ function_id,
2789
+ data: payload,
2790
+ action,
2791
+ metadata,
2792
+ namespace,
2793
+ ...outgoing,
2794
+ activation
2795
+ }));
2796
+ });
2797
+ }
2798
+ /**
2799
+ * The local path (sdk.md §4.3): runs the handler in-process, with a copy of
2800
+ * the payload, inside a new invocation context; the same timeout and the
2801
+ * same rejection value as the remote path; reports the call when an
2802
+ * observer matches. Puts nothing on the wire when nobody observes the
2803
+ * function.
2804
+ */
2805
+ invokeLocal(function_id, handler, observe, request) {
2806
+ const parent = callContext();
2807
+ const caller = this.workerId !== void 0 ? {
2808
+ worker_id: this.workerId,
2809
+ worker_name: this.workerName
2810
+ } : { worker_name: this.workerName };
2811
+ if (parent) {
2812
+ caller.function_id = parent.function_id;
2813
+ caller.invocation_id = parent.invocation_id;
2814
+ const grandparent = stripCaller(parent.caller);
2815
+ if (grandparent && Object.keys(grandparent).length > 0) caller.parent = grandparent;
2816
+ }
2817
+ const ctx = {
2818
+ function_id,
2819
+ invocation_id: randomUUID(),
2820
+ caller,
2821
+ observe_depth: parent ? parent.observe_depth : callDepth(),
2822
+ metadata: request.metadata,
2823
+ localDepth: callLocalDepth() + 1
2824
+ };
2825
+ const traceparent = request.traceparent ?? parent?.traceparent;
2826
+ const baggage = request.baggage ?? parent?.baggage;
2827
+ if (traceparent !== void 0) ctx.traceparent = traceparent;
2828
+ if (baggage !== void 0) ctx.baggage = baggage;
2829
+ const set = observe.delivery === "auto" ? observe.compiled : [];
2830
+ let input;
2831
+ let observedInput;
2832
+ let observedMetadata;
2833
+ let metadata;
2834
+ try {
2835
+ if (set.length > 0) {
2836
+ observedInput = cloneValue(request.payload);
2837
+ observedMetadata = request.metadata === void 0 ? void 0 : cloneValue(request.metadata);
2838
+ }
2839
+ input = this.resolveChannelValue(cloneValue(request.payload));
2840
+ metadata = request.metadata === void 0 ? void 0 : cloneValue(request.metadata);
2841
+ } catch (error) {
2842
+ return Promise.reject(error);
2843
+ }
2844
+ const startedAt = Date.now();
2845
+ const t0 = performance.now();
2846
+ const finish = (ok, output, error) => {
2847
+ try {
2848
+ const duration = performance.now() - t0;
2849
+ this.reporter.recordLocal(function_id, ok, duration);
2850
+ observe.reportLocal(set, {
2851
+ invocation_id: ctx.invocation_id,
2852
+ ok,
2853
+ input: observedInput,
2854
+ output,
2855
+ error,
2856
+ caller: ctx.caller,
2857
+ metadata: observedMetadata,
2858
+ started_at_ms: startedAt,
2859
+ duration_ms: duration,
2860
+ observe_depth: ctx.observe_depth,
2861
+ traceparent,
2862
+ baggage
2863
+ });
2864
+ } catch (reportError) {
2865
+ this.logError(`Failed to report a local invocation of ${function_id}`, reportError);
2866
+ }
2867
+ };
2868
+ const effectiveTimeout = request.timeoutMs ?? this.invocationTimeoutMs;
2869
+ const untrack = trackRunning(ctx, effectiveTimeout);
2870
+ let started;
2871
+ try {
2872
+ started = runInContext(ctx, () => handler(input, metadata));
2873
+ } catch (error) {
2874
+ started = Promise.reject(error);
2875
+ }
2876
+ const done = started.then((output) => {
2877
+ untrack();
2878
+ finish(true, output, void 0);
2879
+ return output;
2880
+ }, (error) => {
2881
+ untrack();
2882
+ const body = handlerErrorBody(error);
2883
+ finish(false, void 0, body);
2884
+ throw body;
2885
+ });
2886
+ if (request.action?.type === "void") {
2887
+ done.catch((error) => this.logError(`Error invoking function ${function_id}`, error));
2888
+ return Promise.resolve(void 0);
2889
+ }
2890
+ return new Promise((resolve, reject) => {
2891
+ let timeout;
2892
+ done.then((output) => {
2893
+ if (timeout !== void 0) clearTimeout(timeout);
2894
+ try {
2895
+ resolve(cloneValue(output));
2896
+ } catch (error) {
2897
+ reject(error);
2898
+ }
2899
+ }, (error) => {
2900
+ if (timeout !== void 0) clearTimeout(timeout);
2901
+ reject(error);
2902
+ });
2903
+ timeout = setTimeout(() => {
2904
+ reject(timeoutError(effectiveTimeout, function_id));
2905
+ }, effectiveTimeout);
2906
+ });
2907
+ }
299
2908
  setConnectionState(state) {
300
2909
  if (this.connectionState !== state) {
301
2910
  this.connectionState = state;
@@ -352,6 +2961,7 @@ var Sdk = class {
352
2961
  this.ws.onmessage = null;
353
2962
  }
354
2963
  this.ws = void 0;
2964
+ this.registeredOnConnection = false;
355
2965
  if (this.isShuttingDown) return;
356
2966
  this.setConnectionState("disconnected");
357
2967
  this.scheduleReconnect();
@@ -360,33 +2970,81 @@ var Sdk = class {
360
2970
  this.clearReconnectTimeout();
361
2971
  this.reconnectAttempt = 0;
362
2972
  this.setConnectionState("connected");
2973
+ this.connectionEpoch++;
2974
+ this.registeredOnConnection = false;
363
2975
  if (this.ws) this.ws.onmessage = this.onMessage.bind(this);
364
- if (this.workerId) this.sendMessageRaw(JSON.stringify({
365
- type: "reattach",
366
- previous_worker_id: this.workerId,
367
- reattach_token: this.reattachToken
368
- }));
2976
+ if (this.workerId) try {
2977
+ this.sendMessageRaw(JSON.stringify({
2978
+ type: "reattach",
2979
+ previous_worker_id: this.workerId,
2980
+ reattach_token: this.reattachToken
2981
+ }));
2982
+ } catch (error) {
2983
+ if (!isPayloadTooLargeError(error)) throw error;
2984
+ console.error("[iii] Reattach JSON envelope rejected", error);
2985
+ }
369
2986
  this.registerWorkerMetadata();
370
2987
  this.triggerTypes.forEach(({ message }) => {
371
- this.sendMessage("registertriggertype", message, true);
2988
+ this.replayRegistration("registertriggertype", message);
372
2989
  });
373
2990
  this.functions.forEach(({ message }) => {
374
- this.sendMessage("registerfunction", message, true);
2991
+ this.replayRegistration("registerfunction", message);
375
2992
  });
376
2993
  this.triggers.forEach((trigger) => {
377
- this.sendMessage("registertrigger", trigger, true);
2994
+ this.replayRegistration("registertrigger", trigger);
378
2995
  });
379
2996
  const pending = this.messagesToSend;
380
2997
  this.messagesToSend = [];
381
2998
  for (const message of pending) {
382
2999
  if (message.type === "invokefunction" && typeof message.invocation_id === "string" && !this.invocations.has(message.invocation_id)) continue;
383
- this.sendMessageRaw(JSON.stringify(message));
3000
+ try {
3001
+ this.sendMessageRaw(JSON.stringify(message));
3002
+ } catch (error) {
3003
+ if (!isPayloadTooLargeError(error)) throw error;
3004
+ console.error("[iii] Queued JSON envelope rejected", error);
3005
+ }
384
3006
  }
385
3007
  }
386
3008
  isOpen() {
387
3009
  return this.ws?.readyState === WebSocket.OPEN;
388
3010
  }
3011
+ snapshotRegistration(message) {
3012
+ return JSON.parse(JSON.stringify(message));
3013
+ }
3014
+ replayRegistration(type, message) {
3015
+ try {
3016
+ this.sendMessage(type, message, true);
3017
+ } catch (error) {
3018
+ if (!isPayloadTooLargeError(error)) throw error;
3019
+ console.error("[iii] Registration JSON envelope rejected", error);
3020
+ }
3021
+ }
3022
+ prepareJson(message) {
3023
+ const data = JSON.stringify(message);
3024
+ const size = JSON_ENCODER.encode(data).byteLength;
3025
+ if (size <= MAX_JSON_FRAME_BYTES) return data;
3026
+ const error = createPayloadTooLargeError(size, typeof message.function_id === "string" ? message.function_id : void 0);
3027
+ if (message.type === "invocationresult") {
3028
+ const fallback = JSON.stringify({
3029
+ type: "invocationresult",
3030
+ invocation_id: message.invocation_id,
3031
+ function_id: message.function_id,
3032
+ error: {
3033
+ code: error.code,
3034
+ message: payloadTooLargeMessage(size)
3035
+ }
3036
+ });
3037
+ if (JSON_ENCODER.encode(fallback).byteLength <= MAX_JSON_FRAME_BYTES) return fallback;
3038
+ }
3039
+ if (typeof message.invocation_id === "string") {
3040
+ const pending = this.invocations.get(message.invocation_id);
3041
+ this.invocations.delete(message.invocation_id);
3042
+ pending?.reject(error);
3043
+ }
3044
+ throw error;
3045
+ }
389
3046
  sendMessageRaw(data) {
3047
+ if (JSON_ENCODER.encode(data).byteLength > MAX_JSON_FRAME_BYTES) data = this.prepareJson(JSON.parse(data));
390
3048
  if (this.ws && this.isOpen()) try {
391
3049
  this.ws.send(data);
392
3050
  } catch (error) {
@@ -436,15 +3094,17 @@ var Sdk = class {
436
3094
  runtime: "browser",
437
3095
  name: this.workerName,
438
3096
  os: globalThis.navigator?.userAgent ?? "browser",
439
- ...this.namespace !== void 0 ? { namespace: this.namespace } : {}
3097
+ ...this.namespace !== void 0 ? { namespace: this.namespace } : {},
3098
+ features: [...SDK_FEATURES]
440
3099
  },
441
3100
  action: { type: "void" }
442
3101
  });
443
3102
  }
444
3103
  sendMessage(messageType, message, skipIfClosed = false) {
445
3104
  const wireMessage = this.toWireFormat(messageType, message);
446
- if (this.isOpen()) this.sendMessageRaw(JSON.stringify(wireMessage));
447
- else if (!skipIfClosed) this.messagesToSend.push(wireMessage);
3105
+ const data = this.prepareJson(wireMessage);
3106
+ if (this.isOpen()) this.sendMessageRaw(data);
3107
+ else if (!skipIfClosed) this.messagesToSend.push(JSON.parse(data));
448
3108
  }
449
3109
  onInvocationResult(invocation_id, result, error) {
450
3110
  const invocation = this.invocations.get(invocation_id);
@@ -454,30 +3114,73 @@ var Sdk = class {
454
3114
  }
455
3115
  this.invocations.delete(invocation_id);
456
3116
  }
3117
+ /**
3118
+ * Replaces channel refs with readers / writers. Copy-on-write: a value
3119
+ * without refs is returned as it is. Only arrays and plain objects are
3120
+ * walked, so a locally dispatched payload keeps its `Date`s, `Map`s and
3121
+ * class instances.
3122
+ */
457
3123
  resolveChannelValue(value) {
458
3124
  if (isChannelRef(value)) return value.direction === "read" ? new ChannelReader(this.address, value) : new ChannelWriter(this.address, value);
459
- if (Array.isArray(value)) return value.map((item) => this.resolveChannelValue(item));
3125
+ if (Array.isArray(value)) {
3126
+ let out;
3127
+ for (let i = 0; i < value.length; i++) {
3128
+ const resolved = this.resolveChannelValue(value[i]);
3129
+ if (resolved !== value[i]) {
3130
+ out ?? (out = value.slice());
3131
+ out[i] = resolved;
3132
+ }
3133
+ }
3134
+ return out ?? value;
3135
+ }
460
3136
  if (value !== null && typeof value === "object") {
461
- const out = {};
462
- for (const [k, v] of Object.entries(value)) out[k] = this.resolveChannelValue(v);
463
- return out;
3137
+ const proto = Object.getPrototypeOf(value);
3138
+ if (proto !== Object.prototype && proto !== null) return value;
3139
+ let out;
3140
+ for (const [k, v] of Object.entries(value)) {
3141
+ const resolved = this.resolveChannelValue(v);
3142
+ if (resolved !== v) {
3143
+ out ?? (out = { ...value });
3144
+ out[k] = resolved;
3145
+ }
3146
+ }
3147
+ return out ?? value;
464
3148
  }
465
3149
  return value;
466
3150
  }
467
- async onInvokeFunction(invocation_id, function_id, input, traceparent, baggage) {
3151
+ async onInvokeFunction(invocation_id, function_id, input, metadata, traceparent, baggage, observeFields = {}) {
468
3152
  const fn = this.functions.get(function_id);
469
3153
  const resolvedInput = this.resolveChannelValue(input);
470
3154
  if (fn?.handler) {
3155
+ const handler = fn.handler;
3156
+ const ctx = {
3157
+ function_id,
3158
+ invocation_id: invocation_id ?? randomUUID(),
3159
+ observe_depth: observeFields.observe_depth ?? 0,
3160
+ metadata
3161
+ };
3162
+ if (observeFields.caller) ctx.caller = observeFields.caller;
3163
+ if (observeFields.activation) ctx.activation = observeFields.activation;
3164
+ if (traceparent !== void 0) ctx.traceparent = traceparent;
3165
+ if (baggage !== void 0) ctx.baggage = baggage;
3166
+ const run = async () => {
3167
+ const untrack = trackRunning(ctx, MAX_RUNNING_INVOCATION_MS);
3168
+ try {
3169
+ return await runInContext(ctx, () => handler(resolvedInput, metadata));
3170
+ } finally {
3171
+ untrack();
3172
+ }
3173
+ };
471
3174
  if (!invocation_id) {
472
3175
  try {
473
- await fn.handler(resolvedInput, traceparent, baggage);
3176
+ await run();
474
3177
  } catch (error) {
475
3178
  console.error(`[iii] Error invoking function ${function_id}`, error);
476
3179
  }
477
3180
  return;
478
3181
  }
479
3182
  try {
480
- const result = await fn.handler(resolvedInput, traceparent, baggage);
3183
+ const result = await run();
481
3184
  this.sendMessage("invocationresult", {
482
3185
  invocation_id,
483
3186
  function_id,
@@ -486,15 +3189,10 @@ var Sdk = class {
486
3189
  baggage
487
3190
  });
488
3191
  } catch (error) {
489
- const isError = error instanceof Error;
490
3192
  this.sendMessage("invocationresult", {
491
3193
  invocation_id,
492
3194
  function_id,
493
- error: {
494
- code: "invocation_failed",
495
- message: isError ? error.message : String(error),
496
- stacktrace: isError ? error.stack : void 0
497
- },
3195
+ error: handlerErrorBody(error),
498
3196
  traceparent,
499
3197
  baggage
500
3198
  });
@@ -585,16 +3283,68 @@ var Sdk = class {
585
3283
  const { invocation_id, result, error } = message;
586
3284
  this.onInvocationResult(invocation_id, result, error);
587
3285
  } else if (msgType === "invokefunction") {
588
- const { invocation_id, function_id, data, traceparent, baggage } = message;
589
- this.onInvokeFunction(invocation_id, function_id, data, traceparent, baggage);
3286
+ const { invocation_id, function_id, data, metadata, traceparent, baggage, caller, observe_depth, activation } = decodeInvokeFunction(message);
3287
+ this.onInvokeFunction(invocation_id, function_id, data, metadata, traceparent, baggage, {
3288
+ caller,
3289
+ observe_depth,
3290
+ activation
3291
+ });
3292
+ } else if (msgType === "functionregistered") {
3293
+ const msg = decodeFunctionRegistered(message);
3294
+ this.functions.get(msg.id)?.observe?.onFunctionRegistered(msg, this.connectionEpoch);
3295
+ } else if (msgType === "observeradded") {
3296
+ const msg = decodeObserverAdded(message);
3297
+ this.functions.get(msg.function_id)?.observe?.onObserverAdded(msg);
3298
+ } else if (msgType === "observerremoved") {
3299
+ const msg = decodeObserverRemoved(message);
3300
+ this.functions.get(msg.function_id)?.observe?.onObserverRemoved(msg);
3301
+ } else if (msgType === "observeresult") {
3302
+ const msg = decodeObserveResult(message);
3303
+ if (msg.warnings && msg.warnings.length > 0) console.warn(`[iii] Observer ${msg.id}: ${msg.warnings.join("; ")}`);
3304
+ this.onObserverState(msg.id, msg.state, msg.error);
3305
+ } else if (msgType === "observerstatechanged") {
3306
+ const msg = decodeObserverStateChanged(message);
3307
+ this.onObserverState(msg.id, msg.state, msg.reason);
590
3308
  } else if (msgType === "registertrigger") this.onRegisterTrigger(message);
591
3309
  else if (msgType === "unregistertrigger") this.onUnregisterTrigger(message);
592
3310
  else if (msgType === "registrationrejected") this.onRegistrationRejected(message);
593
3311
  else if (msgType === "workerregistered") {
594
- const { worker_id, reattach_token } = message;
3312
+ const { worker_id, reattach_token, features } = decodeWorkerRegistered(message);
595
3313
  this.workerId = worker_id;
596
3314
  this.reattachToken = reattach_token;
3315
+ this.onEngineFeatures(features ?? []);
3316
+ }
3317
+ }
3318
+ /**
3319
+ * `WorkerRegistered` told this connection what the engine supports. With
3320
+ * `observe.v1` the observers are replayed (after the functions, sent on
3321
+ * open) and held reports flushed; without it `observe()` fails with
3322
+ * `UNSUPPORTED` and observe hooks are inactive.
3323
+ */
3324
+ onEngineFeatures(features) {
3325
+ this.engineFeatures = new Set(features);
3326
+ this.registeredOnConnection = true;
3327
+ const queued = this.observeQueue;
3328
+ this.observeQueue = [];
3329
+ if (this.engineFeatures.has("observe.v1")) {
3330
+ for (const frame of queued) this.sendMessageRaw(JSON.stringify(frame));
3331
+ for (const handle of this.observers.values()) this.sendObserve(handle);
3332
+ this.reporter.flush();
3333
+ return;
597
3334
  }
3335
+ for (const handle of this.observers.values()) handle.setState("error", UNSUPPORTED_REASON);
3336
+ for (const [functionId, fn] of this.functions) if (fn.observe?.needsObserve) this.warnHooksInactive(functionId);
3337
+ this.reporter.clear();
3338
+ }
3339
+ onObserverState(id, wireState, reason) {
3340
+ const handle = this.observers.get(id);
3341
+ if (!handle) return;
3342
+ const state = toObserverState(wireState);
3343
+ handle.setState(state, reason ? {
3344
+ code: reason.code,
3345
+ message: reason.message
3346
+ } : void 0);
3347
+ if (state === "disposed") this.observers.delete(id);
598
3348
  }
599
3349
  /**
600
3350
  * The engine rejected a registration. A `FUNCTION_NAMESPACE_CONFLICT` costs
@@ -606,6 +3356,7 @@ var Sdk = class {
606
3356
  */
607
3357
  onRegistrationRejected(init) {
608
3358
  if (init.code === "FUNCTION_NAMESPACE_CONFLICT") {
3359
+ if (init.function_id !== void 0) this.functions.get(init.function_id)?.observe?.onRegistrationRejected(this.connectionEpoch);
609
3360
  console.warn(`[iii] Function registration rejected: function "${init.function_id ?? "<unknown>"}" in namespace "${init.namespace}" is already exported by worker ${init.owner_worker_id}. Staying connected and serving the rest.`);
610
3361
  return;
611
3362
  }
@@ -682,5 +3433,5 @@ const TriggerAction = {
682
3433
  const registerWorker = (address, options) => new Sdk(address, options);
683
3434
 
684
3435
  //#endregion
685
- export { ChannelReader, ChannelWriter, EngineFunctions, EngineTriggers, RegistrationRejectedError, TriggerAction, registerWorker };
3436
+ export { ChannelReader, ChannelWriter, EngineFunctions, EngineTriggers, InvocationError, ObserveRejection, RegistrationRejectedError, TriggerAction, registerWorker };
686
3437
  //# sourceMappingURL=index.mjs.map