@vite-hub/queue 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 +41 -23
- package/dist/client-CIc3jsj2.js +114 -0
- package/dist/cloudflare-client-COzQ8fHk.js +147 -0
- package/dist/{cloudflare-resource-name-R8zYQiZb.js → cloudflare-resource-name-CCuLDvSP.js} +3 -2
- package/dist/{cloudflare-vite-BlQfDVZD.js → cloudflare-vite-BCuJOXcT.js} +23 -9
- package/dist/{cloudflare-vite-nFPor46-.d.ts → cloudflare-vite-CjdP5yBN.d.ts} +9 -4
- package/dist/config-BINujLv4.js +74 -0
- package/dist/enqueue-CnQ0QR3O.js +22 -0
- package/dist/error-diagnostics-A_8Kp-48.js +116 -0
- package/dist/error-diagnostics-qzRF6IVB.js +109 -0
- package/dist/errors-DIFaM9tW.js +42 -0
- package/dist/handler-response-CBwIkmTS.js +56 -0
- package/dist/index.d.ts +32 -70
- package/dist/index.js +9 -8
- package/dist/inspect-PeuckaC3.js +30 -0
- package/dist/internal/runtime/cloudflare-client.d.ts +3 -5
- package/dist/internal/runtime/cloudflare-client.js +1 -1
- package/dist/internal/runtime/cloudflare-vite.d.ts +1 -1
- package/dist/internal/runtime/cloudflare-vite.js +1 -1
- package/dist/internal/runtime/state.d.ts +16 -15
- package/dist/internal/runtime/state.js +2 -2
- package/dist/internal/runtime/vercel-client.d.ts +3 -5
- package/dist/internal/runtime/vercel-client.js +93 -62
- package/dist/nuxt.d.ts +27 -7
- package/dist/nuxt.js +6 -2
- package/dist/object-B1NW521B.js +7 -0
- package/dist/operations-Cnjbz8kk.js +63 -0
- package/dist/operations-tNUdj3G4.d.ts +212 -0
- package/dist/operations.d.ts +32 -0
- package/dist/operations.js +1195 -0
- package/dist/runtime/hosted.d.ts +4 -6
- package/dist/runtime/hosted.js +30 -8
- package/dist/state-G9s378-e.js +184 -0
- package/dist/{types-CwvoMATy.d.ts → types-1GRMYES1.d.ts} +35 -24
- package/dist/vercel-region-cjskrOKl.js +122 -0
- package/dist/vite-ChWLzOVu.js +1512 -0
- package/dist/vite.d.ts +334 -34
- package/dist/vite.js +2 -2
- package/package.json +68 -25
- package/dist/_app-D29AwUdD.d.ts +0 -11
- package/dist/app-BZpq2cwC.js +0 -10
- package/dist/client-DG9fweET.js +0 -93
- package/dist/cloudflare-client-w5vphoNn.js +0 -99
- package/dist/config-CNgAeIND.js +0 -53
- package/dist/delivery-error-glgYWC9g.js +0 -45
- package/dist/errors-CjuG_qr-.js +0 -108
- package/dist/internal/runtime/vercel-vite.d.ts +0 -20
- package/dist/internal/runtime/vercel-vite.js +0 -49
- package/dist/state-Cno9O7YS.js +0 -110
- package/dist/vercel-runtime-package-copy-CEToJtCu.js +0 -116
- package/dist/vite-DOuoen0w.js +0 -4414
package/README.md
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
# @vite-hub/queue
|
|
2
2
|
|
|
3
|
+
[](https://npmx.dev/package/@vite-hub/queue)
|
|
4
|
+
[](https://npmx.dev/package/@vite-hub/queue)
|
|
5
|
+
[](https://github.com/vite-hub/vitehub/blob/main/LICENSE)
|
|
6
|
+
[](https://vitehub.dev/docs)
|
|
7
|
+
|
|
3
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.
|
|
4
9
|
|
|
5
|
-
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/
|
|
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.
|
|
6
11
|
|
|
7
12
|
## Install the owner package
|
|
8
13
|
|
|
@@ -42,7 +47,9 @@ Enqueue it by its discovered name:
|
|
|
42
47
|
import { runQueue } from "@vite-hub/queue";
|
|
43
48
|
|
|
44
49
|
export async function enqueueWelcomeEmail(email: string) {
|
|
45
|
-
|
|
50
|
+
const [error, result] = await runQueue("welcome-email", { email });
|
|
51
|
+
if (error) throw error;
|
|
52
|
+
return result;
|
|
46
53
|
}
|
|
47
54
|
|
|
48
55
|
export default function handleRequest() {
|
|
@@ -50,23 +57,17 @@ export default function handleRequest() {
|
|
|
50
57
|
}
|
|
51
58
|
```
|
|
52
59
|
|
|
53
|
-
Register the
|
|
60
|
+
Register the Vite integration with the Nitro Vite plugin. Nitro is the only host output:
|
|
54
61
|
|
|
55
62
|
```ts
|
|
56
63
|
// vite.config.ts
|
|
57
|
-
import { resolve } from "node:path";
|
|
58
|
-
|
|
59
64
|
import { hubQueue } from "@vite-hub/queue/vite";
|
|
65
|
+
import { nitro } from "nitro/vite";
|
|
60
66
|
import { defineConfig } from "vite";
|
|
61
67
|
|
|
62
68
|
export default defineConfig({
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
input: resolve(import.meta.dirname, "src/server.ts"),
|
|
66
|
-
},
|
|
67
|
-
ssr: true,
|
|
68
|
-
},
|
|
69
|
-
plugins: [hubQueue({ provider: "cloudflare" })],
|
|
69
|
+
nitro: { preset: "cloudflare-module", serverEntry: "./src/server.ts" },
|
|
70
|
+
plugins: [hubQueue({ provider: "cloudflare" }), nitro()],
|
|
70
71
|
});
|
|
71
72
|
```
|
|
72
73
|
|
|
@@ -76,18 +77,18 @@ Run a production-shaped build:
|
|
|
76
77
|
pnpm vite build
|
|
77
78
|
```
|
|
78
79
|
|
|
79
|
-
A successful build writes `.vitehub/queue/registry.mjs` with the `welcome-email` definition.
|
|
80
|
+
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.
|
|
80
81
|
|
|
81
|
-
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 `{ 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.
|
|
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.
|
|
82
83
|
|
|
83
84
|
## Choose Cloudflare or Vercel
|
|
84
85
|
|
|
85
86
|
| Provider | Choose it when | Generated output | Enqueue options |
|
|
86
87
|
| ---------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | -------------------------------------------------------------- |
|
|
87
88
|
| Cloudflare | The deployed runtime supplies request-scoped Cloudflare Queue bindings | Worker bundle and `wrangler.json` producer and consumer entries | `contentType`, `delaySeconds` |
|
|
88
|
-
| Vercel | The deployment runs Vercel Queue callbacks and has a Queue region when the installed SDK requires one |
|
|
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` |
|
|
89
90
|
|
|
90
|
-
The ViteHub framework preset selects Cloudflare for `preset: "cloudflare"` and Vercel for `preset: "vercel"`. With the
|
|
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.
|
|
91
92
|
|
|
92
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`.
|
|
93
94
|
|
|
@@ -95,7 +96,7 @@ Vercel needs a generated topic and the `@vercel/queue` runtime. It rejects Cloud
|
|
|
95
96
|
|
|
96
97
|
## Treat acceptance and delivery separately
|
|
97
98
|
|
|
98
|
-
`runQueue()` waits for provider enqueue and returns this portable
|
|
99
|
+
`runQueue()` waits for provider enqueue and returns `[error, result]`. `result` is this portable value:
|
|
99
100
|
|
|
100
101
|
```ts
|
|
101
102
|
type QueueSendResult = {
|
|
@@ -104,22 +105,22 @@ type QueueSendResult = {
|
|
|
104
105
|
};
|
|
105
106
|
```
|
|
106
107
|
|
|
107
|
-
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/
|
|
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.
|
|
108
109
|
|
|
109
110
|
`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.
|
|
110
111
|
|
|
111
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.
|
|
112
113
|
|
|
113
|
-
On Cloudflare, successful handlers acknowledge the message. Failed handlers retry by default unless
|
|
114
|
+
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.
|
|
114
115
|
|
|
115
|
-
|
|
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.
|
|
116
117
|
|
|
117
118
|
## Public imports
|
|
118
119
|
|
|
119
120
|
| Import | Purpose |
|
|
120
121
|
| -------------------------------- | ----------------------------------------------------------------------------------- |
|
|
121
122
|
| `@vite-hub/queue` | Queue Definitions, enqueue helpers, direct clients, host adapters, and public types |
|
|
122
|
-
| `@vite-hub/queue/vite` | Vite discovery and Cloudflare or Vercel
|
|
123
|
+
| `@vite-hub/queue/vite` | Vite discovery and Cloudflare or Vercel Nitro configuration |
|
|
123
124
|
| `@vite-hub/queue/nuxt` | Nuxt module that composes Queue into Nitro |
|
|
124
125
|
| `@vite-hub/queue/runtime/hosted` | Advanced hosted Vercel callback adapter |
|
|
125
126
|
|
|
@@ -127,7 +128,24 @@ Queue operations use the shared `ViteHubError` contract. Public `code` and JSON-
|
|
|
127
128
|
|
|
128
129
|
## Go deeper
|
|
129
130
|
|
|
130
|
-
- [Queue guide](https://vitehub.dev/docs/
|
|
131
|
+
- [Queue guide](https://vitehub.dev/docs/queue)
|
|
131
132
|
- [Runtime and host support](https://vitehub.dev/docs/frameworks-hosts/support-matrix)
|
|
132
|
-
- [Definitions and discovery](https://vitehub.dev/docs/
|
|
133
|
+
- [Definitions and discovery](https://vitehub.dev/docs/development/definition-discovery)
|
|
133
134
|
- [Public import paths](https://vitehub.dev/docs/reference/import-paths)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
## Definition-owned dispatch types
|
|
138
|
+
|
|
139
|
+
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
|
+
|
|
141
|
+
```ts
|
|
142
|
+
const [error] = await runQueue("welcome-email", { email: "ada@example.com" }, { delaySeconds: 60 })
|
|
143
|
+
const queue = await getQueue("welcome-email")
|
|
144
|
+
const [sendError] = await queue.send({ email: "ada@example.com" })
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
`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
|
+
|
|
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.
|
|
150
|
+
|
|
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.
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { t as normalizeQueueOptions } from "./config-BINujLv4.js";
|
|
2
|
+
import { t as queueErrorDiagnostics } from "./error-diagnostics-qzRF6IVB.js";
|
|
3
|
+
import { i as normalizePublicQueueIdentifier, r as isQueueError } from "./errors-DIFaM9tW.js";
|
|
4
|
+
import { t as getCloudflareQueueBindingName } from "./cloudflare-GosJefIK.js";
|
|
5
|
+
import { t as getVercelQueueTopicName } from "./vercel-C_4vqxcl.js";
|
|
6
|
+
import { a as getQueueRuntimeEvent, h as resolveWaitUntil, i as getQueueRuntimeConfig, l as runWithQueueRuntimeEvent, m as getCloudflareEnv, n as getOrCreateQueueClient, r as getQueueRuntimeClientFactory, s as loadQueueDefinition } from "./state-G9s378-e.js";
|
|
7
|
+
import { t as resolveVercelQueueRegion } from "./vercel-region-cjskrOKl.js";
|
|
8
|
+
//#region src/runtime/client.ts
|
|
9
|
+
async function loadNamedQueueDefinition(name) {
|
|
10
|
+
try {
|
|
11
|
+
return await loadQueueDefinition(name);
|
|
12
|
+
} catch (cause) {
|
|
13
|
+
throw queueErrorDiagnostics.QUEUE_DEFINITION_LOAD_FAILED({
|
|
14
|
+
cause,
|
|
15
|
+
queue: normalizePublicQueueIdentifier(name)
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function resolveCloudflareBinding(binding, name) {
|
|
20
|
+
if (binding && typeof binding !== "string") return binding;
|
|
21
|
+
const bindingName = binding || getCloudflareQueueBindingName(name);
|
|
22
|
+
return getCloudflareEnv(getQueueRuntimeEvent())?.[bindingName] || bindingName;
|
|
23
|
+
}
|
|
24
|
+
function toProviderOptions(name, config) {
|
|
25
|
+
if (config.provider === "cloudflare") return {
|
|
26
|
+
...config,
|
|
27
|
+
binding: resolveCloudflareBinding(config.binding, name)
|
|
28
|
+
};
|
|
29
|
+
return {
|
|
30
|
+
...config,
|
|
31
|
+
topic: getVercelQueueTopicName(name)
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
function getActiveQueueConfig() {
|
|
35
|
+
const config = getQueueRuntimeConfig();
|
|
36
|
+
if (config === false) return false;
|
|
37
|
+
return config || normalizeQueueOptions(void 0, { hosting: "vercel" });
|
|
38
|
+
}
|
|
39
|
+
async function createNamedQueueClient(name) {
|
|
40
|
+
const config = getActiveQueueConfig();
|
|
41
|
+
if (config === false) throw queueErrorDiagnostics.QUEUE_DISABLED();
|
|
42
|
+
const provider = toProviderOptions(name, config);
|
|
43
|
+
const createClient = getQueueRuntimeClientFactory();
|
|
44
|
+
if (!createClient) throw queueErrorDiagnostics.QUEUE_RUNTIME_NOT_INSTALLED();
|
|
45
|
+
try {
|
|
46
|
+
return await createClient(provider);
|
|
47
|
+
} catch (cause) {
|
|
48
|
+
if (isQueueError(cause)) throw cause;
|
|
49
|
+
throw queueErrorDiagnostics.QUEUE_PROVIDER_FAILED({
|
|
50
|
+
cause,
|
|
51
|
+
operation: "create-client",
|
|
52
|
+
provider: provider.provider
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
async function getDynamicQueue(name) {
|
|
57
|
+
const definition = await loadNamedQueueDefinition(name);
|
|
58
|
+
if (!definition) throw queueErrorDiagnostics.QUEUE_DEFINITION_NOT_FOUND({ queue: normalizePublicQueueIdentifier(name) });
|
|
59
|
+
const config = getActiveQueueConfig();
|
|
60
|
+
if (definition.options?.cache === false || config === false || config.cache === false || config.provider === "cloudflare" || config.provider === "vercel" && resolveVercelQueueRegion(config.region).requestScoped) return await createNamedQueueClient(name);
|
|
61
|
+
return await getOrCreateQueueClient(name, () => createNamedQueueClient(name));
|
|
62
|
+
}
|
|
63
|
+
async function runDynamicQueue(name, payload, options) {
|
|
64
|
+
let queue;
|
|
65
|
+
try {
|
|
66
|
+
queue = await getDynamicQueue(name);
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (isQueueError(error, ["QUEUE_PROVIDER_FAILED"])) return [error, void 0];
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
return await queue.send(payload, options);
|
|
72
|
+
}
|
|
73
|
+
function deferDynamicQueue(name, payload, options) {
|
|
74
|
+
const request = getQueueRuntimeEvent();
|
|
75
|
+
const task = async () => {
|
|
76
|
+
const [error] = await runWithQueueRuntimeEvent(request, () => runDynamicQueue(name, payload, options));
|
|
77
|
+
if (error) throw error;
|
|
78
|
+
};
|
|
79
|
+
const handleError = async (error) => {
|
|
80
|
+
console.error(`[vitehub] Deferred queue dispatch failed for "${name}"`, error);
|
|
81
|
+
try {
|
|
82
|
+
await (await loadNamedQueueDefinition(name))?.options?.onDispatchError?.(error, { name });
|
|
83
|
+
} catch (hookError) {
|
|
84
|
+
console.error(`[vitehub] onDispatchError hook failed for "${name}"`, hookError);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
const promise = task().catch(handleError);
|
|
88
|
+
const waitUntil = resolveWaitUntil(request);
|
|
89
|
+
if (typeof waitUntil === "function") waitUntil(promise);
|
|
90
|
+
}
|
|
91
|
+
/** Dispatch externally supplied names and payloads after application validation. */
|
|
92
|
+
const dynamicQueue = {
|
|
93
|
+
defer: deferDynamicQueue,
|
|
94
|
+
get: getDynamicQueue,
|
|
95
|
+
run: runDynamicQueue
|
|
96
|
+
};
|
|
97
|
+
/**
|
|
98
|
+
* Returns the QueueClient of a discovered Queue Definition. Config errors, for example an unknown name, throw.
|
|
99
|
+
*/
|
|
100
|
+
async function getQueue(name) {
|
|
101
|
+
return await getDynamicQueue(name);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Enqueues one job and returns `[error, result]`. `error.code` is a `QueueErrorCode`.
|
|
105
|
+
* Config errors, for example an unknown Queue name, throw.
|
|
106
|
+
*/
|
|
107
|
+
function runQueue(name, payload, options) {
|
|
108
|
+
return runDynamicQueue(name, payload, options);
|
|
109
|
+
}
|
|
110
|
+
function deferQueue(name, payload, options) {
|
|
111
|
+
deferDynamicQueue(name, payload, options);
|
|
112
|
+
}
|
|
113
|
+
//#endregion
|
|
114
|
+
export { runQueue as i, dynamicQueue as n, getQueue as r, deferQueue as t };
|
|
@@ -0,0 +1,147 @@
|
|
|
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";
|
|
4
|
+
import { n as getCloudflareQueueDefinitionName } from "./cloudflare-GosJefIK.js";
|
|
5
|
+
import { n as isNonRetryableQueueError, r as reportQueueDeliveryError, t as checkQueueHandlerResponse } from "./handler-response-CBwIkmTS.js";
|
|
6
|
+
//#region src/providers/cloudflare.ts
|
|
7
|
+
const cloudflareBindingName = /^[A-Z_]\w{0,127}$/i;
|
|
8
|
+
function isCloudflareQueueBinding(binding) {
|
|
9
|
+
if (binding === null || typeof binding !== "object" || Array.isArray(binding)) return false;
|
|
10
|
+
const hasCallableMethod = (name) => {
|
|
11
|
+
let owner = binding;
|
|
12
|
+
while (owner && owner !== Object.prototype) {
|
|
13
|
+
let descriptor;
|
|
14
|
+
try {
|
|
15
|
+
descriptor = Object.getOwnPropertyDescriptor(owner, name);
|
|
16
|
+
} catch {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
if (descriptor) {
|
|
20
|
+
if (owner !== binding) {
|
|
21
|
+
const constructor = Object.getOwnPropertyDescriptor(owner, "constructor");
|
|
22
|
+
if (!constructor || !("value" in constructor) || typeof constructor.value !== "function" || constructor.value.prototype !== owner) return false;
|
|
23
|
+
}
|
|
24
|
+
if ("value" in descriptor) return typeof descriptor.value === "function";
|
|
25
|
+
try {
|
|
26
|
+
return typeof Reflect.get(binding, name) === "function";
|
|
27
|
+
} catch {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
owner = Object.getPrototypeOf(owner);
|
|
33
|
+
} catch {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return false;
|
|
38
|
+
};
|
|
39
|
+
return hasCallableMethod("send") && hasCallableMethod("sendBatch");
|
|
40
|
+
}
|
|
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];
|
|
47
|
+
return [void 0, {
|
|
48
|
+
contentType: options.contentType,
|
|
49
|
+
delaySeconds: options.delaySeconds
|
|
50
|
+
}];
|
|
51
|
+
}
|
|
52
|
+
function resolveAction(action, message, fallback) {
|
|
53
|
+
if (action && typeof action === "object" && !Array.isArray(action) && Object.hasOwn(action, "retry")) {
|
|
54
|
+
message.retry(action.retry);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if ((action === "ack" || action === "retry" ? action : fallback) === "ack") message.ack();
|
|
58
|
+
else message.retry();
|
|
59
|
+
}
|
|
60
|
+
function createCloudflareQueueBatchHandler(options) {
|
|
61
|
+
const requested = Number(options.concurrency ?? 1);
|
|
62
|
+
const concurrency = Number.isFinite(requested) ? Math.max(1, Math.floor(requested)) : 1;
|
|
63
|
+
return async (batch) => {
|
|
64
|
+
const messages = Array.isArray(batch?.messages) ? batch.messages : [];
|
|
65
|
+
if (!messages.length) return;
|
|
66
|
+
let index = 0;
|
|
67
|
+
const worker = async () => {
|
|
68
|
+
while (index < messages.length) {
|
|
69
|
+
const message = messages[index++];
|
|
70
|
+
try {
|
|
71
|
+
checkQueueHandlerResponse(await options.onMessage(message, batch));
|
|
72
|
+
message.ack();
|
|
73
|
+
} catch (error) {
|
|
74
|
+
const reportContext = {
|
|
75
|
+
attempts: message.attempts,
|
|
76
|
+
id: message.id,
|
|
77
|
+
provider: "cloudflare",
|
|
78
|
+
queue: getCloudflareQueueDefinitionName(batch.queue)
|
|
79
|
+
};
|
|
80
|
+
reportQueueDeliveryError(error, reportContext);
|
|
81
|
+
let action = void 0;
|
|
82
|
+
if (options.onError) try {
|
|
83
|
+
action = await options.onError(error, message, batch);
|
|
84
|
+
} catch (hookError) {
|
|
85
|
+
reportQueueDeliveryError(hookError, reportContext);
|
|
86
|
+
}
|
|
87
|
+
resolveAction(action, message, isNonRetryableQueueError(error) ? "ack" : "retry");
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, messages.length) }, () => worker()));
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function createCloudflareQueueClient(provider) {
|
|
95
|
+
if (typeof provider.binding === "undefined" || typeof provider.binding === "string") {
|
|
96
|
+
const binding = typeof provider.binding === "string" && cloudflareBindingName.test(provider.binding) ? provider.binding : void 0;
|
|
97
|
+
throw queueErrorDiagnostics.QUEUE_BINDING_NOT_FOUND({ binding });
|
|
98
|
+
}
|
|
99
|
+
if (!isCloudflareQueueBinding(provider.binding)) throw queueErrorDiagnostics.QUEUE_INVALID_BINDING();
|
|
100
|
+
const binding = provider.binding;
|
|
101
|
+
return {
|
|
102
|
+
provider: "cloudflare",
|
|
103
|
+
native: binding,
|
|
104
|
+
binding,
|
|
105
|
+
async send(payload, options) {
|
|
106
|
+
const normalized = normalizeQueueEnqueueInput(payload, options);
|
|
107
|
+
const [optionsError, sendOptions] = toSendOptions(normalized.options);
|
|
108
|
+
if (optionsError) return [optionsError, void 0];
|
|
109
|
+
const [error] = await queueProviderResult("cloudflare", "send", () => binding.send(normalized.payload, sendOptions));
|
|
110
|
+
if (error) return [error, void 0];
|
|
111
|
+
return [void 0, {
|
|
112
|
+
status: "queued",
|
|
113
|
+
messageId: normalized.id
|
|
114
|
+
}];
|
|
115
|
+
},
|
|
116
|
+
async sendBatch(items, options) {
|
|
117
|
+
const messages = [];
|
|
118
|
+
for (const item of items) {
|
|
119
|
+
const [optionsError, sendOptions] = toSendOptions({
|
|
120
|
+
...options,
|
|
121
|
+
contentType: item.contentType || options?.contentType,
|
|
122
|
+
delaySeconds: item.delaySeconds ?? options?.delaySeconds
|
|
123
|
+
});
|
|
124
|
+
if (optionsError) return [optionsError, void 0];
|
|
125
|
+
messages.push({
|
|
126
|
+
...item,
|
|
127
|
+
...sendOptions
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
const [error] = await queueProviderResult("cloudflare", "send-batch", () => binding.sendBatch(messages));
|
|
131
|
+
if (error) return [error, void 0];
|
|
132
|
+
return [void 0, messages.map(() => ({ status: "queued" }))];
|
|
133
|
+
},
|
|
134
|
+
createBatchHandler: createCloudflareQueueBatchHandler
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
//#endregion
|
|
138
|
+
//#region src/internal/runtime/cloudflare-client.ts
|
|
139
|
+
async function createCloudflareQueueRuntimeClient(options) {
|
|
140
|
+
if (options.provider !== "cloudflare") throw queueErrorDiagnostics.QUEUE_PROVIDER_MISMATCH({
|
|
141
|
+
expected: "cloudflare",
|
|
142
|
+
provider: options.provider
|
|
143
|
+
});
|
|
144
|
+
return createCloudflareQueueClient(options);
|
|
145
|
+
}
|
|
146
|
+
//#endregion
|
|
147
|
+
export { createCloudflareQueueBatchHandler as n, createCloudflareQueueRuntimeClient as t };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { t as queueErrorDiagnostics } from "./error-diagnostics-qzRF6IVB.js";
|
|
1
2
|
import { r as encodeNameHex } from "./cloudflare-GosJefIK.js";
|
|
2
3
|
//#region src/internal/cloudflare-resource-name.ts
|
|
3
4
|
const cloudflareQueueNamePrefix = "queue--";
|
|
@@ -8,7 +9,7 @@ const maxCloudflareQueueNameLength = 63;
|
|
|
8
9
|
const digestLength = 32;
|
|
9
10
|
function digestCloudflareQueueName(name, namePrefix) {
|
|
10
11
|
const crypto = globalThis.process?.getBuiltinModule("node:crypto");
|
|
11
|
-
if (!crypto) throw
|
|
12
|
+
if (!crypto) throw queueErrorDiagnostics.QUEUE_CRYPTO_UNAVAILABLE();
|
|
12
13
|
return crypto.hash("sha256", JSON.stringify([
|
|
13
14
|
"vitehub",
|
|
14
15
|
"cloudflare",
|
|
@@ -27,7 +28,7 @@ function createBoundedCloudflareQueueName(name, namePrefix) {
|
|
|
27
28
|
}
|
|
28
29
|
function getCloudflareQueueName(name, namePrefix = "") {
|
|
29
30
|
const queueName = `${namePrefix}${cloudflareQueueNamePrefix}${encodeNameHex(name)}`;
|
|
30
|
-
if (!cloudflareQueueNamePattern.test(queueName)) throw
|
|
31
|
+
if (!cloudflareQueueNamePattern.test(queueName)) throw queueErrorDiagnostics.QUEUE_INVALID_NAME({ name: queueName });
|
|
31
32
|
return queueName.length <= maxCloudflareQueueNameLength ? queueName : createBoundedCloudflareQueueName(name, namePrefix);
|
|
32
33
|
}
|
|
33
34
|
//#endregion
|
|
@@ -1,9 +1,19 @@
|
|
|
1
|
-
import { t as
|
|
1
|
+
import { t as internalErrorDiagnostics } from "./error-diagnostics-A_8Kp-48.js";
|
|
2
|
+
import { t as normalizeQueueOptions } from "./config-BINujLv4.js";
|
|
3
|
+
import { t as queueErrorDiagnostics } from "./error-diagnostics-qzRF6IVB.js";
|
|
2
4
|
import { n as getCloudflareQueueDefinitionName } from "./cloudflare-GosJefIK.js";
|
|
3
|
-
import { n as createCloudflareQueueBatchHandler, t as createCloudflareQueueRuntimeClient } from "./cloudflare-client-
|
|
4
|
-
import { t as getCloudflareQueueName } from "./cloudflare-resource-name-
|
|
5
|
-
import {
|
|
6
|
-
|
|
5
|
+
import { n as createCloudflareQueueBatchHandler, t as createCloudflareQueueRuntimeClient } from "./cloudflare-client-COzQ8fHk.js";
|
|
6
|
+
import { t as getCloudflareQueueName } from "./cloudflare-resource-name-CCuLDvSP.js";
|
|
7
|
+
import { f as setQueueRuntimeRegistry, g as runWithActiveCloudflareEnv, l as runWithQueueRuntimeEvent, p as createCloudflareRuntimeEvent, s as loadQueueDefinition, u as setQueueRuntimeConfig } from "./state-G9s378-e.js";
|
|
8
|
+
//#region ../internal/src/runtime/app.ts
|
|
9
|
+
function resolveAppFetch(label, app) {
|
|
10
|
+
if (!app) return;
|
|
11
|
+
if (typeof app === "function") return app;
|
|
12
|
+
if (typeof app.request === "function") return (request, context) => app.request(request, void 0, context);
|
|
13
|
+
if (typeof app.fetch === "function") return app.fetch.bind(app);
|
|
14
|
+
throw internalErrorDiagnostics.INTERNAL_R0011({ message: `Invalid ${label} app. Expected an h3 app or a fetch-compatible handler.` });
|
|
15
|
+
}
|
|
16
|
+
//#endregion
|
|
7
17
|
//#region ../internal/src/runtime/cloudflare-hosted.ts
|
|
8
18
|
function createWebRequestHandler(appHandler) {
|
|
9
19
|
return async (request, context) => await Promise.resolve(appHandler ? appHandler(request, context) : new Response(JSON.stringify({
|
|
@@ -47,7 +57,11 @@ function createRegistryDefinitionNames(registry, namePrefix) {
|
|
|
47
57
|
const definitions = {};
|
|
48
58
|
for (const name of Object.keys(registry)) {
|
|
49
59
|
const physicalName = getCloudflareQueueName(name, namePrefix);
|
|
50
|
-
if (definitions[physicalName]) throw
|
|
60
|
+
if (definitions[physicalName]) throw queueErrorDiagnostics.QUEUE_NAME_COLLISION({
|
|
61
|
+
first: definitions[physicalName],
|
|
62
|
+
resolved: physicalName,
|
|
63
|
+
second: name
|
|
64
|
+
});
|
|
51
65
|
definitions[physicalName] = name;
|
|
52
66
|
}
|
|
53
67
|
return definitions;
|
|
@@ -76,10 +90,10 @@ function createQueueCloudflareWorker(options = {}) {
|
|
|
76
90
|
if (queueConfig === false || queueConfig?.provider !== "cloudflare") return;
|
|
77
91
|
const runtimeEvent = createCloudflareRuntimeEvent(env, context);
|
|
78
92
|
await runWithActiveCloudflareEnv(env, async () => {
|
|
79
|
-
const definitionName = definitions ? definitions[batch.queue] : registryDefinitions?.[batch.queue] ?? (/-[0-9a-f]{32}$/.test(batch.queue) && !/(?:^|-)queue--(?:[0-9a-f]{2})+$/i.test(batch.queue) || queueConfig.namePrefix && !batch.queue.startsWith(queueConfig.namePrefix) ? void 0 : getCloudflareQueueDefinitionName(batch.queue, queueConfig.namePrefix));
|
|
80
|
-
if (!definitionName) throw
|
|
93
|
+
const definitionName = definitions ? Object.hasOwn(definitions, batch.queue) ? definitions[batch.queue] : void 0 : registryDefinitions?.[batch.queue] ?? (/-[0-9a-f]{32}$/.test(batch.queue) && !/(?:^|-)queue--(?:[0-9a-f]{2})+$/i.test(batch.queue) || queueConfig.namePrefix && !batch.queue.startsWith(queueConfig.namePrefix) ? void 0 : getCloudflareQueueDefinitionName(batch.queue, queueConfig.namePrefix));
|
|
94
|
+
if (!definitionName) throw queueErrorDiagnostics.QUEUE_DEFINITION_NOT_FOUND({ queue: batch.queue });
|
|
81
95
|
const definition = await loadQueueDefinition(definitionName);
|
|
82
|
-
if (!definition) throw
|
|
96
|
+
if (!definition) throw queueErrorDiagnostics.QUEUE_DEFINITION_NOT_FOUND({ queue: definitionName });
|
|
83
97
|
await createCloudflareQueueBatchHandler({
|
|
84
98
|
concurrency: definition.options?.concurrency,
|
|
85
99
|
onError: definition.options?.onError,
|
|
@@ -1,14 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as QueueApp } from "./_app-D29AwUdD.js";
|
|
3
|
-
|
|
1
|
+
import { C as ResolvedQueueOptions, a as CloudflareQueueMessageBatch, u as QueueDefinitionRegistry } from "./types-1GRMYES1.js";
|
|
4
2
|
//#region ../internal/src/runtime/cloudflare-env.d.ts
|
|
5
3
|
type CloudflareWorkerEnv = Record<string, unknown>;
|
|
6
4
|
interface CloudflareWorkerExecutionContext {
|
|
7
5
|
waitUntil?: (promise: Promise<unknown>) => void;
|
|
8
6
|
}
|
|
9
7
|
//#endregion
|
|
8
|
+
//#region ../internal/src/runtime/app.d.ts
|
|
9
|
+
type AppHandler = (request: Request, context?: Record<string, unknown>) => Response | Promise<Response>;
|
|
10
|
+
type VitehubApp = AppHandler | {
|
|
11
|
+
fetch?: AppHandler;
|
|
12
|
+
request?: (request: Request, options?: RequestInit, context?: Record<string, unknown>) => Response | Promise<Response>;
|
|
13
|
+
};
|
|
14
|
+
//#endregion
|
|
10
15
|
//#region src/internal/runtime/cloudflare-vite.d.ts
|
|
11
|
-
type CloudflareWorkerApp =
|
|
16
|
+
type CloudflareWorkerApp = VitehubApp;
|
|
12
17
|
interface QueueCloudflareWorkerOptions {
|
|
13
18
|
app?: CloudflareWorkerApp;
|
|
14
19
|
definitions?: Record<string, string>;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { t as isPlainObject } from "./object-B1NW521B.js";
|
|
2
|
+
import { t as queueErrorDiagnostics } from "./error-diagnostics-qzRF6IVB.js";
|
|
3
|
+
import { defu } from "defu";
|
|
4
|
+
function deploymentPresetFromNitro(value) {
|
|
5
|
+
const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
|
|
6
|
+
if (!normalized) return;
|
|
7
|
+
if (normalized.startsWith("cloudflare")) return "cloudflare";
|
|
8
|
+
if (normalized.startsWith("deno")) return "deno";
|
|
9
|
+
if (normalized.startsWith("netlify")) return "netlify";
|
|
10
|
+
if (normalized === "node" || normalized.startsWith("node-")) return "node";
|
|
11
|
+
if (normalized.startsWith("vercel")) return "vercel";
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region ../internal/src/hosting.ts
|
|
15
|
+
/**
|
|
16
|
+
* Returns the Nitro preset name that this build targets, as the developer wrote it.
|
|
17
|
+
* The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOSTING`.
|
|
18
|
+
* Empty values are skipped.
|
|
19
|
+
*/
|
|
20
|
+
function resolveHostPreset(input = {}) {
|
|
21
|
+
const env = input.env ?? (typeof process === "undefined" ? {} : process.env);
|
|
22
|
+
const nitroPreset = input.nitro && typeof input.nitro === "object" ? Reflect.get(input.nitro, "preset") : void 0;
|
|
23
|
+
for (const value of [
|
|
24
|
+
nitroPreset,
|
|
25
|
+
input.hosting,
|
|
26
|
+
env.NITRO_PRESET,
|
|
27
|
+
env.SERVER_PRESET,
|
|
28
|
+
env.VITEHUB_HOSTING
|
|
29
|
+
]) if (typeof value === "string" && value.trim()) return value.trim();
|
|
30
|
+
}
|
|
31
|
+
/** Returns the host that this build targets: `cloudflare`, `deno`, `netlify`, `node`, or `vercel`. */
|
|
32
|
+
function resolveHost(input = {}) {
|
|
33
|
+
return deploymentPresetFromNitro(resolveHostPreset(input));
|
|
34
|
+
}
|
|
35
|
+
function normalizeHosting(hosting) {
|
|
36
|
+
const normalized = hosting?.trim().toLowerCase().replaceAll("_", "-") || "";
|
|
37
|
+
if (normalized === "cloudflare") return "cloudflare-module";
|
|
38
|
+
return normalized;
|
|
39
|
+
}
|
|
40
|
+
/** Narrows a preset or host name to the hosts that have a native provider: Cloudflare, Netlify, or Vercel. */
|
|
41
|
+
function getHostingProvider(hosting) {
|
|
42
|
+
const preset = deploymentPresetFromNitro(hosting);
|
|
43
|
+
if (preset === "cloudflare" || preset === "netlify" || preset === "vercel") return preset;
|
|
44
|
+
}
|
|
45
|
+
//#endregion
|
|
46
|
+
//#region src/config.ts
|
|
47
|
+
const knownProviders = /* @__PURE__ */ new Set(["cloudflare", "vercel"]);
|
|
48
|
+
function readOwnOption(options, key) {
|
|
49
|
+
return Object.hasOwn(options, key) ? options[key] : void 0;
|
|
50
|
+
}
|
|
51
|
+
function resolveProvider(options, hosting) {
|
|
52
|
+
const cache = readOwnOption(options, "cache");
|
|
53
|
+
const shared = typeof cache === "boolean" ? { cache } : {};
|
|
54
|
+
const provider = readOwnOption(options, "provider");
|
|
55
|
+
if (typeof provider === "string" && !knownProviders.has(provider)) throw queueErrorDiagnostics.QUEUE_INVALID_PROVIDER({ provider });
|
|
56
|
+
if (typeof provider === "undefined" && hosting && !hosting.includes("cloudflare") && !hosting.includes("vercel")) throw queueErrorDiagnostics.QUEUE_MISSING_PROVIDER({ hosting });
|
|
57
|
+
if ((provider || (hosting.includes("cloudflare") ? "cloudflare" : "vercel")) === "cloudflare") {
|
|
58
|
+
const binding = readOwnOption(options, "binding");
|
|
59
|
+
const namePrefix = readOwnOption(options, "namePrefix");
|
|
60
|
+
return defu({
|
|
61
|
+
...typeof binding === "string" ? { binding } : {},
|
|
62
|
+
...typeof namePrefix === "string" ? { namePrefix } : {}
|
|
63
|
+
}, shared, { provider: "cloudflare" });
|
|
64
|
+
}
|
|
65
|
+
const region = readOwnOption(options, "region");
|
|
66
|
+
return defu(typeof region === "string" ? { region } : {}, shared, { provider: "vercel" });
|
|
67
|
+
}
|
|
68
|
+
function normalizeQueueOptions(options, input = {}) {
|
|
69
|
+
if (options === false) return void 0;
|
|
70
|
+
if (typeof options !== "undefined" && !isPlainObject(options)) throw queueErrorDiagnostics.QUEUE_INVALID_CONFIG();
|
|
71
|
+
return resolveProvider(options || {}, normalizeHosting(input.hosting));
|
|
72
|
+
}
|
|
73
|
+
//#endregion
|
|
74
|
+
export { resolveHostPreset as i, getHostingProvider as n, resolveHost as r, normalizeQueueOptions as t };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
//#region src/enqueue.ts
|
|
2
|
+
let fallbackCounter = 0;
|
|
3
|
+
function createQueueMessageId(prefix = "queue") {
|
|
4
|
+
const uuid = globalThis.crypto?.randomUUID?.();
|
|
5
|
+
if (uuid) return `${prefix}_${uuid}`;
|
|
6
|
+
fallbackCounter = fallbackCounter + 1 >>> 0;
|
|
7
|
+
return `${prefix}_${Date.now().toString(36)}_${fallbackCounter.toString(36)}`;
|
|
8
|
+
}
|
|
9
|
+
/** Payload properties never select enqueue options. */
|
|
10
|
+
function normalizeQueueEnqueueInput(payload, options = {}) {
|
|
11
|
+
const hasOwnId = Object.hasOwn(options, "id");
|
|
12
|
+
const providerOptions = { ...options };
|
|
13
|
+
const id = hasOwnId ? Object.hasOwn(providerOptions, "id") ? providerOptions.id : options.id : void 0;
|
|
14
|
+
delete providerOptions.id;
|
|
15
|
+
return {
|
|
16
|
+
id: typeof id === "string" && id.length > 0 ? id : createQueueMessageId(),
|
|
17
|
+
options: providerOptions,
|
|
18
|
+
payload
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
//#endregion
|
|
22
|
+
export { normalizeQueueEnqueueInput as n, createQueueMessageId as t };
|