@velajs/cloudflare 1.35.0 → 1.36.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/CHANGELOG.md +29 -0
- package/README.md +28 -6
- package/dist/_virtual/{_@oxc-project_runtime@0.150.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/decorate.js +1 -2
- package/dist/_virtual/{_@oxc-project_runtime@0.150.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/decorateMetadata.js +1 -2
- package/dist/_virtual/{_@oxc-project_runtime@0.150.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/decorateParam.js +1 -2
- package/dist/bindings.js +1 -2
- package/dist/{cloudflare-application-Dsscb3Mo.d.ts → cloudflare-application-Zw9th_-h.d.ts} +2 -7
- package/dist/cloudflare-application.js +2 -3
- package/dist/cloudflare-application.js.map +1 -1
- package/dist/{cloudflare-factory-DM9CBvNH.d.ts → cloudflare-factory-Ab6XoKqO.d.ts} +5 -9
- package/dist/cloudflare-factory.js +5 -6
- package/dist/cloudflare-factory.js.map +1 -1
- package/dist/decorators/queue-consumer.js +1 -2
- package/dist/diagnostics.js +1 -2
- package/dist/durable-object/boot.js +5 -6
- package/dist/durable-object/host-dispatch.js +4 -5
- package/dist/durable-object/host-dispatch.js.map +1 -1
- package/dist/durable-object/host-methods.js +1 -2
- package/dist/durable-object/tokens.js +1 -2
- package/dist/durable-object/vela-durable-object.js +3 -4
- package/dist/durable-objects.d.ts +7 -19
- package/dist/durable-objects.js +1 -1
- package/dist/email/email-dispatch.js +1 -2
- package/dist/email/on-email.js +2 -3
- package/dist/email.d.ts +2 -6
- package/dist/email.js +1 -1
- package/dist/entrypoint/vela-entrypoint.js +4 -5
- package/dist/entrypoints.d.ts +3 -5
- package/dist/entrypoints.js +1 -2
- package/dist/environment.js +1 -2
- package/dist/host/host-invoker.js +2 -3
- package/dist/host/host-invoker.js.map +1 -1
- package/dist/host/host-members.js +1 -2
- package/dist/{host-members-DECj_4yz.d.ts → host-members-bKCWuJP2.d.ts} +0 -2
- package/dist/index.d.ts +53 -42
- package/dist/index.js +6 -5
- package/dist/nonce/durable-object-nonce.store.js +1 -2
- package/dist/nonce/nonce-validation.js +1 -2
- package/dist/nonce/nonce.durable-object.js +2 -3
- package/dist/nonce/nonce.durable-object.js.map +1 -1
- package/dist/{nonce.durable-object-Bg1e0BMD.d.ts → nonce.durable-object-Csuy3U9e.d.ts} +0 -4
- package/dist/pipelines.d.ts +1 -3
- package/dist/pipelines.js +1 -2
- package/dist/platform.js +2 -3
- package/dist/queue/cloudflare-queues.js +3 -4
- package/dist/queue-events/consume.js +1 -2
- package/dist/queue-events/consume.js.map +1 -1
- package/dist/queue-events.d.ts +1 -2
- package/dist/queue-events.js +1 -2
- package/dist/queues.d.ts +1 -3
- package/dist/queues.js +1 -2
- package/dist/rate-limit/cloudflare-rate-limit.store.js +1 -2
- package/dist/rate-limit/d1-throttler.store.js +96 -0
- package/dist/rate-limit/d1-throttler.store.js.map +1 -0
- package/dist/root-module.js +1 -2
- package/dist/rpc/entrypoint-error.js +1 -2
- package/dist/rpc/entrypoint-error.js.map +1 -1
- package/dist/schedule-diagnostics.js +2 -3
- package/dist/schedule-diagnostics.js.map +1 -1
- package/dist/scheduled-event.js +1 -2
- package/dist/services/flagship-flag.driver.js +1 -2
- package/dist/services/flagship-flag.driver.js.map +1 -1
- package/dist/services/kv-cache.store.js +1 -2
- package/dist/services/kv-cache.store.js.map +1 -1
- package/dist/services/kv-flag.driver.js +1 -2
- package/dist/services/kv-flag.driver.js.map +1 -1
- package/dist/storage/r2-storage.js +2 -3
- package/dist/storage.d.ts +1 -3
- package/dist/storage.js +1 -2
- package/dist/tail/on-tail.js +2 -3
- package/dist/tail/tail-dispatch.js +2 -3
- package/dist/tail.d.ts +2 -6
- package/dist/tail.js +1 -2
- package/dist/testing.d.ts +5 -5
- package/dist/testing.js +6 -6
- package/dist/testing.js.map +1 -1
- package/dist/tracing.d.ts +1 -3
- package/dist/tracing.js +3 -4
- package/dist/{vela-env-DFvyoNT3.d.ts → vela-env-5graXefc.d.ts} +0 -1
- package/dist/websocket/binding-gateways.js +2 -3
- package/dist/websocket/cf-room-registry.js +2 -3
- package/dist/websocket/cf-room-registry.js.map +1 -1
- package/dist/websocket/cf-ws-client.js +2 -3
- package/dist/websocket/cf-ws-client.js.map +1 -1
- package/dist/websocket/do-bootstrap.js +5 -6
- package/dist/websocket/do-live.js +4 -5
- package/dist/websocket/do-live.js.map +1 -1
- package/dist/websocket/do-pitr.js +1 -2
- package/dist/websocket/do-pitr.js.map +1 -1
- package/dist/websocket/do-state.js +1 -2
- package/dist/websocket/do-websocket-host.js +3 -4
- package/dist/websocket/do-websocket-host.js.map +1 -1
- package/dist/websocket/live-driver.js +3 -4
- package/dist/websocket/live-driver.js.map +1 -1
- package/dist/websocket/room-id.js +1 -2
- package/dist/websocket/websocket.durable-object.js +5 -6
- package/dist/websocket/websocket.durable-object.js.map +1 -1
- package/dist/websocket/worker-transport.js +3 -4
- package/dist/websocket/ws-attachment.js +1 -2
- package/dist/worker-events.js +1 -2
- package/dist/workflow/portable-workflow-step.js +1 -2
- package/dist/workflow/vela-workflow-definition.js +7 -8
- package/dist/workflow/vela-workflow-definition.js.map +1 -1
- package/dist/workflow/vela-workflow.js +2 -3
- package/dist/workflow-definitions.d.ts +2 -4
- package/dist/workflow-definitions.js +1 -2
- package/dist/workflows.d.ts +2 -4
- package/dist/workflows.js +1 -2
- package/package.json +19 -19
package/dist/index.d.ts
CHANGED
|
@@ -1,19 +1,15 @@
|
|
|
1
|
-
import "./vela-env-
|
|
2
|
-
import { a as
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { DynamicModule, ExecutionContext, InjectionToken, Type, VelaEnv } from "@velajs/vela";
|
|
6
|
-
import { Binding, BindingRef, EnvFactory, RuntimeAdapter } from "@velajs/vela/module-kit";
|
|
7
|
-
import { CommitStamp, CursorLog, InvalidationCommand, LiveDriver, LiveInvalidationSink, ResumeVerdict } from "@velajs/vela/live";
|
|
8
|
-
import { BroadcastCommand } from "@velajs/vela/websocket";
|
|
1
|
+
import "./vela-env-5graXefc.js";
|
|
2
|
+
import { _ as defineCloudflareApp, a as CloudflareApp, c as CloudflareEntrypointDescriptor, d as CloudflareWorkerOptions, f as CloudflareWorkflowDescriptor, g as createCloudflareWorker, h as createCloudflareApp, i as CLOUDFLARE_WORKFLOW, l as CloudflareWorker, m as cloudflareAdapter, n as CLOUDFLARE_ENTRYPOINT, o as CloudflareAppOptions, p as CreateCloudflareAppOptions, r as CLOUDFLARE_WORKER, s as CloudflareDurableObjectDescriptor, t as CLOUDFLARE_DURABLE_OBJECT, u as CloudflareWorkerDescriptor, v as isCloudflareApp, y as CloudflareRoot } from "./cloudflare-factory-Ab6XoKqO.js";
|
|
3
|
+
import { a as ScheduledEvent, i as CloudflareScheduledEvent, n as MountOpenApiOptions, r as CLOUDFLARE_SCHEDULED_EVENT, t as CloudflareApplication } from "./cloudflare-application-Zw9th_-h.js";
|
|
4
|
+
import { Binding, BindingRef, EnvFactory } from "@velajs/vela/module-kit";
|
|
9
5
|
import { CacheEntry, CacheEntryReader, CacheEntryWriter, CacheInvalidationStore, CacheStore } from "@velajs/vela/cache";
|
|
6
|
+
import { a as DoPitrId, c as DoPitrUnavailableError, d as isDoPitrUnavailable, f as readDoPitrBookmark, i as DoPitrBookmarkRead, l as VelaDoPitrRpc, n as DoPitrArmOptions, o as DoPitrNamespace, r as DoPitrArmResult, s as DoPitrStorage, t as VelaNonceDurableObject, u as armDoPitr } from "./nonce.durable-object-Csuy3U9e.js";
|
|
7
|
+
import { CommitStamp, CursorLog, InvalidationCommand, LiveDriver, LiveInvalidationSink, ResumeVerdict } from "@velajs/vela/live";
|
|
8
|
+
import { VelaEnv } from "@velajs/vela";
|
|
10
9
|
import { ThrottlerStore } from "@velajs/vela/throttler";
|
|
11
10
|
import { NonceStore } from "@velajs/vela/security";
|
|
12
|
-
//#region src/websocket/room-id.d.ts
|
|
13
11
|
/** Stable, collision-free Durable Object name for one gateway's room. */
|
|
14
12
|
export declare function durableObjectRoomName(gatewayPath: string, roomId: string): string;
|
|
15
|
-
//#endregion
|
|
16
|
-
//#region src/rpc/entrypoint-error.d.ts
|
|
17
13
|
/** What a failed JS-RPC call of a Vela entrypoint carries across the RPC boundary. */
|
|
18
14
|
interface EntrypointErrorInit {
|
|
19
15
|
/** An HTTP error status, 400–599. */
|
|
@@ -63,8 +59,6 @@ export declare class EntrypointError extends Error implements EntrypointErrorIni
|
|
|
63
59
|
* this is false.
|
|
64
60
|
*/
|
|
65
61
|
export declare function isEntrypointError(error: unknown): error is EntrypointError;
|
|
66
|
-
//#endregion
|
|
67
|
-
//#region src/bindings.d.ts
|
|
68
62
|
export declare const kv: (ref: BindingRef) => Binding<KVNamespace<string>>;
|
|
69
63
|
export declare const r2: (ref: BindingRef) => Binding<R2Bucket>;
|
|
70
64
|
export declare const d1: (ref: BindingRef) => Binding<D1Database>;
|
|
@@ -83,8 +77,6 @@ export declare const rateLimit: (ref: BindingRef) => Binding<RateLimit>;
|
|
|
83
77
|
export declare function workflow<Params = unknown>(ref: BindingRef): Binding<Workflow<Params>>;
|
|
84
78
|
export declare const flagship: (ref: BindingRef) => Binding<Flagship>;
|
|
85
79
|
export declare const secretsStoreSecret: (ref: BindingRef) => Binding<SecretsStoreSecret>;
|
|
86
|
-
//#endregion
|
|
87
|
-
//#region src/services/kv-cache.store.d.ts
|
|
88
80
|
/** A KV namespace, or a function that reads it when an operation needs it. */
|
|
89
81
|
type KVNamespaceSource = KVNamespace | (() => KVNamespace);
|
|
90
82
|
/**
|
|
@@ -136,9 +128,6 @@ export declare function kvCache(ref: {
|
|
|
136
128
|
export declare function kvCacheInvalidation(ref: {
|
|
137
129
|
binding: string;
|
|
138
130
|
}): EnvFactory<CacheInvalidationStore>;
|
|
139
|
-
//#endregion
|
|
140
|
-
//#region ../feature-flags/dist/memory.driver-C5Vcv2gb.d.ts
|
|
141
|
-
//#region src/drivers/driver.d.ts
|
|
142
131
|
/**
|
|
143
132
|
* The cross-package contract every feature-flag backend implements.
|
|
144
133
|
*
|
|
@@ -164,8 +153,6 @@ interface FeatureFlagDriver {
|
|
|
164
153
|
getNumberDetails?(key: string, fallback: number, ctx?: FlagContext): Promise<FlagEvaluationDetails<number>>;
|
|
165
154
|
getObjectDetails?(key: string, fallback: object, ctx?: FlagContext): Promise<FlagEvaluationDetails<unknown>>;
|
|
166
155
|
}
|
|
167
|
-
//#endregion
|
|
168
|
-
//#region src/feature-flags.types.d.ts
|
|
169
156
|
/**
|
|
170
157
|
* A value a feature flag can resolve to. Mirrors the four evaluation methods
|
|
171
158
|
* on {@link FeatureFlagDriver}.
|
|
@@ -187,8 +174,6 @@ interface FlagEvaluationDetails<T = FlagValue> {
|
|
|
187
174
|
errorCode?: string;
|
|
188
175
|
errorMessage?: string;
|
|
189
176
|
}
|
|
190
|
-
//#endregion
|
|
191
|
-
//#region src/services/flagship-flag.driver.d.ts
|
|
192
177
|
/**
|
|
193
178
|
* The subset of a Cloudflare **Flagship** binding this driver evaluates against
|
|
194
179
|
* — typed value methods and optional evaluation details. The binding itself returns the supplied
|
|
@@ -254,8 +239,6 @@ export declare class FlagshipFlagDriver implements FeatureFlagDriver {
|
|
|
254
239
|
}
|
|
255
240
|
/** Convenience factory for {@link FlagshipFlagDriver}. */
|
|
256
241
|
export declare function flagshipFlagDriver(binding: FlagshipBinding | (() => FlagshipBinding), options?: FlagshipFlagDriverOptions): FlagshipFlagDriver;
|
|
257
|
-
//#endregion
|
|
258
|
-
//#region src/services/kv-flag.driver.d.ts
|
|
259
242
|
interface KvFlagDriverOptions {
|
|
260
243
|
/** Driver name used for `use(name)` / default-driver selection. Default `"kv"`. */
|
|
261
244
|
name?: string;
|
|
@@ -301,8 +284,6 @@ export declare class KvFlagDriver implements FeatureFlagDriver {
|
|
|
301
284
|
}
|
|
302
285
|
/** Convenience factory for {@link KvFlagDriver}. */
|
|
303
286
|
export declare function kvFlagDriver(kv: KVNamespace, options?: KvFlagDriverOptions): KvFlagDriver;
|
|
304
|
-
//#endregion
|
|
305
|
-
//#region src/decorators/queue-consumer.d.ts
|
|
306
287
|
interface QueueConsumerMetadata {
|
|
307
288
|
queueName: string;
|
|
308
289
|
methodName: string;
|
|
@@ -325,16 +306,12 @@ interface QueueConsumerMetadata {
|
|
|
325
306
|
* ```
|
|
326
307
|
*/
|
|
327
308
|
export declare function QueueConsumer(queueName: string): MethodDecorator;
|
|
328
|
-
//#endregion
|
|
329
|
-
//#region src/websocket/do-state.d.ts
|
|
330
309
|
/** Structural view of the DO's SQLite handle (`ctx.storage.sql`, requires `new_sqlite_classes`). */
|
|
331
310
|
interface SqlStorageLike {
|
|
332
311
|
exec(query: string, ...bindings: unknown[]): {
|
|
333
312
|
toArray(): Record<string, unknown>[];
|
|
334
313
|
};
|
|
335
314
|
}
|
|
336
|
-
//#endregion
|
|
337
|
-
//#region src/websocket/binding-gateways.d.ts
|
|
338
315
|
/** A gateway whose rooms live in Durable Objects: its path and namespace binding. */
|
|
339
316
|
interface BindingGateway {
|
|
340
317
|
path: string;
|
|
@@ -342,15 +319,11 @@ interface BindingGateway {
|
|
|
342
319
|
/** The gateway class name, for diagnostics. */
|
|
343
320
|
name: string;
|
|
344
321
|
}
|
|
345
|
-
//#endregion
|
|
346
|
-
//#region src/websocket/worker-transport.d.ts
|
|
347
322
|
/** One gateway room's Durable Object: its id, and calls to its operations. */
|
|
348
323
|
interface GatewayRoomObject {
|
|
349
324
|
readonly id: unknown;
|
|
350
325
|
call(method: string, ...args: unknown[]): Promise<unknown>;
|
|
351
326
|
}
|
|
352
|
-
//#endregion
|
|
353
|
-
//#region src/websocket/live-driver.d.ts
|
|
354
327
|
interface DurableObjectLiveOptions {
|
|
355
328
|
/**
|
|
356
329
|
* Durable Object namespace binding that holds the gateway's rooms, read from
|
|
@@ -416,8 +389,6 @@ declare class CfLiveDriver implements LiveDriver {
|
|
|
416
389
|
* ```
|
|
417
390
|
*/
|
|
418
391
|
export declare function durableObjectLive(options?: DurableObjectLiveOptions): CfLiveDriver;
|
|
419
|
-
//#endregion
|
|
420
|
-
//#region src/websocket/do-live.d.ts
|
|
421
392
|
/**
|
|
422
393
|
* The durable `CursorLog`: an append-only tag-invalidation log in the DO's
|
|
423
394
|
* SQLite (`__vela_live_log`, AUTOINCREMENT seq = cursor) plus an epoch UUID in
|
|
@@ -448,8 +419,6 @@ export declare class DoCursorLog implements CursorLog {
|
|
|
448
419
|
* gateway without roomParam keeps every room in one object, named by its path.
|
|
449
420
|
*/
|
|
450
421
|
export declare function liveInvalidateToRoom(ns: LiveNamespace, gatewayPath: string, room: string, tags: string[]): Promise<CommitStamp | undefined>;
|
|
451
|
-
//#endregion
|
|
452
|
-
//#region src/rate-limit/cloudflare-rate-limit.store.d.ts
|
|
453
422
|
interface RateLimitStoreOptions {
|
|
454
423
|
/**
|
|
455
424
|
* The Workers Rate Limiting binding (declared under `ratelimits`) that
|
|
@@ -484,8 +453,51 @@ interface RateLimitStoreOptions {
|
|
|
484
453
|
* throttlers against the bindings when the application starts.
|
|
485
454
|
*/
|
|
486
455
|
export declare function rateLimitStore(options: RateLimitStoreOptions): EnvFactory<ThrottlerStore>;
|
|
487
|
-
|
|
488
|
-
|
|
456
|
+
interface D1ThrottlerStoreOptions {
|
|
457
|
+
/** The D1 binding (declared under `d1_databases`) that holds the counters. */
|
|
458
|
+
binding: string;
|
|
459
|
+
/** Counter table, created by {@link d1ThrottlerMigration}. Default `vela_rate_limits`. */
|
|
460
|
+
table?: string;
|
|
461
|
+
/** Bound attacker-influenced tracking keys before they reach D1. Default 1024 bytes. */
|
|
462
|
+
maxKeyBytes?: number;
|
|
463
|
+
/**
|
|
464
|
+
* Remove up to this many ended windows on about one count in 100, so the
|
|
465
|
+
* table does not grow with every client ever seen. Default 100; 0 never
|
|
466
|
+
* prunes (prune on a schedule instead).
|
|
467
|
+
*/
|
|
468
|
+
pruneBatch?: number;
|
|
469
|
+
}
|
|
470
|
+
/** A D1 store with its table and a way to drop ended windows on a schedule. */
|
|
471
|
+
interface D1ThrottlerStore extends ThrottlerStore {
|
|
472
|
+
/** Delete up to `limit` ended windows; answers how many went. */
|
|
473
|
+
prune(limit?: number): Promise<number>;
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* The statements that create the counter table and its expiry index, for a D1
|
|
477
|
+
* migration file (each one a complete statement; end them with `;`).
|
|
478
|
+
*/
|
|
479
|
+
export declare function d1ThrottlerMigration(options?: {
|
|
480
|
+
table?: string;
|
|
481
|
+
}): string[];
|
|
482
|
+
/**
|
|
483
|
+
* `ThrottlerModule` storage on D1, read from each application's `ENV` by name:
|
|
484
|
+
*
|
|
485
|
+
* ```ts
|
|
486
|
+
* ThrottlerModule.forRoot({
|
|
487
|
+
* throttlers: [{ name: 'login', ttl: 10 * 60_000, limit: 30 }],
|
|
488
|
+
* storage: d1ThrottlerStore({ binding: 'DB' }),
|
|
489
|
+
* })
|
|
490
|
+
* ```
|
|
491
|
+
*
|
|
492
|
+
* Every count is one `INSERT … ON CONFLICT … RETURNING` statement: D1 runs it
|
|
493
|
+
* atomically on the database's primary, so all isolates and locations share
|
|
494
|
+
* one exact fixed-window counter per key, with windows of any length and
|
|
495
|
+
* `@Throttle()` overrides. Each counted request costs one D1 write, and about
|
|
496
|
+
* one in 100 also deletes up to `pruneBatch` ended windows. The store
|
|
497
|
+
* also reads and resets counters, which `FailureCounter` needs. Create the
|
|
498
|
+
* table with {@link d1ThrottlerMigration}.
|
|
499
|
+
*/
|
|
500
|
+
export declare function d1ThrottlerStore(options: D1ThrottlerStoreOptions): EnvFactory<D1ThrottlerStore>;
|
|
489
501
|
/** The generated Workers binding type for {@link VelaNonceDurableObject}. */
|
|
490
502
|
type DurableObjectNonceNamespace = DurableObjectNamespace<VelaNonceDurableObject>;
|
|
491
503
|
interface DurableObjectNonceStoreOptions {
|
|
@@ -511,5 +523,4 @@ interface DurableObjectNonceStoreOptions {
|
|
|
511
523
|
* the Durable Object is accepted.
|
|
512
524
|
*/
|
|
513
525
|
export declare function durableObjectNonceStore(options: DurableObjectNonceStoreOptions): NonceStore;
|
|
514
|
-
|
|
515
|
-
export { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_SCHEDULED_EVENT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, type CfLiveDriver, type CloudflareApp, type CloudflareAppOptions, CloudflareApplication, type CloudflareDurableObjectDescriptor, type CloudflareEntrypointDescriptor, type CloudflareRoot, type CloudflareScheduledEvent, type CloudflareWorker, type CloudflareWorkerDescriptor, type CloudflareWorkerOptions, type CloudflareWorkflowDescriptor, type CreateCloudflareAppOptions, type DoPitrArmOptions, type DoPitrArmResult, type DoPitrBookmarkRead, type DoPitrId, type DoPitrNamespace, type DoPitrStorage, DoPitrUnavailableError, type DurableObjectLiveOptions, type DurableObjectNonceNamespace, type DurableObjectNonceStoreOptions, type EntrypointErrorInit, type FlagshipBinding, type FlagshipFlagDriverOptions, type KVNamespaceSource, type KvFlagDriverOptions, type LiveNamespace, type MountOpenApiOptions, type QueueConsumerMetadata, type RateLimitStoreOptions, type ScheduledEvent, type VelaDoPitrRpc, armDoPitr, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, defineCloudflareApp, isCloudflareApp, isDoPitrUnavailable, readDoPitrBookmark };
|
|
526
|
+
export { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_SCHEDULED_EVENT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, type CfLiveDriver, type CloudflareApp, type CloudflareAppOptions, CloudflareApplication, type CloudflareDurableObjectDescriptor, type CloudflareEntrypointDescriptor, type CloudflareRoot, type CloudflareScheduledEvent, type CloudflareWorker, type CloudflareWorkerDescriptor, type CloudflareWorkerOptions, type CloudflareWorkflowDescriptor, type CreateCloudflareAppOptions, type D1ThrottlerStore, type D1ThrottlerStoreOptions, type DoPitrArmOptions, type DoPitrArmResult, type DoPitrBookmarkRead, type DoPitrId, type DoPitrNamespace, type DoPitrStorage, DoPitrUnavailableError, type DurableObjectLiveOptions, type DurableObjectNonceNamespace, type DurableObjectNonceStoreOptions, type EntrypointErrorInit, type FlagshipBinding, type FlagshipFlagDriverOptions, type KVNamespaceSource, type KvFlagDriverOptions, type LiveNamespace, type MountOpenApiOptions, type QueueConsumerMetadata, type RateLimitStoreOptions, type ScheduledEvent, type VelaDoPitrRpc, armDoPitr, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, defineCloudflareApp, isCloudflareApp, isDoPitrUnavailable, readDoPitrBookmark };
|
package/dist/index.js
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import { durableObjectRoomName } from "./websocket/room-id.js";
|
|
2
|
-
import { CLOUDFLARE_SCHEDULED_EVENT } from "./scheduled-event.js";
|
|
3
|
-
import { CloudflareApplication } from "./cloudflare-application.js";
|
|
4
|
-
import { d1, durableObject, flagship, kv, queue, r2, rateLimit, secretsStoreSecret, workflow } from "./bindings.js";
|
|
5
|
-
import { durableObjectLive } from "./websocket/live-driver.js";
|
|
6
2
|
import { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, defineCloudflareApp, isCloudflareApp } from "./cloudflare-factory.js";
|
|
3
|
+
import { CloudflareApplication } from "./cloudflare-application.js";
|
|
7
4
|
import { EntrypointError, isEntrypointError } from "./rpc/entrypoint-error.js";
|
|
5
|
+
import { d1, durableObject, flagship, kv, queue, r2, rateLimit, secretsStoreSecret, workflow } from "./bindings.js";
|
|
8
6
|
import { KVCacheInvalidationStore, KVCacheStore, kvCache, kvCacheInvalidation } from "./services/kv-cache.store.js";
|
|
9
7
|
import { FlagshipFlagDriver, flagshipFlagDriver } from "./services/flagship-flag.driver.js";
|
|
10
8
|
import { KvFlagDriver, kvFlagDriver } from "./services/kv-flag.driver.js";
|
|
11
9
|
import { QueueConsumer } from "./decorators/queue-consumer.js";
|
|
10
|
+
import { CLOUDFLARE_SCHEDULED_EVENT } from "./scheduled-event.js";
|
|
12
11
|
import { DoPitrUnavailableError, armDoPitr, isDoPitrUnavailable, readDoPitrBookmark } from "./websocket/do-pitr.js";
|
|
13
12
|
import { DoCursorLog, liveInvalidateToRoom } from "./websocket/do-live.js";
|
|
13
|
+
import { durableObjectLive } from "./websocket/live-driver.js";
|
|
14
|
+
import { d1ThrottlerMigration, d1ThrottlerStore } from "./rate-limit/d1-throttler.store.js";
|
|
14
15
|
import { rateLimitStore } from "./rate-limit/cloudflare-rate-limit.store.js";
|
|
15
16
|
import { durableObjectNonceStore } from "./nonce/durable-object-nonce.store.js";
|
|
16
|
-
export { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_SCHEDULED_EVENT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, CloudflareApplication, DoCursorLog, DoPitrUnavailableError, EntrypointError, FlagshipFlagDriver, KVCacheInvalidationStore, KVCacheStore, KvFlagDriver, QueueConsumer, armDoPitr, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, d1, defineCloudflareApp, durableObject, durableObjectLive, durableObjectNonceStore, durableObjectRoomName, flagship, flagshipFlagDriver, isCloudflareApp, isDoPitrUnavailable, isEntrypointError, kv, kvCache, kvCacheInvalidation, kvFlagDriver, liveInvalidateToRoom, queue, r2, rateLimit, rateLimitStore, readDoPitrBookmark, secretsStoreSecret, workflow };
|
|
17
|
+
export { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_SCHEDULED_EVENT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, CloudflareApplication, DoCursorLog, DoPitrUnavailableError, EntrypointError, FlagshipFlagDriver, KVCacheInvalidationStore, KVCacheStore, KvFlagDriver, QueueConsumer, armDoPitr, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, d1, d1ThrottlerMigration, d1ThrottlerStore, defineCloudflareApp, durableObject, durableObjectLive, durableObjectNonceStore, durableObjectRoomName, flagship, flagshipFlagDriver, isCloudflareApp, isDoPitrUnavailable, isEntrypointError, kv, kvCache, kvCacheInvalidation, kvFlagDriver, liveInvalidateToRoom, queue, r2, rateLimit, rateLimitStore, readDoPitrBookmark, secretsStoreSecret, workflow };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { MAX_NONCE_BYTES, isCanonicalBoundedText, isValidExpiry } from "./nonce-validation.js";
|
|
2
|
-
|
|
2
|
+
// src/nonce/durable-object-nonce.store.ts
|
|
3
3
|
const APP_NAMESPACE_PREFIX = "vela:nonce:v1:";
|
|
4
4
|
const MAX_APP_NAMESPACE_BYTES = 128;
|
|
5
5
|
/**
|
|
@@ -27,7 +27,6 @@ function durableObjectNonceStore(options) {
|
|
|
27
27
|
}
|
|
28
28
|
} };
|
|
29
29
|
}
|
|
30
|
-
//#endregion
|
|
31
30
|
export { durableObjectNonceStore };
|
|
32
31
|
|
|
33
32
|
//# sourceMappingURL=durable-object-nonce.store.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/nonce/nonce-validation.ts
|
|
2
2
|
const encoder = new TextEncoder();
|
|
3
3
|
const MAX_NONCE_BYTES = 512;
|
|
4
4
|
function isCanonicalBoundedText(value, maxBytes) {
|
|
@@ -12,7 +12,6 @@ function isCanonicalBoundedText(value, maxBytes) {
|
|
|
12
12
|
function isValidExpiry(expEpochSeconds, nowEpochSeconds) {
|
|
13
13
|
return typeof expEpochSeconds === "number" && Number.isSafeInteger(expEpochSeconds) && expEpochSeconds > 0 && expEpochSeconds >= nowEpochSeconds;
|
|
14
14
|
}
|
|
15
|
-
//#endregion
|
|
16
15
|
export { MAX_NONCE_BYTES, isCanonicalBoundedText, isValidExpiry };
|
|
17
16
|
|
|
18
17
|
//# sourceMappingURL=nonce-validation.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { MAX_NONCE_BYTES, isCanonicalBoundedText, isValidExpiry } from "./nonce-validation.js";
|
|
2
1
|
import { DurableObject } from "cloudflare:workers";
|
|
3
|
-
|
|
2
|
+
import { MAX_NONCE_BYTES, isCanonicalBoundedText, isValidExpiry } from "./nonce-validation.js";
|
|
3
|
+
// src/nonce/nonce.durable-object.ts
|
|
4
4
|
const EXPIRED_DELETE_BATCH = 1024;
|
|
5
5
|
const CREATE_TABLE = "CREATE TABLE IF NOT EXISTS __vela_nonce_claims (nonce TEXT PRIMARY KEY NOT NULL, expires_at INTEGER NOT NULL CHECK (expires_at > 0)) WITHOUT ROWID";
|
|
6
6
|
const CREATE_EXPIRY_INDEX = "CREATE INDEX IF NOT EXISTS __vela_nonce_claims_expiry ON __vela_nonce_claims (expires_at)";
|
|
@@ -48,7 +48,6 @@ var VelaNonceDurableObject = class extends DurableObject {
|
|
|
48
48
|
}
|
|
49
49
|
}
|
|
50
50
|
};
|
|
51
|
-
//#endregion
|
|
52
51
|
export { VelaNonceDurableObject };
|
|
53
52
|
|
|
54
53
|
//# sourceMappingURL=nonce.durable-object.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nonce.durable-object.js","names":[],"sources":["../../src/nonce/nonce.durable-object.ts"],"sourcesContent":["import { DurableObject } from 'cloudflare:workers';\nimport { MAX_NONCE_BYTES, isCanonicalBoundedText, isValidExpiry } from './nonce-validation';\nconst EXPIRED_DELETE_BATCH = 1_024;\n\nconst CREATE_TABLE =\n 'CREATE TABLE IF NOT EXISTS __vela_nonce_claims (' +\n 'nonce TEXT PRIMARY KEY NOT NULL, ' +\n 'expires_at INTEGER NOT NULL CHECK (expires_at > 0)' +\n ') WITHOUT ROWID';\nconst CREATE_EXPIRY_INDEX =\n 'CREATE INDEX IF NOT EXISTS __vela_nonce_claims_expiry ON __vela_nonce_claims (expires_at)';\nconst DELETE_EXPIRED =\n 'DELETE FROM __vela_nonce_claims WHERE nonce IN (' +\n 'SELECT nonce FROM __vela_nonce_claims ' +\n 'WHERE expires_at < ? ORDER BY expires_at LIMIT ?' +\n ')';\nconst INSERT_CLAIM =\n 'INSERT INTO __vela_nonce_claims (nonce, expires_at) VALUES (?, ?) ' +\n 'ON CONFLICT(nonce) DO NOTHING RETURNING nonce, expires_at';\n\ninterface NonceSqlCursor {\n toArray(): Record<string, unknown>[];\n}\n\ninterface NonceSqlStorage {\n exec(query: string, ...bindings: unknown[]): NonceSqlCursor;\n}\n\n/**\n * SQLite Durable Object that atomically consumes nonces.\n *\n * Export this class from the Worker entry and register it through a Wrangler\n * `new_sqlite_classes` migration. `INSERT ... ON CONFLICT DO NOTHING RETURNING`\n * is the single-use decision; all SQL runs synchronously before the RPC method\n * yields, and the nonce primary key is the final concurrency boundary.\n */\nexport class VelaNonceDurableObject extends DurableObject<Record<string, unknown>> {\n private sql?: NonceSqlStorage;\n\n constructor(ctx: DurableObjectState, env: Record<string, unknown>) {\n super(ctx, env);\n try {\n const sql = ctx.storage?.sql;\n if (!sql || typeof sql.exec !== 'function') return;\n sql.exec(CREATE_TABLE);\n sql.exec(CREATE_EXPIRY_INDEX);\n this.sql = sql;\n } catch {\n // A non-SQLite/misconfigured class stays fail-closed: every claim denies.\n this.sql = undefined;\n }\n }\n\n async claim(nonce: string, expEpochSeconds: number): Promise<boolean> {\n const sql = this.sql;\n if (!sql) return false;\n\n const now = Math.floor(Date.now() / 1_000);\n if (!isCanonicalBoundedText(nonce, MAX_NONCE_BYTES) || !isValidExpiry(expEpochSeconds, now)) {\n return false;\n }\n\n try {\n // Keep cleanup bounded so one claim cannot monopolize the DO. Entries at\n // exactly `now` remain: Vela's invocation verifier accepts `now === exp`.\n sql.exec(DELETE_EXPIRED, now, EXPIRED_DELETE_BATCH);\n\n const cursor = sql.exec(INSERT_CLAIM, nonce, expEpochSeconds);\n if (!cursor || typeof cursor.toArray !== 'function') return false;\n const rows: unknown = cursor.toArray();\n if (!Array.isArray(rows) || rows.length !== 1) return false;\n\n const row: unknown = rows[0];\n if (typeof row !== 'object' || row === null) return false;\n if (\n !Object.hasOwn(row, 'nonce') ||\n !Object.hasOwn(row, 'expires_at') ||\n !('nonce' in row) ||\n !('expires_at' in row)\n ) {\n return false;\n }\n return row.nonce === nonce && row.expires_at === expEpochSeconds;\n } catch {\n return false;\n }\n }\n}\n"],"mappings":";;;AAEA,MAAM,uBAAuB;AAE7B,MAAM,eACJ;AAIF,MAAM,sBACJ;AACF,MAAM,iBACJ;AAIF,MAAM,eACJ;;;;;;;;;AAmBF,IAAa,yBAAb,cAA4C,cAAuC;
|
|
1
|
+
{"version":3,"file":"nonce.durable-object.js","names":[],"sources":["../../src/nonce/nonce.durable-object.ts"],"sourcesContent":["import { DurableObject } from 'cloudflare:workers';\nimport { MAX_NONCE_BYTES, isCanonicalBoundedText, isValidExpiry } from './nonce-validation';\nconst EXPIRED_DELETE_BATCH = 1_024;\n\nconst CREATE_TABLE =\n 'CREATE TABLE IF NOT EXISTS __vela_nonce_claims (' +\n 'nonce TEXT PRIMARY KEY NOT NULL, ' +\n 'expires_at INTEGER NOT NULL CHECK (expires_at > 0)' +\n ') WITHOUT ROWID';\nconst CREATE_EXPIRY_INDEX =\n 'CREATE INDEX IF NOT EXISTS __vela_nonce_claims_expiry ON __vela_nonce_claims (expires_at)';\nconst DELETE_EXPIRED =\n 'DELETE FROM __vela_nonce_claims WHERE nonce IN (' +\n 'SELECT nonce FROM __vela_nonce_claims ' +\n 'WHERE expires_at < ? ORDER BY expires_at LIMIT ?' +\n ')';\nconst INSERT_CLAIM =\n 'INSERT INTO __vela_nonce_claims (nonce, expires_at) VALUES (?, ?) ' +\n 'ON CONFLICT(nonce) DO NOTHING RETURNING nonce, expires_at';\n\ninterface NonceSqlCursor {\n toArray(): Record<string, unknown>[];\n}\n\ninterface NonceSqlStorage {\n exec(query: string, ...bindings: unknown[]): NonceSqlCursor;\n}\n\n/**\n * SQLite Durable Object that atomically consumes nonces.\n *\n * Export this class from the Worker entry and register it through a Wrangler\n * `new_sqlite_classes` migration. `INSERT ... ON CONFLICT DO NOTHING RETURNING`\n * is the single-use decision; all SQL runs synchronously before the RPC method\n * yields, and the nonce primary key is the final concurrency boundary.\n */\nexport class VelaNonceDurableObject extends DurableObject<Record<string, unknown>> {\n private sql?: NonceSqlStorage;\n\n constructor(ctx: DurableObjectState, env: Record<string, unknown>) {\n super(ctx, env);\n try {\n const sql = ctx.storage?.sql;\n if (!sql || typeof sql.exec !== 'function') return;\n sql.exec(CREATE_TABLE);\n sql.exec(CREATE_EXPIRY_INDEX);\n this.sql = sql;\n } catch {\n // A non-SQLite/misconfigured class stays fail-closed: every claim denies.\n this.sql = undefined;\n }\n }\n\n async claim(nonce: string, expEpochSeconds: number): Promise<boolean> {\n const sql = this.sql;\n if (!sql) return false;\n\n const now = Math.floor(Date.now() / 1_000);\n if (!isCanonicalBoundedText(nonce, MAX_NONCE_BYTES) || !isValidExpiry(expEpochSeconds, now)) {\n return false;\n }\n\n try {\n // Keep cleanup bounded so one claim cannot monopolize the DO. Entries at\n // exactly `now` remain: Vela's invocation verifier accepts `now === exp`.\n sql.exec(DELETE_EXPIRED, now, EXPIRED_DELETE_BATCH);\n\n const cursor = sql.exec(INSERT_CLAIM, nonce, expEpochSeconds);\n if (!cursor || typeof cursor.toArray !== 'function') return false;\n const rows: unknown = cursor.toArray();\n if (!Array.isArray(rows) || rows.length !== 1) return false;\n\n const row: unknown = rows[0];\n if (typeof row !== 'object' || row === null) return false;\n if (\n !Object.hasOwn(row, 'nonce') ||\n !Object.hasOwn(row, 'expires_at') ||\n !('nonce' in row) ||\n !('expires_at' in row)\n ) {\n return false;\n }\n return row.nonce === nonce && row.expires_at === expEpochSeconds;\n } catch {\n return false;\n }\n }\n}\n"],"mappings":";;;AAEA,MAAM,uBAAuB;AAE7B,MAAM,eACJ;AAIF,MAAM,sBACJ;AACF,MAAM,iBACJ;AAIF,MAAM,eACJ;;;;;;;;;AAmBF,IAAa,yBAAb,cAA4C,cAAuC;CACzE;CAER,YAAY,KAAyB,KAA8B;EACjE,MAAM,KAAK,GAAG;EACd,IAAI;GACF,MAAM,MAAM,IAAI,SAAS;GACzB,IAAI,CAAC,OAAO,OAAO,IAAI,SAAS,YAAY;GAC5C,IAAI,KAAK,YAAY;GACrB,IAAI,KAAK,mBAAmB;GAC5B,KAAK,MAAM;EACb,QAAQ;GAEN,KAAK,MAAM,KAAA;EACb;CACF;CAEA,MAAM,MAAM,OAAe,iBAA2C;EACpE,MAAM,MAAM,KAAK;EACjB,IAAI,CAAC,KAAK,OAAO;EAEjB,MAAM,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAK;EACzC,IAAI,CAAC,uBAAuB,OAAO,eAAe,KAAK,CAAC,cAAc,iBAAiB,GAAG,GACxF,OAAO;EAGT,IAAI;GAGF,IAAI,KAAK,gBAAgB,KAAK,oBAAoB;GAElD,MAAM,SAAS,IAAI,KAAK,cAAc,OAAO,eAAe;GAC5D,IAAI,CAAC,UAAU,OAAO,OAAO,YAAY,YAAY,OAAO;GAC5D,MAAM,OAAgB,OAAO,QAAQ;GACrC,IAAI,CAAC,MAAM,QAAQ,IAAI,KAAK,KAAK,WAAW,GAAG,OAAO;GAEtD,MAAM,MAAe,KAAK;GAC1B,IAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM,OAAO;GACpD,IACE,CAAC,OAAO,OAAO,KAAK,OAAO,KAC3B,CAAC,OAAO,OAAO,KAAK,YAAY,KAChC,EAAE,WAAW,QACb,EAAE,gBAAgB,MAElB,OAAO;GAET,OAAO,IAAI,UAAU,SAAS,IAAI,eAAe;EACnD,QAAQ;GACN,OAAO;EACT;CACF;AACF"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { DurableObject } from "cloudflare:workers";
|
|
2
|
-
//#region src/websocket/do-pitr.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* Durable Object point-in-time recovery (PITR) — thin, testable wrappers over a
|
|
5
4
|
* SQLite-backed DO's native bookmark API. A SQLite Durable Object exposes three
|
|
@@ -114,8 +113,6 @@ declare function readDoPitrBookmark(storage: DoPitrStorage, time?: number | stri
|
|
|
114
113
|
* arming API (or the by-time resolver a `time` target needs) is absent.
|
|
115
114
|
*/
|
|
116
115
|
declare function armDoPitr(storage: DoPitrStorage, opts: DoPitrArmOptions): Promise<DoPitrArmResult>;
|
|
117
|
-
//#endregion
|
|
118
|
-
//#region src/nonce/nonce.durable-object.d.ts
|
|
119
116
|
/**
|
|
120
117
|
* SQLite Durable Object that atomically consumes nonces.
|
|
121
118
|
*
|
|
@@ -129,5 +126,4 @@ declare class VelaNonceDurableObject extends DurableObject<Record<string, unknow
|
|
|
129
126
|
constructor(ctx: DurableObjectState, env: Record<string, unknown>);
|
|
130
127
|
claim(nonce: string, expEpochSeconds: number): Promise<boolean>;
|
|
131
128
|
}
|
|
132
|
-
//#endregion
|
|
133
129
|
export { DoPitrId as a, DoPitrUnavailableError as c, isDoPitrUnavailable as d, readDoPitrBookmark as f, DoPitrBookmarkRead as i, VelaDoPitrRpc as l, DoPitrArmOptions as n, DoPitrNamespace as o, DoPitrArmResult as r, DoPitrStorage as s, VelaNonceDurableObject as t, armDoPitr as u };
|
package/dist/pipelines.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { StandardSchemaV1 } from "@velajs/vela/validation";
|
|
2
|
-
//#region src/pipelines.d.ts
|
|
3
2
|
/** The native stream handle remains usable independently of the writer. */
|
|
4
3
|
export interface PipelinesBinding<Output = Record<string, unknown>> {
|
|
5
4
|
readonly send: (records: Output[]) => Promise<void>;
|
|
@@ -16,5 +15,4 @@ export interface PipelinesWriter<Input> {
|
|
|
16
15
|
*/
|
|
17
16
|
export declare function createPipelinesWriter<S extends StandardSchemaV1<unknown, Record<string, unknown>>>(binding: PipelinesBinding<NoInfer<StandardSchemaV1.InferOutput<S>>>, { schema }: {
|
|
18
17
|
readonly schema: S;
|
|
19
|
-
}): PipelinesWriter<StandardSchemaV1.InferInput<S>>;
|
|
20
|
-
//#endregion
|
|
18
|
+
}): PipelinesWriter<StandardSchemaV1.InferInput<S>>;
|
package/dist/pipelines.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { SchemaValidationError, isStandardSchema, parseSchemaAsync } from "@velajs/vela/validation";
|
|
2
|
-
|
|
2
|
+
// src/pipelines.ts
|
|
3
3
|
const MAX_BATCH_BYTES = 5e6;
|
|
4
4
|
const encoder = new TextEncoder();
|
|
5
5
|
/**
|
|
@@ -81,7 +81,6 @@ function snapshotJson(value, path, ancestors) {
|
|
|
81
81
|
ancestors.delete(value);
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
|
-
//#endregion
|
|
85
84
|
export { createPipelinesWriter };
|
|
86
85
|
|
|
87
86
|
//# sourceMappingURL=pipelines.js.map
|
package/dist/platform.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { registerCloudflareEnvironment } from "./environment.js";
|
|
2
1
|
import { defineProvider } from "@velajs/vela";
|
|
3
2
|
import { LIVE_PLATFORM } from "@velajs/vela/live";
|
|
4
3
|
import { WS_TRANSPORT } from "@velajs/vela/websocket";
|
|
5
|
-
|
|
4
|
+
import { registerCloudflareEnvironment } from "./environment.js";
|
|
5
|
+
// src/platform.ts
|
|
6
6
|
/**
|
|
7
7
|
* Seed the application's ENV and its platform wiring, as global tokens,
|
|
8
8
|
* before any module loads: `WebSocketModule` and `LiveModule` read
|
|
@@ -16,7 +16,6 @@ function registerCloudflarePlatform(container, env, platform) {
|
|
|
16
16
|
container.register(defineProvider(LIVE_PLATFORM, { useValue: platform.live }));
|
|
17
17
|
container.markGlobalToken(LIVE_PLATFORM);
|
|
18
18
|
}
|
|
19
|
-
//#endregion
|
|
20
19
|
export { registerCloudflarePlatform };
|
|
21
20
|
|
|
22
21
|
//# sourceMappingURL=platform.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { QUEUE_PRODUCER } from "../bindings.js";
|
|
2
|
-
import { resolveBinding } from "@velajs/vela/module-kit";
|
|
3
1
|
import { QueueBatchError, observeMessage, parseQueueJob } from "@velajs/vela/queue";
|
|
4
|
-
|
|
2
|
+
import { resolveBinding } from "@velajs/vela/module-kit";
|
|
3
|
+
import { QUEUE_PRODUCER } from "../bindings.js";
|
|
4
|
+
// src/queue/cloudflare-queues.ts
|
|
5
5
|
/** The Cloudflare Queues send limits `addBulk` is chunked to (bytes are decimal kilobytes). */
|
|
6
6
|
const QUEUE_SEND_LIMITS = Object.freeze({
|
|
7
7
|
/** Messages per `sendBatch` call. */
|
|
@@ -209,7 +209,6 @@ async function consumeQueueBatch(batch, dispatch, options = {}) {
|
|
|
209
209
|
if (errors.length === 1) throw errors[0];
|
|
210
210
|
if (errors.length > 1) throw new AggregateError(errors, "Queue batch deliveries failed.");
|
|
211
211
|
}
|
|
212
|
-
//#endregion
|
|
213
212
|
export { QUEUE_SEND_LIMITS, cloudflareQueues, consumeQueueBatch, estimateQueueMessageBytes };
|
|
214
213
|
|
|
215
214
|
//# sourceMappingURL=cloudflare-queues.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { isStandardSchema, validateSchema } from "@velajs/vela/validation";
|
|
2
|
-
|
|
2
|
+
// src/queue-events/consume.ts
|
|
3
3
|
var QueueEventError = class extends Error {
|
|
4
4
|
code;
|
|
5
5
|
constructor(code, options) {
|
|
@@ -114,7 +114,6 @@ async function consumeQueueEvents(batch, options) {
|
|
|
114
114
|
}
|
|
115
115
|
if (failures.length > 0) throw new QueueEventsBatchError(failures);
|
|
116
116
|
}
|
|
117
|
-
//#endregion
|
|
118
117
|
export { QueueEventError, QueueEventsBatchError, consumeQueueEvents, defineQueueEvent };
|
|
119
118
|
|
|
120
119
|
//# sourceMappingURL=consume.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"consume.js","names":[],"sources":["../../src/queue-events/consume.ts"],"sourcesContent":["import { isStandardSchema, validateSchema, type StandardSchemaV1 } from '@velajs/vela/validation';\n\nexport interface QueueEvent<Payload = unknown> {\n readonly type: string;\n readonly source: Readonly<Record<string, unknown>> & { readonly type: string };\n readonly payload: Payload;\n readonly metadata: Readonly<Record<string, unknown>> & {\n readonly accountId: string;\n readonly eventSubscriptionId: string;\n readonly eventSchemaVersion: 1;\n readonly eventTimestamp: string;\n };\n}\n\n/** Native delivery identity, not a universal platform event ID or an idempotency guarantee. */\nexport interface QueueEventContext {\n readonly queue: string;\n readonly messageId: string;\n readonly timestamp: Date;\n readonly attempts: number;\n}\n\nexport type QueueEventErrorCode =\n | 'invalid-envelope'\n | 'unsupported-version'\n | 'unexpected-account'\n | 'unexpected-subscription'\n | 'unhandled-type'\n | 'unexpected-source'\n | 'invalid-payload'\n | 'handler-failed';\n\nexport class QueueEventError extends Error {\n constructor(\n readonly code: QueueEventErrorCode,\n options?: ErrorOptions,\n ) {\n super(`Queue event ${code}`, options);\n this.name = 'QueueEventError';\n }\n}\n\nexport interface QueueEventFailure {\n readonly messageId: string;\n readonly error: QueueEventError;\n}\n\n/** Successful siblings are already acknowledged; failures have requested native retries. */\nexport class QueueEventsBatchError extends AggregateError {\n constructor(readonly failures: readonly QueueEventFailure[]) {\n super(\n failures.map(({ error }) => error),\n `${failures.length} queue event(s) failed`,\n );\n this.name = 'QueueEventsBatchError';\n }\n}\n\nexport interface QueueEventOptions<Payload> {\n /** The full documented event type, for example cf.workersBuilds.worker.build.succeeded. */\n readonly type: string;\n /** Exact matches for source.type and any source selectors required by the application. */\n readonly source: Readonly<Record<string, string>> & { readonly type: string };\n readonly schema: StandardSchemaV1<unknown, Payload>;\n readonly handle: (event: QueueEvent<Payload>, context: QueueEventContext) => void | Promise<void>;\n}\n\nconst dispatch = Symbol('queue-event-dispatch');\n\n/** Created with defineQueueEvent so each heterogeneous payload retains its validated type. */\nexport interface QueueEventHandler {\n readonly type: string;\n readonly [dispatch]: (event: QueueEvent, context: QueueEventContext) => Promise<void>;\n}\n\nfunction nonempty(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0;\n}\n\n/** No module registration or global state: define handlers alongside their consuming provider. */\nexport function defineQueueEvent<Payload>(options: QueueEventOptions<Payload>): QueueEventHandler {\n if (\n !nonempty(options.type) ||\n !nonempty(options.source.type) ||\n !Object.values(options.source).every(nonempty)\n ) {\n throw new TypeError('Queue event type and source expectations must be nonempty strings');\n }\n if (!isStandardSchema(options.schema))\n throw new TypeError('Expected a Standard Schema validator');\n const { type, schema, handle } = options;\n const source = Object.entries(options.source);\n return Object.freeze({\n type,\n async [dispatch](event: QueueEvent, context: QueueEventContext) {\n if (!source.every(([key, value]) => event.source[key] === value)) {\n throw new QueueEventError('unexpected-source');\n }\n let payload: Payload;\n try {\n payload = await validateSchema(schema, event.payload);\n } catch (cause) {\n throw new QueueEventError('invalid-payload', { cause });\n }\n try {\n await handle({ ...event, payload }, context);\n } catch (cause) {\n throw new QueueEventError('handler-failed', { cause });\n }\n },\n });\n}\n\nexport interface ConsumeQueueEventsOptions {\n /** Dedicated physical queue name, also claimed by @QueueConsumer. */\n readonly queue: string;\n readonly accountId: string;\n readonly eventSubscriptionIds: readonly string[];\n /** One handler per exact event type; each may require source selectors. */\n readonly handlers: readonly QueueEventHandler[];\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction parseEvent(value: unknown): QueueEvent {\n if (\n !record(value) ||\n !nonempty(value.type) ||\n !record(value.source) ||\n !nonempty(value.source.type) ||\n !Object.hasOwn(value, 'payload') ||\n !record(value.metadata)\n ) {\n throw new QueueEventError('invalid-envelope');\n }\n const { source, metadata } = value;\n if (\n !nonempty(metadata.accountId) ||\n !nonempty(metadata.eventSubscriptionId) ||\n !Number.isInteger(metadata.eventSchemaVersion) ||\n !nonempty(metadata.eventTimestamp) ||\n !/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/.test(\n metadata.eventTimestamp,\n ) ||\n !Number.isFinite(Date.parse(metadata.eventTimestamp)) ||\n // Date.parse normalizes impossible dates such as February 30. Reject those too.\n new Date(metadata.eventTimestamp.slice(0, 10)).toISOString().slice(0, 10) !==\n metadata.eventTimestamp.slice(0, 10)\n ) {\n throw new QueueEventError('invalid-envelope');\n }\n if (metadata.eventSchemaVersion !== 1) throw new QueueEventError('unsupported-version');\n return {\n type: value.type,\n source: { ...source, type: value.source.type },\n payload: value.payload,\n metadata: {\n ...metadata,\n accountId: metadata.accountId,\n eventSubscriptionId: metadata.eventSubscriptionId,\n eventSchemaVersion: 1,\n eventTimestamp: metadata.eventTimestamp,\n },\n };\n}\n\n/**\n * Await each validated handler, then acknowledge that message. Every malformed,\n * unmatched or failing message requests retry; all siblings are attempted before\n * throwing QueueEventsBatchError. Cloudflare owns retry limits, delays and DLQ routing.\n * Do not acknowledge the batch elsewhere or convert these bodies into Vela jobs.\n */\nexport async function consumeQueueEvents(\n batch: MessageBatch<unknown>,\n options: ConsumeQueueEventsOptions,\n): Promise<void> {\n if (\n !nonempty(options.queue) ||\n !nonempty(options.accountId) ||\n options.eventSubscriptionIds.length === 0 ||\n !options.eventSubscriptionIds.every(nonempty)\n ) {\n throw new TypeError('Expected a physical queue, account and nonempty subscription allowlist');\n }\n if (batch.queue !== options.queue)\n throw new Error('Unexpected physical queue for platform events');\n const handlers = new Map<string, QueueEventHandler>();\n for (const handler of options.handlers) {\n if (handlers.has(handler.type))\n throw new TypeError(`Duplicate queue event handler: ${handler.type}`);\n handlers.set(handler.type, handler);\n }\n const accountId = options.accountId;\n const subscriptions = new Set(options.eventSubscriptionIds);\n const failures: QueueEventFailure[] = [];\n for (const message of batch.messages) {\n try {\n const event = parseEvent(message.body);\n if (event.metadata.accountId !== accountId) throw new QueueEventError('unexpected-account');\n if (!subscriptions.has(event.metadata.eventSubscriptionId))\n throw new QueueEventError('unexpected-subscription');\n const handler = handlers.get(event.type);\n if (!handler) throw new QueueEventError('unhandled-type');\n await handler[dispatch](event, {\n queue: batch.queue,\n messageId: message.id,\n timestamp: message.timestamp,\n attempts: message.attempts,\n });\n } catch (error) {\n message.retry();\n failures.push({\n messageId: message.id,\n error:\n error instanceof QueueEventError\n ? error\n : new QueueEventError('handler-failed', { cause: error }),\n });\n continue;\n }\n message.ack();\n }\n if (failures.length > 0) throw new QueueEventsBatchError(failures);\n}\n"],"mappings":";;AAgCA,IAAa,kBAAb,cAAqC,MAAM;CAE9B;CADX,YACE,MACA,SACA;EACA,MAAM,eAAe,QAAQ,OAAO;EAH3B,KAAA,OAAA;EAIT,KAAK,OAAO;CACd;AACF;;AAQA,IAAa,wBAAb,cAA2C,eAAe;CACnC;CAArB,YAAY,UAAiD;EAC3D,MACE,SAAS,KAAK,EAAE,YAAY,KAAK,GACjC,GAAG,SAAS,OAAO,uBACrB;EAJmB,KAAA,WAAA;EAKnB,KAAK,OAAO;CACd;AACF;AAWA,MAAM,WAAW,OAAO,sBAAsB;AAQ9C,SAAS,SAAS,OAAiC;CACjD,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,SAAS;AAC5D;;AAGA,SAAgB,iBAA0B,SAAwD;CAChG,IACE,CAAC,SAAS,QAAQ,IAAI,KACtB,CAAC,SAAS,QAAQ,OAAO,IAAI,KAC7B,CAAC,OAAO,OAAO,QAAQ,MAAM,CAAC,CAAC,MAAM,QAAQ,GAE7C,MAAM,IAAI,UAAU,mEAAmE;CAEzF,IAAI,CAAC,iBAAiB,QAAQ,MAAM,GAClC,MAAM,IAAI,UAAU,sCAAsC;CAC5D,MAAM,EAAE,MAAM,QAAQ,WAAW;CACjC,MAAM,SAAS,OAAO,QAAQ,QAAQ,MAAM;CAC5C,OAAO,OAAO,OAAO;EACnB;EACA,OAAO,UAAU,OAAmB,SAA4B;GAC9D,IAAI,CAAC,OAAO,OAAO,CAAC,KAAK,WAAW,MAAM,OAAO,SAAS,KAAK,GAC7D,MAAM,IAAI,gBAAgB,mBAAmB;GAE/C,IAAI;GACJ,IAAI;IACF,UAAU,M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,QACA,IAAI,gBAAgB,kBAAkB,EAAE,OAAO,MAAM,CAAC;GAC9D,CAAC;GACD;EACF;EACA,QAAQ,IAAI;CACd;CACA,IAAI,SAAS,SAAS,GAAG,MAAM,IAAI,sBAAsB,QAAQ;AACnE"}
|
|
1
|
+
{"version":3,"file":"consume.js","names":[],"sources":["../../src/queue-events/consume.ts"],"sourcesContent":["import { isStandardSchema, validateSchema, type StandardSchemaV1 } from '@velajs/vela/validation';\n\nexport interface QueueEvent<Payload = unknown> {\n readonly type: string;\n readonly source: Readonly<Record<string, unknown>> & { readonly type: string };\n readonly payload: Payload;\n readonly metadata: Readonly<Record<string, unknown>> & {\n readonly accountId: string;\n readonly eventSubscriptionId: string;\n readonly eventSchemaVersion: 1;\n readonly eventTimestamp: string;\n };\n}\n\n/** Native delivery identity, not a universal platform event ID or an idempotency guarantee. */\nexport interface QueueEventContext {\n readonly queue: string;\n readonly messageId: string;\n readonly timestamp: Date;\n readonly attempts: number;\n}\n\nexport type QueueEventErrorCode =\n | 'invalid-envelope'\n | 'unsupported-version'\n | 'unexpected-account'\n | 'unexpected-subscription'\n | 'unhandled-type'\n | 'unexpected-source'\n | 'invalid-payload'\n | 'handler-failed';\n\nexport class QueueEventError extends Error {\n constructor(\n readonly code: QueueEventErrorCode,\n options?: ErrorOptions,\n ) {\n super(`Queue event ${code}`, options);\n this.name = 'QueueEventError';\n }\n}\n\nexport interface QueueEventFailure {\n readonly messageId: string;\n readonly error: QueueEventError;\n}\n\n/** Successful siblings are already acknowledged; failures have requested native retries. */\nexport class QueueEventsBatchError extends AggregateError {\n constructor(readonly failures: readonly QueueEventFailure[]) {\n super(\n failures.map(({ error }) => error),\n `${failures.length} queue event(s) failed`,\n );\n this.name = 'QueueEventsBatchError';\n }\n}\n\nexport interface QueueEventOptions<Payload> {\n /** The full documented event type, for example cf.workersBuilds.worker.build.succeeded. */\n readonly type: string;\n /** Exact matches for source.type and any source selectors required by the application. */\n readonly source: Readonly<Record<string, string>> & { readonly type: string };\n readonly schema: StandardSchemaV1<unknown, Payload>;\n readonly handle: (event: QueueEvent<Payload>, context: QueueEventContext) => void | Promise<void>;\n}\n\nconst dispatch = Symbol('queue-event-dispatch');\n\n/** Created with defineQueueEvent so each heterogeneous payload retains its validated type. */\nexport interface QueueEventHandler {\n readonly type: string;\n readonly [dispatch]: (event: QueueEvent, context: QueueEventContext) => Promise<void>;\n}\n\nfunction nonempty(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0;\n}\n\n/** No module registration or global state: define handlers alongside their consuming provider. */\nexport function defineQueueEvent<Payload>(options: QueueEventOptions<Payload>): QueueEventHandler {\n if (\n !nonempty(options.type) ||\n !nonempty(options.source.type) ||\n !Object.values(options.source).every(nonempty)\n ) {\n throw new TypeError('Queue event type and source expectations must be nonempty strings');\n }\n if (!isStandardSchema(options.schema))\n throw new TypeError('Expected a Standard Schema validator');\n const { type, schema, handle } = options;\n const source = Object.entries(options.source);\n return Object.freeze({\n type,\n async [dispatch](event: QueueEvent, context: QueueEventContext) {\n if (!source.every(([key, value]) => event.source[key] === value)) {\n throw new QueueEventError('unexpected-source');\n }\n let payload: Payload;\n try {\n payload = await validateSchema(schema, event.payload);\n } catch (cause) {\n throw new QueueEventError('invalid-payload', { cause });\n }\n try {\n await handle({ ...event, payload }, context);\n } catch (cause) {\n throw new QueueEventError('handler-failed', { cause });\n }\n },\n });\n}\n\nexport interface ConsumeQueueEventsOptions {\n /** Dedicated physical queue name, also claimed by @QueueConsumer. */\n readonly queue: string;\n readonly accountId: string;\n readonly eventSubscriptionIds: readonly string[];\n /** One handler per exact event type; each may require source selectors. */\n readonly handlers: readonly QueueEventHandler[];\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction parseEvent(value: unknown): QueueEvent {\n if (\n !record(value) ||\n !nonempty(value.type) ||\n !record(value.source) ||\n !nonempty(value.source.type) ||\n !Object.hasOwn(value, 'payload') ||\n !record(value.metadata)\n ) {\n throw new QueueEventError('invalid-envelope');\n }\n const { source, metadata } = value;\n if (\n !nonempty(metadata.accountId) ||\n !nonempty(metadata.eventSubscriptionId) ||\n !Number.isInteger(metadata.eventSchemaVersion) ||\n !nonempty(metadata.eventTimestamp) ||\n !/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/.test(\n metadata.eventTimestamp,\n ) ||\n !Number.isFinite(Date.parse(metadata.eventTimestamp)) ||\n // Date.parse normalizes impossible dates such as February 30. Reject those too.\n new Date(metadata.eventTimestamp.slice(0, 10)).toISOString().slice(0, 10) !==\n metadata.eventTimestamp.slice(0, 10)\n ) {\n throw new QueueEventError('invalid-envelope');\n }\n if (metadata.eventSchemaVersion !== 1) throw new QueueEventError('unsupported-version');\n return {\n type: value.type,\n source: { ...source, type: value.source.type },\n payload: value.payload,\n metadata: {\n ...metadata,\n accountId: metadata.accountId,\n eventSubscriptionId: metadata.eventSubscriptionId,\n eventSchemaVersion: 1,\n eventTimestamp: metadata.eventTimestamp,\n },\n };\n}\n\n/**\n * Await each validated handler, then acknowledge that message. Every malformed,\n * unmatched or failing message requests retry; all siblings are attempted before\n * throwing QueueEventsBatchError. Cloudflare owns retry limits, delays and DLQ routing.\n * Do not acknowledge the batch elsewhere or convert these bodies into Vela jobs.\n */\nexport async function consumeQueueEvents(\n batch: MessageBatch<unknown>,\n options: ConsumeQueueEventsOptions,\n): Promise<void> {\n if (\n !nonempty(options.queue) ||\n !nonempty(options.accountId) ||\n options.eventSubscriptionIds.length === 0 ||\n !options.eventSubscriptionIds.every(nonempty)\n ) {\n throw new TypeError('Expected a physical queue, account and nonempty subscription allowlist');\n }\n if (batch.queue !== options.queue)\n throw new Error('Unexpected physical queue for platform events');\n const handlers = new Map<string, QueueEventHandler>();\n for (const handler of options.handlers) {\n if (handlers.has(handler.type))\n throw new TypeError(`Duplicate queue event handler: ${handler.type}`);\n handlers.set(handler.type, handler);\n }\n const accountId = options.accountId;\n const subscriptions = new Set(options.eventSubscriptionIds);\n const failures: QueueEventFailure[] = [];\n for (const message of batch.messages) {\n try {\n const event = parseEvent(message.body);\n if (event.metadata.accountId !== accountId) throw new QueueEventError('unexpected-account');\n if (!subscriptions.has(event.metadata.eventSubscriptionId))\n throw new QueueEventError('unexpected-subscription');\n const handler = handlers.get(event.type);\n if (!handler) throw new QueueEventError('unhandled-type');\n await handler[dispatch](event, {\n queue: batch.queue,\n messageId: message.id,\n timestamp: message.timestamp,\n attempts: message.attempts,\n });\n } catch (error) {\n message.retry();\n failures.push({\n messageId: message.id,\n error:\n error instanceof QueueEventError\n ? error\n : new QueueEventError('handler-failed', { cause: error }),\n });\n continue;\n }\n message.ack();\n }\n if (failures.length > 0) throw new QueueEventsBatchError(failures);\n}\n"],"mappings":";;AAgCA,IAAa,kBAAb,cAAqC,MAAM;CAE9B;CADX,YACW,MACT,SACA;EACA,MAAM,eAAe,QAAQ,OAAO;EAH3B,KAAA,OAAA;EAIT,KAAK,OAAO;CACd;AACF;;AAQA,IAAa,wBAAb,cAA2C,eAAe;CACnC;CAArB,YAAqB,UAAwC;EAC3D,MACE,SAAS,KAAK,EAAE,YAAY,KAAK,GACjC,GAAG,SAAS,OAAO,uBACrB;EAJmB,KAAA,WAAA;EAKnB,KAAK,OAAO;CACd;AACF;AAWA,MAAM,WAAW,OAAO,sBAAsB;AAQ9C,SAAS,SAAS,OAAiC;CACjD,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,SAAS;AAC5D;;AAGA,SAAgB,iBAA0B,SAAwD;CAChG,IACE,CAAC,SAAS,QAAQ,IAAI,KACtB,CAAC,SAAS,QAAQ,OAAO,IAAI,KAC7B,CAAC,OAAO,OAAO,QAAQ,MAAM,CAAC,CAAC,MAAM,QAAQ,GAE7C,MAAM,IAAI,UAAU,mEAAmE;CAEzF,IAAI,CAAC,iBAAiB,QAAQ,MAAM,GAClC,MAAM,IAAI,UAA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UAAU,SAAS,IAAI,MAAM,IAAI;GACvC,IAAI,CAAC,SAAS,MAAM,IAAI,gBAAgB,gBAAgB;GACxD,MAAM,QAAQ,SAAS,CAAC,OAAO;IAC7B,OAAO,MAAM;IACb,WAAW,QAAQ;IACnB,WAAW,QAAQ;IACnB,UAAU,QAAQ;GACpB,CAAC;EACH,SAAS,OAAO;GACd,QAAQ,MAAM;GACd,SAAS,KAAK;IACZ,WAAW,QAAQ;IACnB,OACE,iBAAiB,kBACb,QACA,IAAI,gBAAgB,kBAAkB,EAAE,OAAO,MAAM,CAAC;GAC9D,CAAC;GACD;EACF;EACA,QAAQ,IAAI;CACd;CACA,IAAI,SAAS,SAAS,GAAG,MAAM,IAAI,sBAAsB,QAAQ;AACnE"}
|
package/dist/queue-events.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
/** Validated platform event subscriptions inside an existing native @QueueConsumer. */
|
|
1
2
|
import { StandardSchemaV1 } from "@velajs/vela/validation";
|
|
2
|
-
//#region src/queue-events/consume.d.ts
|
|
3
3
|
interface QueueEvent<Payload = unknown> {
|
|
4
4
|
readonly type: string;
|
|
5
5
|
readonly source: Readonly<Record<string, unknown>> & {
|
|
@@ -67,5 +67,4 @@ interface ConsumeQueueEventsOptions {
|
|
|
67
67
|
* Do not acknowledge the batch elsewhere or convert these bodies into Vela jobs.
|
|
68
68
|
*/
|
|
69
69
|
export declare function consumeQueueEvents(batch: MessageBatch<unknown>, options: ConsumeQueueEventsOptions): Promise<void>;
|
|
70
|
-
//#endregion
|
|
71
70
|
export type { ConsumeQueueEventsOptions, QueueEvent, QueueEventContext, QueueEventErrorCode, QueueEventFailure, QueueEventHandler, QueueEventOptions };
|
package/dist/queue-events.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { QueueEventError, QueueEventsBatchError, consumeQueueEvents, defineQueueEvent };
|
|
1
|
+
export { QueueEventError, QueueEventsBatchError, consumeQueueEvents, defineQueueEvent } from "./queue-events/consume.js";
|
package/dist/queues.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import "./vela-env-
|
|
1
|
+
import "./vela-env-5graXefc.js";
|
|
2
2
|
import { QueueDispatchResult, QueueDriverFactory, QueueJob, QueueMessageLike } from "@velajs/vela/queue";
|
|
3
|
-
//#region src/queue/cloudflare-queues.d.ts
|
|
4
3
|
/** The native producer surface the driver uses: a Wrangler `queues.producers` binding. */
|
|
5
4
|
interface CloudflareQueueProducer {
|
|
6
5
|
send(message: QueueJob, options?: QueueSendOptions): Promise<unknown>;
|
|
@@ -44,5 +43,4 @@ export declare function consumeQueueBatch(batch: {
|
|
|
44
43
|
readonly queue: string;
|
|
45
44
|
readonly messages: readonly QueueMessageLike[];
|
|
46
45
|
}, dispatch: (job: QueueJob, message: QueueMessageLike) => Promise<QueueDispatchResult | void>, options?: ConsumeQueueBatchOptions): Promise<void>;
|
|
47
|
-
//#endregion
|
|
48
46
|
export type { CloudflareQueueProducer, ConsumeQueueBatchOptions };
|
package/dist/queues.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { cloudflareQueues, consumeQueueBatch };
|
|
1
|
+
export { cloudflareQueues, consumeQueueBatch } from "./queue/cloudflare-queues.js";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { rateLimit } from "../bindings.js";
|
|
2
|
-
|
|
2
|
+
// src/rate-limit/cloudflare-rate-limit.store.ts
|
|
3
3
|
/** The periods a Rate Limiting binding supports, in milliseconds. */
|
|
4
4
|
const PERIODS = /* @__PURE__ */ new Set([1e4, 6e4]);
|
|
5
5
|
/**
|
|
@@ -73,7 +73,6 @@ function rateLimitStore(options) {
|
|
|
73
73
|
};
|
|
74
74
|
};
|
|
75
75
|
}
|
|
76
|
-
//#endregion
|
|
77
76
|
export { rateLimitStore };
|
|
78
77
|
|
|
79
78
|
//# sourceMappingURL=cloudflare-rate-limit.store.js.map
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { d1 } from "../bindings.js";
|
|
2
|
+
// src/rate-limit/d1-throttler.store.ts
|
|
3
|
+
const DEFAULT_TABLE = "vela_rate_limits";
|
|
4
|
+
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;
|
|
5
|
+
const PRUNE_ODDS = .01;
|
|
6
|
+
function tableName(table) {
|
|
7
|
+
const name = table ?? DEFAULT_TABLE;
|
|
8
|
+
if (!IDENTIFIER.test(name)) throw new TypeError(`Invalid throttler table name '${name}'`);
|
|
9
|
+
return name;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The statements that create the counter table and its expiry index, for a D1
|
|
13
|
+
* migration file (each one a complete statement; end them with `;`).
|
|
14
|
+
*/
|
|
15
|
+
function d1ThrottlerMigration(options = {}) {
|
|
16
|
+
const table = tableName(options.table);
|
|
17
|
+
return [`CREATE TABLE IF NOT EXISTS "${table}" ("key" TEXT PRIMARY KEY NOT NULL, "count" INTEGER NOT NULL, "reset_at" INTEGER NOT NULL) WITHOUT ROWID`, `CREATE INDEX IF NOT EXISTS "${table}_reset_at" ON "${table}" ("reset_at")`];
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* `ThrottlerModule` storage on D1, read from each application's `ENV` by name:
|
|
21
|
+
*
|
|
22
|
+
* ```ts
|
|
23
|
+
* ThrottlerModule.forRoot({
|
|
24
|
+
* throttlers: [{ name: 'login', ttl: 10 * 60_000, limit: 30 }],
|
|
25
|
+
* storage: d1ThrottlerStore({ binding: 'DB' }),
|
|
26
|
+
* })
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* Every count is one `INSERT … ON CONFLICT … RETURNING` statement: D1 runs it
|
|
30
|
+
* atomically on the database's primary, so all isolates and locations share
|
|
31
|
+
* one exact fixed-window counter per key, with windows of any length and
|
|
32
|
+
* `@Throttle()` overrides. Each counted request costs one D1 write, and about
|
|
33
|
+
* one in 100 also deletes up to `pruneBatch` ended windows. The store
|
|
34
|
+
* also reads and resets counters, which `FailureCounter` needs. Create the
|
|
35
|
+
* table with {@link d1ThrottlerMigration}.
|
|
36
|
+
*/
|
|
37
|
+
function d1ThrottlerStore(options) {
|
|
38
|
+
const table = tableName(options.table);
|
|
39
|
+
const maxKeyBytes = options.maxKeyBytes ?? 1024;
|
|
40
|
+
if (!Number.isSafeInteger(maxKeyBytes) || maxKeyBytes <= 0 || maxKeyBytes > 4096) throw new RangeError("maxKeyBytes must be between 1 and 4096");
|
|
41
|
+
const pruneBatch = options.pruneBatch ?? 100;
|
|
42
|
+
if (!Number.isSafeInteger(pruneBatch) || pruneBatch < 0 || pruneBatch > 1e4) throw new RangeError("pruneBatch must be an integer from 0 to 10000");
|
|
43
|
+
const database = d1({ binding: options.binding });
|
|
44
|
+
const encoder = new TextEncoder();
|
|
45
|
+
const quoted = `"${table}"`;
|
|
46
|
+
const countSql = `INSERT INTO ${quoted} ("key", "count", "reset_at") VALUES (?1, 1, ?2 + ?3) ON CONFLICT ("key") DO UPDATE SET "count" = CASE WHEN "reset_at" <= ?2 THEN 1 ELSE "count" + 1 END, "reset_at" = CASE WHEN "reset_at" <= ?2 THEN ?2 + ?3 ELSE "reset_at" END RETURNING "count", "reset_at"`;
|
|
47
|
+
const readSql = `SELECT "count", "reset_at" FROM ${quoted} WHERE "key" = ?1 AND "reset_at" > ?2`;
|
|
48
|
+
const resetSql = `DELETE FROM ${quoted} WHERE "key" = ?1`;
|
|
49
|
+
const pruneSql = `DELETE FROM ${quoted} WHERE "key" IN (SELECT "key" FROM ${quoted} WHERE "reset_at" <= ?1 LIMIT ?2)`;
|
|
50
|
+
const checkKey = (key) => {
|
|
51
|
+
if (typeof key !== "string" || key.length === 0 || /[\u0000-\u001f\u007f]/.test(key) || encoder.encode(key).byteLength > maxKeyBytes) throw new Error("Refusing an invalid or oversized rate-limit key");
|
|
52
|
+
};
|
|
53
|
+
const record = (row, now) => {
|
|
54
|
+
const count = typeof row === "object" && row !== null ? Reflect.get(row, "count") : void 0;
|
|
55
|
+
const resetAt = typeof row === "object" && row !== null ? Reflect.get(row, "reset_at") : void 0;
|
|
56
|
+
if (typeof count !== "number" || typeof resetAt !== "number") throw new Error("D1 throttler table returned an invalid counter");
|
|
57
|
+
return {
|
|
58
|
+
count,
|
|
59
|
+
ttlMs: Math.max(1, resetAt - now)
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
return (env) => {
|
|
63
|
+
const db = () => database(env);
|
|
64
|
+
const prune = async (limit = pruneBatch || 100) => {
|
|
65
|
+
if (!Number.isSafeInteger(limit) || limit < 1) throw new RangeError("prune limit must be positive");
|
|
66
|
+
return (await db().prepare(pruneSql).bind(Date.now(), limit).run()).meta.changes ?? 0;
|
|
67
|
+
};
|
|
68
|
+
return {
|
|
69
|
+
validate(throttlers) {
|
|
70
|
+
for (const { name, ttl } of throttlers) if (!Number.isSafeInteger(ttl) || ttl < 1) throw new Error(`Throttler '${name}' needs a positive whole-millisecond ttl`);
|
|
71
|
+
},
|
|
72
|
+
async increment(key, ttl) {
|
|
73
|
+
checkKey(key);
|
|
74
|
+
if (!Number.isSafeInteger(ttl) || ttl < 1) throw new Error("Rate-limit windows must be positive whole milliseconds");
|
|
75
|
+
const now = Date.now();
|
|
76
|
+
const row = await db().prepare(countSql).bind(key, now, ttl).first();
|
|
77
|
+
if (pruneBatch > 0 && Math.random() < PRUNE_ODDS) await prune(pruneBatch).catch(() => 0);
|
|
78
|
+
return record(row, now);
|
|
79
|
+
},
|
|
80
|
+
async get(key) {
|
|
81
|
+
checkKey(key);
|
|
82
|
+
const now = Date.now();
|
|
83
|
+
const row = await db().prepare(readSql).bind(key, now).first();
|
|
84
|
+
return row === null ? void 0 : record(row, now);
|
|
85
|
+
},
|
|
86
|
+
async reset(key) {
|
|
87
|
+
checkKey(key);
|
|
88
|
+
await db().prepare(resetSql).bind(key).run();
|
|
89
|
+
},
|
|
90
|
+
prune
|
|
91
|
+
};
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
export { d1ThrottlerMigration, d1ThrottlerStore };
|
|
95
|
+
|
|
96
|
+
//# sourceMappingURL=d1-throttler.store.js.map
|