@vite-hub/kv 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +7 -3
  2. package/dist/{batch--v0ri69O.js → batch-D-ib5_0P.js} +0 -1
  3. package/dist/{cli-DpPhz_Ek.d.ts → cli-BvVInMht.d.ts} +1 -6
  4. package/dist/cli.d.ts +2 -4
  5. package/dist/cli.js +24 -14
  6. package/dist/{cloudflare-env-lOtHHsgP.js → cloudflare-env-Bm6huR35.js} +4 -4
  7. package/dist/{cloudflare-env-lookup-Bs0VDpU5.js → cloudflare-env-lookup-Dgq5n1Aq.js} +1 -2
  8. package/dist/{cloudflare-kv-C3NO4C21.js → cloudflare-kv-K2MzfP6D.js} +12 -16
  9. package/dist/{cloudflare-kv-local-C2sbIrFy.js → cloudflare-kv-local-lov9LLhU.js} +5 -10
  10. package/dist/{config-LfpUj9hs.js → config-B8FRGmX_.js} +53 -22
  11. package/dist/{create-storage-BORQm2a8.js → create-storage-BMvkkYdM.js} +9 -15
  12. package/dist/{cursor-history-DRHh5bO5.js → cursor-history-C6oG12QO.js} +9 -6
  13. package/dist/{deno-kv-D_VtffFv.js → deno-kv-MnqlNH1e.js} +45 -10
  14. package/dist/{dev-peer-CHafxbtj.js → dev-peer-D0vOxmrD.js} +1 -2
  15. package/dist/driver-bLMl-wMO.d.ts +43 -0
  16. package/dist/durability.d.ts +1 -3
  17. package/dist/durability.js +1 -2
  18. package/dist/{error-diagnostics-C54QQEhN.js → error-diagnostics-DUIp6FhO.js} +7 -4
  19. package/dist/{errors-DzD6YNEH.js → errors-IaVOqzAs.js} +42 -8
  20. package/dist/errors.d.ts +8 -5
  21. package/dist/errors.js +1 -2
  22. package/dist/fs-lite-DhXLUL-H.js +1 -0
  23. package/dist/{fs-lite-BaklCLuV.js → fs-lite-fvNdBEr9.js} +3 -5
  24. package/dist/index.d.ts +1 -3
  25. package/dist/index.js +34 -66
  26. package/dist/{inspect-BIKQsqX4.js → inspect-BWMcVWD8.js} +2 -4
  27. package/dist/{invariant-DolT9EEx.js → invariant-Dj2R1eMr.js} +1 -2
  28. package/dist/{object-Da1zyPCR.js → object-CAK6UYR5.js} +1 -2
  29. package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CqZkx1Rm.d.ts} +8 -6
  30. package/dist/{operations-D2iI9oN4.js → operations-CGAX5ASA.js} +53 -28
  31. package/dist/{operations-CtrWLmPK.js → operations-FgS_sJ3M.js} +27 -45
  32. package/dist/operations.d.ts +2 -8
  33. package/dist/operations.js +8 -12
  34. package/dist/out-By90R-Bo.js +22706 -0
  35. package/dist/{redis-shared-5ogRd3-Y.js → redis-shared-DO7Ib1Sz.js} +2 -3
  36. package/dist/request-log-DllKQXj7.js +104 -0
  37. package/dist/results-emgN7uDS.js +4 -0
  38. package/dist/rolldown-runtime-DegdyBIC.js +25 -0
  39. package/dist/runtime/cloudflare-kv.d.ts +1 -3
  40. package/dist/runtime/cloudflare-kv.js +1 -2
  41. package/dist/runtime/cloudflare-request-env.d.ts +1 -3
  42. package/dist/runtime/cloudflare-request-env.js +2 -3
  43. package/dist/runtime/database.d.ts +2 -0
  44. package/dist/{database-oJdy0ZVX.js → runtime/database.js} +69 -39
  45. package/dist/runtime/nitro-plugin.d.ts +1 -2
  46. package/dist/runtime/nitro-plugin.js +11 -8
  47. package/dist/runtime/redis-driver.d.ts +3 -5
  48. package/dist/runtime/redis-driver.js +6 -10
  49. package/dist/runtime/unstorage-driver.d.ts +2 -4
  50. package/dist/runtime/unstorage-driver.js +2 -3
  51. package/dist/runtime/upstash-driver.d.ts +3 -5
  52. package/dist/runtime/upstash-driver.js +6 -11
  53. package/dist/{types-Bj3EQoRg.d.ts → types-BUb0FcjM.d.ts} +0 -2
  54. package/dist/{types-Dv-OSXZC.d.ts → types-C397WKyf.d.ts} +4 -20
  55. package/dist/{upstash-B-vaUYqO.js → upstash-DQVo1zbz.js} +3 -4
  56. package/dist/{utils2-FozcTsmb.js → utils2-By8eee1x.js} +1 -2
  57. package/dist/vite.d.ts +8 -19
  58. package/dist/vite.js +2676 -104
  59. package/package.json +15 -10
  60. package/dist/driver-R4Z5Z5fl.d.ts +0 -15
  61. package/dist/fs-lite-BAgpmNAF.js +0 -2
  62. package/dist/results-p7nPCnaJ.js +0 -6
@@ -1,5 +1,5 @@
1
- import { n as kvErrorDiagnostics } from "./error-diagnostics-C54QQEhN.js";
2
- //#region src/runtime/redis-shared.ts
1
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-DUIp6FhO.js";
2
+ // src/runtime/redis-shared.ts
3
3
  const redisIncrementScript = `
4
4
  local existed = redis.call('EXISTS', KEYS[1])
5
5
  local current = redis.call('GET', KEYS[1])
@@ -90,5 +90,4 @@ function createPortableRedisKeyLister(provider, scan) {
90
90
  };
91
91
  };
92
92
  }
93
- //#endregion
94
93
  export { redisIncrementScript as a, redisIncrementResult as i, escapeRedisGlob as n, redisTTLSeconds as o, redisDeleteIfEqualsScript as r, createPortableRedisKeyLister as t };
@@ -0,0 +1,104 @@
1
+ // ../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
+ export { logFailure as t };
@@ -0,0 +1,4 @@
1
+ // src/results.ts
2
+ /** Largest `--limit` of one `list` page. */
3
+ const kvDevMaximumListLimit = 1e3;
4
+ export { kvDevMaximumListLimit as t };
@@ -0,0 +1,25 @@
1
+ import { createRequire } from "node:module";
2
+ // \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
+ key = keys[i];
13
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
21
+ value: mod,
22
+ enumerable: true
23
+ }) : target, mod));
24
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
25
+ export { __require as n, __toESM as r, __commonJSMin as t };
@@ -1,6 +1,4 @@
1
- import { t as KVRuntimeDriver } from "../driver-R4Z5Z5fl.js";
2
- //#region src/runtime/cloudflare-kv.d.ts
1
+ import { t as KVRuntimeDriver } from "../driver-bLMl-wMO.js";
3
2
  declare function createCloudflareDriver(options: Record<string, unknown>): KVRuntimeDriver;
4
3
  export declare function createCloudflareKVStorage(options: Record<string, unknown>): unknown;
5
- //#endregion
6
4
  export { createCloudflareDriver as default };
@@ -1,2 +1 @@
1
- import { n as createCloudflareKVStorage, t as createCloudflareDriver } from "../cloudflare-kv-C3NO4C21.js";
2
- export { createCloudflareKVStorage, createCloudflareDriver as default };
1
+ export { n as createCloudflareKVStorage, t as default } from "../cloudflare-kv-K2MzfP6D.js";
@@ -1,7 +1,5 @@
1
- //#region src/runtime/cloudflare-request-env.d.ts
2
1
  /**
3
2
  * Nitro middleware for Cloudflare KV. A Cloudflare KV store reads its binding from the active env, and only the request
4
3
  * carries that env in `vite dev`, so the middleware installs it before the route runs.
5
4
  */
6
- export default function vitehubKVCloudflareRequestEnv(event: unknown): void;
7
- //#endregion
5
+ export default function vitehubKVCloudflareRequestEnv(event: unknown): void;
@@ -1,5 +1,5 @@
1
- import { n as installCloudflareRequestEnv } from "../cloudflare-env-lOtHHsgP.js";
2
- //#region src/runtime/cloudflare-request-env.ts
1
+ import { r as installCloudflareRequestEnv } from "../cloudflare-env-Bm6huR35.js";
2
+ // 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
5
5
  * carries that env in `vite dev`, so the middleware installs it before the route runs.
@@ -7,5 +7,4 @@ import { n as installCloudflareRequestEnv } from "../cloudflare-env-lOtHHsgP.js"
7
7
  function vitehubKVCloudflareRequestEnv(event) {
8
8
  installCloudflareRequestEnv(event);
9
9
  }
10
- //#endregion
11
10
  export { vitehubKVCloudflareRequestEnv as default };
@@ -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-bLMl-wMO.js";
2
+ export { KVDatabases, KVSqlClient, KVSqlParam, createDatabaseKVDriver as default, kvSqlClientFromDatabase, kvTable };
@@ -1,39 +1,60 @@
1
- import { n as kvErrorDiagnostics } from "./error-diagnostics-C54QQEhN.js";
2
- import { t as chunks } from "./batch--v0ri69O.js";
3
- //#region src/runtime/database.ts
1
+ import { t as logFailure } from "../request-log-DllKQXj7.js";
2
+ import { t as d1PrimaryClient } from "../cloudflare-env-Bm6huR35.js";
3
+ import { n as kvErrorDiagnostics } from "../error-diagnostics-DUIp6FhO.js";
4
+ import { t as chunks } from "../batch-D-ib5_0P.js";
5
+ // 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
  }
@@ -246,5 +277,4 @@ function createDatabaseKVDriver(options, connect) {
246
277
  }
247
278
  };
248
279
  }
249
- //#endregion
250
- export { createDatabaseKVDriver as default, kvSqlClientFromDatabase };
280
+ export { createDatabaseKVDriver as default, kvSqlClientFromDatabase, kvTable };
@@ -1,4 +1,3 @@
1
- //#region src/runtime/nitro-plugin.d.ts
2
1
  interface NitroAppLike {
3
2
  hooks: {
4
3
  hook(name: "close", callback: () => Promise<void>): unknown;
@@ -9,4 +8,4 @@ interface NitroAppLike {
9
8
  * so the process can exit.
10
9
  */
11
10
  export default function kvNitroPlugin(nitroApp: NitroAppLike): void;
12
- //#endregion
11
+ export {};
@@ -1,10 +1,7 @@
1
- import { t as kvInferredStoreNotice } from "../config-LfpUj9hs.js";
1
+ import { t as logFailure } from "../request-log-DllKQXj7.js";
2
+ import { t as kvInferredStoreNotice } from "../config-B8FRGmX_.js";
2
3
  import { disposeKVStores } from "@vite-hub/kv";
3
- //#region src/runtime/nitro-plugin.ts
4
- /**
5
- * Prints the driver that each inferred store uses in this process. A Node build of `vitehub()` prints the stores in its
6
- * Durability table at boot, so KV prints nothing there.
7
- */
4
+ // src/runtime/nitro-plugin.ts
8
5
  async function logInferredStores() {
9
6
  const { durabilityReportsStores, kv } = await import("#vitehub/kv/config");
10
7
  if (!kv || durabilityReportsStores) return;
@@ -19,7 +16,13 @@ async function logInferredStores() {
19
16
  */
20
17
  function kvNitroPlugin(nitroApp) {
21
18
  nitroApp.hooks.hook("close", disposeKVStores);
22
- 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
+ });
23
27
  }
24
- //#endregion
25
28
  export { kvNitroPlugin as default };
@@ -1,11 +1,9 @@
1
- import { z as ResolvedRedisKVStoreConfig } from "../types-Dv-OSXZC.js";
2
- import { t as KVRuntimeDriver } from "../driver-R4Z5Z5fl.js";
3
- //#region src/runtime/redis-driver.d.ts
1
+ import { z as ResolvedRedisKVStoreConfig } from "../types-C397WKyf.js";
2
+ import { t as KVRuntimeDriver } from "../driver-bLMl-wMO.js";
4
3
  /** The URL of a store: `env:<NAME>` reads the variable now, so a build never holds the URL of its server. */
5
4
  export declare function resolveRedisUrl(url: string, env?: Record<string, string | undefined>): string;
6
5
  /**
7
6
  * KV over a Redis server through TCP, with `ioredis`. Each atomic operation is one command or one script. This module
8
7
  * loads only for a Redis store, so other stores do not load `ioredis`.
9
8
  */
10
- export default function createRedisKVDriver(options: ResolvedRedisKVStoreConfig): KVRuntimeDriver;
11
- //#endregion
9
+ export default function createRedisKVDriver(options: ResolvedRedisKVStoreConfig): KVRuntimeDriver;
@@ -1,10 +1,10 @@
1
- import { t as invariant } from "../invariant-DolT9EEx.js";
2
- import { n as kvErrorDiagnostics } from "../error-diagnostics-C54QQEhN.js";
3
- import { o as normalizeKey } from "../utils2-FozcTsmb.js";
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-5ogRd3-Y.js";
1
+ import { t as invariant } from "../invariant-Dj2R1eMr.js";
2
+ import { o as normalizeKey } from "../utils2-By8eee1x.js";
3
+ import { n as kvErrorDiagnostics } from "../error-diagnostics-DUIp6FhO.js";
4
+ import { t as chunks } from "../batch-D-ib5_0P.js";
5
+ import { a as redisIncrementScript, i as redisIncrementResult, n as escapeRedisGlob, o as redisTTLSeconds, r as redisDeleteIfEqualsScript, t as createPortableRedisKeyLister } from "../redis-shared-DO7Ib1Sz.js";
6
6
  import { Redis } from "ioredis";
7
- //#region src/runtime/redis-driver.ts
7
+ // 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. */
9
9
  function resolveRedisUrl(url, env = globalThis.process?.env ?? {}) {
10
10
  if (!url.startsWith("env:")) return url;
@@ -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
@@ -109,5 +106,4 @@ function createRedisKVDriver(options) {
109
106
  }
110
107
  };
111
108
  }
112
- //#endregion
113
109
  export { createRedisKVDriver as default, resolveRedisUrl };
@@ -1,5 +1,4 @@
1
- import { t as Driver } from "../types-Bj3EQoRg.js";
2
- //#region src/runtime/unstorage-driver.d.ts
1
+ import { t as Driver } from "../types-BUb0FcjM.js";
3
2
  export interface KVStorageDriverOptions {
4
3
  /** The named KV store. Default: the default store. */
5
4
  store?: string;
@@ -10,5 +9,4 @@ export interface KVStorageDriverOptions {
10
9
  * Unstorage driver over one KV store, for Nitro storage mounts such as `kv` and `cache`.
11
10
  * It resolves the store on each call, so a Cloudflare store uses the binding of the current request.
12
11
  */
13
- export default function createKVStorageDriver(options?: KVStorageDriverOptions): Driver<KVStorageDriverOptions>;
14
- //#endregion
12
+ export default function createKVStorageDriver(options?: KVStorageDriverOptions): Driver<KVStorageDriverOptions>;
@@ -1,6 +1,6 @@
1
- import { o as normalizeKey } from "../utils2-FozcTsmb.js";
1
+ import { o as normalizeKey } from "../utils2-By8eee1x.js";
2
2
  import { kv } from "@vite-hub/kv";
3
- //#region src/runtime/unstorage-driver.ts
3
+ // src/runtime/unstorage-driver.ts
4
4
  async function unwrap(pending) {
5
5
  const [error, value] = await pending;
6
6
  if (error) throw error;
@@ -33,5 +33,4 @@ function createKVStorageDriver(options = {}) {
33
33
  clear: (keyBase) => unwrap(store().clear({ prefix: below(keyBase) }))
34
34
  };
35
35
  }
36
- //#endregion
37
36
  export { createKVStorageDriver as default };
@@ -1,5 +1,3 @@
1
- import { B as ResolvedUpstashKVStoreConfig } from "../types-Dv-OSXZC.js";
2
- import { t as KVRuntimeDriver } from "../driver-R4Z5Z5fl.js";
3
- //#region src/runtime/upstash-driver.d.ts
4
- export default function createUpstashKVDriver(options: ResolvedUpstashKVStoreConfig): KVRuntimeDriver;
5
- //#endregion
1
+ import { B as ResolvedUpstashKVStoreConfig } from "../types-C397WKyf.js";
2
+ import { t as KVRuntimeDriver } from "../driver-bLMl-wMO.js";
3
+ export default function createUpstashKVDriver(options: ResolvedUpstashKVStoreConfig): KVRuntimeDriver;
@@ -1,10 +1,10 @@
1
- import { t as invariant } from "../invariant-DolT9EEx.js";
2
- import { n as kvErrorDiagnostics } from "../error-diagnostics-C54QQEhN.js";
3
- import { o as normalizeKey } from "../utils2-FozcTsmb.js";
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-5ogRd3-Y.js";
1
+ import { t as invariant } from "../invariant-Dj2R1eMr.js";
2
+ import { o as normalizeKey } from "../utils2-By8eee1x.js";
3
+ import { n as kvErrorDiagnostics } from "../error-diagnostics-DUIp6FhO.js";
4
+ import { t as chunks } from "../batch-D-ib5_0P.js";
5
+ import { a as redisIncrementScript, i as redisIncrementResult, n as escapeRedisGlob, o as redisTTLSeconds, r as redisDeleteIfEqualsScript, t as createPortableRedisKeyLister } from "../redis-shared-DO7Ib1Sz.js";
6
6
  import createDriver from "unstorage/drivers/upstash";
7
- //#region src/runtime/upstash-driver.ts
7
+ // src/runtime/upstash-driver.ts
8
8
  const keyBatchSize = 1e3;
9
9
  function createUpstashKVDriver(options) {
10
10
  const base = normalizeKey(options.base);
@@ -61,11 +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
- //#endregion
71
66
  export { createUpstashKVDriver as default };
@@ -1,4 +1,3 @@
1
- //#region ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/_chunks/types.d.mts
2
1
  type StorageValue = null | string | number | boolean | object;
3
2
  type WatchEvent = "update" | "remove";
4
3
  type WatchCallback = (event: WatchEvent, key: string) => any;
@@ -65,5 +64,4 @@ interface Driver<OptionsT = any, InstanceT = any> {
65
64
  dispose?: () => MaybePromise<void>;
66
65
  watch?: (callback: WatchCallback) => MaybePromise<Unwatch>;
67
66
  }
68
- //#endregion
69
67
  export { TransactionOptions as i, GetItemType as n, GetItemTypeMap as r, Driver as t };
@@ -1,6 +1,5 @@
1
- import { n as GetItemType, r as GetItemTypeMap } from "./types-Bj3EQoRg.js";
1
+ import { n as GetItemType, r as GetItemTypeMap } from "./types-BUb0FcjM.js";
2
2
  import { Duration, Result } from "@vite-hub/runtime";
3
- //#region src/types.d.ts
4
3
  type KVDriver = "cloudflare" | "database" | "deno-kv" | "fs-lite" | "redis" | "upstash";
5
4
  /**
6
5
  * The atomic operations of each driver. A store returns `KV_UNSUPPORTED_OPERATION` for an atomic operation that its
@@ -65,7 +64,7 @@ interface DatabaseKVStoreConfig {
65
64
  driver: "database";
66
65
  /**
67
66
  * 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.
67
+ * it is missing. Postgres, libSQL, and Cloudflare D1 work.
69
68
  */
70
69
  database?: string;
71
70
  /** A Database store uses the Database of the app, in `vite dev` too. */
@@ -164,7 +163,6 @@ type KVGetTypeMap = GetItemTypeMap;
164
163
  type KVGetOptions<K extends KVGetType | undefined = KVGetType | undefined> = Record<string, unknown> & {
165
164
  type?: K;
166
165
  };
167
- /** A read value: the caller's `T` without a `type`, the converted type with one. */
168
166
  type KVValue<T, K> = K extends KVGetType ? KVGetTypeMap[K] : T;
169
167
  /** Options of `kv.set()`, `kv.setMany()`, and `kv.setIfAbsent()`. Other fields return `KV_INVALID_OPTION`. */
170
168
  interface KVSetOptions {
@@ -210,7 +208,8 @@ interface KVLock {
210
208
  /**
211
209
  * Takes the lock, runs `fn`, and releases the lock, also when `fn` throws. An error from `fn` is thrown again after
212
210
  * the release. Returns `{ acquired: false }` without calling `fn` when another runner holds the lock after `wait`.
213
- * A release that fails returns `KV_OPERATION_FAILED` after `fn` ran; the lock then expires after `ttl`.
211
+ * A release that fails returns `KV_OPERATION_FAILED` after `fn` ran; the lock then expires after `ttl`. When `fn`
212
+ * threw, its error is thrown and the failed release is logged as a warning.
214
213
  */
215
214
  run<T>(fn: () => T): Promise<Result<KVLockRunResult<Awaited<T>>, KVLockErrorCode>>;
216
215
  /** Takes the lock and returns a `release()` function. Prefer `run()`, which always releases. */
@@ -241,22 +240,8 @@ interface KVStorage {
241
240
  * The drivers in {@link KVDriversWith}`<"deleteIfEquals">` support it. The others return `KV_UNSUPPORTED_OPERATION`.
242
241
  */
243
242
  deleteIfEquals<T = unknown>(key: string, expected: T): Promise<Result<boolean, "KV_INVALID_VALUE" | "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION">>;
244
- /**
245
- * Reads a value or returns `null`. Without `options.type`, a string value is parsed as JSON, so `"123"` reads back as `123`.
246
- * `{ type: "text" }` returns the stored text, and `json`, `bytes`, `stream`, and `blob` convert it to that type.
247
- */
248
243
  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">>;
249
- /**
250
- * Reads many keys in one call. Returns one value per key, in the order of `keys`, with `null` for a missing key.
251
- * `options` works as in `get()` and applies to every key. Stores with a batch read use it: Cloudflare KV reads 100
252
- * keys per call, Redis and Upstash use `MGET`, and the `database` driver runs one query. Other stores read the keys
253
- * one by one, 16 at a time.
254
- */
255
244
  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">>;
256
- /**
257
- * Atomically returns and deletes a value. `{ type: "text" }` returns the stored text.
258
- * The drivers in {@link KVDriversWith}`<"getAndDelete">` support it. The others return `KV_UNSUPPORTED_OPERATION`.
259
- */
260
245
  getAndDelete<T = unknown, K extends "text" | undefined = undefined>(key: string, options?: {
261
246
  type?: K;
262
247
  }): Promise<Result<KVValue<T, K> | null, "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION">>;
@@ -321,5 +306,4 @@ interface ReadonlyKVStorage {
321
306
  has: KVStorage["has"];
322
307
  list: KVStorage["list"];
323
308
  }
324
- //#endregion
325
309
  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 };