@leofcoin/peernet 0.15.2 → 0.16.0

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,3725 +0,0 @@
1
- "use strict";
2
- (self["webpackChunk_leofcoin_peernet"] = self["webpackChunk_leofcoin_peernet"] || []).push([[851],{
3
-
4
- /***/ 110:
5
- /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
6
-
7
- __webpack_require__.r(__webpack_exports__);
8
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
9
- /* harmony export */ "default": function() { return /* binding */ LeofcoinStorage; }
10
- /* harmony export */ });
11
- /* harmony import */ var buffer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(764);
12
- /* harmony import */ var events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(187);
13
- /* harmony import */ var events__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(events__WEBPACK_IMPORTED_MODULE_1__);
14
- /* provided dependency */ var process = __webpack_require__(155);
15
-
16
-
17
-
18
- // import base32 from '@vandeurenglenn/base32'
19
- // import base58 from '@vandeurenglenn/base58'
20
-
21
- // export const encodings = {
22
- // base58,
23
- // base32
24
- // }
25
-
26
- const encode = (string, encoding = 'utf-8') => {
27
- if (typeof string === 'string') {
28
- let encoded;
29
-
30
- // if (encodings[encoding]) encoded = encodings[encoding].encode(encoded)
31
- encoded = new TextEncoder().encode(string);
32
- return encoded
33
- }
34
- throw Error(`expected typeof String instead got ${string}`)
35
- };
36
-
37
- const decode = (uint8Array, encoding) => {
38
- if (uint8Array instanceof Uint8Array) {
39
- let decoded;
40
- // if (encodings[encoding]) decoded = encodings[encoding].decode(decoded)
41
- decoded = new TextDecoder().decode(uint8Array);
42
-
43
- return decoded
44
- }
45
- throw Error(`expected typeof uint8Array instead got ${uint8Array}`)
46
- };
47
-
48
- const pathSepS = '/';
49
- class KeyPath {
50
-
51
- /**
52
- * @param {string | Uint8Array} input
53
- */
54
- constructor(input) {
55
- if (typeof input === 'string') {
56
- this.uint8Array = encode(input);
57
- } else if (input instanceof Uint8Array) {
58
- this.uint8Array = input;
59
- } else if (input instanceof KeyPath) {
60
- this.uint8Array = input.uint8Array;
61
- } else {
62
- throw new Error('Invalid keyPath, should be a String, Uint8Array or KeyPath')
63
- }
64
- }
65
-
66
- /**
67
- * Convert to the string representation
68
- *
69
- * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.
70
- * @returns {string}
71
- */
72
- toString (encoding = 'hex') {
73
- return decode(this.uint8Array)
74
- }
75
-
76
- /**
77
- * Returns the `list` representation of this path.
78
- *
79
- * @returns {Array<string>}
80
- *
81
- * @example
82
- * ```js
83
- * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()
84
- * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']
85
- * ```
86
- */
87
- list() {
88
- return this.toString().split(pathSepS).slice(1)
89
- }
90
-
91
- }
92
-
93
- class KeyValue {
94
-
95
- /**
96
- * @param {string | Uint8Array} input
97
- */
98
- constructor(input) {
99
- if (typeof input === 'string') {
100
- this.uint8Array = encode(input);
101
- } else if (input instanceof Uint8Array) {
102
- this.uint8Array = input;
103
- } else if (input instanceof KeyValue) {
104
- this.uint8Array = input.uint8Array;
105
- } else {
106
- throw new Error('Invalid KeyValue, should be a String, Uint8Array or KeyValue')
107
- }
108
- }
109
-
110
- /**
111
- * Convert to the string representation
112
- *
113
- * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.
114
- * @returns {string}
115
- */
116
- toString(encoding = 'utf8') {
117
- return decode(this.uint8Array)
118
- }
119
-
120
- }
121
-
122
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof self !== 'undefined' ? self : {};
123
-
124
- var abstractLevel$1 = {};
125
-
126
- var abstractLevel = {};
127
-
128
- var levelSupports = {};
129
-
130
- levelSupports.supports = function supports (...manifests) {
131
- const manifest = manifests.reduce((acc, m) => Object.assign(acc, m), {});
132
-
133
- return Object.assign(manifest, {
134
- snapshots: manifest.snapshots || false,
135
- permanence: manifest.permanence || false,
136
- seek: manifest.seek || false,
137
- clear: manifest.clear || false,
138
- getMany: manifest.getMany || false,
139
- keyIterator: manifest.keyIterator || false,
140
- valueIterator: manifest.valueIterator || false,
141
- iteratorNextv: manifest.iteratorNextv || false,
142
- iteratorAll: manifest.iteratorAll || false,
143
- status: manifest.status || false,
144
- createIfMissing: manifest.createIfMissing || false,
145
- errorIfExists: manifest.errorIfExists || false,
146
- deferredOpen: manifest.deferredOpen || false,
147
- promises: manifest.promises || false,
148
- streams: manifest.streams || false,
149
- encodings: Object.assign({}, manifest.encodings),
150
- events: Object.assign({}, manifest.events),
151
- additionalMethods: Object.assign({}, manifest.additionalMethods)
152
- })
153
- };
154
-
155
- var levelTranscoder = {};
156
-
157
- var moduleError = class ModuleError extends Error {
158
- /**
159
- * @param {string} message Error message
160
- * @param {{ code?: string, cause?: Error, expected?: boolean, transient?: boolean }} [options]
161
- */
162
- constructor (message, options) {
163
- super(message || '');
164
-
165
- if (typeof options === 'object' && options !== null) {
166
- if (options.code) this.code = String(options.code);
167
- if (options.expected) this.expected = true;
168
- if (options.transient) this.transient = true;
169
- if (options.cause) this.cause = options.cause;
170
- }
171
-
172
- if (Error.captureStackTrace) {
173
- Error.captureStackTrace(this, this.constructor);
174
- }
175
- }
176
- };
177
-
178
- var encodings$1 = {};
179
-
180
- /** @type {{ textEncoder: TextEncoder, textDecoder: TextDecoder }|null} */
181
- let lazy = null;
182
-
183
- /**
184
- * Get semi-global instances of TextEncoder and TextDecoder.
185
- * @returns {{ textEncoder: TextEncoder, textDecoder: TextDecoder }}
186
- */
187
- var textEndec$1 = function () {
188
- if (lazy === null) {
189
- lazy = {
190
- textEncoder: new TextEncoder(),
191
- textDecoder: new TextDecoder()
192
- };
193
- }
194
-
195
- return lazy
196
- };
197
-
198
- var formats$2 = {};
199
-
200
- var encoding = {};
201
-
202
- const ModuleError$8 = moduleError;
203
- const formats$1 = new Set(['buffer', 'view', 'utf8']);
204
-
205
- /**
206
- * @template TIn, TFormat, TOut
207
- * @abstract
208
- */
209
- class Encoding$2 {
210
- /**
211
- * @param {IEncoding<TIn,TFormat,TOut>} options
212
- */
213
- constructor (options) {
214
- /** @type {(data: TIn) => TFormat} */
215
- this.encode = options.encode || this.encode;
216
-
217
- /** @type {(data: TFormat) => TOut} */
218
- this.decode = options.decode || this.decode;
219
-
220
- /** @type {string} */
221
- this.name = options.name || this.name;
222
-
223
- /** @type {string} */
224
- this.format = options.format || this.format;
225
-
226
- if (typeof this.encode !== 'function') {
227
- throw new TypeError("The 'encode' property must be a function")
228
- }
229
-
230
- if (typeof this.decode !== 'function') {
231
- throw new TypeError("The 'decode' property must be a function")
232
- }
233
-
234
- this.encode = this.encode.bind(this);
235
- this.decode = this.decode.bind(this);
236
-
237
- if (typeof this.name !== 'string' || this.name === '') {
238
- throw new TypeError("The 'name' property must be a string")
239
- }
240
-
241
- if (typeof this.format !== 'string' || !formats$1.has(this.format)) {
242
- throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'")
243
- }
244
-
245
- if (options.createViewTranscoder) {
246
- this.createViewTranscoder = options.createViewTranscoder;
247
- }
248
-
249
- if (options.createBufferTranscoder) {
250
- this.createBufferTranscoder = options.createBufferTranscoder;
251
- }
252
-
253
- if (options.createUTF8Transcoder) {
254
- this.createUTF8Transcoder = options.createUTF8Transcoder;
255
- }
256
- }
257
-
258
- get commonName () {
259
- return /** @type {string} */ (this.name.split('+')[0])
260
- }
261
-
262
- /** @return {BufferFormat<TIn,TOut>} */
263
- createBufferTranscoder () {
264
- throw new ModuleError$8(`Encoding '${this.name}' cannot be transcoded to 'buffer'`, {
265
- code: 'LEVEL_ENCODING_NOT_SUPPORTED'
266
- })
267
- }
268
-
269
- /** @return {ViewFormat<TIn,TOut>} */
270
- createViewTranscoder () {
271
- throw new ModuleError$8(`Encoding '${this.name}' cannot be transcoded to 'view'`, {
272
- code: 'LEVEL_ENCODING_NOT_SUPPORTED'
273
- })
274
- }
275
-
276
- /** @return {UTF8Format<TIn,TOut>} */
277
- createUTF8Transcoder () {
278
- throw new ModuleError$8(`Encoding '${this.name}' cannot be transcoded to 'utf8'`, {
279
- code: 'LEVEL_ENCODING_NOT_SUPPORTED'
280
- })
281
- }
282
- }
283
-
284
- encoding.Encoding = Encoding$2;
285
-
286
- const { Buffer: Buffer$1 } = buffer__WEBPACK_IMPORTED_MODULE_0__ || {};
287
- const { Encoding: Encoding$1 } = encoding;
288
- const textEndec = textEndec$1;
289
-
290
- /**
291
- * @template TIn, TOut
292
- * @extends {Encoding<TIn,Buffer,TOut>}
293
- */
294
- class BufferFormat$2 extends Encoding$1 {
295
- /**
296
- * @param {Omit<IEncoding<TIn, Buffer, TOut>, 'format'>} options
297
- */
298
- constructor (options) {
299
- super({ ...options, format: 'buffer' });
300
- }
301
-
302
- /** @override */
303
- createViewTranscoder () {
304
- return new ViewFormat$2({
305
- encode: this.encode, // Buffer is a view (UInt8Array)
306
- decode: (data) => this.decode(
307
- Buffer$1.from(data.buffer, data.byteOffset, data.byteLength)
308
- ),
309
- name: `${this.name}+view`
310
- })
311
- }
312
-
313
- /** @override */
314
- createBufferTranscoder () {
315
- return this
316
- }
317
- }
318
-
319
- /**
320
- * @extends {Encoding<TIn,Uint8Array,TOut>}
321
- * @template TIn, TOut
322
- */
323
- class ViewFormat$2 extends Encoding$1 {
324
- /**
325
- * @param {Omit<IEncoding<TIn, Uint8Array, TOut>, 'format'>} options
326
- */
327
- constructor (options) {
328
- super({ ...options, format: 'view' });
329
- }
330
-
331
- /** @override */
332
- createBufferTranscoder () {
333
- return new BufferFormat$2({
334
- encode: (data) => {
335
- const view = this.encode(data);
336
- return Buffer$1.from(view.buffer, view.byteOffset, view.byteLength)
337
- },
338
- decode: this.decode, // Buffer is a view (UInt8Array)
339
- name: `${this.name}+buffer`
340
- })
341
- }
342
-
343
- /** @override */
344
- createViewTranscoder () {
345
- return this
346
- }
347
- }
348
-
349
- /**
350
- * @extends {Encoding<TIn,string,TOut>}
351
- * @template TIn, TOut
352
- */
353
- class UTF8Format$2 extends Encoding$1 {
354
- /**
355
- * @param {Omit<IEncoding<TIn, string, TOut>, 'format'>} options
356
- */
357
- constructor (options) {
358
- super({ ...options, format: 'utf8' });
359
- }
360
-
361
- /** @override */
362
- createBufferTranscoder () {
363
- return new BufferFormat$2({
364
- encode: (data) => Buffer$1.from(this.encode(data), 'utf8'),
365
- decode: (data) => this.decode(data.toString('utf8')),
366
- name: `${this.name}+buffer`
367
- })
368
- }
369
-
370
- /** @override */
371
- createViewTranscoder () {
372
- const { textEncoder, textDecoder } = textEndec();
373
-
374
- return new ViewFormat$2({
375
- encode: (data) => textEncoder.encode(this.encode(data)),
376
- decode: (data) => this.decode(textDecoder.decode(data)),
377
- name: `${this.name}+view`
378
- })
379
- }
380
-
381
- /** @override */
382
- createUTF8Transcoder () {
383
- return this
384
- }
385
- }
386
-
387
- formats$2.BufferFormat = BufferFormat$2;
388
- formats$2.ViewFormat = ViewFormat$2;
389
- formats$2.UTF8Format = UTF8Format$2;
390
-
391
- const { Buffer } = buffer__WEBPACK_IMPORTED_MODULE_0__ || { Buffer: { isBuffer: () => false } };
392
- const { textEncoder: textEncoder$1, textDecoder } = textEndec$1();
393
- const { BufferFormat: BufferFormat$1, ViewFormat: ViewFormat$1, UTF8Format: UTF8Format$1 } = formats$2;
394
-
395
- /** @type {<T>(v: T) => v} */
396
- const identity = (v) => v;
397
-
398
- /**
399
- * @type {typeof import('./encodings').utf8}
400
- */
401
- encodings$1.utf8 = new UTF8Format$1({
402
- encode: function (data) {
403
- // On node 16.9.1 buffer.toString() is 5x faster than TextDecoder
404
- return Buffer.isBuffer(data)
405
- ? data.toString('utf8')
406
- : ArrayBuffer.isView(data)
407
- ? textDecoder.decode(data)
408
- : String(data)
409
- },
410
- decode: identity,
411
- name: 'utf8',
412
- createViewTranscoder () {
413
- return new ViewFormat$1({
414
- encode: function (data) {
415
- return ArrayBuffer.isView(data) ? data : textEncoder$1.encode(data)
416
- },
417
- decode: function (data) {
418
- return textDecoder.decode(data)
419
- },
420
- name: `${this.name}+view`
421
- })
422
- },
423
- createBufferTranscoder () {
424
- return new BufferFormat$1({
425
- encode: function (data) {
426
- return Buffer.isBuffer(data)
427
- ? data
428
- : ArrayBuffer.isView(data)
429
- ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
430
- : Buffer.from(String(data), 'utf8')
431
- },
432
- decode: function (data) {
433
- return data.toString('utf8')
434
- },
435
- name: `${this.name}+buffer`
436
- })
437
- }
438
- });
439
-
440
- /**
441
- * @type {typeof import('./encodings').json}
442
- */
443
- encodings$1.json = new UTF8Format$1({
444
- encode: JSON.stringify,
445
- decode: JSON.parse,
446
- name: 'json'
447
- });
448
-
449
- /**
450
- * @type {typeof import('./encodings').buffer}
451
- */
452
- encodings$1.buffer = new BufferFormat$1({
453
- encode: function (data) {
454
- return Buffer.isBuffer(data)
455
- ? data
456
- : ArrayBuffer.isView(data)
457
- ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
458
- : Buffer.from(String(data), 'utf8')
459
- },
460
- decode: identity,
461
- name: 'buffer',
462
- createViewTranscoder () {
463
- return new ViewFormat$1({
464
- encode: function (data) {
465
- return ArrayBuffer.isView(data) ? data : Buffer.from(String(data), 'utf8')
466
- },
467
- decode: function (data) {
468
- return Buffer.from(data.buffer, data.byteOffset, data.byteLength)
469
- },
470
- name: `${this.name}+view`
471
- })
472
- }
473
- });
474
-
475
- /**
476
- * @type {typeof import('./encodings').view}
477
- */
478
- encodings$1.view = new ViewFormat$1({
479
- encode: function (data) {
480
- return ArrayBuffer.isView(data) ? data : textEncoder$1.encode(data)
481
- },
482
- decode: identity,
483
- name: 'view',
484
- createBufferTranscoder () {
485
- return new BufferFormat$1({
486
- encode: function (data) {
487
- return Buffer.isBuffer(data)
488
- ? data
489
- : ArrayBuffer.isView(data)
490
- ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
491
- : Buffer.from(String(data), 'utf8')
492
- },
493
- decode: identity,
494
- name: `${this.name}+buffer`
495
- })
496
- }
497
- });
498
-
499
- /**
500
- * @type {typeof import('./encodings').hex}
501
- */
502
- encodings$1.hex = new BufferFormat$1({
503
- encode: function (data) {
504
- return Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'hex')
505
- },
506
- decode: function (buffer) {
507
- return buffer.toString('hex')
508
- },
509
- name: 'hex'
510
- });
511
-
512
- /**
513
- * @type {typeof import('./encodings').base64}
514
- */
515
- encodings$1.base64 = new BufferFormat$1({
516
- encode: function (data) {
517
- return Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'base64')
518
- },
519
- decode: function (buffer) {
520
- return buffer.toString('base64')
521
- },
522
- name: 'base64'
523
- });
524
-
525
- const ModuleError$7 = moduleError;
526
- const encodings = encodings$1;
527
- const { Encoding } = encoding;
528
- const { BufferFormat, ViewFormat, UTF8Format } = formats$2;
529
-
530
- const kFormats = Symbol('formats');
531
- const kEncodings = Symbol('encodings');
532
- const validFormats = new Set(['buffer', 'view', 'utf8']);
533
-
534
- /** @template T */
535
- class Transcoder$1 {
536
- /**
537
- * @param {Array<'buffer'|'view'|'utf8'>} formats
538
- */
539
- constructor (formats) {
540
- if (!Array.isArray(formats)) {
541
- throw new TypeError("The first argument 'formats' must be an array")
542
- } else if (!formats.every(f => validFormats.has(f))) {
543
- // Note: we only only support aliases in key- and valueEncoding options (where we already did)
544
- throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")
545
- }
546
-
547
- /** @type {Map<string|MixedEncoding<any, any, any>, Encoding<any, any, any>>} */
548
- this[kEncodings] = new Map();
549
- this[kFormats] = new Set(formats);
550
-
551
- // Register encodings (done early in order to populate encodings())
552
- for (const k in encodings) {
553
- try {
554
- this.encoding(k);
555
- } catch (err) {
556
- /* istanbul ignore if: assertion */
557
- if (err.code !== 'LEVEL_ENCODING_NOT_SUPPORTED') throw err
558
- }
559
- }
560
- }
561
-
562
- /**
563
- * @returns {Array<Encoding<any,T,any>>}
564
- */
565
- encodings () {
566
- return Array.from(new Set(this[kEncodings].values()))
567
- }
568
-
569
- /**
570
- * @param {string|MixedEncoding<any, any, any>} encoding
571
- * @returns {Encoding<any, T, any>}
572
- */
573
- encoding (encoding) {
574
- let resolved = this[kEncodings].get(encoding);
575
-
576
- if (resolved === undefined) {
577
- if (typeof encoding === 'string' && encoding !== '') {
578
- resolved = lookup[encoding];
579
-
580
- if (!resolved) {
581
- throw new ModuleError$7(`Encoding '${encoding}' is not found`, {
582
- code: 'LEVEL_ENCODING_NOT_FOUND'
583
- })
584
- }
585
- } else if (typeof encoding !== 'object' || encoding === null) {
586
- throw new TypeError("First argument 'encoding' must be a string or object")
587
- } else {
588
- resolved = from(encoding);
589
- }
590
-
591
- const { name, format } = resolved;
592
-
593
- if (!this[kFormats].has(format)) {
594
- if (this[kFormats].has('view')) {
595
- resolved = resolved.createViewTranscoder();
596
- } else if (this[kFormats].has('buffer')) {
597
- resolved = resolved.createBufferTranscoder();
598
- } else if (this[kFormats].has('utf8')) {
599
- resolved = resolved.createUTF8Transcoder();
600
- } else {
601
- throw new ModuleError$7(`Encoding '${name}' cannot be transcoded`, {
602
- code: 'LEVEL_ENCODING_NOT_SUPPORTED'
603
- })
604
- }
605
- }
606
-
607
- for (const k of [encoding, name, resolved.name, resolved.commonName]) {
608
- this[kEncodings].set(k, resolved);
609
- }
610
- }
611
-
612
- return resolved
613
- }
614
- }
615
-
616
- levelTranscoder.Transcoder = Transcoder$1;
617
-
618
- /**
619
- * @param {MixedEncoding<any, any, any>} options
620
- * @returns {Encoding<any, any, any>}
621
- */
622
- function from (options) {
623
- if (options instanceof Encoding) {
624
- return options
625
- }
626
-
627
- // Loosely typed for ecosystem compatibility
628
- const maybeType = 'type' in options && typeof options.type === 'string' ? options.type : undefined;
629
- const name = options.name || maybeType || `anonymous-${anonymousCount++}`;
630
-
631
- switch (detectFormat(options)) {
632
- case 'view': return new ViewFormat({ ...options, name })
633
- case 'utf8': return new UTF8Format({ ...options, name })
634
- case 'buffer': return new BufferFormat({ ...options, name })
635
- default: {
636
- throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")
637
- }
638
- }
639
- }
640
-
641
- /**
642
- * If format is not provided, fallback to detecting `level-codec`
643
- * or `multiformats` encodings, else assume a format of buffer.
644
- * @param {MixedEncoding<any, any, any>} options
645
- * @returns {string}
646
- */
647
- function detectFormat (options) {
648
- if ('format' in options && options.format !== undefined) {
649
- return options.format
650
- } else if ('buffer' in options && typeof options.buffer === 'boolean') {
651
- return options.buffer ? 'buffer' : 'utf8' // level-codec
652
- } else if ('code' in options && Number.isInteger(options.code)) {
653
- return 'view' // multiformats
654
- } else {
655
- return 'buffer'
656
- }
657
- }
658
-
659
- /**
660
- * @typedef {import('./lib/encoding').MixedEncoding<TIn,TFormat,TOut>} MixedEncoding
661
- * @template TIn, TFormat, TOut
662
- */
663
-
664
- /**
665
- * @type {Object.<string, Encoding<any, any, any>>}
666
- */
667
- const aliases = {
668
- binary: encodings.buffer,
669
- 'utf-8': encodings.utf8
670
- };
671
-
672
- /**
673
- * @type {Object.<string, Encoding<any, any, any>>}
674
- */
675
- const lookup = {
676
- ...encodings,
677
- ...aliases
678
- };
679
-
680
- let anonymousCount = 0;
681
-
682
- var catering = {};
683
-
684
- var nextTick$2 = process.nextTick.bind(process);
685
-
686
- var nextTick$1 = nextTick$2;
687
-
688
- catering.fromCallback = function (callback, symbol) {
689
- if (callback === undefined) {
690
- var promise = new Promise(function (resolve, reject) {
691
- callback = function (err, res) {
692
- if (err) reject(err);
693
- else resolve(res);
694
- };
695
- });
696
-
697
- callback[symbol !== undefined ? symbol : 'promise'] = promise;
698
- } else if (typeof callback !== 'function') {
699
- throw new TypeError('Callback must be a function')
700
- }
701
-
702
- return callback
703
- };
704
-
705
- catering.fromPromise = function (promise, callback) {
706
- if (callback === undefined) return promise
707
-
708
- promise
709
- .then(function (res) { nextTick$1(() => callback(null, res)); })
710
- .catch(function (err) { nextTick$1(() => callback(err)); });
711
- };
712
-
713
- var abstractIterator = {};
714
-
715
- var common = {};
716
-
717
- common.getCallback = function (options, callback) {
718
- return typeof options === 'function' ? options : callback
719
- };
720
-
721
- common.getOptions = function (options, def) {
722
- if (typeof options === 'object' && options !== null) {
723
- return options
724
- }
725
-
726
- if (def !== undefined) {
727
- return def
728
- }
729
-
730
- return {}
731
- };
732
-
733
- const { fromCallback: fromCallback$3 } = catering;
734
- const ModuleError$6 = moduleError;
735
- const { getOptions: getOptions$2, getCallback: getCallback$2 } = common;
736
-
737
- const kPromise$3 = Symbol('promise');
738
- const kCallback$1 = Symbol('callback');
739
- const kWorking = Symbol('working');
740
- const kHandleOne$1 = Symbol('handleOne');
741
- const kHandleMany$1 = Symbol('handleMany');
742
- const kAutoClose = Symbol('autoClose');
743
- const kFinishWork = Symbol('finishWork');
744
- const kReturnMany = Symbol('returnMany');
745
- const kClosing = Symbol('closing');
746
- const kHandleClose = Symbol('handleClose');
747
- const kClosed = Symbol('closed');
748
- const kCloseCallbacks$1 = Symbol('closeCallbacks');
749
- const kKeyEncoding$1 = Symbol('keyEncoding');
750
- const kValueEncoding$1 = Symbol('valueEncoding');
751
- const kAbortOnClose = Symbol('abortOnClose');
752
- const kLegacy = Symbol('legacy');
753
- const kKeys = Symbol('keys');
754
- const kValues = Symbol('values');
755
- const kLimit = Symbol('limit');
756
- const kCount = Symbol('count');
757
-
758
- const emptyOptions$1 = Object.freeze({});
759
- const noop$1 = () => {};
760
- let warnedEnd = false;
761
-
762
- // This class is an internal utility for common functionality between AbstractIterator,
763
- // AbstractKeyIterator and AbstractValueIterator. It's not exported.
764
- class CommonIterator {
765
- constructor (db, options, legacy) {
766
- if (typeof db !== 'object' || db === null) {
767
- const hint = db === null ? 'null' : typeof db;
768
- throw new TypeError(`The first argument must be an abstract-level database, received ${hint}`)
769
- }
770
-
771
- if (typeof options !== 'object' || options === null) {
772
- throw new TypeError('The second argument must be an options object')
773
- }
774
-
775
- this[kClosed] = false;
776
- this[kCloseCallbacks$1] = [];
777
- this[kWorking] = false;
778
- this[kClosing] = false;
779
- this[kAutoClose] = false;
780
- this[kCallback$1] = null;
781
- this[kHandleOne$1] = this[kHandleOne$1].bind(this);
782
- this[kHandleMany$1] = this[kHandleMany$1].bind(this);
783
- this[kHandleClose] = this[kHandleClose].bind(this);
784
- this[kKeyEncoding$1] = options[kKeyEncoding$1];
785
- this[kValueEncoding$1] = options[kValueEncoding$1];
786
- this[kLegacy] = legacy;
787
- this[kLimit] = Number.isInteger(options.limit) && options.limit >= 0 ? options.limit : Infinity;
788
- this[kCount] = 0;
789
-
790
- // Undocumented option to abort pending work on close(). Used by the
791
- // many-level module as a temporary solution to a blocked close().
792
- // TODO (next major): consider making this the default behavior. Native
793
- // implementations should have their own logic to safely close iterators.
794
- this[kAbortOnClose] = !!options.abortOnClose;
795
-
796
- this.db = db;
797
- this.db.attachResource(this);
798
- this.nextTick = db.nextTick;
799
- }
800
-
801
- get count () {
802
- return this[kCount]
803
- }
804
-
805
- get limit () {
806
- return this[kLimit]
807
- }
808
-
809
- next (callback) {
810
- let promise;
811
-
812
- if (callback === undefined) {
813
- promise = new Promise((resolve, reject) => {
814
- callback = (err, key, value) => {
815
- if (err) reject(err);
816
- else if (!this[kLegacy]) resolve(key);
817
- else if (key === undefined && value === undefined) resolve();
818
- else resolve([key, value]);
819
- };
820
- });
821
- } else if (typeof callback !== 'function') {
822
- throw new TypeError('Callback must be a function')
823
- }
824
-
825
- if (this[kClosing]) {
826
- this.nextTick(callback, new ModuleError$6('Iterator is not open: cannot call next() after close()', {
827
- code: 'LEVEL_ITERATOR_NOT_OPEN'
828
- }));
829
- } else if (this[kWorking]) {
830
- this.nextTick(callback, new ModuleError$6('Iterator is busy: cannot call next() until previous call has completed', {
831
- code: 'LEVEL_ITERATOR_BUSY'
832
- }));
833
- } else {
834
- this[kWorking] = true;
835
- this[kCallback$1] = callback;
836
-
837
- if (this[kCount] >= this[kLimit]) this.nextTick(this[kHandleOne$1], null);
838
- else this._next(this[kHandleOne$1]);
839
- }
840
-
841
- return promise
842
- }
843
-
844
- _next (callback) {
845
- this.nextTick(callback);
846
- }
847
-
848
- nextv (size, options, callback) {
849
- callback = getCallback$2(options, callback);
850
- callback = fromCallback$3(callback, kPromise$3);
851
- options = getOptions$2(options, emptyOptions$1);
852
-
853
- if (!Number.isInteger(size)) {
854
- this.nextTick(callback, new TypeError("The first argument 'size' must be an integer"));
855
- return callback[kPromise$3]
856
- }
857
-
858
- if (this[kClosing]) {
859
- this.nextTick(callback, new ModuleError$6('Iterator is not open: cannot call nextv() after close()', {
860
- code: 'LEVEL_ITERATOR_NOT_OPEN'
861
- }));
862
- } else if (this[kWorking]) {
863
- this.nextTick(callback, new ModuleError$6('Iterator is busy: cannot call nextv() until previous call has completed', {
864
- code: 'LEVEL_ITERATOR_BUSY'
865
- }));
866
- } else {
867
- if (size < 1) size = 1;
868
- if (this[kLimit] < Infinity) size = Math.min(size, this[kLimit] - this[kCount]);
869
-
870
- this[kWorking] = true;
871
- this[kCallback$1] = callback;
872
-
873
- if (size <= 0) this.nextTick(this[kHandleMany$1], null, []);
874
- else this._nextv(size, options, this[kHandleMany$1]);
875
- }
876
-
877
- return callback[kPromise$3]
878
- }
879
-
880
- _nextv (size, options, callback) {
881
- const acc = [];
882
- const onnext = (err, key, value) => {
883
- if (err) {
884
- return callback(err)
885
- } else if (this[kLegacy] ? key === undefined && value === undefined : key === undefined) {
886
- return callback(null, acc)
887
- }
888
-
889
- acc.push(this[kLegacy] ? [key, value] : key);
890
-
891
- if (acc.length === size) {
892
- callback(null, acc);
893
- } else {
894
- this._next(onnext);
895
- }
896
- };
897
-
898
- this._next(onnext);
899
- }
900
-
901
- all (options, callback) {
902
- callback = getCallback$2(options, callback);
903
- callback = fromCallback$3(callback, kPromise$3);
904
- options = getOptions$2(options, emptyOptions$1);
905
-
906
- if (this[kClosing]) {
907
- this.nextTick(callback, new ModuleError$6('Iterator is not open: cannot call all() after close()', {
908
- code: 'LEVEL_ITERATOR_NOT_OPEN'
909
- }));
910
- } else if (this[kWorking]) {
911
- this.nextTick(callback, new ModuleError$6('Iterator is busy: cannot call all() until previous call has completed', {
912
- code: 'LEVEL_ITERATOR_BUSY'
913
- }));
914
- } else {
915
- this[kWorking] = true;
916
- this[kCallback$1] = callback;
917
- this[kAutoClose] = true;
918
-
919
- if (this[kCount] >= this[kLimit]) this.nextTick(this[kHandleMany$1], null, []);
920
- else this._all(options, this[kHandleMany$1]);
921
- }
922
-
923
- return callback[kPromise$3]
924
- }
925
-
926
- _all (options, callback) {
927
- // Must count here because we're directly calling _nextv()
928
- let count = this[kCount];
929
- const acc = [];
930
-
931
- const nextv = () => {
932
- // Not configurable, because implementations should optimize _all().
933
- const size = this[kLimit] < Infinity ? Math.min(1e3, this[kLimit] - count) : 1e3;
934
-
935
- if (size <= 0) {
936
- this.nextTick(callback, null, acc);
937
- } else {
938
- this._nextv(size, emptyOptions$1, onnextv);
939
- }
940
- };
941
-
942
- const onnextv = (err, items) => {
943
- if (err) {
944
- callback(err);
945
- } else if (items.length === 0) {
946
- callback(null, acc);
947
- } else {
948
- acc.push.apply(acc, items);
949
- count += items.length;
950
- nextv();
951
- }
952
- };
953
-
954
- nextv();
955
- }
956
-
957
- [kFinishWork] () {
958
- const cb = this[kCallback$1];
959
-
960
- // Callback will be null if work was aborted on close
961
- if (this[kAbortOnClose] && cb === null) return noop$1
962
-
963
- this[kWorking] = false;
964
- this[kCallback$1] = null;
965
-
966
- if (this[kClosing]) this._close(this[kHandleClose]);
967
-
968
- return cb
969
- }
970
-
971
- [kReturnMany] (cb, err, items) {
972
- if (this[kAutoClose]) {
973
- this.close(cb.bind(null, err, items));
974
- } else {
975
- cb(err, items);
976
- }
977
- }
978
-
979
- seek (target, options) {
980
- options = getOptions$2(options, emptyOptions$1);
981
-
982
- if (this[kClosing]) ; else if (this[kWorking]) {
983
- throw new ModuleError$6('Iterator is busy: cannot call seek() until next() has completed', {
984
- code: 'LEVEL_ITERATOR_BUSY'
985
- })
986
- } else {
987
- const keyEncoding = this.db.keyEncoding(options.keyEncoding || this[kKeyEncoding$1]);
988
- const keyFormat = keyEncoding.format;
989
-
990
- if (options.keyEncoding !== keyFormat) {
991
- options = { ...options, keyEncoding: keyFormat };
992
- }
993
-
994
- const mapped = this.db.prefixKey(keyEncoding.encode(target), keyFormat);
995
- this._seek(mapped, options);
996
- }
997
- }
998
-
999
- _seek (target, options) {
1000
- throw new ModuleError$6('Iterator does not support seek()', {
1001
- code: 'LEVEL_NOT_SUPPORTED'
1002
- })
1003
- }
1004
-
1005
- close (callback) {
1006
- callback = fromCallback$3(callback, kPromise$3);
1007
-
1008
- if (this[kClosed]) {
1009
- this.nextTick(callback);
1010
- } else if (this[kClosing]) {
1011
- this[kCloseCallbacks$1].push(callback);
1012
- } else {
1013
- this[kClosing] = true;
1014
- this[kCloseCallbacks$1].push(callback);
1015
-
1016
- if (!this[kWorking]) {
1017
- this._close(this[kHandleClose]);
1018
- } else if (this[kAbortOnClose]) {
1019
- // Don't wait for work to finish. Subsequently ignore the result.
1020
- const cb = this[kFinishWork]();
1021
-
1022
- cb(new ModuleError$6('Aborted on iterator close()', {
1023
- code: 'LEVEL_ITERATOR_NOT_OPEN'
1024
- }));
1025
- }
1026
- }
1027
-
1028
- return callback[kPromise$3]
1029
- }
1030
-
1031
- _close (callback) {
1032
- this.nextTick(callback);
1033
- }
1034
-
1035
- [kHandleClose] () {
1036
- this[kClosed] = true;
1037
- this.db.detachResource(this);
1038
-
1039
- const callbacks = this[kCloseCallbacks$1];
1040
- this[kCloseCallbacks$1] = [];
1041
-
1042
- for (const cb of callbacks) {
1043
- cb();
1044
- }
1045
- }
1046
-
1047
- async * [Symbol.asyncIterator] () {
1048
- try {
1049
- let item;
1050
-
1051
- while ((item = (await this.next())) !== undefined) {
1052
- yield item;
1053
- }
1054
- } finally {
1055
- if (!this[kClosed]) await this.close();
1056
- }
1057
- }
1058
- }
1059
-
1060
- // For backwards compatibility this class is not (yet) called AbstractEntryIterator.
1061
- class AbstractIterator$3 extends CommonIterator {
1062
- constructor (db, options) {
1063
- super(db, options, true);
1064
- this[kKeys] = options.keys !== false;
1065
- this[kValues] = options.values !== false;
1066
- }
1067
-
1068
- [kHandleOne$1] (err, key, value) {
1069
- const cb = this[kFinishWork]();
1070
- if (err) return cb(err)
1071
-
1072
- try {
1073
- key = this[kKeys] && key !== undefined ? this[kKeyEncoding$1].decode(key) : undefined;
1074
- value = this[kValues] && value !== undefined ? this[kValueEncoding$1].decode(value) : undefined;
1075
- } catch (err) {
1076
- return cb(new IteratorDecodeError('entry', err))
1077
- }
1078
-
1079
- if (!(key === undefined && value === undefined)) {
1080
- this[kCount]++;
1081
- }
1082
-
1083
- cb(null, key, value);
1084
- }
1085
-
1086
- [kHandleMany$1] (err, entries) {
1087
- const cb = this[kFinishWork]();
1088
- if (err) return this[kReturnMany](cb, err)
1089
-
1090
- try {
1091
- for (const entry of entries) {
1092
- const key = entry[0];
1093
- const value = entry[1];
1094
-
1095
- entry[0] = this[kKeys] && key !== undefined ? this[kKeyEncoding$1].decode(key) : undefined;
1096
- entry[1] = this[kValues] && value !== undefined ? this[kValueEncoding$1].decode(value) : undefined;
1097
- }
1098
- } catch (err) {
1099
- return this[kReturnMany](cb, new IteratorDecodeError('entries', err))
1100
- }
1101
-
1102
- this[kCount] += entries.length;
1103
- this[kReturnMany](cb, null, entries);
1104
- }
1105
-
1106
- end (callback) {
1107
- if (!warnedEnd && typeof console !== 'undefined') {
1108
- warnedEnd = true;
1109
- console.warn(new ModuleError$6(
1110
- 'The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version',
1111
- { code: 'LEVEL_LEGACY' }
1112
- ));
1113
- }
1114
-
1115
- return this.close(callback)
1116
- }
1117
- }
1118
-
1119
- class AbstractKeyIterator$2 extends CommonIterator {
1120
- constructor (db, options) {
1121
- super(db, options, false);
1122
- }
1123
-
1124
- [kHandleOne$1] (err, key) {
1125
- const cb = this[kFinishWork]();
1126
- if (err) return cb(err)
1127
-
1128
- try {
1129
- key = key !== undefined ? this[kKeyEncoding$1].decode(key) : undefined;
1130
- } catch (err) {
1131
- return cb(new IteratorDecodeError('key', err))
1132
- }
1133
-
1134
- if (key !== undefined) this[kCount]++;
1135
- cb(null, key);
1136
- }
1137
-
1138
- [kHandleMany$1] (err, keys) {
1139
- const cb = this[kFinishWork]();
1140
- if (err) return this[kReturnMany](cb, err)
1141
-
1142
- try {
1143
- for (let i = 0; i < keys.length; i++) {
1144
- const key = keys[i];
1145
- keys[i] = key !== undefined ? this[kKeyEncoding$1].decode(key) : undefined;
1146
- }
1147
- } catch (err) {
1148
- return this[kReturnMany](cb, new IteratorDecodeError('keys', err))
1149
- }
1150
-
1151
- this[kCount] += keys.length;
1152
- this[kReturnMany](cb, null, keys);
1153
- }
1154
- }
1155
-
1156
- class AbstractValueIterator$2 extends CommonIterator {
1157
- constructor (db, options) {
1158
- super(db, options, false);
1159
- }
1160
-
1161
- [kHandleOne$1] (err, value) {
1162
- const cb = this[kFinishWork]();
1163
- if (err) return cb(err)
1164
-
1165
- try {
1166
- value = value !== undefined ? this[kValueEncoding$1].decode(value) : undefined;
1167
- } catch (err) {
1168
- return cb(new IteratorDecodeError('value', err))
1169
- }
1170
-
1171
- if (value !== undefined) this[kCount]++;
1172
- cb(null, value);
1173
- }
1174
-
1175
- [kHandleMany$1] (err, values) {
1176
- const cb = this[kFinishWork]();
1177
- if (err) return this[kReturnMany](cb, err)
1178
-
1179
- try {
1180
- for (let i = 0; i < values.length; i++) {
1181
- const value = values[i];
1182
- values[i] = value !== undefined ? this[kValueEncoding$1].decode(value) : undefined;
1183
- }
1184
- } catch (err) {
1185
- return this[kReturnMany](cb, new IteratorDecodeError('values', err))
1186
- }
1187
-
1188
- this[kCount] += values.length;
1189
- this[kReturnMany](cb, null, values);
1190
- }
1191
- }
1192
-
1193
- // Internal utility, not typed or exported
1194
- class IteratorDecodeError extends ModuleError$6 {
1195
- constructor (subject, cause) {
1196
- super(`Iterator could not decode ${subject}`, {
1197
- code: 'LEVEL_DECODE_ERROR',
1198
- cause
1199
- });
1200
- }
1201
- }
1202
-
1203
- // To help migrating to abstract-level
1204
- for (const k of ['_ended property', '_nexting property', '_end method']) {
1205
- Object.defineProperty(AbstractIterator$3.prototype, k.split(' ')[0], {
1206
- get () { throw new ModuleError$6(`The ${k} has been removed`, { code: 'LEVEL_LEGACY' }) },
1207
- set () { throw new ModuleError$6(`The ${k} has been removed`, { code: 'LEVEL_LEGACY' }) }
1208
- });
1209
- }
1210
-
1211
- // Exposed so that AbstractLevel can set these options
1212
- AbstractIterator$3.keyEncoding = kKeyEncoding$1;
1213
- AbstractIterator$3.valueEncoding = kValueEncoding$1;
1214
-
1215
- abstractIterator.AbstractIterator = AbstractIterator$3;
1216
- abstractIterator.AbstractKeyIterator = AbstractKeyIterator$2;
1217
- abstractIterator.AbstractValueIterator = AbstractValueIterator$2;
1218
-
1219
- var defaultKvIterator = {};
1220
-
1221
- const { AbstractKeyIterator: AbstractKeyIterator$1, AbstractValueIterator: AbstractValueIterator$1 } = abstractIterator;
1222
-
1223
- const kIterator = Symbol('iterator');
1224
- const kCallback = Symbol('callback');
1225
- const kHandleOne = Symbol('handleOne');
1226
- const kHandleMany = Symbol('handleMany');
1227
-
1228
- class DefaultKeyIterator$1 extends AbstractKeyIterator$1 {
1229
- constructor (db, options) {
1230
- super(db, options);
1231
-
1232
- this[kIterator] = db.iterator({ ...options, keys: true, values: false });
1233
- this[kHandleOne] = this[kHandleOne].bind(this);
1234
- this[kHandleMany] = this[kHandleMany].bind(this);
1235
- }
1236
- }
1237
-
1238
- class DefaultValueIterator$1 extends AbstractValueIterator$1 {
1239
- constructor (db, options) {
1240
- super(db, options);
1241
-
1242
- this[kIterator] = db.iterator({ ...options, keys: false, values: true });
1243
- this[kHandleOne] = this[kHandleOne].bind(this);
1244
- this[kHandleMany] = this[kHandleMany].bind(this);
1245
- }
1246
- }
1247
-
1248
- for (const Iterator of [DefaultKeyIterator$1, DefaultValueIterator$1]) {
1249
- const keys = Iterator === DefaultKeyIterator$1;
1250
- const mapEntry = keys ? (entry) => entry[0] : (entry) => entry[1];
1251
-
1252
- Iterator.prototype._next = function (callback) {
1253
- this[kCallback] = callback;
1254
- this[kIterator].next(this[kHandleOne]);
1255
- };
1256
-
1257
- Iterator.prototype[kHandleOne] = function (err, key, value) {
1258
- const callback = this[kCallback];
1259
- if (err) callback(err);
1260
- else callback(null, keys ? key : value);
1261
- };
1262
-
1263
- Iterator.prototype._nextv = function (size, options, callback) {
1264
- this[kCallback] = callback;
1265
- this[kIterator].nextv(size, options, this[kHandleMany]);
1266
- };
1267
-
1268
- Iterator.prototype._all = function (options, callback) {
1269
- this[kCallback] = callback;
1270
- this[kIterator].all(options, this[kHandleMany]);
1271
- };
1272
-
1273
- Iterator.prototype[kHandleMany] = function (err, entries) {
1274
- const callback = this[kCallback];
1275
- if (err) callback(err);
1276
- else callback(null, entries.map(mapEntry));
1277
- };
1278
-
1279
- Iterator.prototype._seek = function (target, options) {
1280
- this[kIterator].seek(target, options);
1281
- };
1282
-
1283
- Iterator.prototype._close = function (callback) {
1284
- this[kIterator].close(callback);
1285
- };
1286
- }
1287
-
1288
- // Internal utilities, should be typed as AbstractKeyIterator and AbstractValueIterator
1289
- defaultKvIterator.DefaultKeyIterator = DefaultKeyIterator$1;
1290
- defaultKvIterator.DefaultValueIterator = DefaultValueIterator$1;
1291
-
1292
- var deferredIterator = {};
1293
-
1294
- const { AbstractIterator: AbstractIterator$2, AbstractKeyIterator, AbstractValueIterator } = abstractIterator;
1295
- const ModuleError$5 = moduleError;
1296
-
1297
- const kNut = Symbol('nut');
1298
- const kUndefer$1 = Symbol('undefer');
1299
- const kFactory = Symbol('factory');
1300
-
1301
- class DeferredIterator$1 extends AbstractIterator$2 {
1302
- constructor (db, options) {
1303
- super(db, options);
1304
-
1305
- this[kNut] = null;
1306
- this[kFactory] = () => db.iterator(options);
1307
-
1308
- this.db.defer(() => this[kUndefer$1]());
1309
- }
1310
- }
1311
-
1312
- class DeferredKeyIterator$1 extends AbstractKeyIterator {
1313
- constructor (db, options) {
1314
- super(db, options);
1315
-
1316
- this[kNut] = null;
1317
- this[kFactory] = () => db.keys(options);
1318
-
1319
- this.db.defer(() => this[kUndefer$1]());
1320
- }
1321
- }
1322
-
1323
- class DeferredValueIterator$1 extends AbstractValueIterator {
1324
- constructor (db, options) {
1325
- super(db, options);
1326
-
1327
- this[kNut] = null;
1328
- this[kFactory] = () => db.values(options);
1329
-
1330
- this.db.defer(() => this[kUndefer$1]());
1331
- }
1332
- }
1333
-
1334
- for (const Iterator of [DeferredIterator$1, DeferredKeyIterator$1, DeferredValueIterator$1]) {
1335
- Iterator.prototype[kUndefer$1] = function () {
1336
- if (this.db.status === 'open') {
1337
- this[kNut] = this[kFactory]();
1338
- }
1339
- };
1340
-
1341
- Iterator.prototype._next = function (callback) {
1342
- if (this[kNut] !== null) {
1343
- this[kNut].next(callback);
1344
- } else if (this.db.status === 'opening') {
1345
- this.db.defer(() => this._next(callback));
1346
- } else {
1347
- this.nextTick(callback, new ModuleError$5('Iterator is not open: cannot call next() after close()', {
1348
- code: 'LEVEL_ITERATOR_NOT_OPEN'
1349
- }));
1350
- }
1351
- };
1352
-
1353
- Iterator.prototype._nextv = function (size, options, callback) {
1354
- if (this[kNut] !== null) {
1355
- this[kNut].nextv(size, options, callback);
1356
- } else if (this.db.status === 'opening') {
1357
- this.db.defer(() => this._nextv(size, options, callback));
1358
- } else {
1359
- this.nextTick(callback, new ModuleError$5('Iterator is not open: cannot call nextv() after close()', {
1360
- code: 'LEVEL_ITERATOR_NOT_OPEN'
1361
- }));
1362
- }
1363
- };
1364
-
1365
- Iterator.prototype._all = function (options, callback) {
1366
- if (this[kNut] !== null) {
1367
- this[kNut].all(callback);
1368
- } else if (this.db.status === 'opening') {
1369
- this.db.defer(() => this._all(options, callback));
1370
- } else {
1371
- this.nextTick(callback, new ModuleError$5('Iterator is not open: cannot call all() after close()', {
1372
- code: 'LEVEL_ITERATOR_NOT_OPEN'
1373
- }));
1374
- }
1375
- };
1376
-
1377
- Iterator.prototype._seek = function (target, options) {
1378
- if (this[kNut] !== null) {
1379
- // TODO: explain why we need _seek() rather than seek() here
1380
- this[kNut]._seek(target, options);
1381
- } else if (this.db.status === 'opening') {
1382
- this.db.defer(() => this._seek(target, options));
1383
- }
1384
- };
1385
-
1386
- Iterator.prototype._close = function (callback) {
1387
- if (this[kNut] !== null) {
1388
- this[kNut].close(callback);
1389
- } else if (this.db.status === 'opening') {
1390
- this.db.defer(() => this._close(callback));
1391
- } else {
1392
- this.nextTick(callback);
1393
- }
1394
- };
1395
- }
1396
-
1397
- deferredIterator.DeferredIterator = DeferredIterator$1;
1398
- deferredIterator.DeferredKeyIterator = DeferredKeyIterator$1;
1399
- deferredIterator.DeferredValueIterator = DeferredValueIterator$1;
1400
-
1401
- var defaultChainedBatch = {};
1402
-
1403
- var abstractChainedBatch = {};
1404
-
1405
- const { fromCallback: fromCallback$2 } = catering;
1406
- const ModuleError$4 = moduleError;
1407
- const { getCallback: getCallback$1, getOptions: getOptions$1 } = common;
1408
-
1409
- const kPromise$2 = Symbol('promise');
1410
- const kStatus$1 = Symbol('status');
1411
- const kOperations$1 = Symbol('operations');
1412
- const kFinishClose = Symbol('finishClose');
1413
- const kCloseCallbacks = Symbol('closeCallbacks');
1414
-
1415
- class AbstractChainedBatch$1 {
1416
- constructor (db) {
1417
- if (typeof db !== 'object' || db === null) {
1418
- const hint = db === null ? 'null' : typeof db;
1419
- throw new TypeError(`The first argument must be an abstract-level database, received ${hint}`)
1420
- }
1421
-
1422
- this[kOperations$1] = [];
1423
- this[kCloseCallbacks] = [];
1424
- this[kStatus$1] = 'open';
1425
- this[kFinishClose] = this[kFinishClose].bind(this);
1426
-
1427
- this.db = db;
1428
- this.db.attachResource(this);
1429
- this.nextTick = db.nextTick;
1430
- }
1431
-
1432
- get length () {
1433
- return this[kOperations$1].length
1434
- }
1435
-
1436
- put (key, value, options) {
1437
- if (this[kStatus$1] !== 'open') {
1438
- throw new ModuleError$4('Batch is not open: cannot call put() after write() or close()', {
1439
- code: 'LEVEL_BATCH_NOT_OPEN'
1440
- })
1441
- }
1442
-
1443
- const err = this.db._checkKey(key) || this.db._checkValue(value);
1444
- if (err) throw err
1445
-
1446
- const db = options && options.sublevel != null ? options.sublevel : this.db;
1447
- const original = options;
1448
- const keyEncoding = db.keyEncoding(options && options.keyEncoding);
1449
- const valueEncoding = db.valueEncoding(options && options.valueEncoding);
1450
- const keyFormat = keyEncoding.format;
1451
-
1452
- // Forward encoding options
1453
- options = { ...options, keyEncoding: keyFormat, valueEncoding: valueEncoding.format };
1454
-
1455
- // Prevent double prefixing
1456
- if (db !== this.db) {
1457
- options.sublevel = null;
1458
- }
1459
-
1460
- const mappedKey = db.prefixKey(keyEncoding.encode(key), keyFormat);
1461
- const mappedValue = valueEncoding.encode(value);
1462
-
1463
- this._put(mappedKey, mappedValue, options);
1464
- this[kOperations$1].push({ ...original, type: 'put', key, value });
1465
-
1466
- return this
1467
- }
1468
-
1469
- _put (key, value, options) {}
1470
-
1471
- del (key, options) {
1472
- if (this[kStatus$1] !== 'open') {
1473
- throw new ModuleError$4('Batch is not open: cannot call del() after write() or close()', {
1474
- code: 'LEVEL_BATCH_NOT_OPEN'
1475
- })
1476
- }
1477
-
1478
- const err = this.db._checkKey(key);
1479
- if (err) throw err
1480
-
1481
- const db = options && options.sublevel != null ? options.sublevel : this.db;
1482
- const original = options;
1483
- const keyEncoding = db.keyEncoding(options && options.keyEncoding);
1484
- const keyFormat = keyEncoding.format;
1485
-
1486
- // Forward encoding options
1487
- options = { ...options, keyEncoding: keyFormat };
1488
-
1489
- // Prevent double prefixing
1490
- if (db !== this.db) {
1491
- options.sublevel = null;
1492
- }
1493
-
1494
- this._del(db.prefixKey(keyEncoding.encode(key), keyFormat), options);
1495
- this[kOperations$1].push({ ...original, type: 'del', key });
1496
-
1497
- return this
1498
- }
1499
-
1500
- _del (key, options) {}
1501
-
1502
- clear () {
1503
- if (this[kStatus$1] !== 'open') {
1504
- throw new ModuleError$4('Batch is not open: cannot call clear() after write() or close()', {
1505
- code: 'LEVEL_BATCH_NOT_OPEN'
1506
- })
1507
- }
1508
-
1509
- this._clear();
1510
- this[kOperations$1] = [];
1511
-
1512
- return this
1513
- }
1514
-
1515
- _clear () {}
1516
-
1517
- write (options, callback) {
1518
- callback = getCallback$1(options, callback);
1519
- callback = fromCallback$2(callback, kPromise$2);
1520
- options = getOptions$1(options);
1521
-
1522
- if (this[kStatus$1] !== 'open') {
1523
- this.nextTick(callback, new ModuleError$4('Batch is not open: cannot call write() after write() or close()', {
1524
- code: 'LEVEL_BATCH_NOT_OPEN'
1525
- }));
1526
- } else if (this.length === 0) {
1527
- this.close(callback);
1528
- } else {
1529
- this[kStatus$1] = 'writing';
1530
- this._write(options, (err) => {
1531
- this[kStatus$1] = 'closing';
1532
- this[kCloseCallbacks].push(() => callback(err));
1533
-
1534
- // Emit after setting 'closing' status, because event may trigger a
1535
- // db close which in turn triggers (idempotently) closing this batch.
1536
- if (!err) this.db.emit('batch', this[kOperations$1]);
1537
-
1538
- this._close(this[kFinishClose]);
1539
- });
1540
- }
1541
-
1542
- return callback[kPromise$2]
1543
- }
1544
-
1545
- _write (options, callback) {}
1546
-
1547
- close (callback) {
1548
- callback = fromCallback$2(callback, kPromise$2);
1549
-
1550
- if (this[kStatus$1] === 'closing') {
1551
- this[kCloseCallbacks].push(callback);
1552
- } else if (this[kStatus$1] === 'closed') {
1553
- this.nextTick(callback);
1554
- } else {
1555
- this[kCloseCallbacks].push(callback);
1556
-
1557
- if (this[kStatus$1] !== 'writing') {
1558
- this[kStatus$1] = 'closing';
1559
- this._close(this[kFinishClose]);
1560
- }
1561
- }
1562
-
1563
- return callback[kPromise$2]
1564
- }
1565
-
1566
- _close (callback) {
1567
- this.nextTick(callback);
1568
- }
1569
-
1570
- [kFinishClose] () {
1571
- this[kStatus$1] = 'closed';
1572
- this.db.detachResource(this);
1573
-
1574
- const callbacks = this[kCloseCallbacks];
1575
- this[kCloseCallbacks] = [];
1576
-
1577
- for (const cb of callbacks) {
1578
- cb();
1579
- }
1580
- }
1581
- }
1582
-
1583
- abstractChainedBatch.AbstractChainedBatch = AbstractChainedBatch$1;
1584
-
1585
- const { AbstractChainedBatch } = abstractChainedBatch;
1586
- const ModuleError$3 = moduleError;
1587
- const kEncoded = Symbol('encoded');
1588
-
1589
- // Functional default for chained batch, with support of deferred open
1590
- class DefaultChainedBatch$1 extends AbstractChainedBatch {
1591
- constructor (db) {
1592
- super(db);
1593
- this[kEncoded] = [];
1594
- }
1595
-
1596
- _put (key, value, options) {
1597
- this[kEncoded].push({ ...options, type: 'put', key, value });
1598
- }
1599
-
1600
- _del (key, options) {
1601
- this[kEncoded].push({ ...options, type: 'del', key });
1602
- }
1603
-
1604
- _clear () {
1605
- this[kEncoded] = [];
1606
- }
1607
-
1608
- // Assumes this[kEncoded] cannot change after write()
1609
- _write (options, callback) {
1610
- if (this.db.status === 'opening') {
1611
- this.db.defer(() => this._write(options, callback));
1612
- } else if (this.db.status === 'open') {
1613
- if (this[kEncoded].length === 0) this.nextTick(callback);
1614
- else this.db._batch(this[kEncoded], options, callback);
1615
- } else {
1616
- this.nextTick(callback, new ModuleError$3('Batch is not open: cannot call write() after write() or close()', {
1617
- code: 'LEVEL_BATCH_NOT_OPEN'
1618
- }));
1619
- }
1620
- }
1621
- }
1622
-
1623
- defaultChainedBatch.DefaultChainedBatch = DefaultChainedBatch$1;
1624
-
1625
- const ModuleError$2 = moduleError;
1626
- const hasOwnProperty = Object.prototype.hasOwnProperty;
1627
- const rangeOptions$1 = new Set(['lt', 'lte', 'gt', 'gte']);
1628
-
1629
- var rangeOptions_1 = function (options, keyEncoding) {
1630
- const result = {};
1631
-
1632
- for (const k in options) {
1633
- if (!hasOwnProperty.call(options, k)) continue
1634
- if (k === 'keyEncoding' || k === 'valueEncoding') continue
1635
-
1636
- if (k === 'start' || k === 'end') {
1637
- throw new ModuleError$2(`The legacy range option '${k}' has been removed`, {
1638
- code: 'LEVEL_LEGACY'
1639
- })
1640
- } else if (k === 'encoding') {
1641
- // To help migrating to abstract-level
1642
- throw new ModuleError$2("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead", {
1643
- code: 'LEVEL_LEGACY'
1644
- })
1645
- }
1646
-
1647
- if (rangeOptions$1.has(k)) {
1648
- // Note that we don't reject nullish and empty options here. While
1649
- // those types are invalid as keys, they are valid as range options.
1650
- result[k] = keyEncoding.encode(options[k]);
1651
- } else {
1652
- result[k] = options[k];
1653
- }
1654
- }
1655
-
1656
- result.reverse = !!result.reverse;
1657
- result.limit = Number.isInteger(result.limit) && result.limit >= 0 ? result.limit : -1;
1658
-
1659
- return result
1660
- };
1661
-
1662
- var nextTick;
1663
- var hasRequiredNextTick;
1664
-
1665
- function requireNextTick () {
1666
- if (hasRequiredNextTick) return nextTick;
1667
- hasRequiredNextTick = 1;
1668
-
1669
- nextTick = process.nextTick;
1670
- return nextTick;
1671
- }
1672
-
1673
- var abstractSublevelIterator = {};
1674
-
1675
- var hasRequiredAbstractSublevelIterator;
1676
-
1677
- function requireAbstractSublevelIterator () {
1678
- if (hasRequiredAbstractSublevelIterator) return abstractSublevelIterator;
1679
- hasRequiredAbstractSublevelIterator = 1;
1680
-
1681
- const { AbstractIterator, AbstractKeyIterator, AbstractValueIterator } = abstractIterator;
1682
-
1683
- const kUnfix = Symbol('unfix');
1684
- const kIterator = Symbol('iterator');
1685
- const kHandleOne = Symbol('handleOne');
1686
- const kHandleMany = Symbol('handleMany');
1687
- const kCallback = Symbol('callback');
1688
-
1689
- // TODO: unfix natively if db supports it
1690
- class AbstractSublevelIterator extends AbstractIterator {
1691
- constructor (db, options, iterator, unfix) {
1692
- super(db, options);
1693
-
1694
- this[kIterator] = iterator;
1695
- this[kUnfix] = unfix;
1696
- this[kHandleOne] = this[kHandleOne].bind(this);
1697
- this[kHandleMany] = this[kHandleMany].bind(this);
1698
- this[kCallback] = null;
1699
- }
1700
-
1701
- [kHandleOne] (err, key, value) {
1702
- const callback = this[kCallback];
1703
- if (err) return callback(err)
1704
- if (key !== undefined) key = this[kUnfix](key);
1705
- callback(err, key, value);
1706
- }
1707
-
1708
- [kHandleMany] (err, entries) {
1709
- const callback = this[kCallback];
1710
- if (err) return callback(err)
1711
-
1712
- for (const entry of entries) {
1713
- const key = entry[0];
1714
- if (key !== undefined) entry[0] = this[kUnfix](key);
1715
- }
1716
-
1717
- callback(err, entries);
1718
- }
1719
- }
1720
-
1721
- class AbstractSublevelKeyIterator extends AbstractKeyIterator {
1722
- constructor (db, options, iterator, unfix) {
1723
- super(db, options);
1724
-
1725
- this[kIterator] = iterator;
1726
- this[kUnfix] = unfix;
1727
- this[kHandleOne] = this[kHandleOne].bind(this);
1728
- this[kHandleMany] = this[kHandleMany].bind(this);
1729
- this[kCallback] = null;
1730
- }
1731
-
1732
- [kHandleOne] (err, key) {
1733
- const callback = this[kCallback];
1734
- if (err) return callback(err)
1735
- if (key !== undefined) key = this[kUnfix](key);
1736
- callback(err, key);
1737
- }
1738
-
1739
- [kHandleMany] (err, keys) {
1740
- const callback = this[kCallback];
1741
- if (err) return callback(err)
1742
-
1743
- for (let i = 0; i < keys.length; i++) {
1744
- const key = keys[i];
1745
- if (key !== undefined) keys[i] = this[kUnfix](key);
1746
- }
1747
-
1748
- callback(err, keys);
1749
- }
1750
- }
1751
-
1752
- class AbstractSublevelValueIterator extends AbstractValueIterator {
1753
- constructor (db, options, iterator) {
1754
- super(db, options);
1755
- this[kIterator] = iterator;
1756
- }
1757
- }
1758
-
1759
- for (const Iterator of [AbstractSublevelIterator, AbstractSublevelKeyIterator]) {
1760
- Iterator.prototype._next = function (callback) {
1761
- this[kCallback] = callback;
1762
- this[kIterator].next(this[kHandleOne]);
1763
- };
1764
-
1765
- Iterator.prototype._nextv = function (size, options, callback) {
1766
- this[kCallback] = callback;
1767
- this[kIterator].nextv(size, options, this[kHandleMany]);
1768
- };
1769
-
1770
- Iterator.prototype._all = function (options, callback) {
1771
- this[kCallback] = callback;
1772
- this[kIterator].all(options, this[kHandleMany]);
1773
- };
1774
- }
1775
-
1776
- for (const Iterator of [AbstractSublevelValueIterator]) {
1777
- Iterator.prototype._next = function (callback) {
1778
- this[kIterator].next(callback);
1779
- };
1780
-
1781
- Iterator.prototype._nextv = function (size, options, callback) {
1782
- this[kIterator].nextv(size, options, callback);
1783
- };
1784
-
1785
- Iterator.prototype._all = function (options, callback) {
1786
- this[kIterator].all(options, callback);
1787
- };
1788
- }
1789
-
1790
- for (const Iterator of [AbstractSublevelIterator, AbstractSublevelKeyIterator, AbstractSublevelValueIterator]) {
1791
- Iterator.prototype._seek = function (target, options) {
1792
- this[kIterator].seek(target, options);
1793
- };
1794
-
1795
- Iterator.prototype._close = function (callback) {
1796
- this[kIterator].close(callback);
1797
- };
1798
- }
1799
-
1800
- abstractSublevelIterator.AbstractSublevelIterator = AbstractSublevelIterator;
1801
- abstractSublevelIterator.AbstractSublevelKeyIterator = AbstractSublevelKeyIterator;
1802
- abstractSublevelIterator.AbstractSublevelValueIterator = AbstractSublevelValueIterator;
1803
- return abstractSublevelIterator;
1804
- }
1805
-
1806
- var abstractSublevel;
1807
- var hasRequiredAbstractSublevel;
1808
-
1809
- function requireAbstractSublevel () {
1810
- if (hasRequiredAbstractSublevel) return abstractSublevel;
1811
- hasRequiredAbstractSublevel = 1;
1812
-
1813
- const ModuleError = moduleError;
1814
- const { Buffer } = buffer__WEBPACK_IMPORTED_MODULE_0__ || {};
1815
- const {
1816
- AbstractSublevelIterator,
1817
- AbstractSublevelKeyIterator,
1818
- AbstractSublevelValueIterator
1819
- } = requireAbstractSublevelIterator();
1820
-
1821
- const kPrefix = Symbol('prefix');
1822
- const kUpperBound = Symbol('upperBound');
1823
- const kPrefixRange = Symbol('prefixRange');
1824
- const kParent = Symbol('parent');
1825
- const kUnfix = Symbol('unfix');
1826
-
1827
- const textEncoder = new TextEncoder();
1828
- const defaults = { separator: '!' };
1829
-
1830
- // Wrapped to avoid circular dependency
1831
- abstractSublevel = function ({ AbstractLevel }) {
1832
- class AbstractSublevel extends AbstractLevel {
1833
- static defaults (options) {
1834
- // To help migrating from subleveldown to abstract-level
1835
- if (typeof options === 'string') {
1836
- throw new ModuleError('The subleveldown string shorthand for { separator } has been removed', {
1837
- code: 'LEVEL_LEGACY'
1838
- })
1839
- } else if (options && options.open) {
1840
- throw new ModuleError('The subleveldown open option has been removed', {
1841
- code: 'LEVEL_LEGACY'
1842
- })
1843
- }
1844
-
1845
- if (options == null) {
1846
- return defaults
1847
- } else if (!options.separator) {
1848
- return { ...options, separator: '!' }
1849
- } else {
1850
- return options
1851
- }
1852
- }
1853
-
1854
- // TODO: add autoClose option, which if true, does parent.attachResource(this)
1855
- constructor (db, name, options) {
1856
- // Don't forward AbstractSublevel options to AbstractLevel
1857
- const { separator, manifest, ...forward } = AbstractSublevel.defaults(options);
1858
- name = trim(name, separator);
1859
-
1860
- // Reserve one character between separator and name to give us an upper bound
1861
- const reserved = separator.charCodeAt(0) + 1;
1862
- const parent = db[kParent] || db;
1863
-
1864
- // Keys should sort like ['!a!', '!a!!a!', '!a"', '!aa!', '!b!'].
1865
- // Use ASCII for consistent length between string, Buffer and Uint8Array
1866
- if (!textEncoder.encode(name).every(x => x > reserved && x < 127)) {
1867
- throw new ModuleError(`Prefix must use bytes > ${reserved} < ${127}`, {
1868
- code: 'LEVEL_INVALID_PREFIX'
1869
- })
1870
- }
1871
-
1872
- super(mergeManifests(parent, manifest), forward);
1873
-
1874
- const prefix = (db.prefix || '') + separator + name + separator;
1875
- const upperBound = prefix.slice(0, -1) + String.fromCharCode(reserved);
1876
-
1877
- this[kParent] = parent;
1878
- this[kPrefix] = new MultiFormat(prefix);
1879
- this[kUpperBound] = new MultiFormat(upperBound);
1880
- this[kUnfix] = new Unfixer();
1881
-
1882
- this.nextTick = parent.nextTick;
1883
- }
1884
-
1885
- prefixKey (key, keyFormat) {
1886
- if (keyFormat === 'utf8') {
1887
- return this[kPrefix].utf8 + key
1888
- } else if (key.byteLength === 0) {
1889
- // Fast path for empty key (no copy)
1890
- return this[kPrefix][keyFormat]
1891
- } else if (keyFormat === 'view') {
1892
- const view = this[kPrefix].view;
1893
- const result = new Uint8Array(view.byteLength + key.byteLength);
1894
-
1895
- result.set(view, 0);
1896
- result.set(key, view.byteLength);
1897
-
1898
- return result
1899
- } else {
1900
- const buffer = this[kPrefix].buffer;
1901
- return Buffer.concat([buffer, key], buffer.byteLength + key.byteLength)
1902
- }
1903
- }
1904
-
1905
- // Not exposed for now.
1906
- [kPrefixRange] (range, keyFormat) {
1907
- if (range.gte !== undefined) {
1908
- range.gte = this.prefixKey(range.gte, keyFormat);
1909
- } else if (range.gt !== undefined) {
1910
- range.gt = this.prefixKey(range.gt, keyFormat);
1911
- } else {
1912
- range.gte = this[kPrefix][keyFormat];
1913
- }
1914
-
1915
- if (range.lte !== undefined) {
1916
- range.lte = this.prefixKey(range.lte, keyFormat);
1917
- } else if (range.lt !== undefined) {
1918
- range.lt = this.prefixKey(range.lt, keyFormat);
1919
- } else {
1920
- range.lte = this[kUpperBound][keyFormat];
1921
- }
1922
- }
1923
-
1924
- get prefix () {
1925
- return this[kPrefix].utf8
1926
- }
1927
-
1928
- get db () {
1929
- return this[kParent]
1930
- }
1931
-
1932
- _open (options, callback) {
1933
- // The parent db must open itself or be (re)opened by the user because
1934
- // a sublevel should not initiate state changes on the rest of the db.
1935
- this[kParent].open({ passive: true }, callback);
1936
- }
1937
-
1938
- _put (key, value, options, callback) {
1939
- this[kParent].put(key, value, options, callback);
1940
- }
1941
-
1942
- _get (key, options, callback) {
1943
- this[kParent].get(key, options, callback);
1944
- }
1945
-
1946
- _getMany (keys, options, callback) {
1947
- this[kParent].getMany(keys, options, callback);
1948
- }
1949
-
1950
- _del (key, options, callback) {
1951
- this[kParent].del(key, options, callback);
1952
- }
1953
-
1954
- _batch (operations, options, callback) {
1955
- this[kParent].batch(operations, options, callback);
1956
- }
1957
-
1958
- _clear (options, callback) {
1959
- // TODO (refactor): move to AbstractLevel
1960
- this[kPrefixRange](options, options.keyEncoding);
1961
- this[kParent].clear(options, callback);
1962
- }
1963
-
1964
- _iterator (options) {
1965
- // TODO (refactor): move to AbstractLevel
1966
- this[kPrefixRange](options, options.keyEncoding);
1967
- const iterator = this[kParent].iterator(options);
1968
- const unfix = this[kUnfix].get(this[kPrefix].utf8.length, options.keyEncoding);
1969
- return new AbstractSublevelIterator(this, options, iterator, unfix)
1970
- }
1971
-
1972
- _keys (options) {
1973
- this[kPrefixRange](options, options.keyEncoding);
1974
- const iterator = this[kParent].keys(options);
1975
- const unfix = this[kUnfix].get(this[kPrefix].utf8.length, options.keyEncoding);
1976
- return new AbstractSublevelKeyIterator(this, options, iterator, unfix)
1977
- }
1978
-
1979
- _values (options) {
1980
- this[kPrefixRange](options, options.keyEncoding);
1981
- const iterator = this[kParent].values(options);
1982
- return new AbstractSublevelValueIterator(this, options, iterator)
1983
- }
1984
- }
1985
-
1986
- return { AbstractSublevel }
1987
- };
1988
-
1989
- const mergeManifests = function (parent, manifest) {
1990
- return {
1991
- // Inherit manifest of parent db
1992
- ...parent.supports,
1993
-
1994
- // Disable unsupported features
1995
- createIfMissing: false,
1996
- errorIfExists: false,
1997
-
1998
- // Unset additional events because we're not forwarding them
1999
- events: {},
2000
-
2001
- // Unset additional methods (like approximateSize) which we can't support here unless
2002
- // the AbstractSublevel class is overridden by an implementation of `abstract-level`.
2003
- additionalMethods: {},
2004
-
2005
- // Inherit manifest of custom AbstractSublevel subclass. Such a class is not
2006
- // allowed to override encodings.
2007
- ...manifest,
2008
-
2009
- encodings: {
2010
- utf8: supportsEncoding(parent, 'utf8'),
2011
- buffer: supportsEncoding(parent, 'buffer'),
2012
- view: supportsEncoding(parent, 'view')
2013
- }
2014
- }
2015
- };
2016
-
2017
- const supportsEncoding = function (parent, encoding) {
2018
- // Prefer a non-transcoded encoding for optimal performance
2019
- return parent.supports.encodings[encoding]
2020
- ? parent.keyEncoding(encoding).name === encoding
2021
- : false
2022
- };
2023
-
2024
- class MultiFormat {
2025
- constructor (key) {
2026
- this.utf8 = key;
2027
- this.view = textEncoder.encode(key);
2028
- this.buffer = Buffer ? Buffer.from(this.view.buffer, 0, this.view.byteLength) : {};
2029
- }
2030
- }
2031
-
2032
- class Unfixer {
2033
- constructor () {
2034
- this.cache = new Map();
2035
- }
2036
-
2037
- get (prefixLength, keyFormat) {
2038
- let unfix = this.cache.get(keyFormat);
2039
-
2040
- if (unfix === undefined) {
2041
- if (keyFormat === 'view') {
2042
- unfix = function (prefixLength, key) {
2043
- // Avoid Uint8Array#slice() because it copies
2044
- return key.subarray(prefixLength)
2045
- }.bind(null, prefixLength);
2046
- } else {
2047
- unfix = function (prefixLength, key) {
2048
- // Avoid Buffer#subarray() because it's slow
2049
- return key.slice(prefixLength)
2050
- }.bind(null, prefixLength);
2051
- }
2052
-
2053
- this.cache.set(keyFormat, unfix);
2054
- }
2055
-
2056
- return unfix
2057
- }
2058
- }
2059
-
2060
- const trim = function (str, char) {
2061
- let start = 0;
2062
- let end = str.length;
2063
-
2064
- while (start < end && str[start] === char) start++;
2065
- while (end > start && str[end - 1] === char) end--;
2066
-
2067
- return str.slice(start, end)
2068
- };
2069
- return abstractSublevel;
2070
- }
2071
-
2072
- const { supports } = levelSupports;
2073
- const { Transcoder } = levelTranscoder;
2074
- const { EventEmitter } = (events__WEBPACK_IMPORTED_MODULE_1___default());
2075
- const { fromCallback: fromCallback$1 } = catering;
2076
- const ModuleError$1 = moduleError;
2077
- const { AbstractIterator: AbstractIterator$1 } = abstractIterator;
2078
- const { DefaultKeyIterator, DefaultValueIterator } = defaultKvIterator;
2079
- const { DeferredIterator, DeferredKeyIterator, DeferredValueIterator } = deferredIterator;
2080
- const { DefaultChainedBatch } = defaultChainedBatch;
2081
- const { getCallback, getOptions } = common;
2082
- const rangeOptions = rangeOptions_1;
2083
-
2084
- const kPromise$1 = Symbol('promise');
2085
- const kLanded = Symbol('landed');
2086
- const kResources = Symbol('resources');
2087
- const kCloseResources = Symbol('closeResources');
2088
- const kOperations = Symbol('operations');
2089
- const kUndefer = Symbol('undefer');
2090
- const kDeferOpen = Symbol('deferOpen');
2091
- const kOptions$1 = Symbol('options');
2092
- const kStatus = Symbol('status');
2093
- const kDefaultOptions = Symbol('defaultOptions');
2094
- const kTranscoder = Symbol('transcoder');
2095
- const kKeyEncoding = Symbol('keyEncoding');
2096
- const kValueEncoding = Symbol('valueEncoding');
2097
- const noop = () => {};
2098
-
2099
- class AbstractLevel$1 extends EventEmitter {
2100
- constructor (manifest, options) {
2101
- super();
2102
-
2103
- if (typeof manifest !== 'object' || manifest === null) {
2104
- throw new TypeError("The first argument 'manifest' must be an object")
2105
- }
2106
-
2107
- options = getOptions(options);
2108
- const { keyEncoding, valueEncoding, passive, ...forward } = options;
2109
-
2110
- this[kResources] = new Set();
2111
- this[kOperations] = [];
2112
- this[kDeferOpen] = true;
2113
- this[kOptions$1] = forward;
2114
- this[kStatus] = 'opening';
2115
-
2116
- this.supports = supports(manifest, {
2117
- status: true,
2118
- promises: true,
2119
- clear: true,
2120
- getMany: true,
2121
- deferredOpen: true,
2122
-
2123
- // TODO (next major): add seek
2124
- snapshots: manifest.snapshots !== false,
2125
- permanence: manifest.permanence !== false,
2126
-
2127
- // TODO: remove from level-supports because it's always supported
2128
- keyIterator: true,
2129
- valueIterator: true,
2130
- iteratorNextv: true,
2131
- iteratorAll: true,
2132
-
2133
- encodings: manifest.encodings || {},
2134
- events: Object.assign({}, manifest.events, {
2135
- opening: true,
2136
- open: true,
2137
- closing: true,
2138
- closed: true,
2139
- put: true,
2140
- del: true,
2141
- batch: true,
2142
- clear: true
2143
- })
2144
- });
2145
-
2146
- this[kTranscoder] = new Transcoder(formats(this));
2147
- this[kKeyEncoding] = this[kTranscoder].encoding(keyEncoding || 'utf8');
2148
- this[kValueEncoding] = this[kTranscoder].encoding(valueEncoding || 'utf8');
2149
-
2150
- // Add custom and transcoder encodings to manifest
2151
- for (const encoding of this[kTranscoder].encodings()) {
2152
- if (!this.supports.encodings[encoding.commonName]) {
2153
- this.supports.encodings[encoding.commonName] = true;
2154
- }
2155
- }
2156
-
2157
- this[kDefaultOptions] = {
2158
- empty: Object.freeze({}),
2159
- entry: Object.freeze({
2160
- keyEncoding: this[kKeyEncoding].commonName,
2161
- valueEncoding: this[kValueEncoding].commonName
2162
- }),
2163
- key: Object.freeze({
2164
- keyEncoding: this[kKeyEncoding].commonName
2165
- })
2166
- };
2167
-
2168
- // Let subclass finish its constructor
2169
- this.nextTick(() => {
2170
- if (this[kDeferOpen]) {
2171
- this.open({ passive: false }, noop);
2172
- }
2173
- });
2174
- }
2175
-
2176
- get status () {
2177
- return this[kStatus]
2178
- }
2179
-
2180
- keyEncoding (encoding) {
2181
- return this[kTranscoder].encoding(encoding != null ? encoding : this[kKeyEncoding])
2182
- }
2183
-
2184
- valueEncoding (encoding) {
2185
- return this[kTranscoder].encoding(encoding != null ? encoding : this[kValueEncoding])
2186
- }
2187
-
2188
- open (options, callback) {
2189
- callback = getCallback(options, callback);
2190
- callback = fromCallback$1(callback, kPromise$1);
2191
-
2192
- options = { ...this[kOptions$1], ...getOptions(options) };
2193
-
2194
- options.createIfMissing = options.createIfMissing !== false;
2195
- options.errorIfExists = !!options.errorIfExists;
2196
-
2197
- const maybeOpened = (err) => {
2198
- if (this[kStatus] === 'closing' || this[kStatus] === 'opening') {
2199
- // Wait until pending state changes are done
2200
- this.once(kLanded, err ? () => maybeOpened(err) : maybeOpened);
2201
- } else if (this[kStatus] !== 'open') {
2202
- callback(new ModuleError$1('Database is not open', {
2203
- code: 'LEVEL_DATABASE_NOT_OPEN',
2204
- cause: err
2205
- }));
2206
- } else {
2207
- callback();
2208
- }
2209
- };
2210
-
2211
- if (options.passive) {
2212
- if (this[kStatus] === 'opening') {
2213
- this.once(kLanded, maybeOpened);
2214
- } else {
2215
- this.nextTick(maybeOpened);
2216
- }
2217
- } else if (this[kStatus] === 'closed' || this[kDeferOpen]) {
2218
- this[kDeferOpen] = false;
2219
- this[kStatus] = 'opening';
2220
- this.emit('opening');
2221
-
2222
- this._open(options, (err) => {
2223
- if (err) {
2224
- this[kStatus] = 'closed';
2225
-
2226
- // Resources must be safe to close in any db state
2227
- this[kCloseResources](() => {
2228
- this.emit(kLanded);
2229
- maybeOpened(err);
2230
- });
2231
-
2232
- this[kUndefer]();
2233
- return
2234
- }
2235
-
2236
- this[kStatus] = 'open';
2237
- this[kUndefer]();
2238
- this.emit(kLanded);
2239
-
2240
- // Only emit public event if pending state changes are done
2241
- if (this[kStatus] === 'open') this.emit('open');
2242
-
2243
- // TODO (next major): remove this alias
2244
- if (this[kStatus] === 'open') this.emit('ready');
2245
-
2246
- maybeOpened();
2247
- });
2248
- } else if (this[kStatus] === 'open') {
2249
- this.nextTick(maybeOpened);
2250
- } else {
2251
- this.once(kLanded, () => this.open(options, callback));
2252
- }
2253
-
2254
- return callback[kPromise$1]
2255
- }
2256
-
2257
- _open (options, callback) {
2258
- this.nextTick(callback);
2259
- }
2260
-
2261
- close (callback) {
2262
- callback = fromCallback$1(callback, kPromise$1);
2263
-
2264
- const maybeClosed = (err) => {
2265
- if (this[kStatus] === 'opening' || this[kStatus] === 'closing') {
2266
- // Wait until pending state changes are done
2267
- this.once(kLanded, err ? maybeClosed(err) : maybeClosed);
2268
- } else if (this[kStatus] !== 'closed') {
2269
- callback(new ModuleError$1('Database is not closed', {
2270
- code: 'LEVEL_DATABASE_NOT_CLOSED',
2271
- cause: err
2272
- }));
2273
- } else {
2274
- callback();
2275
- }
2276
- };
2277
-
2278
- if (this[kStatus] === 'open') {
2279
- this[kStatus] = 'closing';
2280
- this.emit('closing');
2281
-
2282
- const cancel = (err) => {
2283
- this[kStatus] = 'open';
2284
- this[kUndefer]();
2285
- this.emit(kLanded);
2286
- maybeClosed(err);
2287
- };
2288
-
2289
- this[kCloseResources](() => {
2290
- this._close((err) => {
2291
- if (err) return cancel(err)
2292
-
2293
- this[kStatus] = 'closed';
2294
- this[kUndefer]();
2295
- this.emit(kLanded);
2296
-
2297
- // Only emit public event if pending state changes are done
2298
- if (this[kStatus] === 'closed') this.emit('closed');
2299
-
2300
- maybeClosed();
2301
- });
2302
- });
2303
- } else if (this[kStatus] === 'closed') {
2304
- this.nextTick(maybeClosed);
2305
- } else {
2306
- this.once(kLanded, () => this.close(callback));
2307
- }
2308
-
2309
- return callback[kPromise$1]
2310
- }
2311
-
2312
- [kCloseResources] (callback) {
2313
- if (this[kResources].size === 0) {
2314
- return this.nextTick(callback)
2315
- }
2316
-
2317
- let pending = this[kResources].size;
2318
- let sync = true;
2319
-
2320
- const next = () => {
2321
- if (--pending === 0) {
2322
- // We don't have tests for generic resources, so dezalgo
2323
- if (sync) this.nextTick(callback);
2324
- else callback();
2325
- }
2326
- };
2327
-
2328
- // In parallel so that all resources know they are closed
2329
- for (const resource of this[kResources]) {
2330
- resource.close(next);
2331
- }
2332
-
2333
- sync = false;
2334
- this[kResources].clear();
2335
- }
2336
-
2337
- _close (callback) {
2338
- this.nextTick(callback);
2339
- }
2340
-
2341
- get (key, options, callback) {
2342
- callback = getCallback(options, callback);
2343
- callback = fromCallback$1(callback, kPromise$1);
2344
- options = getOptions(options, this[kDefaultOptions].entry);
2345
-
2346
- if (this[kStatus] === 'opening') {
2347
- this.defer(() => this.get(key, options, callback));
2348
- return callback[kPromise$1]
2349
- }
2350
-
2351
- if (maybeError(this, callback)) {
2352
- return callback[kPromise$1]
2353
- }
2354
-
2355
- const err = this._checkKey(key);
2356
-
2357
- if (err) {
2358
- this.nextTick(callback, err);
2359
- return callback[kPromise$1]
2360
- }
2361
-
2362
- const keyEncoding = this.keyEncoding(options.keyEncoding);
2363
- const valueEncoding = this.valueEncoding(options.valueEncoding);
2364
- const keyFormat = keyEncoding.format;
2365
- const valueFormat = valueEncoding.format;
2366
-
2367
- // Forward encoding options to the underlying store
2368
- if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {
2369
- // Avoid spread operator because of https://bugs.chromium.org/p/chromium/issues/detail?id=1204540
2370
- options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat });
2371
- }
2372
-
2373
- this._get(this.prefixKey(keyEncoding.encode(key), keyFormat), options, (err, value) => {
2374
- if (err) {
2375
- // Normalize not found error for backwards compatibility with abstract-leveldown and level(up)
2376
- if (err.code === 'LEVEL_NOT_FOUND' || err.notFound || /NotFound/i.test(err)) {
2377
- if (!err.code) err.code = 'LEVEL_NOT_FOUND'; // Preferred way going forward
2378
- if (!err.notFound) err.notFound = true; // Same as level-errors
2379
- if (!err.status) err.status = 404; // Same as level-errors
2380
- }
2381
-
2382
- return callback(err)
2383
- }
2384
-
2385
- try {
2386
- value = valueEncoding.decode(value);
2387
- } catch (err) {
2388
- return callback(new ModuleError$1('Could not decode value', {
2389
- code: 'LEVEL_DECODE_ERROR',
2390
- cause: err
2391
- }))
2392
- }
2393
-
2394
- callback(null, value);
2395
- });
2396
-
2397
- return callback[kPromise$1]
2398
- }
2399
-
2400
- _get (key, options, callback) {
2401
- this.nextTick(callback, new Error('NotFound'));
2402
- }
2403
-
2404
- getMany (keys, options, callback) {
2405
- callback = getCallback(options, callback);
2406
- callback = fromCallback$1(callback, kPromise$1);
2407
- options = getOptions(options, this[kDefaultOptions].entry);
2408
-
2409
- if (this[kStatus] === 'opening') {
2410
- this.defer(() => this.getMany(keys, options, callback));
2411
- return callback[kPromise$1]
2412
- }
2413
-
2414
- if (maybeError(this, callback)) {
2415
- return callback[kPromise$1]
2416
- }
2417
-
2418
- if (!Array.isArray(keys)) {
2419
- this.nextTick(callback, new TypeError("The first argument 'keys' must be an array"));
2420
- return callback[kPromise$1]
2421
- }
2422
-
2423
- if (keys.length === 0) {
2424
- this.nextTick(callback, null, []);
2425
- return callback[kPromise$1]
2426
- }
2427
-
2428
- const keyEncoding = this.keyEncoding(options.keyEncoding);
2429
- const valueEncoding = this.valueEncoding(options.valueEncoding);
2430
- const keyFormat = keyEncoding.format;
2431
- const valueFormat = valueEncoding.format;
2432
-
2433
- // Forward encoding options
2434
- if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {
2435
- options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat });
2436
- }
2437
-
2438
- const mappedKeys = new Array(keys.length);
2439
-
2440
- for (let i = 0; i < keys.length; i++) {
2441
- const key = keys[i];
2442
- const err = this._checkKey(key);
2443
-
2444
- if (err) {
2445
- this.nextTick(callback, err);
2446
- return callback[kPromise$1]
2447
- }
2448
-
2449
- mappedKeys[i] = this.prefixKey(keyEncoding.encode(key), keyFormat);
2450
- }
2451
-
2452
- this._getMany(mappedKeys, options, (err, values) => {
2453
- if (err) return callback(err)
2454
-
2455
- try {
2456
- for (let i = 0; i < values.length; i++) {
2457
- if (values[i] !== undefined) {
2458
- values[i] = valueEncoding.decode(values[i]);
2459
- }
2460
- }
2461
- } catch (err) {
2462
- return callback(new ModuleError$1(`Could not decode one or more of ${values.length} value(s)`, {
2463
- code: 'LEVEL_DECODE_ERROR',
2464
- cause: err
2465
- }))
2466
- }
2467
-
2468
- callback(null, values);
2469
- });
2470
-
2471
- return callback[kPromise$1]
2472
- }
2473
-
2474
- _getMany (keys, options, callback) {
2475
- this.nextTick(callback, null, new Array(keys.length).fill(undefined));
2476
- }
2477
-
2478
- put (key, value, options, callback) {
2479
- callback = getCallback(options, callback);
2480
- callback = fromCallback$1(callback, kPromise$1);
2481
- options = getOptions(options, this[kDefaultOptions].entry);
2482
-
2483
- if (this[kStatus] === 'opening') {
2484
- this.defer(() => this.put(key, value, options, callback));
2485
- return callback[kPromise$1]
2486
- }
2487
-
2488
- if (maybeError(this, callback)) {
2489
- return callback[kPromise$1]
2490
- }
2491
-
2492
- const err = this._checkKey(key) || this._checkValue(value);
2493
-
2494
- if (err) {
2495
- this.nextTick(callback, err);
2496
- return callback[kPromise$1]
2497
- }
2498
-
2499
- const keyEncoding = this.keyEncoding(options.keyEncoding);
2500
- const valueEncoding = this.valueEncoding(options.valueEncoding);
2501
- const keyFormat = keyEncoding.format;
2502
- const valueFormat = valueEncoding.format;
2503
-
2504
- // Forward encoding options
2505
- if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {
2506
- options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat });
2507
- }
2508
-
2509
- const mappedKey = this.prefixKey(keyEncoding.encode(key), keyFormat);
2510
- const mappedValue = valueEncoding.encode(value);
2511
-
2512
- this._put(mappedKey, mappedValue, options, (err) => {
2513
- if (err) return callback(err)
2514
- this.emit('put', key, value);
2515
- callback();
2516
- });
2517
-
2518
- return callback[kPromise$1]
2519
- }
2520
-
2521
- _put (key, value, options, callback) {
2522
- this.nextTick(callback);
2523
- }
2524
-
2525
- del (key, options, callback) {
2526
- callback = getCallback(options, callback);
2527
- callback = fromCallback$1(callback, kPromise$1);
2528
- options = getOptions(options, this[kDefaultOptions].key);
2529
-
2530
- if (this[kStatus] === 'opening') {
2531
- this.defer(() => this.del(key, options, callback));
2532
- return callback[kPromise$1]
2533
- }
2534
-
2535
- if (maybeError(this, callback)) {
2536
- return callback[kPromise$1]
2537
- }
2538
-
2539
- const err = this._checkKey(key);
2540
-
2541
- if (err) {
2542
- this.nextTick(callback, err);
2543
- return callback[kPromise$1]
2544
- }
2545
-
2546
- const keyEncoding = this.keyEncoding(options.keyEncoding);
2547
- const keyFormat = keyEncoding.format;
2548
-
2549
- // Forward encoding options
2550
- if (options.keyEncoding !== keyFormat) {
2551
- options = Object.assign({}, options, { keyEncoding: keyFormat });
2552
- }
2553
-
2554
- this._del(this.prefixKey(keyEncoding.encode(key), keyFormat), options, (err) => {
2555
- if (err) return callback(err)
2556
- this.emit('del', key);
2557
- callback();
2558
- });
2559
-
2560
- return callback[kPromise$1]
2561
- }
2562
-
2563
- _del (key, options, callback) {
2564
- this.nextTick(callback);
2565
- }
2566
-
2567
- batch (operations, options, callback) {
2568
- if (!arguments.length) {
2569
- if (this[kStatus] === 'opening') return new DefaultChainedBatch(this)
2570
- if (this[kStatus] !== 'open') {
2571
- throw new ModuleError$1('Database is not open', {
2572
- code: 'LEVEL_DATABASE_NOT_OPEN'
2573
- })
2574
- }
2575
- return this._chainedBatch()
2576
- }
2577
-
2578
- if (typeof operations === 'function') callback = operations;
2579
- else callback = getCallback(options, callback);
2580
-
2581
- callback = fromCallback$1(callback, kPromise$1);
2582
- options = getOptions(options, this[kDefaultOptions].empty);
2583
-
2584
- if (this[kStatus] === 'opening') {
2585
- this.defer(() => this.batch(operations, options, callback));
2586
- return callback[kPromise$1]
2587
- }
2588
-
2589
- if (maybeError(this, callback)) {
2590
- return callback[kPromise$1]
2591
- }
2592
-
2593
- if (!Array.isArray(operations)) {
2594
- this.nextTick(callback, new TypeError("The first argument 'operations' must be an array"));
2595
- return callback[kPromise$1]
2596
- }
2597
-
2598
- if (operations.length === 0) {
2599
- this.nextTick(callback);
2600
- return callback[kPromise$1]
2601
- }
2602
-
2603
- const mapped = new Array(operations.length);
2604
- const { keyEncoding: ke, valueEncoding: ve, ...forward } = options;
2605
-
2606
- for (let i = 0; i < operations.length; i++) {
2607
- if (typeof operations[i] !== 'object' || operations[i] === null) {
2608
- this.nextTick(callback, new TypeError('A batch operation must be an object'));
2609
- return callback[kPromise$1]
2610
- }
2611
-
2612
- const op = Object.assign({}, operations[i]);
2613
-
2614
- if (op.type !== 'put' && op.type !== 'del') {
2615
- this.nextTick(callback, new TypeError("A batch operation must have a type property that is 'put' or 'del'"));
2616
- return callback[kPromise$1]
2617
- }
2618
-
2619
- const err = this._checkKey(op.key);
2620
-
2621
- if (err) {
2622
- this.nextTick(callback, err);
2623
- return callback[kPromise$1]
2624
- }
2625
-
2626
- const db = op.sublevel != null ? op.sublevel : this;
2627
- const keyEncoding = db.keyEncoding(op.keyEncoding || ke);
2628
- const keyFormat = keyEncoding.format;
2629
-
2630
- op.key = db.prefixKey(keyEncoding.encode(op.key), keyFormat);
2631
- op.keyEncoding = keyFormat;
2632
-
2633
- if (op.type === 'put') {
2634
- const valueErr = this._checkValue(op.value);
2635
-
2636
- if (valueErr) {
2637
- this.nextTick(callback, valueErr);
2638
- return callback[kPromise$1]
2639
- }
2640
-
2641
- const valueEncoding = db.valueEncoding(op.valueEncoding || ve);
2642
-
2643
- op.value = valueEncoding.encode(op.value);
2644
- op.valueEncoding = valueEncoding.format;
2645
- }
2646
-
2647
- // Prevent double prefixing
2648
- if (db !== this) {
2649
- op.sublevel = null;
2650
- }
2651
-
2652
- mapped[i] = op;
2653
- }
2654
-
2655
- this._batch(mapped, forward, (err) => {
2656
- if (err) return callback(err)
2657
- this.emit('batch', operations);
2658
- callback();
2659
- });
2660
-
2661
- return callback[kPromise$1]
2662
- }
2663
-
2664
- _batch (operations, options, callback) {
2665
- this.nextTick(callback);
2666
- }
2667
-
2668
- sublevel (name, options) {
2669
- return this._sublevel(name, AbstractSublevel.defaults(options))
2670
- }
2671
-
2672
- _sublevel (name, options) {
2673
- return new AbstractSublevel(this, name, options)
2674
- }
2675
-
2676
- prefixKey (key, keyFormat) {
2677
- return key
2678
- }
2679
-
2680
- clear (options, callback) {
2681
- callback = getCallback(options, callback);
2682
- callback = fromCallback$1(callback, kPromise$1);
2683
- options = getOptions(options, this[kDefaultOptions].empty);
2684
-
2685
- if (this[kStatus] === 'opening') {
2686
- this.defer(() => this.clear(options, callback));
2687
- return callback[kPromise$1]
2688
- }
2689
-
2690
- if (maybeError(this, callback)) {
2691
- return callback[kPromise$1]
2692
- }
2693
-
2694
- const original = options;
2695
- const keyEncoding = this.keyEncoding(options.keyEncoding);
2696
-
2697
- options = rangeOptions(options, keyEncoding);
2698
- options.keyEncoding = keyEncoding.format;
2699
-
2700
- if (options.limit === 0) {
2701
- this.nextTick(callback);
2702
- } else {
2703
- this._clear(options, (err) => {
2704
- if (err) return callback(err)
2705
- this.emit('clear', original);
2706
- callback();
2707
- });
2708
- }
2709
-
2710
- return callback[kPromise$1]
2711
- }
2712
-
2713
- _clear (options, callback) {
2714
- this.nextTick(callback);
2715
- }
2716
-
2717
- iterator (options) {
2718
- const keyEncoding = this.keyEncoding(options && options.keyEncoding);
2719
- const valueEncoding = this.valueEncoding(options && options.valueEncoding);
2720
-
2721
- options = rangeOptions(options, keyEncoding);
2722
- options.keys = options.keys !== false;
2723
- options.values = options.values !== false;
2724
-
2725
- // We need the original encoding options in AbstractIterator in order to decode data
2726
- options[AbstractIterator$1.keyEncoding] = keyEncoding;
2727
- options[AbstractIterator$1.valueEncoding] = valueEncoding;
2728
-
2729
- // Forward encoding options to private API
2730
- options.keyEncoding = keyEncoding.format;
2731
- options.valueEncoding = valueEncoding.format;
2732
-
2733
- if (this[kStatus] === 'opening') {
2734
- return new DeferredIterator(this, options)
2735
- } else if (this[kStatus] !== 'open') {
2736
- throw new ModuleError$1('Database is not open', {
2737
- code: 'LEVEL_DATABASE_NOT_OPEN'
2738
- })
2739
- }
2740
-
2741
- return this._iterator(options)
2742
- }
2743
-
2744
- _iterator (options) {
2745
- return new AbstractIterator$1(this, options)
2746
- }
2747
-
2748
- keys (options) {
2749
- // Also include valueEncoding (though unused) because we may fallback to _iterator()
2750
- const keyEncoding = this.keyEncoding(options && options.keyEncoding);
2751
- const valueEncoding = this.valueEncoding(options && options.valueEncoding);
2752
-
2753
- options = rangeOptions(options, keyEncoding);
2754
-
2755
- // We need the original encoding options in AbstractKeyIterator in order to decode data
2756
- options[AbstractIterator$1.keyEncoding] = keyEncoding;
2757
- options[AbstractIterator$1.valueEncoding] = valueEncoding;
2758
-
2759
- // Forward encoding options to private API
2760
- options.keyEncoding = keyEncoding.format;
2761
- options.valueEncoding = valueEncoding.format;
2762
-
2763
- if (this[kStatus] === 'opening') {
2764
- return new DeferredKeyIterator(this, options)
2765
- } else if (this[kStatus] !== 'open') {
2766
- throw new ModuleError$1('Database is not open', {
2767
- code: 'LEVEL_DATABASE_NOT_OPEN'
2768
- })
2769
- }
2770
-
2771
- return this._keys(options)
2772
- }
2773
-
2774
- _keys (options) {
2775
- return new DefaultKeyIterator(this, options)
2776
- }
2777
-
2778
- values (options) {
2779
- const keyEncoding = this.keyEncoding(options && options.keyEncoding);
2780
- const valueEncoding = this.valueEncoding(options && options.valueEncoding);
2781
-
2782
- options = rangeOptions(options, keyEncoding);
2783
-
2784
- // We need the original encoding options in AbstractValueIterator in order to decode data
2785
- options[AbstractIterator$1.keyEncoding] = keyEncoding;
2786
- options[AbstractIterator$1.valueEncoding] = valueEncoding;
2787
-
2788
- // Forward encoding options to private API
2789
- options.keyEncoding = keyEncoding.format;
2790
- options.valueEncoding = valueEncoding.format;
2791
-
2792
- if (this[kStatus] === 'opening') {
2793
- return new DeferredValueIterator(this, options)
2794
- } else if (this[kStatus] !== 'open') {
2795
- throw new ModuleError$1('Database is not open', {
2796
- code: 'LEVEL_DATABASE_NOT_OPEN'
2797
- })
2798
- }
2799
-
2800
- return this._values(options)
2801
- }
2802
-
2803
- _values (options) {
2804
- return new DefaultValueIterator(this, options)
2805
- }
2806
-
2807
- defer (fn) {
2808
- if (typeof fn !== 'function') {
2809
- throw new TypeError('The first argument must be a function')
2810
- }
2811
-
2812
- this[kOperations].push(fn);
2813
- }
2814
-
2815
- [kUndefer] () {
2816
- if (this[kOperations].length === 0) {
2817
- return
2818
- }
2819
-
2820
- const operations = this[kOperations];
2821
- this[kOperations] = [];
2822
-
2823
- for (const op of operations) {
2824
- op();
2825
- }
2826
- }
2827
-
2828
- // TODO: docs and types
2829
- attachResource (resource) {
2830
- if (typeof resource !== 'object' || resource === null ||
2831
- typeof resource.close !== 'function') {
2832
- throw new TypeError('The first argument must be a resource object')
2833
- }
2834
-
2835
- this[kResources].add(resource);
2836
- }
2837
-
2838
- // TODO: docs and types
2839
- detachResource (resource) {
2840
- this[kResources].delete(resource);
2841
- }
2842
-
2843
- _chainedBatch () {
2844
- return new DefaultChainedBatch(this)
2845
- }
2846
-
2847
- _checkKey (key) {
2848
- if (key === null || key === undefined) {
2849
- return new ModuleError$1('Key cannot be null or undefined', {
2850
- code: 'LEVEL_INVALID_KEY'
2851
- })
2852
- }
2853
- }
2854
-
2855
- _checkValue (value) {
2856
- if (value === null || value === undefined) {
2857
- return new ModuleError$1('Value cannot be null or undefined', {
2858
- code: 'LEVEL_INVALID_VALUE'
2859
- })
2860
- }
2861
- }
2862
- }
2863
-
2864
- // Expose browser-compatible nextTick for dependents
2865
- // TODO: after we drop node 10, also use queueMicrotask in node
2866
- AbstractLevel$1.prototype.nextTick = requireNextTick();
2867
-
2868
- const { AbstractSublevel } = requireAbstractSublevel()({ AbstractLevel: AbstractLevel$1 });
2869
-
2870
- abstractLevel.AbstractLevel = AbstractLevel$1;
2871
- abstractLevel.AbstractSublevel = AbstractSublevel;
2872
-
2873
- const maybeError = function (db, callback) {
2874
- if (db[kStatus] !== 'open') {
2875
- db.nextTick(callback, new ModuleError$1('Database is not open', {
2876
- code: 'LEVEL_DATABASE_NOT_OPEN'
2877
- }));
2878
- return true
2879
- }
2880
-
2881
- return false
2882
- };
2883
-
2884
- const formats = function (db) {
2885
- return Object.keys(db.supports.encodings)
2886
- .filter(k => !!db.supports.encodings[k])
2887
- };
2888
-
2889
- abstractLevel$1.AbstractLevel = abstractLevel.AbstractLevel;
2890
- abstractLevel$1.AbstractSublevel = abstractLevel.AbstractSublevel;
2891
- abstractLevel$1.AbstractIterator = abstractIterator.AbstractIterator;
2892
- abstractLevel$1.AbstractKeyIterator = abstractIterator.AbstractKeyIterator;
2893
- abstractLevel$1.AbstractValueIterator = abstractIterator.AbstractValueIterator;
2894
- abstractLevel$1.AbstractChainedBatch = abstractChainedBatch.AbstractChainedBatch;
2895
-
2896
- /*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
2897
-
2898
- let promise;
2899
-
2900
- var queueMicrotask_1 = typeof queueMicrotask === 'function'
2901
- ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal)
2902
- // reuse resolved promise, and allocate it lazily
2903
- : cb => (promise || (promise = Promise.resolve()))
2904
- .then(cb)
2905
- .catch(err => setTimeout(() => { throw err }, 0));
2906
-
2907
- /*! run-parallel-limit. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
2908
-
2909
- var runParallelLimit_1 = runParallelLimit;
2910
-
2911
- const queueMicrotask$1 = queueMicrotask_1;
2912
-
2913
- function runParallelLimit (tasks, limit, cb) {
2914
- if (typeof limit !== 'number') throw new Error('second argument must be a Number')
2915
- let results, len, pending, keys, isErrored;
2916
- let isSync = true;
2917
- let next;
2918
-
2919
- if (Array.isArray(tasks)) {
2920
- results = [];
2921
- pending = len = tasks.length;
2922
- } else {
2923
- keys = Object.keys(tasks);
2924
- results = {};
2925
- pending = len = keys.length;
2926
- }
2927
-
2928
- function done (err) {
2929
- function end () {
2930
- if (cb) cb(err, results);
2931
- cb = null;
2932
- }
2933
- if (isSync) queueMicrotask$1(end);
2934
- else end();
2935
- }
2936
-
2937
- function each (i, err, result) {
2938
- results[i] = result;
2939
- if (err) isErrored = true;
2940
- if (--pending === 0 || err) {
2941
- done(err);
2942
- } else if (!isErrored && next < len) {
2943
- let key;
2944
- if (keys) {
2945
- key = keys[next];
2946
- next += 1;
2947
- tasks[key](function (err, result) { each(key, err, result); });
2948
- } else {
2949
- key = next;
2950
- next += 1;
2951
- tasks[key](function (err, result) { each(key, err, result); });
2952
- }
2953
- }
2954
- }
2955
-
2956
- next = limit;
2957
- if (!pending) {
2958
- // empty
2959
- done(null);
2960
- } else if (keys) {
2961
- // object
2962
- keys.some(function (key, i) {
2963
- tasks[key](function (err, result) { each(key, err, result); });
2964
- if (i === limit - 1) return true // early return
2965
- return false
2966
- });
2967
- } else {
2968
- // array
2969
- tasks.some(function (task, i) {
2970
- task(function (err, result) { each(i, err, result); });
2971
- if (i === limit - 1) return true // early return
2972
- return false
2973
- });
2974
- }
2975
-
2976
- isSync = false;
2977
- }
2978
-
2979
- var iterator = {};
2980
-
2981
- /* global IDBKeyRange */
2982
-
2983
- var keyRange = function createKeyRange (options) {
2984
- const lower = options.gte !== undefined ? options.gte : options.gt !== undefined ? options.gt : undefined;
2985
- const upper = options.lte !== undefined ? options.lte : options.lt !== undefined ? options.lt : undefined;
2986
- const lowerExclusive = options.gte === undefined;
2987
- const upperExclusive = options.lte === undefined;
2988
-
2989
- if (lower !== undefined && upper !== undefined) {
2990
- return IDBKeyRange.bound(lower, upper, lowerExclusive, upperExclusive)
2991
- } else if (lower !== undefined) {
2992
- return IDBKeyRange.lowerBound(lower, lowerExclusive)
2993
- } else if (upper !== undefined) {
2994
- return IDBKeyRange.upperBound(upper, upperExclusive)
2995
- } else {
2996
- return null
2997
- }
2998
- };
2999
-
3000
- const textEncoder = new TextEncoder();
3001
-
3002
- var deserialize$2 = function (data) {
3003
- if (data instanceof Uint8Array) {
3004
- return data
3005
- } else if (data instanceof ArrayBuffer) {
3006
- return new Uint8Array(data)
3007
- } else {
3008
- // Non-binary data stored with an old version (level-js < 5.0.0)
3009
- return textEncoder.encode(data)
3010
- }
3011
- };
3012
-
3013
- const { AbstractIterator } = abstractLevel$1;
3014
- const createKeyRange$1 = keyRange;
3015
- const deserialize$1 = deserialize$2;
3016
-
3017
- const kCache = Symbol('cache');
3018
- const kFinished = Symbol('finished');
3019
- const kOptions = Symbol('options');
3020
- const kCurrentOptions = Symbol('currentOptions');
3021
- const kPosition = Symbol('position');
3022
- const kLocation$1 = Symbol('location');
3023
- const kFirst = Symbol('first');
3024
- const emptyOptions = {};
3025
-
3026
- class Iterator$1 extends AbstractIterator {
3027
- constructor (db, location, options) {
3028
- super(db, options);
3029
-
3030
- this[kCache] = [];
3031
- this[kFinished] = this.limit === 0;
3032
- this[kOptions] = options;
3033
- this[kCurrentOptions] = { ...options };
3034
- this[kPosition] = undefined;
3035
- this[kLocation$1] = location;
3036
- this[kFirst] = true;
3037
- }
3038
-
3039
- // Note: if called by _all() then size can be Infinity. This is an internal
3040
- // detail; by design AbstractIterator.nextv() does not support Infinity.
3041
- _nextv (size, options, callback) {
3042
- this[kFirst] = false;
3043
-
3044
- if (this[kFinished]) {
3045
- return this.nextTick(callback, null, [])
3046
- } else if (this[kCache].length > 0) {
3047
- // TODO: mixing next and nextv is not covered by test suite
3048
- size = Math.min(size, this[kCache].length);
3049
- return this.nextTick(callback, null, this[kCache].splice(0, size))
3050
- }
3051
-
3052
- // Adjust range by what we already visited
3053
- if (this[kPosition] !== undefined) {
3054
- if (this[kOptions].reverse) {
3055
- this[kCurrentOptions].lt = this[kPosition];
3056
- this[kCurrentOptions].lte = undefined;
3057
- } else {
3058
- this[kCurrentOptions].gt = this[kPosition];
3059
- this[kCurrentOptions].gte = undefined;
3060
- }
3061
- }
3062
-
3063
- let keyRange;
3064
-
3065
- try {
3066
- keyRange = createKeyRange$1(this[kCurrentOptions]);
3067
- } catch (_) {
3068
- // The lower key is greater than the upper key.
3069
- // IndexedDB throws an error, but we'll just return 0 results.
3070
- this[kFinished] = true;
3071
- return this.nextTick(callback, null, [])
3072
- }
3073
-
3074
- const transaction = this.db.db.transaction([this[kLocation$1]], 'readonly');
3075
- const store = transaction.objectStore(this[kLocation$1]);
3076
- const entries = [];
3077
-
3078
- if (!this[kOptions].reverse) {
3079
- let keys;
3080
- let values;
3081
-
3082
- const complete = () => {
3083
- // Wait for both requests to complete
3084
- if (keys === undefined || values === undefined) return
3085
-
3086
- const length = Math.max(keys.length, values.length);
3087
-
3088
- if (length === 0 || size === Infinity) {
3089
- this[kFinished] = true;
3090
- } else {
3091
- this[kPosition] = keys[length - 1];
3092
- }
3093
-
3094
- // Resize
3095
- entries.length = length;
3096
-
3097
- // Merge keys and values
3098
- for (let i = 0; i < length; i++) {
3099
- const key = keys[i];
3100
- const value = values[i];
3101
-
3102
- entries[i] = [
3103
- this[kOptions].keys && key !== undefined ? deserialize$1(key) : undefined,
3104
- this[kOptions].values && value !== undefined ? deserialize$1(value) : undefined
3105
- ];
3106
- }
3107
-
3108
- maybeCommit(transaction);
3109
- };
3110
-
3111
- // If keys were not requested and size is Infinity, we don't have to keep
3112
- // track of position and can thus skip getting keys.
3113
- if (this[kOptions].keys || size < Infinity) {
3114
- store.getAllKeys(keyRange, size < Infinity ? size : undefined).onsuccess = (ev) => {
3115
- keys = ev.target.result;
3116
- complete();
3117
- };
3118
- } else {
3119
- keys = [];
3120
- this.nextTick(complete);
3121
- }
3122
-
3123
- if (this[kOptions].values) {
3124
- store.getAll(keyRange, size < Infinity ? size : undefined).onsuccess = (ev) => {
3125
- values = ev.target.result;
3126
- complete();
3127
- };
3128
- } else {
3129
- values = [];
3130
- this.nextTick(complete);
3131
- }
3132
- } else {
3133
- // Can't use getAll() in reverse, so use a slower cursor that yields one item at a time
3134
- // TODO: test if all target browsers support openKeyCursor
3135
- const method = !this[kOptions].values && store.openKeyCursor ? 'openKeyCursor' : 'openCursor';
3136
-
3137
- store[method](keyRange, 'prev').onsuccess = (ev) => {
3138
- const cursor = ev.target.result;
3139
-
3140
- if (cursor) {
3141
- const { key, value } = cursor;
3142
- this[kPosition] = key;
3143
-
3144
- entries.push([
3145
- this[kOptions].keys && key !== undefined ? deserialize$1(key) : undefined,
3146
- this[kOptions].values && value !== undefined ? deserialize$1(value) : undefined
3147
- ]);
3148
-
3149
- if (entries.length < size) {
3150
- cursor.continue();
3151
- } else {
3152
- maybeCommit(transaction);
3153
- }
3154
- } else {
3155
- this[kFinished] = true;
3156
- }
3157
- };
3158
- }
3159
-
3160
- // If an error occurs (on the request), the transaction will abort.
3161
- transaction.onabort = () => {
3162
- callback(transaction.error || new Error('aborted by user'));
3163
- callback = null;
3164
- };
3165
-
3166
- transaction.oncomplete = () => {
3167
- callback(null, entries);
3168
- callback = null;
3169
- };
3170
- }
3171
-
3172
- _next (callback) {
3173
- if (this[kCache].length > 0) {
3174
- const [key, value] = this[kCache].shift();
3175
- this.nextTick(callback, null, key, value);
3176
- } else if (this[kFinished]) {
3177
- this.nextTick(callback);
3178
- } else {
3179
- let size = Math.min(100, this.limit - this.count);
3180
-
3181
- if (this[kFirst]) {
3182
- // It's common to only want one entry initially or after a seek()
3183
- this[kFirst] = false;
3184
- size = 1;
3185
- }
3186
-
3187
- this._nextv(size, emptyOptions, (err, entries) => {
3188
- if (err) return callback(err)
3189
- this[kCache] = entries;
3190
- this._next(callback);
3191
- });
3192
- }
3193
- }
3194
-
3195
- _all (options, callback) {
3196
- this[kFirst] = false;
3197
-
3198
- // TODO: mixing next and all is not covered by test suite
3199
- const cache = this[kCache].splice(0, this[kCache].length);
3200
- const size = this.limit - this.count - cache.length;
3201
-
3202
- if (size <= 0) {
3203
- return this.nextTick(callback, null, cache)
3204
- }
3205
-
3206
- this._nextv(size, emptyOptions, (err, entries) => {
3207
- if (err) return callback(err)
3208
- if (cache.length > 0) entries = cache.concat(entries);
3209
- callback(null, entries);
3210
- });
3211
- }
3212
-
3213
- _seek (target, options) {
3214
- this[kFirst] = true;
3215
- this[kCache] = [];
3216
- this[kFinished] = false;
3217
- this[kPosition] = undefined;
3218
-
3219
- // TODO: not covered by test suite
3220
- this[kCurrentOptions] = { ...this[kOptions] };
3221
-
3222
- let keyRange;
3223
-
3224
- try {
3225
- keyRange = createKeyRange$1(this[kOptions]);
3226
- } catch (_) {
3227
- this[kFinished] = true;
3228
- return
3229
- }
3230
-
3231
- if (keyRange !== null && !keyRange.includes(target)) {
3232
- this[kFinished] = true;
3233
- } else if (this[kOptions].reverse) {
3234
- this[kCurrentOptions].lte = target;
3235
- } else {
3236
- this[kCurrentOptions].gte = target;
3237
- }
3238
- }
3239
- }
3240
-
3241
- iterator.Iterator = Iterator$1;
3242
-
3243
- function maybeCommit (transaction) {
3244
- // Commit (meaning close) now instead of waiting for auto-commit
3245
- if (typeof transaction.commit === 'function') {
3246
- transaction.commit();
3247
- }
3248
- }
3249
-
3250
- var clear$1 = function clear (db, location, keyRange, options, callback) {
3251
- if (options.limit === 0) return db.nextTick(callback)
3252
-
3253
- const transaction = db.db.transaction([location], 'readwrite');
3254
- const store = transaction.objectStore(location);
3255
- let count = 0;
3256
-
3257
- transaction.oncomplete = function () {
3258
- callback();
3259
- };
3260
-
3261
- transaction.onabort = function () {
3262
- callback(transaction.error || new Error('aborted by user'));
3263
- };
3264
-
3265
- // A key cursor is faster (skips reading values) but not supported by IE
3266
- // TODO: we no longer support IE. Test others
3267
- const method = store.openKeyCursor ? 'openKeyCursor' : 'openCursor';
3268
- const direction = options.reverse ? 'prev' : 'next';
3269
-
3270
- store[method](keyRange, direction).onsuccess = function (ev) {
3271
- const cursor = ev.target.result;
3272
-
3273
- if (cursor) {
3274
- // Wait for a request to complete before continuing, saving CPU.
3275
- store.delete(cursor.key).onsuccess = function () {
3276
- if (options.limit <= 0 || ++count < options.limit) {
3277
- cursor.continue();
3278
- }
3279
- };
3280
- }
3281
- };
3282
- };
3283
-
3284
- /* global indexedDB */
3285
-
3286
- const { AbstractLevel } = abstractLevel$1;
3287
- const ModuleError = moduleError;
3288
- const parallel = runParallelLimit_1;
3289
- const { fromCallback } = catering;
3290
- const { Iterator } = iterator;
3291
- const deserialize = deserialize$2;
3292
- const clear = clear$1;
3293
- const createKeyRange = keyRange;
3294
-
3295
- // Keep as-is for compatibility with existing level-js databases
3296
- const DEFAULT_PREFIX = 'level-js-';
3297
-
3298
- const kIDB = Symbol('idb');
3299
- const kNamePrefix = Symbol('namePrefix');
3300
- const kLocation = Symbol('location');
3301
- const kVersion = Symbol('version');
3302
- const kStore = Symbol('store');
3303
- const kOnComplete = Symbol('onComplete');
3304
- const kPromise = Symbol('promise');
3305
-
3306
- class BrowserLevel extends AbstractLevel {
3307
- constructor (location, options, _) {
3308
- // To help migrating to abstract-level
3309
- if (typeof options === 'function' || typeof _ === 'function') {
3310
- throw new ModuleError('The levelup-style callback argument has been removed', {
3311
- code: 'LEVEL_LEGACY'
3312
- })
3313
- }
3314
-
3315
- const { prefix, version, ...forward } = options || {};
3316
-
3317
- super({
3318
- encodings: { view: true },
3319
- snapshots: false,
3320
- createIfMissing: false,
3321
- errorIfExists: false,
3322
- seek: true
3323
- }, forward);
3324
-
3325
- if (typeof location !== 'string') {
3326
- throw new Error('constructor requires a location string argument')
3327
- }
3328
-
3329
- // TODO (next major): remove default prefix
3330
- this[kLocation] = location;
3331
- this[kNamePrefix] = prefix == null ? DEFAULT_PREFIX : prefix;
3332
- this[kVersion] = parseInt(version || 1, 10);
3333
- this[kIDB] = null;
3334
- }
3335
-
3336
- get location () {
3337
- return this[kLocation]
3338
- }
3339
-
3340
- get namePrefix () {
3341
- return this[kNamePrefix]
3342
- }
3343
-
3344
- get version () {
3345
- return this[kVersion]
3346
- }
3347
-
3348
- // Exposed for backwards compat and unit tests
3349
- get db () {
3350
- return this[kIDB]
3351
- }
3352
-
3353
- get type () {
3354
- return 'browser-level'
3355
- }
3356
-
3357
- _open (options, callback) {
3358
- const req = indexedDB.open(this[kNamePrefix] + this[kLocation], this[kVersion]);
3359
-
3360
- req.onerror = function () {
3361
- callback(req.error || new Error('unknown error'));
3362
- };
3363
-
3364
- req.onsuccess = () => {
3365
- this[kIDB] = req.result;
3366
- callback();
3367
- };
3368
-
3369
- req.onupgradeneeded = (ev) => {
3370
- const db = ev.target.result;
3371
-
3372
- if (!db.objectStoreNames.contains(this[kLocation])) {
3373
- db.createObjectStore(this[kLocation]);
3374
- }
3375
- };
3376
- }
3377
-
3378
- [kStore] (mode) {
3379
- const transaction = this[kIDB].transaction([this[kLocation]], mode);
3380
- return transaction.objectStore(this[kLocation])
3381
- }
3382
-
3383
- [kOnComplete] (request, callback) {
3384
- const transaction = request.transaction;
3385
-
3386
- // Take advantage of the fact that a non-canceled request error aborts
3387
- // the transaction. I.e. no need to listen for "request.onerror".
3388
- transaction.onabort = function () {
3389
- callback(transaction.error || new Error('aborted by user'));
3390
- };
3391
-
3392
- transaction.oncomplete = function () {
3393
- callback(null, request.result);
3394
- };
3395
- }
3396
-
3397
- _get (key, options, callback) {
3398
- const store = this[kStore]('readonly');
3399
- let req;
3400
-
3401
- try {
3402
- req = store.get(key);
3403
- } catch (err) {
3404
- return this.nextTick(callback, err)
3405
- }
3406
-
3407
- this[kOnComplete](req, function (err, value) {
3408
- if (err) return callback(err)
3409
-
3410
- if (value === undefined) {
3411
- return callback(new ModuleError('Entry not found', {
3412
- code: 'LEVEL_NOT_FOUND'
3413
- }))
3414
- }
3415
-
3416
- callback(null, deserialize(value));
3417
- });
3418
- }
3419
-
3420
- _getMany (keys, options, callback) {
3421
- const store = this[kStore]('readonly');
3422
- const tasks = keys.map((key) => (next) => {
3423
- let request;
3424
-
3425
- try {
3426
- request = store.get(key);
3427
- } catch (err) {
3428
- return next(err)
3429
- }
3430
-
3431
- request.onsuccess = () => {
3432
- const value = request.result;
3433
- next(null, value === undefined ? value : deserialize(value));
3434
- };
3435
-
3436
- request.onerror = (ev) => {
3437
- ev.stopPropagation();
3438
- next(request.error);
3439
- };
3440
- });
3441
-
3442
- parallel(tasks, 16, callback);
3443
- }
3444
-
3445
- _del (key, options, callback) {
3446
- const store = this[kStore]('readwrite');
3447
- let req;
3448
-
3449
- try {
3450
- req = store.delete(key);
3451
- } catch (err) {
3452
- return this.nextTick(callback, err)
3453
- }
3454
-
3455
- this[kOnComplete](req, callback);
3456
- }
3457
-
3458
- _put (key, value, options, callback) {
3459
- const store = this[kStore]('readwrite');
3460
- let req;
3461
-
3462
- try {
3463
- // Will throw a DataError or DataCloneError if the environment
3464
- // does not support serializing the key or value respectively.
3465
- req = store.put(value, key);
3466
- } catch (err) {
3467
- return this.nextTick(callback, err)
3468
- }
3469
-
3470
- this[kOnComplete](req, callback);
3471
- }
3472
-
3473
- // TODO: implement key and value iterators
3474
- _iterator (options) {
3475
- return new Iterator(this, this[kLocation], options)
3476
- }
3477
-
3478
- _batch (operations, options, callback) {
3479
- const store = this[kStore]('readwrite');
3480
- const transaction = store.transaction;
3481
- let index = 0;
3482
- let error;
3483
-
3484
- transaction.onabort = function () {
3485
- callback(error || transaction.error || new Error('aborted by user'));
3486
- };
3487
-
3488
- transaction.oncomplete = function () {
3489
- callback();
3490
- };
3491
-
3492
- // Wait for a request to complete before making the next, saving CPU.
3493
- function loop () {
3494
- const op = operations[index++];
3495
- const key = op.key;
3496
-
3497
- let req;
3498
-
3499
- try {
3500
- req = op.type === 'del' ? store.delete(key) : store.put(op.value, key);
3501
- } catch (err) {
3502
- error = err;
3503
- transaction.abort();
3504
- return
3505
- }
3506
-
3507
- if (index < operations.length) {
3508
- req.onsuccess = loop;
3509
- } else if (typeof transaction.commit === 'function') {
3510
- // Commit now instead of waiting for auto-commit
3511
- transaction.commit();
3512
- }
3513
- }
3514
-
3515
- loop();
3516
- }
3517
-
3518
- _clear (options, callback) {
3519
- let keyRange;
3520
- let req;
3521
-
3522
- try {
3523
- keyRange = createKeyRange(options);
3524
- } catch (e) {
3525
- // The lower key is greater than the upper key.
3526
- // IndexedDB throws an error, but we'll just do nothing.
3527
- return this.nextTick(callback)
3528
- }
3529
-
3530
- if (options.limit >= 0) {
3531
- // IDBObjectStore#delete(range) doesn't have such an option.
3532
- // Fall back to cursor-based implementation.
3533
- return clear(this, this[kLocation], keyRange, options, callback)
3534
- }
3535
-
3536
- try {
3537
- const store = this[kStore]('readwrite');
3538
- req = keyRange ? store.delete(keyRange) : store.clear();
3539
- } catch (err) {
3540
- return this.nextTick(callback, err)
3541
- }
3542
-
3543
- this[kOnComplete](req, callback);
3544
- }
3545
-
3546
- _close (callback) {
3547
- this[kIDB].close();
3548
- this.nextTick(callback);
3549
- }
3550
- }
3551
-
3552
- BrowserLevel.destroy = function (location, prefix, callback) {
3553
- if (typeof prefix === 'function') {
3554
- callback = prefix;
3555
- prefix = DEFAULT_PREFIX;
3556
- }
3557
-
3558
- callback = fromCallback(callback, kPromise);
3559
- const request = indexedDB.deleteDatabase(prefix + location);
3560
-
3561
- request.onsuccess = function () {
3562
- callback();
3563
- };
3564
-
3565
- request.onerror = function (err) {
3566
- callback(err);
3567
- };
3568
-
3569
- return callback[kPromise]
3570
- };
3571
-
3572
- var BrowserLevel_1 = BrowserLevel;
3573
-
3574
- class Store {
3575
- constructor(name = 'storage', root, version = 'v1.0.0') {
3576
- this.name = name;
3577
- this.root = root;
3578
- this.version = version;
3579
-
3580
- this.db = new BrowserLevel_1(
3581
- this.name,
3582
- { valueEncoding: 'view'}
3583
- );
3584
- }
3585
-
3586
- toKeyPath(key) {
3587
- return key ? key.toString('base32') : key
3588
- }
3589
-
3590
- toKeyValue(value) {
3591
- return value.uint8Array
3592
- }
3593
-
3594
- async get(key) {
3595
- return this.db.get(this.toKeyPath(key))
3596
- }
3597
-
3598
- async put(key, value) {
3599
- return this.db.put(this.toKeyPath(key), this.toKeyValue(value))
3600
- }
3601
-
3602
- async delete(key) {
3603
- return this.db.del(this.toKeyPath(key))
3604
- }
3605
-
3606
- async clear() {
3607
- return this.db.clear()
3608
- }
3609
-
3610
- async values(limit = -1) {
3611
- const values = [];
3612
- for await (const value of this.db.values({limit})) {
3613
- values.push(value);
3614
- }
3615
- return values
3616
- }
3617
-
3618
- async keys(limit = -1) {
3619
- const keys = [];
3620
- for await (const key of this.db.keys({limit})) {
3621
- keys.push(key);
3622
- }
3623
- return keys
3624
- }
3625
-
3626
- }
3627
-
3628
- class LeofcoinStorage {
3629
-
3630
- constructor(name = 'storage', root = '.leofcoin') {
3631
- this.name = name;
3632
- this.db = new Store(name, root);
3633
- }
3634
-
3635
- async get(key) {
3636
- if (!key) return this.query()
3637
- if (typeof key === 'object') return this.many('get', key);
3638
- return this.db.get(new KeyPath(key))
3639
- }
3640
-
3641
- /**
3642
- *
3643
- * @param {*} key
3644
- * @param {*} value
3645
- * @returns Promise
3646
- */
3647
- put(key, value) {
3648
- if (typeof key === 'object') return this.many('put', key);
3649
- return this.db.put(new KeyPath(key), new KeyValue(value));
3650
- }
3651
-
3652
- async has(key) {
3653
- if (typeof key === 'object') return this.many('has', key);
3654
-
3655
- try {
3656
- const has = await this.db.get(new KeyPath(key));
3657
-
3658
- return Boolean(has);
3659
- } catch (e) {
3660
- return false
3661
- }
3662
- }
3663
-
3664
- async delete(key) {
3665
- return this.db.delete(new KeyPath(key))
3666
- }
3667
-
3668
- keys(limit = -1) {
3669
- return this.db.keys({limit})
3670
- }
3671
-
3672
- async #queryJob(key) {
3673
- const value = await this.db.get(key);
3674
- return { key, value }
3675
- }
3676
-
3677
- async query() {
3678
- const keys = await this.keys();
3679
- let promises = [];
3680
- for (const key of keys) {
3681
- promises.push(this.#queryJob(key));
3682
- }
3683
- return Promise.all(promises)
3684
- }
3685
-
3686
- async values(limit = -1) {
3687
- return this.db.values({limit})
3688
- }
3689
-
3690
- async many(type, _value) {
3691
- const jobs = [];
3692
-
3693
- for (const key of Object.keys(_value)) {
3694
- jobs.push(this[type](key, _value[key]));
3695
- }
3696
-
3697
- return Promise.all(jobs)
3698
- }
3699
-
3700
- async length() {
3701
- const keys = await this.keys();
3702
- return keys.length
3703
- }
3704
-
3705
- async size() {
3706
- let size = 0;
3707
- const query = await this.query();
3708
- for (const item of query) {
3709
- size += item.value.length;
3710
- }
3711
- return size
3712
- }
3713
-
3714
- async clear() {
3715
- return this.db.clear()
3716
- }
3717
-
3718
- }
3719
-
3720
-
3721
-
3722
-
3723
- /***/ })
3724
-
3725
- }]);