@vite-hub/kv 0.1.0 → 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 +86 -15
- package/dist/batch--v0ri69O.js +40 -0
- package/dist/cli-DpPhz_Ek.d.ts +163 -0
- package/dist/cli.d.ts +4 -2
- package/dist/cli.js +98 -77
- 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/{create-storage-29gMzf41.js → create-storage-BGsrQKw3.js} +206 -50
- package/dist/{cursor-history-dqYDlsaD.js → cursor-history-BqIQePNP.js} +31 -14
- package/dist/database-72Jk3VVk.js +250 -0
- package/dist/{deno-kv-CSYGvRx4.js → deno-kv-BM9mYdUp.js} +12 -4
- 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 +12 -1
- package/dist/errors.js +2 -2
- package/dist/fs-lite-BLZId9_P.js +386 -0
- package/dist/fs-lite-RAoxu8L0.js +2 -0
- package/dist/index.d.ts +7 -2
- package/dist/index.js +302 -75
- 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/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
- package/dist/operations-B-WZ7P1h.js +1351 -0
- package/dist/{operations-pn8_eGob.js → operations-Ch-gKaey.js} +67 -58
- package/dist/operations.d.ts +15 -8
- package/dist/operations.js +55 -192
- package/dist/redis-shared-E5mahECF.js +94 -0
- package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
- package/dist/runtime/cloudflare-kv.d.ts +1 -1
- package/dist/runtime/cloudflare-kv.js +1 -99
- 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 +2 -2
- package/dist/runtime/upstash-driver.js +58 -98
- package/dist/{driver-D9fI27jl.d.ts → types-Bj3EQoRg.d.ts} +16 -41
- package/dist/types-DEiKew_3.d.ts +312 -0
- package/dist/upstash-DDlqTttY.js +40 -0
- package/dist/{utils2-Dsb9P4_2.js → utils2-FozcTsmb.js} +5 -2
- package/dist/virtual-module.d.ts +2 -0
- package/dist/vite.d.ts +152 -11
- package/dist/vite.js +888 -2836
- package/package.json +30 -21
- package/dist/cli-Cniq99iX.d.ts +0 -85
- package/dist/cloudflare-env-C5rM7kUY.js +0 -74
- package/dist/config-DR6_5ZwI.js +0 -124
- package/dist/continuations-DPyH_vr1.js +0 -63
- package/dist/error-diagnostics-D_cQeZTi.js +0 -82
- package/dist/errors-Dc2oiW-Y.js +0 -38
- package/dist/fs-lite-CbLKxLut.js +0 -90
- package/dist/object-B1NW521B.js +0 -7
- package/dist/operations-ByuDE12r.js +0 -1442
- package/dist/types-CMDvN0Wr.d.ts +0 -81
|
@@ -1,24 +1,11 @@
|
|
|
1
|
+
import { t as redactInspectionText } from "./inspect-BIKQsqX4.js";
|
|
2
|
+
import { n as invariantError } from "./invariant-DolT9EEx.js";
|
|
3
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
|
|
1
4
|
import { t as kvDevMaximumListLimit } from "./results-p7nPCnaJ.js";
|
|
2
|
-
import {
|
|
5
|
+
import { o as normalizeKey } from "./utils2-FozcTsmb.js";
|
|
3
6
|
import { kv } from "@vite-hub/kv";
|
|
4
|
-
//#region ../internal/src/inspect.ts
|
|
5
|
-
const redactedInspectionValue = "[redacted]";
|
|
6
|
-
const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
|
|
7
|
-
const embeddedUrlCredentialPattern = /\b([a-z][a-z0-9+.-]*:\/\/)[^/\s?#]*@/gi;
|
|
8
|
-
const embeddedCookiePattern = /\b([\w-]*cookie[\w-]*["']?\s*[:=]\s*)(?:"(?:\\[^\r\n]|[^"\\\r\n])*"(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|'(?:\\[^\r\n]|[^'\\\r\n])*'(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|[^\r\n]+?(?=\s*(?:;\s*[^;=\r\n/]+\s*(?:\r?\n|$)|&|\r?\n|$)))/gi;
|
|
9
|
-
const embeddedBearerPattern = /\bbearer\s+[^\s,;]+/gi;
|
|
10
|
-
const embeddedAuthorizationPattern = new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
|
|
11
|
-
const embeddedSecretAssignmentPattern = new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
|
|
12
|
-
/**
|
|
13
|
-
* Removes credentials inside free text, for example an error message. URL credentials, bearer tokens, and
|
|
14
|
-
* `name=value` pairs with a secret name are replaced with `[redacted]`.
|
|
15
|
-
*/
|
|
16
|
-
function redactInspectionText(value) {
|
|
17
|
-
return value.replace(embeddedUrlCredentialPattern, `$1${redactedInspectionValue}@`).replace(embeddedAuthorizationPattern, `$1${redactedInspectionValue}`).replace(embeddedCookiePattern, `$1${redactedInspectionValue}`).replace(embeddedBearerPattern, `Bearer ${redactedInspectionValue}`).replace(embeddedSecretAssignmentPattern, `$1${redactedInspectionValue}`);
|
|
18
|
-
}
|
|
19
|
-
//#endregion
|
|
20
7
|
//#region src/runtime/inspect-value.ts
|
|
21
|
-
|
|
8
|
+
const unsupported = () => kvErrorDiagnostics.KV_VALUE_UNSUPPORTED();
|
|
22
9
|
function isUint8Array(value) {
|
|
23
10
|
try {
|
|
24
11
|
if (!ArrayBuffer.isView(value)) return false;
|
|
@@ -37,11 +24,11 @@ function kvValueType(value) {
|
|
|
37
24
|
function encodeBase64(bytes) {
|
|
38
25
|
try {
|
|
39
26
|
const lengthGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "length")?.get;
|
|
40
|
-
if (!lengthGetter) throw
|
|
27
|
+
if (!lengthGetter) throw unsupported();
|
|
41
28
|
const length = Reflect.apply(lengthGetter, bytes, []);
|
|
42
29
|
for (const key of ["byteLength", "length"]) {
|
|
43
30
|
const descriptor = Object.getOwnPropertyDescriptor(bytes, key);
|
|
44
|
-
if (descriptor && (!("value" in descriptor) || descriptor.value !== length)) throw
|
|
31
|
+
if (descriptor && (!("value" in descriptor) || descriptor.value !== length)) throw unsupported();
|
|
45
32
|
}
|
|
46
33
|
const encoded = [];
|
|
47
34
|
let chunk = [];
|
|
@@ -55,7 +42,7 @@ function encodeBase64(bytes) {
|
|
|
55
42
|
if (chunk.length) encoded.push(btoa(String.fromCharCode(...chunk)));
|
|
56
43
|
return encoded.join("");
|
|
57
44
|
} catch {
|
|
58
|
-
throw
|
|
45
|
+
throw unsupported();
|
|
59
46
|
}
|
|
60
47
|
}
|
|
61
48
|
/** JSON inspection accepts JSON values and represents bigint values as decimal strings. */
|
|
@@ -63,18 +50,18 @@ function inspectValue(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
|
63
50
|
if (typeof value === "bigint") return value.toString();
|
|
64
51
|
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
65
52
|
if (typeof value === "number" && Number.isFinite(value) && !Object.is(value, -0)) return value;
|
|
66
|
-
if (typeof value !== "object" && typeof value !== "function" || seen.has(value)) throw
|
|
53
|
+
if (typeof value !== "object" && typeof value !== "function" || seen.has(value)) throw unsupported();
|
|
67
54
|
seen.add(value);
|
|
68
55
|
try {
|
|
69
56
|
const ownKeys = Reflect.ownKeys(value);
|
|
70
57
|
const dataKeys = Array.isArray(value) ? ownKeys.filter((key) => key !== "length") : ownKeys;
|
|
71
|
-
if (dataKeys.map((key) => Object.getOwnPropertyDescriptor(value, key)).some((descriptor) => !descriptor?.enumerable || !("value" in descriptor))) throw
|
|
58
|
+
if (dataKeys.map((key) => Object.getOwnPropertyDescriptor(value, key)).some((descriptor) => !descriptor?.enumerable || !("value" in descriptor))) throw unsupported();
|
|
72
59
|
if (Array.isArray(value)) {
|
|
73
|
-
if (dataKeys.length !== value.length || dataKeys.some((key) => typeof key !== "string" || String(Number(key)) !== key || !Number.isInteger(Number(key)) || Number(key) < 0 || Number(key) >= value.length)) throw
|
|
60
|
+
if (dataKeys.length !== value.length || dataKeys.some((key) => typeof key !== "string" || String(Number(key)) !== key || !Number.isInteger(Number(key)) || Number(key) < 0 || Number(key) >= value.length)) throw unsupported();
|
|
74
61
|
return Array.from({ length: value.length }, (_, index) => inspectValue(Object.getOwnPropertyDescriptor(value, String(index))?.value, seen));
|
|
75
62
|
}
|
|
76
63
|
const prototype = Object.getPrototypeOf(value);
|
|
77
|
-
if (prototype !== Object.prototype && prototype !== null || Object.getOwnPropertySymbols(value).length) throw
|
|
64
|
+
if (prototype !== Object.prototype && prototype !== null || Object.getOwnPropertySymbols(value).length) throw unsupported();
|
|
78
65
|
return Object.fromEntries(dataKeys.map((key) => [key, inspectValue(Object.getOwnPropertyDescriptor(value, key)?.value, seen)]));
|
|
79
66
|
} finally {
|
|
80
67
|
seen.delete(value);
|
|
@@ -93,7 +80,7 @@ function inspectKVValue(value) {
|
|
|
93
80
|
value: inspectValue(value)
|
|
94
81
|
};
|
|
95
82
|
} catch (error) {
|
|
96
|
-
if (error
|
|
83
|
+
if (Reflect.get(Object(error), "code") === "KV_VALUE_UNSUPPORTED") return;
|
|
97
84
|
throw error;
|
|
98
85
|
}
|
|
99
86
|
}
|
|
@@ -165,7 +152,7 @@ function boundedJSONStringify(value) {
|
|
|
165
152
|
editable = false;
|
|
166
153
|
const toJSON = Reflect.get(Object(input), "toJSON");
|
|
167
154
|
if (applyToJSON && typeof toJSON === "function") return serialize(toJSON.call(input, key), depth, arrayValue, key, false);
|
|
168
|
-
throw
|
|
155
|
+
throw invariantError("JSON has no bigint without `toJSON()`");
|
|
169
156
|
}
|
|
170
157
|
const object = Object(input);
|
|
171
158
|
const prototype = Object.getPrototypeOf(object);
|
|
@@ -184,7 +171,7 @@ function boundedJSONStringify(value) {
|
|
|
184
171
|
editable = false;
|
|
185
172
|
return serialize(boxed, depth, arrayValue, key);
|
|
186
173
|
}
|
|
187
|
-
if (ancestors.has(object)) throw
|
|
174
|
+
if (ancestors.has(object)) throw invariantError("JSON has no circular value");
|
|
188
175
|
if (seen.has(object)) editable = false;
|
|
189
176
|
seen.add(object);
|
|
190
177
|
ancestors.add(object);
|
|
@@ -279,24 +266,20 @@ try {
|
|
|
279
266
|
} catch (error) {
|
|
280
267
|
if (!isMissingKVConfig(error)) throw error;
|
|
281
268
|
}
|
|
282
|
-
/**
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
this.code = code;
|
|
291
|
-
this.fix = fix;
|
|
292
|
-
}
|
|
269
|
+
/** The HTTP status that the CLI, the Console, and Agents report for each code of a failed operation. */
|
|
270
|
+
const kvOperationStatus = {
|
|
271
|
+
KV_DISABLED: 409,
|
|
272
|
+
KV_INVALID_CURSOR: 400,
|
|
273
|
+
KV_INVALID_INPUT: 400,
|
|
274
|
+
KV_RESERVED_KEY: 403,
|
|
275
|
+
KV_STORE_NOT_FOUND: 404,
|
|
276
|
+
KV_VALUE_UNSUPPORTED: 422
|
|
293
277
|
};
|
|
294
278
|
const maximumKeyLength = 2048;
|
|
295
279
|
function unwrap(result) {
|
|
296
280
|
const [error, value] = result;
|
|
297
281
|
if (!error) return value;
|
|
298
|
-
|
|
299
|
-
throw new KVOperationError(`${error.message}${cause}`, error.code === "KV_INVALID_CURSOR" ? 400 : 502, error.code);
|
|
282
|
+
throw Object.assign(error, { status: kvOperationStatus[error.code] ?? 502 });
|
|
300
283
|
}
|
|
301
284
|
function resolvedStores(config) {
|
|
302
285
|
if (!config) return [];
|
|
@@ -311,18 +294,20 @@ function listKVDevStores() {
|
|
|
311
294
|
return resolvedStores(kvConfig);
|
|
312
295
|
}
|
|
313
296
|
function ttlNotice(driver, ttl) {
|
|
314
|
-
if (driver === "fs-lite") return "The fs-lite driver ignores TTL. The value does not expire.";
|
|
315
297
|
if (driver === "upstash" && Math.ceil(ttl) !== ttl) return `Upstash rounds the TTL up to ${Math.ceil(ttl)} seconds.`;
|
|
316
|
-
if (driver === "cloudflare
|
|
298
|
+
if (driver === "cloudflare") {
|
|
317
299
|
const effectiveTTL = Math.max(60, Math.ceil(ttl));
|
|
318
300
|
if (ttl < 60) return "Cloudflare KV raises a TTL below 60 seconds to 60 seconds.";
|
|
319
301
|
if (effectiveTTL !== ttl) return `Cloudflare KV rounds the TTL up to ${effectiveTTL} seconds.`;
|
|
320
302
|
}
|
|
321
303
|
}
|
|
322
304
|
function selectStore(stores, name = "default") {
|
|
323
|
-
if (stores.length === 0) throw
|
|
305
|
+
if (stores.length === 0) throw kvErrorDiagnostics.KV_DISABLED();
|
|
324
306
|
const store = stores.find((entry) => entry.name === name);
|
|
325
|
-
if (!store) throw
|
|
307
|
+
if (!store) throw kvErrorDiagnostics.KV_STORE_NOT_FOUND({
|
|
308
|
+
store: name,
|
|
309
|
+
stores: stores.map((entry) => entry.name).join(", ")
|
|
310
|
+
});
|
|
326
311
|
return {
|
|
327
312
|
driver: store.driver,
|
|
328
313
|
name,
|
|
@@ -332,11 +317,17 @@ function selectStore(stores, name = "default") {
|
|
|
332
317
|
/** The keys under `vitehub:` belong to ViteHub, which keeps its own state there. */
|
|
333
318
|
function requireWritableKey(operation, key) {
|
|
334
319
|
if (!normalizeKey(key).toLowerCase().startsWith("vitehub:")) return;
|
|
335
|
-
throw
|
|
320
|
+
throw kvErrorDiagnostics.KV_RESERVED_KEY({
|
|
321
|
+
key,
|
|
322
|
+
operation
|
|
323
|
+
});
|
|
336
324
|
}
|
|
337
325
|
function requireKey(operation, input) {
|
|
338
|
-
if (input.key === void 0) throw
|
|
339
|
-
|
|
326
|
+
if (input.key === void 0) throw kvErrorDiagnostics.KV_INVALID_INPUT({
|
|
327
|
+
operation,
|
|
328
|
+
problem: "key"
|
|
329
|
+
});
|
|
330
|
+
if (input.key.length > maximumKeyLength) throw kvErrorDiagnostics.KV_INVALID_INPUT({ problem: "key-length" });
|
|
340
331
|
return input.key;
|
|
341
332
|
}
|
|
342
333
|
/**
|
|
@@ -344,12 +335,29 @@ function requireKey(operation, input) {
|
|
|
344
335
|
* bindings, so this runs where the app does. There is no operation that clears a store.
|
|
345
336
|
*/
|
|
346
337
|
async function runKVOperation(operation, input, stores = listKVDevStores()) {
|
|
338
|
+
try {
|
|
339
|
+
return await runOperation(operation, input, stores);
|
|
340
|
+
} catch (error) {
|
|
341
|
+
const code = Reflect.get(Object(error), "code");
|
|
342
|
+
const status = Reflect.get(Object(error), "status") ?? (typeof code === "string" ? kvOperationStatus[code] : void 0);
|
|
343
|
+
if (typeof status !== "number" || !(error instanceof Error)) throw error;
|
|
344
|
+
const cause = code === "KV_OPERATION_FAILED" && error.cause instanceof Error ? ` ${error.cause.message}` : "";
|
|
345
|
+
throw Object.assign(error, {
|
|
346
|
+
status,
|
|
347
|
+
statusMessage: redactInspectionText(`${error.message}${cause}`)
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
async function runOperation(operation, input, stores) {
|
|
347
352
|
const selected = selectStore(stores, input.store);
|
|
348
353
|
switch (operation) {
|
|
349
354
|
case "list": {
|
|
350
355
|
const limit = input.limit ?? 100;
|
|
351
|
-
if (limit > 1e3) throw
|
|
352
|
-
|
|
356
|
+
if (limit > 1e3) throw kvErrorDiagnostics.KV_INVALID_INPUT({
|
|
357
|
+
limit: kvDevMaximumListLimit,
|
|
358
|
+
problem: "limit"
|
|
359
|
+
});
|
|
360
|
+
if ((input.prefix?.length ?? 0) > maximumKeyLength) throw kvErrorDiagnostics.KV_INVALID_INPUT({ problem: "prefix-length" });
|
|
353
361
|
const listOptions = {
|
|
354
362
|
limit,
|
|
355
363
|
prefix: input.prefix ?? ""
|
|
@@ -357,6 +365,7 @@ async function runKVOperation(operation, input, stores = listKVDevStores()) {
|
|
|
357
365
|
if (input.cursor) listOptions.cursor = input.cursor;
|
|
358
366
|
const page = unwrap(await selected.storage.list(listOptions));
|
|
359
367
|
const result = {
|
|
368
|
+
driver: selected.driver,
|
|
360
369
|
keys: page.keys,
|
|
361
370
|
limit,
|
|
362
371
|
prefix: input.prefix ?? "",
|
|
@@ -375,14 +384,14 @@ async function runKVOperation(operation, input, stores = listKVDevStores()) {
|
|
|
375
384
|
key,
|
|
376
385
|
store: selected.name
|
|
377
386
|
};
|
|
378
|
-
if (found) result.expiry =
|
|
387
|
+
if (found) result.expiry = "unknown";
|
|
379
388
|
if (!found) return result;
|
|
380
389
|
if (input.preview) return {
|
|
381
390
|
...result,
|
|
382
391
|
...previewKVValue(value)
|
|
383
392
|
};
|
|
384
393
|
const inspected = inspectKVValue(value);
|
|
385
|
-
if (!inspected) throw
|
|
394
|
+
if (!inspected) throw kvErrorDiagnostics.KV_VALUE_UNSUPPORTED();
|
|
386
395
|
return {
|
|
387
396
|
...result,
|
|
388
397
|
...inspected
|
|
@@ -399,10 +408,10 @@ async function runKVOperation(operation, input, stores = listKVDevStores()) {
|
|
|
399
408
|
case "set": {
|
|
400
409
|
const key = requireKey(operation, input);
|
|
401
410
|
requireWritableKey(operation, key);
|
|
402
|
-
if (input.value === void 0) throw
|
|
403
|
-
if (selected.driver === "upstash" && input.ttl !== void 0 && input.ttl < 1) throw
|
|
411
|
+
if (input.value === void 0) throw kvErrorDiagnostics.KV_INVALID_INPUT({ problem: "value" });
|
|
412
|
+
if (selected.driver === "upstash" && input.ttl !== void 0 && input.ttl < 1) throw kvErrorDiagnostics.KV_INVALID_INPUT({ problem: "ttl" });
|
|
404
413
|
const existed = unwrap(await selected.storage.has(key));
|
|
405
|
-
const ttl = input.ttl === void 0 ? void 0 : selected.driver === "cloudflare
|
|
414
|
+
const ttl = input.ttl === void 0 ? void 0 : selected.driver === "cloudflare" ? Math.max(60, Math.ceil(input.ttl)) : selected.driver === "upstash" ? Math.ceil(input.ttl) : input.ttl;
|
|
406
415
|
unwrap(await selected.storage.set(key, input.value, ttl === void 0 ? void 0 : { ttl }));
|
|
407
416
|
const notice = input.ttl ? ttlNotice(selected.driver, input.ttl) : void 0;
|
|
408
417
|
const result = {
|
|
@@ -415,11 +424,11 @@ async function runKVOperation(operation, input, stores = listKVDevStores()) {
|
|
|
415
424
|
if (ttl) result.ttl = ttl;
|
|
416
425
|
return result;
|
|
417
426
|
}
|
|
418
|
-
case "
|
|
427
|
+
case "delete": {
|
|
419
428
|
const key = requireKey(operation, input);
|
|
420
429
|
requireWritableKey(operation, key);
|
|
421
430
|
const existed = unwrap(await selected.storage.has(key));
|
|
422
|
-
unwrap(await selected.storage.
|
|
431
|
+
unwrap(await selected.storage.delete(key));
|
|
423
432
|
return {
|
|
424
433
|
deleted: existed,
|
|
425
434
|
key,
|
|
@@ -429,4 +438,4 @@ async function runKVOperation(operation, input, stores = listKVDevStores()) {
|
|
|
429
438
|
}
|
|
430
439
|
}
|
|
431
440
|
//#endregion
|
|
432
|
-
export {
|
|
441
|
+
export { listKVDevStores, runKVOperation };
|
package/dist/operations.d.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import "./types-
|
|
2
|
-
import { t as AnyOperation } from "./
|
|
1
|
+
import { s as KVDriver } from "./types-DEiKew_3.js";
|
|
2
|
+
import { t as AnyOperation } from "./operation-definition-8gOe-ubD.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. `
|
|
23
|
-
*
|
|
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?: "
|
|
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
|
-
/**
|
|
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):
|
|
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
|
|
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 };
|
package/dist/operations.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { a as
|
|
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
2
|
import { t as kvDevMaximumListLimit } from "./results-p7nPCnaJ.js";
|
|
3
|
-
import {
|
|
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
|
-
/**
|
|
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
|
-
|
|
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(
|
|
303
|
-
readPath(
|
|
304
|
-
readPath(
|
|
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) ||
|
|
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,10 +194,11 @@ function createStandaloneOperationHandler(sources, root) {
|
|
|
340
194
|
} catch {
|
|
341
195
|
reject(400, "Malformed operation request.");
|
|
342
196
|
}
|
|
343
|
-
|
|
344
|
-
if (
|
|
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
|
|
201
|
+
const context = {
|
|
347
202
|
access: {
|
|
348
203
|
mode: "local",
|
|
349
204
|
sections: "all"
|
|
@@ -352,29 +207,37 @@ function createStandaloneOperationHandler(sources, root) {
|
|
|
352
207
|
surface: "cli",
|
|
353
208
|
user: null,
|
|
354
209
|
request,
|
|
210
|
+
event: request,
|
|
355
211
|
response,
|
|
356
|
-
env:
|
|
357
|
-
waitUntil:
|
|
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 })
|
|
358
224
|
});
|
|
359
|
-
return Response.json(
|
|
225
|
+
return Response.json(reply, {
|
|
360
226
|
headers,
|
|
361
|
-
status:
|
|
227
|
+
status: "e" in reply ? reply.e.status : response.status ?? 200
|
|
362
228
|
});
|
|
363
229
|
} catch (error) {
|
|
364
230
|
const failure = toOperationFailure(error);
|
|
365
|
-
return Response.json({
|
|
366
|
-
ok: false,
|
|
367
|
-
...failure
|
|
368
|
-
}, {
|
|
231
|
+
return Response.json(operationRpcRefusal(failure), {
|
|
369
232
|
headers,
|
|
370
233
|
status: failure.status
|
|
371
234
|
});
|
|
372
235
|
}
|
|
373
|
-
};
|
|
236
|
+
} };
|
|
374
237
|
}
|
|
375
238
|
//#endregion
|
|
376
239
|
//#region src/operations.ts
|
|
377
|
-
const runtime = () => import("./operations-
|
|
240
|
+
const runtime = () => import("./operations-Ch-gKaey.js");
|
|
378
241
|
const store = v.optional(v.pipe(v.string(), v.check((name) => name.trim() !== "", "Name a store.")));
|
|
379
242
|
const key = v.string();
|
|
380
243
|
function defineKVOperation(definition) {
|
|
@@ -384,7 +247,7 @@ function defineKVOperation(definition) {
|
|
|
384
247
|
user: false
|
|
385
248
|
});
|
|
386
249
|
}
|
|
387
|
-
/** The `kv.*` operations: list, get, has, set, and
|
|
250
|
+
/** The `kv.*` operations: list, get, has, set, and delete. The Console, `vitehub kv`, and agents run them. */
|
|
388
251
|
const kvOperations = [
|
|
389
252
|
defineKVOperation({
|
|
390
253
|
cli: { command: "list" },
|
|
@@ -438,7 +301,7 @@ const kvOperations = [
|
|
|
438
301
|
}),
|
|
439
302
|
defineKVOperation({
|
|
440
303
|
cli: {
|
|
441
|
-
command: "
|
|
304
|
+
command: "delete",
|
|
442
305
|
positional: ["key"]
|
|
443
306
|
},
|
|
444
307
|
description: "Delete one key. There is no operation that clears a store.",
|
|
@@ -447,8 +310,8 @@ const kvOperations = [
|
|
|
447
310
|
store
|
|
448
311
|
}),
|
|
449
312
|
kind: "destructive",
|
|
450
|
-
name: "kv.
|
|
451
|
-
run: async (input) => await (await runtime()).runKVOperation("
|
|
313
|
+
name: "kv.delete",
|
|
314
|
+
run: async (input) => await (await runtime()).runKVOperation("delete", input)
|
|
452
315
|
})
|
|
453
316
|
];
|
|
454
317
|
//#endregion
|