@vite-hub/queue 0.0.4 → 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.
Files changed (63) hide show
  1. package/README.md +170 -31
  2. package/dist/client-Cj50hQYp.js +180 -0
  3. package/dist/cloudflare-client-DYsAjM8B.js +140 -0
  4. package/dist/{cloudflare-resource-name-R8zYQiZb.js → cloudflare-resource-name-BJHYRCMQ.js} +3 -2
  5. package/dist/config-BcTDeQIP.js +105 -0
  6. package/dist/durability.d.ts +13 -0
  7. package/dist/durability.js +47 -0
  8. package/dist/error-diagnostics-BRartC1z.js +181 -0
  9. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  10. package/dist/errors-DL3pcNO4.js +77 -0
  11. package/dist/handler-response-By0Fpspv.js +61 -0
  12. package/dist/index.d.ts +29 -83
  13. package/dist/index.js +24 -11
  14. package/dist/inspect-PeuckaC3.js +30 -0
  15. package/dist/internal/runtime/cloudflare-client.d.ts +3 -5
  16. package/dist/internal/runtime/cloudflare-client.js +1 -1
  17. package/dist/internal/runtime/cloudflare-vite.d.ts +30 -2
  18. package/dist/internal/runtime/cloudflare-vite.js +111 -1
  19. package/dist/internal/runtime/local-client.d.ts +17 -0
  20. package/dist/internal/runtime/local-client.js +71 -0
  21. package/dist/internal/runtime/postgres-client.d.ts +46 -0
  22. package/dist/internal/runtime/postgres-client.js +560 -0
  23. package/dist/internal/runtime/state.d.ts +23 -15
  24. package/dist/internal/runtime/state.js +2 -2
  25. package/dist/internal/runtime/vercel-client.d.ts +3 -5
  26. package/dist/internal/runtime/vercel-client.js +120 -63
  27. package/dist/internal/runtime/worker-client.d.ts +6 -0
  28. package/dist/internal/runtime/worker-client.js +11 -0
  29. package/dist/invariant-D8_xBqmZ.js +22 -0
  30. package/dist/local-CGckW5nr.js +540 -0
  31. package/dist/local-CVVRVWeR.d.ts +22 -0
  32. package/dist/object-D8pRdprI.js +15 -0
  33. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  34. package/dist/operations-Crwjca91.js +124 -0
  35. package/dist/operations.d.ts +69 -0
  36. package/dist/operations.js +1344 -0
  37. package/dist/runtime/hosted.d.ts +5 -9
  38. package/dist/runtime/hosted.js +21 -23
  39. package/dist/state-mVA2X_wa.js +196 -0
  40. package/dist/types-BD-8U9zS.d.ts +420 -0
  41. package/dist/types-DS_rqu9l.d.ts +10 -0
  42. package/dist/vercel-region-D1CivgdA.js +26 -0
  43. package/dist/virtual.d.ts +4 -0
  44. package/dist/vite.d.ts +655 -40
  45. package/dist/vite.js +2071 -2
  46. package/package.json +66 -30
  47. package/dist/_app-D29AwUdD.d.ts +0 -11
  48. package/dist/app-BZpq2cwC.js +0 -10
  49. package/dist/client-DG9fweET.js +0 -93
  50. package/dist/cloudflare-client-w5vphoNn.js +0 -99
  51. package/dist/cloudflare-vite-BlQfDVZD.js +0 -97
  52. package/dist/cloudflare-vite-nFPor46-.d.ts +0 -24
  53. package/dist/config-CNgAeIND.js +0 -53
  54. package/dist/delivery-error-glgYWC9g.js +0 -45
  55. package/dist/errors-CjuG_qr-.js +0 -108
  56. package/dist/internal/runtime/vercel-vite.d.ts +0 -20
  57. package/dist/internal/runtime/vercel-vite.js +0 -49
  58. package/dist/nuxt.d.ts +0 -19
  59. package/dist/nuxt.js +0 -30
  60. package/dist/state-Cno9O7YS.js +0 -110
  61. package/dist/types-CwvoMATy.d.ts +0 -169
  62. package/dist/vercel-runtime-package-copy-CEToJtCu.js +0 -116
  63. package/dist/vite-DOuoen0w.js +0 -4414
@@ -0,0 +1,77 @@
1
+ import { t as queueErrorDiagnostics } from "./error-diagnostics-BRartC1z.js";
2
+ //#region src/enqueue.ts
3
+ let fallbackCounter = 0;
4
+ function createQueueMessageId(prefix = "queue") {
5
+ const uuid = globalThis.crypto?.randomUUID?.();
6
+ if (uuid) return `${prefix}_${uuid}`;
7
+ fallbackCounter = fallbackCounter + 1 >>> 0;
8
+ return `${prefix}_${Date.now().toString(36)}_${fallbackCounter.toString(36)}`;
9
+ }
10
+ /** Payload properties never select enqueue options. The message ID is always generated. */
11
+ function normalizeQueueEnqueueInput(payload, options = {}) {
12
+ return {
13
+ id: createQueueMessageId(),
14
+ options: { ...options },
15
+ payload
16
+ };
17
+ }
18
+ //#endregion
19
+ //#region src/errors.ts
20
+ const cloudflareUnsupportedEnqueueOptions = [
21
+ "idempotencyKey",
22
+ "region",
23
+ "retentionSeconds"
24
+ ];
25
+ const localUnsupportedEnqueueOptions = [
26
+ "contentType",
27
+ "region",
28
+ "retentionSeconds"
29
+ ];
30
+ const postgresUnsupportedEnqueueOptions = localUnsupportedEnqueueOptions;
31
+ const unsupportedEnqueueOptions = {
32
+ cloudflare: cloudflareUnsupportedEnqueueOptions,
33
+ local: localUnsupportedEnqueueOptions,
34
+ postgres: postgresUnsupportedEnqueueOptions,
35
+ vercel: ["contentType"]
36
+ };
37
+ /** Shared pre-dispatch option validation for provider clients and the test backend. */
38
+ function queueUnsupportedOptionsError(options, provider, names = unsupportedEnqueueOptions[provider]) {
39
+ const unsupported = [...Object.hasOwn(options, "id") ? ["id"] : [], ...names.filter((option) => options[option] !== void 0)];
40
+ return unsupported.length ? queueErrorDiagnostics.QUEUE_UNSUPPORTED_OPTION({
41
+ options: formatQueueOptionNames(unsupported),
42
+ provider
43
+ }) : void 0;
44
+ }
45
+ /** Returns `true` for an error from the Queue catalog. Pass `codes` to accept only some codes. */
46
+ function isQueueError(error, codes) {
47
+ return queueErrorDiagnostics.is(error) && (!codes || codes.some((code) => code === error.code));
48
+ }
49
+ /** Formats option names for an error `why`, for example `"region" and "retentionSeconds"`. */
50
+ function formatQueueOptionNames(names) {
51
+ const quoted = names.map((name) => `\`${name}\``);
52
+ return quoted.length > 1 ? `${quoted.slice(0, -1).join(", ")} and ${quoted.at(-1)}` : quoted.join("");
53
+ }
54
+ function normalizePublicQueueIdentifier(value) {
55
+ if (typeof value !== "string" || !value || value.length > 128 || value.trim() !== value) return;
56
+ if (!/^[a-z\d][a-z\d._/-]*$/i.test(value)) return;
57
+ if (/^[a-z][a-z\d+.-]*:\/\//i.test(value) || /^[a-z]:\//i.test(value)) return;
58
+ if (value.split("/").some((part) => part === "." || part === "..")) return;
59
+ return value;
60
+ }
61
+ /**
62
+ * Runs one provider call and returns `[error, data]`.
63
+ * Any failure becomes `QUEUE_PROVIDER_FAILED` with the failure in `cause`.
64
+ */
65
+ async function queueProviderResult(provider, operation, run) {
66
+ try {
67
+ return [void 0, await run()];
68
+ } catch (cause) {
69
+ return [queueErrorDiagnostics.QUEUE_PROVIDER_FAILED({
70
+ cause,
71
+ operation,
72
+ provider
73
+ }), void 0];
74
+ }
75
+ }
76
+ //#endregion
77
+ export { postgresUnsupportedEnqueueOptions as a, createQueueMessageId as c, normalizePublicQueueIdentifier as i, normalizeQueueEnqueueInput as l, isQueueError as n, queueProviderResult as o, localUnsupportedEnqueueOptions as r, queueUnsupportedOptionsError as s, cloudflareUnsupportedEnqueueOptions as t };
@@ -0,0 +1,61 @@
1
+ import { i as normalizePublicQueueIdentifier, n as isQueueError } from "./errors-DL3pcNO4.js";
2
+ import { getViteHubErrorShape, toResponse } from "@vite-hub/runtime";
3
+ //#region src/internal/delivery-error.ts
4
+ const retryableQueueCodes = /* @__PURE__ */ new Set(["QUEUE_PROVIDER_FAILED", "QUEUE_PROVIDER_INVALID_RESPONSE"]);
5
+ function isNonRetryableQueueError(error) {
6
+ return isQueueError(error) && !retryableQueueCodes.has(error.code);
7
+ }
8
+ function toReportError(error, development) {
9
+ if (isQueueError(error)) return {
10
+ code: error.code,
11
+ docs: error.docs,
12
+ fix: error.fix,
13
+ message: error.why,
14
+ name: error.name
15
+ };
16
+ const shape = getViteHubErrorShape(error);
17
+ if (shape) return {
18
+ code: shape.code,
19
+ details: shape.details,
20
+ message: shape.message,
21
+ name: "ViteHubError"
22
+ };
23
+ if (development && error instanceof Error) return {
24
+ message: error.message,
25
+ name: error.name,
26
+ ...error.stack ? { stack: error.stack } : {}
27
+ };
28
+ return {
29
+ message: "[vitehub] Queue Delivery failed.",
30
+ name: "Error"
31
+ };
32
+ }
33
+ function createQueueDeliveryErrorReport(error, context) {
34
+ const id = normalizePublicQueueIdentifier(context.id);
35
+ const queue = normalizePublicQueueIdentifier(context.queue);
36
+ return {
37
+ attempts: context.attempts,
38
+ provider: context.provider,
39
+ ...id ? { id } : {},
40
+ ...queue ? { queue } : {},
41
+ error: toReportError(error, context.development === true),
42
+ retryable: !isNonRetryableQueueError(error)
43
+ };
44
+ }
45
+ function reportQueueDeliveryError(error, context) {
46
+ console.error("[vitehub:queue] Queue Delivery failed.", createQueueDeliveryErrorReport(error, context));
47
+ }
48
+ //#endregion
49
+ //#region src/internal/handler-response.ts
50
+ /** Queue deliveries use the handler's status and discard its response body. */
51
+ function checkQueueHandlerResponse(value) {
52
+ const response = toResponse(value);
53
+ response.body?.cancel().catch(() => {});
54
+ if (!response.ok) {
55
+ const error = /* @__PURE__ */ new Error(`Queue handler returned HTTP ${response.status}`);
56
+ Object.assign(error, { status: response.status });
57
+ throw error;
58
+ }
59
+ }
60
+ //#endregion
61
+ export { reportQueueDeliveryError as i, createQueueDeliveryErrorReport as n, isNonRetryableQueueError as r, checkQueueHandlerResponse as t };
package/dist/index.d.ts CHANGED
@@ -1,91 +1,37 @@
1
- import { C as VercelQueueRetryHandler, S as VercelQueueRetryDirective, _ as QueueProviderOptions, a as DiscoveredQueueDefinition, b as VercelQueueCallbackOptions, c as QueueDefinitionOptions, d as QueueEnqueueOptions, f as QueueHandler, g as QueueProvider, h as QueueModuleProviderOptions, i as CloudflareQueueMessageBatch, l as QueueDefinitionRegistry, m as QueueModuleOptions, n as CloudflareQueueClient, o as QueueClient, p as QueueJob, r as CloudflareQueueMessage, s as QueueDefinition, t as CloudflareQueueBatchHandlerOptions, u as QueueEnqueueInput, v as QueueSendResult, w as VercelQueueSendResult, x as VercelQueueClient, y as ResolvedQueueOptions } from "./types-CwvoMATy.js";
2
- import { i as createQueueCloudflareWorker } from "./cloudflare-vite-nFPor46-.js";
3
- import { ViteHubError, ViteHubErrorDetails } from "@vite-hub/runtime";
4
-
5
- //#region src/config.d.ts
6
- interface QueueResolutionInput {
7
- hosting?: string;
8
- }
9
- declare function normalizeQueueOptions(options: QueueModuleOptions | undefined, input?: QueueResolutionInput): ResolvedQueueOptions | undefined;
10
- //#endregion
1
+ import { A as QueueModuleDriverOptions, B as VercelQueueClient, C as QueueDriver, D as QueueHandler, E as QueueErrorCode, F as QueueSendResult, G as VercelQueueSendBatchOptions, H as VercelQueueRetryDirective, I as ResolvedLocalQueueOptions, K as VercelQueueSendResult, L as ResolvedQueueOptions, M as QueueOptions, N as QueuePayload, O as QueueJob, P as QueueRegistry, R as VercelQueueBatchSendResult, S as QueueDefinitionRegistry, T as QueueEnqueueOptions, U as VercelQueueRetryHandler, V as VercelQueueErrorCode, W as VercelQueueSendBatchMessage, _ as PostgresQueueDriverOptions, a as CloudflareQueueMessageBatch, b as QueueDefinition, c as LocalQueueDriverOptions, f as LocalQueueRules, g as PostgresQueueClient, h as NodeQueueDriver, i as CloudflareQueueMessage, j as QueueName, k as QueueJobStore, l as LocalQueueErrorCode, n as CloudflareQueueClient, o as DiscoveredQueueDefinition, p as LocalQueueSendBatchMessage, r as CloudflareQueueErrorCode, s as LocalQueueClient, t as CloudflareQueueBatchHandlerOptions, v as PostgresQueueErrorCode, w as QueueDriverOptions, x as QueueDefinitionOptions, y as QueueClient, z as VercelQueueCallbackOptions } from "./types-BD-8U9zS.js";
2
+ import { Result } from "@vite-hub/runtime";
11
3
  //#region src/definition.d.ts
12
- declare function defineQueue<TPayload = unknown, TResult = unknown>(handler: QueueHandler<TPayload, TResult>, options?: QueueDefinitionOptions): QueueDefinition<TPayload, TResult>;
4
+ export declare function defineQueue<TPayload = unknown, TResult = unknown>(handler: QueueHandler<TPayload, TResult>, options?: QueueDefinitionOptions): QueueDefinition<TPayload, TResult>;
13
5
  //#endregion
14
6
  //#region src/enqueue.d.ts
15
- declare function createQueueMessageId(prefix?: string): string;
16
- //#endregion
17
- //#region src/errors.d.ts
18
- type QueueProviderOperation = "create-client" | "load-sdk" | "send" | "send-batch";
19
- declare const cloudflareUnsupportedEnqueueOptions: readonly ["idempotencyKey", "region", "retentionSeconds"];
20
- type QueueErrorCode = "CLOUDFLARE_BINDING_INVALID" | "CLOUDFLARE_BINDING_RESOLUTION_REQUIRED" | "CLOUDFLARE_UNSUPPORTED_ENQUEUE_OPTIONS" | "QUEUE_DEFINITION_LOAD_FAILED" | "QUEUE_DEFINITION_NOT_FOUND" | "QUEUE_DISABLED" | "QUEUE_PROVIDER_OPERATION_FAILED" | "QUEUE_PROVIDER_RESPONSE_INVALID" | "VERCEL_PROVIDER_EXPECTED" | "VERCEL_QUEUE_REGION_REQUIRED" | "VERCEL_QUEUE_SDK_INVALID" | "VERCEL_QUEUE_SDK_LOAD_FAILED" | "VERCEL_TOPIC_RESOLUTION_REQUIRED" | "VERCEL_UNSUPPORTED_ENQUEUE_OPTIONS";
21
- type QueueErrorDetailMap = {
22
- CLOUDFLARE_BINDING_INVALID: {
23
- readonly provider: "cloudflare";
24
- };
25
- CLOUDFLARE_BINDING_RESOLUTION_REQUIRED: {
26
- readonly provider: "cloudflare";
27
- };
28
- CLOUDFLARE_UNSUPPORTED_ENQUEUE_OPTIONS: {
29
- readonly provider: "cloudflare";
30
- readonly unsupported: readonly (typeof cloudflareUnsupportedEnqueueOptions)[number][];
31
- };
32
- QUEUE_DEFINITION_LOAD_FAILED: {
33
- readonly queue?: string;
34
- };
35
- QUEUE_DEFINITION_NOT_FOUND: {
36
- readonly queue?: string;
37
- };
38
- QUEUE_DISABLED: ViteHubErrorDetails;
39
- QUEUE_PROVIDER_OPERATION_FAILED: {
40
- readonly operation: Exclude<QueueProviderOperation, "load-sdk">;
41
- readonly provider: QueueProvider;
42
- };
43
- QUEUE_PROVIDER_RESPONSE_INVALID: {
44
- readonly operation: "send";
45
- readonly provider: "vercel";
46
- };
47
- VERCEL_PROVIDER_EXPECTED: {
48
- readonly provider: QueueProvider;
49
- };
50
- VERCEL_QUEUE_REGION_REQUIRED: {
51
- readonly provider: "vercel";
52
- };
53
- VERCEL_QUEUE_SDK_INVALID: {
54
- readonly provider: "vercel";
55
- };
56
- VERCEL_QUEUE_SDK_LOAD_FAILED: {
57
- readonly operation: "load-sdk";
58
- readonly provider: "vercel";
59
- };
60
- VERCEL_TOPIC_RESOLUTION_REQUIRED: {
61
- readonly provider: "vercel";
62
- };
63
- VERCEL_UNSUPPORTED_ENQUEUE_OPTIONS: {
64
- readonly provider: "vercel";
65
- readonly unsupported: readonly "contentType"[];
66
- };
67
- };
68
- type QueueErrorDetails<TCode extends QueueErrorCode = QueueErrorCode> = QueueErrorDetailMap[TCode];
69
- //#endregion
70
- //#region src/providers/cloudflare.d.ts
71
- declare function createCloudflareQueueBatchHandler<TPayload = unknown>(options: CloudflareQueueBatchHandlerOptions<TPayload>): (batch: CloudflareQueueMessageBatch<TPayload>) => Promise<void>;
72
- //#endregion
73
- //#region src/integrations/cloudflare.d.ts
74
- declare function getCloudflareQueueBindingName(name: string): string;
75
- declare function getCloudflareQueueDefinitionName(name: string, namePrefix?: string): string;
76
- //#endregion
77
- //#region src/internal/cloudflare-resource-name.d.ts
78
- declare function getCloudflareQueueName(name: string, namePrefix?: string): string;
79
- //#endregion
80
- //#region src/integrations/vercel.d.ts
81
- declare function getVercelQueueTopicName(name: string): string;
7
+ export declare function createQueueMessageId(prefix?: string): string;
82
8
  //#endregion
83
9
  //#region src/runtime/client.d.ts
84
- declare function getQueue(name: string): Promise<QueueClient>;
85
- declare function runQueue<TPayload = unknown>(name: string, input: QueueEnqueueInput<TPayload>): Promise<QueueSendResult>;
86
- declare function deferQueue<TPayload = unknown>(name: string, input: QueueEnqueueInput<TPayload>): void;
10
+ declare function useDynamicQueue(name: string): Promise<QueueClient>;
11
+ declare function sendDynamicQueue(name: string, payload: unknown, options?: QueueEnqueueOptions): Promise<Result<QueueSendResult, QueueErrorCode>>;
12
+ declare function deferDynamicQueue(name: string, payload: unknown, options?: QueueEnqueueOptions): void;
13
+ /** Dispatch externally supplied names and payloads after application validation. */
14
+ export declare const dynamicQueue: {
15
+ defer: typeof deferDynamicQueue;
16
+ send: typeof sendDynamicQueue;
17
+ use: typeof useDynamicQueue;
18
+ };
19
+ /**
20
+ * Returns the QueueClient of a discovered Queue Definition, for `sendBatch()` and provider methods. Config errors, for example an unknown name, throw.
21
+ */
22
+ export declare function useQueue<TName extends QueueName>(name: TName): Promise<QueueClient<QueueDriver, QueuePayload<TName>>>;
23
+ /**
24
+ * Sends one job to the Queue and returns `[error, result]`. `error.code` is a `QueueErrorCode`.
25
+ * Config errors, for example an unknown Queue name, throw.
26
+ */
27
+ export declare function sendQueue<TName extends QueueName>(name: TName, payload: NoInfer<QueuePayload<TName>>, options?: QueueEnqueueOptions): Promise<Result<QueueSendResult, QueueErrorCode>>;
28
+ /**
29
+ * Sends one job after the response, through `waitUntil`. It returns nothing: a failure goes to the log and to the
30
+ * `onDispatchError` option of the Queue Definition. Call `sendQueue()` when the caller needs the message ID.
31
+ */
32
+ export declare function deferQueue<TName extends QueueName>(name: TName, payload: NoInfer<QueuePayload<TName>>, options?: QueueEnqueueOptions): void;
87
33
  //#endregion
88
34
  //#region src/runtime/create-client.d.ts
89
- declare function createQueueClient(options: QueueProviderOptions): Promise<QueueClient>;
35
+ export declare function createQueueClient(options: QueueDriverOptions): Promise<QueueClient>;
90
36
  //#endregion
91
- export { type CloudflareQueueBatchHandlerOptions, type CloudflareQueueClient, type CloudflareQueueMessage, type CloudflareQueueMessageBatch, type DiscoveredQueueDefinition, type QueueClient, type QueueDefinition, type QueueDefinitionOptions, type QueueDefinitionRegistry, type QueueEnqueueInput, type QueueEnqueueOptions, type QueueErrorCode, type QueueErrorDetails, type QueueHandler, type QueueJob, type QueueModuleOptions, type QueueModuleProviderOptions, type QueueProvider, type QueueProviderOperation, type QueueProviderOptions, type QueueSendResult, type ResolvedQueueOptions, type VercelQueueCallbackOptions, type VercelQueueClient, type VercelQueueRetryDirective, type VercelQueueRetryHandler, type VercelQueueSendResult, createCloudflareQueueBatchHandler, createQueueClient, createQueueCloudflareWorker, createQueueMessageId, deferQueue, defineQueue, getCloudflareQueueBindingName, getCloudflareQueueDefinitionName, getCloudflareQueueName, getQueue, getVercelQueueTopicName, normalizeQueueOptions, runQueue };
37
+ export type { CloudflareQueueBatchHandlerOptions, CloudflareQueueClient, CloudflareQueueErrorCode, CloudflareQueueMessage, CloudflareQueueMessageBatch, DiscoveredQueueDefinition, LocalQueueClient, LocalQueueDriverOptions, LocalQueueErrorCode, LocalQueueRules, LocalQueueSendBatchMessage, NodeQueueDriver, PostgresQueueClient, PostgresQueueDriverOptions, PostgresQueueErrorCode, QueueClient, QueueDefinition, QueueDefinitionOptions, QueueDefinitionRegistry, QueueDriver, QueueDriverOptions, QueueEnqueueOptions, QueueErrorCode, QueueHandler, QueueJob, QueueJobStore, QueueModuleDriverOptions, QueueName, QueueOptions, QueuePayload, QueueRegistry, QueueSendResult, ResolvedLocalQueueOptions, ResolvedQueueOptions, VercelQueueBatchSendResult, VercelQueueCallbackOptions, VercelQueueClient, VercelQueueErrorCode, VercelQueueRetryDirective, VercelQueueRetryHandler, VercelQueueSendBatchMessage, VercelQueueSendBatchOptions, VercelQueueSendResult };
package/dist/index.js CHANGED
@@ -1,14 +1,9 @@
1
- import { t as normalizeQueueOptions } from "./config-CNgAeIND.js";
2
- import { c as createQueueMessageId } from "./errors-CjuG_qr-.js";
3
- import { n as getCloudflareQueueDefinitionName, t as getCloudflareQueueBindingName } from "./cloudflare-GosJefIK.js";
4
- import { n as createCloudflareQueueBatchHandler } from "./cloudflare-client-w5vphoNn.js";
5
- import { t as getCloudflareQueueName } from "./cloudflare-resource-name-R8zYQiZb.js";
6
- import { t as getVercelQueueTopicName } from "./vercel-C_4vqxcl.js";
7
- import { n as getQueue, r as runQueue, t as deferQueue } from "./client-DG9fweET.js";
8
- import { t as createQueueCloudflareWorker } from "./cloudflare-vite-BlQfDVZD.js";
1
+ import { t as queueErrorDiagnostics } from "./error-diagnostics-BRartC1z.js";
2
+ import { c as createQueueMessageId } from "./errors-DL3pcNO4.js";
3
+ import { i as useQueue, n as dynamicQueue, r as sendQueue, t as deferQueue } from "./client-Cj50hQYp.js";
9
4
  //#region src/definition.ts
10
5
  function defineQueue(handler, options) {
11
- if (typeof handler !== "function") throw new TypeError("`defineQueue()` requires a queue handler.");
6
+ if (typeof handler !== "function") throw queueErrorDiagnostics.QUEUE_INVALID_DEFINITION();
12
7
  return {
13
8
  handler,
14
9
  options
@@ -17,12 +12,30 @@ function defineQueue(handler, options) {
17
12
  //#endregion
18
13
  //#region src/runtime/create-client.ts
19
14
  async function createQueueClient(options) {
20
- if (options.provider === "cloudflare") {
15
+ if (options.driver === void 0 && Object.hasOwn(options, "provider")) {
16
+ const provider = options.provider;
17
+ throw queueErrorDiagnostics.QUEUE_RENAMED_PROVIDER_KEY({ value: JSON.stringify(provider) ?? String(provider) });
18
+ }
19
+ if (options.driver === "cloudflare") {
21
20
  const { createCloudflareQueueRuntimeClient } = await import("./internal/runtime/cloudflare-client.js");
22
21
  return await createCloudflareQueueRuntimeClient(options);
23
22
  }
23
+ if (options.driver === "local") {
24
+ const { createLocalQueueRuntimeClient } = await import("./internal/runtime/local-client.js");
25
+ return await createLocalQueueRuntimeClient({
26
+ base: options.base,
27
+ cache: options.cache,
28
+ driver: options.driver,
29
+ queue: options.queue,
30
+ rules: options.rules
31
+ });
32
+ }
33
+ if (options.driver === "postgres") {
34
+ const { createPostgresQueueRuntimeClient } = await import("#vitehub/queue/node-client");
35
+ return await createPostgresQueueRuntimeClient(options);
36
+ }
24
37
  const { createVercelQueueRuntimeClient } = await import("./internal/runtime/vercel-client.js");
25
38
  return await createVercelQueueRuntimeClient(options);
26
39
  }
27
40
  //#endregion
28
- export { createCloudflareQueueBatchHandler, createQueueClient, createQueueCloudflareWorker, createQueueMessageId, deferQueue, defineQueue, getCloudflareQueueBindingName, getCloudflareQueueDefinitionName, getCloudflareQueueName, getQueue, getVercelQueueTopicName, normalizeQueueOptions, runQueue };
41
+ export { createQueueClient, createQueueMessageId, deferQueue, defineQueue, dynamicQueue, sendQueue, useQueue };
@@ -0,0 +1,30 @@
1
+ import { relative } from "pathe";
2
+ //#region ../internal/src/inspect.ts
3
+ function relativeDefinitionFile(projectRoot, file) {
4
+ return relative(projectRoot, file).replaceAll("\\", "/");
5
+ }
6
+ /** Summarizes Definitions that have no owner-specific fields. */
7
+ function summarizeDefinitions(projectRoot, definitions, fallbackSource) {
8
+ return definitions.map((definition) => ({
9
+ fields: [],
10
+ file: relativeDefinitionFile(projectRoot, definition.handler),
11
+ name: definition.name,
12
+ source: definition.source || fallbackSource
13
+ }));
14
+ }
15
+ const redactedInspectionValue = "[redacted]";
16
+ const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
17
+ const embeddedUrlCredentialPattern = /\b([a-z][a-z0-9+.-]*:\/\/)[^/\s?#]*@/gi;
18
+ const embeddedCookiePattern = /\b([\w-]*cookie[\w-]*["']?\s*[:=]\s*)(?:"(?:\\[^\r\n]|[^"\\\r\n])*"(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|'(?:\\[^\r\n]|[^'\\\r\n])*'(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|[^\r\n]+?(?=\s*(?:;\s*[^;=\r\n/]+\s*(?:\r?\n|$)|&|\r?\n|$)))/gi;
19
+ const embeddedBearerPattern = /\bbearer\s+[^\s,;]+/gi;
20
+ const embeddedAuthorizationPattern = new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
21
+ const embeddedSecretAssignmentPattern = new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
22
+ /**
23
+ * Removes credentials inside free text, for example an error message. URL credentials, bearer tokens, and
24
+ * `name=value` pairs with a secret name are replaced with `[redacted]`.
25
+ */
26
+ function redactInspectionText(value) {
27
+ return value.replace(embeddedUrlCredentialPattern, `$1${redactedInspectionValue}@`).replace(embeddedAuthorizationPattern, `$1${redactedInspectionValue}`).replace(embeddedCookiePattern, `$1${redactedInspectionValue}`).replace(embeddedBearerPattern, `Bearer ${redactedInspectionValue}`).replace(embeddedSecretAssignmentPattern, `$1${redactedInspectionValue}`);
28
+ }
29
+ //#endregion
30
+ export { summarizeDefinitions as n, redactInspectionText as t };
@@ -1,6 +1,4 @@
1
- import { _ as QueueProviderOptions, o as QueueClient } from "../../types-CwvoMATy.js";
2
-
1
+ import { w as QueueDriverOptions, y as QueueClient } from "../../types-BD-8U9zS.js";
3
2
  //#region src/internal/runtime/cloudflare-client.d.ts
4
- declare function createCloudflareQueueRuntimeClient(options: QueueProviderOptions): Promise<QueueClient>;
5
- //#endregion
6
- export { createCloudflareQueueRuntimeClient };
3
+ export declare function createCloudflareQueueRuntimeClient(options: QueueDriverOptions): Promise<QueueClient>;
4
+ //#endregion
@@ -1,2 +1,2 @@
1
- import { t as createCloudflareQueueRuntimeClient } from "../../cloudflare-client-w5vphoNn.js";
1
+ import { t as createCloudflareQueueRuntimeClient } from "../../cloudflare-client-DYsAjM8B.js";
2
2
  export { createCloudflareQueueRuntimeClient };
@@ -1,2 +1,30 @@
1
- import { i as createQueueCloudflareWorker, n as QueueCloudflareWorker, r as QueueCloudflareWorkerOptions, t as CloudflareWorkerApp } from "../../cloudflare-vite-nFPor46-.js";
2
- export { CloudflareWorkerApp, QueueCloudflareWorker, QueueCloudflareWorkerOptions, createQueueCloudflareWorker };
1
+ import { L as ResolvedQueueOptions, S as QueueDefinitionRegistry, a as CloudflareQueueMessageBatch } from "../../types-BD-8U9zS.js";
2
+ //#region ../internal/src/runtime/cloudflare-env-lookup.d.ts
3
+ type CloudflareWorkerEnv = Record<string, unknown>;
4
+ //#endregion
5
+ //#region ../internal/src/runtime/cloudflare-env.d.ts
6
+ interface CloudflareWorkerExecutionContext {
7
+ waitUntil?: (promise: Promise<unknown>) => void;
8
+ }
9
+ //#endregion
10
+ //#region ../internal/src/runtime/app.d.ts
11
+ type AppHandler = (request: Request, context?: Record<string, unknown>) => Response | Promise<Response>;
12
+ type VitehubApp = AppHandler | {
13
+ fetch?: AppHandler;
14
+ request?: (request: Request, options?: RequestInit, context?: Record<string, unknown>) => Response | Promise<Response>;
15
+ };
16
+ //#endregion
17
+ //#region src/internal/runtime/cloudflare-vite.d.ts
18
+ export type CloudflareWorkerApp = VitehubApp;
19
+ export interface QueueCloudflareWorkerOptions {
20
+ app?: CloudflareWorkerApp;
21
+ definitions?: Record<string, string>;
22
+ queue?: false | ResolvedQueueOptions;
23
+ registry?: QueueDefinitionRegistry;
24
+ }
25
+ export interface QueueCloudflareWorker {
26
+ fetch: (request: Request, env: CloudflareWorkerEnv, context: CloudflareWorkerExecutionContext) => Promise<Response>;
27
+ queue: (batch: CloudflareQueueMessageBatch, env: CloudflareWorkerEnv, context: CloudflareWorkerExecutionContext) => Promise<void>;
28
+ }
29
+ export declare function createQueueCloudflareWorker(options?: QueueCloudflareWorkerOptions): QueueCloudflareWorker;
30
+ //#endregion
@@ -1,2 +1,112 @@
1
- import { t as createQueueCloudflareWorker } from "../../cloudflare-vite-BlQfDVZD.js";
1
+ import { t as queueErrorDiagnostics } from "../../error-diagnostics-BRartC1z.js";
2
+ import { _ as runWithActiveCloudflareEnv, c as loadQueueDefinition, d as setQueueRuntimeConfig, h as createCloudflareRuntimeEvent, m as setQueueRuntimeRegistry, u as runWithQueueRuntimeEvent } from "../../state-mVA2X_wa.js";
3
+ import { t as internalErrorDiagnostics } from "../../error-diagnostics-DSkCJC_L.js";
4
+ import { n as normalizeQueueOptions } from "../../config-BcTDeQIP.js";
5
+ import { n as getCloudflareQueueDefinitionName } from "../../cloudflare-GosJefIK.js";
6
+ import { t as getCloudflareQueueName } from "../../cloudflare-resource-name-BJHYRCMQ.js";
7
+ import { n as createCloudflareQueueBatchHandler, t as createCloudflareQueueRuntimeClient } from "../../cloudflare-client-DYsAjM8B.js";
8
+ import { runInRunScopes } from "@vite-hub/runtime/internal/run-scope";
9
+ //#region ../internal/src/runtime/app.ts
10
+ function resolveAppFetch(label, app) {
11
+ if (!app) return;
12
+ if (typeof app === "function") return app;
13
+ if (typeof app.request === "function") return (request, context) => app.request(request, void 0, context);
14
+ if (typeof app.fetch === "function") return app.fetch.bind(app);
15
+ throw internalErrorDiagnostics.INTERNAL_R0011({ message: `Invalid ${label} app. Expected an h3 app or a fetch-compatible handler.` });
16
+ }
17
+ //#endregion
18
+ //#region ../internal/src/runtime/cloudflare-hosted.ts
19
+ function createWebRequestHandler(appHandler) {
20
+ return async (request, context) => await Promise.resolve(appHandler ? appHandler(request, context) : new Response(JSON.stringify({
21
+ status: 404,
22
+ message: `Cannot find any route matching [${request.method}] ${request.url}`
23
+ }), {
24
+ headers: { "content-type": "application/json;charset=UTF-8" },
25
+ status: 404,
26
+ statusText: "Not Found"
27
+ }));
28
+ }
29
+ function createCloudflareHostedWorker(adapter) {
30
+ const requestHandler = createWebRequestHandler(resolveAppFetch(adapter.label, adapter.app));
31
+ return { async fetch(request, env, context) {
32
+ const handle = async (handlerContext) => await Promise.resolve(requestHandler(request, handlerContext));
33
+ if (adapter.onRequest) return await adapter.onRequest({
34
+ env,
35
+ executionContext: context,
36
+ handle
37
+ });
38
+ return await handle();
39
+ } };
40
+ }
41
+ //#endregion
42
+ //#region src/runtime/cloudflare-shared.ts
43
+ function createQueueJob(message, batch) {
44
+ return {
45
+ attempts: typeof message.attempts === "number" ? message.attempts : 1,
46
+ id: message.id,
47
+ metadata: {
48
+ batch,
49
+ message
50
+ },
51
+ payload: message.body
52
+ };
53
+ }
54
+ //#endregion
55
+ //#region src/internal/runtime/cloudflare-vite.ts
56
+ function createRegistryDefinitionNames(registry, namePrefix) {
57
+ if (!registry) return void 0;
58
+ const definitions = {};
59
+ for (const name of Object.keys(registry)) {
60
+ const physicalName = getCloudflareQueueName(name, namePrefix);
61
+ if (definitions[physicalName]) throw queueErrorDiagnostics.QUEUE_NAME_COLLISION({
62
+ first: definitions[physicalName],
63
+ resolved: physicalName,
64
+ second: name
65
+ });
66
+ definitions[physicalName] = name;
67
+ }
68
+ return definitions;
69
+ }
70
+ function createQueueCloudflareWorker(options = {}) {
71
+ const queueConfig = options.queue === false ? false : normalizeQueueOptions(options.queue, { hosting: "cloudflare" });
72
+ const registry = options.registry;
73
+ const definitions = options.definitions;
74
+ const registryDefinitions = !definitions && queueConfig !== false && queueConfig.driver === "cloudflare" ? createRegistryDefinitionNames(registry, queueConfig.namePrefix ?? "") : void 0;
75
+ const applyRuntimeState = () => {
76
+ setQueueRuntimeConfig(queueConfig, createCloudflareQueueRuntimeClient);
77
+ setQueueRuntimeRegistry(registry);
78
+ };
79
+ return {
80
+ ...createCloudflareHostedWorker({
81
+ app: options.app,
82
+ label: "queue",
83
+ async onRequest({ env, executionContext, handle }) {
84
+ applyRuntimeState();
85
+ const runtimeEvent = createCloudflareRuntimeEvent(env, executionContext);
86
+ return await runWithActiveCloudflareEnv(env, () => runWithQueueRuntimeEvent(runtimeEvent, () => handle(runtimeEvent.context)));
87
+ }
88
+ }),
89
+ async queue(batch, env, context) {
90
+ applyRuntimeState();
91
+ if (queueConfig === false || queueConfig?.driver !== "cloudflare") return;
92
+ const runtimeEvent = createCloudflareRuntimeEvent(env, context);
93
+ await runWithActiveCloudflareEnv(env, async () => {
94
+ 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));
95
+ if (!definitionName) throw queueErrorDiagnostics.QUEUE_DEFINITION_NOT_FOUND({ queue: batch.queue });
96
+ const definition = await loadQueueDefinition(definitionName);
97
+ if (!definition) throw queueErrorDiagnostics.QUEUE_DEFINITION_NOT_FOUND({ queue: definitionName });
98
+ await createCloudflareQueueBatchHandler({
99
+ concurrency: definition.options?.concurrency,
100
+ onError: definition.options?.onError,
101
+ onMessage: async (message, currentBatch) => {
102
+ await runWithQueueRuntimeEvent(runtimeEvent, async () => {
103
+ await runInRunScopes(() => definition.handler(createQueueJob(message, currentBatch)));
104
+ });
105
+ }
106
+ })(batch);
107
+ });
108
+ }
109
+ };
110
+ }
111
+ //#endregion
2
112
  export { createQueueCloudflareWorker };
@@ -0,0 +1,17 @@
1
+ import { m as LocalQueueStatus, y as QueueClient } from "../../types-BD-8U9zS.js";
2
+ import { t as LocalQueueEngine } from "../../local-CVVRVWeR.js";
3
+ import { n as QueueRuntimeOptions, t as QueueRuntimeDriverOptions } from "../../types-DS_rqu9l.js";
4
+ //#region src/internal/runtime/local-client.d.ts
5
+ export declare function createLocalQueueRuntimeClient(options: QueueRuntimeDriverOptions): Promise<QueueClient>;
6
+ /**
7
+ * Starts delivery of the stored jobs when the server starts, so jobs from before a restart run without a new send.
8
+ * Logs once where the jobs are and what survives.
9
+ */
10
+ export declare function startLocalQueue(config: false | QueueRuntimeOptions): void;
11
+ /** The engine of the stored jobs, for `vitehub queue list`, `vitehub queue jobs`, and the Console. */
12
+ export declare function useLocalQueueEngine(config: QueueRuntimeOptions): LocalQueueEngine | undefined;
13
+ /** Status of the stored jobs, for `vitehub queue list` and the Console. */
14
+ export declare function getLocalQueueStatus(config: QueueRuntimeOptions): Promise<LocalQueueStatus | undefined>;
15
+ /** Stops the timers of every local engine. The stored jobs stay. */
16
+ export declare function closeLocalQueues(): void;
17
+ //#endregion
@@ -0,0 +1,71 @@
1
+ import { t as queueErrorDiagnostics } from "../../error-diagnostics-BRartC1z.js";
2
+ import { c as loadQueueDefinition, l as missingQueueDefinitionError } from "../../state-mVA2X_wa.js";
3
+ import { t as defaultLocalQueueBase } from "../../config-BcTDeQIP.js";
4
+ import { i as localQueueDeliveryRules, n as createLocalQueueEngine, t as createLocalQueueClient } from "../../local-CGckW5nr.js";
5
+ import { resolve } from "pathe";
6
+ //#region src/internal/runtime/local-client.ts
7
+ const engines = /* @__PURE__ */ new Map();
8
+ function getLocalQueueEngine({ base = defaultLocalQueueBase, development, rules = "local" }) {
9
+ const directory = resolve(base);
10
+ const cached = engines.get(directory);
11
+ const discloseErrors = development === true;
12
+ if (cached) {
13
+ if (cached.development !== discloseErrors) throw queueErrorDiagnostics.QUEUE_LOCAL_MODE_MISMATCH();
14
+ return cached.engine;
15
+ }
16
+ const engine = createLocalQueueEngine({
17
+ base: directory,
18
+ development: discloseErrors,
19
+ load: loadQueueDefinition,
20
+ missing: missingQueueDefinitionError,
21
+ rules: localQueueDeliveryRules[rules]
22
+ });
23
+ engines.set(directory, {
24
+ development: discloseErrors,
25
+ engine
26
+ });
27
+ return engine;
28
+ }
29
+ async function createLocalQueueRuntimeClient(options) {
30
+ if (options.driver !== "local") throw queueErrorDiagnostics.QUEUE_DRIVER_MISMATCH({
31
+ driver: options.driver,
32
+ expected: "local"
33
+ });
34
+ if (!options.queue) throw queueErrorDiagnostics.QUEUE_MISSING_QUEUE();
35
+ return createLocalQueueClient(getLocalQueueEngine(options), options.queue);
36
+ }
37
+ const providerNames = {
38
+ cloudflare: "Cloudflare",
39
+ local: "local",
40
+ postgres: "Postgres",
41
+ vercel: "Vercel"
42
+ };
43
+ /**
44
+ * Starts delivery of the stored jobs when the server starts, so jobs from before a restart run without a new send.
45
+ * Logs once where the jobs are and what survives.
46
+ */
47
+ function startLocalQueue(config) {
48
+ if (config === false || config.driver !== "local") return;
49
+ const engine = getLocalQueueEngine(config);
50
+ if (config.rules && config.rules !== "local") console.warn(`[vitehub:queue] The dev server runs Queue jobs in this process with the ${providerNames[config.rules]} delivery rules. It stores them in ${engine.base}. The build uses ${providerNames[config.rules]} Queues. Run \`vitehub queue jobs list\` to inspect the jobs.`);
51
+ else console.warn(`[vitehub:queue] Queue uses the local driver. This process stores jobs in ${engine.base} and runs them. The jobs survive a restart on this host, but not a move to another host or a new container. Run one server process per directory.`);
52
+ engine.start().catch((error) => {
53
+ console.error(`[vitehub:queue] The local driver cannot read the stored jobs in ${engine.base}.`, error);
54
+ });
55
+ }
56
+ /** The engine of the stored jobs, for `vitehub queue list`, `vitehub queue jobs`, and the Console. */
57
+ function useLocalQueueEngine(config) {
58
+ if (config.driver !== "local") return;
59
+ return getLocalQueueEngine(config);
60
+ }
61
+ /** Status of the stored jobs, for `vitehub queue list` and the Console. */
62
+ async function getLocalQueueStatus(config) {
63
+ return await useLocalQueueEngine(config)?.status();
64
+ }
65
+ /** Stops the timers of every local engine. The stored jobs stay. */
66
+ function closeLocalQueues() {
67
+ for (const { engine } of engines.values()) engine.close();
68
+ engines.clear();
69
+ }
70
+ //#endregion
71
+ export { closeLocalQueues, createLocalQueueRuntimeClient, getLocalQueueStatus, startLocalQueue, useLocalQueueEngine };