@fireproof/core 0.6.2 → 0.6.3-dev2

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.
@@ -1,3 +1,6 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { mkdir, writeFile } from 'node:fs/promises';
3
+
1
4
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
2
5
 
3
6
  function getDefaultExportFromCjs (x) {
@@ -8141,267 +8144,6 @@ var raw = /*#__PURE__*/Object.freeze({
8141
8144
  name: name$2
8142
8145
  });
8143
8146
 
8144
- const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);
8145
-
8146
- let idbProxyableTypes;
8147
- let cursorAdvanceMethods;
8148
- // This is a function to prevent it throwing up in node environments.
8149
- function getIdbProxyableTypes() {
8150
- return (idbProxyableTypes ||
8151
- (idbProxyableTypes = [
8152
- IDBDatabase,
8153
- IDBObjectStore,
8154
- IDBIndex,
8155
- IDBCursor,
8156
- IDBTransaction,
8157
- ]));
8158
- }
8159
- // This is a function to prevent it throwing up in node environments.
8160
- function getCursorAdvanceMethods() {
8161
- return (cursorAdvanceMethods ||
8162
- (cursorAdvanceMethods = [
8163
- IDBCursor.prototype.advance,
8164
- IDBCursor.prototype.continue,
8165
- IDBCursor.prototype.continuePrimaryKey,
8166
- ]));
8167
- }
8168
- const cursorRequestMap = new WeakMap();
8169
- const transactionDoneMap = new WeakMap();
8170
- const transactionStoreNamesMap = new WeakMap();
8171
- const transformCache = new WeakMap();
8172
- const reverseTransformCache = new WeakMap();
8173
- function promisifyRequest(request) {
8174
- const promise = new Promise((resolve, reject) => {
8175
- const unlisten = () => {
8176
- request.removeEventListener('success', success);
8177
- request.removeEventListener('error', error);
8178
- };
8179
- const success = () => {
8180
- resolve(wrap$1(request.result));
8181
- unlisten();
8182
- };
8183
- const error = () => {
8184
- reject(request.error);
8185
- unlisten();
8186
- };
8187
- request.addEventListener('success', success);
8188
- request.addEventListener('error', error);
8189
- });
8190
- promise
8191
- .then((value) => {
8192
- // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval
8193
- // (see wrapFunction).
8194
- if (value instanceof IDBCursor) {
8195
- cursorRequestMap.set(value, request);
8196
- }
8197
- // Catching to avoid "Uncaught Promise exceptions"
8198
- })
8199
- .catch(() => { });
8200
- // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This
8201
- // is because we create many promises from a single IDBRequest.
8202
- reverseTransformCache.set(promise, request);
8203
- return promise;
8204
- }
8205
- function cacheDonePromiseForTransaction(tx) {
8206
- // Early bail if we've already created a done promise for this transaction.
8207
- if (transactionDoneMap.has(tx))
8208
- return;
8209
- const done = new Promise((resolve, reject) => {
8210
- const unlisten = () => {
8211
- tx.removeEventListener('complete', complete);
8212
- tx.removeEventListener('error', error);
8213
- tx.removeEventListener('abort', error);
8214
- };
8215
- const complete = () => {
8216
- resolve();
8217
- unlisten();
8218
- };
8219
- const error = () => {
8220
- reject(tx.error || new DOMException('AbortError', 'AbortError'));
8221
- unlisten();
8222
- };
8223
- tx.addEventListener('complete', complete);
8224
- tx.addEventListener('error', error);
8225
- tx.addEventListener('abort', error);
8226
- });
8227
- // Cache it for later retrieval.
8228
- transactionDoneMap.set(tx, done);
8229
- }
8230
- let idbProxyTraps = {
8231
- get(target, prop, receiver) {
8232
- if (target instanceof IDBTransaction) {
8233
- // Special handling for transaction.done.
8234
- if (prop === 'done')
8235
- return transactionDoneMap.get(target);
8236
- // Polyfill for objectStoreNames because of Edge.
8237
- if (prop === 'objectStoreNames') {
8238
- return target.objectStoreNames || transactionStoreNamesMap.get(target);
8239
- }
8240
- // Make tx.store return the only store in the transaction, or undefined if there are many.
8241
- if (prop === 'store') {
8242
- return receiver.objectStoreNames[1]
8243
- ? undefined
8244
- : receiver.objectStore(receiver.objectStoreNames[0]);
8245
- }
8246
- }
8247
- // Else transform whatever we get back.
8248
- return wrap$1(target[prop]);
8249
- },
8250
- set(target, prop, value) {
8251
- target[prop] = value;
8252
- return true;
8253
- },
8254
- has(target, prop) {
8255
- if (target instanceof IDBTransaction &&
8256
- (prop === 'done' || prop === 'store')) {
8257
- return true;
8258
- }
8259
- return prop in target;
8260
- },
8261
- };
8262
- function replaceTraps(callback) {
8263
- idbProxyTraps = callback(idbProxyTraps);
8264
- }
8265
- function wrapFunction(func) {
8266
- // Due to expected object equality (which is enforced by the caching in `wrap`), we
8267
- // only create one new func per func.
8268
- // Edge doesn't support objectStoreNames (booo), so we polyfill it here.
8269
- if (func === IDBDatabase.prototype.transaction &&
8270
- !('objectStoreNames' in IDBTransaction.prototype)) {
8271
- return function (storeNames, ...args) {
8272
- const tx = func.call(unwrap(this), storeNames, ...args);
8273
- transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
8274
- return wrap$1(tx);
8275
- };
8276
- }
8277
- // Cursor methods are special, as the behaviour is a little more different to standard IDB. In
8278
- // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the
8279
- // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense
8280
- // with real promises, so each advance methods returns a new promise for the cursor object, or
8281
- // undefined if the end of the cursor has been reached.
8282
- if (getCursorAdvanceMethods().includes(func)) {
8283
- return function (...args) {
8284
- // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
8285
- // the original object.
8286
- func.apply(unwrap(this), args);
8287
- return wrap$1(cursorRequestMap.get(this));
8288
- };
8289
- }
8290
- return function (...args) {
8291
- // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
8292
- // the original object.
8293
- return wrap$1(func.apply(unwrap(this), args));
8294
- };
8295
- }
8296
- function transformCachableValue(value) {
8297
- if (typeof value === 'function')
8298
- return wrapFunction(value);
8299
- // This doesn't return, it just creates a 'done' promise for the transaction,
8300
- // which is later returned for transaction.done (see idbObjectHandler).
8301
- if (value instanceof IDBTransaction)
8302
- cacheDonePromiseForTransaction(value);
8303
- if (instanceOfAny(value, getIdbProxyableTypes()))
8304
- return new Proxy(value, idbProxyTraps);
8305
- // Return the same value back if we're not going to transform it.
8306
- return value;
8307
- }
8308
- function wrap$1(value) {
8309
- // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
8310
- // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.
8311
- if (value instanceof IDBRequest)
8312
- return promisifyRequest(value);
8313
- // If we've already transformed this value before, reuse the transformed value.
8314
- // This is faster, but it also provides object equality.
8315
- if (transformCache.has(value))
8316
- return transformCache.get(value);
8317
- const newValue = transformCachableValue(value);
8318
- // Not all types are transformed.
8319
- // These may be primitive types, so they can't be WeakMap keys.
8320
- if (newValue !== value) {
8321
- transformCache.set(value, newValue);
8322
- reverseTransformCache.set(newValue, value);
8323
- }
8324
- return newValue;
8325
- }
8326
- const unwrap = (value) => reverseTransformCache.get(value);
8327
-
8328
- /**
8329
- * Open a database.
8330
- *
8331
- * @param name Name of the database.
8332
- * @param version Schema version.
8333
- * @param callbacks Additional callbacks.
8334
- */
8335
- function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {
8336
- const request = indexedDB.open(name, version);
8337
- const openPromise = wrap$1(request);
8338
- if (upgrade) {
8339
- request.addEventListener('upgradeneeded', (event) => {
8340
- upgrade(wrap$1(request.result), event.oldVersion, event.newVersion, wrap$1(request.transaction), event);
8341
- });
8342
- }
8343
- if (blocked) {
8344
- request.addEventListener('blocked', (event) => blocked(
8345
- // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
8346
- event.oldVersion, event.newVersion, event));
8347
- }
8348
- openPromise
8349
- .then((db) => {
8350
- if (terminated)
8351
- db.addEventListener('close', () => terminated());
8352
- if (blocking) {
8353
- db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));
8354
- }
8355
- })
8356
- .catch(() => { });
8357
- return openPromise;
8358
- }
8359
-
8360
- const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
8361
- const writeMethods = ['put', 'add', 'delete', 'clear'];
8362
- const cachedMethods = new Map();
8363
- function getMethod(target, prop) {
8364
- if (!(target instanceof IDBDatabase &&
8365
- !(prop in target) &&
8366
- typeof prop === 'string')) {
8367
- return;
8368
- }
8369
- if (cachedMethods.get(prop))
8370
- return cachedMethods.get(prop);
8371
- const targetFuncName = prop.replace(/FromIndex$/, '');
8372
- const useIndex = prop !== targetFuncName;
8373
- const isWrite = writeMethods.includes(targetFuncName);
8374
- if (
8375
- // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
8376
- !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||
8377
- !(isWrite || readMethods.includes(targetFuncName))) {
8378
- return;
8379
- }
8380
- const method = async function (storeName, ...args) {
8381
- // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(
8382
- const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
8383
- let target = tx.store;
8384
- if (useIndex)
8385
- target = target.index(args.shift());
8386
- // Must reject if op rejects.
8387
- // If it's a write operation, must reject if tx.done rejects.
8388
- // Must reject with op rejection first.
8389
- // Must resolve with op value.
8390
- // Must handle both promises (no unhandled rejections)
8391
- return (await Promise.all([
8392
- target[targetFuncName](...args),
8393
- isWrite && tx.done,
8394
- ]))[0];
8395
- };
8396
- cachedMethods.set(prop, method);
8397
- return method;
8398
- }
8399
- replaceTraps((oldTraps) => ({
8400
- ...oldTraps,
8401
- get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
8402
- has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),
8403
- }));
8404
-
8405
8147
  var cargoQueueExports = {};
8406
8148
  var cargoQueue$1 = {
8407
8149
  get exports(){ return cargoQueueExports; },
@@ -8443,7 +8185,7 @@ Object.defineProperty(setImmediate$1, "__esModule", {
8443
8185
  value: true
8444
8186
  });
8445
8187
  setImmediate$1.fallback = fallback;
8446
- setImmediate$1.wrap = wrap;
8188
+ setImmediate$1.wrap = wrap$1;
8447
8189
  /* istanbul ignore file */
8448
8190
 
8449
8191
  var hasQueueMicrotask = setImmediate$1.hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask;
@@ -8454,7 +8196,7 @@ function fallback(fn) {
8454
8196
  setTimeout(fn, 0);
8455
8197
  }
8456
8198
 
8457
- function wrap(defer) {
8199
+ function wrap$1(defer) {
8458
8200
  return (fn, ...args) => defer(() => fn(...args));
8459
8201
  }
8460
8202
 
@@ -8470,7 +8212,7 @@ if (hasQueueMicrotask) {
8470
8212
  _defer = fallback;
8471
8213
  }
8472
8214
 
8473
- setImmediate$1.default = wrap(_defer);
8215
+ setImmediate$1.default = wrap$1(_defer);
8474
8216
 
8475
8217
  var DoublyLinkedListExports = {};
8476
8218
  var DoublyLinkedList = {
@@ -9141,6 +8883,559 @@ function requireWrapAsync () {
9141
8883
 
9142
8884
  var cargoQueue = /*@__PURE__*/getDefaultExportFromCjs(cargoQueueExports);
9143
8885
 
8886
+ const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);
8887
+
8888
+ let idbProxyableTypes;
8889
+ let cursorAdvanceMethods;
8890
+ // This is a function to prevent it throwing up in node environments.
8891
+ function getIdbProxyableTypes() {
8892
+ return (idbProxyableTypes ||
8893
+ (idbProxyableTypes = [
8894
+ IDBDatabase,
8895
+ IDBObjectStore,
8896
+ IDBIndex,
8897
+ IDBCursor,
8898
+ IDBTransaction,
8899
+ ]));
8900
+ }
8901
+ // This is a function to prevent it throwing up in node environments.
8902
+ function getCursorAdvanceMethods() {
8903
+ return (cursorAdvanceMethods ||
8904
+ (cursorAdvanceMethods = [
8905
+ IDBCursor.prototype.advance,
8906
+ IDBCursor.prototype.continue,
8907
+ IDBCursor.prototype.continuePrimaryKey,
8908
+ ]));
8909
+ }
8910
+ const cursorRequestMap = new WeakMap();
8911
+ const transactionDoneMap = new WeakMap();
8912
+ const transactionStoreNamesMap = new WeakMap();
8913
+ const transformCache = new WeakMap();
8914
+ const reverseTransformCache = new WeakMap();
8915
+ function promisifyRequest(request) {
8916
+ const promise = new Promise((resolve, reject) => {
8917
+ const unlisten = () => {
8918
+ request.removeEventListener('success', success);
8919
+ request.removeEventListener('error', error);
8920
+ };
8921
+ const success = () => {
8922
+ resolve(wrap(request.result));
8923
+ unlisten();
8924
+ };
8925
+ const error = () => {
8926
+ reject(request.error);
8927
+ unlisten();
8928
+ };
8929
+ request.addEventListener('success', success);
8930
+ request.addEventListener('error', error);
8931
+ });
8932
+ promise
8933
+ .then((value) => {
8934
+ // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval
8935
+ // (see wrapFunction).
8936
+ if (value instanceof IDBCursor) {
8937
+ cursorRequestMap.set(value, request);
8938
+ }
8939
+ // Catching to avoid "Uncaught Promise exceptions"
8940
+ })
8941
+ .catch(() => { });
8942
+ // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This
8943
+ // is because we create many promises from a single IDBRequest.
8944
+ reverseTransformCache.set(promise, request);
8945
+ return promise;
8946
+ }
8947
+ function cacheDonePromiseForTransaction(tx) {
8948
+ // Early bail if we've already created a done promise for this transaction.
8949
+ if (transactionDoneMap.has(tx))
8950
+ return;
8951
+ const done = new Promise((resolve, reject) => {
8952
+ const unlisten = () => {
8953
+ tx.removeEventListener('complete', complete);
8954
+ tx.removeEventListener('error', error);
8955
+ tx.removeEventListener('abort', error);
8956
+ };
8957
+ const complete = () => {
8958
+ resolve();
8959
+ unlisten();
8960
+ };
8961
+ const error = () => {
8962
+ reject(tx.error || new DOMException('AbortError', 'AbortError'));
8963
+ unlisten();
8964
+ };
8965
+ tx.addEventListener('complete', complete);
8966
+ tx.addEventListener('error', error);
8967
+ tx.addEventListener('abort', error);
8968
+ });
8969
+ // Cache it for later retrieval.
8970
+ transactionDoneMap.set(tx, done);
8971
+ }
8972
+ let idbProxyTraps = {
8973
+ get(target, prop, receiver) {
8974
+ if (target instanceof IDBTransaction) {
8975
+ // Special handling for transaction.done.
8976
+ if (prop === 'done')
8977
+ return transactionDoneMap.get(target);
8978
+ // Polyfill for objectStoreNames because of Edge.
8979
+ if (prop === 'objectStoreNames') {
8980
+ return target.objectStoreNames || transactionStoreNamesMap.get(target);
8981
+ }
8982
+ // Make tx.store return the only store in the transaction, or undefined if there are many.
8983
+ if (prop === 'store') {
8984
+ return receiver.objectStoreNames[1]
8985
+ ? undefined
8986
+ : receiver.objectStore(receiver.objectStoreNames[0]);
8987
+ }
8988
+ }
8989
+ // Else transform whatever we get back.
8990
+ return wrap(target[prop]);
8991
+ },
8992
+ set(target, prop, value) {
8993
+ target[prop] = value;
8994
+ return true;
8995
+ },
8996
+ has(target, prop) {
8997
+ if (target instanceof IDBTransaction &&
8998
+ (prop === 'done' || prop === 'store')) {
8999
+ return true;
9000
+ }
9001
+ return prop in target;
9002
+ },
9003
+ };
9004
+ function replaceTraps(callback) {
9005
+ idbProxyTraps = callback(idbProxyTraps);
9006
+ }
9007
+ function wrapFunction(func) {
9008
+ // Due to expected object equality (which is enforced by the caching in `wrap`), we
9009
+ // only create one new func per func.
9010
+ // Edge doesn't support objectStoreNames (booo), so we polyfill it here.
9011
+ if (func === IDBDatabase.prototype.transaction &&
9012
+ !('objectStoreNames' in IDBTransaction.prototype)) {
9013
+ return function (storeNames, ...args) {
9014
+ const tx = func.call(unwrap(this), storeNames, ...args);
9015
+ transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
9016
+ return wrap(tx);
9017
+ };
9018
+ }
9019
+ // Cursor methods are special, as the behaviour is a little more different to standard IDB. In
9020
+ // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the
9021
+ // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense
9022
+ // with real promises, so each advance methods returns a new promise for the cursor object, or
9023
+ // undefined if the end of the cursor has been reached.
9024
+ if (getCursorAdvanceMethods().includes(func)) {
9025
+ return function (...args) {
9026
+ // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
9027
+ // the original object.
9028
+ func.apply(unwrap(this), args);
9029
+ return wrap(cursorRequestMap.get(this));
9030
+ };
9031
+ }
9032
+ return function (...args) {
9033
+ // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
9034
+ // the original object.
9035
+ return wrap(func.apply(unwrap(this), args));
9036
+ };
9037
+ }
9038
+ function transformCachableValue(value) {
9039
+ if (typeof value === 'function')
9040
+ return wrapFunction(value);
9041
+ // This doesn't return, it just creates a 'done' promise for the transaction,
9042
+ // which is later returned for transaction.done (see idbObjectHandler).
9043
+ if (value instanceof IDBTransaction)
9044
+ cacheDonePromiseForTransaction(value);
9045
+ if (instanceOfAny(value, getIdbProxyableTypes()))
9046
+ return new Proxy(value, idbProxyTraps);
9047
+ // Return the same value back if we're not going to transform it.
9048
+ return value;
9049
+ }
9050
+ function wrap(value) {
9051
+ // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
9052
+ // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.
9053
+ if (value instanceof IDBRequest)
9054
+ return promisifyRequest(value);
9055
+ // If we've already transformed this value before, reuse the transformed value.
9056
+ // This is faster, but it also provides object equality.
9057
+ if (transformCache.has(value))
9058
+ return transformCache.get(value);
9059
+ const newValue = transformCachableValue(value);
9060
+ // Not all types are transformed.
9061
+ // These may be primitive types, so they can't be WeakMap keys.
9062
+ if (newValue !== value) {
9063
+ transformCache.set(value, newValue);
9064
+ reverseTransformCache.set(newValue, value);
9065
+ }
9066
+ return newValue;
9067
+ }
9068
+ const unwrap = (value) => reverseTransformCache.get(value);
9069
+
9070
+ /**
9071
+ * Open a database.
9072
+ *
9073
+ * @param name Name of the database.
9074
+ * @param version Schema version.
9075
+ * @param callbacks Additional callbacks.
9076
+ */
9077
+ function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {
9078
+ const request = indexedDB.open(name, version);
9079
+ const openPromise = wrap(request);
9080
+ if (upgrade) {
9081
+ request.addEventListener('upgradeneeded', (event) => {
9082
+ upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);
9083
+ });
9084
+ }
9085
+ if (blocked) {
9086
+ request.addEventListener('blocked', (event) => blocked(
9087
+ // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
9088
+ event.oldVersion, event.newVersion, event));
9089
+ }
9090
+ openPromise
9091
+ .then((db) => {
9092
+ if (terminated)
9093
+ db.addEventListener('close', () => terminated());
9094
+ if (blocking) {
9095
+ db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));
9096
+ }
9097
+ })
9098
+ .catch(() => { });
9099
+ return openPromise;
9100
+ }
9101
+
9102
+ const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
9103
+ const writeMethods = ['put', 'add', 'delete', 'clear'];
9104
+ const cachedMethods = new Map();
9105
+ function getMethod(target, prop) {
9106
+ if (!(target instanceof IDBDatabase &&
9107
+ !(prop in target) &&
9108
+ typeof prop === 'string')) {
9109
+ return;
9110
+ }
9111
+ if (cachedMethods.get(prop))
9112
+ return cachedMethods.get(prop);
9113
+ const targetFuncName = prop.replace(/FromIndex$/, '');
9114
+ const useIndex = prop !== targetFuncName;
9115
+ const isWrite = writeMethods.includes(targetFuncName);
9116
+ if (
9117
+ // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
9118
+ !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||
9119
+ !(isWrite || readMethods.includes(targetFuncName))) {
9120
+ return;
9121
+ }
9122
+ const method = async function (storeName, ...args) {
9123
+ // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(
9124
+ const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
9125
+ let target = tx.store;
9126
+ if (useIndex)
9127
+ target = target.index(args.shift());
9128
+ // Must reject if op rejects.
9129
+ // If it's a write operation, must reject if tx.done rejects.
9130
+ // Must reject with op rejection first.
9131
+ // Must resolve with op value.
9132
+ // Must handle both promises (no unhandled rejections)
9133
+ return (await Promise.all([
9134
+ target[targetFuncName](...args),
9135
+ isWrite && tx.done,
9136
+ ]))[0];
9137
+ };
9138
+ cachedMethods.set(prop, method);
9139
+ return method;
9140
+ }
9141
+ replaceTraps((oldTraps) => ({
9142
+ ...oldTraps,
9143
+ get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
9144
+ has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),
9145
+ }));
9146
+
9147
+ // Copyright Joyent, Inc. and other Node contributors.
9148
+ //
9149
+ // Permission is hereby granted, free of charge, to any person obtaining a
9150
+ // copy of this software and associated documentation files (the
9151
+ // "Software"), to deal in the Software without restriction, including
9152
+ // without limitation the rights to use, copy, modify, merge, publish,
9153
+ // distribute, sublicense, and/or sell copies of the Software, and to permit
9154
+ // persons to whom the Software is furnished to do so, subject to the
9155
+ // following conditions:
9156
+ //
9157
+ // The above copyright notice and this permission notice shall be included
9158
+ // in all copies or substantial portions of the Software.
9159
+ //
9160
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
9161
+ // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
9162
+ // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
9163
+ // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
9164
+ // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
9165
+ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
9166
+ // USE OR OTHER DEALINGS IN THE SOFTWARE.
9167
+
9168
+ // resolves . and .. elements in a path array with directory names there
9169
+ // must be no slashes, empty elements, or device names (c:\) in the array
9170
+ // (so also no leading and trailing slashes - it does not distinguish
9171
+ // relative and absolute paths)
9172
+ function normalizeArray(parts, allowAboveRoot) {
9173
+ // if the path tries to go above the root, `up` ends up > 0
9174
+ var up = 0;
9175
+ for (var i = parts.length - 1; i >= 0; i--) {
9176
+ var last = parts[i];
9177
+ if (last === '.') {
9178
+ parts.splice(i, 1);
9179
+ } else if (last === '..') {
9180
+ parts.splice(i, 1);
9181
+ up++;
9182
+ } else if (up) {
9183
+ parts.splice(i, 1);
9184
+ up--;
9185
+ }
9186
+ }
9187
+
9188
+ // if the path is allowed to go above the root, restore leading ..s
9189
+ if (allowAboveRoot) {
9190
+ for (; up--; up) {
9191
+ parts.unshift('..');
9192
+ }
9193
+ }
9194
+
9195
+ return parts;
9196
+ }
9197
+
9198
+ // Split a filename into [root, dir, basename, ext], unix version
9199
+ // 'root' is just a slash, or nothing.
9200
+ var splitPathRe =
9201
+ /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
9202
+ var splitPath = function(filename) {
9203
+ return splitPathRe.exec(filename).slice(1);
9204
+ };
9205
+
9206
+ // path.normalize(path)
9207
+ // posix version
9208
+ function normalize(path) {
9209
+ var isPathAbsolute = isAbsolute(path),
9210
+ trailingSlash = substr(path, -1) === '/';
9211
+
9212
+ // Normalize the path
9213
+ path = normalizeArray(filter(path.split('/'), function(p) {
9214
+ return !!p;
9215
+ }), !isPathAbsolute).join('/');
9216
+
9217
+ if (!path && !isPathAbsolute) {
9218
+ path = '.';
9219
+ }
9220
+ if (path && trailingSlash) {
9221
+ path += '/';
9222
+ }
9223
+
9224
+ return (isPathAbsolute ? '/' : '') + path;
9225
+ }
9226
+ // posix version
9227
+ function isAbsolute(path) {
9228
+ return path.charAt(0) === '/';
9229
+ }
9230
+
9231
+ // posix version
9232
+ function join() {
9233
+ var paths = Array.prototype.slice.call(arguments, 0);
9234
+ return normalize(filter(paths, function(p, index) {
9235
+ if (typeof p !== 'string') {
9236
+ throw new TypeError('Arguments to path.join must be strings');
9237
+ }
9238
+ return p;
9239
+ }).join('/'));
9240
+ }
9241
+
9242
+ function dirname(path) {
9243
+ var result = splitPath(path),
9244
+ root = result[0],
9245
+ dir = result[1];
9246
+
9247
+ if (!root && !dir) {
9248
+ // No dirname whatsoever
9249
+ return '.';
9250
+ }
9251
+
9252
+ if (dir) {
9253
+ // It has a dirname, strip trailing slash
9254
+ dir = dir.substr(0, dir.length - 1);
9255
+ }
9256
+
9257
+ return root + dir;
9258
+ }
9259
+ function filter (xs, f) {
9260
+ if (xs.filter) return xs.filter(f);
9261
+ var res = [];
9262
+ for (var i = 0; i < xs.length; i++) {
9263
+ if (f(xs[i], i, xs)) res.push(xs[i]);
9264
+ }
9265
+ return res;
9266
+ }
9267
+
9268
+ // String.prototype.substr - negative index don't work in IE8
9269
+ var substr = 'ab'.substr(-1) === 'b' ?
9270
+ function (str, start, len) { return str.substr(start, len) } :
9271
+ function (str, start, len) {
9272
+ if (start < 0) start = str.length + start;
9273
+ return str.substr(start, len);
9274
+ }
9275
+ ;
9276
+
9277
+ function homedir(){
9278
+ return '$HOME'
9279
+ }
9280
+
9281
+ const defaultConfig = {
9282
+ dataDir: join(homedir(), '.fireproof'),
9283
+ headerKeyPrefix: 'fp.'
9284
+ };
9285
+
9286
+ const FORCE_IDB = typeof process !== 'undefined' && !!process.env?.FORCE_IDB;
9287
+
9288
+ /* global localStorage */
9289
+
9290
+ class Loader {
9291
+ constructor (name, keyId, config = defaultConfig) {
9292
+ this.name = name;
9293
+ this.keyId = keyId;
9294
+ this.config = config;
9295
+ this.isBrowser = false;
9296
+ try {
9297
+ this.isBrowser = window.localStorage && true;
9298
+ } catch (e) {}
9299
+ }
9300
+
9301
+ withDB = async (dbWorkFun) => {
9302
+ if (!this.idb) {
9303
+ this.idb = await openDB(`fp.${this.keyId}.${this.name}.valet`, 3, {
9304
+ upgrade (db, oldVersion, newVersion, transaction) {
9305
+ if (oldVersion < 1) {
9306
+ db.createObjectStore('cars');
9307
+ }
9308
+ }
9309
+ });
9310
+ }
9311
+ return await dbWorkFun(this.idb)
9312
+ }
9313
+
9314
+ async writeCars (cars) {
9315
+ // console.log('writeCars', this.config.dataDir, this.name, cars.map(c => c.cid.toString()))
9316
+ // console.log('writeCars', cars.length)
9317
+
9318
+ if (FORCE_IDB || this.isBrowser) {
9319
+ await this.writeCarsIDB(cars);
9320
+ } else {
9321
+ const writes = [];
9322
+ for (const { cid, bytes } of cars) {
9323
+ const carFilename = join(this.config.dataDir, this.name, `${cid.toString()}.car`);
9324
+ // console.log('writeCars', carFilename)
9325
+ writes.push(writeSync(carFilename, bytes));
9326
+ }
9327
+ await Promise.all(writes);
9328
+ }
9329
+ }
9330
+
9331
+ async writeCarsIDB (cars) {
9332
+ return await this.withDB(async db => {
9333
+ const tx = db.transaction(['cars'], 'readwrite');
9334
+ for (const { cid, bytes, replaces } of cars) {
9335
+ await tx.objectStore('cars').put(bytes, cid.toString());
9336
+ // todo remove old maps
9337
+ if (replaces) {
9338
+ await tx.objectStore('cars').delete(replaces.toString());
9339
+ }
9340
+ }
9341
+ return await tx.done
9342
+ })
9343
+ }
9344
+
9345
+ async readCar (carCid) {
9346
+ if (FORCE_IDB || this.isBrowser) {
9347
+ return await this.readCarIDB(carCid)
9348
+ } else {
9349
+ const carFilename = join(this.config.dataDir, this.name, `${carCid.toString()}.car`);
9350
+ const got = readFileSync(carFilename);
9351
+ // console.log('readCar', carFilename, got.constructor.name)
9352
+ return got
9353
+ }
9354
+ }
9355
+
9356
+ async readCarIDB (carCid) {
9357
+ return await this.withDB(async db => {
9358
+ const tx = db.transaction(['cars'], 'readonly');
9359
+ // console.log('getCarReader', carCid)
9360
+ return await tx.objectStore('cars').get(carCid)
9361
+ })
9362
+ }
9363
+
9364
+ getHeader () {
9365
+ if (this.isBrowser) {
9366
+ return localStorage.getItem(this.config.headerKeyPrefix + this.name)
9367
+ } else {
9368
+ return loadSync(this.headerFilename())
9369
+ // return null
9370
+ }
9371
+ }
9372
+
9373
+ async saveHeader (stringValue) {
9374
+ // console.log('saveHeader', this.isBrowser)
9375
+ if (this.isBrowser) {
9376
+ // console.log('localStorage!', this.config.headerKeyPrefix)
9377
+ return localStorage.setItem(this.config.headerKeyPrefix + this.name, stringValue)
9378
+ } else {
9379
+ // console.log('no localStorage', this.config.dataDir, this.name)
9380
+ // console.log('saving clock to', this.headerFilename(), stringValue)
9381
+
9382
+ try {
9383
+ await writeSync(this.headerFilename(), stringValue);
9384
+ } catch (error) {
9385
+ console.log('error', error);
9386
+ }
9387
+
9388
+ // console.log('saved clock to', this.headerFilename())
9389
+ }
9390
+ }
9391
+
9392
+ headerFilename () {
9393
+ // console.log('headerFilename', this.config.dataDir, this.name)
9394
+ return join(this.config.dataDir, this.name, 'header.json')
9395
+ }
9396
+
9397
+ // async loadData (database, filename) {
9398
+ // const fullFilePath = join(process.cwd(), filename)
9399
+ // const readableStream = createReadStream(fullFilePath)
9400
+ // const parseStream = parse()
9401
+ // readableStream.pipe(parseStream)
9402
+
9403
+ // const saveQueue = cargoQueue(async (tasks, callback) => {
9404
+ // for (const t of tasks) {
9405
+ // await database.put(t)
9406
+ // }
9407
+ // callback()
9408
+ // })
9409
+
9410
+ // parseStream.on('data', async (data) => {
9411
+ // saveQueue.push(data)
9412
+ // })
9413
+ // let res
9414
+ // const p = new Promise((resolve, reject) => {
9415
+ // res = resolve
9416
+ // })
9417
+ // saveQueue.drain(async (x) => {
9418
+ // res()
9419
+ // })
9420
+ // return p
9421
+ // }
9422
+ }
9423
+
9424
+ function loadSync (filename) {
9425
+ try {
9426
+ return readFileSync(filename, 'utf8').toString()
9427
+ } catch (error) {
9428
+ // console.log('error', error)
9429
+ return null
9430
+ }
9431
+ }
9432
+
9433
+ async function writeSync (fullpath, stringValue) {
9434
+ await mkdir(dirname(fullpath), { recursive: true });
9435
+ // writeFileSync(fullpath, stringValue)
9436
+ await writeFile(fullpath, stringValue);
9437
+ }
9438
+
9144
9439
  var cryptoBrowserify = {};
9145
9440
 
9146
9441
  var inherits$x;
@@ -9661,15 +9956,7 @@ var _polyfillNode_events = /*#__PURE__*/Object.freeze({
9661
9956
 
9662
9957
  var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_events);
9663
9958
 
9664
- var streamBrowser;
9665
- var hasRequiredStreamBrowser;
9666
-
9667
- function requireStreamBrowser () {
9668
- if (hasRequiredStreamBrowser) return streamBrowser;
9669
- hasRequiredStreamBrowser = 1;
9670
- streamBrowser = require$$0$1.EventEmitter;
9671
- return streamBrowser;
9672
- }
9959
+ var streamBrowser = require$$0$1.EventEmitter;
9673
9960
 
9674
9961
  // shim for using process in browser
9675
9962
  // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
@@ -9812,7 +10099,7 @@ var argv = [];
9812
10099
  var version$2 = ''; // empty string to avoid regexp issues
9813
10100
  var versions = {};
9814
10101
  var release = {};
9815
- var config = {};
10102
+ var config$1 = {};
9816
10103
 
9817
10104
  function noop$3() {}
9818
10105
 
@@ -9889,7 +10176,7 @@ var browser$1$1 = {
9889
10176
  hrtime: hrtime,
9890
10177
  platform: platform,
9891
10178
  release: release,
9892
- config: config,
10179
+ config: config$1,
9893
10180
  uptime: uptime
9894
10181
  };
9895
10182
 
@@ -9970,11 +10257,11 @@ function format(f) {
9970
10257
  // Mark that a method should not be used.
9971
10258
  // Returns a modified function which warns once by default.
9972
10259
  // If --no-deprecation is set, then it is a no-op.
9973
- function deprecate$1(fn, msg) {
10260
+ function deprecate$2(fn, msg) {
9974
10261
  // Allow for deprecating things in the process of starting up.
9975
10262
  if (isUndefined(global$1.process)) {
9976
10263
  return function() {
9977
- return deprecate$1(fn, msg).apply(this, arguments);
10264
+ return deprecate$2(fn, msg).apply(this, arguments);
9978
10265
  };
9979
10266
  }
9980
10267
 
@@ -10583,7 +10870,7 @@ var _polyfillNode_util = {
10583
10870
  isBoolean: isBoolean,
10584
10871
  isArray: isArray,
10585
10872
  inspect: inspect,
10586
- deprecate: deprecate$1,
10873
+ deprecate: deprecate$2,
10587
10874
  format: format,
10588
10875
  debuglog: debuglog,
10589
10876
  promisify: promisify,
@@ -10596,7 +10883,7 @@ var _polyfillNode_util$1 = /*#__PURE__*/Object.freeze({
10596
10883
  callbackify: callbackify,
10597
10884
  debuglog: debuglog,
10598
10885
  default: _polyfillNode_util,
10599
- deprecate: deprecate$1,
10886
+ deprecate: deprecate$2,
10600
10887
  format: format,
10601
10888
  inherits: inherits$w,
10602
10889
  inspect: inspect,
@@ -10784,108 +11071,99 @@ function requireBuffer_list () {
10784
11071
  return buffer_list;
10785
11072
  }
10786
11073
 
10787
- var destroy_1;
10788
- var hasRequiredDestroy;
10789
-
10790
- function requireDestroy () {
10791
- if (hasRequiredDestroy) return destroy_1;
10792
- hasRequiredDestroy = 1;
10793
-
10794
- // undocumented cb() API, needed for core, not for public API
10795
- function destroy(err, cb) {
10796
- const readableDestroyed = this._readableState && this._readableState.destroyed;
10797
- const writableDestroyed = this._writableState && this._writableState.destroyed;
10798
- if (readableDestroyed || writableDestroyed) {
10799
- if (cb) {
10800
- cb(err);
10801
- } else if (err) {
10802
- if (!this._writableState) {
10803
- process.nextTick(emitErrorNT, this, err);
10804
- } else if (!this._writableState.errorEmitted) {
10805
- this._writableState.errorEmitted = true;
10806
- process.nextTick(emitErrorNT, this, err);
10807
- }
10808
- }
10809
- return this;
10810
- }
11074
+ // undocumented cb() API, needed for core, not for public API
11075
+ function destroy(err, cb) {
11076
+ const readableDestroyed = this._readableState && this._readableState.destroyed;
11077
+ const writableDestroyed = this._writableState && this._writableState.destroyed;
11078
+ if (readableDestroyed || writableDestroyed) {
11079
+ if (cb) {
11080
+ cb(err);
11081
+ } else if (err) {
11082
+ if (!this._writableState) {
11083
+ process.nextTick(emitErrorNT, this, err);
11084
+ } else if (!this._writableState.errorEmitted) {
11085
+ this._writableState.errorEmitted = true;
11086
+ process.nextTick(emitErrorNT, this, err);
11087
+ }
11088
+ }
11089
+ return this;
11090
+ }
10811
11091
 
10812
- // we set destroyed to true before firing error callbacks in order
10813
- // to make it re-entrance safe in case destroy() is called within callbacks
11092
+ // we set destroyed to true before firing error callbacks in order
11093
+ // to make it re-entrance safe in case destroy() is called within callbacks
10814
11094
 
10815
- if (this._readableState) {
10816
- this._readableState.destroyed = true;
10817
- }
11095
+ if (this._readableState) {
11096
+ this._readableState.destroyed = true;
11097
+ }
10818
11098
 
10819
- // if this is a duplex stream mark the writable part as destroyed as well
10820
- if (this._writableState) {
10821
- this._writableState.destroyed = true;
10822
- }
10823
- this._destroy(err || null, err => {
10824
- if (!cb && err) {
10825
- if (!this._writableState) {
10826
- process.nextTick(emitErrorAndCloseNT, this, err);
10827
- } else if (!this._writableState.errorEmitted) {
10828
- this._writableState.errorEmitted = true;
10829
- process.nextTick(emitErrorAndCloseNT, this, err);
10830
- } else {
10831
- process.nextTick(emitCloseNT, this);
10832
- }
10833
- } else if (cb) {
10834
- process.nextTick(emitCloseNT, this);
10835
- cb(err);
10836
- } else {
10837
- process.nextTick(emitCloseNT, this);
10838
- }
10839
- });
10840
- return this;
10841
- }
10842
- function emitErrorAndCloseNT(self, err) {
10843
- emitErrorNT(self, err);
10844
- emitCloseNT(self);
10845
- }
10846
- function emitCloseNT(self) {
10847
- if (self._writableState && !self._writableState.emitClose) return;
10848
- if (self._readableState && !self._readableState.emitClose) return;
10849
- self.emit('close');
10850
- }
10851
- function undestroy() {
10852
- if (this._readableState) {
10853
- this._readableState.destroyed = false;
10854
- this._readableState.reading = false;
10855
- this._readableState.ended = false;
10856
- this._readableState.endEmitted = false;
10857
- }
10858
- if (this._writableState) {
10859
- this._writableState.destroyed = false;
10860
- this._writableState.ended = false;
10861
- this._writableState.ending = false;
10862
- this._writableState.finalCalled = false;
10863
- this._writableState.prefinished = false;
10864
- this._writableState.finished = false;
10865
- this._writableState.errorEmitted = false;
10866
- }
10867
- }
10868
- function emitErrorNT(self, err) {
10869
- self.emit('error', err);
10870
- }
10871
- function errorOrDestroy(stream, err) {
10872
- // We have tests that rely on errors being emitted
10873
- // in the same tick, so changing this is semver major.
10874
- // For now when you opt-in to autoDestroy we allow
10875
- // the error to be emitted nextTick. In a future
10876
- // semver major update we should change the default to this.
10877
-
10878
- const rState = stream._readableState;
10879
- const wState = stream._writableState;
10880
- if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
10881
- }
10882
- destroy_1 = {
10883
- destroy,
10884
- undestroy,
10885
- errorOrDestroy
10886
- };
10887
- return destroy_1;
11099
+ // if this is a duplex stream mark the writable part as destroyed as well
11100
+ if (this._writableState) {
11101
+ this._writableState.destroyed = true;
11102
+ }
11103
+ this._destroy(err || null, err => {
11104
+ if (!cb && err) {
11105
+ if (!this._writableState) {
11106
+ process.nextTick(emitErrorAndCloseNT, this, err);
11107
+ } else if (!this._writableState.errorEmitted) {
11108
+ this._writableState.errorEmitted = true;
11109
+ process.nextTick(emitErrorAndCloseNT, this, err);
11110
+ } else {
11111
+ process.nextTick(emitCloseNT, this);
11112
+ }
11113
+ } else if (cb) {
11114
+ process.nextTick(emitCloseNT, this);
11115
+ cb(err);
11116
+ } else {
11117
+ process.nextTick(emitCloseNT, this);
11118
+ }
11119
+ });
11120
+ return this;
11121
+ }
11122
+ function emitErrorAndCloseNT(self, err) {
11123
+ emitErrorNT(self, err);
11124
+ emitCloseNT(self);
11125
+ }
11126
+ function emitCloseNT(self) {
11127
+ if (self._writableState && !self._writableState.emitClose) return;
11128
+ if (self._readableState && !self._readableState.emitClose) return;
11129
+ self.emit('close');
11130
+ }
11131
+ function undestroy() {
11132
+ if (this._readableState) {
11133
+ this._readableState.destroyed = false;
11134
+ this._readableState.reading = false;
11135
+ this._readableState.ended = false;
11136
+ this._readableState.endEmitted = false;
11137
+ }
11138
+ if (this._writableState) {
11139
+ this._writableState.destroyed = false;
11140
+ this._writableState.ended = false;
11141
+ this._writableState.ending = false;
11142
+ this._writableState.finalCalled = false;
11143
+ this._writableState.prefinished = false;
11144
+ this._writableState.finished = false;
11145
+ this._writableState.errorEmitted = false;
11146
+ }
11147
+ }
11148
+ function emitErrorNT(self, err) {
11149
+ self.emit('error', err);
10888
11150
  }
11151
+ function errorOrDestroy(stream, err) {
11152
+ // We have tests that rely on errors being emitted
11153
+ // in the same tick, so changing this is semver major.
11154
+ // For now when you opt-in to autoDestroy we allow
11155
+ // the error to be emitted nextTick. In a future
11156
+ // semver major update we should change the default to this.
11157
+
11158
+ const rState = stream._readableState;
11159
+ const wState = stream._writableState;
11160
+ if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
11161
+ }
11162
+ var destroy_1 = {
11163
+ destroy,
11164
+ undestroy,
11165
+ errorOrDestroy
11166
+ };
10889
11167
 
10890
11168
  var errorsBrowser = {};
10891
11169
 
@@ -11015,109 +11293,92 @@ createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
11015
11293
  createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
11016
11294
  errorsBrowser.codes = codes;
11017
11295
 
11018
- var state;
11019
- var hasRequiredState;
11020
-
11021
- function requireState () {
11022
- if (hasRequiredState) return state;
11023
- hasRequiredState = 1;
11024
-
11025
- const ERR_INVALID_OPT_VALUE = errorsBrowser.codes.ERR_INVALID_OPT_VALUE;
11026
- function highWaterMarkFrom(options, isDuplex, duplexKey) {
11027
- return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
11028
- }
11029
- function getHighWaterMark(state, options, duplexKey, isDuplex) {
11030
- const hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
11031
- if (hwm != null) {
11032
- if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
11033
- const name = isDuplex ? duplexKey : 'highWaterMark';
11034
- throw new ERR_INVALID_OPT_VALUE(name, hwm);
11035
- }
11036
- return Math.floor(hwm);
11037
- }
11038
-
11039
- // Default value
11040
- return state.objectMode ? 16 : 16 * 1024;
11041
- }
11042
- state = {
11043
- getHighWaterMark
11044
- };
11045
- return state;
11296
+ const ERR_INVALID_OPT_VALUE = errorsBrowser.codes.ERR_INVALID_OPT_VALUE;
11297
+ function highWaterMarkFrom(options, isDuplex, duplexKey) {
11298
+ return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
11046
11299
  }
11300
+ function getHighWaterMark(state, options, duplexKey, isDuplex) {
11301
+ const hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
11302
+ if (hwm != null) {
11303
+ if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
11304
+ const name = isDuplex ? duplexKey : 'highWaterMark';
11305
+ throw new ERR_INVALID_OPT_VALUE(name, hwm);
11306
+ }
11307
+ return Math.floor(hwm);
11308
+ }
11047
11309
 
11048
- var browser$b;
11049
- var hasRequiredBrowser$3;
11310
+ // Default value
11311
+ return state.objectMode ? 16 : 16 * 1024;
11312
+ }
11313
+ var state = {
11314
+ getHighWaterMark
11315
+ };
11050
11316
 
11051
- function requireBrowser$3 () {
11052
- if (hasRequiredBrowser$3) return browser$b;
11053
- hasRequiredBrowser$3 = 1;
11054
- /**
11055
- * Module exports.
11056
- */
11317
+ /**
11318
+ * Module exports.
11319
+ */
11057
11320
 
11058
- browser$b = deprecate;
11321
+ var browser$b = deprecate$1;
11059
11322
 
11060
- /**
11061
- * Mark that a method should not be used.
11062
- * Returns a modified function which warns once by default.
11063
- *
11064
- * If `localStorage.noDeprecation = true` is set, then it is a no-op.
11065
- *
11066
- * If `localStorage.throwDeprecation = true` is set, then deprecated functions
11067
- * will throw an Error when invoked.
11068
- *
11069
- * If `localStorage.traceDeprecation = true` is set, then deprecated functions
11070
- * will invoke `console.trace()` instead of `console.error()`.
11071
- *
11072
- * @param {Function} fn - the function to deprecate
11073
- * @param {String} msg - the string to print to the console when `fn` is invoked
11074
- * @returns {Function} a new "deprecated" version of `fn`
11075
- * @api public
11076
- */
11323
+ /**
11324
+ * Mark that a method should not be used.
11325
+ * Returns a modified function which warns once by default.
11326
+ *
11327
+ * If `localStorage.noDeprecation = true` is set, then it is a no-op.
11328
+ *
11329
+ * If `localStorage.throwDeprecation = true` is set, then deprecated functions
11330
+ * will throw an Error when invoked.
11331
+ *
11332
+ * If `localStorage.traceDeprecation = true` is set, then deprecated functions
11333
+ * will invoke `console.trace()` instead of `console.error()`.
11334
+ *
11335
+ * @param {Function} fn - the function to deprecate
11336
+ * @param {String} msg - the string to print to the console when `fn` is invoked
11337
+ * @returns {Function} a new "deprecated" version of `fn`
11338
+ * @api public
11339
+ */
11077
11340
 
11078
- function deprecate (fn, msg) {
11079
- if (config('noDeprecation')) {
11080
- return fn;
11081
- }
11341
+ function deprecate$1 (fn, msg) {
11342
+ if (config('noDeprecation')) {
11343
+ return fn;
11344
+ }
11082
11345
 
11083
- var warned = false;
11084
- function deprecated() {
11085
- if (!warned) {
11086
- if (config('throwDeprecation')) {
11087
- throw new Error(msg);
11088
- } else if (config('traceDeprecation')) {
11089
- console.trace(msg);
11090
- } else {
11091
- console.warn(msg);
11092
- }
11093
- warned = true;
11094
- }
11095
- return fn.apply(this, arguments);
11096
- }
11346
+ var warned = false;
11347
+ function deprecated() {
11348
+ if (!warned) {
11349
+ if (config('throwDeprecation')) {
11350
+ throw new Error(msg);
11351
+ } else if (config('traceDeprecation')) {
11352
+ console.trace(msg);
11353
+ } else {
11354
+ console.warn(msg);
11355
+ }
11356
+ warned = true;
11357
+ }
11358
+ return fn.apply(this, arguments);
11359
+ }
11097
11360
 
11098
- return deprecated;
11099
- }
11361
+ return deprecated;
11362
+ }
11100
11363
 
11101
- /**
11102
- * Checks `localStorage` for boolean values for the given `name`.
11103
- *
11104
- * @param {String} name
11105
- * @returns {Boolean}
11106
- * @api private
11107
- */
11364
+ /**
11365
+ * Checks `localStorage` for boolean values for the given `name`.
11366
+ *
11367
+ * @param {String} name
11368
+ * @returns {Boolean}
11369
+ * @api private
11370
+ */
11108
11371
 
11109
- function config (name) {
11110
- // accessing global.localStorage can trigger a DOMException in sandboxed iframes
11111
- try {
11112
- if (!commonjsGlobal.localStorage) return false;
11113
- } catch (_) {
11114
- return false;
11115
- }
11116
- var val = commonjsGlobal.localStorage[name];
11117
- if (null == val) return false;
11118
- return String(val).toLowerCase() === 'true';
11119
- }
11120
- return browser$b;
11372
+ function config (name) {
11373
+ // accessing global.localStorage can trigger a DOMException in sandboxed iframes
11374
+ try {
11375
+ if (!commonjsGlobal.localStorage) return false;
11376
+ } catch (_) {
11377
+ return false;
11378
+ }
11379
+ var val = commonjsGlobal.localStorage[name];
11380
+ if (null == val) return false;
11381
+ return String(val).toLowerCase() === 'true';
11121
11382
  }
11122
11383
 
11123
11384
  var _stream_writable;
@@ -11148,12 +11409,12 @@ function require_stream_writable () {
11148
11409
 
11149
11410
  /*<replacement>*/
11150
11411
  const internalUtil = {
11151
- deprecate: requireBrowser$3()
11412
+ deprecate: browser$b
11152
11413
  };
11153
11414
  /*</replacement>*/
11154
11415
 
11155
11416
  /*<replacement>*/
11156
- var Stream = requireStreamBrowser();
11417
+ var Stream = streamBrowser;
11157
11418
  /*</replacement>*/
11158
11419
 
11159
11420
  const Buffer = require$$6$1.Buffer;
@@ -11164,8 +11425,8 @@ function require_stream_writable () {
11164
11425
  function _isUint8Array(obj) {
11165
11426
  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
11166
11427
  }
11167
- const destroyImpl = requireDestroy();
11168
- const _require = requireState(),
11428
+ const destroyImpl = destroy_1;
11429
+ const _require = state,
11169
11430
  getHighWaterMark = _require.getHighWaterMark;
11170
11431
  const _require$codes = errorsBrowser.codes,
11171
11432
  ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
@@ -12359,7 +12620,7 @@ function require_stream_readable () {
12359
12620
  /*</replacement>*/
12360
12621
 
12361
12622
  /*<replacement>*/
12362
- var Stream = requireStreamBrowser();
12623
+ var Stream = streamBrowser;
12363
12624
  /*</replacement>*/
12364
12625
 
12365
12626
  const Buffer = require$$6$1.Buffer;
@@ -12382,8 +12643,8 @@ function require_stream_readable () {
12382
12643
  /*</replacement>*/
12383
12644
 
12384
12645
  const BufferList = requireBuffer_list();
12385
- const destroyImpl = requireDestroy();
12386
- const _require = requireState(),
12646
+ const destroyImpl = destroy_1;
12647
+ const _require = state,
12387
12648
  getHighWaterMark = _require.getHighWaterMark;
12388
12649
  const _require$codes = errorsBrowser.codes,
12389
12650
  ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
@@ -15749,7 +16010,7 @@ function WriteReq(chunk, encoding, cb) {
15749
16010
 
15750
16011
  function WritableState(options, stream) {
15751
16012
  Object.defineProperty(this, 'buffer', {
15752
- get: deprecate$1(function () {
16013
+ get: deprecate$2(function () {
15753
16014
  return this.getBuffer();
15754
16015
  }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
15755
16016
  });
@@ -39544,6 +39805,7 @@ class Valet {
39544
39805
  constructor (name = 'default', keyMaterial) {
39545
39806
  this.name = name;
39546
39807
  this.setKeyMaterial(keyMaterial);
39808
+ this.loader = new Loader(name, this.keyId); // todo send this config.loader, if we ever need it
39547
39809
  this.uploadQueue = cargoQueue(async (tasks, callback) => {
39548
39810
  // console.log(
39549
39811
  // 'queue worker',
@@ -39578,6 +39840,10 @@ class Valet {
39578
39840
  });
39579
39841
  }
39580
39842
 
39843
+ saveHeader (header) {
39844
+ return this.loader.saveHeader(header)
39845
+ }
39846
+
39581
39847
  getKeyMaterial () {
39582
39848
  return this.keyMaterial
39583
39849
  }
@@ -39618,19 +39884,6 @@ class Valet {
39618
39884
  }
39619
39885
  }
39620
39886
 
39621
- withDB = async dbWorkFun => {
39622
- if (!this.idb) {
39623
- this.idb = await openDB(`fp.${this.keyId}.${this.name}.valet`, 3, {
39624
- upgrade (db, oldVersion, newVersion, transaction) {
39625
- if (oldVersion < 1) {
39626
- db.createObjectStore('cars');
39627
- }
39628
- }
39629
- });
39630
- }
39631
- return await dbWorkFun(this.idb)
39632
- }
39633
-
39634
39887
  /**
39635
39888
  * Iterate over all blocks in the store.
39636
39889
  *
@@ -39671,6 +39924,7 @@ class Valet {
39671
39924
  blockHasher: blockOpts$1.hasher,
39672
39925
  blockCodec: blockOpts$1.codec
39673
39926
  });
39927
+ this.valetRoot = indexNode;
39674
39928
  }
39675
39929
 
39676
39930
  const got = await indexNode.get(cid);
@@ -39717,6 +39971,7 @@ class Valet {
39717
39971
  * @param {*} value
39718
39972
  */
39719
39973
  async parkCar (carCid, value, cids) {
39974
+ // const callId = Math.random().toString(36).substring(7)
39720
39975
  // console.log('parkCar', this.instanceId, this.name, carCid, cids)
39721
39976
  const combinedReader = await this.getCombinedReader(carCid);
39722
39977
  const mapNode = await addCidsToCarIndex(
@@ -39729,7 +39984,7 @@ class Valet {
39729
39984
  this.valetRoot = mapNode;
39730
39985
  this.valetRootCid = mapNode.cid;
39731
39986
  // make a block set with all the cids of the map
39732
- const saveValetBlocks = new VMemoryBlockstore(); // todo this blockstore should read from the last valetCid car also
39987
+ const saveValetBlocks = new VMemoryBlockstore();
39733
39988
 
39734
39989
  for await (const cidx of mapNode.cids()) {
39735
39990
  const bytes = await combinedReader.get(cidx);
@@ -39742,7 +39997,8 @@ class Valet {
39742
39997
  newValetCidCar = await blocksToCarBlock(this.valetRootCid, saveValetBlocks);
39743
39998
  }
39744
39999
  // console.log('newValetCidCar', this.name, Math.floor(newValetCidCar.bytes.length / 1024))
39745
- await this.writeCars([
40000
+ // console.log('writeCars', callId, carCid.toString(), newValetCidCar.cid.toString())
40001
+ await this.loader.writeCars([
39746
40002
  {
39747
40003
  cid: carCid,
39748
40004
  bytes: value,
@@ -39758,6 +40014,8 @@ class Valet {
39758
40014
 
39759
40015
  this.valetRootCarCid = newValetCidCar.cid; // goes to clock
39760
40016
 
40017
+ // console.log('wroteCars', callId, carCid.toString(), newValetCidCar.cid.toString())
40018
+
39761
40019
  // console.log('parked car', carCid, value.length, Array.from(cids))
39762
40020
  // upload to web3.storage if we have credentials
39763
40021
  if (this.uploadFunction) {
@@ -39772,29 +40030,13 @@ class Valet {
39772
40030
  }
39773
40031
  }
39774
40032
 
39775
- async writeCars (cars) {
39776
- return await this.withDB(async db => {
39777
- const tx = db.transaction(['cars'], 'readwrite');
39778
- for (const { cid, bytes, replaces } of cars) {
39779
- await tx.objectStore('cars').put(bytes, cid.toString());
39780
- // todo remove old maps
39781
- if (replaces) {
39782
- await tx.objectStore('cars').delete(replaces.toString());
39783
- }
39784
- }
39785
- return await tx.done
39786
- })
39787
- }
39788
-
39789
40033
  remoteBlockFunction = null
39790
40034
 
39791
40035
  async getCarReader (carCid) {
39792
40036
  carCid = carCid.toString();
39793
- const carBytes = await this.withDB(async db => {
39794
- const tx = db.transaction(['cars'], 'readonly');
39795
- // console.log('getCarReader', carCid)
39796
- return await tx.objectStore('cars').get(carCid)
39797
- });
40037
+ const carBytes = await this.loader.readCar(carCid);
40038
+ // const callID = Math.random().toString(36).substring(7)
40039
+ // console.log('getCarReader', callID, carCid)
39798
40040
  const reader = await CarReader.fromBytes(carBytes);
39799
40041
  if (this.keyMaterial) {
39800
40042
  const roots = await reader.getRoots();
@@ -39818,7 +40060,7 @@ class Valet {
39818
40060
 
39819
40061
  // last block is the root ??? todo
39820
40062
  const rootBlock = blocks[blocks.length - 1];
39821
-
40063
+ // console.log('got reader', callID, carCid)
39822
40064
  return {
39823
40065
  root: rootBlock,
39824
40066
  get: async dataCID => {
@@ -39945,6 +40187,8 @@ const blocksFromEncryptedCarBlock = async (cid, get, keyMaterial) => {
39945
40187
 
39946
40188
  const addCidsToCarIndex = async (blockstore, valetRoot, valetRootCid, bulkOperations) => {
39947
40189
  let indexNode;
40190
+ // const callID = Math.random().toString(32).substring(2, 8)
40191
+ // console.log('addCidsToCarIndex', callID, valetRootCid, bulkOperations.length)
39948
40192
  if (valetRootCid) {
39949
40193
  if (valetRoot) {
39950
40194
  indexNode = valetRoot;
@@ -39964,6 +40208,7 @@ const addCidsToCarIndex = async (blockstore, valetRoot, valetRootCid, bulkOperat
39964
40208
  // console.log('adding', key, value)
39965
40209
  await indexNode.set(key, value);
39966
40210
  }
40211
+ // console.log('newCidsToCarIndex', callID, indexNode.cid, bulkOperations.length)
39967
40212
  return indexNode
39968
40213
  };
39969
40214
 
@@ -40916,22 +41161,6 @@ object.factory = function (codec) {
40916
41161
  exports.type = 'charwise';
40917
41162
  } (charwise));
40918
41163
 
40919
- /* global localStorage */
40920
- let storageSupported = false;
40921
- try {
40922
- storageSupported = window.localStorage && true;
40923
- } catch (e) {}
40924
- function localGet (key) {
40925
- if (storageSupported) {
40926
- return localStorage && localStorage.getItem(key)
40927
- }
40928
- }
40929
- function localSet (key, value) {
40930
- if (storageSupported) {
40931
- return localStorage && localStorage.setItem(key, value)
40932
- }
40933
- }
40934
-
40935
41164
  // @ts-nocheck
40936
41165
  const parseCID = cid => (typeof cid === 'string' ? CID$1.parse(cid) : cid);
40937
41166
 
@@ -40956,7 +41185,7 @@ class Database {
40956
41185
  this.name = name;
40957
41186
  this.instanceId = `fp.${this.name}.${Math.random().toString(36).substring(2, 7)}`;
40958
41187
  this.blocks = new TransactionBlockstore(name, config.key);
40959
- this.indexBlocks = new TransactionBlockstore(name + '.indexes', config.key);
41188
+ this.indexBlocks = new TransactionBlockstore(name ? name + '.indexes' : null, config.key);
40960
41189
  this.clock = clock;
40961
41190
  this.config = config;
40962
41191
  }
@@ -41000,7 +41229,7 @@ class Database {
41000
41229
 
41001
41230
  maybeSaveClock () {
41002
41231
  if (this.name && this.blocks.valet) {
41003
- localSet('fp.' + this.name, JSON.stringify(this));
41232
+ this.blocks.valet.saveHeader(JSON.stringify(this));
41004
41233
  }
41005
41234
  }
41006
41235
 
@@ -41236,6 +41465,7 @@ class Database {
41236
41465
  console.error('failed', event);
41237
41466
  throw new Error('failed to put at storage layer')
41238
41467
  }
41468
+ // await new Promise(resolve => setTimeout(resolve, 10)) // makes concurrent tests work
41239
41469
  this.applyClock(prevClock, result.head);
41240
41470
  await this.notifyListeners([decodedEvent]); // this type is odd
41241
41471
  return {
@@ -44097,8 +44327,8 @@ class Fireproof {
44097
44327
  static storage = (name = null, opts = {}) => {
44098
44328
  if (name) {
44099
44329
  opts.name = name;
44100
- // todo this can come from a registry also eg remote database / config, etc
44101
- const existing = localGet('fp.' + name);
44330
+ const loader = new Loader(name, opts.loader);
44331
+ const existing = loader.getHeader();
44102
44332
  if (existing) {
44103
44333
  const existingConfig = JSON.parse(existing);
44104
44334
  return Fireproof.fromConfig(name, existingConfig, opts)