@zlink-systems/stream-connector 0.22.0 → 0.24.0

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.
@@ -26,7 +26,6 @@ var ZlinkStreamConnectorBundle = (() => {
26
26
  ZlinkStreamCodec: () => ZlinkStreamCodec,
27
27
  ZlinkStreamCompression: () => ZlinkStreamCompression,
28
28
  ZlinkStreamConnectionState: () => ZlinkStreamConnectionState,
29
- ZlinkStreamDiagnosticsLevel: () => ZlinkStreamDiagnosticsLevel,
30
29
  ZlinkStreamDispatchMode: () => ZlinkStreamDispatchMode,
31
30
  ZlinkStreamErrorCode: () => ZlinkStreamErrorCode,
32
31
  ZlinkStreamException: () => ZlinkStreamException,
@@ -165,7 +164,8 @@ var ZlinkStreamConnectorBundle = (() => {
165
164
  hasRequestSeq: 1,
166
165
  hasMetadata: 2,
167
166
  hasCorrelationId: 8,
168
- hasFlowId: 16
167
+ hasFlowId: 16,
168
+ hasActorSlot: 32
169
169
  };
170
170
  var ZLINK_STREAM_FORMAT_MARKER = 242;
171
171
  var ZLINK_STREAM_RESPONSE_KIND = 3;
@@ -212,6 +212,7 @@ var ZlinkStreamConnectorBundle = (() => {
212
212
  }
213
213
  const hasCorrelation = correlationBytes !== void 0;
214
214
  const hasFlow = header.flowId !== void 0 || header.flowOrigin !== void 0;
215
+ const hasActorSlot = header.actorSlot !== void 0;
215
216
  if (hasFlow && (header.flowId === void 0 || header.flowOrigin === void 0)) {
216
217
  throw new Error("Stream flow id and origin must be provided together.");
217
218
  }
@@ -219,13 +220,17 @@ var ZlinkStreamConnectorBundle = (() => {
219
220
  if (header.flowOrigin !== void 0 && ![1, 2, 3, 4].includes(header.flowOrigin)) {
220
221
  throw new Error("Stream flow origin is invalid.");
221
222
  }
223
+ if (header.actorSlot !== void 0 && (!Number.isInteger(header.actorSlot) || header.actorSlot < 1 || header.actorSlot > 65535)) {
224
+ throw new Error("Stream actor slot is invalid.");
225
+ }
222
226
  let headerFlags = header.flags;
223
227
  headerFlags = hasRequestSeq ? headerFlags | flags.hasRequestSeq : headerFlags & ~flags.hasRequestSeq;
224
228
  headerFlags = hasMetadata ? headerFlags | flags.hasMetadata : headerFlags & ~flags.hasMetadata;
225
229
  headerFlags = hasCorrelation ? headerFlags | flags.hasCorrelationId : headerFlags & ~flags.hasCorrelationId;
226
230
  headerFlags = hasFlow ? headerFlags | flags.hasFlowId : headerFlags & ~flags.hasFlowId;
231
+ headerFlags = hasActorSlot ? headerFlags | flags.hasActorSlot : headerFlags & ~flags.hasActorSlot;
227
232
  const metadataBytes = hasMetadata ? encodeStreamWireMetadata(header.metadata) : new Uint8Array();
228
- const size = 4 + (hasRequestSeq ? 8 : 0) + 1 + nameBytes.length + (hasMetadata ? 2 + metadataBytes.length : 0) + (hasCorrelation ? 1 + correlationBytes.length : 0) + (hasFlow ? 37 : 0);
233
+ const size = 4 + (hasRequestSeq ? 8 : 0) + 1 + nameBytes.length + (hasMetadata ? 2 + metadataBytes.length : 0) + (hasCorrelation ? 1 + correlationBytes.length : 0) + (hasFlow ? 37 : 0) + (hasActorSlot ? 2 : 0);
229
234
  const buffer = new Uint8Array(size);
230
235
  let offset = 0;
231
236
  buffer[offset++] = ZLINK_STREAM_FORMAT_MARKER;
@@ -258,6 +263,9 @@ var ZlinkStreamConnectorBundle = (() => {
258
263
  offset += 36;
259
264
  buffer[offset++] = header.flowOrigin;
260
265
  }
266
+ if (hasActorSlot) {
267
+ writeUInt16BE(buffer, offset, header.actorSlot);
268
+ }
261
269
  return buffer;
262
270
  }
263
271
  function decodeStreamWireHeader(header, flagOverrides, includeFlow = true) {
@@ -276,7 +284,8 @@ var ZlinkStreamConnectorBundle = (() => {
276
284
  const hasMetadata = (headerFlags & flags.hasMetadata) !== 0;
277
285
  const hasCorrelation = (headerFlags & flags.hasCorrelationId) !== 0;
278
286
  const hasFlow = (headerFlags & flags.hasFlowId) !== 0;
279
- if ((headerFlags & ~31) !== 0) {
287
+ const hasActorSlot = (headerFlags & flags.hasActorSlot) !== 0;
288
+ if ((headerFlags & ~63) !== 0) {
280
289
  throw new Error("Unknown mandatory stream header flag.");
281
290
  }
282
291
  let requestSeq;
@@ -331,6 +340,17 @@ var ZlinkStreamConnectorBundle = (() => {
331
340
  }
332
341
  flowOrigin = includeFlow ? decodedFlowOrigin : void 0;
333
342
  }
343
+ let actorSlot;
344
+ if (hasActorSlot) {
345
+ if (header.length - offset < 2) {
346
+ throw new Error("Stream actor slot is incomplete.");
347
+ }
348
+ actorSlot = readUInt16BE(header, offset);
349
+ if (actorSlot === 0) {
350
+ throw new Error("Stream actor slot must not be zero.");
351
+ }
352
+ offset += 2;
353
+ }
334
354
  if (offset !== header.length) {
335
355
  throw new Error("Stream header has trailing bytes.");
336
356
  }
@@ -343,7 +363,8 @@ var ZlinkStreamConnectorBundle = (() => {
343
363
  metadata: decodedMetadata.metadata,
344
364
  correlationId,
345
365
  flowId,
346
- flowOrigin
366
+ flowOrigin,
367
+ actorSlot
347
368
  };
348
369
  }
349
370
  function validateFlowId(flowId) {
@@ -509,13 +530,6 @@ var ZlinkStreamConnectorBundle = (() => {
509
530
  ZlinkStreamDispatchMode2["Immediate"] = "immediate";
510
531
  return ZlinkStreamDispatchMode2;
511
532
  })(ZlinkStreamDispatchMode || {});
512
- var ZlinkStreamDiagnosticsLevel = /* @__PURE__ */ ((ZlinkStreamDiagnosticsLevel4) => {
513
- ZlinkStreamDiagnosticsLevel4["Off"] = "off";
514
- ZlinkStreamDiagnosticsLevel4["Errors"] = "errors";
515
- ZlinkStreamDiagnosticsLevel4["Normal"] = "normal";
516
- ZlinkStreamDiagnosticsLevel4["Detailed"] = "detailed";
517
- return ZlinkStreamDiagnosticsLevel4;
518
- })(ZlinkStreamDiagnosticsLevel || {});
519
533
  var ZlinkStreamMessageKind = /* @__PURE__ */ ((ZlinkStreamMessageKind2) => {
520
534
  ZlinkStreamMessageKind2[ZlinkStreamMessageKind2["Send"] = 1] = "Send";
521
535
  ZlinkStreamMessageKind2[ZlinkStreamMessageKind2["Request"] = 2] = "Request";
@@ -531,6 +545,7 @@ var ZlinkStreamConnectorBundle = (() => {
531
545
  ZlinkStreamHeaderFlags2[ZlinkStreamHeaderFlags2["PayloadCompressed"] = 4] = "PayloadCompressed";
532
546
  ZlinkStreamHeaderFlags2[ZlinkStreamHeaderFlags2["HasCorrelationId"] = 8] = "HasCorrelationId";
533
547
  ZlinkStreamHeaderFlags2[ZlinkStreamHeaderFlags2["HasFlowId"] = 16] = "HasFlowId";
548
+ ZlinkStreamHeaderFlags2[ZlinkStreamHeaderFlags2["HasActorSlot"] = 32] = "HasActorSlot";
534
549
  return ZlinkStreamHeaderFlags2;
535
550
  })(ZlinkStreamHeaderFlags || {});
536
551
  var ZlinkStreamErrorCode = /* @__PURE__ */ ((ZlinkStreamErrorCode2) => {
@@ -781,16 +796,18 @@ var ZlinkStreamConnectorBundle = (() => {
781
796
 
782
797
  // packages/stream-connector/src/Runtime/Calls/ZlinkStreamCallBuilders.ts
783
798
  var ZlinkStreamCallBuilderState = class {
784
- constructor(name) {
799
+ constructor(name, actorSlot, validateActor) {
800
+ this.actorSlot = actorSlot;
801
+ this.validateActor = validateActor;
785
802
  __publicField(this, "executed", false);
786
803
  __publicField(this, "name");
787
804
  __publicField(this, "metadata", ZlinkStreamMetadataMap.empty);
788
805
  __publicField(this, "timeoutMs");
789
806
  __publicField(this, "compress", false);
790
- __publicField(this, "flow");
791
807
  this.name = name;
792
808
  }
793
809
  ensureNotExecuted() {
810
+ var _a;
794
811
  if (this.executed) {
795
812
  throw connectorError(
796
813
  "validationFailed" /* ValidationFailed */,
@@ -798,6 +815,7 @@ var ZlinkStreamConnectorBundle = (() => {
798
815
  );
799
816
  }
800
817
  this.executed = true;
818
+ (_a = this.validateActor) == null ? void 0 : _a.call(this);
801
819
  }
802
820
  resolveMessageName() {
803
821
  if (this.name === void 0) {
@@ -810,11 +828,11 @@ var ZlinkStreamConnectorBundle = (() => {
810
828
  }
811
829
  };
812
830
  var ZlinkStreamSendBuilder = class {
813
- constructor(connector, name, payload) {
831
+ constructor(connector, name, payload, actorSlot, validateActor) {
814
832
  this.connector = connector;
815
833
  this.payload = payload;
816
834
  __publicField(this, "state");
817
- this.state = new ZlinkStreamCallBuilderState(name);
835
+ this.state = new ZlinkStreamCallBuilderState(name, actorSlot, validateActor);
818
836
  }
819
837
  packetName(name) {
820
838
  validateName(name);
@@ -829,10 +847,6 @@ var ZlinkStreamConnectorBundle = (() => {
829
847
  this.state.compress = true;
830
848
  return this;
831
849
  }
832
- flowFrom(flow) {
833
- this.state.flow = flow;
834
- return this;
835
- }
836
850
  async submit(signal) {
837
851
  throwIfAborted(signal);
838
852
  this.state.ensureNotExecuted();
@@ -844,16 +858,17 @@ var ZlinkStreamConnectorBundle = (() => {
844
858
  this.state.compress,
845
859
  void 0,
846
860
  signal,
847
- this.state.flow
861
+ void 0,
862
+ this.state.actorSlot
848
863
  );
849
864
  }
850
865
  };
851
866
  var ZlinkStreamRequestBuilder = class {
852
- constructor(connector, name, payload) {
867
+ constructor(connector, name, payload, actorSlot, validateActor) {
853
868
  this.connector = connector;
854
869
  this.payload = payload;
855
870
  __publicField(this, "state");
856
- this.state = new ZlinkStreamCallBuilderState(name);
871
+ this.state = new ZlinkStreamCallBuilderState(name, actorSlot, validateActor);
857
872
  }
858
873
  packetName(name) {
859
874
  validateName(name);
@@ -872,10 +887,6 @@ var ZlinkStreamConnectorBundle = (() => {
872
887
  this.state.compress = true;
873
888
  return this;
874
889
  }
875
- flowFrom(flow) {
876
- this.state.flow = flow;
877
- return this;
878
- }
879
890
  submit(signalOrCallback) {
880
891
  var _a;
881
892
  this.state.ensureNotExecuted();
@@ -886,7 +897,7 @@ var ZlinkStreamConnectorBundle = (() => {
886
897
  this.state.compress,
887
898
  (_a = this.state.timeoutMs) != null ? _a : this.connector.options.requestTimeoutMs,
888
899
  typeof signalOrCallback === "function" ? void 0 : signalOrCallback,
889
- this.state.flow
900
+ this.state.actorSlot
890
901
  );
891
902
  if (typeof signalOrCallback === "function") {
892
903
  operation.then(
@@ -912,7 +923,7 @@ var ZlinkStreamConnectorBundle = (() => {
912
923
  this.state.compress,
913
924
  (_a = this.state.timeoutMs) != null ? _a : this.connector.options.requestTimeoutMs,
914
925
  signal,
915
- this.state.flow
926
+ this.state.actorSlot
916
927
  );
917
928
  }
918
929
  };
@@ -1270,8 +1281,7 @@ var ZlinkStreamConnectorBundle = (() => {
1270
1281
  name: header.name,
1271
1282
  metadata: header.metadata.values,
1272
1283
  correlationId: header.correlationId,
1273
- flowId: header.flowId,
1274
- flowOrigin: encodeFlowOrigin(header.flowOrigin)
1284
+ actorSlot: header.actorSlot
1275
1285
  });
1276
1286
  } catch (cause) {
1277
1287
  throw connectorError(
@@ -1281,15 +1291,10 @@ var ZlinkStreamConnectorBundle = (() => {
1281
1291
  );
1282
1292
  }
1283
1293
  }
1284
- /**
1285
- * `includeFlow=false` (diagnostics Off, spec 27 §4) skips reading and
1286
- * validating the inbound flow fields while the structural length checks in
1287
- * the wire decoder are preserved.
1288
- */
1289
- static decode(header, includeFlow = true) {
1294
+ static decode(header) {
1290
1295
  let decoded;
1291
1296
  try {
1292
- const wire = decodeStreamWireHeader(header, void 0, includeFlow);
1297
+ const wire = decodeStreamWireHeader(header, void 0, false);
1293
1298
  const metadata = wire.metadata.size === 0 ? ZlinkStreamMetadataMap.empty : ZlinkStreamMetadataMap.from(wire.metadata);
1294
1299
  decoded = {
1295
1300
  kind: wire.kind,
@@ -1299,8 +1304,7 @@ var ZlinkStreamConnectorBundle = (() => {
1299
1304
  name: wire.name,
1300
1305
  metadata,
1301
1306
  correlationId: wire.correlationId,
1302
- flowId: wire.flowId,
1303
- flowOrigin: decodeFlowOrigin(wire.flowOrigin)
1307
+ actorSlot: wire.actorSlot
1304
1308
  };
1305
1309
  } catch (cause) {
1306
1310
  throw connectorError(
@@ -1323,7 +1327,7 @@ var ZlinkStreamConnectorBundle = (() => {
1323
1327
  function streamWireErrorMessage2(cause) {
1324
1328
  return cause instanceof Error ? cause.message : "Stream header is invalid.";
1325
1329
  }
1326
- function buildHeader(kind, name, codec, metadata, compress, requestSeq, correlationId, flowId, flowOrigin) {
1330
+ function buildHeader(kind, name, codec, metadata, compress, requestSeq, correlationId, actorSlot) {
1327
1331
  let flags = 0 /* None */;
1328
1332
  if (requestSeq !== void 0) {
1329
1333
  flags |= 1 /* HasRequestSeq */;
@@ -1337,8 +1341,17 @@ var ZlinkStreamConnectorBundle = (() => {
1337
1341
  if (correlationId !== void 0 && correlationId.length > 0) {
1338
1342
  flags |= 8 /* HasCorrelationId */;
1339
1343
  }
1340
- if (flowId !== void 0) flags |= 16 /* HasFlowId */;
1341
- return { kind, codec, flags, requestSeq, name, metadata, correlationId, flowId, flowOrigin };
1344
+ if (actorSlot !== void 0) flags |= 32 /* HasActorSlot */;
1345
+ return {
1346
+ kind,
1347
+ codec,
1348
+ flags,
1349
+ requestSeq,
1350
+ name,
1351
+ metadata,
1352
+ correlationId,
1353
+ actorSlot
1354
+ };
1342
1355
  }
1343
1356
  function validateHeaderSemantics(header) {
1344
1357
  validateEnum(header.kind, header.codec, header.flags);
@@ -1364,8 +1377,9 @@ var ZlinkStreamConnectorBundle = (() => {
1364
1377
  }
1365
1378
  if (header.kind === 5 /* Control */) {
1366
1379
  const hasCorrelation = header.correlationId !== void 0 && header.correlationId.length > 0 || (header.flags & 8 /* HasCorrelationId */) !== 0;
1367
- const hasFlow = header.flowId !== void 0 || header.flowOrigin !== void 0 || (header.flags & 16 /* HasFlowId */) !== 0;
1368
- if (header.flags !== 0 /* None */ || hasRequestSeq || hasMetadata || hasCorrelation || hasFlow || header.codec !== 0 /* Raw */) {
1380
+ const hasFlow = (header.flags & 16 /* HasFlowId */) !== 0;
1381
+ const hasActorSlot = header.actorSlot !== void 0 || (header.flags & 32 /* HasActorSlot */) !== 0;
1382
+ if (header.flags !== 0 /* None */ || hasRequestSeq || hasMetadata || hasCorrelation || hasFlow || hasActorSlot || header.codec !== 0 /* Raw */) {
1369
1383
  throw connectorError(
1370
1384
  "frameDecodeFailed" /* FrameDecodeFailed */,
1371
1385
  "Control packet must use raw codec and must not contain flags."
@@ -1380,17 +1394,11 @@ var ZlinkStreamConnectorBundle = (() => {
1380
1394
  if (![0, 1, 2, 3].includes(codec)) {
1381
1395
  throw connectorError("frameDecodeFailed" /* FrameDecodeFailed */, "Unknown stream codec.");
1382
1396
  }
1383
- const known = 1 /* HasRequestSeq */ | 2 /* HasMetadata */ | 4 /* PayloadCompressed */ | 8 /* HasCorrelationId */ | 16 /* HasFlowId */;
1397
+ const known = 1 /* HasRequestSeq */ | 2 /* HasMetadata */ | 4 /* PayloadCompressed */ | 8 /* HasCorrelationId */ | 16 /* HasFlowId */ | 32 /* HasActorSlot */;
1384
1398
  if ((flags & ~known) !== 0) {
1385
1399
  throw connectorError("frameDecodeFailed" /* FrameDecodeFailed */, "Unknown stream header flag.");
1386
1400
  }
1387
1401
  }
1388
- function encodeFlowOrigin(origin) {
1389
- return origin === void 0 ? void 0 : { Inbound: 1, Timer: 2, Application: 3, Lifecycle: 4 }[origin];
1390
- }
1391
- function decodeFlowOrigin(origin) {
1392
- return origin === void 0 ? void 0 : { 1: "Inbound", 2: "Timer", 3: "Application", 4: "Lifecycle" }[origin];
1393
- }
1394
1402
 
1395
1403
  // packages/stream-connector/src/Runtime/Protocol/ZlinkStreamFrameProtocol.ts
1396
1404
  var ZLINK_STREAM_HEARTBEAT_PING = "$zlink.heartbeat.ping";
@@ -1399,7 +1407,7 @@ var ZlinkStreamConnectorBundle = (() => {
1399
1407
  constructor(options) {
1400
1408
  this.options = options;
1401
1409
  }
1402
- encode(kind, name, payload, metadata, compress, requestSeq, correlationId, flowId, flowOrigin) {
1410
+ encode(kind, name, payload, metadata, compress, requestSeq, correlationId, actorSlot) {
1403
1411
  const payloadBytes = compress ? compressPayload(payload.payload, this.options.compression, this.options.compressionCodec) : payload.payload;
1404
1412
  const header = buildHeader(
1405
1413
  kind,
@@ -1409,8 +1417,7 @@ var ZlinkStreamConnectorBundle = (() => {
1409
1417
  compress,
1410
1418
  requestSeq,
1411
1419
  correlationId,
1412
- flowId,
1413
- flowOrigin
1420
+ actorSlot
1414
1421
  );
1415
1422
  return this.encodeFrame(header, payloadBytes);
1416
1423
  }
@@ -1426,21 +1433,16 @@ var ZlinkStreamConnectorBundle = (() => {
1426
1433
  payload
1427
1434
  );
1428
1435
  }
1429
- decode(frameBytes, flowEnabled = this.flowEnabled()) {
1436
+ decode(frameBytes) {
1430
1437
  const frame = ZlinkStreamFrameCodec.decode(frameBytes);
1431
1438
  return {
1432
- // Spec 27 §4: with diagnostics Off the inbound flow fields are neither
1433
- // read nor validated (structural length checks are preserved).
1434
- header: ZlinkStreamHeaderCodec.decode(frame.header, flowEnabled),
1439
+ header: ZlinkStreamHeaderCodec.decode(frame.header),
1435
1440
  payload: frame.payload
1436
1441
  };
1437
1442
  }
1438
- flowEnabled() {
1439
- return this.options.diagnosticsLevel !== "off" /* Off */;
1440
- }
1441
- decodeFrames(chunk, flowEnabled = this.flowEnabled()) {
1443
+ decodeFrames(chunk) {
1442
1444
  return splitZlinkStreamFrames(chunk).map((frame) => {
1443
- const decoded = this.decode(frame, flowEnabled);
1445
+ const decoded = this.decode(frame);
1444
1446
  if (decoded.payload.length > this.options.maxReceivePayloadSize) {
1445
1447
  throw connectorError(
1446
1448
  "frameTooLarge" /* FrameTooLarge */,
@@ -1492,14 +1494,8 @@ var ZlinkStreamConnectorBundle = (() => {
1492
1494
  }
1493
1495
 
1494
1496
  // packages/stream-connector/src/Runtime/ZlinkStreamConnectorOptions.ts
1495
- var validDiagnosticsLevels = /* @__PURE__ */ new Set([
1496
- "off" /* Off */,
1497
- "errors" /* Errors */,
1498
- "normal" /* Normal */,
1499
- "detailed" /* Detailed */
1500
- ]);
1501
1497
  function normalizeOptions(options, defaultTransportFactory) {
1502
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D;
1498
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C;
1503
1499
  const endpoint = options.endpoint;
1504
1500
  if (endpoint.trim().length === 0) {
1505
1501
  throw connectorError("configurationError" /* ConfigurationError */, "Endpoint must not be empty.");
@@ -1518,7 +1514,6 @@ var ZlinkStreamConnectorBundle = (() => {
1518
1514
  validatePositive((_e = options.maxReceivePayloadSize) != null ? _e : 64 * 1024, "MaxReceivePayloadSize");
1519
1515
  validateHeartbeat(options.heartbeat);
1520
1516
  validateReconnect(options.reconnect);
1521
- validateDiagnosticsLevel(options.diagnosticsLevel);
1522
1517
  return {
1523
1518
  endpoint,
1524
1519
  transport: inferredTransport,
@@ -1544,10 +1539,7 @@ var ZlinkStreamConnectorBundle = (() => {
1544
1539
  compressionCodec: resolveCompressionCodec2(options),
1545
1540
  nameResolver: (_B = options.nameResolver) != null ? _B : defaultPacketNameResolver,
1546
1541
  transportFactory: (_C = options.transportFactory) != null ? _C : defaultTransportFactory,
1547
- codec: options.codec,
1548
- // Spec 26 §4: the default diagnostics level is Errors, which preserves
1549
- // the connector's established wire behavior.
1550
- diagnosticsLevel: (_D = options.diagnosticsLevel) != null ? _D : "errors" /* Errors */
1542
+ codec: options.codec
1551
1543
  };
1552
1544
  }
1553
1545
  var defaultPacketNameResolver = {
@@ -1573,11 +1565,6 @@ var ZlinkStreamConnectorBundle = (() => {
1573
1565
  }
1574
1566
  return options.compressionCodec;
1575
1567
  }
1576
- function validateDiagnosticsLevel(level) {
1577
- if (level !== void 0 && !validDiagnosticsLevels.has(level)) {
1578
- throw connectorError("configurationError" /* ConfigurationError */, "DiagnosticsLevel is invalid.");
1579
- }
1580
- }
1581
1568
  function validatePositive(value, name) {
1582
1569
  if (value <= 0) {
1583
1570
  throw connectorError("validationFailed" /* ValidationFailed */, `${name} must be positive.`);
@@ -1623,25 +1610,6 @@ var ZlinkStreamConnectorBundle = (() => {
1623
1610
  }
1624
1611
  }
1625
1612
 
1626
- // packages/stream-connector/src/Runtime/ZlinkStreamDiagnosticsLevelCell.ts
1627
- var ZlinkStreamDiagnosticsLevelCell = class {
1628
- constructor(initial) {
1629
- __publicField(this, "current");
1630
- this.current = initial;
1631
- }
1632
- get level() {
1633
- return this.current;
1634
- }
1635
- set(level) {
1636
- const candidate = level;
1637
- if (candidate === void 0 || candidate === null) {
1638
- throw connectorError("configurationError" /* ConfigurationError */, "DiagnosticsLevel is invalid.");
1639
- }
1640
- validateDiagnosticsLevel(level);
1641
- this.current = level;
1642
- }
1643
- };
1644
-
1645
1613
  // packages/stream-connector/src/Runtime/ZlinkStreamPendingRequests.ts
1646
1614
  var ZlinkStreamPendingRequests = class {
1647
1615
  constructor() {
@@ -1656,16 +1624,21 @@ var ZlinkStreamConnectorBundle = (() => {
1656
1624
  let timeout;
1657
1625
  let resolvePending;
1658
1626
  let rejectPending;
1659
- const promise = new Promise((resolve, reject) => {
1660
- timeout = setTimeout(() => {
1661
- this.active.delete(requestSeq);
1662
- reject(
1663
- connectorError("requestTimeout" /* RequestTimeout */, `Request '${packetName}' timed out.`)
1664
- );
1665
- }, timeoutMs);
1666
- resolvePending = resolve;
1667
- rejectPending = (error) => reject(connectorError(error.code, error.message, error.cause));
1668
- });
1627
+ const promise = new Promise(
1628
+ (resolve, reject) => {
1629
+ timeout = setTimeout(() => {
1630
+ this.active.delete(requestSeq);
1631
+ reject(
1632
+ connectorError(
1633
+ "requestTimeout" /* RequestTimeout */,
1634
+ `Request '${packetName}' timed out.`
1635
+ )
1636
+ );
1637
+ }, timeoutMs);
1638
+ resolvePending = resolve;
1639
+ rejectPending = (error) => reject(connectorError(error.code, error.message, error.cause));
1640
+ }
1641
+ );
1669
1642
  this.active.set(requestSeq, {
1670
1643
  packetName,
1671
1644
  promise,
@@ -1689,15 +1662,14 @@ var ZlinkStreamConnectorBundle = (() => {
1689
1662
  });
1690
1663
  return { requestSeq, promise };
1691
1664
  }
1692
- /* stream connector spec §5.2: a pending request is matched by request_seq alone. Diagnostics
1693
- * use the original request name retained by this registry, never a legacy reply name. */
1694
- resolve(requestSeq, value) {
1665
+ /* stream connector spec §5.2: a pending request is matched by request_seq alone. */
1666
+ resolve(requestSeq, value, metadata) {
1695
1667
  const pending = this.active.get(requestSeq);
1696
1668
  if (pending === void 0) {
1697
1669
  return false;
1698
1670
  }
1699
1671
  this.active.delete(requestSeq);
1700
- pending.resolve(value);
1672
+ pending.resolve({ name: pending.packetName, metadata, payload: value });
1701
1673
  return true;
1702
1674
  }
1703
1675
  reject(requestSeq, error) {
@@ -1835,9 +1807,11 @@ var ZlinkStreamConnectorBundle = (() => {
1835
1807
  */
1836
1808
  resetForNewConnection() {
1837
1809
  this.receivedCounts.clear();
1810
+ const submittedCallbacks = this.queue.slice(this.queueHead).filter((item) => (item == null ? void 0 : item.kind) === "callback");
1838
1811
  this.queue.length = 0;
1812
+ this.queue.push(...submittedCallbacks);
1839
1813
  this.queueHead = 0;
1840
- this.queuedCount = 0;
1814
+ this.queuedCount = submittedCallbacks.length;
1841
1815
  }
1842
1816
  /**
1843
1817
  * Releases every registered wait surface because the connection it was
@@ -1853,7 +1827,7 @@ var ZlinkStreamConnectorBundle = (() => {
1853
1827
  if (this.observers.size === 0) {
1854
1828
  return;
1855
1829
  }
1856
- const abandoned = [...this.observers.values()].flatMap((set) => [...set]);
1830
+ const abandoned = Array.from(this.observers.values()).flatMap((set) => Array.from(set));
1857
1831
  this.observers.clear();
1858
1832
  for (const registration of abandoned) {
1859
1833
  registration.onConnectionEnded();
@@ -1862,12 +1836,19 @@ var ZlinkStreamConnectorBundle = (() => {
1862
1836
  enqueue(message, signal) {
1863
1837
  var _a, _b;
1864
1838
  this.receivedCounts.set(message.name, ((_a = this.receivedCounts.get(message.name)) != null ? _a : 0) + 1);
1865
- for (const registration of [...(_b = this.observers.get(message.name)) != null ? _b : []]) {
1839
+ for (const registration of Array.from((_b = this.observers.get(message.name)) != null ? _b : [])) {
1866
1840
  if (registration.consume(message)) {
1867
1841
  return;
1868
1842
  }
1869
1843
  }
1870
- this.queue.push({ message, signal });
1844
+ this.queue.push({ kind: "message", message, signal });
1845
+ this.queuedCount += 1;
1846
+ if (this.deliverOnArrival) {
1847
+ this.scheduleDrain();
1848
+ }
1849
+ }
1850
+ enqueueCallback(callback) {
1851
+ this.queue.push({ kind: "callback", callback });
1871
1852
  this.queuedCount += 1;
1872
1853
  if (this.deliverOnArrival) {
1873
1854
  this.scheduleDrain();
@@ -1894,7 +1875,7 @@ var ZlinkStreamConnectorBundle = (() => {
1894
1875
  offerQueued(name, registration) {
1895
1876
  for (let index = this.queueHead; index < this.queue.length; index += 1) {
1896
1877
  const queued = this.queue[index];
1897
- if (queued === void 0 || queued.message.name !== name) {
1878
+ if (queued === void 0 || queued.kind !== "message" || queued.message.name !== name) {
1898
1879
  continue;
1899
1880
  }
1900
1881
  if (!registration.consume(queued.message)) {
@@ -1922,8 +1903,12 @@ var ZlinkStreamConnectorBundle = (() => {
1922
1903
  const queued = this.queue[index];
1923
1904
  if (queued === void 0) continue;
1924
1905
  this.removeAt(index);
1906
+ if (queued.kind === "callback") {
1907
+ await queued.callback();
1908
+ continue;
1909
+ }
1925
1910
  const { message, signal } = queued;
1926
- const handlers = [...this.handlers.get(message.name)];
1911
+ const handlers = Array.from(this.handlers.get(message.name));
1927
1912
  for (const handler of handlers) {
1928
1913
  try {
1929
1914
  await handler(message, signal);
@@ -1953,16 +1938,16 @@ var ZlinkStreamConnectorBundle = (() => {
1953
1938
  var _a, _b;
1954
1939
  for (let index = this.queueHead; index < this.queue.length; index += 1) {
1955
1940
  const queued = this.queue[index];
1956
- if (queued !== void 0 && ((_b = (_a = this.handlers.get(queued.message.name)) == null ? void 0 : _a.size) != null ? _b : 0) > 0) {
1941
+ if (queued !== void 0 && (queued.kind === "callback" || ((_b = (_a = this.handlers.get(queued.message.name)) == null ? void 0 : _a.size) != null ? _b : 0) > 0)) {
1957
1942
  return index;
1958
1943
  }
1959
1944
  }
1960
1945
  return -1;
1961
1946
  }
1962
1947
  hasQueuedMessage(name) {
1963
- var _a;
1964
1948
  for (let index = this.queueHead; index < this.queue.length; index += 1) {
1965
- if (((_a = this.queue[index]) == null ? void 0 : _a.message.name) === name) return true;
1949
+ const queued = this.queue[index];
1950
+ if ((queued == null ? void 0 : queued.kind) === "message" && queued.message.name === name) return true;
1966
1951
  }
1967
1952
  return false;
1968
1953
  }
@@ -1986,14 +1971,12 @@ var ZlinkStreamConnectorBundle = (() => {
1986
1971
 
1987
1972
  // packages/stream-connector/src/Runtime/ZlinkStreamFrameSender.ts
1988
1973
  var ZlinkStreamFrameSender = class {
1989
- constructor(protocol, flowContext) {
1974
+ constructor(protocol) {
1990
1975
  this.protocol = protocol;
1991
- this.flowContext = flowContext;
1992
1976
  __publicField(this, "pendingWrites", /* @__PURE__ */ new Set());
1993
1977
  }
1994
- async send(connection, kind, name, payload, metadata, compress, requestSeq, signal, correlationId, explicitFlow) {
1978
+ async send(connection, kind, name, payload, metadata, compress, requestSeq, signal, correlationId, actorSlot) {
1995
1979
  throwIfAborted(signal);
1996
- const flow = this.protocol.flowEnabled() ? this.flowContext.currentOrCreate(explicitFlow) : void 0;
1997
1980
  await this.write(
1998
1981
  connection,
1999
1982
  this.protocol.encode(
@@ -2004,8 +1987,7 @@ var ZlinkStreamConnectorBundle = (() => {
2004
1987
  compress,
2005
1988
  requestSeq,
2006
1989
  correlationId,
2007
- flow == null ? void 0 : flow.flowId,
2008
- flow == null ? void 0 : flow.flowOrigin
1990
+ actorSlot
2009
1991
  ),
2010
1992
  signal
2011
1993
  );
@@ -2016,7 +1998,7 @@ var ZlinkStreamConnectorBundle = (() => {
2016
1998
  async drain(signal) {
2017
1999
  while (this.pendingWrites.size > 0) {
2018
2000
  throwIfAborted(signal);
2019
- await Promise.allSettled([...this.pendingWrites]);
2001
+ await Promise.allSettled(Array.from(this.pendingWrites));
2020
2002
  }
2021
2003
  }
2022
2004
  async write(connection, frame, signal) {
@@ -2052,15 +2034,185 @@ var ZlinkStreamConnectorBundle = (() => {
2052
2034
  return { closeReason, diagnostic };
2053
2035
  }
2054
2036
 
2037
+ // packages/stream-connector/src/Runtime/ZlinkStreamActors.ts
2038
+ var ACTOR_BOUND = "$zlink.actor.bound";
2039
+ var ACTOR_UNBOUND = "$zlink.actor.unbound";
2040
+ var zlinkStreamActorBinding = Symbol("zlink.stream.actorBinding");
2041
+ var DefaultZlinkStreamActor = class {
2042
+ constructor(connector, actorId, slot) {
2043
+ this.connector = connector;
2044
+ this.actorId = actorId;
2045
+ this.slot = slot;
2046
+ __publicField(this, "bound", true);
2047
+ }
2048
+ get isBound() {
2049
+ return this.bound;
2050
+ }
2051
+ send(payload, messageType) {
2052
+ this.ensureBound();
2053
+ return this.connector.sendForActor(this, payload, messageType);
2054
+ }
2055
+ request(payload, messageType) {
2056
+ this.ensureBound();
2057
+ return this.connector.requestForActor(this, payload, messageType);
2058
+ }
2059
+ on(nameOrType, handler, messageType) {
2060
+ return this.connector.onActorMessage(this, nameOrType, handler, messageType);
2061
+ }
2062
+ ensureBound() {
2063
+ if (!this.bound) {
2064
+ throw connectorError(
2065
+ "validationFailed" /* ValidationFailed */,
2066
+ `Actor '${this.actorId}' is no longer bound.`
2067
+ );
2068
+ }
2069
+ }
2070
+ close() {
2071
+ this.bound = false;
2072
+ }
2073
+ };
2074
+ var ZlinkStreamActors = class {
2075
+ constructor(connector, receivedMessages, events) {
2076
+ this.connector = connector;
2077
+ this.receivedMessages = receivedMessages;
2078
+ this.events = events;
2079
+ __publicField(this, "bySlot", /* @__PURE__ */ new Map());
2080
+ __publicField(this, "byId", /* @__PURE__ */ new Map());
2081
+ __publicField(this, "issued", []);
2082
+ __publicField(this, "boundHandlers", /* @__PURE__ */ new Set());
2083
+ __publicField(this, "unboundHandlers", /* @__PURE__ */ new Set());
2084
+ }
2085
+ get snapshot() {
2086
+ return Object.freeze(Array.from(this.bySlot.values()));
2087
+ }
2088
+ find(actorId) {
2089
+ return this.byId.get(actorId);
2090
+ }
2091
+ onBound(handler) {
2092
+ this.boundHandlers.add(handler);
2093
+ return subscription(() => this.boundHandlers.delete(handler));
2094
+ }
2095
+ onUnbound(handler) {
2096
+ this.unboundHandlers.add(handler);
2097
+ return subscription(() => this.unboundHandlers.delete(handler));
2098
+ }
2099
+ processControl(name, payload, signal) {
2100
+ if (name === ACTOR_BOUND) {
2101
+ this.bind(payload, signal);
2102
+ return true;
2103
+ }
2104
+ if (name === ACTOR_UNBOUND) {
2105
+ this.unbind(payload, signal);
2106
+ return true;
2107
+ }
2108
+ return false;
2109
+ }
2110
+ resolve(slot) {
2111
+ const actor = this.bySlot.get(slot);
2112
+ if (actor === void 0) {
2113
+ throw connectorError(
2114
+ "frameDecodeFailed" /* FrameDecodeFailed */,
2115
+ `Actor slot '${slot}' is not bound.`
2116
+ );
2117
+ }
2118
+ return actor;
2119
+ }
2120
+ closeAll(signal) {
2121
+ for (const actor of this.issued) {
2122
+ if (!actor.isBound) continue;
2123
+ this.bySlot.delete(actor.slot);
2124
+ this.byId.delete(actor.actorId);
2125
+ actor.close();
2126
+ this.queue(this.unboundHandlers, actor, signal);
2127
+ }
2128
+ this.issued.length = 0;
2129
+ }
2130
+ bind(payload, signal) {
2131
+ if (payload.length < 5 || payload[0] !== 1) {
2132
+ throw invalidControl("Actor bound payload is invalid.");
2133
+ }
2134
+ const slot = payload[1] << 8 | payload[2];
2135
+ const idLength = payload[3];
2136
+ if (slot === 0 || idLength === 0 || payload.length !== 4 + idLength) {
2137
+ throw invalidControl("Actor bound payload is invalid.");
2138
+ }
2139
+ let actorId;
2140
+ try {
2141
+ actorId = new TextDecoder("utf-8", { fatal: true }).decode(payload.subarray(4));
2142
+ } catch (cause) {
2143
+ throw connectorError(
2144
+ "frameDecodeFailed" /* FrameDecodeFailed */,
2145
+ "Actor id is not valid UTF-8.",
2146
+ cause
2147
+ );
2148
+ }
2149
+ if (actorId.length === 0 || this.bySlot.has(slot) || this.byId.has(actorId)) {
2150
+ throw invalidControl("Actor bound identity is already in use.");
2151
+ }
2152
+ const actor = new DefaultZlinkStreamActor(this.connector, actorId, slot);
2153
+ this.bySlot.set(slot, actor);
2154
+ this.byId.set(actorId, actor);
2155
+ this.issued.push(actor);
2156
+ this.queue(this.boundHandlers, actor, signal);
2157
+ }
2158
+ unbind(payload, signal) {
2159
+ if (payload.length !== 3 || payload[0] !== 1) {
2160
+ throw invalidControl("Actor unbound payload is invalid.");
2161
+ }
2162
+ const slot = payload[1] << 8 | payload[2];
2163
+ const actor = this.bySlot.get(slot);
2164
+ if (slot === 0 || actor === void 0) {
2165
+ throw invalidControl(`Actor slot '${slot}' is not bound.`);
2166
+ }
2167
+ this.bySlot.delete(slot);
2168
+ this.byId.delete(actor.actorId);
2169
+ actor.close();
2170
+ this.queue(this.unboundHandlers, actor, signal);
2171
+ }
2172
+ queue(handlers, actor, signal) {
2173
+ this.receivedMessages.enqueueCallback(() => {
2174
+ for (const handler of Array.from(handlers)) {
2175
+ this.invoke(handler, actor, signal);
2176
+ }
2177
+ });
2178
+ }
2179
+ invoke(handler, actor, signal) {
2180
+ try {
2181
+ Promise.resolve(handler(actor, signal)).catch((cause) => {
2182
+ void this.events.publishError(
2183
+ {
2184
+ code: "userCallbackFailed" /* UserCallbackFailed */,
2185
+ message: "Actor lifecycle handler failed.",
2186
+ cause
2187
+ },
2188
+ signal
2189
+ );
2190
+ });
2191
+ } catch (cause) {
2192
+ void this.events.publishError(
2193
+ {
2194
+ code: "userCallbackFailed" /* UserCallbackFailed */,
2195
+ message: "Actor lifecycle handler failed.",
2196
+ cause
2197
+ },
2198
+ signal
2199
+ );
2200
+ }
2201
+ }
2202
+ };
2203
+ function invalidControl(message) {
2204
+ return connectorError("frameDecodeFailed" /* FrameDecodeFailed */, message);
2205
+ }
2206
+
2055
2207
  // packages/stream-connector/src/Runtime/ZlinkStreamReceiveDispatcher.ts
2056
2208
  var ZlinkStreamReceiveDispatcher = class {
2057
- constructor(protocol, pendingRequests, receivedMessages, frameSender, events, flowContext, serverClosing) {
2209
+ constructor(protocol, pendingRequests, receivedMessages, frameSender, events, actors, serverClosing) {
2058
2210
  this.protocol = protocol;
2059
2211
  this.pendingRequests = pendingRequests;
2060
2212
  this.receivedMessages = receivedMessages;
2061
2213
  this.frameSender = frameSender;
2062
2214
  this.events = events;
2063
- this.flowContext = flowContext;
2215
+ this.actors = actors;
2064
2216
  this.serverClosing = serverClosing;
2065
2217
  }
2066
2218
  /**
@@ -2087,49 +2239,47 @@ var ZlinkStreamConnectorBundle = (() => {
2087
2239
  if (frameBytes === void 0) {
2088
2240
  return { available: false, inbound: false };
2089
2241
  }
2090
- const flowEnabled = this.protocol.flowEnabled();
2091
2242
  let frames;
2092
2243
  try {
2093
- frames = this.protocol.decodeFrames(frameBytes, flowEnabled);
2244
+ frames = this.protocol.decodeFrames(frameBytes);
2094
2245
  } catch (cause) {
2095
- await this.events.publishError(
2096
- toStreamError(cause, "frameDecodeFailed" /* FrameDecodeFailed */, "Frame decode failed."),
2097
- signal
2098
- );
2099
- return { available: true, inbound: false };
2246
+ throw cause;
2100
2247
  }
2101
2248
  for (const frame of frames) {
2102
2249
  if (isCurrent !== void 0 && !isCurrent()) {
2103
2250
  break;
2104
2251
  }
2105
2252
  try {
2106
- await this.dispatch(
2107
- connection,
2108
- frame.header,
2109
- frame.payload,
2110
- signal,
2111
- flowEnabled,
2112
- connectionForSend
2113
- );
2253
+ await this.dispatch(connection, frame.header, frame.payload, signal, connectionForSend);
2114
2254
  } catch (cause) {
2115
2255
  if (frame.header.kind === 5 /* Control */ && frame.header.name === ZLINK_STREAM_HEARTBEAT_PING) {
2116
2256
  throw cause;
2117
2257
  }
2118
- await this.events.publishError(
2119
- toStreamError(cause, "frameDecodeFailed" /* FrameDecodeFailed */, "Frame dispatch failed."),
2120
- signal
2258
+ const error = toStreamError(
2259
+ cause,
2260
+ "frameDecodeFailed" /* FrameDecodeFailed */,
2261
+ "Frame dispatch failed."
2121
2262
  );
2263
+ if (error.code === "frameDecodeFailed" /* FrameDecodeFailed */) {
2264
+ throw cause;
2265
+ }
2266
+ await this.events.publishError(error, signal);
2122
2267
  }
2123
2268
  }
2124
2269
  return { available: true, inbound: true };
2125
2270
  }
2126
- async dispatch(connection, header, payload, signal, flowEnabled, connectionForSend) {
2271
+ async dispatch(connection, header, payload, signal, connectionForSend) {
2272
+ const actor = header.actorSlot === void 0 ? void 0 : this.actors.resolve(header.actorSlot);
2127
2273
  if (header.kind === 3 /* Response */ && header.requestSeq !== void 0) {
2128
2274
  try {
2129
- if (!this.pendingRequests.resolve(header.requestSeq, {
2130
- codec: header.codec,
2131
- payload: this.protocol.decodePayload(header, payload)
2132
- })) {
2275
+ if (!this.pendingRequests.resolve(
2276
+ header.requestSeq,
2277
+ {
2278
+ codec: header.codec,
2279
+ payload: this.protocol.decodePayload(header, payload)
2280
+ },
2281
+ header.metadata
2282
+ )) {
2133
2283
  await this.events.publishError(
2134
2284
  {
2135
2285
  code: "frameDecodeFailed" /* FrameDecodeFailed */,
@@ -2177,14 +2327,13 @@ var ZlinkStreamConnectorBundle = (() => {
2177
2327
  return;
2178
2328
  }
2179
2329
  if (header.kind === 1 /* Send */) {
2180
- const flow = flowEnabled ? this.flowContext.createInbound(header.flowId, header.flowOrigin) : void 0;
2181
2330
  this.receivedMessages.enqueue(
2182
2331
  {
2183
2332
  name: header.name,
2184
2333
  metadata: header.metadata,
2185
2334
  payload: { codec: header.codec, payload: this.protocol.decodePayload(header, payload) },
2186
- flowId: flow == null ? void 0 : flow.flowId,
2187
- flowOrigin: flow == null ? void 0 : flow.flowOrigin
2335
+ actorId: actor == null ? void 0 : actor.actorId,
2336
+ [zlinkStreamActorBinding]: actor
2188
2337
  },
2189
2338
  signal
2190
2339
  );
@@ -2192,6 +2341,9 @@ var ZlinkStreamConnectorBundle = (() => {
2192
2341
  }
2193
2342
  async dispatchControl(connection, header, payload, signal, connectionForSend) {
2194
2343
  var _a, _b;
2344
+ if (this.actors.processControl(header.name, payload, signal)) {
2345
+ return;
2346
+ }
2195
2347
  if (header.name === ZLINK_SESSION_CLOSING) {
2196
2348
  const closing = decodeSessionClosing(payload);
2197
2349
  await ((_a = this.serverClosing) == null ? void 0 : _a.call(this, closing.closeReason));
@@ -2250,12 +2402,13 @@ var ZlinkStreamConnectorBundle = (() => {
2250
2402
  return Math.round(baseDelayMs * (0.5 + Math.random() * 0.5));
2251
2403
  }
2252
2404
  var ZlinkStreamConnectorLifecycle = class {
2253
- constructor(options, pendingRequests, frameSender, receiveDispatcher, receivedMessages, events) {
2405
+ constructor(options, pendingRequests, frameSender, receiveDispatcher, receivedMessages, actors, events) {
2254
2406
  this.options = options;
2255
2407
  this.pendingRequests = pendingRequests;
2256
2408
  this.frameSender = frameSender;
2257
2409
  this.receiveDispatcher = receiveDispatcher;
2258
2410
  this.receivedMessages = receivedMessages;
2411
+ this.actors = actors;
2259
2412
  this.events = events;
2260
2413
  __publicField(this, "receiveLoopAbort");
2261
2414
  __publicField(this, "receiveLoopSleeping", false);
@@ -2394,8 +2547,9 @@ var ZlinkStreamConnectorBundle = (() => {
2394
2547
  message: "Connector closed."
2395
2548
  });
2396
2549
  this.receivedMessages.connectionEnded();
2397
- void this.setState("closed" /* Closed */, void 0, signal);
2398
- this.publishDisconnectedWithoutWaiting(signal);
2550
+ this.actors.closeAll(signal);
2551
+ this.queueState("closed" /* Closed */, void 0, signal);
2552
+ this.queueDisconnected(signal);
2399
2553
  if (errors.length === 1) throw errors[0];
2400
2554
  if (errors.length > 1) throw new AggregateError(errors, "Stream connector close failed.");
2401
2555
  }
@@ -2628,6 +2782,7 @@ var ZlinkStreamConnectorBundle = (() => {
2628
2782
  this.currentConnection = void 0;
2629
2783
  this.pendingRequests.failAll(error);
2630
2784
  this.receivedMessages.connectionEnded();
2785
+ this.actors.closeAll();
2631
2786
  try {
2632
2787
  await (connection == null ? void 0 : connection.close());
2633
2788
  } catch {
@@ -2643,11 +2798,8 @@ var ZlinkStreamConnectorBundle = (() => {
2643
2798
  */
2644
2799
  async announceDisconnect(error) {
2645
2800
  if (this.closeRequested) return;
2646
- const announce = this.claimDisconnectedPublish();
2647
- void this.setState("disconnected" /* Disconnected */, error);
2648
- if (announce) {
2649
- void this.events.publishDisconnected().catch(() => void 0);
2650
- }
2801
+ this.queueState("disconnected" /* Disconnected */, error);
2802
+ this.queueDisconnected();
2651
2803
  if (this.shouldReconnect()) {
2652
2804
  queueMicrotask(() => {
2653
2805
  void this.connect().catch(() => void 0);
@@ -2695,16 +2847,35 @@ var ZlinkStreamConnectorBundle = (() => {
2695
2847
  publishDisconnectedWithoutWaiting(signal) {
2696
2848
  void this.publishDisconnectedOnce(signal).catch(() => void 0);
2697
2849
  }
2850
+ queueDisconnected(signal) {
2851
+ if (!this.claimDisconnectedPublish()) return;
2852
+ this.receivedMessages.enqueueCallback(() => {
2853
+ void this.events.publishDisconnected(signal).catch(() => void 0);
2854
+ });
2855
+ }
2856
+ queueState(current, error, signal) {
2857
+ const change = this.transitionState(current, error);
2858
+ if (change === void 0) return;
2859
+ this.receivedMessages.enqueueCallback(() => {
2860
+ void this.publishStateChange(change, signal).catch(() => void 0);
2861
+ });
2862
+ }
2698
2863
  async setState(current, error, signal) {
2864
+ const change = this.transitionState(current, error);
2865
+ if (change === void 0) return;
2866
+ await this.publishStateChange(change, signal);
2867
+ }
2868
+ transitionState(current, error) {
2699
2869
  const previous = this.currentState;
2700
2870
  this.currentState = current;
2701
2871
  if (previous === current && error === void 0) {
2702
- return;
2703
- }
2704
- await this.events.publishStateChanged({ previous, current, error }, signal);
2705
- if (error !== void 0) {
2706
- await this.events.publishError(error, signal);
2872
+ return void 0;
2707
2873
  }
2874
+ return { previous, current, error };
2875
+ }
2876
+ async publishStateChange(change, signal) {
2877
+ await this.events.publishStateChanged(change, signal);
2878
+ if (change.error !== void 0) await this.events.publishError(change.error, signal);
2708
2879
  }
2709
2880
  };
2710
2881
 
@@ -2728,49 +2899,25 @@ var ZlinkStreamConnectorBundle = (() => {
2728
2899
  return subscription(() => this.stateHandlers.delete(handler));
2729
2900
  }
2730
2901
  async publishError(error, signal) {
2731
- await this.publish([...this.errorHandlers].map((handler) => () => handler(error, signal)));
2902
+ await this.publish(
2903
+ Array.from(this.errorHandlers).map((handler) => () => handler(error, signal))
2904
+ );
2732
2905
  }
2733
2906
  async publishDisconnected(signal) {
2734
- await this.publish([...this.disconnectedHandlers].map((handler) => () => handler(signal)));
2907
+ await this.publish(
2908
+ Array.from(this.disconnectedHandlers).map((handler) => () => handler(signal))
2909
+ );
2735
2910
  }
2736
2911
  async publishStateChanged(change, signal) {
2737
- await this.publish([...this.stateHandlers].map((handler) => () => handler(change, signal)));
2912
+ await this.publish(
2913
+ Array.from(this.stateHandlers).map((handler) => () => handler(change, signal))
2914
+ );
2738
2915
  }
2739
2916
  async publish(handlers) {
2740
2917
  await Promise.allSettled(handlers.map(async (handler) => handler()));
2741
2918
  }
2742
2919
  };
2743
2920
 
2744
- // packages/stream-connector/src/Runtime/ZlinkFlowContext.ts
2745
- var BrowserZlinkFlowContext = class {
2746
- currentOrCreate(explicit) {
2747
- return explicit != null ? explicit : { flowId: this.createUuidV7(), flowOrigin: "Application" };
2748
- }
2749
- createInbound(flowId, flowOrigin) {
2750
- return { flowId: flowId != null ? flowId : this.createUuidV7(), flowOrigin: flowOrigin != null ? flowOrigin : "Inbound" };
2751
- }
2752
- createUuidV7() {
2753
- const crypto = globalThis.crypto;
2754
- if (crypto === void 0) {
2755
- throw connectorError(
2756
- "configurationError" /* ConfigurationError */,
2757
- "The browser entrypoint requires the platform Web Crypto API."
2758
- );
2759
- }
2760
- return formatUuidV7(crypto.getRandomValues(new Uint8Array(16)));
2761
- }
2762
- };
2763
- function formatUuidV7(bytes) {
2764
- const timestamp = BigInt(Date.now());
2765
- for (let index = 5; index >= 0; index -= 1) {
2766
- bytes[index] = Number(timestamp >> BigInt((5 - index) * 8) & 0xffn);
2767
- }
2768
- bytes[6] = 112 | bytes[6] & 15;
2769
- bytes[8] = 128 | bytes[8] & 63;
2770
- const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
2771
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
2772
- }
2773
-
2774
2921
  // packages/stream-connector/src/Runtime/Transport/BrowserWebSocketConnection.ts
2775
2922
  var BrowserStreamTransportFactory = class {
2776
2923
  async connect(options, signal) {
@@ -2985,29 +3132,25 @@ var ZlinkStreamConnectorBundle = (() => {
2985
3132
  __publicField(this, "pendingRequests", new ZlinkStreamPendingRequests());
2986
3133
  __publicField(this, "frameSender");
2987
3134
  __publicField(this, "receiveDispatcher");
2988
- __publicField(this, "diagnosticsLevelCell");
3135
+ __publicField(this, "requestSendingHandlers", /* @__PURE__ */ new Set());
3136
+ __publicField(this, "replyReceivedHandlers", /* @__PURE__ */ new Set());
3137
+ __publicField(this, "boundActors");
2989
3138
  __publicField(this, "options");
2990
- const flowContext = new BrowserZlinkFlowContext();
2991
3139
  this.options = normalizeOptions(options, new BrowserStreamTransportFactory());
2992
- this.diagnosticsLevelCell = new ZlinkStreamDiagnosticsLevelCell(this.options.diagnosticsLevel);
2993
- Object.defineProperty(this.options, "diagnosticsLevel", {
2994
- enumerable: true,
2995
- configurable: true,
2996
- get: () => this.diagnosticsLevelCell.level
2997
- });
2998
3140
  const protocol = new ZlinkStreamFrameProtocol(this.options);
2999
- this.frameSender = new ZlinkStreamFrameSender(protocol, flowContext);
3141
+ this.frameSender = new ZlinkStreamFrameSender(protocol);
3000
3142
  this.receivedMessages = new ZlinkStreamReceivedMessages(
3001
3143
  this.events,
3002
3144
  this.options.dispatchMode === "immediate" /* Immediate */
3003
3145
  );
3146
+ this.boundActors = new ZlinkStreamActors(this, this.receivedMessages, this.events);
3004
3147
  this.receiveDispatcher = new ZlinkStreamReceiveDispatcher(
3005
3148
  protocol,
3006
3149
  this.pendingRequests,
3007
3150
  this.receivedMessages,
3008
3151
  this.frameSender,
3009
3152
  this.events,
3010
- flowContext,
3153
+ this.boundActors,
3011
3154
  (reason) => this.lifecycle.serverClosing(reason)
3012
3155
  );
3013
3156
  this.lifecycle = new ZlinkStreamConnectorLifecycle(
@@ -3016,6 +3159,7 @@ var ZlinkStreamConnectorBundle = (() => {
3016
3159
  this.frameSender,
3017
3160
  this.receiveDispatcher,
3018
3161
  this.receivedMessages,
3162
+ this.boundActors,
3019
3163
  this.events
3020
3164
  );
3021
3165
  }
@@ -3031,6 +3175,18 @@ var ZlinkStreamConnectorBundle = (() => {
3031
3175
  get pendingDispatchCount() {
3032
3176
  return this.pendingRequests.count;
3033
3177
  }
3178
+ get actors() {
3179
+ return this.boundActors.snapshot;
3180
+ }
3181
+ actor(actorId) {
3182
+ return this.boundActors.find(actorId);
3183
+ }
3184
+ onActorBound(handler) {
3185
+ return this.boundActors.onBound(handler);
3186
+ }
3187
+ onActorUnbound(handler) {
3188
+ return this.boundActors.onUnbound(handler);
3189
+ }
3034
3190
  /**
3035
3191
  * Spec stream-connector 32 §10: how many packets carrying `name` arrived on
3036
3192
  * the current connection. Arrivals are what is counted, so a message a
@@ -3042,37 +3198,6 @@ var ZlinkStreamConnectorBundle = (() => {
3042
3198
  validateName(name);
3043
3199
  return this.receivedMessages.receivedCount(name);
3044
3200
  }
3045
- /**
3046
- * Current diagnostics level (spec 26 §4.1, spec stream-connector 32 §13).
3047
- * Reflects the level set by the most recent {@link setDiagnosticsLevel}
3048
- * call, or the construction-time option (default
3049
- * {@link ZlinkStreamDiagnosticsLevel.Errors}) if it was never changed.
3050
- */
3051
- get diagnosticsLevel() {
3052
- return this.diagnosticsLevelCell.level;
3053
- }
3054
- /**
3055
- * Changes the diagnostics level in place without recreating the connector
3056
- * (spec 26 §4.1, spec stream-connector 32 §13). The change is an atomic
3057
- * state update: it applies to processing points that read the level after
3058
- * this call returns and is never applied retroactively to frames already
3059
- * built. Rejects unknown values with {@link ZlinkStreamErrorCode.ConfigurationError}.
3060
- * Spec stream-connector 32 §13: this surface changes the value without
3061
- * waiting for anything; it is not a blocking call over the asynchronous pair,
3062
- * which a receive callback would otherwise make wait for its own completion.
3063
- */
3064
- setDiagnosticsLevel(level) {
3065
- this.diagnosticsLevelCell.set(level);
3066
- }
3067
- /**
3068
- * Asynchronous counterpart of {@link setDiagnosticsLevel} (spec
3069
- * stream-connector 32 §13). It changes the same value; awaiting it is how a
3070
- * caller observes the change, and it never replaces the synchronous surface.
3071
- */
3072
- setDiagnosticsLevelAsync(level) {
3073
- this.setDiagnosticsLevel(level);
3074
- return Promise.resolve();
3075
- }
3076
3201
  onErrorReceived(handler) {
3077
3202
  return this.events.onError(handler);
3078
3203
  }
@@ -3082,6 +3207,14 @@ var ZlinkStreamConnectorBundle = (() => {
3082
3207
  onConnectionStateChanged(handler) {
3083
3208
  return this.events.onStateChanged(handler);
3084
3209
  }
3210
+ onRequestSending(handler) {
3211
+ this.requestSendingHandlers.add(handler);
3212
+ return subscription(() => this.requestSendingHandlers.delete(handler));
3213
+ }
3214
+ onReplyReceived(handler) {
3215
+ this.replyReceivedHandlers.add(handler);
3216
+ return subscription(() => this.replyReceivedHandlers.delete(handler));
3217
+ }
3085
3218
  async connect(signal) {
3086
3219
  await this.lifecycle.connect(signal);
3087
3220
  }
@@ -3099,18 +3232,60 @@ var ZlinkStreamConnectorBundle = (() => {
3099
3232
  const encoded = this.encodePayload(payload, messageType);
3100
3233
  return new ZlinkStreamRequestBuilder(this, this.resolveNameOrDefault(encoded), encoded);
3101
3234
  }
3102
- on(name, handler, messageType) {
3235
+ on(nameOrType, handler, messageType) {
3103
3236
  const encodedHandler = (message, signal) => handler(
3104
3237
  {
3105
3238
  name: message.name,
3106
3239
  metadata: message.metadata,
3107
- payload: this.decodePayload(message.payload, messageType),
3108
- flowId: message.flowId,
3109
- flowOrigin: message.flowOrigin
3240
+ payload: this.decodePayload(
3241
+ message.payload,
3242
+ messageType != null ? messageType : typeof nameOrType === "function" ? nameOrType : void 0
3243
+ ),
3244
+ actorId: message.actorId
3110
3245
  },
3111
3246
  signal
3112
3247
  );
3113
- return this.receivedMessages.on(name, encodedHandler);
3248
+ return this.receivedMessages.on(this.observedName(nameOrType), encodedHandler);
3249
+ }
3250
+ sendForActor(actor, payload, messageType) {
3251
+ const encoded = this.encodePayload(payload, messageType);
3252
+ return new ZlinkStreamSendBuilder(
3253
+ this,
3254
+ this.resolveNameOrDefault(encoded),
3255
+ encoded,
3256
+ actor.slot,
3257
+ () => actor.ensureBound()
3258
+ );
3259
+ }
3260
+ requestForActor(actor, payload, messageType) {
3261
+ const encoded = this.encodePayload(payload, messageType);
3262
+ return new ZlinkStreamRequestBuilder(
3263
+ this,
3264
+ this.resolveNameOrDefault(encoded),
3265
+ encoded,
3266
+ actor.slot,
3267
+ () => actor.ensureBound()
3268
+ );
3269
+ }
3270
+ onActorMessage(actor, nameOrType, handler, messageType) {
3271
+ const encodedHandler = (message, signal) => {
3272
+ if (message[zlinkStreamActorBinding] !== actor) {
3273
+ return;
3274
+ }
3275
+ return handler(
3276
+ {
3277
+ name: message.name,
3278
+ metadata: message.metadata,
3279
+ payload: this.decodePayload(
3280
+ message.payload,
3281
+ messageType != null ? messageType : typeof nameOrType === "function" ? nameOrType : void 0
3282
+ ),
3283
+ actorId: message.actorId
3284
+ },
3285
+ signal
3286
+ );
3287
+ };
3288
+ return this.receivedMessages.on(this.observedName(nameOrType), encodedHandler);
3114
3289
  }
3115
3290
  waitFor(nameOrType) {
3116
3291
  return new ZlinkStreamWaitBuilder(this, this.observedName(nameOrType));
@@ -3193,8 +3368,7 @@ var ZlinkStreamConnectorBundle = (() => {
3193
3368
  name: message.name,
3194
3369
  metadata: message.metadata,
3195
3370
  payload: this.decodeWaitPayload(message.payload),
3196
- flowId: message.flowId,
3197
- flowOrigin: message.flowOrigin
3371
+ actorId: message.actorId
3198
3372
  };
3199
3373
  if (!predicate(decoded)) {
3200
3374
  return false;
@@ -3236,7 +3410,7 @@ var ZlinkStreamConnectorBundle = (() => {
3236
3410
  }
3237
3411
  return payload;
3238
3412
  }
3239
- async sendEncoded(kind, name, payload, metadata, compress, requestSeq, signal, flow, correlationId) {
3413
+ async sendEncoded(kind, name, payload, metadata, compress, requestSeq, signal, correlationId, actorSlot) {
3240
3414
  await this.frameSender.send(
3241
3415
  this.lifecycle.connectionForSend(),
3242
3416
  kind,
@@ -3247,37 +3421,105 @@ var ZlinkStreamConnectorBundle = (() => {
3247
3421
  requestSeq,
3248
3422
  signal,
3249
3423
  correlationId,
3250
- flow
3424
+ actorSlot
3251
3425
  );
3252
3426
  }
3253
3427
  /**
3254
3428
  * Per-connector monotonic correlation id (hex). The client generates it on each request
3255
- * and the server echoes it back on the reply, so flows can be joined across the wire.
3429
+ * and the server echoes it back on the reply.
3256
3430
  */
3257
3431
  nextCorrelationId() {
3258
3432
  this.correlationCounter += 1n;
3259
3433
  return this.correlationCounter.toString(16);
3260
3434
  }
3261
- async requestEncoded(name, payload, metadata, compress, timeoutMs, signal, flow) {
3262
- const pending = this.pendingRequests.create(name, timeoutMs);
3435
+ async requestEncoded(name, payload, metadata, compress, timeoutMs, signal, actorSlot) {
3436
+ const startedAt = Date.now();
3437
+ const actorId = actorSlot === void 0 ? void 0 : this.boundActors.resolve(actorSlot).actorId;
3438
+ let requestMetadata = metadata;
3439
+ const sendingContext = {
3440
+ requestPacketName: name,
3441
+ actorId,
3442
+ setMetadata(key, value) {
3443
+ requestMetadata = requestMetadata.with(key, value);
3444
+ }
3445
+ };
3446
+ let pending;
3263
3447
  try {
3448
+ throwIfAborted(signal);
3449
+ for (const handler of Array.from(this.requestSendingHandlers)) {
3450
+ try {
3451
+ handler(sendingContext);
3452
+ } catch (cause) {
3453
+ queueMicrotask(() => {
3454
+ void this.events.publishError(
3455
+ toStreamError(
3456
+ cause,
3457
+ "userCallbackFailed" /* UserCallbackFailed */,
3458
+ "Request sending hook failed."
3459
+ ),
3460
+ signal
3461
+ );
3462
+ });
3463
+ }
3464
+ }
3465
+ pending = this.pendingRequests.create(name, timeoutMs);
3264
3466
  await this.sendEncoded(
3265
3467
  2 /* Request */,
3266
3468
  name,
3267
3469
  payload,
3268
- metadata,
3470
+ requestMetadata,
3269
3471
  compress,
3270
3472
  pending.requestSeq,
3271
3473
  signal,
3272
- flow,
3273
- this.nextCorrelationId()
3474
+ this.nextCorrelationId(),
3475
+ actorSlot
3476
+ );
3477
+ const reply = await pending.promise;
3478
+ this.publishReplyReceived(
3479
+ {
3480
+ requestPacketName: name,
3481
+ actorId,
3482
+ succeeded: true,
3483
+ reply: { ...reply, actorId },
3484
+ elapsed: Date.now() - startedAt
3485
+ },
3486
+ signal
3274
3487
  );
3275
- return await pending.promise;
3488
+ return reply.payload;
3276
3489
  } catch (error) {
3277
- this.pendingRequests.cancel(pending.requestSeq);
3490
+ if (pending !== void 0) this.pendingRequests.cancel(pending.requestSeq);
3491
+ this.publishReplyReceived(
3492
+ {
3493
+ requestPacketName: name,
3494
+ actorId,
3495
+ succeeded: false,
3496
+ error: unwrapStreamError(error),
3497
+ elapsed: Date.now() - startedAt
3498
+ },
3499
+ signal
3500
+ );
3278
3501
  throw error;
3279
3502
  }
3280
3503
  }
3504
+ publishReplyReceived(context, signal) {
3505
+ if (this.replyReceivedHandlers.size === 0) return;
3506
+ this.receivedMessages.enqueueCallback(async () => {
3507
+ for (const handler of Array.from(this.replyReceivedHandlers)) {
3508
+ try {
3509
+ await handler(context, signal);
3510
+ } catch (cause) {
3511
+ await this.events.publishError(
3512
+ toStreamError(
3513
+ cause,
3514
+ "userCallbackFailed" /* UserCallbackFailed */,
3515
+ "Reply received hook failed."
3516
+ ),
3517
+ signal
3518
+ );
3519
+ }
3520
+ }
3521
+ });
3522
+ }
3281
3523
  resolveNameOrDefault(payload) {
3282
3524
  if (payload.messageType === void 0) {
3283
3525
  return void 0;