@vite-hub/kv 0.1.0 → 0.4.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.
- package/README.md +94 -21
- package/dist/batch--v0ri69O.js +40 -0
- package/dist/cli-DpPhz_Ek.d.ts +163 -0
- package/dist/cli.d.ts +4 -2
- package/dist/cli.js +99 -77
- package/dist/cloudflare-env-lOtHHsgP.js +46 -0
- package/dist/cloudflare-env-lookup-Bs0VDpU5.js +42 -0
- package/dist/cloudflare-kv-C3NO4C21.js +201 -0
- package/dist/cloudflare-kv-local-C2sbIrFy.js +71 -0
- package/dist/config-LfpUj9hs.js +252 -0
- package/dist/{create-storage-29gMzf41.js → create-storage-BORQm2a8.js} +206 -50
- package/dist/{cursor-history-dqYDlsaD.js → cursor-history-DRHh5bO5.js} +31 -14
- package/dist/database-oJdy0ZVX.js +250 -0
- package/dist/{deno-kv-CSYGvRx4.js → deno-kv-D_VtffFv.js} +12 -4
- package/dist/dev-peer-CHafxbtj.js +238 -0
- package/dist/driver-R4Z5Z5fl.d.ts +15 -0
- package/dist/durability.d.ts +17 -0
- package/dist/durability.js +53 -0
- package/dist/error-diagnostics-C54QQEhN.js +155 -0
- package/dist/errors-DzD6YNEH.js +88 -0
- package/dist/errors.d.ts +17 -1
- package/dist/errors.js +2 -2
- package/dist/fs-lite-BAgpmNAF.js +2 -0
- package/dist/fs-lite-BaklCLuV.js +386 -0
- package/dist/index.d.ts +7 -2
- package/dist/index.js +326 -84
- package/dist/inspect-BIKQsqX4.js +118 -0
- package/dist/invariant-DolT9EEx.js +22 -0
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/{operations-tNUdj3G4.d.ts → operation-definition-nmRu_O3V.d.ts} +42 -15
- package/dist/{operations-pn8_eGob.js → operations-CtrWLmPK.js} +69 -66
- package/dist/operations-D2iI9oN4.js +1363 -0
- package/dist/operations.d.ts +15 -8
- package/dist/operations.js +56 -192
- package/dist/redis-shared-5ogRd3-Y.js +94 -0
- package/dist/runtime/cloudflare-kv.d.ts +1 -1
- package/dist/runtime/cloudflare-kv.js +1 -99
- package/dist/runtime/cloudflare-request-env.d.ts +7 -0
- package/dist/runtime/cloudflare-request-env.js +11 -0
- package/dist/runtime/nitro-plugin.d.ts +12 -0
- package/dist/runtime/nitro-plugin.js +25 -0
- package/dist/runtime/redis-driver.d.ts +11 -0
- package/dist/runtime/redis-driver.js +113 -0
- package/dist/runtime/unstorage-driver.d.ts +14 -0
- package/dist/runtime/unstorage-driver.js +37 -0
- package/dist/runtime/upstash-driver.d.ts +2 -2
- package/dist/runtime/upstash-driver.js +58 -98
- package/dist/{driver-D9fI27jl.d.ts → types-Bj3EQoRg.d.ts} +16 -41
- package/dist/types-Dv-OSXZC.d.ts +325 -0
- package/dist/upstash-B-vaUYqO.js +40 -0
- package/dist/{utils2-Dsb9P4_2.js → utils2-FozcTsmb.js} +5 -2
- package/dist/virtual-module.d.ts +3 -0
- package/dist/vite.d.ts +167 -14
- package/dist/vite.js +1195 -2876
- package/package.json +30 -21
- package/dist/cli-Cniq99iX.d.ts +0 -85
- package/dist/cloudflare-env-C5rM7kUY.js +0 -74
- package/dist/config-DR6_5ZwI.js +0 -124
- package/dist/continuations-DPyH_vr1.js +0 -63
- package/dist/error-diagnostics-D_cQeZTi.js +0 -82
- package/dist/errors-Dc2oiW-Y.js +0 -38
- package/dist/fs-lite-CbLKxLut.js +0 -90
- package/dist/object-B1NW521B.js +0 -7
- package/dist/operations-ByuDE12r.js +0 -1442
- package/dist/types-CMDvN0Wr.d.ts +0 -81
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as KVStoreOptions, B as ResolvedUpstashKVStoreConfig, C as KVOperation, D as KVStorage, E as KVSetOptions, F as ResolvedDenoKVStoreConfig, I as ResolvedFsLiteKVStoreConfig, L as ResolvedKVModuleOptions, M as RedisKVStoreConfig, N as ResolvedCloudflareKVStoreConfig, O as KVStoreConfig, P as ResolvedDatabaseKVStoreConfig, R as ResolvedKVStoreConfig, S as KVLockRunResult, V as UpstashKVStoreConfig, _ as KVListPage, a as InferredKVStoreConfig, b as KVLockErrorCode, c as KVDriver, d as KVEntry, f as KVErrorCode, g as KVListOptions, h as KVGetTypeMap, i as FsLiteKVStoreConfig, j as ReadonlyKVStorage, k as KVStoreName, l as KVDriverAtomicOperations, m as KVGetType, n as DatabaseKVStoreConfig, o as KVAtomicOperation, p as KVGetOptions, r as DenoKVStoreConfig, s as KVClearOptions, t as CloudflareKVStoreConfig, u as KVDriversWith, v as KVLock, w as KVOptions, x as KVLockOptions, y as KVLockAcquisition, z as ResolvedRedisKVStoreConfig } from "./types-Dv-OSXZC.js";
|
|
2
2
|
//#region src/runtime/storage.d.ts
|
|
3
3
|
/** Releases every cached store. Call from the application's shutdown hook after stopping new work. */
|
|
4
4
|
export declare function disposeKVStores(): Promise<void>;
|
|
5
|
+
/**
|
|
6
|
+
* The configured driver that a store uses in this server process. App tests return `fs-lite`.
|
|
7
|
+
* An unknown store throws. Reading the driver does not open a connection to the store.
|
|
8
|
+
*/
|
|
9
|
+
export declare function getKVStoreDriver(name?: KVStoreName): Promise<KVDriver>;
|
|
5
10
|
export declare const kv: KVStorage;
|
|
6
11
|
//#endregion
|
|
7
|
-
export type { CloudflareKVStoreConfig, DenoKVStoreConfig, FsLiteKVStoreConfig, KVDriver, KVErrorCode, KVListOptions, KVListPage,
|
|
12
|
+
export type { CloudflareKVStoreConfig, DatabaseKVStoreConfig, DenoKVStoreConfig, FsLiteKVStoreConfig, InferredKVStoreConfig, KVAtomicOperation, KVClearOptions, KVDriver, KVDriverAtomicOperations, KVDriversWith, KVEntry, KVErrorCode, KVGetOptions, KVGetType, KVGetTypeMap, KVListOptions, KVListPage, KVLock, KVLockAcquisition, KVLockErrorCode, KVLockOptions, KVLockRunResult, KVOperation, KVOptions, KVSetOptions, KVStorage, KVStoreConfig, KVStoreOptions, ReadonlyKVStorage, RedisKVStoreConfig, ResolvedCloudflareKVStoreConfig, ResolvedDatabaseKVStoreConfig, ResolvedDenoKVStoreConfig, ResolvedFsLiteKVStoreConfig, ResolvedKVModuleOptions, ResolvedKVStoreConfig, ResolvedRedisKVStoreConfig, ResolvedUpstashKVStoreConfig, UpstashKVStoreConfig };
|
package/dist/index.js
CHANGED
|
@@ -1,43 +1,14 @@
|
|
|
1
|
-
import { n as kvErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { n as getActiveCloudflareEnv } from "./cloudflare-env-
|
|
5
|
-
import { n as normalizeKVListPrefix, t as createKVStorage$1 } from "./create-storage-
|
|
6
|
-
import {
|
|
1
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-C54QQEhN.js";
|
|
2
|
+
import { a as kvResult, c as kvWriteLimitCodes, i as kvListLimitInvalid, l as listKVKeys, r as kvKeyLimitCodes, t as kvClearOptionsError, u as kvStoreWithMode } from "./errors-DzD6YNEH.js";
|
|
3
|
+
import { r as normalizeKVOptions, s as readEnv } from "./config-LfpUj9hs.js";
|
|
4
|
+
import { n as getActiveCloudflareEnv } from "./cloudflare-env-lookup-Bs0VDpU5.js";
|
|
5
|
+
import { n as normalizeKVListPrefix, t as createKVStorage$1 } from "./create-storage-BORQm2a8.js";
|
|
6
|
+
import { o as normalizeKey } from "./utils2-FozcTsmb.js";
|
|
7
|
+
import { t as resolveRuntimeKVOptions } from "./upstash-B-vaUYqO.js";
|
|
8
|
+
import { i as setItemsOneByOne, n as getItemsOneByOne } from "./batch--v0ri69O.js";
|
|
9
|
+
import { parseDuration } from "@vite-hub/runtime";
|
|
10
|
+
import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
|
|
7
11
|
import { destr } from "destr";
|
|
8
|
-
//#region src/runtime/upstash.ts
|
|
9
|
-
function isMaskedValue(value) {
|
|
10
|
-
return !value || /^\*+$/.test(value);
|
|
11
|
-
}
|
|
12
|
-
function assertRuntimeValue(value, envNames) {
|
|
13
|
-
if (isMaskedValue(value)) {
|
|
14
|
-
const names = envNames.map((name) => `\`${name}\``).join(" or ");
|
|
15
|
-
throw kvErrorDiagnostics.KV_MISSING_ENV({ names });
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
function resolveRuntimeUpstashStore(config, env) {
|
|
19
|
-
const completeEnvPair = upstashUrlEnvNames.map((urlName, index) => [readEnv(env, urlName), readEnv(env, upstashTokenEnvNames[index])]).find(([url, token]) => url && token);
|
|
20
|
-
const envUrl = readEnv(env, ...upstashUrlEnvNames);
|
|
21
|
-
const envToken = readEnv(env, ...upstashTokenEnvNames);
|
|
22
|
-
const hasMaskedPair = isMaskedValue(config.url) && isMaskedValue(config.token);
|
|
23
|
-
const resolveMaskedValue = (value, pairValue, fallback) => isMaskedValue(value) ? pairValue || fallback || value || "********" : value ?? "********";
|
|
24
|
-
const resolved = {
|
|
25
|
-
...config,
|
|
26
|
-
token: resolveMaskedValue(config.token, completeEnvPair?.[1], hasMaskedPair ? void 0 : envToken),
|
|
27
|
-
url: resolveMaskedValue(config.url, completeEnvPair?.[0], hasMaskedPair ? void 0 : envUrl)
|
|
28
|
-
};
|
|
29
|
-
assertRuntimeValue(resolved.url, upstashUrlEnvNames);
|
|
30
|
-
assertRuntimeValue(resolved.token, upstashTokenEnvNames);
|
|
31
|
-
return resolved;
|
|
32
|
-
}
|
|
33
|
-
function resolveRuntimeKVOptions(config, env = process.env) {
|
|
34
|
-
if (!config || config.store.driver !== "upstash") return config;
|
|
35
|
-
return {
|
|
36
|
-
...config,
|
|
37
|
-
store: resolveRuntimeUpstashStore(config.store, env)
|
|
38
|
-
};
|
|
39
|
-
}
|
|
40
|
-
//#endregion
|
|
41
12
|
//#region src/runtime/driver.ts
|
|
42
13
|
const lazyDriverMethods = /* @__PURE__ */ new Set([
|
|
43
14
|
"clear",
|
|
@@ -48,32 +19,84 @@ const lazyDriverMethods = /* @__PURE__ */ new Set([
|
|
|
48
19
|
"removeItem",
|
|
49
20
|
"setItem"
|
|
50
21
|
]);
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
"
|
|
54
|
-
"
|
|
22
|
+
/** The driver method behind each atomic KV operation. */
|
|
23
|
+
const atomicDriverMethods = {
|
|
24
|
+
deleteIfEquals: "deleteIfEqualsItem",
|
|
25
|
+
getAndDelete: "getAndDeleteItem",
|
|
26
|
+
increment: "incrementItem",
|
|
27
|
+
setIfAbsent: "setIfAbsentItem"
|
|
28
|
+
};
|
|
29
|
+
const driverAtomicOperations = {
|
|
30
|
+
"cloudflare": {},
|
|
31
|
+
"database": {
|
|
32
|
+
deleteIfEquals: true,
|
|
33
|
+
getAndDelete: true,
|
|
34
|
+
increment: true,
|
|
35
|
+
setIfAbsent: true
|
|
36
|
+
},
|
|
37
|
+
"deno-kv": { setIfAbsent: true },
|
|
38
|
+
"fs-lite": { setIfAbsent: true },
|
|
39
|
+
"redis": {
|
|
40
|
+
deleteIfEquals: true,
|
|
41
|
+
getAndDelete: true,
|
|
42
|
+
increment: true,
|
|
43
|
+
setIfAbsent: true
|
|
44
|
+
},
|
|
45
|
+
"upstash": {
|
|
46
|
+
deleteIfEquals: true,
|
|
47
|
+
getAndDelete: true,
|
|
48
|
+
increment: true,
|
|
49
|
+
setIfAbsent: true
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
/** Other optional unstorage methods that a driver has. */
|
|
53
|
+
const otherOptionalDriverMethods = {
|
|
54
|
+
"cloudflare": ["validateBatch"],
|
|
55
|
+
"fs-lite": [
|
|
55
56
|
"getItemRaw",
|
|
56
57
|
"getMeta",
|
|
57
58
|
"setItemRaw"
|
|
58
|
-
]
|
|
59
|
-
"upstash": /* @__PURE__ */ new Set([
|
|
60
|
-
"getAndDeleteItem",
|
|
61
|
-
"getItems",
|
|
62
|
-
"incrementItem"
|
|
63
|
-
])
|
|
59
|
+
]
|
|
64
60
|
};
|
|
65
|
-
|
|
61
|
+
/** Batch methods. A driver without one gets a version that calls the single-key method for each key. */
|
|
62
|
+
const batchDriverMethods = /* @__PURE__ */ new Set(["getItems", "setItems"]);
|
|
63
|
+
const lazyOptionalDriverMethods = Object.fromEntries(Object.entries(driverAtomicOperations).map(([driver, operations]) => [driver, /* @__PURE__ */ new Set([...Object.keys(operations).map((operation) => atomicDriverMethods[operation]), ...otherOptionalDriverMethods[driver] ?? []])]));
|
|
64
|
+
async function createDatabaseDriver(store, loadDatabases) {
|
|
65
|
+
const { default: factory, kvSqlClientFromDatabase } = await import("./database-oJdy0ZVX.js");
|
|
66
|
+
return factory(store, async () => {
|
|
67
|
+
const entry = loadDatabases ? (await loadDatabases())[store.database] : void 0;
|
|
68
|
+
if (!entry) throw kvErrorDiagnostics.KV_DATABASE_UNAVAILABLE({
|
|
69
|
+
database: store.database,
|
|
70
|
+
problem: "missing"
|
|
71
|
+
});
|
|
72
|
+
return kvSqlClientFromDatabase(entry.db, store.database);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
async function createRuntimeDriver(store, loadDatabases) {
|
|
66
76
|
switch (store.driver) {
|
|
67
|
-
case "cloudflare
|
|
77
|
+
case "cloudflare": {
|
|
78
|
+
const { localBase } = store;
|
|
79
|
+
if (localBase) {
|
|
80
|
+
const { default: factory } = await import("./cloudflare-kv-local-C2sbIrFy.js");
|
|
81
|
+
return factory({
|
|
82
|
+
...store,
|
|
83
|
+
localBase
|
|
84
|
+
});
|
|
85
|
+
}
|
|
68
86
|
const { default: factory } = await import("./runtime/cloudflare-kv.js");
|
|
69
87
|
return factory(store);
|
|
70
88
|
}
|
|
89
|
+
case "database": return createDatabaseDriver(store, loadDatabases);
|
|
71
90
|
case "deno-kv": {
|
|
72
|
-
const { default: factory } = await import("./deno-kv-
|
|
91
|
+
const { default: factory } = await import("./deno-kv-D_VtffFv.js");
|
|
73
92
|
return factory(store);
|
|
74
93
|
}
|
|
75
94
|
case "fs-lite": {
|
|
76
|
-
const { default: factory } = await import("./fs-lite-
|
|
95
|
+
const { default: factory } = await import("./fs-lite-BAgpmNAF.js");
|
|
96
|
+
return factory(store);
|
|
97
|
+
}
|
|
98
|
+
case "redis": {
|
|
99
|
+
const { default: factory } = await import("@vite-hub/kv/runtime/redis-driver");
|
|
77
100
|
return factory(store);
|
|
78
101
|
}
|
|
79
102
|
case "upstash": {
|
|
@@ -82,7 +105,7 @@ async function createRuntimeDriver(store) {
|
|
|
82
105
|
}
|
|
83
106
|
}
|
|
84
107
|
}
|
|
85
|
-
function createLazyKVRuntimeDriver(config) {
|
|
108
|
+
function createLazyKVRuntimeDriver(config, loadDatabases) {
|
|
86
109
|
let driverPromise;
|
|
87
110
|
let disposed = false;
|
|
88
111
|
function resolve() {
|
|
@@ -91,7 +114,7 @@ function createLazyKVRuntimeDriver(config) {
|
|
|
91
114
|
const pending = (async () => {
|
|
92
115
|
const runtime = resolveRuntimeKVOptions(config);
|
|
93
116
|
if (!runtime) throw kvErrorDiagnostics.KV_DISABLED();
|
|
94
|
-
return createRuntimeDriver(runtime.store);
|
|
117
|
+
return createRuntimeDriver(runtime.store, loadDatabases);
|
|
95
118
|
})();
|
|
96
119
|
driverPromise = pending;
|
|
97
120
|
pending.catch(() => {
|
|
@@ -112,6 +135,10 @@ function createLazyKVRuntimeDriver(config) {
|
|
|
112
135
|
const driver = await driverPromise;
|
|
113
136
|
return driver.dispose?.call(driver);
|
|
114
137
|
};
|
|
138
|
+
if (batchDriverMethods.has(prop)) return async (...args) => {
|
|
139
|
+
const driver = await resolve();
|
|
140
|
+
return (prop === "getItems" ? driver.getItems ?? getItemsOneByOne(driver) : driver.setItems ?? setItemsOneByOne(driver)).apply(driver, args);
|
|
141
|
+
};
|
|
115
142
|
const optionalMethods = lazyOptionalDriverMethods[config.store.driver];
|
|
116
143
|
if (!lazyDriverMethods.has(prop) && !optionalMethods.has(prop)) return void 0;
|
|
117
144
|
return async (...args) => {
|
|
@@ -130,18 +157,66 @@ function deserializeValue(value) {
|
|
|
130
157
|
if (typeof value !== "string") return value;
|
|
131
158
|
return destr(value);
|
|
132
159
|
}
|
|
133
|
-
function
|
|
160
|
+
function isPrimitive(value) {
|
|
161
|
+
return value === null || typeof value !== "object" && typeof value !== "function";
|
|
162
|
+
}
|
|
163
|
+
function serializeValue(value, operation = "setIfAbsent") {
|
|
164
|
+
if (value === void 0) throw kvErrorDiagnostics.KV_INVALID_VALUE({
|
|
165
|
+
operation,
|
|
166
|
+
problem: "missing"
|
|
167
|
+
});
|
|
168
|
+
if (isPrimitive(value)) return String(value);
|
|
169
|
+
if (Array.isArray(value)) return serializeJSONValue(value, operation);
|
|
170
|
+
if (value && typeof value === "object") {
|
|
171
|
+
const prototype = Object.getPrototypeOf(value);
|
|
172
|
+
if (prototype === null || prototype === Object.prototype) return serializeJSONValue(value, operation);
|
|
173
|
+
const toJSON = Reflect.get(value, "toJSON");
|
|
174
|
+
if (typeof toJSON === "function") return serializeValue(toJSON.call(value), operation);
|
|
175
|
+
}
|
|
176
|
+
throw kvErrorDiagnostics.KV_INVALID_VALUE({
|
|
177
|
+
operation,
|
|
178
|
+
problem: "unserializable"
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
function serializeJSONValue(value, operation) {
|
|
182
|
+
try {
|
|
183
|
+
const serialized = JSON.stringify(value);
|
|
184
|
+
if (serialized !== void 0) return serialized;
|
|
185
|
+
} catch {
|
|
186
|
+
throw kvErrorDiagnostics.KV_INVALID_VALUE({
|
|
187
|
+
operation,
|
|
188
|
+
problem: "unserializable"
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
throw kvErrorDiagnostics.KV_INVALID_VALUE({
|
|
192
|
+
operation,
|
|
193
|
+
problem: "unserializable"
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
/** The line that `vite dev` prints when a store uses real data. Only `vite dev` resolves a store with `remote: true`. */
|
|
197
|
+
function kvRemoteNotice(name, store) {
|
|
198
|
+
if (store.driver === "upstash" && store.remote) return `[vitehub] KV store "${name}" is remote: \`vite dev\` uses the real Upstash database. Writes change real data.`;
|
|
199
|
+
if (store.driver === "cloudflare" && store.remote) return `[vitehub] KV store "${name}" is remote: \`vite dev\` uses the real Cloudflare KV namespace${store.namespaceId ? ` ${store.namespaceId}` : ""} through the \`${store.binding}\` binding. Writes change real data.`;
|
|
200
|
+
}
|
|
201
|
+
function resolveHostedKVStore(config, name = "default") {
|
|
134
202
|
const resolved = assertHostedConfig(config);
|
|
135
203
|
const stores = resolved.stores || { default: resolved.store };
|
|
136
204
|
const store = Object.hasOwn(stores, name) ? stores[name] : void 0;
|
|
137
205
|
if (!store) throw kvErrorDiagnostics.KV_STORE_NOT_FOUND({ store: name });
|
|
206
|
+
return store;
|
|
207
|
+
}
|
|
208
|
+
/** Creates storage with the build-selected driver; connection credentials are resolved at runtime. */
|
|
209
|
+
function createHostedKVStorage(config, name = "default", loadDatabases) {
|
|
210
|
+
const store = resolveHostedKVStore(config, name);
|
|
211
|
+
const notice = kvRemoteNotice(name, store);
|
|
212
|
+
if (notice) console.warn(notice);
|
|
138
213
|
const driver = createLazyKVRuntimeDriver({
|
|
139
214
|
store,
|
|
140
215
|
stores: {
|
|
141
216
|
default: store,
|
|
142
217
|
[name]: store
|
|
143
218
|
}
|
|
144
|
-
});
|
|
219
|
+
}, loadDatabases);
|
|
145
220
|
const storage = createKVStorage$1(driver);
|
|
146
221
|
storage.listKeys = (options) => driver.listKeys({
|
|
147
222
|
...options,
|
|
@@ -149,13 +224,100 @@ function createHostedKVStorage(config, name = "default") {
|
|
|
149
224
|
});
|
|
150
225
|
const getAndDeleteItem = driver.getAndDeleteItem;
|
|
151
226
|
const incrementItem = driver.incrementItem;
|
|
152
|
-
if (getAndDeleteItem) storage.getAndDeleteItem = async (key) => {
|
|
153
|
-
|
|
227
|
+
if (getAndDeleteItem) storage.getAndDeleteItem = async (key, options) => {
|
|
228
|
+
const value = await getAndDeleteItem(normalizeKey(key));
|
|
229
|
+
return options?.type === "text" ? value : deserializeValue(value);
|
|
154
230
|
};
|
|
155
231
|
if (incrementItem) storage.incrementItem = (key, ttl) => incrementItem(normalizeKey(key), ttl);
|
|
232
|
+
const setIfAbsentItem = driver.setIfAbsentItem;
|
|
233
|
+
if (setIfAbsentItem) storage.setIfAbsentItem = async (key, value, ttl) => setIfAbsentItem(normalizeKey(key), serializeValue(value), ttl);
|
|
234
|
+
const deleteIfEqualsItem = driver.deleteIfEqualsItem;
|
|
235
|
+
if (deleteIfEqualsItem) storage.deleteIfEqualsItem = async (key, expected) => deleteIfEqualsItem(normalizeKey(key), serializeValue(expected, "deleteIfEquals"));
|
|
156
236
|
return storage;
|
|
157
237
|
}
|
|
158
238
|
//#endregion
|
|
239
|
+
//#region src/runtime/ttl.ts
|
|
240
|
+
/**
|
|
241
|
+
* The seconds of a KV `ttl`: a number of seconds, or a duration such as `"1h"`. `undefined` when it is not a positive
|
|
242
|
+
* time, so the caller returns `KV_INVALID_TTL`.
|
|
243
|
+
*/
|
|
244
|
+
function ttlSeconds(ttl) {
|
|
245
|
+
let seconds;
|
|
246
|
+
if (typeof ttl === "number") seconds = ttl;
|
|
247
|
+
else if (typeof ttl !== "string") return;
|
|
248
|
+
else try {
|
|
249
|
+
seconds = parseDuration(ttl) / 1e3;
|
|
250
|
+
} catch {
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
return Number.isFinite(seconds) && seconds > 0 && Number.isSafeInteger(Math.ceil(seconds * 1e3)) ? seconds : void 0;
|
|
254
|
+
}
|
|
255
|
+
//#endregion
|
|
256
|
+
//#region src/runtime/lock.ts
|
|
257
|
+
const firstRetryMs = 25;
|
|
258
|
+
const maxRetryMs = 500;
|
|
259
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
260
|
+
/**
|
|
261
|
+
* A lock on `key` built on `setIfAbsent()` with a TTL and `deleteIfEquals()`. Each acquire writes a new random owner
|
|
262
|
+
* token, and the release deletes the key only when it still holds that token.
|
|
263
|
+
*/
|
|
264
|
+
function createKVLock(store, resolveStorage, key, options) {
|
|
265
|
+
async function acquire() {
|
|
266
|
+
const ttl = ttlSeconds(options.ttl);
|
|
267
|
+
const wait = options.wait ?? 0;
|
|
268
|
+
if (ttl === void 0) return [kvErrorDiagnostics.KV_INVALID_TTL(), void 0];
|
|
269
|
+
if (!Number.isFinite(wait) || wait < 0) return [kvErrorDiagnostics.KV_INVALID_WAIT(), void 0];
|
|
270
|
+
const storage = await resolveStorage();
|
|
271
|
+
return kvResult("lock", store, async () => {
|
|
272
|
+
const claim = storage.setIfAbsentItem;
|
|
273
|
+
const free = storage.deleteIfEqualsItem;
|
|
274
|
+
if (!claim || !free) throw kvErrorDiagnostics.KV_UNSUPPORTED_OPERATION({
|
|
275
|
+
operation: "lock",
|
|
276
|
+
store
|
|
277
|
+
});
|
|
278
|
+
const owner = globalThis.crypto.randomUUID();
|
|
279
|
+
const deadline = performance.now() + wait * 1e3;
|
|
280
|
+
let delay = firstRetryMs;
|
|
281
|
+
while (true) {
|
|
282
|
+
const started = performance.now();
|
|
283
|
+
if (await claim(key, owner, ttl)) {
|
|
284
|
+
if (performance.now() - started < ttl * 1e3) return {
|
|
285
|
+
acquired: true,
|
|
286
|
+
release: () => kvResult("lock", store, () => free(key, owner))
|
|
287
|
+
};
|
|
288
|
+
await free(key, owner);
|
|
289
|
+
return { acquired: false };
|
|
290
|
+
}
|
|
291
|
+
const left = deadline - performance.now();
|
|
292
|
+
if (left <= 0) return { acquired: false };
|
|
293
|
+
await sleep(Math.min(left, delay / 2 + Math.random() * delay / 2));
|
|
294
|
+
delay = Math.min(delay * 2, maxRetryMs);
|
|
295
|
+
}
|
|
296
|
+
}, ["KV_UNSUPPORTED_OPERATION"]);
|
|
297
|
+
}
|
|
298
|
+
return {
|
|
299
|
+
acquire,
|
|
300
|
+
async run(fn) {
|
|
301
|
+
const [error, lock] = await acquire();
|
|
302
|
+
if (error) return [error, void 0];
|
|
303
|
+
if (!lock.acquired) return [void 0, { acquired: false }];
|
|
304
|
+
let value;
|
|
305
|
+
try {
|
|
306
|
+
value = await fn();
|
|
307
|
+
} catch (cause) {
|
|
308
|
+
await lock.release();
|
|
309
|
+
throw cause;
|
|
310
|
+
}
|
|
311
|
+
const [releaseError] = await lock.release();
|
|
312
|
+
if (releaseError) return [releaseError, void 0];
|
|
313
|
+
return [void 0, {
|
|
314
|
+
acquired: true,
|
|
315
|
+
value
|
|
316
|
+
}];
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
//#endregion
|
|
159
321
|
//#region src/runtime/storage.ts
|
|
160
322
|
const storagePromises = /* @__PURE__ */ new Map();
|
|
161
323
|
let disposal;
|
|
@@ -177,7 +339,7 @@ function disposeKVStores() {
|
|
|
177
339
|
}
|
|
178
340
|
function inferHosting(env) {
|
|
179
341
|
if (getActiveCloudflareEnv()) return "cloudflare";
|
|
180
|
-
const explicit = readEnv(env, "
|
|
342
|
+
const explicit = readEnv(env, "VITEHUB_HOST");
|
|
181
343
|
if (explicit) return explicit;
|
|
182
344
|
if (typeof globalThis.Deno?.openKv === "function") return "deno";
|
|
183
345
|
return readEnv(env, "KV_REST_API_URL") ? "vercel" : void 0;
|
|
@@ -188,53 +350,100 @@ function shouldFallbackHostedConfigImport(error) {
|
|
|
188
350
|
}
|
|
189
351
|
async function resolveHostedConfig() {
|
|
190
352
|
try {
|
|
191
|
-
|
|
353
|
+
const module = await import("#vitehub/kv/config");
|
|
354
|
+
const loadDatabases = "loadDatabases" in module ? module.loadDatabases : void 0;
|
|
355
|
+
return {
|
|
356
|
+
kv: module.kv,
|
|
357
|
+
...loadDatabases ? { loadDatabases } : {}
|
|
358
|
+
};
|
|
192
359
|
} catch (error) {
|
|
193
360
|
if (!shouldFallbackHostedConfigImport(error)) throw error;
|
|
194
361
|
const env = typeof process !== "undefined" ? process.env : {};
|
|
195
|
-
return normalizeKVOptions(void 0, {
|
|
362
|
+
return { kv: normalizeKVOptions(void 0, {
|
|
196
363
|
env,
|
|
197
364
|
hosting: inferHosting(env)
|
|
198
|
-
}) || false;
|
|
365
|
+
}) || false };
|
|
199
366
|
}
|
|
200
367
|
}
|
|
201
368
|
async function resolveStorage(name = "default") {
|
|
369
|
+
const test = getViteHubTestMode();
|
|
370
|
+
if (test) {
|
|
371
|
+
resolveHostedKVStore((await resolveHostedConfig()).kv, name);
|
|
372
|
+
return await test.backend(`kv:${name}`, async () => createHostedKVStorage({ store: {
|
|
373
|
+
base: await test.directory(`kv-${name}`),
|
|
374
|
+
driver: "fs-lite"
|
|
375
|
+
} }, "default"), (storage) => storage.dispose());
|
|
376
|
+
}
|
|
202
377
|
if (disposal) await disposal;
|
|
203
378
|
const existing = storagePromises.get(name);
|
|
204
379
|
if (existing) return existing;
|
|
205
|
-
const promise = resolveHostedConfig().then((config) => createHostedKVStorage(config, name));
|
|
380
|
+
const promise = resolveHostedConfig().then((config) => createHostedKVStorage(config.kv, name, config.loadDatabases));
|
|
206
381
|
storagePromises.set(name, promise);
|
|
207
382
|
promise.catch(() => {
|
|
208
383
|
if (storagePromises.get(name) === promise) storagePromises.delete(name);
|
|
209
384
|
});
|
|
210
385
|
return promise;
|
|
211
386
|
}
|
|
387
|
+
/**
|
|
388
|
+
* The configured driver that a store uses in this server process. App tests return `fs-lite`.
|
|
389
|
+
* An unknown store throws. Reading the driver does not open a connection to the store.
|
|
390
|
+
*/
|
|
391
|
+
async function getKVStoreDriver(name = "default") {
|
|
392
|
+
const store = resolveHostedKVStore((await resolveHostedConfig()).kv, name);
|
|
393
|
+
if (getViteHubTestMode()) return "fs-lite";
|
|
394
|
+
return store.driver;
|
|
395
|
+
}
|
|
212
396
|
async function runKVOperation(operation, name, run, codes = []) {
|
|
213
397
|
const storage = await resolveStorage(name);
|
|
214
398
|
return kvResult(operation, name, () => run(storage), codes);
|
|
215
399
|
}
|
|
400
|
+
function readSetTTL(operation, options) {
|
|
401
|
+
if (options === void 0) return;
|
|
402
|
+
for (const option of Object.keys(options)) if (option !== "ttl") throw kvErrorDiagnostics.KV_INVALID_OPTION({
|
|
403
|
+
operation,
|
|
404
|
+
option
|
|
405
|
+
});
|
|
406
|
+
if (options.ttl === void 0) return;
|
|
407
|
+
const ttl = ttlSeconds(options.ttl);
|
|
408
|
+
if (ttl === void 0) throw kvErrorDiagnostics.KV_INVALID_TTL();
|
|
409
|
+
return ttl;
|
|
410
|
+
}
|
|
216
411
|
function createKVStorage(name = "default") {
|
|
217
412
|
return {
|
|
218
|
-
async clear(
|
|
219
|
-
|
|
413
|
+
async clear(options) {
|
|
414
|
+
const error = kvClearOptionsError(options);
|
|
415
|
+
if (error) return [error, void 0];
|
|
416
|
+
return runKVOperation("clear", name, async (storage) => storage.clear(options?.prefix));
|
|
220
417
|
},
|
|
221
|
-
async
|
|
222
|
-
return runKVOperation("
|
|
418
|
+
async delete(key, options) {
|
|
419
|
+
return runKVOperation("delete", name, async (storage) => storage.removeItem(key, options), kvKeyLimitCodes);
|
|
420
|
+
},
|
|
421
|
+
async deleteIfEquals(key, expected) {
|
|
422
|
+
return runKVOperation("deleteIfEquals", name, async (storage) => {
|
|
423
|
+
if (!storage.deleteIfEqualsItem) throw kvErrorDiagnostics.KV_UNSUPPORTED_OPERATION({
|
|
424
|
+
operation: "deleteIfEquals",
|
|
425
|
+
store: name
|
|
426
|
+
});
|
|
427
|
+
return storage.deleteIfEqualsItem(key, expected);
|
|
428
|
+
}, ["KV_INVALID_VALUE", "KV_UNSUPPORTED_OPERATION"]);
|
|
223
429
|
},
|
|
224
430
|
async get(key, options) {
|
|
225
|
-
return runKVOperation("get", name, (storage) => storage.getItem(key, options));
|
|
431
|
+
return runKVOperation("get", name, (storage) => storage.getItem(key, options), kvKeyLimitCodes);
|
|
226
432
|
},
|
|
227
|
-
async getAndDelete(key) {
|
|
433
|
+
async getAndDelete(key, options) {
|
|
228
434
|
return runKVOperation("getAndDelete", name, async (storage) => {
|
|
229
435
|
if (!storage.getAndDeleteItem) throw kvErrorDiagnostics.KV_UNSUPPORTED_OPERATION({
|
|
230
436
|
operation: "getAndDelete",
|
|
231
437
|
store: name
|
|
232
438
|
});
|
|
233
|
-
return storage.getAndDeleteItem(key);
|
|
439
|
+
return storage.getAndDeleteItem(key, options);
|
|
234
440
|
}, ["KV_UNSUPPORTED_OPERATION"]);
|
|
235
441
|
},
|
|
442
|
+
async getMany(keys, options) {
|
|
443
|
+
return runKVOperation("getMany", name, (storage) => storage.getMany(keys, options), kvKeyLimitCodes);
|
|
444
|
+
},
|
|
236
445
|
async has(key, options) {
|
|
237
|
-
return runKVOperation("has", name, (storage) => storage.hasItem(key, options));
|
|
446
|
+
return runKVOperation("has", name, (storage) => storage.hasItem(key, options), kvKeyLimitCodes);
|
|
238
447
|
},
|
|
239
448
|
async increment(key, ttl) {
|
|
240
449
|
return runKVOperation("increment", name, async (storage) => {
|
|
@@ -242,25 +451,58 @@ function createKVStorage(name = "default") {
|
|
|
242
451
|
operation: "increment",
|
|
243
452
|
store: name
|
|
244
453
|
});
|
|
245
|
-
|
|
246
|
-
|
|
454
|
+
const seconds = ttlSeconds(ttl);
|
|
455
|
+
if (seconds === void 0) throw kvErrorDiagnostics.KV_INVALID_TTL();
|
|
456
|
+
return storage.incrementItem(key, seconds);
|
|
247
457
|
}, ["KV_INVALID_TTL", "KV_UNSUPPORTED_OPERATION"]);
|
|
248
458
|
},
|
|
249
|
-
|
|
250
|
-
return
|
|
459
|
+
lock(key, options) {
|
|
460
|
+
return createKVLock(name, () => resolveStorage(name), key, options);
|
|
251
461
|
},
|
|
252
|
-
async list(options) {
|
|
253
|
-
if (
|
|
254
|
-
return runKVOperation("list", name, (storage) => storage.listKeys(options), ["KV_INVALID_CURSOR"]);
|
|
462
|
+
async list(options = {}) {
|
|
463
|
+
if (kvListLimitInvalid(options)) return [kvErrorDiagnostics.KV_INVALID_LIMIT(), void 0];
|
|
464
|
+
return runKVOperation("list", name, (storage) => listKVKeys((page) => storage.listKeys(page), options), ["KV_INVALID_CURSOR"]);
|
|
255
465
|
},
|
|
256
466
|
async set(key, value, options) {
|
|
257
|
-
return runKVOperation("set", name, async (storage) =>
|
|
467
|
+
return runKVOperation("set", name, async (storage) => {
|
|
468
|
+
const ttl = readSetTTL("set", options);
|
|
469
|
+
return storage.setItem(key, value, ttl === void 0 ? void 0 : { ttl });
|
|
470
|
+
}, [
|
|
471
|
+
...kvWriteLimitCodes,
|
|
472
|
+
"KV_INVALID_OPTION",
|
|
473
|
+
"KV_INVALID_TTL"
|
|
474
|
+
]);
|
|
258
475
|
},
|
|
259
|
-
|
|
260
|
-
return
|
|
261
|
-
|
|
476
|
+
async setMany(entries, options) {
|
|
477
|
+
return runKVOperation("setMany", name, async (storage) => {
|
|
478
|
+
const ttl = readSetTTL("setMany", options);
|
|
479
|
+
return storage.setMany(entries, ttl === void 0 ? void 0 : { ttl });
|
|
480
|
+
}, [
|
|
481
|
+
...kvWriteLimitCodes,
|
|
482
|
+
"KV_INVALID_OPTION",
|
|
483
|
+
"KV_INVALID_TTL"
|
|
484
|
+
]);
|
|
485
|
+
},
|
|
486
|
+
async setIfAbsent(key, value, options) {
|
|
487
|
+
return runKVOperation("setIfAbsent", name, async (storage) => {
|
|
488
|
+
if (!storage.setIfAbsentItem) throw kvErrorDiagnostics.KV_UNSUPPORTED_OPERATION({
|
|
489
|
+
operation: "setIfAbsent",
|
|
490
|
+
store: name
|
|
491
|
+
});
|
|
492
|
+
return storage.setIfAbsentItem(key, value, readSetTTL("setIfAbsent", options));
|
|
493
|
+
}, [
|
|
494
|
+
"KV_INVALID_OPTION",
|
|
495
|
+
"KV_INVALID_TTL",
|
|
496
|
+
"KV_INVALID_VALUE",
|
|
497
|
+
"KV_UNSUPPORTED_OPERATION"
|
|
498
|
+
]);
|
|
499
|
+
},
|
|
500
|
+
store: selectKVStore
|
|
262
501
|
};
|
|
263
502
|
}
|
|
503
|
+
function selectKVStore(name, options) {
|
|
504
|
+
return kvStoreWithMode(createKVStorage(name), options);
|
|
505
|
+
}
|
|
264
506
|
const kv = createKVStorage();
|
|
265
507
|
//#endregion
|
|
266
|
-
export { disposeKVStores, kv };
|
|
508
|
+
export { disposeKVStores, getKVStoreDriver, kv };
|