@vite-hub/kv 0.0.4 → 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 (63) hide show
  1. package/README.md +110 -14
  2. package/dist/batch--v0ri69O.js +40 -0
  3. package/dist/cli-DpPhz_Ek.d.ts +163 -0
  4. package/dist/cli.d.ts +17 -0
  5. package/dist/cli.js +469 -0
  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/{dist-DDW1iC5f.js → create-storage-BGsrQKw3.js} +266 -115
  12. package/dist/cursor-history-BqIQePNP.js +165 -0
  13. package/dist/database-72Jk3VVk.js +250 -0
  14. package/dist/deno-kv-BM9mYdUp.js +128 -0
  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 +23 -7
  22. package/dist/errors.js +2 -20
  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 +10 -4
  26. package/dist/index.js +364 -109
  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/operation-definition-8gOe-ubD.d.ts +234 -0
  32. package/dist/operations-B-WZ7P1h.js +1351 -0
  33. package/dist/operations-Ch-gKaey.js +441 -0
  34. package/dist/operations.d.ts +75 -0
  35. package/dist/operations.js +318 -0
  36. package/dist/redis-shared-E5mahECF.js +94 -0
  37. package/dist/results-p7nPCnaJ.js +6 -0
  38. package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
  39. package/dist/runtime/cloudflare-kv.d.ts +3 -4
  40. package/dist/runtime/cloudflare-kv.js +1 -23
  41. package/dist/runtime/cloudflare-request-env.d.ts +7 -0
  42. package/dist/runtime/cloudflare-request-env.js +11 -0
  43. package/dist/runtime/nitro-plugin.d.ts +12 -0
  44. package/dist/runtime/nitro-plugin.js +22 -0
  45. package/dist/runtime/redis-driver.d.ts +11 -0
  46. package/dist/runtime/redis-driver.js +113 -0
  47. package/dist/runtime/unstorage-driver.d.ts +14 -0
  48. package/dist/runtime/unstorage-driver.js +33 -0
  49. package/dist/runtime/upstash-driver.d.ts +4 -6
  50. package/dist/runtime/upstash-driver.js +60 -110
  51. package/dist/{driver-BT9WefKi.d.ts → types-Bj3EQoRg.d.ts} +16 -11
  52. package/dist/types-DEiKew_3.d.ts +312 -0
  53. package/dist/upstash-DDlqTttY.js +40 -0
  54. package/dist/utils2-FozcTsmb.js +31 -0
  55. package/dist/virtual-module.d.ts +2 -0
  56. package/dist/virtual.d.ts +1 -1
  57. package/dist/vite.d.ts +159 -14
  58. package/dist/vite.js +1329 -2898
  59. package/package.json +68 -19
  60. package/dist/config-aM9Ae7tH.js +0 -110
  61. package/dist/deno-kv-cJx3jU10.js +0 -69
  62. package/dist/fs-lite-BxzdiJSi.js +0 -79
  63. package/dist/types-CO0DRjJa.d.ts +0 -78
@@ -1,4 +1,7 @@
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 { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
2
+ import { a as normalizeBaseKey, i as joinKeys, n as filterKeyByDepth, o as normalizeKey, r as hasDotSegment, t as filterKeyByBase } from "./utils2-FozcTsmb.js";
3
+ import { r as mapWithLimit } from "./batch--v0ri69O.js";
4
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/_chunks/libs/destr.mjs
2
5
  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
6
  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
7
  const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
@@ -41,79 +44,7 @@ function destr(value, options = {}) {
41
44
  }
42
45
  }
43
46
  //#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
47
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/drivers/memory.mjs
117
48
  const DRIVER_NAME = "memory";
118
49
  const driver = () => {
119
50
  const data = /* @__PURE__ */ new Map();
@@ -159,6 +90,7 @@ const driver = () => {
159
90
  }
160
91
  };
161
92
  };
93
+ const MAX_TIMER_DELAY = 2 ** 31 - 1;
162
94
  function _clearTimer(timers, key) {
163
95
  const existing = timers.get(key);
164
96
  if (existing !== void 0) {
@@ -167,14 +99,153 @@ function _clearTimer(timers, key) {
167
99
  }
168
100
  }
169
101
  function _scheduleExpiry(data, timers, key, ttl) {
170
- if (!ttl) return;
171
- const ttlMs = ttl * 1e3;
172
- const timer = setTimeout(() => {
173
- data.delete(key);
174
- timers.delete(key);
175
- }, ttlMs);
176
- if (timer && typeof timer === "object" && "unref" in timer) timer.unref();
177
- timers.set(key, timer);
102
+ if (!ttl || !Number.isFinite(ttl)) return;
103
+ let remaining = ttl * 1e3;
104
+ const schedule = () => {
105
+ const delay = Math.min(remaining, MAX_TIMER_DELAY);
106
+ remaining -= delay;
107
+ const timer = setTimeout(() => {
108
+ if (remaining > 0) {
109
+ schedule();
110
+ return;
111
+ }
112
+ data.delete(key);
113
+ timers.delete(key);
114
+ }, delay);
115
+ if (timer && typeof timer === "object" && "unref" in timer) timer.unref();
116
+ timers.set(key, timer);
117
+ };
118
+ schedule();
119
+ }
120
+ //#endregion
121
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/_chunks/_utils.mjs
122
+ function wrapToPromise(value) {
123
+ if (!value || typeof value.then !== "function") return Promise.resolve(value);
124
+ return value;
125
+ }
126
+ function asyncCall(function_, ...arguments_) {
127
+ try {
128
+ return wrapToPromise(function_(...arguments_));
129
+ } catch (error) {
130
+ return Promise.reject(error);
131
+ }
132
+ }
133
+ function isPrimitive(value) {
134
+ const type = typeof value;
135
+ return value === null || type !== "object" && type !== "function";
136
+ }
137
+ function isPureObject(value) {
138
+ const proto = Object.getPrototypeOf(value);
139
+ return !proto || proto.isPrototypeOf(Object);
140
+ }
141
+ function isPlainValue(value) {
142
+ return isPrimitive(value) || isPureObject(value) || Array.isArray(value);
143
+ }
144
+ function stringify(value) {
145
+ if (isPrimitive(value)) return String(value);
146
+ if (isPureObject(value) || Array.isArray(value)) return JSON.stringify(value);
147
+ if (typeof value.toJSON === "function") return stringify(value.toJSON());
148
+ throw new Error("[unstorage] Cannot stringify value!");
149
+ }
150
+ const BASE64_PREFIX = "base64:";
151
+ function serializeRaw(value) {
152
+ if (typeof value === "string") return value;
153
+ return BASE64_PREFIX + base64Encode(value);
154
+ }
155
+ function deserializeRaw(value) {
156
+ if (typeof value !== "string") return value;
157
+ if (!value.startsWith("base64:")) return value;
158
+ return base64Decode(value.slice(7));
159
+ }
160
+ function base64Decode(input) {
161
+ if (typeof Buffer !== "undefined") return Buffer.from(input, "base64");
162
+ return Uint8Array.from(globalThis.atob(input), (c) => c.codePointAt(0));
163
+ }
164
+ function base64Encode(input) {
165
+ if (typeof Buffer !== "undefined") return Buffer.from(input).toString("base64");
166
+ return globalThis.btoa(String.fromCodePoint(...input));
167
+ }
168
+ async function toBytes(value) {
169
+ if (typeof value === "string") return new TextEncoder().encode(value);
170
+ if (ArrayBuffer.isView(value)) return value.constructor === Uint8Array ? value : new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
171
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
172
+ if (typeof value?.arrayBuffer === "function") return new Uint8Array(await value.arrayBuffer());
173
+ if (typeof value?.getReader === "function" || typeof value?.[Symbol.asyncIterator] === "function") return concatBytes(await readChunks(value));
174
+ if (isPlainValue(value)) return new TextEncoder().encode(stringify(value));
175
+ throw new TypeError(`[unstorage] Cannot convert \`${typeName(value)}\` to bytes.`);
176
+ }
177
+ async function toBlob(value) {
178
+ if (value instanceof Blob) return value;
179
+ return new Blob([await toBytes(value)]);
180
+ }
181
+ async function toStream(value) {
182
+ if (value instanceof ReadableStream) return value;
183
+ if (value instanceof Blob) return value.stream();
184
+ const bytes = await toBytes(value);
185
+ return new ReadableStream({ start(controller) {
186
+ controller.enqueue(bytes);
187
+ controller.close();
188
+ } });
189
+ }
190
+ async function readChunks(value) {
191
+ const chunks = [];
192
+ if (typeof value.getReader === "function") {
193
+ const reader = value.getReader();
194
+ try {
195
+ while (true) {
196
+ const { done, value: chunk } = await reader.read();
197
+ if (done) break;
198
+ chunks.push(await chunkToBytes(chunk));
199
+ }
200
+ } finally {
201
+ reader.releaseLock();
202
+ }
203
+ } else for await (const chunk of value) chunks.push(await chunkToBytes(chunk));
204
+ return chunks;
205
+ }
206
+ function chunkToBytes(chunk) {
207
+ if (typeof chunk !== "string" && isPlainValue(chunk)) throw new TypeError(`[unstorage] Cannot convert \`${typeName(chunk)}\` to bytes.`);
208
+ return toBytes(chunk);
209
+ }
210
+ function concatBytes(chunks) {
211
+ if (chunks.length === 1) return chunks[0];
212
+ const bytes = new Uint8Array(chunks.reduce((size, chunk) => size + chunk.length, 0));
213
+ let offset = 0;
214
+ for (const chunk of chunks) {
215
+ bytes.set(chunk, offset);
216
+ offset += chunk.length;
217
+ }
218
+ return bytes;
219
+ }
220
+ function typeName(value) {
221
+ return value?.constructor?.name || typeof value;
222
+ }
223
+ //#endregion
224
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/index.mjs
225
+ function isRawType$1(type) {
226
+ return type === "bytes" || type === "blob" || type === "stream";
227
+ }
228
+ function isRawValue(value) {
229
+ return typeof value === "string" ? value.startsWith(BASE64_PREFIX) : ArrayBuffer.isView(value) || value instanceof ArrayBuffer || value instanceof Blob || value instanceof ReadableStream;
230
+ }
231
+ async function toValueType(value, type) {
232
+ if (value === null || value === void 0) return null;
233
+ if (type !== void 0 && isRawValue(value)) value = new TextDecoder().decode(await toBytes(deserializeRaw(value)));
234
+ if (type === "text") return typeof value === "string" ? value : stringify(value);
235
+ return destr(value);
236
+ }
237
+ async function getTypedItem(driver, relativeKey, opts = {}) {
238
+ const type = opts.type;
239
+ if (isRawType$1(type)) {
240
+ const raw = driver.getItemRaw ? await asyncCall(driver.getItemRaw, relativeKey, opts) : deserializeRaw(await asyncCall(driver.getItem, relativeKey, opts));
241
+ if (raw === null || raw === void 0) return null;
242
+ switch (type) {
243
+ case "bytes": return await toBytes(raw);
244
+ case "blob": return await toBlob(raw);
245
+ case "stream": return await toStream(raw);
246
+ }
247
+ }
248
+ return toValueType(await asyncCall(driver.getItem, relativeKey, opts), type);
178
249
  }
179
250
  function createStorage(options = {}) {
180
251
  const context = {
@@ -184,6 +255,16 @@ function createStorage(options = {}) {
184
255
  watchListeners: [],
185
256
  unwatch: {}
186
257
  };
258
+ const normalizeItemKey = (key) => {
259
+ const normalizedKey = normalizeKey(key);
260
+ if (!normalizedKey || hasDotSegment(normalizedKey)) throw new Error(`[unstorage] Invalid key: ${JSON.stringify(key)}`);
261
+ return normalizedKey;
262
+ };
263
+ const normalizeBase = (base) => {
264
+ const normalizedBase = normalizeBaseKey(base);
265
+ if (hasDotSegment(normalizedBase)) throw new Error(`[unstorage] Invalid base: ${JSON.stringify(base)}`);
266
+ return normalizedBase;
267
+ };
187
268
  const getMount = (key) => {
188
269
  for (const base of context.mountpoints) if (key.startsWith(base)) return {
189
270
  base,
@@ -235,7 +316,7 @@ function createStorage(options = {}) {
235
316
  };
236
317
  for (const item of items) {
237
318
  const isStringItem = typeof item === "string";
238
- const key = normalizeKey(isStringItem ? item : item.key);
319
+ const key = normalizeItemKey(isStringItem ? item : item.key);
239
320
  const value = isStringItem ? void 0 : item.value;
240
321
  const options = isStringItem || !item.options ? commonOptions : {
241
322
  ...commonOptions,
@@ -252,42 +333,52 @@ function createStorage(options = {}) {
252
333
  return Promise.all([...batches.values()].map((batch) => cb(batch))).then((r) => r.flat());
253
334
  };
254
335
  const storage = {
255
- hasItem(key, opts = {}) {
256
- key = normalizeKey(key);
336
+ async hasItem(key, opts = {}) {
337
+ key = normalizeItemKey(key);
257
338
  const { relativeKey, driver } = getMount(key);
258
339
  return asyncCall(driver.hasItem, relativeKey, opts);
259
340
  },
260
- getItem(key, opts = {}) {
261
- key = normalizeKey(key);
341
+ getItem: async (key, opts = {}) => {
342
+ key = normalizeItemKey(key);
262
343
  const { relativeKey, driver } = getMount(key);
263
- return asyncCall(driver.getItem, relativeKey, opts).then((value) => destr(value));
344
+ return getTypedItem(driver, relativeKey, opts);
264
345
  },
265
- getItems(items, commonOptions = {}) {
266
- return runBatch(items, commonOptions, (batch) => {
267
- if (batch.driver.getItems) return asyncCall(batch.driver.getItems, batch.items.map((item) => ({
346
+ async getItems(items, commonOptions = {}) {
347
+ return runBatch(items, commonOptions, async (batch) => {
348
+ if (!batch.driver.getItems) return Promise.all(batch.items.map(async (item) => ({
349
+ key: item.key,
350
+ value: await getTypedItem(batch.driver, item.relativeKey, item.options)
351
+ })));
352
+ const rawItems = batch.items.filter((item) => isRawType$1(item.options?.type));
353
+ const plainItems = rawItems.length === 0 ? batch.items : batch.items.filter((item) => !isRawType$1(item.options?.type));
354
+ const [plain, raw] = await Promise.all([plainItems.length === 0 ? [] : asyncCall(batch.driver.getItems, plainItems.map((item) => ({
268
355
  key: item.relativeKey,
269
356
  options: item.options
270
- })), commonOptions).then((r) => r.map((item) => ({
271
- key: joinKeys(batch.base, item.key),
272
- value: destr(item.value)
273
- })));
274
- return Promise.all(batch.items.map((item) => {
275
- return asyncCall(batch.driver.getItem, item.relativeKey, item.options).then((value) => ({
276
- key: item.key,
277
- value: destr(value)
278
- }));
279
- }));
357
+ })), commonOptions).then((r) => {
358
+ const types = r.length === plainItems.length ? void 0 : new Map(plainItems.map((item) => [item.relativeKey, item.options?.type]));
359
+ return Promise.all(r.map(async (item, index) => ({
360
+ key: joinKeys(batch.base, item.key),
361
+ value: await toValueType(item.value, types ? types.has(item.key) ? types.get(item.key) : commonOptions.type : plainItems[index].options?.type)
362
+ })));
363
+ }), Promise.all(rawItems.map(async (item) => ({
364
+ key: item.key,
365
+ value: await getTypedItem(batch.driver, item.relativeKey, item.options)
366
+ })))]);
367
+ if (rawItems.length === 0 || plain.length !== plainItems.length) return [...plain, ...raw];
368
+ let plainIndex = 0;
369
+ let rawIndex = 0;
370
+ return batch.items.map((item) => isRawType$1(item.options?.type) ? raw[rawIndex++] : plain[plainIndex++]);
280
371
  });
281
372
  },
282
- getItemRaw(key, opts = {}) {
283
- key = normalizeKey(key);
373
+ async getItemRaw(key, opts = {}) {
374
+ key = normalizeItemKey(key);
284
375
  const { relativeKey, driver } = getMount(key);
285
376
  if (driver.getItemRaw) return asyncCall(driver.getItemRaw, relativeKey, opts);
286
377
  return asyncCall(driver.getItem, relativeKey, opts).then((value) => deserializeRaw(value));
287
378
  },
288
379
  async setItem(key, value, opts = {}) {
289
380
  if (value === void 0) return storage.removeItem(key);
290
- key = normalizeKey(key);
381
+ key = normalizeItemKey(key);
291
382
  const { relativeKey, driver } = getMount(key);
292
383
  if (!driver.setItem) return;
293
384
  await asyncCall(driver.setItem, relativeKey, stringify(value), opts);
@@ -308,7 +399,7 @@ function createStorage(options = {}) {
308
399
  },
309
400
  async setItemRaw(key, value, opts = {}) {
310
401
  if (value === void 0) return storage.removeItem(key, opts);
311
- key = normalizeKey(key);
402
+ key = normalizeItemKey(key);
312
403
  const { relativeKey, driver } = getMount(key);
313
404
  if (driver.setItemRaw) await asyncCall(driver.setItemRaw, relativeKey, value, opts);
314
405
  else if (driver.setItem) await asyncCall(driver.setItem, relativeKey, serializeRaw(value), opts);
@@ -317,7 +408,7 @@ function createStorage(options = {}) {
317
408
  },
318
409
  async removeItem(key, opts = {}) {
319
410
  if (typeof opts === "boolean") opts = { removeMeta: opts };
320
- key = normalizeKey(key);
411
+ key = normalizeItemKey(key);
321
412
  const { relativeKey, driver } = getMount(key);
322
413
  if (!driver.removeItem) return;
323
414
  await asyncCall(driver.removeItem, relativeKey, opts);
@@ -326,7 +417,7 @@ function createStorage(options = {}) {
326
417
  },
327
418
  async getMeta(key, opts = {}) {
328
419
  if (typeof opts === "boolean") opts = { nativeOnly: opts };
329
- key = normalizeKey(key);
420
+ key = normalizeItemKey(key);
330
421
  const { relativeKey, driver } = getMount(key);
331
422
  const meta = Object.create(null);
332
423
  if (driver.getMeta) Object.assign(meta, await asyncCall(driver.getMeta, relativeKey, opts));
@@ -340,14 +431,14 @@ function createStorage(options = {}) {
340
431
  }
341
432
  return meta;
342
433
  },
343
- setMeta(key, value, opts = {}) {
344
- return this.setItem(key + "$", value, opts);
434
+ async setMeta(key, value, opts = {}) {
435
+ return this.setItem(normalizeItemKey(key) + "$", value, opts);
345
436
  },
346
- removeMeta(key, opts = {}) {
347
- return this.removeItem(key + "$", opts);
437
+ async removeMeta(key, opts = {}) {
438
+ return this.removeItem(normalizeItemKey(key) + "$", opts);
348
439
  },
349
440
  async getKeys(base, opts = {}) {
350
- base = normalizeBaseKey(base);
441
+ base = normalizeBase(base);
351
442
  const mounts = getMounts(base, true);
352
443
  let maskedMounts = [];
353
444
  const allKeys = [];
@@ -365,7 +456,7 @@ function createStorage(options = {}) {
365
456
  return allKeys.filter((key) => (!shouldFilterByDepth || filterKeyByDepth(key, opts.maxDepth)) && filterKeyByBase(key, base));
366
457
  },
367
458
  async clear(base, opts = {}) {
368
- base = normalizeBaseKey(base);
459
+ base = normalizeBase(base);
369
460
  await Promise.all(getMounts(base, false).map(async (m) => {
370
461
  if (m.driver.clear) return asyncCall(m.driver.clear, m.relativeBase, opts);
371
462
  if (m.driver.removeItem) {
@@ -390,7 +481,7 @@ function createStorage(options = {}) {
390
481
  await stopWatch();
391
482
  },
392
483
  mount(base, driver) {
393
- base = normalizeBaseKey(base);
484
+ base = normalizeBase(base);
394
485
  if (base && context.mounts[base]) throw new Error(`already mounted at ${base}`);
395
486
  if (base) {
396
487
  context.mountpoints.push(base);
@@ -444,4 +535,64 @@ async function dispose(driver) {
444
535
  if (typeof driver.dispose === "function") await asyncCall(driver.dispose);
445
536
  }
446
537
  //#endregion
447
- export { normalizeKey as n, createStorage as t };
538
+ //#region src/runtime/list-prefix.ts
539
+ function normalizeKVListPrefix(prefix = "") {
540
+ const normalized = normalizeKey(prefix);
541
+ const path = prefix.split("?")[0] ?? "";
542
+ return normalized && /[:/\\]$/.test(path) ? `${normalized}:` : normalized;
543
+ }
544
+ //#endregion
545
+ //#region src/runtime/create-storage.ts
546
+ function isRawType(type) {
547
+ return type === "bytes" || type === "blob" || type === "stream";
548
+ }
549
+ const removeBatchSize = 100;
550
+ /** Gives single-store KV prefixes the same meaning for clear() and getKeys(), and adds the batch methods. */
551
+ function createKVStorage(driver) {
552
+ const storage = createStorage({ driver });
553
+ const clear = storage.clear;
554
+ storage.clear = async (base, options = {}) => {
555
+ const prefix = normalizeBaseKey(base);
556
+ if (!prefix) return clear(base, options);
557
+ if (driver.clear) return driver.clear(prefix, options);
558
+ const keys = await storage.getKeys(base, options);
559
+ for (let offset = 0; offset < keys.length; offset += removeBatchSize) await Promise.all(keys.slice(offset, offset + removeBatchSize).map((key) => storage.removeItem(key, options)));
560
+ };
561
+ return Object.assign(storage, {
562
+ async getMany(keys, options = {}) {
563
+ if (!Array.isArray(keys)) throw kvErrorDiagnostics.KV_INVALID_BATCH({ operation: "getMany" });
564
+ if (keys.length === 0) return [];
565
+ if (!driver.getItems || isRawType(options.type)) return mapWithLimit(keys, (key) => storage.getItem(key, options));
566
+ const entries = await storage.getItems(keys, options);
567
+ if (entries.length !== keys.length) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "The batch read returned another number of values than keys." });
568
+ return entries.map((entry) => entry.value);
569
+ },
570
+ async setMany(entries, options) {
571
+ if (!Array.isArray(entries)) throw kvErrorDiagnostics.KV_INVALID_BATCH({ operation: "setMany" });
572
+ const latest = /* @__PURE__ */ new Map();
573
+ for (const { key, value } of entries) {
574
+ const normalized = normalizeKey(key);
575
+ latest.delete(normalized);
576
+ latest.set(normalized, value);
577
+ }
578
+ const writes = [];
579
+ const removals = [];
580
+ for (const [key, value] of latest) if (value === void 0) removals.push(key);
581
+ else writes.push({
582
+ key,
583
+ value
584
+ });
585
+ if (driver.validateBatch) {
586
+ await driver.validateBatch([], removals, options);
587
+ const validateBatch = driver.validateBatch;
588
+ await createStorage({ driver: {
589
+ ...driver,
590
+ setItems: (items) => validateBatch(items, removals, options)
591
+ } }).setItems(writes, options);
592
+ }
593
+ await Promise.all([writes.length === 0 ? void 0 : driver.setItems ? storage.setItems(writes, options) : mapWithLimit(writes, (entry) => storage.setItem(entry.key, entry.value, options)), mapWithLimit(removals, (key) => storage.removeItem(key, options))]);
594
+ }
595
+ });
596
+ }
597
+ //#endregion
598
+ export { normalizeKVListPrefix as n, createKVStorage as t };
@@ -0,0 +1,165 @@
1
+ import { t as invariant } from "./invariant-DolT9EEx.js";
2
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
3
+ //#region src/runtime/cursor-history.ts
4
+ const MAX_CURSOR_HISTORIES = 1024;
5
+ const MAX_CURSORS_PER_HISTORY = 1024;
6
+ const MAX_CURSOR_LENGTH = 8192;
7
+ const MAX_CONTINUATION_LENGTH = 131072;
8
+ function continuationTag(value) {
9
+ const hashes = [
10
+ 2166136261,
11
+ 2246822519,
12
+ 3266489917,
13
+ 668265263
14
+ ];
15
+ for (let index = 0; index < value.length; index++) {
16
+ const code = value.charCodeAt(index);
17
+ for (let hashIndex = 0; hashIndex < hashes.length; hashIndex++) hashes[hashIndex] = Math.imul(hashes[hashIndex] ^ code, 16777619 + hashIndex * 2);
18
+ }
19
+ return hashes.map((hash) => (hash >>> 0).toString(16).padStart(8, "0")).join("");
20
+ }
21
+ function encodeContinuation(providerCursor, history) {
22
+ const nonce = globalThis.crypto.randomUUID();
23
+ const historyTag = continuationTag([...history].join("\0"));
24
+ const payload = encodeURIComponent(JSON.stringify({
25
+ format: "vitehub-continuation",
26
+ providerCursor,
27
+ historyCount: history.size,
28
+ historyTag
29
+ }));
30
+ const token = `vhc1:${nonce}:${payload}:${continuationTag(payload)}`;
31
+ invariant(token.length <= MAX_CONTINUATION_LENGTH, "a KV continuation cursor stays below 128 KiB, because provider cursors are far shorter");
32
+ return token;
33
+ }
34
+ function decodeContinuation(token) {
35
+ const match = /^vhc1:[0-9a-f-]{36}:([^:]+):([0-9a-f]{32})$/.exec(token);
36
+ if (!match || continuationTag(match[1]) !== match[2]) return void 0;
37
+ let payload;
38
+ try {
39
+ payload = JSON.parse(decodeURIComponent(match[1]));
40
+ } catch {
41
+ return;
42
+ }
43
+ if (!payload || typeof payload !== "object" || Reflect.get(payload, "format") !== "vitehub-continuation") return void 0;
44
+ const providerCursor = Reflect.get(payload, "providerCursor");
45
+ return typeof providerCursor === "string" && providerCursor.length > 0 && providerCursor.length <= MAX_CURSOR_LENGTH ? providerCursor : void 0;
46
+ }
47
+ const continuations = /* @__PURE__ */ new Map();
48
+ const continuationOwners = /* @__PURE__ */ new Map();
49
+ const consumedContinuations = /* @__PURE__ */ new Map();
50
+ const consumedOwners = /* @__PURE__ */ new Map();
51
+ const invalidatedContinuations = /* @__PURE__ */ new Set();
52
+ function rememberInvalidated(cursor) {
53
+ invalidatedContinuations.add(cursor);
54
+ while (invalidatedContinuations.size > MAX_CURSOR_HISTORIES) {
55
+ const oldest = invalidatedContinuations.values().next().value;
56
+ if (oldest === void 0) break;
57
+ invalidatedContinuations.delete(oldest);
58
+ }
59
+ }
60
+ /** Keeps continuation history tied to an opaque, traversal-owned token. */
61
+ function createCursorHistory(namespace = "default") {
62
+ const ownedContinuations = /* @__PURE__ */ new Set();
63
+ const ownedConsumedContinuations = /* @__PURE__ */ new Set();
64
+ function take(cursor, requestedNamespace = namespace) {
65
+ let continuation = continuations.get(cursor);
66
+ if (continuation && continuation.namespace !== requestedNamespace) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "foreign" });
67
+ if (!continuation) {
68
+ if (consumedContinuations.has(cursor)) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "in-use" });
69
+ if (invalidatedContinuations.has(cursor)) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "expired" });
70
+ const providerCursor = cursor.length <= MAX_CONTINUATION_LENGTH ? decodeContinuation(cursor) : void 0;
71
+ if (providerCursor) continuation = {
72
+ providerCursor,
73
+ history: /* @__PURE__ */ new Set([providerCursor]),
74
+ namespace: requestedNamespace
75
+ };
76
+ else {
77
+ if (cursor.length > MAX_CURSOR_LENGTH) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "invalid" });
78
+ return {
79
+ providerCursor: cursor,
80
+ history: /* @__PURE__ */ new Set([cursor]),
81
+ namespace
82
+ };
83
+ }
84
+ }
85
+ continuations.delete(cursor);
86
+ continuationOwners.get(cursor)?.delete(cursor);
87
+ continuationOwners.delete(cursor);
88
+ consumedContinuations.set(cursor, continuation);
89
+ ownedConsumedContinuations.add(cursor);
90
+ consumedOwners.set(cursor, ownedConsumedContinuations);
91
+ while (consumedContinuations.size > MAX_CURSOR_HISTORIES) {
92
+ const oldest = consumedContinuations.keys().next().value;
93
+ if (oldest === void 0) break;
94
+ consumedContinuations.delete(oldest);
95
+ consumedOwners.get(oldest)?.delete(oldest);
96
+ consumedOwners.delete(oldest);
97
+ rememberInvalidated(oldest);
98
+ }
99
+ return continuation;
100
+ }
101
+ function store(providerCursor, history, requestedNamespace = namespace) {
102
+ const token = encodeContinuation(providerCursor, history);
103
+ continuations.set(token, {
104
+ providerCursor,
105
+ history,
106
+ namespace: requestedNamespace
107
+ });
108
+ ownedContinuations.add(token);
109
+ continuationOwners.set(token, ownedContinuations);
110
+ while (continuations.size > MAX_CURSOR_HISTORIES) {
111
+ const oldest = continuations.keys().next().value;
112
+ if (oldest === void 0) break;
113
+ continuations.delete(oldest);
114
+ continuationOwners.get(oldest)?.delete(oldest);
115
+ continuationOwners.delete(oldest);
116
+ rememberInvalidated(oldest);
117
+ }
118
+ return token;
119
+ }
120
+ function restore(cursor, continuation) {
121
+ if (consumedContinuations.get(cursor) !== continuation) return;
122
+ continuations.set(cursor, continuation);
123
+ ownedContinuations.add(cursor);
124
+ continuationOwners.set(cursor, ownedContinuations);
125
+ consumedContinuations.delete(cursor);
126
+ consumedOwners.delete(cursor);
127
+ ownedConsumedContinuations.delete(cursor);
128
+ }
129
+ function complete(cursor) {
130
+ if (cursor && ownedConsumedContinuations.has(cursor)) {
131
+ consumedContinuations.delete(cursor);
132
+ consumedOwners.delete(cursor);
133
+ ownedConsumedContinuations.delete(cursor);
134
+ }
135
+ }
136
+ function clear() {
137
+ for (const token of ownedContinuations) {
138
+ continuations.delete(token);
139
+ continuationOwners.delete(token);
140
+ rememberInvalidated(token);
141
+ }
142
+ ownedContinuations.clear();
143
+ for (const token of ownedConsumedContinuations) {
144
+ consumedContinuations.delete(token);
145
+ consumedOwners.delete(token);
146
+ rememberInvalidated(token);
147
+ }
148
+ ownedConsumedContinuations.clear();
149
+ }
150
+ return {
151
+ take,
152
+ store,
153
+ restore,
154
+ complete,
155
+ clear
156
+ };
157
+ }
158
+ /** Records a provider cursor, refusing to weaken repeat detection at the bound. */
159
+ function recordCursor(history, cursor) {
160
+ if (cursor.length > MAX_CURSOR_LENGTH || history.size >= MAX_CURSORS_PER_HISTORY) return false;
161
+ history.add(cursor);
162
+ return true;
163
+ }
164
+ //#endregion
165
+ export { recordCursor as n, createCursorHistory as t };