@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
package/README.md
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
# @vite-hub/kv
|
|
2
2
|
|
|
3
3
|
<p>
|
|
4
|
-
<a href="https://vitehub.dev"><img alt="ViteHub" src="https://
|
|
5
|
-
<img alt="TypeScript" src="https://
|
|
6
|
-
<img alt="Vite" src="https://
|
|
7
|
-
<img alt="KV" src="https://
|
|
4
|
+
<a href="https://vitehub.dev"><img alt="ViteHub" src="https://comark-ui.onmax.me/badge.svg?label=ViteHub&value=vitehub.dev"></a>
|
|
5
|
+
<img alt="TypeScript" src="https://comark-ui.onmax.me/badge.svg?label=TypeScript&value=ready">
|
|
6
|
+
<img alt="Vite" src="https://comark-ui.onmax.me/badge.svg?label=Vite&value=config">
|
|
7
|
+
<img alt="KV" src="https://comark-ui.onmax.me/badge.svg?label=KV&value=stores">
|
|
8
8
|
</p>
|
|
9
9
|
|
|
10
10
|
`@vite-hub/kv` gives server code one small-state API for settings, flags, cache entries, and JSON-like records.
|
|
@@ -52,16 +52,41 @@ export default defineConfig({
|
|
|
52
52
|
|
|
53
53
|
Use `hubKv()` in Vite to resolve KV config and expose the `kv` runtime helper to server code.
|
|
54
54
|
|
|
55
|
-
Providers include local `fs-lite`, [Cloudflare Workers KV](https://developers.cloudflare.com/kv/), and [Upstash Redis](https://upstash.com/docs/redis/overall/getstarted). The storage layer is built on [unstorage](https://unstorage.unjs.io/guide).
|
|
55
|
+
Providers include local `fs-lite`, Deno KV, [Cloudflare Workers KV](https://developers.cloudflare.com/kv/), and [Upstash Redis](https://upstash.com/docs/redis/overall/getstarted). The storage layer is built on [unstorage](https://unstorage.unjs.io/guide).
|
|
56
|
+
|
|
57
|
+
Deno KV accepts `kv.set(key, value, { ttl: seconds })` to expire a value. Omitting `ttl` keeps the value until it is deleted or replaced. Initialization failures do not disable a store for the life of the process. The next operation can retry initialization.
|
|
56
58
|
|
|
57
59
|
## Listing keys
|
|
58
60
|
|
|
59
61
|
`kv.keys(prefix)` is exhaustive. Use `kv.list({ prefix, limit, cursor })` when the caller needs bounded work. `limit` must be a positive integer. A page returns `{ keys, cursor? }`; an omitted cursor means the listing is complete.
|
|
60
62
|
|
|
61
|
-
|
|
63
|
+
List prefixes use the same key normalization as reads and writes. For example, `users/al` matches the stored key `users:alice`. A trailing separator, such as `users/` or `users:`, limits the prefix to children and does not match `users-other`.
|
|
64
|
+
|
|
65
|
+
Cursors are opaque and provider-specific. Pass a returned cursor back to the same store with the same prefix. Cloudflare KV, Upstash, Deno KV, and `fs-lite` stop enumeration when the requested page is full. An `fs-lite` cursor retains a directory iterator in the current process for up to 15 minutes. Upstash uses the same retention window when the provider returns more keys than requested. These process-local cursors can expire sooner when more than 32 listings are left unfinished. Calling `disposeKVStores()` from the application shutdown hook releases these process-local cursors, closes retained directory iterators, and clears their expiry timers. A pending listing cannot retain a new cursor after disposal. Callers must restart listing without a cursor when continuation fails.
|
|
66
|
+
|
|
67
|
+
KV operations return `[error, value]`. `error.code` is one of the codes of the method, for example `KV_INVALID_CURSOR` for `list()`, and `error.why`, `error.fix`, and `error.docs` explain it. Provider failures use the code `KV_OPERATION_FAILED` and keep the provider failure in `cause`. See [KV limits and errors](https://vitehub.dev/docs/kv/limits-and-errors). Configuration errors, for example an unknown named store, throw.
|
|
68
|
+
|
|
69
|
+
Upstash also supports `kv.getAndDelete(key)` and `kv.increment(key, ttl)`. These operations are atomic in the provider. Deno KV, Cloudflare KV, and `fs-lite` return `KV_UNSUPPORTED_OPERATION` because they cannot provide the same contract without extra storage or non-atomic calls.
|
|
70
|
+
|
|
71
|
+
## Application teardown
|
|
72
|
+
|
|
73
|
+
Call `disposeKVStores()` from `@vite-hub/kv` (or `vite-hub/kv`) after stopping new application work. It disposes every initialized default and named store, waits for pending store initialization and cleanup, and reports cleanup failures with an `AggregateError`. Concurrent teardown calls share one promise. Later operations create fresh stores; old process-local cursors cannot resume.
|
|
74
|
+
|
|
75
|
+
For Nitro, register the cleanup in a server plugin:
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
// server/plugins/kv-cleanup.ts
|
|
79
|
+
import { disposeKVStores } from "@vite-hub/kv"
|
|
80
|
+
|
|
81
|
+
export default defineNitroPlugin((nitroApp) => {
|
|
82
|
+
nitroApp.hooks.hook("close", disposeKVStores)
|
|
83
|
+
})
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## CLI
|
|
62
87
|
|
|
63
|
-
|
|
88
|
+
`hubKv()` contributes the `vitehub kv` CLI namespace: `list [--prefix] [--limit] [--cursor]`, `get <key>`, `has <key>`, `set <key> <value|@file> [--ttl <seconds>] [--json-value]`, and `del <key>`. Each command accepts `--store <name>` and `--json`. `get` writes stored strings unchanged, without adding a newline. JSON input rejects underflow and decimal values that change magnitude during parsing; use strings to preserve them. Write commands print what they changed. There is no `clear` command.
|
|
64
89
|
|
|
65
|
-
|
|
90
|
+
Each command runs a `kv.*` operation of the app through the Console RPC (`@vite-hub/kv/operations`). On the dev server it needs no sign-in. With `--url` it calls a deployed app. The same operations serve the Console KV page, which edits and deletes keys, and agents.
|
|
66
91
|
|
|
67
92
|
Learn more at [vitehub.dev](https://vitehub.dev).
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { Diagnostic } from "nostics";
|
|
2
|
+
//#region ../internal/src/provision.d.ts
|
|
3
|
+
type ProvisionProvider = "cloudflare" | "vercel";
|
|
4
|
+
interface ProvisionLogger {
|
|
5
|
+
log: (message: string) => void;
|
|
6
|
+
warn: (message: string) => void;
|
|
7
|
+
}
|
|
8
|
+
interface ProvisionContext {
|
|
9
|
+
env: Record<string, string | undefined>;
|
|
10
|
+
fetch: typeof globalThis.fetch;
|
|
11
|
+
logger: ProvisionLogger;
|
|
12
|
+
markPlanUnchecked?: () => void;
|
|
13
|
+
}
|
|
14
|
+
interface ProvisionState {
|
|
15
|
+
cloudflare?: Record<string, Record<string, string>>;
|
|
16
|
+
vercel?: Record<string, Record<string, string>>;
|
|
17
|
+
}
|
|
18
|
+
interface ProvisionResult {
|
|
19
|
+
ids?: ProvisionState;
|
|
20
|
+
}
|
|
21
|
+
interface ProvisionAction {
|
|
22
|
+
kind: string;
|
|
23
|
+
name: string;
|
|
24
|
+
exists: boolean;
|
|
25
|
+
pending?: boolean;
|
|
26
|
+
apply: () => Promise<ProvisionResult>;
|
|
27
|
+
}
|
|
28
|
+
interface ProvisionStep {
|
|
29
|
+
id: string;
|
|
30
|
+
provider: ProvisionProvider;
|
|
31
|
+
plan: (context: ProvisionContext) => Promise<ProvisionAction[]>;
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region ../internal/src/cli.d.ts
|
|
35
|
+
interface ViteHubCliStreams {
|
|
36
|
+
stderr: {
|
|
37
|
+
write: (chunk: string | Uint8Array, encoding?: BufferEncoding | StdoutWriteCallback, callback?: StdoutWriteCallback) => unknown;
|
|
38
|
+
};
|
|
39
|
+
stdout: {
|
|
40
|
+
write: (chunk: string | Uint8Array) => unknown;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
interface ViteHubCliSpawnResult {
|
|
44
|
+
exitCode: number | null;
|
|
45
|
+
signal?: NodeJS.Signals | null;
|
|
46
|
+
}
|
|
47
|
+
interface ViteHubCliSpawnOptions {
|
|
48
|
+
cwd?: string;
|
|
49
|
+
env?: NodeJS.ProcessEnv;
|
|
50
|
+
stderr?: "inherit" | "pipe";
|
|
51
|
+
stdout?: "inherit" | "pipe";
|
|
52
|
+
}
|
|
53
|
+
type ViteHubCliSpawn = (command: string, args: string[], options?: ViteHubCliSpawnOptions) => Promise<ViteHubCliSpawnResult>;
|
|
54
|
+
interface ViteHubCliContext extends ViteHubCliStreams {
|
|
55
|
+
cwd: string;
|
|
56
|
+
env: NodeJS.ProcessEnv;
|
|
57
|
+
/** Replaces `fetch` for commands that call a running app, so tests need no server. */
|
|
58
|
+
fetch?: typeof fetch;
|
|
59
|
+
rootDir: string;
|
|
60
|
+
spawn: ViteHubCliSpawn;
|
|
61
|
+
}
|
|
62
|
+
interface ViteHubCliFeature {
|
|
63
|
+
description?: string;
|
|
64
|
+
name: string;
|
|
65
|
+
run: (args: string[], context: ViteHubCliContext) => Promise<number | void> | number | void;
|
|
66
|
+
usage?: string;
|
|
67
|
+
}
|
|
68
|
+
interface ViteHubCliCommandNamespace {
|
|
69
|
+
/** The feature that `vitehub <name>` runs when no feature is named. */
|
|
70
|
+
defaultFeature?: string;
|
|
71
|
+
description?: string;
|
|
72
|
+
features: ViteHubCliFeature[];
|
|
73
|
+
name: string;
|
|
74
|
+
}
|
|
75
|
+
interface ViteHubCliContributor {
|
|
76
|
+
namespaces: ViteHubCliCommandNamespace[];
|
|
77
|
+
provision?: ProvisionStep[];
|
|
78
|
+
}
|
|
79
|
+
type ViteHubCliContributorFactory = () => ViteHubCliContributor | undefined | Promise<ViteHubCliContributor | undefined>;
|
|
80
|
+
interface ViteHubCliPluginMetadata {
|
|
81
|
+
cli?: ViteHubCliContributor | ViteHubCliContributorFactory;
|
|
82
|
+
}
|
|
83
|
+
type StdoutWriteCallback = (error?: Error | null) => void;
|
|
84
|
+
//#endregion
|
|
85
|
+
export { ViteHubCliStreams as i, ViteHubCliContributor as n, ViteHubCliPluginMetadata as r, ViteHubCliContext as t };
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { i as ViteHubCliStreams, n as ViteHubCliContributor, t as ViteHubCliContext } from "./cli-Cniq99iX.js";
|
|
2
|
+
//#region src/cli.d.ts
|
|
3
|
+
export type KVCliContext = Pick<ViteHubCliContext, "cwd" | "env" | "fetch" | "rootDir"> & ViteHubCliStreams;
|
|
4
|
+
export interface KVCliOptions {
|
|
5
|
+
/** Asks whether `del` may delete a key. Defaults to a prompt on a terminal, and refuses without one. */
|
|
6
|
+
confirm?: (question: string) => boolean | Promise<boolean>;
|
|
7
|
+
fetch?: typeof fetch;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Runs one `vitehub kv` command against a running Vite + Nitro Development Server.
|
|
11
|
+
* `args[0]` is the command name, for example `list` or `set`.
|
|
12
|
+
*/
|
|
13
|
+
export declare function runKVCli(args: string[], context: KVCliContext, options?: KVCliOptions): Promise<number>;
|
|
14
|
+
export declare function createKVCliContributor(options?: KVCliOptions): ViteHubCliContributor;
|
|
15
|
+
//#endregion
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
import { b as readViteHubDevTargetOption, n as callOperationFromCli } from "./operations-ByuDE12r.js";
|
|
2
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-D_cQeZTi.js";
|
|
3
|
+
import { t as kvDevMaximumListLimit } from "./results-p7nPCnaJ.js";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { resolve } from "node:path";
|
|
6
|
+
import { createInterface } from "node:readline/promises";
|
|
7
|
+
import * as v from "valibot";
|
|
8
|
+
//#region src/cli.ts
|
|
9
|
+
const kvDevTargetErrors = {
|
|
10
|
+
invalidInlineTimeout: (message) => kvErrorDiagnostics.KV_CLI_USAGE({ problem: message }),
|
|
11
|
+
invalidTimeout: (message) => kvErrorDiagnostics.KV_CLI_USAGE({ problem: message }),
|
|
12
|
+
missingValue: (message) => kvErrorDiagnostics.KV_CLI_USAGE({ problem: message })
|
|
13
|
+
};
|
|
14
|
+
const kvCommands = [
|
|
15
|
+
{
|
|
16
|
+
description: "List keys of a KV store, one page at a time.",
|
|
17
|
+
key: false,
|
|
18
|
+
name: "list",
|
|
19
|
+
options: [
|
|
20
|
+
"prefix",
|
|
21
|
+
"limit",
|
|
22
|
+
"cursor"
|
|
23
|
+
]
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
description: "Print the value of one key.",
|
|
27
|
+
key: true,
|
|
28
|
+
name: "get",
|
|
29
|
+
options: []
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
description: "Check if a key exists. The exit code is 0 when it exists and 1 when it does not.",
|
|
33
|
+
key: true,
|
|
34
|
+
name: "has",
|
|
35
|
+
options: []
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
description: "Write the value of one key.",
|
|
39
|
+
key: true,
|
|
40
|
+
name: "set",
|
|
41
|
+
options: ["ttl", "json-value"],
|
|
42
|
+
value: true
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
description: "Delete one key.",
|
|
46
|
+
key: true,
|
|
47
|
+
name: "del",
|
|
48
|
+
options: []
|
|
49
|
+
}
|
|
50
|
+
];
|
|
51
|
+
const optionUsage = {
|
|
52
|
+
"cursor": "[--cursor <cursor>]",
|
|
53
|
+
"json-value": "[--json-value]",
|
|
54
|
+
"limit": "[--limit <n>]",
|
|
55
|
+
"prefix": "[--prefix <prefix>]",
|
|
56
|
+
"ttl": "[--ttl <seconds>]"
|
|
57
|
+
};
|
|
58
|
+
const optionHelp = {
|
|
59
|
+
"cursor": " --cursor <cursor> Read the page after this cursor. `list` prints the next cursor.",
|
|
60
|
+
"json-value": " --json-value Parse the value as JSON. Without it, the value is a string.",
|
|
61
|
+
"limit": ` --limit <n> Show at most n keys. Defaults to 100. Maximum ${kvDevMaximumListLimit}.`,
|
|
62
|
+
"prefix": " --prefix <prefix> Show only keys that start with this prefix.",
|
|
63
|
+
"ttl": " --ttl <seconds> Expire the key after this time. Some drivers ignore TTL or raise it to a minimum."
|
|
64
|
+
};
|
|
65
|
+
function commandUsage(command) {
|
|
66
|
+
const key = command.key ? " <key>" : "";
|
|
67
|
+
const value = command.value ? " <value|@file>" : "";
|
|
68
|
+
const options = command.options.map((option) => ` ${optionUsage[option]}`).join("");
|
|
69
|
+
return `vitehub kv ${command.name}${key}${value}${options} [--store <name>] [--json]${command.name === "del" ? " [--yes]" : ""} [--url <url>]`;
|
|
70
|
+
}
|
|
71
|
+
function writeUsage(command, stream) {
|
|
72
|
+
stream.write([
|
|
73
|
+
`Usage: ${commandUsage(command)}`,
|
|
74
|
+
"",
|
|
75
|
+
command.description,
|
|
76
|
+
"The command runs the kv operation of the app: on the dev server of this project, or on a deployed app with --url.",
|
|
77
|
+
...command.value ? ["A value that starts with @ names a UTF-8 file. The path is relative to the current directory."] : [],
|
|
78
|
+
"",
|
|
79
|
+
"Options:",
|
|
80
|
+
...command.options.map((option) => optionHelp[option]),
|
|
81
|
+
" --store <name> KV store. Defaults to `default`.",
|
|
82
|
+
" --json Print JSON.",
|
|
83
|
+
...command.name === "del" ? [" --yes, -y Delete without asking. Without it, the command asks on a terminal and refuses elsewhere."] : [],
|
|
84
|
+
" --url <url> Deployed app URL. Credentials come from VITEHUB_CONSOLE_AUTHORIZATION, VITEHUB_CONSOLE_COOKIE, or CF_ACCESS_*. Defaults to the dev server of this project.",
|
|
85
|
+
" --timeout <ms> Request timeout.",
|
|
86
|
+
" -h, --help Show this help.",
|
|
87
|
+
""
|
|
88
|
+
].join("\n"));
|
|
89
|
+
}
|
|
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
|
+
function parseTTL(value) {
|
|
96
|
+
const ttl = Number(value);
|
|
97
|
+
if (!value || !Number.isFinite(ttl) || ttl <= 0) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "--ttl must be a positive number." });
|
|
98
|
+
return ttl;
|
|
99
|
+
}
|
|
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
|
+
function parseArgs(command, args) {
|
|
116
|
+
const parsed = {
|
|
117
|
+
help: false,
|
|
118
|
+
json: false,
|
|
119
|
+
jsonValue: false,
|
|
120
|
+
yes: false
|
|
121
|
+
};
|
|
122
|
+
const positionals = [];
|
|
123
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
124
|
+
const arg = args[index];
|
|
125
|
+
if (arg === "-h" || arg === "--help") {
|
|
126
|
+
parsed.help = true;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (arg === "--json") {
|
|
130
|
+
parsed.json = true;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if (command.name === "del" && (arg === "--yes" || arg === "-y")) {
|
|
134
|
+
parsed.yes = true;
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (arg === "--json-value" && command.options.includes("json-value")) {
|
|
138
|
+
parsed.jsonValue = true;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (arg === "--") {
|
|
142
|
+
positionals.push(...args.slice(index + 1));
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
const targetOption = readViteHubDevTargetOption(args, index, parsed, kvDevTargetErrors);
|
|
146
|
+
if (targetOption !== void 0) {
|
|
147
|
+
index += targetOption;
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
const store = readOptionValue(args, index, "store");
|
|
151
|
+
if (store) {
|
|
152
|
+
if (!store.value.trim()) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "--store needs a nonempty name." });
|
|
153
|
+
parsed.store = store.value;
|
|
154
|
+
index += store.consumed;
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
let matched = false;
|
|
158
|
+
for (const option of [
|
|
159
|
+
"cursor",
|
|
160
|
+
"limit",
|
|
161
|
+
"prefix",
|
|
162
|
+
"ttl"
|
|
163
|
+
]) {
|
|
164
|
+
if (!command.options.includes(option)) continue;
|
|
165
|
+
const read = readOptionValue(args, index, option);
|
|
166
|
+
if (!read) continue;
|
|
167
|
+
if (option === "cursor" && !read.value.trim()) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "--cursor needs a nonempty value." });
|
|
168
|
+
if (option === "ttl") parsed.ttl = parseTTL(read.value);
|
|
169
|
+
else if (option === "limit") parsed.limit = parsePositiveInteger(option, read.value);
|
|
170
|
+
else parsed[option] = read.value;
|
|
171
|
+
index += read.consumed;
|
|
172
|
+
matched = true;
|
|
173
|
+
break;
|
|
174
|
+
}
|
|
175
|
+
if (matched) continue;
|
|
176
|
+
if (arg.startsWith("-")) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `Unknown option: ${arg}.` });
|
|
177
|
+
positionals.push(arg);
|
|
178
|
+
}
|
|
179
|
+
const expected = (command.key ? 1 : 0) + (command.value ? 1 : 0);
|
|
180
|
+
if (positionals.length > expected) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `Unexpected argument: ${positionals[expected]}.` });
|
|
181
|
+
if (command.key) parsed.key = positionals[0];
|
|
182
|
+
if (command.value) parsed.value = positionals[1];
|
|
183
|
+
if (!parsed.help && command.key && parsed.key === void 0) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "Missing key." });
|
|
184
|
+
if (!parsed.help && command.value && parsed.value === void 0) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "Missing value." });
|
|
185
|
+
if (parsed.limit !== void 0 && parsed.limit > 1e3) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `--limit must be at most ${kvDevMaximumListLimit}.` });
|
|
186
|
+
return parsed;
|
|
187
|
+
}
|
|
188
|
+
function validateJSONNumbers(value) {
|
|
189
|
+
if (v.is(v.number(), value)) {
|
|
190
|
+
if (!Number.isFinite(value) || Object.is(value, -0)) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "JSON numbers must be finite and cannot be negative zero." });
|
|
191
|
+
if (Number.isInteger(value) && !Number.isSafeInteger(value)) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "JSON integers must be within the safe integer range. Use a string for larger integers." });
|
|
192
|
+
}
|
|
193
|
+
if (Array.isArray(value)) value.forEach(validateJSONNumbers);
|
|
194
|
+
else if (v.is(v.record(v.string(), v.unknown()), value)) Object.values(value).forEach(validateJSONNumbers);
|
|
195
|
+
}
|
|
196
|
+
function normalizedDecimal(source) {
|
|
197
|
+
const negative = source.startsWith("-");
|
|
198
|
+
const [mantissa = "", exponent = "0"] = source.replace(/^-/, "").split(/[eE]/);
|
|
199
|
+
const [whole = "", fraction = ""] = mantissa.split(".");
|
|
200
|
+
const digits = `${whole}${fraction}`.replace(/^0+/, "");
|
|
201
|
+
const significant = digits.replace(/0+$/, "");
|
|
202
|
+
const scale = BigInt(exponent) - BigInt(fraction.length) + BigInt(digits.length - significant.length);
|
|
203
|
+
return `${negative ? "-" : ""}${significant}e${scale}`;
|
|
204
|
+
}
|
|
205
|
+
async function readValue(parsed, cwd) {
|
|
206
|
+
const raw = parsed.value;
|
|
207
|
+
const text = raw.startsWith("@") ? await readFile(resolve(cwd, raw.slice(1)), "utf8") : raw;
|
|
208
|
+
if (!parsed.jsonValue) return text;
|
|
209
|
+
try {
|
|
210
|
+
const value = JSON.parse(text, (_key, value, context) => {
|
|
211
|
+
if (value === 0 && context?.source && /[1-9]/.test(context.source.split(/[eE]/, 1)[0])) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "JSON numbers cannot underflow to zero. Use a string to preserve the supplied value." });
|
|
212
|
+
if (v.is(v.number(), value)) validateJSONNumbers(value);
|
|
213
|
+
if (context?.source && v.is(v.number(), value) && value !== 0 && normalizedDecimal(context.source) !== normalizedDecimal(JSON.stringify(value))) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `${Math.abs(value) <= 2 ** -1022 ? "JSON subnormal numbers" : "JSON numbers"} cannot change magnitude when parsed. Use a string to preserve the supplied value.` });
|
|
214
|
+
return value;
|
|
215
|
+
});
|
|
216
|
+
validateJSONNumbers(value);
|
|
217
|
+
return value;
|
|
218
|
+
} catch (error) {
|
|
219
|
+
throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `The value is not valid JSON: ${error instanceof Error ? error.message : String(error)}` });
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
function isRecord(value) {
|
|
223
|
+
return !Array.isArray(value) && v.is(v.record(v.string(), v.unknown()), value);
|
|
224
|
+
}
|
|
225
|
+
function formatValue(result) {
|
|
226
|
+
if (result.encoding === "base64" && v.is(v.string(), result.value)) return Uint8Array.from(atob(result.value), (character) => character.charCodeAt(0));
|
|
227
|
+
if (v.is(v.string(), result.value)) return result.value;
|
|
228
|
+
return `${JSON.stringify(result.value, null, 2)}\n`;
|
|
229
|
+
}
|
|
230
|
+
const targetFields = {
|
|
231
|
+
key: v.string(),
|
|
232
|
+
store: v.string()
|
|
233
|
+
};
|
|
234
|
+
const positiveNumber = v.pipe(v.number(), v.finite(), v.gtValue(0));
|
|
235
|
+
const resultSchemas = {
|
|
236
|
+
list: v.object({
|
|
237
|
+
cursor: v.optional(v.string()),
|
|
238
|
+
keys: v.array(v.string()),
|
|
239
|
+
limit: v.pipe(positiveNumber, v.integer()),
|
|
240
|
+
prefix: v.string(),
|
|
241
|
+
store: v.string(),
|
|
242
|
+
stores: v.array(v.string())
|
|
243
|
+
}),
|
|
244
|
+
get: v.pipe(v.object({
|
|
245
|
+
...targetFields,
|
|
246
|
+
encoding: v.optional(v.literal("base64")),
|
|
247
|
+
found: v.boolean(),
|
|
248
|
+
type: v.optional(v.string()),
|
|
249
|
+
value: v.optional(v.unknown())
|
|
250
|
+
}), v.check((result) => !result.found || result.type !== void 0 && result.value !== void 0, "found KV values require type and value"), v.check((result) => result.encoding !== "base64" || v.is(v.pipe(v.string(), v.regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)), result.value))),
|
|
251
|
+
has: v.object({
|
|
252
|
+
...targetFields,
|
|
253
|
+
exists: v.boolean()
|
|
254
|
+
}),
|
|
255
|
+
set: v.object({
|
|
256
|
+
...targetFields,
|
|
257
|
+
created: v.boolean(),
|
|
258
|
+
notice: v.optional(v.string()),
|
|
259
|
+
ttl: v.optional(positiveNumber),
|
|
260
|
+
type: v.string()
|
|
261
|
+
}),
|
|
262
|
+
del: v.object({
|
|
263
|
+
...targetFields,
|
|
264
|
+
deleted: v.boolean()
|
|
265
|
+
})
|
|
266
|
+
};
|
|
267
|
+
function parseResult(operation, result) {
|
|
268
|
+
switch (operation) {
|
|
269
|
+
case "list": {
|
|
270
|
+
const parsed = v.safeParse(resultSchemas.list, result);
|
|
271
|
+
return parsed.success ? {
|
|
272
|
+
operation,
|
|
273
|
+
value: parsed.output
|
|
274
|
+
} : void 0;
|
|
275
|
+
}
|
|
276
|
+
case "get": {
|
|
277
|
+
const parsed = v.safeParse(resultSchemas.get, result);
|
|
278
|
+
return parsed.success ? {
|
|
279
|
+
operation,
|
|
280
|
+
value: parsed.output
|
|
281
|
+
} : void 0;
|
|
282
|
+
}
|
|
283
|
+
case "has": {
|
|
284
|
+
const parsed = v.safeParse(resultSchemas.has, result);
|
|
285
|
+
return parsed.success ? {
|
|
286
|
+
operation,
|
|
287
|
+
value: parsed.output
|
|
288
|
+
} : void 0;
|
|
289
|
+
}
|
|
290
|
+
case "set": {
|
|
291
|
+
const parsed = v.safeParse(resultSchemas.set, result);
|
|
292
|
+
return parsed.success ? {
|
|
293
|
+
operation,
|
|
294
|
+
value: parsed.output
|
|
295
|
+
} : void 0;
|
|
296
|
+
}
|
|
297
|
+
case "del": {
|
|
298
|
+
const parsed = v.safeParse(resultSchemas.del, result);
|
|
299
|
+
return parsed.success ? {
|
|
300
|
+
operation,
|
|
301
|
+
value: parsed.output
|
|
302
|
+
} : void 0;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
function writeResult(result, context) {
|
|
307
|
+
switch (result.operation) {
|
|
308
|
+
case "list": {
|
|
309
|
+
const page = result.value;
|
|
310
|
+
if (page.keys.some((key) => /[\r\n\u2028\u2029]/.test(key))) return writeFailure({ json: false }, context, { message: "The KV list contains line-breaking keys. Use --json to preserve the complete keys." });
|
|
311
|
+
if (page.keys.length === 0 && page.cursor) context.stderr.write("No keys on this page.\n");
|
|
312
|
+
else if (page.keys.length === 0) context.stderr.write(`No keys${page.prefix ? ` with prefix ${page.prefix}` : ""} in store ${page.store}.\n`);
|
|
313
|
+
else context.stdout.write(`${page.keys.join("\n")}\n`);
|
|
314
|
+
if (page.cursor) context.stderr.write(`More keys exist. Next page: --cursor ${page.cursor}\n`);
|
|
315
|
+
return 0;
|
|
316
|
+
}
|
|
317
|
+
case "get": {
|
|
318
|
+
const value = result.value;
|
|
319
|
+
if (!value.found) {
|
|
320
|
+
context.stderr.write(`Key ${value.key} was not found in store ${value.store}.\n`);
|
|
321
|
+
return 1;
|
|
322
|
+
}
|
|
323
|
+
context.stdout.write(formatValue(value));
|
|
324
|
+
return 0;
|
|
325
|
+
}
|
|
326
|
+
case "has": {
|
|
327
|
+
const value = result.value;
|
|
328
|
+
context.stdout.write(`Key ${value.key} ${value.exists ? "exists" : "does not exist"} in store ${value.store}.\n`);
|
|
329
|
+
return value.exists ? 0 : 1;
|
|
330
|
+
}
|
|
331
|
+
case "set": {
|
|
332
|
+
const value = result.value;
|
|
333
|
+
context.stdout.write([
|
|
334
|
+
`${value.created ? "Created" : "Updated"} key ${value.key} in store ${value.store} (${value.type}${value.ttl ? `, TTL ${value.ttl} s` : ""}).`,
|
|
335
|
+
...value.notice ? [value.notice] : [],
|
|
336
|
+
""
|
|
337
|
+
].join("\n"));
|
|
338
|
+
return 0;
|
|
339
|
+
}
|
|
340
|
+
case "del": {
|
|
341
|
+
const value = result.value;
|
|
342
|
+
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
|
+
return 0;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
function exitCode(operation, result) {
|
|
348
|
+
if (operation === "get") return result.found === true ? 0 : 1;
|
|
349
|
+
if (operation === "has") return result.exists === true ? 0 : 1;
|
|
350
|
+
return 0;
|
|
351
|
+
}
|
|
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
|
+
async function runKVCommand(command, args, context, options) {
|
|
369
|
+
let parsed;
|
|
370
|
+
let value;
|
|
371
|
+
try {
|
|
372
|
+
parsed = parseArgs(command, args);
|
|
373
|
+
if (command.value && !parsed.help) value = await readValue(parsed, context.cwd);
|
|
374
|
+
} catch (error) {
|
|
375
|
+
const terminator = args.indexOf("--");
|
|
376
|
+
if (args.slice(0, terminator < 0 ? args.length : terminator).includes("--json")) return writeFailure({ json: true }, context, { message: error instanceof Error ? error.message : String(error) });
|
|
377
|
+
context.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
378
|
+
writeUsage(command, context.stderr);
|
|
379
|
+
return 1;
|
|
380
|
+
}
|
|
381
|
+
if (parsed.help) {
|
|
382
|
+
writeUsage(command, context.stdout);
|
|
383
|
+
return 0;
|
|
384
|
+
}
|
|
385
|
+
if (command.name === "del" && !parsed.yes) {
|
|
386
|
+
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 writeFailure(parsed, context, {
|
|
388
|
+
code: "KV_NOT_CONFIRMED",
|
|
389
|
+
fix: "Run it again with --yes.",
|
|
390
|
+
message: "kv del deletes a key and was not confirmed."
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
const input = {};
|
|
394
|
+
if (parsed.cursor !== void 0) input.cursor = parsed.cursor;
|
|
395
|
+
if (parsed.key !== void 0) input.key = parsed.key;
|
|
396
|
+
if (parsed.limit !== void 0) input.limit = parsed.limit;
|
|
397
|
+
if (parsed.prefix !== void 0) input.prefix = parsed.prefix;
|
|
398
|
+
if (parsed.store !== void 0) input.store = parsed.store;
|
|
399
|
+
if (parsed.ttl !== void 0) input.ttl = parsed.ttl;
|
|
400
|
+
if (command.value) input.value = value;
|
|
401
|
+
const called = await callOperationFromCli({
|
|
402
|
+
...command.name === "del" ? { confirmed: true } : {},
|
|
403
|
+
env: context.env,
|
|
404
|
+
fetch: context.fetch ?? options.fetch ?? globalThis.fetch,
|
|
405
|
+
rootDir: context.rootDir,
|
|
406
|
+
...parsed.timeout ? { timeout: parsed.timeout } : {},
|
|
407
|
+
...parsed.url ? { url: parsed.url } : {}
|
|
408
|
+
}, `kv.${command.name}`, input);
|
|
409
|
+
if (!called.ok) return writeFailure(parsed, context, {
|
|
410
|
+
code: called.code,
|
|
411
|
+
message: called.message,
|
|
412
|
+
...called.fix ? { fix: called.fix } : {}
|
|
413
|
+
});
|
|
414
|
+
const result = called.value;
|
|
415
|
+
if (!isRecord(result)) return writeFailure(parsed, context, { message: "The kv operation answered with an invalid result." });
|
|
416
|
+
const commandResult = parseResult(command.name, result);
|
|
417
|
+
if (!commandResult) return writeFailure(parsed, context, { message: "The kv operation answered with an invalid result shape." });
|
|
418
|
+
if (!parsed.json) return writeResult(commandResult, context);
|
|
419
|
+
context.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
420
|
+
return exitCode(command.name, result);
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Runs one `vitehub kv` command against a running Vite + Nitro Development Server.
|
|
424
|
+
* `args[0]` is the command name, for example `list` or `set`.
|
|
425
|
+
*/
|
|
426
|
+
async function runKVCli(args, context, options = {}) {
|
|
427
|
+
const [name, ...rest] = args;
|
|
428
|
+
const command = kvCommands.find((entry) => entry.name === name);
|
|
429
|
+
if (!command) {
|
|
430
|
+
context.stderr.write(`${name ? `Unknown kv command: ${name}\n` : ""}Commands: ${kvCommands.map((entry) => entry.name).join(", ")}\n`);
|
|
431
|
+
return 1;
|
|
432
|
+
}
|
|
433
|
+
return await runKVCommand(command, rest, context, options);
|
|
434
|
+
}
|
|
435
|
+
function createKVCliContributor(options = {}) {
|
|
436
|
+
return { namespaces: [{
|
|
437
|
+
description: "Read and write keys of the KV stores in a running Vite + Nitro Development Server.",
|
|
438
|
+
features: kvCommands.map((command) => ({
|
|
439
|
+
description: command.description,
|
|
440
|
+
name: command.name,
|
|
441
|
+
run: async (args, context) => await runKVCommand(command, args, context, options),
|
|
442
|
+
usage: commandUsage(command)
|
|
443
|
+
})),
|
|
444
|
+
name: "kv"
|
|
445
|
+
}] };
|
|
446
|
+
}
|
|
447
|
+
//#endregion
|
|
448
|
+
export { createKVCliContributor, runKVCli };
|