@xyo-network/xl1-driver-cloudflare-r2 2.0.12

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/LICENSE ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/README.md ADDED
@@ -0,0 +1,111 @@
1
+ [![logo][]](https://xyo.network)
2
+
3
+ # @xyo-network/xl1-driver-cloudflare-r2
4
+
5
+ [![npm-badge][]][npm-link]
6
+ [![license-badge][]][license-link]
7
+
8
+ > Cloudflare R2-backed map driver for XL1 protocol storage — a persistent `AsyncIterableMap` over S3-compatible object storage.
9
+
10
+ ## About
11
+
12
+ XL1 SDK components persist data through the `MapType` (`SyncMap | AsyncMap`) abstraction. This package provides `R2Map`, a Cloudflare R2-backed `AsyncIterableMap` that stores each entry as a JSON object keyed by the map key, with an optional in-memory `LruCacheMap` read-through cache, an optional key prefix so multiple maps can share one bucket, and paged `for await...of` iteration over all entries.
13
+
14
+ R2 speaks the S3 API, so `R2Map` takes a configured [`@aws-sdk/client-s3`](https://www.npmjs.com/package/@aws-sdk/client-s3) `S3Client` pointed at your R2 endpoint:
15
+
16
+ ```ts
17
+ import { S3Client } from '@aws-sdk/client-s3'
18
+ import { R2Map } from '@xyo-network/xl1-driver-cloudflare-r2'
19
+
20
+ const client = new S3Client({
21
+ region: 'auto',
22
+ endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
23
+ credentials: { accessKeyId, secretAccessKey },
24
+ })
25
+
26
+ const map = await R2Map.create({ bucket: 'summaries', client, prefix: 'blocks/' })
27
+ await map.start()
28
+ ```
29
+
30
+ Because object storage has no per-value size ceiling comparable to document databases, `R2Map` suits large cached objects (e.g. block step summaries). Sibling drivers: [`@xyo-network/xl1-driver-memory`](https://www.npmjs.com/package/@xyo-network/xl1-driver-memory), [`@xyo-network/xl1-driver-lmdb`](https://www.npmjs.com/package/@xyo-network/xl1-driver-lmdb), [`@xyo-network/xl1-driver-mongodb`](https://www.npmjs.com/package/@xyo-network/xl1-driver-mongodb).
31
+
32
+ ## Install
33
+
34
+ Using npm:
35
+
36
+ ```sh
37
+ npm i --save @xyo-network/xl1-driver-cloudflare-r2
38
+ ```
39
+
40
+ Using yarn:
41
+
42
+ ```sh
43
+ yarn add @xyo-network/xl1-driver-cloudflare-r2
44
+ ```
45
+
46
+ Using pnpm:
47
+
48
+ ```sh
49
+ pnpm add @xyo-network/xl1-driver-cloudflare-r2
50
+ ```
51
+
52
+ Using bun:
53
+
54
+ ```sh
55
+ bun add @xyo-network/xl1-driver-cloudflare-r2
56
+ ```
57
+
58
+ > `@aws-sdk/client-s3` is an optional peer dependency — install it in the consuming application.
59
+
60
+ ## What's Inside
61
+
62
+ - **`R2Map`** — an R2/S3-backed `AsyncIterableMap<K, V>`: async `get`/`set`/`has`/`getMany`/`setMany`/`delete`/`clear`, optional `LruCacheMap` read cache, key prefixing, and paged iteration over the whole map.
63
+
64
+ ## Building Locally
65
+
66
+ ```sh
67
+ xy build @xyo-network/xl1-driver-cloudflare-r2
68
+ xy test @xyo-network/xl1-driver-cloudflare-r2
69
+ xy lint @xyo-network/xl1-driver-cloudflare-r2
70
+ ```
71
+
72
+ ## Maintainers
73
+
74
+ <table>
75
+ <tr>
76
+ <td align="center" valign="top" width="120">
77
+ <a href="https://github.com/arietrouw">
78
+ <img src="https://github.com/arietrouw.png" width="80" height="80" alt="Arie Trouw" /><br />
79
+ <sub><b>Arie Trouw</b></sub>
80
+ </a>
81
+ <br />
82
+ <a href="https://arietrouw.com">arietrouw.com</a>
83
+ </td>
84
+ <td align="center" valign="top" width="120">
85
+ <a href="https://github.com/jonesmac">
86
+ <img src="https://github.com/jonesmac.png" width="80" height="80" alt="Matt Jones" /><br />
87
+ <sub><b>Matt Jones</b></sub>
88
+ </a>
89
+ </td>
90
+ <td align="center" valign="top" width="120">
91
+ <a href="https://github.com/JoelBCarter">
92
+ <img src="https://github.com/JoelBCarter.png" width="80" height="80" alt="Joel Carter" /><br />
93
+ <sub><b>Joel Carter</b></sub>
94
+ </a>
95
+ </td>
96
+ </tr>
97
+ </table>
98
+
99
+ ## License
100
+
101
+ See the [LICENSE](./LICENSE) file (LGPL-3.0-only).
102
+
103
+ ## Credits
104
+
105
+ [Made with 🔥 and ❄️ by XYO Foundation](https://xyo.network)
106
+
107
+ [npm-badge]: https://img.shields.io/npm/v/@xyo-network/xl1-driver-cloudflare-r2.svg
108
+ [npm-link]: https://www.npmjs.com/package/@xyo-network/xl1-driver-cloudflare-r2
109
+ [license-badge]: https://img.shields.io/npm/l/@xyo-network/xl1-driver-cloudflare-r2.svg
110
+ [license-link]: ./LICENSE
111
+ [logo]: https://cdn.xy.company/img/brand/XYO_full_colored.png
@@ -0,0 +1,39 @@
1
+ import type { S3Client } from '@aws-sdk/client-s3';
2
+ import type { CreatableParams } from '@xylabs/sdk-js';
3
+ import { AbstractCreatable } from '@xylabs/sdk-js';
4
+ import type { AsyncIterableMap } from '@xyo-network/xl1-protocol-lib';
5
+ export interface R2MapParams extends CreatableParams {
6
+ bucket: string;
7
+ /**
8
+ * S3-compatible client pointed at the Cloudflare R2 endpoint
9
+ * (`https://<account-id>.r2.cloudflarestorage.com`).
10
+ */
11
+ client: S3Client;
12
+ getCache?: {
13
+ enabled: boolean;
14
+ maxEntries?: number;
15
+ };
16
+ /** Optional key prefix, allowing multiple maps to share one bucket. */
17
+ prefix?: string;
18
+ }
19
+ export declare class R2Map<K extends string = string, V extends {} = {}> extends AbstractCreatable<R2MapParams> implements AsyncIterableMap<K, V> {
20
+ private _getCache;
21
+ get bucket(): string;
22
+ get client(): S3Client;
23
+ get prefix(): string;
24
+ /**
25
+ * Enable `for await...of` iteration over all entries in the map.
26
+ * Pages through ListObjectsV2 so no fixed result limit is applied.
27
+ */
28
+ [Symbol.asyncIterator](): AsyncIterator<[K, V]>;
29
+ clear(): Promise<void>;
30
+ delete(id: K): Promise<boolean>;
31
+ get(id: K): Promise<V | undefined>;
32
+ getMany(ids: K[]): Promise<V[]>;
33
+ has(id: K): Promise<boolean>;
34
+ set(id: K, data: V): Promise<void>;
35
+ setMany(entries: [K, V][]): Promise<void>;
36
+ startHandler(): Promise<void>;
37
+ private objectKey;
38
+ }
39
+ //# sourceMappingURL=R2Map.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"R2Map.d.ts","sourceRoot":"","s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AG,CAAC,EAAE,EAAE,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;IAc5B,GAAG,CAAC,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAUlC,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAOhC,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;IAQ5C,OAAO,CAAC,SAAS;CAGlB"}
@@ -0,0 +1,2 @@
1
+ export * from './R2Map.ts';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAA"}
@@ -0,0 +1,169 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __decorateClass = (decorators, target, key, kind) => {
4
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
5
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
6
+ if (decorator = decorators[i])
7
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
8
+ if (kind && result) __defProp(target, key, result);
9
+ return result;
10
+ };
11
+
12
+ // src/R2Map.ts
13
+ import {
14
+ DeleteObjectCommand,
15
+ DeleteObjectsCommand,
16
+ GetObjectCommand,
17
+ HeadObjectCommand,
18
+ ListObjectsV2Command,
19
+ PutObjectCommand
20
+ } from "@aws-sdk/client-s3";
21
+ import {
22
+ AbstractCreatable,
23
+ assertEx,
24
+ creatable,
25
+ isDefined
26
+ } from "@xylabs/sdk-js";
27
+ import { LruCacheMap } from "@xyo-network/xl1-driver-memory";
28
+ var isNotFoundError = (error) => {
29
+ if (typeof error !== "object" || error === null) return false;
30
+ const { name, $metadata } = error;
31
+ return name === "NoSuchKey" || name === "NotFound" || $metadata?.httpStatusCode === 404;
32
+ };
33
+ var R2Map = class extends AbstractCreatable {
34
+ _getCache;
35
+ get bucket() {
36
+ return assertEx(this.params.bucket, () => "No bucket specified");
37
+ }
38
+ get client() {
39
+ return assertEx(this.params.client, () => "No client specified");
40
+ }
41
+ get prefix() {
42
+ return this.params.prefix ?? "";
43
+ }
44
+ /**
45
+ * Enable `for await...of` iteration over all entries in the map.
46
+ * Pages through ListObjectsV2 so no fixed result limit is applied.
47
+ */
48
+ [Symbol.asyncIterator]() {
49
+ let pageKeys = [];
50
+ let continuationToken;
51
+ let exhausted = false;
52
+ const loadNextPage = async () => {
53
+ const response = await this.client.send(new ListObjectsV2Command({
54
+ Bucket: this.bucket,
55
+ Prefix: this.prefix === "" ? void 0 : this.prefix,
56
+ ContinuationToken: continuationToken
57
+ }));
58
+ pageKeys = (response.Contents ?? []).map((object) => object.Key).filter(isDefined).map((key) => key.slice(this.prefix.length));
59
+ continuationToken = response.NextContinuationToken;
60
+ exhausted = continuationToken === void 0;
61
+ };
62
+ return {
63
+ next: async () => {
64
+ for (; ; ) {
65
+ while (pageKeys.length === 0) {
66
+ if (exhausted) return { value: void 0, done: true };
67
+ await loadNextPage();
68
+ }
69
+ const key = pageKeys.shift();
70
+ const value = await this.get(key);
71
+ if (value === void 0) continue;
72
+ return { value: [key, value], done: false };
73
+ }
74
+ }
75
+ };
76
+ }
77
+ async clear() {
78
+ await this._getCache?.clear();
79
+ let continuationToken;
80
+ do {
81
+ const response = await this.client.send(new ListObjectsV2Command({
82
+ Bucket: this.bucket,
83
+ Prefix: this.prefix === "" ? void 0 : this.prefix,
84
+ ContinuationToken: continuationToken
85
+ }));
86
+ const keys = (response.Contents ?? []).map((object) => object.Key).filter(isDefined);
87
+ if (keys.length > 0) {
88
+ await this.client.send(new DeleteObjectsCommand({
89
+ Bucket: this.bucket,
90
+ Delete: { Objects: keys.map((key) => ({ Key: key })) }
91
+ }));
92
+ }
93
+ continuationToken = response.NextContinuationToken;
94
+ } while (continuationToken !== void 0);
95
+ }
96
+ async delete(id) {
97
+ await this._getCache?.delete(id);
98
+ const existed = await this.has(id);
99
+ await this.client.send(new DeleteObjectCommand({ Bucket: this.bucket, Key: this.objectKey(id) }));
100
+ return existed;
101
+ }
102
+ async get(id) {
103
+ if (this._getCache) {
104
+ const getCacheResult = await this._getCache.get(id);
105
+ if (getCacheResult) {
106
+ return getCacheResult;
107
+ }
108
+ }
109
+ try {
110
+ const response = await this.client.send(new GetObjectCommand({ Bucket: this.bucket, Key: this.objectKey(id) }));
111
+ const body = await response.Body?.transformToString();
112
+ if (body === void 0) return void 0;
113
+ const value = JSON.parse(body);
114
+ await this._getCache?.set(id, value);
115
+ return value;
116
+ } catch (error) {
117
+ if (isNotFoundError(error)) return void 0;
118
+ throw error;
119
+ }
120
+ }
121
+ async getMany(ids) {
122
+ const results = await Promise.all(ids.map((id) => this.get(id)));
123
+ return results.filter(isDefined);
124
+ }
125
+ async has(id) {
126
+ if (this._getCache) {
127
+ const getCacheResult = await this._getCache.has(id);
128
+ if (getCacheResult) return getCacheResult;
129
+ }
130
+ try {
131
+ await this.client.send(new HeadObjectCommand({ Bucket: this.bucket, Key: this.objectKey(id) }));
132
+ return true;
133
+ } catch (error) {
134
+ if (isNotFoundError(error)) return false;
135
+ throw error;
136
+ }
137
+ }
138
+ async set(id, data) {
139
+ await this.client.send(new PutObjectCommand({
140
+ Bucket: this.bucket,
141
+ Key: this.objectKey(id),
142
+ Body: JSON.stringify(data),
143
+ ContentType: "application/json"
144
+ }));
145
+ await this._getCache?.set(id, data);
146
+ }
147
+ async setMany(entries) {
148
+ for (const [key, value] of entries) {
149
+ await this.set(key, value);
150
+ }
151
+ }
152
+ async startHandler() {
153
+ await super.startHandler();
154
+ if (this.params.getCache?.enabled === true) {
155
+ const maxEntries = this.params.getCache?.maxEntries ?? 5e3;
156
+ this._getCache = new LruCacheMap({ max: maxEntries });
157
+ }
158
+ }
159
+ objectKey(id) {
160
+ return `${this.prefix}${id}`;
161
+ }
162
+ };
163
+ R2Map = __decorateClass([
164
+ creatable()
165
+ ], R2Map);
166
+ export {
167
+ R2Map
168
+ };
169
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/R2Map.ts"],
4
+ "sourcesContent": ["import type { S3Client } from '@aws-sdk/client-s3'\nimport {\n DeleteObjectCommand, DeleteObjectsCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand,\n} from '@aws-sdk/client-s3'\nimport type { CreatableParams } from '@xylabs/sdk-js'\nimport {\n AbstractCreatable, assertEx, creatable, isDefined,\n} from '@xylabs/sdk-js'\nimport { LruCacheMap } from '@xyo-network/xl1-driver-memory'\nimport type { AsyncIterableMap, MapType } from '@xyo-network/xl1-protocol-lib'\n\nexport interface R2MapParams extends CreatableParams {\n bucket: string\n /**\n * S3-compatible client pointed at the Cloudflare R2 endpoint\n * (`https://<account-id>.r2.cloudflarestorage.com`).\n */\n client: S3Client\n getCache?: {\n enabled: boolean\n maxEntries?: number\n }\n /** Optional key prefix, allowing multiple maps to share one bucket. */\n prefix?: string\n}\n\nconst isNotFoundError = (error: unknown): boolean => {\n if (typeof error !== 'object' || error === null) return false\n const { name, $metadata } = error as { $metadata?: { httpStatusCode?: number }; name?: string }\n return name === 'NoSuchKey' || name === 'NotFound' || $metadata?.httpStatusCode === 404\n}\n\n@creatable()\nexport class R2Map<K extends string = string, V extends {} = {}>\n extends AbstractCreatable<R2MapParams>\n implements AsyncIterableMap<K, V> {\n private _getCache: MapType<K, V> | undefined\n\n get bucket(): string {\n return assertEx(this.params.bucket, () => 'No bucket specified')\n }\n\n get client(): S3Client {\n return assertEx(this.params.client, () => 'No client specified')\n }\n\n get prefix(): string {\n return this.params.prefix ?? ''\n }\n\n /**\n * Enable `for await...of` iteration over all entries in the map.\n * Pages through ListObjectsV2 so no fixed result limit is applied.\n */\n [Symbol.asyncIterator](): AsyncIterator<[K, V]> {\n // Keys from the current page, drained front-to-back as the iterator advances.\n let pageKeys: K[] = []\n // Continuation token for the next page; undefined once the final page is consumed.\n let continuationToken: string | undefined\n let exhausted = false\n\n const loadNextPage = async (): Promise<void> => {\n const response = await this.client.send(new ListObjectsV2Command({\n Bucket: this.bucket,\n Prefix: this.prefix === '' ? undefined : this.prefix,\n ContinuationToken: continuationToken,\n }))\n pageKeys = (response.Contents ?? [])\n .map(object => object.Key)\n .filter(isDefined)\n .map(key => key.slice(this.prefix.length) as K)\n continuationToken = response.NextContinuationToken\n exhausted = continuationToken === undefined\n }\n\n return {\n next: async (): Promise<IteratorResult<[K, V]>> => {\n for (;;) {\n // Refill from the next page whenever the current one is drained.\n while (pageKeys.length === 0) {\n if (exhausted) return { value: undefined, done: true }\n await loadNextPage()\n }\n\n const key = pageKeys.shift()!\n const value = await this.get(key)\n // The object may have been deleted between listing and reading; skip it.\n if (value === undefined) continue\n\n // Yield the entry to the async iterator consumer (get() already populated the cache).\n return { value: [key, value], done: false }\n }\n },\n }\n }\n\n async clear(): Promise<void> {\n await this._getCache?.clear()\n // DeleteObjects accepts at most 1000 keys per request; page through the bucket until empty.\n let continuationToken: string | undefined\n do {\n const response = await this.client.send(new ListObjectsV2Command({\n Bucket: this.bucket,\n Prefix: this.prefix === '' ? undefined : this.prefix,\n ContinuationToken: continuationToken,\n }))\n const keys = (response.Contents ?? []).map(object => object.Key).filter(isDefined)\n if (keys.length > 0) {\n await this.client.send(new DeleteObjectsCommand({\n Bucket: this.bucket,\n Delete: { Objects: keys.map(key => ({ Key: key })) },\n }))\n }\n continuationToken = response.NextContinuationToken\n } while (continuationToken !== undefined)\n }\n\n async delete(id: K): Promise<boolean> {\n await this._getCache?.delete(id)\n\n // S3-style deletes are idempotent and do not report prior existence, so check first.\n const existed = await this.has(id)\n await this.client.send(new DeleteObjectCommand({ Bucket: this.bucket, Key: this.objectKey(id) }))\n return existed\n }\n\n async get(id: K): Promise<V | undefined> {\n if (this._getCache) {\n const getCacheResult = await this._getCache.get(id)\n if (getCacheResult) {\n return getCacheResult\n }\n }\n try {\n const response = await this.client.send(new GetObjectCommand({ Bucket: this.bucket, Key: this.objectKey(id) }))\n const body = await response.Body?.transformToString()\n if (body === undefined) return undefined\n const value = JSON.parse(body) as V\n await this._getCache?.set(id, value)\n return value\n } catch (error) {\n if (isNotFoundError(error)) return undefined\n throw error\n }\n }\n\n async getMany(ids: K[]): Promise<V[]> {\n const results = await Promise.all(ids.map(id => this.get(id)))\n return results.filter(isDefined)\n }\n\n async has(id: K): Promise<boolean> {\n if (this._getCache) {\n const getCacheResult = await this._getCache.has(id)\n if (getCacheResult) return getCacheResult\n }\n try {\n await this.client.send(new HeadObjectCommand({ Bucket: this.bucket, Key: this.objectKey(id) }))\n return true\n } catch (error) {\n if (isNotFoundError(error)) return false\n throw error\n }\n }\n\n async set(id: K, data: V): Promise<void> {\n await this.client.send(new PutObjectCommand({\n Bucket: this.bucket,\n Key: this.objectKey(id),\n Body: JSON.stringify(data),\n ContentType: 'application/json',\n }))\n await this._getCache?.set(id, data)\n }\n\n async setMany(entries: [K, V][]): Promise<void> {\n // TODO: Optimize with bounded concurrency\n for (const [key, value] of entries) {\n await this.set(key, value)\n }\n }\n\n override async startHandler(): Promise<void> {\n await super.startHandler()\n if (this.params.getCache?.enabled === true) {\n const maxEntries = this.params.getCache?.maxEntries ?? 5000\n this._getCache = new LruCacheMap<K, V>({ max: maxEntries })\n }\n }\n\n private objectKey(id: K): string {\n return `${this.prefix}${id}`\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;AACA;AAAA,EACE;AAAA,EAAqB;AAAA,EAAsB;AAAA,EAAkB;AAAA,EAAmB;AAAA,EAAsB;AAAA,OACjG;AAEP;AAAA,EACE;AAAA,EAAmB;AAAA,EAAU;AAAA,EAAW;AAAA,OACnC;AACP,SAAS,mBAAmB;AAkB5B,IAAM,kBAAkB,CAAC,UAA4B;AACnD,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,EAAE,MAAM,UAAU,IAAI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AM;AAC1C,YAAM,aAAa,KAAK,OAAO,UAAU,cAAc;AACvD,WAAK,YAAY,IAAI,YAAkB,EAAE,KAAK,WAAW,CAAC;AAAA,IAC5D;AAAA,EACF;AAAA,EAEQ,UAAU,IAAe;AAC/B,WAAO,GAAG,KAAK,MAAM,GAAG,EAAE;AAAA,EAC5B;AACF;AAhKa,QAAN;AAAA,EADN,UAAU;AAAA,GACE;",
6
+ "names": []
7
+ }
package/package.json ADDED
@@ -0,0 +1,115 @@
1
+ {
2
+ "$schema": "http://json.schemastore.org/package.json",
3
+ "name": "@xyo-network/xl1-driver-cloudflare-r2",
4
+ "version": "2.0.12",
5
+ "description": "XYO Layer One SDK Protocol Cloudflare R2 Driver",
6
+ "homepage": "https://xylabs.com",
7
+ "bugs": {
8
+ "url": "https://github.com/XYOracleNetwork/xl1-protocol/issues",
9
+ "email": "support@xylabs.com"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/XYOracleNetwork/xl1-protocol.git"
14
+ },
15
+ "license": "LGPL-3.0-only",
16
+ "author": {
17
+ "name": "XY Labs Development Team",
18
+ "email": "support@xylabs.com",
19
+ "url": "https://xylabs.com"
20
+ },
21
+ "sideEffects": false,
22
+ "type": "module",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/neutral/index.d.ts",
26
+ "default": "./dist/neutral/index.mjs"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "!**/*.bench.*",
33
+ "!**/*.spec.*",
34
+ "!**/*.test.*",
35
+ "README.md"
36
+ ],
37
+ "dependencies": {
38
+ "@xyo-network/xl1-protocol-lib": "~2.0.12",
39
+ "@xyo-network/xl1-driver-memory": "~2.0.12"
40
+ },
41
+ "devDependencies": {
42
+ "@aws-sdk/client-s3": "^3.700.0",
43
+ "@bitauth/libauth": "~3.0",
44
+ "@metamask/providers": "^22.1",
45
+ "@noble/post-quantum": "~0.6.1",
46
+ "@opentelemetry/api": "^1.9",
47
+ "@opentelemetry/sdk-trace-base": "^2.7",
48
+ "@scure/base": "~2.2",
49
+ "@scure/bip39": "~2.2",
50
+ "@xylabs/geo": "^6.0",
51
+ "@xylabs/sdk-js": "^6.0.10",
52
+ "@xylabs/threads": "~6.0",
53
+ "@xylabs/toolchain": "~8.1.19",
54
+ "@xylabs/tsconfig": "~8.1.19",
55
+ "@xyo-network/address": "^6.0",
56
+ "@xyo-network/sdk-js": "^6.0",
57
+ "@xyo-network/sdk-protocol-js": "~6.0",
58
+ "ajv": "^8.20",
59
+ "async-mutex": "^0.5",
60
+ "bn.js": "^5.2",
61
+ "buffer": "^6.0",
62
+ "debug": "~4.4",
63
+ "eslint": "^10.4.1",
64
+ "ethers": "^6.16",
65
+ "hash-wasm": "~4.12",
66
+ "idb": "^8.0",
67
+ "lru-cache": "^11.3",
68
+ "observable-fns": "~0.6",
69
+ "typescript": "~6.0.3",
70
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
71
+ "vitest": "~4.1.8",
72
+ "webextension-polyfill": "^0.12",
73
+ "zod": "~4.4"
74
+ },
75
+ "peerDependencies": {
76
+ "@aws-sdk/client-s3": "^3.700",
77
+ "@bitauth/libauth": "~3.0",
78
+ "@metamask/providers": "^22.1",
79
+ "@noble/post-quantum": "~0.6.1",
80
+ "@opentelemetry/api": "^1.9",
81
+ "@opentelemetry/sdk-trace-base": "^2.7",
82
+ "@scure/base": "~2.2",
83
+ "@scure/bip39": "~2.2",
84
+ "@xylabs/geo": "^6.0",
85
+ "@xylabs/sdk-js": "^6.0",
86
+ "@xylabs/threads": "~6.0",
87
+ "@xyo-network/address": "^6.0",
88
+ "@xyo-network/sdk-js": "^6.0",
89
+ "@xyo-network/sdk-protocol-js": "~6.0",
90
+ "ajv": "^8.20",
91
+ "async-mutex": "^0.5",
92
+ "bn.js": "^5.2",
93
+ "buffer": "^6.0",
94
+ "debug": "~4.4",
95
+ "ethers": "^6.16",
96
+ "hash-wasm": "~4.12",
97
+ "idb": "^8.0",
98
+ "lru-cache": "^11.3",
99
+ "observable-fns": "~0.6",
100
+ "webextension-polyfill": "^0.12",
101
+ "zod": "~4.4"
102
+ },
103
+ "peerDependenciesMeta": {
104
+ "@aws-sdk/client-s3": {
105
+ "optional": true
106
+ }
107
+ },
108
+ "engines": {
109
+ "node": ">=22.3"
110
+ },
111
+ "engineStrict": true,
112
+ "publishConfig": {
113
+ "access": "public"
114
+ }
115
+ }