@ohos-ports/level-js 0.0.0-stage → 6.1.0-beta.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.
package/README.md CHANGED
@@ -1,3 +1,159 @@
1
- # Temporary Holding Version
1
+ # level-js
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > An [`abstract-leveldown`][abstract-leveldown] compliant store on top of [IndexedDB][indexeddb].
4
+
5
+ [![level badge][level-badge]][awesome]
6
+ [![npm](https://img.shields.io/npm/v/level-js.svg)](https://www.npmjs.com/package/level-js)
7
+ [![Test](https://img.shields.io/github/workflow/status/Level/level-js/Test?label=test)](https://github.com/Level/level-js/actions/workflows/test.yml)
8
+ [![Coverage](https://img.shields.io/codecov/c/github/Level/level-js?label=&logo=codecov&logoColor=fff)](https://codecov.io/gh/Level/level-js)
9
+ [![Standard](https://img.shields.io/badge/standard-informational?logo=javascript&logoColor=fff)](https://standardjs.com)
10
+ [![Common Changelog](https://common-changelog.org/badge.svg)](https://common-changelog.org)
11
+ [![Donate](https://img.shields.io/badge/donate-orange?logo=open-collective&logoColor=fff)](https://opencollective.com/level)
12
+
13
+ ## Table of Contents
14
+
15
+ <details><summary>Click to expand</summary>
16
+
17
+ - [Background](#background)
18
+ - [Example](#example)
19
+ - [Browser Support](#browser-support)
20
+ - [Type Support](#type-support)
21
+ - [Install](#install)
22
+ - [API](#api)
23
+ - [`db = leveljs(location[, options])`](#db--leveljslocation-options)
24
+ - [`options`](#options)
25
+ - [Big Thanks](#big-thanks)
26
+ - [Contributing](#contributing)
27
+ - [Donate](#donate)
28
+ - [License](#license)
29
+
30
+ </details>
31
+
32
+ ## Background
33
+
34
+ Here are the goals of `level-js`:
35
+
36
+ - Store large amounts of data in modern browsers
37
+ - Pass the full [`abstract-leveldown`][abstract-leveldown] test suite
38
+ - Support string and [`Buffer`][buffer] keys and values
39
+ - Be as fast as possible
40
+ - ~~Sync with [multilevel](https://github.com/juliangruber/multilevel) over ASCII or binary transports.~~
41
+
42
+ Being `abstract-leveldown` compliant means you can use many of the [Level modules][awesome] on top of this library.
43
+
44
+ ## Example
45
+
46
+ **If you are upgrading:** please see [UPGRADING.md](UPGRADING.md).
47
+
48
+ ```js
49
+ const levelup = require('levelup')
50
+ const leveljs = require('level-js')
51
+ const db = levelup(leveljs('bigdata'))
52
+
53
+ db.put('hello', Buffer.from('world'), function (err) {
54
+ if (err) throw err
55
+
56
+ db.get('hello', function (err, value) {
57
+ if (err) throw err
58
+
59
+ console.log(value.toString()) // 'world'
60
+ })
61
+ })
62
+ ```
63
+
64
+ With `async/await`:
65
+
66
+ ```js
67
+ const levelup = require('levelup')
68
+ const leveljs = require('level-js')
69
+ const db = levelup(leveljs('bigdata'))
70
+
71
+ await db.put('hello', Buffer.from('world'))
72
+ const value = await db.get('hello')
73
+ ```
74
+
75
+ ## Browser Support
76
+
77
+ [![Sauce Test Status](https://app.saucelabs.com/browser-matrix/level-js.svg)](https://app.saucelabs.com/u/level-js)
78
+
79
+ ## Type Support
80
+
81
+ Keys and values can be a string or [`Buffer`][buffer]. Any other type will be irreversibly stringified. The only exceptions are `null` and `undefined`. Keys and values of that type are rejected.
82
+
83
+ In order to sort string and Buffer keys the same way, for compatibility with `leveldown` and the larger ecosystem, `level-js` internally converts keys and values to binary before passing them to IndexedDB.
84
+
85
+ If you desire non-destructive encoding (e.g. to store and retrieve numbers as-is), wrap `level-js` with [`encoding-down`][encoding-down]. Alternatively install [`level`][level] which conveniently bundles [`levelup`][levelup], `level-js` and `encoding-down`. Such an approach is also recommended if you want to achieve universal (isomorphic) behavior. For example, you could have [`leveldown`][leveldown] in a backend and `level-js` in the frontend. The `level` package does exactly that.
86
+
87
+ When getting or iterating keys and values, regardless of the type with which they were stored, keys and values will return as a Buffer unless the `asBuffer`, `keyAsBuffer` or `valueAsBuffer` options are set, in which case strings are returned. Setting these options is not needed when `level-js` is wrapped with `encoding-down`, which determines the optimal return type by the chosen encoding.
88
+
89
+ ```js
90
+ db.get('key', { asBuffer: false })
91
+ db.iterator({ keyAsBuffer: false, valueAsBuffer: false })
92
+ ```
93
+
94
+ ## Install
95
+
96
+ With [npm](https://npmjs.org) do:
97
+
98
+ ```bash
99
+ npm install level-js
100
+ ```
101
+
102
+ Not to be confused with [leveljs](https://www.npmjs.com/package/leveljs).
103
+
104
+ This library is best used with [browserify](http://browserify.org).
105
+
106
+ ## API
107
+
108
+ ### `db = leveljs(location[, options])`
109
+
110
+ Returns a new `leveljs` instance. `location` is the string name of the [`IDBDatabase`](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase) to be opened, as well as the object store within that database. The database name will be prefixed with `options.prefix`.
111
+
112
+ #### `options`
113
+
114
+ The optional `options` argument may contain:
115
+
116
+ - `prefix` _(string, default: `'level-js-'`)_: Prefix for `IDBDatabase` name.
117
+ - `version` _(string | number, default: `1`)_: The version to open the database with.
118
+
119
+ See [`IDBFactory#open`](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory/open) for more details.
120
+
121
+ ## Big Thanks
122
+
123
+ Cross-browser Testing Platform and Open Source ♥ Provided by [Sauce Labs](https://saucelabs.com).
124
+
125
+ [![Sauce Labs logo](./sauce-labs.svg)](https://saucelabs.com)
126
+
127
+ ## Contributing
128
+
129
+ [`Level/level-js`](https://github.com/Level/level-js) is an **OPEN Open Source Project**. This means that:
130
+
131
+ > Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project.
132
+
133
+ See the [Contribution Guide](https://github.com/Level/community/blob/master/CONTRIBUTING.md) for more details.
134
+
135
+ ## Donate
136
+
137
+ Support us with a monthly donation on [Open Collective](https://opencollective.com/level) and help us continue our work.
138
+
139
+ ## License
140
+
141
+ [MIT](LICENSE)
142
+
143
+ [level-badge]: https://leveljs.org/img/badge.svg
144
+
145
+ [indexeddb]: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
146
+
147
+ [buffer]: https://nodejs.org/api/buffer.html
148
+
149
+ [awesome]: https://github.com/Level/awesome
150
+
151
+ [abstract-leveldown]: https://github.com/Level/abstract-leveldown
152
+
153
+ [levelup]: https://github.com/Level/levelup
154
+
155
+ [leveldown]: https://github.com/Level/leveldown
156
+
157
+ [level]: https://github.com/Level/level
158
+
159
+ [encoding-down]: https://github.com/Level/encoding-down
package/UPGRADING.md ADDED
@@ -0,0 +1,183 @@
1
+ # Upgrade Guide
2
+
3
+ This document describes breaking changes and how to upgrade. For a complete list of changes including minor and patch releases, please refer to the [changelog][changelog].
4
+
5
+ ## 6.0.0
6
+
7
+ Legacy range options have been removed ([Level/community#86](https://github.com/Level/community/issues/86)). If you previously did:
8
+
9
+ ```js
10
+ db.iterator({ start: 'a', end: 'z' })
11
+ ```
12
+
13
+ An error would now be thrown and you must instead do:
14
+
15
+ ```js
16
+ db.iterator({ gte: 'a', lte: 'z' })
17
+ ```
18
+
19
+ This release also drops support of legacy runtime environments ([Level/community#98](https://github.com/Level/community/issues/98)):
20
+
21
+ - Internet Explorer 11
22
+ - Safari 9-11.
23
+
24
+ Lastly, and less likely to be a breaking change, the [`immediate`](https://github.com/calvinmetcalf/immediate) browser shim for `process.nextTick()` has been replaced with the smaller [`queue-microtask`](https://github.com/feross/queue-microtask).
25
+
26
+ ## 5.0.0
27
+
28
+ Support of keys & values other than strings and Buffers has been dropped. Internally `level-js` now stores keys & values as binary which solves a number of compatibility issues ([Level/memdown#186](https://github.com/Level/memdown/issues/186)). If you pass in a key or value that isn't a string or Buffer, it will be irreversibly stringified.
29
+
30
+ Existing IndexedDB databases created with `level-js@4` can be read only if they used binary keys and string or binary values. Other types will come out stringified, and string keys will sort incorrectly. Use the included `upgrade()` utility to convert stored data to binary (in so far the environment supports it):
31
+
32
+ ```js
33
+ var leveljs = require('level-js')
34
+ var db = leveljs('my-db')
35
+
36
+ db.open(function (err) {
37
+ if (err) throw err
38
+
39
+ db.upgrade(function (err) {
40
+ if (err) throw err
41
+ })
42
+ })
43
+ ```
44
+
45
+ Or with (the upcoming release of) `level`:
46
+
47
+ ```js
48
+ var level = require('level')
49
+ var reachdown = require('reachdown')
50
+ var db = level('my-db')
51
+
52
+ db.open(function (err) {
53
+ if (err) throw err
54
+
55
+ reachdown(db, 'level-js').upgrade(function (err) {
56
+ if (err) throw err
57
+ })
58
+ })
59
+ ```
60
+
61
+ ## 4.0.0
62
+
63
+ This is an upgrade to `abstract-leveldown@6` which solves long-standing issues around serialization and type support.
64
+
65
+ ### Range options are now serialized
66
+
67
+ Previously, range options like `lt` were passed through as-is by `abstract-leveldown`, unlike keys. For `level-js` it means that Buffers and arrays, if not supported by the environment (e.g. Microsoft Edge), will be stringified.
68
+
69
+ ### The rules for range options have been relaxed
70
+
71
+ Because `null`, `undefined`, zero-length strings and zero-length buffers are significant types in encodings like `bytewise` and `charwise`, they became valid as range options in `abstract-leveldown`. This means `db.iterator({ gt: undefined })` is not the same as `db.iterator({})`.
72
+
73
+ In the case of `level-js`, when used by itself, the aforementioned change means that `db.iterator({ gt: undefined })` will throw an error as `undefined` is not a valid IndexedDB key type. On the other hand `db.iterator({ gt: '' })` is valid and thus now supported. For details on sort order (which is richer than in `leveldown`) please see [the readme](README.md).
74
+
75
+ ### Nullish values are rejected
76
+
77
+ In addition to rejecting `null` and `undefined` as _keys_, `abstract-leveldown` now also rejects these types as _values_, due to preexisting significance in streams and iterators.
78
+
79
+ ### Zero-length array keys are rejected
80
+
81
+ Though this was already the case (both in IndexedDB and `abstract-leveldown`), `abstract-leveldown` has replaced the behavior with an explicit `Array.isArray()` check and a new error message.
82
+
83
+ ### Boolean and `NaN` keys (as well as range options) are rejected
84
+
85
+ Previously, for compliance with `abstract-leveldown` tests that have since been removed, they were stringified. As of `level-js@4` they are rejected (by IndexedDB).
86
+
87
+ ### Added mobile browser support
88
+
89
+ iPhone and Android `latest` are now officially supported. At the time of writing that's iPhone 12.0 and Android 7.1 (note that's Chrome for Android, not the old stock browser). Older versions (iPhone 10+ and Android 6+) did pass our tests but are not included in the test matrix going forward. Feel free to open an issue if you need/want these versions to be supported.
90
+
91
+ ### The value of `iterator#db` has changed
92
+
93
+ Though this was undocumented and only for internal use, the `db` property on an iterator pointed to an `IDBDatabase`. To comply with `abstract-leveldown` the `db` property now points to the `level-js` instance that created that iterator.
94
+
95
+ ## 3.0.0
96
+
97
+ This release brings `level-js` up to par with latest [`levelup`][levelup] (v2), [`abstract-leveldown`][abstract-leveldown] (v5) and IndexedDB Second Edition. It targets modern `browserify` preferring [`Buffer`][buffer] over `ArrayBuffer`. Lastly, [`IDBWrapper`][idbwrapper] has been replaced with straight IndexedDB code.
98
+
99
+ ### Usage with [`levelup`][levelup]
100
+
101
+ Usage has changed to:
102
+
103
+ ```js
104
+ const levelup = require('levelup')
105
+ const leveljs = require('leveljs')
106
+
107
+ const db = levelup(leveljs('mydb'))
108
+ ```
109
+
110
+ From the old:
111
+
112
+ ```js
113
+ const db = levelup('mydb', { db: leveljs })
114
+ ```
115
+
116
+ Friendly reminder: encodings have moved from [`levelup`][levelup] to [`encoding-down`][encoding-down]. To get identical functionality to `levelup < 2` please use the [`level-browserify`][level-browserify] convenience package or wrap `level-js` with `encoding-down`:
117
+
118
+ ```js
119
+ const encode = require('encoding-down')
120
+ const db = levelup(encode(leveljs('mydb')))
121
+ ```
122
+
123
+ ### New database prefix
124
+
125
+ The default prefix of the [`IDBDatabase`][idbdatabase] name has changed from `IDBWrapper-` to `level-js-`. To access databases created using `level-js < 3`, pass a custom prefix to the `level-js` constructor:
126
+
127
+ ```js
128
+ const db = levelup(leveljs('mydb', { prefix: 'IDBWrapper-' }))
129
+ ```
130
+
131
+ ### Browser support
132
+
133
+ As a result of removing [`IDBWrapper`][idbwrapper], only modern browsers with a non-prefixed `window.indexedDB` are supported in this release. The current test matrix of `level-js` includes the latest versions of Chrome, Firefox, Safari, Edge and IE.
134
+
135
+ :fire: Internet Explorer 10 is no longer supported.
136
+
137
+ ### Type support
138
+
139
+ All value types of the [structured clone algorithm][structured-clone-algorithm] and all key types of IndexedDB Second Edition are now supported. This means you can store almost any JavaScript type without the need for [`encoding-down`][encoding-down]. In addition, you can use [`Buffer`][buffer] for both keys and values. For details and caveats please see the [readme][readme].
140
+
141
+ ### No backpressure
142
+
143
+ In `level-js`, iterators are powered by IndexedDB cursors. To fulfill [`abstract-leveldown`][abstract-leveldown] snapshot guarantees (reads not being affected by simultaneous writes) cursors are started immediately and continuously read from, filling an in-memory cache.
144
+
145
+ Though `level-js` now passes the full [`abstract-leveldown`][abstract-leveldown] test suite, fulfilling the snapshot guarantee means a loss of backpressure. Memory consumption might increase if an iterator is not consumed fast enough. A future release will have an option to favor backpressure over snapshot guarantees.
146
+
147
+ ### Removed `raw` option
148
+
149
+ Because `level-js` no longer stringifies values, the `raw` option (which bypassed conversion) became unnecessary and has been removed. If you use [`level-browserify`][level-browserify] or [`levelup`][levelup] with [`encoding-down`][encoding-down], you can store and retrieve raw values (as returned by IndexedDB) using the `id` encoding. Please refer to the [readme][readme] for an example.
150
+
151
+ ### New `destroy()` function signature
152
+
153
+ Previously, a `level-js` instance could be passed to `destroy()`:
154
+
155
+ ```js
156
+ leveljs.destroy(db, callback)
157
+ ```
158
+
159
+ This was useful to destroy a database that used a custom prefix. The new signature is `destroy(location[, prefix], callback)`.
160
+
161
+ ### Strict `.batch(array)`
162
+
163
+ The upgrade to [`abstract-leveldown`][abstract-leveldown] comes with a [breaking change](https://github.com/Level/abstract-leveldown/commit/a2621ad70571f6ade9d2be42632ece042e068805) for the array version of `.batch()`. This change ensures all elements in the batch array are objects. If you previously passed arrays to `.batch()` that contained `undefined` or `null`, they would be silently ignored. Now this will produce an error.
164
+
165
+ [readme]: README.md
166
+
167
+ [changelog]: CHANGELOG.md
168
+
169
+ [buffer]: https://nodejs.org/api/buffer.html
170
+
171
+ [idbwrapper]: https://www.npmjs.com/package/idb-wrapper
172
+
173
+ [abstract-leveldown]: https://github.com/Level/abstract-leveldown
174
+
175
+ [levelup]: https://github.com/Level/levelup
176
+
177
+ [encoding-down]: https://github.com/Level/encoding-down
178
+
179
+ [level-browserify]: https://github.com/Level/level-browserify
180
+
181
+ [idbdatabase]: https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase
182
+
183
+ [structured-clone-algorithm]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
package/index.js ADDED
@@ -0,0 +1,336 @@
1
+ /* global indexedDB */
2
+
3
+ 'use strict'
4
+
5
+ module.exports = Level
6
+
7
+ const AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN
8
+ const inherits = require('inherits')
9
+ const parallel = require('run-parallel-limit')
10
+ const Iterator = require('./iterator')
11
+ const serialize = require('./util/serialize')
12
+ const deserialize = require('./util/deserialize')
13
+ const support = require('./util/support')
14
+ const clear = require('./util/clear')
15
+ const createKeyRange = require('./util/key-range')
16
+ const ensureIndexedDB = require('./util/ensure-indexeddb')
17
+
18
+ const DEFAULT_PREFIX = 'level-js-'
19
+
20
+ // On Node-like platforms without a native IndexedDB (e.g. the HarmonyOS
21
+ // "openharmony" Node.js build), conditionally provide a real IndexedDB
22
+ // runtime (fake-indexeddb). Runs before any code reads the `indexedDB`
23
+ // global (e.g. the constructor's feature detection). No-op in browsers:
24
+ // the native global wins.
25
+ ensureIndexedDB()
26
+
27
+ // Track open stores so that Level.destroy() can close the connections that
28
+ // this library itself opened. Without this, IndexedDB fires a "blocked"
29
+ // event on the delete request and the destroy callback is never called
30
+ // while connections are (still) open.
31
+ const openStores = new Set()
32
+
33
+ function Level (location, opts) {
34
+ if (!(this instanceof Level)) return new Level(location, opts)
35
+
36
+ AbstractLevelDOWN.call(this, {
37
+ bufferKeys: support.bufferKeys(indexedDB),
38
+ snapshots: true,
39
+ permanence: true,
40
+ clear: true,
41
+ getMany: true
42
+ })
43
+
44
+ opts = opts || {}
45
+
46
+ if (typeof location !== 'string') {
47
+ throw new Error('constructor requires a location string argument')
48
+ }
49
+
50
+ this.location = location
51
+ this.prefix = opts.prefix == null ? DEFAULT_PREFIX : opts.prefix
52
+ this.version = parseInt(opts.version || 1, 10)
53
+ }
54
+
55
+ inherits(Level, AbstractLevelDOWN)
56
+
57
+ Level.prototype.type = 'level-js'
58
+
59
+ Level.prototype._open = function (options, callback) {
60
+ const req = indexedDB.open(this.prefix + this.location, this.version)
61
+
62
+ req.onerror = function () {
63
+ callback(req.error || new Error('unknown error'))
64
+ }
65
+
66
+ req.onsuccess = () => {
67
+ this.db = req.result
68
+ openStores.add(this)
69
+ callback()
70
+ }
71
+
72
+ req.onupgradeneeded = (ev) => {
73
+ const db = ev.target.result
74
+
75
+ if (!db.objectStoreNames.contains(this.location)) {
76
+ db.createObjectStore(this.location)
77
+ }
78
+ }
79
+ }
80
+
81
+ Level.prototype.store = function (mode) {
82
+ const transaction = this.db.transaction([this.location], mode)
83
+ return transaction.objectStore(this.location)
84
+ }
85
+
86
+ Level.prototype.await = function (request, callback) {
87
+ const transaction = request.transaction
88
+
89
+ // Take advantage of the fact that a non-canceled request error aborts
90
+ // the transaction. I.e. no need to listen for "request.onerror".
91
+ transaction.onabort = function () {
92
+ callback(transaction.error || new Error('aborted by user'))
93
+ }
94
+
95
+ transaction.oncomplete = function () {
96
+ callback(null, request.result)
97
+ }
98
+ }
99
+
100
+ Level.prototype._get = function (key, options, callback) {
101
+ const store = this.store('readonly')
102
+ let req
103
+
104
+ try {
105
+ req = store.get(key)
106
+ } catch (err) {
107
+ return this._nextTick(callback, err)
108
+ }
109
+
110
+ this.await(req, function (err, value) {
111
+ if (err) return callback(err)
112
+
113
+ if (value === undefined) {
114
+ // 'NotFound' error, consistent with LevelDOWN API
115
+ return callback(new Error('NotFound'))
116
+ }
117
+
118
+ callback(null, deserialize(value, options.asBuffer))
119
+ })
120
+ }
121
+
122
+ Level.prototype._getMany = function (keys, options, callback) {
123
+ const asBuffer = options.asBuffer
124
+ const store = this.store('readonly')
125
+ const tasks = keys.map((key) => (next) => {
126
+ let request
127
+
128
+ try {
129
+ request = store.get(key)
130
+ } catch (err) {
131
+ return next(err)
132
+ }
133
+
134
+ request.onsuccess = () => {
135
+ const value = request.result
136
+ next(null, value === undefined ? value : deserialize(value, asBuffer))
137
+ }
138
+
139
+ request.onerror = (ev) => {
140
+ ev.stopPropagation()
141
+ next(request.error)
142
+ }
143
+ })
144
+
145
+ parallel(tasks, 16, callback)
146
+ }
147
+
148
+ Level.prototype._del = function (key, options, callback) {
149
+ const store = this.store('readwrite')
150
+ let req
151
+
152
+ try {
153
+ req = store.delete(key)
154
+ } catch (err) {
155
+ return this._nextTick(callback, err)
156
+ }
157
+
158
+ this.await(req, callback)
159
+ }
160
+
161
+ Level.prototype._put = function (key, value, options, callback) {
162
+ const store = this.store('readwrite')
163
+ let req
164
+
165
+ try {
166
+ // Will throw a DataError or DataCloneError if the environment
167
+ // does not support serializing the key or value respectively.
168
+ req = store.put(value, key)
169
+ } catch (err) {
170
+ return this._nextTick(callback, err)
171
+ }
172
+
173
+ this.await(req, callback)
174
+ }
175
+
176
+ Level.prototype._serializeKey = function (key) {
177
+ return serialize(key, this.supports.bufferKeys)
178
+ }
179
+
180
+ Level.prototype._serializeValue = function (value) {
181
+ return serialize(value, true)
182
+ }
183
+
184
+ Level.prototype._iterator = function (options) {
185
+ return new Iterator(this, this.location, options)
186
+ }
187
+
188
+ Level.prototype._batch = function (operations, options, callback) {
189
+ if (operations.length === 0) return this._nextTick(callback)
190
+
191
+ const store = this.store('readwrite')
192
+ const transaction = store.transaction
193
+ let index = 0
194
+ let error
195
+
196
+ transaction.onabort = function () {
197
+ callback(error || transaction.error || new Error('aborted by user'))
198
+ }
199
+
200
+ transaction.oncomplete = function () {
201
+ callback()
202
+ }
203
+
204
+ // Wait for a request to complete before making the next, saving CPU.
205
+ function loop () {
206
+ const op = operations[index++]
207
+ const key = op.key
208
+
209
+ let req
210
+
211
+ try {
212
+ req = op.type === 'del' ? store.delete(key) : store.put(op.value, key)
213
+ } catch (err) {
214
+ error = err
215
+ transaction.abort()
216
+ return
217
+ }
218
+
219
+ if (index < operations.length) {
220
+ req.onsuccess = loop
221
+ }
222
+ }
223
+
224
+ loop()
225
+ }
226
+
227
+ Level.prototype._clear = function (options, callback) {
228
+ let keyRange
229
+ let req
230
+
231
+ try {
232
+ keyRange = createKeyRange(options)
233
+ } catch (e) {
234
+ // The lower key is greater than the upper key.
235
+ // IndexedDB throws an error, but we'll just do nothing.
236
+ return this._nextTick(callback)
237
+ }
238
+
239
+ if (options.limit >= 0) {
240
+ // IDBObjectStore#delete(range) doesn't have such an option.
241
+ // Fall back to cursor-based implementation.
242
+ return clear(this, this.location, keyRange, options, callback)
243
+ }
244
+
245
+ try {
246
+ const store = this.store('readwrite')
247
+ req = keyRange ? store.delete(keyRange) : store.clear()
248
+ } catch (err) {
249
+ return this._nextTick(callback, err)
250
+ }
251
+
252
+ this.await(req, callback)
253
+ }
254
+
255
+ Level.prototype._close = function (callback) {
256
+ openStores.delete(this)
257
+ this.db.close()
258
+ this._nextTick(callback)
259
+ }
260
+
261
+ // NOTE: remove in a next major release
262
+ Level.prototype.upgrade = function (callback) {
263
+ if (this.status !== 'open') {
264
+ return this._nextTick(callback, new Error('cannot upgrade() before open()'))
265
+ }
266
+
267
+ const it = this.iterator()
268
+ const batchOptions = {}
269
+ const self = this
270
+
271
+ it._deserializeKey = it._deserializeValue = identity
272
+ next()
273
+
274
+ function next (err) {
275
+ if (err) return finish(err)
276
+ it.next(each)
277
+ }
278
+
279
+ function each (err, key, value) {
280
+ if (err || key === undefined) {
281
+ return finish(err)
282
+ }
283
+
284
+ const newKey = self._serializeKey(deserialize(key, true))
285
+ const newValue = self._serializeValue(deserialize(value, true))
286
+
287
+ // To bypass serialization on the old key, use _batch() instead of batch().
288
+ // NOTE: if we disable snapshotting (#86) this could lead to a loop of
289
+ // inserting and then iterating those same entries, because the new keys
290
+ // possibly sort after the old keys.
291
+ self._batch([
292
+ { type: 'del', key: key },
293
+ { type: 'put', key: newKey, value: newValue }
294
+ ], batchOptions, next)
295
+ }
296
+
297
+ function finish (err) {
298
+ it.end(function (err2) {
299
+ callback(err || err2)
300
+ })
301
+ }
302
+
303
+ function identity (data) {
304
+ return data
305
+ }
306
+ }
307
+
308
+ Level.destroy = function (location, prefix, callback) {
309
+ if (typeof prefix === 'function') {
310
+ callback = prefix
311
+ prefix = DEFAULT_PREFIX
312
+ }
313
+
314
+ // Close connections that this library opened for the same database.
315
+ // IndexedDB otherwise fires a "blocked" event on the delete request and
316
+ // the destroy callback below is never called while those connections
317
+ // are (still) open.
318
+ for (const store of openStores) {
319
+ if (store.prefix === prefix && store.location === location && store.db) {
320
+ openStores.delete(store)
321
+ try {
322
+ store.db.close()
323
+ } catch (err) {
324
+ // Connection was already closed
325
+ }
326
+ }
327
+ }
328
+
329
+ const request = indexedDB.deleteDatabase(prefix + location)
330
+ request.onsuccess = function () {
331
+ callback()
332
+ }
333
+ request.onerror = function (err) {
334
+ callback(err)
335
+ }
336
+ }