@vite-hub/kv 0.0.4 → 0.3.1

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 (63) hide show
  1. package/README.md +110 -14
  2. package/dist/batch--v0ri69O.js +40 -0
  3. package/dist/cli-DpPhz_Ek.d.ts +163 -0
  4. package/dist/cli.d.ts +17 -0
  5. package/dist/cli.js +469 -0
  6. package/dist/cloudflare-env-lOtHHsgP.js +46 -0
  7. package/dist/cloudflare-env-lookup-Bs0VDpU5.js +42 -0
  8. package/dist/cloudflare-kv-BIEUFzRT.js +187 -0
  9. package/dist/cloudflare-kv-local-BBw3ZT1K.js +71 -0
  10. package/dist/config-BXEVoZE3.js +250 -0
  11. package/dist/{dist-DDW1iC5f.js → create-storage-BGsrQKw3.js} +266 -115
  12. package/dist/cursor-history-BqIQePNP.js +165 -0
  13. package/dist/database-72Jk3VVk.js +250 -0
  14. package/dist/deno-kv-BM9mYdUp.js +128 -0
  15. package/dist/dev-peer-CHafxbtj.js +238 -0
  16. package/dist/driver-BwxgaQ-f.d.ts +15 -0
  17. package/dist/durability.d.ts +17 -0
  18. package/dist/durability.js +53 -0
  19. package/dist/error-diagnostics-BxqvtEIb.js +147 -0
  20. package/dist/errors-DbwufFZp.js +60 -0
  21. package/dist/errors.d.ts +23 -7
  22. package/dist/errors.js +2 -20
  23. package/dist/fs-lite-BLZId9_P.js +386 -0
  24. package/dist/fs-lite-RAoxu8L0.js +2 -0
  25. package/dist/index.d.ts +10 -4
  26. package/dist/index.js +364 -109
  27. package/dist/inspect-BIKQsqX4.js +118 -0
  28. package/dist/invariant-DolT9EEx.js +22 -0
  29. package/dist/main-F3Y22_uV.js +2353 -0
  30. package/dist/object-Da1zyPCR.js +11 -0
  31. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  32. package/dist/operations-B-WZ7P1h.js +1351 -0
  33. package/dist/operations-Ch-gKaey.js +441 -0
  34. package/dist/operations.d.ts +75 -0
  35. package/dist/operations.js +318 -0
  36. package/dist/redis-shared-E5mahECF.js +94 -0
  37. package/dist/results-p7nPCnaJ.js +6 -0
  38. package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
  39. package/dist/runtime/cloudflare-kv.d.ts +3 -4
  40. package/dist/runtime/cloudflare-kv.js +1 -23
  41. package/dist/runtime/cloudflare-request-env.d.ts +7 -0
  42. package/dist/runtime/cloudflare-request-env.js +11 -0
  43. package/dist/runtime/nitro-plugin.d.ts +12 -0
  44. package/dist/runtime/nitro-plugin.js +22 -0
  45. package/dist/runtime/redis-driver.d.ts +11 -0
  46. package/dist/runtime/redis-driver.js +113 -0
  47. package/dist/runtime/unstorage-driver.d.ts +14 -0
  48. package/dist/runtime/unstorage-driver.js +33 -0
  49. package/dist/runtime/upstash-driver.d.ts +4 -6
  50. package/dist/runtime/upstash-driver.js +60 -110
  51. package/dist/{driver-BT9WefKi.d.ts → types-Bj3EQoRg.d.ts} +16 -11
  52. package/dist/types-DEiKew_3.d.ts +312 -0
  53. package/dist/upstash-DDlqTttY.js +40 -0
  54. package/dist/utils2-FozcTsmb.js +31 -0
  55. package/dist/virtual-module.d.ts +2 -0
  56. package/dist/virtual.d.ts +1 -1
  57. package/dist/vite.d.ts +159 -14
  58. package/dist/vite.js +1329 -2898
  59. package/package.json +68 -19
  60. package/dist/config-aM9Ae7tH.js +0 -110
  61. package/dist/deno-kv-cJx3jU10.js +0 -69
  62. package/dist/fs-lite-BxzdiJSi.js +0 -79
  63. package/dist/types-CO0DRjJa.d.ts +0 -78
@@ -0,0 +1,14 @@
1
+ import { t as Driver } from "../types-Bj3EQoRg.js";
2
+ //#region src/runtime/unstorage-driver.d.ts
3
+ export interface KVStorageDriverOptions {
4
+ /** The named KV store. Default: the default store. */
5
+ store?: string;
6
+ /** Key prefix inside the store, so the mount's keys stay apart from the app's other keys. Default: no prefix. */
7
+ base?: string;
8
+ }
9
+ /**
10
+ * Unstorage driver over one KV store, for Nitro storage mounts such as `kv` and `cache`.
11
+ * It resolves the store on each call, so a Cloudflare store uses the binding of the current request.
12
+ */
13
+ export default function createKVStorageDriver(options?: KVStorageDriverOptions): Driver<KVStorageDriverOptions>;
14
+ //#endregion
@@ -0,0 +1,33 @@
1
+ import { o as normalizeKey } from "../utils2-FozcTsmb.js";
2
+ import { kv } from "@vite-hub/kv";
3
+ //#region src/runtime/unstorage-driver.ts
4
+ async function unwrap(pending) {
5
+ const [error, value] = await pending;
6
+ if (error) throw error;
7
+ return value;
8
+ }
9
+ /**
10
+ * Unstorage driver over one KV store, for Nitro storage mounts such as `kv` and `cache`.
11
+ * It resolves the store on each call, so a Cloudflare store uses the binding of the current request.
12
+ */
13
+ function createKVStorageDriver(options = {}) {
14
+ const base = normalizeKey(options.base);
15
+ const prefix = base ? `${base}:` : "";
16
+ const key = (name) => prefix + normalizeKey(name);
17
+ const store = () => options.store === void 0 ? kv : kv.store(options.store);
18
+ return {
19
+ name: "vitehub-kv",
20
+ options,
21
+ hasItem: (name) => unwrap(store().has(key(name))),
22
+ getItem: (name) => unwrap(store().get(key(name), { type: "text" })),
23
+ getItemRaw: (name) => unwrap(store().get(key(name), { type: "bytes" })),
24
+ setItem: (name, value, opts) => unwrap(store().set(key(name), value, typeof opts?.ttl === "number" ? { ttl: opts.ttl } : void 0)),
25
+ removeItem: (name) => unwrap(store().delete(key(name))),
26
+ async getKeys(keyBase) {
27
+ return (await unwrap(store().keys(key(keyBase)))).map((name) => name.slice(prefix.length));
28
+ },
29
+ clear: (keyBase) => unwrap(store().clear(key(keyBase)))
30
+ };
31
+ }
32
+ //#endregion
33
+ export { createKVStorageDriver as default };
@@ -1,7 +1,5 @@
1
- import { v as ResolvedUpstashKVStoreConfig } from "../types-CO0DRjJa.js";
2
- import { t as KVRuntimeDriver } from "../driver-BT9WefKi.js";
3
-
1
+ import { R as ResolvedUpstashKVStoreConfig } from "../types-DEiKew_3.js";
2
+ import { t as KVRuntimeDriver } from "../driver-BwxgaQ-f.js";
4
3
  //#region src/runtime/upstash-driver.d.ts
5
- declare function createUpstashKVDriver(options: ResolvedUpstashKVStoreConfig): KVRuntimeDriver;
6
- //#endregion
7
- export { createUpstashKVDriver as default };
4
+ export default function createUpstashKVDriver(options: ResolvedUpstashKVStoreConfig): KVRuntimeDriver;
5
+ //#endregion
@@ -1,119 +1,69 @@
1
+ import { t as invariant } from "../invariant-DolT9EEx.js";
2
+ import { n as kvErrorDiagnostics } from "../error-diagnostics-BxqvtEIb.js";
3
+ import { o as normalizeKey } from "../utils2-FozcTsmb.js";
4
+ import { t as chunks } from "../batch--v0ri69O.js";
5
+ import { a as redisIncrementScript, i as redisIncrementResult, n as escapeRedisGlob, o as redisTTLSeconds, r as redisDeleteIfEqualsScript, t as createPortableRedisKeyLister } from "../redis-shared-E5mahECF.js";
1
6
  import createDriver from "unstorage/drivers/upstash";
2
7
  //#region src/runtime/upstash-driver.ts
3
- const incrementScript = `
4
- local existed = redis.call('EXISTS', KEYS[1])
5
- local current = redis.call('GET', KEYS[1])
6
- if current then
7
- local negative = string.sub(current, 1, 1) == '-'
8
- local digits = negative and string.sub(current, 2) or current
9
- local boundary = negative and '9007199254740992' or '9007199254740991'
10
- local beyond = #digits > #boundary or (#digits == #boundary and digits > boundary)
11
- local at_positive_boundary = not negative and digits == boundary
12
- if beyond or at_positive_boundary then
13
- return redis.error_reply('Atomic KV increment exceeds the JavaScript safe integer range.')
14
- end
15
- end
16
- local value = redis.call('INCR', KEYS[1])
17
- if existed == 0 then
18
- redis.call('EXPIRE', KEYS[1], ARGV[1])
19
- end
20
- return value
21
- `;
22
- function normalizeTTL(ttl) {
23
- if (!Number.isFinite(ttl) || ttl <= 0) throw new TypeError("Atomic KV increment requires a positive TTL in seconds.");
24
- const seconds = Math.ceil(ttl);
25
- if (!Number.isSafeInteger(seconds)) throw new RangeError("Atomic KV increment TTL exceeds the supported integer range.");
26
- return seconds;
27
- }
28
- function decodeCursor(cursor) {
29
- if (!cursor) return { cursor: "0" };
30
- try {
31
- const value = JSON.parse(decodeURIComponent(cursor));
32
- if (typeof value.cursor !== "string" || value.cursor.length === 0) throw new Error();
33
- return value;
34
- } catch {
35
- throw new TypeError("Invalid Upstash KV cursor.");
36
- }
37
- }
38
- function encodeCursor(cursor) {
39
- return encodeURIComponent(JSON.stringify(cursor));
40
- }
41
- function escapeRedisGlob(value) {
42
- return value.replaceAll(/([*?[\\\]])/g, "\\$1");
43
- }
8
+ const keyBatchSize = 1e3;
44
9
  function createUpstashKVDriver(options) {
45
- const driver = createDriver(options);
46
- const continuations = /* @__PURE__ */ new Map();
47
- const maximumContinuations = 32;
48
- const maximumContinuationBytes = 1024 * 1024;
49
- let continuationBytes = 0;
50
- driver.getAndDeleteItem = async (key) => driver.getInstance().getdel(key);
51
- driver.incrementItem = async (key, ttl) => {
52
- const value = Number(await driver.getInstance().eval(incrementScript, [key], [String(normalizeTTL(ttl))]));
53
- if (!Number.isSafeInteger(value)) throw new RangeError("Atomic KV increment exceeds the JavaScript safe integer range.");
54
- return value;
10
+ const base = normalizeKey(options.base);
11
+ invariant(base, "resolveUpstashStore() gives an Upstash KV store a non-empty `base`, which keeps clear() inside the store");
12
+ const driver = createDriver({
13
+ lib: () => import("@upstash/redis"),
14
+ ...options,
15
+ base,
16
+ automaticDeserialization: false
17
+ });
18
+ const client = () => driver.getInstance();
19
+ const prefixed = (key) => `${base}:${key}`;
20
+ const unprefixed = (key) => key.startsWith(`${base}:`) ? key.slice(base.length + 1) : key;
21
+ driver.setItem = async (key, value, setOptions) => {
22
+ const ttl = setOptions?.ttl;
23
+ if (ttl !== void 0 && ttl !== null && ttl !== 0 && typeof ttl !== "number") throw kvErrorDiagnostics.KV_INVALID_TTL();
24
+ await (await client()).set(prefixed(key), value, typeof ttl === "number" && ttl !== 0 ? { ex: redisTTLSeconds(ttl) } : void 0);
55
25
  };
56
- function releaseContinuation(cursor) {
57
- const continuation = continuations.get(cursor);
58
- if (!continuation) return;
59
- clearTimeout(continuation.timeout);
60
- continuationBytes -= continuation.bytes;
61
- continuations.delete(cursor);
62
- }
63
- function retainContinuation(keys, providerCursor) {
64
- const encoder = new TextEncoder();
65
- const bytes = keys.reduce((total, key) => total + encoder.encode(key).byteLength, 0);
66
- if (bytes > maximumContinuationBytes) throw new RangeError("Upstash KV scan overflow exceeds the continuation size limit.");
67
- while (continuationBytes + bytes > maximumContinuationBytes) {
68
- const oldestCursor = continuations.keys().next().value;
69
- if (!oldestCursor) break;
70
- releaseContinuation(oldestCursor);
71
- }
72
- const cursor = globalThis.crypto.randomUUID();
73
- const timeout = setTimeout(() => releaseContinuation(cursor), 15 * 6e4);
74
- timeout.unref?.();
75
- continuations.set(cursor, {
76
- bytes,
77
- cursor: providerCursor,
78
- keys,
79
- timeout
80
- });
81
- continuationBytes += bytes;
82
- while (continuations.size > maximumContinuations) {
83
- const oldestCursor = continuations.keys().next().value;
84
- if (oldestCursor) releaseContinuation(oldestCursor);
85
- }
86
- return cursor;
87
- }
88
- driver.listKeys = async ({ cursor, limit, prefix = "" }) => {
89
- const retained = cursor ? continuations.get(cursor) : void 0;
90
- if (cursor && !retained && /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(cursor)) throw Object.assign(/* @__PURE__ */ new TypeError("Invalid or expired Upstash KV cursor."), { code: "KV_CURSOR_EXPIRED" });
91
- if (retained && cursor) releaseContinuation(cursor);
92
- let providerCursor;
93
- let keys;
94
- if (retained) {
95
- providerCursor = retained.cursor;
96
- keys = retained.keys;
97
- } else {
98
- providerCursor = decodeCursor(cursor).cursor;
99
- const scanned = await driver.getInstance().scan(providerCursor, {
100
- count: limit,
101
- match: `${escapeRedisGlob(prefix)}*`
26
+ driver.getItems = async (items) => {
27
+ const values = [];
28
+ for (const batch of chunks(items, keyBatchSize)) values.push(...await (await client()).mget(...batch.map((item) => prefixed(item.key))));
29
+ return items.map((item, index) => ({
30
+ key: item.key,
31
+ value: values[index] ?? null
32
+ }));
33
+ };
34
+ driver.clear = async (prefix) => {
35
+ const keys = [];
36
+ let cursor = "0";
37
+ do {
38
+ const [next, page] = await (await client()).scan(cursor, {
39
+ count: keyBatchSize,
40
+ match: `${escapeRedisGlob(prefixed(prefix ?? ""))}*`
102
41
  });
103
- providerCursor = String(scanned[0]);
104
- keys = [...new Set(scanned[1])];
105
- }
106
- const pageKeys = keys.slice(0, limit);
107
- const overflow = keys.slice(limit);
108
- if (overflow.length > 0) return {
109
- keys: pageKeys,
110
- cursor: retainContinuation(overflow, providerCursor)
111
- };
112
- if (providerCursor === "0") return { keys: pageKeys };
113
- return {
114
- keys: pageKeys,
115
- cursor: encodeCursor({ cursor: providerCursor })
42
+ cursor = String(next);
43
+ keys.push(...page);
44
+ } while (cursor !== "0");
45
+ for (const batch of chunks(keys, keyBatchSize)) await (await client()).del(...batch);
46
+ };
47
+ driver.getAndDeleteItem = async (key) => (await client()).getdel(prefixed(key));
48
+ driver.incrementItem = async (key, ttl) => redisIncrementResult(await (await client()).eval(redisIncrementScript, [prefixed(key)], [String(redisTTLSeconds(ttl))]));
49
+ driver.deleteIfEqualsItem = async (key, expected) => Number(await (await client()).eval(redisDeleteIfEqualsScript, [prefixed(key)], [expected])) === 1;
50
+ driver.setIfAbsentItem = async (key, value, ttl) => {
51
+ const setOptions = ttl === void 0 ? { nx: true } : {
52
+ ex: redisTTLSeconds(ttl),
53
+ nx: true
116
54
  };
55
+ return await (await client()).set(prefixed(key), value, setOptions) === "OK";
56
+ };
57
+ driver.listKeys = createPortableRedisKeyLister("Upstash KV", async (cursor, match, count) => {
58
+ const [next, keys] = await (await client()).scan(cursor, {
59
+ count,
60
+ match: `${escapeRedisGlob(base)}:${match}`
61
+ });
62
+ return [String(next), keys.map(unprefixed)];
63
+ });
64
+ const dispose = driver.dispose;
65
+ driver.dispose = async () => {
66
+ await dispose?.call(driver);
117
67
  };
118
68
  return driver;
119
69
  }
@@ -1,10 +1,22 @@
1
- import { o as KVListOptions, s as KVListPage } from "./types-CO0DRjJa.js";
2
- //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.7_@azure+identity@4.13.1_@azure+storage-blob@12.31.0_@netlify+blo_8194820fdb6706e28a1ff20070ef4217/node_modules/unstorage/dist/_chunks/types.d.mts
3
- //#region src/types.d.ts
1
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/_chunks/types.d.mts
4
2
  type StorageValue = null | string | number | boolean | object;
5
3
  type WatchEvent = "update" | "remove";
6
4
  type WatchCallback = (event: WatchEvent, key: string) => any;
7
5
  type MaybePromise<T> = T | Promise<T>;
6
+ /** Types that {@link Storage.getItem} can convert the stored value to. */
7
+ type GetItemType = keyof GetItemTypeMap;
8
+ interface GetItemTypeMap {
9
+ text: string;
10
+ json: JSONValue;
11
+ bytes: Uint8Array;
12
+ stream: ReadableStream<Uint8Array>;
13
+ blob: Blob;
14
+ }
15
+ type JSONValue = string | number | boolean | null | JSONObject | JSONArray;
16
+ interface JSONObject {
17
+ [key: string]: JSONValue;
18
+ }
19
+ type JSONArray = JSONValue[];
8
20
  type Unwatch = () => MaybePromise<void>;
9
21
  interface StorageMeta {
10
22
  atime?: Date;
@@ -54,11 +66,4 @@ interface Driver<OptionsT = any, InstanceT = any> {
54
66
  watch?: (callback: WatchCallback) => MaybePromise<Unwatch>;
55
67
  }
56
68
  //#endregion
57
- //#region src/runtime/driver.d.ts
58
- type KVRuntimeDriver = Driver & Record<string, unknown> & {
59
- getAndDeleteItem?: <T = unknown>(key: string) => Promise<T | null>;
60
- incrementItem?: (key: string, ttl: number) => Promise<number>;
61
- listKeys: (options: KVListOptions) => Promise<KVListPage>;
62
- };
63
- //#endregion
64
- export { KVRuntimeDriver as t };
69
+ export { TransactionOptions as i, GetItemType as n, GetItemTypeMap as r, Driver as t };
@@ -0,0 +1,312 @@
1
+ import { n as GetItemType, r as GetItemTypeMap } from "./types-Bj3EQoRg.js";
2
+ import { Result } from "@vite-hub/runtime";
3
+ //#region src/types.d.ts
4
+ type KVDriver = "cloudflare" | "database" | "deno-kv" | "fs-lite" | "redis" | "upstash";
5
+ /**
6
+ * The atomic operations of each driver. A store returns `KV_UNSUPPORTED_OPERATION` for an atomic operation that its
7
+ * driver does not list. `get`, `set`, `delete`, `has`, `keys`, `list`, and `clear` work on every driver.
8
+ */
9
+ interface KVDriverAtomicOperations {
10
+ "cloudflare": never;
11
+ "database": "deleteIfEquals" | "getAndDelete" | "increment" | "setIfAbsent";
12
+ "deno-kv": "setIfAbsent";
13
+ "fs-lite": "setIfAbsent";
14
+ "redis": "deleteIfEquals" | "getAndDelete" | "increment" | "setIfAbsent";
15
+ "upstash": "deleteIfEquals" | "getAndDelete" | "increment" | "setIfAbsent";
16
+ }
17
+ /** The drivers that run `operation` atomically, for example `KVDriversWith<"deleteIfEquals">`. */
18
+ type KVDriversWith<TOperation extends KVAtomicOperation> = { [Driver in KVDriver]: TOperation extends KVDriverAtomicOperations[Driver] ? Driver : never; }[KVDriver];
19
+ /** The KV operations that need an atomic provider operation. */
20
+ type KVAtomicOperation = "deleteIfEquals" | "getAndDelete" | "increment" | "setIfAbsent";
21
+ interface CloudflareKVStoreConfig {
22
+ driver: "cloudflare";
23
+ binding?: string;
24
+ /**
25
+ * In `vite dev`, use the real namespace: ViteHub writes `remote: true` on the Wrangler binding and does not fall back
26
+ * to the local `fs-lite` store. Writes change real data. Builds ignore it.
27
+ */
28
+ remote?: boolean;
29
+ /** Cloudflare KV namespace id. When omitted, the build reads the id recorded by `vitehub provision run`. */
30
+ namespaceId?: string;
31
+ /** Cloudflare KV namespace title that `vitehub provision run` finds or creates when `namespaceId` is not set. */
32
+ namespaceName?: string;
33
+ }
34
+ interface UpstashKVStoreConfig {
35
+ driver: "upstash";
36
+ /** An Upstash store is always remote, in `vite dev` too. */
37
+ remote?: true;
38
+ token?: string;
39
+ url?: string;
40
+ /**
41
+ * Prefix of every key in Upstash. Default `vitehub:kv:<store>`, as for a Redis store, so `kv.clear()` and `kv.keys()`
42
+ * stay inside the store. An empty value uses the default.
43
+ */
44
+ base?: string;
45
+ }
46
+ interface RedisKVStoreConfig {
47
+ driver: "redis";
48
+ /**
49
+ * The Redis URL, such as `redis://user:password@host:6379`. Default `env:REDIS_URL`: the server reads `REDIS_URL`
50
+ * when the store starts, not at build time. `env:<NAME>` reads another variable. A literal URL goes into the build
51
+ * output, so keep passwords in a variable.
52
+ */
53
+ url?: string;
54
+ /**
55
+ * Prefix of every key in Redis. Default `vitehub:kv:<store>`, which keeps keys that are not ViteHub's apart.
56
+ * The generated store segment escapes `%`, `:`, `/`, `\`, and `?`; an empty store name uses `%`.
57
+ * Two ViteHub apps on one Redis database share this default, so give each app its own database or `base`.
58
+ * An empty value uses the default.
59
+ */
60
+ base?: string;
61
+ /** A Redis store uses the server that `url` points to, in `vite dev` too. */
62
+ remote?: never;
63
+ }
64
+ interface DatabaseKVStoreConfig {
65
+ driver: "database";
66
+ /**
67
+ * The Database that keeps the keys, in the table `vitehub_kv`. Default `"default"`. The store creates the table when
68
+ * it is missing. Postgres and libSQL work. D1 does not.
69
+ */
70
+ database?: string;
71
+ /** A Database store uses the Database of the app, in `vite dev` too. */
72
+ remote?: never;
73
+ }
74
+ interface DenoKVStoreConfig {
75
+ driver: "deno-kv";
76
+ path?: string;
77
+ /** A Deno KV store is local. */
78
+ remote?: false;
79
+ }
80
+ interface FsLiteKVStoreConfig {
81
+ driver: "fs-lite";
82
+ base?: string;
83
+ /** An `fs-lite` store is local. */
84
+ remote?: false;
85
+ }
86
+ /** A store without `driver`. ViteHub infers the driver from the host and the env. */
87
+ interface InferredKVStoreConfig {
88
+ driver?: undefined;
89
+ /**
90
+ * In `vite dev`, the inferred store is local unless this is `true`: Upstash env and the Vercel host do not select
91
+ * Upstash, and the Cloudflare host uses the local `fs-lite` store when the dev runtime has no KV binding. With
92
+ * `true`, `vite dev` uses the real store, so writes change real data. Builds ignore it.
93
+ */
94
+ remote?: boolean;
95
+ }
96
+ type KVStoreConfig = CloudflareKVStoreConfig | DatabaseKVStoreConfig | DenoKVStoreConfig | FsLiteKVStoreConfig | RedisKVStoreConfig | UpstashKVStoreConfig;
97
+ interface ResolvedCloudflareKVStoreConfig extends CloudflareKVStoreConfig {
98
+ binding: string;
99
+ /** Only in `vite dev`: the `fs-lite` directory that the store uses when the runtime has no binding. */
100
+ localBase?: string;
101
+ /** Only in `vite dev`. */
102
+ remote?: true;
103
+ }
104
+ interface ResolvedUpstashKVStoreConfig extends UpstashKVStoreConfig {
105
+ base: string;
106
+ token: string;
107
+ url: string;
108
+ }
109
+ interface ResolvedDenoKVStoreConfig extends DenoKVStoreConfig {
110
+ path?: string;
111
+ }
112
+ interface ResolvedFsLiteKVStoreConfig extends FsLiteKVStoreConfig {
113
+ base: string;
114
+ /** {@link ResolvedDatabaseKVStoreConfig.inferred} */
115
+ inferred?: true;
116
+ }
117
+ interface ResolvedRedisKVStoreConfig extends RedisKVStoreConfig {
118
+ base: string;
119
+ url: string;
120
+ }
121
+ interface ResolvedDatabaseKVStoreConfig extends DatabaseKVStoreConfig {
122
+ database: string;
123
+ /** The value of the `namespace` column for the keys of this store: the store name. */
124
+ namespace: string;
125
+ /**
126
+ * The build inferred this store on Node. The server keeps this driver regardless of `REDIS_URL`.
127
+ */
128
+ inferred?: true;
129
+ }
130
+ type ResolvedKVStoreConfig = ResolvedCloudflareKVStoreConfig | ResolvedDatabaseKVStoreConfig | ResolvedDenoKVStoreConfig | ResolvedFsLiteKVStoreConfig | ResolvedRedisKVStoreConfig | ResolvedUpstashKVStoreConfig;
131
+ type KVStoreName = "default" | (string & {});
132
+ interface KVStoresConfig {
133
+ stores: Record<string, KVStoreConfig>;
134
+ }
135
+ type KVOptions = KVStoreConfig | InferredKVStoreConfig | KVStoresConfig | false;
136
+ interface ResolvedKVModuleOptions {
137
+ store: ResolvedKVStoreConfig;
138
+ stores?: Record<string, ResolvedKVStoreConfig>;
139
+ }
140
+ type KVOperation = "clear" | "delete" | "deleteIfEquals" | "get" | "getAndDelete" | "getMany" | "has" | "increment" | "keys" | "list" | "lock" | "set" | "setIfAbsent" | "setMany";
141
+ /** Codes that KV operations return in the `[error, data]` tuple. Config errors throw instead. */
142
+ type KVErrorCode = "KV_INVALID_CURSOR" | "KV_INVALID_LIMIT" | "KV_INVALID_OPTION" | "KV_INVALID_TTL" | "KV_INVALID_VALUE" | "KV_INVALID_WAIT" | "KV_KEY_TOO_LONG" | "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION" | "KV_VALUE_TOO_LARGE";
143
+ interface KVListOptions {
144
+ /** Opaque continuation cursor returned by a previous page. */
145
+ cursor?: string;
146
+ /** Maximum number of keys to read. Must be a positive integer. */
147
+ limit: number;
148
+ prefix?: string;
149
+ }
150
+ /** What `kv.get()` converts the stored value to: `text`, `json`, `bytes`, `stream`, or `blob`. */
151
+ type KVGetType = GetItemType;
152
+ /** The value type `kv.get()` returns for each {@link KVGetType}. */
153
+ type KVGetTypeMap = GetItemTypeMap;
154
+ /** Options of `kv.get()`. Other fields go to the driver. */
155
+ type KVGetOptions<K extends KVGetType | undefined = KVGetType | undefined> = Record<string, unknown> & {
156
+ type?: K;
157
+ };
158
+ /** A read value: the caller's `T` without a `type`, the converted type with one. */
159
+ type KVValue<T, K> = K extends KVGetType ? KVGetTypeMap[K] : T;
160
+ /** Options of `kv.set()`, `kv.setMany()`, and `kv.setIfAbsent()`. Other fields return `KV_INVALID_OPTION`. */
161
+ interface KVSetOptions {
162
+ /** Seconds until the key expires, a positive number. Every driver expires the key. Cloudflare KV keeps it at least 60 seconds. */
163
+ ttl?: number;
164
+ }
165
+ /** Options of `kv.lock()`. */
166
+ interface KVLockOptions {
167
+ /**
168
+ * Seconds until the lock expires, so a crashed holder never keeps it. Pick a value longer than the work.
169
+ * KV does not renew a lock: when the work runs longer than `ttl`, another runner can take the lock.
170
+ */
171
+ ttl: number;
172
+ /** Seconds to wait for a held lock, polling with backoff. Default `0`: return `{ acquired: false }` at once. */
173
+ wait?: number;
174
+ }
175
+ /** Codes that `kv.lock().run()` and `kv.lock().acquire()` return. */
176
+ type KVLockErrorCode = "KV_INVALID_TTL" | "KV_INVALID_WAIT" | "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION";
177
+ /** The data of `kv.lock().run()`: the callback's value, or `acquired: false` when another runner held the lock. */
178
+ type KVLockRunResult<T> = {
179
+ acquired: true;
180
+ value: T;
181
+ } | {
182
+ acquired: false;
183
+ };
184
+ /** The data of `kv.lock().acquire()`. */
185
+ type KVLockAcquisition = {
186
+ acquired: true;
187
+ /**
188
+ * Deletes the lock only when this runner still holds it. Returns `true` when it deleted the lock and `false` when
189
+ * the lock had expired, so another runner can hold it now.
190
+ */
191
+ release(): Promise<Result<boolean, "KV_OPERATION_FAILED">>;
192
+ } | {
193
+ acquired: false;
194
+ };
195
+ /** A lock on one key. Create it with `kv.lock(key, options)`. */
196
+ interface KVLock {
197
+ /**
198
+ * Takes the lock, runs `fn`, and releases the lock, also when `fn` throws. An error from `fn` is thrown again after
199
+ * the release. Returns `{ acquired: false }` without calling `fn` when another runner holds the lock after `wait`.
200
+ * A release that fails returns `KV_OPERATION_FAILED` after `fn` ran; the lock then expires after `ttl`.
201
+ */
202
+ run<T>(fn: () => T): Promise<Result<KVLockRunResult<Awaited<T>>, KVLockErrorCode>>;
203
+ /** Takes the lock and returns a `release()` function. Prefer `run()`, which always releases. */
204
+ acquire(): Promise<Result<KVLockAcquisition, KVLockErrorCode>>;
205
+ }
206
+ /** One entry of `kv.setMany()`. */
207
+ interface KVEntry<T = unknown> {
208
+ key: string;
209
+ value: T;
210
+ }
211
+ interface KVListPage {
212
+ /** Provider-ordered keys. */
213
+ keys: string[];
214
+ /** Omitted when enumeration is complete. */
215
+ cursor?: string;
216
+ }
217
+ /**
218
+ * Each method returns `[error, data]`. `error.code` is one of the codes in the method type.
219
+ * Config errors, for example an unknown store name, throw.
220
+ */
221
+ interface KVStorage {
222
+ clear(base?: string, options?: unknown): Promise<Result<void, "KV_OPERATION_FAILED">>;
223
+ delete(key: string, options?: unknown): Promise<Result<void, "KV_KEY_TOO_LONG" | "KV_OPERATION_FAILED">>;
224
+ /**
225
+ * Deletes the key only when its value equals `expected`, in one atomic step. Returns `true` when this call deleted it.
226
+ * KV compares the stored text with `expected` serialized as `set()` stores it, so `{ a: 1, b: 2 }` and
227
+ * `{ b: 2, a: 1 }` are different values. Use it to free a token that only its owner may free.
228
+ * The drivers in {@link KVDriversWith}`<"deleteIfEquals">` support it. The others return `KV_UNSUPPORTED_OPERATION`.
229
+ */
230
+ deleteIfEquals<T = unknown>(key: string, expected: T): Promise<Result<boolean, "KV_INVALID_VALUE" | "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION">>;
231
+ /**
232
+ * Reads a value or returns `null`. Without `options.type`, a string value is parsed as JSON, so `"123"` reads back as `123`.
233
+ * `{ type: "text" }` returns the stored text, and `json`, `bytes`, `stream`, and `blob` convert it to that type.
234
+ */
235
+ get<T = unknown, K extends KVGetType | undefined = undefined>(key: string, options?: KVGetOptions<K>): Promise<Result<KVValue<T, K> | null, "KV_KEY_TOO_LONG" | "KV_OPERATION_FAILED">>;
236
+ /**
237
+ * Reads many keys in one call. Returns one value per key, in the order of `keys`, with `null` for a missing key.
238
+ * `options` works as in `get()` and applies to every key. Stores with a batch read use it: Cloudflare KV reads 100
239
+ * keys per call, Redis and Upstash use `MGET`, and the `database` driver runs one query. Other stores read the keys
240
+ * one by one, 16 at a time.
241
+ */
242
+ getMany<T = unknown, K extends KVGetType | undefined = undefined>(keys: readonly string[], options?: KVGetOptions<K>): Promise<Result<Array<KVValue<T, K> | null>, "KV_KEY_TOO_LONG" | "KV_OPERATION_FAILED">>;
243
+ /**
244
+ * Atomically returns and deletes a value. `{ type: "text" }` returns the stored text.
245
+ * The drivers in {@link KVDriversWith}`<"getAndDelete">` support it. The others return `KV_UNSUPPORTED_OPERATION`.
246
+ */
247
+ getAndDelete<T = unknown, K extends "text" | undefined = undefined>(key: string, options?: {
248
+ type?: K;
249
+ }): Promise<Result<KVValue<T, K> | null, "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION">>;
250
+ has(key: string, options?: unknown): Promise<Result<boolean, "KV_KEY_TOO_LONG" | "KV_OPERATION_FAILED">>;
251
+ /**
252
+ * Atomically increments a counter. The TTL is applied only when the counter is created.
253
+ * The drivers in {@link KVDriversWith}`<"increment">` support it. The others return `KV_UNSUPPORTED_OPERATION`.
254
+ */
255
+ increment(key: string, ttl: number): Promise<Result<number, "KV_INVALID_TTL" | "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION">>;
256
+ keys(base?: string, options?: unknown): Promise<Result<string[], "KV_OPERATION_FAILED">>;
257
+ list(options: KVListOptions): Promise<Result<KVListPage, "KV_INVALID_CURSOR" | "KV_INVALID_LIMIT" | "KV_OPERATION_FAILED">>;
258
+ /**
259
+ * A lock on `key` that one runner holds at a time, across server processes that share the store. It writes a random
260
+ * owner token with `setIfAbsent()` and a TTL, and frees it with `deleteIfEquals()`, so a runner never deletes a lock
261
+ * that another runner took after it expired. Nothing renews a lock.
262
+ * The drivers in {@link KVDriversWith}`<"deleteIfEquals">` support it. The others return `KV_UNSUPPORTED_OPERATION`.
263
+ */
264
+ lock(key: string, options: KVLockOptions): KVLock;
265
+ /**
266
+ * Writes a value. `{ ttl }` expires it after that many seconds; without `ttl`, the value stays until you delete or replace it.
267
+ * Cloudflare KV stores return `KV_KEY_TOO_LONG` and `KV_VALUE_TOO_LARGE` before a write that Cloudflare rejects.
268
+ */
269
+ set<T = unknown>(key: string, value: T, options?: KVSetOptions): Promise<Result<void, "KV_INVALID_OPTION" | "KV_INVALID_TTL" | "KV_KEY_TOO_LONG" | "KV_OPERATION_FAILED" | "KV_VALUE_TOO_LARGE">>;
270
+ /**
271
+ * Writes many keys in one call. `options` works as in `set()` and applies to every entry. When a key is in `entries`
272
+ * more than once, the last entry wins. A `value` of `undefined` deletes the key, as `set()` does. The writes are not
273
+ * atomic: when the call fails, some entries can be written. Redis sends one pipeline and the `database` driver runs one
274
+ * statement. Other stores write the entries one by one, 16 at a time. A Cloudflare KV store checks every entry against
275
+ * the Workers KV limits before it writes any.
276
+ */
277
+ setMany<T = unknown>(entries: readonly KVEntry<T>[], options?: KVSetOptions): Promise<Result<void, "KV_INVALID_OPTION" | "KV_INVALID_TTL" | "KV_KEY_TOO_LONG" | "KV_OPERATION_FAILED" | "KV_VALUE_TOO_LARGE">>;
278
+ /**
279
+ * Writes the value only when the key has no value, in one atomic step.
280
+ * Returns `true` when this call wrote the value and `false` when the key already had one.
281
+ * The drivers in {@link KVDriversWith}`<"setIfAbsent">` support it. Cloudflare KV is eventually consistent and returns
282
+ * `KV_UNSUPPORTED_OPERATION`.
283
+ */
284
+ setIfAbsent<T = unknown>(key: string, value: T, options?: KVSetOptions): Promise<Result<boolean, "KV_INVALID_OPTION" | "KV_INVALID_TTL" | "KV_INVALID_VALUE" | "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION">>;
285
+ /** Selects a named KV store. `{ mode: "read" }` returns a handle without write methods. */
286
+ store(name: KVStoreName, options?: {
287
+ mode?: "write";
288
+ }): KVStorage;
289
+ store(name: KVStoreName, options: {
290
+ mode: "read";
291
+ }): ReadonlyKVStorage;
292
+ store(name: KVStoreName, options?: KVStoreOptions): KVStorage | ReadonlyKVStorage;
293
+ }
294
+ /** Options of `kv.store()`. */
295
+ interface KVStoreOptions {
296
+ /** `"read"` returns a handle without write methods. Defaults to `"write"`. */
297
+ mode?: "read" | "write";
298
+ }
299
+ /**
300
+ * KV handle from `kv.store(name, { mode: "read" })`, with only `get()`, `getMany()`, `has()`, `keys()`, and `list()`.
301
+ * It limits this API, not the host: the KV binding or provider token keeps full access, so it is not a security
302
+ * boundary against code that reads the binding directly.
303
+ */
304
+ interface ReadonlyKVStorage {
305
+ get: KVStorage["get"];
306
+ getMany: KVStorage["getMany"];
307
+ has: KVStorage["has"];
308
+ keys: KVStorage["keys"];
309
+ list: KVStorage["list"];
310
+ }
311
+ //#endregion
312
+ export { RedisKVStoreConfig as A, KVOptions as C, KVStoreName as D, KVStoreConfig as E, ResolvedKVModuleOptions as F, ResolvedKVStoreConfig as I, ResolvedRedisKVStoreConfig as L, ResolvedDatabaseKVStoreConfig as M, ResolvedDenoKVStoreConfig as N, KVStoreOptions as O, ResolvedFsLiteKVStoreConfig as P, ResolvedUpstashKVStoreConfig as R, KVOperation as S, KVStorage as T, KVLock as _, InferredKVStoreConfig as a, KVLockOptions as b, KVDriverAtomicOperations as c, KVErrorCode as d, KVGetOptions as f, KVListPage as g, KVListOptions as h, FsLiteKVStoreConfig as i, ResolvedCloudflareKVStoreConfig as j, ReadonlyKVStorage as k, KVDriversWith as l, KVGetTypeMap as m, DatabaseKVStoreConfig as n, KVAtomicOperation as o, KVGetType as p, DenoKVStoreConfig as r, KVDriver as s, CloudflareKVStoreConfig as t, KVEntry as u, KVLockAcquisition as v, KVSetOptions as w, KVLockRunResult as x, KVLockErrorCode as y, UpstashKVStoreConfig as z };
@@ -0,0 +1,40 @@
1
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
2
+ import { a as upstashUrlEnvNames, i as upstashTokenEnvNames, s as readEnv } from "./config-BXEVoZE3.js";
3
+ //#region src/runtime/upstash.ts
4
+ function isMaskedValue(value) {
5
+ return !value || /^\*+$/.test(value);
6
+ }
7
+ function assertRuntimeValue(value, envNames) {
8
+ if (isMaskedValue(value)) {
9
+ const names = envNames.map((name) => `\`${name}\``).join(" or ");
10
+ throw kvErrorDiagnostics.KV_MISSING_ENV({
11
+ driver: "upstash",
12
+ names
13
+ });
14
+ }
15
+ }
16
+ /** Fills credentials without validating them, so development still reports missing env on the first operation. */
17
+ function resolveUpstashRuntimeValues(config, env) {
18
+ const completeEnvPair = upstashUrlEnvNames.map((urlName, index) => [readEnv(env, urlName), readEnv(env, upstashTokenEnvNames[index])]).find(([url, token]) => url && token);
19
+ const envUrl = readEnv(env, ...upstashUrlEnvNames);
20
+ const envToken = readEnv(env, ...upstashTokenEnvNames);
21
+ const hasMaskedPair = isMaskedValue(config.url) && isMaskedValue(config.token);
22
+ const resolveMaskedValue = (value, pairValue, fallback) => isMaskedValue(value) ? pairValue || fallback || value || "********" : value ?? "********";
23
+ return {
24
+ ...config,
25
+ token: resolveMaskedValue(config.token, completeEnvPair?.[1], hasMaskedPair ? void 0 : envToken),
26
+ url: resolveMaskedValue(config.url, completeEnvPair?.[0], hasMaskedPair ? void 0 : envUrl)
27
+ };
28
+ }
29
+ function resolveRuntimeKVOptions(config, env = process.env) {
30
+ if (!config || config.store.driver !== "upstash") return config;
31
+ const store = resolveUpstashRuntimeValues(config.store, env);
32
+ assertRuntimeValue(store.url, upstashUrlEnvNames);
33
+ assertRuntimeValue(store.token, upstashTokenEnvNames);
34
+ return {
35
+ ...config,
36
+ store
37
+ };
38
+ }
39
+ //#endregion
40
+ export { resolveUpstashRuntimeValues as n, resolveRuntimeKVOptions as t };