iii-browser-sdk 0.24.6 → 0.25.0-rc.2

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