@vite-hub/kv 0.1.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +86 -15
- package/dist/batch--v0ri69O.js +40 -0
- package/dist/cli-DpPhz_Ek.d.ts +163 -0
- package/dist/cli.d.ts +4 -2
- package/dist/cli.js +98 -77
- package/dist/cloudflare-env-lOtHHsgP.js +46 -0
- package/dist/cloudflare-env-lookup-Bs0VDpU5.js +42 -0
- package/dist/cloudflare-kv-BIEUFzRT.js +187 -0
- package/dist/cloudflare-kv-local-BBw3ZT1K.js +71 -0
- package/dist/config-BXEVoZE3.js +250 -0
- package/dist/{create-storage-29gMzf41.js → create-storage-BGsrQKw3.js} +206 -50
- package/dist/{cursor-history-dqYDlsaD.js → cursor-history-BqIQePNP.js} +31 -14
- package/dist/database-72Jk3VVk.js +250 -0
- package/dist/{deno-kv-CSYGvRx4.js → deno-kv-BM9mYdUp.js} +12 -4
- package/dist/dev-peer-CHafxbtj.js +238 -0
- package/dist/driver-BwxgaQ-f.d.ts +15 -0
- package/dist/durability.d.ts +17 -0
- package/dist/durability.js +53 -0
- package/dist/error-diagnostics-BxqvtEIb.js +147 -0
- package/dist/errors-DbwufFZp.js +60 -0
- package/dist/errors.d.ts +12 -1
- package/dist/errors.js +2 -2
- package/dist/fs-lite-BLZId9_P.js +386 -0
- package/dist/fs-lite-RAoxu8L0.js +2 -0
- package/dist/index.d.ts +7 -2
- package/dist/index.js +302 -75
- package/dist/inspect-BIKQsqX4.js +118 -0
- package/dist/invariant-DolT9EEx.js +22 -0
- package/dist/main-F3Y22_uV.js +2353 -0
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
- package/dist/operations-B-WZ7P1h.js +1351 -0
- package/dist/{operations-pn8_eGob.js → operations-Ch-gKaey.js} +67 -58
- package/dist/operations.d.ts +15 -8
- package/dist/operations.js +55 -192
- package/dist/redis-shared-E5mahECF.js +94 -0
- package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
- package/dist/runtime/cloudflare-kv.d.ts +1 -1
- package/dist/runtime/cloudflare-kv.js +1 -99
- package/dist/runtime/cloudflare-request-env.d.ts +7 -0
- package/dist/runtime/cloudflare-request-env.js +11 -0
- package/dist/runtime/nitro-plugin.d.ts +12 -0
- package/dist/runtime/nitro-plugin.js +22 -0
- package/dist/runtime/redis-driver.d.ts +11 -0
- package/dist/runtime/redis-driver.js +113 -0
- package/dist/runtime/unstorage-driver.d.ts +14 -0
- package/dist/runtime/unstorage-driver.js +33 -0
- package/dist/runtime/upstash-driver.d.ts +2 -2
- package/dist/runtime/upstash-driver.js +58 -98
- package/dist/{driver-D9fI27jl.d.ts → types-Bj3EQoRg.d.ts} +16 -41
- package/dist/types-DEiKew_3.d.ts +312 -0
- package/dist/upstash-DDlqTttY.js +40 -0
- package/dist/{utils2-Dsb9P4_2.js → utils2-FozcTsmb.js} +5 -2
- package/dist/virtual-module.d.ts +2 -0
- package/dist/vite.d.ts +152 -11
- package/dist/vite.js +888 -2836
- package/package.json +30 -21
- package/dist/cli-Cniq99iX.d.ts +0 -85
- package/dist/cloudflare-env-C5rM7kUY.js +0 -74
- package/dist/config-DR6_5ZwI.js +0 -124
- package/dist/continuations-DPyH_vr1.js +0 -63
- package/dist/error-diagnostics-D_cQeZTi.js +0 -82
- package/dist/errors-Dc2oiW-Y.js +0 -38
- package/dist/fs-lite-CbLKxLut.js +0 -90
- package/dist/object-B1NW521B.js +0 -7
- package/dist/operations-ByuDE12r.js +0 -1442
- package/dist/types-CMDvN0Wr.d.ts +0 -81
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
pnpm add @vite-hub/kv
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
-
Add `@upstash/redis` when you use the Upstash driver.
|
|
18
|
+
Add `@upstash/redis` when you use the Upstash driver. The `redis` driver uses `ioredis`, which KV installs.
|
|
19
19
|
|
|
20
20
|
## Minimal API
|
|
21
21
|
|
|
@@ -36,25 +36,63 @@ export default defineEventHandler(async (event) => {
|
|
|
36
36
|
|
|
37
37
|
```ts
|
|
38
38
|
// vite.config.ts
|
|
39
|
-
import {
|
|
39
|
+
import { hubKV } from "@vite-hub/kv/vite"
|
|
40
40
|
import { defineConfig } from "vite"
|
|
41
41
|
|
|
42
42
|
export default defineConfig({
|
|
43
|
-
|
|
43
|
+
plugins: [hubKV({
|
|
44
44
|
driver: "fs-lite",
|
|
45
45
|
base: ".vitehub/data/kv",
|
|
46
|
-
},
|
|
47
|
-
plugins: [hubKv()],
|
|
46
|
+
})],
|
|
48
47
|
})
|
|
49
48
|
```
|
|
50
49
|
|
|
51
50
|
## Vite Integration
|
|
52
51
|
|
|
53
|
-
Use `
|
|
52
|
+
Use `hubKV()` in Vite to resolve KV config and expose the `kv` runtime helper to server code.
|
|
54
53
|
|
|
55
|
-
|
|
54
|
+
An `fs-lite` store without `base` keeps the default store in `.vitehub/data/kv` and each named store in `.vitehub/data/kv-stores/<store>`, so named stores never share keys.
|
|
56
55
|
|
|
57
|
-
|
|
56
|
+
Providers include local `fs-lite`, Deno KV, [Cloudflare Workers KV](https://developers.cloudflare.com/kv/), [Upstash Redis](https://upstash.com/docs/redis/overall/getstarted), Redis over TCP (`redis`), and a table in the app's Database (`database`). The storage layer is built on [unstorage](https://unstorage.unjs.io/guide).
|
|
57
|
+
|
|
58
|
+
## Shared stores on Node
|
|
59
|
+
|
|
60
|
+
Several Node processes share keys only through a shared store. Without a `driver`, a Node build picks:
|
|
61
|
+
|
|
62
|
+
1. `database` when the app has a Default Database on Postgres (the `@vite-hub/database` plugin with a `dialect: "postgresql"` Definition).
|
|
63
|
+
2. `fs-lite` in `.vitehub/data/kv` otherwise.
|
|
64
|
+
|
|
65
|
+
`{ driver: "redis", url?, base? }` reads `url` at runtime when it is `env:<NAME>`, and `env:REDIS_URL` is the default. A literal URL goes into the build output. `base` prefixes every key and defaults to `vitehub:kv:<store>`, so keys that are not ViteHub's stay apart. The generated store segment escapes `%`, `:`, `/`, `\`, and `?`; an empty store name uses `%`. This keeps store names separate after key normalization. Two ViteHub apps on one Redis database share the default, so give each app its own database or `base`. A Redis listing cursor holds its whole state, so another server process can read the next page.
|
|
66
|
+
|
|
67
|
+
`{ driver: "upstash", url?, token?, base? }` uses the same `base` rule as `redis`: every key gets the prefix `vitehub:kv:<store>` unless `base` sets another one, so `kv.clear()` and `kv.keys()` stay inside the store. Upstash takes whole seconds, so `set()` rounds a TTL up. Its listing cursor also holds its whole state, so the next page works in another serverless invocation.
|
|
68
|
+
|
|
69
|
+
`{ driver: "database", database? }` keeps keys in the table `vitehub_kv` of the Database `database` (default `"default"`), with one `namespace` per store. The store creates the table when it is missing; on Postgres, an advisory lock lets several servers start at once. Every atomic operation is one SQL statement, and expiry uses the clock of the Database. Writes start background cleanup of at most 1000 expired rows in their namespace. A full batch lets the next write start another batch; once a batch is not full, cleanup waits a minute. Postgres sweeps skip rows locked by another process. It works on Postgres and libSQL, not on D1.
|
|
70
|
+
|
|
71
|
+
The driver is selected at build time. Redis requires `kv: { driver: "redis" }`; every process must supply its URL, and a missing URL fails. An unrelated `REDIS_URL` never changes the selected driver. A build without a `driver` that has `REDIS_URL`, or a `KV_URL` that starts with `rediss://`, prints a warning with the fix `kv: { driver: "redis" }`. On Vercel without Upstash variables, the same warning says that the inferred Upstash store fails at runtime. The `kv.list` operation (`vitehub kv list`, the Console) reports that driver.
|
|
72
|
+
|
|
73
|
+
This changes the default of a Node build with a Postgres Database from `fs-lite` to `database`. Keys in `.vitehub/data/kv` are not copied. Set `kv: { driver: "fs-lite" }` to keep the old store.
|
|
74
|
+
|
|
75
|
+
`fs-lite` writes each key as one file in `base`. The file name starts with `key-`, followed by the key with `%` and `:` escaped as in a URL, so `signups` and `signups:reset-at` are the files `key-signups` and `key-signups%3Areset-at`. This prefix keeps application keys separate from migration metadata and temporary files. Most file systems limit a file name to 255 bytes, so an escaped key longer than 251 bytes fails with `KV_OPERATION_FAILED`. Earlier versions wrote `a:b` as the file `a/b`. The store moves those files to their new names when it opens the folder and preserves literal `%` characters in old key names. It keeps a hidden layout record and metadata folder in `base`. The migration lock stays in that folder, so only `base` needs write access. Stop all processes that use the store before moving it. Copies and backups must preserve hidden files and hard links. Use GNU `cp -a` and verify the copied layout record before opening the copy; see [Move an fs-lite store](https://vitehub.dev/docs/kv/configure#move-an-fs-lite-store). Ordinary `cp -R` breaks the layout identity and can make existing keys inaccessible.
|
|
76
|
+
|
|
77
|
+
`kv.set(key, value, { ttl: seconds })` expires a value on every driver. Omitting `ttl` keeps the value until it is deleted or replaced. `ttl` is the only option; other options return `KV_INVALID_OPTION`. Cloudflare KV keeps a value at least 60 seconds. `fs-lite` keeps the expiry time of each key in its metadata folder and treats an expired key as missing. Initialization failures do not disable a store for the life of the process. The next operation can retry initialization.
|
|
78
|
+
|
|
79
|
+
## Development stays local
|
|
80
|
+
|
|
81
|
+
In `vite dev` (and `nuxt dev`), a KV store is local unless it sets `remote: true`. When ViteHub infers the driver, Upstash env vars and the Vercel host do not select Upstash in development: the store is `fs-lite` in `.vitehub/data/kv`. On the Cloudflare host, a store uses the KV binding of the dev runtime when there is one, for example on the workerd runner. Without one, for example on Nitro's default Node runner, it uses `fs-lite` in `.vitehub/data/kv-cloudflare/<binding>` with the Workers KV limits.
|
|
82
|
+
|
|
83
|
+
`kv: { remote: true }` lets development infer the hosted store as a build does. On Cloudflare, ViteHub then writes `remote: true` on the generated Wrangler KV binding. The first operation prints `KV store "<name>" is remote`, and `vitehub inspect definitions --kind kv` shows `Development: Remote`. Writes change real data.
|
|
84
|
+
|
|
85
|
+
Development reads Upstash credentials from Vite's `.env` files for the current mode and `envDir`, with process environment values taking precedence. The credentials stay in the development server runtime.
|
|
86
|
+
|
|
87
|
+
An explicit `driver` is honored as before; an `upstash` store prints the same notice. Builds ignore `remote`. A `remote` value that is not a boolean fails with `KV_INVALID_REMOTE`. `remote: true` with `fs-lite` or `deno-kv`, `remote: false` with `upstash`, and `remote: true` in development without a hosted store fail with `KV_REMOTE_CONFLICT`.
|
|
88
|
+
|
|
89
|
+
## Nitro storage
|
|
90
|
+
|
|
91
|
+
When KV is enabled in a Nitro app, the default store is the Nitro storage mount `kv`, and a named store is the mount `kv-<name>`. `useStorage("kv").getItem("a")` reads the same value as `kv.get("a")`, and `clear()` on a mount clears only that store. Store names escape `%`, `:`, `/`, `\\`, and `?` as percent-encoded characters; an empty name uses `%` (for example, `a/b` mounts at `kv-a%2Fb`). A mount with the same name in `nitro.kv` (or the deprecated `nitro.storage`) wins. Nuxt modules that take a mount name, such as nuxt-og-image's `runtimeCacheStorage: "kv"`, store their data in KV this way.
|
|
92
|
+
|
|
93
|
+
`kvStorageDriver` from `@vite-hub/kv/vite` is the file path of the unstorage driver behind these mounts. Its options are `store` (default: the default store) and `base`, a key prefix. Pass it to a module that takes a driver name, or mount it yourself. The driver opens the store on each call, so on Cloudflare it uses the binding of the current request. Nitro's `ttl` goes to `kv.set()`.
|
|
94
|
+
|
|
95
|
+
With `vitehub()`, `cache: { driver: "kv" }` mounts the same driver at Nitro's `cache` mount, with the `nitro-cache:` prefix or the `base` option.
|
|
58
96
|
|
|
59
97
|
## Listing keys
|
|
60
98
|
|
|
@@ -62,19 +100,50 @@ Deno KV accepts `kv.set(key, value, { ttl: seconds })` to expire a value. Omitti
|
|
|
62
100
|
|
|
63
101
|
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
102
|
|
|
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.
|
|
103
|
+
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. Cloudflare KV and Deno KV cursors carry the provider cursor, so a request in another isolate can continue the listing. 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
104
|
|
|
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.
|
|
105
|
+
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`. A Cloudflare KV store checks the [Workers KV limits](https://developers.cloudflare.com/kv/platform/limits/) before it calls the binding, in production and in `vite dev`: a key above 512 bytes returns `KV_KEY_TOO_LONG`, a value above 25 MiB returns `KV_VALUE_TOO_LARGE`, and a `ttl` below 60 seconds becomes 60 seconds. See [KV limits and errors](https://vitehub.dev/docs/kv/limits-and-errors). Configuration errors, for example an unknown named store, throw.
|
|
68
106
|
|
|
69
|
-
|
|
107
|
+
`kv.getMany(keys)` reads many keys in one call and returns one value or `null` per key, in the order of `keys`. `kv.setMany([{ key, value }], options)` writes many keys; the last entry of a key wins, and it is not atomic. Redis uses `MGET` and one pipeline, the `database` driver one statement per 200 keys, Upstash `MGET`, and Cloudflare KV one bulk `get()` per 100 keys. Other reads and writes run one key at a time, 16 at once. Cloudflare KV checks every entry against the Workers KV limits before it writes any.
|
|
108
|
+
|
|
109
|
+
`kv.setIfAbsent(key, value, { ttl })` writes the value only when the key has no value, in one atomic step. Its value is `true` for the one call that wrote it and `false` for the others. Use it for upload tickets, invite codes, and nonces instead of `get()` then `set()`, which two requests can race. Redis runs `SET NX` with `PX`, the `database` driver one `INSERT ... ON CONFLICT` that also replaces an expired key, and Upstash `SET NX`. Deno KV commits an atomic check that the key is missing; it deletes expired keys some time after the TTL. `fs-lite` creates the file exclusively, which is atomic on one disk, and expires keys with `ttl` on time. Cloudflare KV returns `KV_UNSUPPORTED_OPERATION`, because Workers KV is eventually consistent; use D1 or a Durable Object there.
|
|
110
|
+
|
|
111
|
+
`redis`, `database`, and Upstash also support `kv.getAndDelete(key)`, `kv.increment(key, ttl)`, and `kv.deleteIfEquals(key, expected)`. These operations are atomic in the provider. `deleteIfEquals()` deletes the key only when its stored text equals `expected` serialized as `set()` stores it, and returns `true` when this call deleted it. 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. The type `KVDriverAtomicOperations` lists the atomic operations of each driver, and `KVDriversWith<"deleteIfEquals">` the drivers of one operation.
|
|
112
|
+
|
|
113
|
+
## Locks
|
|
114
|
+
|
|
115
|
+
`kv.lock(key, { ttl, wait })` gives a lock that one runner holds at a time across the processes that share a store. `run(fn)` takes the lock, calls `fn`, and releases the lock, also when `fn` throws:
|
|
116
|
+
|
|
117
|
+
```ts fragment
|
|
118
|
+
const [error, result] = await kv.lock("cron:daily", { ttl: 60 }).run(() => sendDailyReport())
|
|
119
|
+
if (error) throw error
|
|
120
|
+
if (!result.acquired) return // Another runner holds the lock.
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
`ttl` (seconds) is required, so a crashed runner never keeps the lock. `wait` (seconds) polls with backoff until the lock is free. Each lock writes a random owner token with `setIfAbsent()` and frees it with `deleteIfEquals()`, so a runner whose lock expired cannot delete the next runner's lock. `acquire()` returns a `release()` function for code that does not fit in one callback. KV does not renew a lock: when the work runs longer than `ttl`, another runner can take it.
|
|
124
|
+
|
|
125
|
+
Only the drivers in `KVDriversWith<"deleteIfEquals">` (`redis`, `database`, `upstash`) support locks. Deno KV, Cloudflare KV, and `fs-lite` return `KV_UNSUPPORTED_OPERATION` without calling `fn`. App tests use `fs-lite`, so they return this code too.
|
|
126
|
+
|
|
127
|
+
## Read-only handles
|
|
128
|
+
|
|
129
|
+
`kv.store(name, { mode: "read" })` returns a `ReadonlyKVStorage` handle with `get()`, `getMany()`, `has()`, `keys()`, and `list()`. Write methods are a type error and absent at runtime. `mode` defaults to `"write"`, and another value throws `KV_INVALID_STORE_MODE`.
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
import { kv } from "@vite-hub/kv"
|
|
133
|
+
|
|
134
|
+
const flags = kv.store("default", { mode: "read" })
|
|
135
|
+
const [error, value] = await flags.get("flags")
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
The mode limits this API, not the host. The KV binding or provider token keeps full access, and code can still import the full `kv` export, so it is not a security boundary against code that reads the binding directly.
|
|
70
139
|
|
|
71
140
|
## Application teardown
|
|
72
141
|
|
|
73
142
|
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
143
|
|
|
75
|
-
For Nitro, register the cleanup in a server plugin:
|
|
144
|
+
For an explicit Redis store or an inferred Node store, `hubKV()` registers this cleanup on Nitro's `close` hook, so the Redis connection does not keep the process alive after a stop signal. For other stores, register the cleanup in a server plugin:
|
|
76
145
|
|
|
77
|
-
```ts
|
|
146
|
+
```ts fragment
|
|
78
147
|
// server/plugins/kv-cleanup.ts
|
|
79
148
|
import { disposeKVStores } from "@vite-hub/kv"
|
|
80
149
|
|
|
@@ -85,8 +154,10 @@ export default defineNitroPlugin((nitroApp) => {
|
|
|
85
154
|
|
|
86
155
|
## CLI
|
|
87
156
|
|
|
88
|
-
`
|
|
157
|
+
`hubKV()` contributes the `vitehub kv` CLI namespace: `list [--prefix] [--limit] [--cursor]`, `get <key>`, `has <key>`, `set <key> <value|@file> [--ttl <seconds>] [--json-value]`, and `delete <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.
|
|
158
|
+
|
|
159
|
+
`vitehub seed` writes each file in `server/seed/kv/` to the default store: `habits.json` is the JSON value of the key `habits`, and any other extension is a string.
|
|
89
160
|
|
|
90
|
-
Each command runs a `kv.*` operation of the app through the Console RPC
|
|
161
|
+
Each command runs a `kv.*` operation of the app through the Console RPC. 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.
|
|
91
162
|
|
|
92
163
|
Learn more at [vitehub.dev](https://vitehub.dev).
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Runs `run` for each item, at most `limit` at once, and keeps the input order. */
|
|
2
|
+
async function mapWithLimit(items, run, limit = 16) {
|
|
3
|
+
const results = Array.from({ length: items.length });
|
|
4
|
+
let next = 0;
|
|
5
|
+
async function worker() {
|
|
6
|
+
while (next < items.length) {
|
|
7
|
+
const index = next++;
|
|
8
|
+
results[index] = await run(items[index]);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
12
|
+
return results;
|
|
13
|
+
}
|
|
14
|
+
/** Splits `items` into arrays of at most `size` items. */
|
|
15
|
+
function chunks(items, size) {
|
|
16
|
+
const result = [];
|
|
17
|
+
for (let offset = 0; offset < items.length; offset += size) result.push(items.slice(offset, offset + size));
|
|
18
|
+
return result;
|
|
19
|
+
}
|
|
20
|
+
/** `getItems()` for a driver without a batch read: one `getItem()` per key, at most {@link kvBatchConcurrency} at once. */
|
|
21
|
+
function getItemsOneByOne(driver) {
|
|
22
|
+
return (items, commonOptions) => mapWithLimit(items, async (item) => ({
|
|
23
|
+
key: item.key,
|
|
24
|
+
value: await driver.getItem(item.key, {
|
|
25
|
+
...commonOptions,
|
|
26
|
+
...item.options
|
|
27
|
+
})
|
|
28
|
+
}));
|
|
29
|
+
}
|
|
30
|
+
/** `setItems()` for a driver without a batch write: one `setItem()` per entry, at most {@link kvBatchConcurrency} at once. */
|
|
31
|
+
function setItemsOneByOne(driver) {
|
|
32
|
+
return async (items, commonOptions) => {
|
|
33
|
+
await mapWithLimit(items, async (item) => driver.setItem?.(item.key, item.value, {
|
|
34
|
+
...commonOptions,
|
|
35
|
+
...item.options
|
|
36
|
+
}));
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
//#endregion
|
|
40
|
+
export { setItemsOneByOne as i, getItemsOneByOne as n, mapWithLimit as r, chunks as t };
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import "nostics";
|
|
2
|
+
//#region ../internal/src/host-credentials.d.ts
|
|
3
|
+
interface HostCliRunResult {
|
|
4
|
+
exitCode: number | null;
|
|
5
|
+
stdout: string;
|
|
6
|
+
}
|
|
7
|
+
/** Runs a host CLI with an argument array and no shell, and returns its stdout. */
|
|
8
|
+
type HostCliRun = (command: string, args: readonly string[], options: {
|
|
9
|
+
cwd?: string;
|
|
10
|
+
env: NodeJS.ProcessEnv;
|
|
11
|
+
signal?: AbortSignal;
|
|
12
|
+
}) => Promise<HostCliRunResult>;
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region ../internal/src/provision.d.ts
|
|
15
|
+
type ProvisionProvider = "cloudflare" | "vercel";
|
|
16
|
+
interface ProvisionLogger {
|
|
17
|
+
log: (message: string) => void;
|
|
18
|
+
warn: (message: string) => void;
|
|
19
|
+
}
|
|
20
|
+
interface ProvisionContext {
|
|
21
|
+
env: Record<string, string | undefined>;
|
|
22
|
+
fetch: typeof globalThis.fetch;
|
|
23
|
+
logger: ProvisionLogger;
|
|
24
|
+
markPlanUnchecked?: () => void;
|
|
25
|
+
}
|
|
26
|
+
interface ProvisionState {
|
|
27
|
+
cloudflare?: Record<string, Record<string, string>>;
|
|
28
|
+
vercel?: Record<string, Record<string, string>>;
|
|
29
|
+
}
|
|
30
|
+
interface ProvisionResult {
|
|
31
|
+
ids?: ProvisionState;
|
|
32
|
+
}
|
|
33
|
+
interface ProvisionAction {
|
|
34
|
+
kind: string;
|
|
35
|
+
name: string;
|
|
36
|
+
exists: boolean;
|
|
37
|
+
pending?: boolean;
|
|
38
|
+
/** Describes the change that `apply()` makes to an existing resource, for example `read replication: disabled -> auto`. */
|
|
39
|
+
update?: string;
|
|
40
|
+
apply: () => Promise<ProvisionResult>;
|
|
41
|
+
}
|
|
42
|
+
/** One Provision State category that a step records, with the keys that current Definitions use. */
|
|
43
|
+
interface ProvisionStateCategory {
|
|
44
|
+
category: string;
|
|
45
|
+
declared: readonly string[];
|
|
46
|
+
/** Provider resource identity for shared-resource checks. Return undefined when the recorded id lacks enough information. Defaults to the recorded id. */
|
|
47
|
+
resourceIdentity?: (entry: {
|
|
48
|
+
id: string;
|
|
49
|
+
key: string;
|
|
50
|
+
}) => string | undefined;
|
|
51
|
+
/** Identity expected by current config for a declared key. Omit when it cannot be established without provider access. */
|
|
52
|
+
declaredResourceIdentity?: (key: string) => string | undefined;
|
|
53
|
+
/** Tells a developer how to delete the resource of a recorded entry that no Definition declares. ViteHub never runs it. */
|
|
54
|
+
deleteHint: (entry: {
|
|
55
|
+
id: string;
|
|
56
|
+
key: string;
|
|
57
|
+
}) => string;
|
|
58
|
+
}
|
|
59
|
+
interface ProvisionStep {
|
|
60
|
+
id: string;
|
|
61
|
+
provider: ProvisionProvider;
|
|
62
|
+
plan: (context: ProvisionContext) => Promise<ProvisionAction[]>;
|
|
63
|
+
/** Describes the Provision State this step records. Runs without network access, also without credentials. */
|
|
64
|
+
recordedState?: (context: Pick<ProvisionContext, "env">) => ProvisionStateCategory[];
|
|
65
|
+
}
|
|
66
|
+
//#endregion
|
|
67
|
+
//#region ../internal/src/cli.d.ts
|
|
68
|
+
interface ViteHubCliStreams {
|
|
69
|
+
stderr: {
|
|
70
|
+
write: (chunk: string | Uint8Array, encoding?: BufferEncoding | StdoutWriteCallback, callback?: StdoutWriteCallback) => unknown;
|
|
71
|
+
};
|
|
72
|
+
stdout: {
|
|
73
|
+
write: (chunk: string | Uint8Array) => unknown;
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
interface ViteHubCliSpawnResult {
|
|
77
|
+
exitCode: number | null;
|
|
78
|
+
signal?: NodeJS.Signals | null;
|
|
79
|
+
/** The output of the child when `stdout` is `pipe`. */
|
|
80
|
+
stdout?: string;
|
|
81
|
+
}
|
|
82
|
+
interface ViteHubCliSpawnOptions {
|
|
83
|
+
cwd?: string;
|
|
84
|
+
env?: NodeJS.ProcessEnv;
|
|
85
|
+
stderr?: "inherit" | "pipe";
|
|
86
|
+
/** `ignore` gives the child no terminal input, so a tool that asks questions on a terminal does not ask. */
|
|
87
|
+
stdin?: "ignore" | "inherit";
|
|
88
|
+
/** `stderr` sends the child's stdout to the parent's stderr, so the parent's stdout keeps only its own output. */
|
|
89
|
+
stdout?: "inherit" | "pipe" | "stderr";
|
|
90
|
+
}
|
|
91
|
+
type ViteHubCliSpawn = (command: string, args: string[], options?: ViteHubCliSpawnOptions) => Promise<ViteHubCliSpawnResult>;
|
|
92
|
+
interface ViteHubCliContext extends ViteHubCliStreams {
|
|
93
|
+
cwd: string;
|
|
94
|
+
env: NodeJS.ProcessEnv;
|
|
95
|
+
/** Replaces `fetch` for commands that call a running app, so tests need no server. */
|
|
96
|
+
fetch?: typeof fetch;
|
|
97
|
+
/**
|
|
98
|
+
* Loads the project config for a build on `host` and returns the Provision Steps of its plugins, with the config root
|
|
99
|
+
* that holds `.vitehub/provision.json`. Setup commands, such as `vitehub deploy`, call it only when they need the
|
|
100
|
+
* steps, so they still run on a config that throws.
|
|
101
|
+
*/
|
|
102
|
+
loadProvision?: (host: ProvisionProvider) => Promise<ViteHubCliProvision>;
|
|
103
|
+
/** The deployed app's public origin from `vitehub({ publicUrl })`, when it is one string. */
|
|
104
|
+
publicUrl?: string;
|
|
105
|
+
rootDir: string;
|
|
106
|
+
/** Replaces the host CLI runner, such as for `wrangler auth token`, so tests need no real host CLI. */
|
|
107
|
+
runHostCli?: HostCliRun;
|
|
108
|
+
spawn: ViteHubCliSpawn;
|
|
109
|
+
}
|
|
110
|
+
interface ViteHubCliProvision {
|
|
111
|
+
rootDir: string;
|
|
112
|
+
steps: readonly ProvisionStep[];
|
|
113
|
+
}
|
|
114
|
+
interface ViteHubCliFeature {
|
|
115
|
+
description?: string;
|
|
116
|
+
name: string;
|
|
117
|
+
run: (args: string[], context: ViteHubCliContext) => Promise<number | void> | number | void;
|
|
118
|
+
usage?: string;
|
|
119
|
+
}
|
|
120
|
+
interface ViteHubCliCommandNamespace {
|
|
121
|
+
/** The feature that `vitehub <name>` runs when the next argument names no other feature. It gets every argument after `<name>`. */
|
|
122
|
+
defaultFeature?: string;
|
|
123
|
+
description?: string;
|
|
124
|
+
features: ViteHubCliFeature[];
|
|
125
|
+
name: string;
|
|
126
|
+
}
|
|
127
|
+
/** The flags of `vitehub seed` that every seed gets. */
|
|
128
|
+
interface ViteHubCliSeedOptions {
|
|
129
|
+
/** `--database <name>`: seed only this Database. Only the Database seed runs. */
|
|
130
|
+
database?: string;
|
|
131
|
+
/** The process environment with the env files of `--stage`. */
|
|
132
|
+
env: NodeJS.ProcessEnv;
|
|
133
|
+
/** `--remote`: write the deployed stores. Without it, a seed writes only local data. */
|
|
134
|
+
remote: boolean;
|
|
135
|
+
/** `--timeout <ms>` of each call to the app. */
|
|
136
|
+
timeout?: number;
|
|
137
|
+
/** The deployed app with `--remote`: `--url`, or `vitehub({ publicUrl })`. */
|
|
138
|
+
url?: string;
|
|
139
|
+
}
|
|
140
|
+
/** The seed files of one primitive, which `vitehub seed` writes. */
|
|
141
|
+
interface ViteHubCliSeed {
|
|
142
|
+
/** Where the seed files are, such as `server/seed/kv/`. `vitehub seed` names it when it finds no seed files. */
|
|
143
|
+
files: string;
|
|
144
|
+
/** The primitive, such as `database` or `kv`. `vitehub seed <name>` runs only this seed. */
|
|
145
|
+
name: string;
|
|
146
|
+
/** Writes the seed files and returns the exit code, or `undefined` when the project has no seed files for this primitive. */
|
|
147
|
+
run: (options: ViteHubCliSeedOptions, context: ViteHubCliContext) => Promise<number | undefined>;
|
|
148
|
+
}
|
|
149
|
+
interface ViteHubCliContributor {
|
|
150
|
+
namespaces: ViteHubCliCommandNamespace[];
|
|
151
|
+
provision?: ProvisionStep[];
|
|
152
|
+
/** The seed files that `vitehub seed` writes. */
|
|
153
|
+
seeds?: ViteHubCliSeed[];
|
|
154
|
+
/** The deployed app's public origin. Commands receive it as `context.publicUrl`. */
|
|
155
|
+
publicUrl?: string;
|
|
156
|
+
}
|
|
157
|
+
type ViteHubCliContributorFactory = () => ViteHubCliContributor | undefined | Promise<ViteHubCliContributor | undefined>;
|
|
158
|
+
interface ViteHubCliPluginMetadata {
|
|
159
|
+
cli?: ViteHubCliContributor | ViteHubCliContributorFactory;
|
|
160
|
+
}
|
|
161
|
+
type StdoutWriteCallback = (error?: Error | null) => void;
|
|
162
|
+
//#endregion
|
|
163
|
+
export { ViteHubCliStreams as i, ViteHubCliContributor as n, ViteHubCliPluginMetadata as r, ViteHubCliContext as t };
|
package/dist/cli.d.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import { i as ViteHubCliStreams, n as ViteHubCliContributor, t as ViteHubCliContext } from "./cli-
|
|
1
|
+
import { i as ViteHubCliStreams, n as ViteHubCliContributor, t as ViteHubCliContext } from "./cli-DpPhz_Ek.js";
|
|
2
2
|
//#region src/cli.d.ts
|
|
3
3
|
export type KVCliContext = Pick<ViteHubCliContext, "cwd" | "env" | "fetch" | "rootDir"> & ViteHubCliStreams;
|
|
4
4
|
export interface KVCliOptions {
|
|
5
|
-
/** Asks whether `
|
|
5
|
+
/** Asks whether `delete` may delete a key. Defaults to a prompt on a terminal, and refuses without one. */
|
|
6
6
|
confirm?: (question: string) => boolean | Promise<boolean>;
|
|
7
7
|
fetch?: typeof fetch;
|
|
8
|
+
/** The project root that holds `server/seed/kv/`. Defaults to the root of the CLI context. */
|
|
9
|
+
projectRoot?: () => string;
|
|
8
10
|
}
|
|
9
11
|
/**
|
|
10
12
|
* Runs one `vitehub kv` command against a running Vite + Nitro Development Server.
|