@vite-hub/kv 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +9 -7
  2. package/dist/{cli-BvVInMht.d.ts → cli-C-uep33j.d.ts} +15 -0
  3. package/dist/cli.d.ts +2 -2
  4. package/dist/cli.js +3 -2
  5. package/dist/{cloudflare-kv-Cp8HPUlJ.js → cloudflare-kv-hMdZQZz1.js} +3 -3
  6. package/dist/{cloudflare-kv-local-COoOI34K.js → cloudflare-kv-local-BpPaDG49.js} +2 -2
  7. package/dist/{config-_1oBDv2R.js → config-x_Nru3R5.js} +4 -4
  8. package/dist/{create-storage-DbWVAY9l.js → create-storage-DrhV0F4S.js} +1 -1
  9. package/dist/{cursor-history-CMcEEnTO.js → cursor-history-MzSrXXXX.js} +1 -1
  10. package/dist/{database-4iAg2GoV.js → database-D0NvYrhk.js} +66 -20
  11. package/dist/{deno-kv-CatE7zSS.js → deno-kv-DwcTL95B.js} +2 -2
  12. package/dist/{driver-BruahGvT.d.ts → driver-CZTAQ_07.d.ts} +2 -2
  13. package/dist/{error-diagnostics-CuVl1nvE.js → error-diagnostics-DAi25E6F.js} +10 -5
  14. package/dist/{errors-CJoAP4Bu.js → errors-kZRpu7Wa.js} +15 -2
  15. package/dist/errors.d.ts +6 -1
  16. package/dist/errors.js +1 -1
  17. package/dist/{fs-lite-DzTTR6R3.js → fs-lite-1n_Dvy4p.js} +195 -131
  18. package/dist/fs-lite-Co1NzxYo.js +1 -0
  19. package/dist/index.d.ts +1 -1
  20. package/dist/index.js +79 -69
  21. package/dist/{operation-definition-CqZkx1Rm.d.ts → operations-BAlr2zUj.d.ts} +1 -0
  22. package/dist/{operations-DSOTGwST.js → operations-Cj_0pSSA.js} +22 -29
  23. package/dist/{operations-BkVt17cd.js → operations-DP8iWjQK.js} +75 -11
  24. package/dist/operations.d.ts +2 -2
  25. package/dist/operations.js +2 -2
  26. package/dist/{redis-shared-CR3ANc_N.js → redis-shared-DEwmedD5.js} +1 -1
  27. package/dist/runtime/cloudflare-kv.d.ts +1 -1
  28. package/dist/runtime/cloudflare-kv.js +1 -1
  29. package/dist/runtime/nitro-plugin.js +1 -1
  30. package/dist/runtime/redis-driver.d.ts +2 -2
  31. package/dist/runtime/redis-driver.js +3 -5
  32. package/dist/runtime/upstash-driver.d.ts +2 -2
  33. package/dist/runtime/upstash-driver.js +2 -2
  34. package/dist/{types-CPDL9enF.d.ts → types-BLxnI_rU.d.ts} +14 -14
  35. package/dist/{upstash-DeM3_U5H.js → upstash-DINRYhXI.js} +2 -2
  36. package/dist/vite.d.ts +9 -5
  37. package/dist/vite.js +211 -75
  38. package/package.json +8 -4
  39. package/dist/fs-lite-DwbPkc-C.js +0 -1
@@ -1,5 +1,5 @@
1
- import { n as kvErrorDiagnostics } from "./error-diagnostics-CuVl1nvE.js";
2
- import { link, lstat, mkdir, mkdtemp, opendir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
1
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-DAi25E6F.js";
2
+ import { link, lstat, mkdir, mkdtemp, opendir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
3
3
  import { basename, join, relative, resolve, sep } from "node:path";
4
4
  import createDriver from "unstorage/drivers/fs-lite";
5
5
  import { createHash, randomUUID } from "node:crypto";
@@ -71,6 +71,12 @@ const layoutRecord = /^\.unstorage-tmp-vitehub-layout-v1(?:-\d+)?$/;
71
71
  const layoutRecordName = ".unstorage-tmp-vitehub-layout-v1";
72
72
  const layoutMarkerName = ".unstorage-tmp-vitehub-record";
73
73
  const keyPrefix = "key-";
74
+ const canonicalInteger = /^(?:0|-?[1-9]\d{0,15})$/;
75
+ const lockRetries = {
76
+ retries: 100,
77
+ minTimeout: 20,
78
+ maxTimeout: 100
79
+ };
74
80
  function fileName(key) {
75
81
  return keyPrefix + key.replace(/[%:]/g, encodeURIComponent);
76
82
  }
@@ -137,11 +143,7 @@ async function migrateKeys(root) {
137
143
  }
138
144
  const release = await lock(layout, {
139
145
  lockfilePath: join(layout, "lock"),
140
- retries: {
141
- retries: 100,
142
- minTimeout: 20,
143
- maxTimeout: 100
144
- }
146
+ retries: lockRetries
145
147
  });
146
148
  try {
147
149
  for (const candidate of candidates) if (candidate !== layout) await rm(candidate, {
@@ -187,6 +189,59 @@ async function migrateKeys(root) {
187
189
  await release();
188
190
  }
189
191
  }
192
+ const maxTasksPerLock = 100;
193
+ const folderQueues = /* @__PURE__ */ new Map();
194
+ function queueUnderFolderLock(layout, operation, mode = "batch") {
195
+ return new Promise((resolveTask, rejectTask) => {
196
+ const task = {
197
+ mode,
198
+ runAndReturnSettle: async () => {
199
+ try {
200
+ const value = await operation();
201
+ return () => resolveTask(value);
202
+ } catch (error) {
203
+ return () => rejectTask(error);
204
+ }
205
+ },
206
+ fail: rejectTask
207
+ };
208
+ const queue = folderQueues.get(layout);
209
+ if (queue) {
210
+ queue.push(task);
211
+ return;
212
+ }
213
+ const created = [task];
214
+ folderQueues.set(layout, created);
215
+ drainFolderQueue(layout, created);
216
+ });
217
+ }
218
+ async function drainFolderQueue(layout, queue) {
219
+ while (queue.length) {
220
+ let count = 1;
221
+ if (queue[0]?.mode === "batch") while (count < maxTasksPerLock && queue[count]?.mode === "batch") count++;
222
+ const tasks = queue.splice(0, count);
223
+ let release;
224
+ try {
225
+ release = await lock(layout, {
226
+ lockfilePath: join(layout, "lock"),
227
+ retries: lockRetries
228
+ });
229
+ } catch (error) {
230
+ for (const task of tasks) task.fail(error);
231
+ continue;
232
+ }
233
+ const settles = [];
234
+ for (const task of tasks) settles.push(await task.runAndReturnSettle());
235
+ try {
236
+ await release();
237
+ } catch (error) {
238
+ for (const task of tasks) task.fail(error);
239
+ continue;
240
+ }
241
+ for (const settle of settles) settle();
242
+ }
243
+ folderQueues.delete(layout);
244
+ }
190
245
  function ttlMilliseconds(ttl) {
191
246
  if (!Number.isFinite(ttl) || ttl <= 0) throw kvErrorDiagnostics.KV_INVALID_TTL();
192
247
  const ms = Math.ceil(ttl * 1e3);
@@ -194,9 +249,8 @@ function ttlMilliseconds(ttl) {
194
249
  return ms;
195
250
  }
196
251
  function setExpiry(options) {
197
- const ttl = options && typeof options === "object" ? Reflect.get(options, "ttl") : void 0;
198
- if (ttl === void 0 || ttl === null || ttl === 0) return;
199
- if (typeof ttl !== "number") throw kvErrorDiagnostics.KV_INVALID_TTL();
252
+ const ttl = options?.ttl;
253
+ if (ttl === void 0 || ttl === 0) return;
200
254
  return Date.now() + ttlMilliseconds(ttl);
201
255
  }
202
256
  async function createFsLiteKVDriver(options) {
@@ -212,21 +266,7 @@ async function createFsLiteKVDriver(options) {
212
266
  const expiresAt = text === void 0 ? NaN : Number(text);
213
267
  return Number.isSafeInteger(expiresAt) ? expiresAt : void 0;
214
268
  }
215
- async function synchronized(operation) {
216
- const release = await lock(layout, {
217
- lockfilePath: join(layout, "lock"),
218
- retries: {
219
- retries: 100,
220
- minTimeout: 20,
221
- maxTimeout: 100
222
- }
223
- });
224
- try {
225
- return await operation();
226
- } finally {
227
- await release();
228
- }
229
- }
269
+ const synchronized = (operation) => queueUnderFolderLock(layout, operation);
230
270
  async function writeExpiry(key, expiresAt) {
231
271
  if (expiresAt === void 0) {
232
272
  await rm(expiryPath(key), { force: true });
@@ -244,51 +284,10 @@ async function createFsLiteKVDriver(options) {
244
284
  await rm(expiryPath(key), { force: true });
245
285
  return false;
246
286
  }
247
- const driver = createDriver(options);
248
- const { getItem, getItemRaw, getMeta, hasItem, removeItem, setItem, setItemRaw } = driver;
249
- driver.getItem = async (key, operationOptions) => {
250
- if (!await live(key)) return null;
251
- const value = await getItem(fileName(key), operationOptions);
252
- if (value instanceof Error) throw value;
253
- return value;
254
- };
255
- driver.getItemRaw = async (key, operationOptions) => {
256
- if (!await live(key)) return null;
257
- const value = await getItemRaw?.(fileName(key), operationOptions);
258
- if (value instanceof Error) throw value;
259
- return value;
260
- };
261
- driver.getMeta = async (key, operationOptions) => await live(key) ? getMeta?.(fileName(key), operationOptions) ?? null : null;
262
- driver.setItem = async (key, value, operationOptions) => {
263
- await writeExpiry(key, setExpiry(operationOptions));
264
- return setItem?.(fileName(key), value, operationOptions);
265
- };
266
- driver.setItemRaw = async (key, value, operationOptions) => {
267
- await writeExpiry(key, setExpiry(operationOptions));
268
- return setItemRaw?.(fileName(key), value, operationOptions);
269
- };
270
- driver.removeItem = async (key, operationOptions) => {
271
- await rm(expiryPath(key), { force: true });
272
- await removeItem?.(fileName(key), operationOptions);
273
- };
274
- driver.clear = async (base = "") => {
275
- const entries = await readdir(root).catch((error) => {
276
- if (hasCode(error, "ENOENT")) return [];
277
- throw error;
278
- });
279
- for (const entry of entries) {
280
- const key = keyOf(entry);
281
- if (key !== void 0 && key.startsWith(base)) {
282
- await rm(join(root, entry), {
283
- force: true,
284
- recursive: true
285
- });
286
- await rm(expiryPath(key), { force: true });
287
- }
288
- }
289
- };
287
+ const base = createDriver(options);
288
+ const locked = (operation) => (...args) => synchronized(() => operation(...args));
290
289
  const hasLiveItem = async (key, operationOptions) => {
291
- if (!await hasItem(fileName(key), operationOptions)) return false;
290
+ if (!await base.hasItem(fileName(key), operationOptions)) return false;
292
291
  if (!await live(key)) return false;
293
292
  try {
294
293
  return (await stat(join(root, fileName(key)))).isFile();
@@ -297,25 +296,16 @@ async function createFsLiteKVDriver(options) {
297
296
  throw error;
298
297
  }
299
298
  };
300
- driver.hasItem = hasLiveItem;
301
- driver.setIfAbsentItem = async (key, value, ttl) => {
302
- const expiresAt = ttl === void 0 ? void 0 : Date.now() + ttlMilliseconds(ttl);
303
- if (await hasLiveItem(key, {})) return false;
304
- const path = join(root, fileName(key));
305
- await mkdir(root, { recursive: true });
306
- const temporary = join(root, `.unstorage-tmp-${randomUUID()}`);
307
- await writeFile(temporary, value, "utf8");
308
- try {
309
- await link(temporary, path);
310
- await writeExpiry(key, expiresAt);
311
- return true;
312
- } catch (error) {
313
- if (hasCode(error, "EEXIST") && (await stat(path)).isFile()) return false;
314
- throw error;
315
- } finally {
316
- await rm(temporary, { force: true });
317
- }
318
- };
299
+ async function readLiveText(key) {
300
+ if (!await live(key)) return null;
301
+ const value = await base.getItem(fileName(key), {});
302
+ if (value instanceof Error) throw value;
303
+ return typeof value === "string" ? value : null;
304
+ }
305
+ async function deleteKey(key) {
306
+ await unlink(join(root, fileName(key)));
307
+ await rm(expiryPath(key), { force: true });
308
+ }
319
309
  async function* walk() {
320
310
  let entries;
321
311
  try {
@@ -330,55 +320,129 @@ async function createFsLiteKVDriver(options) {
330
320
  yield key !== void 0 && await synchronized(() => live(key)) ? key : void 0;
331
321
  }
332
322
  }
333
- driver.getKeys = async () => {
334
- const keys = [];
335
- for await (const key of walk()) if (key !== void 0) keys.push(key);
336
- return keys;
337
- };
338
323
  const expired = () => kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "expired" });
339
324
  const continuations = createKVContinuations({
340
325
  expired,
341
326
  release: (iterator) => iterator.return(void 0)
342
327
  });
343
- const dispose = driver.dispose;
344
- driver.dispose = async () => {
345
- try {
346
- await continuations.dispose();
347
- } finally {
348
- await dispose?.call(driver);
349
- }
350
- };
351
- driver.listKeys = async ({ cursor, limit, prefix = "" }) => {
352
- const keys = [];
353
- const iterator = cursor ? continuations.take(cursor) : walk();
354
- if (!iterator) throw expired();
355
- let scanned = 0;
356
- while (scanned < limit) {
357
- const entry = await iterator.next();
358
- if (entry.done) return { keys };
359
- scanned++;
360
- const key = entry.value;
361
- if (key !== void 0 && key.startsWith(prefix)) keys.push(key);
328
+ return {
329
+ ...base,
330
+ getItem: locked(async (key, operationOptions) => {
331
+ if (!await live(key)) return null;
332
+ const value = await base.getItem(fileName(key), operationOptions);
333
+ if (value instanceof Error) throw value;
334
+ return value;
335
+ }),
336
+ getItemRaw: locked(async (key, operationOptions) => {
337
+ if (!await live(key)) return null;
338
+ const value = await base.getItemRaw?.(fileName(key), operationOptions);
339
+ if (value instanceof Error) throw value;
340
+ return value;
341
+ }),
342
+ getMeta: locked(async (key, operationOptions) => await live(key) ? base.getMeta?.(fileName(key), operationOptions) ?? null : null),
343
+ setItem: locked(async (key, value, operationOptions) => {
344
+ await writeExpiry(key, setExpiry(operationOptions));
345
+ return base.setItem?.(fileName(key), value, operationOptions);
346
+ }),
347
+ setItemRaw: locked(async (key, value, operationOptions) => {
348
+ await writeExpiry(key, setExpiry(operationOptions));
349
+ return base.setItemRaw?.(fileName(key), value, operationOptions);
350
+ }),
351
+ removeItem: locked(async (key, operationOptions) => {
352
+ await rm(expiryPath(key), { force: true });
353
+ await base.removeItem?.(fileName(key), operationOptions);
354
+ }),
355
+ clear: (prefix = "") => queueUnderFolderLock(layout, async () => {
356
+ const entries = await readdir(root).catch((error) => {
357
+ if (hasCode(error, "ENOENT")) return [];
358
+ throw error;
359
+ });
360
+ for (const entry of entries) {
361
+ const key = keyOf(entry);
362
+ if (key !== void 0 && key.startsWith(prefix)) {
363
+ await rm(join(root, entry), {
364
+ force: true,
365
+ recursive: true
366
+ });
367
+ await rm(expiryPath(key), { force: true });
368
+ }
369
+ }
370
+ }, "single"),
371
+ hasItem: locked(hasLiveItem),
372
+ setIfAbsentItem: locked(async (key, value, ttl) => {
373
+ const expiresAt = ttl === void 0 ? void 0 : Date.now() + ttlMilliseconds(ttl);
374
+ if (await hasLiveItem(key, {})) return false;
375
+ const path = join(root, fileName(key));
376
+ await mkdir(root, { recursive: true });
377
+ const temporary = join(root, `.unstorage-tmp-${randomUUID()}`);
378
+ await writeFile(temporary, value, "utf8");
379
+ try {
380
+ await link(temporary, path);
381
+ await writeExpiry(key, expiresAt);
382
+ return true;
383
+ } catch (error) {
384
+ if (hasCode(error, "EEXIST") && (await stat(path)).isFile()) return false;
385
+ throw error;
386
+ } finally {
387
+ await rm(temporary, { force: true });
388
+ }
389
+ }),
390
+ getAndDeleteItem: locked(async (key) => {
391
+ const text = await readLiveText(key);
392
+ if (text === null) return null;
393
+ await deleteKey(key);
394
+ return text;
395
+ }),
396
+ incrementItem: locked(async (key, ttl) => {
397
+ const expiresAt = Date.now() + ttlMilliseconds(ttl);
398
+ const text = await readLiveText(key);
399
+ const counter = text === null ? 0 : canonicalInteger.test(text) ? Number(text) : NaN;
400
+ if (!(counter >= Number.MIN_SAFE_INTEGER - 1 && counter < Number.MAX_SAFE_INTEGER)) throw kvErrorDiagnostics.KV_INVALID_COUNTER();
401
+ const next = counter + 1;
402
+ const temporary = join(root, `.unstorage-tmp-${randomUUID()}`);
403
+ try {
404
+ await writeFile(temporary, String(next));
405
+ if (text === null) await writeExpiry(key, expiresAt);
406
+ await rename(temporary, join(root, fileName(key)));
407
+ } finally {
408
+ await rm(temporary, { force: true });
409
+ }
410
+ return next;
411
+ }),
412
+ deleteIfEqualsItem: locked(async (key, expected) => {
413
+ if (await readLiveText(key) !== expected) return false;
414
+ await deleteKey(key);
415
+ return true;
416
+ }),
417
+ getKeys: async () => {
418
+ const keys = [];
419
+ for await (const key of walk()) if (key !== void 0) keys.push(key);
420
+ return keys;
421
+ },
422
+ dispose: async () => {
423
+ try {
424
+ await continuations.dispose();
425
+ } finally {
426
+ await base.dispose?.();
427
+ }
428
+ },
429
+ listKeys: async ({ cursor, limit, prefix = "" }) => {
430
+ const keys = [];
431
+ const iterator = cursor ? continuations.take(cursor) : walk();
432
+ if (!iterator) throw expired();
433
+ let scanned = 0;
434
+ while (scanned < limit) {
435
+ const entry = await iterator.next();
436
+ if (entry.done) return { keys };
437
+ scanned++;
438
+ const key = entry.value;
439
+ if (key !== void 0 && key.startsWith(prefix)) keys.push(key);
440
+ }
441
+ return {
442
+ keys,
443
+ cursor: await continuations.retain(iterator)
444
+ };
362
445
  }
363
- return {
364
- keys,
365
- cursor: await continuations.retain(iterator)
366
- };
367
446
  };
368
- for (const name of [
369
- "getItem",
370
- "getItemRaw",
371
- "getMeta",
372
- "hasItem",
373
- "setItem",
374
- "setItemRaw",
375
- "removeItem",
376
- "clear",
377
- "setIfAbsentItem"
378
- ]) {
379
- const operation = driver[name];
380
- if (operation) Reflect.set(driver, name, (...args) => synchronized(async () => Reflect.apply(operation, driver, args)));
381
- }
382
- return driver;
383
447
  }
384
448
  export { createFsLiteKVDriver as t };
@@ -0,0 +1 @@
1
+ export { t as default } from "./fs-lite-1n_Dvy4p.js";
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as KVStoreOptions, B as ResolvedUpstashKVStoreConfig, C as KVOperation, D as KVStorage, E as KVSetOptions, F as ResolvedDenoKVStoreConfig, I as ResolvedFsLiteKVStoreConfig, L as ResolvedKVModuleOptions, M as RedisKVStoreConfig, N as ResolvedCloudflareKVStoreConfig, O as KVStoreConfig, P as ResolvedDatabaseKVStoreConfig, R as ResolvedKVStoreConfig, S as KVLockRunResult, V as UpstashKVStoreConfig, _ as KVListPage, a as InferredKVStoreConfig, b as KVLockErrorCode, c as KVDriver, d as KVEntry, f as KVErrorCode, g as KVListOptions, h as KVGetTypeMap, i as FsLiteKVStoreConfig, j as ReadonlyKVStorage, k as KVStoreName, l as KVDriverAtomicOperations, m as KVGetType, n as DatabaseKVStoreConfig, o as KVAtomicOperation, p as KVGetOptions, r as DenoKVStoreConfig, s as KVClearOptions, t as CloudflareKVStoreConfig, u as KVDriversWith, v as KVLock, w as KVOptions, x as KVLockOptions, y as KVLockAcquisition, z as ResolvedRedisKVStoreConfig } from "./types-CPDL9enF.js";
1
+ import { A as KVStoreOptions, B as ResolvedUpstashKVStoreConfig, C as KVOperation, D as KVStorage, E as KVSetOptions, F as ResolvedDenoKVStoreConfig, I as ResolvedFsLiteKVStoreConfig, L as ResolvedKVModuleOptions, M as RedisKVStoreConfig, N as ResolvedCloudflareKVStoreConfig, O as KVStoreConfig, P as ResolvedDatabaseKVStoreConfig, R as ResolvedKVStoreConfig, S as KVLockRunResult, V as UpstashKVStoreConfig, _ as KVListPage, a as InferredKVStoreConfig, b as KVLockErrorCode, c as KVDriver, d as KVEntry, f as KVErrorCode, g as KVListOptions, h as KVGetTypeMap, i as FsLiteKVStoreConfig, j as ReadonlyKVStorage, k as KVStoreName, l as KVDriverAtomicOperations, m as KVGetType, n as DatabaseKVStoreConfig, o as KVAtomicOperation, p as KVGetOptions, r as DenoKVStoreConfig, s as KVClearOptions, t as CloudflareKVStoreConfig, u as KVDriversWith, v as KVLock, w as KVOptions, x as KVLockOptions, y as KVLockAcquisition, z as ResolvedRedisKVStoreConfig } from "./types-BLxnI_rU.js";
2
2
  /** Releases every cached store. Call from the application's shutdown hook after stopping new work. */
3
3
  export declare function disposeKVStores(): Promise<void>;
4
4
  /**