flash-store 2.0.1 → 2.2.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.
Files changed (52) hide show
  1. package/README.md +94 -19
  2. package/dist/package.json +90 -61
  3. package/dist/src/config.d.ts +4 -0
  4. package/dist/src/config.d.ts.map +1 -1
  5. package/dist/src/config.js +4 -11
  6. package/dist/src/config.js.map +1 -1
  7. package/dist/src/{flash-store.d.ts → flash-store-core.d.ts} +17 -21
  8. package/dist/src/flash-store-core.d.ts.map +1 -0
  9. package/dist/src/flash-store-core.js +201 -0
  10. package/dist/src/flash-store-core.js.map +1 -0
  11. package/dist/src/{flash-store-sync.d.ts → flash-store-sync-core.d.ts} +8 -9
  12. package/dist/src/flash-store-sync-core.d.ts.map +1 -0
  13. package/dist/src/{flash-store-sync.js → flash-store-sync-core.js} +10 -11
  14. package/dist/src/flash-store-sync-core.js.map +1 -0
  15. package/dist/src/indexeddb-backend.d.ts +44 -0
  16. package/dist/src/indexeddb-backend.d.ts.map +1 -0
  17. package/dist/src/indexeddb-backend.js +207 -0
  18. package/dist/src/indexeddb-backend.js.map +1 -0
  19. package/dist/src/key-encoding.d.ts +9 -0
  20. package/dist/src/key-encoding.d.ts.map +1 -0
  21. package/dist/src/key-encoding.js +11 -0
  22. package/dist/src/key-encoding.js.map +1 -0
  23. package/dist/src/mod.d.ts +21 -5
  24. package/dist/src/mod.d.ts.map +1 -1
  25. package/dist/src/mod.js +25 -4
  26. package/dist/src/mod.js.map +1 -1
  27. package/dist/src/node/flash-store-sync.d.ts +12 -0
  28. package/dist/src/node/flash-store-sync.d.ts.map +1 -0
  29. package/dist/src/node/flash-store-sync.js +14 -0
  30. package/dist/src/node/flash-store-sync.js.map +1 -0
  31. package/dist/src/node/flash-store.d.ts +11 -0
  32. package/dist/src/node/flash-store.d.ts.map +1 -0
  33. package/dist/src/node/flash-store.js +108 -0
  34. package/dist/src/node/flash-store.js.map +1 -0
  35. package/dist/src/node/key-encoding.d.ts +8 -0
  36. package/dist/src/node/key-encoding.d.ts.map +1 -0
  37. package/dist/src/node/key-encoding.js +18 -0
  38. package/dist/src/node/key-encoding.js.map +1 -0
  39. package/dist/src/node/mod.d.ts +14 -0
  40. package/dist/src/node/mod.d.ts.map +1 -0
  41. package/dist/src/node/mod.js +13 -0
  42. package/dist/src/node/mod.js.map +1 -0
  43. package/dist/src/store-backend.d.ts +35 -0
  44. package/dist/src/store-backend.d.ts.map +1 -0
  45. package/dist/src/store-backend.js +2 -0
  46. package/dist/src/store-backend.js.map +1 -0
  47. package/package.json +39 -10
  48. package/dist/src/flash-store-sync.d.ts.map +0 -1
  49. package/dist/src/flash-store-sync.js.map +0 -1
  50. package/dist/src/flash-store.d.ts.map +0 -1
  51. package/dist/src/flash-store.js +0 -246
  52. package/dist/src/flash-store.js.map +0 -1
package/README.md CHANGED
@@ -13,13 +13,13 @@
13
13
  [![Downloads](http://img.shields.io/npm/dm/flash-store.svg?style=flat-square)](https://npmjs.org/package/flash-store)
14
14
  [![node](https://img.shields.io/node/v/flash-store.svg?maxAge=604800)](https://nodejs.org/)
15
15
 
16
- FlashStore is persistent key-value storage with asynchronous and synchronous Map-like APIs, powered by LMDB.
16
+ FlashStore provides persistent key-value storage with asynchronous and synchronous Map-like APIs. It uses LMDB in Node.js and Deno and IndexedDB in Chrome.
17
17
 
18
18
  ![flash store](https://huan.github.io/flash-store/images/flash-store.png)
19
19
 
20
20
  ## Requirements
21
21
 
22
- Node.js 26 or newer and npm 11 or newer. The npm package is ESM-only.
22
+ The npm package is ESM-only. For Node.js development use Node.js 26 and npm 11 or newer. For Deno use Deno 2.9.8 or newer with local `node_modules` and permission to load the LMDB native addon. Chrome uses its built-in IndexedDB.
23
23
 
24
24
  ## Examples
25
25
 
@@ -47,6 +47,64 @@ console.log(`key: 1, value: ${await flashStore.get(1)}`)
47
47
  await flashStore.close()
48
48
  ```
49
49
 
50
+ ### Deno
51
+
52
+ Install the package with `deno install --node-modules-dir=auto npm:flash-store`.
53
+ Use `import { FlashStore } from 'npm:flash-store'` and run the program with
54
+ `deno run --node-modules-dir=auto --allow-read --allow-write --allow-env --allow-ffi=./node_modules app.ts`.
55
+ Grant `--allow-sys=homedir` if the program calls `destroy()` so Flash Store
56
+ can check protected directories.
57
+
58
+ ### Chrome
59
+
60
+ Import only `'flash-store'`; the build tool picks the build. Tools that use the
61
+ `browser` export condition (and any runtime without a `node` condition, such as
62
+ Cloudflare Workers) resolve it to IndexedDB, while Node.js, Deno, and Bun
63
+ resolve it to LMDB. Applications can force a build with `flash-store/browser` or
64
+ `flash-store/node`; libraries should not. For a page that loads
65
+ modules directly, serve the installed package files and use an HTML import map
66
+ to resolve the entry and its two bare imports:
67
+
68
+ ```html
69
+ <script type="importmap">
70
+ {
71
+ "imports": {
72
+ "flash-store/browser": "/node_modules/flash-store/dist/src/mod.js",
73
+ "brolog": "/node_modules/brolog/dist/esm/src/mod.js"
74
+ }
75
+ }
76
+ </script>
77
+ ```
78
+
79
+ Serve the referenced JavaScript and the package's `dist/package.json` with
80
+ their JavaScript and JSON content types, respectively.
81
+
82
+ ```js
83
+ import { FlashStore, FlashStoreSync } from 'flash-store/browser'
84
+
85
+ const store = new FlashStore('app-cache')
86
+ await store.set('theme', 'dark')
87
+ await store.close()
88
+
89
+ const cache = new FlashStoreSync('app-cache')
90
+ await cache.ready()
91
+ console.log(cache.get('theme'))
92
+ await cache.close()
93
+ ```
94
+
95
+ The constructor takes a database name scoped to the current origin. Its
96
+ operations wait for IndexedDB to open. `destroy()` deletes that named database
97
+ and waits for other connections to release it. Flash Store connections close
98
+ when Chrome requests an upgrade or deletion. A handle closed by that event
99
+ rejects a later `destroy()`. Once you explicitly call `close()`, the handle
100
+ stops receiving database events. A later `destroy()` uses the database name,
101
+ which can refer to a replacement created by another tab. Call `destroy()`
102
+ directly on an open handle when you intend to remove its database.
103
+
104
+ A synchronous cache sees its own writes and the snapshot restored by `ready()`. If another tab changes
105
+ the database, reopen the cache to read the updated state. Browser data is
106
+ subject to site storage quotas and eviction.
107
+
50
108
  ## API Reference
51
109
 
52
110
  ### `FlashStore`
@@ -54,8 +112,10 @@ await flashStore.close()
54
112
  `FlashStore` provides async `set`, `get`, `has`, `delete`, `clear`, `forEach`,
55
113
  and `size`, plus async iteration through `entries`, `keys`, and `values`.
56
114
  Keys are finite numbers or strings without null characters; values use JSON
57
- serialization. Numeric keys sort naturally before strings. LMDB imposes a
58
- maximum encoded key size. See the [LMDB documentation](https://github.com/kriszyp/lmdb-js#keys).
115
+ serialization. Numeric keys sort naturally before strings. Both backends enforce the default LMDB limit of 1978 encoded bytes per key.
116
+ See the [LMDB documentation](https://github.com/kriszyp/lmdb-js#keys).
117
+ For arbitrary string identifiers in LMDB, encode embedded control characters and
118
+ unpaired UTF-16 surrogates before storing them as keys.
59
119
 
60
120
  Values are serialized with `JSON.stringify` and read back with `JSON.parse`.
61
121
  This is not a lossless round trip for every JavaScript value: for example,
@@ -65,7 +125,12 @@ objects, and `BigInt` cannot be stored. The TypeScript value type `V` is not
65
125
  validated against the decoded JSON, so it may not match the runtime value.
66
126
  Use JSON-compatible values and validate decoded data when its shape matters.
67
127
 
68
- Async iteration uses a snapshot in LMDB key order, not Map insertion order.
128
+ Async iteration uses a snapshot in key order. LMDB orders string keys by
129
+ UTF-8 bytes, whereas Chromium IndexedDB orders strings by native UTF-16 code
130
+ units. Chrome collects the matching records inside a single IndexedDB
131
+ transaction before yielding the first result, so its memory use grows with the
132
+ number of matches. For large datasets in browser environments, paginate
133
+ queries with `limit` and range bounds.
69
134
  `forEach` awaits each callback sequentially and stops on the first error,
70
135
  rejecting its returned promise. `FlashStoreSync.forEach` remains synchronous.
71
136
 
@@ -76,8 +141,10 @@ last match, so it does not read unrelated entries. `delete` resolves to whether
76
141
  a key existed.
77
142
 
78
143
  `close()` waits for outstanding writes. `destroy()` closes and **deletes the
79
- entire database directory**, so use a dedicated directory and never a shared
80
- directory. Both reject on failure.
144
+ entire database directory** under Node.js and Deno, so use a dedicated
145
+ directory. In Chrome it deletes the named IndexedDB database. After a
146
+ successful `destroy()`, another call on the same handle has no effect. Both
147
+ operations reject on failure.
81
148
 
82
149
  ### `FlashStoreSync`
83
150
 
@@ -91,28 +158,36 @@ observe write failures. After a detected write failure, further mutations throw;
91
158
  and reopen the store to recover. Mutations queued before the failure is detected
92
159
  may remain in the cache without being persisted. `close()` and `destroy()` wait
93
160
  for queued writes and close the database even on failure. `destroy()` removes
94
- the directory only if writes succeeded. Until `ready()` completes, reads and
161
+ the backing store only if writes succeeded. Until `ready()` completes, reads and
95
162
  delete return values only reflect the cache loaded so far.
96
163
 
97
164
  The cache iterates in its current insertion order, but reopening restores
98
- entries in LMDB key order rather than their original insertion order. Mutations
165
+ entries in storage key order. Mutations
99
166
  during restoration may also affect the cache order. The cache holds the values
100
167
  supplied to it; after reopening, values reflect the JSON round trip above.
101
168
 
102
169
  ## Diagnostics
103
170
 
104
- The `flash-store.operation` Node diagnostics channel publishes `{ operation }`
171
+ On Node.js and Deno the `flash-store.operation` diagnostics channel publishes `{ operation }`
105
172
  after successful `set`, `delete`, and `clear` operations. Messages contain no
106
173
  keys, values, or paths. The existing exported `log` remains available; its
107
174
  configured log level determines what application data it logs.
108
175
 
109
176
  ## Development
110
177
 
111
- Node executes TypeScript directly; `npm test` performs type-checking, Biome
112
- checks, and Node tests without building. `npm run test:deno` runs the same unit
113
- tests on Deno. `npm run coverage:node` and `npm run coverage:deno` enforce
114
- independently measured baselines and generate local reports. `npm run test:pack`
115
- builds the package and verifies it in an isolated npm consumer.
178
+ Node executes TypeScript directly. `npm test` runs type checking, Biome, and
179
+ the Node unit tests. The same unit test files run with
180
+ `npm run test:unit:deno` and `npm run test:unit:browser`. Install Chromium for
181
+ the browser suite with `npx playwright install chromium`.
182
+
183
+ `npm run test:integration` and `npm run test:integration:deno` exercise raw
184
+ LMDB and native diagnostics. `npm run coverage:node`, `npm run coverage:deno`,
185
+ and `npm run coverage:browser` enforce independent line, branch, and function
186
+ floors for each runtime adapter and shared sources. The coverage check fails if
187
+ an executable production file in that scope is absent from the runtime report.
188
+ CI uploads each runtime's LCOV and HTML reports. `npm run test:pack` verifies the installed package in Node,
189
+ Deno, and Chromium and checks consumer type resolution. The Chromium smoke
190
+ test covers both bundled and direct ESM loading.
116
191
 
117
192
  ### Benchmark
118
193
 
@@ -172,7 +247,7 @@ the benchmark CLI, its option validation, and temporary-directory cleanup.
172
247
 
173
248
  See the [documentation](https://huan.github.io/flash-store).
174
249
 
175
- * [ECMAScript 6: Maps - 2ality – JavaScript and more](http://2ality.com/2015/01/es6-maps-sets.html)
250
+ - [ECMAScript 6: Maps - 2ality – JavaScript and more](http://2ality.com/2015/01/es6-maps-sets.html)
176
251
 
177
252
  ## Version History
178
253
 
@@ -205,6 +280,6 @@ Long answer:
205
280
 
206
281
  ## Copyright & License
207
282
 
208
- * Code & Docs © 2017-now Huan Li \<huan@chatie.io\>
209
- * Code released under the Apache-2.0 License
210
- * Docs released under Creative Commons
283
+ - Code & Docs © 2017-now Huan Li \<huan@chatie.io\>
284
+ - Code released under the Apache-2.0 License
285
+ - Docs released under Creative Commons
package/dist/package.json CHANGED
@@ -1,64 +1,93 @@
1
1
  {
2
- "name": "flash-store",
3
- "version": "2.0.1",
4
- "description": "Persistent Map-like storage backed by LMDB.",
5
- "type": "module",
6
- "exports": {
7
- ".": {
8
- "types": "./dist/src/mod.d.ts",
9
- "import": "./dist/src/mod.js"
2
+ "name": "flash-store",
3
+ "version": "2.2.0",
4
+ "description": "Persistent Map-like storage for Node.js, Deno, and Chrome.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/src/mod.d.ts",
9
+ "browser": "./dist/src/mod.js",
10
+ "node": "./dist/src/node/mod.js",
11
+ "default": "./dist/src/mod.js"
12
+ },
13
+ "./browser": {
14
+ "types": "./dist/src/mod.d.ts",
15
+ "default": "./dist/src/mod.js"
16
+ },
17
+ "./node": {
18
+ "types": "./dist/src/node/mod.d.ts",
19
+ "default": "./dist/src/node/mod.js"
20
+ }
21
+ },
22
+ "types": "./dist/src/mod.d.ts",
23
+ "engines": {
24
+ "node": ">=26",
25
+ "npm": ">=11"
26
+ },
27
+ "scripts": {
28
+ "build": "node scripts/prepare-package.ts && tsc",
29
+ "prepack": "npm run build",
30
+ "demo": "node example/demo.ts",
31
+ "benchmark": "node scripts/benchmark.ts",
32
+ "lint": "biome check src example scripts tests web-test-runner.config.js tsconfig.json package.json biome.json .github/coverage-baselines",
33
+ "typecheck": "tsc --noEmit",
34
+ "test": "npm run typecheck && npm run lint && npm run test:unit",
35
+ "test:unit": "node --test \"src/**/*.test.ts\"",
36
+ "test:deno": "npm run test:unit:deno",
37
+ "coverage:node": "node scripts/coverage.ts node",
38
+ "coverage:deno": "node scripts/coverage.ts deno",
39
+ "coverage:browser": "node scripts/coverage.ts browser",
40
+ "test:pack": "node scripts/pack-test.ts",
41
+ "test:unit:deno": "deno test --no-check --allow-read --allow-write --allow-env --allow-ffi --allow-sys=homedir src/",
42
+ "test:unit:browser": "wtr --config web-test-runner.config.js",
43
+ "test:integration": "node --test \"tests/*.integration.test.ts\"",
44
+ "test:integration:deno": "deno test --no-check --allow-read --allow-write --allow-env --allow-ffi --allow-sys=homedir tests/native.integration.test.ts"
45
+ },
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "git+https://github.com/huan/flash-store.git"
49
+ },
50
+ "keywords": [
51
+ "lmdb",
52
+ "nosql",
53
+ "database"
54
+ ],
55
+ "author": "Huan LI <zixia@zixia.net>",
56
+ "license": "Apache-2.0",
57
+ "bugs": {
58
+ "url": "https://github.com/huan/flash-store/issues"
59
+ },
60
+ "homepage": "https://github.com/huan/flash-store#readme",
61
+ "dependencies": {
62
+ "brolog": "^2.0.0",
63
+ "lmdb": "~3.5.9"
64
+ },
65
+ "devDependencies": {
66
+ "@biomejs/biome": "2.6.7",
67
+ "@types/chai": "^5.2.3",
68
+ "@types/node": "^26.6.6",
69
+ "@web/dev-server-esbuild": "^2.0.1",
70
+ "@web/test-runner": "^1.0.1",
71
+ "@web/test-runner-playwright": "^1.0.2",
72
+ "chai": "^6.3.0",
73
+ "esbuild": "^0.28.2",
74
+ "playwright": "^1.61.1",
75
+ "typescript": "^7.0.2"
76
+ },
77
+ "files": [
78
+ "dist/src/",
79
+ "!dist/src/**/*.test.*",
80
+ "!dist/src/**/test-fixture.*",
81
+ "dist/package.json"
82
+ ],
83
+ "publishConfig": {
84
+ "access": "public",
85
+ "tag": "next"
86
+ },
87
+ "imports": {
88
+ "#test-store": {
89
+ "browser": "./src/mod.ts",
90
+ "default": "./src/node/mod.ts"
91
+ }
10
92
  }
11
- },
12
- "types": "./dist/src/mod.d.ts",
13
- "engines": {
14
- "node": ">=26",
15
- "npm": ">=11"
16
- },
17
- "scripts": {
18
- "build": "tsc && node scripts/prepare-package.ts",
19
- "prepack": "npm run build",
20
- "demo": "node example/demo.ts",
21
- "benchmark": "node scripts/benchmark.ts",
22
- "lint": "biome check src example scripts tsconfig.json package.json biome.json coverage-baselines.json",
23
- "typecheck": "tsc --noEmit",
24
- "test": "npm run typecheck && npm run lint && npm run test:unit",
25
- "test:unit": "node --test src/*.test.ts",
26
- "test:deno": "deno test --no-check --allow-read --allow-write --allow-env --allow-ffi --allow-sys=homedir src/",
27
- "coverage:node": "node scripts/coverage.ts node",
28
- "coverage:deno": "node scripts/coverage.ts deno",
29
- "test:pack": "node scripts/pack-test.ts"
30
- },
31
- "repository": {
32
- "type": "git",
33
- "url": "git+https://github.com/huan/flash-store.git"
34
- },
35
- "keywords": [
36
- "lmdb",
37
- "nosql",
38
- "database"
39
- ],
40
- "author": "Huan LI <zixia@zixia.net>",
41
- "license": "Apache-2.0",
42
- "bugs": {
43
- "url": "https://github.com/huan/flash-store/issues"
44
- },
45
- "homepage": "https://github.com/huan/flash-store#readme",
46
- "dependencies": {
47
- "brolog": "^1.14.2",
48
- "lmdb": "~3.5.9"
49
- },
50
- "devDependencies": {
51
- "@biomejs/biome": "2.6.7",
52
- "@types/node": "^26.6.6",
53
- "typescript": "^7.0.2"
54
- },
55
- "files": [
56
- "dist/src/",
57
- "!dist/src/*.test.*",
58
- "dist/package.json"
59
- ],
60
- "publishConfig": {
61
- "access": "public",
62
- "tag": "next"
63
- }
64
93
  }
@@ -1,3 +1,7 @@
1
+ /**
2
+ * Shares the published package identity and public logger across runtime
3
+ * entry points. TypeScript emits the imported manifest during packaging.
4
+ */
1
5
  import { log } from 'brolog';
2
6
  declare const VERSION: string;
3
7
  export { log, VERSION };
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAA;AAa5B,QAAA,MAAM,OAAO,QAAsB,CAAA;AAEnC,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,CAAA"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAA;AAG5B,QAAA,MAAM,OAAO,QAAmB,CAAA;AAEhC,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,CAAA"}
@@ -1,16 +1,9 @@
1
1
  /**
2
- * Shares package identity and the existing public logger between both store APIs.
3
- * The manifest is copied beside the compiled source during package emission.
2
+ * Shares the published package identity and public logger across runtime
3
+ * entry points. TypeScript emits the imported manifest during packaging.
4
4
  */
5
- import { readFileSync } from 'node:fs';
6
5
  import { log } from 'brolog';
7
- const packageJson = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
8
- if (typeof packageJson !== 'object' ||
9
- packageJson === null ||
10
- !('version' in packageJson) ||
11
- typeof packageJson.version !== 'string') {
12
- throw new Error('Package manifest does not contain a version');
13
- }
14
- const VERSION = packageJson.version;
6
+ import manifest from '../package.json' with { type: 'json' };
7
+ const VERSION = manifest.version;
15
8
  export { log, VERSION };
16
9
  //# sourceMappingURL=config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AACtC,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAA;AAE5B,MAAM,WAAW,GAAY,IAAI,CAAC,KAAK,CACrC,YAAY,CAAC,IAAI,GAAG,CAAC,iBAAiB,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,CAClE,CAAA;AACD,IACE,OAAO,WAAW,KAAK,QAAQ;IAC/B,WAAW,KAAK,IAAI;IACpB,CAAC,CAAC,SAAS,IAAI,WAAW,CAAC;IAC3B,OAAO,WAAW,CAAC,OAAO,KAAK,QAAQ,EACvC,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAA;AAChE,CAAC;AACD,MAAM,OAAO,GAAG,WAAW,CAAC,OAAO,CAAA;AAEnC,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,CAAA"}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAA;AAC5B,OAAO,QAAQ,MAAM,iBAAiB,CAAC,OAAO,IAAI,EAAE,MAAM,EAAE,CAAA;AAE5D,MAAM,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAA;AAEhC,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,CAAA"}
@@ -1,4 +1,5 @@
1
- /** Keys are ordered by LMDB: numbers precede strings and each type is ordered naturally. */
1
+ import type { StoreBackend } from './store-backend.ts';
2
+ /** Numbers precede strings in storage key order. */
2
3
  export type StoreKey = string | number;
3
4
  /** Bounds and ordering for a range of keys. Prefix is restricted to string keys. */
4
5
  export interface IteratorOptions<K extends StoreKey = StoreKey> {
@@ -10,26 +11,24 @@ export interface IteratorOptions<K extends StoreKey = StoreKey> {
10
11
  limit?: number;
11
12
  prefix?: string;
12
13
  }
13
- /** Reject keys that the configured ordered-binary encoding cannot represent safely. */
14
+ /** Reject keys outside the serialized storage contract. */
14
15
  export declare function validateKey(key: StoreKey): void;
15
16
  /** Serialize a value once, rejecting values that JSON cannot represent. */
16
17
  export declare function serialize(value: unknown): string;
17
18
  /**
18
19
  * Writes pre-serialized JSON for FlashStoreSync, which serializes at call time.
19
- * Internal: mod.ts does not export it, and package exports expose only mod.ts.
20
+ * Used by the shared synchronous cache, outside the public package entries.
20
21
  */
21
- export declare let writeSerialized: <K extends StoreKey>(store: FlashStore<K, unknown>, key: K, serialized: string) => Promise<void>;
22
- /**
23
- * Persistent key-value store. Values use JSON round-tripping, which may change their
24
- * runtime type; the generic value type does not validate or prevent this.
25
- */
26
- export declare class FlashStore<K extends StoreKey = StoreKey, V = unknown> {
22
+ export declare let writeSerialized: <K extends StoreKey>(store: FlashStoreCore<K, unknown>, key: K, serialized: string) => Promise<void>;
23
+ /** Shared Map API for the installed runtime-specific entries. */
24
+ export declare class FlashStoreCore<K extends StoreKey, V> {
27
25
  static VERSION: string;
28
26
  readonly workdir: string;
29
- private readonly db;
27
+ private readonly backend;
30
28
  private closePromise?;
31
- /** Opens an LMDB database in the specified directory. */
32
- constructor(workdir: string);
29
+ private destroyPromise?;
30
+ /** Binds a storage backend and exposes its location through the public workdir property. */
31
+ protected constructor(workdir: string, backend: StoreBackend, requested?: string);
33
32
  /** Returns the package version. */
34
33
  version(): string;
35
34
  /** Stores a JSON-serializable value and resolves after its write completes. */
@@ -44,13 +43,9 @@ export declare class FlashStore<K extends StoreKey = StoreKey, V = unknown> {
44
43
  delete(key: K): Promise<boolean>;
45
44
  /** Removes every entry after queued writes. */
46
45
  clear(): Promise<void>;
47
- /** Resolves to the number of entries in the current snapshot. */
46
+ /** Starts counting immediately and resolves to the size of that read snapshot. */
48
47
  get size(): Promise<number>;
49
- /**
50
- * Iterates a snapshot in LMDB key order, releasing the cursor on early exit.
51
- * A prefix seeks to its contiguous key interval and stops on leaving it, so
52
- * the cost depends on matching entries rather than database size.
53
- */
48
+ /** Iterates a snapshot in storage key order and releases it on early exit. */
54
49
  entries(options?: IteratorOptions<K>): AsyncIterableIterator<[K, V]>;
55
50
  /** Iterates keys with the same range semantics as entries(). */
56
51
  keys(options?: IteratorOptions<K>): AsyncIterableIterator<K>;
@@ -62,8 +57,9 @@ export declare class FlashStore<K extends StoreKey = StoreKey, V = unknown> {
62
57
  forEach(callback: (value: V, key: K, store: this) => unknown, thisArg?: unknown): Promise<void>;
63
58
  /** Closes the database after outstanding writes; repeated calls are safe. */
64
59
  close(): Promise<void>;
65
- /** Closes and removes the entire database directory. Never pass a shared directory. */
60
+ /** Closes this handle and removes its backing storage once. Failed removals can be retried. */
66
61
  destroy(): Promise<void>;
62
+ /** Releases the handle before removal and leaves failures available for retry. */
63
+ private removeStorage;
67
64
  }
68
- export default FlashStore;
69
- //# sourceMappingURL=flash-store.d.ts.map
65
+ //# sourceMappingURL=flash-store-core.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flash-store-core.d.ts","sourceRoot":"","sources":["../../src/flash-store-core.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Owns the async Map API, validation, and JSON encoding shared by the node
3
+ * and web entries. Its storage backend supplies transactions and snapshots.
4
+ */
5
+ import { log, VERSION } from './config.js';
6
+ import { validateKeySize } from './key-encoding.js';
7
+ /** Reject keys outside the serialized storage contract. */
8
+ export function validateKey(key) {
9
+ if ((typeof key === 'number' && !Number.isFinite(key)) ||
10
+ (typeof key === 'string' && key.includes('\0')) ||
11
+ (typeof key !== 'number' && typeof key !== 'string')) {
12
+ throw new TypeError('Keys must be finite numbers or strings without null characters');
13
+ }
14
+ validateKeySize(key);
15
+ }
16
+ /** Serialize a value once, rejecting values that JSON cannot represent. */
17
+ export function serialize(value) {
18
+ const serialized = JSON.stringify(value);
19
+ if (serialized === undefined)
20
+ throw new TypeError('Value must be JSON serializable');
21
+ return serialized;
22
+ }
23
+ /**
24
+ * Writes pre-serialized JSON for FlashStoreSync, which serializes at call time.
25
+ * Used by the shared synchronous cache, outside the public package entries.
26
+ */
27
+ export let writeSerialized;
28
+ /** Use Map's zero equality; TypeScript represents both signs as the same numeric type. */
29
+ function normalizeKey(key) {
30
+ return Object.is(key, -0) ? 0 : key;
31
+ }
32
+ /** Reject ambiguous bounds before starting a storage scan. */
33
+ function validateOptions(options) {
34
+ if (options.prefix !== undefined) {
35
+ if (typeof options.prefix !== 'string') {
36
+ throw new TypeError('prefix must be a string');
37
+ }
38
+ validateKey(options.prefix);
39
+ }
40
+ if ((options.gt !== undefined && options.gte !== undefined) ||
41
+ (options.lt !== undefined && options.lte !== undefined) ||
42
+ (options.prefix !== undefined &&
43
+ (options.gt !== undefined ||
44
+ options.gte !== undefined ||
45
+ options.lt !== undefined ||
46
+ options.lte !== undefined))) {
47
+ throw new TypeError('Conflicting range bounds');
48
+ }
49
+ if (options.limit !== undefined &&
50
+ (!Number.isSafeInteger(options.limit) || options.limit < 0)) {
51
+ throw new RangeError('limit must be a non-negative safe integer');
52
+ }
53
+ for (const bound of [options.gt, options.gte, options.lt, options.lte]) {
54
+ if (bound !== undefined)
55
+ validateKey(bound);
56
+ }
57
+ }
58
+ /** Shared Map API for the installed runtime-specific entries. */
59
+ export class FlashStoreCore {
60
+ static VERSION = VERSION;
61
+ workdir;
62
+ backend;
63
+ closePromise;
64
+ destroyPromise;
65
+ static {
66
+ writeSerialized = (store, key, serialized) => store.write(key, serialized);
67
+ }
68
+ /** Binds a storage backend and exposes its location through the public workdir property. */
69
+ constructor(workdir, backend, requested = workdir) {
70
+ this.workdir = workdir;
71
+ this.backend = backend;
72
+ log.verbose('FlashStore', 'constructor(%s)', requested);
73
+ }
74
+ /** Returns the package version. */
75
+ version() {
76
+ return VERSION;
77
+ }
78
+ /** Stores a JSON-serializable value and resolves after its write completes. */
79
+ async set(key, value) {
80
+ validateKey(key);
81
+ const serialized = serialize(value);
82
+ log.verbose('FlashStore', 'set(%s, %s)', key, typeof value);
83
+ await this.write(key, serialized);
84
+ return this;
85
+ }
86
+ /** Writes validated, serialized JSON and publishes the set event on success. */
87
+ async write(key, serialized) {
88
+ log.silly('FlashStore', 'set(%s, %s)', key, serialized);
89
+ await this.backend.put(normalizeKey(key), serialized);
90
+ this.backend.publish?.('set');
91
+ }
92
+ /** Returns the stored value, or undefined when the key is absent. */
93
+ async get(key) {
94
+ validateKey(key);
95
+ log.verbose('FlashStore', 'get(%s)', key);
96
+ const value = await this.backend.get(normalizeKey(key));
97
+ return value === undefined ? undefined : JSON.parse(value);
98
+ }
99
+ /** Returns whether the key exists, including when its value is falsey. */
100
+ async has(key) {
101
+ validateKey(key);
102
+ return this.backend.has(normalizeKey(key));
103
+ }
104
+ /** Deletes a key and reports whether an entry existed. */
105
+ async delete(key) {
106
+ validateKey(key);
107
+ log.verbose('FlashStore', 'delete(%s)', key);
108
+ const deleted = await this.backend.delete(normalizeKey(key));
109
+ this.backend.publish?.('delete');
110
+ return deleted;
111
+ }
112
+ /** Removes every entry after queued writes. */
113
+ async clear() {
114
+ log.verbose('FlashStore', 'clear()');
115
+ await this.backend.clear();
116
+ this.backend.publish?.('clear');
117
+ }
118
+ /** Starts counting immediately and resolves to the size of that read snapshot. */
119
+ get size() {
120
+ log.verbose('FlashStore', 'size()');
121
+ return this.backend.count();
122
+ }
123
+ /** Iterates a snapshot in storage key order and releases it on early exit. */
124
+ async *entries(options = {}) {
125
+ log.verbose('FlashStore', '*entries(%s)', JSON.stringify(options));
126
+ validateOptions(options);
127
+ if (options.limit === 0)
128
+ return;
129
+ const lower = options.gte ?? options.gt;
130
+ const upper = options.lte ?? options.lt;
131
+ const range = {
132
+ lower: lower === undefined ? undefined : normalizeKey(lower),
133
+ upper: upper === undefined ? undefined : normalizeKey(upper),
134
+ lowerOpen: options.gt !== undefined,
135
+ upperOpen: options.lt !== undefined,
136
+ reverse: options.reverse ?? false,
137
+ prefix: options.prefix,
138
+ limit: options.limit,
139
+ };
140
+ // Native LMDB provides a synchronous cursor. Chromium finishes its read
141
+ // transaction before yielding so consumer awaits cannot invalidate it.
142
+ const entries = this.backend.scan(range);
143
+ for (const { key, value } of entries instanceof Promise
144
+ ? await entries
145
+ : entries)
146
+ yield [key, JSON.parse(value)];
147
+ }
148
+ /** Iterates keys with the same range semantics as entries(). */
149
+ async *keys(options = {}) {
150
+ log.verbose('FlashStore', 'keys()');
151
+ for await (const [key] of this.entries(options))
152
+ yield key;
153
+ }
154
+ /** Iterates values with the same range semantics as entries(). */
155
+ async *values(options = {}) {
156
+ log.verbose('FlashStore', 'values()');
157
+ for await (const [, value] of this.entries(options))
158
+ yield value;
159
+ }
160
+ /** Returns the asynchronous entries iterator. */
161
+ [Symbol.asyncIterator]() {
162
+ log.verbose('FlashStore', '*[Symbol.asyncIterator]()');
163
+ return this.entries();
164
+ }
165
+ /** Awaits each callback in snapshot key order; stops and rejects on the first failure. */
166
+ async forEach(callback, thisArg) {
167
+ log.verbose('FlashStore', 'forEach()');
168
+ for await (const [key, value] of this)
169
+ await callback.call(thisArg, value, key, this);
170
+ }
171
+ /** Closes the database after outstanding writes; repeated calls are safe. */
172
+ async close() {
173
+ log.verbose('FlashStore', 'close()');
174
+ try {
175
+ this.closePromise ??= this.backend.close();
176
+ await this.closePromise;
177
+ }
178
+ catch (error) {
179
+ this.closePromise = undefined;
180
+ throw error;
181
+ }
182
+ }
183
+ /** Closes this handle and removes its backing storage once. Failed removals can be retried. */
184
+ async destroy() {
185
+ log.verbose('FlashStore', 'destroy()');
186
+ this.destroyPromise ??= this.removeStorage();
187
+ await this.destroyPromise;
188
+ }
189
+ /** Releases the handle before removal and leaves failures available for retry. */
190
+ async removeStorage() {
191
+ try {
192
+ await this.close();
193
+ await this.backend.destroy();
194
+ }
195
+ catch (error) {
196
+ this.destroyPromise = undefined;
197
+ throw error;
198
+ }
199
+ }
200
+ }
201
+ //# sourceMappingURL=flash-store-core.js.map