iii-browser-sdk 0.25.0 → 0.25.1-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 { a as utf8ByteLength, c as ChannelReader, i as unrefTimer, l as ChannelWriter, n as isChannelRef, r as randomUUID } from "./utils-Bz5eP_hN.mjs";
1
+ import { a as utf8ByteLength, c as ChannelReader, i as unrefTimer, l as ChannelWriter, n as isChannelRef, r as randomUUID } from "./utils-CyT9CwWA.mjs";
2
2
 
3
3
  //#region src/errors.ts
4
4
  /**
@@ -19,14 +19,13 @@ var RegistrationRejectedError = class extends Error {
19
19
  };
20
20
  /**
21
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.
22
+ * `code`: `LOCAL_DEPTH_EXCEEDED` (a local call nested too deep while the
23
+ * socket is closed) and `payload_too_large`. Mirrors the Node SDK.
25
24
  *
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.
25
+ * A call the engine answers with an error rejects with the engine's error
26
+ * body (`{ code, message, stacktrace? }`), and so does a locally dispatched
27
+ * call whose handler or deliver hook throws: both paths reject with the same
28
+ * value.
30
29
  */
31
30
  var InvocationError = class extends Error {
32
31
  constructor(init) {
@@ -38,6 +37,110 @@ var InvocationError = class extends Error {
38
37
  }
39
38
  };
40
39
  /**
40
+ * The error a call that timed out rejects with, on the remote and the local
41
+ * path: an `Error` (its message unchanged from earlier releases) that also
42
+ * carries `code: 'TIMEOUT'` and the `function_id`, like the Node SDK's.
43
+ */
44
+ var InvocationTimeoutError = class extends Error {
45
+ constructor(ms, functionId) {
46
+ super(`Invocation timeout after ${ms}ms: ${functionId}`);
47
+ this.code = "TIMEOUT";
48
+ this.function_id = functionId;
49
+ }
50
+ };
51
+ /** What a failure reports when the thrown value cannot even be read (a getter or `toString` that throws). */
52
+ const UNREADABLE_FAILURE = "the handler failed with a value that cannot be read";
53
+ function safeString(value) {
54
+ try {
55
+ return String(value);
56
+ } catch {
57
+ return UNREADABLE_FAILURE;
58
+ }
59
+ }
60
+ /**
61
+ * An error body as the engine sends it, and as this SDK's own calls reject
62
+ * with: a plain (JSON-parsed) object with a string `code`, a string `message`
63
+ * and, optionally, a string `stacktrace`. A class instance or anything else
64
+ * with such fields is not one: it is reported through `String()`.
65
+ */
66
+ function isEngineErrorBody(value) {
67
+ if (value === null || typeof value !== "object") return false;
68
+ const proto = Object.getPrototypeOf(value);
69
+ if (proto !== Object.prototype && proto !== null) return false;
70
+ const body = value;
71
+ return typeof body.code === "string" && typeof body.message === "string" && (body.stacktrace === void 0 || typeof body.stacktrace === "string");
72
+ }
73
+ /**
74
+ * The error a handler's failure becomes, the same on the local and the remote
75
+ * path (code `invocation_failed`):
76
+ * - an `Error`, from any realm (an iframe's too): its message and stack;
77
+ * - an engine error body (a failed call's rejection, rethrown): its message and stacktrace;
78
+ * - anything else: `String(value)`.
79
+ * Never throws: when reading the value throws, a fixed message is reported, so
80
+ * the caller always gets its answer.
81
+ */
82
+ function handlerErrorBody(error) {
83
+ try {
84
+ if (error instanceof Error || Object.prototype.toString.call(error) === "[object Error]") {
85
+ const { message, stack } = error;
86
+ return {
87
+ code: "invocation_failed",
88
+ message: typeof message === "string" ? message : safeString(message),
89
+ stacktrace: typeof stack === "string" ? stack : void 0
90
+ };
91
+ }
92
+ if (isEngineErrorBody(error)) return {
93
+ code: "invocation_failed",
94
+ message: error.message,
95
+ stacktrace: error.stacktrace
96
+ };
97
+ return {
98
+ code: "invocation_failed",
99
+ message: String(error),
100
+ stacktrace: void 0
101
+ };
102
+ } catch {
103
+ return {
104
+ code: "invocation_failed",
105
+ message: safeString(error),
106
+ stacktrace: void 0
107
+ };
108
+ }
109
+ }
110
+ /**
111
+ * The error a deliver hook's failure becomes: an {@link ObserveRejection}, an
112
+ * {@link InvocationError}, a call that timed out ({@link InvocationTimeoutError})
113
+ * or an engine error body (a failed call's rejection, rethrown) keeps its code
114
+ * and message; anything else is a handler failure ({@link handlerErrorBody}).
115
+ * Never throws.
116
+ */
117
+ function deliverErrorBody(error) {
118
+ try {
119
+ if (error instanceof ObserveRejection) return {
120
+ code: error.code,
121
+ message: error.message
122
+ };
123
+ if (error instanceof InvocationError) {
124
+ const prefix = `${error.code}: `;
125
+ return {
126
+ code: error.code,
127
+ message: error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message,
128
+ stacktrace: error.stacktrace
129
+ };
130
+ }
131
+ if (error instanceof InvocationTimeoutError) return {
132
+ code: error.code,
133
+ message: error.message
134
+ };
135
+ if (isEngineErrorBody(error)) return {
136
+ code: error.code,
137
+ message: error.message,
138
+ stacktrace: error.stacktrace
139
+ };
140
+ } catch {}
141
+ return handlerErrorBody(error);
142
+ }
143
+ /**
41
144
  * Thrown by an `onObserverAdded` hook to reject an observer with a code of
42
145
  * its own (`HTTP_ROUTE_CONFLICT`, `INVALID_CRON_EXPRESSION`, ...); any other
43
146
  * error rejects it with `OBSERVE_REJECTED`. Also the error `ObserverHandle.ready()`
@@ -45,11 +148,11 @@ var InvocationError = class extends Error {
45
148
  *
46
149
  * @example
47
150
  * ```typescript
48
- * onObserverAdded(obs) {
151
+ * iii.onObserverAdded('cron::on-tick', (obs) => {
49
152
  * if (!isValidCron(obs.args.expression)) {
50
153
  * throw new ObserveRejection('INVALID_CRON_EXPRESSION', 'invalid day-of-week field')
51
154
  * }
52
- * }
155
+ * })
53
156
  * ```
54
157
  */
55
158
  var ObserveRejection = class extends Error {
@@ -60,44 +163,6 @@ var ObserveRejection = class extends Error {
60
163
  }
61
164
  };
62
165
 
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
166
  //#endregion
102
167
  //#region ../iii/src/filter/errors.ts
103
168
  const MAX_ENCODED_BYTES = 8192;
@@ -144,7 +209,7 @@ function checkString(s, at, what) {
144
209
  }
145
210
  }
146
211
  /** 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) {
212
+ function isPlainObject$1(v) {
148
213
  const proto = Object.getPrototypeOf(v);
149
214
  return proto === null || Object.getPrototypeOf(proto) === null;
150
215
  }
@@ -208,7 +273,7 @@ function checkJson(src) {
208
273
  }
209
274
  continue;
210
275
  }
211
- if (!isPlainObject(value)) throw FilterError.invalid(`${where(at)}: ${describe(value)} is not a JSON object (use a plain object)`);
276
+ if (!isPlainObject$1(value)) throw FilterError.invalid(`${where(at)}: ${describe(value)} is not a JSON object (use a plain object)`);
212
277
  if (Object.getOwnPropertySymbols(value).length > 0) throw FilterError.invalid(`${where(at)}: symbol keys are not JSON`);
213
278
  for (const key of Object.getOwnPropertyNames(value)) {
214
279
  const member = at === "" ? key : `${at}.${key}`;
@@ -759,6 +824,221 @@ function checkLiteralDepth(path, name, literal) {
759
824
  }
760
825
  }
761
826
 
827
+ //#endregion
828
+ //#region ../iii/src/filter/filter-index.ts
829
+ function isScalar(value) {
830
+ return value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string";
831
+ }
832
+ /**
833
+ * The equality conditions of `source`, a filter that compiled: for each
834
+ * clause of its top-level `$and` (its keys and those of the filters its
835
+ * `$and`s hold, never inside `$or`, `$not` or `$any`), its `$eq` operand or
836
+ * its `$in` operands, when they are scalars. `path` is the parsed path,
837
+ * spelled one way whatever escapes the filter used.
838
+ */
839
+ function conditionsOf(source) {
840
+ const out = [];
841
+ const pending = [source];
842
+ while (pending.length > 0) {
843
+ const current = pending.pop();
844
+ for (const key of Object.keys(current)) {
845
+ const value = current[key];
846
+ if (key === "$and") {
847
+ for (const item of value) pending.push(item);
848
+ continue;
849
+ }
850
+ if (key.startsWith("$")) continue;
851
+ const ops = value;
852
+ const eq = ops.$eq;
853
+ const inItems = ops.$in;
854
+ const hasEq = Object.prototype.hasOwnProperty.call(ops, "$eq");
855
+ if (!hasEq && !Array.isArray(inItems)) continue;
856
+ const parsed = parsePath(key, false);
857
+ const path = JSON.stringify([parsed.root, ...parsed.segments.map((s) => s.key)]);
858
+ if (hasEq && isScalar(eq)) out.push({
859
+ path,
860
+ raw: key,
861
+ values: [eq]
862
+ });
863
+ if (Array.isArray(inItems) && inItems.length > 0 && inItems.every(isScalar)) out.push({
864
+ path,
865
+ raw: key,
866
+ values: [...new Set(inItems)]
867
+ });
868
+ }
869
+ }
870
+ return out;
871
+ }
872
+ /**
873
+ * Filters, each with a value and an order, matched against a document by an
874
+ * index of their equality conditions (see the module docs).
875
+ * {@link FilterIndex.matches} returns exactly the values whose filter
876
+ * matches the document (and that `accept` accepts), by ascending `order`.
877
+ */
878
+ var FilterIndex = class {
879
+ constructor() {
880
+ this.filed = /* @__PURE__ */ new Map();
881
+ this.scanned = /* @__PURE__ */ new Set();
882
+ this.paths = /* @__PURE__ */ new Map();
883
+ this.indexed = 0;
884
+ }
885
+ /** Entries held. */
886
+ get size() {
887
+ return this.filed.size;
888
+ }
889
+ /**
890
+ * Whether {@link FilterIndex.matches} can evaluate fewer filters than
891
+ * evaluating each entry's would. Looking a document's value up at an
892
+ * indexed path costs about one evaluation, and rules out the entries filed
893
+ * there under other values, so it can only when some indexed path files
894
+ * more than one entry. Otherwise evaluating each filter in order costs less
895
+ * and yields the same matches.
896
+ */
897
+ get narrows() {
898
+ return this.indexed > this.paths.size;
899
+ }
900
+ has(value) {
901
+ return this.filed.has(value);
902
+ }
903
+ /**
904
+ * Files `value` with `filter`, in place of the entry `value` had. `order`
905
+ * sorts the matches. The condition it is filed under is the one of the
906
+ * filter's top-level `$and` that the fewest entries share now (an `$eq`
907
+ * before an `$in` of several values).
908
+ */
909
+ insert(value, filter, order) {
910
+ this.remove(value);
911
+ const entry = {
912
+ value,
913
+ filter,
914
+ order
915
+ };
916
+ const condition = this.conditionFor(filter);
917
+ if (!condition) {
918
+ this.scanned.add(entry);
919
+ this.filed.set(value, { entry });
920
+ return;
921
+ }
922
+ let index = this.paths.get(condition.path);
923
+ if (!index) {
924
+ index = {
925
+ resolve: compilePath(parsePath(condition.raw, false)),
926
+ buckets: /* @__PURE__ */ new Map(),
927
+ entries: 0
928
+ };
929
+ this.paths.set(condition.path, index);
930
+ }
931
+ for (const scalar of condition.values) {
932
+ const bucket = index.buckets.get(scalar);
933
+ if (bucket) bucket.add(entry);
934
+ else index.buckets.set(scalar, new Set([entry]));
935
+ }
936
+ index.entries++;
937
+ this.indexed++;
938
+ this.filed.set(value, {
939
+ entry,
940
+ path: condition.path,
941
+ values: condition.values
942
+ });
943
+ }
944
+ /** Takes the entry of `value` out. */
945
+ remove(value) {
946
+ const filed = this.filed.get(value);
947
+ if (!filed) return;
948
+ this.filed.delete(value);
949
+ if (filed.path === void 0 || filed.values === void 0) {
950
+ this.scanned.delete(filed.entry);
951
+ return;
952
+ }
953
+ const index = this.paths.get(filed.path);
954
+ if (!index) return;
955
+ this.indexed--;
956
+ for (const scalar of filed.values) {
957
+ const bucket = index.buckets.get(scalar);
958
+ if (!bucket) continue;
959
+ bucket.delete(filed.entry);
960
+ if (bucket.size === 0) index.buckets.delete(scalar);
961
+ }
962
+ if (--index.entries === 0) this.paths.delete(filed.path);
963
+ }
964
+ /**
965
+ * The values whose filter matches `doc`, by ascending order. Resolves each
966
+ * indexed path of `doc` once, and evaluates the filters of the entries
967
+ * filed under the value found there and of the scanned entries
968
+ * ({@link FilterIndex.candidates} counts them); every other entry has a
969
+ * condition `doc` fails. `accept` is asked first, for each candidate.
970
+ */
971
+ matches(doc, accept) {
972
+ const found = [];
973
+ let sorted = true;
974
+ let last = -Infinity;
975
+ if (this.paths.size > 0) for (const index of this.paths.values()) {
976
+ const bucket = this.bucket(index, doc);
977
+ if (bucket === void 0) continue;
978
+ for (const entry of bucket) if ((accept === void 0 || accept(entry.value)) && entry.filter.matches(doc)) {
979
+ if (entry.order < last) sorted = false;
980
+ last = entry.order;
981
+ found.push(entry);
982
+ }
983
+ }
984
+ if (this.scanned.size > 0) {
985
+ for (const entry of this.scanned) if ((accept === void 0 || accept(entry.value)) && entry.filter.matches(doc)) {
986
+ if (entry.order < last) sorted = false;
987
+ last = entry.order;
988
+ found.push(entry);
989
+ }
990
+ }
991
+ if (!sorted) found.sort((a, b) => a.order - b.order);
992
+ const values = new Array(found.length);
993
+ for (let i = 0; i < found.length; i++) values[i] = found[i].value;
994
+ return values;
995
+ }
996
+ /** How many filters a match of `doc` evaluates: the entries filed under its values, and the scanned ones. */
997
+ candidates(doc) {
998
+ let n = this.scanned.size;
999
+ for (const index of this.paths.values()) n += this.bucket(index, doc)?.size ?? 0;
1000
+ return n;
1001
+ }
1002
+ /**
1003
+ * The entries filed under `doc`'s value at the path. A value an index
1004
+ * cannot hold (absent, an array, an object) matches no condition, and
1005
+ * neither does a path whose reading throws: each filter filed under it
1006
+ * holds a clause on that path, and a filter whose reading throws does not
1007
+ * match.
1008
+ */
1009
+ bucket(index, doc) {
1010
+ let value;
1011
+ try {
1012
+ value = index.resolve(doc !== null && typeof doc === "object" ? doc : {}, void 0);
1013
+ } catch {
1014
+ return;
1015
+ }
1016
+ return isScalar(value) ? index.buckets.get(value) : void 0;
1017
+ }
1018
+ conditionFor(filter) {
1019
+ let best;
1020
+ for (const condition of conditionsOf(filter.source)) {
1021
+ const held = this.paths.get(condition.path);
1022
+ let sharing = 0;
1023
+ if (held) for (const scalar of condition.values) sharing += held.buckets.get(scalar)?.size ?? 0;
1024
+ const score = [
1025
+ condition.values.length > 1 ? 1 : 0,
1026
+ sharing,
1027
+ condition.values.length
1028
+ ];
1029
+ if (best === void 0 || lessThan(score, best.score)) best = {
1030
+ condition,
1031
+ score
1032
+ };
1033
+ }
1034
+ return best?.condition;
1035
+ }
1036
+ };
1037
+ function lessThan(a, b) {
1038
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return a[i] < b[i];
1039
+ return false;
1040
+ }
1041
+
762
1042
  //#endregion
763
1043
  //#region ../iii/src/filter/index.ts
764
1044
  /**
@@ -796,6 +1076,49 @@ function compileFilter(src, options) {
796
1076
  /** The filter that matches every document (`{}`). */
797
1077
  const MATCH_ALL = compileFilter({});
798
1078
 
1079
+ //#endregion
1080
+ //#region src/iii-constants.ts
1081
+ /**
1082
+ * Constants for the III module.
1083
+ */
1084
+ /** Engine function paths for internal operations. */
1085
+ const EngineFunctions = {
1086
+ LIST_FUNCTIONS: "engine::functions::list",
1087
+ INFO_FUNCTIONS: "engine::functions::info",
1088
+ LIST_WORKERS: "engine::workers::list",
1089
+ INFO_WORKERS: "engine::workers::info",
1090
+ REGISTER_WORKER: "engine::workers::register"
1091
+ };
1092
+ /**
1093
+ * The event sources the engine hosts: private functions whose handler
1094
+ * returns the event, observed with `iii.observe(EngineSources.X, target)`.
1095
+ * None takes args; filter on the event (`input`) instead.
1096
+ */
1097
+ const EngineSources = {
1098
+ /** A function was registered or unregistered; each row carries `observer_count`. */
1099
+ FUNCTIONS_CHANGED: "engine::on-functions-changed",
1100
+ /** A worker connected or left. */
1101
+ WORKERS_CHANGED: "engine::on-workers-changed",
1102
+ /** An observer changed state: `{ observer_id, function_id, target, state, reason? }`. */
1103
+ OBSERVERS_CHANGED: "engine::on-observers-changed",
1104
+ /** A log record. */
1105
+ LOG: "observability::on-log",
1106
+ /** A finished span. */
1107
+ SPAN: "observability::on-span",
1108
+ /** The engine's configuration was reloaded. */
1109
+ CONFIGURATION_UPDATED: "configuration::on-updated"
1110
+ };
1111
+ /** Default reconnection configuration */
1112
+ const DEFAULT_BRIDGE_RECONNECTION_CONFIG = {
1113
+ initialDelayMs: 1e3,
1114
+ maxDelayMs: 3e4,
1115
+ backoffMultiplier: 2,
1116
+ jitterFactor: .3,
1117
+ maxRetries: -1
1118
+ };
1119
+ /** Default invocation timeout in milliseconds */
1120
+ const DEFAULT_INVOCATION_TIMEOUT_MS = 3e4;
1121
+
799
1122
  //#endregion
800
1123
  //#region src/iii-types.ts
801
1124
  /**
@@ -803,13 +1126,23 @@ const MATCH_ALL = compileFilter({});
803
1126
  * `engine::workers::register` `features` from the SDK).
804
1127
  */
805
1128
  const FEATURE_OBSERVE_V1 = "observe.v1";
1129
+ /**
1130
+ * The host delivers the calls of its functions (routed ones included), and
1131
+ * functions may set `args_format`, `private`, `observable: false` and
1132
+ * `onObservationDeliver`. Includes `observe.v1`.
1133
+ */
1134
+ const FEATURE_OBSERVE_V2 = "observe.v2";
806
1135
  const FEATURE_LOCAL_DISPATCH_V1 = "local-dispatch.v1";
807
1136
  /**
808
1137
  * What this SDK declares in `engine::workers::register`. Not
809
1138
  * `large-messages.v1`, unlike the other SDKs: a browser receives one 16 MiB
810
1139
  * WebSocket frame at most.
811
1140
  */
812
- const SDK_FEATURES = [FEATURE_OBSERVE_V1, FEATURE_LOCAL_DISPATCH_V1];
1141
+ const SDK_FEATURES = [
1142
+ FEATURE_OBSERVE_V1,
1143
+ FEATURE_OBSERVE_V2,
1144
+ FEATURE_LOCAL_DISPATCH_V1
1145
+ ];
813
1146
 
814
1147
  //#endregion
815
1148
  //#region src/invocation-context.ts
@@ -832,10 +1165,10 @@ const MAX_RUNNING_INVOCATION_MS = 600 * 1e3;
832
1165
  *
833
1166
  * One scope for the whole page, like the Node SDK's one `AsyncLocalStorage`
834
1167
  * per process: a handler of one worker that calls another worker's
835
- * `trigger()` is that call's caller.
1168
+ * `call()` is that call's caller.
836
1169
  */
837
1170
  let current;
838
- /** The public views handed out, so `withInvocation(view, fn)` restores everything (metadata included). */
1171
+ /** The public views handed out, so `withInvocation(view, fn)` restores the invocation they were taken from. */
839
1172
  const views = /* @__PURE__ */ new WeakMap();
840
1173
  function currentContext() {
841
1174
  return current;
@@ -879,33 +1212,37 @@ function live() {
879
1212
  }
880
1213
  return out;
881
1214
  }
882
- /** What a fallback attribution lends: the invocation without its metadata sidecar (one object per invocation). */
883
- const lent = /* @__PURE__ */ new WeakMap();
884
- function lend(ctx) {
885
- let view = lent.get(ctx);
886
- if (!view) {
887
- const { metadata: _, ...rest } = ctx;
888
- view = rest;
889
- lent.set(ctx, view);
890
- }
891
- return view;
1215
+ /**
1216
+ * The invocations whose function's deliver hook is running: code after the
1217
+ * hook's `await`s falls back to them (see {@link callContext}).
1218
+ */
1219
+ const delivering = /* @__PURE__ */ new WeakSet();
1220
+ /**
1221
+ * Marks `ctx` as delivering (its function's deliver hook is running); call
1222
+ * the returned function when the hook settles.
1223
+ */
1224
+ function trackDelivering(ctx) {
1225
+ delivering.add(ctx);
1226
+ return () => {
1227
+ delivering.delete(ctx);
1228
+ };
892
1229
  }
893
1230
  /**
894
- * The invocation a call, an emit or a report made now belongs to. Inside a
895
- * scope, the scope's. Outside any scope (code after an `await`), the running
896
- * invocation when that is unambiguous: it is the only one running and it is
897
- * an observe activation. It lends its ids, caller and trace context, never its
898
- * metadata: filters on `metadata.*` see only what a real scope carries.
899
- * Otherwise none, and the call carries no `caller`: the SDK cannot tell which
900
- * handler, if any, made it.
1231
+ * The invocation a call or a report made now belongs to. Inside a scope, the
1232
+ * scope's. Outside any scope (code after an `await`), the running invocation
1233
+ * when that is unambiguous: it is the only one running, and it is an observe
1234
+ * activation or its function's deliver hook is running (the calls the hook
1235
+ * makes after an `await`, through its observers or not). It lends its ids,
1236
+ * caller and trace context. Otherwise none, and the call carries no
1237
+ * `caller`: the SDK cannot tell which handler, if any, made it.
901
1238
  */
902
1239
  function callContext() {
903
1240
  if (current) return current;
904
1241
  const all = live();
905
- return all.length === 1 && all[0].activation ? lend(all[0]) : void 0;
1242
+ return all.length === 1 && (all[0].activation || delivering.has(all[0])) ? all[0] : void 0;
906
1243
  }
907
1244
  /**
908
- * The `observe_depth` a call, an emit or a report made now carries. Inside a
1245
+ * The `observe_depth` a call or a report made now carries. Inside a
909
1246
  * scope, the scope's. Outside any scope, the deepest running invocation's:
910
1247
  * the engine's loop guard counts on this depth, so code after an `await`
911
1248
  * over-counts (a chain may stop earlier than `max_observe_depth`) rather than
@@ -972,7 +1309,7 @@ function runInContext(ctx, fn) {
972
1309
  current = previous;
973
1310
  }
974
1311
  }
975
- /** The public view of the current invocation (without the metadata sidecar). */
1312
+ /** The public view of the current invocation. */
976
1313
  function publicContext(ctx) {
977
1314
  if (!ctx) return void 0;
978
1315
  const view = {
@@ -1017,278 +1354,123 @@ function contextFromView(view) {
1017
1354
  }
1018
1355
 
1019
1356
  //#endregion
1020
- //#region src/observe-wire.ts
1021
- /** CONTRACT D1: what an absent `capture` means. */
1022
- const DEFAULT_CAPTURE = [
1023
- "input",
1024
- "output",
1025
- "caller"
1026
- ];
1027
- function isRecord(v) {
1028
- return v !== null && typeof v === "object" && !Array.isArray(v);
1357
+ //#region src/observable.ts
1358
+ /**
1359
+ * The host side of observe (v2 §4): per-function observer state, the
1360
+ * observer hooks of the worker and of the function, the `Observer` object
1361
+ * handed to them, matching (the key index, and the index of the filters'
1362
+ * equality conditions), and the delivery of each call of a hosted function.
1363
+ */
1364
+ /** CONTRACT D11: an observer hook still running after this is `OWNER_TIMEOUT`. */
1365
+ const OBSERVE_HOOK_TIMEOUT_MS = 3e4;
1366
+ function sameJson(a, b) {
1367
+ return JSON.stringify(a) === JSON.stringify(b);
1029
1368
  }
1030
- function str(v) {
1031
- return typeof v === "string" ? v : void 0;
1369
+ /** Whether `obs` is served with the view `info` announces: its filters, target, capture and `on`. */
1370
+ function sameView(obs, info) {
1371
+ return obs.target === info.target && obs.on === info.on && sameJson(obs.capture, info.capture) && sameJson(obs.filters, info.filters);
1032
1372
  }
1033
- function num(v) {
1034
- return typeof v === "number" ? v : void 0;
1373
+ function rejectionBody(error) {
1374
+ if (error instanceof ObserveRejection) return {
1375
+ code: error.code,
1376
+ message: error.message
1377
+ };
1378
+ return {
1379
+ code: "OBSERVE_REJECTED",
1380
+ message: error instanceof Error ? error.message : String(error)
1381
+ };
1035
1382
  }
1036
- function errorBody(v) {
1037
- if (!isRecord(v)) return void 0;
1038
- const body = {
1039
- code: String(v.code ?? ""),
1040
- message: String(v.message ?? "")
1383
+ function onAccepts(on, ok) {
1384
+ return on === "complete" || (on === "success" ? ok : on === "error" ? !ok : false);
1385
+ }
1386
+ /**
1387
+ * Whether two copies of a value hold the same JSON data: primitives, arrays
1388
+ * and plain objects, compared member by member in one walk. Any other object
1389
+ * (a `Date`, a class instance, a channel reader) is the same only as itself,
1390
+ * and so is an object the walk reaches twice (a shared member or a cycle).
1391
+ * A local call compares the handler's copy of its input with the copy the
1392
+ * delivery took when the call started.
1393
+ */
1394
+ function sameData(a, b) {
1395
+ const left = [a];
1396
+ const right = [b];
1397
+ const seen = /* @__PURE__ */ new Set();
1398
+ while (left.length > 0) {
1399
+ const x = left.pop();
1400
+ const y = right.pop();
1401
+ if (x === y || Number.isNaN(x) && Number.isNaN(y)) continue;
1402
+ if (x === null || y === null || typeof x !== "object" || typeof y !== "object" || seen.has(x)) return false;
1403
+ seen.add(x);
1404
+ if (Array.isArray(x)) {
1405
+ if (!Array.isArray(y) || x.length !== y.length) return false;
1406
+ for (let i = 0; i < x.length; i++) {
1407
+ left.push(x[i]);
1408
+ right.push(y[i]);
1409
+ }
1410
+ continue;
1411
+ }
1412
+ if (Array.isArray(y) || !isPlainObject(x) || !isPlainObject(y)) return false;
1413
+ const keys = Object.keys(x);
1414
+ if (keys.length !== Object.keys(y).length) return false;
1415
+ for (const key of keys) {
1416
+ if (!Object.prototype.hasOwnProperty.call(y, key)) return false;
1417
+ left.push(x[key]);
1418
+ right.push(y[key]);
1419
+ }
1420
+ }
1421
+ return true;
1422
+ }
1423
+ function isPlainObject(value) {
1424
+ const proto = Object.getPrototypeOf(value);
1425
+ return proto === Object.prototype || proto === null;
1426
+ }
1427
+ /** What filters read from a call; a call without `status` reads as a successful one. */
1428
+ function filterDoc(call) {
1429
+ const doc = {
1430
+ input: call.input,
1431
+ caller: call.caller,
1432
+ metadata: call.metadata
1041
1433
  };
1042
- if (typeof v.stacktrace === "string") body.stacktrace = v.stacktrace;
1043
- return body;
1434
+ if (call.status === "error") doc.error = call.error;
1435
+ else doc.output = call.output;
1436
+ return doc;
1044
1437
  }
1045
- /** Copies the wire caller, dropping `null`s and a `parent` inside `parent`. */
1046
- function decodeCaller(v, depth = 0) {
1047
- if (!isRecord(v)) return void 0;
1048
- const caller = {};
1049
- for (const key of [
1050
- "worker_id",
1051
- "worker_name",
1052
- "function_id",
1053
- "invocation_id"
1054
- ]) {
1055
- const value = str(v[key]);
1056
- if (value !== void 0) caller[key] = value;
1057
- }
1058
- if (depth === 0) {
1059
- const parent = decodeCaller(v.parent, 1);
1060
- if (parent) caller.parent = parent;
1061
- }
1062
- return caller;
1063
- }
1064
- function decodeActivation(v) {
1065
- if (!isRecord(v) || typeof v.observer_id !== "string") return void 0;
1066
- const activation = { observer_id: v.observer_id };
1067
- if (typeof v.activation_id === "string") activation.activation_id = v.activation_id;
1068
- return activation;
1069
- }
1070
- /** An observer as the owner sees it (`observeradded.observer`, `functionregistered.observers[]`). */
1071
- function decodeObserverInfo(v) {
1072
- const raw = isRecord(v) ? v : {};
1073
- const info = {
1074
- id: String(raw.id ?? ""),
1075
- args: isRecord(raw.args) ? raw.args : {},
1076
- filters: raw.filters === void 0 ? {} : raw.filters,
1077
- target: String(raw.target ?? ""),
1078
- capture: Array.isArray(raw.capture) ? raw.capture.filter((c) => typeof c === "string") : [...DEFAULT_CAPTURE],
1079
- on: str(raw.on) ?? "success"
1080
- };
1081
- if (isRecord(raw.legacy) && typeof raw.legacy.trigger_type === "string") info.legacy = {
1082
- trigger_type: raw.legacy.trigger_type,
1083
- config: raw.legacy.config ?? null
1084
- };
1085
- return info;
1086
- }
1087
- function decodeFunctionRegistered(v) {
1088
- return {
1089
- id: String(v.id ?? ""),
1090
- namespace: String(v.namespace ?? ""),
1091
- revision: num(v.revision) ?? 0,
1092
- local_dispatch: v.local_dispatch === true,
1093
- observers: Array.isArray(v.observers) ? v.observers.map(decodeObserverInfo) : []
1094
- };
1095
- }
1096
- function decodeObserverAdded(v) {
1097
- return {
1098
- function_id: String(v.function_id ?? ""),
1099
- namespace: String(v.namespace ?? ""),
1100
- revision: num(v.revision) ?? 0,
1101
- observer: decodeObserverInfo(v.observer)
1102
- };
1103
- }
1104
- function decodeObserverRemoved(v) {
1105
- return {
1106
- function_id: String(v.function_id ?? ""),
1107
- namespace: String(v.namespace ?? ""),
1108
- revision: num(v.revision) ?? 0,
1109
- id: String(v.id ?? "")
1110
- };
1111
- }
1112
- function decodeObserveResult(v) {
1113
- const msg = {
1114
- id: String(v.id ?? ""),
1115
- state: String(v.state ?? "")
1116
- };
1117
- const error = errorBody(v.error);
1118
- if (error) msg.error = error;
1119
- if (Array.isArray(v.warnings)) msg.warnings = v.warnings.filter((w) => typeof w === "string");
1120
- return msg;
1121
- }
1122
- function decodeObserverStateChanged(v) {
1123
- const msg = {
1124
- id: String(v.id ?? ""),
1125
- state: String(v.state ?? ""),
1126
- fires: num(v.fires) ?? 0
1127
- };
1128
- const reason = errorBody(v.reason);
1129
- if (reason) msg.reason = reason;
1130
- return msg;
1131
- }
1132
- function decodeWorkerRegistered(v) {
1133
- const msg = { worker_id: String(v.worker_id ?? "") };
1134
- if (typeof v.reattach_token === "string") msg.reattach_token = v.reattach_token;
1135
- if (Array.isArray(v.features)) msg.features = v.features.filter((f) => typeof f === "string");
1136
- return msg;
1137
- }
1138
- /** The observe fields of an inbound `invokefunction` (`caller`, `observe_depth`, `activation`). */
1139
- function decodeInvokeFunction(v) {
1140
- const msg = {
1141
- function_id: String(v.function_id ?? ""),
1142
- data: v.data
1143
- };
1144
- if (typeof v.invocation_id === "string") msg.invocation_id = v.invocation_id;
1145
- if (typeof v.traceparent === "string") msg.traceparent = v.traceparent;
1146
- if (typeof v.baggage === "string") msg.baggage = v.baggage;
1147
- if (isRecord(v.action)) msg.action = v.action;
1148
- if (v.metadata !== void 0 && v.metadata !== null) msg.metadata = v.metadata;
1149
- if (typeof v.namespace === "string") msg.namespace = v.namespace;
1150
- const caller = decodeCaller(v.caller);
1151
- if (caller) msg.caller = caller;
1152
- const depth = num(v.observe_depth);
1153
- if (depth !== void 0 && depth > 0) msg.observe_depth = depth;
1154
- const activation = decodeActivation(v.activation);
1155
- if (activation) msg.activation = activation;
1156
- return msg;
1157
- }
1158
- /** Drops `parent` (one level only). */
1159
- function stripCaller(caller) {
1160
- if (!caller) return void 0;
1161
- const { parent: _, ...rest } = caller;
1162
- return rest;
1163
- }
1164
- /** JSON's view of a message: `undefined` fields left out, no caller-owned objects retained. */
1165
- function snapshot(value) {
1166
- return JSON.parse(JSON.stringify(value));
1167
- }
1168
- /**
1169
- * `observe { id, source, target, ... }` from the three arguments of
1170
- * `iii.observe`. Only what the caller set is sent; the engine applies the
1171
- * defaults. `resolveNamespace` gives the namespace of an unqualified id (this
1172
- * worker's, `default` for `engine::*`).
1173
- */
1174
- function buildObserveMessage(id, source, target, options, resolveNamespace) {
1175
- const targetRef = typeof target === "string" ? { function_id: target } : target;
1176
- const sourceNamespace = resolveNamespace(source.namespace, source.function_id, "ObserveSource.namespace");
1177
- const targetNamespace = resolveNamespace(targetRef.namespace, targetRef.function_id, "Target.namespace");
1178
- return snapshot({
1179
- id,
1180
- source: {
1181
- function_id: source.function_id,
1182
- namespace: sourceNamespace,
1183
- args: source.args,
1184
- filters: source.filters,
1185
- capture: source.capture,
1186
- on: source.on,
1187
- deliver: source.deliver
1188
- },
1189
- target: {
1190
- function_id: targetRef.function_id,
1191
- namespace: targetNamespace
1192
- },
1193
- metadata: options?.metadata,
1194
- max_fires: options?.max_fires,
1195
- expires_in_ms: options?.expires_in_ms,
1196
- max_in_flight: options?.max_in_flight
1197
- });
1198
- }
1199
- /** `registerfunction.observe`: the four fields that travel, or `undefined` when none is set. */
1200
- function observeDescriptor(hooks) {
1201
- if (!hooks) return void 0;
1202
- const descriptor = snapshot({
1203
- delivery: hooks.delivery,
1204
- args_format: hooks.args_format,
1205
- legacy_trigger_type: hooks.legacy_trigger_type,
1206
- allow: hooks.allow
1207
- });
1208
- return Object.keys(descriptor).length > 0 ? descriptor : void 0;
1209
- }
1210
- function buildObserverAck(ack) {
1211
- const msg = {
1212
- function_id: ack.function_id,
1213
- id: ack.id,
1214
- revision: ack.revision
1215
- };
1216
- if (ack.namespace !== void 0) msg.namespace = ack.namespace;
1217
- if (ack.error) msg.error = {
1218
- code: ack.error.code,
1219
- message: ack.error.message
1220
- };
1221
- return msg;
1222
- }
1223
- /**
1224
- * An outbound `invokefunction`. `observe_depth` is left out when 0, and every
1225
- * optional field when unset.
1226
- */
1227
- function buildInvokeFunction(init) {
1228
- const msg = {};
1229
- if (init.invocation_id !== void 0) msg.invocation_id = init.invocation_id;
1230
- msg.function_id = init.function_id;
1231
- msg.data = init.data;
1232
- if (init.traceparent !== void 0) msg.traceparent = init.traceparent;
1233
- if (init.baggage !== void 0) msg.baggage = init.baggage;
1234
- if (init.action !== void 0) msg.action = init.action;
1235
- if (init.metadata !== void 0) msg.metadata = init.metadata;
1236
- if (init.namespace !== void 0) msg.namespace = init.namespace;
1237
- if (init.caller !== void 0) msg.caller = init.caller;
1238
- if (init.observe_depth !== void 0 && init.observe_depth > 0) msg.observe_depth = init.observe_depth;
1239
- if (init.activation !== void 0) msg.activation = init.activation;
1240
- return msg;
1241
- }
1242
- /** The caller an outbound call asserts from inside a handler: that handler, and its own caller one level up. */
1243
- function callerFor(ctx) {
1244
- const caller = {
1245
- function_id: ctx.function_id,
1246
- invocation_id: ctx.invocation_id
1247
- };
1248
- const parent = stripCaller(ctx.caller);
1249
- if (parent && Object.keys(parent).length > 0) caller.parent = parent;
1250
- return caller;
1251
- }
1252
-
1253
- //#endregion
1254
- //#region src/observable.ts
1255
1438
  /**
1256
- * The owner side of observe (sdk.md §1, §4.1–§4.3): per-function observer
1257
- * state, the observe hooks, the `Observer` object handed to them, and the
1258
- * reports of local invocations and `obs.emit` events.
1439
+ * The caller a report item carries: the engine sets `worker_id` and
1440
+ * `worker_name` itself, so they are left out (a `parent` keeps its own).
1441
+ * Nothing for a call made outside any handler.
1259
1442
  */
1260
- /** CONTRACT D11: `onObserverAdded` (and `onObserverRemoved`) still running after this is `OWNER_TIMEOUT`. */
1261
- const OBSERVE_HOOK_TIMEOUT_MS = 3e4;
1262
- function sameJson(a, b) {
1263
- return JSON.stringify(a) === JSON.stringify(b);
1443
+ function reportCaller(caller) {
1444
+ if (!caller) return void 0;
1445
+ const { worker_id: _, worker_name: __, ...rest } = caller;
1446
+ return Object.keys(rest).length > 0 ? rest : void 0;
1264
1447
  }
1265
- function rejectionBody(error) {
1266
- if (error instanceof ObserveRejection) return {
1267
- code: error.code,
1268
- message: error.message
1269
- };
1270
- return {
1271
- code: "OBSERVE_REJECTED",
1272
- message: error instanceof Error ? error.message : String(error)
1273
- };
1448
+ /** The key functions of a match hook given as keys, if it is one. */
1449
+ function matchKeysOf(hook) {
1450
+ return hook !== void 0 && typeof hook !== "function" ? hook : void 0;
1274
1451
  }
1275
- function onAccepts(on, ok) {
1276
- return on === "complete" || (on === "success" ? ok : on === "error" ? !ok : false);
1452
+ function keyList(keys) {
1453
+ return typeof keys === "string" ? [keys] : keys;
1277
1454
  }
1278
- /** The `Observer` an owner receives. Its identity is stable while the observer lives. */
1455
+ /** The `Observer` a host receives. Its identity is stable while the observer lives. */
1279
1456
  var ObserverImpl = class {
1280
1457
  constructor(owner, info, filter, revision) {
1281
1458
  this.owner = owner;
1282
1459
  this.active = false;
1460
+ this.activatedSeq = 0;
1283
1461
  this.adding = false;
1462
+ this.levels = {
1463
+ worker: "none",
1464
+ fn: "none"
1465
+ };
1466
+ this.acceptance = "pending";
1284
1467
  this.id = info.id;
1285
1468
  this.function_id = owner.functionId;
1286
1469
  this.args = info.args;
1287
1470
  this.filters = info.filters;
1288
1471
  this.target = info.target;
1289
- this.capture = info.capture;
1290
1472
  this.on = info.on;
1291
- if (info.legacy) this.legacy = info.legacy;
1473
+ this.capture = info.capture;
1292
1474
  this.filter = filter;
1293
1475
  this.revision = revision;
1294
1476
  }
@@ -1297,21 +1479,36 @@ var ObserverImpl = class {
1297
1479
  this.filters = info.filters;
1298
1480
  this.filter = filter;
1299
1481
  this.target = info.target;
1300
- this.capture = info.capture;
1301
1482
  this.on = info.on;
1483
+ this.capture = info.capture;
1302
1484
  }
1303
- matches(doc) {
1304
- return this.filter.matches(doc);
1305
- }
1306
- emit(event) {
1307
- return this.owner.emit(this, event);
1485
+ matches(call) {
1486
+ return onAccepts(this.on, call.status !== "error") && this.filter.matches(filterDoc(call));
1308
1487
  }
1309
- call(payload, opts) {
1310
- return this.owner.call(this, payload, opts?.timeoutMs);
1488
+ accepted() {
1489
+ const state = this.acceptance;
1490
+ if (state === "accepted") return Promise.resolve();
1491
+ if (state !== "pending") return Promise.reject(new ObserveRejection(state.code, state.message));
1492
+ return new Promise((resolve, reject) => {
1493
+ this.waiters ?? (this.waiters = []);
1494
+ this.waiters.push({
1495
+ resolve,
1496
+ reject
1497
+ });
1498
+ });
1311
1499
  }
1312
1500
  reject(code, message) {
1313
1501
  this.owner.reject(this, code, message);
1314
1502
  }
1503
+ /** @internal Acked (`accepted`) or never to be: settles `accepted()`, once. */
1504
+ settleAcceptance(outcome) {
1505
+ if (this.acceptance !== "pending") return;
1506
+ this.acceptance = outcome;
1507
+ const waiters = this.waiters ?? [];
1508
+ this.waiters = void 0;
1509
+ for (const waiter of waiters) if (outcome === "accepted") waiter.resolve();
1510
+ else waiter.reject(new ObserveRejection(outcome.code, outcome.message));
1511
+ }
1315
1512
  toJSON() {
1316
1513
  return {
1317
1514
  id: this.id,
@@ -1319,21 +1516,19 @@ var ObserverImpl = class {
1319
1516
  args: this.args,
1320
1517
  filters: this.filters,
1321
1518
  target: this.target,
1322
- capture: this.capture,
1323
1519
  on: this.on,
1324
- ...this.legacy ? { legacy: this.legacy } : {}
1520
+ capture: this.capture
1325
1521
  };
1326
1522
  }
1327
1523
  };
1328
1524
  /**
1329
1525
  * One registered function's observers, as the engine pushed them
1330
1526
  * (`functionregistered`, `observeradded`, `observerremoved`). Hooks run one
1331
- * at a time, in revision order.
1527
+ * at a time, in the order the engine announced the observers.
1332
1528
  */
1333
1529
  var FunctionObservers = class {
1334
- constructor(functionId, hooks, localDispatchOption, hasHandler, host) {
1530
+ constructor(functionId, localDispatchOption, hasHandler, host) {
1335
1531
  this.functionId = functionId;
1336
- this.hooks = hooks;
1337
1532
  this.localDispatchOption = localDispatchOption;
1338
1533
  this.hasHandler = hasHandler;
1339
1534
  this.host = host;
@@ -1343,17 +1538,79 @@ var FunctionObservers = class {
1343
1538
  this.revision = -1;
1344
1539
  this.known = /* @__PURE__ */ new Map();
1345
1540
  this.compiled = [];
1541
+ this.activations = 0;
1346
1542
  this.queue = Promise.resolve();
1347
1543
  this.disposed = false;
1348
1544
  this.releases = 0;
1349
- this.delivery = hooks?.delivery === "owner" ? "owner" : "auto";
1545
+ this.filterIndex = new FilterIndex();
1546
+ this.matchFailureLogged = false;
1547
+ this.matchChanged();
1548
+ }
1549
+ get reporter() {
1550
+ return this.host.reporter;
1551
+ }
1552
+ /** @internal */
1553
+ observeV2() {
1554
+ return this.host.observeV2();
1555
+ }
1556
+ /**
1557
+ * Whether a call would reach anyone. Without a call: any active observer
1558
+ * (one load). With a call, on a function matched by keys: an observer filed
1559
+ * under one of its keys (one lookup per key). Otherwise the call is not read.
1560
+ */
1561
+ isObserved(call) {
1562
+ if (this.compiled.length === 0) return false;
1563
+ const keys = this.matchKeys;
1564
+ const index = this.index;
1565
+ if (call === void 0 || !keys || !index) return true;
1566
+ for (const key of this.callKeys(keys, call)) if (index.has(key)) return true;
1567
+ return false;
1568
+ }
1569
+ /**
1570
+ * The observers of the call's snapshot that want `call` (`onObservationMatch`):
1571
+ * all of `snapshot` without a match hook, those of it the predicate accepts,
1572
+ * or those filed under one of the call's keys that joined the active set no
1573
+ * later than `activations` (the count when the call started), each once. A
1574
+ * match hook that throws matches nothing.
1575
+ */
1576
+ matching(call, snapshot, activations) {
1577
+ const hook = this.host.hooks(this.functionId).match;
1578
+ if (hook === void 0) return snapshot;
1579
+ if (typeof hook === "function") return snapshot.filter((obs) => {
1580
+ try {
1581
+ return hook(obs, call) === true;
1582
+ } catch (error) {
1583
+ this.matchFailed(error);
1584
+ return false;
1585
+ }
1586
+ });
1587
+ const index = this.index;
1588
+ if (this.matchKeys !== hook || !index) return [];
1589
+ const found = /* @__PURE__ */ new Set();
1590
+ for (const key of this.callKeys(hook, call)) {
1591
+ const filed = index.get(key);
1592
+ if (!filed) continue;
1593
+ for (const obs of filed) if (obs.activatedSeq <= activations) found.add(obs);
1594
+ }
1595
+ return [...found];
1350
1596
  }
1351
- /** Callbacks or owner delivery: what needs `observe.v1` on both sides. */
1352
- get needsObserve() {
1353
- return this.delivery === "owner" || !!this.hooks?.onObserverAdded || !!this.hooks?.onObserverRemoved;
1597
+ /** The function has a match hook (`onObservationMatch`) now. */
1598
+ hasMatchHook() {
1599
+ return this.host.hooks(this.functionId).match !== void 0;
1354
1600
  }
1355
- isObserved() {
1356
- return this.compiled.length > 0;
1601
+ /**
1602
+ * The active observers whose `on` accepts a call that succeeded (`ok`) or
1603
+ * failed and whose filters match `doc`, in the order of `compiled`. Matched
1604
+ * through the index of their filters' equality conditions when it narrows
1605
+ * them (`FilterIndex.narrows`): the call evaluates the filters of the
1606
+ * observers the index does not rule out. Otherwise each observer of
1607
+ * `compiled` is evaluated in order, which costs less and yields the same
1608
+ * observers in the same order.
1609
+ */
1610
+ selectActive(doc, ok) {
1611
+ const index = this.filterIndex;
1612
+ if (!index.narrows) return this.compiled.filter((obs) => onAccepts(obs.on, ok) && obs.filter.matches(doc));
1613
+ return index.matches(doc, (obs) => onAccepts(obs.on, ok));
1357
1614
  }
1358
1615
  observers() {
1359
1616
  return [...this.compiled];
@@ -1366,9 +1623,10 @@ var FunctionObservers = class {
1366
1623
  this.localDispatch = msg.local_dispatch && this.localDispatchOption && this.hasHandler;
1367
1624
  this.namespace = msg.namespace;
1368
1625
  this.revision = msg.revision;
1626
+ const releases = this.releases;
1369
1627
  this.enqueue(async () => {
1370
1628
  try {
1371
- await this.applySet(msg.observers, msg.revision, msg.namespace);
1629
+ if (this.releases === releases) await this.applySet(msg.observers, msg.revision, msg.namespace);
1372
1630
  } finally {
1373
1631
  this.confirmedEpoch = epoch;
1374
1632
  this.host.reporter.flush();
@@ -1378,8 +1636,12 @@ var FunctionObservers = class {
1378
1636
  onObserverAdded(msg) {
1379
1637
  if (this.disposed || msg.revision <= this.revision) return;
1380
1638
  this.revision = msg.revision;
1639
+ const releases = this.releases;
1381
1640
  this.enqueue(async () => {
1382
- if (this.known.get(msg.observer.id)?.rejection) await this.remove(msg.observer.id);
1641
+ if (this.disposed || this.releases !== releases || this.releasedEpoch !== void 0) return;
1642
+ const held = this.known.get(msg.observer.id);
1643
+ if (held && this.reack(held, msg.observer, msg.revision, msg.namespace, false)) return;
1644
+ if (held) await this.remove(held.id);
1383
1645
  await this.add(msg.observer, msg.revision, msg.namespace);
1384
1646
  });
1385
1647
  }
@@ -1389,9 +1651,10 @@ var FunctionObservers = class {
1389
1651
  this.enqueue(() => this.remove(msg.id));
1390
1652
  }
1391
1653
  /**
1392
- * `RegistrationRejected{FUNCTION_NAMESPACE_CONFLICT}`: no local dispatch, no
1393
- * observers, and its held reports are discarded (they could never be
1394
- * confirmed, and would starve other functions of buffer).
1654
+ * The engine refused the function (`registrationrejected`), or it no
1655
+ * longer holds it here: no local dispatch, no observers, and its held
1656
+ * reports are discarded (they could never be confirmed, and would starve
1657
+ * other functions of buffer).
1395
1658
  */
1396
1659
  onRegistrationRejected(epoch) {
1397
1660
  this.confirmed = false;
@@ -1408,30 +1671,134 @@ var FunctionObservers = class {
1408
1671
  this.onRegistrationRejected(-1);
1409
1672
  }
1410
1673
  /**
1674
+ * An `onObserverAdded` was set at `level` (the worker's, or this
1675
+ * function's): the active observers that were set up without one there are
1676
+ * caught up. It runs for each of them, in the hook queue; a throw
1677
+ * late-rejects that observer. One warning names the function and how many
1678
+ * observers were active without the hook.
1679
+ */
1680
+ catchUp(level) {
1681
+ if (this.disposed) return;
1682
+ this.enqueue(async () => {
1683
+ const behind = this.compiled.filter((obs) => obs.levels[level] === "bare");
1684
+ if (behind.length === 0) return;
1685
+ this.host.logWarn(`onObserverAdded was set for ${this.functionId} while ${behind.length} observer(s) were active without it; it runs for each of them now`);
1686
+ for (const obs of behind) {
1687
+ const hook = this.addedHook(level);
1688
+ if (!hook) return;
1689
+ if (!obs.active || obs.levels[level] !== "bare") continue;
1690
+ const outcome = await this.runHook(() => hook(obs));
1691
+ if (outcome.ok) {
1692
+ obs.levels[level] = "hooked";
1693
+ continue;
1694
+ }
1695
+ obs.levels[level] = "none";
1696
+ if (outcome.timedOut) this.undoLate(outcome.late, obs, level);
1697
+ this.reject(obs, outcome.code, outcome.message);
1698
+ }
1699
+ });
1700
+ }
1701
+ /**
1702
+ * The function's match hook was set or removed (decision 45). Matching by
1703
+ * keys rebuilds the index from the active observers; an observer whose keys
1704
+ * cannot be computed is late-rejected.
1705
+ */
1706
+ matchChanged() {
1707
+ const keys = matchKeysOf(this.host.hooks(this.functionId).match);
1708
+ if (keys === this.matchKeys) return;
1709
+ this.matchKeys = keys;
1710
+ this.index = keys ? /* @__PURE__ */ new Map() : void 0;
1711
+ for (const obs of this.known.values()) obs.keys = void 0;
1712
+ for (const obs of this.compiled) {
1713
+ const failure = this.prepareKeys(obs);
1714
+ if (failure) this.reject(obs, failure.code, failure.message);
1715
+ else this.file(obs);
1716
+ }
1717
+ }
1718
+ /** The keys of a call; a key function that throws gives none. */
1719
+ callKeys(keys, call) {
1720
+ try {
1721
+ return keyList(keys.call(call));
1722
+ } catch (error) {
1723
+ this.matchFailed(error);
1724
+ return [];
1725
+ }
1726
+ }
1727
+ matchFailed(error) {
1728
+ if (this.matchFailureLogged) return;
1729
+ this.matchFailureLogged = true;
1730
+ this.host.logError(`onObservationMatch of ${this.functionId} threw; the call matches no observer`, error);
1731
+ }
1732
+ /**
1411
1733
  * Stops delivery at once, then removes every observer through the hook
1412
1734
  * queue, after the adds queued before it (which undo themselves: `add`).
1413
1735
  */
1414
1736
  dropAll() {
1415
- for (const obs of this.compiled) obs.active = false;
1416
- this.compiled = [];
1737
+ for (const obs of this.compiled) this.deactivate(obs);
1417
1738
  this.enqueue(async () => {
1418
1739
  for (const id of [...this.known.keys()]) await this.remove(id);
1419
1740
  });
1420
1741
  }
1421
1742
  enqueue(task) {
1422
1743
  this.queue = this.queue.then(task).catch((error) => {
1423
- this.host.logError(`Observe hook failed for ${this.functionId}`, error);
1744
+ this.host.logError(`Observer hook failed for ${this.functionId}`, error);
1424
1745
  });
1425
1746
  }
1426
- activate(obs) {
1747
+ addedHook(level) {
1748
+ const hooks = this.host.hooks(this.functionId);
1749
+ return level === "worker" ? hooks.workerAdded : hooks.added;
1750
+ }
1751
+ removedHook(level) {
1752
+ const hooks = this.host.hooks(this.functionId);
1753
+ return level === "worker" ? hooks.workerRemoved : hooks.removed;
1754
+ }
1755
+ activate(obs) {
1427
1756
  if (obs.active) return;
1428
1757
  obs.active = true;
1758
+ obs.activatedSeq = ++this.activations;
1429
1759
  this.compiled = [...this.compiled, obs];
1760
+ this.filterIndex.insert(obs, obs.filter, obs.activatedSeq);
1761
+ this.file(obs);
1430
1762
  }
1431
1763
  deactivate(obs) {
1432
1764
  if (!obs.active) return;
1433
1765
  obs.active = false;
1434
1766
  this.compiled = this.compiled.filter((o) => o !== obs);
1767
+ this.filterIndex.remove(obs);
1768
+ this.unfile(obs);
1769
+ }
1770
+ /** Computes the keys `obs` is filed under, once, when the function is matched by keys. */
1771
+ prepareKeys(obs) {
1772
+ const keys = this.matchKeys;
1773
+ if (!keys || obs.keys) return void 0;
1774
+ try {
1775
+ obs.keys = [...new Set(keyList(keys.observer(obs)))];
1776
+ return;
1777
+ } catch (error) {
1778
+ return {
1779
+ code: "OBSERVE_REJECTED",
1780
+ message: `the keys of observer ${obs.id} of ${this.functionId} could not be computed: ${error instanceof Error ? error.message : String(error)}`
1781
+ };
1782
+ }
1783
+ }
1784
+ file(obs) {
1785
+ const index = this.index;
1786
+ if (!index || !obs.keys) return;
1787
+ for (const key of obs.keys) {
1788
+ const filed = index.get(key);
1789
+ if (filed) filed.add(obs);
1790
+ else index.set(key, new Set([obs]));
1791
+ }
1792
+ }
1793
+ unfile(obs) {
1794
+ const index = this.index;
1795
+ if (!index || !obs.keys) return;
1796
+ for (const key of obs.keys) {
1797
+ const filed = index.get(key);
1798
+ if (!filed) continue;
1799
+ filed.delete(obs);
1800
+ if (filed.size === 0) index.delete(key);
1801
+ }
1435
1802
  }
1436
1803
  ack(info, revision, namespace, error) {
1437
1804
  this.host.sendAck({
@@ -1442,55 +1809,82 @@ var FunctionObservers = class {
1442
1809
  ...error ? { error } : {}
1443
1810
  });
1444
1811
  }
1445
- /** Diffs the engine's full set against what this SDK holds. */
1812
+ /**
1813
+ * Diffs the engine's full set against what this SDK holds: the ones it no
1814
+ * longer lists are removed, the ones it holds are acked again
1815
+ * ({@link FunctionObservers.reack}), and the others are added.
1816
+ */
1446
1817
  async applySet(list, revision, namespace) {
1447
1818
  const incoming = new Set(list.map((o) => o.id));
1448
1819
  for (const id of [...this.known.keys()]) if (!incoming.has(id)) await this.remove(id);
1449
1820
  for (const info of list) {
1450
- const existing = this.known.get(info.id);
1451
- if (existing && sameJson(existing.args, info.args) && sameJson(existing.legacy, info.legacy)) this.keep(existing, info, revision, namespace);
1452
- else {
1453
- if (existing) await this.remove(info.id);
1454
- await this.add(info, revision, namespace);
1455
- }
1821
+ const held = this.known.get(info.id);
1822
+ if (held && this.reack(held, info, revision, namespace, true)) continue;
1823
+ if (held) await this.remove(info.id);
1824
+ await this.add(info, revision, namespace);
1456
1825
  }
1457
1826
  }
1458
1827
  /**
1459
- * A kept observer: the hook already ran for it; take the engine's filters
1460
- * and ack it again, or repeat the owner's late rejection of it.
1828
+ * Acks again, at `revision` and without running any hook, an observer this
1829
+ * SDK holds that the engine announced again (decision 44): one with the
1830
+ * same args, served from now on with the filters, target, capture and `on`
1831
+ * it was announced with (its keys computed again when they changed), or,
1832
+ * when `listed` by `functionregistered`, one rejected late, whose rejection
1833
+ * is sent again. `false` for an observer to add as a new one after removing
1834
+ * the one held: other args, a late rejection announced by `observeradded`,
1835
+ * or a view this SDK cannot serve (filters that do not compile, keys that
1836
+ * throw).
1461
1837
  */
1462
- keep(obs, info, revision, namespace) {
1463
- if (obs.rejection) {
1464
- obs.revision = revision;
1465
- this.ack(info, revision, namespace, obs.rejection);
1466
- return;
1838
+ reack(held, info, revision, namespace, listed) {
1839
+ if (held.rejection) {
1840
+ if (!listed) return false;
1841
+ held.revision = revision;
1842
+ this.ack(info, revision, namespace, held.rejection);
1843
+ return true;
1467
1844
  }
1468
- let filter = obs.filter;
1469
- if (!sameJson(obs.filters, info.filters)) try {
1470
- filter = compileFilter(info.filters, { trusted: true });
1471
- } catch (error) {
1472
- obs.revision = revision;
1473
- this.deactivate(obs);
1474
- this.ack(info, revision, namespace, {
1475
- code: "INVALID_FILTER",
1476
- message: error.message
1477
- });
1478
- return;
1845
+ if (!sameJson(held.args, info.args)) return false;
1846
+ if (!sameView(held, info)) {
1847
+ let filter = held.filter;
1848
+ if (!sameJson(held.filters, info.filters)) try {
1849
+ filter = compileFilter(info.filters, { trusted: true });
1850
+ } catch {
1851
+ return false;
1852
+ }
1853
+ const keys = this.viewKeys(held, info, filter);
1854
+ if (keys === null) return false;
1855
+ if (held.active) this.unfile(held);
1856
+ held.update(info, filter);
1857
+ if (keys !== void 0) held.keys = keys;
1858
+ if (held.active) {
1859
+ this.file(held);
1860
+ this.filterIndex.insert(held, held.filter, held.activatedSeq);
1861
+ }
1479
1862
  }
1480
- obs.update(info, filter);
1481
- obs.revision = revision;
1482
- this.activate(obs);
1863
+ held.revision = revision;
1483
1864
  this.ack(info, revision, namespace);
1865
+ return true;
1866
+ }
1867
+ /**
1868
+ * The keys `held` is filed under once it takes the view `info` (with
1869
+ * `filter`), on a function matched by keys: computed on a copy, so a key
1870
+ * function that throws (`null`) leaves `held` as it was. `undefined` when
1871
+ * the function is not matched by keys.
1872
+ */
1873
+ viewKeys(held, info, filter) {
1874
+ const keys = this.matchKeys;
1875
+ if (!keys) return void 0;
1876
+ const view = Object.assign(Object.create(Object.getPrototypeOf(held)), held);
1877
+ view.update(info, filter);
1878
+ try {
1879
+ return [...new Set(keyList(keys.observer(view)))];
1880
+ } catch {
1881
+ return null;
1882
+ }
1484
1883
  }
1485
- /** handleAdded (§4.2): hook, then the compiled set, then the ack. */
1884
+ /** handleAdded (§4.3): the hooks of both levels, then the active set, then the ack. */
1486
1885
  async add(info, revision, namespace) {
1487
1886
  if (this.disposed || this.releasedEpoch !== void 0) return;
1488
1887
  const releases = this.releases;
1489
- const existing = this.known.get(info.id);
1490
- if (existing) {
1491
- this.keep(existing, info, revision, namespace);
1492
- return;
1493
- }
1494
1888
  let filter;
1495
1889
  try {
1496
1890
  filter = compileFilter(info.filters, { trusted: true });
@@ -1502,43 +1896,91 @@ var FunctionObservers = class {
1502
1896
  return;
1503
1897
  }
1504
1898
  const obs = new ObserverImpl(this, info, filter, revision);
1505
- const onAdded = this.hooks?.onObserverAdded;
1506
- if (onAdded) {
1507
- obs.adding = true;
1508
- const outcome = await this.runHook(() => onAdded.call(this.hooks, obs));
1509
- obs.adding = false;
1510
- if (!outcome.ok) {
1511
- this.ack(info, revision, namespace, {
1512
- code: outcome.code,
1513
- message: outcome.message
1514
- });
1515
- if (outcome.timedOut) outcome.late.then(() => this.enqueue(() => this.callRemoved(obs)), () => void 0);
1516
- return;
1517
- }
1899
+ obs.adding = true;
1900
+ const failure = await this.setUp(obs);
1901
+ obs.adding = false;
1902
+ if (failure) {
1903
+ this.ack(info, revision, namespace, failure);
1904
+ obs.settleAcceptance(failure);
1905
+ return;
1518
1906
  }
1519
1907
  if (this.disposed || this.releases !== releases) {
1520
- await this.callRemoved(obs);
1908
+ await this.unwind(obs);
1909
+ obs.settleAcceptance({
1910
+ code: "OBSERVER_NOT_ACTIVE",
1911
+ message: `${this.functionId} was released before observer ${obs.id} was accepted`
1912
+ });
1521
1913
  return;
1522
1914
  }
1523
1915
  this.known.set(obs.id, obs);
1524
- if (obs.rejection) {
1525
- this.ack(info, revision, namespace, obs.rejection);
1916
+ const rejection = obs.rejection ?? this.prepareKeys(obs);
1917
+ if (rejection) {
1918
+ obs.rejection = rejection;
1919
+ this.ack(info, revision, namespace, rejection);
1920
+ obs.settleAcceptance(rejection);
1921
+ await this.unwind(obs);
1526
1922
  return;
1527
1923
  }
1528
1924
  this.activate(obs);
1529
1925
  this.ack(info, revision, namespace);
1926
+ obs.settleAcceptance("accepted");
1927
+ }
1928
+ /**
1929
+ * Runs `onObserverAdded` of the worker, then of the function. When one
1930
+ * fails, the levels whose `onObserverAdded` resolved are torn down, and the
1931
+ * rejection is returned.
1932
+ */
1933
+ async setUp(obs) {
1934
+ for (const level of ["worker", "fn"]) {
1935
+ const hook = this.addedHook(level);
1936
+ if (!hook) {
1937
+ obs.levels[level] = "bare";
1938
+ continue;
1939
+ }
1940
+ const outcome = await this.runHook(() => hook(obs));
1941
+ if (!outcome.ok) {
1942
+ if (outcome.timedOut) this.undoLate(outcome.late, obs, level);
1943
+ await this.unwind(obs);
1944
+ return {
1945
+ code: outcome.code,
1946
+ message: outcome.message
1947
+ };
1948
+ }
1949
+ obs.levels[level] = "hooked";
1950
+ }
1951
+ }
1952
+ /**
1953
+ * Undoes the setup of an observer that is not accepted: `onObserverRemoved`
1954
+ * runs only at the levels whose `onObserverAdded` resolved (§4.3), never at
1955
+ * a level set up without one.
1956
+ */
1957
+ async unwind(obs) {
1958
+ for (const level of ["worker", "fn"]) if (obs.levels[level] === "bare") obs.levels[level] = "none";
1959
+ await this.tearDown(obs);
1960
+ }
1961
+ /** Runs `onObserverRemoved` of the function, then of the worker, for each level set up, once. */
1962
+ async tearDown(obs) {
1963
+ for (const level of ["fn", "worker"]) {
1964
+ if (obs.levels[level] === "none") continue;
1965
+ obs.levels[level] = "none";
1966
+ await this.runRemoved(obs, level);
1967
+ }
1968
+ }
1969
+ /** A timed-out `onObserverAdded` that resolves later is undone by its level's `onObserverRemoved`. */
1970
+ undoLate(late, obs, level) {
1971
+ late.then(() => this.enqueue(() => this.runRemoved(obs, level)), () => void 0);
1530
1972
  }
1531
1973
  async remove(id) {
1532
1974
  const obs = this.known.get(id);
1533
1975
  if (!obs) return;
1534
1976
  this.known.delete(id);
1535
1977
  this.deactivate(obs);
1536
- await this.callRemoved(obs);
1978
+ await this.tearDown(obs);
1537
1979
  }
1538
- async callRemoved(obs) {
1539
- const onRemoved = this.hooks?.onObserverRemoved;
1540
- if (!onRemoved) return;
1541
- const outcome = await this.runHook(() => onRemoved.call(this.hooks, obs));
1980
+ async runRemoved(obs, level) {
1981
+ const hook = this.removedHook(level);
1982
+ if (!hook) return;
1983
+ const outcome = await this.runHook(() => hook(obs));
1542
1984
  if (!outcome.ok) this.host.logError(`onObserverRemoved failed for observer ${obs.id} of ${this.functionId}: ${outcome.message}`);
1543
1985
  }
1544
1986
  async runHook(fn) {
@@ -1553,7 +1995,7 @@ var FunctionObservers = class {
1553
1995
  if (await Promise.race([run.then(() => "done"), timeout]) === "timeout") return {
1554
1996
  ok: false,
1555
1997
  code: "OWNER_TIMEOUT",
1556
- message: `observe hook of ${this.functionId} still running after ${timeoutMs}ms`,
1998
+ message: `observer hook of ${this.functionId} still running after ${timeoutMs}ms`,
1557
1999
  timedOut: true,
1558
2000
  late: run
1559
2001
  };
@@ -1569,103 +2011,7 @@ var FunctionObservers = class {
1569
2011
  if (timer) clearTimeout(timer);
1570
2012
  }
1571
2013
  }
1572
- requireOwnerDelivery(what) {
1573
- if (this.delivery !== "owner") throw new InvocationError({
1574
- code: "NOT_OWNER_DELIVERED",
1575
- message: `obs.${what}() needs an owner-delivered function; ${this.functionId} is auto-delivered (observe.delivery)`,
1576
- function_id: this.functionId
1577
- });
1578
- }
1579
- isActive(obs) {
1580
- return obs.active && this.known.get(obs.id) === obs;
1581
- }
1582
- /**
1583
- * The caller an event carries (sdk.md §1): inside the function's own
1584
- * handler, that invocation's caller; inside another handler, that handler;
1585
- * outside any handler, this worker only.
1586
- */
1587
- eventCaller(cur) {
1588
- if (cur && cur.function_id === this.functionId) return {
1589
- caller: cur.caller,
1590
- own: true
1591
- };
1592
- const { worker_id, worker_name } = this.host.identity();
1593
- const caller = worker_id !== void 0 ? {
1594
- worker_id,
1595
- worker_name
1596
- } : { worker_name };
1597
- if (cur) {
1598
- caller.function_id = cur.function_id;
1599
- caller.invocation_id = cur.invocation_id;
1600
- const parent = stripCaller(cur.caller);
1601
- if (parent && Object.keys(parent).length > 0) caller.parent = parent;
1602
- }
1603
- return {
1604
- caller,
1605
- own: false
1606
- };
1607
- }
1608
- /**
1609
- * Hands `event` to one observer. `false`, and nothing sent, when its
1610
- * filters reject the event or it is no longer active (removed or rejected
1611
- * meanwhile): an owner's fan-out loop must not stop for one observer.
1612
- */
1613
- emit(obs, event) {
1614
- this.requireOwnerDelivery("emit");
1615
- if (!this.isActive(obs)) return false;
1616
- const cur = callContext();
1617
- const { caller, own } = this.eventCaller(cur);
1618
- const metadata = cur?.metadata;
1619
- if (!obs.filter.matches({
1620
- input: event,
1621
- caller,
1622
- metadata
1623
- })) return false;
1624
- const values = { input: event };
1625
- if (caller !== void 0) values.caller = caller;
1626
- if (metadata !== void 0) values.metadata = metadata;
1627
- const trace = cur ? {
1628
- traceparent: cur.traceparent,
1629
- baggage: cur.baggage
1630
- } : this.host.traceContext();
1631
- this.host.reporter.pushEmit({
1632
- function_id: this.functionId,
1633
- namespace: this.namespace,
1634
- invocation_id: own && cur ? cur.invocation_id : randomUUID(),
1635
- status: "success",
1636
- values,
1637
- captures: obs.capture,
1638
- started_at_ms: Date.now(),
1639
- duration_ms: 0,
1640
- observe_depth: cur ? cur.observe_depth : callDepth(),
1641
- traceparent: trace.traceparent,
1642
- baggage: trace.baggage,
1643
- observer_id: obs.id,
1644
- event,
1645
- context: cur
1646
- });
1647
- return true;
1648
- }
1649
- async call(obs, payload, timeoutMs) {
1650
- this.requireOwnerDelivery("call");
1651
- if (!this.isActive(obs)) throw new InvocationError({
1652
- code: "OBSERVER_NOT_ACTIVE",
1653
- message: `observer ${obs.id} of ${this.functionId} is not active`,
1654
- function_id: this.functionId
1655
- });
1656
- const cur = callContext();
1657
- const { caller } = this.eventCaller(cur);
1658
- if (!obs.filter.matches({
1659
- input: payload,
1660
- caller,
1661
- metadata: cur?.metadata
1662
- })) throw new InvocationError({
1663
- code: "FILTERS_NOT_MATCHED",
1664
- message: `the filters of observer ${obs.id} reject this payload`,
1665
- function_id: this.functionId
1666
- });
1667
- return this.host.callTarget(obs.target, obs.id, payload, timeoutMs);
1668
- }
2014
+ /** @internal Late rejection (`obs.reject`, a failed catch-up): inactive at once, then torn down. */
1669
2015
  reject(obs, code, message) {
1670
2016
  if (obs.adding) {
1671
2017
  obs.rejection = {
@@ -1674,7 +2020,7 @@ var FunctionObservers = class {
1674
2020
  };
1675
2021
  return;
1676
2022
  }
1677
- if (this.known.get(obs.id) !== obs) return;
2023
+ if (this.known.get(obs.id) !== obs || obs.rejection) return;
1678
2024
  obs.rejection = {
1679
2025
  code,
1680
2026
  message
@@ -1690,52 +2036,343 @@ var FunctionObservers = class {
1690
2036
  message
1691
2037
  }
1692
2038
  });
2039
+ this.enqueue(() => this.tearDown(obs));
2040
+ }
2041
+ };
2042
+ /**
2043
+ * The delivery of one call (v2 §4.4–§4.6, decisions 20, 36, 38, 45, 55): the
2044
+ * observers are matched (`onObservationMatch`), then the function's
2045
+ * `onObservationDeliver` delivers the call itself, or iii delivers it to the
2046
+ * matched observers whose `on` and filters accept it. For a local call the
2047
+ * host evaluates `on` and filters and reports the observers delivered in
2048
+ * one report item. For a routed call the engine evaluates them: the answer
2049
+ * carries the observers the match hook matched (`matched`), or says that
2050
+ * the deliver hook delivered the call (`delivered`), or neither for a
2051
+ * function with no match hook and no deliver hook.
2052
+ */
2053
+ var Delivery = class {
2054
+ constructor(owner, init) {
2055
+ this.owner = owner;
2056
+ this.init = init;
2057
+ this.delivered = false;
2058
+ }
2059
+ /** Resolves to what the caller gets back, or rejects with what it gets thrown. */
2060
+ async run(deliver) {
2061
+ const { call, snapshot, activations, thrown, routed } = this.init;
2062
+ const matched = this.owner.matching(call, snapshot, activations);
2063
+ if (deliver !== void 0) {
2064
+ if (routed) this.delivered = true;
2065
+ return deliver(call, matched);
2066
+ }
2067
+ if (routed) {
2068
+ if (this.owner.hasMatchHook()) this.matched = matched.map((obs) => obs.id);
2069
+ } else {
2070
+ const selected = this.select(call, matched);
2071
+ if (selected.length > 0) this.owner.reporter.push(this.item(call, selected));
2072
+ }
2073
+ if (call.status === "error") throw thrown;
2074
+ return call.output;
1693
2075
  }
1694
2076
  /**
1695
- * Evaluates `set` (the compiled set captured when the call started) on a
1696
- * finished local invocation of an auto function, and reports it when an
1697
- * observer matches. Never throws.
2077
+ * The error body a call answers with for `error`: the handler's own, or
2078
+ * what the deliver hook threw ({@link deliverErrorBody}).
1698
2079
  */
1699
- reportLocal(set, init) {
1700
- if (this.delivery !== "auto" || set.length === 0) return;
1701
- const doc = {
1702
- input: init.input,
1703
- caller: init.caller,
1704
- metadata: init.metadata
1705
- };
1706
- if (init.ok) doc.output = init.output;
1707
- else doc.error = init.error;
1708
- const matched = [];
2080
+ errorBody(error) {
2081
+ const { call, thrown } = this.init;
2082
+ return error === thrown && call.error ? call.error : deliverErrorBody(error);
2083
+ }
2084
+ /**
2085
+ * The matched observers whose `on` and filters accept `call`, in the order
2086
+ * of `matched`. Without a match hook `matched` is the call's snapshot; while
2087
+ * it is also the active set (no observer joined or left since the call
2088
+ * started), {@link FunctionObservers.selectActive} selects them, through
2089
+ * the index of the filters' equality conditions when it narrows them.
2090
+ * Otherwise each matched observer's filters are evaluated.
2091
+ */
2092
+ select(call, matched) {
2093
+ const ok = call.status !== "error";
2094
+ const doc = filterDoc(call);
2095
+ if (matched === this.init.snapshot && matched === this.owner.compiled) return this.owner.selectActive(doc, ok);
2096
+ return matched.filter((obs) => onAccepts(obs.on, ok) && obs.filter.matches(doc));
2097
+ }
2098
+ /** The report item of a local call delivered to `selected`. */
2099
+ item(call, selected) {
2100
+ const init = this.init;
1709
2101
  const captures = /* @__PURE__ */ new Set();
1710
- for (const obs of set) {
1711
- if (!onAccepts(obs.on, init.ok)) continue;
1712
- if (!obs.filter.matches(doc)) continue;
1713
- matched.push(obs.id);
1714
- for (const c of obs.capture) captures.add(c);
1715
- }
1716
- if (matched.length === 0) return;
1717
- const values = { input: init.input };
1718
- if (init.ok) values.output = init.output;
1719
- else values.error = init.error;
1720
- if (init.caller !== void 0) values.caller = init.caller;
1721
- if (init.metadata !== void 0) values.metadata = init.metadata;
1722
- this.host.reporter.push({
1723
- function_id: this.functionId,
1724
- namespace: this.namespace,
1725
- invocation_id: init.invocation_id,
1726
- matched,
1727
- status: init.ok ? "success" : "error",
2102
+ for (const obs of selected) for (const c of obs.capture) captures.add(c);
2103
+ const ok = call.status !== "error";
2104
+ const values = { input: call.input };
2105
+ if (ok) values.output = call.output;
2106
+ else values.error = call.error;
2107
+ const caller = reportCaller(call.caller);
2108
+ if (caller !== void 0) values.caller = caller;
2109
+ if (call.metadata !== void 0) values.metadata = call.metadata;
2110
+ return {
2111
+ function_id: this.owner.functionId,
2112
+ namespace: this.owner.namespace,
2113
+ invocation_id: call.invocation_id,
2114
+ matched: selected.map((obs) => obs.id),
2115
+ status: ok ? "success" : "error",
1728
2116
  values,
1729
2117
  captures,
2118
+ output_is_input: ok && call.output === call.input && this.owner.observeV2(),
1730
2119
  started_at_ms: init.started_at_ms,
1731
2120
  duration_ms: init.duration_ms,
1732
2121
  observe_depth: init.observe_depth,
1733
2122
  traceparent: init.traceparent,
1734
2123
  baggage: init.baggage
1735
- });
2124
+ };
1736
2125
  }
1737
2126
  };
1738
2127
 
2128
+ //#endregion
2129
+ //#region src/observe-wire.ts
2130
+ /** CONTRACT D1: what an absent `capture` means. */
2131
+ const DEFAULT_CAPTURE = [
2132
+ "input",
2133
+ "output",
2134
+ "caller"
2135
+ ];
2136
+ function isRecord(v) {
2137
+ return v !== null && typeof v === "object" && !Array.isArray(v);
2138
+ }
2139
+ function str(v) {
2140
+ return typeof v === "string" ? v : void 0;
2141
+ }
2142
+ function num(v) {
2143
+ return typeof v === "number" ? v : void 0;
2144
+ }
2145
+ function errorBody(v) {
2146
+ if (!isRecord(v)) return void 0;
2147
+ const body = {
2148
+ code: String(v.code ?? ""),
2149
+ message: String(v.message ?? "")
2150
+ };
2151
+ if (typeof v.stacktrace === "string") body.stacktrace = v.stacktrace;
2152
+ return body;
2153
+ }
2154
+ /** Copies the wire caller, dropping `null`s and a `parent` inside `parent`. */
2155
+ function decodeCaller(v, depth = 0) {
2156
+ if (!isRecord(v)) return void 0;
2157
+ const caller = {};
2158
+ for (const key of [
2159
+ "worker_id",
2160
+ "worker_name",
2161
+ "function_id",
2162
+ "invocation_id"
2163
+ ]) {
2164
+ const value = str(v[key]);
2165
+ if (value !== void 0) caller[key] = value;
2166
+ }
2167
+ if (depth === 0) {
2168
+ const parent = decodeCaller(v.parent, 1);
2169
+ if (parent) caller.parent = parent;
2170
+ }
2171
+ return caller;
2172
+ }
2173
+ function decodeActivation(v) {
2174
+ if (!isRecord(v) || typeof v.observer_id !== "string") return void 0;
2175
+ const activation = { observer_id: v.observer_id };
2176
+ if (typeof v.activation_id === "string") activation.activation_id = v.activation_id;
2177
+ return activation;
2178
+ }
2179
+ /** An observer as its host sees it (`observeradded.observer`, `functionregistered.observers[]`). */
2180
+ function decodeObserverInfo(v) {
2181
+ const raw = isRecord(v) ? v : {};
2182
+ return {
2183
+ id: String(raw.id ?? ""),
2184
+ args: isRecord(raw.args) ? raw.args : {},
2185
+ filters: raw.filters === void 0 ? {} : raw.filters,
2186
+ target: String(raw.target ?? ""),
2187
+ capture: Array.isArray(raw.capture) ? raw.capture.filter((c) => typeof c === "string") : [...DEFAULT_CAPTURE],
2188
+ on: str(raw.on) ?? "success"
2189
+ };
2190
+ }
2191
+ function decodeFunctionRegistered(v) {
2192
+ return {
2193
+ id: String(v.id ?? ""),
2194
+ namespace: String(v.namespace ?? ""),
2195
+ revision: num(v.revision) ?? 0,
2196
+ local_dispatch: v.local_dispatch === true,
2197
+ observers: Array.isArray(v.observers) ? v.observers.map(decodeObserverInfo) : []
2198
+ };
2199
+ }
2200
+ function decodeObserverAdded(v) {
2201
+ return {
2202
+ function_id: String(v.function_id ?? ""),
2203
+ namespace: String(v.namespace ?? ""),
2204
+ revision: num(v.revision) ?? 0,
2205
+ observer: decodeObserverInfo(v.observer)
2206
+ };
2207
+ }
2208
+ function decodeObserverRemoved(v) {
2209
+ return {
2210
+ function_id: String(v.function_id ?? ""),
2211
+ namespace: String(v.namespace ?? ""),
2212
+ revision: num(v.revision) ?? 0,
2213
+ id: String(v.id ?? "")
2214
+ };
2215
+ }
2216
+ function decodeObserveResult(v) {
2217
+ const msg = {
2218
+ id: String(v.id ?? ""),
2219
+ state: String(v.state ?? "")
2220
+ };
2221
+ const error = errorBody(v.error);
2222
+ if (error) msg.error = error;
2223
+ if (Array.isArray(v.warnings)) msg.warnings = v.warnings.filter((w) => typeof w === "string");
2224
+ return msg;
2225
+ }
2226
+ function decodeObserverStateChanged(v) {
2227
+ const msg = {
2228
+ id: String(v.id ?? ""),
2229
+ state: String(v.state ?? ""),
2230
+ fires: num(v.fires) ?? 0
2231
+ };
2232
+ const reason = errorBody(v.reason);
2233
+ if (reason) msg.reason = reason;
2234
+ return msg;
2235
+ }
2236
+ function decodeWorkerRegistered(v) {
2237
+ const msg = { worker_id: String(v.worker_id ?? "") };
2238
+ if (typeof v.reattach_token === "string") msg.reattach_token = v.reattach_token;
2239
+ if (Array.isArray(v.features)) msg.features = v.features.filter((f) => typeof f === "string");
2240
+ return msg;
2241
+ }
2242
+ /** The observe fields of an inbound `invokefunction` (`caller`, `observe_depth`, `activation`). */
2243
+ function decodeInvokeFunction(v) {
2244
+ const msg = {
2245
+ function_id: String(v.function_id ?? ""),
2246
+ data: v.data
2247
+ };
2248
+ if (typeof v.invocation_id === "string") msg.invocation_id = v.invocation_id;
2249
+ if (typeof v.traceparent === "string") msg.traceparent = v.traceparent;
2250
+ if (typeof v.baggage === "string") msg.baggage = v.baggage;
2251
+ if (isRecord(v.action)) msg.action = v.action;
2252
+ if (v.metadata !== void 0 && v.metadata !== null) msg.metadata = v.metadata;
2253
+ if (typeof v.namespace === "string") msg.namespace = v.namespace;
2254
+ const caller = decodeCaller(v.caller);
2255
+ if (caller) msg.caller = caller;
2256
+ const depth = num(v.observe_depth);
2257
+ if (depth !== void 0 && depth > 0) msg.observe_depth = depth;
2258
+ const activation = decodeActivation(v.activation);
2259
+ if (activation) msg.activation = activation;
2260
+ return msg;
2261
+ }
2262
+ function decodeRegistrationRejected(v) {
2263
+ const msg = {
2264
+ code: String(v.code ?? ""),
2265
+ namespace: String(v.namespace ?? ""),
2266
+ owner_worker_id: String(v.owner_worker_id ?? "")
2267
+ };
2268
+ if (typeof v.worker_name === "string") msg.worker_name = v.worker_name;
2269
+ if (typeof v.function_id === "string") msg.function_id = v.function_id;
2270
+ return msg;
2271
+ }
2272
+ /** Drops `parent` (one level only). */
2273
+ function stripCaller(caller) {
2274
+ if (!caller) return void 0;
2275
+ const { parent: _, ...rest } = caller;
2276
+ return rest;
2277
+ }
2278
+ /** JSON's view of a message: `undefined` fields left out, no caller-owned objects retained. */
2279
+ function snapshot(value) {
2280
+ return JSON.parse(JSON.stringify(value));
2281
+ }
2282
+ /**
2283
+ * `observe { id, source, target, ... }` from the three arguments of
2284
+ * `iii.observe`. Only what the caller set is sent; the engine applies the
2285
+ * defaults. `resolveNamespace` gives the namespace of an unqualified id (this
2286
+ * worker's, `default` for `engine::*`).
2287
+ */
2288
+ function buildObserveMessage(id, source, target, options, resolveNamespace) {
2289
+ const targetRef = typeof target === "string" ? { function_id: target } : target;
2290
+ const sourceNamespace = resolveNamespace(source.namespace, source.function_id, "ObserveSource.namespace");
2291
+ const targetNamespace = resolveNamespace(targetRef.namespace, targetRef.function_id, "Target.namespace");
2292
+ return snapshot({
2293
+ id,
2294
+ source: {
2295
+ function_id: source.function_id,
2296
+ namespace: sourceNamespace,
2297
+ args: source.args,
2298
+ filters: source.filters,
2299
+ capture: source.capture,
2300
+ on: source.on,
2301
+ deliver: source.deliver
2302
+ },
2303
+ target: {
2304
+ function_id: targetRef.function_id,
2305
+ namespace: targetNamespace
2306
+ },
2307
+ metadata: options?.metadata,
2308
+ max_fires: options?.max_fires,
2309
+ expires_in_ms: options?.expires_in_ms,
2310
+ max_in_flight: options?.max_in_flight
2311
+ });
2312
+ }
2313
+ function buildObserverAck(ack) {
2314
+ const msg = {
2315
+ function_id: ack.function_id,
2316
+ id: ack.id,
2317
+ revision: ack.revision
2318
+ };
2319
+ if (ack.namespace !== void 0) msg.namespace = ack.namespace;
2320
+ if (ack.error) msg.error = {
2321
+ code: ack.error.code,
2322
+ message: ack.error.message
2323
+ };
2324
+ return msg;
2325
+ }
2326
+ /**
2327
+ * An outbound `invokefunction`. `observe_depth` is left out when 0, and every
2328
+ * optional field when unset.
2329
+ */
2330
+ function buildInvokeFunction(init) {
2331
+ const msg = {};
2332
+ if (init.invocation_id !== void 0) msg.invocation_id = init.invocation_id;
2333
+ msg.function_id = init.function_id;
2334
+ msg.data = init.data;
2335
+ if (init.traceparent !== void 0) msg.traceparent = init.traceparent;
2336
+ if (init.baggage !== void 0) msg.baggage = init.baggage;
2337
+ if (init.action !== void 0) msg.action = init.action;
2338
+ if (init.metadata !== void 0) msg.metadata = init.metadata;
2339
+ if (init.namespace !== void 0) msg.namespace = init.namespace;
2340
+ if (init.caller !== void 0) msg.caller = init.caller;
2341
+ if (init.observe_depth !== void 0 && init.observe_depth > 0) msg.observe_depth = init.observe_depth;
2342
+ if (init.activation !== void 0) msg.activation = init.activation;
2343
+ return msg;
2344
+ }
2345
+ /**
2346
+ * An outbound `invocationresult`: `result` is left out when the function
2347
+ * returned nothing (`undefined`). A routed call's answer says how the call
2348
+ * is delivered (decision 55): `delivered: true` (its deliver hook delivered
2349
+ * it), or `matched` (the observers its match hook matched, `[]` when none),
2350
+ * or neither; `delivered` outweighs `matched`, and only one is sent.
2351
+ */
2352
+ function buildInvocationResult(init) {
2353
+ const msg = {
2354
+ invocation_id: init.invocation_id,
2355
+ function_id: init.function_id
2356
+ };
2357
+ if (init.result !== void 0) msg.result = init.result;
2358
+ if (init.error !== void 0) msg.error = init.error;
2359
+ if (init.traceparent !== void 0) msg.traceparent = init.traceparent;
2360
+ if (init.baggage !== void 0) msg.baggage = init.baggage;
2361
+ if (init.delivered === true) msg.delivered = true;
2362
+ else if (init.matched !== void 0) msg.matched = [...init.matched];
2363
+ return msg;
2364
+ }
2365
+ /** The caller an outbound call asserts from inside a handler: that handler, and its own caller one level up. */
2366
+ function callerFor(ctx) {
2367
+ const caller = {
2368
+ function_id: ctx.function_id,
2369
+ invocation_id: ctx.invocation_id
2370
+ };
2371
+ const parent = stripCaller(ctx.caller);
2372
+ if (parent && Object.keys(parent).length > 0) caller.parent = parent;
2373
+ return caller;
2374
+ }
2375
+
1739
2376
  //#endregion
1740
2377
  //#region src/observer-handle.ts
1741
2378
  /**
@@ -1764,6 +2401,8 @@ var ObserverHandleImpl = class {
1764
2401
  this.undelivered = [];
1765
2402
  this.delivering = false;
1766
2403
  this.sent = false;
2404
+ this.answered = false;
2405
+ this.refused = false;
1767
2406
  }
1768
2407
  get state() {
1769
2408
  return this.currentState;
@@ -1851,47 +2490,27 @@ const DEFAULT_REPORTER_LIMITS = {
1851
2490
  statsIntervalMs: 1e4
1852
2491
  };
1853
2492
  var ReportItem = class {
1854
- constructor(init, emit, coalesceKey, context) {
2493
+ constructor(init) {
1855
2494
  this.init = init;
1856
- this.emit = emit;
1857
- this.coalesceKey = coalesceKey;
1858
- this.context = context;
1859
2495
  this.parts = /* @__PURE__ */ new Map();
1860
- this.captured = /* @__PURE__ */ new Set();
2496
+ this.outputIsInput = false;
1861
2497
  this.json = "";
1862
2498
  this.bytes = 0;
1863
2499
  }
1864
- /** Adds the parts `captures` asks for that are not in the item yet. */
2500
+ /** Encodes the parts `captures` asks for. */
1865
2501
  capture(captures) {
1866
- for (const c of captures) {
1867
- if (this.captured.has(c)) continue;
1868
- this.captured.add(c);
1869
- if (!PART_ORDER.includes(c)) continue;
1870
- const part = c;
1871
- if (!(part in this.init.values)) continue;
1872
- const encoded = encodeJson(this.init.values[part]);
2502
+ const wanted = new Set(captures);
2503
+ const values = this.init.values;
2504
+ for (const part of PART_ORDER) {
2505
+ if (!wanted.has(part) || !(part in values)) continue;
2506
+ if (part === "output" && this.init.output_is_input && this.parts.has("input")) {
2507
+ this.outputIsInput = true;
2508
+ continue;
2509
+ }
2510
+ const encoded = encodeJson(values[part]);
1873
2511
  if (encoded !== void 0) this.parts.set(part, encoded);
1874
2512
  }
1875
2513
  }
1876
- /** What a merge can change, to undo it. */
1877
- save() {
1878
- return {
1879
- matched: this.init.matched.length,
1880
- captured: [...this.captured],
1881
- parts: [...this.parts],
1882
- json: this.json,
1883
- bytes: this.bytes
1884
- };
1885
- }
1886
- restore(state) {
1887
- this.init.matched.length = state.matched;
1888
- this.captured.clear();
1889
- for (const c of state.captured) this.captured.add(c);
1890
- this.parts.clear();
1891
- for (const [part, encoded] of state.parts) this.parts.set(part, encoded);
1892
- this.json = state.json;
1893
- this.bytes = state.bytes;
1894
- }
1895
2514
  /** Assembles the wire JSON from the pre-encoded parts. */
1896
2515
  render() {
1897
2516
  const i = this.init;
@@ -1902,6 +2521,7 @@ var ReportItem = class {
1902
2521
  for (const part of PART_ORDER) {
1903
2522
  const encoded = this.parts.get(part);
1904
2523
  if (encoded !== void 0) s += `,"${part}":${encoded}`;
2524
+ if (part === "input" && this.outputIsInput) s += ",\"output_is_input\":true";
1905
2525
  }
1906
2526
  s += `,"started_at_ms":${finite(i.started_at_ms)},"duration_ms":${finite(i.duration_ms)}`;
1907
2527
  s += `,"observe_depth":${finite(i.observe_depth)}`;
@@ -1946,7 +2566,6 @@ var Reporter = class {
1946
2566
  this.items = [];
1947
2567
  this.bytes = 0;
1948
2568
  this.perFunction = /* @__PURE__ */ new Map();
1949
- this.openEmits = /* @__PURE__ */ new Map();
1950
2569
  this.stats = /* @__PURE__ */ new Map();
1951
2570
  this.drops = /* @__PURE__ */ new Map();
1952
2571
  this.windowStart = Date.now();
@@ -1973,59 +2592,13 @@ var Reporter = class {
1973
2592
  get size() {
1974
2593
  return this.items.length;
1975
2594
  }
1976
- /** A matched local invocation of an auto function. */
2595
+ /** A local call that observers matched. */
1977
2596
  push(init) {
1978
2597
  const { captures, ...rest } = init;
1979
- const item = new ReportItem(rest, false, void 0, void 0);
1980
- if (!this.build(item, captures)) return false;
1981
- return this.enqueue(item);
1982
- }
1983
- /**
1984
- * An `obs.emit` event. The same event value emitted to several observers
1985
- * from the same invocation context, before the buffer is flushed, becomes
1986
- * one item whose `matched` lists them all.
1987
- */
1988
- pushEmit(init) {
1989
- const { observer_id, event, context, captures, ...rest } = init;
1990
- const merge = this.openEmits.get(event)?.find((it) => it.init.function_id === rest.function_id && it.context === context && !it.init.matched.includes(observer_id));
1991
- if (merge) return this.merge(merge, observer_id, captures);
1992
- const item = new ReportItem({
1993
- ...rest,
1994
- matched: [observer_id]
1995
- }, true, event, context);
2598
+ const item = new ReportItem(rest);
1996
2599
  if (!this.build(item, captures)) return false;
1997
2600
  return this.enqueue(item);
1998
2601
  }
1999
- /** Makes a buffered emit item a merge target. Only items in the buffer are: a flush re-indexes. */
2000
- index(item) {
2001
- if (!item.emit) return;
2002
- const list = this.openEmits.get(item.coalesceKey);
2003
- if (list) list.push(item);
2004
- else this.openEmits.set(item.coalesceKey, [item]);
2005
- }
2006
- /** Adds an observer (and its captures) to a buffered emit item, within the same bounds as a new item. */
2007
- merge(item, observerId, captures) {
2008
- const fn = item.init.function_id;
2009
- const before = item.save();
2010
- try {
2011
- item.init.matched.push(observerId);
2012
- item.capture(captures);
2013
- item.render();
2014
- } catch (error) {
2015
- item.restore(before);
2016
- this.logUnencodable(fn, error);
2017
- return false;
2018
- }
2019
- const growth = item.bytes - before.bytes;
2020
- const reason = this.tooLarge(item) ? "TOO_LARGE" : growth > 0 && this.bytes + this.host.pendingBytes() + growth > this.limits.maxBytes ? "BUFFER_FULL" : void 0;
2021
- if (reason) {
2022
- item.restore(before);
2023
- this.drop(fn, reason);
2024
- return false;
2025
- }
2026
- this.bytes += growth;
2027
- return true;
2028
- }
2029
2602
  build(item, captures) {
2030
2603
  try {
2031
2604
  item.capture(captures);
@@ -2061,7 +2634,6 @@ var Reporter = class {
2061
2634
  this.items.push(item);
2062
2635
  this.bytes += item.bytes;
2063
2636
  this.perFunction.set(fn, (this.perFunction.get(fn) ?? 0) + 1);
2064
- this.index(item);
2065
2637
  if (this.items.length >= this.limits.batchItems) this.flush();
2066
2638
  else this.arm(this.limits.lingerMs);
2067
2639
  return true;
@@ -2163,17 +2735,15 @@ var Reporter = class {
2163
2735
  if (this.host.online()) this.arm(this.limits.lingerMs * 20);
2164
2736
  }
2165
2737
  }
2166
- /** Replaces the buffer, keeping the per-function counts and the emit coalescing index in step. */
2738
+ /** Replaces the buffer, keeping the per-function counts in step. */
2167
2739
  setItems(items) {
2168
2740
  this.items = items;
2169
2741
  this.bytes = 0;
2170
2742
  this.perFunction.clear();
2171
- this.openEmits.clear();
2172
2743
  for (const item of items) {
2173
2744
  this.bytes += item.bytes;
2174
2745
  const fn = item.init.function_id;
2175
2746
  this.perFunction.set(fn, (this.perFunction.get(fn) ?? 0) + 1);
2176
- this.index(item);
2177
2747
  }
2178
2748
  }
2179
2749
  /** Puts items back at the front of the buffer, within its bounds. */
@@ -2250,6 +2820,26 @@ function createPayloadTooLargeError(size, functionId) {
2250
2820
  function isPayloadTooLargeError(error) {
2251
2821
  return error instanceof Error && "code" in error && error.code === "payload_too_large";
2252
2822
  }
2823
+ /**
2824
+ * `registrationrejected` code (engine `protocol.rs`): another live worker
2825
+ * already holds this `(namespace, worker_name)`. The engine closes the
2826
+ * connection -- fatal.
2827
+ */
2828
+ const WORKER_NAMESPACE_CONFLICT = "WORKER_NAMESPACE_CONFLICT";
2829
+ /**
2830
+ * `registrationrejected` code (engine `protocol.rs`): another live worker in
2831
+ * this namespace already exports this one function id. The connection stays
2832
+ * open -- non-fatal.
2833
+ */
2834
+ const FUNCTION_NAMESPACE_CONFLICT = "FUNCTION_NAMESPACE_CONFLICT";
2835
+ /**
2836
+ * `registrationrejected` codes that refuse one function only (decisions 1,
2837
+ * 11): its `args_format` is not a valid JSON Schema, or the engine does not
2838
+ * support what it declares. The connection stays open -- non-fatal.
2839
+ */
2840
+ const FUNCTION_REJECTIONS = new Set(["INVALID_ARGS_FORMAT", "UNSUPPORTED"]);
2841
+ /** Why `call` refuses a call through an observer that names metadata (v2 §4.6, decision 53); the same in every SDK. */
2842
+ const OBSERVER_CALL_METADATA = "a call through an observer takes no metadata; its target receives the observer's metadata";
2253
2843
  /** Short random suffix; `crypto.randomUUID` is unavailable on insecure origins. */
2254
2844
  function randomId() {
2255
2845
  const c = globalThis.crypto;
@@ -2258,20 +2848,6 @@ function randomId() {
2258
2848
  return Math.random().toString(16).slice(2, 10);
2259
2849
  }
2260
2850
  /**
2261
- * The worker's namespace, refusing one that was named and left blank.
2262
- *
2263
- * Absent and blank mean opposite things. Absent asks for the engine's
2264
- * `default`; blank names a namespace and gives nothing to name it with. Read as
2265
- * absent, the worker registers in `default`, and since a worker's calls and
2266
- * triggers follow its namespace, the whole project quietly serves from a place
2267
- * its declaration never named -- the one thing an operator cannot see by
2268
- * reading the declaration.
2269
- *
2270
- * The browser has no `III_NAMESPACE` to fall back to, so unlike the other SDKs
2271
- * there is only the option here, and an option that was written and left empty
2272
- * is never what someone meant.
2273
- */
2274
- /**
2275
2851
  * The namespace one call or one binding resolves in.
2276
2852
  *
2277
2853
  * `undefined` inherits the worker's. A blank one is refused: named and left
@@ -2284,17 +2860,20 @@ function callNamespace(explicit, worker, source) {
2284
2860
  return explicit ?? worker;
2285
2861
  }
2286
2862
  /** Resolve one function invocation without leaking engine and configuration builtins into a worker namespace. */
2287
- function invocationNamespace(explicit, worker, functionId, source = "TriggerRequest.namespace") {
2863
+ function invocationNamespace(explicit, worker, functionId, source = "CallRequest.namespace") {
2288
2864
  const namespace = callNamespace(explicit, worker, source);
2289
2865
  return explicit === void 0 && (functionId.startsWith("engine::") || functionId.startsWith("configuration::")) ? "default" : namespace;
2290
2866
  }
2291
- const MIGRATION_GUIDE = "https://iii.dev/docs/upgrading/from-0-24-x";
2292
- /** CONTRACT §5: one warning per page per deprecated API. */
2293
- const DEPRECATIONS = {
2294
- registerTrigger: `registerTrigger is deprecated and will be removed in a future release. Use iii.observe(source, target) instead. Migration guide: ${MIGRATION_GUIDE}`,
2295
- registerTriggerType: `registerTriggerType is deprecated and will be removed in a future release. Register a function with an observe descriptor (registerFunction(id, handler, { observe: { ... } })) instead. Migration guide: ${MIGRATION_GUIDE}`
2296
- };
2297
- const deprecationsWarned = /* @__PURE__ */ new Set();
2867
+ /** Whether an observer of the snapshot captures the input or filters on it; computed once per snapshot. */
2868
+ const inputReaders = /* @__PURE__ */ new WeakMap();
2869
+ function readsInput(snapshot) {
2870
+ let reads = inputReaders.get(snapshot);
2871
+ if (reads === void 0) {
2872
+ reads = snapshot.some((obs) => obs.capture.includes("input") || obs.filter.roots.has("input"));
2873
+ inputReaders.set(snapshot, reads);
2874
+ }
2875
+ return reads;
2876
+ }
2298
2877
  /**
2299
2878
  * Local dispatch hands the handler a copy of the caller's payload and the
2300
2879
  * caller a copy of the result (value semantics, as over the wire):
@@ -2313,222 +2892,115 @@ const UNSUPPORTED_REASON = {
2313
2892
  code: "UNSUPPORTED",
2314
2893
  message: "the engine does not support observe (no observe.v1 in its features); upgrade it to 0.25 or later"
2315
2894
  };
2316
- /** `args_format` needs `delivery: 'owner'`: an auto function's events are its invocations, offered to every observer. */
2317
- function validateObserveHooks(functionId, hooks) {
2318
- if (!hooks) return;
2319
- const delivery = hooks.delivery;
2320
- if (delivery !== void 0 && delivery !== "auto" && delivery !== "owner") throw new InvocationError({
2321
- code: "INVALID_OBSERVE_DESCRIPTOR",
2322
- message: `observe.delivery must be 'auto' or 'owner', got ${JSON.stringify(delivery)}`,
2323
- function_id: functionId
2324
- });
2325
- if (hooks.args_format !== void 0 && delivery !== "owner") throw new InvocationError({
2326
- code: "INVALID_OBSERVE_DESCRIPTOR",
2327
- message: "observe.args_format requires delivery: 'owner' (an auto function takes no args)",
2328
- function_id: functionId
2329
- });
2330
- }
2331
- /**
2332
- * The error a call that timed out rejects with, on the remote and the local
2333
- * path: an `Error` (its message unchanged from earlier releases) that also
2334
- * carries `code: 'TIMEOUT'` and the `function_id`, like the Node SDK's.
2335
- */
2336
- function timeoutError(ms, functionId) {
2337
- return Object.assign(/* @__PURE__ */ new Error(`Invocation timeout after ${ms}ms: ${functionId}`), {
2338
- code: "TIMEOUT",
2339
- function_id: functionId
2340
- });
2341
- }
2342
- /** What a handler failure reports when the thrown value cannot even be read (a getter or `toString` that throws). */
2343
- const UNREADABLE_FAILURE = "the handler failed with a value that cannot be read";
2344
- function safeString(value) {
2345
- try {
2346
- return String(value);
2347
- } catch {
2348
- return UNREADABLE_FAILURE;
2349
- }
2350
- }
2351
- /**
2352
- * An error body as the engine sends it, and as this SDK's own calls reject
2353
- * with: a plain (JSON-parsed) object with a string `code`, a string `message`
2354
- * and, optionally, a string `stacktrace`. A class instance or anything else
2355
- * with such fields is not one: it is reported through `String()`.
2356
- */
2357
- function isEngineErrorBody(value) {
2358
- if (value === null || typeof value !== "object") return false;
2359
- const proto = Object.getPrototypeOf(value);
2360
- if (proto !== Object.prototype && proto !== null) return false;
2361
- const body = value;
2362
- return typeof body.code === "string" && typeof body.message === "string" && (body.stacktrace === void 0 || typeof body.stacktrace === "string");
2363
- }
2364
- /**
2365
- * The error a handler's failure becomes, the same on the local and the remote
2366
- * path (code `invocation_failed`):
2367
- * - an `Error`, from any realm (an iframe's too): its message and stack;
2368
- * - an engine error body (a failed call's rejection, rethrown): its message and stacktrace;
2369
- * - anything else: `String(value)`.
2370
- * Never throws: when reading the value throws, a fixed message is reported, so
2371
- * the caller always gets its answer.
2372
- */
2373
- function handlerErrorBody(error) {
2374
- try {
2375
- if (error instanceof Error || Object.prototype.toString.call(error) === "[object Error]") {
2376
- const { message, stack } = error;
2377
- return {
2378
- code: "invocation_failed",
2379
- message: typeof message === "string" ? message : safeString(message),
2380
- stacktrace: typeof stack === "string" ? stack : void 0
2381
- };
2382
- }
2383
- if (isEngineErrorBody(error)) return {
2384
- code: "invocation_failed",
2385
- message: error.message,
2386
- stacktrace: error.stacktrace
2387
- };
2388
- return {
2389
- code: "invocation_failed",
2390
- message: String(error),
2391
- stacktrace: void 0
2392
- };
2393
- } catch {
2394
- return {
2395
- code: "invocation_failed",
2396
- message: safeString(error),
2397
- stacktrace: void 0
2398
- };
2399
- }
2400
- }
2401
2895
  function resolveNamespace(optionNamespace) {
2402
2896
  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\`.`);
2403
2897
  return optionNamespace;
2404
2898
  }
2899
+ /** The upgrade guide the removed 0.25 trigger APIs point to. */
2900
+ const UPGRADE_GUIDE = "https://iii.dev/docs/upgrading/from-0-25-x";
2405
2901
  var Sdk = class {
2406
2902
  constructor(address, options) {
2407
2903
  this.address = address;
2408
- this.options = options;
2409
2904
  this.functions = /* @__PURE__ */ new Map();
2410
2905
  this.invocations = /* @__PURE__ */ new Map();
2411
- this.triggers = /* @__PURE__ */ new Map();
2412
- this.triggerTypes = /* @__PURE__ */ new Map();
2413
2906
  this.messagesToSend = [];
2414
2907
  this.reconnectAttempt = 0;
2415
2908
  this.connectionState = "disconnected";
2416
2909
  this.connectionListeners = /* @__PURE__ */ new Set();
2417
2910
  this.isShuttingDown = false;
2418
- this.observers = /* @__PURE__ */ new Map();
2911
+ this.observerHandles = /* @__PURE__ */ new Map();
2912
+ this.observesSent = /* @__PURE__ */ new Map();
2419
2913
  this.engineFeatures = /* @__PURE__ */ new Set();
2420
2914
  this.registeredOnConnection = false;
2421
2915
  this.connectionEpoch = 0;
2916
+ this.workerHooks = {};
2917
+ this.functionHooks = /* @__PURE__ */ new Map();
2422
2918
  this.hooksInactiveWarned = /* @__PURE__ */ new Set();
2919
+ this.unsupportedWarned = /* @__PURE__ */ new Set();
2920
+ this.unregisteredHooksWarned = /* @__PURE__ */ new Set();
2423
2921
  this.observeQueue = [];
2424
- this.registerTriggerType = (triggerType, handler) => {
2425
- this.warnDeprecated("registerTriggerType");
2426
- const message = this.snapshotRegistration({
2427
- ...triggerType,
2428
- message_type: "registertriggertype"
2429
- });
2430
- this.sendMessage("registertriggertype", message, true);
2431
- this.triggerTypes.set(message.id, {
2432
- message,
2433
- handler
2434
- });
2435
- return {
2436
- id: message.id,
2437
- registerTrigger: (functionId, config) => {
2438
- return this.registerTrigger({
2439
- type: message.id,
2440
- function_id: functionId,
2441
- config,
2442
- namespace: this.namespace
2443
- });
2444
- },
2445
- registerFunction: (functionId, handler, config) => {
2446
- const ref = this.registerFunction(functionId, handler);
2447
- this.registerTrigger({
2448
- type: message.id,
2449
- function_id: functionId,
2450
- config,
2451
- namespace: this.namespace
2452
- });
2453
- return ref;
2454
- },
2455
- unregister: () => {
2456
- this.unregisterTriggerType(message);
2457
- }
2458
- };
2459
- };
2460
- this.unregisterTriggerType = (triggerType) => {
2461
- const { id, namespace } = triggerType;
2462
- this.sendMessage("unregistertriggertype", namespace !== void 0 ? {
2463
- id,
2464
- namespace
2465
- } : { id }, true);
2466
- this.triggerTypes.delete(id);
2467
- };
2468
- this.registerTrigger = (trigger) => {
2469
- this.warnDeprecated("registerTrigger");
2470
- const id = randomUUID();
2471
- const fullTrigger = this.snapshotRegistration({
2472
- ...trigger,
2473
- id,
2474
- message_type: "registertrigger",
2475
- ...(() => {
2476
- const namespace = callNamespace(trigger.namespace, this.namespace, "RegisterTriggerInput.namespace");
2477
- return namespace !== void 0 ? { namespace } : {};
2478
- })()
2479
- });
2480
- this.sendMessage("registertrigger", fullTrigger, true);
2481
- this.triggers.set(id, fullTrigger);
2482
- return { unregister: () => {
2483
- this.sendMessage("unregistertrigger", {
2484
- id,
2485
- message_type: "unregistertrigger",
2486
- type: fullTrigger.type
2487
- });
2488
- this.triggers.delete(id);
2489
- } };
2490
- };
2491
- this.registerFunction = (functionId, handlerOrInvocation, options) => {
2922
+ this.registerFunction = (functionId, handler, options) => {
2492
2923
  if (!functionId || functionId.trim() === "") throw new Error("id is required");
2493
2924
  if (this.functions.has(functionId)) throw new Error(`function id already registered: ${functionId}`);
2494
- const { observe: hooks, localDispatch, ...wireOptions } = options ?? {};
2495
- validateObserveHooks(functionId, hooks);
2496
- const descriptor = observeDescriptor(hooks);
2925
+ const { localDispatch, private: isPrivate, observable, ...wireOptions } = options ?? {};
2497
2926
  const fullMessage = this.snapshotRegistration({
2498
2927
  ...wireOptions,
2499
- ...descriptor ? { observe: descriptor } : {},
2928
+ ...isPrivate === true ? { private: true } : {},
2929
+ ...observable === false ? { observable: false } : {},
2500
2930
  id: functionId,
2501
2931
  message_type: "registerfunction"
2502
2932
  });
2503
- this.sendMessage("registerfunction", fullMessage, true);
2504
- const observe = new FunctionObservers(functionId, hooks, localDispatch !== false, true, this.observeHost);
2505
- if (observe.needsObserve && this.registeredOnConnection && !this.engineFeatures.has("observe.v1")) this.warnHooksInactive(functionId);
2506
- const handler = handlerOrInvocation;
2507
- this.functions.set(functionId, {
2933
+ const frame = this.prepareJson(this.toWireFormat("registerfunction", fullMessage));
2934
+ const observe = new FunctionObservers(functionId, localDispatch !== false, true, this.observeHost);
2935
+ const fn = {
2508
2936
  message: fullMessage,
2509
2937
  observe,
2510
2938
  handler: async (input, metadata) => {
2511
2939
  return await handler(input, metadata);
2512
2940
  }
2513
- });
2514
- return {
2941
+ };
2942
+ this.functions.set(functionId, fn);
2943
+ if (this.mayRegister(functionId, fn)) {
2944
+ this.sendMessageRaw(frame);
2945
+ fn.sentEpoch = this.connectionEpoch;
2946
+ }
2947
+ if (this.registeredOnConnection && !this.engineFeatures.has("observe.v1") && this.hasObserverHooks(functionId)) this.warnHooksInactive(functionId);
2948
+ const ref = {
2515
2949
  id: functionId,
2950
+ onObserverAdded: (hook) => {
2951
+ this.onObserverAdded(functionId, hook);
2952
+ return ref;
2953
+ },
2954
+ onObserverRemoved: (hook) => {
2955
+ this.onObserverRemoved(functionId, hook);
2956
+ return ref;
2957
+ },
2958
+ onObservationMatch: (hook) => {
2959
+ this.onObservationMatch(functionId, hook);
2960
+ return ref;
2961
+ },
2962
+ onObservationDeliver: (hook) => {
2963
+ this.onObservationDeliver(functionId, hook);
2964
+ return ref;
2965
+ },
2966
+ observers: () => observe.observers(),
2967
+ isObserved: (call) => observe.isObserved(call),
2516
2968
  unregister: () => {
2517
- if (this.functions.get(functionId)?.observe !== observe) return;
2969
+ if (this.functions.get(functionId) !== fn) return;
2518
2970
  this.sendMessage("unregisterfunction", { id: functionId }, true);
2519
2971
  this.functions.delete(functionId);
2520
2972
  observe.dispose();
2521
- },
2522
- isObserved: () => observe.isObserved(),
2523
- observers: () => observe.observers()
2973
+ }
2524
2974
  };
2975
+ return ref;
2976
+ };
2977
+ this.onObserverAdded = (a, b) => {
2978
+ if (typeof a === "string") this.setFunctionHook(a, "added", b);
2979
+ else this.setWorkerHook("added", a);
2980
+ return this;
2981
+ };
2982
+ this.onObserverRemoved = (a, b) => {
2983
+ if (typeof a === "string") this.setFunctionHook(a, "removed", b);
2984
+ else this.setWorkerHook("removed", a);
2985
+ return this;
2986
+ };
2987
+ this.onObservationMatch = (functionId, hook) => {
2988
+ this.setFunctionHook(functionId, "match", hook);
2989
+ return this;
2525
2990
  };
2526
- this.observe = (source, target, options) => {
2991
+ this.onObservationDeliver = (functionId, hook) => {
2992
+ this.setFunctionHook(functionId, "deliver", hook);
2993
+ return this;
2994
+ };
2995
+ this.observers = (functionId) => this.functions.get(functionId)?.observe.observers() ?? [];
2996
+ this.isObserved = (functionId, call) => this.functions.get(functionId)?.observe.isObserved(call) ?? false;
2997
+ this.observe = (sourceOrId, target, options) => {
2998
+ const source = typeof sourceOrId === "string" ? { function_id: sourceOrId } : sourceOrId;
2527
2999
  if (!source || typeof source.function_id !== "string" || source.function_id.trim() === "") throw new Error("observe: source.function_id is required");
2528
3000
  const targetId = typeof target === "string" ? target : target?.function_id;
2529
3001
  if (typeof targetId !== "string" || targetId.trim() === "") throw new Error("observe: target is required (the id of a registered function)");
2530
3002
  const id = options?.id ?? randomUUID();
2531
- if (this.observers.has(id)) throw new Error(`observe: observer id already in use: ${id}`);
3003
+ if (this.observerHandles.has(id)) throw new ObserveRejection("OBSERVER_ID_CONFLICT", `observe: observer id already in use: ${id}`);
2532
3004
  const onDispose = (h) => this.disposeObserver(h);
2533
3005
  const logError = (msg, error) => this.logError(msg, error);
2534
3006
  const refused = (reason) => {
@@ -2560,7 +3032,7 @@ var Sdk = class {
2560
3032
  });
2561
3033
  }
2562
3034
  const handle = new ObserverHandleImpl(id, message, onDispose, logError);
2563
- this.observers.set(id, handle);
3035
+ this.observerHandles.set(id, handle);
2564
3036
  if (this.registeredOnConnection && this.isOpen()) if (this.engineFeatures.has("observe.v1")) this.sendObserve(handle);
2565
3037
  else handle.setState("error", UNSUPPORTED_REASON);
2566
3038
  return handle;
@@ -2568,7 +3040,7 @@ var Sdk = class {
2568
3040
  this.currentInvocation = () => publicContext(currentContext());
2569
3041
  this.withInvocation = (invocation, fn) => enterInvocation(contextFromView(invocation), fn, MAX_RUNNING_INVOCATION_MS);
2570
3042
  this.__helpers_create_channel = async (bufferSize) => {
2571
- const result = await this.trigger({
3043
+ const result = await this.call({
2572
3044
  function_id: "engine::channels::create",
2573
3045
  payload: { buffer_size: bufferSize }
2574
3046
  });
@@ -2579,17 +3051,31 @@ var Sdk = class {
2579
3051
  readerRef: result.reader
2580
3052
  };
2581
3053
  };
2582
- this.trigger = async (request) => {
2583
- const { function_id, action } = request;
2584
- const namespace = invocationNamespace(request.namespace, this.namespace, function_id);
2585
- if (request.dispatch !== "remote" && action?.type !== "enqueue") {
3054
+ this.call = async (request) => {
3055
+ if (request.observer !== void 0) {
3056
+ const { observer, payload, action, timeoutMs } = request;
3057
+ if (request.metadata != null) throw new Error(OBSERVER_CALL_METADATA);
3058
+ return this.invokeRemote({
3059
+ function_id: observer.target,
3060
+ payload,
3061
+ action,
3062
+ timeoutMs
3063
+ }, void 0, { observer_id: observer.id });
3064
+ }
3065
+ const req = request.metadata === null ? {
3066
+ ...request,
3067
+ metadata: void 0
3068
+ } : request;
3069
+ const { function_id, action } = req;
3070
+ const namespace = invocationNamespace(req.namespace, this.namespace, function_id);
3071
+ if (req.dispatch !== "remote" && action?.type !== "enqueue") {
2586
3072
  const fn = this.functions.get(function_id);
2587
3073
  const observe = fn?.observe;
2588
3074
  if (fn?.handler && observe?.localDispatch && (namespace === void 0 || namespace === observe.namespace)) {
2589
3075
  const depth = callLocalDepth();
2590
- if (depth < 64) return this.invokeLocal(function_id, fn.handler, observe, request);
3076
+ if (depth < 64) return this.invokeLocal(function_id, fn, req);
2591
3077
  if (!this.isOpen()) {
2592
- if (depth < 256) return this.invokeLocal(function_id, fn.handler, observe, request);
3078
+ if (depth < 256) return this.invokeLocal(function_id, fn, req);
2593
3079
  throw new InvocationError({
2594
3080
  code: "LOCAL_DEPTH_EXCEEDED",
2595
3081
  message: `${function_id} is called ${depth} local calls deep: past ${64} the call needs the engine, and the socket is closed`,
@@ -2598,7 +3084,17 @@ var Sdk = class {
2598
3084
  }
2599
3085
  }
2600
3086
  }
2601
- return this.invokeRemote(request, namespace);
3087
+ return this.invokeRemote(req, namespace);
3088
+ };
3089
+ this.trigger = this.call;
3090
+ this.registerTrigger = () => {
3091
+ throw new Error(`registerTrigger was removed in iii 0.26.0: bind functions with iii.observe(source, target). registerTrigger({ type: 'cron', function_id, config }) becomes iii.observe({ function_id: 'cron::on-tick', args: config }, function_id). Every trigger type's function is in the migration guide: ${UPGRADE_GUIDE}`);
3092
+ };
3093
+ this.registerTriggerType = () => {
3094
+ throw new Error(`registerTriggerType was removed in iii 0.26.0: a trigger type is now a function that consumers observe. Register it with registerFunction('<worker>::on-<event>', (event) => event, { args_format, private: true }), move the TriggerHandler to onObserverAdded and onObserverRemoved, and call the function once per event. Migration guide: ${UPGRADE_GUIDE}#move-a-trigger-type-to-an-observable-function`);
3095
+ };
3096
+ this.unregisterTriggerType = () => {
3097
+ throw new Error(`unregisterTriggerType was removed in iii 0.26.0: a trigger type is now a function. Unregister it with the FunctionRef that registerFunction returns: functionRef.unregister(). Migration guide: ${UPGRADE_GUIDE}#move-a-trigger-type-to-an-observable-function`);
2602
3098
  };
2603
3099
  this.__helpers_create_stream = (streamName, stream) => {
2604
3100
  this.registerFunction(`stream::get(${streamName})`, stream.get.bind(stream));
@@ -2669,39 +3165,146 @@ var Sdk = class {
2669
3165
  logError: (message, error) => this.logError(message, error)
2670
3166
  }, options?.observe?.reporter);
2671
3167
  this.observeHost = {
2672
- identity: () => this.workerId !== void 0 ? {
2673
- worker_id: this.workerId,
2674
- worker_name: this.workerName
2675
- } : { worker_name: this.workerName },
2676
3168
  sendAck: (ack) => this.sendMessage("observerack", buildObserverAck(ack), true),
2677
3169
  reporter: this.reporter,
2678
- callTarget: (target, observerId, payload, timeoutMs) => this.invokeRemote({
2679
- function_id: target,
2680
- payload,
2681
- timeoutMs
2682
- }, void 0, { observer_id: observerId }),
3170
+ hooks: (functionId) => this.hooksOf(functionId),
2683
3171
  logError: (message, error) => this.logError(message, error),
3172
+ logWarn: (message) => this.logWarn(message),
2684
3173
  hookTimeoutMs: () => options?.observe?.hookTimeoutMs ?? 3e4,
2685
- traceContext: () => ({})
3174
+ observeV2: () => this.engineFeatures.has(FEATURE_OBSERVE_V2)
2686
3175
  };
2687
3176
  this.reporter.start();
2688
3177
  this.connect();
2689
3178
  }
2690
- warnDeprecated(api) {
2691
- if (deprecationsWarned.has(api)) return;
2692
- deprecationsWarned.add(api);
2693
- console.warn(`[iii] ${DEPRECATIONS[api]}`);
2694
- }
2695
3179
  logError(message, error) {
2696
3180
  if (error === void 0) console.error(`[iii] ${message}`);
2697
3181
  else console.error(`[iii] ${message}`, error);
2698
3182
  }
3183
+ logWarn(message) {
3184
+ console.warn(`[iii] ${message}`);
3185
+ }
3186
+ logInfo(message) {
3187
+ console.info(`[iii] ${message}`);
3188
+ }
3189
+ /**
3190
+ * What a function needs `observe.v2` for (decision 18): `args_format`,
3191
+ * `private`, `observable: false`, a match hook or a deliver hook.
3192
+ */
3193
+ needsObserveV2(functionId, fn) {
3194
+ const { message } = fn;
3195
+ const hooks = this.functionHooks.get(functionId);
3196
+ return message.args_format !== void 0 || message.private === true || message.observable === false || hooks?.match !== void 0 || hooks?.deliver !== void 0;
3197
+ }
3198
+ /**
3199
+ * Whether the function's `registerfunction` may go out on the current
3200
+ * connection now. One that needs `observe.v2` waits for this connection's
3201
+ * `WorkerRegistered`, and stays unregistered (`holdUnsupported`) when the
3202
+ * engine does not advertise it (decision 41).
3203
+ */
3204
+ mayRegister(functionId, fn) {
3205
+ if (!this.isOpen()) return false;
3206
+ if (!this.needsObserveV2(functionId, fn)) return true;
3207
+ if (!this.registeredOnConnection) return false;
3208
+ if (this.engineFeatures.has("observe.v2")) return true;
3209
+ this.holdUnsupported(functionId, fn);
3210
+ return false;
3211
+ }
3212
+ /**
3213
+ * A function that needs `observe.v2` on a connection whose engine does not
3214
+ * advertise it: the engine does not hold it here, so what it kept from an
3215
+ * earlier connection is released once per connection (local dispatch, its
3216
+ * observers through `onObserverRemoved`, held reports), and `UNSUPPORTED`
3217
+ * is logged once per function.
3218
+ */
3219
+ holdUnsupported(functionId, fn) {
3220
+ if (fn.observe.releasedEpoch !== this.connectionEpoch) fn.observe.onRegistrationRejected(this.connectionEpoch);
3221
+ this.warnUnsupported(functionId);
3222
+ }
3223
+ /** Sends the registrations that may go out now and have not on this connection. */
3224
+ sendRegistrations() {
3225
+ for (const [functionId, fn] of this.functions) {
3226
+ if (fn.sentEpoch === this.connectionEpoch || !this.mayRegister(functionId, fn)) continue;
3227
+ this.replayRegistration("registerfunction", fn.message);
3228
+ fn.sentEpoch = this.connectionEpoch;
3229
+ }
3230
+ }
3231
+ /**
3232
+ * Decides the registration again once a match or deliver hook may have
3233
+ * changed whether the function needs `observe.v2` (set or removed, or set
3234
+ * before `WorkerRegistered`): against an engine without it, a registered
3235
+ * function is unregistered (and one held back is registered once it no
3236
+ * longer needs it).
3237
+ */
3238
+ reconcileRegistration(functionId) {
3239
+ const fn = this.functions.get(functionId);
3240
+ if (!fn || !this.isOpen() || !this.registeredOnConnection) return;
3241
+ const sent = fn.sentEpoch === this.connectionEpoch;
3242
+ const allowed = this.engineFeatures.has("observe.v2") || !this.needsObserveV2(functionId, fn);
3243
+ if (sent && !allowed) {
3244
+ this.sendMessage("unregisterfunction", { id: functionId }, true);
3245
+ fn.sentEpoch = void 0;
3246
+ this.holdUnsupported(functionId, fn);
3247
+ } else if (!sent && allowed) {
3248
+ this.replayRegistration("registerfunction", fn.message);
3249
+ fn.sentEpoch = this.connectionEpoch;
3250
+ }
3251
+ }
3252
+ warnUnsupported(functionId) {
3253
+ if (this.unsupportedWarned.has(functionId)) return;
3254
+ this.unsupportedWarned.add(functionId);
3255
+ this.logWarn(`UNSUPPORTED: function "${functionId}" needs observe.v2 (args_format, private, observable: false, onObservationMatch or onObservationDeliver), which this engine does not advertise; it stays unregistered until the worker connects to an engine with observe.v2.`);
3256
+ }
3257
+ /** The hooks that apply to one function now: the worker's, and those set for its id. */
3258
+ hooksOf(functionId) {
3259
+ const own = this.functionHooks.get(functionId);
3260
+ return {
3261
+ workerAdded: this.workerHooks.added,
3262
+ workerRemoved: this.workerHooks.removed,
3263
+ added: own?.added,
3264
+ removed: own?.removed,
3265
+ match: own?.match,
3266
+ deliver: own?.deliver
3267
+ };
3268
+ }
3269
+ hasObserverHooks(functionId) {
3270
+ const own = this.functionHooks.get(functionId);
3271
+ return !!(this.workerHooks.added || this.workerHooks.removed || own?.added || own?.removed || own?.match || own?.deliver);
3272
+ }
3273
+ setFunctionHook(functionId, kind, hook) {
3274
+ if (typeof functionId !== "string" || functionId.trim() === "") throw new TypeError("the function id of an observer hook is required");
3275
+ const keys = kind === "match" && hook !== null && typeof hook === "object" && typeof hook.observer === "function" && typeof hook.call === "function";
3276
+ if (hook !== null && typeof hook !== "function" && !keys) throw new TypeError(kind === "match" ? `the match hook of ${functionId} must be a predicate, { observer, call } key functions, or null to remove it` : `the ${kind} hook of ${functionId} must be a function, or null to remove it`);
3277
+ const hooks = {
3278
+ ...this.functionHooks.get(functionId),
3279
+ [kind]: hook ?? void 0
3280
+ };
3281
+ if (hooks.added || hooks.removed || hooks.match || hooks.deliver) this.functionHooks.set(functionId, hooks);
3282
+ else this.functionHooks.delete(functionId);
3283
+ const fn = this.functions.get(functionId);
3284
+ if (!fn) return;
3285
+ if (kind === "added" && hook) fn.observe.catchUp("fn");
3286
+ if (kind === "match") fn.observe.matchChanged();
3287
+ if (kind === "match" || kind === "deliver") this.reconcileRegistration(functionId);
3288
+ }
3289
+ setWorkerHook(kind, hook) {
3290
+ if (hook !== null && typeof hook !== "function") throw new TypeError(`the worker's ${kind} hook must be a function, or null to remove it`);
3291
+ this.workerHooks = {
3292
+ ...this.workerHooks,
3293
+ [kind]: hook ?? void 0
3294
+ };
3295
+ if (kind === "added" && hook) for (const fn of this.functions.values()) fn.observe.catchUp("worker");
3296
+ }
2699
3297
  sendObserve(handle) {
2700
3298
  this.sendMessage("observe", handle.message, true);
2701
3299
  handle.sent = true;
3300
+ handle.answered = false;
3301
+ const sent = this.observesSent.get(handle.id);
3302
+ if (sent) sent.push(handle);
3303
+ else this.observesSent.set(handle.id, [handle]);
2702
3304
  }
2703
3305
  disposeObserver(handle) {
2704
- if (this.observers.get(handle.id) === handle) this.observers.delete(handle.id);
3306
+ if (this.observerHandles.get(handle.id) === handle) this.observerHandles.delete(handle.id);
3307
+ if (handle.answered) this.unlistObserve(handle);
2705
3308
  if (!handle.sent) return;
2706
3309
  this.sendObserveFamily("unobserve", { id: handle.id });
2707
3310
  }
@@ -2721,7 +3324,15 @@ var Sdk = class {
2721
3324
  warnHooksInactive(functionId) {
2722
3325
  if (this.hooksInactiveWarned.has(functionId)) return;
2723
3326
  this.hooksInactiveWarned.add(functionId);
2724
- console.warn(`[iii] Function "${functionId}" declares observe hooks or owner delivery, but the engine does not support observe (observe.v1): it is registered as a plain function and its observe hooks are inactive.`);
3327
+ this.logWarn(`Function "${functionId}" has observer hooks, but the engine does not support observe (observe.v1): it is registered as a plain function and its observer hooks are inactive.`);
3328
+ }
3329
+ /** Once the connection is registered: a hook set for an id this worker has not registered (a mistyped id?). */
3330
+ warnUnregisteredHookIds() {
3331
+ for (const functionId of this.functionHooks.keys()) {
3332
+ if (this.functions.has(functionId) || this.unregisteredHooksWarned.has(functionId)) continue;
3333
+ this.unregisteredHooksWarned.add(functionId);
3334
+ this.logWarn(`Observer hooks are set for "${functionId}", which this worker has not registered; check the function id.`);
3335
+ }
2725
3336
  }
2726
3337
  /** Connected to an engine that advertised `observe.v1`. */
2727
3338
  observeOnline() {
@@ -2749,6 +3360,7 @@ var Sdk = class {
2749
3360
  }
2750
3361
  /** The routed path: an `InvokeFunction` through the engine. */
2751
3362
  invokeRemote(request, namespace, activation) {
3363
+ if (this.fatalError) return Promise.reject(this.fatalError);
2752
3364
  const { function_id, payload, action, timeoutMs, metadata } = request;
2753
3365
  const effectiveTimeout = timeoutMs ?? this.invocationTimeoutMs;
2754
3366
  const outgoing = this.outgoingFields(request);
@@ -2769,7 +3381,7 @@ var Sdk = class {
2769
3381
  const timeout = setTimeout(() => {
2770
3382
  if (this.invocations.get(invocation_id)) {
2771
3383
  this.invocations.delete(invocation_id);
2772
- reject(timeoutError(effectiveTimeout, function_id));
3384
+ reject(new InvocationTimeoutError(effectiveTimeout, function_id));
2773
3385
  }
2774
3386
  }, effectiveTimeout);
2775
3387
  this.invocations.set(invocation_id, {
@@ -2796,13 +3408,30 @@ var Sdk = class {
2796
3408
  });
2797
3409
  }
2798
3410
  /**
2799
- * The local path (sdk.md §4.3): runs the handler in-process, with a copy of
2800
- * the payload, inside a new invocation context; the same timeout and the
2801
- * same rejection value as the remote path; reports the call when an
2802
- * observer matches. Puts nothing on the wire when nobody observes the
2803
- * function.
3411
+ * Runs a call's delivery inside `ctx`: the function's deliver hook, or
3412
+ * iii's delivery to its observers. The hook sees the invocation up to its
3413
+ * first `await`, and counts as delivering until it settles, so the calls it
3414
+ * makes after an `await` fall back to the invocation while it is the only
3415
+ * one running (`callContext`).
3416
+ */
3417
+ deliverIn(ctx, delivery, hook) {
3418
+ if (hook === void 0) return delivery.run(void 0);
3419
+ const untrack = trackDelivering(ctx);
3420
+ return runInContext(ctx, () => delivery.run(hook)).finally(untrack);
3421
+ }
3422
+ /**
3423
+ * The local path (sdk.md §4.3): runs the handler in-process inside a new
3424
+ * invocation context, then delivers the call (the function's deliver hook,
3425
+ * or iii's delivery to its observers); the same timeout and the same
3426
+ * rejection value as the remote path. A call of a function nobody observes
3427
+ * and without a deliver hook puts nothing on the wire.
3428
+ *
3429
+ * The handler gets a copy of the payload and the caller a copy of the
3430
+ * result; a private function's input and result pass by reference.
2804
3431
  */
2805
- invokeLocal(function_id, handler, observe, request) {
3432
+ invokeLocal(function_id, fn, request) {
3433
+ const { observe } = fn;
3434
+ const handler = fn.handler;
2806
3435
  const parent = callContext();
2807
3436
  const caller = this.workerId !== void 0 ? {
2808
3437
  worker_id: this.workerId,
@@ -2819,51 +3448,63 @@ var Sdk = class {
2819
3448
  invocation_id: randomUUID(),
2820
3449
  caller,
2821
3450
  observe_depth: parent ? parent.observe_depth : callDepth(),
2822
- metadata: request.metadata,
2823
3451
  localDepth: callLocalDepth() + 1
2824
3452
  };
2825
3453
  const traceparent = request.traceparent ?? parent?.traceparent;
2826
3454
  const baggage = request.baggage ?? parent?.baggage;
2827
3455
  if (traceparent !== void 0) ctx.traceparent = traceparent;
2828
3456
  if (baggage !== void 0) ctx.baggage = baggage;
2829
- const set = observe.delivery === "auto" ? observe.compiled : [];
3457
+ const snapshot = observe.compiled;
3458
+ const activations = observe.activations;
3459
+ const hook = this.functionHooks.get(function_id)?.deliver;
3460
+ const delivering = hook !== void 0 || snapshot.length > 0;
3461
+ const copiesInput = delivering && (hook !== void 0 || this.functionHooks.get(function_id)?.match !== void 0 || readsInput(snapshot));
3462
+ const byReference = fn.message.private === true;
2830
3463
  let input;
2831
- let observedInput;
2832
- let observedMetadata;
2833
3464
  let metadata;
3465
+ let callInput;
3466
+ let callMetadata;
2834
3467
  try {
2835
- if (set.length > 0) {
2836
- observedInput = cloneValue(request.payload);
2837
- observedMetadata = request.metadata === void 0 ? void 0 : cloneValue(request.metadata);
3468
+ if (byReference) {
3469
+ callInput = request.payload;
3470
+ callMetadata = request.metadata;
3471
+ input = this.resolveChannelValue(request.payload);
3472
+ metadata = request.metadata;
3473
+ } else {
3474
+ if (copiesInput) {
3475
+ callInput = cloneValue(request.payload);
3476
+ callMetadata = request.metadata === void 0 ? void 0 : cloneValue(request.metadata);
3477
+ }
3478
+ input = this.resolveChannelValue(cloneValue(request.payload));
3479
+ metadata = request.metadata === void 0 ? void 0 : cloneValue(request.metadata);
2838
3480
  }
2839
- input = this.resolveChannelValue(cloneValue(request.payload));
2840
- metadata = request.metadata === void 0 ? void 0 : cloneValue(request.metadata);
2841
3481
  } catch (error) {
2842
3482
  return Promise.reject(error);
2843
3483
  }
2844
3484
  const startedAt = Date.now();
2845
3485
  const t0 = performance.now();
2846
- const finish = (ok, output, error) => {
2847
- try {
2848
- const duration = performance.now() - t0;
2849
- this.reporter.recordLocal(function_id, ok, duration);
2850
- observe.reportLocal(set, {
2851
- invocation_id: ctx.invocation_id,
2852
- ok,
2853
- input: observedInput,
2854
- output,
2855
- error,
2856
- caller: ctx.caller,
2857
- metadata: observedMetadata,
2858
- started_at_ms: startedAt,
2859
- duration_ms: duration,
2860
- observe_depth: ctx.observe_depth,
2861
- traceparent,
2862
- baggage
2863
- });
2864
- } catch (reportError) {
2865
- this.logError(`Failed to report a local invocation of ${function_id}`, reportError);
3486
+ let delivery;
3487
+ const settle = (handled) => {
3488
+ const duration = performance.now() - t0;
3489
+ this.reporter.recordLocal(function_id, handled.ok, duration);
3490
+ if (!delivering) {
3491
+ if (handled.ok) return handled.value;
3492
+ throw handled.error;
2866
3493
  }
3494
+ const outcome = byReference ? handled : this.deliveredOutcome(handled, input, callInput);
3495
+ delivery = new Delivery(observe, {
3496
+ call: this.callOf(function_id, ctx.invocation_id, outcome, callInput, ctx.caller, callMetadata),
3497
+ thrown: outcome.ok ? void 0 : outcome.error,
3498
+ snapshot,
3499
+ activations,
3500
+ started_at_ms: startedAt,
3501
+ duration_ms: duration,
3502
+ observe_depth: ctx.observe_depth,
3503
+ traceparent,
3504
+ baggage,
3505
+ routed: false
3506
+ });
3507
+ return this.deliverIn(ctx, delivery, hook);
2867
3508
  };
2868
3509
  const effectiveTimeout = request.timeoutMs ?? this.invocationTimeoutMs;
2869
3510
  const untrack = trackRunning(ctx, effectiveTimeout);
@@ -2873,15 +3514,18 @@ var Sdk = class {
2873
3514
  } catch (error) {
2874
3515
  started = Promise.reject(error);
2875
3516
  }
2876
- const done = started.then((output) => {
3517
+ const done = started.then((value) => settle({
3518
+ ok: true,
3519
+ value
3520
+ }), (error) => settle({
3521
+ ok: false,
3522
+ error
3523
+ })).then((output) => {
2877
3524
  untrack();
2878
- finish(true, output, void 0);
2879
3525
  return output;
2880
3526
  }, (error) => {
2881
3527
  untrack();
2882
- const body = handlerErrorBody(error);
2883
- finish(false, void 0, body);
2884
- throw body;
3528
+ throw delivery ? delivery.errorBody(error) : handlerErrorBody(error);
2885
3529
  });
2886
3530
  if (request.action?.type === "void") {
2887
3531
  done.catch((error) => this.logError(`Error invoking function ${function_id}`, error));
@@ -2892,7 +3536,7 @@ var Sdk = class {
2892
3536
  done.then((output) => {
2893
3537
  if (timeout !== void 0) clearTimeout(timeout);
2894
3538
  try {
2895
- resolve(cloneValue(output));
3539
+ resolve(byReference ? output : cloneValue(output));
2896
3540
  } catch (error) {
2897
3541
  reject(error);
2898
3542
  }
@@ -2901,10 +3545,37 @@ var Sdk = class {
2901
3545
  reject(error);
2902
3546
  });
2903
3547
  timeout = setTimeout(() => {
2904
- reject(timeoutError(effectiveTimeout, function_id));
3548
+ reject(new InvocationTimeoutError(effectiveTimeout, function_id));
2905
3549
  }, effectiveTimeout);
2906
3550
  });
2907
3551
  }
3552
+ /**
3553
+ * The outcome a local call of a function that is not private is delivered
3554
+ * with: a handler that returns its own input unchanged is delivered with
3555
+ * the input the call started with as its output, so the report carries the
3556
+ * value once (`output_is_input`, decision 4).
3557
+ */
3558
+ deliveredOutcome(outcome, input, callInput) {
3559
+ if (!outcome.ok) return outcome;
3560
+ return outcome.value === input && input !== null && typeof input === "object" && sameData(callInput, input) ? {
3561
+ ok: true,
3562
+ value: callInput
3563
+ } : outcome;
3564
+ }
3565
+ /** The {@link Call} a finished handler made: what it was called with, and what it returned or threw. */
3566
+ callOf(function_id, invocation_id, outcome, input, caller, metadata) {
3567
+ const call = {
3568
+ function_id,
3569
+ invocation_id,
3570
+ status: outcome.ok ? "success" : "error",
3571
+ input
3572
+ };
3573
+ if (outcome.ok) call.output = outcome.value;
3574
+ else call.error = handlerErrorBody(outcome.error);
3575
+ if (caller !== void 0) call.caller = caller;
3576
+ if (metadata !== void 0) call.metadata = metadata;
3577
+ return call;
3578
+ }
2908
3579
  setConnectionState(state) {
2909
3580
  if (this.connectionState !== state) {
2910
3581
  this.connectionState = state;
@@ -2962,6 +3633,7 @@ var Sdk = class {
2962
3633
  }
2963
3634
  this.ws = void 0;
2964
3635
  this.registeredOnConnection = false;
3636
+ this.observesSent.clear();
2965
3637
  if (this.isShuttingDown) return;
2966
3638
  this.setConnectionState("disconnected");
2967
3639
  this.scheduleReconnect();
@@ -2972,6 +3644,7 @@ var Sdk = class {
2972
3644
  this.setConnectionState("connected");
2973
3645
  this.connectionEpoch++;
2974
3646
  this.registeredOnConnection = false;
3647
+ this.observesSent.clear();
2975
3648
  if (this.ws) this.ws.onmessage = this.onMessage.bind(this);
2976
3649
  if (this.workerId) try {
2977
3650
  this.sendMessageRaw(JSON.stringify({
@@ -2984,15 +3657,7 @@ var Sdk = class {
2984
3657
  console.error("[iii] Reattach JSON envelope rejected", error);
2985
3658
  }
2986
3659
  this.registerWorkerMetadata();
2987
- this.triggerTypes.forEach(({ message }) => {
2988
- this.replayRegistration("registertriggertype", message);
2989
- });
2990
- this.functions.forEach(({ message }) => {
2991
- this.replayRegistration("registerfunction", message);
2992
- });
2993
- this.triggers.forEach((trigger) => {
2994
- this.replayRegistration("registertrigger", trigger);
2995
- });
3660
+ this.sendRegistrations();
2996
3661
  const pending = this.messagesToSend;
2997
3662
  this.messagesToSend = [];
2998
3663
  for (const message of pending) {
@@ -3019,13 +3684,31 @@ var Sdk = class {
3019
3684
  console.error("[iii] Registration JSON envelope rejected", error);
3020
3685
  }
3021
3686
  }
3687
+ /**
3688
+ * The `payload_too_large` error that replaces an answer too large to send
3689
+ * is not the handler's outcome, so it activates no observer: to an engine
3690
+ * with `observe.v2` it says `delivered` when the deliver hook delivered the
3691
+ * call (`answer.delivered`), and `matched: []` otherwise, whatever the
3692
+ * function's hooks. An engine without `observe.v2` gets the bare error.
3693
+ */
3694
+ oversizedAnswer(answer, fallback) {
3695
+ if (!this.engineFeatures.has("observe.v2")) return fallback;
3696
+ if (answer.delivered === true) return {
3697
+ ...fallback,
3698
+ delivered: true
3699
+ };
3700
+ return {
3701
+ ...fallback,
3702
+ matched: []
3703
+ };
3704
+ }
3022
3705
  prepareJson(message) {
3023
3706
  const data = JSON.stringify(message);
3024
3707
  const size = JSON_ENCODER.encode(data).byteLength;
3025
3708
  if (size <= MAX_JSON_FRAME_BYTES) return data;
3026
3709
  const error = createPayloadTooLargeError(size, typeof message.function_id === "string" ? message.function_id : void 0);
3027
3710
  if (message.type === "invocationresult") {
3028
- const fallback = JSON.stringify({
3711
+ const fallback = JSON.stringify(this.oversizedAnswer(message, {
3029
3712
  type: "invocationresult",
3030
3713
  invocation_id: message.invocation_id,
3031
3714
  function_id: message.function_id,
@@ -3033,7 +3716,7 @@ var Sdk = class {
3033
3716
  code: error.code,
3034
3717
  message: payloadTooLargeMessage(size)
3035
3718
  }
3036
- });
3719
+ }));
3037
3720
  if (JSON_ENCODER.encode(fallback).byteLength <= MAX_JSON_FRAME_BYTES) return fallback;
3038
3721
  }
3039
3722
  if (typeof message.invocation_id === "string") {
@@ -3053,30 +3736,6 @@ var Sdk = class {
3053
3736
  }
3054
3737
  toWireFormat(messageType, message) {
3055
3738
  const { message_type: _, ...rest } = message;
3056
- if (messageType === "registertrigger" && "type" in message) {
3057
- const { type: triggerType, ...triggerRest } = message;
3058
- return {
3059
- type: messageType,
3060
- ...triggerRest,
3061
- trigger_type: triggerType
3062
- };
3063
- }
3064
- if (messageType === "unregistertrigger" && "type" in message) {
3065
- const { type: triggerType, ...triggerRest } = message;
3066
- return {
3067
- type: messageType,
3068
- ...triggerRest,
3069
- trigger_type: triggerType
3070
- };
3071
- }
3072
- if (messageType === "triggerregistrationresult" && "type" in message) {
3073
- const { type: triggerType, ...resultRest } = message;
3074
- return {
3075
- type: messageType,
3076
- ...resultRest,
3077
- trigger_type: triggerType
3078
- };
3079
- }
3080
3739
  return {
3081
3740
  type: messageType,
3082
3741
  ...rest
@@ -3150,23 +3809,60 @@ var Sdk = class {
3150
3809
  }
3151
3810
  async onInvokeFunction(invocation_id, function_id, input, metadata, traceparent, baggage, observeFields = {}) {
3152
3811
  const fn = this.functions.get(function_id);
3153
- const resolvedInput = this.resolveChannelValue(input);
3154
3812
  if (fn?.handler) {
3155
3813
  const handler = fn.handler;
3156
3814
  const ctx = {
3157
3815
  function_id,
3158
3816
  invocation_id: invocation_id ?? randomUUID(),
3159
- observe_depth: observeFields.observe_depth ?? 0,
3160
- metadata
3817
+ observe_depth: observeFields.observe_depth ?? 0
3161
3818
  };
3162
3819
  if (observeFields.caller) ctx.caller = observeFields.caller;
3163
3820
  if (observeFields.activation) ctx.activation = observeFields.activation;
3164
3821
  if (traceparent !== void 0) ctx.traceparent = traceparent;
3165
3822
  if (baggage !== void 0) ctx.baggage = baggage;
3823
+ const snapshot = fn.observe.compiled;
3824
+ const activations = fn.observe.activations;
3825
+ const hook = this.functionHooks.get(function_id)?.deliver;
3826
+ const answering = this.engineFeatures.has(FEATURE_OBSERVE_V2);
3827
+ const startedAt = Date.now();
3828
+ const t0 = performance.now();
3829
+ let delivery;
3830
+ let matched;
3831
+ const resolvedInput = this.resolveChannelValue(input);
3166
3832
  const run = async () => {
3167
3833
  const untrack = trackRunning(ctx, MAX_RUNNING_INVOCATION_MS);
3168
3834
  try {
3169
- return await runInContext(ctx, () => handler(resolvedInput, metadata));
3835
+ let outcome;
3836
+ try {
3837
+ outcome = {
3838
+ ok: true,
3839
+ value: await runInContext(ctx, () => handler(resolvedInput, metadata))
3840
+ };
3841
+ } catch (error) {
3842
+ outcome = {
3843
+ ok: false,
3844
+ error
3845
+ };
3846
+ }
3847
+ const narrowed = answering && hook === void 0 && fn.observe.hasMatchHook();
3848
+ if (!answering || hook === void 0 && (!narrowed || snapshot.length === 0)) {
3849
+ if (narrowed) matched = [];
3850
+ if (outcome.ok) return outcome.value;
3851
+ throw outcome.error;
3852
+ }
3853
+ delivery = new Delivery(fn.observe, {
3854
+ call: this.callOf(function_id, ctx.invocation_id, outcome, input, ctx.caller, metadata),
3855
+ thrown: outcome.ok ? void 0 : outcome.error,
3856
+ snapshot,
3857
+ activations,
3858
+ started_at_ms: startedAt,
3859
+ duration_ms: performance.now() - t0,
3860
+ observe_depth: ctx.observe_depth,
3861
+ traceparent,
3862
+ baggage,
3863
+ routed: true
3864
+ });
3865
+ return await this.deliverIn(ctx, delivery, hook);
3170
3866
  } finally {
3171
3867
  untrack();
3172
3868
  }
@@ -3181,26 +3877,30 @@ var Sdk = class {
3181
3877
  }
3182
3878
  try {
3183
3879
  const result = await run();
3184
- this.sendMessage("invocationresult", {
3880
+ this.sendMessage("invocationresult", buildInvocationResult({
3185
3881
  invocation_id,
3186
3882
  function_id,
3187
3883
  result,
3188
3884
  traceparent,
3189
- baggage
3190
- });
3885
+ baggage,
3886
+ matched: delivery ? delivery.matched : matched,
3887
+ delivered: delivery?.delivered
3888
+ }));
3191
3889
  } catch (error) {
3192
- this.sendMessage("invocationresult", {
3890
+ this.sendMessage("invocationresult", buildInvocationResult({
3193
3891
  invocation_id,
3194
3892
  function_id,
3195
- error: handlerErrorBody(error),
3893
+ error: delivery ? delivery.errorBody(error) : handlerErrorBody(error),
3196
3894
  traceparent,
3197
- baggage
3198
- });
3895
+ baggage,
3896
+ matched: delivery ? delivery.matched : matched,
3897
+ delivered: delivery?.delivered
3898
+ }));
3199
3899
  }
3200
3900
  } else {
3201
3901
  const errorCode = fn ? "function_not_invokable" : "function_not_found";
3202
3902
  const errorMessage = fn ? "Function is HTTP-invoked and cannot be invoked locally" : "Function not found";
3203
- if (invocation_id) this.sendMessage("invocationresult", {
3903
+ if (invocation_id) this.sendMessage("invocationresult", buildInvocationResult({
3204
3904
  invocation_id,
3205
3905
  function_id,
3206
3906
  error: {
@@ -3209,62 +3909,7 @@ var Sdk = class {
3209
3909
  },
3210
3910
  traceparent,
3211
3911
  baggage
3212
- });
3213
- }
3214
- }
3215
- async onRegisterTrigger(message) {
3216
- const { trigger_type, id, function_id, config, namespace } = message;
3217
- const triggerTypeData = this.triggerTypes.get(trigger_type);
3218
- if (triggerTypeData) try {
3219
- await triggerTypeData.handler.registerTrigger({
3220
- id,
3221
- function_id,
3222
- config,
3223
- namespace
3224
- });
3225
- this.sendMessage("triggerregistrationresult", {
3226
- id,
3227
- message_type: "triggerregistrationresult",
3228
- type: trigger_type,
3229
- function_id
3230
- });
3231
- } catch (error) {
3232
- this.sendMessage("triggerregistrationresult", {
3233
- id,
3234
- message_type: "triggerregistrationresult",
3235
- type: trigger_type,
3236
- function_id,
3237
- error: {
3238
- code: "trigger_registration_failed",
3239
- message: error.message
3240
- }
3241
- });
3242
- }
3243
- else this.sendMessage("triggerregistrationresult", {
3244
- id,
3245
- message_type: "triggerregistrationresult",
3246
- type: trigger_type,
3247
- function_id,
3248
- error: {
3249
- code: "trigger_type_not_found",
3250
- message: "Trigger type not found"
3251
- }
3252
- });
3253
- }
3254
- async onUnregisterTrigger(message) {
3255
- const trigger_type = message.trigger_type;
3256
- if (!trigger_type) return;
3257
- const triggerTypeData = this.triggerTypes.get(trigger_type);
3258
- if (!triggerTypeData) return;
3259
- const { id, function_id = "", config } = message;
3260
- try {
3261
- await triggerTypeData.handler.unregisterTrigger({
3262
- id,
3263
- function_id,
3264
- config
3265
- });
3266
- } catch (error) {
3267
- console.error(`[iii] Error unregistering trigger ${id}`, error);
3912
+ }));
3268
3913
  }
3269
3914
  }
3270
3915
  onMessage(event) {
@@ -3291,23 +3936,23 @@ var Sdk = class {
3291
3936
  });
3292
3937
  } else if (msgType === "functionregistered") {
3293
3938
  const msg = decodeFunctionRegistered(message);
3294
- this.functions.get(msg.id)?.observe?.onFunctionRegistered(msg, this.connectionEpoch);
3939
+ const fn = this.functions.get(msg.id);
3940
+ if (fn && fn.sentEpoch === this.connectionEpoch) fn.observe.onFunctionRegistered(msg, this.connectionEpoch);
3295
3941
  } else if (msgType === "observeradded") {
3296
3942
  const msg = decodeObserverAdded(message);
3297
- this.functions.get(msg.function_id)?.observe?.onObserverAdded(msg);
3943
+ const fn = this.functions.get(msg.function_id);
3944
+ if (fn && fn.sentEpoch === this.connectionEpoch) fn.observe.onObserverAdded(msg);
3298
3945
  } else if (msgType === "observerremoved") {
3299
3946
  const msg = decodeObserverRemoved(message);
3300
- this.functions.get(msg.function_id)?.observe?.onObserverRemoved(msg);
3947
+ this.functions.get(msg.function_id)?.observe.onObserverRemoved(msg);
3301
3948
  } else if (msgType === "observeresult") {
3302
3949
  const msg = decodeObserveResult(message);
3303
- if (msg.warnings && msg.warnings.length > 0) console.warn(`[iii] Observer ${msg.id}: ${msg.warnings.join("; ")}`);
3304
- this.onObserverState(msg.id, msg.state, msg.error);
3950
+ if (msg.warnings && msg.warnings.length > 0) this.logWarn(`Observer ${msg.id}: ${msg.warnings.join("; ")}`);
3951
+ this.onObserveResult(msg.id, msg.state, msg.error);
3305
3952
  } else if (msgType === "observerstatechanged") {
3306
3953
  const msg = decodeObserverStateChanged(message);
3307
- this.onObserverState(msg.id, msg.state, msg.reason);
3308
- } else if (msgType === "registertrigger") this.onRegisterTrigger(message);
3309
- else if (msgType === "unregistertrigger") this.onUnregisterTrigger(message);
3310
- else if (msgType === "registrationrejected") this.onRegistrationRejected(message);
3954
+ this.onObserverStateChanged(msg.id, msg.state, msg.reason);
3955
+ } else if (msgType === "registrationrejected") this.onRegistrationRejected(decodeRegistrationRejected(message));
3311
3956
  else if (msgType === "workerregistered") {
3312
3957
  const { worker_id, reattach_token, features } = decodeWorkerRegistered(message);
3313
3958
  this.workerId = worker_id;
@@ -3316,51 +3961,112 @@ var Sdk = class {
3316
3961
  }
3317
3962
  }
3318
3963
  /**
3319
- * `WorkerRegistered` told this connection what the engine supports. With
3320
- * `observe.v1` the observers are replayed (after the functions, sent on
3321
- * open) and held reports flushed; without it `observe()` fails with
3322
- * `UNSUPPORTED` and observe hooks are inactive.
3964
+ * `WorkerRegistered` told this connection what the engine supports. The
3965
+ * functions that need `observe.v2` go out now, or stay unregistered without
3966
+ * it; without it, one sent earlier on this connection that has gained a
3967
+ * match or deliver hook since is unregistered. With `observe.v1` the observers the
3968
+ * engine has not refused are replayed (after the functions) and held reports flushed; without it
3969
+ * `observe()` fails with `UNSUPPORTED` and observer hooks are inactive.
3323
3970
  */
3324
3971
  onEngineFeatures(features) {
3325
3972
  this.engineFeatures = new Set(features);
3326
3973
  this.registeredOnConnection = true;
3974
+ this.sendRegistrations();
3975
+ for (const [functionId, fn] of this.functions) if (fn.sentEpoch === this.connectionEpoch) this.reconcileRegistration(functionId);
3976
+ this.warnUnregisteredHookIds();
3327
3977
  const queued = this.observeQueue;
3328
3978
  this.observeQueue = [];
3329
3979
  if (this.engineFeatures.has("observe.v1")) {
3330
3980
  for (const frame of queued) this.sendMessageRaw(JSON.stringify(frame));
3331
- for (const handle of this.observers.values()) this.sendObserve(handle);
3981
+ for (const handle of this.observerHandles.values()) if (!handle.refused) this.sendObserve(handle);
3332
3982
  this.reporter.flush();
3333
3983
  return;
3334
3984
  }
3335
- for (const handle of this.observers.values()) handle.setState("error", UNSUPPORTED_REASON);
3336
- for (const [functionId, fn] of this.functions) if (fn.observe?.needsObserve) this.warnHooksInactive(functionId);
3985
+ for (const handle of this.observerHandles.values()) if (!handle.refused) handle.setState("error", UNSUPPORTED_REASON);
3986
+ for (const functionId of this.functions.keys()) if (this.hasObserverHooks(functionId)) this.warnHooksInactive(functionId);
3337
3987
  this.reporter.clear();
3338
3988
  }
3339
- onObserverState(id, wireState, reason) {
3340
- const handle = this.observers.get(id);
3989
+ /**
3990
+ * An `observeresult`: the answer to the oldest `observe` of the id sent on
3991
+ * this connection that has none yet. The engine answers every `observe`
3992
+ * once, in the order it read them (decision 56).
3993
+ */
3994
+ onObserveResult(id, wireState, reason) {
3995
+ const handle = this.observesSent.get(id)?.find((h) => !h.answered);
3341
3996
  if (!handle) return;
3997
+ handle.answered = true;
3998
+ if (toObserverState(wireState) === "error") {
3999
+ handle.sent = false;
4000
+ handle.refused = true;
4001
+ this.unlistObserve(handle);
4002
+ handle.setState("error", reason ? {
4003
+ code: reason.code,
4004
+ message: reason.message
4005
+ } : void 0);
4006
+ return;
4007
+ }
4008
+ if (handle.state === "disposed") this.unlistObserve(handle);
4009
+ else this.applyObserverState(handle, wireState, reason);
4010
+ }
4011
+ /**
4012
+ * An `observerstatechanged`: about the newest observer of the id whose
4013
+ * `observeresult` arrived on this connection. One that arrives before any
4014
+ * did is dropped: a reattached connection hears its observers resume
4015
+ * before its replayed `observe`s are answered, and each answer carries the
4016
+ * current state (decision 56).
4017
+ */
4018
+ onObserverStateChanged(id, wireState, reason) {
4019
+ const sent = this.observesSent.get(id);
4020
+ if (!sent) return;
4021
+ for (let at = sent.length - 1; at >= 0; at--) if (sent[at].answered) {
4022
+ this.applyObserverState(sent[at], wireState, reason);
4023
+ return;
4024
+ }
4025
+ }
4026
+ /** A state from the engine for `handle`; `disposed` frees its id. */
4027
+ applyObserverState(handle, wireState, reason) {
3342
4028
  const state = toObserverState(wireState);
3343
4029
  handle.setState(state, reason ? {
3344
4030
  code: reason.code,
3345
4031
  message: reason.message
3346
4032
  } : void 0);
3347
- if (state === "disposed") this.observers.delete(id);
4033
+ if (state !== "disposed") return;
4034
+ this.unlistObserve(handle);
4035
+ if (this.observerHandles.get(handle.id) === handle) this.observerHandles.delete(handle.id);
4036
+ }
4037
+ unlistObserve(handle) {
4038
+ const sent = this.observesSent.get(handle.id);
4039
+ const at = sent ? sent.indexOf(handle) : -1;
4040
+ if (!sent || at < 0) return;
4041
+ sent.splice(at, 1);
4042
+ if (sent.length === 0) this.observesSent.delete(handle.id);
3348
4043
  }
3349
4044
  /**
3350
- * The engine rejected a registration. A `FUNCTION_NAMESPACE_CONFLICT` costs
3351
- * one function and leaves the connection open, so log and keep serving. A
3352
- * `WORKER_NAMESPACE_CONFLICT` means another live worker owns this name in the
3353
- * namespace: it is terminal — stop and do not reconnect (otherwise the engine
3354
- * would only reject the same name again, which with `maxRetries: -1` loops
3355
- * forever).
4045
+ * The engine rejected a registration. The `code` decides the severity:
4046
+ *
4047
+ * - {@link FUNCTION_NAMESPACE_CONFLICT}: another live worker in this
4048
+ * namespace already exports this one function id. Only that registration
4049
+ * is refused; the connection stays open and the worker keeps serving its
4050
+ * other functions.
4051
+ * - {@link FUNCTION_REJECTIONS} on one function: only that function is
4052
+ * refused. Logged; the worker keeps serving.
4053
+ * - {@link WORKER_NAMESPACE_CONFLICT}, or any other code: terminal — stop and
4054
+ * do not reconnect (otherwise the engine would only reject the same name
4055
+ * again, which with `maxRetries: -1` loops forever).
3356
4056
  */
3357
4057
  onRegistrationRejected(init) {
3358
- if (init.code === "FUNCTION_NAMESPACE_CONFLICT") {
3359
- if (init.function_id !== void 0) this.functions.get(init.function_id)?.observe?.onRegistrationRejected(this.connectionEpoch);
3360
- console.warn(`[iii] Function registration rejected: function "${init.function_id ?? "<unknown>"}" in namespace "${init.namespace}" is already exported by worker ${init.owner_worker_id}. Staying connected and serving the rest.`);
4058
+ if (init.code === FUNCTION_NAMESPACE_CONFLICT) {
4059
+ (init.function_id !== void 0 ? this.functions.get(init.function_id) : void 0)?.observe.onRegistrationRejected(this.connectionEpoch);
4060
+ this.logWarn(`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.`);
4061
+ return;
4062
+ }
4063
+ if (FUNCTION_REJECTIONS.has(init.code) && init.function_id !== void 0) {
4064
+ this.functions.get(init.function_id)?.observe.onRegistrationRejected(this.connectionEpoch);
4065
+ this.logError(`Function registration rejected with ${init.code}: function "${init.function_id}" in namespace "${init.namespace}" is not registered. Staying connected and serving the rest.`);
3361
4066
  return;
3362
4067
  }
3363
- console.error(`[iii] Registration rejected (${init.code}): worker "${init.worker_name}" in namespace "${init.namespace}" is already owned by ${init.owner_worker_id}. Not reconnecting.`);
4068
+ if (init.code === WORKER_NAMESPACE_CONFLICT) this.logError(`Registration rejected (${init.code}): worker "${init.worker_name}" in namespace "${init.namespace}" is already owned by ${init.owner_worker_id}. Not reconnecting.`);
4069
+ else this.logError(`Registration rejected by engine with unknown code "${init.code}"; treating as fatal. Not reconnecting.`);
3364
4070
  this.isShuttingDown = true;
3365
4071
  this.clearReconnectTimeout();
3366
4072
  const error = new RegistrationRejectedError(init);
@@ -3375,28 +4081,28 @@ var Sdk = class {
3375
4081
  }
3376
4082
  };
3377
4083
  /**
3378
- * Factory object that constructs routing actions for {@link ISdk.trigger}.
4084
+ * Factory object that constructs routing actions for {@link ISdk.call}.
3379
4085
  *
3380
4086
  * @example
3381
4087
  * ```typescript
3382
- * import { TriggerAction } from 'iii-browser-sdk'
4088
+ * import { CallAction } from 'iii-browser-sdk'
3383
4089
  *
3384
4090
  * // Enqueue to a named queue
3385
- * worker.trigger({
4091
+ * worker.call({
3386
4092
  * function_id: 'process',
3387
4093
  * payload: { data: 'hello' },
3388
- * action: TriggerAction.Enqueue({ queue: 'jobs' }),
4094
+ * action: CallAction.Enqueue({ queue: 'jobs' }),
3389
4095
  * })
3390
4096
  *
3391
4097
  * // Fire-and-forget
3392
- * worker.trigger({
4098
+ * worker.call({
3393
4099
  * function_id: 'notify',
3394
4100
  * payload: {},
3395
- * action: TriggerAction.Void(),
4101
+ * action: CallAction.Void(),
3396
4102
  * })
3397
4103
  * ```
3398
4104
  */
3399
- const TriggerAction = {
4105
+ const CallAction = {
3400
4106
  /**
3401
4107
  * Routes the invocation through a named queue. The engine enqueues the job,
3402
4108
  * acknowledges the caller with `{ messageReceiptId }`, and processes it
@@ -3415,6 +4121,8 @@ const TriggerAction = {
3415
4121
  */
3416
4122
  Void: () => ({ type: "void" })
3417
4123
  };
4124
+ /** @deprecated Use {@link CallAction}, the same object. */
4125
+ const TriggerAction = CallAction;
3418
4126
  /**
3419
4127
  * Register the worker with a iii instance, returns a connected worker client.
3420
4128
  * The WebSocket connection is established automatically.
@@ -3433,5 +4141,5 @@ const TriggerAction = {
3433
4141
  const registerWorker = (address, options) => new Sdk(address, options);
3434
4142
 
3435
4143
  //#endregion
3436
- export { ChannelReader, ChannelWriter, EngineFunctions, EngineTriggers, InvocationError, ObserveRejection, RegistrationRejectedError, TriggerAction, registerWorker };
4144
+ export { CallAction, ChannelReader, ChannelWriter, EngineFunctions, EngineSources, InvocationError, ObserveRejection, RegistrationRejectedError, TriggerAction, registerWorker };
3437
4145
  //# sourceMappingURL=index.mjs.map