@leofcoin/peernet 0.16.7 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,463 @@
1
+ import { K as KeyValue } from './value-40634404.js';
2
+
3
+ const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);
4
+
5
+ let idbProxyableTypes;
6
+ let cursorAdvanceMethods;
7
+ // This is a function to prevent it throwing up in node environments.
8
+ function getIdbProxyableTypes() {
9
+ return (idbProxyableTypes ||
10
+ (idbProxyableTypes = [
11
+ IDBDatabase,
12
+ IDBObjectStore,
13
+ IDBIndex,
14
+ IDBCursor,
15
+ IDBTransaction,
16
+ ]));
17
+ }
18
+ // This is a function to prevent it throwing up in node environments.
19
+ function getCursorAdvanceMethods() {
20
+ return (cursorAdvanceMethods ||
21
+ (cursorAdvanceMethods = [
22
+ IDBCursor.prototype.advance,
23
+ IDBCursor.prototype.continue,
24
+ IDBCursor.prototype.continuePrimaryKey,
25
+ ]));
26
+ }
27
+ const cursorRequestMap = new WeakMap();
28
+ const transactionDoneMap = new WeakMap();
29
+ const transactionStoreNamesMap = new WeakMap();
30
+ const transformCache = new WeakMap();
31
+ const reverseTransformCache = new WeakMap();
32
+ function promisifyRequest(request) {
33
+ const promise = new Promise((resolve, reject) => {
34
+ const unlisten = () => {
35
+ request.removeEventListener('success', success);
36
+ request.removeEventListener('error', error);
37
+ };
38
+ const success = () => {
39
+ resolve(wrap(request.result));
40
+ unlisten();
41
+ };
42
+ const error = () => {
43
+ reject(request.error);
44
+ unlisten();
45
+ };
46
+ request.addEventListener('success', success);
47
+ request.addEventListener('error', error);
48
+ });
49
+ promise
50
+ .then((value) => {
51
+ // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval
52
+ // (see wrapFunction).
53
+ if (value instanceof IDBCursor) {
54
+ cursorRequestMap.set(value, request);
55
+ }
56
+ // Catching to avoid "Uncaught Promise exceptions"
57
+ })
58
+ .catch(() => { });
59
+ // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This
60
+ // is because we create many promises from a single IDBRequest.
61
+ reverseTransformCache.set(promise, request);
62
+ return promise;
63
+ }
64
+ function cacheDonePromiseForTransaction(tx) {
65
+ // Early bail if we've already created a done promise for this transaction.
66
+ if (transactionDoneMap.has(tx))
67
+ return;
68
+ const done = new Promise((resolve, reject) => {
69
+ const unlisten = () => {
70
+ tx.removeEventListener('complete', complete);
71
+ tx.removeEventListener('error', error);
72
+ tx.removeEventListener('abort', error);
73
+ };
74
+ const complete = () => {
75
+ resolve();
76
+ unlisten();
77
+ };
78
+ const error = () => {
79
+ reject(tx.error || new DOMException('AbortError', 'AbortError'));
80
+ unlisten();
81
+ };
82
+ tx.addEventListener('complete', complete);
83
+ tx.addEventListener('error', error);
84
+ tx.addEventListener('abort', error);
85
+ });
86
+ // Cache it for later retrieval.
87
+ transactionDoneMap.set(tx, done);
88
+ }
89
+ let idbProxyTraps = {
90
+ get(target, prop, receiver) {
91
+ if (target instanceof IDBTransaction) {
92
+ // Special handling for transaction.done.
93
+ if (prop === 'done')
94
+ return transactionDoneMap.get(target);
95
+ // Polyfill for objectStoreNames because of Edge.
96
+ if (prop === 'objectStoreNames') {
97
+ return target.objectStoreNames || transactionStoreNamesMap.get(target);
98
+ }
99
+ // Make tx.store return the only store in the transaction, or undefined if there are many.
100
+ if (prop === 'store') {
101
+ return receiver.objectStoreNames[1]
102
+ ? undefined
103
+ : receiver.objectStore(receiver.objectStoreNames[0]);
104
+ }
105
+ }
106
+ // Else transform whatever we get back.
107
+ return wrap(target[prop]);
108
+ },
109
+ set(target, prop, value) {
110
+ target[prop] = value;
111
+ return true;
112
+ },
113
+ has(target, prop) {
114
+ if (target instanceof IDBTransaction &&
115
+ (prop === 'done' || prop === 'store')) {
116
+ return true;
117
+ }
118
+ return prop in target;
119
+ },
120
+ };
121
+ function replaceTraps(callback) {
122
+ idbProxyTraps = callback(idbProxyTraps);
123
+ }
124
+ function wrapFunction(func) {
125
+ // Due to expected object equality (which is enforced by the caching in `wrap`), we
126
+ // only create one new func per func.
127
+ // Edge doesn't support objectStoreNames (booo), so we polyfill it here.
128
+ if (func === IDBDatabase.prototype.transaction &&
129
+ !('objectStoreNames' in IDBTransaction.prototype)) {
130
+ return function (storeNames, ...args) {
131
+ const tx = func.call(unwrap(this), storeNames, ...args);
132
+ transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
133
+ return wrap(tx);
134
+ };
135
+ }
136
+ // Cursor methods are special, as the behaviour is a little more different to standard IDB. In
137
+ // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the
138
+ // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense
139
+ // with real promises, so each advance methods returns a new promise for the cursor object, or
140
+ // undefined if the end of the cursor has been reached.
141
+ if (getCursorAdvanceMethods().includes(func)) {
142
+ return function (...args) {
143
+ // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
144
+ // the original object.
145
+ func.apply(unwrap(this), args);
146
+ return wrap(cursorRequestMap.get(this));
147
+ };
148
+ }
149
+ return function (...args) {
150
+ // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
151
+ // the original object.
152
+ return wrap(func.apply(unwrap(this), args));
153
+ };
154
+ }
155
+ function transformCachableValue(value) {
156
+ if (typeof value === 'function')
157
+ return wrapFunction(value);
158
+ // This doesn't return, it just creates a 'done' promise for the transaction,
159
+ // which is later returned for transaction.done (see idbObjectHandler).
160
+ if (value instanceof IDBTransaction)
161
+ cacheDonePromiseForTransaction(value);
162
+ if (instanceOfAny(value, getIdbProxyableTypes()))
163
+ return new Proxy(value, idbProxyTraps);
164
+ // Return the same value back if we're not going to transform it.
165
+ return value;
166
+ }
167
+ function wrap(value) {
168
+ // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
169
+ // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.
170
+ if (value instanceof IDBRequest)
171
+ return promisifyRequest(value);
172
+ // If we've already transformed this value before, reuse the transformed value.
173
+ // This is faster, but it also provides object equality.
174
+ if (transformCache.has(value))
175
+ return transformCache.get(value);
176
+ const newValue = transformCachableValue(value);
177
+ // Not all types are transformed.
178
+ // These may be primitive types, so they can't be WeakMap keys.
179
+ if (newValue !== value) {
180
+ transformCache.set(value, newValue);
181
+ reverseTransformCache.set(newValue, value);
182
+ }
183
+ return newValue;
184
+ }
185
+ const unwrap = (value) => reverseTransformCache.get(value);
186
+
187
+ /**
188
+ * Open a database.
189
+ *
190
+ * @param name Name of the database.
191
+ * @param version Schema version.
192
+ * @param callbacks Additional callbacks.
193
+ */
194
+ function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {
195
+ const request = indexedDB.open(name, version);
196
+ const openPromise = wrap(request);
197
+ if (upgrade) {
198
+ request.addEventListener('upgradeneeded', (event) => {
199
+ upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);
200
+ });
201
+ }
202
+ if (blocked) {
203
+ request.addEventListener('blocked', (event) => blocked(
204
+ // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
205
+ event.oldVersion, event.newVersion, event));
206
+ }
207
+ openPromise
208
+ .then((db) => {
209
+ if (terminated)
210
+ db.addEventListener('close', () => terminated());
211
+ if (blocking) {
212
+ db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));
213
+ }
214
+ })
215
+ .catch(() => { });
216
+ return openPromise;
217
+ }
218
+
219
+ const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
220
+ const writeMethods = ['put', 'add', 'delete', 'clear'];
221
+ const cachedMethods = new Map();
222
+ function getMethod(target, prop) {
223
+ if (!(target instanceof IDBDatabase &&
224
+ !(prop in target) &&
225
+ typeof prop === 'string')) {
226
+ return;
227
+ }
228
+ if (cachedMethods.get(prop))
229
+ return cachedMethods.get(prop);
230
+ const targetFuncName = prop.replace(/FromIndex$/, '');
231
+ const useIndex = prop !== targetFuncName;
232
+ const isWrite = writeMethods.includes(targetFuncName);
233
+ if (
234
+ // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
235
+ !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||
236
+ !(isWrite || readMethods.includes(targetFuncName))) {
237
+ return;
238
+ }
239
+ const method = async function (storeName, ...args) {
240
+ // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(
241
+ const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
242
+ let target = tx.store;
243
+ if (useIndex)
244
+ target = target.index(args.shift());
245
+ // Must reject if op rejects.
246
+ // If it's a write operation, must reject if tx.done rejects.
247
+ // Must reject with op rejection first.
248
+ // Must resolve with op value.
249
+ // Must handle both promises (no unhandled rejections)
250
+ return (await Promise.all([
251
+ target[targetFuncName](...args),
252
+ isWrite && tx.done,
253
+ ]))[0];
254
+ };
255
+ cachedMethods.set(prop, method);
256
+ return method;
257
+ }
258
+ replaceTraps((oldTraps) => ({
259
+ ...oldTraps,
260
+ get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
261
+ has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),
262
+ }));
263
+
264
+ const advanceMethodProps = ['continue', 'continuePrimaryKey', 'advance'];
265
+ const methodMap = {};
266
+ const advanceResults = new WeakMap();
267
+ const ittrProxiedCursorToOriginalProxy = new WeakMap();
268
+ const cursorIteratorTraps = {
269
+ get(target, prop) {
270
+ if (!advanceMethodProps.includes(prop))
271
+ return target[prop];
272
+ let cachedFunc = methodMap[prop];
273
+ if (!cachedFunc) {
274
+ cachedFunc = methodMap[prop] = function (...args) {
275
+ advanceResults.set(this, ittrProxiedCursorToOriginalProxy.get(this)[prop](...args));
276
+ };
277
+ }
278
+ return cachedFunc;
279
+ },
280
+ };
281
+ async function* iterate(...args) {
282
+ // tslint:disable-next-line:no-this-assignment
283
+ let cursor = this;
284
+ if (!(cursor instanceof IDBCursor)) {
285
+ cursor = await cursor.openCursor(...args);
286
+ }
287
+ if (!cursor)
288
+ return;
289
+ cursor = cursor;
290
+ const proxiedCursor = new Proxy(cursor, cursorIteratorTraps);
291
+ ittrProxiedCursorToOriginalProxy.set(proxiedCursor, cursor);
292
+ // Map this double-proxy back to the original, so other cursor methods work.
293
+ reverseTransformCache.set(proxiedCursor, unwrap(cursor));
294
+ while (cursor) {
295
+ yield proxiedCursor;
296
+ // If one of the advancing methods was not called, call continue().
297
+ cursor = await (advanceResults.get(proxiedCursor) || cursor.continue());
298
+ advanceResults.delete(proxiedCursor);
299
+ }
300
+ }
301
+ function isIteratorProp(target, prop) {
302
+ return ((prop === Symbol.asyncIterator &&
303
+ instanceOfAny(target, [IDBIndex, IDBObjectStore, IDBCursor])) ||
304
+ (prop === 'iterate' && instanceOfAny(target, [IDBIndex, IDBObjectStore])));
305
+ }
306
+ replaceTraps((oldTraps) => ({
307
+ ...oldTraps,
308
+ get(target, prop, receiver) {
309
+ if (isIteratorProp(target, prop))
310
+ return iterate;
311
+ return oldTraps.get(target, prop, receiver);
312
+ },
313
+ has(target, prop) {
314
+ return isIteratorProp(target, prop) || oldTraps.has(target, prop);
315
+ },
316
+ }));
317
+
318
+ // import base32 from '@vandeurenglenn/base32'
319
+ // import base58 from '@vandeurenglenn/base58'
320
+
321
+ // export const encodings = {
322
+ // base58,
323
+ // base32
324
+ // }
325
+
326
+ const encode = (string, encoding = 'utf-8') => {
327
+ if (typeof string === 'string') {
328
+ let encoded;
329
+
330
+ // if (encodings[encoding]) encoded = encodings[encoding].encode(encoded)
331
+ encoded = new TextEncoder().encode(string);
332
+ return encoded
333
+ }
334
+ throw Error(`expected typeof String instead got ${string}`)
335
+ };
336
+
337
+ const decode = (uint8Array, encoding) => {
338
+ if (uint8Array instanceof Uint8Array) {
339
+ let decoded;
340
+ // if (encodings[encoding]) decoded = encodings[encoding].decode(decoded)
341
+ decoded = new TextDecoder().decode(uint8Array);
342
+
343
+ return decoded
344
+ }
345
+ throw Error(`expected typeof uint8Array instead got ${uint8Array}`)
346
+ };
347
+
348
+ const pathSepS = '/';
349
+ class KeyPath {
350
+
351
+ /**
352
+ * @param {string | Uint8Array} input
353
+ */
354
+ constructor(input) {
355
+ if (typeof input === 'string') {
356
+ this.uint8Array = encode(input);
357
+ } else if (input instanceof Uint8Array) {
358
+ this.uint8Array = input;
359
+ } else if (input instanceof KeyPath) {
360
+ this.uint8Array = input.uint8Array;
361
+ } else {
362
+ throw new Error('Invalid keyPath, should be a String, Uint8Array or KeyPath')
363
+ }
364
+ }
365
+
366
+ isKeyPath() {
367
+ return true
368
+ }
369
+
370
+ /**
371
+ * Convert to the string representation
372
+ *
373
+ * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.
374
+ * @returns {string}
375
+ */
376
+ toString(encoding = 'hex') {
377
+ return decode(this.uint8Array)
378
+ }
379
+
380
+ /**
381
+ * Returns the `list` representation of this path.
382
+ *
383
+ * @returns string[]
384
+ *
385
+ * @example
386
+ * ```js
387
+ * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()
388
+ * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']
389
+ * ```
390
+ */
391
+ list() {
392
+ return this.toString().split(pathSepS).slice(1)
393
+ }
394
+
395
+ }
396
+
397
+ class Store {
398
+ constructor(name = 'storage', root = '.leofcoin', version = 1) {
399
+ this.version = version;
400
+ this.name = name;
401
+ this.root = root;
402
+ this.db = openDB(`${root}/${name}`, version, {
403
+ upgrade(db) {
404
+ db.createObjectStore(name);
405
+ }
406
+ });
407
+ }
408
+
409
+ toKeyPath(key) {
410
+ if (!key.isKeyPath()) key = new KeyPath(key);
411
+ return key.toString('base32')
412
+ }
413
+
414
+ toKeyValue(value) {
415
+ if (!value.isKeyValue()) value = new KeyValue(value);
416
+ return value.uint8Array
417
+ }
418
+
419
+ async get(key) {
420
+ return (await this.db).get(this.name, this.toKeyPath(key))
421
+ }
422
+
423
+ async put(key, value) {
424
+ return (await this.db).put(this.name, this.toKeyValue(value), this.toKeyPath(key))
425
+ }
426
+
427
+ async delete(key) {
428
+ return (await this.db).delete(this.name, this.toKeyPath(key))
429
+ }
430
+
431
+ async clear() {
432
+ return (await this.db).clear(this.name)
433
+ }
434
+
435
+ async values(limit = -1) {
436
+ const values = [];
437
+ const tx = (await this.db).transaction(this.name);
438
+
439
+ for await (const cursor of tx.store) {
440
+ values.push(cursor.value);
441
+ if (limit && values.length === limit) return values
442
+ }
443
+ return values
444
+ }
445
+
446
+ async keys(limit = -1) {
447
+ const keys = [];
448
+ const tx = (await this.db).transaction(this.name);
449
+
450
+ for await (const cursor of tx.store) {
451
+ keys.push(cursor.key);
452
+ if (limit && keys.length === limit) return keys
453
+ }
454
+ return keys
455
+ }
456
+
457
+ async iterate() {
458
+ return (await this.db).transaction(this.name).store
459
+ }
460
+
461
+ }
462
+
463
+ export { Store as default };