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

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