@vite-hub/kv 0.0.4 → 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 (37) hide show
  1. package/README.md +33 -8
  2. package/dist/cli-Cniq99iX.d.ts +85 -0
  3. package/dist/cli.d.ts +15 -0
  4. package/dist/cli.js +448 -0
  5. package/dist/cloudflare-env-C5rM7kUY.js +74 -0
  6. package/dist/{config-aM9Ae7tH.js → config-DR6_5ZwI.js} +36 -22
  7. package/dist/continuations-DPyH_vr1.js +63 -0
  8. package/dist/{dist-DDW1iC5f.js → create-storage-29gMzf41.js} +70 -75
  9. package/dist/cursor-history-dqYDlsaD.js +148 -0
  10. package/dist/deno-kv-CSYGvRx4.js +120 -0
  11. package/dist/{driver-BT9WefKi.d.ts → driver-D9fI27jl.d.ts} +33 -3
  12. package/dist/error-diagnostics-D_cQeZTi.js +82 -0
  13. package/dist/errors-Dc2oiW-Y.js +38 -0
  14. package/dist/errors.d.ts +12 -7
  15. package/dist/errors.js +2 -20
  16. package/dist/fs-lite-CbLKxLut.js +90 -0
  17. package/dist/index.d.ts +5 -4
  18. package/dist/index.js +92 -64
  19. package/dist/object-B1NW521B.js +7 -0
  20. package/dist/operations-ByuDE12r.js +1442 -0
  21. package/dist/operations-pn8_eGob.js +432 -0
  22. package/dist/operations-tNUdj3G4.d.ts +212 -0
  23. package/dist/operations.d.ts +68 -0
  24. package/dist/operations.js +455 -0
  25. package/dist/results-p7nPCnaJ.js +6 -0
  26. package/dist/runtime/cloudflare-kv.d.ts +3 -4
  27. package/dist/runtime/cloudflare-kv.js +84 -8
  28. package/dist/runtime/upstash-driver.d.ts +4 -6
  29. package/dist/runtime/upstash-driver.js +34 -44
  30. package/dist/{types-CO0DRjJa.d.ts → types-CMDvN0Wr.d.ts} +20 -17
  31. package/dist/utils2-Dsb9P4_2.js +28 -0
  32. package/dist/virtual.d.ts +1 -1
  33. package/dist/vite.d.ts +14 -10
  34. package/dist/vite.js +603 -224
  35. package/package.json +56 -16
  36. package/dist/deno-kv-cJx3jU10.js +0 -69
  37. package/dist/fs-lite-BxzdiJSi.js +0 -79
@@ -1,3 +1,5 @@
1
+ import { n as kvErrorDiagnostics } from "../error-diagnostics-D_cQeZTi.js";
2
+ import { t as createKVContinuations } from "../continuations-DPyH_vr1.js";
1
3
  import createDriver from "unstorage/drivers/upstash";
2
4
  //#region src/runtime/upstash-driver.ts
3
5
  const incrementScript = `
@@ -20,19 +22,19 @@ end
20
22
  return value
21
23
  `;
22
24
  function normalizeTTL(ttl) {
23
- if (!Number.isFinite(ttl) || ttl <= 0) throw new TypeError("Atomic KV increment requires a positive TTL in seconds.");
25
+ if (!Number.isFinite(ttl) || ttl <= 0) throw kvErrorDiagnostics.KV_INVALID_TTL();
24
26
  const seconds = Math.ceil(ttl);
25
- if (!Number.isSafeInteger(seconds)) throw new RangeError("Atomic KV increment TTL exceeds the supported integer range.");
27
+ if (!Number.isSafeInteger(seconds)) throw kvErrorDiagnostics.KV_INVALID_TTL();
26
28
  return seconds;
27
29
  }
28
30
  function decodeCursor(cursor) {
29
31
  if (!cursor) return { cursor: "0" };
30
32
  try {
31
33
  const value = JSON.parse(decodeURIComponent(cursor));
32
- if (typeof value.cursor !== "string" || value.cursor.length === 0) throw new Error();
34
+ if (typeof value.cursor !== "string" || value.cursor.length === 0) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "invalid" });
33
35
  return value;
34
36
  } catch {
35
- throw new TypeError("Invalid Upstash KV cursor.");
37
+ throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "invalid" });
36
38
  }
37
39
  }
38
40
  function encodeCursor(cursor) {
@@ -43,71 +45,59 @@ function escapeRedisGlob(value) {
43
45
  }
44
46
  function createUpstashKVDriver(options) {
45
47
  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);
48
+ const maximumContinuationBytes = 1048576;
49
+ const expired = () => kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "expired" });
50
+ const continuations = createKVContinuations({
51
+ expired,
52
+ maximumBytes: maximumContinuationBytes
53
+ });
54
+ const dispose = driver.dispose;
55
+ driver.dispose = async () => {
56
+ try {
57
+ await continuations.dispose();
58
+ } finally {
59
+ await dispose?.call(driver);
60
+ }
61
+ };
62
+ driver.getAndDeleteItem = async (key) => (await driver.getInstance()).getdel(key);
51
63
  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.");
64
+ const value = Number(await (await driver.getInstance()).eval(incrementScript, [key], [String(normalizeTTL(ttl))]));
65
+ if (!Number.isSafeInteger(value)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "The counter exceeds the JavaScript safe integer range." });
54
66
  return value;
55
67
  };
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
68
  function retainContinuation(keys, providerCursor) {
64
69
  const encoder = new TextEncoder();
65
70
  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,
71
+ if (bytes > maximumContinuationBytes) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Upstash KV scan overflow exceeds the continuation size limit." });
72
+ return continuations.retain({
77
73
  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;
74
+ keys
75
+ }, bytes);
87
76
  }
88
77
  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);
78
+ const retained = cursor ? continuations.take(cursor) : void 0;
79
+ if (cursor && !retained && /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(cursor)) throw expired();
92
80
  let providerCursor;
93
81
  let keys;
94
82
  if (retained) {
95
83
  providerCursor = retained.cursor;
96
84
  keys = retained.keys;
97
85
  } else {
98
- providerCursor = decodeCursor(cursor).cursor;
99
- const scanned = await driver.getInstance().scan(providerCursor, {
86
+ const state = decodeCursor(cursor);
87
+ providerCursor = state.cursor;
88
+ const scanned = await (await driver.getInstance()).scan(providerCursor, {
100
89
  count: limit,
101
90
  match: `${escapeRedisGlob(prefix)}*`
102
91
  });
103
92
  providerCursor = String(scanned[0]);
93
+ if (providerCursor === state.cursor && providerCursor !== "0") throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Upstash KV scan returned a repeated pagination cursor." });
104
94
  keys = [...new Set(scanned[1])];
105
95
  }
106
96
  const pageKeys = keys.slice(0, limit);
107
97
  const overflow = keys.slice(limit);
108
98
  if (overflow.length > 0) return {
109
99
  keys: pageKeys,
110
- cursor: retainContinuation(overflow, providerCursor)
100
+ cursor: await retainContinuation(overflow, providerCursor)
111
101
  };
112
102
  if (providerCursor === "0") return { keys: pageKeys };
113
103
  return {
@@ -1,11 +1,13 @@
1
- import { ViteHubError, ViteHubErrorDetails } from "@vite-hub/runtime";
2
-
1
+ import { Result } from "@vite-hub/runtime";
3
2
  //#region src/types.d.ts
4
3
  type KVDriver = "cloudflare-kv-binding" | "deno-kv" | "upstash" | "fs-lite";
5
4
  interface CloudflareKVStoreConfig {
6
5
  driver: "cloudflare-kv-binding";
7
6
  binding?: string;
7
+ /** Cloudflare KV namespace id. When omitted, the build reads the id recorded by `vitehub provision run`. */
8
8
  namespaceId?: string;
9
+ /** Cloudflare KV namespace title that `vitehub provision run` finds or creates when `namespaceId` is not set. */
10
+ namespaceName?: string;
9
11
  }
10
12
  interface UpstashKVStoreConfig {
11
13
  driver: "upstash";
@@ -42,11 +44,8 @@ interface ResolvedKVModuleOptions {
42
44
  stores?: Record<string, ResolvedKVStoreConfig>;
43
45
  }
44
46
  type KVOperation = "clear" | "del" | "get" | "getAndDelete" | "has" | "increment" | "keys" | "list" | "set";
45
- type KVErrorDetails = ViteHubErrorDetails & {
46
- operation: KVOperation;
47
- store: string;
48
- };
49
- type KVResult<TResult> = [error: null, value: TResult] | [error: ViteHubError<"KV_OPERATION_FAILED", KVErrorDetails>, value: undefined];
47
+ /** Codes that KV operations return in the `[error, data]` tuple. Config errors throw instead. */
48
+ type KVErrorCode = "KV_INVALID_CURSOR" | "KV_INVALID_LIMIT" | "KV_INVALID_TTL" | "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION";
50
49
  interface KVListOptions {
51
50
  /** Opaque continuation cursor returned by a previous page. */
52
51
  cursor?: string;
@@ -60,19 +59,23 @@ interface KVListPage {
60
59
  /** Omitted when enumeration is complete. */
61
60
  cursor?: string;
62
61
  }
62
+ /**
63
+ * Each method returns `[error, data]`. `error.code` is one of the codes in the method type.
64
+ * Config errors, for example an unknown store name, throw.
65
+ */
63
66
  interface KVStorage {
64
- clear(base?: string, options?: unknown): Promise<KVResult<void>>;
65
- del(key: string, options?: unknown): Promise<KVResult<void>>;
66
- get<T = unknown>(key: string, options?: unknown): Promise<KVResult<T | null>>;
67
+ clear(base?: string, options?: unknown): Promise<Result<void, "KV_OPERATION_FAILED">>;
68
+ del(key: string, options?: unknown): Promise<Result<void, "KV_OPERATION_FAILED">>;
69
+ get<T = unknown>(key: string, options?: unknown): Promise<Result<T | null, "KV_OPERATION_FAILED">>;
67
70
  /** Atomically returns and deletes a value when the configured store supports it. */
68
- getAndDelete<T = unknown>(key: string): Promise<KVResult<T | null>>;
69
- has(key: string, options?: unknown): Promise<KVResult<boolean>>;
71
+ getAndDelete<T = unknown>(key: string): Promise<Result<T | null, "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION">>;
72
+ has(key: string, options?: unknown): Promise<Result<boolean, "KV_OPERATION_FAILED">>;
70
73
  /** Atomically increments a counter. The TTL is applied only when the counter is created. */
71
- increment(key: string, ttl: number): Promise<KVResult<number>>;
72
- keys(base?: string, options?: unknown): Promise<KVResult<string[]>>;
73
- list(options: KVListOptions): Promise<KVResult<KVListPage>>;
74
- set<T = unknown>(key: string, value: T, options?: unknown): Promise<KVResult<void>>;
74
+ increment(key: string, ttl: number): Promise<Result<number, "KV_INVALID_TTL" | "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION">>;
75
+ keys(base?: string, options?: unknown): Promise<Result<string[], "KV_OPERATION_FAILED">>;
76
+ list(options: KVListOptions): Promise<Result<KVListPage, "KV_INVALID_CURSOR" | "KV_INVALID_LIMIT" | "KV_OPERATION_FAILED">>;
77
+ set<T = unknown>(key: string, value: T, options?: unknown): Promise<Result<void, "KV_OPERATION_FAILED">>;
75
78
  store(name: KVStoreName): KVStorage;
76
79
  }
77
80
  //#endregion
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 };
81
+ export { ResolvedUpstashKVStoreConfig as _, KVErrorCode as a, KVModuleOptions as c, KVStoreConfig as d, ResolvedCloudflareKVStoreConfig as f, ResolvedKVStoreConfig as g, ResolvedKVModuleOptions as h, KVDriver as i, KVOperation as l, ResolvedFsLiteKVStoreConfig as m, DenoKVStoreConfig as n, KVListOptions as o, ResolvedDenoKVStoreConfig as p, FsLiteKVStoreConfig as r, KVListPage as s, CloudflareKVStoreConfig as t, KVStorage as u, UpstashKVStoreConfig as v };
@@ -0,0 +1,28 @@
1
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.10/node_modules/unstorage/dist/_chunks/utils2.mjs
2
+ function normalizeKey(key) {
3
+ if (!key) return "";
4
+ return key.split("?")[0]?.replace(/[/\\]/g, ":").replace(/:+/g, ":").replace(/^:|:$/g, "") || "";
5
+ }
6
+ function joinKeys(...keys) {
7
+ return normalizeKey(keys.join(":"));
8
+ }
9
+ function normalizeBaseKey(base) {
10
+ base = normalizeKey(base);
11
+ return base ? base + ":" : "";
12
+ }
13
+ function filterKeyByDepth(key, depth) {
14
+ if (depth === void 0) return true;
15
+ let substrCount = 0;
16
+ let index = key.indexOf(":");
17
+ while (index > -1) {
18
+ substrCount++;
19
+ index = key.indexOf(":", index + 1);
20
+ }
21
+ return substrCount <= depth;
22
+ }
23
+ function filterKeyByBase(key, base) {
24
+ if (base) return key.startsWith(base) && key[key.length - 1] !== "$";
25
+ return key[key.length - 1] !== "$";
26
+ }
27
+ //#endregion
28
+ export { normalizeKey as a, normalizeBaseKey as i, filterKeyByDepth as n, joinKeys as r, filterKeyByBase as t };
package/dist/virtual.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  /// <reference path="./virtual-module.d.ts" />
2
- export { };
2
+ export {}
package/dist/vite.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { c as KVModuleOptions, g as ResolvedKVModuleOptions } from "./types-CO0DRjJa.js";
1
+ import { c as KVModuleOptions, h as ResolvedKVModuleOptions } from "./types-CMDvN0Wr.js";
2
+ import { r as ViteHubCliPluginMetadata } from "./cli-Cniq99iX.js";
3
+ import { n as OperationContributionEntry } from "./operations-tNUdj3G4.js";
2
4
  import { Plugin } from "vite";
3
-
4
5
  //#region src/config.d.ts
5
6
  interface KVResolutionInput {
6
7
  env?: Record<string, string | undefined>;
@@ -8,19 +9,19 @@ interface KVResolutionInput {
8
9
  }
9
10
  //#endregion
10
11
  //#region src/vite-config.d.ts
11
- declare const KV_VITE_PLUGIN_NAME = "@vite-hub/kv/vite";
12
- declare const KV_VIRTUAL_CONFIG_ID = "#vitehub/kv/config";
12
+ export declare const KV_VITE_PLUGIN_NAME = "@vite-hub/kv/vite";
13
+ export declare const KV_VIRTUAL_CONFIG_ID = "#vitehub/kv/config";
13
14
  interface KVViteRuntimeConfig {
14
15
  hosting?: string;
15
16
  kv: false | ResolvedKVModuleOptions;
16
17
  }
17
- declare function resolveKVViteConfig(kv: KVModuleOptions | undefined, input?: KVResolutionInput): KVViteRuntimeConfig;
18
+ export declare function resolveKVViteConfig(kv: KVModuleOptions | undefined, input?: KVResolutionInput): KVViteRuntimeConfig;
18
19
  //#endregion
19
20
  //#region src/vite.d.ts
20
- interface KVVitePluginAPI {
21
+ export interface KVVitePluginAPI {
21
22
  getConfig: () => KVViteRuntimeConfig;
22
23
  }
23
- type KVVitePlugin = Plugin & {
24
+ export type KVVitePlugin = Plugin & {
24
25
  api: KVVitePluginAPI;
25
26
  nitro: {
26
27
  name: string;
@@ -28,8 +29,11 @@ type KVVitePlugin = Plugin & {
28
29
  options: NitroCloudflareKVTarget;
29
30
  }) => void;
30
31
  };
32
+ vitehub: ViteHubCliPluginMetadata & {
33
+ operations: readonly OperationContributionEntry[];
34
+ };
31
35
  };
32
- declare function hubKvOptionalPeerResolver(): Plugin;
36
+ export declare function hubKvOptionalPeerResolver(): Plugin;
33
37
  interface NitroCloudflareKVTarget {
34
38
  cloudflare?: {
35
39
  wrangler?: {
@@ -40,11 +44,11 @@ interface NitroCloudflareKVTarget {
40
44
  };
41
45
  };
42
46
  }
43
- declare function hubKv(options?: KVModuleOptions): KVVitePlugin;
47
+ export declare function hubKv(options?: KVModuleOptions): KVVitePlugin;
44
48
  declare module "vite" {
45
49
  interface UserConfig {
46
50
  kv?: KVModuleOptions;
47
51
  }
48
52
  }
49
53
  //#endregion
50
- export { KVVitePlugin, KVVitePluginAPI, type KVViteRuntimeConfig, KV_VIRTUAL_CONFIG_ID, KV_VITE_PLUGIN_NAME, hubKv, hubKvOptionalPeerResolver, resolveKVViteConfig };
54
+ export type { KVViteRuntimeConfig };