@vite-hub/kv 0.7.0 → 0.9.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 (35) hide show
  1. package/README.md +2 -0
  2. package/dist/cli.js +2 -2
  3. package/dist/{cloudflare-env-Cpy3Bqdn.js → cloudflare-env-JD7uO5-i.js} +0 -4
  4. package/dist/{cloudflare-kv-hMdZQZz1.js → cloudflare-kv-CkrnHHnv.js} +4 -4
  5. package/dist/{cloudflare-kv-local-DO1g7PrA.js → cloudflare-kv-local-qb92SO8d.js} +3 -3
  6. package/dist/{config-Dr4GKknB.js → config-CZ4CZy9h.js} +4 -4
  7. package/dist/{create-storage-DrhV0F4S.js → create-storage-DeGjkDl8.js} +1 -1
  8. package/dist/{cursor-history-MzSrXXXX.js → cursor-history-KSuS5xrH.js} +1 -1
  9. package/dist/{database-DJp7XHhu.js → database-CtQO7n6H.js} +6 -6
  10. package/dist/{deno-kv-DwcTL95B.js → deno-kv-ClGWU3yO.js} +2 -2
  11. package/dist/{dev-peer-D0vOxmrD.js → dev-peer-CpFxuBAP.js} +0 -24
  12. package/dist/{driver-Cvu4k8t4.d.ts → driver-CZTAQ_07.d.ts} +1 -1
  13. package/dist/{error-diagnostics-DAi25E6F.js → error-diagnostics-C7c-Bfrl.js} +2 -2
  14. package/dist/{errors-kZRpu7Wa.js → errors-BV0MKLrD.js} +1 -1
  15. package/dist/errors.js +1 -1
  16. package/dist/{fs-lite-4ccAiYae.js → fs-lite-Bmcw5tUV.js} +124 -140
  17. package/dist/fs-lite-D33j4kWD.js +1 -0
  18. package/dist/index.js +56 -58
  19. package/dist/{operations-UeAgPdtY.js → operations-CbpFdf91.js} +17 -24
  20. package/dist/{operations-BKAO0rkO.js → operations-mNN-HppH.js} +2 -3
  21. package/dist/operations.js +3 -10
  22. package/dist/{redis-shared-DEwmedD5.js → redis-shared-DIUSIQAC.js} +1 -1
  23. package/dist/runtime/cloudflare-kv.d.ts +1 -1
  24. package/dist/runtime/cloudflare-kv.js +1 -1
  25. package/dist/runtime/cloudflare-request-env.js +1 -1
  26. package/dist/runtime/nitro-plugin.js +1 -1
  27. package/dist/runtime/redis-driver.d.ts +1 -1
  28. package/dist/runtime/redis-driver.js +3 -5
  29. package/dist/runtime/upstash-driver.d.ts +1 -1
  30. package/dist/runtime/upstash-driver.js +2 -2
  31. package/dist/{upstash-BKkqGQGE.js → upstash-CiqFI55W.js} +2 -2
  32. package/dist/vite.d.ts +1 -0
  33. package/dist/vite.js +40 -55
  34. package/package.json +4 -4
  35. package/dist/fs-lite-BMY853UK.js +0 -1
package/README.md CHANGED
@@ -19,6 +19,8 @@ Add `@upstash/redis` when you use the Upstash driver. The `redis` driver uses `i
19
19
 
20
20
  ## Minimal API
21
21
 
22
+ Install H3 2 for the route below: `pnpm add h3@^2.0.8`.
23
+
22
24
  ```ts
23
25
  // server/api/settings.put.ts
24
26
  import { kv } from "@vite-hub/kv"
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
- import { D as listSeedFiles, E as askOnTerminal, N as writeCliFailure, O as parseCliPositiveInteger, j as readViteHubDevTargetOption, k as readCliOptionValue, n as callOperationFromCli } from "./operations-BKAO0rkO.js";
1
+ import { D as listSeedFiles, E as askOnTerminal, N as writeCliFailure, O as parseCliPositiveInteger, j as readViteHubDevTargetOption, k as readCliOptionValue, n as callOperationFromCli } from "./operations-mNN-HppH.js";
2
2
  import { t as isRecord } from "./object-CAK6UYR5.js";
3
- import { n as kvErrorDiagnostics } from "./error-diagnostics-DAi25E6F.js";
3
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-C7c-Bfrl.js";
4
4
  import { t as kvDevMaximumListLimit } from "./results-emgN7uDS.js";
5
5
  import { readFile } from "node:fs/promises";
6
6
  import { extname, join, relative, resolve } from "node:path";
@@ -4,10 +4,6 @@ import { AsyncLocalStorage } from "node:async_hooks";
4
4
  const runtimeGlobal = globalThis;
5
5
  const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
6
6
  const globalEnvProbe = Symbol("vitehub.cloudflare.global-env-probe");
7
- /**
8
- * Under the Nitro Cloudflare dev server, `cloudflare:workers` exports unenv's env proxy, which reads every key from
9
- * `globalThis.__env__`. Storing that proxy in `__env__` makes it read itself, and the next read overflows the stack.
10
- */
11
7
  function readsGlobalEnv(env) {
12
8
  const scope = globalThis;
13
9
  const owned = Object.hasOwn(scope, "__env__");
@@ -1,8 +1,8 @@
1
1
  import { t as invariant } from "./invariant-Dj2R1eMr.js";
2
- import { t as getActiveCloudflareBinding } from "./cloudflare-env-Cpy3Bqdn.js";
3
- import { n as normalizeKVListPrefix, t as createKVStorage } from "./create-storage-DrhV0F4S.js";
4
- import { n as kvErrorDiagnostics } from "./error-diagnostics-DAi25E6F.js";
5
- import { n as recordCursor, t as createCursorHistory } from "./cursor-history-MzSrXXXX.js";
2
+ import { t as getActiveCloudflareBinding } from "./cloudflare-env-JD7uO5-i.js";
3
+ import { n as normalizeKVListPrefix, t as createKVStorage } from "./create-storage-DeGjkDl8.js";
4
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-C7c-Bfrl.js";
5
+ import { n as recordCursor, t as createCursorHistory } from "./cursor-history-KSuS5xrH.js";
6
6
  import { i as setItemsOneByOne, t as chunks } from "./batch-D-ib5_0P.js";
7
7
  import createDriver from "unstorage/drivers/cloudflare-kv-binding";
8
8
  // src/runtime/cloudflare-kv-limits.ts
@@ -1,6 +1,6 @@
1
- import { t as getActiveCloudflareBinding } from "./cloudflare-env-Cpy3Bqdn.js";
2
- import { a as validateCloudflareKVBatch, i as installCloudflareKVLimits, r as assertCloudflareKVWrite, t as createCloudflareDriver } from "./cloudflare-kv-hMdZQZz1.js";
3
- import { t as createFsLiteKVDriver } from "./fs-lite-4ccAiYae.js";
1
+ import { t as getActiveCloudflareBinding } from "./cloudflare-env-JD7uO5-i.js";
2
+ import { a as validateCloudflareKVBatch, i as installCloudflareKVLimits, r as assertCloudflareKVWrite, t as createCloudflareDriver } from "./cloudflare-kv-CkrnHHnv.js";
3
+ import { t as createFsLiteKVDriver } from "./fs-lite-Bmcw5tUV.js";
4
4
  import { i as setItemsOneByOne, n as getItemsOneByOne } from "./batch-D-ib5_0P.js";
5
5
  // src/runtime/cloudflare-kv-local.ts
6
6
  function cloudflareExpirationSeconds(options) {
@@ -1,6 +1,6 @@
1
1
  import { o as normalizeKey } from "./utils2-By8eee1x.js";
2
2
  import { t as isRecord } from "./object-CAK6UYR5.js";
3
- import { n as kvErrorDiagnostics } from "./error-diagnostics-DAi25E6F.js";
3
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-C7c-Bfrl.js";
4
4
  import { defu } from "defu";
5
5
  // ../internal/src/env.ts
6
6
  function trimmed(value) {
@@ -61,7 +61,7 @@ function cloudflareKVLocalBase(binding) {
61
61
  return `.vitehub/data/kv-cloudflare/${binding}`;
62
62
  }
63
63
  function readRemote(config, store) {
64
- const remote = Reflect.get(config, "remote");
64
+ const remote = config.remote;
65
65
  if (remote === void 0 || typeof remote === "boolean") return remote;
66
66
  throw kvErrorDiagnostics.KV_INVALID_REMOTE({ store });
67
67
  }
@@ -178,7 +178,7 @@ function assertKnownKVStoreKeys(store, driver, path) {
178
178
  "remote",
179
179
  ...driver ? kvDriverOptions[driver] : []
180
180
  ]);
181
- const key = Object.keys(store).find((name) => !known.has(name) && Reflect.get(store, name) !== void 0);
181
+ const key = Object.entries(store).find(([name, value]) => !known.has(name) && value !== void 0)?.[0];
182
182
  if (key === void 0) return;
183
183
  const drivers = Object.keys(kvDriverOptions).filter((name) => kvDriverOptions[name].includes(key));
184
184
  throw kvErrorDiagnostics.KV_UNKNOWN_STORE_OPTION({
@@ -208,7 +208,7 @@ function normalizeKVOptions(options, input = {}) {
208
208
  const hosting = normalizeHosting(input.hosting);
209
209
  const explicit = options;
210
210
  const hasOwnStores = options !== void 0 && Object.hasOwn(options, "stores");
211
- const stores = hasOwnStores ? Reflect.get(options, "stores", options) : void 0;
211
+ const stores = hasOwnStores && "stores" in options ? options.stores : void 0;
212
212
  if (hasOwnStores && !isRecord(stores)) throw kvErrorDiagnostics.KV_INVALID_CONFIG({ path: "kv.stores" });
213
213
  if (hasStoresConfig(options, stores)) {
214
214
  const extra = Object.entries(options ?? {}).find(([key, value]) => key !== "stores" && value !== void 0)?.[0];
@@ -1,5 +1,5 @@
1
1
  import { a as normalizeBaseKey, i as joinKeys, n as filterKeyByDepth, o as normalizeKey, r as hasDotSegment, t as filterKeyByBase } from "./utils2-By8eee1x.js";
2
- import { n as kvErrorDiagnostics } from "./error-diagnostics-DAi25E6F.js";
2
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-C7c-Bfrl.js";
3
3
  import { r as mapWithLimit } from "./batch-D-ib5_0P.js";
4
4
  // ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/_chunks/libs/destr.mjs
5
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*:/;
@@ -1,5 +1,5 @@
1
1
  import { t as invariant } from "./invariant-Dj2R1eMr.js";
2
- import { n as kvErrorDiagnostics } from "./error-diagnostics-DAi25E6F.js";
2
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-C7c-Bfrl.js";
3
3
  // src/runtime/cursor-history.ts
4
4
  const MAX_CURSOR_HISTORIES = 1024;
5
5
  const MAX_CURSORS_PER_HISTORY = 1024;
@@ -1,5 +1,5 @@
1
1
  import { t as logFailure } from "./request-log-DllKQXj7.js";
2
- import { n as kvErrorDiagnostics } from "./error-diagnostics-DAi25E6F.js";
2
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-C7c-Bfrl.js";
3
3
  import { t as chunks } from "./batch-D-ib5_0P.js";
4
4
  // src/runtime/database.ts
5
5
  /** The table that keeps the keys of every `database` store. Each store has its rows under its own `namespace`. */
@@ -58,18 +58,18 @@ async function runStatement(value, database, sql, params) {
58
58
  }
59
59
  /**
60
60
  * A SQL client over the Drizzle database of the app: postgres.js, node-postgres, PGlite, libSQL, or a D1 binding. The
61
- * Database gives the dialect. It reads `$client` on each query, because a Postgres Database on Cloudflare has a client
62
- * per request.
61
+ * Database adapters can expose these properties only on read. Read `$client` on each query because a Postgres Database
62
+ * on Cloudflare has a client per request.
63
63
  */
64
64
  function kvSqlClientFromDatabase(db, database) {
65
- const client = () => Reflect.get(db, "$client");
65
+ const client = () => db.$client;
66
66
  const kind = sqlClient(client())?.kind;
67
67
  if (!kind) throw kvErrorDiagnostics.KV_DATABASE_UNAVAILABLE({
68
68
  database,
69
69
  problem: "unsupported"
70
70
  });
71
71
  return {
72
- dialect: typeof Reflect.get(db, postgresConnectionUrl) === "function" || kind === "postgres.js" || kind === "node-postgres-or-pglite" ? "postgresql" : "sqlite",
72
+ dialect: typeof db[postgresConnectionUrl] === "function" || kind === "postgres.js" || kind === "node-postgres-or-pglite" ? "postgresql" : "sqlite",
73
73
  ...kind === "d1" ? { maxParams: d1MaxParams } : {},
74
74
  query: (sql, params) => runStatement(client(), database, sql, params)
75
75
  };
@@ -87,7 +87,7 @@ function decodeCursor(cursor) {
87
87
  if (!cursor) return void 0;
88
88
  try {
89
89
  const value = JSON.parse(decodeURIComponent(cursor));
90
- const after = typeof value === "object" && value !== null ? Reflect.get(value, "after") : void 0;
90
+ const after = typeof value === "object" && value !== null && "after" in value ? value.after : void 0;
91
91
  if (typeof after === "string") return after;
92
92
  } catch {}
93
93
  throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "invalid" });
@@ -1,6 +1,6 @@
1
1
  import { t as invariant } from "./invariant-Dj2R1eMr.js";
2
- import { n as kvErrorDiagnostics } from "./error-diagnostics-DAi25E6F.js";
3
- import { n as recordCursor, t as createCursorHistory } from "./cursor-history-MzSrXXXX.js";
2
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-C7c-Bfrl.js";
3
+ import { n as recordCursor, t as createCursorHistory } from "./cursor-history-KSuS5xrH.js";
4
4
  // src/runtime/deno-kv.ts
5
5
  const MAX_DENO_KEY_BYTES = 2048;
6
6
  function getDenoRuntime() {
@@ -1,24 +1,4 @@
1
1
  // ../internal/src/dev-peer.ts
2
- /**
3
- * Proof that a development request came from this machine, for dev servers that run the app behind a proxy.
4
- *
5
- * Nitro 3 runs the app in a worker behind an env-runner proxy. The worker never sees the client's address
6
- * (https://github.com/unjs/env-runner/issues/113):
7
- * over a Unix socket it sees none, and over TCP it sees the proxy on `127.0.0.1`. The proxy forwards a client
8
- * `x-forwarded-for` as is. The front process sees the real socket, so its Nitro dev handler removes any client copy
9
- * of {@link viteHubDevPeerHeader} and, for a loopback socket only, adds an HMAC over the method, the path, a
10
- * timestamp, and a nonce. The key is random for each process and reaches the worker only through its environment
11
- * ({@link viteHubDevPeerKeyEnv}), never through a header. The worker takes the key out of its environment, so the
12
- * processes that the app starts do not inherit it.
13
- *
14
- * A tunnel or a reverse proxy on this machine, such as `cloudflared`, `ngrok`, `tailscale serve`, or Caddy, connects
15
- * from a loopback socket too. Such a request is not from this machine, so the front process signs no request that
16
- * names another host or carries a forwarding header ({@link isViteHubForwardedRequest}). A forwarder that copies raw
17
- * TCP bytes, such as `ssh -R`, sends no such sign. Only sign-in protects a dev server behind one.
18
- *
19
- * The worker calls {@link verifyViteHubDevPeer}. Each piece of evidence is valid once, for one method and path, for a
20
- * short time. This module uses Web Crypto and no Node import, so the check also runs in Worker runtimes.
21
- */
22
2
  /** The request header that carries the evidence from the front process to the worker. */
23
3
  const viteHubDevPeerHeader = "x-vitehub-dev-peer";
24
4
  /** The environment variable that carries the per-process key from the front process to the worker. */
@@ -190,10 +170,6 @@ function isViteHubLoopbackHost(host) {
190
170
  }
191
171
  return name === "localhost" || name.endsWith(".localhost") || name === "[::1]" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(name);
192
172
  }
193
- /**
194
- * Remove a client copy of the evidence. Returns the request to sign when it came from a loopback socket, names this
195
- * machine in `Host`, and carries no forwarding header.
196
- */
197
173
  function takeSignableRequest(node) {
198
174
  delete node.headers[viteHubDevPeerHeader];
199
175
  if (!isViteHubLoopbackAddress(node.socket?.remoteAddress) || !node.method || !node.url?.startsWith("/")) return;
@@ -4,7 +4,7 @@ type KVRuntimeDriver = Driver & Record<string, unknown> & {
4
4
  validateBatch?: (items: Parameters<NonNullable<Driver["setItems"]>>[0], removals: string[], options?: TransactionOptions) => void | Promise<void>;
5
5
  /** Deletes the key when it holds the serialized `expected` value. Resolves `true` when this call deleted it. */
6
6
  deleteIfEqualsItem?: (key: string, expected: string) => Promise<boolean>;
7
- getAndDeleteItem?: <T = unknown>(key: string) => Promise<T | null>;
7
+ getAndDeleteItem?: (key: string) => Promise<string | null>;
8
8
  incrementItem?: (key: string, ttl: number) => Promise<number>;
9
9
  listKeys: (options: KVPageOptions) => Promise<KVListPage>;
10
10
  /** Writes the serialized value only when the key is missing. Resolves `true` when this call wrote it. */
@@ -95,7 +95,7 @@ const kvErrorDiagnostics = /*#__PURE__*/ defineErrors({
95
95
  },
96
96
  KV_INVALID_DRIVER: {
97
97
  why: ({ driver, renamed }) => renamed ? `\`kv.driver\` is ${driver}. ViteHub renamed this driver to "${renamed}", and it does not read ${driver}.` : `\`kv.driver\` ${driver} is not a KV driver.`,
98
- fix: ({ renamed }) => renamed ? `Set \`kv: { driver: "${renamed}" }\`, or run \`npx @vite-hub/codemods driver-key\` to rename it in every config file.` : "Set `kv.driver` to \"cloudflare\", \"database\", \"deno-kv\", \"fs-lite\", \"redis\", or \"upstash\"."
98
+ fix: ({ renamed }) => renamed ? `Set \`kv: { driver: "${renamed}" }\`.` : "Set `kv.driver` to \"cloudflare\", \"database\", \"deno-kv\", \"fs-lite\", \"redis\", or \"upstash\"."
99
99
  },
100
100
  KV_INVALID_REMOTE: {
101
101
  why: ({ store }) => `\`remote\` of the KV store "${store}" must be \`true\` or \`false\`.`,
@@ -127,7 +127,7 @@ const kvErrorDiagnostics = /*#__PURE__*/ defineErrors({
127
127
  },
128
128
  KV_UNKNOWN_STORE_OPTION: {
129
129
  why: ({ driver, key, path, stores }) => stores ? `\`${path}\` has \`stores\`, so it takes no other key, and it has \`${key}\`.` : driver ? `\`${path}.${key}\` is not an option of the \`${driver}\` KV driver.` : `\`${path}.${key}\` is not an option of a KV store without \`driver\`. ViteHub picks the driver from the host and would ignore it.`,
130
- fix: ({ drivers, driver, key, stores }) => stores ? `Move \`${key}\` into a store under \`stores\`, for example \`stores: { default: { driver: "fs-lite" } }\`.` : drivers.length && !driver ? `Set \`driver\` to ${drivers.map((name) => `"${name}"`).join(" or ")}, which reads \`${key}\`. ViteHub renamed some drivers, so run \`npx @vite-hub/codemods driver-key\` when the config had an old driver name.` : drivers.length ? `Remove \`${key}\`, or set \`driver\` to ${drivers.map((name) => `"${name}"`).join(" or ")}, which reads it.` : `Remove \`${key}\`. A KV store takes \`driver\`, \`remote\`, and the options of its driver.`
130
+ fix: ({ drivers, driver, key, stores }) => stores ? `Move \`${key}\` into a store under \`stores\`, for example \`stores: { default: { driver: "fs-lite" } }\`.` : drivers.length && !driver ? `Set \`driver\` to ${drivers.map((name) => `"${name}"`).join(" or ")}, which reads \`${key}\`. ViteHub renamed some drivers, so replace an old driver name with one of these.` : drivers.length ? `Remove \`${key}\`, or set \`driver\` to ${drivers.map((name) => `"${name}"`).join(" or ")}, which reads it.` : `Remove \`${key}\`. A KV store takes \`driver\`, \`remote\`, and the options of its driver.`
131
131
  },
132
132
  KV_INVALID_COUNTER: {
133
133
  why: "kv.increment() needs a stored integer below 9007199254740991. The value did not change.",
@@ -1,5 +1,5 @@
1
1
  import { o as normalizeKey } from "./utils2-By8eee1x.js";
2
- import { n as kvErrorDiagnostics, t as kvConfigErrorCodes } from "./error-diagnostics-DAi25E6F.js";
2
+ import { n as kvErrorDiagnostics, t as kvConfigErrorCodes } from "./error-diagnostics-C7c-Bfrl.js";
3
3
  import { isRuntimeDiagnostic, parseDuration, toResultError } from "@vite-hub/runtime";
4
4
  // src/runtime/ttl.ts
5
5
  /**
package/dist/errors.js CHANGED
@@ -1 +1 @@
1
- export { t as kvClearOptionsError, n as kvInvalidKeyError, r as kvInvalidLimitError, i as kvKeyLimitCodes, a as kvListLimitInvalid, o as kvResult, s as kvSetCodes, c as kvSetTTL, l as kvStoreNotFoundError, p as kvStoreWithMode, u as kvUnsupportedOperationError, d as kvWriteLimitCodes, f as listKVKeys } from "./errors-kZRpu7Wa.js";
1
+ export { t as kvClearOptionsError, n as kvInvalidKeyError, r as kvInvalidLimitError, i as kvKeyLimitCodes, a as kvListLimitInvalid, o as kvResult, s as kvSetCodes, c as kvSetTTL, l as kvStoreNotFoundError, p as kvStoreWithMode, u as kvUnsupportedOperationError, d as kvWriteLimitCodes, f as listKVKeys } from "./errors-BV0MKLrD.js";
@@ -1,4 +1,4 @@
1
- import { n as kvErrorDiagnostics } from "./error-diagnostics-DAi25E6F.js";
1
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-C7c-Bfrl.js";
2
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";
@@ -249,9 +249,8 @@ function ttlMilliseconds(ttl) {
249
249
  return ms;
250
250
  }
251
251
  function setExpiry(options) {
252
- const ttl = options && typeof options === "object" ? Reflect.get(options, "ttl") : void 0;
253
- if (ttl === void 0 || ttl === null || ttl === 0) return;
254
- if (typeof ttl !== "number") throw kvErrorDiagnostics.KV_INVALID_TTL();
252
+ const ttl = options?.ttl;
253
+ if (ttl === void 0 || ttl === 0) return;
255
254
  return Date.now() + ttlMilliseconds(ttl);
256
255
  }
257
256
  async function createFsLiteKVDriver(options) {
@@ -285,51 +284,10 @@ async function createFsLiteKVDriver(options) {
285
284
  await rm(expiryPath(key), { force: true });
286
285
  return false;
287
286
  }
288
- const driver = createDriver(options);
289
- const { getItem, getItemRaw, getMeta, hasItem, removeItem, setItem, setItemRaw } = driver;
290
- driver.getItem = async (key, operationOptions) => {
291
- if (!await live(key)) return null;
292
- const value = await getItem(fileName(key), operationOptions);
293
- if (value instanceof Error) throw value;
294
- return value;
295
- };
296
- driver.getItemRaw = async (key, operationOptions) => {
297
- if (!await live(key)) return null;
298
- const value = await getItemRaw?.(fileName(key), operationOptions);
299
- if (value instanceof Error) throw value;
300
- return value;
301
- };
302
- driver.getMeta = async (key, operationOptions) => await live(key) ? getMeta?.(fileName(key), operationOptions) ?? null : null;
303
- driver.setItem = async (key, value, operationOptions) => {
304
- await writeExpiry(key, setExpiry(operationOptions));
305
- return setItem?.(fileName(key), value, operationOptions);
306
- };
307
- driver.setItemRaw = async (key, value, operationOptions) => {
308
- await writeExpiry(key, setExpiry(operationOptions));
309
- return setItemRaw?.(fileName(key), value, operationOptions);
310
- };
311
- driver.removeItem = async (key, operationOptions) => {
312
- await rm(expiryPath(key), { force: true });
313
- await removeItem?.(fileName(key), operationOptions);
314
- };
315
- driver.clear = (base = "") => queueUnderFolderLock(layout, async () => {
316
- const entries = await readdir(root).catch((error) => {
317
- if (hasCode(error, "ENOENT")) return [];
318
- throw error;
319
- });
320
- for (const entry of entries) {
321
- const key = keyOf(entry);
322
- if (key !== void 0 && key.startsWith(base)) {
323
- await rm(join(root, entry), {
324
- force: true,
325
- recursive: true
326
- });
327
- await rm(expiryPath(key), { force: true });
328
- }
329
- }
330
- }, "single");
287
+ const base = createDriver(options);
288
+ const locked = (operation) => (...args) => synchronized(() => operation(...args));
331
289
  const hasLiveItem = async (key, operationOptions) => {
332
- if (!await hasItem(fileName(key), operationOptions)) return false;
290
+ if (!await base.hasItem(fileName(key), operationOptions)) return false;
333
291
  if (!await live(key)) return false;
334
292
  try {
335
293
  return (await stat(join(root, fileName(key)))).isFile();
@@ -338,28 +296,9 @@ async function createFsLiteKVDriver(options) {
338
296
  throw error;
339
297
  }
340
298
  };
341
- driver.hasItem = hasLiveItem;
342
- driver.setIfAbsentItem = async (key, value, ttl) => {
343
- const expiresAt = ttl === void 0 ? void 0 : Date.now() + ttlMilliseconds(ttl);
344
- if (await hasLiveItem(key, {})) return false;
345
- const path = join(root, fileName(key));
346
- await mkdir(root, { recursive: true });
347
- const temporary = join(root, `.unstorage-tmp-${randomUUID()}`);
348
- await writeFile(temporary, value, "utf8");
349
- try {
350
- await link(temporary, path);
351
- await writeExpiry(key, expiresAt);
352
- return true;
353
- } catch (error) {
354
- if (hasCode(error, "EEXIST") && (await stat(path)).isFile()) return false;
355
- throw error;
356
- } finally {
357
- await rm(temporary, { force: true });
358
- }
359
- };
360
299
  async function readLiveText(key) {
361
300
  if (!await live(key)) return null;
362
- const value = await getItem(fileName(key), {});
301
+ const value = await base.getItem(fileName(key), {});
363
302
  if (value instanceof Error) throw value;
364
303
  return typeof value === "string" ? value : null;
365
304
  }
@@ -367,33 +306,6 @@ async function createFsLiteKVDriver(options) {
367
306
  await unlink(join(root, fileName(key)));
368
307
  await rm(expiryPath(key), { force: true });
369
308
  }
370
- driver.getAndDeleteItem = async (key) => {
371
- const text = await readLiveText(key);
372
- if (text === null) return null;
373
- await deleteKey(key);
374
- return text;
375
- };
376
- driver.incrementItem = async (key, ttl) => {
377
- const expiresAt = Date.now() + ttlMilliseconds(ttl);
378
- const text = await readLiveText(key);
379
- const counter = text === null ? 0 : canonicalInteger.test(text) ? Number(text) : NaN;
380
- if (!(counter >= Number.MIN_SAFE_INTEGER - 1 && counter < Number.MAX_SAFE_INTEGER)) throw kvErrorDiagnostics.KV_INVALID_COUNTER();
381
- const next = counter + 1;
382
- const temporary = join(root, `.unstorage-tmp-${randomUUID()}`);
383
- try {
384
- await writeFile(temporary, String(next));
385
- if (text === null) await writeExpiry(key, expiresAt);
386
- await rename(temporary, join(root, fileName(key)));
387
- } finally {
388
- await rm(temporary, { force: true });
389
- }
390
- return next;
391
- };
392
- driver.deleteIfEqualsItem = async (key, expected) => {
393
- if (await readLiveText(key) !== expected) return false;
394
- await deleteKey(key);
395
- return true;
396
- };
397
309
  async function* walk() {
398
310
  let entries;
399
311
  try {
@@ -408,57 +320,129 @@ async function createFsLiteKVDriver(options) {
408
320
  yield key !== void 0 && await synchronized(() => live(key)) ? key : void 0;
409
321
  }
410
322
  }
411
- driver.getKeys = async () => {
412
- const keys = [];
413
- for await (const key of walk()) if (key !== void 0) keys.push(key);
414
- return keys;
415
- };
416
323
  const expired = () => kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "expired" });
417
324
  const continuations = createKVContinuations({
418
325
  expired,
419
326
  release: (iterator) => iterator.return(void 0)
420
327
  });
421
- const dispose = driver.dispose;
422
- driver.dispose = async () => {
423
- try {
424
- await continuations.dispose();
425
- } finally {
426
- await dispose?.call(driver);
427
- }
428
- };
429
- driver.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);
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
+ };
440
445
  }
441
- return {
442
- keys,
443
- cursor: await continuations.retain(iterator)
444
- };
445
446
  };
446
- for (const name of [
447
- "getItem",
448
- "getItemRaw",
449
- "getMeta",
450
- "hasItem",
451
- "setItem",
452
- "setItemRaw",
453
- "removeItem",
454
- "setIfAbsentItem",
455
- "getAndDeleteItem",
456
- "incrementItem",
457
- "deleteIfEqualsItem"
458
- ]) {
459
- const operation = driver[name];
460
- if (operation) Reflect.set(driver, name, (...args) => synchronized(async () => Reflect.apply(operation, driver, args)));
461
- }
462
- return driver;
463
447
  }
464
448
  export { createFsLiteKVDriver as t };
@@ -0,0 +1 @@
1
+ export { t as default } from "./fs-lite-Bmcw5tUV.js";