@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
@@ -0,0 +1,74 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ //#region ../internal/src/runtime/cloudflare-env.ts
3
+ let activeEnv;
4
+ const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
5
+ const runtimeGlobal = globalThis;
6
+ const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
7
+ function getActiveCloudflareEnv() {
8
+ const scoped = activeEnvStorage.getStore();
9
+ if (scoped) return scoped.env;
10
+ const host = globalThis;
11
+ return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
12
+ }
13
+ function getActiveCloudflareBinding(name) {
14
+ const env = getActiveCloudflareEnv();
15
+ return env && Object.hasOwn(env, name) ? env[name] : void 0;
16
+ }
17
+ function ownValue(value, key) {
18
+ if (value === null || typeof value !== "object" && typeof value !== "function" || !Object.hasOwn(value, key)) return void 0;
19
+ return Reflect.get(value, key);
20
+ }
21
+ function ownObject(value) {
22
+ return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
23
+ }
24
+ /** The objects where H3 1, H3 2, and Nitro hosts put Cloudflare `env` and `context`, in lookup order. */
25
+ function cloudflareOwners(target) {
26
+ const context = ownObject(ownValue(target, "context"));
27
+ const platform = ownObject(ownValue(context, "_platform"));
28
+ const req = ownObject(ownValue(target, "req"));
29
+ const nodeReq = ownObject(ownValue(ownObject(ownValue(target, "node")), "req"));
30
+ return [
31
+ ownObject(ownValue(context, "cloudflare")),
32
+ ownObject(ownValue(platform, "cloudflare")),
33
+ ownObject(ownValue(ownObject(ownValue(req, "runtime")), "cloudflare")),
34
+ ownObject(ownValue(ownObject(ownValue(nodeReq, "runtime")), "cloudflare"))
35
+ ];
36
+ }
37
+ function getCloudflareEnv(event, options = {}) {
38
+ const target = ownObject(event);
39
+ for (const candidate of [ownValue(target, "env"), ...cloudflareOwners(target).map((owner) => ownValue(owner, "env"))]) if (candidate) return candidate;
40
+ return options.fallback === false ? void 0 : getActiveCloudflareEnv();
41
+ }
42
+ function resolveWaitUntil(event, options = {}) {
43
+ const target = ownObject(event);
44
+ const context = ownObject(ownValue(target, "context"));
45
+ const cloudflare = ownObject(ownValue(context, "cloudflare"));
46
+ const cloudflareContext = ownObject(ownValue(cloudflare, "context"));
47
+ const platformCloudflare = ownObject(ownValue(ownObject(ownValue(context, "_platform")), "cloudflare"));
48
+ const platformCloudflareContext = ownObject(ownValue(platformCloudflare, "context"));
49
+ const req = ownObject(ownValue(target, "req"));
50
+ const reqCloudflare = ownObject(ownValue(ownObject(ownValue(req, "runtime")), "cloudflare"));
51
+ const reqCloudflareContext = ownObject(ownValue(reqCloudflare, "context"));
52
+ const nodeReq = ownObject(ownValue(ownObject(ownValue(target, "node")), "req"));
53
+ const nodeCloudflare = ownObject(ownValue(ownObject(ownValue(nodeReq, "runtime")), "cloudflare"));
54
+ const hosts = [
55
+ context,
56
+ cloudflare,
57
+ cloudflareContext,
58
+ platformCloudflare,
59
+ platformCloudflareContext,
60
+ req,
61
+ reqCloudflare,
62
+ reqCloudflareContext,
63
+ nodeReq,
64
+ nodeCloudflare,
65
+ ownObject(ownValue(nodeCloudflare, "context"))
66
+ ];
67
+ const owners = options.preferHost ? [...hosts, target] : [target, ...hosts];
68
+ for (const owner of owners) {
69
+ const waitUntil = ownValue(owner, "waitUntil");
70
+ if (typeof waitUntil === "function") return waitUntil.bind(owner);
71
+ }
72
+ }
73
+ //#endregion
74
+ export { resolveWaitUntil as i, getActiveCloudflareEnv as n, getCloudflareEnv as r, getActiveCloudflareBinding as t };
@@ -1,3 +1,5 @@
1
+ import { t as isPlainObject } from "./object-B1NW521B.js";
2
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-D_cQeZTi.js";
1
3
  import { defu } from "defu";
2
4
  //#region ../internal/src/env.ts
3
5
  function trimmed(value) {
@@ -11,28 +13,36 @@ function readEnv(env, ...names) {
11
13
  }
12
14
  //#endregion
13
15
  //#region ../internal/src/hosting.ts
16
+ /**
17
+ * Returns the Nitro preset name that this build targets, as the developer wrote it.
18
+ * The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOSTING`.
19
+ * Empty values are skipped.
20
+ */
21
+ function resolveHostPreset(input = {}) {
22
+ const env = input.env ?? (typeof process === "undefined" ? {} : process.env);
23
+ const nitroPreset = input.nitro && typeof input.nitro === "object" ? Reflect.get(input.nitro, "preset") : void 0;
24
+ for (const value of [
25
+ nitroPreset,
26
+ input.hosting,
27
+ env.NITRO_PRESET,
28
+ env.SERVER_PRESET,
29
+ env.VITEHUB_HOSTING
30
+ ]) if (typeof value === "string" && value.trim()) return value.trim();
31
+ }
14
32
  function normalizeHosting(hosting) {
15
33
  const normalized = hosting?.trim().toLowerCase().replaceAll("_", "-") || "";
16
34
  if (normalized === "cloudflare") return "cloudflare-module";
17
35
  return normalized;
18
36
  }
19
37
  //#endregion
20
- //#region ../internal/src/object.ts
21
- function isPlainObject(value) {
22
- if (value === null || Object(value) !== value || Array.isArray(value)) return false;
23
- try {
24
- Function.prototype.toString.call(value);
25
- return false;
26
- } catch {
27
- return true;
28
- }
29
- }
30
- //#endregion
31
38
  //#region src/integrations/upstash.ts
32
39
  const maskedUpstashRuntimeValue = "********";
40
+ /** Vercel names first, then the names that the Upstash console and NuxtHub use. */
41
+ const upstashUrlEnvNames = ["KV_REST_API_URL", "UPSTASH_REDIS_REST_URL"];
42
+ const upstashTokenEnvNames = ["KV_REST_API_TOKEN", "UPSTASH_REDIS_REST_TOKEN"];
33
43
  function hasUpstashEnv(env) {
34
- const url = readEnv(env, "KV_REST_API_URL");
35
- const token = readEnv(env, "KV_REST_API_TOKEN");
44
+ const url = readEnv(env, ...upstashUrlEnvNames);
45
+ const token = readEnv(env, ...upstashTokenEnvNames);
36
46
  return Boolean(url && token);
37
47
  }
38
48
  function resolveUpstashStore(config = {}) {
@@ -53,7 +63,8 @@ function resolveFsLiteStore(config = {}) {
53
63
  function resolveCloudflareStore(config = {}, env = process.env) {
54
64
  return defu({
55
65
  binding: trimmed(config.binding),
56
- namespaceId: trimmed(config.namespaceId) ?? readEnv(env, "KV_NAMESPACE_ID")
66
+ namespaceId: trimmed(config.namespaceId) ?? readEnv(env, "KV_NAMESPACE_ID"),
67
+ namespaceName: trimmed(config.namespaceName)
57
68
  }, {
58
69
  driver: "cloudflare-kv-binding",
59
70
  binding: "KV"
@@ -72,7 +83,7 @@ function resolveExplicitStore(store, env) {
72
83
  case "deno-kv": return resolveDenoStore(store);
73
84
  case "upstash": return resolveUpstashStore(store);
74
85
  case "fs-lite": return resolveFsLiteStore(store);
75
- default: throw new TypeError(`Unknown \`kv.driver\`: ${JSON.stringify(store.driver)}. Expected "cloudflare-kv-binding", "deno-kv", "upstash", or "fs-lite".`);
86
+ default: throw kvErrorDiagnostics.KV_INVALID_DRIVER({ driver: JSON.stringify(store.driver) });
76
87
  }
77
88
  }
78
89
  function createResolvedConfig(store, stores) {
@@ -84,19 +95,22 @@ function createResolvedConfig(store, stores) {
84
95
  }
85
96
  } : { store };
86
97
  }
87
- function hasStoresConfig(options) {
88
- return !!options && "stores" in options && isPlainObject(options.stores);
98
+ function hasStoresConfig(options, stores) {
99
+ return !!options && Object.hasOwn(options, "stores") && isPlainObject(stores);
89
100
  }
90
101
  function normalizeKVOptions(options, input = {}) {
91
102
  if (options === false) return;
92
- if (typeof options !== "undefined" && !isPlainObject(options)) throw new TypeError("`kv` must be a plain object.");
103
+ if (typeof options !== "undefined" && !isPlainObject(options)) throw kvErrorDiagnostics.KV_INVALID_CONFIG({ path: "kv" });
93
104
  const env = input.env || process.env;
94
105
  const hosting = normalizeHosting(input.hosting);
95
106
  const explicit = options;
96
- if (hasStoresConfig(options)) {
97
- const resolvedStores = Object.fromEntries(Object.entries(options.stores).map(([name, store]) => [name, resolveExplicitStore(store, env)]));
107
+ const hasOwnStores = options !== void 0 && Object.hasOwn(options, "stores");
108
+ const stores = hasOwnStores ? Reflect.get(options, "stores", options) : void 0;
109
+ if (hasOwnStores && !isPlainObject(stores)) throw kvErrorDiagnostics.KV_INVALID_CONFIG({ path: "kv.stores" });
110
+ if (hasStoresConfig(options, stores)) {
111
+ const resolvedStores = Object.fromEntries(Object.entries(stores).map(([name, store]) => [name, resolveExplicitStore(store, env)]));
98
112
  const defaultStore = resolvedStores.default;
99
- if (!defaultStore) throw new TypeError("`kv.stores.default` is required when using named KV stores.");
113
+ if (!defaultStore) throw kvErrorDiagnostics.KV_MISSING_DEFAULT_STORE();
100
114
  return createResolvedConfig(defaultStore, resolvedStores);
101
115
  }
102
116
  if (explicit?.driver) return createResolvedConfig(resolveExplicitStore(explicit, env));
@@ -107,4 +121,4 @@ function normalizeKVOptions(options, input = {}) {
107
121
  return createResolvedConfig(resolveFsLiteStore());
108
122
  }
109
123
  //#endregion
110
- export { trimmed as i, isPlainObject as n, readEnv as r, normalizeKVOptions as t };
124
+ export { readEnv as a, resolveHostPreset as i, upstashTokenEnvNames as n, upstashUrlEnvNames as r, normalizeKVOptions as t };
@@ -0,0 +1,63 @@
1
+ //#region src/runtime/continuations.ts
2
+ /** Owns process-local cursor retention. Taking a cursor transfers its resource to the caller. */
3
+ function createKVContinuations(options) {
4
+ const entries = /* @__PURE__ */ new Map();
5
+ const releases = /* @__PURE__ */ new Set();
6
+ const failures = [];
7
+ let bytes = 0;
8
+ let disposed = false;
9
+ function take(cursor) {
10
+ const entry = entries.get(cursor);
11
+ if (!entry) return void 0;
12
+ clearTimeout(entry.timeout);
13
+ entries.delete(cursor);
14
+ bytes -= entry.bytes;
15
+ return entry.value;
16
+ }
17
+ function release(value, surfaceFailure = false) {
18
+ const pending = Promise.resolve().then(() => options.release?.(value)).then(() => void 0).catch((error) => {
19
+ if (failures.length === 0) failures.push(error);
20
+ if (surfaceFailure) throw error;
21
+ }).finally(() => {
22
+ releases.delete(pending);
23
+ });
24
+ releases.add(pending);
25
+ return pending;
26
+ }
27
+ function evict(cursor) {
28
+ const value = take(cursor);
29
+ if (value !== void 0) release(value);
30
+ }
31
+ return {
32
+ take,
33
+ async retain(value, size = 0) {
34
+ if (disposed) {
35
+ await release(value, true);
36
+ throw options.expired();
37
+ }
38
+ while (entries.size >= 32 || bytes + size > (options.maximumBytes ?? Number.POSITIVE_INFINITY)) {
39
+ const oldest = entries.keys().next().value;
40
+ if (!oldest) break;
41
+ evict(oldest);
42
+ }
43
+ const cursor = globalThis.crypto.randomUUID();
44
+ const timeout = setTimeout(() => evict(cursor), 9e5);
45
+ timeout.unref?.();
46
+ entries.set(cursor, {
47
+ value,
48
+ bytes: size,
49
+ timeout
50
+ });
51
+ bytes += size;
52
+ return cursor;
53
+ },
54
+ async dispose() {
55
+ disposed = true;
56
+ for (const cursor of entries.keys()) evict(cursor);
57
+ await Promise.all(releases);
58
+ if (failures.length > 0) throw new AggregateError(failures.splice(0), "Failed to release KV listing continuations.");
59
+ }
60
+ };
61
+ }
62
+ //#endregion
63
+ export { createKVContinuations as t };
@@ -1,4 +1,5 @@
1
- //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.7_@azure+identity@4.13.1_@azure+storage-blob@12.31.0_@netlify+blo_8194820fdb6706e28a1ff20070ef4217/node_modules/unstorage/dist/_chunks/libs/destr.mjs
1
+ import { a as normalizeKey, i as normalizeBaseKey, n as filterKeyByDepth, r as joinKeys, t as filterKeyByBase } from "./utils2-Dsb9P4_2.js";
2
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.10/node_modules/unstorage/dist/_chunks/libs/destr.mjs
2
3
  const suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/;
3
4
  const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
4
5
  const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
@@ -41,79 +42,7 @@ function destr(value, options = {}) {
41
42
  }
42
43
  }
43
44
  //#endregion
44
- //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.7_@azure+identity@4.13.1_@azure+storage-blob@12.31.0_@netlify+blo_8194820fdb6706e28a1ff20070ef4217/node_modules/unstorage/dist/_chunks/_utils.mjs
45
- function wrapToPromise(value) {
46
- if (!value || typeof value.then !== "function") return Promise.resolve(value);
47
- return value;
48
- }
49
- function asyncCall(function_, ...arguments_) {
50
- try {
51
- return wrapToPromise(function_(...arguments_));
52
- } catch (error) {
53
- return Promise.reject(error);
54
- }
55
- }
56
- function isPrimitive(value) {
57
- const type = typeof value;
58
- return value === null || type !== "object" && type !== "function";
59
- }
60
- function isPureObject(value) {
61
- const proto = Object.getPrototypeOf(value);
62
- return !proto || proto.isPrototypeOf(Object);
63
- }
64
- function stringify(value) {
65
- if (isPrimitive(value)) return String(value);
66
- if (isPureObject(value) || Array.isArray(value)) return JSON.stringify(value);
67
- if (typeof value.toJSON === "function") return stringify(value.toJSON());
68
- throw new Error("[unstorage] Cannot stringify value!");
69
- }
70
- const BASE64_PREFIX = "base64:";
71
- function serializeRaw(value) {
72
- if (typeof value === "string") return value;
73
- return BASE64_PREFIX + base64Encode(value);
74
- }
75
- function deserializeRaw(value) {
76
- if (typeof value !== "string") return value;
77
- if (!value.startsWith("base64:")) return value;
78
- return base64Decode(value.slice(7));
79
- }
80
- function base64Decode(input) {
81
- if (globalThis.Buffer) return Buffer.from(input, "base64");
82
- return Uint8Array.from(globalThis.atob(input), (c) => c.codePointAt(0));
83
- }
84
- function base64Encode(input) {
85
- if (globalThis.Buffer) return Buffer.from(input).toString("base64");
86
- return globalThis.btoa(String.fromCodePoint(...input));
87
- }
88
- //#endregion
89
- //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.7_@azure+identity@4.13.1_@azure+storage-blob@12.31.0_@netlify+blo_8194820fdb6706e28a1ff20070ef4217/node_modules/unstorage/dist/_chunks/utils.mjs
90
- function normalizeKey(key) {
91
- if (!key) return "";
92
- return key.split("?")[0]?.replace(/[/\\]/g, ":").replace(/:+/g, ":").replace(/^:|:$/g, "") || "";
93
- }
94
- function joinKeys(...keys) {
95
- return normalizeKey(keys.join(":"));
96
- }
97
- function normalizeBaseKey(base) {
98
- base = normalizeKey(base);
99
- return base ? base + ":" : "";
100
- }
101
- function filterKeyByDepth(key, depth) {
102
- if (depth === void 0) return true;
103
- let substrCount = 0;
104
- let index = key.indexOf(":");
105
- while (index > -1) {
106
- substrCount++;
107
- index = key.indexOf(":", index + 1);
108
- }
109
- return substrCount <= depth;
110
- }
111
- function filterKeyByBase(key, base) {
112
- if (base) return key.startsWith(base) && key[key.length - 1] !== "$";
113
- return key[key.length - 1] !== "$";
114
- }
115
- //#endregion
116
- //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.7_@azure+identity@4.13.1_@azure+storage-blob@12.31.0_@netlify+blo_8194820fdb6706e28a1ff20070ef4217/node_modules/unstorage/dist/index.mjs
45
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.10/node_modules/unstorage/dist/drivers/memory.mjs
117
46
  const DRIVER_NAME = "memory";
118
47
  const driver = () => {
119
48
  const data = /* @__PURE__ */ new Map();
@@ -176,6 +105,53 @@ function _scheduleExpiry(data, timers, key, ttl) {
176
105
  if (timer && typeof timer === "object" && "unref" in timer) timer.unref();
177
106
  timers.set(key, timer);
178
107
  }
108
+ //#endregion
109
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.10/node_modules/unstorage/dist/_chunks/_utils.mjs
110
+ function wrapToPromise(value) {
111
+ if (!value || typeof value.then !== "function") return Promise.resolve(value);
112
+ return value;
113
+ }
114
+ function asyncCall(function_, ...arguments_) {
115
+ try {
116
+ return wrapToPromise(function_(...arguments_));
117
+ } catch (error) {
118
+ return Promise.reject(error);
119
+ }
120
+ }
121
+ function isPrimitive(value) {
122
+ const type = typeof value;
123
+ return value === null || type !== "object" && type !== "function";
124
+ }
125
+ function isPureObject(value) {
126
+ const proto = Object.getPrototypeOf(value);
127
+ return !proto || proto.isPrototypeOf(Object);
128
+ }
129
+ function stringify(value) {
130
+ if (isPrimitive(value)) return String(value);
131
+ if (isPureObject(value) || Array.isArray(value)) return JSON.stringify(value);
132
+ if (typeof value.toJSON === "function") return stringify(value.toJSON());
133
+ throw new Error("[unstorage] Cannot stringify value!");
134
+ }
135
+ const BASE64_PREFIX = "base64:";
136
+ function serializeRaw(value) {
137
+ if (typeof value === "string") return value;
138
+ return BASE64_PREFIX + base64Encode(value);
139
+ }
140
+ function deserializeRaw(value) {
141
+ if (typeof value !== "string") return value;
142
+ if (!value.startsWith("base64:")) return value;
143
+ return base64Decode(value.slice(7));
144
+ }
145
+ function base64Decode(input) {
146
+ if (typeof Buffer !== "undefined") return Buffer.from(input, "base64");
147
+ return Uint8Array.from(globalThis.atob(input), (c) => c.codePointAt(0));
148
+ }
149
+ function base64Encode(input) {
150
+ if (typeof Buffer !== "undefined") return Buffer.from(input).toString("base64");
151
+ return globalThis.btoa(String.fromCodePoint(...input));
152
+ }
153
+ //#endregion
154
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.10/node_modules/unstorage/dist/index.mjs
179
155
  function createStorage(options = {}) {
180
156
  const context = {
181
157
  mounts: { "": options.driver || driver() },
@@ -444,4 +420,23 @@ async function dispose(driver) {
444
420
  if (typeof driver.dispose === "function") await asyncCall(driver.dispose);
445
421
  }
446
422
  //#endregion
447
- export { normalizeKey as n, createStorage as t };
423
+ //#region src/runtime/list-prefix.ts
424
+ function normalizeKVListPrefix(prefix = "") {
425
+ const normalized = normalizeKey(prefix);
426
+ const path = prefix.split("?")[0] ?? "";
427
+ return normalized && /[:/\\]$/.test(path) ? `${normalized}:` : normalized;
428
+ }
429
+ //#endregion
430
+ //#region src/runtime/create-storage.ts
431
+ /** Gives single-store KV prefixes the same meaning for clear() and getKeys(). */
432
+ function createKVStorage(driver) {
433
+ const storage = createStorage({ driver });
434
+ const clear = storage.clear;
435
+ storage.clear = async (base, options) => {
436
+ if (!normalizeKey(base)) return clear(base, options);
437
+ for (const key of await storage.getKeys(base, options)) await storage.removeItem(key, options);
438
+ };
439
+ return storage;
440
+ }
441
+ //#endregion
442
+ export { normalizeKVListPrefix as n, createKVStorage as t };
@@ -0,0 +1,148 @@
1
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-D_cQeZTi.js";
2
+ //#region src/runtime/cursor-history.ts
3
+ const MAX_CURSOR_HISTORIES = 1024;
4
+ const MAX_CURSORS_PER_HISTORY = 1024;
5
+ const MAX_CURSOR_LENGTH = 8192;
6
+ const MAX_CONTINUATION_LENGTH = 131072;
7
+ function continuationTag(value) {
8
+ const hashes = [
9
+ 2166136261,
10
+ 2246822519,
11
+ 3266489917,
12
+ 668265263
13
+ ];
14
+ for (let index = 0; index < value.length; index++) {
15
+ const code = value.charCodeAt(index);
16
+ for (let hashIndex = 0; hashIndex < hashes.length; hashIndex++) hashes[hashIndex] = Math.imul(hashes[hashIndex] ^ code, 16777619 + hashIndex * 2);
17
+ }
18
+ return hashes.map((hash) => (hash >>> 0).toString(16).padStart(8, "0")).join("");
19
+ }
20
+ function encodeContinuation(providerCursor, history) {
21
+ const nonce = globalThis.crypto.randomUUID();
22
+ const historyTag = continuationTag([...history].join("\0"));
23
+ const payload = encodeURIComponent(JSON.stringify({
24
+ format: "vitehub-continuation",
25
+ providerCursor,
26
+ historyCount: history.size,
27
+ historyTag
28
+ }));
29
+ const token = `vhc1:${nonce}:${payload}:${continuationTag(payload)}`;
30
+ if (token.length > MAX_CONTINUATION_LENGTH) throw new Error("ViteHub continuation cursor exceeds the maximum size.");
31
+ return token;
32
+ }
33
+ const continuations = /* @__PURE__ */ new Map();
34
+ const continuationOwners = /* @__PURE__ */ new Map();
35
+ const consumedContinuations = /* @__PURE__ */ new Map();
36
+ const consumedOwners = /* @__PURE__ */ new Map();
37
+ const invalidatedContinuations = /* @__PURE__ */ new Set();
38
+ function rememberInvalidated(cursor) {
39
+ invalidatedContinuations.add(cursor);
40
+ while (invalidatedContinuations.size > MAX_CURSOR_HISTORIES) {
41
+ const oldest = invalidatedContinuations.values().next().value;
42
+ if (oldest === void 0) break;
43
+ invalidatedContinuations.delete(oldest);
44
+ }
45
+ }
46
+ /** Keeps continuation history tied to an opaque, traversal-owned token. */
47
+ function createCursorHistory(namespace = "default") {
48
+ const ownedContinuations = /* @__PURE__ */ new Set();
49
+ const ownedConsumedContinuations = /* @__PURE__ */ new Set();
50
+ let epoch = 0;
51
+ function take(cursor, requestedNamespace = namespace) {
52
+ const continuation = continuations.get(cursor);
53
+ if (continuation && continuation.namespace !== requestedNamespace) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "foreign" });
54
+ if (!continuation) {
55
+ if (consumedContinuations.has(cursor)) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "in-use" });
56
+ if (invalidatedContinuations.has(cursor)) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "expired" });
57
+ if (cursor.length > MAX_CURSOR_LENGTH) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "invalid" });
58
+ return {
59
+ providerCursor: cursor,
60
+ history: /* @__PURE__ */ new Set([cursor]),
61
+ epoch,
62
+ namespace
63
+ };
64
+ }
65
+ continuations.delete(cursor);
66
+ continuationOwners.get(cursor)?.delete(cursor);
67
+ continuationOwners.delete(cursor);
68
+ continuation.epoch = epoch;
69
+ consumedContinuations.set(cursor, continuation);
70
+ ownedConsumedContinuations.add(cursor);
71
+ consumedOwners.set(cursor, ownedConsumedContinuations);
72
+ while (consumedContinuations.size > MAX_CURSOR_HISTORIES) {
73
+ const oldest = consumedContinuations.keys().next().value;
74
+ if (oldest === void 0) break;
75
+ consumedContinuations.delete(oldest);
76
+ consumedOwners.get(oldest)?.delete(oldest);
77
+ consumedOwners.delete(oldest);
78
+ rememberInvalidated(oldest);
79
+ }
80
+ return continuation;
81
+ }
82
+ function store(providerCursor, history, requestedNamespace = namespace) {
83
+ const token = encodeContinuation(providerCursor, history);
84
+ continuations.set(token, {
85
+ providerCursor,
86
+ history,
87
+ epoch,
88
+ namespace: requestedNamespace
89
+ });
90
+ ownedContinuations.add(token);
91
+ continuationOwners.set(token, ownedContinuations);
92
+ while (continuations.size > MAX_CURSOR_HISTORIES) {
93
+ const oldest = continuations.keys().next().value;
94
+ if (oldest === void 0) break;
95
+ continuations.delete(oldest);
96
+ continuationOwners.get(oldest)?.delete(oldest);
97
+ continuationOwners.delete(oldest);
98
+ rememberInvalidated(oldest);
99
+ }
100
+ return token;
101
+ }
102
+ function restore(cursor, continuation) {
103
+ if (continuation.epoch !== epoch || consumedContinuations.get(cursor) !== continuation) return;
104
+ continuations.set(cursor, continuation);
105
+ ownedContinuations.add(cursor);
106
+ continuationOwners.set(cursor, ownedContinuations);
107
+ consumedContinuations.delete(cursor);
108
+ consumedOwners.delete(cursor);
109
+ ownedConsumedContinuations.delete(cursor);
110
+ }
111
+ function complete(cursor) {
112
+ if (cursor && ownedConsumedContinuations.has(cursor)) {
113
+ consumedContinuations.delete(cursor);
114
+ consumedOwners.delete(cursor);
115
+ ownedConsumedContinuations.delete(cursor);
116
+ }
117
+ }
118
+ function clear() {
119
+ epoch++;
120
+ for (const token of ownedContinuations) {
121
+ continuations.delete(token);
122
+ continuationOwners.delete(token);
123
+ rememberInvalidated(token);
124
+ }
125
+ ownedContinuations.clear();
126
+ for (const token of ownedConsumedContinuations) {
127
+ consumedContinuations.delete(token);
128
+ consumedOwners.delete(token);
129
+ rememberInvalidated(token);
130
+ }
131
+ ownedConsumedContinuations.clear();
132
+ }
133
+ return {
134
+ take,
135
+ store,
136
+ restore,
137
+ complete,
138
+ clear
139
+ };
140
+ }
141
+ /** Records a provider cursor, refusing to weaken repeat detection at the bound. */
142
+ function recordCursor(history, cursor) {
143
+ if (cursor.length > MAX_CURSOR_LENGTH || history.size >= MAX_CURSORS_PER_HISTORY) return false;
144
+ history.add(cursor);
145
+ return true;
146
+ }
147
+ //#endregion
148
+ export { recordCursor as n, createCursorHistory as t };
@@ -0,0 +1,120 @@
1
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-D_cQeZTi.js";
2
+ import { n as recordCursor, t as createCursorHistory } from "./cursor-history-dqYDlsaD.js";
3
+ //#region src/runtime/deno-kv.ts
4
+ function getDenoRuntime() {
5
+ return globalThis.Deno;
6
+ }
7
+ function toDenoKey(key) {
8
+ return [key];
9
+ }
10
+ function fromDenoKey(key) {
11
+ return key.length === 1 && typeof key[0] === "string" ? key[0] : void 0;
12
+ }
13
+ function toDenoExpireIn(ttl) {
14
+ if (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl <= 0) return void 0;
15
+ const expireIn = Math.max(1, Math.ceil(ttl * 1e3));
16
+ return Number.isSafeInteger(expireIn) ? { expireIn } : void 0;
17
+ }
18
+ function createDenoKVDriver(options = { driver: "deno-kv" }) {
19
+ let kvPromise;
20
+ let disposed = false;
21
+ let disposal;
22
+ const cursorNamespace = `deno-kv:${options.path ?? "default"}`;
23
+ const cursorHistories = createCursorHistory(cursorNamespace);
24
+ function open() {
25
+ if (disposed) return Promise.reject(/* @__PURE__ */ new Error("KV storage has been disposed."));
26
+ if (kvPromise) return kvPromise;
27
+ const pending = (async () => {
28
+ const openKv = getDenoRuntime()?.openKv;
29
+ if (!openKv) throw kvErrorDiagnostics.KV_DENO_KV_UNAVAILABLE();
30
+ return openKv(options.path);
31
+ })();
32
+ kvPromise = pending;
33
+ pending.catch(() => {
34
+ if (kvPromise === pending) kvPromise = void 0;
35
+ });
36
+ return pending;
37
+ }
38
+ async function matchingKeys(base = "") {
39
+ const kv = await open();
40
+ const keys = [];
41
+ for await (const entry of kv.list({ prefix: [] })) if (fromDenoKey(entry.key)?.startsWith(base)) keys.push(entry.key);
42
+ return keys;
43
+ }
44
+ return {
45
+ name: "deno-kv",
46
+ options,
47
+ async clear(base = "") {
48
+ const kv = await open();
49
+ for (const key of await matchingKeys(base)) await kv.delete(key);
50
+ },
51
+ dispose() {
52
+ return disposal ??= (async () => {
53
+ disposed = true;
54
+ cursorHistories.clear();
55
+ try {
56
+ if (kvPromise) {
57
+ (await kvPromise).close?.();
58
+ kvPromise = void 0;
59
+ }
60
+ } finally {
61
+ cursorHistories.clear();
62
+ }
63
+ })();
64
+ },
65
+ async getItem(key) {
66
+ const entry = await (await open()).get(toDenoKey(key));
67
+ return entry.versionstamp === null ? null : entry.value;
68
+ },
69
+ async getKeys(base = "") {
70
+ return (await matchingKeys(base)).flatMap((key) => fromDenoKey(key) ?? []).sort();
71
+ },
72
+ async listKeys({ cursor, limit, prefix = "" }) {
73
+ if (disposed) throw new Error("KV storage has been disposed.");
74
+ const continuation = cursor ? cursorHistories.take(cursor) : {
75
+ providerCursor: void 0,
76
+ history: /* @__PURE__ */ new Set(),
77
+ namespace: cursorNamespace
78
+ };
79
+ try {
80
+ const cursors = continuation.history;
81
+ const iterator = (await open()).list({ prefix: [] }, {
82
+ cursor: continuation.providerCursor,
83
+ limit
84
+ });
85
+ const keys = [];
86
+ for await (const entry of iterator) {
87
+ const key = fromDenoKey(entry.key);
88
+ if (key?.startsWith(prefix)) keys.push(key);
89
+ }
90
+ if (!iterator.cursor) {
91
+ cursorHistories.complete(cursor);
92
+ return { keys };
93
+ }
94
+ if (disposed) throw new Error("KV storage has been disposed.");
95
+ if (cursors.has(iterator.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Deno KV list returned a repeated pagination cursor." });
96
+ if (!recordCursor(cursors, iterator.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Deno KV rejected pagination after the cursor history limit was reached." });
97
+ const nextCursor = cursorHistories.store(iterator.cursor, cursors);
98
+ cursorHistories.complete(cursor);
99
+ return {
100
+ keys,
101
+ cursor: nextCursor
102
+ };
103
+ } catch (error) {
104
+ if (cursor && !disposed) cursorHistories.restore(cursor, continuation);
105
+ throw error;
106
+ }
107
+ },
108
+ async hasItem(key) {
109
+ return (await (await open()).get(toDenoKey(key))).versionstamp !== null;
110
+ },
111
+ async removeItem(key) {
112
+ await (await open()).delete(toDenoKey(key));
113
+ },
114
+ async setItem(key, value, writeOptions) {
115
+ await (await open()).set(toDenoKey(key), value, toDenoExpireIn(writeOptions?.ttl));
116
+ }
117
+ };
118
+ }
119
+ //#endregion
120
+ export { createDenoKVDriver as default };