@vite-hub/kv 0.4.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 (47) hide show
  1. package/README.md +6 -2
  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 +22 -11
  5. package/dist/{cloudflare-env-lOtHHsgP.js → cloudflare-env-Dl349h_9.js} +2 -1
  6. package/dist/{cloudflare-kv-C3NO4C21.js → cloudflare-kv-DQJhmGof.js} +8 -10
  7. package/dist/{cloudflare-kv-local-C2sbIrFy.js → cloudflare-kv-local-COjgHweC.js} +3 -7
  8. package/dist/{config-LfpUj9hs.js → config-pfyPiPrI.js} +47 -12
  9. package/dist/{create-storage-BORQm2a8.js → create-storage-DQ1BbFqH.js} +1 -1
  10. package/dist/{cursor-history-DRHh5bO5.js → cursor-history-CAT4mpP1.js} +7 -3
  11. package/dist/{deno-kv-D_VtffFv.js → deno-kv-Cf0ZveeN.js} +43 -7
  12. package/dist/driver-Du6Eh9p2.d.ts +47 -0
  13. package/dist/{error-diagnostics-C54QQEhN.js → error-diagnostics-C4VTHInS.js} +6 -2
  14. package/dist/{errors-DzD6YNEH.js → errors-BpiM-Vmh.js} +41 -4
  15. package/dist/errors.d.ts +8 -1
  16. package/dist/errors.js +2 -2
  17. package/dist/{fs-lite-BaklCLuV.js → fs-lite-BTcBUP6B.js} +1 -1
  18. package/dist/fs-lite-C8yXCVDM.js +2 -0
  19. package/dist/index.d.ts +1 -1
  20. package/dist/index.js +27 -55
  21. package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CI2PJGqu.d.ts} +8 -2
  22. package/dist/{operations-CtrWLmPK.js → operations-CqKs7Ykc.js} +22 -37
  23. package/dist/{operations-D2iI9oN4.js → operations-nAaONxzh.js} +38 -8
  24. package/dist/operations.d.ts +2 -2
  25. package/dist/operations.js +3 -3
  26. package/dist/out-BbXG-yVX.js +21755 -0
  27. package/dist/{redis-shared-5ogRd3-Y.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/rolldown-runtime-CMFfr-1z.js +26 -0
  31. package/dist/runtime/cloudflare-kv.d.ts +1 -1
  32. package/dist/runtime/cloudflare-kv.js +1 -1
  33. package/dist/runtime/cloudflare-request-env.js +1 -1
  34. package/dist/runtime/database.d.ts +2 -0
  35. package/dist/{database-oJdy0ZVX.js → runtime/database.js} +68 -37
  36. package/dist/runtime/nitro-plugin.js +10 -6
  37. package/dist/runtime/redis-driver.d.ts +2 -2
  38. package/dist/runtime/redis-driver.js +2 -5
  39. package/dist/runtime/upstash-driver.d.ts +2 -2
  40. package/dist/runtime/upstash-driver.js +2 -6
  41. package/dist/{types-Dv-OSXZC.d.ts → types-Cp6IBhSN.d.ts} +3 -17
  42. package/dist/{upstash-B-vaUYqO.js → upstash-5sTbIR35.js} +2 -2
  43. package/dist/vite.d.ts +8 -5
  44. package/dist/vite.js +2102 -46
  45. package/package.json +9 -4
  46. package/dist/driver-R4Z5Z5fl.d.ts +0 -15
  47. package/dist/fs-lite-BAgpmNAF.js +0 -2
@@ -1,4 +1,4 @@
1
- import { n as kvErrorDiagnostics } from "./error-diagnostics-C54QQEhN.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
@@ -0,0 +1,26 @@
1
+ import { createRequire } from "node:module";
2
+ //#region \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), 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
+ //#endregion
26
+ export { __require as n, __toESM as r, __commonJSMin as t };
@@ -1,4 +1,4 @@
1
- import { t as KVRuntimeDriver } from "../driver-R4Z5Z5fl.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-C3NO4C21.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-C54QQEhN.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,7 @@
1
- import { t as kvInferredStoreNotice } from "../config-LfpUj9hs.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
- /**
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
- */
8
5
  async function logInferredStores() {
9
6
  const { durabilityReportsStores, kv } = await import("#vitehub/kv/config");
10
7
  if (!kv || durabilityReportsStores) return;
@@ -19,7 +16,14 @@ 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
28
  //#endregion
25
29
  export { kvNitroPlugin as default };
@@ -1,5 +1,5 @@
1
- import { z as ResolvedRedisKVStoreConfig } from "../types-Dv-OSXZC.js";
2
- import { t as KVRuntimeDriver } from "../driver-R4Z5Z5fl.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-C54QQEhN.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-5ogRd3-Y.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
@@ -1,5 +1,5 @@
1
- import { B as ResolvedUpstashKVStoreConfig } from "../types-Dv-OSXZC.js";
2
- import { t as KVRuntimeDriver } from "../driver-R4Z5Z5fl.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-C54QQEhN.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-5ogRd3-Y.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
@@ -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. */
@@ -164,7 +164,6 @@ type KVGetTypeMap = GetItemTypeMap;
164
164
  type KVGetOptions<K extends KVGetType | undefined = KVGetType | undefined> = Record<string, unknown> & {
165
165
  type?: K;
166
166
  };
167
- /** A read value: the caller's `T` without a `type`, the converted type with one. */
168
167
  type KVValue<T, K> = K extends KVGetType ? KVGetTypeMap[K] : T;
169
168
  /** Options of `kv.set()`, `kv.setMany()`, and `kv.setIfAbsent()`. Other fields return `KV_INVALID_OPTION`. */
170
169
  interface KVSetOptions {
@@ -210,7 +209,8 @@ interface KVLock {
210
209
  /**
211
210
  * Takes the lock, runs `fn`, and releases the lock, also when `fn` throws. An error from `fn` is thrown again after
212
211
  * 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`.
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.
214
214
  */
215
215
  run<T>(fn: () => T): Promise<Result<KVLockRunResult<Awaited<T>>, KVLockErrorCode>>;
216
216
  /** Takes the lock and returns a `release()` function. Prefer `run()`, which always releases. */
@@ -241,22 +241,8 @@ interface KVStorage {
241
241
  * The drivers in {@link KVDriversWith}`<"deleteIfEquals">` support it. The others return `KV_UNSUPPORTED_OPERATION`.
242
242
  */
243
243
  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
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">>;
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
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">>;
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
246
  getAndDelete<T = unknown, K extends "text" | undefined = undefined>(key: string, options?: {
261
247
  type?: K;
262
248
  }): Promise<Result<KVValue<T, K> | null, "KV_OPERATION_FAILED" | "KV_UNSUPPORTED_OPERATION">>;
@@ -1,5 +1,5 @@
1
- import { n as kvErrorDiagnostics } from "./error-diagnostics-C54QQEhN.js";
2
- import { a as upstashUrlEnvNames, i as upstashTokenEnvNames, s as readEnv } from "./config-LfpUj9hs.js";
1
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-C4VTHInS.js";
2
+ import { a as upstashUrlEnvNames, i as upstashTokenEnvNames, s as readEnv } from "./config-pfyPiPrI.js";
3
3
  //#region src/runtime/upstash.ts
4
4
  function isMaskedValue(value) {
5
5
  return !value || /^\*+$/.test(value);
package/dist/vite.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { L as ResolvedKVModuleOptions, w as KVOptions } from "./types-Dv-OSXZC.js";
2
- import { r as ViteHubCliPluginMetadata } from "./cli-DpPhz_Ek.js";
3
- import { n as OperationContributionEntry } from "./operation-definition-nmRu_O3V.js";
1
+ import { L as ResolvedKVModuleOptions, w as KVOptions } from "./types-Cp6IBhSN.js";
2
+ import { r as ViteHubCliPluginMetadata } from "./cli-CLomw9ml.js";
3
+ import { n as OperationContributionEntry } from "./operation-definition-CI2PJGqu.js";
4
4
  import "nostics";
5
5
  import { Plugin } from "vite";
6
6
  //#region src/config.d.ts
@@ -83,6 +83,8 @@ interface ViteHubResourceSummary {
83
83
  owner: string;
84
84
  /** Absent when no id is known yet. */
85
85
  source?: ViteHubResourceIdSource;
86
+ /** The resource is in the Wrangler config of a standalone Provider Output Worker, not in Nitro's. */
87
+ standalone?: boolean;
86
88
  }
87
89
  interface ViteHubInspectionContributor {
88
90
  definitions?: readonly ViteHubDefinitionInspector[];
@@ -172,11 +174,9 @@ export type KVVitePlugin = Plugin & {
172
174
  };
173
175
  };
174
176
  export declare function hubKVOptionalPeerResolver(): Plugin;
175
- /** The part of Nitro's prerender config that KV changes. */
176
177
  interface KVPrerenderConfig {
177
178
  virtual?: Record<string, string | (() => string)>;
178
179
  }
179
- /** The parts of a Nitro build that KV changes. */
180
180
  interface KVNitroBuild {
181
181
  hooks?: {
182
182
  hook: (name: "prerender:config", callback: (config: KVPrerenderConfig) => void) => unknown;
@@ -184,6 +184,9 @@ interface KVNitroBuild {
184
184
  options: NitroCloudflareKVTarget;
185
185
  }
186
186
  interface NitroCloudflareKVTarget {
187
+ deps?: {
188
+ paths?: Record<string, string>;
189
+ };
187
190
  handlers?: unknown[];
188
191
  kv?: Record<string, unknown>;
189
192
  storage?: Record<string, unknown>;