@wovin/core 0.0.9-RC3 → 0.0.10

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.
Files changed (78) hide show
  1. package/LICENSE +661 -0
  2. package/dist/applog/applog-helpers.d.ts +26 -7
  3. package/dist/applog/applog-helpers.d.ts.map +1 -1
  4. package/dist/applog/applog-utils.d.ts +11 -2
  5. package/dist/applog/applog-utils.d.ts.map +1 -1
  6. package/dist/applog/datom-types.d.ts +24 -13
  7. package/dist/applog/datom-types.d.ts.map +1 -1
  8. package/dist/applog.min.js +11 -3
  9. package/dist/chunk-4432UCLM.min.js +544 -0
  10. package/dist/chunk-4432UCLM.min.js.map +1 -0
  11. package/dist/{chunk-PTGUFZ3Q.min.js → chunk-5UN776TZ.min.js} +1 -5
  12. package/dist/{chunk-PTGUFZ3Q.min.js.map → chunk-5UN776TZ.min.js.map} +1 -1
  13. package/dist/{chunk-RMPMFLPZ.min.js → chunk-BLAIQY2K.min.js} +345 -296
  14. package/dist/chunk-BLAIQY2K.min.js.map +1 -0
  15. package/dist/chunk-DF3UOPRV.min.js +5085 -0
  16. package/dist/chunk-DF3UOPRV.min.js.map +1 -0
  17. package/dist/{chunk-QXKFFDHN.min.js → chunk-ITYJ7DMX.min.js} +5931 -5722
  18. package/dist/chunk-ITYJ7DMX.min.js.map +1 -0
  19. package/dist/chunk-QPGEBDMJ.min.js +9 -0
  20. package/dist/chunk-QPGEBDMJ.min.js.map +1 -0
  21. package/dist/index.min.js +99 -50
  22. package/dist/ipfs/car.d.ts +47 -7
  23. package/dist/ipfs/car.d.ts.map +1 -1
  24. package/dist/ipfs/ipfs-utils.d.ts +18 -7
  25. package/dist/ipfs/ipfs-utils.d.ts.map +1 -1
  26. package/dist/ipfs.min.js +26 -7
  27. package/dist/mobx/mobx-utils.d.ts +23 -17
  28. package/dist/mobx/mobx-utils.d.ts.map +1 -1
  29. package/dist/mobx.d.ts +2 -0
  30. package/dist/mobx.d.ts.map +1 -0
  31. package/dist/mobx.min.js +141 -0
  32. package/dist/pubsub/connector.d.ts +3 -1
  33. package/dist/pubsub/connector.d.ts.map +1 -1
  34. package/dist/pubsub/pub-pull.d.ts +14 -0
  35. package/dist/pubsub/pub-pull.d.ts.map +1 -0
  36. package/dist/pubsub/pub-push.d.ts +41 -0
  37. package/dist/pubsub/pub-push.d.ts.map +1 -0
  38. package/dist/pubsub/pubsub-types.d.ts +25 -0
  39. package/dist/pubsub/pubsub-types.d.ts.map +1 -1
  40. package/dist/pubsub.d.ts +2 -1
  41. package/dist/pubsub.d.ts.map +1 -1
  42. package/dist/pubsub.min.js +18 -7
  43. package/dist/query/basic.d.ts +40 -8
  44. package/dist/query/basic.d.ts.map +1 -1
  45. package/dist/query/divergences.d.ts.map +1 -1
  46. package/dist/query.min.js +36 -20
  47. package/dist/thread/basic.d.ts +24 -4
  48. package/dist/thread/basic.d.ts.map +1 -1
  49. package/dist/thread/filters.d.ts +1 -1
  50. package/dist/thread/filters.d.ts.map +1 -1
  51. package/dist/thread/mapped.d.ts +10 -3
  52. package/dist/thread/mapped.d.ts.map +1 -1
  53. package/dist/thread/utils.d.ts +16 -0
  54. package/dist/thread/utils.d.ts.map +1 -0
  55. package/dist/thread/writeable.d.ts +4 -3
  56. package/dist/thread/writeable.d.ts.map +1 -1
  57. package/dist/thread.d.ts +1 -0
  58. package/dist/thread.d.ts.map +1 -1
  59. package/dist/thread.min.js +13 -3
  60. package/dist/types/typescript-utils.d.ts +5 -4
  61. package/dist/types/typescript-utils.d.ts.map +1 -1
  62. package/dist/types.min.js +1 -5
  63. package/dist/utils.d.ts +3 -0
  64. package/dist/utils.d.ts.map +1 -1
  65. package/dist/utils.min.js +9 -0
  66. package/package.json +16 -11
  67. package/dist/chunk-GJGWIEIE.min.js +0 -66
  68. package/dist/chunk-GJGWIEIE.min.js.map +0 -1
  69. package/dist/chunk-PG6EJTCU.min.js +0 -4411
  70. package/dist/chunk-PG6EJTCU.min.js.map +0 -1
  71. package/dist/chunk-QXKFFDHN.min.js.map +0 -1
  72. package/dist/chunk-RMPMFLPZ.min.js.map +0 -1
  73. package/dist/chunk-RPPZKO5L.min.js +0 -1
  74. package/dist/chunk-WIE7ME3N.min.js +0 -120
  75. package/dist/chunk-WIE7ME3N.min.js.map +0 -1
  76. package/dist/pubsub/publication.d.ts +0 -15
  77. package/dist/pubsub/publication.d.ts.map +0 -1
  78. /package/dist/{chunk-RPPZKO5L.min.js.map → mobx.min.js.map} +0 -0
@@ -1,14 +1,30 @@
1
+ import {
2
+ keepTruthy
3
+ } from "./chunk-QPGEBDMJ.min.js";
4
+ import {
5
+ lastWriteWins
6
+ } from "./chunk-4432UCLM.min.js";
1
7
  import {
2
8
  CID,
3
- Logger,
9
+ E,
4
10
  Token,
5
11
  Type,
12
+ areCidsEqual,
13
+ containsCid,
14
+ cyrb53hash,
6
15
  decode,
7
16
  decode2,
8
17
  decode3,
9
18
  encode,
10
- makeCborEncoders
11
- } from "./chunk-PG6EJTCU.min.js";
19
+ encodeBlockOriginal,
20
+ ensureTsPvAndFinalizeApplog,
21
+ getLogsFromThread,
22
+ makeCborEncoders,
23
+ prepareForPub,
24
+ rollingFilter,
25
+ src_exports,
26
+ wrapper_default
27
+ } from "./chunk-ITYJ7DMX.min.js";
12
28
  import {
13
29
  __commonJS,
14
30
  __toESM
@@ -101,7 +117,7 @@ var require_varint = __commonJS({
101
117
  }
102
118
  });
103
119
 
104
- // ../../../node_modules/.pnpm/@ipld+dag-cbor@9.0.6/node_modules/@ipld/dag-cbor/src/index.js
120
+ // ../../../node_modules/.pnpm/@ipld+dag-cbor@9.1.0/node_modules/@ipld/dag-cbor/src/index.js
105
121
  var CID_CBOR_TAG = 42;
106
122
  function cidEncoder(obj) {
107
123
  if (obj.asCID !== obj && obj["/"] !== obj.bytes) {
@@ -130,7 +146,7 @@ function numberEncoder(num) {
130
146
  }
131
147
  return null;
132
148
  }
133
- var encodeOptions = {
149
+ var _encodeOptions = {
134
150
  float64: true,
135
151
  typeEncoders: {
136
152
  Object: cidEncoder,
@@ -138,13 +154,19 @@ var encodeOptions = {
138
154
  number: numberEncoder
139
155
  }
140
156
  };
157
+ var encodeOptions = {
158
+ ..._encodeOptions,
159
+ typeEncoders: {
160
+ ..._encodeOptions.typeEncoders
161
+ }
162
+ };
141
163
  function cidDecoder(bytes) {
142
164
  if (bytes[0] !== 0) {
143
165
  throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");
144
166
  }
145
167
  return CID.decode(bytes.subarray(1));
146
168
  }
147
- var decodeOptions = {
169
+ var _decodeOptions = {
148
170
  allowIndefinite: false,
149
171
  coerceUndefinedToNull: true,
150
172
  allowNaN: false,
@@ -158,11 +180,15 @@ var decodeOptions = {
158
180
  /** @type {import('cborg').TagDecoder[]} */
159
181
  tags: []
160
182
  };
161
- decodeOptions.tags[CID_CBOR_TAG] = cidDecoder;
162
- var encode2 = (node) => encode(node, encodeOptions);
163
- var decode4 = (data) => decode(data, decodeOptions);
183
+ _decodeOptions.tags[CID_CBOR_TAG] = cidDecoder;
184
+ var decodeOptions = {
185
+ ..._decodeOptions,
186
+ tags: _decodeOptions.tags.slice()
187
+ };
188
+ var encode2 = (node) => encode(node, _encodeOptions);
189
+ var decode4 = (data) => decode(data, _decodeOptions);
164
190
 
165
- // ../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/decoder-common.js
191
+ // ../../../node_modules/.pnpm/@ipld+car@5.2.6/node_modules/@ipld/car/src/decoder-common.js
166
192
  var import_varint = __toESM(require_varint(), 1);
167
193
  var CIDV0_BYTES = {
168
194
  SHA2_256: 18,
@@ -215,7 +241,7 @@ function getMultihashLength(bytes) {
215
241
  return mhLength;
216
242
  }
217
243
 
218
- // ../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/header-validator.js
244
+ // ../../../node_modules/.pnpm/@ipld+car@5.2.6/node_modules/@ipld/car/src/header-validator.js
219
245
  var Kinds = {
220
246
  Null: (
221
247
  /** @returns {undefined|null} */
@@ -437,10 +463,10 @@ var CarV1HeaderOrV2Pragma = {
437
463
  toRepresentation: Reprs.CarV1HeaderOrV2Pragma
438
464
  };
439
465
 
440
- // ../../../node_modules/.pnpm/cborg@4.0.5/node_modules/cborg/lib/length.js
466
+ // ../../../node_modules/.pnpm/cborg@4.0.9/node_modules/cborg/lib/length.js
441
467
  var cborEncoders = makeCborEncoders();
442
468
 
443
- // ../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/buffer-writer.js
469
+ // ../../../node_modules/.pnpm/@ipld+car@5.2.6/node_modules/@ipld/car/src/buffer-writer.js
444
470
  var import_varint2 = __toESM(require_varint(), 1);
445
471
  var headerPreludeTokens = [
446
472
  new Token(Type.map, 2),
@@ -450,7 +476,7 @@ var headerPreludeTokens = [
450
476
  ];
451
477
  var CID_TAG = new Token(Type.tag, 42);
452
478
 
453
- // ../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/decoder.js
479
+ // ../../../node_modules/.pnpm/@ipld+car@5.2.6/node_modules/@ipld/car/src/decoder.js
454
480
  async function readHeader(reader, strictVersion) {
455
481
  const length = decodeVarint(await reader.upTo(8), reader);
456
482
  if (length === 0) {
@@ -668,83 +694,7 @@ function limitReader(reader, byteLimit) {
668
694
  };
669
695
  }
670
696
 
671
- // ../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/indexer.js
672
- var CarIndexer = class {
673
- /**
674
- * @param {number} version
675
- * @param {CID[]} roots
676
- * @param {AsyncGenerator<BlockIndex>} iterator
677
- */
678
- constructor(version, roots, iterator) {
679
- this._version = version;
680
- this._roots = roots;
681
- this._iterator = iterator;
682
- }
683
- get version() {
684
- return this._version;
685
- }
686
- /**
687
- * Get the list of roots defined by the CAR referenced by this indexer. May be
688
- * zero or more `CID`s.
689
- *
690
- * @function
691
- * @memberof CarIndexer
692
- * @instance
693
- * @async
694
- * @returns {Promise<CID[]>}
695
- */
696
- async getRoots() {
697
- return this._roots;
698
- }
699
- /**
700
- * @returns {AsyncIterator<BlockIndex>}
701
- */
702
- [Symbol.asyncIterator]() {
703
- return this._iterator;
704
- }
705
- /**
706
- * Instantiate a {@link CarIndexer} from a `Uint8Array` blob. Only the header
707
- * is decoded initially, the remainder is processed and emitted via the
708
- * iterator as it is consumed.
709
- *
710
- * @async
711
- * @static
712
- * @memberof CarIndexer
713
- * @param {Uint8Array} bytes
714
- * @returns {Promise<CarIndexer>}
715
- */
716
- static async fromBytes(bytes) {
717
- if (!(bytes instanceof Uint8Array)) {
718
- throw new TypeError("fromBytes() requires a Uint8Array");
719
- }
720
- return decodeIndexerComplete(bytesReader(bytes));
721
- }
722
- /**
723
- * Instantiate a {@link CarIndexer} from a `AsyncIterable<Uint8Array>`,
724
- * such as a [modern Node.js stream](https://nodejs.org/api/stream.html#stream_streams_compatibility_with_async_generators_and_async_iterators).
725
- * is decoded initially, the remainder is processed and emitted via the
726
- * iterator as it is consumed.
727
- *
728
- * @async
729
- * @static
730
- * @memberof CarIndexer
731
- * @param {AsyncIterable<Uint8Array>} asyncIterable
732
- * @returns {Promise<CarIndexer>}
733
- */
734
- static async fromIterable(asyncIterable) {
735
- if (!asyncIterable || !(typeof asyncIterable[Symbol.asyncIterator] === "function")) {
736
- throw new TypeError("fromIterable() requires an async iterable");
737
- }
738
- return decodeIndexerComplete(asyncIterableReader(asyncIterable));
739
- }
740
- };
741
- async function decodeIndexerComplete(reader) {
742
- const decoder = createDecoder(reader);
743
- const { version, roots } = await decoder.header();
744
- return new CarIndexer(version, roots, decoder.blocksIndex());
745
- }
746
-
747
- // ../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/reader-browser.js
697
+ // ../../../node_modules/.pnpm/@ipld+car@5.2.6/node_modules/@ipld/car/src/reader-browser.js
748
698
  var CarReader = class {
749
699
  /**
750
700
  * @constructs CarReader
@@ -891,174 +841,7 @@ async function decodeReaderComplete(reader) {
891
841
  return new CarReader(header, blocks);
892
842
  }
893
843
 
894
- // ../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/iterator.js
895
- var CarIteratorBase = class {
896
- /**
897
- * @param {number} version
898
- * @param {CID[]} roots
899
- * @param {AsyncIterable<Block>|void} iterable
900
- */
901
- constructor(version, roots, iterable) {
902
- this._version = version;
903
- this._roots = roots;
904
- this._iterable = iterable;
905
- this._decoded = false;
906
- }
907
- get version() {
908
- return this._version;
909
- }
910
- /**
911
- * @returns {Promise<CID[]>}
912
- */
913
- async getRoots() {
914
- return this._roots;
915
- }
916
- };
917
- var CarBlockIterator = class _CarBlockIterator extends CarIteratorBase {
918
- // inherited method
919
- /**
920
- * Get the list of roots defined by the CAR referenced by this iterator. May be
921
- * zero or more `CID`s.
922
- *
923
- * @function getRoots
924
- * @memberof CarBlockIterator
925
- * @instance
926
- * @async
927
- * @returns {Promise<CID[]>}
928
- */
929
- /**
930
- * @returns {AsyncIterator<Block>}
931
- */
932
- [Symbol.asyncIterator]() {
933
- if (this._decoded) {
934
- throw new Error("Cannot decode more than once");
935
- }
936
- if (!this._iterable) {
937
- throw new Error("Block iterable not found");
938
- }
939
- this._decoded = true;
940
- return this._iterable[Symbol.asyncIterator]();
941
- }
942
- /**
943
- * Instantiate a {@link CarBlockIterator} from a `Uint8Array` blob. Rather
944
- * than decoding the entire byte array prior to returning the iterator, as in
945
- * {@link CarReader.fromBytes}, only the header is decoded and the remainder
946
- * of the CAR is parsed as the `Block`s as yielded.
947
- *
948
- * @async
949
- * @static
950
- * @memberof CarBlockIterator
951
- * @param {Uint8Array} bytes
952
- * @returns {Promise<CarBlockIterator>}
953
- */
954
- static async fromBytes(bytes) {
955
- const { version, roots, iterator } = await fromBytes2(bytes);
956
- return new _CarBlockIterator(version, roots, iterator);
957
- }
958
- /**
959
- * Instantiate a {@link CarBlockIterator} from a `AsyncIterable<Uint8Array>`,
960
- * such as a [modern Node.js stream](https://nodejs.org/api/stream.html#stream_streams_compatibility_with_async_generators_and_async_iterators).
961
- * Rather than decoding the entire byte array prior to returning the iterator,
962
- * as in {@link CarReader.fromIterable}, only the header is decoded and the
963
- * remainder of the CAR is parsed as the `Block`s as yielded.
964
- *
965
- * @async
966
- * @static
967
- * @param {AsyncIterable<Uint8Array>} asyncIterable
968
- * @returns {Promise<CarBlockIterator>}
969
- */
970
- static async fromIterable(asyncIterable) {
971
- const { version, roots, iterator } = await fromIterable(asyncIterable);
972
- return new _CarBlockIterator(version, roots, iterator);
973
- }
974
- };
975
- var CarCIDIterator = class _CarCIDIterator extends CarIteratorBase {
976
- // inherited method
977
- /**
978
- * Get the list of roots defined by the CAR referenced by this iterator. May be
979
- * zero or more `CID`s.
980
- *
981
- * @function getRoots
982
- * @memberof CarCIDIterator
983
- * @instance
984
- * @async
985
- * @returns {Promise<CID[]>}
986
- */
987
- /**
988
- * @returns {AsyncIterator<CID>}
989
- */
990
- [Symbol.asyncIterator]() {
991
- if (this._decoded) {
992
- throw new Error("Cannot decode more than once");
993
- }
994
- if (!this._iterable) {
995
- throw new Error("Block iterable not found");
996
- }
997
- this._decoded = true;
998
- const iterable = this._iterable[Symbol.asyncIterator]();
999
- return {
1000
- async next() {
1001
- const next = await iterable.next();
1002
- if (next.done) {
1003
- return next;
1004
- }
1005
- return { done: false, value: next.value.cid };
1006
- }
1007
- };
1008
- }
1009
- /**
1010
- * Instantiate a {@link CarCIDIterator} from a `Uint8Array` blob. Rather
1011
- * than decoding the entire byte array prior to returning the iterator, as in
1012
- * {@link CarReader.fromBytes}, only the header is decoded and the remainder
1013
- * of the CAR is parsed as the `CID`s as yielded.
1014
- *
1015
- * @async
1016
- * @static
1017
- * @memberof CarCIDIterator
1018
- * @param {Uint8Array} bytes
1019
- * @returns {Promise<CarCIDIterator>}
1020
- */
1021
- static async fromBytes(bytes) {
1022
- const { version, roots, iterator } = await fromBytes2(bytes);
1023
- return new _CarCIDIterator(version, roots, iterator);
1024
- }
1025
- /**
1026
- * Instantiate a {@link CarCIDIterator} from a `AsyncIterable<Uint8Array>`,
1027
- * such as a [modern Node.js stream](https://nodejs.org/api/stream.html#stream_streams_compatibility_with_async_generators_and_async_iterators).
1028
- * Rather than decoding the entire byte array prior to returning the iterator,
1029
- * as in {@link CarReader.fromIterable}, only the header is decoded and the
1030
- * remainder of the CAR is parsed as the `CID`s as yielded.
1031
- *
1032
- * @async
1033
- * @static
1034
- * @memberof CarCIDIterator
1035
- * @param {AsyncIterable<Uint8Array>} asyncIterable
1036
- * @returns {Promise<CarCIDIterator>}
1037
- */
1038
- static async fromIterable(asyncIterable) {
1039
- const { version, roots, iterator } = await fromIterable(asyncIterable);
1040
- return new _CarCIDIterator(version, roots, iterator);
1041
- }
1042
- };
1043
- async function fromBytes2(bytes) {
1044
- if (!(bytes instanceof Uint8Array)) {
1045
- throw new TypeError("fromBytes() requires a Uint8Array");
1046
- }
1047
- return decodeIterator(bytesReader(bytes));
1048
- }
1049
- async function fromIterable(asyncIterable) {
1050
- if (!asyncIterable || !(typeof asyncIterable[Symbol.asyncIterator] === "function")) {
1051
- throw new TypeError("fromIterable() requires an async iterable");
1052
- }
1053
- return decodeIterator(asyncIterableReader(asyncIterable));
1054
- }
1055
- async function decodeIterator(reader) {
1056
- const decoder = createDecoder(reader);
1057
- const { version, roots } = await decoder.header();
1058
- return { version, roots, iterator: decoder.blocks() };
1059
- }
1060
-
1061
- // ../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/encoder.js
844
+ // ../../../node_modules/.pnpm/@ipld+car@5.2.6/node_modules/@ipld/car/src/encoder.js
1062
845
  var import_varint3 = __toESM(require_varint(), 1);
1063
846
  function createHeader(roots) {
1064
847
  const headerBytes = encode2({ version: 1, roots });
@@ -1099,7 +882,7 @@ function createEncoder(writer) {
1099
882
  };
1100
883
  }
1101
884
 
1102
- // ../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/iterator-channel.js
885
+ // ../../../node_modules/.pnpm/@ipld+car@5.2.6/node_modules/@ipld/car/src/iterator-channel.js
1103
886
  function noop() {
1104
887
  }
1105
888
  function create() {
@@ -1168,7 +951,7 @@ function create() {
1168
951
  return { writer, iterator };
1169
952
  }
1170
953
 
1171
- // ../../../node_modules/.pnpm/@ipld+car@5.2.4/node_modules/@ipld/car/src/writer-browser.js
954
+ // ../../../node_modules/.pnpm/@ipld+car@5.2.6/node_modules/@ipld/car/src/writer-browser.js
1172
955
  var CarWriter = class _CarWriter {
1173
956
  /**
1174
957
  * @param {CID[]} roots
@@ -1338,54 +1121,307 @@ function toRoots(roots) {
1338
1121
  return _roots;
1339
1122
  }
1340
1123
 
1341
- // src/ipfs/car.ts
1342
- var { WARN, LOG, DEBUG, VERBOSE, ERROR } = Logger.setup(Logger.INFO);
1343
- async function decodeCarToApplogs(car) {
1344
- const { roots, blocks } = await decodeCar(car);
1345
- if (!roots || !blocks) {
1346
- throw ERROR("decodeCar is funky", { roots, blocks });
1124
+ // src/pubsub/pub-pull.ts
1125
+ var { WARN, LOG, DEBUG, VERBOSE, ERROR } = E.setup(E.DEBUG);
1126
+ function integratePub({ targetThread, agentHash, subID, pubData }) {
1127
+ const newLogs = pubData.thread.applogs.filter((log) => !targetThread.hasApplog(log, false));
1128
+ LOG(`[integratePub] integrating ${newLogs.length} logs`, { targetThread, subID, pubData });
1129
+ let toInsert = newLogs;
1130
+ if (subID) {
1131
+ toInsert = toInsert.concat(ensureTsPvAndFinalizeApplog(
1132
+ { en: subID, at: "subscription/cid", vl: pubData.cid.toString(), ag: agentHash },
1133
+ targetThread
1134
+ ));
1347
1135
  }
1348
- if (roots.length !== 1) {
1349
- WARN("Unexpected roots count:", roots);
1136
+ targetThread.insertRaw(toInsert);
1137
+ return newLogs;
1138
+ }
1139
+
1140
+ // src/pubsub/pub-push.ts
1141
+ var { WARN: WARN2, LOG: LOG2, DEBUG: DEBUG2, VERBOSE: VERBOSE2, ERROR: ERROR2 } = E.setup(E.DEBUG);
1142
+ async function preparePubForPush(agent, appThread, threadToPublish, publication, prevPubCID) {
1143
+ let logsToPublish = getLogsFromThread(threadToPublish);
1144
+ DEBUG2(`[preparePubForPush] Collected ${logsToPublish.length} logs :`, {
1145
+ logsToPublish,
1146
+ threadOrLogsCount: threadToPublish.nameAndSizeUntracked || `[${threadToPublish.length}]`
1147
+ });
1148
+ const { sharedAgents, sharedKeyMap, sharedKey, pubCounter } = publication ?? {};
1149
+ const getExistingOrNewLog = (thread, publication2, ag, at, vl) => {
1150
+ let logInQuestion = rollingFilter(lastWriteWins(thread), { en: publication2.id, at }).latestLog;
1151
+ if (!logInQuestion && vl !== void 0) {
1152
+ logInQuestion = ensureTsPvAndFinalizeApplog({ ag, en: publication2.id, at, vl }, thread);
1153
+ }
1154
+ return logInQuestion;
1155
+ };
1156
+ const pubNameLog = getExistingOrNewLog(appThread, publication, agent.ag, "pub/name", publication.name);
1157
+ const pubCounterLog = getExistingOrNewLog(appThread, publication, agent.ag, "pub/counter", `${agent.did}<::>${pubCounter}`);
1158
+ const encryptApplog = async (applog, keyToUse) => {
1159
+ const { log: eachLog, cid } = prepareForPub(applog);
1160
+ const enc = new TextEncoder();
1161
+ const stringified = wrapper_default(eachLog);
1162
+ const stringifiedEncodedAppLogPayload = enc.encode(stringified);
1163
+ VERBOSE2("[odd]", { eachLog, stringified, stringifiedEncodedAppLogPayload });
1164
+ try {
1165
+ const encPayload = await agent.crypto?.aes.encrypt(stringifiedEncodedAppLogPayload, keyToUse, "AES-GCM");
1166
+ VERBOSE2("[odd] encrypted length:", stringifiedEncodedAppLogPayload.length, { encPayload });
1167
+ return encPayload;
1168
+ } catch (err) {
1169
+ throw ERROR2("FAILED TO ENC payload length:", stringifiedEncodedAppLogPayload.length, { err });
1170
+ }
1171
+ };
1172
+ let maybeEncryptedApplogs;
1173
+ const encryptedApplogs = [];
1174
+ const agentSharedKeyLogs = [];
1175
+ if (sharedAgents) {
1176
+ if (!sharedKey || !sharedKeyMap) {
1177
+ throw ERROR2("sharedAgents but no Keys/Map", { sharedAgents, sharedKeyMap, sharedKey });
1178
+ }
1179
+ LOG2("encrypting", { sharedAgents, sharedKeyMap });
1180
+ for (const [eachAgent, eachEncKey] of Array.from(sharedKeyMap.entries())) {
1181
+ VERBOSE2.force("adding key", { eachAgent, eachEncKey });
1182
+ agentSharedKeyLogs.push({
1183
+ ag: agent.ag,
1184
+ en: eachAgent,
1185
+ at: "pub/sharedKey",
1186
+ vl: eachEncKey
1187
+ // these are encrypted with the derived key from the local agent private and remote agent public keys
1188
+ });
1189
+ }
1190
+ const CIDlist = [];
1191
+ const pubCIDmap = {};
1192
+ for (const eachLog of logsToPublish) {
1193
+ VERBOSE2.force("[crypto] encrypting ", { eachLog, sharedKey });
1194
+ const encPayload = await encryptApplog(eachLog, sharedKey);
1195
+ DEBUG2.force("[crypto] encrypted ", { eachLog, encPayload, sharedKey });
1196
+ encryptedApplogs.push({ enc: encPayload });
1197
+ }
1198
+ maybeEncryptedApplogs = encryptedApplogs;
1199
+ } else {
1200
+ maybeEncryptedApplogs = logsToPublish;
1201
+ }
1202
+ DEBUG2.force("adding all agent info and pubAtoms", { publication, agent, logsToPublish, threadToPublish, agentSharedKeyLogs });
1203
+ const infoLogs = [
1204
+ ...rollingFilter(lastWriteWins(appThread), {
1205
+ // TODO: use static filter for performance
1206
+ en: agent.ag,
1207
+ at: ["agent/ecdh", "agent/jwkd", "agent/appAgent"]
1208
+ }).applogs,
1209
+ ...pubNameLog ? [pubNameLog] : [],
1210
+ ...pubCounterLog ? [pubCounterLog] : [],
1211
+ ...agentSharedKeyLogs
1212
+ ];
1213
+ DEBUG2(`[preparePubForPush] info logs:`, infoLogs);
1214
+ if (!infoLogs.find(({ at }) => at === "agent/appAgent"))
1215
+ throw ERROR2(`[preparePubForPush] appThread missing agent/appAgent log`);
1216
+ const applogsToEncode = keepTruthy(maybeEncryptedApplogs);
1217
+ const infologsToEncode = keepTruthy(infoLogs);
1218
+ if (!applogsToEncode.length) {
1219
+ throw ERROR2("no valid applogs", { agent, maybeEncryptedApplogs, infoLogs, applogsToEncode, infologsToEncode, prevPubCID });
1350
1220
  }
1351
- const root = blocks.get(roots[0]);
1352
- let applogArr;
1353
- DEBUG(`root:`, root, { blocks });
1354
- if (root.info) {
1355
- applogArr = blocks.get(root.applogs.toString()).logs;
1356
- DEBUG(`new format - infoLogs`, blocks.get(root.info.toString()));
1221
+ if (!infologsToEncode.length) {
1222
+ throw ERROR2("no valid infologs", { agent, maybeEncryptedApplogs, infoLogs, applogsToEncode, infologsToEncode, prevPubCID });
1223
+ }
1224
+ const encodedPub = encodePubAsCar(agent, applogsToEncode, infologsToEncode, prevPubCID);
1225
+ DEBUG2("inPreparePubForPush", { encodedPub });
1226
+ return encodedPub;
1227
+ }
1228
+ async function encodePubAsCar(agent, applogs, infoLogs, prevPubCID) {
1229
+ DEBUG2(`[encodePubAsCar] encoding`, { agent, applogs, infoLogs });
1230
+ const { cids: infoLogCids, encodedApplogs: encodedInfoLogs } = await encodeApplogsAsIPLD(infoLogs);
1231
+ const { cids: applogCids, encodedApplogs } = await encodeApplogsAsIPLD(applogs);
1232
+ const blocks = [...encodedApplogs, ...encodedInfoLogs];
1233
+ const infoLogsWrap = await encodeBlockOriginal({ logs: infoLogCids });
1234
+ blocks.push(infoLogsWrap);
1235
+ const { rootCID: chunkRootCID, blocks: chunkBlocks } = await chunkApplogs(applogCids);
1236
+ blocks.push(...chunkBlocks);
1237
+ const infoSignature = await agent.sign(infoLogsWrap.cid.bytes);
1238
+ const applogsSignature = await agent.sign(chunkRootCID.bytes);
1239
+ const root = {
1240
+ info: infoLogsWrap.cid,
1241
+ applogs: chunkRootCID,
1242
+ infoSignature,
1243
+ applogsSignature,
1244
+ prev: prevPubCID
1245
+ };
1246
+ DEBUG2("[encodePubAsCar] encoding root", { root, logCids: applogCids, infoLogCids });
1247
+ const encodedRoot = await encodeBlockOriginal(root);
1248
+ blocks.push(encodedRoot);
1249
+ DEBUG2("[encodePubAsCar] => root", { encodedRoot });
1250
+ return {
1251
+ cid: encodedRoot.cid,
1252
+ blob: await makeCarBlob(encodedRoot.cid, blocks),
1253
+ // TODO: create CarBuilder (incl .encodeAndAdd({...}))
1254
+ blocks,
1255
+ infoLogCids,
1256
+ applogCids
1257
+ };
1258
+ }
1259
+ async function chunkApplogs(applogCids, size = 1e4) {
1260
+ if (!applogCids.length)
1261
+ throw ERROR2(`[chunkApplogs] called with empty array`);
1262
+ const chunks = [];
1263
+ for (let i = 0; i < applogCids.length; i += size) {
1264
+ const chunk = await encodeBlockOriginal({ logs: applogCids.slice(i, Math.min(i + applogCids.length, i + size)) });
1265
+ chunks.push(chunk);
1266
+ }
1267
+ if (chunks.length === 1)
1268
+ return { rootCID: chunks[0].cid, blocks: chunks };
1269
+ const root = await encodeBlockOriginal({ chunks: chunks.map((chunk) => chunk.cid) });
1270
+ const blocks = [root, ...chunks];
1271
+ DEBUG2(`[chunkApplogs] ${applogCids.length} logs chunked into ${chunks.length}`, { applogCids, root, blocks, chunks, dagJson: src_exports });
1272
+ return { rootCID: root.cid, blocks, chunks };
1273
+ }
1274
+ async function unchunkApplogsBlock(block, blockStore) {
1275
+ if (isPubBlockChunks(block)) {
1276
+ return (await Promise.all(
1277
+ block.chunks.map(async (chunkCid) => {
1278
+ const block2 = await getDecodedBlock(blockStore, chunkCid);
1279
+ if (!block2.logs)
1280
+ throw ERROR2(`Weird chunk`, block2);
1281
+ return block2.logs;
1282
+ })
1283
+ )).flat();
1357
1284
  } else {
1358
- applogArr = root.applogs;
1285
+ return block.logs;
1359
1286
  }
1360
- let applogs;
1361
- applogs = applogArr.map((cidOrLink) => {
1362
- const cid = cidOrLink.toV1 ? cidOrLink.toV1().toString() : cidOrLink["/"];
1363
- const applog = blocks.get(cid);
1287
+ }
1288
+ function isPubBlockChunks(block) {
1289
+ return block.chunks;
1290
+ }
1291
+ async function encodeApplogsAsCar(applogs) {
1292
+ const encoded = await encodeApplogsAsIPLD(applogs);
1293
+ if (!encoded)
1294
+ throw ERROR2("invalid applogs cannot continue", { applogs, encoded });
1295
+ const { cids, encodedApplogs } = encoded;
1296
+ const root = { applogs: cids };
1297
+ const encodedRoot = await encodeBlockOriginal(root);
1298
+ DEBUG2("[encodeApplogsAsCar] encoded root", { cids, encodedRoot });
1299
+ return await makeCarBlob(encodedRoot.cid, [encodedRoot, ...encodedApplogs]);
1300
+ }
1301
+ async function encodeApplogsAsIPLD(applogs) {
1302
+ DEBUG2.force({ applogs });
1303
+ const validApplogs = applogs.filter((eachLog) => !!eachLog);
1304
+ DEBUG2.force({ validApplogs });
1305
+ if (!validApplogs.length)
1306
+ throw ERROR2("no valid applogs");
1307
+ const preppedLogs = validApplogs.map((log) => prepareForPub(log).log);
1308
+ const encodedApplogs = await Promise.all(preppedLogs.map(encodeBlockOriginal));
1309
+ DEBUG2.force("[encodeApplogsAsIpld] encoded applogs", { preppedLogs, encodedApplogs });
1310
+ const cids = encodedApplogs.map((b) => {
1311
+ if (!b.cid)
1312
+ throw ERROR2(`[publish] no cid for encoded log:`, b);
1313
+ return b.cid;
1314
+ });
1315
+ return { cids, encodedApplogs };
1316
+ }
1317
+
1318
+ // src/pubsub/pubsub-types.ts
1319
+ function isPublication(obj) {
1320
+ return obj?.pk !== void 0 && obj?.lastPush !== void 0;
1321
+ }
1322
+ function isSubscription(obj) {
1323
+ return obj?.lastPull !== void 0;
1324
+ }
1325
+ function agentToShortHash(agentString) {
1326
+ return cyrb53hash(agentString, 31, 7);
1327
+ }
1328
+
1329
+ // src/ipfs/car.ts
1330
+ var { WARN: WARN3, LOG: LOG3, DEBUG: DEBUG3, VERBOSE: VERBOSE3, ERROR: ERROR3 } = E.setup(E.DEBUG);
1331
+ async function decodePubFromCar(car) {
1332
+ const decoded = await getBlocksOfCar(car);
1333
+ return await decodePubFromBlocks(decoded);
1334
+ }
1335
+ async function decodePubFromBlocks({ rootCID, blockStore }, recursionTrace = []) {
1336
+ if (!rootCID || !blockStore) {
1337
+ throw ERROR3("Empty roots/blocks", { rootCID, blockStore });
1338
+ }
1339
+ const root = await getDecodedBlock(blockStore, rootCID);
1340
+ let pubLogsArray;
1341
+ let applogsCID = null;
1342
+ let info = null;
1343
+ VERBOSE3(`[decodePubFromBlocks] root:`, rootCID.toString(), root, { blockStore });
1344
+ if (!root)
1345
+ throw ERROR3("root not found in blockStore", { blockStore, rootCID });
1346
+ if (root?.info) {
1347
+ applogsCID = root.applogs;
1348
+ const applogsBlock = await getDecodedBlock(blockStore, applogsCID);
1349
+ pubLogsArray = await unchunkApplogsBlock(applogsBlock, blockStore);
1350
+ info = await getDecodedBlock(blockStore, root.info);
1351
+ DEBUG3(`new format - infoLogs`, info.logs.map((l) => ({ [l.toString()]: l })));
1352
+ } else {
1353
+ pubLogsArray = root.applogs;
1354
+ }
1355
+ const resolveLogFromCidLink = async (cidOrLink) => {
1356
+ const cid = cidOrLink;
1357
+ const applog = await getDecodedBlock(blockStore, cid);
1364
1358
  if (!applog) {
1365
- ERROR(`Could not find applog CID in Car file:`, cid, { root, blocks });
1366
- throw new Error(`Could not find applog CID in Car file: ${cid.toString()}`);
1359
+ ERROR3(`Could not find applog CID in pub blocks:`, cid.toString(), { cid, root, blockStore });
1360
+ throw new Error(`Could not find applog CID in pub blocks: ${cid.toString()}`);
1367
1361
  }
1368
1362
  if (applog.pv instanceof CID)
1369
1363
  applog.pv = applog.pv.toV1().toString();
1370
1364
  return {
1371
1365
  ...applog,
1372
- cid
1366
+ cid: cid.toV1().toString()
1373
1367
  };
1374
- });
1375
- DEBUG("Decoded car logs:", root, { roots, blocks, applogs });
1376
- return { applogs };
1368
+ };
1369
+ let applogs;
1370
+ applogs = await Promise.all(pubLogsArray.map(resolveLogFromCidLink));
1371
+ if (root.prev) {
1372
+ if (areCidsEqual(root.prev, rootCID) || containsCid(recursionTrace, root.prev)) {
1373
+ throw ERROR3(`[pubFromBlocks] pub chain has a loop`, { rootCID, prev: root.prev, recursionTrace });
1374
+ }
1375
+ applogs.push(...(await decodePubFromBlocks({ rootCID: root.prev, blockStore }, [...recursionTrace, rootCID])).applogs);
1376
+ }
1377
+ const result = {
1378
+ cid: rootCID,
1379
+ info: {
1380
+ ...info,
1381
+ logs: await Promise.all(info.logs.map(resolveLogFromCidLink))
1382
+ },
1383
+ applogsCID,
1384
+ applogs
1385
+ };
1386
+ DEBUG3("[decodePubFromBlocks] result:", result, { rootCID: rootCID.toString(), root, blockStore, applogs, info });
1387
+ return result;
1377
1388
  }
1378
- async function decodeCar(car) {
1379
- const roots = (await car.getRoots()).map((c) => c.toV1().toString());
1389
+ async function getBlocksOfCar(car) {
1390
+ const rootsFromCar = await car.getRoots();
1391
+ const roots = rootsFromCar.map((c) => (typeof c.toV1 === "function" ? c : CID.decode(c.bytes)).toV1().toString());
1380
1392
  const blocks = /* @__PURE__ */ new Map();
1381
- for await (const { cid, bytes } of car.blocks()) {
1382
- blocks.set(cid.toV1().toString(), decode3(bytes));
1393
+ for await (const { cid: cidFromCarblocks, bytes } of car.blocks()) {
1394
+ const cid = typeof cidFromCarblocks.toV1 === "function" ? cidFromCarblocks : CID.decode(cidFromCarblocks.bytes);
1395
+ VERBOSE3({ cidFromCarblocks, cid });
1396
+ blocks.set(cid.toV1().toString(), bytes);
1397
+ }
1398
+ if (roots.length !== 1) {
1399
+ WARN3("Unexpected roots count:", roots);
1400
+ }
1401
+ return {
1402
+ rootCID: CID.parse(roots[0]),
1403
+ blockStore: {
1404
+ get: (cid) => blocks.get(cid.toV1().toString())
1405
+ }
1406
+ };
1407
+ }
1408
+ async function getDecodedBlock(blockStore, cid) {
1409
+ try {
1410
+ var blob = await blockStore.get(cid);
1411
+ if (!blob) {
1412
+ WARN3("returning null");
1413
+ return null;
1414
+ }
1415
+ } catch (err) {
1416
+ if (err.message === "Not Found")
1417
+ return null;
1418
+ throw err;
1383
1419
  }
1384
- return { roots, blocks };
1420
+ return decode3(blob);
1385
1421
  }
1386
1422
  async function makeCarOut(roots, blocks) {
1387
1423
  const { writer, out } = CarWriter.create(Array.isArray(roots) ? roots : [roots]);
1388
- VERBOSE(`Writing ${blocks.length} blocks to CAR`, { roots, blocks });
1424
+ VERBOSE3(`Writing ${blocks.length} blocks to CAR`, { roots, blocks });
1389
1425
  blocks.forEach((b) => writer.put(b));
1390
1426
  writer.close();
1391
1427
  return out;
@@ -1406,6 +1442,7 @@ function streamReaderToIterable(bodyReader) {
1406
1442
  return async function* () {
1407
1443
  while (true) {
1408
1444
  const { done, value } = await bodyReader.read();
1445
+ VERBOSE3(`[car] chunk`, { done, value });
1409
1446
  if (done) {
1410
1447
  break;
1411
1448
  }
@@ -1415,11 +1452,23 @@ function streamReaderToIterable(bodyReader) {
1415
1452
  }
1416
1453
 
1417
1454
  export {
1418
- decodeCarToApplogs,
1419
- decodeCar,
1455
+ decodePubFromCar,
1456
+ decodePubFromBlocks,
1457
+ getBlocksOfCar,
1458
+ getDecodedBlock,
1420
1459
  makeCarOut,
1421
1460
  makeCarBlob,
1422
1461
  carFromBlob,
1423
- streamReaderToIterable
1462
+ streamReaderToIterable,
1463
+ integratePub,
1464
+ preparePubForPush,
1465
+ encodePubAsCar,
1466
+ chunkApplogs,
1467
+ unchunkApplogsBlock,
1468
+ isPubBlockChunks,
1469
+ encodeApplogsAsCar,
1470
+ isPublication,
1471
+ isSubscription,
1472
+ agentToShortHash
1424
1473
  };
1425
- //# sourceMappingURL=chunk-RMPMFLPZ.min.js.map
1474
+ //# sourceMappingURL=chunk-BLAIQY2K.min.js.map