@fireproof/core 0.4.1 → 0.5.1

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.
@@ -9541,15 +9541,7 @@ var _polyfillNode_events = /*#__PURE__*/Object.freeze({
9541
9541
 
9542
9542
  var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_events);
9543
9543
 
9544
- var streamBrowser;
9545
- var hasRequiredStreamBrowser;
9546
-
9547
- function requireStreamBrowser () {
9548
- if (hasRequiredStreamBrowser) return streamBrowser;
9549
- hasRequiredStreamBrowser = 1;
9550
- streamBrowser = require$$0$1.EventEmitter;
9551
- return streamBrowser;
9552
- }
9544
+ var streamBrowser = require$$0$1.EventEmitter;
9553
9545
 
9554
9546
  // shim for using process in browser
9555
9547
  // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
@@ -9692,7 +9684,7 @@ var argv = [];
9692
9684
  var version$2 = ''; // empty string to avoid regexp issues
9693
9685
  var versions = {};
9694
9686
  var release = {};
9695
- var config = {};
9687
+ var config$1 = {};
9696
9688
 
9697
9689
  function noop$2() {}
9698
9690
 
@@ -9769,7 +9761,7 @@ var browser$1$1 = {
9769
9761
  hrtime: hrtime,
9770
9762
  platform: platform,
9771
9763
  release: release,
9772
- config: config,
9764
+ config: config$1,
9773
9765
  uptime: uptime
9774
9766
  };
9775
9767
 
@@ -9850,11 +9842,11 @@ function format(f) {
9850
9842
  // Mark that a method should not be used.
9851
9843
  // Returns a modified function which warns once by default.
9852
9844
  // If --no-deprecation is set, then it is a no-op.
9853
- function deprecate$1(fn, msg) {
9845
+ function deprecate$2(fn, msg) {
9854
9846
  // Allow for deprecating things in the process of starting up.
9855
9847
  if (isUndefined(global$1.process)) {
9856
9848
  return function() {
9857
- return deprecate$1(fn, msg).apply(this, arguments);
9849
+ return deprecate$2(fn, msg).apply(this, arguments);
9858
9850
  };
9859
9851
  }
9860
9852
 
@@ -10463,7 +10455,7 @@ var _polyfillNode_util = {
10463
10455
  isBoolean: isBoolean,
10464
10456
  isArray: isArray,
10465
10457
  inspect: inspect,
10466
- deprecate: deprecate$1,
10458
+ deprecate: deprecate$2,
10467
10459
  format: format,
10468
10460
  debuglog: debuglog,
10469
10461
  promisify: promisify,
@@ -10476,7 +10468,7 @@ var _polyfillNode_util$1 = /*#__PURE__*/Object.freeze({
10476
10468
  callbackify: callbackify,
10477
10469
  debuglog: debuglog,
10478
10470
  default: _polyfillNode_util,
10479
- deprecate: deprecate$1,
10471
+ deprecate: deprecate$2,
10480
10472
  format: format,
10481
10473
  inherits: inherits$w,
10482
10474
  inspect: inspect,
@@ -10664,108 +10656,99 @@ function requireBuffer_list () {
10664
10656
  return buffer_list;
10665
10657
  }
10666
10658
 
10667
- var destroy_1;
10668
- var hasRequiredDestroy;
10669
-
10670
- function requireDestroy () {
10671
- if (hasRequiredDestroy) return destroy_1;
10672
- hasRequiredDestroy = 1;
10673
-
10674
- // undocumented cb() API, needed for core, not for public API
10675
- function destroy(err, cb) {
10676
- const readableDestroyed = this._readableState && this._readableState.destroyed;
10677
- const writableDestroyed = this._writableState && this._writableState.destroyed;
10678
- if (readableDestroyed || writableDestroyed) {
10679
- if (cb) {
10680
- cb(err);
10681
- } else if (err) {
10682
- if (!this._writableState) {
10683
- process.nextTick(emitErrorNT, this, err);
10684
- } else if (!this._writableState.errorEmitted) {
10685
- this._writableState.errorEmitted = true;
10686
- process.nextTick(emitErrorNT, this, err);
10687
- }
10688
- }
10689
- return this;
10690
- }
10659
+ // undocumented cb() API, needed for core, not for public API
10660
+ function destroy(err, cb) {
10661
+ const readableDestroyed = this._readableState && this._readableState.destroyed;
10662
+ const writableDestroyed = this._writableState && this._writableState.destroyed;
10663
+ if (readableDestroyed || writableDestroyed) {
10664
+ if (cb) {
10665
+ cb(err);
10666
+ } else if (err) {
10667
+ if (!this._writableState) {
10668
+ process.nextTick(emitErrorNT, this, err);
10669
+ } else if (!this._writableState.errorEmitted) {
10670
+ this._writableState.errorEmitted = true;
10671
+ process.nextTick(emitErrorNT, this, err);
10672
+ }
10673
+ }
10674
+ return this;
10675
+ }
10691
10676
 
10692
- // we set destroyed to true before firing error callbacks in order
10693
- // to make it re-entrance safe in case destroy() is called within callbacks
10677
+ // we set destroyed to true before firing error callbacks in order
10678
+ // to make it re-entrance safe in case destroy() is called within callbacks
10694
10679
 
10695
- if (this._readableState) {
10696
- this._readableState.destroyed = true;
10697
- }
10680
+ if (this._readableState) {
10681
+ this._readableState.destroyed = true;
10682
+ }
10698
10683
 
10699
- // if this is a duplex stream mark the writable part as destroyed as well
10700
- if (this._writableState) {
10701
- this._writableState.destroyed = true;
10702
- }
10703
- this._destroy(err || null, err => {
10704
- if (!cb && err) {
10705
- if (!this._writableState) {
10706
- process.nextTick(emitErrorAndCloseNT, this, err);
10707
- } else if (!this._writableState.errorEmitted) {
10708
- this._writableState.errorEmitted = true;
10709
- process.nextTick(emitErrorAndCloseNT, this, err);
10710
- } else {
10711
- process.nextTick(emitCloseNT, this);
10712
- }
10713
- } else if (cb) {
10714
- process.nextTick(emitCloseNT, this);
10715
- cb(err);
10716
- } else {
10717
- process.nextTick(emitCloseNT, this);
10718
- }
10719
- });
10720
- return this;
10721
- }
10722
- function emitErrorAndCloseNT(self, err) {
10723
- emitErrorNT(self, err);
10724
- emitCloseNT(self);
10725
- }
10726
- function emitCloseNT(self) {
10727
- if (self._writableState && !self._writableState.emitClose) return;
10728
- if (self._readableState && !self._readableState.emitClose) return;
10729
- self.emit('close');
10730
- }
10731
- function undestroy() {
10732
- if (this._readableState) {
10733
- this._readableState.destroyed = false;
10734
- this._readableState.reading = false;
10735
- this._readableState.ended = false;
10736
- this._readableState.endEmitted = false;
10737
- }
10738
- if (this._writableState) {
10739
- this._writableState.destroyed = false;
10740
- this._writableState.ended = false;
10741
- this._writableState.ending = false;
10742
- this._writableState.finalCalled = false;
10743
- this._writableState.prefinished = false;
10744
- this._writableState.finished = false;
10745
- this._writableState.errorEmitted = false;
10746
- }
10747
- }
10748
- function emitErrorNT(self, err) {
10749
- self.emit('error', err);
10750
- }
10751
- function errorOrDestroy(stream, err) {
10752
- // We have tests that rely on errors being emitted
10753
- // in the same tick, so changing this is semver major.
10754
- // For now when you opt-in to autoDestroy we allow
10755
- // the error to be emitted nextTick. In a future
10756
- // semver major update we should change the default to this.
10757
-
10758
- const rState = stream._readableState;
10759
- const wState = stream._writableState;
10760
- if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
10761
- }
10762
- destroy_1 = {
10763
- destroy,
10764
- undestroy,
10765
- errorOrDestroy
10766
- };
10767
- return destroy_1;
10684
+ // if this is a duplex stream mark the writable part as destroyed as well
10685
+ if (this._writableState) {
10686
+ this._writableState.destroyed = true;
10687
+ }
10688
+ this._destroy(err || null, err => {
10689
+ if (!cb && err) {
10690
+ if (!this._writableState) {
10691
+ process.nextTick(emitErrorAndCloseNT, this, err);
10692
+ } else if (!this._writableState.errorEmitted) {
10693
+ this._writableState.errorEmitted = true;
10694
+ process.nextTick(emitErrorAndCloseNT, this, err);
10695
+ } else {
10696
+ process.nextTick(emitCloseNT, this);
10697
+ }
10698
+ } else if (cb) {
10699
+ process.nextTick(emitCloseNT, this);
10700
+ cb(err);
10701
+ } else {
10702
+ process.nextTick(emitCloseNT, this);
10703
+ }
10704
+ });
10705
+ return this;
10706
+ }
10707
+ function emitErrorAndCloseNT(self, err) {
10708
+ emitErrorNT(self, err);
10709
+ emitCloseNT(self);
10710
+ }
10711
+ function emitCloseNT(self) {
10712
+ if (self._writableState && !self._writableState.emitClose) return;
10713
+ if (self._readableState && !self._readableState.emitClose) return;
10714
+ self.emit('close');
10715
+ }
10716
+ function undestroy() {
10717
+ if (this._readableState) {
10718
+ this._readableState.destroyed = false;
10719
+ this._readableState.reading = false;
10720
+ this._readableState.ended = false;
10721
+ this._readableState.endEmitted = false;
10722
+ }
10723
+ if (this._writableState) {
10724
+ this._writableState.destroyed = false;
10725
+ this._writableState.ended = false;
10726
+ this._writableState.ending = false;
10727
+ this._writableState.finalCalled = false;
10728
+ this._writableState.prefinished = false;
10729
+ this._writableState.finished = false;
10730
+ this._writableState.errorEmitted = false;
10731
+ }
10768
10732
  }
10733
+ function emitErrorNT(self, err) {
10734
+ self.emit('error', err);
10735
+ }
10736
+ function errorOrDestroy(stream, err) {
10737
+ // We have tests that rely on errors being emitted
10738
+ // in the same tick, so changing this is semver major.
10739
+ // For now when you opt-in to autoDestroy we allow
10740
+ // the error to be emitted nextTick. In a future
10741
+ // semver major update we should change the default to this.
10742
+
10743
+ const rState = stream._readableState;
10744
+ const wState = stream._writableState;
10745
+ if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
10746
+ }
10747
+ var destroy_1 = {
10748
+ destroy,
10749
+ undestroy,
10750
+ errorOrDestroy
10751
+ };
10769
10752
 
10770
10753
  var errorsBrowser = {};
10771
10754
 
@@ -10895,109 +10878,92 @@ createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
10895
10878
  createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
10896
10879
  errorsBrowser.codes = codes;
10897
10880
 
10898
- var state;
10899
- var hasRequiredState;
10900
-
10901
- function requireState () {
10902
- if (hasRequiredState) return state;
10903
- hasRequiredState = 1;
10904
-
10905
- const ERR_INVALID_OPT_VALUE = errorsBrowser.codes.ERR_INVALID_OPT_VALUE;
10906
- function highWaterMarkFrom(options, isDuplex, duplexKey) {
10907
- return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
10908
- }
10909
- function getHighWaterMark(state, options, duplexKey, isDuplex) {
10910
- const hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
10911
- if (hwm != null) {
10912
- if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
10913
- const name = isDuplex ? duplexKey : 'highWaterMark';
10914
- throw new ERR_INVALID_OPT_VALUE(name, hwm);
10915
- }
10916
- return Math.floor(hwm);
10917
- }
10918
-
10919
- // Default value
10920
- return state.objectMode ? 16 : 16 * 1024;
10921
- }
10922
- state = {
10923
- getHighWaterMark
10924
- };
10925
- return state;
10881
+ const ERR_INVALID_OPT_VALUE = errorsBrowser.codes.ERR_INVALID_OPT_VALUE;
10882
+ function highWaterMarkFrom(options, isDuplex, duplexKey) {
10883
+ return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
10926
10884
  }
10885
+ function getHighWaterMark(state, options, duplexKey, isDuplex) {
10886
+ const hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
10887
+ if (hwm != null) {
10888
+ if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
10889
+ const name = isDuplex ? duplexKey : 'highWaterMark';
10890
+ throw new ERR_INVALID_OPT_VALUE(name, hwm);
10891
+ }
10892
+ return Math.floor(hwm);
10893
+ }
10927
10894
 
10928
- var browser$a;
10929
- var hasRequiredBrowser$3;
10895
+ // Default value
10896
+ return state.objectMode ? 16 : 16 * 1024;
10897
+ }
10898
+ var state = {
10899
+ getHighWaterMark
10900
+ };
10930
10901
 
10931
- function requireBrowser$3 () {
10932
- if (hasRequiredBrowser$3) return browser$a;
10933
- hasRequiredBrowser$3 = 1;
10934
- /**
10935
- * Module exports.
10936
- */
10902
+ /**
10903
+ * Module exports.
10904
+ */
10937
10905
 
10938
- browser$a = deprecate;
10906
+ var browser$a = deprecate$1;
10939
10907
 
10940
- /**
10941
- * Mark that a method should not be used.
10942
- * Returns a modified function which warns once by default.
10943
- *
10944
- * If `localStorage.noDeprecation = true` is set, then it is a no-op.
10945
- *
10946
- * If `localStorage.throwDeprecation = true` is set, then deprecated functions
10947
- * will throw an Error when invoked.
10948
- *
10949
- * If `localStorage.traceDeprecation = true` is set, then deprecated functions
10950
- * will invoke `console.trace()` instead of `console.error()`.
10951
- *
10952
- * @param {Function} fn - the function to deprecate
10953
- * @param {String} msg - the string to print to the console when `fn` is invoked
10954
- * @returns {Function} a new "deprecated" version of `fn`
10955
- * @api public
10956
- */
10908
+ /**
10909
+ * Mark that a method should not be used.
10910
+ * Returns a modified function which warns once by default.
10911
+ *
10912
+ * If `localStorage.noDeprecation = true` is set, then it is a no-op.
10913
+ *
10914
+ * If `localStorage.throwDeprecation = true` is set, then deprecated functions
10915
+ * will throw an Error when invoked.
10916
+ *
10917
+ * If `localStorage.traceDeprecation = true` is set, then deprecated functions
10918
+ * will invoke `console.trace()` instead of `console.error()`.
10919
+ *
10920
+ * @param {Function} fn - the function to deprecate
10921
+ * @param {String} msg - the string to print to the console when `fn` is invoked
10922
+ * @returns {Function} a new "deprecated" version of `fn`
10923
+ * @api public
10924
+ */
10957
10925
 
10958
- function deprecate (fn, msg) {
10959
- if (config('noDeprecation')) {
10960
- return fn;
10961
- }
10926
+ function deprecate$1 (fn, msg) {
10927
+ if (config('noDeprecation')) {
10928
+ return fn;
10929
+ }
10962
10930
 
10963
- var warned = false;
10964
- function deprecated() {
10965
- if (!warned) {
10966
- if (config('throwDeprecation')) {
10967
- throw new Error(msg);
10968
- } else if (config('traceDeprecation')) {
10969
- console.trace(msg);
10970
- } else {
10971
- console.warn(msg);
10972
- }
10973
- warned = true;
10974
- }
10975
- return fn.apply(this, arguments);
10976
- }
10931
+ var warned = false;
10932
+ function deprecated() {
10933
+ if (!warned) {
10934
+ if (config('throwDeprecation')) {
10935
+ throw new Error(msg);
10936
+ } else if (config('traceDeprecation')) {
10937
+ console.trace(msg);
10938
+ } else {
10939
+ console.warn(msg);
10940
+ }
10941
+ warned = true;
10942
+ }
10943
+ return fn.apply(this, arguments);
10944
+ }
10977
10945
 
10978
- return deprecated;
10979
- }
10946
+ return deprecated;
10947
+ }
10980
10948
 
10981
- /**
10982
- * Checks `localStorage` for boolean values for the given `name`.
10983
- *
10984
- * @param {String} name
10985
- * @returns {Boolean}
10986
- * @api private
10987
- */
10949
+ /**
10950
+ * Checks `localStorage` for boolean values for the given `name`.
10951
+ *
10952
+ * @param {String} name
10953
+ * @returns {Boolean}
10954
+ * @api private
10955
+ */
10988
10956
 
10989
- function config (name) {
10990
- // accessing global.localStorage can trigger a DOMException in sandboxed iframes
10991
- try {
10992
- if (!commonjsGlobal.localStorage) return false;
10993
- } catch (_) {
10994
- return false;
10995
- }
10996
- var val = commonjsGlobal.localStorage[name];
10997
- if (null == val) return false;
10998
- return String(val).toLowerCase() === 'true';
10999
- }
11000
- return browser$a;
10957
+ function config (name) {
10958
+ // accessing global.localStorage can trigger a DOMException in sandboxed iframes
10959
+ try {
10960
+ if (!commonjsGlobal.localStorage) return false;
10961
+ } catch (_) {
10962
+ return false;
10963
+ }
10964
+ var val = commonjsGlobal.localStorage[name];
10965
+ if (null == val) return false;
10966
+ return String(val).toLowerCase() === 'true';
11001
10967
  }
11002
10968
 
11003
10969
  var _stream_writable;
@@ -11028,12 +10994,12 @@ function require_stream_writable () {
11028
10994
 
11029
10995
  /*<replacement>*/
11030
10996
  const internalUtil = {
11031
- deprecate: requireBrowser$3()
10997
+ deprecate: browser$a
11032
10998
  };
11033
10999
  /*</replacement>*/
11034
11000
 
11035
11001
  /*<replacement>*/
11036
- var Stream = requireStreamBrowser();
11002
+ var Stream = streamBrowser;
11037
11003
  /*</replacement>*/
11038
11004
 
11039
11005
  const Buffer = require$$0$2.Buffer;
@@ -11044,8 +11010,8 @@ function require_stream_writable () {
11044
11010
  function _isUint8Array(obj) {
11045
11011
  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
11046
11012
  }
11047
- const destroyImpl = requireDestroy();
11048
- const _require = requireState(),
11013
+ const destroyImpl = destroy_1;
11014
+ const _require = state,
11049
11015
  getHighWaterMark = _require.getHighWaterMark;
11050
11016
  const _require$codes = errorsBrowser.codes,
11051
11017
  ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
@@ -12239,7 +12205,7 @@ function require_stream_readable () {
12239
12205
  /*</replacement>*/
12240
12206
 
12241
12207
  /*<replacement>*/
12242
- var Stream = requireStreamBrowser();
12208
+ var Stream = streamBrowser;
12243
12209
  /*</replacement>*/
12244
12210
 
12245
12211
  const Buffer = require$$0$2.Buffer;
@@ -12262,8 +12228,8 @@ function require_stream_readable () {
12262
12228
  /*</replacement>*/
12263
12229
 
12264
12230
  const BufferList = requireBuffer_list();
12265
- const destroyImpl = requireDestroy();
12266
- const _require = requireState(),
12231
+ const destroyImpl = destroy_1;
12232
+ const _require = state,
12267
12233
  getHighWaterMark = _require.getHighWaterMark;
12268
12234
  const _require$codes = errorsBrowser.codes,
12269
12235
  ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
@@ -15629,7 +15595,7 @@ function WriteReq(chunk, encoding, cb) {
15629
15595
 
15630
15596
  function WritableState(options, stream) {
15631
15597
  Object.defineProperty(this, 'buffer', {
15632
- get: deprecate$1(function () {
15598
+ get: deprecate$2(function () {
15633
15599
  return this.getBuffer();
15634
15600
  }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
15635
15601
  });
@@ -37118,6 +37084,7 @@ const blocksToCarBlock = async (lastCid, blocks) => {
37118
37084
  blocks = Array.from(blocks.entries());
37119
37085
  }
37120
37086
  for (const { cid, bytes } of blocks) {
37087
+ // console.log(cid, bytes)
37121
37088
  size += blockLength({ cid, bytes });
37122
37089
  }
37123
37090
  const buffer = new Uint8Array(size);
@@ -37697,7 +37664,8 @@ async function root (inBlocks, head) {
37697
37664
  */
37698
37665
  async function eventsSince (blocks, head, since) {
37699
37666
  if (!head.length) {
37700
- throw new Error('no head')
37667
+ // throw new Error('no head')
37668
+ return { clockCIDs: [], result: [] }
37701
37669
  }
37702
37670
  // @ts-ignore
37703
37671
  const sinceHead = [...since, ...head]; // ?
@@ -38135,7 +38103,7 @@ class Database {
38135
38103
  // console.log('change rows', this.instanceId, rows)
38136
38104
  } else {
38137
38105
  const allResp = await getAll(this.blocks, this.clock);
38138
- rows = allResp.result.map(({ key, value }) => (decodeEvent({ key, value })));
38106
+ rows = allResp.result.map(({ key, value }) => decodeEvent({ key, value }));
38139
38107
  dataCIDs = allResp.cids;
38140
38108
  // console.log('dbdoc rows', this.instanceId, rows)
38141
38109
  }
@@ -38148,7 +38116,9 @@ class Database {
38148
38116
 
38149
38117
  async allDocuments () {
38150
38118
  const allResp = await getAll(this.blocks, this.clock);
38151
- const rows = allResp.result.map(({ key, value }) => (decodeEvent({ key, value }))).map(({ key, value }) => ({ key, value: { _id: key, ...value } }));
38119
+ const rows = allResp.result
38120
+ .map(({ key, value }) => decodeEvent({ key, value }))
38121
+ .map(({ key, value }) => ({ key, value: { _id: key, ...value } }));
38152
38122
  return {
38153
38123
  rows,
38154
38124
  clock: this.clockToJSON(),
@@ -38156,6 +38126,15 @@ class Database {
38156
38126
  }
38157
38127
  }
38158
38128
 
38129
+ async allCIDs () {
38130
+ const allResp = await getAll(this.blocks, this.clock);
38131
+ const cids = await cidsToProof(allResp.cids);
38132
+ const clockCids = await cidsToProof(allResp.clockCIDs);
38133
+ // console.log('allcids', cids, clockCids)
38134
+ // todo we need to put the clock head as the last block in the encrypted car
38135
+ return [...cids, ...clockCids] // need a single block version of clock head, maybe an encoded block for it
38136
+ }
38137
+
38159
38138
  /**
38160
38139
  * Runs validation on the specified document using the Fireproof instance's configuration. Throws an error if the document is invalid.
38161
38140
  *
@@ -38168,7 +38147,7 @@ class Database {
38168
38147
  async runValidation (doc) {
38169
38148
  if (this.config && this.config.validateChange) {
38170
38149
  const oldDoc = await this.get(doc._id)
38171
- .then((doc) => doc)
38150
+ .then(doc => doc)
38172
38151
  .catch(() => ({}));
38173
38152
  this.config.validateChange(doc, oldDoc, this.authCtx);
38174
38153
  }
@@ -38203,13 +38182,13 @@ class Database {
38203
38182
  return doc
38204
38183
  }
38205
38184
  /**
38206
- * @typedef {Object} Document
38207
- * @property {string} _id - The ID of the document (required)
38208
- * @property {string} [_proof] - The proof of the document (optional)
38209
- * @property {string} [_clock] - The clock of the document (optional)
38210
- * @property {any} [key: string] - Index signature notation to allow any other unknown fields
38211
- * * @property {Object.<string, any>} [otherProperties] - Any other unknown properties (optional)
38212
- */
38185
+ * @typedef {Object} Document
38186
+ * @property {string} _id - The ID of the document (required)
38187
+ * @property {string} [_proof] - The proof of the document (optional)
38188
+ * @property {string} [_clock] - The clock of the document (optional)
38189
+ * @property {any} [key: string] - Index signature notation to allow any other unknown fields
38190
+ * * @property {Object.<string, any>} [otherProperties] - Any other unknown properties (optional)
38191
+ */
38213
38192
 
38214
38193
  /**
38215
38194
  * Adds a new document to the database, or updates an existing document. Returns the ID of the document and the new clock head.
@@ -38264,17 +38243,17 @@ class Database {
38264
38243
  throw new Error('MVCC conflict, document is changed, please reload the document and try again.')
38265
38244
  }
38266
38245
  }
38246
+ const prevClock = [...this.clock];
38267
38247
  const result = await doTransaction(
38268
38248
  'putToProllyTree',
38269
38249
  this.blocks,
38270
- async (blocks) => await put(blocks, this.clock, event)
38250
+ async blocks => await put(blocks, this.clock, event)
38271
38251
  );
38272
38252
  if (!result) {
38273
38253
  console.error('failed', event);
38274
38254
  throw new Error('failed to put at storage layer')
38275
38255
  }
38276
- // console.log('new clock head', this.instanceId, result.head.toString())
38277
- this.clock = result.head; // do we want to do this as a finally block
38256
+ this.applyClock(prevClock, result.head);
38278
38257
  await this.notifyListeners([decodedEvent]); // this type is odd
38279
38258
  return {
38280
38259
  id: decodedEvent.key,
@@ -38284,6 +38263,12 @@ class Database {
38284
38263
  // todo should include additions (or split clock)
38285
38264
  }
38286
38265
 
38266
+ applyClock (prevClock, newClock) {
38267
+ // console.log('applyClock', prevClock, newClock, this.clock)
38268
+ const removedprevCIDs = this.clock.filter(cid => prevClock.indexOf(cid) === -1);
38269
+ this.clock = removedprevCIDs.concat(newClock);
38270
+ }
38271
+
38287
38272
  // /**
38288
38273
  // * Advances the clock to the specified event and updates the root CID
38289
38274
  // * Will be used by replication
@@ -38342,7 +38327,7 @@ class Database {
38342
38327
  async function cidsToProof (cids) {
38343
38328
  if (!cids || !cids.all) return []
38344
38329
  const all = await cids.all();
38345
- return [...all].map((cid) => cid.toString())
38330
+ return [...all].map(cid => cid.toString())
38346
38331
  }
38347
38332
 
38348
38333
  function decodeEvent (event) {
@@ -38652,10 +38637,10 @@ const indexEntriesForChanges = (changes, mapFn) => {
38652
38637
  changes.forEach(({ key, value, del }) => {
38653
38638
  if (del || !value) return
38654
38639
  mapFn(makeDoc({ key, value }), (k, v) => {
38655
- if (typeof v === 'undefined' || typeof k === 'undefined') return
38640
+ if (typeof k === 'undefined') return
38656
38641
  indexEntries.push({
38657
38642
  key: [charwise.encode(k), key],
38658
- value: v
38643
+ value: v || null
38659
38644
  });
38660
38645
  });
38661
38646
  });
@@ -38673,23 +38658,25 @@ const indexEntriesForChanges = (changes, mapFn) => {
38673
38658
  *
38674
38659
  */
38675
38660
  class DbIndex {
38676
- constructor (database, mapFn, clock, opts = {}) {
38661
+ constructor (database, name, mapFn, clock = null, opts = {}) {
38677
38662
  this.database = database;
38678
38663
  if (!database.indexBlocks) {
38679
38664
  database.indexBlocks = new TransactionBlockstore(database?.name + '.indexes', database.blocks.valet?.getKeyMaterial());
38680
38665
  }
38681
- /**
38682
- * The map function to apply to each entry in the database.
38683
- * @type {Function}
38684
- */
38685
-
38666
+ if (typeof name === 'function') {
38667
+ // app is using deprecated API, remove in 0.7
38668
+ opts = clock;
38669
+ clock = mapFn;
38670
+ mapFn = name;
38671
+ name = null;
38672
+ }
38686
38673
  if (typeof mapFn === 'string') {
38687
38674
  this.mapFnString = mapFn;
38688
38675
  } else {
38689
38676
  this.mapFn = mapFn;
38690
38677
  this.mapFnString = mapFn.toString();
38691
38678
  }
38692
- this.name = opts.name || this.makeName();
38679
+ this.name = name || this.makeName();
38693
38680
  this.indexById = { root: null, cid: null };
38694
38681
  this.indexByKey = { root: null, cid: null };
38695
38682
  this.dbHead = null;
@@ -38739,7 +38726,7 @@ class DbIndex {
38739
38726
 
38740
38727
  static fromJSON (database, { code, clock, name }) {
38741
38728
  // console.log('DbIndex.fromJSON', database.constructor.name, code, clock)
38742
- return new DbIndex(database, code, clock, { name })
38729
+ return new DbIndex(database, name, code, clock)
38743
38730
  }
38744
38731
 
38745
38732
  /**
@@ -38756,7 +38743,7 @@ class DbIndex {
38756
38743
  * @memberof DbIndex
38757
38744
  * @instance
38758
38745
  */
38759
- async query (query, update = true) {
38746
+ async query (query = {}, update = true) {
38760
38747
  // const callId = Math.random().toString(36).substring(2, 7)
38761
38748
  // todo pass a root to query a snapshot
38762
38749
  // console.time(callId + '.updateIndex')
@@ -38783,7 +38770,12 @@ class DbIndex {
38783
38770
  async updateIndex (blocks) {
38784
38771
  // todo this could enqueue the request and give fresh ones to all second comers -- right now it gives out stale promises while working
38785
38772
  // what would it do in a world where all indexes provide a database snapshot to query?
38786
- if (this.updateIndexPromise) return this.updateIndexPromise
38773
+ if (this.updateIndexPromise) {
38774
+ return this.updateIndexPromise.then(() => {
38775
+ this.updateIndexPromise = null;
38776
+ return this.updateIndex(blocks)
38777
+ })
38778
+ }
38787
38779
  this.updateIndexPromise = this.innerUpdateIndex(blocks);
38788
38780
  this.updateIndexPromise.finally(() => { this.updateIndexPromise = null; });
38789
38781
  return this.updateIndexPromise
@@ -38804,7 +38796,7 @@ class DbIndex {
38804
38796
  this.dbHead = result.clock;
38805
38797
  return
38806
38798
  }
38807
- await doTransaction('updateIndex', inBlocks, async (blocks) => {
38799
+ const didT = await doTransaction('updateIndex', inBlocks, async (blocks) => {
38808
38800
  let oldIndexEntries = [];
38809
38801
  let removeByIdIndexEntries = [];
38810
38802
  await loadIndex(blocks, this.indexById, idIndexOpts);
@@ -38826,6 +38818,7 @@ class DbIndex {
38826
38818
  this.database.notifyExternal('dbIndex');
38827
38819
  // console.timeEnd(callTag + '.doTransactionupdateIndex')
38828
38820
  // console.log(`updateIndex ${callTag} <`, this.instanceId, this.dbHead?.toString(), this.indexByKey.cid?.toString(), this.indexById.cid?.toString())
38821
+ return didT
38829
38822
  }
38830
38823
  }
38831
38824
 
@@ -38868,7 +38861,11 @@ async function bulkIndex (blocks, inIndex, indexEntries, opts) {
38868
38861
  async function loadIndex (blocks, index, indexOpts) {
38869
38862
  if (!index.root) {
38870
38863
  const cid = index.cid;
38871
- if (!cid) return
38864
+ if (!cid) {
38865
+ // console.log('no cid', index)
38866
+ // throw new Error('cannot load index')
38867
+ return null
38868
+ }
38872
38869
  const { getBlock } = makeGetBlock(blocks);
38873
38870
  index.root = await load({ cid, get: getBlock, ...indexOpts });
38874
38871
  }
@@ -38895,7 +38892,7 @@ async function doIndexQuery (blocks, indexByKey, query = {}) {
38895
38892
  }
38896
38893
  }
38897
38894
 
38898
- const parseCID = cid => typeof cid === 'string' ? CID$1.parse(cid) : cid;
38895
+ const parseCID = cid => (typeof cid === 'string' ? CID$1.parse(cid) : cid);
38899
38896
 
38900
38897
  class Fireproof {
38901
38898
  /**
@@ -38926,7 +38923,11 @@ class Fireproof {
38926
38923
  static fromJSON (json, database) {
38927
38924
  database.hydrate({ clock: json.clock.map(c => parseCID(c)), name: json.name, key: json.key });
38928
38925
  if (json.indexes) {
38929
- for (const { name, code, clock: { byId, byKey, db } } of json.indexes) {
38926
+ for (const {
38927
+ name,
38928
+ code,
38929
+ clock: { byId, byKey, db }
38930
+ } of json.indexes) {
38930
38931
  DbIndex.fromJSON(database, {
38931
38932
  clock: {
38932
38933
  byId: byId ? parseCID(byId) : null,
@@ -38953,14 +38954,14 @@ class Fireproof {
38953
38954
  });
38954
38955
  }
38955
38956
  const snappedDb = this.fromJSON(definition, withBlocks)
38956
- ;([...database.indexes.values()]).forEach(index => {
38957
+ ;[...database.indexes.values()].forEach(index => {
38957
38958
  snappedDb.indexes.get(index.mapFnString).mapFn = index.mapFn;
38958
38959
  });
38959
38960
  return snappedDb
38960
38961
  }
38961
38962
 
38962
38963
  static async zoom (database, clock) {
38963
- ([...database.indexes.values()]).forEach(index => {
38964
+ [...database.indexes.values()].forEach(index => {
38964
38965
  index.indexById = { root: null, cid: null };
38965
38966
  index.indexByKey = { root: null, cid: null };
38966
38967
  index.dbHead = null;
@@ -38969,8 +38970,44 @@ class Fireproof {
38969
38970
  await database.notifyReset(); // hmm... indexes should listen to this? might be more complex than worth it. so far this is the only caller
38970
38971
  return database
38971
38972
  }
38973
+
38974
+ // get all the cids
38975
+ // tell valet to make a file
38976
+ static async makeCar (database, key) {
38977
+ const allCIDs = await database.allCIDs();
38978
+ const blocks = database.blocks;
38979
+
38980
+ const rootCid = CID$1.parse(allCIDs[allCIDs.length - 1]);
38981
+ if (typeof key === 'undefined') {
38982
+ key = blocks.valet?.getKeyMaterial();
38983
+ }
38984
+ if (key) {
38985
+ return blocksToEncryptedCarBlock(
38986
+ rootCid,
38987
+ {
38988
+ entries: () => allCIDs.map(cid => ({ cid })),
38989
+ get: async cid => await blocks.get(cid)
38990
+ },
38991
+ key
38992
+ )
38993
+ } else {
38994
+ const carBlocks = await Promise.all(
38995
+ allCIDs.map(async c => {
38996
+ const b = await blocks.get(c);
38997
+ // console.log('block', b)
38998
+ if (typeof b.cid === 'string') { b.cid = CID$1.parse(b.cid); }
38999
+ // if (b.bytes.constructor.name === 'Buffer') console.log('conver vbuff')
39000
+ return b
39001
+ })
39002
+ );
39003
+ return blocksToCarBlock(rootCid, {
39004
+ entries: () => carBlocks
39005
+ })
39006
+ }
39007
+ }
38972
39008
  }
38973
39009
 
39010
+ exports.Database = Database;
38974
39011
  exports.Fireproof = Fireproof;
38975
39012
  exports.Index = DbIndex;
38976
39013
  exports.Listener = Listener;