@vite-hub/queue 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.
Files changed (60) hide show
  1. package/README.md +152 -29
  2. package/dist/client-B53_G4ky.js +182 -0
  3. package/dist/{cloudflare-client-COzQ8fHk.js → cloudflare-client-CoISDpIx.js} +28 -21
  4. package/dist/{cloudflare-resource-name-CCuLDvSP.js → cloudflare-resource-name-BIfBglC2.js} +1 -1
  5. package/dist/config-B2eaXaT5.js +105 -0
  6. package/dist/durability.d.ts +13 -0
  7. package/dist/durability.js +47 -0
  8. package/dist/duration-tujyhAKt.js +111 -0
  9. package/dist/error-diagnostics-CQ4BUqRe.js +270 -0
  10. package/dist/error-diagnostics-mJXBjmQx.js +181 -0
  11. package/dist/{handler-response-CBwIkmTS.js → handler-response-B6lz9nCn.js} +9 -4
  12. package/dist/index.d.ts +20 -32
  13. package/dist/index.js +39 -17
  14. package/dist/internal/runtime/cloudflare-client.d.ts +2 -2
  15. package/dist/internal/runtime/cloudflare-client.js +1 -1
  16. package/dist/internal/runtime/cloudflare-vite.d.ts +30 -2
  17. package/dist/internal/runtime/cloudflare-vite.js +111 -1
  18. package/dist/internal/runtime/local-client.d.ts +17 -0
  19. package/dist/internal/runtime/local-client.js +71 -0
  20. package/dist/internal/runtime/postgres-client.d.ts +46 -0
  21. package/dist/internal/runtime/postgres-client.js +570 -0
  22. package/dist/internal/runtime/state.d.ts +11 -4
  23. package/dist/internal/runtime/state.js +2 -2
  24. package/dist/internal/runtime/vercel-client.d.ts +2 -2
  25. package/dist/internal/runtime/vercel-client.js +66 -28
  26. package/dist/internal/runtime/worker-client.d.ts +6 -0
  27. package/dist/internal/runtime/worker-client.js +11 -0
  28. package/dist/invariant-D8_xBqmZ.js +22 -0
  29. package/dist/local-CUaWoRUx.d.ts +23 -0
  30. package/dist/local-Di0FrVUw.js +553 -0
  31. package/dist/object-D8pRdprI.js +15 -0
  32. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-nmRu_O3V.d.ts} +42 -15
  33. package/dist/operations-BVV-9Q0N.js +129 -0
  34. package/dist/operations.d.ts +47 -9
  35. package/dist/operations.js +186 -69
  36. package/dist/runtime/hosted.d.ts +3 -5
  37. package/dist/runtime/hosted.js +21 -45
  38. package/dist/{state-G9s378-e.js → state-DLqTqF6V.js} +59 -47
  39. package/dist/types-CiuSIPR0.d.ts +440 -0
  40. package/dist/types-Dsbb_Pvp.d.ts +10 -0
  41. package/dist/vercel-region-B95MAMXN.js +26 -0
  42. package/dist/virtual.d.ts +4 -0
  43. package/dist/vite.d.ts +366 -49
  44. package/dist/vite.js +2071 -2
  45. package/package.json +39 -46
  46. package/dist/client-CIc3jsj2.js +0 -114
  47. package/dist/cloudflare-vite-BCuJOXcT.js +0 -111
  48. package/dist/cloudflare-vite-CjdP5yBN.d.ts +0 -29
  49. package/dist/config-BINujLv4.js +0 -74
  50. package/dist/enqueue-CnQ0QR3O.js +0 -22
  51. package/dist/error-diagnostics-A_8Kp-48.js +0 -116
  52. package/dist/error-diagnostics-qzRF6IVB.js +0 -109
  53. package/dist/errors-DIFaM9tW.js +0 -42
  54. package/dist/nuxt.d.ts +0 -39
  55. package/dist/nuxt.js +0 -34
  56. package/dist/object-B1NW521B.js +0 -7
  57. package/dist/operations-Cnjbz8kk.js +0 -63
  58. package/dist/types-1GRMYES1.d.ts +0 -180
  59. package/dist/vercel-region-cjskrOKl.js +0 -122
  60. package/dist/vite-ChWLzOVu.js +0 -1512
package/README.md CHANGED
@@ -1,11 +1,11 @@
1
1
  # @vite-hub/queue
2
2
 
3
- [![npm version](https://comark-ui.onmax.me/badge.svg?source=npm-version&package=%40vite-hub%2Fqueue&icon=npm)](https://npmx.dev/package/@vite-hub/queue)
4
- [![npm downloads](https://comark-ui.onmax.me/badge.svg?source=npm-downloads&package=%40vite-hub%2Fqueue&period=month&icon=npm)](https://npmx.dev/package/@vite-hub/queue)
5
- [![license](https://comark-ui.onmax.me/badge.svg?label=license&value=Apache-2.0)](https://github.com/vite-hub/vitehub/blob/main/LICENSE)
6
- [![docs](https://comark-ui.onmax.me/badge.svg?label=docs&value=vitehub.dev)](https://vitehub.dev/docs)
3
+ [![npm version](https://img.shields.io/npm/v/@vite-hub/queue)](https://npmx.dev/package/@vite-hub/queue)
4
+ [![npm downloads](https://img.shields.io/npm/dm/@vite-hub/queue)](https://npmx.dev/package/@vite-hub/queue)
5
+ [![license](https://img.shields.io/static/v1?label=license&message=Apache-2.0&color=blue)](https://github.com/vite-hub/vitehub/blob/main/LICENSE)
6
+ [![docs](https://img.shields.io/static/v1?label=docs&message=vitehub.dev&color=blue)](https://vitehub.dev/docs)
7
7
 
8
- `@vite-hub/queue` discovers background job handlers during a Vite build and connects `runQueue()` to Cloudflare Queues or Vercel Queues. A successful enqueue means the provider accepted the job. It does not mean the handler finished.
8
+ `@vite-hub/queue` discovers background job handlers during a Vite build and connects `sendQueue()` to Cloudflare Queues, Vercel Queues, or a Node server that runs the jobs from Postgres or from local files. In `vite dev`, every app runs its jobs in the dev server, so you can test a handler without an account. A successful enqueue means the provider accepted the job. It does not mean the handler finished.
9
9
 
10
10
  Applications that already use the `vite-hub` framework distribution should enable Queue in `vitehub()` and import from `vite-hub/queue`. Install this owner package directly when you are building a custom composition, another framework integration, or package-level tooling. The [Queue guide](https://vitehub.dev/docs/queue) covers the framework-distribution setup.
11
11
 
@@ -16,18 +16,18 @@ pnpm add @vite-hub/queue
16
16
  pnpm add -D @vite-hub/cli vite
17
17
  ```
18
18
 
19
- The package requires Node 24 or newer. Vite is an optional peer dependency and is required for definition discovery and provider output. The ViteHub CLI provides the `vitehub provision` command used by the host guides.
19
+ The package requires Node.js 24.15 or newer. Vite is an optional peer dependency and is required for definition discovery and provider output. The ViteHub CLI provides the `vitehub provision` command used by the host guides.
20
20
 
21
21
  For Vercel Queues, also install the provider package and the ambient types used by generated functions:
22
22
 
23
23
  ```sh
24
- pnpm add @vercel/queue
24
+ pnpm add @vercel/queue @vercel/functions
25
25
  pnpm add -D @types/node @types/ws
26
26
  ```
27
27
 
28
28
  ## Build the first Queue Definition
29
29
 
30
- Queue has no in-memory provider for local delivery. The first credential-free result is a build that discovers a Queue Definition and emits provider configuration. This example selects Cloudflare explicitly.
30
+ The local provider runs Queue Definitions in a Node server without credentials. See [Run jobs on a Node server](#run-jobs-on-a-node-server). The example below selects Cloudflare explicitly, so its first result is a build that discovers a Queue Definition and emits provider configuration.
31
31
 
32
32
  Define the handler in a discoverable file:
33
33
 
@@ -35,8 +35,10 @@ Define the handler in a discoverable file:
35
35
  // src/welcome-email.queue.ts
36
36
  import { defineQueue } from "@vite-hub/queue";
37
37
 
38
- export default defineQueue<{ email: string }>(async ({ payload }) => {
39
- console.log(`Send welcome email to ${payload.email}`);
38
+ export default defineQueue<{ email: string }>({
39
+ handler: async ({ payload }) => {
40
+ console.log(`Send welcome email to ${payload.email}`);
41
+ },
40
42
  });
41
43
  ```
42
44
 
@@ -44,10 +46,10 @@ Enqueue it by its discovered name:
44
46
 
45
47
  ```ts
46
48
  // src/server.ts
47
- import { runQueue } from "@vite-hub/queue";
49
+ import { sendQueue } from "@vite-hub/queue";
48
50
 
49
51
  export async function enqueueWelcomeEmail(email: string) {
50
- const [error, result] = await runQueue("welcome-email", { email });
52
+ const [error, result] = await sendQueue("welcome-email", { email });
51
53
  if (error) throw error;
52
54
  return result;
53
55
  }
@@ -67,7 +69,7 @@ import { defineConfig } from "vite";
67
69
 
68
70
  export default defineConfig({
69
71
  nitro: { preset: "cloudflare-module", serverEntry: "./src/server.ts" },
70
- plugins: [hubQueue({ provider: "cloudflare" }), nitro()],
72
+ plugins: [hubQueue({ driver: "cloudflare" }), nitro()],
71
73
  });
72
74
  ```
73
75
 
@@ -79,24 +81,118 @@ pnpm vite build
79
81
 
80
82
  A successful build writes `.vitehub/queue/registry.mjs` with the `welcome-email` definition. Nitro writes the Worker and `.output/server/wrangler.json`. The Wrangler configuration contains one generated producer binding and one consumer for the Queue Definition.
81
83
 
82
- That build proves discovery and generated output only. `runQueue()` needs the generated runtime, a deployed Cloudflare binding, and an existing queue before it can return `[undefined, { status: "queued" }]`. Use the [Cloudflare host guide](https://vitehub.dev/docs/frameworks-hosts/cloudflare) for provisioning and deployment checks. Do not import `.vitehub` or `dist` files from application code.
84
+ That build proves discovery and generated output only. In the built Worker, `sendQueue()` needs a deployed Cloudflare binding and an existing queue before it can return `[undefined, { status: "queued" }]`. In `vite dev`, it needs neither: see [Run jobs in vite dev](#run-jobs-in-vite-dev). Use the [Cloudflare host guide](https://vitehub.dev/docs/frameworks-hosts/cloudflare) for provisioning and deployment checks. Do not import `.vitehub` or `dist` files from application code.
83
85
 
84
- ## Choose Cloudflare or Vercel
86
+ ## Choose a driver
85
87
 
86
88
  | Provider | Choose it when | Generated output | Enqueue options |
87
89
  | ---------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | -------------------------------------------------------------- |
88
- | Cloudflare | The deployed runtime supplies request-scoped Cloudflare Queue bindings | Worker bundle and `wrangler.json` producer and consumer entries | `contentType`, `delaySeconds` |
89
- | Vercel | The deployment runs Vercel Queue callbacks and has a Queue region when the installed SDK requires one | One Nitro route per Queue Definition, with a Vercel queue trigger | `delaySeconds`, `idempotencyKey`, `region`, `retentionSeconds` |
90
+ | Cloudflare | The deployed runtime supplies request-scoped Cloudflare Queue bindings | Worker bundle and `wrangler.json` producer and consumer entries | `contentType`, `delay` |
91
+ | Vercel | The deployment runs Vercel Queue callbacks and has a Queue region when the installed SDK requires one | One Nitro route per Queue Definition, with a Vercel queue trigger | `delay`, `idempotencyKey`, `region`, `retention` |
92
+ | Local | One Node server runs the jobs: `node .output/server/index.mjs`, Docker, or a WebContainer | A Nitro plugin that runs stored jobs in the server process | `delay`, `idempotencyKey` |
93
+ | Postgres | One or more Node servers share a Postgres database | A Nitro plugin that starts workers in each server process | `delay`, `idempotencyKey` |
90
94
 
91
- The ViteHub framework preset selects Cloudflare for `preset: "cloudflare"` and Vercel for `preset: "vercel"`. With the owner package, set `provider` explicitly when host inference would be ambiguous. Netlify cannot infer one. ViteHub provides no Queue Provider for local delivery, Deno, or self-hosted Node. Check the [runtime and host support matrix](https://vitehub.dev/docs/frameworks-hosts/support-matrix) before choosing a deployment target.
95
+ The ViteHub framework host selects Cloudflare for `host: "cloudflare"` and Vercel for `host: "vercel"`. For `host: "node"` and a Nitro `node-server` preset, it selects the postgres driver when the app has a Postgres Default Database, else the local driver. `vitehub({ queue: { driver: "postgres" } })` or `{ driver: "local" }` picks one on Node. Set `driver` explicitly when host inference would be ambiguous. Netlify cannot infer one. ViteHub provides no Queue driver for Deno. Check the [runtime and host support matrix](https://vitehub.dev/docs/frameworks-hosts/support-matrix) before choosing a deployment target.
92
96
 
93
- Cloudflare needs a concrete request-scoped binding at runtime. Its generated queue resources can be created through the ViteHub Cloudflare provision step when the required account credentials are present. Cloudflare rejects Vercel-only options such as `idempotencyKey`, `region`, and `retentionSeconds`.
97
+ Cloudflare needs a concrete request-scoped binding at runtime. Its generated queue resources can be created through the ViteHub Cloudflare provision step when the required account credentials are present. Cloudflare rejects Vercel-only options such as `idempotencyKey`, `region`, and `retention`.
94
98
 
95
99
  Vercel needs a generated topic and the `@vercel/queue` runtime. It rejects Cloudflare's `contentType` option. The [Vercel host guide](https://vitehub.dev/docs/frameworks-hosts/vercel) explains the generated Build Output boundary.
96
100
 
101
+ ## Run jobs on a Node server
102
+
103
+ The local provider stores each accepted job as a file in `.vitehub/data/queue`, next to the KV `fs-lite` store, and runs the Queue Definition in the same server process. `sendQueue()` returns after the file is written.
104
+
105
+ ```ts
106
+ // vite.config.ts
107
+ import { nitro } from "nitro/vite"
108
+ import { hubQueue } from "@vite-hub/queue/vite"
109
+ import { defineConfig } from "vite"
110
+
111
+ export default defineConfig({
112
+ nitro: { preset: "node-server", serverEntry: "./src/server.ts" },
113
+ plugins: [hubQueue(), nitro()],
114
+ })
115
+ ```
116
+
117
+ `hubQueue({ driver: "local", base: "data/queue" })` selects it explicitly and changes the directory.
118
+
119
+ Direct clients from `createQueueClient()` always redact plain handler errors. They cannot share a directory with the generated dev engine, which reports error details: that fails with `QUEUE_LOCAL_MODE_MISMATCH`. Use `useQueue()` in the dev server, or give the direct client a separate `base` directory.
120
+
121
+ When a production server reopens a dev store, it redacts stored errors without a code before it exposes the jobs. Queue errors and `ViteHubError` keep their code and message.
122
+
123
+ - A failed job runs again after 1, 2, and 4 seconds. After 4 attempts, or after a Queue error that a retry cannot fix, it becomes a dead job. A dead job stays in its file with the last error. The provider keeps the 100 newest dead jobs of each Queue Definition.
124
+ - The server writes the attempt count before the handler runs. A job whose handler was running when the process stopped runs again after the restart. If that was the fourth attempt, the job becomes a dead job instead.
125
+ - Delivery is at least once. A successful handler can run again after a restart if the process stops before completion is saved, or if both deleting the job and saving its completed state fail. Make handler side effects idempotent.
126
+ - `delay` survives a restart. `idempotencyKey` returns the message ID of a pending or running job with the same key. A dead job does not hold its key. `sendBatch()` stores all jobs or none.
127
+ - The jobs survive a restart on the same disk. Another host, a new container, or an ephemeral filesystem does not have them. Run one server process per directory: there is no lock between processes, so two processes can run the same job.
128
+ - `onError` and `callbackOptions` are Cloudflare and Vercel options. The local provider does not call them.
129
+
130
+ The server logs the directory and this durability once when it starts. `vitehub queue list` shows the provider, the directory, `durability: "single-host"`, the dead-job limit, and the pending, running, and dead jobs of each Queue Definition. In `vite dev`, it also shows `rules`, the provider of the build. `vitehub queue jobs list` shows each job.
131
+
132
+ ## Run jobs on several Node servers
133
+
134
+ The postgres driver keeps the jobs in the `vitehub_queue_jobs` table, and every server process of the app takes due jobs from it. Install `postgres` (postgres.js). The jobs use the postgres.js client of the Default Database, so they connect as the Database does, whatever variable or URL its Definition reads. `QUEUE_POSTGRES_URL` on the server overrides it. An explicit `driver: "postgres"` without a Postgres Default Database needs `QUEUE_POSTGRES_URL`.
135
+
136
+ ```ts
137
+ // vite.config.ts
138
+ import { hubQueue } from "@vite-hub/queue/vite"
139
+ import { nitro } from "nitro/vite"
140
+ import { defineConfig } from "vite"
141
+
142
+ export default defineConfig({
143
+ nitro: { preset: "node-server", serverEntry: "./src/server.ts" },
144
+ plugins: [hubQueue({ driver: "postgres" }), nitro()],
145
+ })
146
+ ```
147
+
148
+ - The first server creates the table and its indexes under `pg_advisory_xact_lock`, so servers that start at the same time do not race.
149
+ - Workers claim jobs with `UPDATE ... WHERE id IN (SELECT ... FOR UPDATE SKIP LOCKED)`. A send wakes the workers with `NOTIFY`. Without it, each worker checks every second.
150
+ - A claim holds a job for 30 seconds, and a running handler renews it. When a process stops during a handler, another instance runs the job again with the next attempt number after the claim ends.
151
+ - Retries, dead jobs, `delay`, `idempotencyKey`, `sendBatch()`, and `concurrency` follow the local rules above. `concurrency` applies per process.
152
+ - When Nitro closes, the workers stop taking jobs and wait up to 10 seconds for the running jobs.
153
+ - `vitehub queue list` shows the table and its database without the password, and `durability: "shared"`. `vitehub queue jobs` and the Console read the table, so any instance shows the jobs of all instances.
154
+ - `vite dev` runs the jobs of a postgres app with the local provider and the same rules, so development needs no Postgres.
155
+
156
+ ## Run jobs in vite dev
157
+
158
+ In `vite dev` and `nuxt dev`, `sendQueue()` stores the job in `.vitehub/data/queue` of the project and the dev server runs the Queue Definition, whatever the provider of the build. A Cloudflare or Vercel app needs no binding, credentials, or `wrangler dev`. The build output does not change: `vite build` still writes the Cloudflare or Vercel runtime.
159
+
160
+ The dev server follows the documented defaults of the provider of the build, so a handler fails and retries in dev as it does on the host:
161
+
162
+ | Rule | Cloudflare | Vercel | Local |
163
+ | --- | --- | --- | --- |
164
+ | Attempts | 4 (`max_retries` 3) | No limit until the job expires | 4 |
165
+ | Retry delay | None | 60 seconds (`retryAfterSeconds`) | 1, 2, then 4 seconds |
166
+ | Largest `delay` | `"24h"` (86400 seconds) | `"7d"` (604800 seconds) | No limit |
167
+ | Retention | None | `retention` from `"1m"` to `"7d"`, default `"1d"` | None |
168
+ | Largest payload | 128 KB of JSON | 100 MB of JSON | No limit |
169
+ | Largest `sendBatch()` | 100 jobs, 256 KB | 100 jobs | No limit |
170
+ | Rejected options | `idempotencyKey`, `region`, `retention` | `contentType` | `contentType`, `region`, `retention` |
171
+
172
+ The sources are the [Cloudflare Queues limits](https://developers.cloudflare.com/queues/platform/limits/), [Cloudflare batching and retries](https://developers.cloudflare.com/queues/configuration/batching-retries/), the [Vercel Queues concepts](https://vercel.com/docs/queues/concepts), and the [Vercel Queues limits](https://vercel.com/docs/queues/pricing#limits). A broken limit fails `sendQueue()` with `QUEUE_PROVIDER_FAILED`, and `error.cause` names the limit. A rejected option fails with `QUEUE_UNSUPPORTED_OPTION` and names the provider of the build.
173
+
174
+ Dev does not emulate these parts of the host:
175
+
176
+ - It delivers one job at a time per Queue Definition, up to `concurrency`. It has no Cloudflare batches, `max_batch_size`, or `max_batch_timeout`.
177
+ - It does not call `onError` or `callbackOptions`. A failed handler retries by the rules above, and a Queue error that a retry cannot fix makes the job dead at once.
178
+ - It keeps a dead job for inspection. Cloudflare deletes it, or moves it to a dead-letter queue, and Vercel deletes an expired job.
179
+ - The payload is a JSON copy. Cloudflare `contentType: "v8"` can send values that JSON cannot, such as a `Map`. The payload size is the JSON size, not the provider encoding.
180
+ - `idempotencyKey` deduplicates only while a job is pending or running. Vercel deduplicates for the retention, up to 24 hours. `useQueue()` returns the local client.
181
+
182
+ List, inspect, run again, and remove the stored jobs with the CLI. The commands call the `queue.jobs-list`, `queue.jobs-show`, `queue.jobs-retry`, and `queue.jobs-clear` operations of the running dev server, or of a deployed app with `--url`. The Console and agents run the same operations.
183
+
184
+ ```sh
185
+ pnpm vitehub queue jobs list --state dead
186
+ pnpm vitehub queue jobs show <message-id>
187
+ pnpm vitehub queue jobs retry <message-id>
188
+ pnpm vitehub queue jobs clear --state dead --yes
189
+ ```
190
+
191
+ `--json` prints JSON. `jobs list` takes `--queue` and `--state`. `jobs retry` runs the job now: a dead job gets a new set of attempts, and a delayed job does not wait. `jobs clear` removes pending and dead jobs, not running ones. It asks for confirmation on a terminal and needs `--yes` elsewhere. The handler of a successful job deletes it, so the list shows pending, running, and dead jobs. In `vite dev`, a plain `Error` from a handler shows its message and stack. A production server shows `Queue Delivery failed.` instead, because a message can hold private data; throw a `ViteHubError` to keep a code and message. The same commands work on a Node server with the local or postgres provider. Cloudflare and Vercel do not let the app read their queue, so the commands fail there with `QUEUE_JOBS_UNAVAILABLE`.
192
+
97
193
  ## Treat acceptance and delivery separately
98
194
 
99
- `runQueue()` waits for provider enqueue and returns `[error, result]`. `result` is this portable value:
195
+ `sendQueue()` waits for provider enqueue and returns `[error, result]`. `result` is this portable value:
100
196
 
101
197
  ```ts
102
198
  type QueueSendResult = {
@@ -105,23 +201,48 @@ type QueueSendResult = {
105
201
  };
106
202
  ```
107
203
 
108
- The optional message ID is provider-specific. Vercel returns the ID from its enqueue response. Cloudflare returns the input's `id`, generating one locally when omitted; it does not send that ID to Cloudflare, and the later delivery has a different Cloudflare message ID. In both cases, `status: "queued"` is the portable acceptance signal. Queue handlers run later and return no value to the producer. Use a [Workflow](https://vitehub.dev/docs/workflows) when the caller needs a tracked run, durable steps, waits, or progress.
204
+ ViteHub generates the message ID; an `id` option returns `QUEUE_UNSUPPORTED_OPTION`. Pass `idempotencyKey` to deduplicate sends on the local, postgres, and Vercel providers. When `send()` returns a `messageId`, the handler receives the same `id`. The local and postgres providers return the ID of the stored job, and Vercel returns the ID from its enqueue response. Cloudflare returns no `messageId`, because its binding does not report the ID that the delivery gets. In every case, `status: "queued"` is the portable acceptance signal. Queue handlers run later and return no value to the producer. Use a [Workflow](https://vitehub.dev/docs/workflows) when the caller needs a tracked run, durable steps, waits, or progress.
109
205
 
110
206
  `deferQueue()` does not wait for provider acceptance. It schedules enqueue work through the current request's `waitUntil`, logs dispatch failures, and calls the Queue Definition's `onDispatchError` hook when present.
111
207
 
112
- Providers can retry failed delivery, so handlers must tolerate another invocation after a partial side effect. ViteHub does not expose an exactly-once delivery guarantee. Vercel sends an idempotency key, using the generated message ID by default; pass a stable application key when repeated enqueue attempts should share one key. Cloudflare does not accept `idempotencyKey`, so protect non-repeatable side effects inside the handler.
208
+ Providers, the local one included, can retry failed delivery, so handlers must tolerate another invocation after a partial side effect. ViteHub does not expose an exactly-once delivery guarantee. Vercel sends an idempotency key, using the generated message ID by default; pass a stable application key when repeated enqueue attempts should share one key. Cloudflare does not accept `idempotencyKey`, so protect non-repeatable side effects inside the handler.
113
209
 
114
210
  On Cloudflare, successful handlers acknowledge the message. Failed handlers retry by default unless the error is a Queue error that a retry cannot fix or `onError` returns an explicit acknowledge or retry action. On Vercel, `callbackOptions.retry` can return an explicit directive; returning nothing preserves provider behavior. Application error codes do not choose retry policy.
115
211
 
116
- `runQueue()`, `dynamicQueue.run()`, `send()`, and `sendBatch()` return `[error, data]`. `error.code` is `QUEUE_PROVIDER_FAILED`, `QUEUE_PROVIDER_INVALID_RESPONSE`, or `QUEUE_UNSUPPORTED_OPTION`, and each error has `why`, `fix`, `docs`, and `cause`. Configuration errors, for example an unknown Queue name or a missing Cloudflare binding, throw. `JSON.stringify(error)` and Queue delivery reports omit `cause`, so keep credentials and provider responses there. Throw `ViteHubError` from a handler for an application code. See the [Queue error reference](https://vitehub.dev/docs/queue/limits-and-errors) for each code and the retry policy.
212
+ `sendQueue()`, `dynamicQueue.send()`, `send()`, and `sendBatch()` return `[error, data]`. `error.code` is `QUEUE_PROVIDER_FAILED`, `QUEUE_PROVIDER_INVALID_RESPONSE`, or `QUEUE_UNSUPPORTED_OPTION`, and each error has `why`, `fix`, `docs`, and `cause`. Configuration errors, for example an unknown Queue name or a missing Cloudflare binding, throw. `JSON.stringify(error)` and Queue delivery reports omit `cause`, so keep credentials and provider responses there. Throw `ViteHubError` from a handler for an application code. See the [Queue error reference](https://vitehub.dev/docs/queue/limits-and-errors) for each code and the retry policy.
213
+
214
+ ## Add a Queue from another plugin
215
+
216
+ A package can add a Queue Definition from its Vite plugin, so the app needs no file in `server/queues/`. Put the entry in `vitehub.queues`:
217
+
218
+ ```ts
219
+ import { fileURLToPath } from "node:url"
220
+
221
+ import type { Plugin } from "vite"
222
+ import type { QueueContributingPlugin } from "@vite-hub/queue/vite"
223
+
224
+ export function webhooks(): Plugin & QueueContributingPlugin {
225
+ return {
226
+ name: "@acme/webhooks",
227
+ vitehub: {
228
+ queues: [{
229
+ name: "acme-webhooks",
230
+ definition: { module: fileURLToPath(new URL("./deliver.js", import.meta.url)) },
231
+ reason: "Delivers webhooks after their delay.",
232
+ }],
233
+ },
234
+ }
235
+ }
236
+ ```
237
+
238
+ `definition.module` is an absolute path or `file:` URL of a module with `export default defineQueue(...)`. `vitehub.queues` can also be a function that gets `{ root, projectRoot, serverDirs }` and returns the list. Queue treats the entry like a discovered file: it goes in the registry and the generated types, and gets its Cloudflare binding, Vercel consumer route, provisioning, and inspection. `vitehub inspect` shows the plugin and the reason. A name that a file or another plugin also uses fails with `QUEUE_DEFINITION_DUPLICATE`, and an invalid entry fails with `QUEUE_CONTRIBUTION_INVALID`.
117
239
 
118
240
  ## Public imports
119
241
 
120
242
  | Import | Purpose |
121
243
  | -------------------------------- | ----------------------------------------------------------------------------------- |
122
244
  | `@vite-hub/queue` | Queue Definitions, enqueue helpers, direct clients, host adapters, and public types |
123
- | `@vite-hub/queue/vite` | Vite discovery and Cloudflare or Vercel Nitro configuration |
124
- | `@vite-hub/queue/nuxt` | Nuxt module that composes Queue into Nitro |
245
+ | `@vite-hub/queue/vite` | Vite discovery and Cloudflare, Vercel, local, or postgres Nitro configuration |
125
246
  | `@vite-hub/queue/runtime/hosted` | Advanced hosted Vercel callback adapter |
126
247
 
127
248
  `@vite-hub/queue/internal/*` exists for generated framework integration. Application code should not import it.
@@ -139,13 +260,15 @@ On Cloudflare, successful handlers acknowledge the message. Failed handlers retr
139
260
  The Vite Integration writes `.vitehub/queue.d.ts`. Include that file in your TypeScript project. The Nuxt Integration adds it to the generated type context. Names and payloads then come from the discovered Queue Definitions:
140
261
 
141
262
  ```ts
142
- const [error] = await runQueue("welcome-email", { email: "ada@example.com" }, { delaySeconds: 60 })
143
- const queue = await getQueue("welcome-email")
263
+ import { sendQueue, useQueue } from "@vite-hub/queue"
264
+
265
+ const [error] = await sendQueue("welcome-email", { email: "ada@example.com" }, { delay: "1m" })
266
+ const queue = await useQueue("welcome-email")
144
267
  const [sendError] = await queue.send({ email: "ada@example.com" })
145
268
  ```
146
269
 
147
270
  `QueueRegistry` is the generated definition map. `QueuePayload<"welcome-email">` extracts a payload type. A missing name or wrong payload is a type error. Run Vite configuration or the Nuxt prepare step after you add a definition. For a standalone TypeScript host, you can extend `QueueRegistry` with `typeof import("./welcome.queue").default`.
148
271
 
149
- Use `dynamicQueue.run(name, payload, options?)`, `dynamicQueue.defer()`, or `dynamicQueue.get()` for names read from external input. These methods check that the definition exists at runtime. They do not validate payload shape. Validate external data in your application. Direct provider clients from `createQueueClient()` also accept unknown payloads because they have no Queue Definition.
272
+ Use `dynamicQueue.send(name, payload, options?)`, `dynamicQueue.defer()`, or `dynamicQueue.use()` for names read from external input. These methods check that the definition exists at runtime. They do not validate payload shape. Validate external data in your application. Direct provider clients from `createQueueClient()` also accept unknown payloads because they have no Queue Definition.
150
273
 
151
- This is a breaking change: replace `runQueue(name, { payload, ...options })` with `runQueue(name, payload, options)`, and `client.send({ payload, ...options })` with `client.send(payload, options)`. There is no envelope detection. Existing envelope objects are delivered whole as payloads.
274
+ This is a breaking change: replace `sendQueue(name, { payload, ...options })` with `sendQueue(name, payload, options)`, and `client.send({ payload, ...options })` with `client.send(payload, options)`. There is no envelope detection. Existing envelope objects are delivered whole as payloads.
@@ -0,0 +1,182 @@
1
+ import { t as queueErrorDiagnostics } from "./error-diagnostics-mJXBjmQx.js";
2
+ import { a as normalizePublicQueueIdentifier, c as queueRemovedOptionsError, d as normalizeQueueEnqueueInput, l as queueUnsupportedOptionsError, r as isQueueError, t as readQueueTimes } from "./duration-tujyhAKt.js";
3
+ import { a as getQueueRuntimeEvent, c as loadQueueDefinition, g as resolveWaitUntil, i as getQueueRuntimeConfig, n as getOrCreateQueueClient, r as getQueueRuntimeClientFactory, u as runWithQueueRuntimeEvent, v as getCloudflareEnv } from "./state-DLqTqF6V.js";
4
+ import { n as normalizeQueueOptions } from "./config-B2eaXaT5.js";
5
+ import { t as resolveVercelQueueRegion } from "./vercel-region-B95MAMXN.js";
6
+ import { t as getCloudflareQueueBindingName } from "./cloudflare-GosJefIK.js";
7
+ import { t as getVercelQueueTopicName } from "./vercel-C_4vqxcl.js";
8
+ import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
9
+ //#region src/runtime/test-client.ts
10
+ /** The sent jobs of the current test. `vite-hub/test` reads the same list. */
11
+ function queueTestMessages(test) {
12
+ return test.backend("queue", () => []);
13
+ }
14
+ /** Records the job and does not run it, so a test asserts what the app sent. */
15
+ function recordQueueTestMessage(test, queue, input) {
16
+ const messages = queueTestMessages(test);
17
+ const duplicate = input.options.idempotencyKey === void 0 ? void 0 : messages.find((message) => message.queue === queue && message.options.idempotencyKey === input.options.idempotencyKey);
18
+ if (duplicate) return {
19
+ messageId: duplicate.id,
20
+ status: "queued"
21
+ };
22
+ messages.push({
23
+ id: input.id,
24
+ options: input.options,
25
+ payload: structuredClone(input.payload),
26
+ queue
27
+ });
28
+ return {
29
+ messageId: input.id,
30
+ status: "queued"
31
+ };
32
+ }
33
+ /** A Queue client that records every job in the test's list. */
34
+ function createTestQueueClient(test, queue, provider) {
35
+ return {
36
+ native: void 0,
37
+ provider: "local",
38
+ queue,
39
+ async send(payload, options) {
40
+ const input = normalizeQueueEnqueueInput(payload, options);
41
+ const error = queueUnsupportedOptionsError(input.options, provider) ?? readQueueTimes(input.options)[0];
42
+ if (error) return [error, void 0];
43
+ return [void 0, recordQueueTestMessage(test, queue, input)];
44
+ },
45
+ async sendBatch(items, options = {}) {
46
+ const removed = queueRemovedOptionsError(provider, options, items);
47
+ if (removed) return [removed, void 0];
48
+ const inputs = items.map(({ body, ...itemOptions }) => normalizeQueueEnqueueInput(body, {
49
+ ...options,
50
+ ...Object.fromEntries(Object.entries(itemOptions).filter(([, value]) => value !== void 0))
51
+ }));
52
+ for (const input of inputs) {
53
+ const error = queueUnsupportedOptionsError(input.options, provider) ?? readQueueTimes(input.options)[0];
54
+ if (error) return [error, void 0];
55
+ }
56
+ return [void 0, inputs.map((input) => recordQueueTestMessage(test, queue, input))];
57
+ }
58
+ };
59
+ }
60
+ //#endregion
61
+ //#region src/runtime/client.ts
62
+ async function loadNamedQueueDefinition(name) {
63
+ try {
64
+ return await loadQueueDefinition(name);
65
+ } catch (cause) {
66
+ throw queueErrorDiagnostics.QUEUE_DEFINITION_LOAD_FAILED({
67
+ cause,
68
+ queue: normalizePublicQueueIdentifier(name)
69
+ });
70
+ }
71
+ }
72
+ function resolveCloudflareBinding(binding, name) {
73
+ if (binding && typeof binding !== "string") return binding;
74
+ const bindingName = binding || getCloudflareQueueBindingName(name);
75
+ return getCloudflareEnv(getQueueRuntimeEvent())?.[bindingName] || bindingName;
76
+ }
77
+ function toDriverOptions(name, config) {
78
+ if (config.driver === "cloudflare") return {
79
+ ...config,
80
+ binding: resolveCloudflareBinding(config.binding, name)
81
+ };
82
+ if (config.driver === "local") return {
83
+ ...config,
84
+ queue: name
85
+ };
86
+ if (config.driver === "postgres") return {
87
+ ...config,
88
+ queue: name
89
+ };
90
+ return {
91
+ ...config,
92
+ topic: getVercelQueueTopicName(name)
93
+ };
94
+ }
95
+ function getActiveQueueConfig() {
96
+ const config = getQueueRuntimeConfig();
97
+ if (config === false) return false;
98
+ return config || normalizeQueueOptions(void 0, { hosting: "vercel" });
99
+ }
100
+ async function createNamedQueueClient(name) {
101
+ const config = getActiveQueueConfig();
102
+ if (config === false) throw queueErrorDiagnostics.QUEUE_DISABLED();
103
+ const driverOptions = toDriverOptions(name, config);
104
+ const createClient = getQueueRuntimeClientFactory();
105
+ if (!createClient) throw queueErrorDiagnostics.QUEUE_RUNTIME_NOT_INSTALLED();
106
+ try {
107
+ return await createClient(driverOptions);
108
+ } catch (cause) {
109
+ if (isQueueError(cause)) throw cause;
110
+ throw queueErrorDiagnostics.QUEUE_PROVIDER_FAILED({
111
+ cause,
112
+ operation: "create-client",
113
+ provider: driverOptions.driver
114
+ });
115
+ }
116
+ }
117
+ async function useDynamicQueue(name) {
118
+ const config = getActiveQueueConfig();
119
+ if (config === false) throw queueErrorDiagnostics.QUEUE_DISABLED();
120
+ const definition = await loadNamedQueueDefinition(name);
121
+ if (!definition) throw queueErrorDiagnostics.QUEUE_DEFINITION_NOT_FOUND({ queue: normalizePublicQueueIdentifier(name) });
122
+ const test = getViteHubTestMode();
123
+ if (test) return createTestQueueClient(test, name, config.driver === "local" ? config.rules ?? "local" : config.driver);
124
+ if (definition.cache === false || config.cache === false || config.driver === "cloudflare" || config.driver === "vercel" && resolveVercelQueueRegion(config.region).requestScoped) return await createNamedQueueClient(name);
125
+ return await getOrCreateQueueClient(name, () => createNamedQueueClient(name));
126
+ }
127
+ async function sendDynamicQueue(name, payload, options) {
128
+ let queue;
129
+ try {
130
+ queue = await useDynamicQueue(name);
131
+ } catch (error) {
132
+ if (isQueueError(error, ["QUEUE_PROVIDER_FAILED"])) return [error, void 0];
133
+ throw error;
134
+ }
135
+ return await queue.send(payload, options);
136
+ }
137
+ function deferDynamicQueue(name, payload, options) {
138
+ const request = getQueueRuntimeEvent();
139
+ const task = async () => {
140
+ const [error] = await runWithQueueRuntimeEvent(request, () => sendDynamicQueue(name, payload, options));
141
+ if (error) throw error;
142
+ };
143
+ const handleError = async (error) => {
144
+ console.error(`[vitehub] Deferred queue dispatch failed for "${name}"`, error);
145
+ try {
146
+ await (await loadNamedQueueDefinition(name))?.onDispatchError?.(error, { name });
147
+ } catch (hookError) {
148
+ console.error(`[vitehub] onDispatchError hook failed for "${name}"`, hookError);
149
+ }
150
+ };
151
+ const promise = task().catch(handleError);
152
+ const waitUntil = resolveWaitUntil(request);
153
+ if (typeof waitUntil === "function") waitUntil(promise);
154
+ }
155
+ /** Dispatch externally supplied names and payloads after application validation. */
156
+ const dynamicQueue = {
157
+ defer: deferDynamicQueue,
158
+ send: sendDynamicQueue,
159
+ use: useDynamicQueue
160
+ };
161
+ /**
162
+ * Returns the QueueClient of a discovered Queue Definition, for `sendBatch()` and provider methods. Config errors, for example an unknown name, throw.
163
+ */
164
+ async function useQueue(name) {
165
+ return await useDynamicQueue(name);
166
+ }
167
+ /**
168
+ * Sends one job to the Queue and returns `[error, result]`. `error.code` is a `QueueErrorCode`.
169
+ * Config errors, for example an unknown Queue name, throw.
170
+ */
171
+ function sendQueue(name, payload, options) {
172
+ return sendDynamicQueue(name, payload, options);
173
+ }
174
+ /**
175
+ * Sends one job after the response, through `waitUntil`. It returns nothing: a failure goes to the log and to the
176
+ * `onDispatchError` option of the Queue Definition. Call `sendQueue()` when the caller needs the message ID.
177
+ */
178
+ function deferQueue(name, payload, options) {
179
+ deferDynamicQueue(name, payload, options);
180
+ }
181
+ //#endregion
182
+ export { useQueue as i, dynamicQueue as n, sendQueue as r, deferQueue as t };
@@ -1,8 +1,8 @@
1
- import { t as queueErrorDiagnostics } from "./error-diagnostics-qzRF6IVB.js";
2
- import { n as normalizeQueueEnqueueInput } from "./enqueue-CnQ0QR3O.js";
3
- import { a as queueProviderResult, n as formatQueueOptionNames, t as cloudflareUnsupportedEnqueueOptions } from "./errors-DIFaM9tW.js";
1
+ import { t as queueErrorDiagnostics } from "./error-diagnostics-mJXBjmQx.js";
2
+ import { c as queueRemovedOptionsError, d as normalizeQueueEnqueueInput, l as queueUnsupportedOptionsError, s as queueProviderResult, t as readQueueTimes } from "./duration-tujyhAKt.js";
4
3
  import { n as getCloudflareQueueDefinitionName } from "./cloudflare-GosJefIK.js";
5
- import { n as isNonRetryableQueueError, r as reportQueueDeliveryError, t as checkQueueHandlerResponse } from "./handler-response-CBwIkmTS.js";
4
+ import { i as reportQueueDeliveryError, r as isNonRetryableQueueError, t as checkQueueHandlerResponse } from "./handler-response-B6lz9nCn.js";
5
+ import { parseDuration } from "@vite-hub/runtime";
6
6
  //#region src/providers/cloudflare.ts
7
7
  const cloudflareBindingName = /^[A-Z_]\w{0,127}$/i;
8
8
  function isCloudflareQueueBinding(binding) {
@@ -39,19 +39,22 @@ function isCloudflareQueueBinding(binding) {
39
39
  return hasCallableMethod("send") && hasCallableMethod("sendBatch");
40
40
  }
41
41
  function toSendOptions(options = {}) {
42
- const unsupported = cloudflareUnsupportedEnqueueOptions.filter((option) => options[option] !== void 0);
43
- if (unsupported.length) return [queueErrorDiagnostics.QUEUE_UNSUPPORTED_OPTION({
44
- options: formatQueueOptionNames(unsupported),
45
- provider: "cloudflare"
46
- }), void 0];
42
+ const error = queueUnsupportedOptionsError(options, "cloudflare");
43
+ if (error) return [error, void 0];
44
+ const [timeError, times] = readQueueTimes(options, "ceil");
45
+ if (timeError) return [timeError, void 0];
47
46
  return [void 0, {
48
47
  contentType: options.contentType,
49
- delaySeconds: options.delaySeconds
48
+ delaySeconds: times.delaySeconds
50
49
  }];
51
50
  }
51
+ /** Runs the action that `onError` returned. A `delay` that is not a duration throws, and the caller retries at once. */
52
52
  function resolveAction(action, message, fallback) {
53
53
  if (action && typeof action === "object" && !Array.isArray(action) && Object.hasOwn(action, "retry")) {
54
- message.retry(action.retry);
54
+ const removed = queueRemovedOptionsError("cloudflare", action.retry);
55
+ if (removed) throw removed;
56
+ const delay = action.retry?.delay;
57
+ message.retry(delay === void 0 ? void 0 : { delaySeconds: Math.ceil(parseDuration(delay, "delay", void 0, "s") / 1e3) });
55
58
  return;
56
59
  }
57
60
  if ((action === "ack" || action === "retry" ? action : fallback) === "ack") message.ack();
@@ -84,7 +87,12 @@ function createCloudflareQueueBatchHandler(options) {
84
87
  } catch (hookError) {
85
88
  reportQueueDeliveryError(hookError, reportContext);
86
89
  }
87
- resolveAction(action, message, isNonRetryableQueueError(error) ? "ack" : "retry");
90
+ try {
91
+ resolveAction(action, message, isNonRetryableQueueError(error) ? "ack" : "retry");
92
+ } catch (actionError) {
93
+ reportQueueDeliveryError(actionError, reportContext);
94
+ message.retry();
95
+ }
88
96
  }
89
97
  }
90
98
  };
@@ -108,22 +116,21 @@ function createCloudflareQueueClient(provider) {
108
116
  if (optionsError) return [optionsError, void 0];
109
117
  const [error] = await queueProviderResult("cloudflare", "send", () => binding.send(normalized.payload, sendOptions));
110
118
  if (error) return [error, void 0];
111
- return [void 0, {
112
- status: "queued",
113
- messageId: normalized.id
114
- }];
119
+ return [void 0, { status: "queued" }];
115
120
  },
116
121
  async sendBatch(items, options) {
122
+ const removed = queueRemovedOptionsError("cloudflare", options, items);
123
+ if (removed) return [removed, void 0];
117
124
  const messages = [];
118
125
  for (const item of items) {
119
126
  const [optionsError, sendOptions] = toSendOptions({
120
127
  ...options,
121
128
  contentType: item.contentType || options?.contentType,
122
- delaySeconds: item.delaySeconds ?? options?.delaySeconds
129
+ delay: item.delay ?? options?.delay
123
130
  });
124
131
  if (optionsError) return [optionsError, void 0];
125
132
  messages.push({
126
- ...item,
133
+ body: item.body,
127
134
  ...sendOptions
128
135
  });
129
136
  }
@@ -137,9 +144,9 @@ function createCloudflareQueueClient(provider) {
137
144
  //#endregion
138
145
  //#region src/internal/runtime/cloudflare-client.ts
139
146
  async function createCloudflareQueueRuntimeClient(options) {
140
- if (options.provider !== "cloudflare") throw queueErrorDiagnostics.QUEUE_PROVIDER_MISMATCH({
141
- expected: "cloudflare",
142
- provider: options.provider
147
+ if (options.driver !== "cloudflare") throw queueErrorDiagnostics.QUEUE_DRIVER_MISMATCH({
148
+ driver: options.driver,
149
+ expected: "cloudflare"
143
150
  });
144
151
  return createCloudflareQueueClient(options);
145
152
  }
@@ -1,4 +1,4 @@
1
- import { t as queueErrorDiagnostics } from "./error-diagnostics-qzRF6IVB.js";
1
+ import { t as queueErrorDiagnostics } from "./error-diagnostics-mJXBjmQx.js";
2
2
  import { r as encodeNameHex } from "./cloudflare-GosJefIK.js";
3
3
  //#region src/internal/cloudflare-resource-name.ts
4
4
  const cloudflareQueueNamePrefix = "queue--";