@vite-hub/kv 0.1.0 → 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 (67) hide show
  1. package/README.md +86 -15
  2. package/dist/batch--v0ri69O.js +40 -0
  3. package/dist/cli-DpPhz_Ek.d.ts +163 -0
  4. package/dist/cli.d.ts +4 -2
  5. package/dist/cli.js +98 -77
  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/{create-storage-29gMzf41.js → create-storage-BGsrQKw3.js} +206 -50
  12. package/dist/{cursor-history-dqYDlsaD.js → cursor-history-BqIQePNP.js} +31 -14
  13. package/dist/database-72Jk3VVk.js +250 -0
  14. package/dist/{deno-kv-CSYGvRx4.js → deno-kv-BM9mYdUp.js} +12 -4
  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 +12 -1
  22. package/dist/errors.js +2 -2
  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 +7 -2
  26. package/dist/index.js +302 -75
  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/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
  32. package/dist/operations-B-WZ7P1h.js +1351 -0
  33. package/dist/{operations-pn8_eGob.js → operations-Ch-gKaey.js} +67 -58
  34. package/dist/operations.d.ts +15 -8
  35. package/dist/operations.js +55 -192
  36. package/dist/redis-shared-E5mahECF.js +94 -0
  37. package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
  38. package/dist/runtime/cloudflare-kv.d.ts +1 -1
  39. package/dist/runtime/cloudflare-kv.js +1 -99
  40. package/dist/runtime/cloudflare-request-env.d.ts +7 -0
  41. package/dist/runtime/cloudflare-request-env.js +11 -0
  42. package/dist/runtime/nitro-plugin.d.ts +12 -0
  43. package/dist/runtime/nitro-plugin.js +22 -0
  44. package/dist/runtime/redis-driver.d.ts +11 -0
  45. package/dist/runtime/redis-driver.js +113 -0
  46. package/dist/runtime/unstorage-driver.d.ts +14 -0
  47. package/dist/runtime/unstorage-driver.js +33 -0
  48. package/dist/runtime/upstash-driver.d.ts +2 -2
  49. package/dist/runtime/upstash-driver.js +58 -98
  50. package/dist/{driver-D9fI27jl.d.ts → types-Bj3EQoRg.d.ts} +16 -41
  51. package/dist/types-DEiKew_3.d.ts +312 -0
  52. package/dist/upstash-DDlqTttY.js +40 -0
  53. package/dist/{utils2-Dsb9P4_2.js → utils2-FozcTsmb.js} +5 -2
  54. package/dist/virtual-module.d.ts +2 -0
  55. package/dist/vite.d.ts +152 -11
  56. package/dist/vite.js +888 -2836
  57. package/package.json +30 -21
  58. package/dist/cli-Cniq99iX.d.ts +0 -85
  59. package/dist/cloudflare-env-C5rM7kUY.js +0 -74
  60. package/dist/config-DR6_5ZwI.js +0 -124
  61. package/dist/continuations-DPyH_vr1.js +0 -63
  62. package/dist/error-diagnostics-D_cQeZTi.js +0 -82
  63. package/dist/errors-Dc2oiW-Y.js +0 -38
  64. package/dist/fs-lite-CbLKxLut.js +0 -90
  65. package/dist/object-B1NW521B.js +0 -7
  66. package/dist/operations-ByuDE12r.js +0 -1442
  67. package/dist/types-CMDvN0Wr.d.ts +0 -81
@@ -0,0 +1,71 @@
1
+ import { t as getActiveCloudflareBinding } from "./cloudflare-env-lOtHHsgP.js";
2
+ import { i as setItemsOneByOne, n as getItemsOneByOne } from "./batch--v0ri69O.js";
3
+ import { a as validateCloudflareKVBatch, i as installCloudflareKVLimits, r as assertCloudflareKVWrite, t as createCloudflareDriver } from "./cloudflare-kv-BIEUFzRT.js";
4
+ import { t as createFsLiteKVDriver } from "./fs-lite-BLZId9_P.js";
5
+ //#region src/runtime/cloudflare-kv-local.ts
6
+ /**
7
+ * Seconds until the key expires, as the binding computes them from unstorage's options: `ttl` becomes an
8
+ * `expirationTtl` of at least 60 seconds, and a relative expiration wins over the absolute `expiration`.
9
+ */
10
+ function cloudflareExpirationSeconds(options) {
11
+ if (!options || typeof options !== "object") return;
12
+ const ttl = Reflect.get(options, "ttl");
13
+ const put = {
14
+ expirationTtl: typeof ttl === "number" && ttl ? Math.max(ttl, 60) : void 0,
15
+ ...options
16
+ };
17
+ if (typeof put.expirationTtl === "number") return put.expirationTtl;
18
+ if (typeof put.expiration === "number") return put.expiration - Date.now() / 1e3;
19
+ }
20
+ /**
21
+ * A Cloudflare KV store in `vite dev`. It uses the binding when the runtime has one, for example on the workerd
22
+ * runner. Otherwise, for example on Nitro's default Node runner, it uses a local `fs-lite` store with the Workers KV limits and expirations.
23
+ */
24
+ function createCloudflareKVLocalDriver(store) {
25
+ const binding = createCloudflareDriver({
26
+ binding: store.binding,
27
+ namespaceId: store.namespaceId
28
+ });
29
+ let localPromise;
30
+ const pick = async () => {
31
+ if (getActiveCloudflareBinding(store.binding)) return binding;
32
+ return localPromise ??= createFsLiteKVDriver({
33
+ base: store.localBase,
34
+ driver: "fs-lite"
35
+ }).then((local) => {
36
+ const { setItem } = local;
37
+ local.setItem = (key, value, options) => setItem?.call(local, key, value, { ttl: cloudflareExpirationSeconds(options) });
38
+ installCloudflareKVLimits(local);
39
+ return local;
40
+ }).catch((error) => {
41
+ localPromise = void 0;
42
+ throw error;
43
+ });
44
+ };
45
+ return {
46
+ name: "cloudflare-kv-local",
47
+ validateBatch: validateCloudflareKVBatch,
48
+ options: store,
49
+ clear: async (base, options) => (await pick()).clear?.(base, options),
50
+ async dispose() {
51
+ await Promise.all([binding.dispose?.(), localPromise?.then((local) => local.dispose?.())]);
52
+ },
53
+ getItem: async (key, options) => (await pick()).getItem(key, options),
54
+ async getItems(items, options) {
55
+ const driver = await pick();
56
+ return (driver.getItems ?? getItemsOneByOne(driver))(items, options);
57
+ },
58
+ getKeys: async (base, options) => (await pick()).getKeys(base, options),
59
+ hasItem: async (key, options) => (await pick()).hasItem(key, options),
60
+ listKeys: async (options) => (await pick()).listKeys(options),
61
+ removeItem: async (key, options) => (await pick()).removeItem?.(key, options),
62
+ setItem: async (key, value, options) => (await pick()).setItem?.(key, value, options),
63
+ async setItems(items, options) {
64
+ for (const item of items) assertCloudflareKVWrite(item.key, item.value);
65
+ const driver = await pick();
66
+ return (driver.setItems ?? setItemsOneByOne(driver))(items, options);
67
+ }
68
+ };
69
+ }
70
+ //#endregion
71
+ export { createCloudflareKVLocalDriver as default };
@@ -0,0 +1,250 @@
1
+ import { t as isRecord } from "./object-Da1zyPCR.js";
2
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
3
+ import { o as normalizeKey } from "./utils2-FozcTsmb.js";
4
+ import { defu } from "defu";
5
+ //#region ../internal/src/env.ts
6
+ function trimmed(value) {
7
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
8
+ }
9
+ function readEnv(env, ...names) {
10
+ for (const name of names) {
11
+ const value = trimmed(env[name]);
12
+ if (value) return value;
13
+ }
14
+ }
15
+ //#endregion
16
+ //#region ../internal/src/hosting.ts
17
+ /**
18
+ * Returns the Nitro preset name that this build targets, as the developer wrote it.
19
+ * The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOST`.
20
+ * Empty values are skipped.
21
+ */
22
+ function resolveHostPreset(input = {}) {
23
+ const env = input.env ?? (typeof process === "undefined" ? {} : process.env);
24
+ const nitroPreset = input.nitro && typeof input.nitro === "object" ? Reflect.get(input.nitro, "preset") : void 0;
25
+ for (const value of [
26
+ nitroPreset,
27
+ input.hosting,
28
+ env.NITRO_PRESET,
29
+ env.SERVER_PRESET,
30
+ env.VITEHUB_HOST
31
+ ]) if (typeof value === "string" && value.trim()) return value.trim();
32
+ }
33
+ function normalizeHosting(hosting) {
34
+ const normalized = hosting?.trim().toLowerCase().replaceAll("_", "-") || "";
35
+ if (normalized === "cloudflare") return "cloudflare-module";
36
+ return normalized;
37
+ }
38
+ //#endregion
39
+ //#region src/integrations/upstash.ts
40
+ const maskedUpstashRuntimeValue = "********";
41
+ /** Vercel names first, then the names that the Upstash console and NuxtHub use. */
42
+ const upstashUrlEnvNames = ["KV_REST_API_URL", "UPSTASH_REDIS_REST_URL"];
43
+ const upstashTokenEnvNames = ["KV_REST_API_TOKEN", "UPSTASH_REDIS_REST_TOKEN"];
44
+ function hasUpstashEnv(env) {
45
+ const url = readEnv(env, ...upstashUrlEnvNames);
46
+ const token = readEnv(env, ...upstashTokenEnvNames);
47
+ return Boolean(url && token);
48
+ }
49
+ /** `base` is the resolved key prefix of the store, never empty. */
50
+ function resolveUpstashStore(config, base) {
51
+ return {
52
+ driver: "upstash",
53
+ base,
54
+ token: trimmed(config.token) ?? maskedUpstashRuntimeValue,
55
+ url: trimmed(config.url) ?? maskedUpstashRuntimeValue
56
+ };
57
+ }
58
+ //#endregion
59
+ //#region src/config.ts
60
+ /** The variable that a `redis` store reads at runtime when it sets no `url`. */
61
+ const redisUrlEnvName = "REDIS_URL";
62
+ /** Where a Cloudflare KV store keeps its keys in `vite dev` when the runtime has no binding. */
63
+ function cloudflareKVLocalBase(binding) {
64
+ return `.vitehub/data/kv-cloudflare/${binding}`;
65
+ }
66
+ function readRemote(config, store) {
67
+ const remote = Reflect.get(config, "remote");
68
+ if (remote === void 0 || typeof remote === "boolean") return remote;
69
+ throw kvErrorDiagnostics.KV_INVALID_REMOTE({ store });
70
+ }
71
+ /** Applies `vite dev` mode: hosted stores are marked remote, and a Cloudflare store gets its local fallback. */
72
+ function resolveDevStore(store, remote) {
73
+ if (store.driver === "upstash") return {
74
+ ...store,
75
+ remote: true
76
+ };
77
+ if (store.driver !== "cloudflare") return store;
78
+ return remote ? {
79
+ ...store,
80
+ remote: true
81
+ } : {
82
+ ...store,
83
+ localBase: cloudflareKVLocalBase(store.binding)
84
+ };
85
+ }
86
+ /**
87
+ * The folder of an `fs-lite` store without `base`. The default store keeps `.vitehub/data/kv`. Each named store gets its
88
+ * own folder next to it, so stores never share keys. It is not inside `.vitehub/data/kv`, because the default store
89
+ * treats folders there as keys from the old layout.
90
+ */
91
+ function fsLiteStoreBase(name) {
92
+ if (name === "default") return ".vitehub/data/kv";
93
+ return `.vitehub/data/kv-stores/${encodeURIComponent(name).replace(/\./g, "%2E") || "%"}`;
94
+ }
95
+ function resolveFsLiteStore(config = {}, name = "default") {
96
+ return defu({ base: trimmed(config.base) }, {
97
+ driver: "fs-lite",
98
+ base: fsLiteStoreBase(name)
99
+ });
100
+ }
101
+ /** The key prefix of a Redis store without `base`. Every store has one, so a shared Redis keeps other keys apart. */
102
+ function redisStorePrefix(name) {
103
+ return `vitehub:kv:${name.replace(/[%:/\\?]/g, (character) => encodeURIComponent(character)) || "%"}`;
104
+ }
105
+ /** An empty prefix would let `kv.clear()` and `kv.keys()` reach every key of the Redis or Upstash database. */
106
+ function resolveStoreBase(base, name) {
107
+ return normalizeKey(trimmed(base)) || redisStorePrefix(name);
108
+ }
109
+ function resolveRedisStore(config, name) {
110
+ return {
111
+ driver: "redis",
112
+ base: resolveStoreBase(config.base, name),
113
+ url: trimmed(config.url) ?? `env:REDIS_URL`
114
+ };
115
+ }
116
+ function resolveDatabaseStore(config, name) {
117
+ return {
118
+ driver: "database",
119
+ database: trimmed(config.database) ?? "default",
120
+ namespace: name
121
+ };
122
+ }
123
+ function resolveCloudflareStore(config = {}, env = process.env) {
124
+ return defu({
125
+ binding: trimmed(config.binding),
126
+ namespaceId: trimmed(config.namespaceId) ?? readEnv(env, "KV_NAMESPACE_ID"),
127
+ namespaceName: trimmed(config.namespaceName)
128
+ }, {
129
+ driver: "cloudflare",
130
+ binding: "KV"
131
+ });
132
+ }
133
+ function resolveDenoStore(config = {}) {
134
+ const path = trimmed(config.path);
135
+ return path ? {
136
+ driver: "deno-kv",
137
+ path
138
+ } : { driver: "deno-kv" };
139
+ }
140
+ function resolveExplicitStore(store, env, name, dev) {
141
+ const remote = readRemote(store, name);
142
+ const { driver } = store;
143
+ if (dev && (remote === true && (driver === "fs-lite" || driver === "deno-kv") || remote === false && driver === "upstash")) throw kvErrorDiagnostics.KV_REMOTE_CONFLICT({
144
+ driver,
145
+ remote,
146
+ store: name
147
+ });
148
+ const resolved = resolveStoreDriver(store, env, name);
149
+ return dev ? resolveDevStore(resolved, remote) : resolved;
150
+ }
151
+ function resolveStoreDriver(store, env, name) {
152
+ switch (store.driver) {
153
+ case "cloudflare": return resolveCloudflareStore(store, env);
154
+ case "database": return resolveDatabaseStore(store, name);
155
+ case "deno-kv": return resolveDenoStore(store);
156
+ case "fs-lite": return resolveFsLiteStore(store, name);
157
+ case "redis": return resolveRedisStore(store, name);
158
+ case "upstash": return resolveUpstashStore(store, resolveStoreBase(store.base, name));
159
+ default: {
160
+ const driver = store.driver;
161
+ throw kvErrorDiagnostics.KV_INVALID_DRIVER({
162
+ driver: JSON.stringify(driver) ?? String(driver),
163
+ renamed: renamedKVDrivers.get(String(driver))
164
+ });
165
+ }
166
+ }
167
+ }
168
+ /** Driver names that ViteHub renamed to the host name. `npx @vite-hub/codemods driver-key` moves them. */
169
+ const renamedKVDrivers = /* @__PURE__ */ new Map([["cloudflare-kv-binding", "cloudflare"]]);
170
+ function createResolvedConfig(store, stores) {
171
+ return stores ? {
172
+ store,
173
+ stores: {
174
+ default: store,
175
+ ...stores
176
+ }
177
+ } : { store };
178
+ }
179
+ function hasStoresConfig(options, stores) {
180
+ return !!options && Object.hasOwn(options, "stores") && isRecord(stores);
181
+ }
182
+ function normalizeKVOptions(options, input = {}) {
183
+ if (options === false) return;
184
+ if (typeof options !== "undefined" && !isRecord(options)) throw kvErrorDiagnostics.KV_INVALID_CONFIG({ path: "kv" });
185
+ const env = input.env || process.env;
186
+ const hosting = normalizeHosting(input.hosting);
187
+ const explicit = options;
188
+ const hasOwnStores = options !== void 0 && Object.hasOwn(options, "stores");
189
+ const stores = hasOwnStores ? Reflect.get(options, "stores", options) : void 0;
190
+ if (hasOwnStores && !isRecord(stores)) throw kvErrorDiagnostics.KV_INVALID_CONFIG({ path: "kv.stores" });
191
+ if (hasStoresConfig(options, stores)) {
192
+ const resolvedStores = Object.fromEntries(Object.entries(stores).map(([name, store]) => [name, resolveExplicitStore(store, env, name, input.dev)]));
193
+ const defaultStore = resolvedStores.default;
194
+ if (!defaultStore) throw kvErrorDiagnostics.KV_MISSING_DEFAULT_STORE();
195
+ return createResolvedConfig(defaultStore, resolvedStores);
196
+ }
197
+ if (explicit?.driver) return createResolvedConfig(resolveExplicitStore(explicit, env, "default", input.dev));
198
+ const remote = explicit ? readRemote(explicit, "default") : void 0;
199
+ const inferred = (store) => createResolvedConfig(input.dev ? resolveDevStore(store, remote) : store);
200
+ const hosted = !input.dev || remote === true;
201
+ if (hosting.includes("deno")) {
202
+ if (input.dev && remote === true) throw kvErrorDiagnostics.KV_REMOTE_CONFLICT({
203
+ driver: "deno-kv",
204
+ remote,
205
+ store: "default"
206
+ });
207
+ return inferred(resolveDenoStore());
208
+ }
209
+ if (hosted && hasUpstashEnv(env)) return inferred(resolveUpstashStore({}, redisStorePrefix("default")));
210
+ if (hosted && hosting.includes("vercel")) return inferred(resolveUpstashStore({}, redisStorePrefix("default")));
211
+ if (hosting.includes("cloudflare")) return inferred(resolveCloudflareStore({}, env));
212
+ if (input.dev && remote === true) throw kvErrorDiagnostics.KV_REMOTE_CONFLICT({
213
+ driver: "fs-lite",
214
+ remote,
215
+ store: "default"
216
+ });
217
+ if (input.dev) return inferred(resolveFsLiteStore());
218
+ if (input.postgresDatabase) return inferred({
219
+ ...resolveDatabaseStore({}, "default"),
220
+ inferred: true
221
+ });
222
+ return inferred({
223
+ ...resolveFsLiteStore(),
224
+ inferred: true
225
+ });
226
+ }
227
+ /** The line that a server prints at boot for its build-selected inferred store. */
228
+ function kvInferredStoreNotice(name, store) {
229
+ if (!("inferred" in store) || !store.inferred) return;
230
+ if (store.driver === "database") return `[vitehub] KV store "${name}" uses the table vitehub_kv of the Database "${store.database}", selected at build time.`;
231
+ if (store.driver === "fs-lite") return `[vitehub] KV store "${name}" uses fs-lite in ${store.base}, selected at build time. Other server processes cannot read its keys.`;
232
+ }
233
+ /**
234
+ * The build warning for a Redis URL that KV does not use. Redis is never inferred, because a `REDIS_URL` often belongs to
235
+ * another service, such as BullMQ or sessions. A NuxtHub app that kept its keys in Redis must select it.
236
+ */
237
+ function kvRedisEnvWarning(options, input = {}) {
238
+ if (options === false || input.dev || options && ("stores" in options || options.driver)) return;
239
+ const env = input.env || process.env;
240
+ const name = readEnv(env, "REDIS_URL") ? redisUrlEnvName : readEnv(env, "KV_URL")?.startsWith("rediss://") ? "KV_URL" : void 0;
241
+ if (!name) return;
242
+ const fix = `To keep KV in that Redis, set \`kv: { driver: "redis"${name === "REDIS_URL" ? "" : `, url: "env:${name}"`} }\`. To keep this store, set its \`driver\`.`;
243
+ const store = normalizeKVOptions(options, input)?.store;
244
+ if (store?.driver === "upstash" && !hasUpstashEnv(env)) return `[vitehub] KV on Vercel uses Upstash, and the build has no \`KV_REST_API_URL\` and \`KV_REST_API_TOKEN\`, so KV fails at runtime. The build has \`${name}\`, and KV does not select Redis on its own. ${fix}`;
245
+ const selected = store?.driver === "database" ? `the table vitehub_kv of the Database "${store.database}"` : store?.driver === "fs-lite" ? `fs-lite in ${store.base}` : void 0;
246
+ if (!selected) return;
247
+ return `[vitehub] The build has \`${name}\`, but KV does not select Redis on its own. The KV store "default" uses ${selected}. ${fix}`;
248
+ }
249
+ //#endregion
250
+ export { upstashUrlEnvNames as a, upstashTokenEnvNames as i, kvRedisEnvWarning as n, resolveHostPreset as o, normalizeKVOptions as r, readEnv as s, kvInferredStoreNotice as t };