@vite-hub/kv 0.0.4 → 0.3.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.
- package/README.md +110 -14
- package/dist/batch--v0ri69O.js +40 -0
- package/dist/cli-DpPhz_Ek.d.ts +163 -0
- package/dist/cli.d.ts +17 -0
- package/dist/cli.js +469 -0
- package/dist/cloudflare-env-lOtHHsgP.js +46 -0
- package/dist/cloudflare-env-lookup-Bs0VDpU5.js +42 -0
- package/dist/cloudflare-kv-BIEUFzRT.js +187 -0
- package/dist/cloudflare-kv-local-BBw3ZT1K.js +71 -0
- package/dist/config-BXEVoZE3.js +250 -0
- package/dist/{dist-DDW1iC5f.js → create-storage-BGsrQKw3.js} +266 -115
- package/dist/cursor-history-BqIQePNP.js +165 -0
- package/dist/database-72Jk3VVk.js +250 -0
- package/dist/deno-kv-BM9mYdUp.js +128 -0
- package/dist/dev-peer-CHafxbtj.js +238 -0
- package/dist/driver-BwxgaQ-f.d.ts +15 -0
- package/dist/durability.d.ts +17 -0
- package/dist/durability.js +53 -0
- package/dist/error-diagnostics-BxqvtEIb.js +147 -0
- package/dist/errors-DbwufFZp.js +60 -0
- package/dist/errors.d.ts +23 -7
- package/dist/errors.js +2 -20
- package/dist/fs-lite-BLZId9_P.js +386 -0
- package/dist/fs-lite-RAoxu8L0.js +2 -0
- package/dist/index.d.ts +10 -4
- package/dist/index.js +364 -109
- package/dist/inspect-BIKQsqX4.js +118 -0
- package/dist/invariant-DolT9EEx.js +22 -0
- package/dist/main-F3Y22_uV.js +2353 -0
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
- package/dist/operations-B-WZ7P1h.js +1351 -0
- package/dist/operations-Ch-gKaey.js +441 -0
- package/dist/operations.d.ts +75 -0
- package/dist/operations.js +318 -0
- package/dist/redis-shared-E5mahECF.js +94 -0
- package/dist/results-p7nPCnaJ.js +6 -0
- package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
- package/dist/runtime/cloudflare-kv.d.ts +3 -4
- package/dist/runtime/cloudflare-kv.js +1 -23
- package/dist/runtime/cloudflare-request-env.d.ts +7 -0
- package/dist/runtime/cloudflare-request-env.js +11 -0
- package/dist/runtime/nitro-plugin.d.ts +12 -0
- package/dist/runtime/nitro-plugin.js +22 -0
- package/dist/runtime/redis-driver.d.ts +11 -0
- package/dist/runtime/redis-driver.js +113 -0
- package/dist/runtime/unstorage-driver.d.ts +14 -0
- package/dist/runtime/unstorage-driver.js +33 -0
- package/dist/runtime/upstash-driver.d.ts +4 -6
- package/dist/runtime/upstash-driver.js +60 -110
- package/dist/{driver-BT9WefKi.d.ts → types-Bj3EQoRg.d.ts} +16 -11
- package/dist/types-DEiKew_3.d.ts +312 -0
- package/dist/upstash-DDlqTttY.js +40 -0
- package/dist/utils2-FozcTsmb.js +31 -0
- package/dist/virtual-module.d.ts +2 -0
- package/dist/virtual.d.ts +1 -1
- package/dist/vite.d.ts +159 -14
- package/dist/vite.js +1329 -2898
- package/package.json +68 -19
- package/dist/config-aM9Ae7tH.js +0 -110
- package/dist/deno-kv-cJx3jU10.js +0 -69
- package/dist/fs-lite-BxzdiJSi.js +0 -79
- package/dist/types-CO0DRjJa.d.ts +0 -78
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
import { a as operationRootHeader, c as projectRootHash, d as defineOperation, f as answerOperationRpc, g as internalErrorDiagnostics, 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-B-WZ7P1h.js";
|
|
2
|
+
import { t as kvDevMaximumListLimit } from "./results-p7nPCnaJ.js";
|
|
3
|
+
import { n as isViteHubLoopbackPeer } from "./dev-peer-CHafxbtj.js";
|
|
4
|
+
import * as v from "valibot";
|
|
5
|
+
//#region ../internal/src/secret.ts
|
|
6
|
+
const secretEncoder = new TextEncoder();
|
|
7
|
+
/**
|
|
8
|
+
* Compares a request value with an expected secret in constant time for the length of `expected`. Returns `false`
|
|
9
|
+
* when either value is missing or empty. It uses no Node API, so it also runs in Worker runtimes.
|
|
10
|
+
*/
|
|
11
|
+
function isViteHubSecretEqual(actual, expected) {
|
|
12
|
+
if (!actual || !expected) return false;
|
|
13
|
+
const left = secretEncoder.encode(actual);
|
|
14
|
+
const right = secretEncoder.encode(expected);
|
|
15
|
+
let difference = left.length ^ right.length;
|
|
16
|
+
for (let index = 0; index < right.length; index += 1) difference |= (left[index] ?? 0) ^ right[index];
|
|
17
|
+
return difference === 0;
|
|
18
|
+
}
|
|
19
|
+
Object.freeze({ prefix: "sha256=" });
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region ../internal/src/dev-endpoint.ts
|
|
22
|
+
const viteHubDevRequestGrantBrand = Symbol("vitehub.devRequestGrant");
|
|
23
|
+
const devRequestGrants = /* @__PURE__ */ new WeakMap();
|
|
24
|
+
function grantDevRequest(request, label) {
|
|
25
|
+
const grant = Object.freeze({
|
|
26
|
+
[viteHubDevRequestGrantBrand]: true,
|
|
27
|
+
label
|
|
28
|
+
});
|
|
29
|
+
devRequestGrants.set(grant, request);
|
|
30
|
+
return { grant };
|
|
31
|
+
}
|
|
32
|
+
function rejectDevRequest(rejection) {
|
|
33
|
+
return { rejection };
|
|
34
|
+
}
|
|
35
|
+
const fileOrExtensionProtocol = /^(?:file|.+-extension):/i;
|
|
36
|
+
const ipv4Octet = "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)";
|
|
37
|
+
const ipv4Literal = new RegExp(`^${ipv4Octet}(?:\\.${ipv4Octet}){3}$`);
|
|
38
|
+
/**
|
|
39
|
+
* Tests IP literals like `node:net` `isIP`, without a Node import, so the Nitro-side check also runs in Worker
|
|
40
|
+
* runtimes. IPv4 uses the Node pattern (dotted decimal, no leading zeros). IPv6 uses the WHATWG URL parser, which
|
|
41
|
+
* rejects zone IDs. Browsers do not send zone IDs in `Host`.
|
|
42
|
+
*/
|
|
43
|
+
function isIPv4Literal(value) {
|
|
44
|
+
return ipv4Literal.test(value);
|
|
45
|
+
}
|
|
46
|
+
function isIPv6Literal(value) {
|
|
47
|
+
if (!value.includes(":") || !/^[\d.:a-f]+$/i.test(value)) return false;
|
|
48
|
+
try {
|
|
49
|
+
return new URL(`http://[${value}]/`).hostname !== "";
|
|
50
|
+
} catch {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function hostHeaderAllowed(host, allowedHosts) {
|
|
55
|
+
if (fileOrExtensionProtocol.test(host)) return true;
|
|
56
|
+
const trimmed = host.trim();
|
|
57
|
+
if (trimmed.startsWith("[")) {
|
|
58
|
+
const end = trimmed.indexOf("]");
|
|
59
|
+
return end > 0 && isIPv6Literal(trimmed.slice(1, end));
|
|
60
|
+
}
|
|
61
|
+
const colon = trimmed.indexOf(":");
|
|
62
|
+
const hostname = (colon === -1 ? trimmed : trimmed.slice(0, colon)).toLowerCase();
|
|
63
|
+
if (isIPv4Literal(hostname)) return true;
|
|
64
|
+
if (hostname === "localhost" || hostname.endsWith(".localhost")) return true;
|
|
65
|
+
return allowedHosts.some((allowed) => {
|
|
66
|
+
const normalized = allowed.toLowerCase();
|
|
67
|
+
return normalized === hostname || normalized.startsWith(".") && (normalized.slice(1) === hostname || hostname.endsWith(normalized));
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Checks the host of a request that reaches the Nitro dev handler.
|
|
72
|
+
*
|
|
73
|
+
* {@link forwardViteHubDevRequestToNitro} always calls `http://localhost`, so a forwarded request passes. The Nitro
|
|
74
|
+
* route is also reachable over HTTP on the dev server, and the Nitro runtime does not know `server.allowedHosts`.
|
|
75
|
+
* This check therefore accepts only `localhost`, `*.localhost`, and IP literals in the request URL and in the `Host`
|
|
76
|
+
* header. A DNS rebinding page uses another host name, so it gets `403`.
|
|
77
|
+
*/
|
|
78
|
+
function isViteHubNitroDevHostAllowed(request) {
|
|
79
|
+
const host = request.headers.get("host");
|
|
80
|
+
return hostHeaderAllowed(new URL(request.url).host, []) && (host === null || hostHeaderAllowed(host, []));
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Checks a request inside the Nitro dev handler: the host, the guard header, the request origin, `POST`, the JSON
|
|
84
|
+
* content type, and the optional owner `authorize` callback. Returns a grant bound to `request`, or the rejection
|
|
85
|
+
* response. The Nitro route exists only in `vite dev`, but it is reachable on the dev server origin, so it checks the
|
|
86
|
+
* same guard as the Vite endpoint.
|
|
87
|
+
*/
|
|
88
|
+
async function validateViteHubNitroDevRequest(request, guard) {
|
|
89
|
+
if (!isViteHubNitroDevHostAllowed(request)) return rejectDevRequest(new Response(`Forbidden ${guard.label} host.`, { status: 403 }));
|
|
90
|
+
if (!isViteHubSecretEqual(request.headers.get(guard.header), guard.headerValue)) return rejectDevRequest(new Response(`Forbidden ${guard.label} request.`, { status: 403 }));
|
|
91
|
+
const origin = request.headers.get("origin");
|
|
92
|
+
if (origin && origin !== new URL(request.url).origin) return rejectDevRequest(new Response(`Forbidden ${guard.label} origin.`, { status: 403 }));
|
|
93
|
+
if (request.method !== "POST") return rejectDevRequest(new Response("Method not allowed.", {
|
|
94
|
+
headers: { allow: "POST" },
|
|
95
|
+
status: 405
|
|
96
|
+
}));
|
|
97
|
+
if (!request.headers.get("content-type")?.toLowerCase().startsWith("application/json")) return rejectDevRequest(new Response(`${guard.label} requests must use application/json.`, { status: 415 }));
|
|
98
|
+
const rejection = await guard.authorize?.(request);
|
|
99
|
+
return rejection ? rejectDevRequest(rejection) : grantDevRequest(request, guard.label);
|
|
100
|
+
}
|
|
101
|
+
//#endregion
|
|
102
|
+
//#region ../internal/src/operations-dev.ts
|
|
103
|
+
function readPath(value, ...path) {
|
|
104
|
+
for (const key of path) value = value !== null && typeof value === "object" ? Reflect.get(value, key) : void 0;
|
|
105
|
+
return value;
|
|
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
|
+
}
|
|
123
|
+
function localHost(host) {
|
|
124
|
+
try {
|
|
125
|
+
const name = new URL(`http://${host}`).hostname;
|
|
126
|
+
return name === "localhost" || name.endsWith(".localhost") || name === "127.0.0.1" || name === "[::1]";
|
|
127
|
+
} catch {
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function reject(status, message) {
|
|
132
|
+
throw Object.assign(new Error(message), {
|
|
133
|
+
code: "OPERATION_DEV_REQUEST",
|
|
134
|
+
status
|
|
135
|
+
});
|
|
136
|
+
}
|
|
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
|
+
*/
|
|
141
|
+
function createStandaloneOperationHandler(sources, root) {
|
|
142
|
+
const registry = createOperationRegistry(sources.map((source) => ({
|
|
143
|
+
...source,
|
|
144
|
+
operations: operationsOf(source.operations)
|
|
145
|
+
})));
|
|
146
|
+
const defaultLimit = 65536;
|
|
147
|
+
const maximum = Math.max(defaultLimit, ...registry.list().map((operation) => operation.maxRequestBytes ?? defaultLimit));
|
|
148
|
+
const operations = Object.fromEntries(registry.list().map((operation) => [operation.name, operation]));
|
|
149
|
+
return { async fetch(request) {
|
|
150
|
+
const headers = {
|
|
151
|
+
"cache-control": "no-store",
|
|
152
|
+
"x-content-type-options": "nosniff",
|
|
153
|
+
[operationRootHeader]: projectRootHash(root)
|
|
154
|
+
};
|
|
155
|
+
try {
|
|
156
|
+
const address = [
|
|
157
|
+
readPath(request, "ip"),
|
|
158
|
+
readPath(request, "context", "clientAddress"),
|
|
159
|
+
readPath(request, "runtime", "node", "req", "socket", "remoteAddress")
|
|
160
|
+
].find((value) => typeof value === "string" && value !== "");
|
|
161
|
+
const forwarded = request.headers.get("x-forwarded-host");
|
|
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.");
|
|
163
|
+
const site = request.headers.get("sec-fetch-site");
|
|
164
|
+
if (site === "cross-site" || site === "same-site") reject(403, "Cross-origin operation requests are not allowed.");
|
|
165
|
+
const checked = await validateViteHubNitroDevRequest(request, {
|
|
166
|
+
header: operationRpcHeader,
|
|
167
|
+
headerValue: "1",
|
|
168
|
+
label: "Operation RPC"
|
|
169
|
+
});
|
|
170
|
+
if (checked.rejection) reject(checked.rejection.status, await checked.rejection.text());
|
|
171
|
+
assertOperationProject(request, root);
|
|
172
|
+
const reader = request.body?.getReader();
|
|
173
|
+
const decoder = new TextDecoder();
|
|
174
|
+
let text = "";
|
|
175
|
+
let bytes = 0;
|
|
176
|
+
try {
|
|
177
|
+
if (reader) while (true) {
|
|
178
|
+
const chunk = await reader.read();
|
|
179
|
+
if (chunk.done) break;
|
|
180
|
+
bytes += chunk.value.byteLength;
|
|
181
|
+
if (bytes > maximum) reject(413, "Operation request exceeds the byte limit.");
|
|
182
|
+
text += decoder.decode(chunk.value, { stream: true });
|
|
183
|
+
}
|
|
184
|
+
text += decoder.decode();
|
|
185
|
+
} catch (error) {
|
|
186
|
+
await reader?.cancel();
|
|
187
|
+
throw error;
|
|
188
|
+
} finally {
|
|
189
|
+
reader?.releaseLock();
|
|
190
|
+
}
|
|
191
|
+
let payload;
|
|
192
|
+
try {
|
|
193
|
+
payload = JSON.parse(text);
|
|
194
|
+
} catch {
|
|
195
|
+
reject(400, "Malformed operation request.");
|
|
196
|
+
}
|
|
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.");
|
|
200
|
+
const response = {};
|
|
201
|
+
const context = {
|
|
202
|
+
access: {
|
|
203
|
+
mode: "local",
|
|
204
|
+
sections: "all"
|
|
205
|
+
},
|
|
206
|
+
development: true,
|
|
207
|
+
surface: "cli",
|
|
208
|
+
user: null,
|
|
209
|
+
request,
|
|
210
|
+
event: request,
|
|
211
|
+
response,
|
|
212
|
+
env: requestEnv(request),
|
|
213
|
+
waitUntil: requestWaitUntil(request)
|
|
214
|
+
};
|
|
215
|
+
const reply = await answerOperationRpc(call, {
|
|
216
|
+
failure: toOperationFailure,
|
|
217
|
+
operations,
|
|
218
|
+
run: async (operation, input) => {
|
|
219
|
+
const result = await runOperation(registry, operation.name, input, context);
|
|
220
|
+
if (!result.ok) throw Object.assign(new Error(result.message), result);
|
|
221
|
+
return result.value;
|
|
222
|
+
},
|
|
223
|
+
unknown: (name) => Object.assign(internalErrorDiagnostics.INTERNAL_R0021({ message: `No operation is named ${JSON.stringify(name)}.` }), { status: 404 })
|
|
224
|
+
});
|
|
225
|
+
return Response.json(reply, {
|
|
226
|
+
headers,
|
|
227
|
+
status: "e" in reply ? reply.e.status : response.status ?? 200
|
|
228
|
+
});
|
|
229
|
+
} catch (error) {
|
|
230
|
+
const failure = toOperationFailure(error);
|
|
231
|
+
return Response.json(operationRpcRefusal(failure), {
|
|
232
|
+
headers,
|
|
233
|
+
status: failure.status
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
} };
|
|
237
|
+
}
|
|
238
|
+
//#endregion
|
|
239
|
+
//#region src/operations.ts
|
|
240
|
+
const runtime = () => import("./operations-Ch-gKaey.js");
|
|
241
|
+
const store = v.optional(v.pipe(v.string(), v.check((name) => name.trim() !== "", "Name a store.")));
|
|
242
|
+
const key = v.string();
|
|
243
|
+
function defineKVOperation(definition) {
|
|
244
|
+
return defineOperation({
|
|
245
|
+
...definition,
|
|
246
|
+
section: "kv",
|
|
247
|
+
user: false
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
/** The `kv.*` operations: list, get, has, set, and delete. The Console, `vitehub kv`, and agents run them. */
|
|
251
|
+
const kvOperations = [
|
|
252
|
+
defineKVOperation({
|
|
253
|
+
cli: { command: "list" },
|
|
254
|
+
description: "List the keys of a KV store, one page at a time.",
|
|
255
|
+
input: v.object({
|
|
256
|
+
cursor: v.optional(v.string()),
|
|
257
|
+
limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(kvDevMaximumListLimit))),
|
|
258
|
+
prefix: v.optional(v.string()),
|
|
259
|
+
store
|
|
260
|
+
}),
|
|
261
|
+
kind: "read",
|
|
262
|
+
name: "kv.list",
|
|
263
|
+
run: async (input) => await (await runtime()).runKVOperation("list", input)
|
|
264
|
+
}),
|
|
265
|
+
defineKVOperation({
|
|
266
|
+
cli: { positional: ["key"] },
|
|
267
|
+
description: "Read the value of one key. `preview` returns it as text of at most 256 KiB.",
|
|
268
|
+
input: v.object({
|
|
269
|
+
key,
|
|
270
|
+
preview: v.optional(v.boolean()),
|
|
271
|
+
store
|
|
272
|
+
}),
|
|
273
|
+
kind: "read",
|
|
274
|
+
name: "kv.get",
|
|
275
|
+
run: async (input) => await (await runtime()).runKVOperation("get", input)
|
|
276
|
+
}),
|
|
277
|
+
defineKVOperation({
|
|
278
|
+
cli: { positional: ["key"] },
|
|
279
|
+
description: "Check if a key exists.",
|
|
280
|
+
input: v.object({
|
|
281
|
+
key,
|
|
282
|
+
store
|
|
283
|
+
}),
|
|
284
|
+
kind: "read",
|
|
285
|
+
name: "kv.has",
|
|
286
|
+
run: async (input) => await (await runtime()).runKVOperation("has", input)
|
|
287
|
+
}),
|
|
288
|
+
defineKVOperation({
|
|
289
|
+
cli: { positional: ["key", "value"] },
|
|
290
|
+
description: "Write the value of one key. A string, or any JSON value.",
|
|
291
|
+
input: v.object({
|
|
292
|
+
key,
|
|
293
|
+
store,
|
|
294
|
+
ttl: v.optional(v.pipe(v.number(), v.finite(), v.gtValue(0))),
|
|
295
|
+
value: v.unknown()
|
|
296
|
+
}),
|
|
297
|
+
kind: "write",
|
|
298
|
+
maxRequestBytes: 4194304,
|
|
299
|
+
name: "kv.set",
|
|
300
|
+
run: async (input) => await (await runtime()).runKVOperation("set", input)
|
|
301
|
+
}),
|
|
302
|
+
defineKVOperation({
|
|
303
|
+
cli: {
|
|
304
|
+
command: "delete",
|
|
305
|
+
positional: ["key"]
|
|
306
|
+
},
|
|
307
|
+
description: "Delete one key. There is no operation that clears a store.",
|
|
308
|
+
input: v.object({
|
|
309
|
+
key,
|
|
310
|
+
store
|
|
311
|
+
}),
|
|
312
|
+
kind: "destructive",
|
|
313
|
+
name: "kv.delete",
|
|
314
|
+
run: async (input) => await (await runtime()).runKVOperation("delete", input)
|
|
315
|
+
})
|
|
316
|
+
];
|
|
317
|
+
//#endregion
|
|
318
|
+
export { createStandaloneOperationHandler, kvOperations };
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.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 };
|
|
@@ -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,7 +1,6 @@
|
|
|
1
|
-
import { t as KVRuntimeDriver } from "../driver-
|
|
2
|
-
|
|
1
|
+
import { t as KVRuntimeDriver } from "../driver-BwxgaQ-f.js";
|
|
3
2
|
//#region src/runtime/cloudflare-kv.d.ts
|
|
4
3
|
declare function createCloudflareDriver(options: Record<string, unknown>): KVRuntimeDriver;
|
|
5
|
-
declare function createCloudflareKVStorage(options: Record<string, unknown>): unknown;
|
|
4
|
+
export declare function createCloudflareKVStorage(options: Record<string, unknown>): unknown;
|
|
6
5
|
//#endregion
|
|
7
|
-
export {
|
|
6
|
+
export { createCloudflareDriver as default };
|
|
@@ -1,24 +1,2 @@
|
|
|
1
|
-
import { t as
|
|
2
|
-
import createDriver from "unstorage/drivers/cloudflare-kv-binding";
|
|
3
|
-
//#region src/runtime/cloudflare-kv.ts
|
|
4
|
-
function createCloudflareDriver(options) {
|
|
5
|
-
const driver = createDriver(options);
|
|
6
|
-
driver.listKeys = async ({ cursor, limit, prefix = "" }) => {
|
|
7
|
-
const listOptions = { limit };
|
|
8
|
-
if (cursor) listOptions.cursor = cursor;
|
|
9
|
-
if (prefix) listOptions.prefix = prefix;
|
|
10
|
-
const page = await driver.getInstance().list(listOptions);
|
|
11
|
-
const result = { keys: page.keys.map((key) => key.name) };
|
|
12
|
-
if (!page.list_complete) result.cursor = page.cursor;
|
|
13
|
-
return result;
|
|
14
|
-
};
|
|
15
|
-
return driver;
|
|
16
|
-
}
|
|
17
|
-
function createCloudflareKVStorage(options) {
|
|
18
|
-
const driver = createCloudflareDriver(options);
|
|
19
|
-
const storage = createStorage({ driver });
|
|
20
|
-
storage.listKeys = (listOptions) => driver.listKeys(listOptions);
|
|
21
|
-
return storage;
|
|
22
|
-
}
|
|
23
|
-
//#endregion
|
|
1
|
+
import { n as createCloudflareKVStorage, t as createCloudflareDriver } from "../cloudflare-kv-BIEUFzRT.js";
|
|
24
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,22 @@
|
|
|
1
|
+
import { t as kvInferredStoreNotice } from "../config-BXEVoZE3.js";
|
|
2
|
+
import { disposeKVStores } from "@vite-hub/kv";
|
|
3
|
+
//#region src/runtime/nitro-plugin.ts
|
|
4
|
+
/** Prints the driver that each inferred store uses in this process. */
|
|
5
|
+
async function logInferredStores() {
|
|
6
|
+
const { kv } = await import("#vitehub/kv/config");
|
|
7
|
+
if (!kv) return;
|
|
8
|
+
for (const [name, store] of Object.entries(kv.stores ?? { default: kv.store })) {
|
|
9
|
+
const notice = kvInferredStoreNotice(name, store);
|
|
10
|
+
if (notice) console.info(notice);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Nitro plugin of KV for Redis connections and inferred-store boot notices. On close it releases KV connections,
|
|
15
|
+
* so the process can exit.
|
|
16
|
+
*/
|
|
17
|
+
function kvNitroPlugin(nitroApp) {
|
|
18
|
+
nitroApp.hooks.hook("close", disposeKVStores);
|
|
19
|
+
logInferredStores().catch((error) => console.warn("[vitehub] Could not read the KV configuration.", error));
|
|
20
|
+
}
|
|
21
|
+
//#endregion
|
|
22
|
+
export { kvNitroPlugin as default };
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { L as ResolvedRedisKVStoreConfig } from "../types-DEiKew_3.js";
|
|
2
|
+
import { t as KVRuntimeDriver } from "../driver-BwxgaQ-f.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
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { t as invariant } from "../invariant-DolT9EEx.js";
|
|
2
|
+
import { n as kvErrorDiagnostics } from "../error-diagnostics-BxqvtEIb.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-E5mahECF.js";
|
|
6
|
+
import { Redis } from "ioredis";
|
|
7
|
+
//#region src/runtime/redis-driver.ts
|
|
8
|
+
/** The URL of a store: `env:<NAME>` reads the variable now, so a build never holds the URL of its server. */
|
|
9
|
+
function resolveRedisUrl(url, env = globalThis.process?.env ?? {}) {
|
|
10
|
+
if (!url.startsWith("env:")) return url;
|
|
11
|
+
const name = url.slice(4);
|
|
12
|
+
const value = env[name]?.trim();
|
|
13
|
+
if (!value) throw kvErrorDiagnostics.KV_MISSING_ENV({
|
|
14
|
+
driver: "redis",
|
|
15
|
+
names: `\`${name}\``
|
|
16
|
+
});
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
/** Milliseconds for `SET PX`, which keeps fractional TTLs, as the other drivers do. */
|
|
20
|
+
function ttlMilliseconds(ttl) {
|
|
21
|
+
redisTTLSeconds(ttl);
|
|
22
|
+
return Math.ceil(ttl * 1e3);
|
|
23
|
+
}
|
|
24
|
+
/** The `PX` milliseconds of a write. Like other unstorage drivers, no TTL or 0 keeps the key. */
|
|
25
|
+
function writeTTL(options) {
|
|
26
|
+
const ttl = options?.ttl;
|
|
27
|
+
if (ttl === void 0 || ttl === null || ttl === 0) return;
|
|
28
|
+
if (typeof ttl === "number") return ttlMilliseconds(ttl);
|
|
29
|
+
throw kvErrorDiagnostics.KV_INVALID_TTL();
|
|
30
|
+
}
|
|
31
|
+
/** Keys per `MGET`, so one reply stays a moderate size. */
|
|
32
|
+
const mgetBatchSize = 1e3;
|
|
33
|
+
/**
|
|
34
|
+
* KV over a Redis server through TCP, with `ioredis`. Each atomic operation is one command or one script. This module
|
|
35
|
+
* loads only for a Redis store, so other stores do not load `ioredis`.
|
|
36
|
+
*/
|
|
37
|
+
function createRedisKVDriver(options) {
|
|
38
|
+
const base = normalizeKey(options.base);
|
|
39
|
+
invariant(base, "resolveRedisStore() gives a Redis KV store a non-empty `base`, which keeps clear() inside the store");
|
|
40
|
+
const client = new Redis(resolveRedisUrl(options.url), {
|
|
41
|
+
lazyConnect: true,
|
|
42
|
+
maxRetriesPerRequest: 3
|
|
43
|
+
});
|
|
44
|
+
const prefixed = (key) => `${base}:${key}`;
|
|
45
|
+
const unprefixed = (key) => key.startsWith(`${base}:`) ? key.slice(base.length + 1) : key;
|
|
46
|
+
const pattern = (match) => `${escapeRedisGlob(base)}:${match}`;
|
|
47
|
+
async function scanAll(prefix) {
|
|
48
|
+
const keys = [];
|
|
49
|
+
let cursor = "0";
|
|
50
|
+
do {
|
|
51
|
+
const [next, page] = await client.scan(cursor, "MATCH", pattern(`${escapeRedisGlob(prefix ?? "")}*`), "COUNT", 1e3);
|
|
52
|
+
cursor = next;
|
|
53
|
+
for (const key of page) keys.push(key);
|
|
54
|
+
} while (cursor !== "0");
|
|
55
|
+
return keys;
|
|
56
|
+
}
|
|
57
|
+
return {
|
|
58
|
+
name: "vitehub-kv-redis",
|
|
59
|
+
options,
|
|
60
|
+
hasItem: async (key) => await client.exists(prefixed(key)) > 0,
|
|
61
|
+
getItem: async (key) => await client.get(prefixed(key)),
|
|
62
|
+
async getItems(items) {
|
|
63
|
+
const values = [];
|
|
64
|
+
for (const batch of chunks(items, mgetBatchSize)) values.push(...await client.mget(...batch.map((item) => prefixed(item.key))));
|
|
65
|
+
return items.map((item, index) => ({
|
|
66
|
+
key: item.key,
|
|
67
|
+
value: values[index] ?? null
|
|
68
|
+
}));
|
|
69
|
+
},
|
|
70
|
+
async setItem(key, value, setOptions) {
|
|
71
|
+
const ttl = writeTTL(setOptions);
|
|
72
|
+
if (ttl === void 0) await client.set(prefixed(key), value);
|
|
73
|
+
else await client.set(prefixed(key), value, "PX", ttl);
|
|
74
|
+
},
|
|
75
|
+
async setItems(items, setOptions) {
|
|
76
|
+
const pipeline = client.pipeline();
|
|
77
|
+
for (const item of items) {
|
|
78
|
+
const ttl = writeTTL({
|
|
79
|
+
...setOptions,
|
|
80
|
+
...item.options
|
|
81
|
+
});
|
|
82
|
+
if (ttl === void 0) pipeline.set(prefixed(item.key), item.value);
|
|
83
|
+
else pipeline.set(prefixed(item.key), item.value, "PX", ttl);
|
|
84
|
+
}
|
|
85
|
+
for (const [error] of await pipeline.exec() ?? []) if (error) throw error;
|
|
86
|
+
},
|
|
87
|
+
async removeItem(key) {
|
|
88
|
+
await client.unlink(prefixed(key));
|
|
89
|
+
},
|
|
90
|
+
getKeys: async (base) => (await scanAll(base)).map(unprefixed),
|
|
91
|
+
async clear(base) {
|
|
92
|
+
const keys = await scanAll(base);
|
|
93
|
+
for (let offset = 0; offset < keys.length; offset += 1e3) await client.unlink(...keys.slice(offset, offset + 1e3));
|
|
94
|
+
},
|
|
95
|
+
async setIfAbsentItem(key, value, ttl) {
|
|
96
|
+
return (ttl === void 0 ? await client.set(prefixed(key), value, "NX") : await client.set(prefixed(key), value, "PX", ttlMilliseconds(ttl), "NX")) === "OK";
|
|
97
|
+
},
|
|
98
|
+
async getAndDeleteItem(key) {
|
|
99
|
+
return await client.getdel(prefixed(key));
|
|
100
|
+
},
|
|
101
|
+
incrementItem: async (key, ttl) => redisIncrementResult(await client.eval(redisIncrementScript, 1, prefixed(key), redisTTLSeconds(ttl))),
|
|
102
|
+
deleteIfEqualsItem: async (key, expected) => Number(await client.eval(redisDeleteIfEqualsScript, 1, prefixed(key), expected)) === 1,
|
|
103
|
+
listKeys: createPortableRedisKeyLister("Redis KV", async (cursor, match, count) => {
|
|
104
|
+
const [next, keys] = await client.scan(cursor, "MATCH", pattern(match), "COUNT", count);
|
|
105
|
+
return [next, keys.map(unprefixed)];
|
|
106
|
+
}),
|
|
107
|
+
async dispose() {
|
|
108
|
+
client.disconnect();
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
//#endregion
|
|
113
|
+
export { createRedisKVDriver as default, resolveRedisUrl };
|