@vite-hub/kv 0.1.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +94 -21
- 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 +99 -77
- package/dist/cloudflare-env-lOtHHsgP.js +46 -0
- package/dist/cloudflare-env-lookup-Bs0VDpU5.js +42 -0
- package/dist/cloudflare-kv-C3NO4C21.js +201 -0
- package/dist/cloudflare-kv-local-C2sbIrFy.js +71 -0
- package/dist/config-LfpUj9hs.js +252 -0
- package/dist/{create-storage-29gMzf41.js → create-storage-BORQm2a8.js} +206 -50
- package/dist/{cursor-history-dqYDlsaD.js → cursor-history-DRHh5bO5.js} +31 -14
- package/dist/database-oJdy0ZVX.js +250 -0
- package/dist/{deno-kv-CSYGvRx4.js → deno-kv-D_VtffFv.js} +12 -4
- package/dist/dev-peer-CHafxbtj.js +238 -0
- package/dist/driver-R4Z5Z5fl.d.ts +15 -0
- package/dist/durability.d.ts +17 -0
- package/dist/durability.js +53 -0
- package/dist/error-diagnostics-C54QQEhN.js +155 -0
- package/dist/errors-DzD6YNEH.js +88 -0
- package/dist/errors.d.ts +17 -1
- package/dist/errors.js +2 -2
- package/dist/fs-lite-BAgpmNAF.js +2 -0
- package/dist/fs-lite-BaklCLuV.js +386 -0
- package/dist/index.d.ts +7 -2
- package/dist/index.js +326 -84
- package/dist/inspect-BIKQsqX4.js +118 -0
- package/dist/invariant-DolT9EEx.js +22 -0
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/{operations-tNUdj3G4.d.ts → operation-definition-nmRu_O3V.d.ts} +42 -15
- package/dist/{operations-pn8_eGob.js → operations-CtrWLmPK.js} +69 -66
- package/dist/operations-D2iI9oN4.js +1363 -0
- package/dist/operations.d.ts +15 -8
- package/dist/operations.js +56 -192
- package/dist/redis-shared-5ogRd3-Y.js +94 -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 +25 -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 +37 -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-Dv-OSXZC.d.ts +325 -0
- package/dist/upstash-B-vaUYqO.js +40 -0
- package/dist/{utils2-Dsb9P4_2.js → utils2-FozcTsmb.js} +5 -2
- package/dist/virtual-module.d.ts +3 -0
- package/dist/vite.d.ts +167 -14
- package/dist/vite.js +1195 -2876
- 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
package/dist/cli.js
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { A as writeCliFailure, C as askOnTerminal, E as readCliOptionValue, O as readViteHubDevTargetOption, T as parseCliPositiveInteger, n as callOperationFromCli, w as listSeedFiles } from "./operations-D2iI9oN4.js";
|
|
2
|
+
import { t as isRecord } from "./object-Da1zyPCR.js";
|
|
3
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-C54QQEhN.js";
|
|
3
4
|
import { t as kvDevMaximumListLimit } from "./results-p7nPCnaJ.js";
|
|
4
5
|
import { readFile } from "node:fs/promises";
|
|
5
|
-
import { resolve } from "node:path";
|
|
6
|
-
import { createInterface } from "node:readline/promises";
|
|
6
|
+
import { extname, join, relative, resolve } from "node:path";
|
|
7
7
|
import * as v from "valibot";
|
|
8
8
|
//#region src/cli.ts
|
|
9
|
+
const usageError = (problem) => kvErrorDiagnostics.KV_CLI_USAGE({ problem });
|
|
9
10
|
const kvDevTargetErrors = {
|
|
10
|
-
invalidInlineTimeout:
|
|
11
|
-
invalidTimeout:
|
|
12
|
-
missingValue:
|
|
11
|
+
invalidInlineTimeout: usageError,
|
|
12
|
+
invalidTimeout: usageError,
|
|
13
|
+
missingValue: usageError,
|
|
14
|
+
unknownOption: usageError
|
|
13
15
|
};
|
|
14
16
|
const kvCommands = [
|
|
15
17
|
{
|
|
@@ -44,10 +46,11 @@ const kvCommands = [
|
|
|
44
46
|
{
|
|
45
47
|
description: "Delete one key.",
|
|
46
48
|
key: true,
|
|
47
|
-
name: "
|
|
49
|
+
name: "delete",
|
|
48
50
|
options: []
|
|
49
51
|
}
|
|
50
52
|
];
|
|
53
|
+
const setCommand = kvCommands.find((command) => command.name === "set");
|
|
51
54
|
const optionUsage = {
|
|
52
55
|
"cursor": "[--cursor <cursor>]",
|
|
53
56
|
"json-value": "[--json-value]",
|
|
@@ -66,7 +69,7 @@ function commandUsage(command) {
|
|
|
66
69
|
const key = command.key ? " <key>" : "";
|
|
67
70
|
const value = command.value ? " <value|@file>" : "";
|
|
68
71
|
const options = command.options.map((option) => ` ${optionUsage[option]}`).join("");
|
|
69
|
-
return `vitehub kv ${command.name}${key}${value}${options} [--store <name>] [--json]${command.name === "
|
|
72
|
+
return `vitehub kv ${command.name}${key}${value}${options} [--store <name>] [--json]${command.name === "delete" ? " [--yes]" : ""} [--url <url>]`;
|
|
70
73
|
}
|
|
71
74
|
function writeUsage(command, stream) {
|
|
72
75
|
stream.write([
|
|
@@ -80,38 +83,18 @@ function writeUsage(command, stream) {
|
|
|
80
83
|
...command.options.map((option) => optionHelp[option]),
|
|
81
84
|
" --store <name> KV store. Defaults to `default`.",
|
|
82
85
|
" --json Print JSON.",
|
|
83
|
-
...command.name === "
|
|
84
|
-
" --url <url> Deployed app URL.
|
|
86
|
+
...command.name === "delete" ? [" --yes, -y Delete without asking. Without it, the command asks on a terminal and refuses elsewhere."] : [],
|
|
87
|
+
" --url <url> Deployed app URL. Set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to sign the calls. Defaults to the dev server of this project.",
|
|
85
88
|
" --timeout <ms> Request timeout.",
|
|
86
89
|
" -h, --help Show this help.",
|
|
87
90
|
""
|
|
88
91
|
].join("\n"));
|
|
89
92
|
}
|
|
90
|
-
function parsePositiveInteger(name, value) {
|
|
91
|
-
const number = Number(value);
|
|
92
|
-
if (!value || !Number.isInteger(number) || number < 1) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `--${name} must be a positive integer.` });
|
|
93
|
-
return number;
|
|
94
|
-
}
|
|
95
93
|
function parseTTL(value) {
|
|
96
94
|
const ttl = Number(value);
|
|
97
95
|
if (!value || !Number.isFinite(ttl) || ttl <= 0) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "--ttl must be a positive number." });
|
|
98
96
|
return ttl;
|
|
99
97
|
}
|
|
100
|
-
function readOptionValue(args, index, name) {
|
|
101
|
-
const arg = args[index];
|
|
102
|
-
if (arg === `--${name}`) {
|
|
103
|
-
const value = args[index + 1];
|
|
104
|
-
if (value === void 0 || value.startsWith("--")) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `--${name} needs a value.` });
|
|
105
|
-
return {
|
|
106
|
-
consumed: 1,
|
|
107
|
-
value
|
|
108
|
-
};
|
|
109
|
-
}
|
|
110
|
-
if (arg.startsWith(`--${name}=`)) return {
|
|
111
|
-
consumed: 0,
|
|
112
|
-
value: arg.slice(name.length + 3)
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
98
|
function parseArgs(command, args) {
|
|
116
99
|
const parsed = {
|
|
117
100
|
help: false,
|
|
@@ -130,7 +113,7 @@ function parseArgs(command, args) {
|
|
|
130
113
|
parsed.json = true;
|
|
131
114
|
continue;
|
|
132
115
|
}
|
|
133
|
-
if (command.name === "
|
|
116
|
+
if (command.name === "delete" && (arg === "--yes" || arg === "-y")) {
|
|
134
117
|
parsed.yes = true;
|
|
135
118
|
continue;
|
|
136
119
|
}
|
|
@@ -147,7 +130,7 @@ function parseArgs(command, args) {
|
|
|
147
130
|
index += targetOption;
|
|
148
131
|
continue;
|
|
149
132
|
}
|
|
150
|
-
const store =
|
|
133
|
+
const store = readCliOptionValue(args, index, "store", usageError);
|
|
151
134
|
if (store) {
|
|
152
135
|
if (!store.value.trim()) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "--store needs a nonempty name." });
|
|
153
136
|
parsed.store = store.value;
|
|
@@ -162,11 +145,11 @@ function parseArgs(command, args) {
|
|
|
162
145
|
"ttl"
|
|
163
146
|
]) {
|
|
164
147
|
if (!command.options.includes(option)) continue;
|
|
165
|
-
const read =
|
|
148
|
+
const read = readCliOptionValue(args, index, option, usageError);
|
|
166
149
|
if (!read) continue;
|
|
167
150
|
if (option === "cursor" && !read.value.trim()) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "--cursor needs a nonempty value." });
|
|
168
151
|
if (option === "ttl") parsed.ttl = parseTTL(read.value);
|
|
169
|
-
else if (option === "limit") parsed.limit =
|
|
152
|
+
else if (option === "limit") parsed.limit = parseCliPositiveInteger(option, read.value, usageError);
|
|
170
153
|
else parsed[option] = read.value;
|
|
171
154
|
index += read.consumed;
|
|
172
155
|
matched = true;
|
|
@@ -219,9 +202,6 @@ async function readValue(parsed, cwd) {
|
|
|
219
202
|
throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `The value is not valid JSON: ${error instanceof Error ? error.message : String(error)}` });
|
|
220
203
|
}
|
|
221
204
|
}
|
|
222
|
-
function isRecord(value) {
|
|
223
|
-
return !Array.isArray(value) && v.is(v.record(v.string(), v.unknown()), value);
|
|
224
|
-
}
|
|
225
205
|
function formatValue(result) {
|
|
226
206
|
if (result.encoding === "base64" && v.is(v.string(), result.value)) return Uint8Array.from(atob(result.value), (character) => character.charCodeAt(0));
|
|
227
207
|
if (v.is(v.string(), result.value)) return result.value;
|
|
@@ -235,6 +215,14 @@ const positiveNumber = v.pipe(v.number(), v.finite(), v.gtValue(0));
|
|
|
235
215
|
const resultSchemas = {
|
|
236
216
|
list: v.object({
|
|
237
217
|
cursor: v.optional(v.string()),
|
|
218
|
+
driver: v.optional(v.picklist([
|
|
219
|
+
"cloudflare",
|
|
220
|
+
"database",
|
|
221
|
+
"deno-kv",
|
|
222
|
+
"fs-lite",
|
|
223
|
+
"redis",
|
|
224
|
+
"upstash"
|
|
225
|
+
])),
|
|
238
226
|
keys: v.array(v.string()),
|
|
239
227
|
limit: v.pipe(positiveNumber, v.integer()),
|
|
240
228
|
prefix: v.string(),
|
|
@@ -259,7 +247,7 @@ const resultSchemas = {
|
|
|
259
247
|
ttl: v.optional(positiveNumber),
|
|
260
248
|
type: v.string()
|
|
261
249
|
}),
|
|
262
|
-
|
|
250
|
+
delete: v.object({
|
|
263
251
|
...targetFields,
|
|
264
252
|
deleted: v.boolean()
|
|
265
253
|
})
|
|
@@ -294,8 +282,8 @@ function parseResult(operation, result) {
|
|
|
294
282
|
value: parsed.output
|
|
295
283
|
} : void 0;
|
|
296
284
|
}
|
|
297
|
-
case "
|
|
298
|
-
const parsed = v.safeParse(resultSchemas.
|
|
285
|
+
case "delete": {
|
|
286
|
+
const parsed = v.safeParse(resultSchemas.delete, result);
|
|
299
287
|
return parsed.success ? {
|
|
300
288
|
operation,
|
|
301
289
|
value: parsed.output
|
|
@@ -307,10 +295,11 @@ function writeResult(result, context) {
|
|
|
307
295
|
switch (result.operation) {
|
|
308
296
|
case "list": {
|
|
309
297
|
const page = result.value;
|
|
310
|
-
if (page.keys.some((key) => /[\r\n\u2028\u2029]/.test(key))) return
|
|
298
|
+
if (page.keys.some((key) => /[\r\n\u2028\u2029]/.test(key))) return writeCliFailure(false, context, { message: "The KV list contains line-breaking keys. Use --json to preserve the complete keys." });
|
|
311
299
|
if (page.keys.length === 0 && page.cursor) context.stderr.write("No keys on this page.\n");
|
|
312
300
|
else if (page.keys.length === 0) context.stderr.write(`No keys${page.prefix ? ` with prefix ${page.prefix}` : ""} in store ${page.store}.\n`);
|
|
313
301
|
else context.stdout.write(`${page.keys.join("\n")}\n`);
|
|
302
|
+
if (page.driver) context.stderr.write(`Store ${page.store} uses the ${page.driver} driver in this server process.\n`);
|
|
314
303
|
if (page.cursor) context.stderr.write(`More keys exist. Next page: --cursor ${page.cursor}\n`);
|
|
315
304
|
return 0;
|
|
316
305
|
}
|
|
@@ -337,7 +326,7 @@ function writeResult(result, context) {
|
|
|
337
326
|
].join("\n"));
|
|
338
327
|
return 0;
|
|
339
328
|
}
|
|
340
|
-
case "
|
|
329
|
+
case "delete": {
|
|
341
330
|
const value = result.value;
|
|
342
331
|
context.stdout.write(value.deleted ? `Deleted key ${value.key} from store ${value.store}.\n` : `Key ${value.key} was not found in store ${value.store}. Deletion completed.\n`);
|
|
343
332
|
return 0;
|
|
@@ -349,22 +338,6 @@ function exitCode(operation, result) {
|
|
|
349
338
|
if (operation === "has") return result.exists === true ? 0 : 1;
|
|
350
339
|
return 0;
|
|
351
340
|
}
|
|
352
|
-
function writeFailure(parsed, context, failure) {
|
|
353
|
-
if (parsed.json) context.stdout.write(`${JSON.stringify({ error: failure }, null, 2)}\n`);
|
|
354
|
-
else context.stderr.write(`${failure.message}${failure.fix ? `\n${failure.fix}` : ""}\n`);
|
|
355
|
-
return 1;
|
|
356
|
-
}
|
|
357
|
-
async function askOnTerminal(question) {
|
|
358
|
-
const terminal = createInterface({
|
|
359
|
-
input: process.stdin,
|
|
360
|
-
output: process.stderr
|
|
361
|
-
});
|
|
362
|
-
try {
|
|
363
|
-
return /^y(es)?$/i.test((await terminal.question(question)).trim());
|
|
364
|
-
} finally {
|
|
365
|
-
terminal.close();
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
341
|
async function runKVCommand(command, args, context, options) {
|
|
369
342
|
let parsed;
|
|
370
343
|
let value;
|
|
@@ -373,7 +346,7 @@ async function runKVCommand(command, args, context, options) {
|
|
|
373
346
|
if (command.value && !parsed.help) value = await readValue(parsed, context.cwd);
|
|
374
347
|
} catch (error) {
|
|
375
348
|
const terminator = args.indexOf("--");
|
|
376
|
-
if (args.slice(0, terminator < 0 ? args.length : terminator).includes("--json")) return
|
|
349
|
+
if (args.slice(0, terminator < 0 ? args.length : terminator).includes("--json")) return writeCliFailure(true, context, { message: error instanceof Error ? error.message : String(error) });
|
|
377
350
|
context.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
378
351
|
writeUsage(command, context.stderr);
|
|
379
352
|
return 1;
|
|
@@ -382,12 +355,12 @@ async function runKVCommand(command, args, context, options) {
|
|
|
382
355
|
writeUsage(command, context.stdout);
|
|
383
356
|
return 0;
|
|
384
357
|
}
|
|
385
|
-
if (command.name === "
|
|
358
|
+
if (command.name === "delete" && !parsed.yes) {
|
|
386
359
|
const question = `Delete key ${parsed.key} from KV store ${parsed.store ?? "default"} at ${parsed.url ?? context.rootDir}? [y/N] `;
|
|
387
|
-
if (!(options.confirm ? await options.confirm(question) : process.stdin.isTTY && process.stderr.isTTY ? await askOnTerminal(question) : false)) return
|
|
360
|
+
if (!(options.confirm ? await options.confirm(question) : process.stdin.isTTY && process.stderr.isTTY ? await askOnTerminal(question) : false)) return writeCliFailure(parsed.json, context, {
|
|
388
361
|
code: "KV_NOT_CONFIRMED",
|
|
389
362
|
fix: "Run it again with --yes.",
|
|
390
|
-
message: "kv
|
|
363
|
+
message: "kv delete deletes a key and was not confirmed."
|
|
391
364
|
});
|
|
392
365
|
}
|
|
393
366
|
const input = {};
|
|
@@ -399,22 +372,22 @@ async function runKVCommand(command, args, context, options) {
|
|
|
399
372
|
if (parsed.ttl !== void 0) input.ttl = parsed.ttl;
|
|
400
373
|
if (command.value) input.value = value;
|
|
401
374
|
const called = await callOperationFromCli({
|
|
402
|
-
...command.name === "
|
|
375
|
+
...command.name === "delete" ? { confirmed: true } : {},
|
|
403
376
|
env: context.env,
|
|
404
377
|
fetch: context.fetch ?? options.fetch ?? globalThis.fetch,
|
|
405
378
|
rootDir: context.rootDir,
|
|
406
379
|
...parsed.timeout ? { timeout: parsed.timeout } : {},
|
|
407
380
|
...parsed.url ? { url: parsed.url } : {}
|
|
408
381
|
}, `kv.${command.name}`, input);
|
|
409
|
-
if (!called.ok) return
|
|
382
|
+
if (!called.ok) return writeCliFailure(parsed.json, context, {
|
|
410
383
|
code: called.code,
|
|
411
384
|
message: called.message,
|
|
412
385
|
...called.fix ? { fix: called.fix } : {}
|
|
413
386
|
});
|
|
414
387
|
const result = called.value;
|
|
415
|
-
if (!isRecord(result)) return
|
|
388
|
+
if (!isRecord(result)) return writeCliFailure(parsed.json, context, { message: "The kv operation answered with an invalid result." });
|
|
416
389
|
const commandResult = parseResult(command.name, result);
|
|
417
|
-
if (!commandResult) return
|
|
390
|
+
if (!commandResult) return writeCliFailure(parsed.json, context, { message: "The kv operation answered with an invalid result shape." });
|
|
418
391
|
if (!parsed.json) return writeResult(commandResult, context);
|
|
419
392
|
context.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
420
393
|
return exitCode(command.name, result);
|
|
@@ -432,17 +405,66 @@ async function runKVCli(args, context, options = {}) {
|
|
|
432
405
|
}
|
|
433
406
|
return await runKVCommand(command, rest, context, options);
|
|
434
407
|
}
|
|
408
|
+
/** The folder of the KV seed files, relative to the project root. */
|
|
409
|
+
const kvSeedDir = "server/seed/kv";
|
|
410
|
+
/**
|
|
411
|
+
* Writes each file in `server/seed/kv/` to the default KV store with `kv set`. The key is the path without its
|
|
412
|
+
* extension, so `server/seed/kv/settings/theme.json` is the key `settings/theme`. A `.json` file is a JSON value, and
|
|
413
|
+
* any other file is a string.
|
|
414
|
+
*/
|
|
415
|
+
async function runKVSeed(seed, context, options) {
|
|
416
|
+
const dir = resolve(options.projectRoot?.() ?? context.rootDir, kvSeedDir);
|
|
417
|
+
const files = await listSeedFiles(dir);
|
|
418
|
+
if (!files?.length) return void 0;
|
|
419
|
+
if (seed.remote && !seed.url) {
|
|
420
|
+
context.stderr.write("[vitehub] The KV seed with --remote writes the deployed app. Pass --url <url>, or set `vitehub({ publicUrl })`.\n");
|
|
421
|
+
return 1;
|
|
422
|
+
}
|
|
423
|
+
const keys = /* @__PURE__ */ new Map();
|
|
424
|
+
for (const file of files) {
|
|
425
|
+
const key = file.slice(0, file.length - extname(file).length);
|
|
426
|
+
const other = keys.get(key);
|
|
427
|
+
if (other) {
|
|
428
|
+
context.stderr.write(`[vitehub] ${kvSeedDir}/${other} and ${kvSeedDir}/${file} are both the KV key ${key}. Keep one of them.\n`);
|
|
429
|
+
return 1;
|
|
430
|
+
}
|
|
431
|
+
keys.set(key, file);
|
|
432
|
+
}
|
|
433
|
+
for (const [key, file] of keys) {
|
|
434
|
+
const path = relative(context.cwd, join(dir, file)) || join(dir, file);
|
|
435
|
+
const flags = [
|
|
436
|
+
...extname(file) === ".json" ? ["--json-value"] : [],
|
|
437
|
+
...seed.url ? ["--url", seed.url] : [],
|
|
438
|
+
...seed.timeout ? ["--timeout", String(seed.timeout)] : []
|
|
439
|
+
];
|
|
440
|
+
const code = await runKVCommand(setCommand, [
|
|
441
|
+
...flags,
|
|
442
|
+
"--",
|
|
443
|
+
key,
|
|
444
|
+
`@${path}`
|
|
445
|
+
], context, options);
|
|
446
|
+
if (code !== 0) return code;
|
|
447
|
+
}
|
|
448
|
+
return 0;
|
|
449
|
+
}
|
|
435
450
|
function createKVCliContributor(options = {}) {
|
|
436
|
-
return {
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
451
|
+
return {
|
|
452
|
+
namespaces: [{
|
|
453
|
+
description: "Read and write keys of the KV stores in a running Vite + Nitro Development Server.",
|
|
454
|
+
features: kvCommands.map((command) => ({
|
|
455
|
+
description: command.description,
|
|
456
|
+
name: command.name,
|
|
457
|
+
run: async (args, context) => await runKVCommand(command, args, context, options),
|
|
458
|
+
usage: commandUsage(command)
|
|
459
|
+
})),
|
|
460
|
+
name: "kv"
|
|
461
|
+
}],
|
|
462
|
+
seeds: [{
|
|
463
|
+
files: `${kvSeedDir}/<key>.json`,
|
|
464
|
+
name: "kv",
|
|
465
|
+
run: async (seed, context) => await runKVSeed(seed, context, options)
|
|
466
|
+
}]
|
|
467
|
+
};
|
|
446
468
|
}
|
|
447
469
|
//#endregion
|
|
448
470
|
export { createKVCliContributor, runKVCli };
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { i as setInstalledCloudflareEnv, n as getActiveCloudflareEnv, r as getCloudflareEnv, t as activeEnvStorageKey } from "./cloudflare-env-lookup-Bs0VDpU5.js";
|
|
2
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
|
+
//#region ../internal/src/runtime/cloudflare-env.ts
|
|
4
|
+
const runtimeGlobal = globalThis;
|
|
5
|
+
const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
|
|
6
|
+
const globalEnvProbe = Symbol("vitehub.cloudflare.global-env-probe");
|
|
7
|
+
/**
|
|
8
|
+
* Under the Nitro Cloudflare dev server, `cloudflare:workers` exports unenv's env proxy, which reads every key from
|
|
9
|
+
* `globalThis.__env__`. Storing that proxy in `__env__` makes it read itself, and the next read overflows the stack.
|
|
10
|
+
*/
|
|
11
|
+
function readsGlobalEnv(env) {
|
|
12
|
+
const scope = globalThis;
|
|
13
|
+
const owned = Object.hasOwn(scope, "__env__");
|
|
14
|
+
const previous = scope.__env__;
|
|
15
|
+
scope.__env__ = { [globalEnvProbe]: true };
|
|
16
|
+
try {
|
|
17
|
+
return Reflect.get(env, globalEnvProbe) === true;
|
|
18
|
+
} catch {
|
|
19
|
+
return false;
|
|
20
|
+
} finally {
|
|
21
|
+
if (owned) scope.__env__ = previous;
|
|
22
|
+
else delete scope.__env__;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function setActiveCloudflareEnv(env) {
|
|
26
|
+
setInstalledCloudflareEnv(env);
|
|
27
|
+
if (!env || !readsGlobalEnv(env)) globalThis.__env__ = env;
|
|
28
|
+
try {
|
|
29
|
+
activeEnvStorage.enterWith({ env });
|
|
30
|
+
} catch {}
|
|
31
|
+
}
|
|
32
|
+
function getActiveCloudflareBinding(name) {
|
|
33
|
+
const env = getActiveCloudflareEnv();
|
|
34
|
+
return env && Object.hasOwn(env, name) ? env[name] : void 0;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Installs the Cloudflare env of a request event, so code without the event, such as a KV or Blob store, finds its
|
|
38
|
+
* bindings. Nitro middleware of Cloudflare primitives call this. A Node dev runner gives the event no env, so without a
|
|
39
|
+
* `fallback` the active env stays as it is.
|
|
40
|
+
*/
|
|
41
|
+
function installCloudflareRequestEnv(event, fallback) {
|
|
42
|
+
const env = getCloudflareEnv(event, { fallback: false }) ?? fallback;
|
|
43
|
+
if (env) setActiveCloudflareEnv(env);
|
|
44
|
+
}
|
|
45
|
+
//#endregion
|
|
46
|
+
export { installCloudflareRequestEnv as n, getActiveCloudflareBinding as t };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
//#region ../internal/src/runtime/cloudflare-env-lookup.ts
|
|
2
|
+
/** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
|
|
3
|
+
const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
|
|
4
|
+
let activeEnv;
|
|
5
|
+
function setInstalledCloudflareEnv(env) {
|
|
6
|
+
activeEnv = env;
|
|
7
|
+
}
|
|
8
|
+
/** The store of the current `runWithActiveCloudflareEnv()` call, or undefined outside one. */
|
|
9
|
+
function getScopedCloudflareEnv() {
|
|
10
|
+
return globalThis[activeEnvStorageKey]?.getStore();
|
|
11
|
+
}
|
|
12
|
+
function getActiveCloudflareEnv() {
|
|
13
|
+
const scoped = getScopedCloudflareEnv();
|
|
14
|
+
if (scoped) return scoped.env;
|
|
15
|
+
const host = globalThis;
|
|
16
|
+
return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
|
|
17
|
+
}
|
|
18
|
+
function ownValue(value, key) {
|
|
19
|
+
if (value === null || typeof value !== "object" && typeof value !== "function" || !Object.hasOwn(value, key)) return void 0;
|
|
20
|
+
return Reflect.get(value, key);
|
|
21
|
+
}
|
|
22
|
+
function ownObject(value) {
|
|
23
|
+
return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
|
|
24
|
+
}
|
|
25
|
+
/** The objects where H3 and Nitro hosts put Cloudflare `env` and `context`, in lookup order. */
|
|
26
|
+
function cloudflareOwners(target) {
|
|
27
|
+
const context = ownObject(ownValue(target, "context"));
|
|
28
|
+
const platform = ownObject(ownValue(context, "_platform"));
|
|
29
|
+
const req = ownObject(ownValue(target, "req"));
|
|
30
|
+
return [
|
|
31
|
+
ownObject(ownValue(context, "cloudflare")),
|
|
32
|
+
ownObject(ownValue(platform, "cloudflare")),
|
|
33
|
+
ownObject(ownValue(ownObject(ownValue(req, "runtime")), "cloudflare"))
|
|
34
|
+
];
|
|
35
|
+
}
|
|
36
|
+
function getCloudflareEnv(event, options = {}) {
|
|
37
|
+
const target = ownObject(event);
|
|
38
|
+
for (const candidate of [ownValue(target, "env"), ...cloudflareOwners(target).map((owner) => ownValue(owner, "env"))]) if (candidate) return candidate;
|
|
39
|
+
return options.fallback === false ? void 0 : getActiveCloudflareEnv();
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
export { setInstalledCloudflareEnv as i, getActiveCloudflareEnv as n, getCloudflareEnv as r, activeEnvStorageKey as t };
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { t as invariant } from "./invariant-DolT9EEx.js";
|
|
2
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-C54QQEhN.js";
|
|
3
|
+
import { t as getActiveCloudflareBinding } from "./cloudflare-env-lOtHHsgP.js";
|
|
4
|
+
import { n as normalizeKVListPrefix, t as createKVStorage } from "./create-storage-BORQm2a8.js";
|
|
5
|
+
import { i as setItemsOneByOne, t as chunks } from "./batch--v0ri69O.js";
|
|
6
|
+
import { n as recordCursor, t as createCursorHistory } from "./cursor-history-DRHh5bO5.js";
|
|
7
|
+
import createDriver from "unstorage/drivers/cloudflare-kv-binding";
|
|
8
|
+
//#region src/runtime/cloudflare-kv-limits.ts
|
|
9
|
+
const cloudflareKVLimits = {
|
|
10
|
+
keyBytes: 512,
|
|
11
|
+
minExpirationTtl: 60,
|
|
12
|
+
valueBytes: 26214400
|
|
13
|
+
};
|
|
14
|
+
const encoder = /*#__PURE__*/ new TextEncoder();
|
|
15
|
+
/** Returns the UTF-8 size of `value` when it is above `limit`. */
|
|
16
|
+
function bytesAbove(value, limit) {
|
|
17
|
+
if (value.length * 3 <= limit) return;
|
|
18
|
+
const bytes = encoder.encode(value).byteLength;
|
|
19
|
+
return bytes > limit ? bytes : void 0;
|
|
20
|
+
}
|
|
21
|
+
function assertCloudflareKVKey(key) {
|
|
22
|
+
const bytes = bytesAbove(key, cloudflareKVLimits.keyBytes);
|
|
23
|
+
if (bytes !== void 0) throw kvErrorDiagnostics.KV_KEY_TOO_LONG({
|
|
24
|
+
bytes,
|
|
25
|
+
limit: cloudflareKVLimits.keyBytes
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
/** Checks a `put()` before the binding gets it. `value` is the string that unstorage serialized. */
|
|
29
|
+
function assertCloudflareKVWrite(key, value) {
|
|
30
|
+
assertCloudflareKVKey(key);
|
|
31
|
+
const valueBytes = typeof value === "string" ? bytesAbove(value, cloudflareKVLimits.valueBytes) : void 0;
|
|
32
|
+
if (valueBytes !== void 0) throw kvErrorDiagnostics.KV_VALUE_TOO_LARGE({
|
|
33
|
+
bytes: valueBytes,
|
|
34
|
+
limit: cloudflareKVLimits.valueBytes
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
/** Cloudflare KV rejects an expiration below 60 seconds, so a shorter `ttl` becomes 60 seconds, also on the local store of `vite dev`. */
|
|
38
|
+
function cloudflareKVSetOptions(options) {
|
|
39
|
+
const ttl = options?.ttl;
|
|
40
|
+
return typeof ttl === "number" ? { ttl: Math.max(cloudflareKVLimits.minExpirationTtl, ttl) } : options;
|
|
41
|
+
}
|
|
42
|
+
/** Rejects what a Cloudflare KV binding rejects before the driver call, so every store returns the same named code. */
|
|
43
|
+
function installCloudflareKVLimits(driver) {
|
|
44
|
+
const { getItem, hasItem, removeItem, setItem } = driver;
|
|
45
|
+
driver.getItem = (key, options) => {
|
|
46
|
+
assertCloudflareKVKey(key);
|
|
47
|
+
return getItem.call(driver, key, options);
|
|
48
|
+
};
|
|
49
|
+
driver.hasItem = (key, options) => {
|
|
50
|
+
assertCloudflareKVKey(key);
|
|
51
|
+
return hasItem.call(driver, key, options);
|
|
52
|
+
};
|
|
53
|
+
if (removeItem) driver.removeItem = (key, options) => {
|
|
54
|
+
assertCloudflareKVKey(key);
|
|
55
|
+
return removeItem.call(driver, key, options);
|
|
56
|
+
};
|
|
57
|
+
if (setItem) driver.setItem = (key, value, options) => {
|
|
58
|
+
assertCloudflareKVWrite(key, value);
|
|
59
|
+
return setItem.call(driver, key, value, cloudflareKVSetOptions(options));
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** Preflight serialized writes and deletion keys before either branch starts. */
|
|
63
|
+
function validateCloudflareKVBatch(items, removals) {
|
|
64
|
+
for (const key of removals) assertCloudflareKVKey(key);
|
|
65
|
+
for (const item of items) assertCloudflareKVWrite(item.key, item.value);
|
|
66
|
+
}
|
|
67
|
+
//#endregion
|
|
68
|
+
//#region src/runtime/cloudflare-kv.ts
|
|
69
|
+
function isCloudflareKVString(value) {
|
|
70
|
+
return typeof value === "string";
|
|
71
|
+
}
|
|
72
|
+
function isCloudflareKVListPage(value) {
|
|
73
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
74
|
+
const page = value;
|
|
75
|
+
if (typeof page.list_complete !== "boolean" || !Array.isArray(page.keys)) return false;
|
|
76
|
+
if (!page.keys.every((key) => {
|
|
77
|
+
if (!key || typeof key !== "object" || Array.isArray(key)) return false;
|
|
78
|
+
return isCloudflareKVString(Reflect.get(key, "name"));
|
|
79
|
+
})) return false;
|
|
80
|
+
return page.list_complete || isCloudflareKVString(page.cursor) && page.cursor.length > 0;
|
|
81
|
+
}
|
|
82
|
+
/** Cloudflare reads at most 100 keys in one bulk `get()`. */
|
|
83
|
+
const cloudflareKVBulkGetKeys = 100;
|
|
84
|
+
const cloudflareBindingIdentities = /* @__PURE__ */ new WeakMap();
|
|
85
|
+
let nextCloudflareBindingIdentity = 0;
|
|
86
|
+
function cloudflareBindingNamespace(bindingName, namespaceId, binding) {
|
|
87
|
+
if (typeof namespaceId === "string" && namespaceId.length > 0) return `cloudflare-kv:id:${namespaceId}`;
|
|
88
|
+
if (binding && typeof binding === "object") {
|
|
89
|
+
let identity = cloudflareBindingIdentities.get(binding);
|
|
90
|
+
if (identity === void 0) {
|
|
91
|
+
identity = ++nextCloudflareBindingIdentity;
|
|
92
|
+
cloudflareBindingIdentities.set(binding, identity);
|
|
93
|
+
}
|
|
94
|
+
return `cloudflare-kv:object:${identity}`;
|
|
95
|
+
}
|
|
96
|
+
return typeof bindingName === "string" ? `cloudflare-kv:binding:${bindingName}` : "cloudflare-kv:default";
|
|
97
|
+
}
|
|
98
|
+
function createCloudflareDriver(options) {
|
|
99
|
+
const bindingName = options.binding;
|
|
100
|
+
const namespaceId = options.namespaceId;
|
|
101
|
+
const driverOptions = typeof bindingName === "string" ? {
|
|
102
|
+
...options,
|
|
103
|
+
get binding() {
|
|
104
|
+
return getActiveCloudflareBinding(bindingName) ?? bindingName;
|
|
105
|
+
}
|
|
106
|
+
} : options;
|
|
107
|
+
const driver = createDriver(driverOptions);
|
|
108
|
+
installCloudflareKVLimits(driver);
|
|
109
|
+
driver.validateBatch = validateCloudflareKVBatch;
|
|
110
|
+
driver.getItems = async (items) => {
|
|
111
|
+
for (const item of items) assertCloudflareKVKey(item.key);
|
|
112
|
+
const values = /* @__PURE__ */ new Map();
|
|
113
|
+
for (const batch of chunks([...new Set(items.map((item) => item.key))], cloudflareKVBulkGetKeys)) {
|
|
114
|
+
const page = await (await driver.getInstance()).get(batch, "text");
|
|
115
|
+
if (!(page instanceof Map)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Cloudflare KV bulk get did not return a Map." });
|
|
116
|
+
for (const key of batch) {
|
|
117
|
+
const value = page.get(key);
|
|
118
|
+
values.set(key, typeof value === "string" ? value : null);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return items.map((item) => ({
|
|
122
|
+
key: item.key,
|
|
123
|
+
value: values.get(item.key) ?? null
|
|
124
|
+
}));
|
|
125
|
+
};
|
|
126
|
+
const setItemsOneByOneWithLimits = setItemsOneByOne(driver);
|
|
127
|
+
driver.setItems = async (items, commonOptions) => {
|
|
128
|
+
for (const item of items) assertCloudflareKVWrite(item.key, item.value);
|
|
129
|
+
await setItemsOneByOneWithLimits(items, commonOptions);
|
|
130
|
+
};
|
|
131
|
+
const cursorNamespace = cloudflareBindingNamespace(bindingName, namespaceId);
|
|
132
|
+
const cursorHistories = createCursorHistory(cursorNamespace);
|
|
133
|
+
let disposed = false;
|
|
134
|
+
const dispose = driver.dispose;
|
|
135
|
+
driver.dispose = async () => {
|
|
136
|
+
disposed = true;
|
|
137
|
+
cursorHistories.clear();
|
|
138
|
+
try {
|
|
139
|
+
await dispose?.call(driver);
|
|
140
|
+
} finally {
|
|
141
|
+
cursorHistories.clear();
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
driver.listKeys = async ({ cursor, limit, prefix = "" }) => {
|
|
145
|
+
invariant(!disposed, "a KV store is open while the app runs, because Nitro disposes it only when it closes");
|
|
146
|
+
const listOptions = { limit };
|
|
147
|
+
if (cursor) listOptions.cursor = cursor;
|
|
148
|
+
if (prefix) listOptions.prefix = prefix;
|
|
149
|
+
const activeBinding = typeof bindingName === "string" ? getActiveCloudflareBinding(bindingName) : void 0;
|
|
150
|
+
const requestNamespace = cloudflareBindingNamespace(bindingName, namespaceId, activeBinding);
|
|
151
|
+
const continuation = cursor ? cursorHistories.take(cursor, requestNamespace) : {
|
|
152
|
+
providerCursor: void 0,
|
|
153
|
+
history: /* @__PURE__ */ new Set(),
|
|
154
|
+
namespace: requestNamespace
|
|
155
|
+
};
|
|
156
|
+
try {
|
|
157
|
+
if (continuation.providerCursor) listOptions.cursor = continuation.providerCursor;
|
|
158
|
+
const cursors = continuation.history;
|
|
159
|
+
const page = await (await driver.getInstance()).list(listOptions);
|
|
160
|
+
if (!isCloudflareKVListPage(page)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Cloudflare KV list returned an invalid page." });
|
|
161
|
+
const result = { keys: page.keys.map((key) => key.name) };
|
|
162
|
+
if (!page.list_complete) {
|
|
163
|
+
invariant(!disposed, "a KV store is open while the app runs, because Nitro disposes it only when it closes");
|
|
164
|
+
if (cursors.has(page.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "ViteHub rejected a repeated pagination cursor." });
|
|
165
|
+
if (!recordCursor(cursors, page.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "ViteHub rejected pagination after the cursor history limit was reached." });
|
|
166
|
+
result.cursor = cursorHistories.store(page.cursor, cursors, requestNamespace);
|
|
167
|
+
}
|
|
168
|
+
cursorHistories.complete(cursor);
|
|
169
|
+
return result;
|
|
170
|
+
} catch (error) {
|
|
171
|
+
if (cursor && !disposed) cursorHistories.restore(cursor, continuation);
|
|
172
|
+
throw error;
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
driver.clear = async (prefix = "") => {
|
|
176
|
+
const keys = [];
|
|
177
|
+
let cursor;
|
|
178
|
+
do {
|
|
179
|
+
const page = await driver.listKeys({
|
|
180
|
+
cursor,
|
|
181
|
+
limit: 1e3,
|
|
182
|
+
prefix
|
|
183
|
+
});
|
|
184
|
+
keys.push(...page.keys);
|
|
185
|
+
cursor = page.cursor;
|
|
186
|
+
} while (cursor);
|
|
187
|
+
for (const key of keys) await driver.removeItem(key, {});
|
|
188
|
+
};
|
|
189
|
+
return driver;
|
|
190
|
+
}
|
|
191
|
+
function createCloudflareKVStorage(options) {
|
|
192
|
+
const driver = createCloudflareDriver(options);
|
|
193
|
+
const storage = createKVStorage(driver);
|
|
194
|
+
storage.listKeys = (listOptions) => driver.listKeys({
|
|
195
|
+
...listOptions,
|
|
196
|
+
prefix: normalizeKVListPrefix(listOptions.prefix)
|
|
197
|
+
});
|
|
198
|
+
return storage;
|
|
199
|
+
}
|
|
200
|
+
//#endregion
|
|
201
|
+
export { validateCloudflareKVBatch as a, installCloudflareKVLimits as i, createCloudflareKVStorage as n, assertCloudflareKVWrite as r, createCloudflareDriver as t };
|