@vite-hub/kv 0.0.2 → 0.0.4

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/dist/index.js CHANGED
@@ -1,8 +1,11 @@
1
1
  import { kvResult } from "./errors.js";
2
- import { n as readEnv, t as normalizeKVOptions } from "./config-C1ofyzSt.js";
2
+ import { r as readEnv, t as normalizeKVOptions } from "./config-aM9Ae7tH.js";
3
+ import { n as normalizeKey, t as createStorage } from "./dist-DDW1iC5f.js";
3
4
  import { AsyncLocalStorage } from "node:async_hooks";
4
- import { createStorage } from "unstorage";
5
- const activeEnvStorage = new AsyncLocalStorage();
5
+ import { destr } from "destr";
6
+ const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
7
+ const runtimeGlobal = globalThis;
8
+ const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
6
9
  function getActiveCloudflareEnv() {
7
10
  const scoped = activeEnvStorage.getStore();
8
11
  return scoped ? scoped.env : globalThis.__env__;
@@ -41,6 +44,7 @@ const lazyDriverMethods = new Set([
41
44
  "getItem",
42
45
  "getKeys",
43
46
  "hasItem",
47
+ "listKeys",
44
48
  "removeItem",
45
49
  "setItem"
46
50
  ]);
@@ -52,20 +56,24 @@ const lazyOptionalDriverMethods = {
52
56
  "getMeta",
53
57
  "setItemRaw"
54
58
  ]),
55
- "upstash": new Set(["getItems"])
59
+ "upstash": 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-cJx3jU10.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-BxzdiJSi.js");
69
77
  return factory(store);
70
78
  }
71
79
  case "upstash": {
@@ -104,10 +112,19 @@ function createLazyKVRuntimeDriver(config) {
104
112
  //#endregion
105
113
  //#region src/runtime/hosted-storage.ts
106
114
  var KVStoreConfigurationError = class extends Error {};
115
+ var KVAtomicOperationUnsupportedError = class extends KVStoreConfigurationError {
116
+ constructor(store) {
117
+ super(`[vitehub] KV store "${store}" does not support atomic operations. Use Upstash.`);
118
+ }
119
+ };
107
120
  function assertHostedConfig(config) {
108
121
  if (!config) throw new KVStoreConfigurationError("[vitehub] `@vite-hub/kv` requires `hubKv()` and `kv !== false`.");
109
122
  return config;
110
123
  }
124
+ function deserializeValue(value) {
125
+ if (typeof value !== "string") return value;
126
+ return destr(value);
127
+ }
111
128
  function createHostedKVStorage(config) {
112
129
  return createNamedHostedKVStorage(config, "default");
113
130
  }
@@ -115,13 +132,22 @@ function createNamedHostedKVStorage(config, name) {
115
132
  const resolved = assertHostedConfig(config);
116
133
  const store = (resolved.stores || { default: resolved.store })[name];
117
134
  if (!store) throw new KVStoreConfigurationError(`[vitehub] Unknown KV store "${name}".`);
118
- return createStorage({ driver: createLazyKVRuntimeDriver({
135
+ const driver = createLazyKVRuntimeDriver({
119
136
  store,
120
137
  stores: {
121
138
  default: store,
122
139
  [name]: store
123
140
  }
124
- }) });
141
+ });
142
+ const storage = createStorage({ driver });
143
+ storage.listKeys = (options) => driver.listKeys(options);
144
+ const getAndDeleteItem = driver.getAndDeleteItem;
145
+ const incrementItem = driver.incrementItem;
146
+ if (getAndDeleteItem) storage.getAndDeleteItem = async (key) => {
147
+ return deserializeValue(await getAndDeleteItem(normalizeKey(key)));
148
+ };
149
+ if (incrementItem) storage.incrementItem = (key, ttl) => incrementItem(normalizeKey(key), ttl);
150
+ return storage;
125
151
  }
126
152
  //#endregion
127
153
  //#region src/runtime/storage.ts
@@ -177,12 +203,28 @@ function createKVStorage(name = "default") {
177
203
  async get(key, options) {
178
204
  return runKVOperation("get", name, (storage) => storage.getItem(key, options));
179
205
  },
206
+ async getAndDelete(key) {
207
+ return runKVOperation("getAndDelete", name, (storage) => {
208
+ if (!storage.getAndDeleteItem) throw new KVAtomicOperationUnsupportedError(name);
209
+ return storage.getAndDeleteItem(key);
210
+ });
211
+ },
180
212
  async has(key, options) {
181
213
  return runKVOperation("has", name, (storage) => storage.hasItem(key, options));
182
214
  },
215
+ async increment(key, ttl) {
216
+ return runKVOperation("increment", name, (storage) => {
217
+ if (!storage.incrementItem) throw new KVAtomicOperationUnsupportedError(name);
218
+ return storage.incrementItem(key, ttl);
219
+ });
220
+ },
183
221
  async keys(base, options) {
184
222
  return runKVOperation("keys", name, (storage) => storage.getKeys(base, options));
185
223
  },
224
+ async list(options) {
225
+ if (!Number.isInteger(options.limit) || options.limit <= 0) throw new TypeError("`limit` must be a positive integer.");
226
+ return runKVOperation("list", name, (storage) => storage.listKeys(options));
227
+ },
186
228
  async set(key, value, options) {
187
229
  return runKVOperation("set", name, async (storage) => storage.setItem(key, value, options));
188
230
  },
@@ -0,0 +1,7 @@
1
+ import { t as KVRuntimeDriver } from "../driver-BT9WefKi.js";
2
+
3
+ //#region src/runtime/cloudflare-kv.d.ts
4
+ declare function createCloudflareDriver(options: Record<string, unknown>): KVRuntimeDriver;
5
+ declare function createCloudflareKVStorage(options: Record<string, unknown>): unknown;
6
+ //#endregion
7
+ export { createCloudflareKVStorage, createCloudflareDriver as default };
@@ -0,0 +1,24 @@
1
+ import { t as createStorage } from "../dist-DDW1iC5f.js";
2
+ import createDriver from "unstorage/drivers/cloudflare-kv-binding";
3
+ //#region src/runtime/cloudflare-kv.ts
4
+ function createCloudflareDriver(options) {
5
+ const driver = createDriver(options);
6
+ driver.listKeys = async ({ cursor, limit, prefix = "" }) => {
7
+ const listOptions = { limit };
8
+ if (cursor) listOptions.cursor = cursor;
9
+ if (prefix) listOptions.prefix = prefix;
10
+ const page = await driver.getInstance().list(listOptions);
11
+ const result = { keys: page.keys.map((key) => key.name) };
12
+ if (!page.list_complete) result.cursor = page.cursor;
13
+ return result;
14
+ };
15
+ return driver;
16
+ }
17
+ function createCloudflareKVStorage(options) {
18
+ const driver = createCloudflareDriver(options);
19
+ const storage = createStorage({ driver });
20
+ storage.listKeys = (listOptions) => driver.listKeys(listOptions);
21
+ return storage;
22
+ }
23
+ //#endregion
24
+ export { createCloudflareKVStorage, createCloudflareDriver as default };
@@ -1,2 +1,7 @@
1
- import upstash_default from "unstorage/drivers/upstash";
2
- export { upstash_default as default };
1
+ import { v as ResolvedUpstashKVStoreConfig } from "../types-CO0DRjJa.js";
2
+ import { t as KVRuntimeDriver } from "../driver-BT9WefKi.js";
3
+
4
+ //#region src/runtime/upstash-driver.d.ts
5
+ declare function createUpstashKVDriver(options: ResolvedUpstashKVStoreConfig): KVRuntimeDriver;
6
+ //#endregion
7
+ export { createUpstashKVDriver as default };
@@ -1,2 +1,121 @@
1
- import upstash_default from "unstorage/drivers/upstash";
2
- export { upstash_default as default };
1
+ import createDriver from "unstorage/drivers/upstash";
2
+ //#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
+ }
44
+ 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;
55
+ };
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)}*`
102
+ });
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 })
116
+ };
117
+ };
118
+ return driver;
119
+ }
120
+ //#endregion
121
+ export { createUpstashKVDriver as default };
@@ -41,20 +41,38 @@ interface ResolvedKVModuleOptions {
41
41
  store: ResolvedKVStoreConfig;
42
42
  stores?: Record<string, ResolvedKVStoreConfig>;
43
43
  }
44
- type KVOperation = "clear" | "del" | "get" | "has" | "keys" | "set";
44
+ type KVOperation = "clear" | "del" | "get" | "getAndDelete" | "has" | "increment" | "keys" | "list" | "set";
45
45
  type KVErrorDetails = ViteHubErrorDetails & {
46
46
  operation: KVOperation;
47
47
  store: string;
48
48
  };
49
49
  type KVResult<TResult> = [error: null, value: TResult] | [error: ViteHubError<"KV_OPERATION_FAILED", KVErrorDetails>, value: undefined];
50
+ interface KVListOptions {
51
+ /** Opaque continuation cursor returned by a previous page. */
52
+ cursor?: string;
53
+ /** Maximum number of keys to read. Must be a positive integer. */
54
+ limit: number;
55
+ prefix?: string;
56
+ }
57
+ interface KVListPage {
58
+ /** Provider-ordered keys. */
59
+ keys: string[];
60
+ /** Omitted when enumeration is complete. */
61
+ cursor?: string;
62
+ }
50
63
  interface KVStorage {
51
64
  clear(base?: string, options?: unknown): Promise<KVResult<void>>;
52
65
  del(key: string, options?: unknown): Promise<KVResult<void>>;
53
66
  get<T = unknown>(key: string, options?: unknown): Promise<KVResult<T | null>>;
67
+ /** Atomically returns and deletes a value when the configured store supports it. */
68
+ getAndDelete<T = unknown>(key: string): Promise<KVResult<T | null>>;
54
69
  has(key: string, options?: unknown): Promise<KVResult<boolean>>;
70
+ /** Atomically increments a counter. The TTL is applied only when the counter is created. */
71
+ increment(key: string, ttl: number): Promise<KVResult<number>>;
55
72
  keys(base?: string, options?: unknown): Promise<KVResult<string[]>>;
73
+ list(options: KVListOptions): Promise<KVResult<KVListPage>>;
56
74
  set<T = unknown>(key: string, value: T, options?: unknown): Promise<KVResult<void>>;
57
75
  store(name: KVStoreName): KVStorage;
58
76
  }
59
77
  //#endregion
60
- export { UpstashKVStoreConfig as _, KVErrorDetails as a, KVResult as c, ResolvedCloudflareKVStoreConfig as d, ResolvedDenoKVStoreConfig as f, ResolvedUpstashKVStoreConfig as g, ResolvedKVStoreConfig as h, KVDriver as i, KVStorage as l, ResolvedKVModuleOptions as m, DenoKVStoreConfig as n, KVModuleOptions as o, ResolvedFsLiteKVStoreConfig as p, FsLiteKVStoreConfig as r, KVOperation as s, CloudflareKVStoreConfig as t, KVStoreConfig as u };
78
+ export { ResolvedKVStoreConfig as _, KVErrorDetails as a, KVModuleOptions as c, KVStorage as d, KVStoreConfig as f, ResolvedKVModuleOptions as g, ResolvedFsLiteKVStoreConfig as h, KVDriver as i, KVOperation as l, ResolvedDenoKVStoreConfig as m, DenoKVStoreConfig as n, KVListOptions as o, ResolvedCloudflareKVStoreConfig as p, FsLiteKVStoreConfig as r, KVListPage as s, CloudflareKVStoreConfig as t, KVResult as u, ResolvedUpstashKVStoreConfig as v, UpstashKVStoreConfig as y };
@@ -0,0 +1,6 @@
1
+ declare module "#vitehub/kv/config" {
2
+ export const hosting: string | undefined
3
+ export const kv: false | import("./index.js").ResolvedKVModuleOptions
4
+ const config: { hosting?: string, kv: typeof kv }
5
+ export default config
6
+ }
package/dist/virtual.d.ts CHANGED
@@ -1,6 +1,2 @@
1
- declare module "#vitehub/kv/config" {
2
- export const hosting: string | undefined
3
- export const kv: false | import("./index.js").ResolvedKVModuleOptions
4
- const config: { hosting?: string, kv: typeof kv }
5
- export default config
6
- }
1
+ /// <reference path="./virtual-module.d.ts" />
2
+ export { };
package/dist/vite.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { m as ResolvedKVModuleOptions, o as KVModuleOptions } from "./types-Dg4l318i.js";
1
+ import { c as KVModuleOptions, g as ResolvedKVModuleOptions } from "./types-CO0DRjJa.js";
2
2
  import { Plugin } from "vite";
3
3
 
4
4
  //#region src/config.d.ts
@@ -22,8 +22,24 @@ interface KVVitePluginAPI {
22
22
  }
23
23
  type KVVitePlugin = Plugin & {
24
24
  api: KVVitePluginAPI;
25
+ nitro: {
26
+ name: string;
27
+ setup: (nitro: {
28
+ options: NitroCloudflareKVTarget;
29
+ }) => void;
30
+ };
25
31
  };
26
32
  declare function hubKvOptionalPeerResolver(): Plugin;
33
+ interface NitroCloudflareKVTarget {
34
+ cloudflare?: {
35
+ wrangler?: {
36
+ kv_namespaces?: Array<{
37
+ binding: string;
38
+ id?: string;
39
+ }>;
40
+ };
41
+ };
42
+ }
27
43
  declare function hubKv(options?: KVModuleOptions): KVVitePlugin;
28
44
  declare module "vite" {
29
45
  interface UserConfig {