@vite-hub/kv 0.3.1 → 0.5.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 (50) hide show
  1. package/README.md +19 -13
  2. package/dist/{cli-DpPhz_Ek.d.ts → cli-CLomw9ml.d.ts} +1 -0
  3. package/dist/cli.d.ts +1 -1
  4. package/dist/cli.js +24 -12
  5. package/dist/{cloudflare-env-lOtHHsgP.js → cloudflare-env-Dl349h_9.js} +2 -1
  6. package/dist/{cloudflare-kv-BIEUFzRT.js → cloudflare-kv-DQJhmGof.js} +22 -10
  7. package/dist/{cloudflare-kv-local-BBw3ZT1K.js → cloudflare-kv-local-COjgHweC.js} +3 -7
  8. package/dist/{config-BXEVoZE3.js → config-pfyPiPrI.js} +65 -28
  9. package/dist/{create-storage-BGsrQKw3.js → create-storage-DQ1BbFqH.js} +5 -5
  10. package/dist/{cursor-history-BqIQePNP.js → cursor-history-CAT4mpP1.js} +7 -3
  11. package/dist/{deno-kv-BM9mYdUp.js → deno-kv-Cf0ZveeN.js} +43 -7
  12. package/dist/driver-Du6Eh9p2.d.ts +47 -0
  13. package/dist/{error-diagnostics-BxqvtEIb.js → error-diagnostics-C4VTHInS.js} +16 -4
  14. package/dist/errors-BpiM-Vmh.js +125 -0
  15. package/dist/errors.d.ts +13 -1
  16. package/dist/errors.js +2 -2
  17. package/dist/{fs-lite-BLZId9_P.js → fs-lite-BTcBUP6B.js} +1 -1
  18. package/dist/fs-lite-C8yXCVDM.js +2 -0
  19. package/dist/index.d.ts +2 -2
  20. package/dist/index.js +39 -52
  21. package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-CI2PJGqu.d.ts} +13 -2
  22. package/dist/{operations-Ch-gKaey.js → operations-CqKs7Ykc.js} +24 -45
  23. package/dist/{operations-B-WZ7P1h.js → operations-nAaONxzh.js} +273 -231
  24. package/dist/operations.d.ts +2 -2
  25. package/dist/operations.js +4 -3
  26. package/dist/out-BbXG-yVX.js +21755 -0
  27. package/dist/{redis-shared-E5mahECF.js → redis-shared-1M0IaguQ.js} +1 -1
  28. package/dist/request-log-Dj9Vw7qG.js +105 -0
  29. package/dist/{results-p7nPCnaJ.js → results-D6jfPtCk.js} +0 -1
  30. package/dist/runtime/cloudflare-kv.d.ts +1 -1
  31. package/dist/runtime/cloudflare-kv.js +1 -1
  32. package/dist/runtime/cloudflare-request-env.js +1 -1
  33. package/dist/runtime/database.d.ts +2 -0
  34. package/dist/{database-72Jk3VVk.js → runtime/database.js} +68 -37
  35. package/dist/runtime/nitro-plugin.js +12 -5
  36. package/dist/runtime/redis-driver.d.ts +2 -2
  37. package/dist/runtime/redis-driver.js +2 -5
  38. package/dist/runtime/unstorage-driver.js +6 -2
  39. package/dist/runtime/upstash-driver.d.ts +2 -2
  40. package/dist/runtime/upstash-driver.js +2 -6
  41. package/dist/{types-DEiKew_3.d.ts → types-Cp6IBhSN.d.ts} +36 -37
  42. package/dist/{upstash-DDlqTttY.js → upstash-5sTbIR35.js} +2 -2
  43. package/dist/virtual-module.d.ts +1 -0
  44. package/dist/vite.d.ts +21 -6
  45. package/dist/vite.js +2738 -415
  46. package/package.json +10 -5
  47. package/dist/driver-BwxgaQ-f.d.ts +0 -15
  48. package/dist/errors-DbwufFZp.js +0 -60
  49. package/dist/fs-lite-RAoxu8L0.js +0 -2
  50. package/dist/main-F3Y22_uV.js +0 -2353
@@ -1,4 +1,4 @@
1
- import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
1
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-C4VTHInS.js";
2
2
  //#region src/runtime/redis-shared.ts
3
3
  const redisIncrementScript = `
4
4
  local existed = redis.call('EXISTS', KEYS[1])
@@ -0,0 +1,105 @@
1
+ //#region ../internal/src/runtime/request-log.ts
2
+ function isRequestLog(value) {
3
+ return value !== null && typeof value === "object" && typeof Reflect.get(value, "set") === "function" && typeof Reflect.get(value, "warn") === "function" && typeof Reflect.get(value, "error") === "function";
4
+ }
5
+ function contextLog(value) {
6
+ const context = value !== null && typeof value === "object" ? Reflect.get(value, "context") : void 0;
7
+ return context !== null && typeof context === "object" ? Reflect.get(context, "log") : void 0;
8
+ }
9
+ /**
10
+ * The evlog request logger of a request, or `undefined` when the app does not register evlog. Pass a Nitro v3 event
11
+ * (evlog sets `event.req.context.log`) or its `Request` (`request.context.log`).
12
+ */
13
+ function requestLog(input) {
14
+ const log = contextLog(input !== null && typeof input === "object" ? Reflect.get(input, "req") : void 0) ?? contextLog(input);
15
+ return isRequestLog(log) ? log : void 0;
16
+ }
17
+ /**
18
+ * The `Symbol.for()` key of the bridge on `globalThis`. Every bundled copy of this module and the Nitro plugin that
19
+ * `vitehub()` generates use the same key.
20
+ */
21
+ const evlogBridgeKey = "vitehub.evlog";
22
+ function isEvlogBridge(value) {
23
+ return value !== null && typeof value === "object" && typeof Reflect.get(value, "createLogger") === "function";
24
+ }
25
+ /** The evlog bridge of this process, or `undefined` when the app does not register evlog. */
26
+ function evlogBridge() {
27
+ const bridge = globalThis[Symbol.for(evlogBridgeKey)];
28
+ return isEvlogBridge(bridge) ? bridge : void 0;
29
+ }
30
+ function activeBridge() {
31
+ const bridge = evlogBridge();
32
+ try {
33
+ return bridge && bridge.isEnabled?.() !== false ? bridge : void 0;
34
+ } catch {
35
+ return;
36
+ }
37
+ }
38
+ /**
39
+ * A short name for the cause of a failure, safe to put in a log field: the string `code` of the error, such as
40
+ * `ENOSPC` or a ViteHub diagnostic code, else its class name. Never the message, which can hold paths or values.
41
+ */
42
+ function errorCode(error) {
43
+ if (error === null || typeof error !== "object") return void 0;
44
+ const code = Reflect.get(error, "code");
45
+ if (typeof code === "string" && code) return code;
46
+ const name = Reflect.get(error, "name");
47
+ return typeof name === "string" && name && name !== "Error" ? name : void 0;
48
+ }
49
+ /**
50
+ * Emits one evlog event of its own, outside a request's wide event. The event also reaches the app's `evlog:drain`
51
+ * hooks. Returns `false` when the app does not register evlog or turned it off, and never throws.
52
+ */
53
+ function emitLogEvent(event) {
54
+ const bridge = activeBridge();
55
+ if (!bridge) return false;
56
+ try {
57
+ const log = bridge.createLogger({
58
+ action: event.field,
59
+ message: event.message,
60
+ [event.field]: event.fields
61
+ }, event.waitUntil ? { waitUntil: event.waitUntil } : void 0);
62
+ if (event.level === "error") log.error(event.withError && event.error instanceof Error ? event.error : event.message);
63
+ else log[event.level](event.message);
64
+ const emitted = log.emit();
65
+ if (emitted && bridge.drain) {
66
+ const drained = Promise.resolve().then(() => bridge.drain?.(emitted)).catch((error) => {
67
+ console.error("[evlog] drain failed:", error);
68
+ });
69
+ event.waitUntil?.(drained);
70
+ }
71
+ return true;
72
+ } catch {
73
+ return false;
74
+ }
75
+ }
76
+ /**
77
+ * Logs a failure that the caller survives, with a fixed message and the `code` of the error. With the evlog request
78
+ * logger of `request`, it replaces `[field]` on the request's wide event and adds a warning. Pass `request` only when the
79
+ * request has not answered yet: evlog drops fields after it emits the wide event. Otherwise it emits an event of its
80
+ * own. Without evlog, or with evlog off, it calls `fallback`, which prints to the server console as before. It never
81
+ * throws.
82
+ */
83
+ function logFailure(failure, fallback) {
84
+ const code = errorCode(failure.error);
85
+ const fields = {
86
+ ...failure.fields,
87
+ ...code ? { code } : {}
88
+ };
89
+ const log = failure.request !== void 0 && activeBridge() ? requestLog(failure.request) : void 0;
90
+ if (log) try {
91
+ log.set({ [failure.field]: false });
92
+ log.warn(failure.message, { [failure.field]: fields });
93
+ return;
94
+ } catch {}
95
+ if (emitLogEvent({
96
+ ...failure,
97
+ fields,
98
+ level: failure.level ?? "warn"
99
+ })) return;
100
+ try {
101
+ fallback();
102
+ } catch {}
103
+ }
104
+ //#endregion
105
+ export { logFailure as t };
@@ -1,5 +1,4 @@
1
1
  //#region src/results.ts
2
- /** Results of the `kv.*` operations, as `vitehub kv` and the Console read them. */
3
2
  /** Largest `--limit` of one `list` page. */
4
3
  const kvDevMaximumListLimit = 1e3;
5
4
  //#endregion
@@ -1,4 +1,4 @@
1
- import { t as KVRuntimeDriver } from "../driver-BwxgaQ-f.js";
1
+ import { t as KVRuntimeDriver } from "../driver-Du6Eh9p2.js";
2
2
  //#region src/runtime/cloudflare-kv.d.ts
3
3
  declare function createCloudflareDriver(options: Record<string, unknown>): KVRuntimeDriver;
4
4
  export declare function createCloudflareKVStorage(options: Record<string, unknown>): unknown;
@@ -1,2 +1,2 @@
1
- import { n as createCloudflareKVStorage, t as createCloudflareDriver } from "../cloudflare-kv-BIEUFzRT.js";
1
+ import { n as createCloudflareKVStorage, t as createCloudflareDriver } from "../cloudflare-kv-DQJhmGof.js";
2
2
  export { createCloudflareKVStorage, createCloudflareDriver as default };
@@ -1,4 +1,4 @@
1
- import { n as installCloudflareRequestEnv } from "../cloudflare-env-lOtHHsgP.js";
1
+ import { r as installCloudflareRequestEnv } from "../cloudflare-env-Dl349h_9.js";
2
2
  //#region src/runtime/cloudflare-request-env.ts
3
3
  /**
4
4
  * Nitro middleware for Cloudflare KV. A Cloudflare KV store reads its binding from the active env, and only the request
@@ -0,0 +1,2 @@
1
+ import { a as createDatabaseKVDriver, i as KVSqlParam, n as KVDatabases, o as kvSqlClientFromDatabase, r as KVSqlClient, s as kvTable } from "../driver-Du6Eh9p2.js";
2
+ export { KVDatabases, KVSqlClient, KVSqlParam, createDatabaseKVDriver as default, kvSqlClientFromDatabase, kvTable };
@@ -1,39 +1,60 @@
1
- import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
2
- import { t as chunks } from "./batch--v0ri69O.js";
1
+ import { n as kvErrorDiagnostics } from "../error-diagnostics-C4VTHInS.js";
2
+ import { t as d1PrimaryClient } from "../cloudflare-env-Dl349h_9.js";
3
+ import { t as chunks } from "../batch--v0ri69O.js";
4
+ import { t as logFailure } from "../request-log-Dj9Vw7qG.js";
3
5
  //#region src/runtime/database.ts
4
6
  /** The table that keeps the keys of every `database` store. Each store has its rows under its own `namespace`. */
5
7
  const kvTable = "vitehub_kv";
8
+ function isD1HttpClient(value) {
9
+ return typeof value === "object" && value !== null && Reflect.get(value, "protocol") === "d1-http" && hasMethod(value, "query");
10
+ }
11
+ function isRow(value) {
12
+ return typeof value === "object" && value !== null && !Array.isArray(value);
13
+ }
14
+ function objectRows(rows) {
15
+ if (rows.every(isRow)) return rows;
16
+ throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Cloudflare D1 returned rows without column names." });
17
+ }
18
+ const d1MaxParameters = 100;
6
19
  function hasMethod(value, name) {
7
20
  if ((typeof value !== "object" || value === null) && typeof value !== "function") return false;
8
21
  return typeof Reflect.get(value, name) === "function";
9
22
  }
10
23
  /**
11
- * A SQL client over the Drizzle database of the app. It reads `$client` on each query, because a Postgres Database on
12
- * Cloudflare has a client per request.
24
+ * A SQL client over the Drizzle database of the app: postgres.js, libSQL, primary Cloudflare D1, or D1 over HTTP. It resolves
25
+ * the client on each query because the Database connection can belong to the request.
13
26
  */
14
27
  function kvSqlClientFromDatabase(db, database) {
15
- const client = () => Reflect.get(db, "$client");
28
+ const client = () => Reflect.get(db, d1PrimaryClient) ?? Reflect.get(db, "$client");
16
29
  const first = client();
17
- const dialect = hasMethod(first, "unsafe") ? "postgresql" : hasMethod(first, "execute") ? "sqlite" : void 0;
18
- if (!dialect) throw kvErrorDiagnostics.KV_DATABASE_UNAVAILABLE({
30
+ if (hasMethod(first, "unsafe")) return {
31
+ dialect: "postgresql",
32
+ query: async (sql, params) => await client().unsafe(sql, params)
33
+ };
34
+ if (hasMethod(first, "execute")) return {
35
+ dialect: "sqlite",
36
+ query: async (sql, params) => (await client().execute({
37
+ sql,
38
+ args: params
39
+ })).rows
40
+ };
41
+ if (hasMethod(first, "prepare") && hasMethod(first, "batch")) return {
42
+ dialect: "sqlite",
43
+ maxParameters: d1MaxParameters,
44
+ query: async (sql, params) => (await client().prepare(sql).bind(...params).all()).results
45
+ };
46
+ if (isD1HttpClient(first)) return {
47
+ dialect: "sqlite",
48
+ maxParameters: d1MaxParameters,
49
+ query: async (sql, params) => objectRows(await client().query(sql, params, "write"))
50
+ };
51
+ throw kvErrorDiagnostics.KV_DATABASE_UNAVAILABLE({
19
52
  database,
20
53
  problem: "unsupported"
21
54
  });
22
- return {
23
- dialect,
24
- async query(sql, params) {
25
- if (dialect === "postgresql") return await client().unsafe(sql, params);
26
- return (await client().execute({
27
- sql,
28
- args: params
29
- })).rows;
30
- }
31
- };
32
55
  }
33
- /** Once cleanup catches up, wait this long before checking for newly expired keys. */
34
56
  const sweepIntervalMs = 6e4;
35
57
  const sweepBatchSize = 1e3;
36
- /** Rows per batch statement. It keeps the parameters below SQLite's oldest limit of 999. */
37
58
  const batchRows = 200;
38
59
  function ttlMilliseconds(ttl) {
39
60
  if (!Number.isFinite(ttl) || ttl <= 0) throw kvErrorDiagnostics.KV_INVALID_TTL();
@@ -53,15 +74,15 @@ function decodeCursor(cursor) {
53
74
  /**
54
75
  * KV in a table of the app's Database. Each atomic operation is one statement, so two servers that write one key at
55
76
  * the same time get one winner. Expiry uses the clock of the Database. Works on Postgres and on SQLite 3.35 or later,
56
- * such as libSQL.
77
+ * such as libSQL and Cloudflare D1. `table` defaults to `vitehub_kv`. A caller that passes another table keeps its rows
78
+ * out of reach of every KV store.
57
79
  */
58
- function createDatabaseKVDriver(options, connect) {
59
- const table = kvTable;
80
+ function createDatabaseKVDriver(options, connect, table = kvTable) {
60
81
  const namespace = options.namespace;
61
82
  let pending;
62
83
  let sweptAt = 0;
63
84
  let sweeping = false;
64
- let sweepWarned = false;
85
+ let sweepFailing = false;
65
86
  async function ready() {
66
87
  pending ??= (async () => {
67
88
  const client = await connect();
@@ -83,7 +104,6 @@ function createDatabaseKVDriver(options, connect) {
83
104
  });
84
105
  return pending;
85
106
  }
86
- /** Runs SQL written with `?` placeholders, which become `$1`, `$2`, ... on Postgres. `{now}` is the Database clock in ms. */
87
107
  async function query(sql, params) {
88
108
  const client = await ready();
89
109
  const now = client.dialect === "postgresql" ? "(extract(epoch from statement_timestamp()) * 1000)::bigint" : "cast((julianday('now') - 2440587.5) * 86400000 as integer)";
@@ -92,28 +112,35 @@ function createDatabaseKVDriver(options, connect) {
92
112
  return client.query(client.dialect === "postgresql" ? text.replace(/\?/g, () => `$${++index}`) : text, params);
93
113
  }
94
114
  const live = `(expires_at is null or expires_at > {now})`;
95
- /**
96
- * Deletes expired rows of this namespace in background batches. A full batch lets the next write sweep again;
97
- * otherwise cleanup waits a minute. Reads already skip expired rows. A failed sweep, for example on a lock
98
- * timeout, does not fail the write that runs it. It warns once and runs again a minute later.
99
- */
100
115
  async function sweep() {
101
116
  if (sweeping || Date.now() - sweptAt < sweepIntervalMs) return;
102
117
  sweeping = true;
103
118
  sweptAt = Date.now();
104
119
  try {
105
120
  const { dialect } = await ready();
106
- if ((await query(`delete from ${table} where (namespace, "key") in (
121
+ const rows = await query(`delete from ${table} where (namespace, "key") in (
107
122
  select namespace, "key" from ${table} where namespace = ? and expires_at <= {now} limit ${sweepBatchSize}${dialect === "postgresql" ? " for update skip locked" : ""}
108
- ) returning 1`, [namespace])).length === sweepBatchSize) sweptAt = 0;
123
+ ) returning 1`, [namespace]);
124
+ sweepFailing = false;
125
+ if (rows.length === sweepBatchSize) sweptAt = 0;
109
126
  } catch (error) {
110
- if (!sweepWarned) console.warn(`[vitehub] KV could not delete expired rows from ${table}. It tries again every minute.`, error);
111
- sweepWarned = true;
127
+ if (!sweepFailing) logFailure({
128
+ field: "kv",
129
+ fields: {
130
+ op: "expiry-sweep",
131
+ driver: "database",
132
+ namespace
133
+ },
134
+ message: "KV could not delete expired rows",
135
+ error
136
+ }, () => {
137
+ console.warn(`[vitehub] KV could not delete expired rows from ${table}. It tries again every minute.`, error);
138
+ });
139
+ sweepFailing = true;
112
140
  } finally {
113
141
  sweeping = false;
114
142
  }
115
143
  }
116
- /** Matches keys that start with `prefix`. `substr()` counts characters on both dialects, unlike `LIKE` on SQLite, which ignores case. */
117
144
  function prefixFilter(prefix) {
118
145
  if (!prefix) return ["", []];
119
146
  return [` and substr("key", 1, ?) = ?`, [[...prefix].length, prefix]];
@@ -122,13 +149,17 @@ function createDatabaseKVDriver(options, connect) {
122
149
  const [filter, params] = prefixFilter(prefix);
123
150
  return (await query(`select "key" from ${table} where namespace = ? and ${live}${filter} order by "key"`, [namespace, ...params])).map((row) => String(row.key));
124
151
  }
152
+ async function rowsPerStatement(parametersPerRow, fixedParameters = 0) {
153
+ const { maxParameters } = await ready();
154
+ return maxParameters === void 0 ? batchRows : Math.min(batchRows, Math.floor((maxParameters - fixedParameters) / parametersPerRow));
155
+ }
125
156
  async function upsert(items, setOptions) {
126
157
  sweep();
127
158
  const ttl = setOptions?.ttl;
128
159
  if (ttl !== void 0 && ttl !== null && ttl !== 0 && typeof ttl !== "number") throw kvErrorDiagnostics.KV_INVALID_TTL();
129
160
  const ms = typeof ttl === "number" && ttl !== 0 ? ttlMilliseconds(ttl) : void 0;
130
161
  const row = `(?, ?, ?, ${ms === void 0 ? "null" : "{now} + cast(? as bigint)"})`;
131
- for (const batch of chunks(items, batchRows)) await query(`insert into ${table} (namespace, "key", value, expires_at) values ${batch.map(() => row).join(", ")}
162
+ for (const batch of chunks(items, await rowsPerStatement(ms === void 0 ? 3 : 4))) await query(`insert into ${table} (namespace, "key", value, expires_at) values ${batch.map(() => row).join(", ")}
132
163
  on conflict (namespace, "key") do update set value = excluded.value, expires_at = excluded.expires_at`, batch.flatMap((item) => ms === void 0 ? [
133
164
  namespace,
134
165
  item.key,
@@ -152,7 +183,7 @@ function createDatabaseKVDriver(options, connect) {
152
183
  },
153
184
  async getItems(items) {
154
185
  const values = /* @__PURE__ */ new Map();
155
- for (const batch of chunks([...new Set(items.map((item) => item.key))], batchRows)) {
186
+ for (const batch of chunks([...new Set(items.map((item) => item.key))], await rowsPerStatement(1, 1))) {
156
187
  const rows = await query(`select "key", value from ${table} where namespace = ? and "key" in (${batch.map(() => "?").join(", ")}) and ${live}`, [namespace, ...batch]);
157
188
  for (const row of rows) values.set(String(row.key), String(row.value));
158
189
  }
@@ -247,4 +278,4 @@ function createDatabaseKVDriver(options, connect) {
247
278
  };
248
279
  }
249
280
  //#endregion
250
- export { createDatabaseKVDriver as default, kvSqlClientFromDatabase };
281
+ export { createDatabaseKVDriver as default, kvSqlClientFromDatabase, kvTable };
@@ -1,10 +1,10 @@
1
- import { t as kvInferredStoreNotice } from "../config-BXEVoZE3.js";
1
+ import { t as kvInferredStoreNotice } from "../config-pfyPiPrI.js";
2
+ import { t as logFailure } from "../request-log-Dj9Vw7qG.js";
2
3
  import { disposeKVStores } from "@vite-hub/kv";
3
4
  //#region src/runtime/nitro-plugin.ts
4
- /** Prints the driver that each inferred store uses in this process. */
5
5
  async function logInferredStores() {
6
- const { kv } = await import("#vitehub/kv/config");
7
- if (!kv) return;
6
+ const { durabilityReportsStores, kv } = await import("#vitehub/kv/config");
7
+ if (!kv || durabilityReportsStores) return;
8
8
  for (const [name, store] of Object.entries(kv.stores ?? { default: kv.store })) {
9
9
  const notice = kvInferredStoreNotice(name, store);
10
10
  if (notice) console.info(notice);
@@ -16,7 +16,14 @@ async function logInferredStores() {
16
16
  */
17
17
  function kvNitroPlugin(nitroApp) {
18
18
  nitroApp.hooks.hook("close", disposeKVStores);
19
- logInferredStores().catch((error) => console.warn("[vitehub] Could not read the KV configuration.", error));
19
+ logInferredStores().catch((error) => {
20
+ logFailure({
21
+ field: "kv",
22
+ fields: { op: "read-config" },
23
+ message: "KV could not read its configuration",
24
+ error
25
+ }, () => console.warn("[vitehub] Could not read the KV configuration.", error));
26
+ });
20
27
  }
21
28
  //#endregion
22
29
  export { kvNitroPlugin as default };
@@ -1,5 +1,5 @@
1
- import { L as ResolvedRedisKVStoreConfig } from "../types-DEiKew_3.js";
2
- import { t as KVRuntimeDriver } from "../driver-BwxgaQ-f.js";
1
+ import { z as ResolvedRedisKVStoreConfig } from "../types-Cp6IBhSN.js";
2
+ import { t as KVRuntimeDriver } from "../driver-Du6Eh9p2.js";
3
3
  //#region src/runtime/redis-driver.d.ts
4
4
  /** The URL of a store: `env:<NAME>` reads the variable now, so a build never holds the URL of its server. */
5
5
  export declare function resolveRedisUrl(url: string, env?: Record<string, string | undefined>): string;
@@ -1,8 +1,8 @@
1
1
  import { t as invariant } from "../invariant-DolT9EEx.js";
2
- import { n as kvErrorDiagnostics } from "../error-diagnostics-BxqvtEIb.js";
2
+ import { n as kvErrorDiagnostics } from "../error-diagnostics-C4VTHInS.js";
3
3
  import { o as normalizeKey } from "../utils2-FozcTsmb.js";
4
4
  import { t as chunks } from "../batch--v0ri69O.js";
5
- import { a as redisIncrementScript, i as redisIncrementResult, n as escapeRedisGlob, o as redisTTLSeconds, r as redisDeleteIfEqualsScript, t as createPortableRedisKeyLister } from "../redis-shared-E5mahECF.js";
5
+ import { a as redisIncrementScript, i as redisIncrementResult, n as escapeRedisGlob, o as redisTTLSeconds, r as redisDeleteIfEqualsScript, t as createPortableRedisKeyLister } from "../redis-shared-1M0IaguQ.js";
6
6
  import { Redis } from "ioredis";
7
7
  //#region src/runtime/redis-driver.ts
8
8
  /** The URL of a store: `env:<NAME>` reads the variable now, so a build never holds the URL of its server. */
@@ -16,19 +16,16 @@ function resolveRedisUrl(url, env = globalThis.process?.env ?? {}) {
16
16
  });
17
17
  return value;
18
18
  }
19
- /** Milliseconds for `SET PX`, which keeps fractional TTLs, as the other drivers do. */
20
19
  function ttlMilliseconds(ttl) {
21
20
  redisTTLSeconds(ttl);
22
21
  return Math.ceil(ttl * 1e3);
23
22
  }
24
- /** The `PX` milliseconds of a write. Like other unstorage drivers, no TTL or 0 keeps the key. */
25
23
  function writeTTL(options) {
26
24
  const ttl = options?.ttl;
27
25
  if (ttl === void 0 || ttl === null || ttl === 0) return;
28
26
  if (typeof ttl === "number") return ttlMilliseconds(ttl);
29
27
  throw kvErrorDiagnostics.KV_INVALID_TTL();
30
28
  }
31
- /** Keys per `MGET`, so one reply stays a moderate size. */
32
29
  const mgetBatchSize = 1e3;
33
30
  /**
34
31
  * KV over a Redis server through TCP, with `ioredis`. Each atomic operation is one command or one script. This module
@@ -14,6 +14,10 @@ function createKVStorageDriver(options = {}) {
14
14
  const base = normalizeKey(options.base);
15
15
  const prefix = base ? `${base}:` : "";
16
16
  const key = (name) => prefix + normalizeKey(name);
17
+ const below = (name) => {
18
+ const value = key(name);
19
+ return value && !value.endsWith(":") ? `${value}:` : value;
20
+ };
17
21
  const store = () => options.store === void 0 ? kv : kv.store(options.store);
18
22
  return {
19
23
  name: "vitehub-kv",
@@ -24,9 +28,9 @@ function createKVStorageDriver(options = {}) {
24
28
  setItem: (name, value, opts) => unwrap(store().set(key(name), value, typeof opts?.ttl === "number" ? { ttl: opts.ttl } : void 0)),
25
29
  removeItem: (name) => unwrap(store().delete(key(name))),
26
30
  async getKeys(keyBase) {
27
- return (await unwrap(store().keys(key(keyBase)))).map((name) => name.slice(prefix.length));
31
+ return (await unwrap(store().list({ prefix: below(keyBase) }))).keys.map((name) => name.slice(prefix.length));
28
32
  },
29
- clear: (keyBase) => unwrap(store().clear(key(keyBase)))
33
+ clear: (keyBase) => unwrap(store().clear({ prefix: below(keyBase) }))
30
34
  };
31
35
  }
32
36
  //#endregion
@@ -1,5 +1,5 @@
1
- import { R as ResolvedUpstashKVStoreConfig } from "../types-DEiKew_3.js";
2
- import { t as KVRuntimeDriver } from "../driver-BwxgaQ-f.js";
1
+ import { B as ResolvedUpstashKVStoreConfig } from "../types-Cp6IBhSN.js";
2
+ import { t as KVRuntimeDriver } from "../driver-Du6Eh9p2.js";
3
3
  //#region src/runtime/upstash-driver.d.ts
4
4
  export default function createUpstashKVDriver(options: ResolvedUpstashKVStoreConfig): KVRuntimeDriver;
5
5
  //#endregion
@@ -1,8 +1,8 @@
1
1
  import { t as invariant } from "../invariant-DolT9EEx.js";
2
- import { n as kvErrorDiagnostics } from "../error-diagnostics-BxqvtEIb.js";
2
+ import { n as kvErrorDiagnostics } from "../error-diagnostics-C4VTHInS.js";
3
3
  import { o as normalizeKey } from "../utils2-FozcTsmb.js";
4
4
  import { t as chunks } from "../batch--v0ri69O.js";
5
- import { a as redisIncrementScript, i as redisIncrementResult, n as escapeRedisGlob, o as redisTTLSeconds, r as redisDeleteIfEqualsScript, t as createPortableRedisKeyLister } from "../redis-shared-E5mahECF.js";
5
+ import { a as redisIncrementScript, i as redisIncrementResult, n as escapeRedisGlob, o as redisTTLSeconds, r as redisDeleteIfEqualsScript, t as createPortableRedisKeyLister } from "../redis-shared-1M0IaguQ.js";
6
6
  import createDriver from "unstorage/drivers/upstash";
7
7
  //#region src/runtime/upstash-driver.ts
8
8
  const keyBatchSize = 1e3;
@@ -61,10 +61,6 @@ function createUpstashKVDriver(options) {
61
61
  });
62
62
  return [String(next), keys.map(unprefixed)];
63
63
  });
64
- const dispose = driver.dispose;
65
- driver.dispose = async () => {
66
- await dispose?.call(driver);
67
- };
68
64
  return driver;
69
65
  }
70
66
  //#endregion
@@ -1,10 +1,10 @@
1
1
  import { n as GetItemType, r as GetItemTypeMap } from "./types-Bj3EQoRg.js";
2
- import { Result } from "@vite-hub/runtime";
2
+ import { Duration, Result } from "@vite-hub/runtime";
3
3
  //#region src/types.d.ts
4
4
  type KVDriver = "cloudflare" | "database" | "deno-kv" | "fs-lite" | "redis" | "upstash";
5
5
  /**
6
6
  * The atomic operations of each driver. A store returns `KV_UNSUPPORTED_OPERATION` for an atomic operation that its
7
- * driver does not list. `get`, `set`, `delete`, `has`, `keys`, `list`, and `clear` work on every driver.
7
+ * driver does not list. `get`, `set`, `delete`, `has`, `list`, and `clear` work on every driver.
8
8
  */
9
9
  interface KVDriverAtomicOperations {
10
10
  "cloudflare": never;
@@ -38,7 +38,7 @@ interface UpstashKVStoreConfig {
38
38
  token?: string;
39
39
  url?: string;
40
40
  /**
41
- * Prefix of every key in Upstash. Default `vitehub:kv:<store>`, as for a Redis store, so `kv.clear()` and `kv.keys()`
41
+ * Prefix of every key in Upstash. Default `vitehub:kv:<store>`, as for a Redis store, so `kv.clear()` and `kv.list()`
42
42
  * stay inside the store. An empty value uses the default.
43
43
  */
44
44
  base?: string;
@@ -65,7 +65,7 @@ interface DatabaseKVStoreConfig {
65
65
  driver: "database";
66
66
  /**
67
67
  * The Database that keeps the keys, in the table `vitehub_kv`. Default `"default"`. The store creates the table when
68
- * it is missing. Postgres and libSQL work. D1 does not.
68
+ * it is missing. Postgres, libSQL, and Cloudflare D1 work.
69
69
  */
70
70
  database?: string;
71
71
  /** A Database store uses the Database of the app, in `vite dev` too. */
@@ -137,14 +137,23 @@ interface ResolvedKVModuleOptions {
137
137
  store: ResolvedKVStoreConfig;
138
138
  stores?: Record<string, ResolvedKVStoreConfig>;
139
139
  }
140
- type KVOperation = "clear" | "delete" | "deleteIfEquals" | "get" | "getAndDelete" | "getMany" | "has" | "increment" | "keys" | "list" | "lock" | "set" | "setIfAbsent" | "setMany";
140
+ type KVOperation = "clear" | "delete" | "deleteIfEquals" | "get" | "getAndDelete" | "getMany" | "has" | "increment" | "list" | "lock" | "set" | "setIfAbsent" | "setMany";
141
141
  /** Codes that KV operations return in the `[error, data]` tuple. Config errors throw instead. */
142
- type KVErrorCode = "KV_INVALID_CURSOR" | "KV_INVALID_LIMIT" | "KV_INVALID_OPTION" | "KV_INVALID_TTL" | "KV_INVALID_VALUE" | "KV_INVALID_WAIT" | "KV_KEY_TOO_LONG" | "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION" | "KV_VALUE_TOO_LARGE";
142
+ type KVErrorCode = "KV_INVALID_CURSOR" | "KV_INVALID_CLEAR_OPTIONS" | "KV_INVALID_LIMIT" | "KV_INVALID_OPTION" | "KV_INVALID_TTL" | "KV_INVALID_VALUE" | "KV_INVALID_WAIT" | "KV_KEY_TOO_LONG" | "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION" | "KV_VALUE_TOO_LARGE";
143
143
  interface KVListOptions {
144
144
  /** Opaque continuation cursor returned by a previous page. */
145
145
  cursor?: string;
146
- /** Maximum number of keys to read. Must be a positive integer. */
146
+ /** Maximum number of keys to read. Must be a positive integer. Without it, the page holds every key and no cursor. */
147
+ limit?: number;
148
+ /** Only keys that start with this text, so `"user"` matches `users:1`. `"users:"` matches the keys below `users`. */
149
+ prefix?: string;
150
+ }
151
+ /** One page that a driver reads: `limit` is set. */
152
+ interface KVPageOptions extends KVListOptions {
147
153
  limit: number;
154
+ }
155
+ interface KVClearOptions {
156
+ /** Only keys that start with this text, as in `list()`. Without it, `clear()` deletes every key of the store. */
148
157
  prefix?: string;
149
158
  }
150
159
  /** What `kv.get()` converts the stored value to: `text`, `json`, `bytes`, `stream`, or `blob`. */
@@ -155,20 +164,23 @@ type KVGetTypeMap = GetItemTypeMap;
155
164
  type KVGetOptions<K extends KVGetType | undefined = KVGetType | undefined> = Record<string, unknown> & {
156
165
  type?: K;
157
166
  };
158
- /** A read value: the caller's `T` without a `type`, the converted type with one. */
159
167
  type KVValue<T, K> = K extends KVGetType ? KVGetTypeMap[K] : T;
160
168
  /** Options of `kv.set()`, `kv.setMany()`, and `kv.setIfAbsent()`. Other fields return `KV_INVALID_OPTION`. */
161
169
  interface KVSetOptions {
162
- /** Seconds until the key expires, a positive number. Every driver expires the key. Cloudflare KV keeps it at least 60 seconds. */
163
- ttl?: number;
170
+ /**
171
+ * How long until the key expires: a number of seconds, or a duration such as `"1h"` or `"7 days"`. Every driver
172
+ * expires the key. Cloudflare KV keeps it at least 60 seconds.
173
+ */
174
+ ttl?: number | Duration;
164
175
  }
165
176
  /** Options of `kv.lock()`. */
166
177
  interface KVLockOptions {
167
178
  /**
168
- * Seconds until the lock expires, so a crashed holder never keeps it. Pick a value longer than the work.
169
- * KV does not renew a lock: when the work runs longer than `ttl`, another runner can take the lock.
179
+ * How long until the lock expires, so a crashed holder never keeps it: a number of seconds, or a duration such as
180
+ * `"30s"`. Pick a value longer than the work. KV does not renew a lock: when the work runs longer than `ttl`, another
181
+ * runner can take the lock.
170
182
  */
171
- ttl: number;
183
+ ttl: number | Duration;
172
184
  /** Seconds to wait for a held lock, polling with backoff. Default `0`: return `{ acquired: false }` at once. */
173
185
  wait?: number;
174
186
  }
@@ -197,7 +209,8 @@ interface KVLock {
197
209
  /**
198
210
  * Takes the lock, runs `fn`, and releases the lock, also when `fn` throws. An error from `fn` is thrown again after
199
211
  * the release. Returns `{ acquired: false }` without calling `fn` when another runner holds the lock after `wait`.
200
- * A release that fails returns `KV_OPERATION_FAILED` after `fn` ran; the lock then expires after `ttl`.
212
+ * A release that fails returns `KV_OPERATION_FAILED` after `fn` ran; the lock then expires after `ttl`. When `fn`
213
+ * threw, its error is thrown and the failed release is logged as a warning.
201
214
  */
202
215
  run<T>(fn: () => T): Promise<Result<KVLockRunResult<Awaited<T>>, KVLockErrorCode>>;
203
216
  /** Takes the lock and returns a `release()` function. Prefer `run()`, which always releases. */
@@ -219,7 +232,7 @@ interface KVListPage {
219
232
  * Config errors, for example an unknown store name, throw.
220
233
  */
221
234
  interface KVStorage {
222
- clear(base?: string, options?: unknown): Promise<Result<void, "KV_OPERATION_FAILED">>;
235
+ clear(options?: KVClearOptions): Promise<Result<void, "KV_INVALID_CLEAR_OPTIONS" | "KV_OPERATION_FAILED">>;
223
236
  delete(key: string, options?: unknown): Promise<Result<void, "KV_KEY_TOO_LONG" | "KV_OPERATION_FAILED">>;
224
237
  /**
225
238
  * Deletes the key only when its value equals `expected`, in one atomic step. Returns `true` when this call deleted it.
@@ -228,33 +241,19 @@ interface KVStorage {
228
241
  * The drivers in {@link KVDriversWith}`<"deleteIfEquals">` support it. The others return `KV_UNSUPPORTED_OPERATION`.
229
242
  */
230
243
  deleteIfEquals<T = unknown>(key: string, expected: T): Promise<Result<boolean, "KV_INVALID_VALUE" | "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION">>;
231
- /**
232
- * Reads a value or returns `null`. Without `options.type`, a string value is parsed as JSON, so `"123"` reads back as `123`.
233
- * `{ type: "text" }` returns the stored text, and `json`, `bytes`, `stream`, and `blob` convert it to that type.
234
- */
235
244
  get<T = unknown, K extends KVGetType | undefined = undefined>(key: string, options?: KVGetOptions<K>): Promise<Result<KVValue<T, K> | null, "KV_KEY_TOO_LONG" | "KV_OPERATION_FAILED">>;
236
- /**
237
- * Reads many keys in one call. Returns one value per key, in the order of `keys`, with `null` for a missing key.
238
- * `options` works as in `get()` and applies to every key. Stores with a batch read use it: Cloudflare KV reads 100
239
- * keys per call, Redis and Upstash use `MGET`, and the `database` driver runs one query. Other stores read the keys
240
- * one by one, 16 at a time.
241
- */
242
245
  getMany<T = unknown, K extends KVGetType | undefined = undefined>(keys: readonly string[], options?: KVGetOptions<K>): Promise<Result<Array<KVValue<T, K> | null>, "KV_KEY_TOO_LONG" | "KV_OPERATION_FAILED">>;
243
- /**
244
- * Atomically returns and deletes a value. `{ type: "text" }` returns the stored text.
245
- * The drivers in {@link KVDriversWith}`<"getAndDelete">` support it. The others return `KV_UNSUPPORTED_OPERATION`.
246
- */
247
246
  getAndDelete<T = unknown, K extends "text" | undefined = undefined>(key: string, options?: {
248
247
  type?: K;
249
248
  }): Promise<Result<KVValue<T, K> | null, "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION">>;
250
249
  has(key: string, options?: unknown): Promise<Result<boolean, "KV_KEY_TOO_LONG" | "KV_OPERATION_FAILED">>;
251
250
  /**
252
- * Atomically increments a counter. The TTL is applied only when the counter is created.
251
+ * Atomically increments a counter. The TTL, a number of seconds or a duration such as `"1m"`, is applied only when
252
+ * the counter is created.
253
253
  * The drivers in {@link KVDriversWith}`<"increment">` support it. The others return `KV_UNSUPPORTED_OPERATION`.
254
254
  */
255
- increment(key: string, ttl: number): Promise<Result<number, "KV_INVALID_TTL" | "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION">>;
256
- keys(base?: string, options?: unknown): Promise<Result<string[], "KV_OPERATION_FAILED">>;
257
- list(options: KVListOptions): Promise<Result<KVListPage, "KV_INVALID_CURSOR" | "KV_INVALID_LIMIT" | "KV_OPERATION_FAILED">>;
255
+ increment(key: string, ttl: number | Duration): Promise<Result<number, "KV_INVALID_TTL" | "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION">>;
256
+ list(options?: KVListOptions): Promise<Result<KVListPage, "KV_INVALID_CURSOR" | "KV_INVALID_LIMIT" | "KV_OPERATION_FAILED">>;
258
257
  /**
259
258
  * A lock on `key` that one runner holds at a time, across server processes that share the store. It writes a random
260
259
  * owner token with `setIfAbsent()` and a TTL, and frees it with `deleteIfEquals()`, so a runner never deletes a lock
@@ -263,7 +262,8 @@ interface KVStorage {
263
262
  */
264
263
  lock(key: string, options: KVLockOptions): KVLock;
265
264
  /**
266
- * Writes a value. `{ ttl }` expires it after that many seconds; without `ttl`, the value stays until you delete or replace it.
265
+ * Writes a value. `{ ttl }` expires it after a number of seconds or a duration such as `"1h"`; without `ttl`, the
266
+ * value stays until you delete or replace it.
267
267
  * Cloudflare KV stores return `KV_KEY_TOO_LONG` and `KV_VALUE_TOO_LARGE` before a write that Cloudflare rejects.
268
268
  */
269
269
  set<T = unknown>(key: string, value: T, options?: KVSetOptions): Promise<Result<void, "KV_INVALID_OPTION" | "KV_INVALID_TTL" | "KV_KEY_TOO_LONG" | "KV_OPERATION_FAILED" | "KV_VALUE_TOO_LARGE">>;
@@ -297,7 +297,7 @@ interface KVStoreOptions {
297
297
  mode?: "read" | "write";
298
298
  }
299
299
  /**
300
- * KV handle from `kv.store(name, { mode: "read" })`, with only `get()`, `getMany()`, `has()`, `keys()`, and `list()`.
300
+ * KV handle from `kv.store(name, { mode: "read" })`, with only `get()`, `getMany()`, `has()`, and `list()`.
301
301
  * It limits this API, not the host: the KV binding or provider token keeps full access, so it is not a security
302
302
  * boundary against code that reads the binding directly.
303
303
  */
@@ -305,8 +305,7 @@ interface ReadonlyKVStorage {
305
305
  get: KVStorage["get"];
306
306
  getMany: KVStorage["getMany"];
307
307
  has: KVStorage["has"];
308
- keys: KVStorage["keys"];
309
308
  list: KVStorage["list"];
310
309
  }
311
310
  //#endregion
312
- export { RedisKVStoreConfig as A, KVOptions as C, KVStoreName as D, KVStoreConfig as E, ResolvedKVModuleOptions as F, ResolvedKVStoreConfig as I, ResolvedRedisKVStoreConfig as L, ResolvedDatabaseKVStoreConfig as M, ResolvedDenoKVStoreConfig as N, KVStoreOptions as O, ResolvedFsLiteKVStoreConfig as P, ResolvedUpstashKVStoreConfig as R, KVOperation as S, KVStorage as T, KVLock as _, InferredKVStoreConfig as a, KVLockOptions as b, KVDriverAtomicOperations as c, KVErrorCode as d, KVGetOptions as f, KVListPage as g, KVListOptions as h, FsLiteKVStoreConfig as i, ResolvedCloudflareKVStoreConfig as j, ReadonlyKVStorage as k, KVDriversWith as l, KVGetTypeMap as m, DatabaseKVStoreConfig as n, KVAtomicOperation as o, KVGetType as p, DenoKVStoreConfig as r, KVDriver as s, CloudflareKVStoreConfig as t, KVEntry as u, KVLockAcquisition as v, KVSetOptions as w, KVLockRunResult as x, KVLockErrorCode as y, UpstashKVStoreConfig as z };
311
+ export { KVStoreOptions as A, ResolvedUpstashKVStoreConfig as B, KVOperation as C, KVStorage as D, KVSetOptions as E, ResolvedDenoKVStoreConfig as F, ResolvedFsLiteKVStoreConfig as I, ResolvedKVModuleOptions as L, RedisKVStoreConfig as M, ResolvedCloudflareKVStoreConfig as N, KVStoreConfig as O, ResolvedDatabaseKVStoreConfig as P, ResolvedKVStoreConfig as R, KVLockRunResult as S, KVPageOptions as T, UpstashKVStoreConfig as V, KVListPage as _, InferredKVStoreConfig as a, KVLockErrorCode as b, KVDriver as c, KVEntry as d, KVErrorCode as f, KVListOptions as g, KVGetTypeMap as h, FsLiteKVStoreConfig as i, ReadonlyKVStorage as j, KVStoreName as k, KVDriverAtomicOperations as l, KVGetType as m, DatabaseKVStoreConfig as n, KVAtomicOperation as o, KVGetOptions as p, DenoKVStoreConfig as r, KVClearOptions as s, CloudflareKVStoreConfig as t, KVDriversWith as u, KVLock as v, KVOptions as w, KVLockOptions as x, KVLockAcquisition as y, ResolvedRedisKVStoreConfig as z };