@vite-hub/kv 0.0.3 → 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.
Files changed (39) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +40 -7
  3. package/dist/cli-Cniq99iX.d.ts +85 -0
  4. package/dist/cli.d.ts +15 -0
  5. package/dist/cli.js +448 -0
  6. package/dist/cloudflare-env-C5rM7kUY.js +74 -0
  7. package/dist/{config-C1ofyzSt.js → config-DR6_5ZwI.js} +37 -17
  8. package/dist/continuations-DPyH_vr1.js +63 -0
  9. package/dist/create-storage-29gMzf41.js +442 -0
  10. package/dist/cursor-history-dqYDlsaD.js +148 -0
  11. package/dist/deno-kv-CSYGvRx4.js +120 -0
  12. package/dist/driver-D9fI27jl.d.ts +94 -0
  13. package/dist/error-diagnostics-D_cQeZTi.js +82 -0
  14. package/dist/errors-Dc2oiW-Y.js +38 -0
  15. package/dist/errors.d.ts +12 -7
  16. package/dist/errors.js +2 -20
  17. package/dist/fs-lite-CbLKxLut.js +90 -0
  18. package/dist/index.d.ts +5 -4
  19. package/dist/index.js +119 -49
  20. package/dist/object-B1NW521B.js +7 -0
  21. package/dist/operations-ByuDE12r.js +1442 -0
  22. package/dist/operations-pn8_eGob.js +432 -0
  23. package/dist/operations-tNUdj3G4.d.ts +212 -0
  24. package/dist/operations.d.ts +68 -0
  25. package/dist/operations.js +455 -0
  26. package/dist/results-p7nPCnaJ.js +6 -0
  27. package/dist/runtime/cloudflare-kv.d.ts +6 -0
  28. package/dist/runtime/cloudflare-kv.js +100 -0
  29. package/dist/runtime/upstash-driver.d.ts +5 -2
  30. package/dist/runtime/upstash-driver.js +111 -2
  31. package/dist/types-CMDvN0Wr.d.ts +81 -0
  32. package/dist/utils2-Dsb9P4_2.js +28 -0
  33. package/dist/virtual-module.d.ts +6 -0
  34. package/dist/virtual.d.ts +2 -6
  35. package/dist/vite.d.ts +30 -10
  36. package/dist/vite.js +4910 -213
  37. package/package.json +57 -15
  38. package/dist/deno-kv-JnitV_jG.js +0 -54
  39. package/dist/types-Dg4l318i.d.ts +0 -60
package/dist/index.js CHANGED
@@ -1,30 +1,33 @@
1
- import { kvResult } from "./errors.js";
2
- import { n as readEnv, t as normalizeKVOptions } from "./config-C1ofyzSt.js";
3
- import { AsyncLocalStorage } from "node:async_hooks";
4
- import { createStorage } from "unstorage";
5
- const activeEnvStorage = new AsyncLocalStorage();
6
- function getActiveCloudflareEnv() {
7
- const scoped = activeEnvStorage.getStore();
8
- return scoped ? scoped.env : globalThis.__env__;
9
- }
10
- //#endregion
1
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-D_cQeZTi.js";
2
+ import { n as kvResult } from "./errors-Dc2oiW-Y.js";
3
+ import { a as readEnv, n as upstashTokenEnvNames, r as upstashUrlEnvNames, t as normalizeKVOptions } from "./config-DR6_5ZwI.js";
4
+ import { n as getActiveCloudflareEnv } from "./cloudflare-env-C5rM7kUY.js";
5
+ import { n as normalizeKVListPrefix, t as createKVStorage$1 } from "./create-storage-29gMzf41.js";
6
+ import { a as normalizeKey } from "./utils2-Dsb9P4_2.js";
7
+ import { destr } from "destr";
11
8
  //#region src/runtime/upstash.ts
12
9
  function isMaskedValue(value) {
13
10
  return !value || /^\*+$/.test(value);
14
11
  }
15
- function assertRuntimeValue(value, envName) {
16
- if (isMaskedValue(value)) throw new Error(`Missing runtime environment variable \`${envName}\` for Upstash KV.`);
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
17
  }
18
18
  function resolveRuntimeUpstashStore(config, env) {
19
- const envUrl = readEnv(env, "KV_REST_API_URL");
20
- const envToken = readEnv(env, "KV_REST_API_TOKEN");
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 ?? "********";
21
24
  const resolved = {
22
25
  ...config,
23
- token: isMaskedValue(config.token) ? envToken || config.token : config.token,
24
- url: isMaskedValue(config.url) ? envUrl || config.url : config.url
26
+ token: resolveMaskedValue(config.token, completeEnvPair?.[1], hasMaskedPair ? void 0 : envToken),
27
+ url: resolveMaskedValue(config.url, completeEnvPair?.[0], hasMaskedPair ? void 0 : envUrl)
25
28
  };
26
- assertRuntimeValue(resolved.url, "KV_REST_API_URL");
27
- assertRuntimeValue(resolved.token, "KV_REST_API_TOKEN");
29
+ assertRuntimeValue(resolved.url, upstashUrlEnvNames);
30
+ assertRuntimeValue(resolved.token, upstashTokenEnvNames);
28
31
  return resolved;
29
32
  }
30
33
  function resolveRuntimeKVOptions(config, env = process.env) {
@@ -36,36 +39,41 @@ function resolveRuntimeKVOptions(config, env = process.env) {
36
39
  }
37
40
  //#endregion
38
41
  //#region src/runtime/driver.ts
39
- const lazyDriverMethods = new Set([
42
+ const lazyDriverMethods = /* @__PURE__ */ new Set([
40
43
  "clear",
41
44
  "getItem",
42
45
  "getKeys",
43
46
  "hasItem",
47
+ "listKeys",
44
48
  "removeItem",
45
49
  "setItem"
46
50
  ]);
47
51
  const lazyOptionalDriverMethods = {
48
52
  "cloudflare-kv-binding": /* @__PURE__ */ new Set(),
49
53
  "deno-kv": /* @__PURE__ */ new Set(),
50
- "fs-lite": new Set([
54
+ "fs-lite": /* @__PURE__ */ new Set([
51
55
  "getItemRaw",
52
56
  "getMeta",
53
57
  "setItemRaw"
54
58
  ]),
55
- "upstash": new Set(["getItems"])
59
+ "upstash": /* @__PURE__ */ new Set([
60
+ "getAndDeleteItem",
61
+ "getItems",
62
+ "incrementItem"
63
+ ])
56
64
  };
57
65
  async function createRuntimeDriver(store) {
58
66
  switch (store.driver) {
59
67
  case "cloudflare-kv-binding": {
60
- const { default: factory } = await import("unstorage/drivers/cloudflare-kv-binding");
68
+ const { default: factory } = await import("./runtime/cloudflare-kv.js");
61
69
  return factory(store);
62
70
  }
63
71
  case "deno-kv": {
64
- const { default: factory } = await import("./deno-kv-JnitV_jG.js");
72
+ const { default: factory } = await import("./deno-kv-CSYGvRx4.js");
65
73
  return factory(store);
66
74
  }
67
75
  case "fs-lite": {
68
- const { default: factory } = await import("unstorage/drivers/fs-lite");
76
+ const { default: factory } = await import("./fs-lite-CbLKxLut.js");
69
77
  return factory(store);
70
78
  }
71
79
  case "upstash": {
@@ -76,11 +84,21 @@ async function createRuntimeDriver(store) {
76
84
  }
77
85
  function createLazyKVRuntimeDriver(config) {
78
86
  let driverPromise;
79
- const resolve = () => driverPromise ||= (async () => {
80
- const runtime = resolveRuntimeKVOptions(config);
81
- if (!runtime) throw new Error("KV runtime is disabled.");
82
- return createRuntimeDriver(runtime.store);
83
- })();
87
+ let disposed = false;
88
+ function resolve() {
89
+ if (disposed) return Promise.reject(/* @__PURE__ */ new Error("KV storage has been disposed."));
90
+ if (driverPromise) return driverPromise;
91
+ const pending = (async () => {
92
+ const runtime = resolveRuntimeKVOptions(config);
93
+ if (!runtime) throw kvErrorDiagnostics.KV_DISABLED();
94
+ return createRuntimeDriver(runtime.store);
95
+ })();
96
+ driverPromise = pending;
97
+ pending.catch(() => {
98
+ if (driverPromise === pending) driverPromise = void 0;
99
+ });
100
+ return pending;
101
+ }
84
102
  const target = {
85
103
  name: `lazy:${config.store.driver}`,
86
104
  options: config.store
@@ -89,6 +107,7 @@ function createLazyKVRuntimeDriver(config) {
89
107
  const own = t[prop];
90
108
  if (own !== void 0) return own;
91
109
  if (prop === "dispose") return async () => {
110
+ disposed = true;
92
111
  if (!driverPromise) return;
93
112
  const driver = await driverPromise;
94
113
  return driver.dispose?.call(driver);
@@ -103,29 +122,59 @@ function createLazyKVRuntimeDriver(config) {
103
122
  }
104
123
  //#endregion
105
124
  //#region src/runtime/hosted-storage.ts
106
- var KVStoreConfigurationError = class extends Error {};
107
125
  function assertHostedConfig(config) {
108
- if (!config) throw new KVStoreConfigurationError("[vitehub] `@vite-hub/kv` requires `hubKv()` and `kv !== false`.");
126
+ if (!config) throw kvErrorDiagnostics.KV_DISABLED();
109
127
  return config;
110
128
  }
111
- function createHostedKVStorage(config) {
112
- return createNamedHostedKVStorage(config, "default");
129
+ function deserializeValue(value) {
130
+ if (typeof value !== "string") return value;
131
+ return destr(value);
113
132
  }
114
- function createNamedHostedKVStorage(config, name) {
133
+ function createHostedKVStorage(config, name = "default") {
115
134
  const resolved = assertHostedConfig(config);
116
- const store = (resolved.stores || { default: resolved.store })[name];
117
- if (!store) throw new KVStoreConfigurationError(`[vitehub] Unknown KV store "${name}".`);
118
- return createStorage({ driver: createLazyKVRuntimeDriver({
135
+ const stores = resolved.stores || { default: resolved.store };
136
+ const store = Object.hasOwn(stores, name) ? stores[name] : void 0;
137
+ if (!store) throw kvErrorDiagnostics.KV_STORE_NOT_FOUND({ store: name });
138
+ const driver = createLazyKVRuntimeDriver({
119
139
  store,
120
140
  stores: {
121
141
  default: store,
122
142
  [name]: store
123
143
  }
124
- }) });
144
+ });
145
+ const storage = createKVStorage$1(driver);
146
+ storage.listKeys = (options) => driver.listKeys({
147
+ ...options,
148
+ prefix: normalizeKVListPrefix(options.prefix)
149
+ });
150
+ const getAndDeleteItem = driver.getAndDeleteItem;
151
+ const incrementItem = driver.incrementItem;
152
+ if (getAndDeleteItem) storage.getAndDeleteItem = async (key) => {
153
+ return deserializeValue(await getAndDeleteItem(normalizeKey(key)));
154
+ };
155
+ if (incrementItem) storage.incrementItem = (key, ttl) => incrementItem(normalizeKey(key), ttl);
156
+ return storage;
125
157
  }
126
158
  //#endregion
127
159
  //#region src/runtime/storage.ts
128
160
  const storagePromises = /* @__PURE__ */ new Map();
161
+ let disposal;
162
+ /** Releases every cached store. Call from the application's shutdown hook after stopping new work. */
163
+ function disposeKVStores() {
164
+ if (disposal) return disposal;
165
+ const stores = [...storagePromises.values()];
166
+ storagePromises.clear();
167
+ const pending = Promise.allSettled(stores.map(async (promise) => {
168
+ await (await promise.catch(() => void 0))?.dispose();
169
+ })).then((results) => {
170
+ const failures = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
171
+ if (failures.length) throw new AggregateError(failures, "Failed to dispose KV stores.");
172
+ }).finally(() => {
173
+ disposal = void 0;
174
+ });
175
+ disposal = pending;
176
+ return pending;
177
+ }
129
178
  function inferHosting(env) {
130
179
  if (getActiveCloudflareEnv()) return "cloudflare";
131
180
  const explicit = readEnv(env, "VITEHUB_HOSTING");
@@ -150,21 +199,19 @@ async function resolveHostedConfig() {
150
199
  }
151
200
  }
152
201
  async function resolveStorage(name = "default") {
202
+ if (disposal) await disposal;
153
203
  const existing = storagePromises.get(name);
154
204
  if (existing) return existing;
155
- if (inferHosting(typeof process !== "undefined" ? process.env : {}) === "vercel") {
156
- const promise = resolveHostedConfig().then((config) => name === "default" ? createHostedKVStorage(config) : createNamedHostedKVStorage(config, name));
157
- storagePromises.set(name, promise);
158
- return promise;
159
- }
160
- const promise = resolveHostedConfig().then((config) => name === "default" ? createHostedKVStorage(config) : createNamedHostedKVStorage(config, name));
205
+ const promise = resolveHostedConfig().then((config) => createHostedKVStorage(config, name));
161
206
  storagePromises.set(name, promise);
207
+ promise.catch(() => {
208
+ if (storagePromises.get(name) === promise) storagePromises.delete(name);
209
+ });
162
210
  return promise;
163
211
  }
164
- async function runKVOperation(operation, name, run) {
165
- const result = await kvResult(operation, name, async () => run(await resolveStorage(name)));
166
- if (result[0]?.cause instanceof KVStoreConfigurationError) throw result[0].cause;
167
- return result;
212
+ async function runKVOperation(operation, name, run, codes = []) {
213
+ const storage = await resolveStorage(name);
214
+ return kvResult(operation, name, () => run(storage), codes);
168
215
  }
169
216
  function createKVStorage(name = "default") {
170
217
  return {
@@ -177,12 +224,35 @@ function createKVStorage(name = "default") {
177
224
  async get(key, options) {
178
225
  return runKVOperation("get", name, (storage) => storage.getItem(key, options));
179
226
  },
227
+ async getAndDelete(key) {
228
+ return runKVOperation("getAndDelete", name, async (storage) => {
229
+ if (!storage.getAndDeleteItem) throw kvErrorDiagnostics.KV_UNSUPPORTED_OPERATION({
230
+ operation: "getAndDelete",
231
+ store: name
232
+ });
233
+ return storage.getAndDeleteItem(key);
234
+ }, ["KV_UNSUPPORTED_OPERATION"]);
235
+ },
180
236
  async has(key, options) {
181
237
  return runKVOperation("has", name, (storage) => storage.hasItem(key, options));
182
238
  },
239
+ async increment(key, ttl) {
240
+ return runKVOperation("increment", name, async (storage) => {
241
+ if (!storage.incrementItem) throw kvErrorDiagnostics.KV_UNSUPPORTED_OPERATION({
242
+ operation: "increment",
243
+ store: name
244
+ });
245
+ if (!Number.isFinite(ttl) || ttl <= 0 || !Number.isSafeInteger(Math.ceil(ttl))) throw kvErrorDiagnostics.KV_INVALID_TTL();
246
+ return storage.incrementItem(key, ttl);
247
+ }, ["KV_INVALID_TTL", "KV_UNSUPPORTED_OPERATION"]);
248
+ },
183
249
  async keys(base, options) {
184
250
  return runKVOperation("keys", name, (storage) => storage.getKeys(base, options));
185
251
  },
252
+ async list(options) {
253
+ if (!Number.isInteger(options.limit) || options.limit <= 0) return [kvErrorDiagnostics.KV_INVALID_LIMIT(), void 0];
254
+ return runKVOperation("list", name, (storage) => storage.listKeys(options), ["KV_INVALID_CURSOR"]);
255
+ },
186
256
  async set(key, value, options) {
187
257
  return runKVOperation("set", name, async (storage) => storage.setItem(key, value, options));
188
258
  },
@@ -193,4 +263,4 @@ function createKVStorage(name = "default") {
193
263
  }
194
264
  const kv = createKVStorage();
195
265
  //#endregion
196
- export { kv };
266
+ export { disposeKVStores, kv };
@@ -0,0 +1,7 @@
1
+ //#region ../internal/src/object.ts
2
+ function isPlainObject(value) {
3
+ if (value === null || Object(value) !== value || Array.isArray(value)) return false;
4
+ return typeof value === "object";
5
+ }
6
+ //#endregion
7
+ export { isPlainObject as t };