@nexcraft-dev/r2d1 0.0.0-stage → 1.0.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 (48) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +169 -2
  3. package/dist/core/codec.d.ts +7 -0
  4. package/dist/core/codec.js +16 -0
  5. package/dist/core/codec.js.map +1 -0
  6. package/dist/core/collection.d.ts +32 -0
  7. package/dist/core/collection.js +193 -0
  8. package/dist/core/collection.js.map +1 -0
  9. package/dist/core/cursor.d.ts +5 -0
  10. package/dist/core/cursor.js +139 -0
  11. package/dist/core/cursor.js.map +1 -0
  12. package/dist/core/errors.d.ts +27 -0
  13. package/dist/core/errors.js +42 -0
  14. package/dist/core/errors.js.map +1 -0
  15. package/dist/core/model.d.ts +91 -0
  16. package/dist/core/model.js +54 -0
  17. package/dist/core/model.js.map +1 -0
  18. package/dist/core/query.d.ts +29 -0
  19. package/dist/core/query.js +65 -0
  20. package/dist/core/query.js.map +1 -0
  21. package/dist/core/schema.d.ts +21 -0
  22. package/dist/core/schema.js +61 -0
  23. package/dist/core/schema.js.map +1 -0
  24. package/dist/index.d.ts +12 -0
  25. package/dist/index.js +8 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/node/d1.d.ts +10 -0
  28. package/dist/node/d1.js +57 -0
  29. package/dist/node/d1.js.map +1 -0
  30. package/dist/node/index.d.ts +4 -0
  31. package/dist/node/index.js +3 -0
  32. package/dist/node/index.js.map +1 -0
  33. package/dist/node/r2.d.ts +23 -0
  34. package/dist/node/r2.js +115 -0
  35. package/dist/node/r2.js.map +1 -0
  36. package/dist/storage/d1.d.ts +28 -0
  37. package/dist/storage/d1.js +301 -0
  38. package/dist/storage/d1.js.map +1 -0
  39. package/dist/storage/r2-key.d.ts +4 -0
  40. package/dist/storage/r2-key.js +36 -0
  41. package/dist/storage/r2-key.js.map +1 -0
  42. package/dist/workers/index.d.ts +47 -0
  43. package/dist/workers/index.js +93 -0
  44. package/dist/workers/index.js.map +1 -0
  45. package/examples/common.ts +54 -0
  46. package/examples/node.ts +36 -0
  47. package/examples/workers.ts +22 -0
  48. package/package.json +61 -4
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,170 @@
1
- # Temporary Holding Version
1
+ # @nexcraft-dev/r2d1
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 ESM TypeScript document library for Node.js 22+ and Cloudflare Workers. R2 stores authoritative document bytes. D1 stores a rebuildable index.
4
+
5
+ This port preserves Java R2D1 storage contracts at commit `5afb4f97635ff8ff533e09b715232be13318b4b9`. It has not been published. Before release, use `npm pack` and install the resulting tarball. After release, install with `npm install @nexcraft-dev/r2d1`.
6
+
7
+ ## Node.js
8
+
9
+ ```ts
10
+ import { R2D1, defineSchema, jsonCodec } from '@nexcraft-dev/r2d1';
11
+ import { NodeR2DocumentStore, NodeD1IndexStore } from '@nexcraft-dev/r2d1/node';
12
+
13
+ interface User {
14
+ id: string;
15
+ country: string;
16
+ score: number;
17
+ }
18
+ const schema = defineSchema<User>({
19
+ collection: 'users',
20
+ id: 'id',
21
+ indexes: { country: 'string', score: 'double' },
22
+ });
23
+ const codec = jsonCodec<User>((value) => {
24
+ if (!value || typeof value !== 'object') throw new TypeError('Invalid user');
25
+ const user = value as Record<string, unknown>;
26
+ if (
27
+ typeof user.id !== 'string' ||
28
+ typeof user.country !== 'string' ||
29
+ typeof user.score !== 'number' ||
30
+ !Number.isFinite(user.score)
31
+ ) {
32
+ throw new TypeError('Invalid user');
33
+ }
34
+ return { id: user.id, country: user.country, score: user.score };
35
+ });
36
+ const documents = new NodeR2DocumentStore({
37
+ endpoint: 'https://<account-id>.r2.cloudflarestorage.com',
38
+ bucket: '<bucket>',
39
+ accessKeyId: '<access-key-id>',
40
+ secretAccessKey: '<secret-access-key>',
41
+ });
42
+ const indexes = new NodeD1IndexStore({
43
+ accountId: '<account-id>',
44
+ databaseId: '<database-id>',
45
+ apiToken: '<api-token>',
46
+ });
47
+ const users = await new R2D1(documents, indexes).collection(schema, codec, {
48
+ hydrationConcurrency: 16,
49
+ maxConcurrentOperations: 32,
50
+ });
51
+ try {
52
+ await users.put({ id: 'user-1', country: 'NZ', score: 4.5 });
53
+ const user = await users.get('user-1'); // undefined only when absent
54
+ const page = await users
55
+ .query()
56
+ .where('country')
57
+ .eq('NZ')
58
+ .sortBy('score', 'DESC')
59
+ .limit(20)
60
+ .fetch();
61
+ if (page.nextCursor) {
62
+ console.log(
63
+ await users
64
+ .query()
65
+ .where('country')
66
+ .eq('NZ')
67
+ .sortBy('score', 'DESC')
68
+ .limit(20)
69
+ .after(page.nextCursor)
70
+ .fetch(),
71
+ );
72
+ }
73
+ console.log(user, page.items);
74
+ await users.delete('user-1');
75
+ } finally {
76
+ documents.close();
77
+ }
78
+ ```
79
+
80
+ Supply credentials from application secret configuration. The library does not read environment variables or log credentials. R2 uses the AWS S3 SDK, region `auto` by default, and no library-configured retries. To borrow a client, supply `{ client, bucket }`. `close()` destroys only an internally created client. A borrowed client's configuration belongs to the caller. D1 uses the Cloudflare REST query endpoint.
81
+
82
+ ## Cloudflare Workers
83
+
84
+ ```ts
85
+ import { R2D1 } from '@nexcraft-dev/r2d1';
86
+ import { WorkersR2DocumentStore, WorkersD1IndexStore } from '@nexcraft-dev/r2d1/workers';
87
+
88
+ // Inside your Worker, using the same schema and codec:
89
+ const users = await new R2D1(
90
+ new WorkersR2DocumentStore(env.DOCUMENTS),
91
+ new WorkersD1IndexStore(env.INDEXES),
92
+ ).collection(schema, codec);
93
+ ```
94
+
95
+ Bind an R2 bucket as `DOCUMENTS` and a D1 database as `INDEXES`. The library does not provision or deploy resources. Core and the Workers adapters need no `nodejs_compat` flag. Their subpaths import no AWS SDK or Node built-ins. The npm package includes the Node dependency, but a Workers bundle includes only reachable modules.
96
+
97
+ See the [Node example](examples/node.ts), [Workers example](examples/workers.ts), and [shared codec example](examples/common.ts). Examples are TypeScript source for your build tool.
98
+
99
+ ## Schema and queries
100
+
101
+ - Collection and indexed-field names must match `[A-Za-z_][A-Za-z0-9_]*`.
102
+ - IDs are nonblank strings. Values are not trimmed or normalized.
103
+ - Each collection has at most five indexed fields. `document_id` is reserved.
104
+ - Index types: `string` (TEXT), `long` (INTEGER), `double` (REAL), `boolean` (INTEGER 0/1).
105
+ - Use signed 64-bit `bigint` for `long`. A JavaScript `number` is rejected for this type.
106
+ - Indexed values must be present and non-null. Double values must be finite.
107
+ - `where(field).eq/notEq/gt/gte/lt/lte(value)` adds an AND filter. Boolean fields support only `eq` and `notEq`.
108
+ - Every indexed field can be sorted. One sort and a positive integer limit are supported. Default order is document ID ascending.
109
+ - Sorted queries use ID as a tie-breaker in the same direction. Continuation uses Java-compatible opaque v1 cursors.
110
+ - Repeat the same collection, filters and sort when continuing. Java cursors do not encode the filter or sort field. They are not signed authorization tokens.
111
+ - Builders are immutable. Repeated sort, limit or cursor configuration fails.
112
+
113
+ Core exports `DocumentStore`, `IndexStore`, `DocumentCodec<T>`, and their model types for custom integrations. SPI methods return Promises. `DocumentStore.get` rejects with `DocumentNotFoundError` when absent. Collection `get` maps only that failure to `undefined`.
114
+
115
+ ## Java data compatibility
116
+
117
+ R2 keys use uppercase percent encoding of each UTF-8 collection and ID segment, separated by `/`. There is no file suffix or added envelope. D1 uses the collection name, `document_id TEXT PRIMARY KEY NOT NULL`, required typed columns, and `idx_<collection>_<field>` indexes.
118
+
119
+ **Java supplies no default document format.** Use a TypeScript codec that matches your application's Java codec. `jsonCodec` is an explicit helper. It uses ordinary JSON and cannot serialize `bigint`. Supply a custom codec for Long values or custom formats. The shared example matches the Java integration-test codec's dot-separated base64url fields and decimal Long.
120
+
121
+ Long bindings use decimal text with `CAST(... AS INTEGER)`. Sorted Long values are selected as text and converted to `bigint`. Stored columns and numeric query order remain compatible. No data rewrite is needed.
122
+
123
+ D1 initialization inspects actual schema. Same-schema initialization shares I/O. Conflicting schemas fail. Initialization failures remain failed for that store instance. Missing columns can be added to an empty table. Required additions to populated tables fail. Extra columns and indexes remain intact. Incompatible columns/index names require application-managed migration. Extra required columns without defaults can prevent insertion and are not removed automatically.
124
+
125
+ ## Consistency and recovery
126
+
127
+ PUT and DELETE mutate the authoritative store first, then the index. No transaction spans both stores. An index failure after authoritative success raises `PartialFailureError`, retaining `documentKey` and `cause`. No rollback occurs. GET reflects authoritative existence.
128
+
129
+ Hydration preserves index order. Missing documents raise `InconsistentStateError` for the whole page. Stale rows are not skipped.
130
+
131
+ Pause all application writes to the collection, including other processes, before calling `await users.rebuildIndex()`. Rebuild prepares the first page before clearing rows. It scans 100 keys per page and preserves schema. First-page preparation failure leaves existing rows intact. Later failure can leave an incomplete index. Resolve the cause and rebuild again. Rebuild is not atomic and has no distributed lock.
132
+
133
+ Hydration defaults to 16 concurrent reads per operation. Optional `maxConcurrentOperations` rejects excess operations on that collection instance with `AdmissionRejectedError`. There is no queue, timer, or cross-instance cap. Caller timeouts do not guarantee cancellation of storage requests.
134
+
135
+ Storage errors use `StorageError`, `StorageAccessError`, `StorageUnavailableError`, and `StorageOperationError`. Native failures without reliable status use `StorageOperationError`. Codec errors propagate unchanged. Library-generated transport errors exclude response bodies and raw SDK errors. There are no automatic retries, background jobs, or automatic recovery.
136
+
137
+ ## Development and validation
138
+
139
+ ```sh
140
+ npm ci
141
+ npm run typecheck
142
+ npm test
143
+ npm run verify:java
144
+ npm run check:package
145
+ ```
146
+
147
+ Tests cover SQLite execution, failure paths, rebuilds, concurrency and local Miniflare/Workerd R2/D1 bindings. `verify:java` requires Java 21+ and the Java checkout at `../r2d1`, or set `R2D1_JAVA_ROOT`. It compiles original source copies in a temporary directory and checks source hashes, fixtures and bidirectional cursors. It never builds or modifies the Java checkout. Normal tests use checked-in fixtures without Java.
148
+
149
+ The `Publish npm package` workflow is manually dispatched from `main`. The first formal release is `1.0.0`. Later runs increment the highest occupied stable version's patch component, checking both Git tags and the npm registry. The workflow updates both version files, validates Node 22 and 24, and atomically pushes a version commit and its `vX.Y.Z` tag. It uses the short-lived `GITHUB_TOKEN` for Git writes and OIDC for npm. No npm access token or PAT is configured.
150
+
151
+ The publish job keeps the workflow's `main` execution context for the `npm` Environment, while checking out the tag's exact commit SHA. It rechecks source ancestry, versions, tests and the tarball. An existing identical npm artifact is a successful no-op. A different artifact at the same version is an error. An unpublished tag is resumed without another version increment. Use the optional `resume_tag` input for explicit recovery of an existing tag. Re-running the same workflow run retains its release through the run ID recorded in the version commit.
152
+
153
+ The `npm` GitHub environment and package-level trusted publisher must be configured first. Repository rules must permit the workflow's short-lived token to update `main` and create release tags. The workflow never force-pushes, moves tags or creates GitHub releases. If Git reservation or npm publication fails, preserve existing tags and artifacts. Re-run all jobs to recover a reserved release, or use `resume_tag` from a new `main` dispatch. A new package may need separately authorized registration before package-level trust settings are available.
154
+
155
+ Live testing is opt-in and writes to dedicated resources. Set these variables:
156
+
157
+ ```text
158
+ R2D1_IT_ALLOW_MUTATIONS=true
159
+ R2D1_IT_R2_ENDPOINT
160
+ R2D1_IT_R2_BUCKET_NAME
161
+ R2D1_IT_R2_ACCESS_KEY_ID
162
+ R2D1_IT_R2_SECRET_ACCESS_KEY
163
+ R2D1_IT_D1_ACCOUNT_ID
164
+ R2D1_IT_D1_DATABASE_ID
165
+ R2D1_IT_D1_API_TOKEN
166
+ ```
167
+
168
+ Run `npm run test:live`. Without opt-in, it is skipped. Do not use production resources. It uses a unique collection, removes its document and rows, and prints its retained table name for manual removal. Local tests do not verify remote permissions, quotas, latency, or sustained load.
169
+
170
+ JDBC, filesystem storage, Java framework integrations, annotation processing, deployment automation, async indexing queues and distributed transactions are outside this package's scope.
@@ -0,0 +1,7 @@
1
+ import { StoredDocument } from './model.js';
2
+ export interface DocumentCodec<T> {
3
+ serialize(document: T): StoredDocument;
4
+ deserialize(document: StoredDocument): T;
5
+ }
6
+ /** Opt-in JSON only. Supply a decoder to validate untrusted data and restore domain types. */
7
+ export declare function jsonCodec<T>(decode: (value: unknown) => T): DocumentCodec<T>;
@@ -0,0 +1,16 @@
1
+ import { StoredDocument } from './model.js';
2
+ /** Opt-in JSON only. Supply a decoder to validate untrusted data and restore domain types. */
3
+ export function jsonCodec(decode) {
4
+ return Object.freeze({
5
+ serialize(document) {
6
+ const json = JSON.stringify(document);
7
+ if (json === undefined)
8
+ throw new TypeError('document is not JSON serializable');
9
+ return new StoredDocument(new TextEncoder().encode(json));
10
+ },
11
+ deserialize(document) {
12
+ return decode(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(document.content())));
13
+ },
14
+ });
15
+ }
16
+ //# sourceMappingURL=codec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codec.js","sourceRoot":"","sources":["../../src/core/codec.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAM5C,8FAA8F;AAC9F,MAAM,UAAU,SAAS,CAAI,MAA6B;IACxD,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,SAAS,CAAC,QAAW;YACnB,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;YACtC,IAAI,IAAI,KAAK,SAAS;gBAAE,MAAM,IAAI,SAAS,CAAC,mCAAmC,CAAC,CAAC;YACjF,OAAO,IAAI,cAAc,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;QAC5D,CAAC;QACD,WAAW,CAAC,QAAwB;YAClC,OAAO,MAAM,CACX,IAAI,CAAC,KAAK,CAAC,IAAI,WAAW,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAY,CAC5F,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { StoredDocument } from './model.js';\n\nexport interface DocumentCodec<T> {\n serialize(document: T): StoredDocument;\n deserialize(document: StoredDocument): T;\n}\n/** Opt-in JSON only. Supply a decoder to validate untrusted data and restore domain types. */\nexport function jsonCodec<T>(decode: (value: unknown) => T): DocumentCodec<T> {\n return Object.freeze({\n serialize(document: T): StoredDocument {\n const json = JSON.stringify(document);\n if (json === undefined) throw new TypeError('document is not JSON serializable');\n return new StoredDocument(new TextEncoder().encode(json));\n },\n deserialize(document: StoredDocument): T {\n return decode(\n JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(document.content())) as unknown,\n );\n },\n });\n}\n"]}
@@ -0,0 +1,32 @@
1
+ import type { DocumentStore, IndexStore } from './model.js';
2
+ import type { DocumentCodec } from './codec.js';
3
+ import type { CollectionSchema } from './schema.js';
4
+ import { Query } from './query.js';
5
+ export interface CollectionOptions {
6
+ readonly hydrationConcurrency?: number;
7
+ readonly maxConcurrentOperations?: number;
8
+ }
9
+ export declare class R2D1Collection<T extends object> {
10
+ #private;
11
+ readonly schema: CollectionSchema<T>;
12
+ private readonly documents;
13
+ private readonly indexes;
14
+ private readonly codec;
15
+ constructor(schema: CollectionSchema<T>, documents: DocumentStore, indexes: IndexStore, codec: DocumentCodec<T>, options?: CollectionOptions);
16
+ put(document: T): Promise<void>;
17
+ get(id: string): Promise<T | undefined>;
18
+ delete(id: string): Promise<void>;
19
+ query(): Query<T>;
20
+ rebuildIndex(): Promise<void>;
21
+ private fetch;
22
+ private validateKey;
23
+ private hydrate;
24
+ private deserialize;
25
+ private run;
26
+ }
27
+ export declare class R2D1 {
28
+ private readonly documents;
29
+ private readonly indexes;
30
+ constructor(documents: DocumentStore, indexes: IndexStore);
31
+ collection<T extends object>(schema: CollectionSchema<T>, codec: DocumentCodec<T>, options?: CollectionOptions): Promise<R2D1Collection<T>>;
32
+ }
@@ -0,0 +1,193 @@
1
+ import { encodeCursor } from './cursor.js';
2
+ import { AdmissionRejectedError, DocumentNotFoundError, InconsistentStateError, PartialFailureError, PersistenceError, } from './errors.js';
3
+ import { key, positive, StoredDocument } from './model.js';
4
+ import { Query } from './query.js';
5
+ async function mapBounded(items, concurrency, map) {
6
+ const output = new Array(items.length);
7
+ let next = 0;
8
+ let failed = false;
9
+ let failure;
10
+ await Promise.all(Array.from({ length: Math.min(items.length, concurrency) }, async () => {
11
+ while (!failed && next < items.length) {
12
+ const index = next++;
13
+ try {
14
+ output[index] = await map(items[index]);
15
+ }
16
+ catch (cause) {
17
+ if (!failed) {
18
+ failed = true;
19
+ failure = cause;
20
+ }
21
+ }
22
+ }
23
+ }));
24
+ // Drain in-flight reads before releasing the admission slot.
25
+ if (failed)
26
+ throw failure;
27
+ return output;
28
+ }
29
+ export class R2D1Collection {
30
+ schema;
31
+ documents;
32
+ indexes;
33
+ codec;
34
+ #concurrency;
35
+ #maxOperations;
36
+ #active = 0;
37
+ constructor(schema, documents, indexes, codec, options = {}) {
38
+ this.schema = schema;
39
+ this.documents = documents;
40
+ this.indexes = indexes;
41
+ this.codec = codec;
42
+ this.#concurrency = positive(options.hydrationConcurrency ?? 16, 'hydrationConcurrency');
43
+ this.#maxOperations =
44
+ options.maxConcurrentOperations === undefined
45
+ ? Infinity
46
+ : positive(options.maxConcurrentOperations, 'maxConcurrentOperations');
47
+ }
48
+ async put(document) {
49
+ return this.run(async () => {
50
+ const entry = this.schema.entry(document);
51
+ const stored = this.codec.serialize(document);
52
+ if (!(stored instanceof StoredDocument))
53
+ throw new TypeError('codec must return StoredDocument');
54
+ await this.documents.put(entry.documentKey, stored);
55
+ try {
56
+ await this.indexes.upsert(entry);
57
+ }
58
+ catch (cause) {
59
+ throw new PartialFailureError('Document write succeeded but index upsert failed', entry.documentKey, cause);
60
+ }
61
+ });
62
+ }
63
+ async get(id) {
64
+ return this.run(async () => {
65
+ let stored;
66
+ try {
67
+ stored = await this.documents.get(key(this.schema.metadata.collection, id));
68
+ }
69
+ catch (cause) {
70
+ if (cause instanceof DocumentNotFoundError)
71
+ return undefined;
72
+ throw cause;
73
+ }
74
+ return this.deserialize(stored);
75
+ });
76
+ }
77
+ async delete(id) {
78
+ return this.run(async () => {
79
+ const documentKey = key(this.schema.metadata.collection, id);
80
+ await this.documents.delete(documentKey);
81
+ try {
82
+ await this.indexes.delete(documentKey);
83
+ }
84
+ catch (cause) {
85
+ throw new PartialFailureError('Document delete succeeded but index cleanup failed', documentKey, cause);
86
+ }
87
+ });
88
+ }
89
+ query() {
90
+ return new Query(this.schema, (query) => this.fetch(query));
91
+ }
92
+ async rebuildIndex() {
93
+ return this.run(async () => {
94
+ const prepare = async (cursor) => {
95
+ const page = await this.documents.list(this.schema.metadata.collection, cursor, 100);
96
+ if (page.documentKeys.length > 100)
97
+ throw new PersistenceError('Document listing exceeded page limit');
98
+ const entries = await mapBounded(page.documentKeys, this.#concurrency, async (documentKey) => {
99
+ this.validateKey(documentKey);
100
+ const entry = this.schema.entry(await this.hydrate(documentKey));
101
+ if (entry.documentKey.id !== documentKey.id)
102
+ throw new InconsistentStateError('Document key does not match its content', documentKey);
103
+ return entry;
104
+ });
105
+ return {
106
+ entries,
107
+ ...(page.nextCursor !== undefined ? { nextCursor: page.nextCursor } : {}),
108
+ };
109
+ };
110
+ let page = await prepare();
111
+ await this.indexes.clear(this.schema.metadata.collection);
112
+ let cursor;
113
+ while (true) {
114
+ for (const entry of page.entries)
115
+ await this.indexes.upsert(entry);
116
+ if (page.nextCursor === undefined)
117
+ break;
118
+ if (!page.nextCursor || page.nextCursor === cursor)
119
+ throw new PersistenceError('Document listing did not advance');
120
+ cursor = page.nextCursor;
121
+ page = await prepare(cursor);
122
+ }
123
+ });
124
+ }
125
+ async fetch(query) {
126
+ return this.run(async () => {
127
+ const page = await this.indexes.query(query);
128
+ if (page.documentKeys.length > query.limit)
129
+ throw new PersistenceError('Index exceeded page limit');
130
+ const items = await mapBounded(page.documentKeys, this.#concurrency, (documentKey) => {
131
+ this.validateKey(documentKey);
132
+ return this.hydrate(documentKey);
133
+ });
134
+ if (page.nextCursor)
135
+ this.validateKey(page.nextCursor.lastDocumentKey);
136
+ return Object.freeze({
137
+ items: Object.freeze(items),
138
+ ...(page.nextCursor ? { nextCursor: encodeCursor(page.nextCursor) } : {}),
139
+ });
140
+ });
141
+ }
142
+ validateKey(documentKey) {
143
+ key(documentKey.collection, documentKey.id);
144
+ if (documentKey.collection !== this.schema.metadata.collection)
145
+ throw new PersistenceError('Storage returned a key outside the collection');
146
+ }
147
+ async hydrate(documentKey) {
148
+ let stored;
149
+ try {
150
+ stored = await this.documents.get(documentKey);
151
+ }
152
+ catch (cause) {
153
+ if (cause instanceof DocumentNotFoundError)
154
+ throw new InconsistentStateError('Index or listing references a missing document', documentKey, cause);
155
+ throw cause;
156
+ }
157
+ return this.deserialize(stored);
158
+ }
159
+ deserialize(stored) {
160
+ const value = this.codec.deserialize(stored);
161
+ if (value === null || value === undefined)
162
+ throw new TypeError('codec returned no document');
163
+ return value;
164
+ }
165
+ async run(operation) {
166
+ if (this.#active >= this.#maxOperations)
167
+ throw new AdmissionRejectedError('Collection operation limit reached');
168
+ this.#active++;
169
+ try {
170
+ return await operation();
171
+ }
172
+ finally {
173
+ this.#active--;
174
+ }
175
+ }
176
+ }
177
+ export class R2D1 {
178
+ documents;
179
+ indexes;
180
+ constructor(documents, indexes) {
181
+ this.documents = documents;
182
+ this.indexes = indexes;
183
+ }
184
+ async collection(schema, codec, options) {
185
+ if (!schema || !codec)
186
+ throw new TypeError('schema and codec are required');
187
+ // Validate options before any schema I/O.
188
+ const collection = new R2D1Collection(schema, this.documents, this.indexes, codec, options);
189
+ await this.indexes.initialize(schema.metadata);
190
+ return collection;
191
+ }
192
+ }
193
+ //# sourceMappingURL=collection.js.map