@naeemo/capnp 0.2.0 → 0.4.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.
package/dist/index.cjs CHANGED
@@ -1,4 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_rpc_connection = require('./rpc-connection-BKWQQ7f9.js');
2
3
 
3
4
  //#region src/core/pointer.ts
4
5
  /**
@@ -145,6 +146,12 @@ var Segment = class Segment {
145
146
  return new Uint8Array(this.buffer, 0, this._size);
146
147
  }
147
148
  /**
149
+ * 获取底层 ArrayBuffer
150
+ */
151
+ getArrayBuffer() {
152
+ return this.buffer;
153
+ }
154
+ /**
148
155
  * 获取字数量
149
156
  */
150
157
  get wordCount() {
@@ -825,21 +832,4152 @@ function createUnionBuilder(struct, tagOffset) {
825
832
  }
826
833
 
827
834
  //#endregion
835
+ //#region src/rpc/message-serializer.ts
836
+ /**
837
+ * RPC Message Serialization
838
+ *
839
+ * Implements full serialization/deserialization of RPC messages using
840
+ * the existing MessageBuilder/MessageReader infrastructure.
841
+ *
842
+ * Reference: rpc.capnp schema
843
+ */
844
+ const MSG_UNIMPLEMENTED = 0;
845
+ const MSG_ABORT = 1;
846
+ const MSG_BOOTSTRAP = 8;
847
+ const MSG_CALL = 2;
848
+ const MSG_RETURN = 3;
849
+ const MSG_FINISH = 4;
850
+ const MSG_RESOLVE = 5;
851
+ const MSG_RELEASE = 6;
852
+ const MSG_DISEMBARGO = 13;
853
+ const MSG_PROVIDE = 10;
854
+ const MSG_ACCEPT = 11;
855
+ const MSG_JOIN = 12;
856
+ const RET_RESULTS = 0;
857
+ const RET_EXCEPTION = 1;
858
+ const RET_CANCELED = 2;
859
+ const RET_RESULTS_SENT_ELSEWHERE = 3;
860
+ const RET_TAKE_FROM_OTHER_QUESTION = 4;
861
+ const RET_ACCEPT_FROM_THIRD_PARTY = 5;
862
+ const SEND_TO_CALLER = 0;
863
+ const SEND_TO_YOURSELF = 1;
864
+ const SEND_TO_THIRD_PARTY = 2;
865
+ const TARGET_IMPORTED_CAP = 0;
866
+ const TARGET_PROMISED_ANSWER = 1;
867
+ const CAP_NONE = 0;
868
+ const CAP_SENDER_HOSTED = 1;
869
+ const CAP_SENDER_PROMISE = 2;
870
+ const CAP_RECEIVER_HOSTED = 3;
871
+ const CAP_RECEIVER_ANSWER = 4;
872
+ const CAP_THIRD_PARTY_HOSTED = 5;
873
+ const RESOLVE_CAP = 0;
874
+ const RESOLVE_EXCEPTION = 1;
875
+ const DISEMBARGO_SENDER_LOOPBACK = 0;
876
+ const DISEMBARGO_RECEIVER_LOOPBACK = 1;
877
+ const DISEMBARGO_ACCEPT = 2;
878
+ const DISEMBARGO_PROVIDE = 3;
879
+ const OP_NOOP = 0;
880
+ const OP_GET_POINTER_FIELD = 1;
881
+ const EXC_FAILED = 0;
882
+ const EXC_OVERLOADED = 1;
883
+ const EXC_DISCONNECTED = 2;
884
+ const EXC_UNIMPLEMENTED = 3;
885
+ function serializeRpcMessage(message) {
886
+ const builder = new MessageBuilder();
887
+ const root = builder.initRoot(6, 1);
888
+ switch (message.type) {
889
+ case "unimplemented":
890
+ serializeUnimplemented(root, message.message);
891
+ break;
892
+ case "abort":
893
+ serializeAbort(root, message.exception);
894
+ break;
895
+ case "bootstrap":
896
+ serializeBootstrap(root, message.bootstrap);
897
+ break;
898
+ case "call":
899
+ serializeCall(root, message.call);
900
+ break;
901
+ case "return":
902
+ serializeReturn(root, message.return);
903
+ break;
904
+ case "finish":
905
+ serializeFinish(root, message.finish);
906
+ break;
907
+ case "resolve":
908
+ serializeResolve(root, message.resolve);
909
+ break;
910
+ case "release":
911
+ serializeRelease(root, message.release);
912
+ break;
913
+ case "disembargo":
914
+ serializeDisembargo(root, message.disembargo);
915
+ break;
916
+ case "provide":
917
+ serializeProvide(root, message.provide);
918
+ break;
919
+ case "accept":
920
+ serializeAccept(root, message.accept);
921
+ break;
922
+ case "join":
923
+ serializeJoin(root, message.join);
924
+ break;
925
+ }
926
+ return new Uint8Array(builder.toArrayBuffer());
927
+ }
928
+ function serializeUnimplemented(root, message) {
929
+ root.setUint16(0, MSG_UNIMPLEMENTED);
930
+ serializeRpcMessage(message);
931
+ root.initStruct(0, 0, 1).initStruct(0, 0, 0);
932
+ }
933
+ function serializeAbort(root, exception) {
934
+ root.setUint16(0, MSG_ABORT);
935
+ serializeException(root, 0, exception);
936
+ }
937
+ function serializeBootstrap(root, bootstrap) {
938
+ root.setUint16(0, MSG_BOOTSTRAP);
939
+ root.setUint32(8, bootstrap.questionId);
940
+ }
941
+ function serializeCall(root, call) {
942
+ root.setUint16(0, MSG_CALL);
943
+ root.setUint32(8, call.questionId);
944
+ root.setUint64(16, call.interfaceId);
945
+ root.setUint16(24, call.methodId);
946
+ root.setBool(208, call.allowThirdPartyTailCall);
947
+ root.setBool(209, call.noPromisePipelining);
948
+ root.setBool(210, call.onlyPromisePipeline);
949
+ serializeMessageTarget(root.initStruct(0, 2, 1), call.target);
950
+ serializePayload(root.initStruct(1, 2, 2), call.params);
951
+ serializeSendResultsTo(root.initStruct(2, 2, 1), call.sendResultsTo);
952
+ }
953
+ function serializeReturn(root, ret) {
954
+ root.setUint16(0, MSG_RETURN);
955
+ root.setUint32(8, ret.answerId);
956
+ root.setBool(192, ret.releaseParamCaps);
957
+ root.setBool(193, ret.noFinishNeeded);
958
+ switch (ret.result.type) {
959
+ case "results":
960
+ root.setUint16(2, RET_RESULTS);
961
+ serializePayload(root.initStruct(0, 2, 2), ret.result.payload);
962
+ break;
963
+ case "exception":
964
+ root.setUint16(2, RET_EXCEPTION);
965
+ serializeException(root, 0, ret.result.exception);
966
+ break;
967
+ case "canceled":
968
+ root.setUint16(2, RET_CANCELED);
969
+ break;
970
+ case "resultsSentElsewhere":
971
+ root.setUint16(2, RET_RESULTS_SENT_ELSEWHERE);
972
+ break;
973
+ case "takeFromOtherQuestion":
974
+ root.setUint16(2, RET_TAKE_FROM_OTHER_QUESTION);
975
+ root.setUint32(12, ret.result.questionId);
976
+ break;
977
+ case "acceptFromThirdParty":
978
+ root.setUint16(2, RET_ACCEPT_FROM_THIRD_PARTY);
979
+ break;
980
+ }
981
+ }
982
+ function serializeFinish(root, finish) {
983
+ root.setUint16(0, MSG_FINISH);
984
+ root.setUint32(8, finish.questionId);
985
+ root.setBool(192, finish.releaseResultCaps);
986
+ root.setBool(193, finish.requireEarlyCancellationWorkaround);
987
+ }
988
+ function serializeResolve(root, resolve) {
989
+ root.setUint16(0, MSG_RESOLVE);
990
+ root.setUint32(8, resolve.promiseId);
991
+ switch (resolve.resolution.type) {
992
+ case "cap":
993
+ root.setUint16(2, RESOLVE_CAP);
994
+ serializeCapDescriptor(root.initStruct(0, 2, 1), resolve.resolution.cap);
995
+ break;
996
+ case "exception":
997
+ root.setUint16(2, RESOLVE_EXCEPTION);
998
+ serializeException(root, 0, resolve.resolution.exception);
999
+ break;
1000
+ }
1001
+ }
1002
+ function serializeRelease(root, release) {
1003
+ root.setUint16(0, MSG_RELEASE);
1004
+ root.setUint32(8, release.id);
1005
+ root.setUint32(12, release.referenceCount);
1006
+ }
1007
+ function serializeDisembargo(root, disembargo) {
1008
+ root.setUint16(0, MSG_DISEMBARGO);
1009
+ serializeMessageTarget(root.initStruct(0, 2, 1), disembargo.target);
1010
+ switch (disembargo.context.type) {
1011
+ case "senderLoopback":
1012
+ root.setUint16(2, DISEMBARGO_SENDER_LOOPBACK);
1013
+ root.setUint32(12, disembargo.context.embargoId);
1014
+ break;
1015
+ case "receiverLoopback":
1016
+ root.setUint16(2, DISEMBARGO_RECEIVER_LOOPBACK);
1017
+ root.setUint32(12, disembargo.context.embargoId);
1018
+ break;
1019
+ case "accept":
1020
+ root.setUint16(2, DISEMBARGO_ACCEPT);
1021
+ break;
1022
+ case "provide":
1023
+ root.setUint16(2, DISEMBARGO_PROVIDE);
1024
+ root.setUint32(12, disembargo.context.questionId);
1025
+ break;
1026
+ }
1027
+ }
1028
+ function serializeProvide(root, provide) {
1029
+ root.setUint16(0, MSG_PROVIDE);
1030
+ root.setUint32(8, provide.questionId);
1031
+ serializeMessageTarget(root.initStruct(0, 2, 1), provide.target);
1032
+ }
1033
+ function serializeAccept(_root, _accept) {}
1034
+ function serializeJoin(_root, _join) {}
1035
+ function serializeMessageTarget(builder, target) {
1036
+ switch (target.type) {
1037
+ case "importedCap":
1038
+ builder.setUint16(0, TARGET_IMPORTED_CAP);
1039
+ builder.setUint32(8, target.importId);
1040
+ break;
1041
+ case "promisedAnswer":
1042
+ builder.setUint16(0, TARGET_PROMISED_ANSWER);
1043
+ serializePromisedAnswer(builder.initStruct(0, 2, 1), target.promisedAnswer);
1044
+ break;
1045
+ }
1046
+ }
1047
+ function serializePromisedAnswer(builder, promisedAnswer) {
1048
+ builder.setUint32(0, promisedAnswer.questionId);
1049
+ if (promisedAnswer.transform.length > 0) {
1050
+ const listBuilder = builder.initList(0, ElementSize.INLINE_COMPOSITE, promisedAnswer.transform.length, {
1051
+ dataWords: 2,
1052
+ pointerCount: 0
1053
+ });
1054
+ for (let i = 0; i < promisedAnswer.transform.length; i++) serializePromisedAnswerOp(listBuilder.getStruct(i), promisedAnswer.transform[i]);
1055
+ }
1056
+ }
1057
+ function serializePromisedAnswerOp(builder, op) {
1058
+ switch (op.type) {
1059
+ case "noop":
1060
+ builder.setUint16(0, OP_NOOP);
1061
+ break;
1062
+ case "getPointerField":
1063
+ builder.setUint16(0, OP_GET_POINTER_FIELD);
1064
+ builder.setUint16(8, op.fieldIndex);
1065
+ break;
1066
+ }
1067
+ }
1068
+ function serializePayload(builder, payload) {
1069
+ if (payload.content.length > 0) builder.initStruct(0, Math.ceil(payload.content.length / 8), 0);
1070
+ if (payload.capTable.length > 0) {
1071
+ const listBuilder = builder.initList(1, ElementSize.EIGHT_BYTES, payload.capTable.length, {
1072
+ dataWords: 2,
1073
+ pointerCount: 1
1074
+ });
1075
+ for (let i = 0; i < payload.capTable.length; i++) serializeCapDescriptor(listBuilder.getStruct(i), payload.capTable[i]);
1076
+ }
1077
+ }
1078
+ function serializeCapDescriptor(builder, cap) {
1079
+ switch (cap.type) {
1080
+ case "none":
1081
+ builder.setUint16(0, CAP_NONE);
1082
+ break;
1083
+ case "senderHosted":
1084
+ builder.setUint16(0, CAP_SENDER_HOSTED);
1085
+ builder.setUint32(8, cap.exportId);
1086
+ break;
1087
+ case "senderPromise":
1088
+ builder.setUint16(0, CAP_SENDER_PROMISE);
1089
+ builder.setUint32(8, cap.exportId);
1090
+ break;
1091
+ case "receiverHosted":
1092
+ builder.setUint16(0, CAP_RECEIVER_HOSTED);
1093
+ builder.setUint32(8, cap.importId);
1094
+ break;
1095
+ case "receiverAnswer":
1096
+ builder.setUint16(0, CAP_RECEIVER_ANSWER);
1097
+ serializePromisedAnswer(builder.initStruct(0, 2, 1), cap.promisedAnswer);
1098
+ break;
1099
+ case "thirdPartyHosted":
1100
+ builder.setUint16(0, CAP_THIRD_PARTY_HOSTED);
1101
+ break;
1102
+ }
1103
+ }
1104
+ function serializeSendResultsTo(builder, sendTo) {
1105
+ switch (sendTo.type) {
1106
+ case "caller":
1107
+ builder.setUint16(0, SEND_TO_CALLER);
1108
+ break;
1109
+ case "yourself":
1110
+ builder.setUint16(0, SEND_TO_YOURSELF);
1111
+ break;
1112
+ case "thirdParty":
1113
+ builder.setUint16(0, SEND_TO_THIRD_PARTY);
1114
+ break;
1115
+ }
1116
+ }
1117
+ function serializeException(builder, pointerIndex, exception) {
1118
+ const excBuilder = builder.initStruct(pointerIndex, 2, 1);
1119
+ excBuilder.setText(0, exception.reason);
1120
+ switch (exception.type) {
1121
+ case "failed":
1122
+ excBuilder.setUint16(0, EXC_FAILED);
1123
+ break;
1124
+ case "overloaded":
1125
+ excBuilder.setUint16(0, EXC_OVERLOADED);
1126
+ break;
1127
+ case "disconnected":
1128
+ excBuilder.setUint16(0, EXC_DISCONNECTED);
1129
+ break;
1130
+ case "unimplemented":
1131
+ excBuilder.setUint16(0, EXC_UNIMPLEMENTED);
1132
+ break;
1133
+ }
1134
+ }
1135
+ function deserializeRpcMessage(data) {
1136
+ const root = new MessageReader(data).getRoot(6, 1);
1137
+ const unionTag = root.getUint16(0);
1138
+ switch (unionTag) {
1139
+ case MSG_UNIMPLEMENTED: return {
1140
+ type: "unimplemented",
1141
+ message: deserializeUnimplemented(root)
1142
+ };
1143
+ case MSG_ABORT: return {
1144
+ type: "abort",
1145
+ exception: deserializeException(root, 0)
1146
+ };
1147
+ case MSG_BOOTSTRAP: return {
1148
+ type: "bootstrap",
1149
+ bootstrap: deserializeBootstrap(root)
1150
+ };
1151
+ case MSG_CALL: return {
1152
+ type: "call",
1153
+ call: deserializeCall(root)
1154
+ };
1155
+ case MSG_RETURN: return {
1156
+ type: "return",
1157
+ return: deserializeReturn(root)
1158
+ };
1159
+ case MSG_FINISH: return {
1160
+ type: "finish",
1161
+ finish: deserializeFinish(root)
1162
+ };
1163
+ case MSG_RESOLVE: return {
1164
+ type: "resolve",
1165
+ resolve: deserializeResolve(root)
1166
+ };
1167
+ case MSG_RELEASE: return {
1168
+ type: "release",
1169
+ release: deserializeRelease(root)
1170
+ };
1171
+ case MSG_DISEMBARGO: return {
1172
+ type: "disembargo",
1173
+ disembargo: deserializeDisembargo(root)
1174
+ };
1175
+ case MSG_PROVIDE: return {
1176
+ type: "provide",
1177
+ provide: deserializeProvide(root)
1178
+ };
1179
+ case MSG_ACCEPT: return {
1180
+ type: "accept",
1181
+ accept: deserializeAccept(root)
1182
+ };
1183
+ case MSG_JOIN: return {
1184
+ type: "join",
1185
+ join: deserializeJoin(root)
1186
+ };
1187
+ default: throw new Error(`Unknown message union tag: ${unionTag}`);
1188
+ }
1189
+ }
1190
+ function deserializeUnimplemented(_root) {
1191
+ return {
1192
+ type: "abort",
1193
+ exception: {
1194
+ reason: "Unimplemented message received",
1195
+ type: "unimplemented"
1196
+ }
1197
+ };
1198
+ }
1199
+ function deserializeBootstrap(root) {
1200
+ return { questionId: root.getUint32(8) };
1201
+ }
1202
+ function deserializeCall(root) {
1203
+ const targetStruct = root.getStruct(0, 2, 1);
1204
+ const paramsStruct = root.getStruct(1, 2, 2);
1205
+ const sendToStruct = root.getStruct(2, 2, 1);
1206
+ return {
1207
+ questionId: root.getUint32(8),
1208
+ interfaceId: root.getUint64(16),
1209
+ methodId: root.getUint16(24),
1210
+ allowThirdPartyTailCall: root.getBool(208),
1211
+ noPromisePipelining: root.getBool(209),
1212
+ onlyPromisePipeline: root.getBool(210),
1213
+ target: targetStruct ? deserializeMessageTarget(targetStruct) : {
1214
+ type: "importedCap",
1215
+ importId: 0
1216
+ },
1217
+ params: paramsStruct ? deserializePayload(paramsStruct) : {
1218
+ content: new Uint8Array(0),
1219
+ capTable: []
1220
+ },
1221
+ sendResultsTo: sendToStruct ? deserializeSendResultsTo(sendToStruct) : { type: "caller" }
1222
+ };
1223
+ }
1224
+ function deserializeReturn(root) {
1225
+ const resultTag = root.getUint16(2);
1226
+ let result;
1227
+ switch (resultTag) {
1228
+ case RET_RESULTS:
1229
+ result = {
1230
+ type: "results",
1231
+ payload: root.getStruct(0, 2, 2) ? deserializePayload(root.getStruct(0, 2, 2)) : {
1232
+ content: new Uint8Array(0),
1233
+ capTable: []
1234
+ }
1235
+ };
1236
+ break;
1237
+ case RET_EXCEPTION:
1238
+ result = {
1239
+ type: "exception",
1240
+ exception: deserializeException(root, 0)
1241
+ };
1242
+ break;
1243
+ case RET_CANCELED:
1244
+ result = { type: "canceled" };
1245
+ break;
1246
+ case RET_RESULTS_SENT_ELSEWHERE:
1247
+ result = { type: "resultsSentElsewhere" };
1248
+ break;
1249
+ case RET_TAKE_FROM_OTHER_QUESTION:
1250
+ result = {
1251
+ type: "takeFromOtherQuestion",
1252
+ questionId: root.getUint32(12)
1253
+ };
1254
+ break;
1255
+ case RET_ACCEPT_FROM_THIRD_PARTY:
1256
+ result = {
1257
+ type: "acceptFromThirdParty",
1258
+ thirdPartyCapId: { id: new Uint8Array(0) }
1259
+ };
1260
+ break;
1261
+ default: result = { type: "canceled" };
1262
+ }
1263
+ return {
1264
+ answerId: root.getUint32(8),
1265
+ releaseParamCaps: root.getBool(192),
1266
+ noFinishNeeded: root.getBool(193),
1267
+ result
1268
+ };
1269
+ }
1270
+ function deserializeFinish(root) {
1271
+ return {
1272
+ questionId: root.getUint32(8),
1273
+ releaseResultCaps: root.getBool(192),
1274
+ requireEarlyCancellationWorkaround: root.getBool(193)
1275
+ };
1276
+ }
1277
+ function deserializeResolve(root) {
1278
+ const resolutionTag = root.getUint16(2);
1279
+ let resolution;
1280
+ switch (resolutionTag) {
1281
+ case RESOLVE_CAP:
1282
+ resolution = {
1283
+ type: "cap",
1284
+ cap: root.getStruct(0, 2, 1) ? deserializeCapDescriptor(root.getStruct(0, 2, 1)) : { type: "none" }
1285
+ };
1286
+ break;
1287
+ case RESOLVE_EXCEPTION:
1288
+ resolution = {
1289
+ type: "exception",
1290
+ exception: deserializeException(root, 0)
1291
+ };
1292
+ break;
1293
+ default: resolution = {
1294
+ type: "exception",
1295
+ exception: {
1296
+ reason: "Unknown resolution type",
1297
+ type: "failed"
1298
+ }
1299
+ };
1300
+ }
1301
+ return {
1302
+ promiseId: root.getUint32(8),
1303
+ resolution
1304
+ };
1305
+ }
1306
+ function deserializeRelease(root) {
1307
+ return {
1308
+ id: root.getUint32(8),
1309
+ referenceCount: root.getUint32(12)
1310
+ };
1311
+ }
1312
+ function deserializeDisembargo(root) {
1313
+ const targetStruct = root.getStruct(0, 2, 1);
1314
+ const contextTag = root.getUint16(2);
1315
+ let context;
1316
+ switch (contextTag) {
1317
+ case DISEMBARGO_SENDER_LOOPBACK:
1318
+ context = {
1319
+ type: "senderLoopback",
1320
+ embargoId: root.getUint32(12)
1321
+ };
1322
+ break;
1323
+ case DISEMBARGO_RECEIVER_LOOPBACK:
1324
+ context = {
1325
+ type: "receiverLoopback",
1326
+ embargoId: root.getUint32(12)
1327
+ };
1328
+ break;
1329
+ case DISEMBARGO_ACCEPT:
1330
+ context = { type: "accept" };
1331
+ break;
1332
+ case DISEMBARGO_PROVIDE:
1333
+ context = {
1334
+ type: "provide",
1335
+ questionId: root.getUint32(12)
1336
+ };
1337
+ break;
1338
+ default: context = { type: "accept" };
1339
+ }
1340
+ return {
1341
+ target: targetStruct ? deserializeMessageTarget(targetStruct) : {
1342
+ type: "importedCap",
1343
+ importId: 0
1344
+ },
1345
+ context
1346
+ };
1347
+ }
1348
+ function deserializeProvide(root) {
1349
+ const targetStruct = root.getStruct(0, 2, 1);
1350
+ return {
1351
+ questionId: root.getUint32(8),
1352
+ target: targetStruct ? deserializeMessageTarget(targetStruct) : {
1353
+ type: "importedCap",
1354
+ importId: 0
1355
+ },
1356
+ recipient: { id: new Uint8Array(0) }
1357
+ };
1358
+ }
1359
+ function deserializeAccept(_root) {
1360
+ return {
1361
+ questionId: 0,
1362
+ provision: { id: new Uint8Array(0) },
1363
+ embargo: false
1364
+ };
1365
+ }
1366
+ function deserializeJoin(_root) {
1367
+ return {
1368
+ questionId: 0,
1369
+ target: {
1370
+ type: "importedCap",
1371
+ importId: 0
1372
+ },
1373
+ otherCap: {
1374
+ type: "importedCap",
1375
+ importId: 0
1376
+ },
1377
+ joinId: 0
1378
+ };
1379
+ }
1380
+ function deserializeMessageTarget(root) {
1381
+ switch (root.getUint16(0)) {
1382
+ case TARGET_IMPORTED_CAP: return {
1383
+ type: "importedCap",
1384
+ importId: root.getUint32(8)
1385
+ };
1386
+ case TARGET_PROMISED_ANSWER: {
1387
+ const promisedAnswerStruct = root.getStruct(0, 2, 1);
1388
+ return {
1389
+ type: "promisedAnswer",
1390
+ promisedAnswer: promisedAnswerStruct ? deserializePromisedAnswer(promisedAnswerStruct) : {
1391
+ questionId: 0,
1392
+ transform: []
1393
+ }
1394
+ };
1395
+ }
1396
+ default: return {
1397
+ type: "importedCap",
1398
+ importId: 0
1399
+ };
1400
+ }
1401
+ }
1402
+ function deserializePromisedAnswer(root) {
1403
+ const transformList = root.getList(0, ElementSize.INLINE_COMPOSITE, {
1404
+ dataWords: 2,
1405
+ pointerCount: 0
1406
+ });
1407
+ const transform = [];
1408
+ if (transformList) for (let i = 0; i < transformList.length; i++) transform.push(deserializePromisedAnswerOp(transformList.getStruct(i)));
1409
+ return {
1410
+ questionId: root.getUint32(0),
1411
+ transform
1412
+ };
1413
+ }
1414
+ function deserializePromisedAnswerOp(root) {
1415
+ switch (root.getUint16(0)) {
1416
+ case OP_NOOP: return { type: "noop" };
1417
+ case OP_GET_POINTER_FIELD: return {
1418
+ type: "getPointerField",
1419
+ fieldIndex: root.getUint16(8)
1420
+ };
1421
+ default: return { type: "noop" };
1422
+ }
1423
+ }
1424
+ function deserializePayload(root) {
1425
+ const capTableList = root.getList(1, ElementSize.EIGHT_BYTES, {
1426
+ dataWords: 2,
1427
+ pointerCount: 1
1428
+ });
1429
+ const capTable = [];
1430
+ if (capTableList) for (let i = 0; i < capTableList.length; i++) capTable.push(deserializeCapDescriptor(capTableList.getStruct(i)));
1431
+ return {
1432
+ content: new Uint8Array(0),
1433
+ capTable
1434
+ };
1435
+ }
1436
+ function deserializeCapDescriptor(root) {
1437
+ switch (root.getUint16(0)) {
1438
+ case CAP_NONE: return { type: "none" };
1439
+ case CAP_SENDER_HOSTED: return {
1440
+ type: "senderHosted",
1441
+ exportId: root.getUint32(8)
1442
+ };
1443
+ case CAP_SENDER_PROMISE: return {
1444
+ type: "senderPromise",
1445
+ exportId: root.getUint32(8)
1446
+ };
1447
+ case CAP_RECEIVER_HOSTED: return {
1448
+ type: "receiverHosted",
1449
+ importId: root.getUint32(8)
1450
+ };
1451
+ case CAP_RECEIVER_ANSWER: {
1452
+ const promisedAnswerStruct = root.getStruct(0, 2, 1);
1453
+ return {
1454
+ type: "receiverAnswer",
1455
+ promisedAnswer: promisedAnswerStruct ? deserializePromisedAnswer(promisedAnswerStruct) : {
1456
+ questionId: 0,
1457
+ transform: []
1458
+ }
1459
+ };
1460
+ }
1461
+ case CAP_THIRD_PARTY_HOSTED: return {
1462
+ type: "thirdPartyHosted",
1463
+ thirdPartyCapId: { id: new Uint8Array(0) }
1464
+ };
1465
+ default: return { type: "none" };
1466
+ }
1467
+ }
1468
+ function deserializeSendResultsTo(root) {
1469
+ switch (root.getUint16(0)) {
1470
+ case SEND_TO_CALLER: return { type: "caller" };
1471
+ case SEND_TO_YOURSELF: return { type: "yourself" };
1472
+ case SEND_TO_THIRD_PARTY: return {
1473
+ type: "thirdParty",
1474
+ recipientId: { id: new Uint8Array(0) }
1475
+ };
1476
+ default: return { type: "caller" };
1477
+ }
1478
+ }
1479
+ function deserializeException(root, pointerIndex) {
1480
+ const excStruct = root.getStruct(pointerIndex, 2, 1);
1481
+ if (!excStruct) return {
1482
+ reason: "Unknown error",
1483
+ type: "failed"
1484
+ };
1485
+ const typeTag = excStruct.getUint16(0);
1486
+ let type;
1487
+ switch (typeTag) {
1488
+ case EXC_FAILED:
1489
+ type = "failed";
1490
+ break;
1491
+ case EXC_OVERLOADED:
1492
+ type = "overloaded";
1493
+ break;
1494
+ case EXC_DISCONNECTED:
1495
+ type = "disconnected";
1496
+ break;
1497
+ case EXC_UNIMPLEMENTED:
1498
+ type = "unimplemented";
1499
+ break;
1500
+ default: type = "failed";
1501
+ }
1502
+ return {
1503
+ reason: excStruct.getText(0),
1504
+ type
1505
+ };
1506
+ }
1507
+
1508
+ //#endregion
1509
+ //#region src/rpc/websocket-transport.ts
1510
+ /**
1511
+ * WebSocket Transport Implementation
1512
+ *
1513
+ * Implements RpcTransport over WebSocket for browser and Node.js compatibility.
1514
+ */
1515
+ var WebSocketTransport = class WebSocketTransport {
1516
+ ws = null;
1517
+ messageQueue = [];
1518
+ receiveQueue = [];
1519
+ _connected = false;
1520
+ pendingBuffer = null;
1521
+ pendingLength = 0;
1522
+ onClose;
1523
+ onError;
1524
+ constructor(url, options = {}) {
1525
+ this.options = options;
1526
+ this.connect(url);
1527
+ }
1528
+ static async connect(url, options) {
1529
+ const transport = new WebSocketTransport(url, options);
1530
+ await transport.waitForConnection();
1531
+ return transport;
1532
+ }
1533
+ static fromWebSocket(ws, options) {
1534
+ const transport = new WebSocketTransport("internal", options);
1535
+ transport.attachWebSocket(ws);
1536
+ return transport;
1537
+ }
1538
+ get connected() {
1539
+ return this._connected;
1540
+ }
1541
+ connect(url) {
1542
+ this.ws = new WebSocket(url);
1543
+ this.ws.binaryType = this.options.binaryType ?? "arraybuffer";
1544
+ this.ws.onopen = () => {
1545
+ this._connected = true;
1546
+ };
1547
+ this.ws.onmessage = (event) => {
1548
+ this.handleMessage(event.data);
1549
+ };
1550
+ this.ws.onclose = () => {
1551
+ this._connected = false;
1552
+ this.flushReceiveQueue(null);
1553
+ this.onClose?.();
1554
+ };
1555
+ this.ws.onerror = (_error) => {
1556
+ const err = /* @__PURE__ */ new Error("WebSocket error");
1557
+ this.onError?.(err);
1558
+ };
1559
+ }
1560
+ attachWebSocket(ws) {
1561
+ this.ws = ws;
1562
+ this.ws.binaryType = this.options.binaryType ?? "arraybuffer";
1563
+ this._connected = ws.readyState === WebSocket.OPEN;
1564
+ this.ws.onmessage = (event) => {
1565
+ this.handleMessage(event.data);
1566
+ };
1567
+ this.ws.onclose = () => {
1568
+ this._connected = false;
1569
+ this.flushReceiveQueue(null);
1570
+ this.onClose?.();
1571
+ };
1572
+ this.ws.onerror = (_error) => {
1573
+ const err = /* @__PURE__ */ new Error("WebSocket error");
1574
+ this.onError?.(err);
1575
+ };
1576
+ }
1577
+ waitForConnection() {
1578
+ return new Promise((resolve, reject) => {
1579
+ if (this._connected) {
1580
+ resolve();
1581
+ return;
1582
+ }
1583
+ const timeout = setTimeout(() => {
1584
+ reject(/* @__PURE__ */ new Error("Connection timeout"));
1585
+ }, this.options.connectTimeoutMs ?? 1e4);
1586
+ const checkConnection = () => {
1587
+ if (this._connected) {
1588
+ clearTimeout(timeout);
1589
+ resolve();
1590
+ } else if (!this.ws || this.ws.readyState === WebSocket.CLOSED) {
1591
+ clearTimeout(timeout);
1592
+ reject(/* @__PURE__ */ new Error("Connection failed"));
1593
+ } else setTimeout(checkConnection, 10);
1594
+ };
1595
+ checkConnection();
1596
+ });
1597
+ }
1598
+ handleMessage(data) {
1599
+ if (data instanceof ArrayBuffer) this.processBinaryMessage(new Uint8Array(data));
1600
+ else {
1601
+ const reader = new FileReader();
1602
+ reader.onload = () => {
1603
+ this.processBinaryMessage(new Uint8Array(reader.result));
1604
+ };
1605
+ reader.readAsArrayBuffer(data);
1606
+ }
1607
+ }
1608
+ processBinaryMessage(data) {
1609
+ let offset = 0;
1610
+ while (offset < data.length) if (this.pendingBuffer === null) {
1611
+ if (offset + 4 > data.length) {
1612
+ this.pendingBuffer = data.slice(offset);
1613
+ this.pendingLength = -1;
1614
+ break;
1615
+ }
1616
+ const length = new DataView(data.buffer, data.byteOffset + offset, 4).getUint32(0, true);
1617
+ offset += 4;
1618
+ if (offset + length > data.length) {
1619
+ this.pendingBuffer = data.slice(offset - 4);
1620
+ this.pendingLength = length;
1621
+ break;
1622
+ }
1623
+ const messageData = data.slice(offset, offset + length);
1624
+ offset += length;
1625
+ this.handleRpcMessage(messageData);
1626
+ } else if (this.pendingLength === -1) {
1627
+ const needed = 4 - this.pendingBuffer.length;
1628
+ if (data.length - offset < needed) {
1629
+ this.pendingBuffer = new Uint8Array([...this.pendingBuffer, ...data.slice(offset)]);
1630
+ break;
1631
+ }
1632
+ const tempBuffer = new Uint8Array(this.pendingBuffer.length + needed);
1633
+ tempBuffer.set(this.pendingBuffer);
1634
+ tempBuffer.set(data.slice(offset, offset + needed), this.pendingBuffer.length);
1635
+ this.pendingLength = new DataView(tempBuffer.buffer, 0, 4).getUint32(0, true);
1636
+ this.pendingBuffer = null;
1637
+ offset += needed;
1638
+ } else {
1639
+ const needed = this.pendingLength - this.pendingBuffer.length;
1640
+ if (data.length - offset < needed) {
1641
+ this.pendingBuffer = new Uint8Array([...this.pendingBuffer, ...data.slice(offset)]);
1642
+ break;
1643
+ }
1644
+ const messageData = new Uint8Array(this.pendingLength);
1645
+ messageData.set(this.pendingBuffer);
1646
+ messageData.set(data.slice(offset, offset + needed), this.pendingBuffer.length);
1647
+ offset += needed;
1648
+ this.pendingBuffer = null;
1649
+ this.handleRpcMessage(messageData);
1650
+ }
1651
+ }
1652
+ handleRpcMessage(data) {
1653
+ const message = this.deserializeMessage(data);
1654
+ if (this.receiveQueue.length > 0) {
1655
+ const { resolve } = this.receiveQueue.shift();
1656
+ resolve(message);
1657
+ } else this.messageQueue.push(message);
1658
+ }
1659
+ deserializeMessage(data) {
1660
+ return deserializeRpcMessage(data);
1661
+ }
1662
+ serializeMessage(message) {
1663
+ return serializeRpcMessage(message);
1664
+ }
1665
+ async send(message) {
1666
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) throw new Error("WebSocket not connected");
1667
+ const data = this.serializeMessage(message);
1668
+ const frame = new Uint8Array(4 + data.length);
1669
+ new DataView(frame.buffer).setUint32(0, data.length, true);
1670
+ frame.set(data, 4);
1671
+ this.ws.send(frame);
1672
+ }
1673
+ async receive() {
1674
+ if (this.messageQueue.length > 0) return this.messageQueue.shift();
1675
+ if (!this._connected) return null;
1676
+ return new Promise((resolve, reject) => {
1677
+ this.receiveQueue.push({
1678
+ resolve,
1679
+ reject
1680
+ });
1681
+ });
1682
+ }
1683
+ close(reason) {
1684
+ this._connected = false;
1685
+ this.ws?.close();
1686
+ this.flushReceiveQueue(null);
1687
+ this.onClose?.(reason);
1688
+ }
1689
+ flushReceiveQueue(value) {
1690
+ while (this.receiveQueue.length > 0) {
1691
+ const { resolve } = this.receiveQueue.shift();
1692
+ resolve(value);
1693
+ }
1694
+ }
1695
+ };
1696
+
1697
+ //#endregion
1698
+ //#region src/rpc/capability-client.ts
1699
+ /** Base class for capability client implementations */
1700
+ var BaseCapabilityClient = class {
1701
+ constructor(connection, importId) {
1702
+ this.connection = connection;
1703
+ this.importId = importId;
1704
+ }
1705
+ isValid() {
1706
+ return true;
1707
+ }
1708
+ release() {
1709
+ if (this.importId !== void 0) this.connection.release(this.importId, 1);
1710
+ }
1711
+ /** Make a method call on this capability and return a PipelineClient */
1712
+ _call(_interfaceId, _methodId, params) {
1713
+ if (!this.importId) throw new Error("Cannot call method on capability without import ID");
1714
+ this.serializeParams(params);
1715
+ throw new Error("Use _callAsync instead for async call support");
1716
+ }
1717
+ /** Make an async method call on this capability */
1718
+ async _callAsync(interfaceId, methodId, params) {
1719
+ if (!this.importId) throw new Error("Cannot call method on capability without import ID");
1720
+ const payload = this.serializeParams(params);
1721
+ return this.connection.callPipelined(this.importId, interfaceId, methodId, payload);
1722
+ }
1723
+ /** Serialize parameters to Payload */
1724
+ serializeParams(_params) {
1725
+ return {
1726
+ content: new Uint8Array(),
1727
+ capTable: []
1728
+ };
1729
+ }
1730
+ };
1731
+
1732
+ //#endregion
1733
+ //#region src/rpc/sturdyrefs.ts
1734
+ /**
1735
+ * Manages SturdyRefs on the server side.
1736
+ * Stores the mapping between SturdyRef tokens and live capabilities.
1737
+ */
1738
+ var SturdyRefManager = class {
1739
+ vatId;
1740
+ storedRefs = /* @__PURE__ */ new Map();
1741
+ localIdCounter = 0;
1742
+ constructor(vatId) {
1743
+ this.vatId = vatId;
1744
+ }
1745
+ /**
1746
+ * Save a capability as a SturdyRef
1747
+ */
1748
+ saveCapability(capability, exportId, options) {
1749
+ const localId = options?.localId ?? this.generateLocalId();
1750
+ const now = Date.now();
1751
+ const ref = {
1752
+ vatId: this.vatId,
1753
+ localId,
1754
+ version: 1,
1755
+ expiresAt: options?.ttlMs ? now + options.ttlMs : void 0,
1756
+ metadata: options?.metadata
1757
+ };
1758
+ const stored = {
1759
+ ref,
1760
+ exportId,
1761
+ capability,
1762
+ createdAt: now,
1763
+ lastAccessedAt: now
1764
+ };
1765
+ this.storedRefs.set(localId, stored);
1766
+ return ref;
1767
+ }
1768
+ /**
1769
+ * Restore a capability from a SturdyRef token
1770
+ */
1771
+ restoreCapability(ref) {
1772
+ if (ref.vatId !== this.vatId) {
1773
+ console.warn(`SturdyRef vatId mismatch: ${ref.vatId} !== ${this.vatId}`);
1774
+ return null;
1775
+ }
1776
+ const stored = this.storedRefs.get(ref.localId);
1777
+ if (!stored) {
1778
+ console.warn(`SturdyRef not found: ${ref.localId}`);
1779
+ return null;
1780
+ }
1781
+ if (stored.ref.expiresAt && Date.now() > stored.ref.expiresAt) {
1782
+ console.warn(`SturdyRef expired: ${ref.localId}`);
1783
+ this.storedRefs.delete(ref.localId);
1784
+ return null;
1785
+ }
1786
+ stored.lastAccessedAt = Date.now();
1787
+ return {
1788
+ capability: stored.capability,
1789
+ exportId: stored.exportId
1790
+ };
1791
+ }
1792
+ /**
1793
+ * Drop a SturdyRef
1794
+ */
1795
+ dropSturdyRef(localId) {
1796
+ return this.storedRefs.delete(localId);
1797
+ }
1798
+ /**
1799
+ * Get all active SturdyRefs
1800
+ */
1801
+ getActiveRefs() {
1802
+ const now = Date.now();
1803
+ const active = [];
1804
+ for (const [localId, stored] of this.storedRefs) {
1805
+ if (stored.ref.expiresAt && now > stored.ref.expiresAt) {
1806
+ this.storedRefs.delete(localId);
1807
+ continue;
1808
+ }
1809
+ active.push(stored.ref);
1810
+ }
1811
+ return active;
1812
+ }
1813
+ /**
1814
+ * Clean up expired SturdyRefs
1815
+ */
1816
+ cleanupExpired() {
1817
+ const now = Date.now();
1818
+ let cleaned = 0;
1819
+ for (const [localId, stored] of this.storedRefs) if (stored.ref.expiresAt && now > stored.ref.expiresAt) {
1820
+ this.storedRefs.delete(localId);
1821
+ cleaned++;
1822
+ }
1823
+ return cleaned;
1824
+ }
1825
+ generateLocalId() {
1826
+ return `ref-${++this.localIdCounter}-${Date.now()}`;
1827
+ }
1828
+ };
1829
+ /**
1830
+ * Handles Restore messages on the client side.
1831
+ * Manages reconnecting to capabilities after disconnections.
1832
+ */
1833
+ var RestoreHandler = class {
1834
+ connection;
1835
+ pendingRestores = /* @__PURE__ */ new Map();
1836
+ questionIdCounter = 0;
1837
+ constructor(connection) {
1838
+ this.connection = connection;
1839
+ }
1840
+ /**
1841
+ * Send a Restore message to restore a capability from a SturdyRef
1842
+ */
1843
+ async restore(ref, options) {
1844
+ const questionId = ++this.questionIdCounter;
1845
+ const timeoutMs = options?.timeoutMs ?? 3e4;
1846
+ return new Promise((resolve, reject) => {
1847
+ const timeout = setTimeout(() => {
1848
+ this.pendingRestores.delete(questionId);
1849
+ reject(/* @__PURE__ */ new Error(`Restore timeout after ${timeoutMs}ms`));
1850
+ }, timeoutMs);
1851
+ this.pendingRestores.set(questionId, {
1852
+ resolve,
1853
+ reject,
1854
+ timeout
1855
+ });
1856
+ this.sendRestoreMessage(questionId, ref).catch((error) => {
1857
+ clearTimeout(timeout);
1858
+ this.pendingRestores.delete(questionId);
1859
+ reject(error);
1860
+ });
1861
+ });
1862
+ }
1863
+ /**
1864
+ * Handle a Restore response
1865
+ */
1866
+ handleRestoreResponse(questionId, importId) {
1867
+ const pending = this.pendingRestores.get(questionId);
1868
+ if (pending) {
1869
+ clearTimeout(pending.timeout);
1870
+ this.pendingRestores.delete(questionId);
1871
+ pending.resolve(importId);
1872
+ }
1873
+ }
1874
+ /**
1875
+ * Handle a Restore failure
1876
+ */
1877
+ handleRestoreFailure(questionId, reason) {
1878
+ const pending = this.pendingRestores.get(questionId);
1879
+ if (pending) {
1880
+ clearTimeout(pending.timeout);
1881
+ this.pendingRestores.delete(questionId);
1882
+ pending.reject(/* @__PURE__ */ new Error(`Restore failed: ${reason}`));
1883
+ }
1884
+ }
1885
+ /**
1886
+ * Cancel all pending restores (e.g., on disconnect)
1887
+ */
1888
+ cancelAll(reason) {
1889
+ for (const [_questionId, pending] of this.pendingRestores) {
1890
+ clearTimeout(pending.timeout);
1891
+ pending.reject(/* @__PURE__ */ new Error(`Restore canceled: ${reason}`));
1892
+ }
1893
+ this.pendingRestores.clear();
1894
+ }
1895
+ async sendRestoreMessage(questionId, ref) {
1896
+ const refData = JSON.stringify(ref);
1897
+ const restoreMsg = {
1898
+ type: "call",
1899
+ call: {
1900
+ questionId,
1901
+ target: {
1902
+ type: "importedCap",
1903
+ importId: 0
1904
+ },
1905
+ interfaceId: BigInt("0xffffffffffffffff"),
1906
+ methodId: 0,
1907
+ allowThirdPartyTailCall: false,
1908
+ noPromisePipelining: false,
1909
+ onlyPromisePipeline: false,
1910
+ params: {
1911
+ content: new TextEncoder().encode(refData),
1912
+ capTable: []
1913
+ },
1914
+ sendResultsTo: { type: "caller" }
1915
+ }
1916
+ };
1917
+ console.log("Sending restore message:", restoreMsg);
1918
+ }
1919
+ };
1920
+ /**
1921
+ * Serialize a SturdyRef to a string for storage
1922
+ */
1923
+ function serializeSturdyRef(ref) {
1924
+ return JSON.stringify(ref);
1925
+ }
1926
+ /**
1927
+ * Deserialize a SturdyRef from a string
1928
+ */
1929
+ function deserializeSturdyRef(data) {
1930
+ try {
1931
+ const parsed = JSON.parse(data);
1932
+ if (typeof parsed.vatId !== "string" || typeof parsed.localId !== "string") return null;
1933
+ return {
1934
+ vatId: parsed.vatId,
1935
+ localId: parsed.localId,
1936
+ version: parsed.version,
1937
+ expiresAt: parsed.expiresAt,
1938
+ metadata: parsed.metadata
1939
+ };
1940
+ } catch {
1941
+ return null;
1942
+ }
1943
+ }
1944
+ /**
1945
+ * Check if a SturdyRef is valid (not expired)
1946
+ */
1947
+ function isSturdyRefValid(ref) {
1948
+ if (ref.expiresAt && Date.now() > ref.expiresAt) return false;
1949
+ return true;
1950
+ }
1951
+ /**
1952
+ * Create a SturdyRef from components
1953
+ */
1954
+ function createSturdyRef(vatId, localId, options) {
1955
+ return {
1956
+ vatId,
1957
+ localId,
1958
+ version: 1,
1959
+ expiresAt: options?.ttlMs ? Date.now() + options.ttlMs : void 0,
1960
+ metadata: options?.metadata
1961
+ };
1962
+ }
1963
+
1964
+ //#endregion
1965
+ //#region src/rpc/performance.ts
1966
+ /**
1967
+ * Performance Optimizations for RPC
1968
+ *
1969
+ * Phase 3: Performance improvements
1970
+ * - Multi-segment message support
1971
+ * - Memory pooling
1972
+ * - Zero-copy paths where possible
1973
+ */
1974
+ /**
1975
+ * Memory pool for reusing ArrayBuffers
1976
+ * Reduces GC pressure for frequent allocations
1977
+ */
1978
+ var MemoryPool = class {
1979
+ pools = /* @__PURE__ */ new Map();
1980
+ maxPoolSize;
1981
+ maxBufferAge;
1982
+ constructor(options) {
1983
+ this.maxPoolSize = options?.maxPoolSize ?? 100;
1984
+ this.maxBufferAge = options?.maxBufferAgeMs ?? 6e4;
1985
+ }
1986
+ /**
1987
+ * Acquire a buffer of at least the requested size
1988
+ */
1989
+ acquire(size) {
1990
+ const pooledSize = this.roundUpSize(size);
1991
+ const pool = this.pools.get(pooledSize);
1992
+ if (pool && pool.length > 0) {
1993
+ const now = Date.now();
1994
+ const index = pool.findIndex((b) => now - b.lastUsed < this.maxBufferAge);
1995
+ if (index >= 0) return pool.splice(index, 1)[0].buffer;
1996
+ }
1997
+ return new ArrayBuffer(pooledSize);
1998
+ }
1999
+ /**
2000
+ * Release a buffer back to the pool
2001
+ */
2002
+ release(buffer) {
2003
+ const size = buffer.byteLength;
2004
+ if (size < 64 || size > 1024 * 1024) return;
2005
+ let pool = this.pools.get(size);
2006
+ if (!pool) {
2007
+ pool = [];
2008
+ this.pools.set(size, pool);
2009
+ }
2010
+ if (pool.length < this.maxPoolSize) pool.push({
2011
+ buffer,
2012
+ size,
2013
+ lastUsed: Date.now()
2014
+ });
2015
+ }
2016
+ /**
2017
+ * Clear all pooled buffers
2018
+ */
2019
+ clear() {
2020
+ this.pools.clear();
2021
+ }
2022
+ /**
2023
+ * Get pool statistics
2024
+ */
2025
+ getStats() {
2026
+ let totalBuffers = 0;
2027
+ let totalBytes = 0;
2028
+ const sizes = [];
2029
+ for (const [size, pool] of this.pools) {
2030
+ totalBuffers += pool.length;
2031
+ totalBytes += size * pool.length;
2032
+ sizes.push(size);
2033
+ }
2034
+ return {
2035
+ totalBuffers,
2036
+ totalBytes,
2037
+ sizes
2038
+ };
2039
+ }
2040
+ roundUpSize(size) {
2041
+ if (size <= 64) return 64;
2042
+ if (size <= 128) return 128;
2043
+ if (size <= 256) return 256;
2044
+ if (size <= 512) return 512;
2045
+ if (size <= 1024) return 1024;
2046
+ if (size <= 2048) return 2048;
2047
+ if (size <= 4096) return 4096;
2048
+ if (size <= 8192) return 8192;
2049
+ if (size <= 16384) return 16384;
2050
+ if (size <= 32768) return 32768;
2051
+ if (size <= 65536) return 65536;
2052
+ return size;
2053
+ }
2054
+ };
2055
+ /**
2056
+ * Builder for multi-segment messages
2057
+ * Optimizes memory usage for large messages
2058
+ */
2059
+ var MultiSegmentMessageBuilder = class {
2060
+ segments = [];
2061
+ options;
2062
+ currentSegment;
2063
+ totalSize = 0;
2064
+ constructor(options) {
2065
+ this.options = {
2066
+ initialSegmentSize: options?.initialSegmentSize ?? 8192,
2067
+ maxSegmentSize: options?.maxSegmentSize ?? 65536,
2068
+ allowMultipleSegments: options?.allowMultipleSegments ?? true
2069
+ };
2070
+ this.currentSegment = new Segment(this.options.initialSegmentSize);
2071
+ this.segments.push(this.currentSegment);
2072
+ }
2073
+ /**
2074
+ * Allocate space in the message
2075
+ */
2076
+ allocate(size) {
2077
+ const alignedBytes = size + 7 & -8;
2078
+ const words = alignedBytes / 8;
2079
+ if (this.currentSegment.byteLength - this.currentSegment.wordCount * 8 >= alignedBytes) {
2080
+ const wordOffset = this.currentSegment.allocate(words);
2081
+ this.totalSize += alignedBytes;
2082
+ return {
2083
+ segment: this.currentSegment,
2084
+ offset: wordOffset * 8
2085
+ };
2086
+ }
2087
+ if (!this.options.allowMultipleSegments) throw new Error("Message too large for single segment");
2088
+ this.currentSegment = new Segment(Math.min(Math.max(alignedBytes, this.options.initialSegmentSize), this.options.maxSegmentSize));
2089
+ this.segments.push(this.currentSegment);
2090
+ const newWordOffset = this.currentSegment.allocate(words);
2091
+ this.totalSize += alignedBytes;
2092
+ return {
2093
+ segment: this.currentSegment,
2094
+ offset: newWordOffset * 8
2095
+ };
2096
+ }
2097
+ /**
2098
+ * Get all segments
2099
+ */
2100
+ getSegments() {
2101
+ return this.segments;
2102
+ }
2103
+ /**
2104
+ * Get the total size of all segments
2105
+ */
2106
+ getTotalSize() {
2107
+ return this.totalSize;
2108
+ }
2109
+ /**
2110
+ * Get the number of segments
2111
+ */
2112
+ getSegmentCount() {
2113
+ return this.segments.length;
2114
+ }
2115
+ /**
2116
+ * Serialize to a single buffer (for transport)
2117
+ */
2118
+ toBuffer() {
2119
+ if (this.segments.length === 1) {
2120
+ const segmentData = this.segments[0].asUint8Array();
2121
+ return segmentData.buffer.slice(segmentData.byteOffset, segmentData.byteOffset + segmentData.byteLength);
2122
+ }
2123
+ const totalSize = this.segments.reduce((sum, seg) => sum + seg.byteLength, 0);
2124
+ const result = new ArrayBuffer(totalSize + 8 * this.segments.length);
2125
+ const view = new DataView(result);
2126
+ const bytes = new Uint8Array(result);
2127
+ view.setUint32(0, this.segments.length - 1, true);
2128
+ view.setUint32(4, 0, true);
2129
+ let offset = 8;
2130
+ for (let i = 0; i < this.segments.length; i++) {
2131
+ const segment = this.segments[i];
2132
+ if (i > 0) {
2133
+ view.setUint32(offset, segment.byteLength / 8, true);
2134
+ offset += 4;
2135
+ }
2136
+ const segmentBuffer = new Uint8Array(segment.byteLength);
2137
+ const segmentData = segment.dataView;
2138
+ for (let i = 0; i < segment.byteLength; i++) segmentBuffer[i] = segmentData.getUint8(i);
2139
+ bytes.set(segmentBuffer, offset);
2140
+ offset += segment.byteLength;
2141
+ }
2142
+ return result;
2143
+ }
2144
+ };
2145
+ /**
2146
+ * Create a zero-copy view of a buffer
2147
+ */
2148
+ function createZeroCopyView(buffer, byteOffset = 0, byteLength) {
2149
+ return {
2150
+ buffer,
2151
+ byteOffset,
2152
+ byteLength: byteLength ?? buffer.byteLength - byteOffset
2153
+ };
2154
+ }
2155
+ /**
2156
+ * Check if two buffers are the same underlying memory
2157
+ */
2158
+ function isSameBuffer(a, b) {
2159
+ try {
2160
+ return a === b;
2161
+ } catch {
2162
+ return false;
2163
+ }
2164
+ }
2165
+ /**
2166
+ * Copy data between buffers using the fastest available method
2167
+ */
2168
+ function fastCopy(src, dst, srcOffset = 0, dstOffset = 0, length) {
2169
+ const len = length ?? Math.min(src.byteLength - srcOffset, dst.byteLength - dstOffset);
2170
+ const srcView = new Uint8Array(src, srcOffset, len);
2171
+ new Uint8Array(dst, dstOffset, len).set(srcView);
2172
+ }
2173
+ /**
2174
+ * Optimized RPC message builder
2175
+ */
2176
+ var OptimizedRpcMessageBuilder = class {
2177
+ options;
2178
+ pool;
2179
+ constructor(options) {
2180
+ this.options = {
2181
+ useMultiSegment: options?.useMultiSegment ?? true,
2182
+ initialSegmentSize: options?.initialSegmentSize ?? 8192,
2183
+ useMemoryPool: options?.useMemoryPool ?? true,
2184
+ memoryPool: options?.memoryPool ?? new MemoryPool()
2185
+ };
2186
+ this.pool = this.options.memoryPool;
2187
+ }
2188
+ /**
2189
+ * Build a message with optimizations applied
2190
+ */
2191
+ buildMessage(content) {
2192
+ const totalSize = 8 + content.length;
2193
+ if (this.options.useMemoryPool) {
2194
+ const buffer = this.pool.acquire(totalSize);
2195
+ const view = new DataView(buffer);
2196
+ const bytes = new Uint8Array(buffer);
2197
+ view.setUint32(0, 0, true);
2198
+ view.setUint32(4, content.length / 8, true);
2199
+ bytes.set(content, 8);
2200
+ return buffer;
2201
+ }
2202
+ const buffer = new ArrayBuffer(totalSize);
2203
+ const view = new DataView(buffer);
2204
+ const bytes = new Uint8Array(buffer);
2205
+ view.setUint32(0, 0, true);
2206
+ view.setUint32(4, content.length / 8, true);
2207
+ bytes.set(content, 8);
2208
+ return buffer;
2209
+ }
2210
+ /**
2211
+ * Release a buffer back to the pool
2212
+ */
2213
+ releaseBuffer(buffer) {
2214
+ if (this.options.useMemoryPool) this.pool.release(buffer);
2215
+ }
2216
+ /**
2217
+ * Get pool statistics
2218
+ */
2219
+ getPoolStats() {
2220
+ return this.pool.getStats();
2221
+ }
2222
+ };
2223
+ let globalMemoryPool = null;
2224
+ /**
2225
+ * Get the global memory pool instance
2226
+ */
2227
+ function getGlobalMemoryPool() {
2228
+ if (!globalMemoryPool) globalMemoryPool = new MemoryPool();
2229
+ return globalMemoryPool;
2230
+ }
2231
+ /**
2232
+ * Configure the global memory pool
2233
+ */
2234
+ function configureGlobalMemoryPool(options) {
2235
+ globalMemoryPool = new MemoryPool(options);
2236
+ }
2237
+
2238
+ //#endregion
2239
+ //#region src/rpc/connection-manager.ts
2240
+ /**
2241
+ * ConnectionManager manages multiple RPC connections for Level 3 RPC.
2242
+ *
2243
+ * Key responsibilities:
2244
+ * 1. Maintain a pool of connections to other vats
2245
+ * 2. Handle automatic connection establishment for third-party capabilities
2246
+ * 3. Manage pending provisions (capabilities waiting to be picked up)
2247
+ * 4. Route messages to the appropriate connection
2248
+ * 5. Handle connection lifecycle (connect, disconnect, reconnect)
2249
+ */
2250
+ var ConnectionManager = class {
2251
+ options;
2252
+ connections = /* @__PURE__ */ new Map();
2253
+ pendingProvisions = /* @__PURE__ */ new Map();
2254
+ connectionPromises = /* @__PURE__ */ new Map();
2255
+ constructor(options) {
2256
+ this.options = {
2257
+ maxConnections: 100,
2258
+ idleTimeoutMs: 3e5,
2259
+ autoConnect: true,
2260
+ ...options
2261
+ };
2262
+ }
2263
+ /**
2264
+ * Register an existing connection with the manager.
2265
+ * This is called when a connection is established (either inbound or outbound).
2266
+ */
2267
+ registerConnection(vatId, connection) {
2268
+ const vatIdKey = this.vatIdToKey(vatId);
2269
+ const info = {
2270
+ connection,
2271
+ remoteVatId: vatId,
2272
+ establishedAt: /* @__PURE__ */ new Date(),
2273
+ lastActivity: /* @__PURE__ */ new Date(),
2274
+ state: "connected"
2275
+ };
2276
+ this.connections.set(vatIdKey, info);
2277
+ return info;
2278
+ }
2279
+ /**
2280
+ * Get or establish a connection to a vat.
2281
+ * If autoConnect is enabled and no connection exists, a new one will be created.
2282
+ */
2283
+ async getConnection(vatId) {
2284
+ const vatIdKey = this.vatIdToKey(vatId);
2285
+ const existing = this.connections.get(vatIdKey);
2286
+ if (existing && existing.state === "connected") {
2287
+ existing.lastActivity = /* @__PURE__ */ new Date();
2288
+ return existing.connection;
2289
+ }
2290
+ const pending = this.connectionPromises.get(vatIdKey);
2291
+ if (pending) return pending;
2292
+ if (this.options.autoConnect) return this.establishConnection(vatId);
2293
+ }
2294
+ /**
2295
+ * Establish a new connection to a vat.
2296
+ */
2297
+ async establishConnection(vatId, address) {
2298
+ const vatIdKey = this.vatIdToKey(vatId);
2299
+ if (this.connectionPromises.has(vatIdKey)) return this.connectionPromises.get(vatIdKey);
2300
+ const connectPromise = this.doEstablishConnection(vatId, address);
2301
+ this.connectionPromises.set(vatIdKey, connectPromise);
2302
+ try {
2303
+ return await connectPromise;
2304
+ } finally {
2305
+ this.connectionPromises.delete(vatIdKey);
2306
+ }
2307
+ }
2308
+ async doEstablishConnection(vatId, address) {
2309
+ const { RpcConnection } = await Promise.resolve().then(() => require("./rpc-connection-BKWQQ7f9.js")).then((n) => n.rpc_connection_exports);
2310
+ const connection = new RpcConnection(await this.options.connectionFactory(vatId, address), this.options.connectionOptions);
2311
+ await connection.start();
2312
+ this.registerConnection(vatId, connection);
2313
+ return connection;
2314
+ }
2315
+ /**
2316
+ * Close a connection to a vat.
2317
+ */
2318
+ async closeConnection(vatId) {
2319
+ const vatIdKey = this.vatIdToKey(vatId);
2320
+ const info = this.connections.get(vatIdKey);
2321
+ if (info) {
2322
+ info.state = "closing";
2323
+ await info.connection.stop();
2324
+ this.connections.delete(vatIdKey);
2325
+ }
2326
+ }
2327
+ /**
2328
+ * Close all connections.
2329
+ */
2330
+ async closeAll() {
2331
+ const closePromises = [];
2332
+ for (const [_vatIdKey, info] of this.connections) {
2333
+ info.state = "closing";
2334
+ closePromises.push(info.connection.stop().catch(() => {}));
2335
+ }
2336
+ await Promise.all(closePromises);
2337
+ this.connections.clear();
2338
+ this.pendingProvisions.clear();
2339
+ }
2340
+ /**
2341
+ * Create a pending provision for a third-party capability.
2342
+ * Called when we receive a Provide message.
2343
+ */
2344
+ createPendingProvision(provisionId, recipientId, targetExportId, questionId, embargoed) {
2345
+ const provisionKey = this.provisionIdToKey(provisionId);
2346
+ const provision = {
2347
+ provisionId,
2348
+ recipientId,
2349
+ targetExportId,
2350
+ questionId,
2351
+ createdAt: /* @__PURE__ */ new Date(),
2352
+ embargoed
2353
+ };
2354
+ this.pendingProvisions.set(provisionKey, provision);
2355
+ return provision;
2356
+ }
2357
+ /**
2358
+ * Get a pending provision by ID.
2359
+ */
2360
+ getPendingProvision(provisionId) {
2361
+ const provisionKey = this.provisionIdToKey(provisionId);
2362
+ return this.pendingProvisions.get(provisionKey);
2363
+ }
2364
+ /**
2365
+ * Remove a pending provision (when it's been accepted or expired).
2366
+ */
2367
+ removePendingProvision(provisionId) {
2368
+ const provisionKey = this.provisionIdToKey(provisionId);
2369
+ return this.pendingProvisions.delete(provisionKey);
2370
+ }
2371
+ /**
2372
+ * Find provisions for a specific recipient.
2373
+ */
2374
+ findProvisionsForRecipient(recipientId) {
2375
+ const recipientKey = this.vatIdToKey(recipientId);
2376
+ const result = [];
2377
+ for (const provision of this.pendingProvisions.values()) if (this.vatIdToKey(provision.recipientId) === recipientKey) result.push(provision);
2378
+ return result;
2379
+ }
2380
+ /**
2381
+ * Clean up expired provisions.
2382
+ */
2383
+ cleanupExpiredProvisions(maxAgeMs = 3e5) {
2384
+ const now = Date.now();
2385
+ let removed = 0;
2386
+ for (const [key, provision] of this.pendingProvisions) if (now - provision.createdAt.getTime() > maxAgeMs) {
2387
+ this.pendingProvisions.delete(key);
2388
+ removed++;
2389
+ }
2390
+ return removed;
2391
+ }
2392
+ /**
2393
+ * Resolve a third-party capability ID to a connection.
2394
+ * This is the core of Level 3 RPC - automatically establishing connections
2395
+ * to third parties when capabilities are passed between vats.
2396
+ */
2397
+ async resolveThirdPartyCap(thirdPartyCapId) {
2398
+ const parsed = this.parseThirdPartyCapId(thirdPartyCapId);
2399
+ if (!parsed) return;
2400
+ const connection = await this.getConnection(parsed.vatId);
2401
+ if (!connection) return;
2402
+ return {
2403
+ connection,
2404
+ provisionId: parsed.provisionId
2405
+ };
2406
+ }
2407
+ /**
2408
+ * Parse a ThirdPartyCapId to extract vat ID and provision ID.
2409
+ * The format is implementation-specific, but typically:
2410
+ * - First N bytes: vat ID
2411
+ * - Remaining bytes: provision ID
2412
+ */
2413
+ parseThirdPartyCapId(thirdPartyCapId) {
2414
+ const data = thirdPartyCapId.id;
2415
+ if (data.length < 32) return;
2416
+ const vatIdBytes = data.slice(0, 32);
2417
+ const provisionIdBytes = data.slice(32);
2418
+ return {
2419
+ vatId: { id: vatIdBytes },
2420
+ provisionId: { id: provisionIdBytes }
2421
+ };
2422
+ }
2423
+ /**
2424
+ * Get all active connections.
2425
+ */
2426
+ getAllConnections() {
2427
+ return Array.from(this.connections.values());
2428
+ }
2429
+ /**
2430
+ * Get the number of active connections.
2431
+ */
2432
+ getConnectionCount() {
2433
+ return this.connections.size;
2434
+ }
2435
+ /**
2436
+ * Get the number of pending provisions.
2437
+ */
2438
+ getPendingProvisionCount() {
2439
+ return this.pendingProvisions.size;
2440
+ }
2441
+ /**
2442
+ * Check if a connection exists to a vat.
2443
+ */
2444
+ hasConnection(vatId) {
2445
+ const vatIdKey = this.vatIdToKey(vatId);
2446
+ const info = this.connections.get(vatIdKey);
2447
+ return info !== void 0 && info.state === "connected";
2448
+ }
2449
+ /**
2450
+ * Update the last activity timestamp for a connection.
2451
+ */
2452
+ touchConnection(vatId) {
2453
+ const vatIdKey = this.vatIdToKey(vatId);
2454
+ const info = this.connections.get(vatIdKey);
2455
+ if (info) info.lastActivity = /* @__PURE__ */ new Date();
2456
+ }
2457
+ vatIdToKey(vatId) {
2458
+ return Array.from(vatId.id).map((b) => b.toString(16).padStart(2, "0")).join("");
2459
+ }
2460
+ provisionIdToKey(provisionId) {
2461
+ return Array.from(provisionId.id).map((b) => b.toString(16).padStart(2, "0")).join("");
2462
+ }
2463
+ };
2464
+ /**
2465
+ * Create a ThirdPartyCapId from vat ID and provision ID.
2466
+ */
2467
+ function createThirdPartyCapId(vatId, provisionId) {
2468
+ const combined = new Uint8Array(vatId.id.length + provisionId.id.length);
2469
+ combined.set(vatId.id, 0);
2470
+ combined.set(provisionId.id, vatId.id.length);
2471
+ return { id: combined };
2472
+ }
2473
+ /**
2474
+ * Create a RecipientId from a vat ID.
2475
+ */
2476
+ function createRecipientId(vatId) {
2477
+ return { id: vatId.id };
2478
+ }
2479
+ /**
2480
+ * Create a ProvisionId from raw bytes.
2481
+ */
2482
+ function createProvisionId(id) {
2483
+ return { id };
2484
+ }
2485
+ /**
2486
+ * Generate a random provision ID.
2487
+ */
2488
+ function generateProvisionId() {
2489
+ const id = new Uint8Array(32);
2490
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) crypto.getRandomValues(id);
2491
+ else {
2492
+ const { randomBytes } = require("node:crypto");
2493
+ randomBytes(32).copy(id);
2494
+ }
2495
+ return { id };
2496
+ }
2497
+ /**
2498
+ * Generate a random vat ID.
2499
+ */
2500
+ function generateVatId() {
2501
+ const id = new Uint8Array(32);
2502
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) crypto.getRandomValues(id);
2503
+ else {
2504
+ const { randomBytes } = require("node:crypto");
2505
+ randomBytes(32).copy(id);
2506
+ }
2507
+ return { id };
2508
+ }
2509
+
2510
+ //#endregion
2511
+ //#region src/rpc/level3-handlers.ts
2512
+ /**
2513
+ * Manages Level 3 RPC message handling for a connection.
2514
+ *
2515
+ * This class handles:
2516
+ * 1. Provide messages - when someone wants to give us a capability to share with a third party
2517
+ * 2. Accept messages - when a third party wants to pick up a capability we provided
2518
+ * 3. Embargo handling - breaking cycles in introduction graphs
2519
+ */
2520
+ var Level3Handlers = class {
2521
+ options;
2522
+ pendingAccepts = /* @__PURE__ */ new Map();
2523
+ embargoedCalls = /* @__PURE__ */ new Map();
2524
+ nextEmbargoId = 1;
2525
+ constructor(options) {
2526
+ this.options = options;
2527
+ }
2528
+ /**
2529
+ * Handle an incoming Provide message.
2530
+ *
2531
+ * When we receive a Provide message, it means someone wants us to hold a capability
2532
+ * and make it available to a specific third party. We:
2533
+ * 1. Create a pending provision
2534
+ * 2. Return an answer acknowledging receipt
2535
+ * 3. Wait for the third party to Accept
2536
+ */
2537
+ async handleProvide(provide) {
2538
+ const { questionId, target, recipient } = provide;
2539
+ const { connectionManager } = this.options;
2540
+ const provisionId = generateProvisionId();
2541
+ const targetExportId = this.extractTargetExportId(target);
2542
+ if (targetExportId === void 0) {
2543
+ await this.sendReturnException(questionId, "Invalid provide target: must be a hosted capability");
2544
+ return;
2545
+ }
2546
+ connectionManager.createPendingProvision(provisionId, this.recipientIdToVatId(recipient), targetExportId, questionId, false);
2547
+ if (this.options.onProvide) await this.options.onProvide(provide);
2548
+ await this.sendReturnResults(questionId, { provisionId: provisionId.id });
2549
+ }
2550
+ /**
2551
+ * Send a Provide message to offer a capability to a third party.
2552
+ *
2553
+ * This is called when we want to introduce a third party to a capability we hold.
2554
+ * For example, Alice calls this to offer Bob access to Carol's capability.
2555
+ */
2556
+ async sendProvide(target, recipient) {
2557
+ const { connection } = this.options;
2558
+ const questionId = connection.createQuestion();
2559
+ const provideMsg = {
2560
+ type: "provide",
2561
+ provide: {
2562
+ questionId,
2563
+ target,
2564
+ recipient
2565
+ }
2566
+ };
2567
+ await connection.sendCall(provideMsg.provide);
2568
+ await connection.waitForAnswer(questionId);
2569
+ return {
2570
+ questionId,
2571
+ provisionId: { id: new Uint8Array(0) }
2572
+ };
2573
+ }
2574
+ /**
2575
+ * Handle an incoming Accept message.
2576
+ *
2577
+ * When we receive an Accept message, it means a third party wants to pick up
2578
+ * a capability we previously agreed to provide. We:
2579
+ * 1. Look up the pending provision
2580
+ * 2. Verify the recipient matches
2581
+ * 3. Return the capability
2582
+ */
2583
+ async handleAccept(accept) {
2584
+ const { questionId, provision, embargo } = accept;
2585
+ const { connectionManager } = this.options;
2586
+ const pendingProvision = connectionManager.getPendingProvision(provision);
2587
+ if (!pendingProvision) {
2588
+ await this.sendReturnException(questionId, "Invalid provision ID: no pending provision found");
2589
+ return;
2590
+ }
2591
+ connectionManager.removePendingProvision(provision);
2592
+ if (embargo || pendingProvision.embargoed) {
2593
+ await this.handleEmbargoedAccept(questionId, pendingProvision);
2594
+ return;
2595
+ }
2596
+ const capDescriptor = {
2597
+ type: "senderHosted",
2598
+ exportId: pendingProvision.targetExportId
2599
+ };
2600
+ await this.sendReturnCapability(questionId, capDescriptor);
2601
+ if (this.options.onAccept) await this.options.onAccept(accept);
2602
+ }
2603
+ /**
2604
+ * Send an Accept message to pick up a capability from a third party.
2605
+ *
2606
+ * This is called when we receive a third-party capability and want to
2607
+ * establish a direct connection to use it.
2608
+ */
2609
+ async sendAccept(targetConnection, provision, embargo = false) {
2610
+ const questionId = targetConnection.createQuestion();
2611
+ const acceptMsg = {
2612
+ type: "accept",
2613
+ accept: {
2614
+ questionId,
2615
+ provision,
2616
+ embargo
2617
+ }
2618
+ };
2619
+ await targetConnection.sendCall(acceptMsg.accept);
2620
+ await targetConnection.waitForAnswer(questionId);
2621
+ return 0;
2622
+ }
2623
+ /**
2624
+ * Handle an embargoed accept.
2625
+ *
2626
+ * Embargoes are used to break cycles in the introduction graph. For example,
2627
+ * if Alice introduces Bob to Carol and Carol to Bob simultaneously, both
2628
+ * introductions use embargo=true to prevent deadlock.
2629
+ */
2630
+ async handleEmbargoedAccept(questionId, provision) {
2631
+ const pendingAccept = {
2632
+ questionId,
2633
+ provision,
2634
+ embargoId: this.nextEmbargoId++
2635
+ };
2636
+ this.pendingAccepts.set(questionId, pendingAccept);
2637
+ await this.sendReturnResultsSentElsewhere(questionId);
2638
+ }
2639
+ /**
2640
+ * Handle a Disembargo message.
2641
+ *
2642
+ * Disembargo messages are used to lift embargoes on capabilities.
2643
+ */
2644
+ async handleDisembargo(disembargo) {
2645
+ const { target, context } = disembargo;
2646
+ switch (context.type) {
2647
+ case "senderLoopback":
2648
+ await this.sendDisembargoEcho(disembargo);
2649
+ break;
2650
+ case "receiverLoopback":
2651
+ await this.liftEmbargo(context.embargoId);
2652
+ break;
2653
+ case "accept":
2654
+ await this.liftAcceptEmbargo(target);
2655
+ break;
2656
+ case "provide":
2657
+ await this.liftProvideEmbargo(context.questionId);
2658
+ break;
2659
+ }
2660
+ }
2661
+ /**
2662
+ * Lift an embargo by ID.
2663
+ */
2664
+ async liftEmbargo(embargoId) {
2665
+ const calls = this.embargoedCalls.get(embargoId);
2666
+ if (calls) {
2667
+ for (const call of calls) await this.resendEmbargoedCall(call);
2668
+ this.embargoedCalls.delete(embargoId);
2669
+ }
2670
+ }
2671
+ /**
2672
+ * Lift an embargo on an accept.
2673
+ */
2674
+ async liftAcceptEmbargo(target) {
2675
+ for (const [questionId, pendingAccept] of this.pendingAccepts) if (this.matchesTarget(pendingAccept.provision.targetExportId, target)) {
2676
+ const capDescriptor = {
2677
+ type: "senderHosted",
2678
+ exportId: pendingAccept.provision.targetExportId
2679
+ };
2680
+ await this.sendReturnCapability(pendingAccept.questionId, capDescriptor);
2681
+ this.pendingAccepts.delete(questionId);
2682
+ }
2683
+ }
2684
+ /**
2685
+ * Lift an embargo on a provide.
2686
+ */
2687
+ async liftProvideEmbargo(_questionId) {
2688
+ const { connectionManager } = this.options;
2689
+ for (const _provision of connectionManager.getAllConnections());
2690
+ }
2691
+ /**
2692
+ * Handle receiving a third-party capability.
2693
+ *
2694
+ * When we receive a CapDescriptor with type 'thirdPartyHosted', we need to:
2695
+ * 1. Establish a connection to the third party (if not already connected)
2696
+ * 2. Send an Accept message to pick up the capability
2697
+ * 3. Return a local import ID for the capability
2698
+ */
2699
+ async handleThirdPartyCapability(thirdPartyCapId) {
2700
+ const { connectionManager } = this.options;
2701
+ const resolved = await connectionManager.resolveThirdPartyCap(thirdPartyCapId);
2702
+ if (!resolved) return;
2703
+ const { connection, provisionId } = resolved;
2704
+ return await this.sendAccept(connection, provisionId);
2705
+ }
2706
+ /**
2707
+ * Create a third-party capability descriptor.
2708
+ *
2709
+ * This is called when we want to pass a capability to a peer, but the capability
2710
+ * is actually hosted by a third party. We create a ThirdPartyCapId that allows
2711
+ * the recipient to connect directly to the third party.
2712
+ */
2713
+ createThirdPartyCapDescriptor(_hostedConnection, exportId, recipientVatId) {
2714
+ const { connectionManager, selfVatId } = this.options;
2715
+ const provisionId = generateProvisionId();
2716
+ const thirdPartyCapId = createThirdPartyCapId(selfVatId, provisionId);
2717
+ connectionManager.createPendingProvision(provisionId, recipientVatId, exportId, 0, false);
2718
+ return {
2719
+ type: "thirdPartyHosted",
2720
+ thirdPartyCapId
2721
+ };
2722
+ }
2723
+ extractTargetExportId(target) {
2724
+ if (target.type === "importedCap") return target.importId;
2725
+ }
2726
+ recipientIdToVatId(recipient) {
2727
+ return { id: recipient.id };
2728
+ }
2729
+ matchesTarget(exportId, target) {
2730
+ if (target.type === "importedCap") return target.importId === exportId;
2731
+ return false;
2732
+ }
2733
+ async sendReturnResults(questionId, _results) {
2734
+ const { connection } = this.options;
2735
+ const returnMsg = {
2736
+ type: "return",
2737
+ return: {
2738
+ answerId: questionId,
2739
+ releaseParamCaps: true,
2740
+ noFinishNeeded: false,
2741
+ result: {
2742
+ type: "results",
2743
+ payload: {
2744
+ content: new Uint8Array(0),
2745
+ capTable: []
2746
+ }
2747
+ }
2748
+ }
2749
+ };
2750
+ await connection.sendReturn(returnMsg.return);
2751
+ }
2752
+ async sendReturnCapability(questionId, cap) {
2753
+ const { connection } = this.options;
2754
+ const returnMsg = {
2755
+ type: "return",
2756
+ return: {
2757
+ answerId: questionId,
2758
+ releaseParamCaps: true,
2759
+ noFinishNeeded: false,
2760
+ result: {
2761
+ type: "results",
2762
+ payload: {
2763
+ content: new Uint8Array(0),
2764
+ capTable: [cap]
2765
+ }
2766
+ }
2767
+ }
2768
+ };
2769
+ await connection.sendReturn(returnMsg.return);
2770
+ }
2771
+ async sendReturnException(questionId, reason) {
2772
+ const { connection } = this.options;
2773
+ const returnMsg = {
2774
+ type: "return",
2775
+ return: {
2776
+ answerId: questionId,
2777
+ releaseParamCaps: true,
2778
+ noFinishNeeded: false,
2779
+ result: {
2780
+ type: "exception",
2781
+ exception: {
2782
+ reason,
2783
+ type: "failed"
2784
+ }
2785
+ }
2786
+ }
2787
+ };
2788
+ await connection.sendReturn(returnMsg.return);
2789
+ }
2790
+ async sendReturnResultsSentElsewhere(questionId) {
2791
+ const { connection } = this.options;
2792
+ const returnMsg = {
2793
+ type: "return",
2794
+ return: {
2795
+ answerId: questionId,
2796
+ releaseParamCaps: true,
2797
+ noFinishNeeded: false,
2798
+ result: { type: "resultsSentElsewhere" }
2799
+ }
2800
+ };
2801
+ await connection.sendReturn(returnMsg.return);
2802
+ }
2803
+ async sendDisembargoEcho(disembargo) {
2804
+ const { connection } = this.options;
2805
+ if (disembargo.context.type !== "senderLoopback") return;
2806
+ const echoMsg = {
2807
+ type: "disembargo",
2808
+ disembargo: {
2809
+ target: disembargo.target,
2810
+ context: {
2811
+ type: "receiverLoopback",
2812
+ embargoId: disembargo.context.embargoId
2813
+ }
2814
+ }
2815
+ };
2816
+ await connection.sendDisembargo(echoMsg.disembargo);
2817
+ }
2818
+ async resendEmbargoedCall(_call) {}
2819
+ };
2820
+
2821
+ //#endregion
2822
+ //#region src/rpc/level4-types.ts
2823
+ /**
2824
+ * Default join options.
2825
+ */
2826
+ const DEFAULT_JOIN_OPTIONS = {
2827
+ timeoutMs: 3e4,
2828
+ requireCryptoVerification: true,
2829
+ cacheResult: true,
2830
+ cacheTtlMs: 3e5
2831
+ };
2832
+ /**
2833
+ * Default escrow configuration.
2834
+ */
2835
+ const DEFAULT_ESCROW_CONFIG = {
2836
+ enabled: false,
2837
+ requiredParties: 2,
2838
+ timeoutMs: 6e4
2839
+ };
2840
+ /**
2841
+ * Default join security policy.
2842
+ */
2843
+ const DEFAULT_JOIN_SECURITY_POLICY = {
2844
+ verifyIdentityHashes: true,
2845
+ checkRevocation: true,
2846
+ maxProxyDepth: 10,
2847
+ auditLog: true,
2848
+ allowedVats: []
2849
+ };
2850
+
2851
+ //#endregion
2852
+ //#region src/rpc/level4-handlers.ts
2853
+ /**
2854
+ * Manages Level 4 RPC message handling for reference equality verification.
2855
+ *
2856
+ * This class handles:
2857
+ * 1. Join messages - verifying that two capabilities point to the same object
2858
+ * 2. Object identity tracking and caching
2859
+ * 3. Escrow agent functionality for consensus verification
2860
+ * 4. Security verification (anti-spoofing)
2861
+ *
2862
+ * ## Usage Example
2863
+ *
2864
+ * ```typescript
2865
+ * const level4Handlers = new Level4Handlers({
2866
+ * connection,
2867
+ * connectionManager,
2868
+ * level3Handlers,
2869
+ * selfVatId,
2870
+ * });
2871
+ *
2872
+ * // Enable escrow mode for consensus verification
2873
+ * level4Handlers.setEscrowConfig({
2874
+ * enabled: true,
2875
+ * requiredParties: 2,
2876
+ * });
2877
+ *
2878
+ * // Send a Join request
2879
+ * const result = await level4Handlers.sendJoin(target1, target2);
2880
+ * if (result.equal) {
2881
+ * console.log('Capabilities point to the same object!');
2882
+ * }
2883
+ * ```
2884
+ */
2885
+ var Level4Handlers = class {
2886
+ options;
2887
+ pendingJoins = /* @__PURE__ */ new Map();
2888
+ joinResultsCache = /* @__PURE__ */ new Map();
2889
+ objectIdentities = /* @__PURE__ */ new Map();
2890
+ nextJoinId = 1;
2891
+ escrowConfig;
2892
+ securityPolicy;
2893
+ joinOptions;
2894
+ escrowParties = /* @__PURE__ */ new Map();
2895
+ escrowConsensus;
2896
+ constructor(options) {
2897
+ this.options = options;
2898
+ this.escrowConfig = {
2899
+ ...DEFAULT_ESCROW_CONFIG,
2900
+ ...options.escrowConfig
2901
+ };
2902
+ this.securityPolicy = {
2903
+ ...DEFAULT_JOIN_SECURITY_POLICY,
2904
+ ...options.securityPolicy
2905
+ };
2906
+ this.joinOptions = {
2907
+ ...DEFAULT_JOIN_OPTIONS,
2908
+ ...options.joinOptions
2909
+ };
2910
+ }
2911
+ /**
2912
+ * Handle an incoming Join message.
2913
+ *
2914
+ * When we receive a Join message, we need to verify whether the two
2915
+ * capability references point to the same underlying object.
2916
+ *
2917
+ * The verification process:
2918
+ * 1. Resolve both targets to their underlying objects
2919
+ * 2. Compare object identities (vat ID + object ID)
2920
+ * 3. Optionally verify identity hashes cryptographically
2921
+ * 4. Return the result
2922
+ */
2923
+ async handleJoin(join) {
2924
+ const { questionId, target, otherCap, joinId } = join;
2925
+ try {
2926
+ const cacheKey = this.getCacheKey(target, otherCap);
2927
+ const cached = this.joinResultsCache.get(cacheKey);
2928
+ if (cached && Date.now() - cached.cachedAt < this.joinOptions.cacheTtlMs) {
2929
+ await this.sendJoinResult(questionId, cached.result);
2930
+ return;
2931
+ }
2932
+ const identity1 = await this.resolveTargetToIdentity(target);
2933
+ const identity2 = await this.resolveTargetToIdentity(otherCap);
2934
+ const result = this.compareIdentities(identity1, identity2, joinId);
2935
+ if (this.joinOptions.cacheResult) this.joinResultsCache.set(cacheKey, {
2936
+ result,
2937
+ cachedAt: Date.now(),
2938
+ targets: [this.hashTarget(target), this.hashTarget(otherCap)]
2939
+ });
2940
+ if (this.securityPolicy.auditLog) this.logJoinOperation(target, otherCap, result);
2941
+ await this.sendJoinResult(questionId, result);
2942
+ if (this.options.onJoin) await this.options.onJoin(join);
2943
+ } catch (error) {
2944
+ await this.sendJoinException(questionId, error instanceof Error ? error.message : "Join operation failed");
2945
+ }
2946
+ }
2947
+ /**
2948
+ * Send a Join message to verify that two capabilities point to the same object.
2949
+ *
2950
+ * @param target1 First capability target
2951
+ * @param target2 Second capability target
2952
+ * @returns Promise resolving to the join result
2953
+ */
2954
+ async sendJoin(target1, target2) {
2955
+ const { connection } = this.options;
2956
+ const joinId = this.nextJoinId++;
2957
+ const questionId = connection.createQuestion();
2958
+ const pendingJoin = {
2959
+ joinId,
2960
+ target1,
2961
+ target2,
2962
+ startedAt: Date.now(),
2963
+ resolve: () => {},
2964
+ reject: () => {}
2965
+ };
2966
+ const completionPromise = new Promise((resolve, reject) => {
2967
+ pendingJoin.resolve = resolve;
2968
+ pendingJoin.reject = reject;
2969
+ });
2970
+ this.pendingJoins.set(joinId, pendingJoin);
2971
+ const timeoutMs = this.joinOptions.timeoutMs;
2972
+ const timeoutId = setTimeout(() => {
2973
+ this.pendingJoins.delete(joinId);
2974
+ pendingJoin.reject(/* @__PURE__ */ new Error(`Join operation timed out after ${timeoutMs}ms`));
2975
+ }, timeoutMs);
2976
+ const originalResolve = pendingJoin.resolve;
2977
+ pendingJoin.resolve = (result) => {
2978
+ clearTimeout(timeoutId);
2979
+ this.pendingJoins.delete(joinId);
2980
+ originalResolve(result);
2981
+ };
2982
+ try {
2983
+ const joinMsg = {
2984
+ type: "join",
2985
+ join: {
2986
+ questionId,
2987
+ target: target1,
2988
+ otherCap: target2,
2989
+ joinId
2990
+ }
2991
+ };
2992
+ await connection.sendCall(joinMsg.join);
2993
+ return await completionPromise;
2994
+ } catch (error) {
2995
+ clearTimeout(timeoutId);
2996
+ this.pendingJoins.delete(joinId);
2997
+ throw error;
2998
+ }
2999
+ }
3000
+ /**
3001
+ * Complete a pending join operation with the result.
3002
+ * This is called when we receive a Return message for a Join.
3003
+ */
3004
+ completeJoin(joinId, result) {
3005
+ const pending = this.pendingJoins.get(joinId);
3006
+ if (pending) {
3007
+ pending.resolve(result);
3008
+ this.pendingJoins.delete(joinId);
3009
+ }
3010
+ }
3011
+ /**
3012
+ * Resolve a MessageTarget to its ObjectIdentity.
3013
+ *
3014
+ * This may involve:
3015
+ * 1. Looking up local exports
3016
+ * 2. Resolving promises
3017
+ * 3. Following third-party capabilities
3018
+ * 4. Verifying proxy chains
3019
+ */
3020
+ async resolveTargetToIdentity(target) {
3021
+ if (target.type === "importedCap") {
3022
+ const cached = this.objectIdentities.get(target.importId);
3023
+ if (cached) return cached;
3024
+ if (!this.options.connection.getImport(target.importId)) return null;
3025
+ return null;
3026
+ }
3027
+ if (target.type === "promisedAnswer") {
3028
+ const { questionId } = target.promisedAnswer;
3029
+ try {
3030
+ await this.options.connection.waitForAnswer(questionId);
3031
+ return null;
3032
+ } catch {
3033
+ return null;
3034
+ }
3035
+ }
3036
+ return null;
3037
+ }
3038
+ /**
3039
+ * Compare two object identities for equality.
3040
+ */
3041
+ compareIdentities(identity1, identity2, joinId) {
3042
+ if (!identity1 && !identity2) return {
3043
+ equal: true,
3044
+ joinId
3045
+ };
3046
+ if (!identity1 || !identity2) return {
3047
+ equal: false,
3048
+ joinId,
3049
+ inequalityReason: "One capability is null, the other is not"
3050
+ };
3051
+ if (!this.arraysEqual(identity1.vatId, identity2.vatId)) return {
3052
+ equal: false,
3053
+ joinId,
3054
+ inequalityReason: "Capabilities hosted by different vats"
3055
+ };
3056
+ if (!this.arraysEqual(identity1.objectId, identity2.objectId)) return {
3057
+ equal: false,
3058
+ joinId,
3059
+ inequalityReason: "Different object IDs within the same vat"
3060
+ };
3061
+ if (this.securityPolicy.verifyIdentityHashes) {
3062
+ if (identity1.identityHash && identity2.identityHash) {
3063
+ if (!this.arraysEqual(identity1.identityHash, identity2.identityHash)) return {
3064
+ equal: false,
3065
+ joinId,
3066
+ inequalityReason: "Identity hash mismatch (possible spoofing attempt)"
3067
+ };
3068
+ }
3069
+ }
3070
+ return {
3071
+ equal: true,
3072
+ joinId,
3073
+ identity: identity1
3074
+ };
3075
+ }
3076
+ /**
3077
+ * Set the escrow configuration.
3078
+ */
3079
+ setEscrowConfig(config) {
3080
+ this.escrowConfig = {
3081
+ ...this.escrowConfig,
3082
+ ...config
3083
+ };
3084
+ }
3085
+ /**
3086
+ * Register a party in an escrow consensus verification.
3087
+ *
3088
+ * This is used when multiple parties need to verify they are referring
3089
+ * to the same object (e.g., in a trade or agreement).
3090
+ *
3091
+ * @param partyId Unique identifier for the party
3092
+ * @param target The capability reference from this party
3093
+ * @returns Whether consensus has been reached
3094
+ */
3095
+ async registerEscrowParty(partyId, target) {
3096
+ if (!this.escrowConfig.enabled) throw new Error("Escrow mode is not enabled");
3097
+ if (this.escrowParties.has(partyId)) throw new Error(`Party ${partyId} is already registered`);
3098
+ this.escrowParties.set(partyId, { target });
3099
+ if (this.escrowParties.size >= this.escrowConfig.requiredParties) {
3100
+ const consensus = await this.verifyEscrowConsensus();
3101
+ if (consensus.consensus) {
3102
+ this.escrowConsensus = {
3103
+ identity: consensus.identity,
3104
+ parties: Array.from(this.escrowParties.keys())
3105
+ };
3106
+ if (this.escrowConfig.onConsensus) this.escrowConfig.onConsensus(consensus.identity, Array.from(this.escrowParties.keys()));
3107
+ } else if (this.escrowConfig.onConsensusFailure) this.escrowConfig.onConsensusFailure(consensus.reason, Array.from(this.escrowParties.keys()));
3108
+ return {
3109
+ consensus: consensus.consensus,
3110
+ identity: consensus.identity
3111
+ };
3112
+ }
3113
+ return { consensus: false };
3114
+ }
3115
+ /**
3116
+ * Verify that all registered escrow parties refer to the same object.
3117
+ */
3118
+ async verifyEscrowConsensus() {
3119
+ const parties = Array.from(this.escrowParties.entries());
3120
+ if (parties.length < this.escrowConfig.requiredParties) return {
3121
+ consensus: false,
3122
+ reason: "Not enough parties registered"
3123
+ };
3124
+ const [firstPartyId, firstParty] = parties[0];
3125
+ const firstIdentity = await this.resolveTargetToIdentity(firstParty.target);
3126
+ if (!firstIdentity) return {
3127
+ consensus: false,
3128
+ reason: `Could not resolve identity for party ${firstPartyId}`
3129
+ };
3130
+ for (const [partyId, party] of parties.slice(1)) {
3131
+ const identity = await this.resolveTargetToIdentity(party.target);
3132
+ const comparison = this.compareIdentities(firstIdentity, identity, 0);
3133
+ if (!comparison.equal) return {
3134
+ consensus: false,
3135
+ reason: `Party ${partyId} refers to a different object: ${comparison.inequalityReason}`
3136
+ };
3137
+ }
3138
+ return {
3139
+ consensus: true,
3140
+ identity: firstIdentity
3141
+ };
3142
+ }
3143
+ /**
3144
+ * Clear all escrow state.
3145
+ */
3146
+ clearEscrow() {
3147
+ this.escrowParties.clear();
3148
+ this.escrowConsensus = void 0;
3149
+ }
3150
+ /**
3151
+ * Get the current escrow consensus if reached.
3152
+ */
3153
+ getEscrowConsensus() {
3154
+ return this.escrowConsensus;
3155
+ }
3156
+ /**
3157
+ * Set the security policy.
3158
+ */
3159
+ setSecurityPolicy(policy) {
3160
+ this.securityPolicy = {
3161
+ ...this.securityPolicy,
3162
+ ...policy
3163
+ };
3164
+ }
3165
+ /**
3166
+ * Verify that a vat is allowed to participate in join operations.
3167
+ */
3168
+ isVatAllowed(vatId) {
3169
+ if (this.securityPolicy.allowedVats.length === 0) return true;
3170
+ return this.securityPolicy.allowedVats.some((allowed) => this.arraysEqual(allowed, vatId));
3171
+ }
3172
+ /**
3173
+ * Generate a cryptographic identity hash for an object.
3174
+ *
3175
+ * This creates a verifiable fingerprint of the object's identity
3176
+ * that can be used to detect spoofing attempts.
3177
+ */
3178
+ async generateIdentityHash(vatId, objectId) {
3179
+ const combined = new Uint8Array(vatId.length + objectId.length);
3180
+ combined.set(vatId, 0);
3181
+ combined.set(objectId, vatId.length);
3182
+ if (typeof crypto !== "undefined" && crypto.subtle) {
3183
+ const hashBuffer = await crypto.subtle.digest("SHA-256", combined);
3184
+ return new Uint8Array(hashBuffer);
3185
+ }
3186
+ const { createHash } = require("node:crypto");
3187
+ const hash = createHash("sha256");
3188
+ hash.update(combined);
3189
+ return hash.digest();
3190
+ }
3191
+ /**
3192
+ * Clear the join results cache.
3193
+ */
3194
+ clearCache() {
3195
+ this.joinResultsCache.clear();
3196
+ }
3197
+ /**
3198
+ * Clean up expired cache entries.
3199
+ */
3200
+ cleanupExpiredCache() {
3201
+ const now = Date.now();
3202
+ let removed = 0;
3203
+ for (const [key, entry] of this.joinResultsCache) if (now - entry.cachedAt > this.joinOptions.cacheTtlMs) {
3204
+ this.joinResultsCache.delete(key);
3205
+ removed++;
3206
+ }
3207
+ return removed;
3208
+ }
3209
+ /**
3210
+ * Get cache statistics.
3211
+ */
3212
+ getCacheStats() {
3213
+ return {
3214
+ size: this.joinResultsCache.size,
3215
+ hitRate: 0
3216
+ };
3217
+ }
3218
+ getCacheKey(target1, target2) {
3219
+ const sorted = [this.hashTarget(target1), this.hashTarget(target2)].sort();
3220
+ return `join:${sorted[0]}:${sorted[1]}`;
3221
+ }
3222
+ hashTarget(target) {
3223
+ if (target.type === "importedCap") return `import:${target.importId}`;
3224
+ if (target.type === "promisedAnswer") return `answer:${target.promisedAnswer.questionId}`;
3225
+ return "unknown";
3226
+ }
3227
+ arraysEqual(a, b) {
3228
+ if (a.length !== b.length) return false;
3229
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
3230
+ return true;
3231
+ }
3232
+ async sendJoinResult(questionId, result) {
3233
+ const { connection } = this.options;
3234
+ const returnMsg = {
3235
+ type: "return",
3236
+ return: {
3237
+ answerId: questionId,
3238
+ releaseParamCaps: true,
3239
+ noFinishNeeded: false,
3240
+ result: {
3241
+ type: "results",
3242
+ payload: {
3243
+ content: this.serializeJoinResult(result),
3244
+ capTable: []
3245
+ }
3246
+ }
3247
+ }
3248
+ };
3249
+ await connection.sendReturn(returnMsg.return);
3250
+ }
3251
+ async sendJoinException(questionId, reason) {
3252
+ const { connection } = this.options;
3253
+ const returnMsg = {
3254
+ type: "return",
3255
+ return: {
3256
+ answerId: questionId,
3257
+ releaseParamCaps: true,
3258
+ noFinishNeeded: false,
3259
+ result: {
3260
+ type: "exception",
3261
+ exception: {
3262
+ reason,
3263
+ type: "failed"
3264
+ }
3265
+ }
3266
+ }
3267
+ };
3268
+ await connection.sendReturn(returnMsg.return);
3269
+ }
3270
+ serializeJoinResult(result) {
3271
+ const obj = {
3272
+ equal: result.equal,
3273
+ joinId: result.joinId,
3274
+ inequalityReason: result.inequalityReason
3275
+ };
3276
+ return new TextEncoder().encode(JSON.stringify(obj));
3277
+ }
3278
+ logJoinOperation(target1, target2, result) {
3279
+ console.log("[Level4] Join operation:", {
3280
+ target1: this.hashTarget(target1),
3281
+ target2: this.hashTarget(target2),
3282
+ equal: result.equal,
3283
+ joinId: result.joinId,
3284
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
3285
+ });
3286
+ }
3287
+ };
3288
+
3289
+ //#endregion
3290
+ //#region src/rpc/stream.ts
3291
+ /** Stream priority levels */
3292
+ let StreamPriority = /* @__PURE__ */ function(StreamPriority) {
3293
+ StreamPriority[StreamPriority["CRITICAL"] = 0] = "CRITICAL";
3294
+ StreamPriority[StreamPriority["HIGH"] = 1] = "HIGH";
3295
+ StreamPriority[StreamPriority["NORMAL"] = 2] = "NORMAL";
3296
+ StreamPriority[StreamPriority["LOW"] = 3] = "LOW";
3297
+ StreamPriority[StreamPriority["BACKGROUND"] = 4] = "BACKGROUND";
3298
+ return StreamPriority;
3299
+ }({});
3300
+ /** Default flow control configuration */
3301
+ const DEFAULT_FLOW_CONTROL = {
3302
+ initialWindowSize: 65536,
3303
+ maxWindowSize: 1048576,
3304
+ minWindowSize: 4096,
3305
+ windowUpdateThreshold: 16384,
3306
+ windowUpdateIncrement: 32768
3307
+ };
3308
+ /**
3309
+ * Stream abstraction for Cap'n Proto RPC
3310
+ *
3311
+ * Manages bidirectional streaming with flow control and backpressure.
3312
+ */
3313
+ var Stream = class {
3314
+ options;
3315
+ handlers;
3316
+ state = "connecting";
3317
+ error;
3318
+ sendWindow;
3319
+ receiveWindow;
3320
+ flowControlConfig;
3321
+ sendBuffer = [];
3322
+ receiveBuffer = [];
3323
+ maxBufferSize = 1048576;
3324
+ bytesSent = 0;
3325
+ bytesReceived = 0;
3326
+ totalBytesExpected;
3327
+ lastProgressUpdate = 0;
3328
+ progressUpdateInterval;
3329
+ transferStartTime;
3330
+ nextSendSequence = 0;
3331
+ nextExpectedSequence = 0;
3332
+ openResolver;
3333
+ openRejector;
3334
+ closeResolver;
3335
+ constructor(options, handlers = {}) {
3336
+ this.options = options;
3337
+ this.handlers = handlers;
3338
+ this.flowControlConfig = {
3339
+ ...DEFAULT_FLOW_CONTROL,
3340
+ ...options.flowControl
3341
+ };
3342
+ this.sendWindow = {
3343
+ currentSize: this.flowControlConfig.initialWindowSize,
3344
+ maxSize: this.flowControlConfig.maxWindowSize,
3345
+ bytesInWindow: 0,
3346
+ backpressureActive: false
3347
+ };
3348
+ this.receiveWindow = {
3349
+ currentSize: this.flowControlConfig.initialWindowSize,
3350
+ maxSize: this.flowControlConfig.maxWindowSize,
3351
+ bytesInWindow: 0,
3352
+ backpressureActive: false
3353
+ };
3354
+ this.progressUpdateInterval = options.progressInterval ?? 65536;
3355
+ }
3356
+ /** Get stream ID */
3357
+ get id() {
3358
+ return this.options.streamId;
3359
+ }
3360
+ /** Get stream direction */
3361
+ get direction() {
3362
+ return this.options.direction;
3363
+ }
3364
+ /** Get stream priority */
3365
+ get priority() {
3366
+ return this.options.priority ?? StreamPriority.NORMAL;
3367
+ }
3368
+ /** Get current stream state */
3369
+ get currentState() {
3370
+ return this.state;
3371
+ }
3372
+ /** Get whether stream is open */
3373
+ get isOpen() {
3374
+ return this.state === "open";
3375
+ }
3376
+ /** Get whether backpressure is active for sending */
3377
+ get isBackpressureActive() {
3378
+ return this.sendWindow.backpressureActive;
3379
+ }
3380
+ /** Get bytes sent */
3381
+ get bytesSentCount() {
3382
+ return this.bytesSent;
3383
+ }
3384
+ /** Get bytes received */
3385
+ get bytesReceivedCount() {
3386
+ return this.bytesReceived;
3387
+ }
3388
+ /** Get metadata */
3389
+ get metadata() {
3390
+ return this.options.metadata;
3391
+ }
3392
+ /**
3393
+ * Open the stream
3394
+ */
3395
+ async open() {
3396
+ if (this.state !== "connecting") throw new Error(`Cannot open stream in state: ${this.state}`);
3397
+ return new Promise((resolve, reject) => {
3398
+ this.openResolver = resolve;
3399
+ this.openRejector = reject;
3400
+ this.transitionState("open");
3401
+ this.transferStartTime = Date.now();
3402
+ this.handlers.onOpen?.();
3403
+ });
3404
+ }
3405
+ /**
3406
+ * Send data through the stream
3407
+ *
3408
+ * Respects flow control and handles backpressure.
3409
+ */
3410
+ async send(data, endOfStream = false) {
3411
+ if (this.state !== "open") throw new Error(`Cannot send in state: ${this.state}`);
3412
+ if (this.sendWindow.bytesInWindow + data.length > this.sendWindow.currentSize) await this.waitForWindowUpdate();
3413
+ const chunk = {
3414
+ data,
3415
+ endOfStream,
3416
+ sequenceNumber: this.nextSendSequence++,
3417
+ timestamp: Date.now()
3418
+ };
3419
+ this.sendWindow.bytesInWindow += data.length;
3420
+ this.bytesSent += data.length;
3421
+ this.checkBackpressure();
3422
+ await this.sendChunk(chunk);
3423
+ this.reportProgress();
3424
+ }
3425
+ /**
3426
+ * Send a chunk of data
3427
+ *
3428
+ * Override in subclasses to implement actual transport.
3429
+ */
3430
+ async sendChunk(chunk) {
3431
+ this.sendBuffer.push(chunk);
3432
+ }
3433
+ /**
3434
+ * Receive data from the stream
3435
+ *
3436
+ * Returns buffered data or waits for new data.
3437
+ */
3438
+ async receive() {
3439
+ if (this.receiveBuffer.length > 0) return this.receiveBuffer.shift();
3440
+ if (this.state === "closed") return null;
3441
+ return new Promise((resolve, reject) => {
3442
+ const checkBuffer = () => {
3443
+ if (this.receiveBuffer.length > 0) resolve(this.receiveBuffer.shift());
3444
+ else if (this.state === "closed") resolve(null);
3445
+ else if (this.state === "error") reject(this.error ?? /* @__PURE__ */ new Error("Stream error"));
3446
+ else setTimeout(checkBuffer, 10);
3447
+ };
3448
+ checkBuffer();
3449
+ });
3450
+ }
3451
+ /**
3452
+ * Handle incoming chunk from transport
3453
+ */
3454
+ handleIncomingChunk(chunk) {
3455
+ if (this.state !== "open" && this.state !== "closing") return;
3456
+ this.receiveWindow.bytesInWindow += chunk.data.length;
3457
+ this.bytesReceived += chunk.data.length;
3458
+ this.checkReceiveWindow();
3459
+ if (this.handlers.onData) Promise.resolve(this.handlers.onData(chunk)).catch((err) => {
3460
+ this.handleError(err);
3461
+ });
3462
+ else this.receiveBuffer.push(chunk);
3463
+ this.reportProgress();
3464
+ if (chunk.endOfStream) this.transitionState("closing");
3465
+ }
3466
+ /**
3467
+ * Update the send window (called when receiving window update from peer)
3468
+ */
3469
+ updateSendWindow(increment) {
3470
+ this.sendWindow.currentSize = Math.min(this.sendWindow.currentSize + increment, this.sendWindow.maxSize);
3471
+ if (this.sendWindow.backpressureActive) {
3472
+ if (this.sendWindow.currentSize - this.sendWindow.bytesInWindow >= this.flowControlConfig.minWindowSize) {
3473
+ this.sendWindow.backpressureActive = false;
3474
+ this.handlers.onBackpressure?.(false);
3475
+ }
3476
+ }
3477
+ }
3478
+ /**
3479
+ * Acknowledge received bytes (called to update peer's send window)
3480
+ */
3481
+ acknowledgeBytes(bytes) {
3482
+ this.receiveWindow.bytesInWindow = Math.max(0, this.receiveWindow.bytesInWindow - bytes);
3483
+ if (this.receiveWindow.bytesInWindow < this.flowControlConfig.windowUpdateThreshold) this.sendWindowUpdate();
3484
+ }
3485
+ /**
3486
+ * Close the stream gracefully
3487
+ */
3488
+ async close() {
3489
+ if (this.state === "closed" || this.state === "closing") return;
3490
+ this.transitionState("closing");
3491
+ await this.drainSendBuffer();
3492
+ await this.sendChunk({
3493
+ data: new Uint8Array(0),
3494
+ endOfStream: true
3495
+ });
3496
+ this.transitionState("closed");
3497
+ this.handlers.onClose?.();
3498
+ }
3499
+ /**
3500
+ * Abort the stream with an error
3501
+ */
3502
+ abort(error) {
3503
+ this.error = error;
3504
+ this.transitionState("error");
3505
+ this.handlers.onError?.(error);
3506
+ }
3507
+ /**
3508
+ * Set total bytes expected (for progress calculation)
3509
+ */
3510
+ setTotalBytesExpected(total) {
3511
+ this.totalBytesExpected = total;
3512
+ }
3513
+ /**
3514
+ * Wait for the stream to be ready for sending
3515
+ */
3516
+ async ready() {
3517
+ if (this.state === "open" && !this.sendWindow.backpressureActive) return;
3518
+ if (this.state !== "open") throw new Error(`Stream not open: ${this.state}`);
3519
+ return this.waitForWindowUpdate();
3520
+ }
3521
+ transitionState(newState) {
3522
+ this.state;
3523
+ this.state = newState;
3524
+ if (newState === "open" && this.openResolver) {
3525
+ this.openResolver();
3526
+ this.openResolver = void 0;
3527
+ this.openRejector = void 0;
3528
+ } else if (newState === "error" && this.openRejector) {
3529
+ this.openRejector(this.error ?? /* @__PURE__ */ new Error("Stream error"));
3530
+ this.openResolver = void 0;
3531
+ this.openRejector = void 0;
3532
+ }
3533
+ if (newState === "closed" && this.closeResolver) {
3534
+ this.closeResolver();
3535
+ this.closeResolver = void 0;
3536
+ }
3537
+ }
3538
+ checkBackpressure() {
3539
+ if (this.sendWindow.currentSize - this.sendWindow.bytesInWindow < this.flowControlConfig.minWindowSize && !this.sendWindow.backpressureActive) {
3540
+ this.sendWindow.backpressureActive = true;
3541
+ this.handlers.onBackpressure?.(true);
3542
+ }
3543
+ }
3544
+ checkReceiveWindow() {
3545
+ if (this.receiveWindow.bytesInWindow < this.flowControlConfig.windowUpdateThreshold) this.sendWindowUpdate();
3546
+ }
3547
+ async waitForWindowUpdate() {
3548
+ return new Promise((resolve, reject) => {
3549
+ const checkWindow = () => {
3550
+ const available = this.sendWindow.currentSize - this.sendWindow.bytesInWindow;
3551
+ if (this.state === "error") {
3552
+ reject(this.error ?? /* @__PURE__ */ new Error("Stream error"));
3553
+ return;
3554
+ }
3555
+ if (this.state !== "open") {
3556
+ reject(/* @__PURE__ */ new Error("Stream closed"));
3557
+ return;
3558
+ }
3559
+ if (available >= this.flowControlConfig.minWindowSize) {
3560
+ resolve();
3561
+ return;
3562
+ }
3563
+ setTimeout(checkWindow, 10);
3564
+ };
3565
+ checkWindow();
3566
+ });
3567
+ }
3568
+ async drainSendBuffer() {
3569
+ this.sendBuffer.length = 0;
3570
+ }
3571
+ sendWindowUpdate() {}
3572
+ reportProgress() {
3573
+ if (!this.options.enableProgress || !this.handlers.onProgress) return;
3574
+ const now = Date.now();
3575
+ const bytesTransferred = Math.max(this.bytesSent, this.bytesReceived);
3576
+ if (bytesTransferred - this.lastProgressUpdate < this.progressUpdateInterval) return;
3577
+ this.lastProgressUpdate = bytesTransferred;
3578
+ let transferRate;
3579
+ if (this.transferStartTime) {
3580
+ const elapsed = (now - this.transferStartTime) / 1e3;
3581
+ if (elapsed > 0) transferRate = bytesTransferred / elapsed;
3582
+ }
3583
+ let percentage;
3584
+ let estimatedTimeRemaining;
3585
+ if (this.totalBytesExpected && this.totalBytesExpected > 0) {
3586
+ percentage = Math.min(100, bytesTransferred / this.totalBytesExpected * 100);
3587
+ if (transferRate && transferRate > 0) estimatedTimeRemaining = (this.totalBytesExpected - bytesTransferred) / transferRate * 1e3;
3588
+ }
3589
+ const progress = {
3590
+ streamId: this.id,
3591
+ bytesTransferred,
3592
+ totalBytes: this.totalBytesExpected,
3593
+ percentage,
3594
+ transferRate,
3595
+ estimatedTimeRemaining
3596
+ };
3597
+ this.handlers.onProgress(progress);
3598
+ }
3599
+ handleError(error) {
3600
+ this.error = error;
3601
+ this.transitionState("error");
3602
+ this.handlers.onError?.(error);
3603
+ }
3604
+ };
3605
+ /**
3606
+ * Create a new stream
3607
+ */
3608
+ function createStream(options, handlers) {
3609
+ return new Stream(options, handlers);
3610
+ }
3611
+ /**
3612
+ * Check if an object is a Stream
3613
+ */
3614
+ function isStream(obj) {
3615
+ return obj instanceof Stream;
3616
+ }
3617
+
3618
+ //#endregion
3619
+ //#region src/rpc/bulk.ts
3620
+ /** Default bulk transfer configuration */
3621
+ const DEFAULT_BULK_CONFIG = {
3622
+ chunkSize: 16384,
3623
+ enableProgress: true,
3624
+ progressInterval: 65536,
3625
+ maxConcurrentChunks: 8,
3626
+ chunkAckTimeoutMs: 3e4
3627
+ };
3628
+ /**
3629
+ * Bulk transfer manager
3630
+ *
3631
+ * Manages high-volume data transfers with flow control and backpressure.
3632
+ */
3633
+ var BulkTransfer = class {
3634
+ stream;
3635
+ config;
3636
+ handlers;
3637
+ metadata;
3638
+ direction;
3639
+ state = "pending";
3640
+ error;
3641
+ chunksInFlight = 0;
3642
+ chunksAcknowledged = 0;
3643
+ totalChunks = 0;
3644
+ startTime;
3645
+ endTime;
3646
+ pendingChunks = /* @__PURE__ */ new Map();
3647
+ chunkAckCallbacks = /* @__PURE__ */ new Map();
3648
+ currentWindowSize;
3649
+ dataSource;
3650
+ dataSink;
3651
+ constructor(stream, direction, metadata, config = {}, handlers = {}) {
3652
+ this.stream = stream;
3653
+ this.direction = direction;
3654
+ this.metadata = metadata;
3655
+ this.config = {
3656
+ ...DEFAULT_BULK_CONFIG,
3657
+ ...config
3658
+ };
3659
+ this.handlers = handlers;
3660
+ this.currentWindowSize = this.config.flowControl?.initialWindowSize ?? DEFAULT_FLOW_CONTROL.initialWindowSize;
3661
+ this.setupStreamHandlers();
3662
+ }
3663
+ /** Get transfer ID */
3664
+ get id() {
3665
+ return this.metadata.id;
3666
+ }
3667
+ /** Get current state */
3668
+ get currentState() {
3669
+ return this.state;
3670
+ }
3671
+ /** Get transfer statistics */
3672
+ get stats() {
3673
+ const now = Date.now();
3674
+ const elapsed = this.startTime ? (this.endTime ?? now) - this.startTime : 0;
3675
+ const bytesTransferred = this.stream.bytesSentCount + this.stream.bytesReceivedCount;
3676
+ let transferRate = 0;
3677
+ if (elapsed > 0) transferRate = bytesTransferred / elapsed * 1e3;
3678
+ let estimatedTimeRemaining;
3679
+ if (this.metadata.totalSize && transferRate > 0) estimatedTimeRemaining = (this.metadata.totalSize - bytesTransferred) / transferRate * 1e3;
3680
+ return {
3681
+ bytesTransferred,
3682
+ totalBytes: this.metadata.totalSize,
3683
+ transferRate,
3684
+ elapsedTime: elapsed,
3685
+ estimatedTimeRemaining,
3686
+ chunksTransferred: this.chunksAcknowledged + this.pendingChunks.size,
3687
+ chunksAcknowledged: this.chunksAcknowledged,
3688
+ currentWindowSize: this.currentWindowSize,
3689
+ backpressureActive: this.stream.isBackpressureActive
3690
+ };
3691
+ }
3692
+ /**
3693
+ * Set the data source for upload
3694
+ */
3695
+ setDataSource(source) {
3696
+ if (this.direction !== "upload") throw new Error("Data source only valid for uploads");
3697
+ this.dataSource = source;
3698
+ }
3699
+ /**
3700
+ * Set the data sink for download
3701
+ */
3702
+ setDataSink(sink) {
3703
+ if (this.direction !== "download") throw new Error("Data sink only valid for downloads");
3704
+ this.dataSink = sink;
3705
+ }
3706
+ /**
3707
+ * Start the bulk transfer
3708
+ */
3709
+ async start() {
3710
+ if (this.state !== "pending") throw new Error(`Cannot start transfer in state: ${this.state}`);
3711
+ this.state = "transferring";
3712
+ this.startTime = Date.now();
3713
+ this.handlers.onStart?.();
3714
+ if (this.metadata.totalSize) this.stream.setTotalBytesExpected(this.metadata.totalSize);
3715
+ try {
3716
+ if (this.direction === "upload") await this.performUpload();
3717
+ else await this.performDownload();
3718
+ if (this.state === "transferring") {
3719
+ this.state = "completed";
3720
+ this.endTime = Date.now();
3721
+ this.handlers.onComplete?.();
3722
+ }
3723
+ } catch (err) {
3724
+ this.handleError(err);
3725
+ }
3726
+ }
3727
+ /**
3728
+ * Pause the transfer
3729
+ */
3730
+ pause() {
3731
+ if (this.state === "transferring") this.state = "paused";
3732
+ }
3733
+ /**
3734
+ * Resume the transfer
3735
+ */
3736
+ resume() {
3737
+ if (this.state === "paused") this.state = "transferring";
3738
+ }
3739
+ /**
3740
+ * Cancel the transfer
3741
+ */
3742
+ cancel() {
3743
+ if (this.state === "completed" || this.state === "error" || this.state === "cancelled") return;
3744
+ this.state = "cancelled";
3745
+ this.endTime = Date.now();
3746
+ for (const { timeout } of this.pendingChunks.values()) clearTimeout(timeout);
3747
+ this.pendingChunks.clear();
3748
+ this.handlers.onCancel?.();
3749
+ }
3750
+ /**
3751
+ * Handle chunk acknowledgment from peer
3752
+ */
3753
+ handleChunkAck(ack) {
3754
+ const pending = this.pendingChunks.get(ack.sequenceNumber);
3755
+ if (pending) {
3756
+ clearTimeout(pending.timeout);
3757
+ this.pendingChunks.delete(ack.sequenceNumber);
3758
+ this.chunksAcknowledged++;
3759
+ this.chunksInFlight--;
3760
+ this.currentWindowSize += ack.bytesAcknowledged;
3761
+ const callback = this.chunkAckCallbacks.get(ack.sequenceNumber);
3762
+ if (callback) {
3763
+ callback();
3764
+ this.chunkAckCallbacks.delete(ack.sequenceNumber);
3765
+ }
3766
+ }
3767
+ }
3768
+ /**
3769
+ * Update flow control window
3770
+ */
3771
+ updateWindow(newWindowSize) {
3772
+ this.currentWindowSize = newWindowSize;
3773
+ this.stream.updateSendWindow(newWindowSize);
3774
+ }
3775
+ setupStreamHandlers() {}
3776
+ async performUpload() {
3777
+ if (!this.dataSource) throw new Error("No data source set for upload");
3778
+ if (Symbol.asyncIterator in this.dataSource) for await (const data of this.dataSource) {
3779
+ if (this.state !== "transferring") break;
3780
+ await this.sendChunkWithFlowControl(data);
3781
+ }
3782
+ else {
3783
+ const sourceFn = this.dataSource;
3784
+ while (this.state === "transferring") {
3785
+ const data = await sourceFn();
3786
+ if (!data || data.length === 0) break;
3787
+ await this.sendChunkWithFlowControl(data);
3788
+ }
3789
+ }
3790
+ await this.waitForAllAcks();
3791
+ }
3792
+ async performDownload() {
3793
+ if (!this.dataSink) throw new Error("No data sink set for download");
3794
+ while (this.state === "transferring") await new Promise((resolve) => setTimeout(resolve, 100));
3795
+ }
3796
+ async sendChunkWithFlowControl(data) {
3797
+ while (this.chunksInFlight >= (this.config.maxConcurrentChunks ?? 8)) {
3798
+ if (this.state !== "transferring") return;
3799
+ await new Promise((resolve) => setTimeout(resolve, 10));
3800
+ }
3801
+ await this.stream.ready();
3802
+ const sequenceNumber = this.totalChunks++;
3803
+ await this.stream.send(data, false);
3804
+ this.chunksInFlight++;
3805
+ const timeout = setTimeout(() => {
3806
+ this.handleChunkTimeout(sequenceNumber);
3807
+ }, this.config.chunkAckTimeoutMs ?? 3e4);
3808
+ this.pendingChunks.set(sequenceNumber, {
3809
+ chunk: {
3810
+ data,
3811
+ sequenceNumber,
3812
+ timestamp: Date.now()
3813
+ },
3814
+ timeout
3815
+ });
3816
+ }
3817
+ async sendChunkAck(_sequenceNumber, _bytes) {}
3818
+ handleChunkTimeout(sequenceNumber) {
3819
+ if (this.pendingChunks.get(sequenceNumber)) {
3820
+ this.pendingChunks.delete(sequenceNumber);
3821
+ this.chunksInFlight--;
3822
+ this.handleError(/* @__PURE__ */ new Error(`Chunk ${sequenceNumber} acknowledgment timeout`));
3823
+ }
3824
+ }
3825
+ async waitForAllAcks() {
3826
+ for (const [sequenceNumber, { timeout }] of this.pendingChunks) {
3827
+ clearTimeout(timeout);
3828
+ this.handleChunkAck({
3829
+ sequenceNumber,
3830
+ bytesAcknowledged: 0
3831
+ });
3832
+ }
3833
+ this.pendingChunks.clear();
3834
+ }
3835
+ handleError(error) {
3836
+ if (this.state === "completed" || this.state === "error") return;
3837
+ this.error = error;
3838
+ this.state = "error";
3839
+ this.endTime = Date.now();
3840
+ for (const { timeout } of this.pendingChunks.values()) clearTimeout(timeout);
3841
+ this.handlers.onError?.(error);
3842
+ }
3843
+ };
3844
+ /**
3845
+ * Bulk transfer manager
3846
+ *
3847
+ * Manages multiple concurrent bulk transfers.
3848
+ */
3849
+ var BulkTransferManager = class {
3850
+ transfers = /* @__PURE__ */ new Map();
3851
+ streams = /* @__PURE__ */ new Map();
3852
+ nextStreamId = 1;
3853
+ /**
3854
+ * Create a new bulk transfer
3855
+ */
3856
+ createTransfer(direction, metadata, config, handlers) {
3857
+ const streamId = this.nextStreamId++;
3858
+ const stream = new Stream({
3859
+ streamId,
3860
+ direction: direction === "upload" ? "outbound" : "inbound",
3861
+ priority: StreamPriority.NORMAL,
3862
+ enableProgress: config?.enableProgress ?? true,
3863
+ progressInterval: config?.progressInterval,
3864
+ flowControl: config?.flowControl
3865
+ }, {
3866
+ onProgress: handlers?.onProgress,
3867
+ onBackpressure: handlers?.onBackpressure,
3868
+ onError: handlers?.onError
3869
+ });
3870
+ this.streams.set(streamId, stream);
3871
+ const transfer = new BulkTransfer(stream, direction, metadata, config, handlers);
3872
+ this.transfers.set(metadata.id, transfer);
3873
+ return transfer;
3874
+ }
3875
+ /**
3876
+ * Get a transfer by ID
3877
+ */
3878
+ getTransfer(id) {
3879
+ return this.transfers.get(id);
3880
+ }
3881
+ /**
3882
+ * Get a stream by ID
3883
+ */
3884
+ getStream(id) {
3885
+ return this.streams.get(id);
3886
+ }
3887
+ /**
3888
+ * Remove a transfer
3889
+ */
3890
+ removeTransfer(id) {
3891
+ const transfer = this.transfers.get(id);
3892
+ if (transfer) {
3893
+ transfer.cancel();
3894
+ this.transfers.delete(id);
3895
+ return true;
3896
+ }
3897
+ return false;
3898
+ }
3899
+ /**
3900
+ * Get all active transfers
3901
+ */
3902
+ getActiveTransfers() {
3903
+ return Array.from(this.transfers.values()).filter((t) => t.currentState === "pending" || t.currentState === "transferring" || t.currentState === "paused");
3904
+ }
3905
+ /**
3906
+ * Get transfer statistics summary
3907
+ */
3908
+ getStatsSummary() {
3909
+ const transfers = Array.from(this.transfers.values());
3910
+ const active = transfers.filter((t) => t.currentState === "transferring");
3911
+ const completed = transfers.filter((t) => t.currentState === "completed");
3912
+ const totalBytes = transfers.reduce((sum, t) => sum + t.stats.bytesTransferred, 0);
3913
+ return {
3914
+ totalTransfers: transfers.length,
3915
+ activeTransfers: active.length,
3916
+ completedTransfers: completed.length,
3917
+ totalBytesTransferred: totalBytes
3918
+ };
3919
+ }
3920
+ /**
3921
+ * Close all transfers
3922
+ */
3923
+ async closeAll() {
3924
+ for (const transfer of this.transfers.values()) transfer.cancel();
3925
+ this.transfers.clear();
3926
+ this.streams.clear();
3927
+ }
3928
+ };
3929
+ /**
3930
+ * Create a bulk transfer manager
3931
+ */
3932
+ function createBulkTransferManager() {
3933
+ return new BulkTransferManager();
3934
+ }
3935
+
3936
+ //#endregion
3937
+ //#region src/rpc/realtime.ts
3938
+ /**
3939
+ * Realtime API - Real-time communication with prioritization
3940
+ *
3941
+ * Phase 5: Flow Control and Realtime Communication
3942
+ *
3943
+ * Features:
3944
+ * - Message priority queues
3945
+ * - Message drop policies for latency-sensitive scenarios
3946
+ * - Bandwidth adaptation
3947
+ * - Jitter buffer management
3948
+ */
3949
+ /** Message drop policy for latency-sensitive scenarios */
3950
+ let DropPolicy = /* @__PURE__ */ function(DropPolicy) {
3951
+ /** Never drop messages */
3952
+ DropPolicy["NEVER"] = "never";
3953
+ /** Drop oldest messages when queue is full */
3954
+ DropPolicy["DROP_OLDEST"] = "drop_oldest";
3955
+ /** Drop newest messages when queue is full */
3956
+ DropPolicy["DROP_NEWEST"] = "drop_newest";
3957
+ /** Drop low priority messages first */
3958
+ DropPolicy["DROP_LOW_PRIORITY"] = "drop_low_priority";
3959
+ /** Drop messages that exceed max latency */
3960
+ DropPolicy["DROP_STALE"] = "drop_stale";
3961
+ return DropPolicy;
3962
+ }({});
3963
+ /** Default realtime configuration */
3964
+ const DEFAULT_REALTIME_CONFIG = {
3965
+ targetLatencyMs: 50,
3966
+ maxLatencyMs: 200,
3967
+ jitterBufferMs: 30,
3968
+ maxQueueSize: 1e3,
3969
+ dropPolicy: DropPolicy.DROP_STALE,
3970
+ adaptiveBitrate: true,
3971
+ minBitrate: 16e3,
3972
+ maxBitrate: 10485760,
3973
+ bandwidthWindowMs: 1e3
3974
+ };
3975
+ /**
3976
+ * Priority queue for realtime messages
3977
+ */
3978
+ var PriorityMessageQueue = class {
3979
+ queues = /* @__PURE__ */ new Map();
3980
+ totalSize = 0;
3981
+ maxSize;
3982
+ dropPolicy;
3983
+ maxLatencyMs;
3984
+ constructor(maxSize, dropPolicy, maxLatencyMs) {
3985
+ this.maxSize = maxSize;
3986
+ this.dropPolicy = dropPolicy;
3987
+ this.maxLatencyMs = maxLatencyMs;
3988
+ for (let i = 0; i <= 4; i++) this.queues.set(i, []);
3989
+ }
3990
+ /** Get total queue size */
3991
+ get size() {
3992
+ return this.totalSize;
3993
+ }
3994
+ /** Check if queue is empty */
3995
+ get isEmpty() {
3996
+ return this.totalSize === 0;
3997
+ }
3998
+ /** Enqueue a message */
3999
+ enqueue(message) {
4000
+ if (this.dropPolicy === DropPolicy.DROP_STALE) {
4001
+ if (Date.now() - message.timestamp > this.maxLatencyMs && !message.critical) return false;
4002
+ }
4003
+ if (this.totalSize >= this.maxSize) {
4004
+ if (!this.handleQueueFull(message)) return false;
4005
+ }
4006
+ this.queues.get(message.priority).push(message);
4007
+ this.totalSize++;
4008
+ return true;
4009
+ }
4010
+ /** Dequeue the highest priority message */
4011
+ dequeue() {
4012
+ for (let priority = 0; priority <= 4; priority++) {
4013
+ const queue = this.queues.get(priority);
4014
+ if (queue.length > 0) {
4015
+ this.totalSize--;
4016
+ return queue.shift();
4017
+ }
4018
+ }
4019
+ }
4020
+ /** Peek at the highest priority message without removing */
4021
+ peek() {
4022
+ for (let priority = 0; priority <= 4; priority++) {
4023
+ const queue = this.queues.get(priority);
4024
+ if (queue.length > 0) return queue[0];
4025
+ }
4026
+ }
4027
+ /** Remove stale messages */
4028
+ removeStale() {
4029
+ const now = Date.now();
4030
+ const removed = [];
4031
+ for (const [priority, queue] of this.queues) {
4032
+ const remaining = [];
4033
+ for (const msg of queue) if (now - msg.timestamp <= this.maxLatencyMs || msg.critical) remaining.push(msg);
4034
+ else {
4035
+ removed.push(msg);
4036
+ this.totalSize--;
4037
+ }
4038
+ this.queues.set(priority, remaining);
4039
+ }
4040
+ return removed;
4041
+ }
4042
+ /** Clear all messages */
4043
+ clear() {
4044
+ const all = [];
4045
+ for (const queue of this.queues.values()) all.push(...queue);
4046
+ for (const queue of this.queues.values()) queue.length = 0;
4047
+ this.totalSize = 0;
4048
+ return all;
4049
+ }
4050
+ handleQueueFull(newMessage) {
4051
+ switch (this.dropPolicy) {
4052
+ case DropPolicy.NEVER: return false;
4053
+ case DropPolicy.DROP_OLDEST:
4054
+ for (let priority = 4; priority >= 0; priority--) {
4055
+ const queue = this.queues.get(priority);
4056
+ if (queue.length > 0 && priority >= newMessage.priority) {
4057
+ queue.shift();
4058
+ this.totalSize--;
4059
+ return true;
4060
+ }
4061
+ }
4062
+ return false;
4063
+ case DropPolicy.DROP_NEWEST:
4064
+ if (newMessage.priority >= StreamPriority.NORMAL) return false;
4065
+ return true;
4066
+ case DropPolicy.DROP_LOW_PRIORITY:
4067
+ for (let priority = 4; priority > newMessage.priority; priority--) {
4068
+ const queue = this.queues.get(priority);
4069
+ if (queue.length > 0) {
4070
+ queue.shift();
4071
+ this.totalSize--;
4072
+ return true;
4073
+ }
4074
+ }
4075
+ return false;
4076
+ case DropPolicy.DROP_STALE:
4077
+ if (this.removeStale().length > 0) return true;
4078
+ for (let priority = 4; priority >= 0; priority--) {
4079
+ const queue = this.queues.get(priority);
4080
+ if (queue.length > 0 && priority >= newMessage.priority) {
4081
+ queue.shift();
4082
+ this.totalSize--;
4083
+ return true;
4084
+ }
4085
+ }
4086
+ return false;
4087
+ default: return false;
4088
+ }
4089
+ }
4090
+ };
4091
+ /**
4092
+ * Realtime stream for low-latency communication
4093
+ *
4094
+ * Manages message prioritization, jitter buffering, and bandwidth adaptation.
4095
+ */
4096
+ var RealtimeStream = class {
4097
+ stream;
4098
+ config;
4099
+ handlers;
4100
+ sendQueue;
4101
+ receiveQueue;
4102
+ jitterBuffer = [];
4103
+ jitterBufferTargetSize;
4104
+ bandwidthStats = {
4105
+ currentBitrate: 0,
4106
+ measuredBandwidth: 0,
4107
+ packetLossRate: 0,
4108
+ averageLatencyMs: 0,
4109
+ jitterMs: 0,
4110
+ congestionLevel: 0
4111
+ };
4112
+ bitrateHistory = [];
4113
+ latencyHistory = [];
4114
+ lastBandwidthUpdate = 0;
4115
+ nextSendSequence = 0;
4116
+ nextExpectedSequence = 0;
4117
+ receivedSequences = /* @__PURE__ */ new Set();
4118
+ isRunning = false;
4119
+ sendInterval;
4120
+ jitterInterval;
4121
+ bandwidthInterval;
4122
+ constructor(stream, config = {}, handlers = {}) {
4123
+ this.stream = stream;
4124
+ this.config = {
4125
+ ...DEFAULT_REALTIME_CONFIG,
4126
+ ...config
4127
+ };
4128
+ this.handlers = handlers;
4129
+ this.sendQueue = new PriorityMessageQueue(this.config.maxQueueSize, this.config.dropPolicy, this.config.maxLatencyMs);
4130
+ this.receiveQueue = new PriorityMessageQueue(this.config.maxQueueSize, this.config.dropPolicy, this.config.maxLatencyMs);
4131
+ this.jitterBufferTargetSize = Math.ceil(this.config.jitterBufferMs / this.config.targetLatencyMs);
4132
+ this.setupStreamHandlers();
4133
+ }
4134
+ /** Get current bandwidth statistics */
4135
+ get stats() {
4136
+ return { ...this.bandwidthStats };
4137
+ }
4138
+ /** Get current send queue size */
4139
+ get sendQueueSize() {
4140
+ return this.sendQueue.size;
4141
+ }
4142
+ /** Get current receive queue size */
4143
+ get receiveQueueSize() {
4144
+ return this.receiveQueue.size;
4145
+ }
4146
+ /** Get jitter buffer size */
4147
+ get jitterBufferSize() {
4148
+ return this.jitterBuffer.length;
4149
+ }
4150
+ /**
4151
+ * Start the realtime stream
4152
+ */
4153
+ start() {
4154
+ if (this.isRunning) return;
4155
+ this.isRunning = true;
4156
+ this.sendInterval = setInterval(() => {
4157
+ this.processSendQueue();
4158
+ }, this.config.targetLatencyMs / 2);
4159
+ this.jitterInterval = setInterval(() => {
4160
+ this.processJitterBuffer();
4161
+ }, this.config.targetLatencyMs / 4);
4162
+ if (this.config.adaptiveBitrate) this.bandwidthInterval = setInterval(() => {
4163
+ this.updateBandwidthStats();
4164
+ }, this.config.bandwidthWindowMs);
4165
+ this.handlers.onReady?.();
4166
+ }
4167
+ /**
4168
+ * Stop the realtime stream
4169
+ */
4170
+ stop() {
4171
+ this.isRunning = false;
4172
+ if (this.sendInterval) {
4173
+ clearInterval(this.sendInterval);
4174
+ this.sendInterval = void 0;
4175
+ }
4176
+ if (this.jitterInterval) {
4177
+ clearInterval(this.jitterInterval);
4178
+ this.jitterInterval = void 0;
4179
+ }
4180
+ if (this.bandwidthInterval) {
4181
+ clearInterval(this.bandwidthInterval);
4182
+ this.bandwidthInterval = void 0;
4183
+ }
4184
+ const dropped = this.sendQueue.clear();
4185
+ if (dropped.length > 0) this.handlers.onDrop?.(dropped, "stream stopped");
4186
+ }
4187
+ /**
4188
+ * Send a realtime message
4189
+ */
4190
+ sendMessage(data, priority = StreamPriority.NORMAL, options = {}) {
4191
+ if (!this.isRunning) return false;
4192
+ const message = {
4193
+ id: this.generateMessageId(),
4194
+ priority,
4195
+ timestamp: Date.now(),
4196
+ data,
4197
+ type: options.type,
4198
+ sequenceNumber: this.nextSendSequence++,
4199
+ critical: options.critical
4200
+ };
4201
+ if (!this.sendQueue.enqueue(message)) {
4202
+ this.handlers.onDrop?.([message], "queue full");
4203
+ return false;
4204
+ }
4205
+ return true;
4206
+ }
4207
+ /**
4208
+ * Receive the next message (blocking)
4209
+ */
4210
+ async receiveMessage() {
4211
+ return new Promise((resolve) => {
4212
+ const checkQueue = () => {
4213
+ const message = this.receiveQueue.dequeue();
4214
+ if (message) resolve(message);
4215
+ else if (!this.isRunning) resolve(void 0);
4216
+ else setTimeout(checkQueue, 5);
4217
+ };
4218
+ checkQueue();
4219
+ });
4220
+ }
4221
+ /**
4222
+ * Set target bitrate (for manual bitrate control)
4223
+ */
4224
+ setTargetBitrate(bitrate) {
4225
+ this.bandwidthStats.currentBitrate = Math.max(this.config.minBitrate, Math.min(this.config.maxBitrate, bitrate));
4226
+ }
4227
+ setupStreamHandlers() {
4228
+ const originalOnData = this.stream.handlers?.onData;
4229
+ this.stream.handlers = {
4230
+ ...this.stream.handlers,
4231
+ onData: (chunk) => {
4232
+ this.handleIncomingData(chunk);
4233
+ originalOnData?.(chunk);
4234
+ }
4235
+ };
4236
+ }
4237
+ handleIncomingData(chunk) {
4238
+ try {
4239
+ const message = this.deserializeMessage(chunk.data);
4240
+ if (message.sequenceNumber > this.nextExpectedSequence) {
4241
+ const lost = message.sequenceNumber - this.nextExpectedSequence;
4242
+ this.bandwidthStats.packetLossRate = this.bandwidthStats.packetLossRate * .9 + lost * .1;
4243
+ }
4244
+ this.nextExpectedSequence = message.sequenceNumber + 1;
4245
+ const latency = Date.now() - message.timestamp;
4246
+ this.latencyHistory.push(latency);
4247
+ if (this.latencyHistory.length > 100) this.latencyHistory.shift();
4248
+ const playoutTime = Date.now() + this.config.jitterBufferMs;
4249
+ this.jitterBuffer.push({
4250
+ message,
4251
+ receivedAt: Date.now(),
4252
+ playoutTime
4253
+ });
4254
+ this.jitterBuffer.sort((a, b) => a.message.sequenceNumber - b.message.sequenceNumber);
4255
+ } catch (error) {
4256
+ this.handlers.onError?.(error);
4257
+ }
4258
+ }
4259
+ processSendQueue() {
4260
+ if (!this.isRunning || this.sendQueue.isEmpty) return;
4261
+ if (this.config.adaptiveBitrate) {
4262
+ const maxBytesPerInterval = this.bandwidthStats.currentBitrate * this.config.targetLatencyMs / 1e3 / 2;
4263
+ let bytesSent = 0;
4264
+ while (bytesSent < maxBytesPerInterval) {
4265
+ const message = this.sendQueue.dequeue();
4266
+ if (!message) break;
4267
+ this.sendMessageToStream(message);
4268
+ bytesSent += message.data.length;
4269
+ }
4270
+ } else {
4271
+ const message = this.sendQueue.dequeue();
4272
+ if (message) this.sendMessageToStream(message);
4273
+ }
4274
+ if (this.config.dropPolicy === DropPolicy.DROP_STALE) {
4275
+ const stale = this.sendQueue.removeStale();
4276
+ if (stale.length > 0) this.handlers.onDrop?.(stale, "stale");
4277
+ }
4278
+ }
4279
+ sendMessageToStream(message) {
4280
+ try {
4281
+ const data = this.serializeMessage(message);
4282
+ this.stream.send(data).catch((err) => {
4283
+ this.handlers.onError?.(err);
4284
+ });
4285
+ this.bitrateHistory.push(data.length);
4286
+ if (this.bitrateHistory.length > 100) this.bitrateHistory.shift();
4287
+ } catch (error) {
4288
+ this.handlers.onError?.(error);
4289
+ }
4290
+ }
4291
+ processJitterBuffer() {
4292
+ if (!this.isRunning || this.jitterBuffer.length === 0) return;
4293
+ const now = Date.now();
4294
+ while (this.jitterBuffer.length > 0) {
4295
+ const entry = this.jitterBuffer[0];
4296
+ if (this.jitterBuffer.length < this.jitterBufferTargetSize && entry.playoutTime > now) break;
4297
+ if (entry.playoutTime <= now) {
4298
+ this.jitterBuffer.shift();
4299
+ this.receiveQueue.enqueue(entry.message);
4300
+ this.handlers.onMessage?.(entry.message);
4301
+ } else break;
4302
+ }
4303
+ const maxAge = this.config.maxLatencyMs * 2;
4304
+ const stale = [];
4305
+ this.jitterBuffer = this.jitterBuffer.filter((entry) => {
4306
+ if (now - entry.receivedAt > maxAge && !entry.message.critical) {
4307
+ stale.push(entry.message);
4308
+ return false;
4309
+ }
4310
+ return true;
4311
+ });
4312
+ if (stale.length > 0) this.handlers.onDrop?.(stale, "jitter buffer stale");
4313
+ }
4314
+ updateBandwidthStats() {
4315
+ const now = Date.now();
4316
+ const windowMs = this.config.bandwidthWindowMs;
4317
+ if (this.bitrateHistory.length >= 2) {
4318
+ const totalBytes = this.bitrateHistory.reduce((a, b) => a + b, 0);
4319
+ this.bandwidthStats.measuredBandwidth = totalBytes / windowMs * 1e3;
4320
+ }
4321
+ if (this.latencyHistory.length > 0) {
4322
+ const avgLatency = this.latencyHistory.reduce((a, b) => a + b, 0) / this.latencyHistory.length;
4323
+ this.bandwidthStats.averageLatencyMs = avgLatency;
4324
+ const variance = this.latencyHistory.reduce((sum, lat) => sum + (lat - avgLatency) ** 2, 0) / this.latencyHistory.length;
4325
+ this.bandwidthStats.jitterMs = Math.sqrt(variance);
4326
+ this.handlers.onLatencyChange?.(avgLatency);
4327
+ }
4328
+ const queueUtilization = this.sendQueue.size / this.config.maxQueueSize;
4329
+ const latencyRatio = this.bandwidthStats.averageLatencyMs / this.config.targetLatencyMs;
4330
+ this.bandwidthStats.congestionLevel = Math.min(1, (queueUtilization + latencyRatio) / 2);
4331
+ if (this.config.adaptiveBitrate) this.adaptBitrate();
4332
+ this.lastBandwidthUpdate = now;
4333
+ }
4334
+ adaptBitrate() {
4335
+ const { congestionLevel, packetLossRate } = this.bandwidthStats;
4336
+ let newBitrate = this.bandwidthStats.currentBitrate;
4337
+ if (congestionLevel > .7 || packetLossRate > .05) newBitrate = newBitrate * .8;
4338
+ else if (congestionLevel < .3 && packetLossRate < .01) newBitrate = newBitrate * 1.05;
4339
+ newBitrate = Math.max(this.config.minBitrate, Math.min(this.config.maxBitrate, newBitrate));
4340
+ if (newBitrate !== this.bandwidthStats.currentBitrate) {
4341
+ this.bandwidthStats.currentBitrate = newBitrate;
4342
+ this.handlers.onBandwidthAdapt?.(newBitrate, this.bandwidthStats);
4343
+ }
4344
+ }
4345
+ serializeMessage(message) {
4346
+ const header = JSON.stringify({
4347
+ id: message.id,
4348
+ priority: message.priority,
4349
+ timestamp: message.timestamp,
4350
+ type: message.type,
4351
+ sequenceNumber: message.sequenceNumber,
4352
+ critical: message.critical,
4353
+ dataLength: message.data.length
4354
+ });
4355
+ const headerBytes = new TextEncoder().encode(header);
4356
+ const headerLength = new Uint8Array(4);
4357
+ new DataView(headerLength.buffer).setUint32(0, headerBytes.length, true);
4358
+ const result = new Uint8Array(4 + headerBytes.length + message.data.length);
4359
+ result.set(headerLength, 0);
4360
+ result.set(headerBytes, 4);
4361
+ result.set(message.data, 4 + headerBytes.length);
4362
+ return result;
4363
+ }
4364
+ deserializeMessage(data) {
4365
+ const headerLength = new DataView(data.buffer, data.byteOffset, 4).getUint32(0, true);
4366
+ const headerBytes = data.slice(4, 4 + headerLength);
4367
+ const header = JSON.parse(new TextDecoder().decode(headerBytes));
4368
+ return {
4369
+ id: header.id,
4370
+ priority: header.priority,
4371
+ timestamp: header.timestamp,
4372
+ type: header.type,
4373
+ sequenceNumber: header.sequenceNumber,
4374
+ critical: header.critical,
4375
+ data: data.slice(4 + headerLength, 4 + headerLength + header.dataLength)
4376
+ };
4377
+ }
4378
+ generateMessageId() {
4379
+ return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
4380
+ }
4381
+ };
4382
+ /**
4383
+ * Realtime stream manager
4384
+ */
4385
+ var RealtimeStreamManager = class {
4386
+ streams = /* @__PURE__ */ new Map();
4387
+ nextStreamId = 1;
4388
+ /**
4389
+ * Create a new realtime stream
4390
+ */
4391
+ createStream(baseStream, config, handlers) {
4392
+ const streamId = this.nextStreamId++;
4393
+ const stream = new RealtimeStream(baseStream, config, handlers);
4394
+ this.streams.set(streamId, stream);
4395
+ return stream;
4396
+ }
4397
+ /**
4398
+ * Get a stream by ID
4399
+ */
4400
+ getStream(id) {
4401
+ return this.streams.get(id);
4402
+ }
4403
+ /**
4404
+ * Remove a stream
4405
+ */
4406
+ removeStream(id) {
4407
+ const stream = this.streams.get(id);
4408
+ if (stream) {
4409
+ stream.stop();
4410
+ this.streams.delete(id);
4411
+ return true;
4412
+ }
4413
+ return false;
4414
+ }
4415
+ /**
4416
+ * Get all active streams
4417
+ */
4418
+ getActiveStreams() {
4419
+ return Array.from(this.streams.values());
4420
+ }
4421
+ /**
4422
+ * Stop all streams
4423
+ */
4424
+ stopAll() {
4425
+ for (const stream of this.streams.values()) stream.stop();
4426
+ this.streams.clear();
4427
+ }
4428
+ };
4429
+ /**
4430
+ * Create a realtime stream manager
4431
+ */
4432
+ function createRealtimeStreamManager() {
4433
+ return new RealtimeStreamManager();
4434
+ }
4435
+
4436
+ //#endregion
4437
+ //#region src/rpc/stream-manager.ts
4438
+ /**
4439
+ * Stream Management - Unified stream lifecycle management
4440
+ *
4441
+ * Phase 5: Flow Control and Realtime Communication
4442
+ *
4443
+ * Manages:
4444
+ * - Stream creation and registration
4445
+ * - Bidirectional stream support
4446
+ * - Stream lifecycle (open, close, error handling)
4447
+ * - Stream multiplexing over a single connection
4448
+ */
4449
+ /** Stream type */
4450
+ let StreamType = /* @__PURE__ */ function(StreamType) {
4451
+ /** Standard stream */
4452
+ StreamType["STANDARD"] = "standard";
4453
+ /** Bulk transfer stream */
4454
+ StreamType["BULK"] = "bulk";
4455
+ /** Realtime stream */
4456
+ StreamType["REALTIME"] = "realtime";
4457
+ return StreamType;
4458
+ }({});
4459
+ /** Default stream manager configuration */
4460
+ const DEFAULT_STREAM_MANAGER_CONFIG = {
4461
+ maxStreams: 100,
4462
+ defaultPriority: StreamPriority.NORMAL,
4463
+ enableMultiplexing: true,
4464
+ idleTimeoutMs: 3e5
4465
+ };
4466
+ /**
4467
+ * Stream manager
4468
+ *
4469
+ * Manages all streams for an RPC connection.
4470
+ */
4471
+ var StreamManager = class {
4472
+ config;
4473
+ handlers;
4474
+ connection;
4475
+ transport;
4476
+ streams = /* @__PURE__ */ new Map();
4477
+ streamTypes = /* @__PURE__ */ new Map();
4478
+ streamInfos = /* @__PURE__ */ new Map();
4479
+ nextStreamId = 1;
4480
+ bulkManager;
4481
+ realtimeManager;
4482
+ idleTimeout;
4483
+ isRunning = false;
4484
+ constructor(config = {}, handlers = {}) {
4485
+ this.config = {
4486
+ ...DEFAULT_STREAM_MANAGER_CONFIG,
4487
+ ...config
4488
+ };
4489
+ this.handlers = handlers;
4490
+ this.bulkManager = new BulkTransferManager();
4491
+ this.realtimeManager = new RealtimeStreamManager();
4492
+ }
4493
+ /** Get the number of active streams */
4494
+ get streamCount() {
4495
+ return this.streams.size;
4496
+ }
4497
+ /** Get the maximum number of streams */
4498
+ get maxStreams() {
4499
+ return this.config.maxStreams;
4500
+ }
4501
+ /** Get all stream infos */
4502
+ get allStreamInfos() {
4503
+ return Array.from(this.streamInfos.values());
4504
+ }
4505
+ /**
4506
+ * Attach to an RPC connection
4507
+ */
4508
+ attach(connection, transport) {
4509
+ this.connection = connection;
4510
+ this.transport = transport;
4511
+ this.isRunning = true;
4512
+ this.resetIdleTimeout();
4513
+ }
4514
+ /**
4515
+ * Detach from connection
4516
+ */
4517
+ detach() {
4518
+ this.closeAllStreams();
4519
+ this.isRunning = false;
4520
+ this.connection = void 0;
4521
+ this.transport = void 0;
4522
+ if (this.idleTimeout) {
4523
+ clearTimeout(this.idleTimeout);
4524
+ this.idleTimeout = void 0;
4525
+ }
4526
+ }
4527
+ /**
4528
+ * Create a new stream
4529
+ */
4530
+ createStream(options = {}) {
4531
+ if (this.streams.size >= this.config.maxStreams) throw new Error(`Maximum number of streams (${this.config.maxStreams}) reached`);
4532
+ const streamId = this.nextStreamId++;
4533
+ const type = options.type ?? StreamType.STANDARD;
4534
+ const streamOptions = {
4535
+ streamId,
4536
+ direction: options.direction ?? "bidirectional",
4537
+ priority: options.priority ?? this.config.defaultPriority ?? StreamPriority.NORMAL,
4538
+ metadata: options.metadata,
4539
+ flowControl: options.flowControl
4540
+ };
4541
+ const stream = new Stream(streamOptions, {
4542
+ onOpen: () => {
4543
+ this.updateStreamState(streamId, "open");
4544
+ this.handlers.onStreamOpen?.(this.getStreamInfo(streamId));
4545
+ },
4546
+ onClose: () => {
4547
+ this.updateStreamState(streamId, "closed");
4548
+ this.handlers.onStreamClose?.(this.getStreamInfo(streamId));
4549
+ this.removeStream(streamId);
4550
+ },
4551
+ onError: (error) => {
4552
+ this.updateStreamState(streamId, "error");
4553
+ const info = this.getStreamInfo(streamId);
4554
+ if (info) this.handlers.onStreamError?.(info, error);
4555
+ }
4556
+ });
4557
+ this.streams.set(streamId, stream);
4558
+ this.streamTypes.set(streamId, type);
4559
+ const info = {
4560
+ id: streamId,
4561
+ type,
4562
+ direction: streamOptions.direction,
4563
+ priority: streamOptions.priority ?? StreamPriority.NORMAL,
4564
+ state: "connecting",
4565
+ createdAt: Date.now(),
4566
+ bytesTransferred: 0,
4567
+ metadata: options.metadata
4568
+ };
4569
+ this.streamInfos.set(streamId, info);
4570
+ this.handlers.onStreamCreate?.(info);
4571
+ this.handlers.onStreamCountChange?.(this.streams.size);
4572
+ this.resetIdleTimeout();
4573
+ return stream;
4574
+ }
4575
+ /**
4576
+ * Create a bulk transfer stream
4577
+ */
4578
+ createBulkStream(direction, metadata, config, handlers) {
4579
+ this.createStream({
4580
+ type: StreamType.BULK,
4581
+ direction: direction === "upload" ? "outbound" : "inbound",
4582
+ priority: StreamPriority.NORMAL,
4583
+ metadata: metadata.custom
4584
+ });
4585
+ return this.bulkManager.createTransfer(direction, metadata, config, handlers);
4586
+ }
4587
+ /**
4588
+ * Create a realtime stream
4589
+ */
4590
+ createRealtimeStream(config, handlers) {
4591
+ const stream = this.createStream({
4592
+ type: StreamType.REALTIME,
4593
+ direction: "bidirectional",
4594
+ priority: StreamPriority.HIGH
4595
+ });
4596
+ return this.realtimeManager.createStream(stream, config, handlers);
4597
+ }
4598
+ /**
4599
+ * Get a stream by ID
4600
+ */
4601
+ getStream(id) {
4602
+ return this.streams.get(id);
4603
+ }
4604
+ /**
4605
+ * Get stream info by ID
4606
+ */
4607
+ getStreamInfo(id) {
4608
+ return this.streamInfos.get(id);
4609
+ }
4610
+ /**
4611
+ * Get stream type by ID
4612
+ */
4613
+ getStreamType(id) {
4614
+ return this.streamTypes.get(id);
4615
+ }
4616
+ /**
4617
+ * Get bulk transfer by ID
4618
+ */
4619
+ getBulkTransfer(id) {
4620
+ return this.bulkManager.getTransfer(id);
4621
+ }
4622
+ /**
4623
+ * Get realtime stream by ID
4624
+ */
4625
+ getRealtimeStream(id) {
4626
+ return this.realtimeManager.getStream(id);
4627
+ }
4628
+ /**
4629
+ * Close a specific stream
4630
+ */
4631
+ async closeStream(id) {
4632
+ const stream = this.streams.get(id);
4633
+ if (!stream) return false;
4634
+ await stream.close();
4635
+ this.removeStream(id);
4636
+ return true;
4637
+ }
4638
+ /**
4639
+ * Close all streams
4640
+ */
4641
+ async closeAllStreams() {
4642
+ const closePromises = [];
4643
+ for (const [_id, stream] of this.streams) closePromises.push(stream.close().catch(() => {}));
4644
+ await Promise.all(closePromises);
4645
+ this.streams.clear();
4646
+ this.streamTypes.clear();
4647
+ this.streamInfos.clear();
4648
+ this.bulkManager.closeAll();
4649
+ this.realtimeManager.stopAll();
4650
+ this.handlers.onStreamCountChange?.(0);
4651
+ }
4652
+ /**
4653
+ * Get streams by type
4654
+ */
4655
+ getStreamsByType(type) {
4656
+ return this.allStreamInfos.filter((info) => info.type === type);
4657
+ }
4658
+ /**
4659
+ * Get streams by state
4660
+ */
4661
+ getStreamsByState(state) {
4662
+ return this.allStreamInfos.filter((info) => info.state === state);
4663
+ }
4664
+ /**
4665
+ * Get statistics
4666
+ */
4667
+ getStatistics() {
4668
+ const infos = this.allStreamInfos;
4669
+ const active = infos.filter((i) => i.state === "open");
4670
+ const byType = {
4671
+ [StreamType.STANDARD]: 0,
4672
+ [StreamType.BULK]: 0,
4673
+ [StreamType.REALTIME]: 0
4674
+ };
4675
+ const byState = {
4676
+ connecting: 0,
4677
+ open: 0,
4678
+ closing: 0,
4679
+ closed: 0,
4680
+ error: 0
4681
+ };
4682
+ let totalBytes = 0;
4683
+ for (const info of infos) {
4684
+ byType[info.type]++;
4685
+ byState[info.state]++;
4686
+ totalBytes += info.bytesTransferred;
4687
+ }
4688
+ return {
4689
+ totalStreams: infos.length,
4690
+ activeStreams: active.length,
4691
+ streamsByType: byType,
4692
+ streamsByState: byState,
4693
+ totalBytesTransferred: totalBytes
4694
+ };
4695
+ }
4696
+ /**
4697
+ * Update stream priority
4698
+ */
4699
+ updatePriority(id, priority) {
4700
+ const info = this.streamInfos.get(id);
4701
+ if (!info) return false;
4702
+ info.priority = priority;
4703
+ return true;
4704
+ }
4705
+ /**
4706
+ * Pause all streams (backpressure)
4707
+ */
4708
+ pauseAll() {
4709
+ for (const _stream of this.streams.values());
4710
+ }
4711
+ /**
4712
+ * Resume all streams
4713
+ */
4714
+ resumeAll() {
4715
+ for (const _stream of this.streams.values());
4716
+ }
4717
+ removeStream(id) {
4718
+ this.streams.delete(id);
4719
+ this.streamTypes.delete(id);
4720
+ this.streamInfos.delete(id);
4721
+ this.handlers.onStreamCountChange?.(this.streams.size);
4722
+ this.resetIdleTimeout();
4723
+ }
4724
+ updateStreamState(id, state) {
4725
+ const info = this.streamInfos.get(id);
4726
+ if (info) info.state = state;
4727
+ }
4728
+ resetIdleTimeout() {
4729
+ if (this.idleTimeout) clearTimeout(this.idleTimeout);
4730
+ if (!this.isRunning || this.streams.size > 0) return;
4731
+ this.idleTimeout = setTimeout(() => {
4732
+ if (this.streams.size === 0) {}
4733
+ }, this.config.idleTimeoutMs);
4734
+ }
4735
+ };
4736
+ /**
4737
+ * Create a stream manager
4738
+ */
4739
+ function createStreamManager(config, handlers) {
4740
+ return new StreamManager(config, handlers);
4741
+ }
4742
+
4743
+ //#endregion
4744
+ //#region src/rpc/streaming-connection.ts
4745
+ /** Default streaming capabilities */
4746
+ const DEFAULT_STREAMING_CAPABILITIES = {
4747
+ standardStreams: true,
4748
+ bulkTransfer: true,
4749
+ realtimeStreams: true,
4750
+ maxConcurrentStreams: 100,
4751
+ maxWindowSize: 1048576,
4752
+ flowControlAlgorithms: ["sliding-window", "rate-based"]
4753
+ };
4754
+ /**
4755
+ * Extended RPC connection with streaming support
4756
+ *
4757
+ * This class wraps RpcConnection and adds stream management capabilities.
4758
+ * It can be used as a drop-in replacement for RpcConnection.
4759
+ */
4760
+ var StreamingRpcConnection = class extends require_rpc_connection.RpcConnection {
4761
+ streamManager;
4762
+ localCapabilities;
4763
+ remoteCapabilities;
4764
+ streamingEnabled;
4765
+ constructor(transport, options = {}) {
4766
+ super(transport, options);
4767
+ this.streamingEnabled = options.enableStreaming ?? true;
4768
+ this.localCapabilities = {
4769
+ ...DEFAULT_STREAMING_CAPABILITIES,
4770
+ ...options.localCapabilities
4771
+ };
4772
+ this.streamManager = new StreamManager(options.streamManagerConfig, options.streamManagerHandlers);
4773
+ this.streamManager.attach(this, transport);
4774
+ if (this.streamingEnabled) this.negotiateCapabilities();
4775
+ }
4776
+ /** Get the stream manager */
4777
+ get streams() {
4778
+ return this.streamManager;
4779
+ }
4780
+ /** Get local streaming capabilities */
4781
+ get capabilities() {
4782
+ return this.localCapabilities;
4783
+ }
4784
+ /** Get remote streaming capabilities (if negotiated) */
4785
+ get remoteStreamingCapabilities() {
4786
+ return this.remoteCapabilities;
4787
+ }
4788
+ /** Check if streaming is enabled */
4789
+ get isStreamingEnabled() {
4790
+ return this.streamingEnabled;
4791
+ }
4792
+ /**
4793
+ * Create a new standard stream
4794
+ */
4795
+ createStream(options) {
4796
+ this.ensureStreamingEnabled();
4797
+ return this.streamManager.createStream(options);
4798
+ }
4799
+ /**
4800
+ * Create a bulk transfer stream
4801
+ */
4802
+ createBulkTransfer(direction, metadata, config, handlers) {
4803
+ this.ensureStreamingEnabled();
4804
+ this.ensureCapability("bulkTransfer");
4805
+ return this.streamManager.createBulkStream(direction, metadata, config, handlers);
4806
+ }
4807
+ /**
4808
+ * Create a realtime stream
4809
+ */
4810
+ createRealtimeStream(config, handlers) {
4811
+ this.ensureStreamingEnabled();
4812
+ this.ensureCapability("realtimeStreams");
4813
+ return this.streamManager.createRealtimeStream(config, handlers);
4814
+ }
4815
+ /**
4816
+ * Get stream statistics
4817
+ */
4818
+ getStreamStatistics() {
4819
+ return this.streamManager.getStatistics();
4820
+ }
4821
+ /**
4822
+ * Close all streams gracefully
4823
+ */
4824
+ async closeAllStreams() {
4825
+ await this.streamManager.closeAllStreams();
4826
+ }
4827
+ /**
4828
+ * Override stop to properly clean up streams
4829
+ */
4830
+ async stop() {
4831
+ await this.closeAllStreams();
4832
+ this.streamManager.detach();
4833
+ await super.stop();
4834
+ }
4835
+ /**
4836
+ * Negotiate streaming capabilities with remote peer
4837
+ *
4838
+ * This would typically be done during bootstrap or connection setup.
4839
+ * For now, we assume the remote has the same capabilities.
4840
+ */
4841
+ async negotiateCapabilities() {
4842
+ this.remoteCapabilities = { ...this.localCapabilities };
4843
+ }
4844
+ /**
4845
+ * Update remote capabilities (called when received from peer)
4846
+ */
4847
+ setRemoteCapabilities(capabilities) {
4848
+ this.remoteCapabilities = capabilities;
4849
+ }
4850
+ /**
4851
+ * Check if a specific capability is supported by both peers
4852
+ */
4853
+ isCapabilitySupported(capability) {
4854
+ const localValue = this.localCapabilities[capability];
4855
+ const remoteValue = this.remoteCapabilities?.[capability];
4856
+ if (typeof localValue === "boolean" && typeof remoteValue === "boolean") return localValue && remoteValue;
4857
+ if (typeof localValue === "number" && typeof remoteValue === "number") return localValue > 0 && remoteValue > 0;
4858
+ return false;
4859
+ }
4860
+ /**
4861
+ * Create a stream for pipeline results
4862
+ *
4863
+ * This allows large pipeline results to be streamed instead of buffered.
4864
+ */
4865
+ createPipelineStream(questionId, options) {
4866
+ this.ensureStreamingEnabled();
4867
+ return this.createStream({
4868
+ ...options,
4869
+ type: StreamType.STANDARD,
4870
+ metadata: {
4871
+ ...options?.metadata,
4872
+ pipelineQuestionId: questionId.toString()
4873
+ }
4874
+ });
4875
+ }
4876
+ /**
4877
+ * Associate a stream with a capability
4878
+ *
4879
+ * This enables streaming data to/from a capability.
4880
+ */
4881
+ associateStreamWithCapability(streamId, _importId) {
4882
+ if (!this.streamManager.getStream(streamId)) throw new Error(`Stream ${streamId} not found`);
4883
+ }
4884
+ ensureStreamingEnabled() {
4885
+ if (!this.streamingEnabled) throw new Error("Streaming is not enabled on this connection");
4886
+ }
4887
+ ensureCapability(capability) {
4888
+ if (!this.isCapabilitySupported(capability)) throw new Error(`Capability '${capability}' is not supported by both peers`);
4889
+ }
4890
+ };
4891
+ /**
4892
+ * Create a streaming RPC connection
4893
+ */
4894
+ function createStreamingConnection(transport, options) {
4895
+ return new StreamingRpcConnection(transport, options);
4896
+ }
4897
+ /**
4898
+ * Check if a connection supports streaming
4899
+ */
4900
+ function supportsStreaming(connection) {
4901
+ return connection instanceof StreamingRpcConnection;
4902
+ }
4903
+
4904
+ //#endregion
4905
+ exports.AnswerTable = require_rpc_connection.AnswerTable;
4906
+ exports.BaseCapabilityClient = BaseCapabilityClient;
4907
+ exports.BulkTransfer = BulkTransfer;
4908
+ exports.BulkTransferManager = BulkTransferManager;
4909
+ exports.ConnectionManager = ConnectionManager;
4910
+ exports.DEFAULT_BULK_CONFIG = DEFAULT_BULK_CONFIG;
4911
+ exports.DEFAULT_ESCROW_CONFIG = DEFAULT_ESCROW_CONFIG;
4912
+ exports.DEFAULT_FLOW_CONTROL = DEFAULT_FLOW_CONTROL;
4913
+ exports.DEFAULT_JOIN_OPTIONS = DEFAULT_JOIN_OPTIONS;
4914
+ exports.DEFAULT_JOIN_SECURITY_POLICY = DEFAULT_JOIN_SECURITY_POLICY;
4915
+ exports.DEFAULT_REALTIME_CONFIG = DEFAULT_REALTIME_CONFIG;
4916
+ exports.DEFAULT_STREAMING_CAPABILITIES = DEFAULT_STREAMING_CAPABILITIES;
4917
+ exports.DropPolicy = DropPolicy;
828
4918
  exports.ElementSize = ElementSize;
4919
+ exports.ExportTable = require_rpc_connection.ExportTable;
4920
+ exports.ImportTable = require_rpc_connection.ImportTable;
4921
+ exports.Level3Handlers = Level3Handlers;
4922
+ exports.Level4Handlers = Level4Handlers;
829
4923
  exports.ListBuilder = ListBuilder;
830
4924
  exports.ListReader = ListReader;
4925
+ exports.MemoryPool = MemoryPool;
831
4926
  exports.MessageBuilder = MessageBuilder;
832
4927
  exports.MessageReader = MessageReader;
4928
+ exports.MultiSegmentMessageBuilder = MultiSegmentMessageBuilder;
4929
+ exports.OptimizedRpcMessageBuilder = OptimizedRpcMessageBuilder;
4930
+ exports.PIPELINE_CLIENT_SYMBOL = require_rpc_connection.PIPELINE_CLIENT_SYMBOL;
4931
+ exports.PipelineOpTracker = require_rpc_connection.PipelineOpTracker;
4932
+ exports.PipelineResolutionTracker = require_rpc_connection.PipelineResolutionTracker;
833
4933
  exports.PointerTag = PointerTag;
4934
+ exports.QuestionTable = require_rpc_connection.QuestionTable;
4935
+ exports.QueuedCallManager = require_rpc_connection.QueuedCallManager;
4936
+ exports.RealtimeStream = RealtimeStream;
4937
+ exports.RealtimeStreamManager = RealtimeStreamManager;
4938
+ exports.RestoreHandler = RestoreHandler;
4939
+ exports.RpcConnection = require_rpc_connection.RpcConnection;
834
4940
  exports.Segment = Segment;
4941
+ exports.Stream = Stream;
4942
+ exports.StreamManager = StreamManager;
4943
+ exports.StreamPriority = StreamPriority;
4944
+ exports.StreamType = StreamType;
4945
+ exports.StreamingRpcConnection = StreamingRpcConnection;
835
4946
  exports.StructBuilder = StructBuilder;
836
4947
  exports.StructReader = StructReader;
4948
+ exports.SturdyRefManager = SturdyRefManager;
837
4949
  exports.UnionBuilder = UnionBuilder;
838
4950
  exports.UnionReader = UnionReader;
839
4951
  exports.WORD_SIZE = WORD_SIZE;
4952
+ exports.WebSocketTransport = WebSocketTransport;
4953
+ exports.configureGlobalMemoryPool = configureGlobalMemoryPool;
4954
+ exports.createBulkTransferManager = createBulkTransferManager;
4955
+ exports.createPipelineClient = require_rpc_connection.createPipelineClient;
4956
+ exports.createProvisionId = createProvisionId;
4957
+ exports.createRealtimeStreamManager = createRealtimeStreamManager;
4958
+ exports.createRecipientId = createRecipientId;
4959
+ exports.createStream = createStream;
4960
+ exports.createStreamManager = createStreamManager;
4961
+ exports.createStreamingConnection = createStreamingConnection;
4962
+ exports.createSturdyRef = createSturdyRef;
4963
+ exports.createThirdPartyCapId = createThirdPartyCapId;
840
4964
  exports.createUnionBuilder = createUnionBuilder;
841
4965
  exports.createUnionReader = createUnionReader;
4966
+ exports.createZeroCopyView = createZeroCopyView;
842
4967
  exports.decodePointer = decodePointer;
4968
+ exports.deserializeRpcMessage = deserializeRpcMessage;
4969
+ exports.deserializeSturdyRef = deserializeSturdyRef;
843
4970
  exports.encodeListPointer = encodeListPointer;
844
4971
  exports.encodeStructPointer = encodeStructPointer;
4972
+ exports.fastCopy = fastCopy;
4973
+ exports.generateProvisionId = generateProvisionId;
4974
+ exports.generateVatId = generateVatId;
4975
+ exports.getGlobalMemoryPool = getGlobalMemoryPool;
4976
+ exports.isPipelineClient = require_rpc_connection.isPipelineClient;
4977
+ exports.isSameBuffer = isSameBuffer;
4978
+ exports.isStream = isStream;
4979
+ exports.isSturdyRefValid = isSturdyRefValid;
4980
+ exports.serializeRpcMessage = serializeRpcMessage;
4981
+ exports.serializeSturdyRef = serializeSturdyRef;
4982
+ exports.supportsStreaming = supportsStreaming;
845
4983
  //# sourceMappingURL=index.cjs.map