@deploybase/kv 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 deploybase
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,87 @@
1
- # Temporary Holding Version
1
+ # @deploybase/kv
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
+ The client for deploybase KV, a key-value store for deploybase functions. No dependencies, no
4
+ configuration: the platform gives each function the address and a token in its environment.
5
+
6
+ KV is in a closed beta. It works in deployed functions of teams that have it turned on. It is not
7
+ available in local development or in the build step yet; there, every call throws a `KVError` with
8
+ code `KV_NOT_AVAILABLE`.
9
+
10
+ ```sh
11
+ npm install @deploybase/kv@next
12
+ ```
13
+
14
+ ## Use
15
+
16
+ ```js
17
+ import { kv } from "@deploybase/kv";
18
+
19
+ await kv.set("user:1", { name: "Ada" }); // JSON by default
20
+ await kv.set("session:abc", data, { ttl: 3600 }); // seconds, minimum 60
21
+ await kv.set("lock", "1", { onlyIfNew: true }); // { modified: false } if it exists
22
+
23
+ const user = await kv.get("user:1"); // parsed JSON, or null
24
+ const text = await kv.get("page", { type: "text" }); // "json" | "text" | "arrayBuffer" | "stream"
25
+
26
+ const entry = await kv.getWithMetadata("user:1"); // { value, version, metadata, expiresAt } | null
27
+ const res = await kv.set("user:1", next, { onlyIfVersion: entry.version, metadata: { by: "cron" } });
28
+ // res = { modified: boolean, version?: string }
29
+
30
+ await kv.delete("user:1"); // also { onlyIfVersion }
31
+
32
+ const page = await kv.list({ prefix: "user:", limit: 100, cursor });
33
+ // { keys: [{ key, version, size, modifiedAt }], cursor, done }
34
+
35
+ const sessions = kv.store("sessions"); // named store, same methods
36
+ ```
37
+
38
+ - **Values**: an `ArrayBuffer`, typed array or `Buffer` is stored as bytes. Anything else is
39
+ stored as JSON. Read bytes back with `{ type: "arrayBuffer" }`.
40
+ - **Environments**: production functions and preview deployments see separate data. All previews
41
+ of a project share one preview data set.
42
+ - **Stores**: `kv` is the store named `default`. A store name is 1 to 64 characters of `a-z`, `0-9`
43
+ and `-`. A key is 1 to 256 bytes of UTF-8.
44
+
45
+ ## Conditions are results, not errors
46
+
47
+ A write whose condition does not hold returns `{ modified: false }`: `onlyIfNew` on a key that
48
+ exists, `onlyIfVersion` on a key at another version or gone. `get` of a missing key returns `null`.
49
+ Deleting a key that does not exist succeeds.
50
+
51
+ Everything else throws a `KVError` with `code`, `status` and `requestId`. Quote the `requestId`
52
+ when you ask for support.
53
+
54
+ ## Retries
55
+
56
+ The client retries at most twice, on network errors and on these answers, waiting for the
57
+ `Retry-After` the service sends (at most 5 seconds):
58
+
59
+ | Status | Code | Wait |
60
+ |---|---|---|
61
+ | 429 | `KV_RATE_LIMITED` | 1 s |
62
+ | 503 | `KV_BUSY` | 1 s |
63
+ | 503 | `KV_REVOCATIONS_STALE` | 5 s |
64
+ | 503 | `KV_STORAGE_MEASURING` | 5 s |
65
+ | 503 | `KV_STORAGE_UNAVAILABLE` | about 250 ms |
66
+
67
+ Every write carries one write id across its attempts, so a retried write that already landed
68
+ is not applied twice and an `onlyIfNew` write does not report its own earlier attempt as a
69
+ conflict.
70
+
71
+ Other errors are never retried. Two you should handle:
72
+
73
+ - `402 KV_STORAGE_LIMIT_EXCEEDED`: your team is over its storage limit. Delete keys to write again.
74
+ - `413 KV_VALUE_TOO_LARGE`: the value is over 1 MB.
75
+
76
+ Each attempt waits 2 seconds for an answer, 5 seconds for a value over 100 KB.
77
+
78
+ ## Beta limits
79
+
80
+ | | Limit |
81
+ |---|---|
82
+ | Storage per team | 1 GB |
83
+ | Value size | 1 MB |
84
+ | Metadata size | 1 KB |
85
+ | Key length | 256 bytes |
86
+ | Shortest `ttl` | 60 s |
87
+ | Keys per `list` page | 1000 |
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@deploybase/kv",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Client for deploybase KV, the key-value store of deploybase functions",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./src/index.d.ts",
10
+ "default": "./src/index.js"
11
+ },
12
+ "./package.json": "./package.json"
13
+ },
14
+ "types": "./src/index.d.ts",
15
+ "files": [
16
+ "src",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "keywords": [
21
+ "deploybase",
22
+ "kv",
23
+ "key-value",
24
+ "functions"
25
+ ],
26
+ "engines": {
27
+ "node": ">=22"
28
+ },
29
+ "devDependencies": {
30
+ "vitest": "^5.0.3"
31
+ },
32
+ "scripts": {
33
+ "test": "vitest run"
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://codeberg.org/deploybase/deploybase-adapters.git",
38
+ "directory": "packages/kv"
39
+ },
40
+ "homepage": "https://codeberg.org/deploybase/deploybase-adapters/src/branch/main/packages/kv#readme",
41
+ "bugs": {
42
+ "url": "https://codeberg.org/deploybase/deploybase-adapters/issues"
43
+ }
44
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,105 @@
1
+ export type ValueType = "json" | "text" | "arrayBuffer" | "stream";
2
+
3
+ export interface GetOptions<T extends ValueType = "json"> {
4
+ /** How to read the value. Default "json". */
5
+ type?: T;
6
+ }
7
+
8
+ type ValueOf<T extends ValueType> = T extends "text"
9
+ ? string
10
+ : T extends "arrayBuffer"
11
+ ? ArrayBuffer
12
+ : T extends "stream"
13
+ ? ReadableStream<Uint8Array>
14
+ : any;
15
+
16
+ export interface Entry<V> {
17
+ value: V;
18
+ /** Opaque version of the stored value. Pass it to onlyIfVersion. */
19
+ version: string;
20
+ /** The metadata set with the value, or {}. */
21
+ metadata: Record<string, unknown>;
22
+ /** When the value expires, or null without a ttl. */
23
+ expiresAt: Date | null;
24
+ }
25
+
26
+ export interface SetOptions {
27
+ /** Seconds until the key expires, at least 60. */
28
+ ttl?: number;
29
+ /** Write only if the key does not exist (or has expired). */
30
+ onlyIfNew?: boolean;
31
+ /** Write only if the key is at this version. */
32
+ onlyIfVersion?: string;
33
+ /** A JSON object stored with the value, at most 1 KB. */
34
+ metadata?: Record<string, unknown>;
35
+ }
36
+
37
+ export interface WriteResult {
38
+ /** false when a condition (onlyIfNew, onlyIfVersion) did not hold. */
39
+ modified: boolean;
40
+ /** The new version, when the write happened. */
41
+ version?: string;
42
+ }
43
+
44
+ export interface DeleteOptions {
45
+ /** Delete only if the key is at this version. */
46
+ onlyIfVersion?: string;
47
+ }
48
+
49
+ export interface ListOptions {
50
+ prefix?: string;
51
+ /** 1 to 1000, default 100. */
52
+ limit?: number;
53
+ /** The cursor of the previous page. */
54
+ cursor?: string;
55
+ }
56
+
57
+ export interface ListedKey {
58
+ key: string;
59
+ version: string;
60
+ size: number;
61
+ modifiedAt: Date;
62
+ }
63
+
64
+ export interface ListPage {
65
+ keys: ListedKey[];
66
+ /** Pass to the next list call; undefined on the last page. */
67
+ cursor?: string;
68
+ done: boolean;
69
+ }
70
+
71
+ export interface Store {
72
+ get<T extends ValueType = "json">(key: string, options?: GetOptions<T>): Promise<ValueOf<T> | null>;
73
+ getWithMetadata<T extends ValueType = "json">(key: string, options?: GetOptions<T>): Promise<Entry<ValueOf<T>> | null>;
74
+ /** Binary values (ArrayBuffer, typed arrays, Buffer) are stored as they are; anything else as JSON. */
75
+ set(key: string, value: unknown, options?: SetOptions): Promise<WriteResult>;
76
+ delete(key: string, options?: DeleteOptions): Promise<WriteResult>;
77
+ list(options?: ListOptions): Promise<ListPage>;
78
+ /** A named store: 1 to 64 characters of a-z, 0-9 and -. */
79
+ store(name: string): Store;
80
+ }
81
+
82
+ export class KVError extends Error {
83
+ /** A KV error code, such as KV_NOT_AVAILABLE, KV_RATE_LIMITED or KV_STORAGE_LIMIT_EXCEEDED. */
84
+ code: string;
85
+ /** The HTTP status, when the service answered. */
86
+ status?: number;
87
+ /** Quote this when you ask for support. */
88
+ requestId?: string;
89
+ details?: Record<string, unknown>;
90
+ }
91
+
92
+ export interface ClientOptions {
93
+ env?: () => Record<string, string | undefined>;
94
+ fetch?: typeof fetch;
95
+ sleep?: (ms: number) => Promise<void>;
96
+ random?: () => number;
97
+ randomUUID?: () => string;
98
+ timeouts?: { small?: number; large?: number };
99
+ }
100
+
101
+ /** A client for the default store. Inside a deployed function, use `kv`. */
102
+ export function createClient(options?: ClientOptions): Store;
103
+
104
+ /** The default store, configured from DEPLOYBASE_KV_URL and DEPLOYBASE_KV_TOKEN. */
105
+ export const kv: Store;
package/src/index.js ADDED
@@ -0,0 +1,359 @@
1
+ // @deploybase/kv: the client for deploybase KV, the key-value store of deploybase functions.
2
+ //
3
+ // The platform gives every function of a team with KV two environment variables:
4
+ // DEPLOYBASE_KV_URL (the service address) and DEPLOYBASE_KV_TOKEN (a token scoped to the
5
+ // team, project and environment). This client reads them on each call, so there is nothing
6
+ // to configure.
7
+
8
+ const DEFAULT_STORE = "default";
9
+ const STORE_RE = /^[a-z0-9-]{1,64}$/;
10
+ const MIN_TTL = 60;
11
+ const MAX_RETRIES = 2;
12
+ const MAX_RETRY_AFTER_MS = 5000;
13
+ const SMALL_TIMEOUT_MS = 2000;
14
+ const LARGE_TIMEOUT_MS = 5000;
15
+ const LARGE_VALUE_BYTES = 100 * 1024;
16
+ const VALUE_TYPES = new Set(["json", "text", "arrayBuffer", "stream"]);
17
+
18
+ // Retryable error codes and the wait used when the response carries no Retry-After.
19
+ const RETRYABLE = new Map([
20
+ ["KV_RATE_LIMITED", 1000],
21
+ ["KV_BUSY", 1000],
22
+ ["KV_REVOCATIONS_STALE", 5000],
23
+ ["KV_STORAGE_MEASURING", 5000],
24
+ ["KV_STORAGE_UNAVAILABLE", null], // jittered, see backoff()
25
+ ]);
26
+
27
+ const NOT_AVAILABLE_MESSAGE =
28
+ "deploybase KV is not available here. It works in deployed functions of teams with KV " +
29
+ "turned on, which receive DEPLOYBASE_KV_URL and DEPLOYBASE_KV_TOKEN. It is not available " +
30
+ "in local development or in the build step yet.";
31
+
32
+ /** An error answered by deploybase KV, or raised by this client. */
33
+ export class KVError extends Error {
34
+ constructor(message, { code, status, requestId, details, cause } = {}) {
35
+ super(message, cause === undefined ? undefined : { cause });
36
+ this.name = "KVError";
37
+ this.code = code;
38
+ this.status = status;
39
+ this.requestId = requestId;
40
+ this.details = details;
41
+ }
42
+ }
43
+
44
+ function defaultSleep(ms) {
45
+ return new Promise((resolve) => setTimeout(resolve, ms));
46
+ }
47
+
48
+ /**
49
+ * createClient returns a client for the default store. The options exist for tests and
50
+ * unusual runtimes; inside a deployed function, use the `kv` export instead.
51
+ */
52
+ export function createClient(options = {}) {
53
+ const ctx = {
54
+ env: options.env ?? (() => (typeof process === "undefined" ? {} : process.env)),
55
+ fetch: options.fetch ?? ((...args) => globalThis.fetch(...args)),
56
+ sleep: options.sleep ?? defaultSleep,
57
+ random: options.random ?? Math.random,
58
+ randomUUID: options.randomUUID ?? (() => globalThis.crypto.randomUUID()),
59
+ timeouts: { small: SMALL_TIMEOUT_MS, large: LARGE_TIMEOUT_MS, ...options.timeouts },
60
+ };
61
+ return makeStore(ctx, DEFAULT_STORE);
62
+ }
63
+
64
+ function makeStore(ctx, storeName) {
65
+ return {
66
+ get: (key, opts) => getEntry(ctx, storeName, key, opts).then((e) => (e === null ? null : e.value)),
67
+ getWithMetadata: (key, opts) => getEntry(ctx, storeName, key, opts),
68
+ set: (key, value, opts) => setKey(ctx, storeName, key, value, opts),
69
+ delete: (key, opts) => deleteKey(ctx, storeName, key, opts),
70
+ list: (opts) => listKeys(ctx, storeName, opts),
71
+ store: (name) => {
72
+ if (typeof name !== "string" || !STORE_RE.test(name)) {
73
+ throw new TypeError("A store name is 1 to 64 characters of a-z, 0-9 and -.");
74
+ }
75
+ return makeStore(ctx, name);
76
+ },
77
+ };
78
+ }
79
+
80
+ function config(ctx) {
81
+ const env = ctx.env() ?? {};
82
+ const url = env.DEPLOYBASE_KV_URL;
83
+ const token = env.DEPLOYBASE_KV_TOKEN;
84
+ if (!url || !token) {
85
+ throw new KVError(NOT_AVAILABLE_MESSAGE, { code: "KV_NOT_AVAILABLE" });
86
+ }
87
+ return { base: url.replace(/\/+$/, ""), token };
88
+ }
89
+
90
+ function checkKey(key) {
91
+ if (typeof key !== "string" || key.length === 0) {
92
+ throw new TypeError("A key is a non-empty string.");
93
+ }
94
+ }
95
+
96
+ function keyPath(storeName, key) {
97
+ return `/v1/stores/${storeName}/keys/${encodeURIComponent(key)}`;
98
+ }
99
+
100
+ // encodeValue turns a value into request bytes: binary values as they are, anything else
101
+ // as JSON.
102
+ function encodeValue(value) {
103
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
104
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
105
+ if (value === undefined) throw new TypeError("A value cannot be undefined.");
106
+ const json = JSON.stringify(value);
107
+ if (json === undefined) throw new TypeError("This value cannot be stored as JSON.");
108
+ return new TextEncoder().encode(json);
109
+ }
110
+
111
+ function encodeMetadata(metadata) {
112
+ if (metadata === null || typeof metadata !== "object" || Array.isArray(metadata)) {
113
+ throw new TypeError("metadata is a plain object.");
114
+ }
115
+ return Buffer.from(JSON.stringify(metadata), "utf8").toString("base64");
116
+ }
117
+
118
+ function decodeMetadata(raw) {
119
+ if (!raw) return {};
120
+ try {
121
+ return JSON.parse(Buffer.from(raw, "base64").toString("utf8"));
122
+ } catch {
123
+ return {};
124
+ }
125
+ }
126
+
127
+ async function errorFrom(res) {
128
+ let body = null;
129
+ try {
130
+ body = await res.json();
131
+ } catch {
132
+ // not the JSON envelope (a proxy page, an empty HEAD body)
133
+ }
134
+ const requestId = body?.meta?.request_id ?? res.headers.get("x-request-id") ?? undefined;
135
+ const code = body?.code ?? `HTTP_${res.status}`;
136
+ const message = body?.error ?? `deploybase KV answered ${res.status}.`;
137
+ return new KVError(message, { code, status: res.status, requestId, details: body?.details });
138
+ }
139
+
140
+ // backoff is the wait before the next attempt, in milliseconds.
141
+ function backoff(ctx, code, retryAfter) {
142
+ if (retryAfter !== null && retryAfter !== "") {
143
+ const secs = Number(retryAfter);
144
+ if (Number.isFinite(secs) && secs >= 0) return Math.min(secs * 1000, MAX_RETRY_AFTER_MS);
145
+ }
146
+ const fixed = code === undefined ? null : RETRYABLE.get(code);
147
+ if (fixed) return fixed;
148
+ return 250 + Math.floor(ctx.random() * 250);
149
+ }
150
+
151
+ // request sends one call with retries. It returns the final answer (2xx, or an error status
152
+ // the caller interprets) and throws KVError after the last retryable failure. Each attempt
153
+ // has timeoutMs; a read whose Content-Length is over 100 KB gets the large timeout instead.
154
+ async function request(ctx, method, path, { headers = {}, body, timeoutMs, stream = false } = {}) {
155
+ const { base, token } = config(ctx);
156
+ const url = base + path;
157
+ let lastError;
158
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
159
+ if (attempt > 0) await ctx.sleep(lastError.wait);
160
+ const controller = new AbortController();
161
+ const started = Date.now();
162
+ let timer = setTimeout(() => controller.abort(), timeoutMs);
163
+ let res;
164
+ try {
165
+ res = await ctx.fetch(url, {
166
+ method,
167
+ headers: { authorization: `Bearer ${token}`, ...headers },
168
+ body,
169
+ signal: controller.signal,
170
+ });
171
+ } catch (err) {
172
+ clearTimeout(timer);
173
+ const timedOut = controller.signal.aborted;
174
+ lastError = {
175
+ error: new KVError(
176
+ timedOut ? `deploybase KV did not answer within ${timeoutMs} ms.` : "Could not reach deploybase KV.",
177
+ { code: timedOut ? "KV_TIMEOUT" : "KV_NETWORK_ERROR", cause: err },
178
+ ),
179
+ wait: backoff(ctx),
180
+ };
181
+ continue;
182
+ }
183
+ if (Number(res.headers.get("content-length")) > LARGE_VALUE_BYTES && ctx.timeouts.large > timeoutMs) {
184
+ clearTimeout(timer);
185
+ timer = setTimeout(() => controller.abort(), Math.max(0, ctx.timeouts.large - (Date.now() - started)));
186
+ }
187
+ if (res.status === 429 || res.status === 503) {
188
+ clearTimeout(timer);
189
+ const error = await errorFrom(res);
190
+ if (RETRYABLE.has(error.code)) {
191
+ lastError = { error, wait: backoff(ctx, error.code, res.headers.get("retry-after")) };
192
+ continue;
193
+ }
194
+ throw error;
195
+ }
196
+ if (stream && res.ok) {
197
+ // The caller reads the body; the timeout covered the wait for the headers.
198
+ clearTimeout(timer);
199
+ return res;
200
+ }
201
+ // Read the body under the same timeout, so a stalled body also ends the call.
202
+ try {
203
+ const bytes = new Uint8Array(await res.arrayBuffer());
204
+ clearTimeout(timer);
205
+ return { status: res.status, ok: res.ok, headers: res.headers, bytes };
206
+ } catch (err) {
207
+ clearTimeout(timer);
208
+ lastError = {
209
+ error: new KVError("The answer of deploybase KV was cut off.", { code: "KV_NETWORK_ERROR", cause: err }),
210
+ wait: backoff(ctx),
211
+ };
212
+ }
213
+ }
214
+ throw lastError.error;
215
+ }
216
+
217
+ function errorFromBytes(res) {
218
+ let body = null;
219
+ try {
220
+ body = JSON.parse(new TextDecoder().decode(res.bytes));
221
+ } catch {
222
+ // not the JSON envelope
223
+ }
224
+ return new KVError(body?.error ?? `deploybase KV answered ${res.status}.`, {
225
+ code: body?.code ?? `HTTP_${res.status}`,
226
+ status: res.status,
227
+ requestId: body?.meta?.request_id ?? res.headers.get("x-request-id") ?? undefined,
228
+ details: body?.details,
229
+ });
230
+ }
231
+
232
+ function decodeValue(bytes, type) {
233
+ switch (type) {
234
+ case "arrayBuffer":
235
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
236
+ case "text":
237
+ return new TextDecoder().decode(bytes);
238
+ default:
239
+ try {
240
+ return JSON.parse(new TextDecoder().decode(bytes));
241
+ } catch (err) {
242
+ throw new KVError('The value is not JSON. Read it with { type: "text" } or { type: "arrayBuffer" }.', {
243
+ code: "KV_NOT_JSON",
244
+ cause: err,
245
+ });
246
+ }
247
+ }
248
+ }
249
+
250
+ async function getEntry(ctx, storeName, key, opts = {}) {
251
+ checkKey(key);
252
+ const type = opts.type ?? "json";
253
+ if (!VALUE_TYPES.has(type)) {
254
+ throw new TypeError('type is "json", "text", "arrayBuffer" or "stream".');
255
+ }
256
+ const res = await request(ctx, "GET", keyPath(storeName, key), {
257
+ timeoutMs: ctx.timeouts.small,
258
+ stream: type === "stream",
259
+ });
260
+ if (res.status === 404) {
261
+ const err = res.bytes ? errorFromBytes(res) : await errorFrom(res);
262
+ if (err.code === "KV_NOT_FOUND") return null;
263
+ throw err;
264
+ }
265
+ if (!res.ok) throw res.bytes ? errorFromBytes(res) : await errorFrom(res);
266
+ const expires = res.headers.get("x-kv-expires-at");
267
+ return {
268
+ value: type === "stream" ? res.body : decodeValue(res.bytes, type),
269
+ version: res.headers.get("x-kv-version") ?? undefined,
270
+ metadata: decodeMetadata(res.headers.get("x-kv-metadata")),
271
+ expiresAt: expires ? new Date(Number(expires) * 1000) : null,
272
+ };
273
+ }
274
+
275
+ async function setKey(ctx, storeName, key, value, opts = {}) {
276
+ checkKey(key);
277
+ const bytes = encodeValue(value);
278
+ const headers = {
279
+ "content-type": "application/octet-stream",
280
+ // One id per call, sent on every attempt: a retry of a write that already landed is
281
+ // recognised by the service and answered as a success.
282
+ "x-kv-write-id": ctx.randomUUID(),
283
+ };
284
+ if (opts.onlyIfNew && opts.onlyIfVersion !== undefined) {
285
+ throw new TypeError("Use onlyIfNew or onlyIfVersion, not both.");
286
+ }
287
+ if (opts.onlyIfNew) headers["if-none-match"] = "*";
288
+ if (opts.onlyIfVersion !== undefined) headers["if-match"] = String(opts.onlyIfVersion);
289
+ if (opts.ttl !== undefined) {
290
+ if (!Number.isInteger(opts.ttl) || opts.ttl < MIN_TTL) {
291
+ throw new TypeError(`ttl is whole seconds, at least ${MIN_TTL}.`);
292
+ }
293
+ headers["x-kv-ttl"] = String(opts.ttl);
294
+ }
295
+ if (opts.metadata !== undefined) headers["x-kv-metadata"] = encodeMetadata(opts.metadata);
296
+
297
+ const res = await request(ctx, "PUT", keyPath(storeName, key), {
298
+ headers,
299
+ body: bytes,
300
+ timeoutMs: bytes.byteLength > LARGE_VALUE_BYTES ? ctx.timeouts.large : ctx.timeouts.small,
301
+ });
302
+ if (res.status === 412) return { modified: false };
303
+ if (!res.ok) throw errorFromBytes(res);
304
+ let version = res.headers.get("x-kv-version") ?? undefined;
305
+ if (version === undefined) {
306
+ try {
307
+ version = JSON.parse(new TextDecoder().decode(res.bytes)).version;
308
+ } catch {
309
+ // no body: the header is the contract, the body a convenience
310
+ }
311
+ }
312
+ return { modified: true, version };
313
+ }
314
+
315
+ async function deleteKey(ctx, storeName, key, opts = {}) {
316
+ checkKey(key);
317
+ const headers = { "x-kv-write-id": ctx.randomUUID() };
318
+ if (opts.onlyIfVersion !== undefined) headers["if-match"] = String(opts.onlyIfVersion);
319
+ const res = await request(ctx, "DELETE", keyPath(storeName, key), { headers, timeoutMs: ctx.timeouts.small });
320
+ if (res.status === 412) return { modified: false };
321
+ if (res.status === 404) {
322
+ const err = errorFromBytes(res);
323
+ if (err.code === "KV_NOT_FOUND") return { modified: false };
324
+ throw err;
325
+ }
326
+ if (!res.ok) throw errorFromBytes(res);
327
+ return { modified: true };
328
+ }
329
+
330
+ async function listKeys(ctx, storeName, opts = {}) {
331
+ const params = new URLSearchParams();
332
+ if (opts.prefix) params.set("prefix", opts.prefix);
333
+ if (opts.limit !== undefined) {
334
+ if (!Number.isInteger(opts.limit) || opts.limit < 1 || opts.limit > 1000) {
335
+ throw new TypeError("limit is 1 to 1000.");
336
+ }
337
+ params.set("limit", String(opts.limit));
338
+ }
339
+ if (opts.cursor) params.set("cursor", opts.cursor);
340
+ const qs = params.toString();
341
+ const res = await request(ctx, "GET", `/v1/stores/${storeName}/keys${qs ? `?${qs}` : ""}`, {
342
+ timeoutMs: ctx.timeouts.small,
343
+ });
344
+ if (!res.ok) throw errorFromBytes(res);
345
+ const page = JSON.parse(new TextDecoder().decode(res.bytes));
346
+ return {
347
+ keys: (page.keys ?? []).map((k) => ({
348
+ key: k.key,
349
+ version: k.version,
350
+ size: k.size,
351
+ modifiedAt: new Date(k.modified_at),
352
+ })),
353
+ cursor: page.cursor || undefined,
354
+ done: page.done === true,
355
+ };
356
+ }
357
+
358
+ /** The client of the default store, configured from the function's environment. */
359
+ export const kv = createClient();