@vite-hub/kv 0.0.4 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -8
- package/dist/cli-Cniq99iX.d.ts +85 -0
- package/dist/cli.d.ts +15 -0
- package/dist/cli.js +448 -0
- package/dist/cloudflare-env-C5rM7kUY.js +74 -0
- package/dist/{config-aM9Ae7tH.js → config-DR6_5ZwI.js} +36 -22
- package/dist/continuations-DPyH_vr1.js +63 -0
- package/dist/{dist-DDW1iC5f.js → create-storage-29gMzf41.js} +70 -75
- package/dist/cursor-history-dqYDlsaD.js +148 -0
- package/dist/deno-kv-CSYGvRx4.js +120 -0
- package/dist/{driver-BT9WefKi.d.ts → driver-D9fI27jl.d.ts} +33 -3
- package/dist/error-diagnostics-D_cQeZTi.js +82 -0
- package/dist/errors-Dc2oiW-Y.js +38 -0
- package/dist/errors.d.ts +12 -7
- package/dist/errors.js +2 -20
- package/dist/fs-lite-CbLKxLut.js +90 -0
- package/dist/index.d.ts +5 -4
- package/dist/index.js +92 -64
- package/dist/object-B1NW521B.js +7 -0
- package/dist/operations-ByuDE12r.js +1442 -0
- package/dist/operations-pn8_eGob.js +432 -0
- package/dist/operations-tNUdj3G4.d.ts +212 -0
- package/dist/operations.d.ts +68 -0
- package/dist/operations.js +455 -0
- package/dist/results-p7nPCnaJ.js +6 -0
- package/dist/runtime/cloudflare-kv.d.ts +3 -4
- package/dist/runtime/cloudflare-kv.js +84 -8
- package/dist/runtime/upstash-driver.d.ts +4 -6
- package/dist/runtime/upstash-driver.js +34 -44
- package/dist/{types-CO0DRjJa.d.ts → types-CMDvN0Wr.d.ts} +20 -17
- package/dist/utils2-Dsb9P4_2.js +28 -0
- package/dist/virtual.d.ts +1 -1
- package/dist/vite.d.ts +14 -10
- package/dist/vite.js +603 -224
- package/package.json +56 -16
- package/dist/deno-kv-cJx3jU10.js +0 -69
- package/dist/fs-lite-BxzdiJSi.js +0 -79
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
import { t as kvDevMaximumListLimit } from "./results-p7nPCnaJ.js";
|
|
2
|
+
import { a as normalizeKey } from "./utils2-Dsb9P4_2.js";
|
|
3
|
+
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
|
+
//#region src/runtime/inspect-value.ts
|
|
21
|
+
var UnsupportedValueError = class extends Error {};
|
|
22
|
+
function isUint8Array(value) {
|
|
23
|
+
try {
|
|
24
|
+
if (!ArrayBuffer.isView(value)) return false;
|
|
25
|
+
const tagGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag)?.get;
|
|
26
|
+
return Boolean(tagGetter && Reflect.apply(tagGetter, value, []) === "Uint8Array");
|
|
27
|
+
} catch {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function kvValueType(value) {
|
|
32
|
+
if (value === null) return "null";
|
|
33
|
+
if (Array.isArray(value)) return "array";
|
|
34
|
+
if (isUint8Array(value)) return "bytes";
|
|
35
|
+
return typeof value;
|
|
36
|
+
}
|
|
37
|
+
function encodeBase64(bytes) {
|
|
38
|
+
try {
|
|
39
|
+
const lengthGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "length")?.get;
|
|
40
|
+
if (!lengthGetter) throw new UnsupportedValueError();
|
|
41
|
+
const length = Reflect.apply(lengthGetter, bytes, []);
|
|
42
|
+
for (const key of ["byteLength", "length"]) {
|
|
43
|
+
const descriptor = Object.getOwnPropertyDescriptor(bytes, key);
|
|
44
|
+
if (descriptor && (!("value" in descriptor) || descriptor.value !== length)) throw new UnsupportedValueError();
|
|
45
|
+
}
|
|
46
|
+
const encoded = [];
|
|
47
|
+
let chunk = [];
|
|
48
|
+
for (const byte of Reflect.apply(Uint8Array.prototype.values, bytes, [])) {
|
|
49
|
+
chunk.push(byte);
|
|
50
|
+
if (chunk.length === 12288) {
|
|
51
|
+
encoded.push(btoa(String.fromCharCode(...chunk)));
|
|
52
|
+
chunk = [];
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (chunk.length) encoded.push(btoa(String.fromCharCode(...chunk)));
|
|
56
|
+
return encoded.join("");
|
|
57
|
+
} catch {
|
|
58
|
+
throw new UnsupportedValueError();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** JSON inspection accepts JSON values and represents bigint values as decimal strings. */
|
|
62
|
+
function inspectValue(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
63
|
+
if (typeof value === "bigint") return value.toString();
|
|
64
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
65
|
+
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 new UnsupportedValueError();
|
|
67
|
+
seen.add(value);
|
|
68
|
+
try {
|
|
69
|
+
const ownKeys = Reflect.ownKeys(value);
|
|
70
|
+
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 new UnsupportedValueError();
|
|
72
|
+
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 new UnsupportedValueError();
|
|
74
|
+
return Array.from({ length: value.length }, (_, index) => inspectValue(Object.getOwnPropertyDescriptor(value, String(index))?.value, seen));
|
|
75
|
+
}
|
|
76
|
+
const prototype = Object.getPrototypeOf(value);
|
|
77
|
+
if (prototype !== Object.prototype && prototype !== null || Object.getOwnPropertySymbols(value).length) throw new UnsupportedValueError();
|
|
78
|
+
return Object.fromEntries(dataKeys.map((key) => [key, inspectValue(Object.getOwnPropertyDescriptor(value, key)?.value, seen)]));
|
|
79
|
+
} finally {
|
|
80
|
+
seen.delete(value);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/** Encodes one inspection result without running getters or exposing non-JSON object behavior. */
|
|
84
|
+
function inspectKVValue(value) {
|
|
85
|
+
try {
|
|
86
|
+
if (isUint8Array(value)) return {
|
|
87
|
+
encoding: "base64",
|
|
88
|
+
type: "bytes",
|
|
89
|
+
value: encodeBase64(value)
|
|
90
|
+
};
|
|
91
|
+
return {
|
|
92
|
+
type: kvValueType(value),
|
|
93
|
+
value: inspectValue(value)
|
|
94
|
+
};
|
|
95
|
+
} catch (error) {
|
|
96
|
+
if (error instanceof UnsupportedValueError) return;
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
//#endregion
|
|
101
|
+
//#region src/runtime/preview.ts
|
|
102
|
+
const maximumValueBytes = 262144;
|
|
103
|
+
function valueType(value) {
|
|
104
|
+
if (value === null) return "null";
|
|
105
|
+
if (Array.isArray(value)) return "array";
|
|
106
|
+
if (value instanceof Uint8Array) return "bytes";
|
|
107
|
+
return typeof value;
|
|
108
|
+
}
|
|
109
|
+
function truncateValue(value) {
|
|
110
|
+
const encoder = new TextEncoder();
|
|
111
|
+
let bytes = 0;
|
|
112
|
+
let end = 0;
|
|
113
|
+
for (const character of value) {
|
|
114
|
+
const characterBytes = encoder.encode(character).byteLength;
|
|
115
|
+
if (bytes + characterBytes > maximumValueBytes) return {
|
|
116
|
+
truncated: true,
|
|
117
|
+
value: value.slice(0, end)
|
|
118
|
+
};
|
|
119
|
+
bytes += characterBytes;
|
|
120
|
+
end += character.length;
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
truncated: false,
|
|
124
|
+
value
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
function boundedJSONStringify(value) {
|
|
128
|
+
let editable = true;
|
|
129
|
+
let bytes = 0;
|
|
130
|
+
let rendered = "";
|
|
131
|
+
let truncated = false;
|
|
132
|
+
const encoder = new TextEncoder();
|
|
133
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
134
|
+
const seen = /* @__PURE__ */ new Set();
|
|
135
|
+
function append(fragment) {
|
|
136
|
+
for (const character of fragment) {
|
|
137
|
+
const characterBytes = encoder.encode(character).byteLength;
|
|
138
|
+
if (bytes + characterBytes > maximumValueBytes) {
|
|
139
|
+
truncated = true;
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
rendered += character;
|
|
143
|
+
bytes += characterBytes;
|
|
144
|
+
}
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
function appendString(text) {
|
|
148
|
+
if (!append("\"")) return false;
|
|
149
|
+
for (const character of text) if (!append(JSON.stringify(character).slice(1, -1))) return false;
|
|
150
|
+
return append("\"");
|
|
151
|
+
}
|
|
152
|
+
function serialize(input, depth, arrayValue, key, applyToJSON = true) {
|
|
153
|
+
if (typeof input === "string") return appendString(input);
|
|
154
|
+
if (input === null) return append("null");
|
|
155
|
+
if (typeof input === "number") {
|
|
156
|
+
if (!Number.isFinite(input) || Object.is(input, -0)) editable = false;
|
|
157
|
+
return append(Number.isFinite(input) ? String(input) : "null");
|
|
158
|
+
}
|
|
159
|
+
if (typeof input === "boolean") return append(input ? "true" : "false");
|
|
160
|
+
if (typeof input === "undefined" || typeof input === "function" || typeof input === "symbol") {
|
|
161
|
+
editable = false;
|
|
162
|
+
return arrayValue ? append("null") : false;
|
|
163
|
+
}
|
|
164
|
+
if (typeof input === "bigint") {
|
|
165
|
+
editable = false;
|
|
166
|
+
const toJSON = Reflect.get(Object(input), "toJSON");
|
|
167
|
+
if (applyToJSON && typeof toJSON === "function") return serialize(toJSON.call(input, key), depth, arrayValue, key, false);
|
|
168
|
+
throw new TypeError("Cannot serialize bigint as JSON.");
|
|
169
|
+
}
|
|
170
|
+
const object = Object(input);
|
|
171
|
+
const prototype = Object.getPrototypeOf(object);
|
|
172
|
+
if (Array.isArray(object) ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) editable = false;
|
|
173
|
+
const keys = Reflect.ownKeys(object).filter((key) => !Array.isArray(object) || key !== "length");
|
|
174
|
+
if (keys.some((key) => typeof key === "symbol" || !Object.getOwnPropertyDescriptor(object, key)?.enumerable)) editable = false;
|
|
175
|
+
if (Array.isArray(object) && keys.length !== object.length) editable = false;
|
|
176
|
+
const toJSON = Reflect.get(object, "toJSON");
|
|
177
|
+
if (applyToJSON && typeof toJSON === "function") {
|
|
178
|
+
editable = false;
|
|
179
|
+
const replacement = toJSON.call(input, key);
|
|
180
|
+
if (replacement !== input) return serialize(replacement, depth, arrayValue, key, false);
|
|
181
|
+
}
|
|
182
|
+
const boxed = input instanceof Number || input instanceof String || input instanceof Boolean || Object.prototype.toString.call(input) === "[object BigInt]" ? Reflect.apply(object.valueOf, input, []) : input;
|
|
183
|
+
if (boxed !== input) {
|
|
184
|
+
editable = false;
|
|
185
|
+
return serialize(boxed, depth, arrayValue, key);
|
|
186
|
+
}
|
|
187
|
+
if (ancestors.has(object)) throw new TypeError("Cannot serialize a circular value as JSON.");
|
|
188
|
+
if (seen.has(object)) editable = false;
|
|
189
|
+
seen.add(object);
|
|
190
|
+
ancestors.add(object);
|
|
191
|
+
if (Array.isArray(object)) {
|
|
192
|
+
if (!append("[")) return false;
|
|
193
|
+
for (let index = 0; index < object.length; index += 1) {
|
|
194
|
+
if (!append(`${index === 0 ? "" : ","}\n${" ".repeat(depth + 1)}`)) return false;
|
|
195
|
+
if (!serialize(object[index], depth + 1, true, String(index))) return false;
|
|
196
|
+
}
|
|
197
|
+
if (object.length > 0 && !append(`\n${" ".repeat(depth)}`)) return false;
|
|
198
|
+
ancestors.delete(object);
|
|
199
|
+
return append("]");
|
|
200
|
+
}
|
|
201
|
+
if (!append("{")) return false;
|
|
202
|
+
let count = 0;
|
|
203
|
+
for (const key in object) {
|
|
204
|
+
if (!Object.prototype.hasOwnProperty.call(object, key)) continue;
|
|
205
|
+
let item = Reflect.get(object, key);
|
|
206
|
+
if (item !== null && (typeof item === "object" || typeof item === "bigint")) {
|
|
207
|
+
const toJSON = Reflect.get(Object(item), "toJSON");
|
|
208
|
+
if (typeof toJSON === "function") {
|
|
209
|
+
editable = false;
|
|
210
|
+
item = toJSON.call(item, key);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if (typeof item === "undefined" || typeof item === "function" || typeof item === "symbol") {
|
|
214
|
+
editable = false;
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
if (!append(`${count === 0 ? "" : ","}\n${" ".repeat(depth + 1)}`)) return false;
|
|
218
|
+
if (!appendString(key) || !append(": ") || !serialize(item, depth + 1, false, key, false)) return false;
|
|
219
|
+
count += 1;
|
|
220
|
+
}
|
|
221
|
+
if (count > 0 && !append(`\n${" ".repeat(depth)}`)) return false;
|
|
222
|
+
ancestors.delete(object);
|
|
223
|
+
return append("}");
|
|
224
|
+
}
|
|
225
|
+
const serialized = serialize(value, 0, false, "");
|
|
226
|
+
return {
|
|
227
|
+
editable,
|
|
228
|
+
truncated,
|
|
229
|
+
value: serialized || truncated ? rendered : void 0
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/** A stored value as text of at most 256 KiB, for a page that shows it. Bytes become hex. */
|
|
233
|
+
function previewKVValue(value) {
|
|
234
|
+
const type = valueType(value);
|
|
235
|
+
let format = "json";
|
|
236
|
+
let rendered;
|
|
237
|
+
let truncated = false;
|
|
238
|
+
let editable = false;
|
|
239
|
+
if (typeof value === "string") {
|
|
240
|
+
editable = true;
|
|
241
|
+
format = "text";
|
|
242
|
+
rendered = value;
|
|
243
|
+
} else if (value instanceof Uint8Array) {
|
|
244
|
+
format = "text";
|
|
245
|
+
const maximumBytes = maximumValueBytes / 2;
|
|
246
|
+
truncated = value.byteLength > maximumBytes;
|
|
247
|
+
rendered = Array.from(value.subarray(0, maximumBytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
248
|
+
} else try {
|
|
249
|
+
const result = boundedJSONStringify(value);
|
|
250
|
+
rendered = result.value ?? String(value);
|
|
251
|
+
truncated = result.truncated;
|
|
252
|
+
editable = result.editable;
|
|
253
|
+
} catch {
|
|
254
|
+
format = "text";
|
|
255
|
+
rendered = String(value);
|
|
256
|
+
}
|
|
257
|
+
const result = truncateValue(rendered);
|
|
258
|
+
const formatted = {
|
|
259
|
+
editable: editable && !truncated && !result.truncated,
|
|
260
|
+
format,
|
|
261
|
+
type,
|
|
262
|
+
value: result.value
|
|
263
|
+
};
|
|
264
|
+
if (truncated || result.truncated) formatted.truncated = true;
|
|
265
|
+
return formatted;
|
|
266
|
+
}
|
|
267
|
+
//#endregion
|
|
268
|
+
//#region src/runtime/operations.ts
|
|
269
|
+
function isMissingKVConfig(error) {
|
|
270
|
+
const code = error instanceof Error && "code" in error ? error.code : void 0;
|
|
271
|
+
const message = error instanceof Error ? error.message : "";
|
|
272
|
+
if (code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND") return /^Cannot find (?:package|module) ["']#vitehub\/kv\/config["']/.test(message);
|
|
273
|
+
if (code === "ERR_PACKAGE_IMPORT_NOT_DEFINED") return /^Package import specifier ["']#vitehub\/kv\/config["'] is not defined/.test(message);
|
|
274
|
+
return false;
|
|
275
|
+
}
|
|
276
|
+
let kvConfig = false;
|
|
277
|
+
try {
|
|
278
|
+
kvConfig = (await import("#vitehub/kv/config")).kv;
|
|
279
|
+
} catch (error) {
|
|
280
|
+
if (!isMissingKVConfig(error)) throw error;
|
|
281
|
+
}
|
|
282
|
+
/** A failure with the fields that every surface reports. */
|
|
283
|
+
var KVOperationError = class extends Error {
|
|
284
|
+
status;
|
|
285
|
+
code;
|
|
286
|
+
fix;
|
|
287
|
+
constructor(message, status, code, fix) {
|
|
288
|
+
super(redactInspectionText(message));
|
|
289
|
+
this.status = status;
|
|
290
|
+
this.code = code;
|
|
291
|
+
this.fix = fix;
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
const maximumKeyLength = 2048;
|
|
295
|
+
function unwrap(result) {
|
|
296
|
+
const [error, value] = result;
|
|
297
|
+
if (!error) return value;
|
|
298
|
+
const cause = error.code === "KV_OPERATION_FAILED" && error.cause instanceof Error ? ` ${error.cause.message}` : "";
|
|
299
|
+
throw new KVOperationError(`${error.message}${cause}`, error.code === "KV_INVALID_CURSOR" ? 400 : 502, error.code);
|
|
300
|
+
}
|
|
301
|
+
function resolvedStores(config) {
|
|
302
|
+
if (!config) return [];
|
|
303
|
+
const stores = Object.entries(config.stores ?? { default: config.store }).map(([name, store]) => ({
|
|
304
|
+
driver: store.driver,
|
|
305
|
+
name
|
|
306
|
+
}));
|
|
307
|
+
return [...stores.filter((store) => store.name === "default"), ...stores.filter((store) => store.name !== "default").sort((left, right) => left.name.localeCompare(right.name))];
|
|
308
|
+
}
|
|
309
|
+
/** Returns the KV stores of this runtime. The operations accept only these store names. */
|
|
310
|
+
function listKVDevStores() {
|
|
311
|
+
return resolvedStores(kvConfig);
|
|
312
|
+
}
|
|
313
|
+
function ttlNotice(driver, ttl) {
|
|
314
|
+
if (driver === "fs-lite") return "The fs-lite driver ignores TTL. The value does not expire.";
|
|
315
|
+
if (driver === "upstash" && Math.ceil(ttl) !== ttl) return `Upstash rounds the TTL up to ${Math.ceil(ttl)} seconds.`;
|
|
316
|
+
if (driver === "cloudflare-kv-binding") {
|
|
317
|
+
const effectiveTTL = Math.max(60, Math.ceil(ttl));
|
|
318
|
+
if (ttl < 60) return "Cloudflare KV raises a TTL below 60 seconds to 60 seconds.";
|
|
319
|
+
if (effectiveTTL !== ttl) return `Cloudflare KV rounds the TTL up to ${effectiveTTL} seconds.`;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
function selectStore(stores, name = "default") {
|
|
323
|
+
if (stores.length === 0) throw new KVOperationError("KV is disabled in this runtime. Configure `hubKv()` without `kv: false`.", 409, "KV_DISABLED", "Enable KV with hubKv() or vitehub({ kv: true }).");
|
|
324
|
+
const store = stores.find((entry) => entry.name === name);
|
|
325
|
+
if (!store) throw new KVOperationError(`KV store "${name}" was not found. Stores: ${stores.map((entry) => entry.name).join(", ")}.`, 404, "KV_STORE_NOT_FOUND");
|
|
326
|
+
return {
|
|
327
|
+
driver: store.driver,
|
|
328
|
+
name,
|
|
329
|
+
storage: name === "default" ? kv : kv.store(name)
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
/** The keys under `vitehub:` belong to ViteHub, which keeps its own state there. */
|
|
333
|
+
function requireWritableKey(operation, key) {
|
|
334
|
+
if (!normalizeKey(key).toLowerCase().startsWith("vitehub:")) return;
|
|
335
|
+
throw new KVOperationError(`The ${operation} operation cannot change ${key}. ViteHub owns the keys that start with \`vitehub:\`.`, 403, "KV_RESERVED_KEY", "Use another key. Read access (get, has, list) stays open.");
|
|
336
|
+
}
|
|
337
|
+
function requireKey(operation, input) {
|
|
338
|
+
if (input.key === void 0) throw new KVOperationError(`The ${operation} operation requires a key.`, 400, "KV_INVALID_INPUT");
|
|
339
|
+
if (input.key.length > maximumKeyLength) throw new KVOperationError("The key is too long.", 400, "KV_INVALID_INPUT");
|
|
340
|
+
return input.key;
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Runs one `kv.*` operation against the KV stores of this runtime. The Nitro runtime owns the stores and their
|
|
344
|
+
* bindings, so this runs where the app does. There is no operation that clears a store.
|
|
345
|
+
*/
|
|
346
|
+
async function runKVOperation(operation, input, stores = listKVDevStores()) {
|
|
347
|
+
const selected = selectStore(stores, input.store);
|
|
348
|
+
switch (operation) {
|
|
349
|
+
case "list": {
|
|
350
|
+
const limit = input.limit ?? 100;
|
|
351
|
+
if (limit > 1e3) throw new KVOperationError(`limit must be at most ${kvDevMaximumListLimit}.`, 400, "KV_INVALID_INPUT");
|
|
352
|
+
if ((input.prefix?.length ?? 0) > maximumKeyLength) throw new KVOperationError("The prefix is too long.", 400, "KV_INVALID_INPUT");
|
|
353
|
+
const listOptions = {
|
|
354
|
+
limit,
|
|
355
|
+
prefix: input.prefix ?? ""
|
|
356
|
+
};
|
|
357
|
+
if (input.cursor) listOptions.cursor = input.cursor;
|
|
358
|
+
const page = unwrap(await selected.storage.list(listOptions));
|
|
359
|
+
const result = {
|
|
360
|
+
keys: page.keys,
|
|
361
|
+
limit,
|
|
362
|
+
prefix: input.prefix ?? "",
|
|
363
|
+
store: selected.name,
|
|
364
|
+
stores: stores.map((store) => store.name)
|
|
365
|
+
};
|
|
366
|
+
if (page.cursor) result.cursor = page.cursor;
|
|
367
|
+
return result;
|
|
368
|
+
}
|
|
369
|
+
case "get": {
|
|
370
|
+
const key = requireKey(operation, input);
|
|
371
|
+
const value = unwrap(await selected.storage.get(key));
|
|
372
|
+
const found = value !== null || unwrap(await selected.storage.has(key));
|
|
373
|
+
const result = {
|
|
374
|
+
found,
|
|
375
|
+
key,
|
|
376
|
+
store: selected.name
|
|
377
|
+
};
|
|
378
|
+
if (found) result.expiry = selected.driver === "fs-lite" ? "none" : "unknown";
|
|
379
|
+
if (!found) return result;
|
|
380
|
+
if (input.preview) return {
|
|
381
|
+
...result,
|
|
382
|
+
...previewKVValue(value)
|
|
383
|
+
};
|
|
384
|
+
const inspected = inspectKVValue(value);
|
|
385
|
+
if (!inspected) throw new KVOperationError("The stored value cannot be represented by the KV inspection protocol.", 422, "KV_VALUE_UNSUPPORTED");
|
|
386
|
+
return {
|
|
387
|
+
...result,
|
|
388
|
+
...inspected
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
case "has": {
|
|
392
|
+
const key = requireKey(operation, input);
|
|
393
|
+
return {
|
|
394
|
+
exists: unwrap(await selected.storage.has(key)),
|
|
395
|
+
key,
|
|
396
|
+
store: selected.name
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
case "set": {
|
|
400
|
+
const key = requireKey(operation, input);
|
|
401
|
+
requireWritableKey(operation, key);
|
|
402
|
+
if (input.value === void 0) throw new KVOperationError("The set operation requires a value.", 400, "KV_INVALID_INPUT");
|
|
403
|
+
if (selected.driver === "upstash" && input.ttl !== void 0 && input.ttl < 1) throw new KVOperationError("Upstash TTL must be at least 1 second.", 400, "KV_INVALID_INPUT");
|
|
404
|
+
const existed = unwrap(await selected.storage.has(key));
|
|
405
|
+
const ttl = input.ttl === void 0 ? void 0 : selected.driver === "cloudflare-kv-binding" ? Math.max(60, Math.ceil(input.ttl)) : selected.driver === "upstash" ? Math.ceil(input.ttl) : input.ttl;
|
|
406
|
+
unwrap(await selected.storage.set(key, input.value, ttl === void 0 ? void 0 : { ttl }));
|
|
407
|
+
const notice = input.ttl ? ttlNotice(selected.driver, input.ttl) : void 0;
|
|
408
|
+
const result = {
|
|
409
|
+
created: !existed,
|
|
410
|
+
key,
|
|
411
|
+
store: selected.name,
|
|
412
|
+
type: kvValueType(input.value)
|
|
413
|
+
};
|
|
414
|
+
if (notice) result.notice = notice;
|
|
415
|
+
if (ttl) result.ttl = ttl;
|
|
416
|
+
return result;
|
|
417
|
+
}
|
|
418
|
+
case "del": {
|
|
419
|
+
const key = requireKey(operation, input);
|
|
420
|
+
requireWritableKey(operation, key);
|
|
421
|
+
const existed = unwrap(await selected.storage.has(key));
|
|
422
|
+
unwrap(await selected.storage.del(key));
|
|
423
|
+
return {
|
|
424
|
+
deleted: existed,
|
|
425
|
+
key,
|
|
426
|
+
store: selected.name
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
//#endregion
|
|
432
|
+
export { KVOperationError, listKVDevStores, runKVOperation };
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
//#region ../../node_modules/.pnpm/@standard-schema+spec@1.1.0/node_modules/@standard-schema/spec/dist/index.d.ts
|
|
2
|
+
/** The Standard Typed interface. This is a base type extended by other specs. */
|
|
3
|
+
interface StandardTypedV1<Input = unknown, Output = Input> {
|
|
4
|
+
/** The Standard properties. */
|
|
5
|
+
readonly "~standard": StandardTypedV1.Props<Input, Output>;
|
|
6
|
+
}
|
|
7
|
+
declare namespace StandardTypedV1 {
|
|
8
|
+
/** The Standard Typed properties interface. */
|
|
9
|
+
interface Props<Input = unknown, Output = Input> {
|
|
10
|
+
/** The version number of the standard. */
|
|
11
|
+
readonly version: 1;
|
|
12
|
+
/** The vendor name of the schema library. */
|
|
13
|
+
readonly vendor: string;
|
|
14
|
+
/** Inferred types associated with the schema. */
|
|
15
|
+
readonly types?: Types<Input, Output> | undefined;
|
|
16
|
+
}
|
|
17
|
+
/** The Standard Typed types interface. */
|
|
18
|
+
interface Types<Input = unknown, Output = Input> {
|
|
19
|
+
/** The input type of the schema. */
|
|
20
|
+
readonly input: Input;
|
|
21
|
+
/** The output type of the schema. */
|
|
22
|
+
readonly output: Output;
|
|
23
|
+
}
|
|
24
|
+
/** Infers the input type of a Standard Typed. */
|
|
25
|
+
type InferInput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["input"];
|
|
26
|
+
/** Infers the output type of a Standard Typed. */
|
|
27
|
+
type InferOutput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["output"];
|
|
28
|
+
}
|
|
29
|
+
/** The Standard Schema interface. */
|
|
30
|
+
interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
31
|
+
/** The Standard Schema properties. */
|
|
32
|
+
readonly "~standard": StandardSchemaV1.Props<Input, Output>;
|
|
33
|
+
}
|
|
34
|
+
declare namespace StandardSchemaV1 {
|
|
35
|
+
/** The Standard Schema properties interface. */
|
|
36
|
+
interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {
|
|
37
|
+
/** Validates unknown input values. */
|
|
38
|
+
readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result<Output> | Promise<Result<Output>>;
|
|
39
|
+
}
|
|
40
|
+
/** The result interface of the validate function. */
|
|
41
|
+
type Result<Output> = SuccessResult<Output> | FailureResult;
|
|
42
|
+
/** The result interface if validation succeeds. */
|
|
43
|
+
interface SuccessResult<Output> {
|
|
44
|
+
/** The typed output value. */
|
|
45
|
+
readonly value: Output;
|
|
46
|
+
/** A falsy value for `issues` indicates success. */
|
|
47
|
+
readonly issues?: undefined;
|
|
48
|
+
}
|
|
49
|
+
interface Options {
|
|
50
|
+
/** Explicit support for additional vendor-specific parameters, if needed. */
|
|
51
|
+
readonly libraryOptions?: Record<string, unknown> | undefined;
|
|
52
|
+
}
|
|
53
|
+
/** The result interface if validation fails. */
|
|
54
|
+
interface FailureResult {
|
|
55
|
+
/** The issues of failed validation. */
|
|
56
|
+
readonly issues: ReadonlyArray<Issue>;
|
|
57
|
+
}
|
|
58
|
+
/** The issue interface of the failure output. */
|
|
59
|
+
interface Issue {
|
|
60
|
+
/** The error message of the issue. */
|
|
61
|
+
readonly message: string;
|
|
62
|
+
/** The path of the issue, if any. */
|
|
63
|
+
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
|
|
64
|
+
}
|
|
65
|
+
/** The path segment interface of the issue. */
|
|
66
|
+
interface PathSegment {
|
|
67
|
+
/** The key representing a path segment. */
|
|
68
|
+
readonly key: PropertyKey;
|
|
69
|
+
}
|
|
70
|
+
/** The Standard types interface. */
|
|
71
|
+
interface Types<Input = unknown, Output = Input> extends StandardTypedV1.Types<Input, Output> {}
|
|
72
|
+
/** Infers the input type of a Standard. */
|
|
73
|
+
type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;
|
|
74
|
+
/** Infers the output type of a Standard. */
|
|
75
|
+
type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
|
|
76
|
+
}
|
|
77
|
+
//#endregion
|
|
78
|
+
//#region ../internal/src/operations.d.ts
|
|
79
|
+
/** `read` never changes state. `write` changes state. `destructive` deletes or publishes. */
|
|
80
|
+
type OperationKind = "read" | "write" | "destructive";
|
|
81
|
+
/** The signed-in user of a call. */
|
|
82
|
+
interface OperationUser {
|
|
83
|
+
id: string;
|
|
84
|
+
name?: string;
|
|
85
|
+
email?: string;
|
|
86
|
+
image?: string;
|
|
87
|
+
[key: string]: unknown;
|
|
88
|
+
}
|
|
89
|
+
/** The Agent Actor when an agent calls through a capability or MCP on behalf of a user. */
|
|
90
|
+
interface OperationActor {
|
|
91
|
+
id: string;
|
|
92
|
+
kind?: string;
|
|
93
|
+
label?: string;
|
|
94
|
+
meta?: object;
|
|
95
|
+
}
|
|
96
|
+
/** The checked Console access of a call. `vite-hub` issues it. `ConsoleAccess` has this shape. */
|
|
97
|
+
interface OperationAccess {
|
|
98
|
+
readonly mode: string;
|
|
99
|
+
/**
|
|
100
|
+
* The sections that the call may use. `"all"` when no section filter applies. An entry is a section id (`"kv"`, every
|
|
101
|
+
* operation of the section) or `"<section>:read"` (only the operations that read).
|
|
102
|
+
*/
|
|
103
|
+
readonly sections: "all" | readonly string[];
|
|
104
|
+
readonly user?: OperationUser;
|
|
105
|
+
}
|
|
106
|
+
interface OperationContext {
|
|
107
|
+
/** The checked Console access of the call. */
|
|
108
|
+
access: OperationAccess;
|
|
109
|
+
/** The signed-in user, or null. */
|
|
110
|
+
user: OperationUser | null;
|
|
111
|
+
/** The Agent Actor when an agent calls on behalf of `user`. */
|
|
112
|
+
actor?: OperationActor;
|
|
113
|
+
surface: "console" | "cli" | "mcp" | "agent";
|
|
114
|
+
/** Set by the host from generated build identity, never from request input or runtime NODE_ENV. */
|
|
115
|
+
development?: boolean;
|
|
116
|
+
env?: Record<string, unknown>;
|
|
117
|
+
waitUntil?: (task: Promise<unknown>) => void;
|
|
118
|
+
request?: Request;
|
|
119
|
+
/** Operations set a success status here, such as 202 for an accepted call. */
|
|
120
|
+
response?: {
|
|
121
|
+
status?: number;
|
|
122
|
+
};
|
|
123
|
+
/**
|
|
124
|
+
* An agent or an MCP client may pass `lease: "override"` to `content.save`, `content.remove`, and `content.restore`
|
|
125
|
+
* only when the developer allowed it. Defaults to false, so a model cannot take over a document that a person is editing.
|
|
126
|
+
*/
|
|
127
|
+
overrideLeases?: boolean;
|
|
128
|
+
/**
|
|
129
|
+
* What an Agent may read of the Channel conversations, set by `operations({ conversations })`. `participant`: only the
|
|
130
|
+
* threads that the Actor takes part in. `all`: every thread. Unset: none.
|
|
131
|
+
*/
|
|
132
|
+
conversations?: "all" | "participant";
|
|
133
|
+
}
|
|
134
|
+
interface OperationDefinition<Input, Output> {
|
|
135
|
+
/** `<section>.<verb>`, such as `content.publish`. Unique per app. */
|
|
136
|
+
name: string;
|
|
137
|
+
/** One sentence. Becomes the CLI help line and the MCP tool description. */
|
|
138
|
+
description: string;
|
|
139
|
+
/**
|
|
140
|
+
* Console section that grants access, such as `content`. `false`: any Console user. A function reads the section
|
|
141
|
+
* from the input, for operations that serve several sections.
|
|
142
|
+
*/
|
|
143
|
+
section: string | false | ((input: Input) => string | undefined);
|
|
144
|
+
/** `read` never changes state. `write` changes state. `destructive` deletes or publishes; the CLI asks for `--yes`, MCP marks `destructiveHint`, agents require approval by default. */
|
|
145
|
+
kind: OperationKind;
|
|
146
|
+
/** Standard Schema (valibot in this repo). Its Standard JSON Schema builds CLI flags and the MCP input schema. */
|
|
147
|
+
input: StandardSchemaV1<unknown, Input>;
|
|
148
|
+
output?: StandardSchemaV1<unknown, Output>;
|
|
149
|
+
cli?: {
|
|
150
|
+
/** Defaults: namespace = section, command = verb. */
|
|
151
|
+
namespace?: string;
|
|
152
|
+
command?: string;
|
|
153
|
+
/** Input keys read from positional arguments, in order. */
|
|
154
|
+
positional?: string[];
|
|
155
|
+
/** Human output, written verbatim. Without it the CLI prints JSON. `--json` always prints JSON. */
|
|
156
|
+
format?: (output: Output) => string;
|
|
157
|
+
/** `vitehub <namespace>` runs this command when no command is named, such as `vitehub usage`. */
|
|
158
|
+
default?: boolean;
|
|
159
|
+
/**
|
|
160
|
+
* Route of the app that takes a signed dispatch of this operation, such as `/_vitehub/schedules/run`. With `--url`
|
|
161
|
+
* and a dispatch key in the environment (`VITEHUB_DISPATCH_KEY`), the command signs the input and posts it there, so
|
|
162
|
+
* a CI job needs no Console credentials. Without a key it calls the RPC.
|
|
163
|
+
*/
|
|
164
|
+
dispatch?: string;
|
|
165
|
+
};
|
|
166
|
+
/** Largest request body in bytes. It can raise the 64 KiB default but not lower it. */
|
|
167
|
+
maxRequestBytes?: number;
|
|
168
|
+
/**
|
|
169
|
+
* Returns true when this call only reads, such as a dry run of a `destructive` operation. The CLI then skips the
|
|
170
|
+
* confirmation, and agents run it without approval. Without it, every call of a `destructive` operation asks.
|
|
171
|
+
*/
|
|
172
|
+
readOnlyWhen?: (input: Input) => boolean;
|
|
173
|
+
/** `false`: MCP does not offer the operation as a tool, such as an editor transport that only the Console uses. */
|
|
174
|
+
mcp?: false;
|
|
175
|
+
/** `false`: the operation never reads `context.user`, so the Console skips the session lookup for it. */
|
|
176
|
+
user?: false;
|
|
177
|
+
/**
|
|
178
|
+
* The operation runs code of the app, such as a workflow, a job, a task, or a schedule. The Console registers it only
|
|
179
|
+
* when `console.invoke` is on, which is the default in development and off in a production build.
|
|
180
|
+
*/
|
|
181
|
+
invoke?: true;
|
|
182
|
+
run: (input: Input, context: OperationContext) => Output | Promise<Output>;
|
|
183
|
+
}
|
|
184
|
+
/** An operation of any input and output, as a registry holds it. */
|
|
185
|
+
interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "output" | "readOnlyWhen" | "run" | "section"> {
|
|
186
|
+
readOnlyWhen?: (input: never) => boolean;
|
|
187
|
+
cli?: {
|
|
188
|
+
namespace?: string;
|
|
189
|
+
command?: string;
|
|
190
|
+
default?: boolean;
|
|
191
|
+
dispatch?: string;
|
|
192
|
+
positional?: string[];
|
|
193
|
+
format?: (output: never) => string;
|
|
194
|
+
};
|
|
195
|
+
input: StandardSchemaV1;
|
|
196
|
+
output?: StandardSchemaV1;
|
|
197
|
+
run: (input: never, context: OperationContext) => unknown;
|
|
198
|
+
section: string | false | ((input: never) => string | undefined);
|
|
199
|
+
}
|
|
200
|
+
/** The contribution of one plugin: operations, or a module that exports them. */
|
|
201
|
+
interface OperationContributionEntry {
|
|
202
|
+
/** Module the app imports, such as `@vite-hub/content/operations`. */
|
|
203
|
+
module: string;
|
|
204
|
+
/** Named export that holds an operation or an array of operations. Defaults to `default`. */
|
|
205
|
+
export?: string;
|
|
206
|
+
/** Loads the export in the tool process, for a module that the tool cannot resolve by name. */
|
|
207
|
+
load?: () => Promise<unknown>;
|
|
208
|
+
/** `false`: the app already has these operations at runtime. Only tools such as the CLI and `vitehub inspect` read the entry. */
|
|
209
|
+
runtime?: false;
|
|
210
|
+
}
|
|
211
|
+
//#endregion
|
|
212
|
+
export { OperationContributionEntry as n, AnyOperation as t };
|