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