@vite-hub/kv 0.1.0 → 0.4.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 (65) hide show
  1. package/README.md +94 -21
  2. package/dist/batch--v0ri69O.js +40 -0
  3. package/dist/cli-DpPhz_Ek.d.ts +163 -0
  4. package/dist/cli.d.ts +4 -2
  5. package/dist/cli.js +99 -77
  6. package/dist/cloudflare-env-lOtHHsgP.js +46 -0
  7. package/dist/cloudflare-env-lookup-Bs0VDpU5.js +42 -0
  8. package/dist/cloudflare-kv-C3NO4C21.js +201 -0
  9. package/dist/cloudflare-kv-local-C2sbIrFy.js +71 -0
  10. package/dist/config-LfpUj9hs.js +252 -0
  11. package/dist/{create-storage-29gMzf41.js → create-storage-BORQm2a8.js} +206 -50
  12. package/dist/{cursor-history-dqYDlsaD.js → cursor-history-DRHh5bO5.js} +31 -14
  13. package/dist/database-oJdy0ZVX.js +250 -0
  14. package/dist/{deno-kv-CSYGvRx4.js → deno-kv-D_VtffFv.js} +12 -4
  15. package/dist/dev-peer-CHafxbtj.js +238 -0
  16. package/dist/driver-R4Z5Z5fl.d.ts +15 -0
  17. package/dist/durability.d.ts +17 -0
  18. package/dist/durability.js +53 -0
  19. package/dist/error-diagnostics-C54QQEhN.js +155 -0
  20. package/dist/errors-DzD6YNEH.js +88 -0
  21. package/dist/errors.d.ts +17 -1
  22. package/dist/errors.js +2 -2
  23. package/dist/fs-lite-BAgpmNAF.js +2 -0
  24. package/dist/fs-lite-BaklCLuV.js +386 -0
  25. package/dist/index.d.ts +7 -2
  26. package/dist/index.js +326 -84
  27. package/dist/inspect-BIKQsqX4.js +118 -0
  28. package/dist/invariant-DolT9EEx.js +22 -0
  29. package/dist/object-Da1zyPCR.js +11 -0
  30. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-nmRu_O3V.d.ts} +42 -15
  31. package/dist/{operations-pn8_eGob.js → operations-CtrWLmPK.js} +69 -66
  32. package/dist/operations-D2iI9oN4.js +1363 -0
  33. package/dist/operations.d.ts +15 -8
  34. package/dist/operations.js +56 -192
  35. package/dist/redis-shared-5ogRd3-Y.js +94 -0
  36. package/dist/runtime/cloudflare-kv.d.ts +1 -1
  37. package/dist/runtime/cloudflare-kv.js +1 -99
  38. package/dist/runtime/cloudflare-request-env.d.ts +7 -0
  39. package/dist/runtime/cloudflare-request-env.js +11 -0
  40. package/dist/runtime/nitro-plugin.d.ts +12 -0
  41. package/dist/runtime/nitro-plugin.js +25 -0
  42. package/dist/runtime/redis-driver.d.ts +11 -0
  43. package/dist/runtime/redis-driver.js +113 -0
  44. package/dist/runtime/unstorage-driver.d.ts +14 -0
  45. package/dist/runtime/unstorage-driver.js +37 -0
  46. package/dist/runtime/upstash-driver.d.ts +2 -2
  47. package/dist/runtime/upstash-driver.js +58 -98
  48. package/dist/{driver-D9fI27jl.d.ts → types-Bj3EQoRg.d.ts} +16 -41
  49. package/dist/types-Dv-OSXZC.d.ts +325 -0
  50. package/dist/upstash-B-vaUYqO.js +40 -0
  51. package/dist/{utils2-Dsb9P4_2.js → utils2-FozcTsmb.js} +5 -2
  52. package/dist/virtual-module.d.ts +3 -0
  53. package/dist/vite.d.ts +167 -14
  54. package/dist/vite.js +1195 -2876
  55. package/package.json +30 -21
  56. package/dist/cli-Cniq99iX.d.ts +0 -85
  57. package/dist/cloudflare-env-C5rM7kUY.js +0 -74
  58. package/dist/config-DR6_5ZwI.js +0 -124
  59. package/dist/continuations-DPyH_vr1.js +0 -63
  60. package/dist/error-diagnostics-D_cQeZTi.js +0 -82
  61. package/dist/errors-Dc2oiW-Y.js +0 -38
  62. package/dist/fs-lite-CbLKxLut.js +0 -90
  63. package/dist/object-B1NW521B.js +0 -7
  64. package/dist/operations-ByuDE12r.js +0 -1442
  65. package/dist/types-CMDvN0Wr.d.ts +0 -81
@@ -1,9 +1,11 @@
1
- import "./types-CMDvN0Wr.js";
2
- import { t as AnyOperation } from "./operations-tNUdj3G4.js";
1
+ import { c as KVDriver } from "./types-Dv-OSXZC.js";
2
+ import { t as AnyOperation } from "./operation-definition-nmRu_O3V.js";
3
3
  //#region src/runtime/operations.d.ts
4
4
  interface KVDevListResult {
5
5
  /** Present when more keys exist. Pass it as `--cursor` to read the next page. */
6
6
  cursor?: string;
7
+ /** The build-selected driver that this store uses. */
8
+ driver?: KVDriver;
7
9
  keys: string[];
8
10
  limit: number;
9
11
  prefix: string;
@@ -19,10 +21,10 @@ interface KVDevGetResult {
19
21
  /** With `preview`: how `value` is written. */
20
22
  format?: "json" | "text";
21
23
  /**
22
- * Whether the key can expire. `none`: the store never expires keys (fs-lite ignores TTL). `unknown`: the store can
23
- * expire keys, but its driver cannot report the time left, so a write that sets no TTL removes the expiry.
24
+ * Whether the key can expire. `unknown`: the store can expire keys, but its driver cannot report the time left, so a
25
+ * write that sets no TTL removes the expiry.
24
26
  */
25
- expiry?: "none" | "unknown";
27
+ expiry?: "unknown";
26
28
  /** With `preview`: the value was cut at 256 KiB. */
27
29
  truncated?: true;
28
30
  key: string;
@@ -55,14 +57,19 @@ interface KVDevDeleteResult {
55
57
  }
56
58
  //#endregion
57
59
  //#region ../internal/src/operations-dev.d.ts
58
- /** Bundled into owner packages and used only by their serve-only generated Nitro route. */
60
+ /**
61
+ * Bundled into owner packages and used only by their serve-only generated Nitro route. Operations get the Request as
62
+ * `context.event`, so owner hooks such as `identify` of Comments read its Standard Context.
63
+ */
59
64
  export declare function createStandaloneOperationHandler(sources: {
60
65
  operations: unknown;
61
66
  plugin: string;
62
- }[], root: string): (event: object) => Promise<Response>;
67
+ }[], root: string): {
68
+ fetch(request: Request): Promise<Response>;
69
+ };
63
70
  //#endregion
64
71
  //#region src/operations.d.ts
65
- /** The `kv.*` operations: list, get, has, set, and del. The Console, `vitehub kv`, and agents run them. */
72
+ /** The `kv.*` operations: list, get, has, set, and delete. The Console, `vitehub kv`, and agents run them. */
66
73
  export declare const kvOperations: readonly AnyOperation[];
67
74
  //#endregion
68
75
  export type { KVDevDeleteResult, KVDevGetResult, KVDevHasResult, KVDevListResult, KVDevSetResult };
@@ -1,6 +1,6 @@
1
- import { a as defineOperation, d as runOperation, f as toOperationFailure, i as createOperationRegistry, l as operationsOf, o as operationRootHeader, s as operationRpcHeader, t as assertOperationProject, u as projectRootHash } from "./operations-ByuDE12r.js";
1
+ import { M as internalErrorDiagnostics, a as operationRootHeader, c as projectRootHash, d as defineOperation, f as answerOperationRpc, h as readOperationRpcCall, i as createOperationRegistry, l as runOperation, m as operationRpcRefusal, o as operationRpcHeader, s as operationsOf, t as assertOperationProject, u as toOperationFailure } from "./operations-D2iI9oN4.js";
2
2
  import { t as kvDevMaximumListLimit } from "./results-p7nPCnaJ.js";
3
- import { i as resolveWaitUntil, r as getCloudflareEnv } from "./cloudflare-env-C5rM7kUY.js";
3
+ import { n as isViteHubLoopbackPeer } from "./dev-peer-CHafxbtj.js";
4
4
  import * as v from "valibot";
5
5
  //#region ../internal/src/secret.ts
6
6
  const secretEncoder = new TextEncoder();
@@ -16,6 +16,7 @@ function isViteHubSecretEqual(actual, expected) {
16
16
  for (let index = 0; index < right.length; index += 1) difference |= (left[index] ?? 0) ^ right[index];
17
17
  return difference === 0;
18
18
  }
19
+ Object.freeze({ prefix: "sha256=" });
19
20
  //#endregion
20
21
  //#region ../internal/src/dev-endpoint.ts
21
22
  const viteHubDevRequestGrantBrand = Symbol("vitehub.devRequestGrant");
@@ -98,176 +99,27 @@ async function validateViteHubNitroDevRequest(request, guard) {
98
99
  return rejection ? rejectDevRequest(rejection) : grantDevRequest(request, guard.label);
99
100
  }
100
101
  //#endregion
101
- //#region ../internal/src/runtime/h3-v1-request.ts
102
- const payloadMethods = /* @__PURE__ */ new Set([
103
- "DELETE",
104
- "PATCH",
105
- "POST",
106
- "PUT"
107
- ]);
108
- const rawBodySymbol = Symbol.for("h3RawBody");
109
- const nodeEventRequests = /* @__PURE__ */ new WeakMap();
110
- /** Return true for an event with an own `node.req` object, such as an H3 1 event. */
111
- function isH3V1Event(input) {
112
- if (!Object.hasOwn(input, "node")) return false;
113
- const node = Reflect.get(input, "node");
114
- return isObjectLike(node) && isObjectLike(Reflect.get(node, "req"));
115
- }
116
- function isObjectLike(value) {
117
- return value !== null && (typeof value === "object" || typeof value === "function");
118
- }
119
- function isWebRequest(value) {
120
- if (!isObjectLike(value)) return false;
121
- const headers = Reflect.get(value, "headers");
122
- return typeof Reflect.get(value, "url") === "string" && typeof Reflect.get(value, "method") === "string" && isObjectLike(headers) && typeof Reflect.get(headers, "get") === "function";
123
- }
124
- function firstHeader(value) {
125
- return Array.isArray(value) ? value[0] : value;
126
- }
127
- function readNodeRequestHeaders(request) {
128
- const headers = new Headers();
129
- for (const [name, value] of Object.entries(request.headers)) if (Array.isArray(value)) for (const item of value) headers.append(name, item);
130
- else if (value !== void 0) headers.set(name, value);
131
- return headers;
132
- }
133
- /** Rebuild the public URL. H3 1 removes the app base path from `url` and keeps it in `originalUrl`. */
134
- function readNodeRequestURL(request) {
135
- const host = firstHeader(request.headers.host) || "localhost";
136
- const encrypted = request.socket?.encrypted || request.connection?.encrypted;
137
- const protocol = firstHeader(request.headers["x-forwarded-proto"]) === "https" || encrypted ? "https" : "http";
138
- const path = (request.originalUrl || request.url || "/").replace(/^[/\\]+/, "/");
139
- return new URL(path, `${protocol}://${host}`);
140
- }
141
- function toBodyStream(value) {
142
- if (value instanceof ReadableStream) return value;
143
- if (value instanceof Uint8Array) return new ReadableStream({ start(controller) {
144
- controller.enqueue(value);
145
- controller.close();
146
- } });
147
- if (typeof value === "string") return new Blob([value]).stream();
148
- if (value instanceof URLSearchParams) return new Blob([value.toString()]).stream();
149
- if (value instanceof Object && Object.getPrototypeOf(value) === Object.prototype) return new Blob([JSON.stringify(value)]).stream();
150
- }
151
- async function openNodeRequestBody(event) {
152
- const request = event.node.req;
153
- const stored = event._requestBody ?? request[rawBodySymbol] ?? request.rawBody ?? request.body;
154
- if (stored !== void 0 && stored !== null) {
155
- const stream = toBodyStream(await stored);
156
- if (stream) {
157
- const reader = stream.getReader();
158
- return () => reader.read();
159
- }
160
- }
161
- const iterator = request[Symbol.asyncIterator]?.();
162
- if (!iterator) return void 0;
163
- const chunks = [];
164
- const collected = [];
165
- let total = 0;
166
- let ended = false;
167
- let failed = false;
168
- let failure;
169
- let waiting;
170
- const produce = async () => {
171
- try {
172
- for await (const chunk of { [Symbol.asyncIterator]: () => iterator }) {
173
- let bytes;
174
- if (typeof chunk === "string") bytes = new TextEncoder().encode(chunk);
175
- else if (chunk instanceof Uint8Array) bytes = chunk;
176
- else throw new TypeError("[vitehub] Request body chunks must be strings or bytes.");
177
- collected.push(bytes);
178
- total += bytes.byteLength;
179
- if (waiting) {
180
- waiting.resolve({ value: bytes });
181
- waiting = void 0;
182
- } else chunks.push(bytes);
183
- }
184
- ended = true;
185
- waiting?.resolve({ done: true });
186
- waiting = void 0;
187
- } catch (error) {
188
- failed = true;
189
- failure = error;
190
- ended = true;
191
- waiting?.reject(error);
192
- waiting = void 0;
193
- throw error;
194
- }
195
- const bytes = new Uint8Array(total);
196
- let offset = 0;
197
- for (const chunk of collected) {
198
- bytes.set(chunk, offset);
199
- offset += chunk.byteLength;
200
- }
201
- return bytes;
202
- };
203
- let body;
204
- const start = () => body ??= produce();
205
- event._requestBody = { then: (resolve, reject) => start().then(resolve, reject) };
206
- return async () => {
207
- start();
208
- body?.catch(() => {});
209
- if (failed) throw failure;
210
- if (chunks.length) return { value: chunks.shift() };
211
- if (ended) return { done: true };
212
- return new Promise((resolve, reject) => {
213
- waiting = {
214
- resolve,
215
- reject
216
- };
217
- });
218
- };
219
- }
220
- /** Read the body lazily, from a value a host already read or from the Node request stream. */
221
- function readNodeRequestBody(event) {
222
- let reader;
223
- return new ReadableStream({ async pull(controller) {
224
- const chunk = await (await (reader ??= openNodeRequestBody(event)))?.();
225
- if (!chunk || chunk.done) {
226
- controller.close();
227
- return;
228
- }
229
- const value = chunk.value;
230
- if (typeof value === "string") controller.enqueue(new TextEncoder().encode(value));
231
- else if (value instanceof Uint8Array) controller.enqueue(value);
232
- else controller.error(/* @__PURE__ */ new TypeError("[vitehub] Request body chunks must be strings or bytes."));
233
- } }, { highWaterMark: 0 });
234
- }
235
- /** Return one Web Request per H3 1 event. The body is read only when a caller reads the Request body. */
236
- function toH3V1Request(event) {
237
- const cached = nodeEventRequests.get(event);
238
- if (cached) return cached;
239
- if (isWebRequest(event.web?.request)) return event.web.request;
240
- const request = event.node.req;
241
- const method = (request.method || "GET").toUpperCase();
242
- const init = {
243
- headers: readNodeRequestHeaders(request),
244
- method
245
- };
246
- if (payloadMethods.has(method)) {
247
- init.body = readNodeRequestBody(event);
248
- init.duplex = "half";
249
- }
250
- const webRequest = new Request(readNodeRequestURL(request), init);
251
- nodeEventRequests.set(event, webRequest);
252
- return webRequest;
253
- }
254
- /**
255
- * Return the Web Request of a request, an H3 2 event with an own `req` request, or an H3 1 event such as Nuxt 4's.
256
- * H3 1 events have no `url`, so read the URL from the request this returns. Throws a `TypeError` for any other value.
257
- */
258
- function toEventRequest(event) {
259
- if (isWebRequest(event)) return event;
260
- const req = Object.hasOwn(event, "req") ? Reflect.get(event, "req") : void 0;
261
- if (isWebRequest(req)) return req;
262
- if (isH3V1Event(event)) return toH3V1Request(event);
263
- throw new TypeError("[vitehub] Expected a Request, an H3 2 event, or an H3 1 event.");
264
- }
265
- //#endregion
266
102
  //#region ../internal/src/operations-dev.ts
267
103
  function readPath(value, ...path) {
268
104
  for (const key of path) value = value !== null && typeof value === "object" ? Reflect.get(value, key) : void 0;
269
105
  return value;
270
106
  }
107
+ /** The Cloudflare bindings of a Request: from the Standard Context that Nitro sets, else where srvx puts them. */
108
+ function requestEnv(request) {
109
+ const env = readPath(request, "~standard", "runtime", "cloudflare", "env") ?? readPath(request, "runtime", "cloudflare", "env");
110
+ return env !== null && typeof env === "object" ? env : void 0;
111
+ }
112
+ /** The `waitUntil` of a Request: from its Standard Context, else from the Request or its Worker ExecutionContext. */
113
+ function requestWaitUntil(request) {
114
+ for (const owner of [
115
+ readPath(request, "~standard"),
116
+ request,
117
+ readPath(request, "runtime", "cloudflare", "context")
118
+ ]) {
119
+ const waitUntil = readPath(owner, "waitUntil");
120
+ if (typeof waitUntil === "function") return waitUntil.bind(owner);
121
+ }
122
+ }
271
123
  function localHost(host) {
272
124
  try {
273
125
  const name = new URL(`http://${host}`).hostname;
@@ -282,7 +134,10 @@ function reject(status, message) {
282
134
  status
283
135
  });
284
136
  }
285
- /** Bundled into owner packages and used only by their serve-only generated Nitro route. */
137
+ /**
138
+ * Bundled into owner packages and used only by their serve-only generated Nitro route. Operations get the Request as
139
+ * `context.event`, so owner hooks such as `identify` of Comments read its Standard Context.
140
+ */
286
141
  function createStandaloneOperationHandler(sources, root) {
287
142
  const registry = createOperationRegistry(sources.map((source) => ({
288
143
  ...source,
@@ -290,22 +145,21 @@ function createStandaloneOperationHandler(sources, root) {
290
145
  })));
291
146
  const defaultLimit = 65536;
292
147
  const maximum = Math.max(defaultLimit, ...registry.list().map((operation) => operation.maxRequestBytes ?? defaultLimit));
293
- return async (event) => {
148
+ const operations = Object.fromEntries(registry.list().map((operation) => [operation.name, operation]));
149
+ return { async fetch(request) {
294
150
  const headers = {
295
151
  "cache-control": "no-store",
296
152
  "x-content-type-options": "nosniff",
297
153
  [operationRootHeader]: projectRootHash(root)
298
154
  };
299
155
  try {
300
- const request = toEventRequest(event);
301
156
  const address = [
302
- readPath(event, "req", "ip"),
303
- readPath(event, "req", "context", "clientAddress"),
304
- readPath(event, "req", "runtime", "node", "req", "socket", "remoteAddress"),
305
- readPath(event, "node", "req", "socket", "remoteAddress")
157
+ readPath(request, "ip"),
158
+ readPath(request, "context", "clientAddress"),
159
+ readPath(request, "runtime", "node", "req", "socket", "remoteAddress")
306
160
  ].find((value) => typeof value === "string" && value !== "");
307
161
  const forwarded = request.headers.get("x-forwarded-host");
308
- if (!localHost(request.headers.get("host") ?? new URL(request.url).host) || forwarded && !localHost(forwarded) || address && address !== "::1" && !address.startsWith("127.") && !address.startsWith("::ffff:127.")) reject(403, "Standalone development operations accept only local requests.");
162
+ if (!localHost(request.headers.get("host") ?? new URL(request.url).host) || forwarded && !localHost(forwarded) || !await isViteHubLoopbackPeer(request, address)) reject(403, "Standalone development operations accept only local requests.");
309
163
  const site = request.headers.get("sec-fetch-site");
310
164
  if (site === "cross-site" || site === "same-site") reject(403, "Cross-origin operation requests are not allowed.");
311
165
  const checked = await validateViteHubNitroDevRequest(request, {
@@ -340,41 +194,51 @@ function createStandaloneOperationHandler(sources, root) {
340
194
  } catch {
341
195
  reject(400, "Malformed operation request.");
342
196
  }
343
- if (!payload || typeof payload !== "object" || !("operation" in payload) || typeof payload.operation !== "string") reject(400, "Invalid operation request.");
344
- if (bytes > (registry.get(payload.operation)?.maxRequestBytes ?? defaultLimit)) reject(413, "Operation request exceeds the byte limit.");
197
+ const call = readOperationRpcCall(payload);
198
+ if (!call) reject(400, "Invalid operation request.");
199
+ if (bytes > (registry.get(call.m)?.maxRequestBytes ?? defaultLimit)) reject(413, "Operation request exceeds the byte limit.");
345
200
  const response = {};
346
- const result = await runOperation(registry, payload.operation, "input" in payload ? payload.input : void 0, {
201
+ const context = {
347
202
  access: {
348
203
  mode: "local",
349
204
  sections: "all"
350
205
  },
351
206
  development: true,
207
+ projectRoot: root,
352
208
  surface: "cli",
353
209
  user: null,
354
210
  request,
211
+ event: request,
355
212
  response,
356
- env: getCloudflareEnv(event, { fallback: false }),
357
- waitUntil: resolveWaitUntil(event, { preferHost: true })
213
+ env: requestEnv(request),
214
+ waitUntil: requestWaitUntil(request)
215
+ };
216
+ const reply = await answerOperationRpc(call, {
217
+ failure: toOperationFailure,
218
+ operations,
219
+ run: async (operation, input) => {
220
+ const result = await runOperation(registry, operation.name, input, context);
221
+ if (!result.ok) throw Object.assign(new Error(result.message), result);
222
+ return result.value;
223
+ },
224
+ unknown: (name) => Object.assign(internalErrorDiagnostics.INTERNAL_R0021({ message: `No operation is named ${JSON.stringify(name)}.` }), { status: 404 })
358
225
  });
359
- return Response.json(result, {
226
+ return Response.json(reply, {
360
227
  headers,
361
- status: result.ok ? response.status ?? 200 : result.status
228
+ status: "e" in reply ? reply.e.status : response.status ?? 200
362
229
  });
363
230
  } catch (error) {
364
231
  const failure = toOperationFailure(error);
365
- return Response.json({
366
- ok: false,
367
- ...failure
368
- }, {
232
+ return Response.json(operationRpcRefusal(failure), {
369
233
  headers,
370
234
  status: failure.status
371
235
  });
372
236
  }
373
- };
237
+ } };
374
238
  }
375
239
  //#endregion
376
240
  //#region src/operations.ts
377
- const runtime = () => import("./operations-pn8_eGob.js");
241
+ const runtime = () => import("./operations-CtrWLmPK.js");
378
242
  const store = v.optional(v.pipe(v.string(), v.check((name) => name.trim() !== "", "Name a store.")));
379
243
  const key = v.string();
380
244
  function defineKVOperation(definition) {
@@ -384,7 +248,7 @@ function defineKVOperation(definition) {
384
248
  user: false
385
249
  });
386
250
  }
387
- /** The `kv.*` operations: list, get, has, set, and del. The Console, `vitehub kv`, and agents run them. */
251
+ /** The `kv.*` operations: list, get, has, set, and delete. The Console, `vitehub kv`, and agents run them. */
388
252
  const kvOperations = [
389
253
  defineKVOperation({
390
254
  cli: { command: "list" },
@@ -438,7 +302,7 @@ const kvOperations = [
438
302
  }),
439
303
  defineKVOperation({
440
304
  cli: {
441
- command: "del",
305
+ command: "delete",
442
306
  positional: ["key"]
443
307
  },
444
308
  description: "Delete one key. There is no operation that clears a store.",
@@ -447,8 +311,8 @@ const kvOperations = [
447
311
  store
448
312
  }),
449
313
  kind: "destructive",
450
- name: "kv.del",
451
- run: async (input) => await (await runtime()).runKVOperation("del", input)
314
+ name: "kv.delete",
315
+ run: async (input) => await (await runtime()).runKVOperation("delete", input)
452
316
  })
453
317
  ];
454
318
  //#endregion
@@ -0,0 +1,94 @@
1
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-C54QQEhN.js";
2
+ //#region src/runtime/redis-shared.ts
3
+ const redisIncrementScript = `
4
+ local existed = redis.call('EXISTS', KEYS[1])
5
+ local current = redis.call('GET', KEYS[1])
6
+ if current then
7
+ local negative = string.sub(current, 1, 1) == '-'
8
+ local digits = negative and string.sub(current, 2) or current
9
+ local boundary = negative and '9007199254740992' or '9007199254740991'
10
+ local beyond = #digits > #boundary or (#digits == #boundary and digits > boundary)
11
+ local at_positive_boundary = not negative and digits == boundary
12
+ if beyond or at_positive_boundary then
13
+ return redis.error_reply('Atomic KV increment exceeds the JavaScript safe integer range.')
14
+ end
15
+ end
16
+ local value = redis.call('INCR', KEYS[1])
17
+ if existed == 0 then
18
+ redis.call('EXPIRE', KEYS[1], ARGV[1])
19
+ end
20
+ return value
21
+ `;
22
+ /** Deletes the key only when it holds ARGV[1]. Redis runs a script as one step. */
23
+ const redisDeleteIfEqualsScript = `
24
+ if redis.call('GET', KEYS[1]) == ARGV[1] then
25
+ return redis.call('DEL', KEYS[1])
26
+ end
27
+ return 0
28
+ `;
29
+ /** Whole seconds for `EXPIRE` and `SET EX`. */
30
+ function redisTTLSeconds(ttl) {
31
+ if (!Number.isFinite(ttl) || ttl <= 0) throw kvErrorDiagnostics.KV_INVALID_TTL();
32
+ const seconds = Math.ceil(ttl);
33
+ if (!Number.isSafeInteger(seconds)) throw kvErrorDiagnostics.KV_INVALID_TTL();
34
+ return seconds;
35
+ }
36
+ function redisIncrementResult(value) {
37
+ const counter = Number(value);
38
+ if (!Number.isSafeInteger(counter)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "The counter exceeds the JavaScript safe integer range." });
39
+ return counter;
40
+ }
41
+ function escapeRedisGlob(value) {
42
+ return value.replaceAll(/([*?[\\\]])/g, "\\$1");
43
+ }
44
+ const maximumScanCount = 1e4;
45
+ function decodePortableCursor(cursor) {
46
+ try {
47
+ const value = JSON.parse(decodeURIComponent(cursor));
48
+ if (typeof value === "object" && value !== null) {
49
+ const scan = Reflect.get(value, "cursor");
50
+ const keys = Reflect.get(value, "keys");
51
+ if (typeof scan === "string" && /^\d+$/.test(scan) && Array.isArray(keys) && keys.every((key) => typeof key === "string")) return {
52
+ cursor: scan,
53
+ keys
54
+ };
55
+ }
56
+ } catch {}
57
+ throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "invalid" });
58
+ }
59
+ function encodePortableCursor(cursor) {
60
+ return encodeURIComponent(JSON.stringify(cursor));
61
+ }
62
+ /**
63
+ * `listKeys()` over Redis `SCAN` with a cursor that holds all its state, so another server process can read the next
64
+ * page. Overflow keys travel with the next SCAN cursor, preserving SCAN's full-iteration guarantee even when earlier
65
+ * pages are deleted. Like SCAN itself, a key that changes during the listing can be missed or repeated.
66
+ */
67
+ function createPortableRedisKeyLister(provider, scan) {
68
+ return async function listKeys({ cursor, limit, prefix = "" }) {
69
+ const state = cursor ? decodePortableCursor(cursor) : {
70
+ cursor: "0",
71
+ keys: []
72
+ };
73
+ let next = state.cursor;
74
+ let batch = state.keys;
75
+ if (batch.length === 0) {
76
+ const [position, found] = await scan(next, `${escapeRedisGlob(prefix)}*`, Math.min(limit, maximumScanCount));
77
+ if (position === next && position !== "0") throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: `${provider} scan returned a repeated pagination cursor.` });
78
+ next = position;
79
+ batch = [...new Set(found)].sort();
80
+ }
81
+ const keys = batch.slice(0, limit);
82
+ const overflow = batch.slice(limit);
83
+ if (overflow.length === 0 && next === "0") return { keys };
84
+ return {
85
+ keys,
86
+ cursor: encodePortableCursor({
87
+ cursor: next,
88
+ keys: overflow
89
+ })
90
+ };
91
+ };
92
+ }
93
+ //#endregion
94
+ export { redisIncrementScript as a, redisIncrementResult as i, escapeRedisGlob as n, redisTTLSeconds as o, redisDeleteIfEqualsScript as r, createPortableRedisKeyLister as t };
@@ -1,4 +1,4 @@
1
- import { t as KVRuntimeDriver } from "../driver-D9fI27jl.js";
1
+ import { t as KVRuntimeDriver } from "../driver-R4Z5Z5fl.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,100 +1,2 @@
1
- import { n as kvErrorDiagnostics } from "../error-diagnostics-D_cQeZTi.js";
2
- import { t as getActiveCloudflareBinding } from "../cloudflare-env-C5rM7kUY.js";
3
- import { n as normalizeKVListPrefix, t as createKVStorage } from "../create-storage-29gMzf41.js";
4
- import { n as recordCursor, t as createCursorHistory } from "../cursor-history-dqYDlsaD.js";
5
- import createDriver from "unstorage/drivers/cloudflare-kv-binding";
6
- //#region src/runtime/cloudflare-kv.ts
7
- function isCloudflareKVString(value) {
8
- return typeof value === "string";
9
- }
10
- function isCloudflareKVListPage(value) {
11
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
12
- const page = value;
13
- if (typeof page.list_complete !== "boolean" || !Array.isArray(page.keys)) return false;
14
- if (!page.keys.every((key) => {
15
- if (!key || typeof key !== "object" || Array.isArray(key)) return false;
16
- return isCloudflareKVString(Reflect.get(key, "name"));
17
- })) return false;
18
- return page.list_complete || isCloudflareKVString(page.cursor) && page.cursor.length > 0;
19
- }
20
- const cloudflareBindingIdentities = /* @__PURE__ */ new WeakMap();
21
- let nextCloudflareBindingIdentity = 0;
22
- function cloudflareBindingNamespace(bindingName, namespaceId, binding) {
23
- if (typeof namespaceId === "string" && namespaceId.length > 0) return `cloudflare-kv:id:${namespaceId}`;
24
- if (binding && typeof binding === "object") {
25
- let identity = cloudflareBindingIdentities.get(binding);
26
- if (identity === void 0) {
27
- identity = ++nextCloudflareBindingIdentity;
28
- cloudflareBindingIdentities.set(binding, identity);
29
- }
30
- return `cloudflare-kv:object:${identity}`;
31
- }
32
- return typeof bindingName === "string" ? `cloudflare-kv:binding:${bindingName}` : "cloudflare-kv:default";
33
- }
34
- function createCloudflareDriver(options) {
35
- const bindingName = options.binding;
36
- const namespaceId = options.namespaceId;
37
- const driverOptions = typeof bindingName === "string" ? {
38
- ...options,
39
- get binding() {
40
- return getActiveCloudflareBinding(bindingName) ?? bindingName;
41
- }
42
- } : options;
43
- const driver = createDriver(driverOptions);
44
- const cursorNamespace = cloudflareBindingNamespace(bindingName, namespaceId);
45
- const cursorHistories = createCursorHistory(cursorNamespace);
46
- let disposed = false;
47
- const dispose = driver.dispose;
48
- driver.dispose = async () => {
49
- disposed = true;
50
- cursorHistories.clear();
51
- try {
52
- await dispose?.call(driver);
53
- } finally {
54
- cursorHistories.clear();
55
- }
56
- };
57
- driver.listKeys = async ({ cursor, limit, prefix = "" }) => {
58
- if (disposed) throw new Error("KV storage has been disposed.");
59
- const listOptions = { limit };
60
- if (cursor) listOptions.cursor = cursor;
61
- if (prefix) listOptions.prefix = prefix;
62
- const activeBinding = typeof bindingName === "string" ? getActiveCloudflareBinding(bindingName) : void 0;
63
- const requestNamespace = cloudflareBindingNamespace(bindingName, namespaceId, activeBinding);
64
- const continuation = cursor ? cursorHistories.take(cursor, requestNamespace) : {
65
- providerCursor: void 0,
66
- history: /* @__PURE__ */ new Set(),
67
- namespace: requestNamespace
68
- };
69
- try {
70
- if (continuation.providerCursor) listOptions.cursor = continuation.providerCursor;
71
- const cursors = continuation.history;
72
- const page = await driver.getInstance().list(listOptions);
73
- if (!isCloudflareKVListPage(page)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Cloudflare KV list returned an invalid page." });
74
- const result = { keys: page.keys.map((key) => key.name) };
75
- if (!page.list_complete) {
76
- if (disposed) throw new Error("KV storage has been disposed.");
77
- if (cursors.has(page.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "ViteHub rejected a repeated pagination cursor." });
78
- if (!recordCursor(cursors, page.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "ViteHub rejected pagination after the cursor history limit was reached." });
79
- result.cursor = cursorHistories.store(page.cursor, cursors, requestNamespace);
80
- }
81
- cursorHistories.complete(cursor);
82
- return result;
83
- } catch (error) {
84
- if (cursor && !disposed) cursorHistories.restore(cursor, continuation);
85
- throw error;
86
- }
87
- };
88
- return driver;
89
- }
90
- function createCloudflareKVStorage(options) {
91
- const driver = createCloudflareDriver(options);
92
- const storage = createKVStorage(driver);
93
- storage.listKeys = (listOptions) => driver.listKeys({
94
- ...listOptions,
95
- prefix: normalizeKVListPrefix(listOptions.prefix)
96
- });
97
- return storage;
98
- }
99
- //#endregion
1
+ import { n as createCloudflareKVStorage, t as createCloudflareDriver } from "../cloudflare-kv-C3NO4C21.js";
100
2
  export { createCloudflareKVStorage, createCloudflareDriver as default };
@@ -0,0 +1,7 @@
1
+ //#region src/runtime/cloudflare-request-env.d.ts
2
+ /**
3
+ * Nitro middleware for Cloudflare KV. A Cloudflare KV store reads its binding from the active env, and only the request
4
+ * carries that env in `vite dev`, so the middleware installs it before the route runs.
5
+ */
6
+ export default function vitehubKVCloudflareRequestEnv(event: unknown): void;
7
+ //#endregion
@@ -0,0 +1,11 @@
1
+ import { n as installCloudflareRequestEnv } from "../cloudflare-env-lOtHHsgP.js";
2
+ //#region src/runtime/cloudflare-request-env.ts
3
+ /**
4
+ * Nitro middleware for Cloudflare KV. A Cloudflare KV store reads its binding from the active env, and only the request
5
+ * carries that env in `vite dev`, so the middleware installs it before the route runs.
6
+ */
7
+ function vitehubKVCloudflareRequestEnv(event) {
8
+ installCloudflareRequestEnv(event);
9
+ }
10
+ //#endregion
11
+ export { vitehubKVCloudflareRequestEnv as default };
@@ -0,0 +1,12 @@
1
+ //#region src/runtime/nitro-plugin.d.ts
2
+ interface NitroAppLike {
3
+ hooks: {
4
+ hook(name: "close", callback: () => Promise<void>): unknown;
5
+ };
6
+ }
7
+ /**
8
+ * Nitro plugin of KV for Redis connections and inferred-store boot notices. On close it releases KV connections,
9
+ * so the process can exit.
10
+ */
11
+ export default function kvNitroPlugin(nitroApp: NitroAppLike): void;
12
+ //#endregion
@@ -0,0 +1,25 @@
1
+ import { t as kvInferredStoreNotice } from "../config-LfpUj9hs.js";
2
+ 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
+ */
8
+ async function logInferredStores() {
9
+ const { durabilityReportsStores, kv } = await import("#vitehub/kv/config");
10
+ if (!kv || durabilityReportsStores) return;
11
+ for (const [name, store] of Object.entries(kv.stores ?? { default: kv.store })) {
12
+ const notice = kvInferredStoreNotice(name, store);
13
+ if (notice) console.info(notice);
14
+ }
15
+ }
16
+ /**
17
+ * Nitro plugin of KV for Redis connections and inferred-store boot notices. On close it releases KV connections,
18
+ * so the process can exit.
19
+ */
20
+ function kvNitroPlugin(nitroApp) {
21
+ nitroApp.hooks.hook("close", disposeKVStores);
22
+ logInferredStores().catch((error) => console.warn("[vitehub] Could not read the KV configuration.", error));
23
+ }
24
+ //#endregion
25
+ export { kvNitroPlugin as default };
@@ -0,0 +1,11 @@
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
4
+ /** The URL of a store: `env:<NAME>` reads the variable now, so a build never holds the URL of its server. */
5
+ export declare function resolveRedisUrl(url: string, env?: Record<string, string | undefined>): string;
6
+ /**
7
+ * KV over a Redis server through TCP, with `ioredis`. Each atomic operation is one command or one script. This module
8
+ * loads only for a Redis store, so other stores do not load `ioredis`.
9
+ */
10
+ export default function createRedisKVDriver(options: ResolvedRedisKVStoreConfig): KVRuntimeDriver;
11
+ //#endregion