@fireproof/core 0.6.3-dev → 0.6.4

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,6 +1,3 @@
1
- import { readFileSync } from 'node:fs';
2
- import { mkdir, writeFile } from 'fs/promises';
3
-
4
1
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
5
2
 
6
3
  function getDefaultExportFromCjs (x) {
@@ -8144,6 +8141,267 @@ var raw = /*#__PURE__*/Object.freeze({
8144
8141
  name: name$2
8145
8142
  });
8146
8143
 
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
+
8147
8405
  var cargoQueueExports = {};
8148
8406
  var cargoQueue$1 = {
8149
8407
  get exports(){ return cargoQueueExports; },
@@ -8185,7 +8443,7 @@ Object.defineProperty(setImmediate$1, "__esModule", {
8185
8443
  value: true
8186
8444
  });
8187
8445
  setImmediate$1.fallback = fallback;
8188
- setImmediate$1.wrap = wrap$1;
8446
+ setImmediate$1.wrap = wrap;
8189
8447
  /* istanbul ignore file */
8190
8448
 
8191
8449
  var hasQueueMicrotask = setImmediate$1.hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask;
@@ -8196,7 +8454,7 @@ function fallback(fn) {
8196
8454
  setTimeout(fn, 0);
8197
8455
  }
8198
8456
 
8199
- function wrap$1(defer) {
8457
+ function wrap(defer) {
8200
8458
  return (fn, ...args) => defer(() => fn(...args));
8201
8459
  }
8202
8460
 
@@ -8212,7 +8470,7 @@ if (hasQueueMicrotask) {
8212
8470
  _defer = fallback;
8213
8471
  }
8214
8472
 
8215
- setImmediate$1.default = wrap$1(_defer);
8473
+ setImmediate$1.default = wrap(_defer);
8216
8474
 
8217
8475
  var DoublyLinkedListExports = {};
8218
8476
  var DoublyLinkedList = {
@@ -8883,559 +9141,6 @@ function requireWrapAsync () {
8883
9141
 
8884
9142
  var cargoQueue = /*@__PURE__*/getDefaultExportFromCjs(cargoQueueExports);
8885
9143
 
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
-
9439
9144
  var cryptoBrowserify = {};
9440
9145
 
9441
9146
  var inherits$x;
@@ -39839,7 +39544,6 @@ class Valet {
39839
39544
  constructor (name = 'default', keyMaterial) {
39840
39545
  this.name = name;
39841
39546
  this.setKeyMaterial(keyMaterial);
39842
- this.loader = new Loader(name, this.keyId); // todo send this config.loader, if we ever need it
39843
39547
  this.uploadQueue = cargoQueue(async (tasks, callback) => {
39844
39548
  // console.log(
39845
39549
  // 'queue worker',
@@ -39874,10 +39578,6 @@ class Valet {
39874
39578
  });
39875
39579
  }
39876
39580
 
39877
- saveHeader (header) {
39878
- return this.loader.saveHeader(header)
39879
- }
39880
-
39881
39581
  getKeyMaterial () {
39882
39582
  return this.keyMaterial
39883
39583
  }
@@ -39918,6 +39618,19 @@ class Valet {
39918
39618
  }
39919
39619
  }
39920
39620
 
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
+
39921
39634
  /**
39922
39635
  * Iterate over all blocks in the store.
39923
39636
  *
@@ -39958,7 +39671,6 @@ class Valet {
39958
39671
  blockHasher: blockOpts$1.hasher,
39959
39672
  blockCodec: blockOpts$1.codec
39960
39673
  });
39961
- this.valetRoot = indexNode;
39962
39674
  }
39963
39675
 
39964
39676
  const got = await indexNode.get(cid);
@@ -40005,7 +39717,6 @@ class Valet {
40005
39717
  * @param {*} value
40006
39718
  */
40007
39719
  async parkCar (carCid, value, cids) {
40008
- // const callId = Math.random().toString(36).substring(7)
40009
39720
  // console.log('parkCar', this.instanceId, this.name, carCid, cids)
40010
39721
  const combinedReader = await this.getCombinedReader(carCid);
40011
39722
  const mapNode = await addCidsToCarIndex(
@@ -40018,7 +39729,7 @@ class Valet {
40018
39729
  this.valetRoot = mapNode;
40019
39730
  this.valetRootCid = mapNode.cid;
40020
39731
  // make a block set with all the cids of the map
40021
- const saveValetBlocks = new VMemoryBlockstore();
39732
+ const saveValetBlocks = new VMemoryBlockstore(); // todo this blockstore should read from the last valetCid car also
40022
39733
 
40023
39734
  for await (const cidx of mapNode.cids()) {
40024
39735
  const bytes = await combinedReader.get(cidx);
@@ -40031,8 +39742,7 @@ class Valet {
40031
39742
  newValetCidCar = await blocksToCarBlock(this.valetRootCid, saveValetBlocks);
40032
39743
  }
40033
39744
  // console.log('newValetCidCar', this.name, Math.floor(newValetCidCar.bytes.length / 1024))
40034
- // console.log('writeCars', callId, carCid.toString(), newValetCidCar.cid.toString())
40035
- await this.loader.writeCars([
39745
+ await this.writeCars([
40036
39746
  {
40037
39747
  cid: carCid,
40038
39748
  bytes: value,
@@ -40048,8 +39758,6 @@ class Valet {
40048
39758
 
40049
39759
  this.valetRootCarCid = newValetCidCar.cid; // goes to clock
40050
39760
 
40051
- // console.log('wroteCars', callId, carCid.toString(), newValetCidCar.cid.toString())
40052
-
40053
39761
  // console.log('parked car', carCid, value.length, Array.from(cids))
40054
39762
  // upload to web3.storage if we have credentials
40055
39763
  if (this.uploadFunction) {
@@ -40064,13 +39772,29 @@ class Valet {
40064
39772
  }
40065
39773
  }
40066
39774
 
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
+
40067
39789
  remoteBlockFunction = null
40068
39790
 
40069
39791
  async getCarReader (carCid) {
40070
39792
  carCid = carCid.toString();
40071
- const carBytes = await this.loader.readCar(carCid);
40072
- // const callID = Math.random().toString(36).substring(7)
40073
- // console.log('getCarReader', callID, carCid)
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
+ });
40074
39798
  const reader = await CarReader.fromBytes(carBytes);
40075
39799
  if (this.keyMaterial) {
40076
39800
  const roots = await reader.getRoots();
@@ -40094,7 +39818,7 @@ class Valet {
40094
39818
 
40095
39819
  // last block is the root ??? todo
40096
39820
  const rootBlock = blocks[blocks.length - 1];
40097
- // console.log('got reader', callID, carCid)
39821
+
40098
39822
  return {
40099
39823
  root: rootBlock,
40100
39824
  get: async dataCID => {
@@ -40221,8 +39945,6 @@ const blocksFromEncryptedCarBlock = async (cid, get, keyMaterial) => {
40221
39945
 
40222
39946
  const addCidsToCarIndex = async (blockstore, valetRoot, valetRootCid, bulkOperations) => {
40223
39947
  let indexNode;
40224
- // const callID = Math.random().toString(32).substring(2, 8)
40225
- // console.log('addCidsToCarIndex', callID, valetRootCid, bulkOperations.length)
40226
39948
  if (valetRootCid) {
40227
39949
  if (valetRoot) {
40228
39950
  indexNode = valetRoot;
@@ -40242,7 +39964,6 @@ const addCidsToCarIndex = async (blockstore, valetRoot, valetRootCid, bulkOperat
40242
39964
  // console.log('adding', key, value)
40243
39965
  await indexNode.set(key, value);
40244
39966
  }
40245
- // console.log('newCidsToCarIndex', callID, indexNode.cid, bulkOperations.length)
40246
39967
  return indexNode
40247
39968
  };
40248
39969
 
@@ -41195,6 +40916,22 @@ object.factory = function (codec) {
41195
40916
  exports.type = 'charwise';
41196
40917
  } (charwise));
41197
40918
 
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
+
41198
40935
  // @ts-nocheck
41199
40936
  const parseCID = cid => (typeof cid === 'string' ? CID$1.parse(cid) : cid);
41200
40937
 
@@ -41219,7 +40956,7 @@ class Database {
41219
40956
  this.name = name;
41220
40957
  this.instanceId = `fp.${this.name}.${Math.random().toString(36).substring(2, 7)}`;
41221
40958
  this.blocks = new TransactionBlockstore(name, config.key);
41222
- this.indexBlocks = new TransactionBlockstore(name ? name + '.indexes' : null, config.key);
40959
+ this.indexBlocks = new TransactionBlockstore(name + '.indexes', config.key);
41223
40960
  this.clock = clock;
41224
40961
  this.config = config;
41225
40962
  }
@@ -41263,7 +41000,7 @@ class Database {
41263
41000
 
41264
41001
  maybeSaveClock () {
41265
41002
  if (this.name && this.blocks.valet) {
41266
- this.blocks.valet.saveHeader(JSON.stringify(this));
41003
+ localSet('fp.' + this.name, JSON.stringify(this));
41267
41004
  }
41268
41005
  }
41269
41006
 
@@ -41499,7 +41236,6 @@ class Database {
41499
41236
  console.error('failed', event);
41500
41237
  throw new Error('failed to put at storage layer')
41501
41238
  }
41502
- // await new Promise(resolve => setTimeout(resolve, 10)) // makes concurrent tests work
41503
41239
  this.applyClock(prevClock, result.head);
41504
41240
  await this.notifyListeners([decodedEvent]); // this type is odd
41505
41241
  return {
@@ -44361,8 +44097,8 @@ class Fireproof {
44361
44097
  static storage = (name = null, opts = {}) => {
44362
44098
  if (name) {
44363
44099
  opts.name = name;
44364
- const loader = new Loader(name, opts.loader);
44365
- const existing = loader.getHeader();
44100
+ // todo this can come from a registry also eg remote database / config, etc
44101
+ const existing = localGet('fp.' + name);
44366
44102
  if (existing) {
44367
44103
  const existingConfig = JSON.parse(existing);
44368
44104
  return Fireproof.fromConfig(name, existingConfig, opts)