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