@velajs/cloudflare 1.33.0 → 1.34.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 +23 -0
- package/README.md +198 -1
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js +9 -0
- package/dist/bindings.js +25 -1
- package/dist/bindings.js.map +1 -1
- package/dist/{cloudflare-application-CXDy9C1R.d.ts → cloudflare-application-Dsscb3Mo.d.ts} +2 -2
- package/dist/{cloudflare-factory-CuFNUJJD.d.ts → cloudflare-factory-DM9CBvNH.d.ts} +5 -5
- package/dist/durable-objects.d.ts +1 -1
- package/dist/email.d.ts +1 -1
- package/dist/entrypoints.d.ts +1 -1
- package/dist/index.d.ts +25 -10
- package/dist/index.js +2 -2
- package/dist/pipelines.d.ts +20 -0
- package/dist/pipelines.js +87 -0
- package/dist/pipelines.js.map +1 -0
- package/dist/queue-events/consume.js +120 -0
- package/dist/queue-events/consume.js.map +1 -0
- package/dist/queue-events.d.ts +71 -0
- package/dist/queue-events.js +2 -0
- package/dist/services/flagship-flag.driver.js +64 -6
- package/dist/services/flagship-flag.driver.js.map +1 -1
- package/dist/tail.d.ts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/tracing.d.ts +15 -0
- package/dist/tracing.js +24 -0
- package/dist/tracing.js.map +1 -0
- package/dist/workflows.d.ts +1 -1
- package/package.json +17 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.34.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 2c61e5b: Unify Wrangler binding discovery across resource addition, configuration sync and deployment checks. Cover current native binding shapes, detect cross-kind name collisions, respect environment inheritance exceptions, and preserve unknown configuration. Known malformed bindings now fail before resource creation or config edits.
|
|
8
|
+
|
|
9
|
+
Add `vela add binding <kind> <BINDING> --options <JSON>` for native JSON/JSONC declarations without provisioning resources or adding modules. Selected-environment type generation now calls Wrangler with `--env` instead of running an unqualified types script.
|
|
10
|
+
|
|
11
|
+
Expose `flagship({ binding })` and `secretsStoreSecret({ binding })` native references from `@velajs/cloudflare`, resolving the original handle separately for each environment without caching values.
|
|
12
|
+
- 3cc469d: Preserve native Flagship evaluation reasons, variants and error codes through optional driver detail methods and Studio responses. Value-only providers now report UNKNOWN instead of STATIC; native context accepts only scalar attributes, and route guards deny all evaluation errors. Existing object-validation callback signatures are unchanged.
|
|
13
|
+
|
|
14
|
+
Add the optional crypto/cloudflare SecretsStoreKeyProvider for immutable, versioned AES-KW key material, with explicit per-instance caching, refresh, retry and rotation using retained decryption keys. Secrets Store supplies material for local Web Crypto; it is not a remote KMS.
|
|
15
|
+
- 9ebb189: Add the optional `@velajs/cloudflare/queue-events` subpath for Cloudflare platform event subscriptions inside existing `@QueueConsumer` handlers. Validate the documented versioned envelope, source/account/subscription expectations and Standard Schema payloads before awaiting explicit handlers. Acknowledge each success individually and request native retries for malformed, unmatched or failing messages while preserving partial-batch progress and DLQ behavior. Include a Worker build example, native delivery identity, idempotency and producer trust guidance, and workerd coverage separate from signed Vela job dispatch.
|
|
16
|
+
- f1c7be8: Add the optional `@velajs/cloudflare/pipelines` writer with Standard Schema producer validation, schema transform inference, strict JSON snapshots, and UTF-8 ingestion payload limits. Validate the entire batch before awaiting one native stream send, preserving the configured binding and its ingestion-only guarantees.
|
|
17
|
+
|
|
18
|
+
### Patch Changes
|
|
19
|
+
|
|
20
|
+
- 5314b4e: Add the optional `/tracing` entrypoint with `CloudflareTracingInterceptor` for
|
|
21
|
+
native Workers spans around awaited HTTP and service RPC handler work. Span
|
|
22
|
+
names are fixed and labels contain only bounded class and method names.
|
|
23
|
+
- Updated dependencies [3cc469d]
|
|
24
|
+
- @velajs/feature-flags@1.32.0
|
|
25
|
+
|
|
3
26
|
## 1.33.0
|
|
4
27
|
|
|
5
28
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -287,6 +287,78 @@ handlers still need the idempotency appropriate to their delivery semantics.
|
|
|
287
287
|
See [execution scopes](../../docs/execution-scopes.md) for lifetime ownership,
|
|
288
288
|
stream boundaries, cancellation and optional transport integration.
|
|
289
289
|
|
|
290
|
+
## Native handler tracing
|
|
291
|
+
|
|
292
|
+
Import `CloudflareTracingInterceptor` from the optional
|
|
293
|
+
`@velajs/cloudflare/tracing` entrypoint and register it on HTTP controllers or
|
|
294
|
+
`VelaEntrypoint` hosts with `@UseInterceptors`. It uses the native
|
|
295
|
+
`cloudflare:workers` tracing API; the package root does not import it.
|
|
296
|
+
|
|
297
|
+
```ts
|
|
298
|
+
import { Controller, Get, Injectable, Module, UseInterceptors } from '@velajs/vela';
|
|
299
|
+
import { defineCloudflareApp } from '@velajs/cloudflare';
|
|
300
|
+
import { VelaEntrypoint } from '@velajs/cloudflare/entrypoints';
|
|
301
|
+
import { CloudflareTracingInterceptor } from '@velajs/cloudflare/tracing';
|
|
302
|
+
|
|
303
|
+
@Controller('/status')
|
|
304
|
+
@UseInterceptors(CloudflareTracingInterceptor)
|
|
305
|
+
class StatusController {
|
|
306
|
+
@Get()
|
|
307
|
+
async read() {
|
|
308
|
+
return { ready: true };
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
@Injectable()
|
|
313
|
+
@UseInterceptors(CloudflareTracingInterceptor)
|
|
314
|
+
class StatusHost {
|
|
315
|
+
async read() {
|
|
316
|
+
return { ready: true };
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
@Module({ controllers: [StatusController] })
|
|
321
|
+
class AppModule {}
|
|
322
|
+
|
|
323
|
+
const app = defineCloudflareApp(AppModule);
|
|
324
|
+
export class Status extends VelaEntrypoint(app, StatusHost, { rpc: ['read'] }) {}
|
|
325
|
+
export default app.worker;
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
Enable traces in Wrangler and choose an application sampling rate:
|
|
329
|
+
|
|
330
|
+
```toml
|
|
331
|
+
[observability.traces]
|
|
332
|
+
enabled = true
|
|
333
|
+
head_sampling_rate = 1
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
The interceptor calls `next.handle()` inside `tracing.enterSpan()` and returns
|
|
337
|
+
its promise. Native child spans and awaited platform calls run within that
|
|
338
|
+
callback's async context. Cloudflare owns sampling, span completion and export,
|
|
339
|
+
including its service RPC transport instrumentation. Unsampled calls still run
|
|
340
|
+
normally. Use a Workers runtime with the
|
|
341
|
+
[native custom-span API](https://developers.cloudflare.com/workers/observability/traces/custom-spans/).
|
|
342
|
+
|
|
343
|
+
Span names are fixed: `vela.http.handler` and `vela.rpc.handler`. Sampled spans
|
|
344
|
+
add only `vela.handler.class` and `vela.handler.method`, each limited to 128
|
|
345
|
+
characters. Symbol method names are omitted. Labels use runtime names, which
|
|
346
|
+
may change with minification. No request values, arguments, errors, identifiers,
|
|
347
|
+
HTTP status or outcome attributes are added by this interceptor. Other execution
|
|
348
|
+
kinds pass through without a span.
|
|
349
|
+
|
|
350
|
+
The span covers the handler and inner interceptors until their returned promise
|
|
351
|
+
settles. Guards and pipes run earlier; response streams, deferred work and scope
|
|
352
|
+
disposal can outlive it. This integration does not implement Vela's portable
|
|
353
|
+
`Telemetry` interface or expose parent selection, span IDs or trace-header
|
|
354
|
+
propagation. See [observability](../../docs/observability.md) for that separate API.
|
|
355
|
+
|
|
356
|
+
The workerd tests exercise nested HTTP/RPC and KV calls, concurrent environments,
|
|
357
|
+
errors and disabled sampling. They do not inspect exported span trees or assert
|
|
358
|
+
parent IDs. Inspect sampled traces with Wrangler's
|
|
359
|
+
[local tracing tools](https://developers.cloudflare.com/changelog/post/2026-08-04-local-tracing/)
|
|
360
|
+
when verifying the runtime's exported hierarchy.
|
|
361
|
+
|
|
290
362
|
## Typed provider factories
|
|
291
363
|
|
|
292
364
|
Bindings retain their full native API and generic parameters. There are no
|
|
@@ -316,6 +388,15 @@ Use native `env.DB`, `env.CACHE`, `env.FILES`, `env.JOBS`, `env.AI`,
|
|
|
316
388
|
(`@InjectEnv()`) and factories (`inject: [ENV]`); it works the same in HTTP,
|
|
317
389
|
queue, cron and Durable Object code.
|
|
318
390
|
|
|
391
|
+
## Platform event subscriptions
|
|
392
|
+
|
|
393
|
+
`@velajs/cloudflare/queue-events` composes inside `@QueueConsumer` to validate
|
|
394
|
+
Cloudflare event subscription envelopes and Standard Schema payloads. It awaits
|
|
395
|
+
explicit handlers, acknowledges each success and retries failed messages through
|
|
396
|
+
the native queue policy. Use a dedicated queue with trusted producer permissions;
|
|
397
|
+
metadata checks are not authentication and duplicate deliveries require consumer
|
|
398
|
+
idempotency. See the [Worker build example and settlement guide](../../docs/cloudflare-queue-events.md).
|
|
399
|
+
|
|
319
400
|
## Queues and cron
|
|
320
401
|
|
|
321
402
|
```ts
|
|
@@ -567,7 +648,8 @@ application that fails to start is logged to the console instead. See
|
|
|
567
648
|
## Bindings by name
|
|
568
649
|
|
|
569
650
|
Module options name a binding instead of holding it. `kv`, `r2`, `d1`,
|
|
570
|
-
`queue`, `durableObject`, `rateLimit
|
|
651
|
+
`queue`, `durableObject`, `rateLimit`, `workflow`, `flagship` and
|
|
652
|
+
`secretsStoreSecret` each take `{ binding }`, the name
|
|
571
653
|
declared in the Wrangler configuration, and read nothing when declared: calling
|
|
572
654
|
the reference with an application's `ENV` returns the typed native binding, or
|
|
573
655
|
fails naming the binding and the Wrangler key that declares it
|
|
@@ -575,6 +657,37 @@ fails naming the binding and the Wrangler key that declares it
|
|
|
575
657
|
The drivers and stores below are built on them, so one static module graph
|
|
576
658
|
serves every environment.
|
|
577
659
|
|
|
660
|
+
`flagship` returns the native `Flagship` handle, including typed value and detail
|
|
661
|
+
methods. `secretsStoreSecret` returns a native `SecretsStoreSecret` handle; call
|
|
662
|
+
`get()` to read its current value. References perform structural checks only:
|
|
663
|
+
they do not read secrets, evaluate flags, cache results, create resources or prove
|
|
664
|
+
remote availability. Native method errors and local-development behavior are
|
|
665
|
+
unchanged. Use current generated Wrangler types or Workers types containing
|
|
666
|
+
these native interfaces (validated with Wrangler 4.135.0 and Workers types
|
|
667
|
+
5.20260920.1).
|
|
668
|
+
|
|
669
|
+
```ts
|
|
670
|
+
import { flagship, secretsStoreSecret } from '@velajs/cloudflare';
|
|
671
|
+
|
|
672
|
+
const flags = flagship({ binding: 'FLAGS' });
|
|
673
|
+
const apiKey = secretsStoreSecret({ binding: 'API_KEY' });
|
|
674
|
+
|
|
675
|
+
// In request/application scope, using that application's environment:
|
|
676
|
+
async function readSettings(env: Env) {
|
|
677
|
+
const enabled = await flags(env).getBooleanValue('new-layout', false);
|
|
678
|
+
const key = await apiKey(env).get();
|
|
679
|
+
return { enabled, key };
|
|
680
|
+
}
|
|
681
|
+
```
|
|
682
|
+
|
|
683
|
+
Declare `FLAGS` under `flagship` with an `app_id`, and `API_KEY` under
|
|
684
|
+
`secrets_store_secrets` with a `store_id` and `secret_name`, separately for each
|
|
685
|
+
named environment. `vela add binding` can write those config declarations;
|
|
686
|
+
resource setup remains explicit. See Cloudflare's [Flagship binding API](https://developers.cloudflare.com/flagship/binding/)
|
|
687
|
+
and [Secrets Store Workers integration](https://developers.cloudflare.com/secrets-store/integrations/workers/)
|
|
688
|
+
for native methods and local setup. In particular, local Secrets Store values
|
|
689
|
+
are separate from production secrets.
|
|
690
|
+
|
|
578
691
|
## Rate limiting
|
|
579
692
|
|
|
580
693
|
`ThrottlerModule` from `@velajs/vela/throttler` counts through Workers Rate
|
|
@@ -724,6 +837,90 @@ it('processes a created todo', async () => {
|
|
|
724
837
|
|
|
725
838
|
The subpath is not part of any Worker bundle: import it from tests only.
|
|
726
839
|
|
|
840
|
+
## Validated Pipelines producers
|
|
841
|
+
|
|
842
|
+
`@velajs/cloudflare/pipelines` adds producer validation to a configured native
|
|
843
|
+
stream handle. It is an optional adapter subpath: there is no module, queue
|
|
844
|
+
driver, or replacement for the native Pipelines API.
|
|
845
|
+
|
|
846
|
+
Configure the stream in Wrangler and regenerate your environment types:
|
|
847
|
+
|
|
848
|
+
```jsonc
|
|
849
|
+
{
|
|
850
|
+
"pipelines": [{ "binding": "EVENT_STREAM", "stream": "<STREAM_ID>" }],
|
|
851
|
+
}
|
|
852
|
+
```
|
|
853
|
+
|
|
854
|
+
Use a Standard Schema validator whose **output** matches the deployed stream
|
|
855
|
+
schema. Synchronous and asynchronous transforms are supported; `send()` takes
|
|
856
|
+
schema **inputs** and sends the validated outputs:
|
|
857
|
+
|
|
858
|
+
```ts
|
|
859
|
+
import { ENV, InjectionToken, defineProvider } from '@velajs/vela';
|
|
860
|
+
import { createPipelinesWriter, type PipelinesWriter } from '@velajs/cloudflare/pipelines';
|
|
861
|
+
import { z } from 'zod';
|
|
862
|
+
|
|
863
|
+
const event = z.object({
|
|
864
|
+
id: z.string().min(1),
|
|
865
|
+
count: z.string().regex(/^\d+$/).transform(Number).pipe(z.number().int().nonnegative()),
|
|
866
|
+
});
|
|
867
|
+
|
|
868
|
+
export const EVENTS = new InjectionToken<PipelinesWriter<z.input<typeof event>>>('events');
|
|
869
|
+
|
|
870
|
+
// Add this provider to your application's providers. ENV and the writer belong
|
|
871
|
+
// to that application; do not capture a request's environment at module scope.
|
|
872
|
+
export const eventsProvider = defineProvider(EVENTS, {
|
|
873
|
+
inject: [ENV],
|
|
874
|
+
useFactory: (env) => createPipelinesWriter(env.EVENT_STREAM, { schema: event }),
|
|
875
|
+
});
|
|
876
|
+
|
|
877
|
+
// In a provider that injects EVENTS:
|
|
878
|
+
// await this.events.send([{ id: 'sample-1', count: '2' }]);
|
|
879
|
+
```
|
|
880
|
+
|
|
881
|
+
The factory also works directly with `createPipelinesWriter(env.EVENT_STREAM,
|
|
882
|
+
{ schema: event })`. The binding is structural (`send(records): Promise<void>`),
|
|
883
|
+
remains available as `env.EVENT_STREAM`, and needs no `cloudflare:pipelines`
|
|
884
|
+
runtime import. Generated `Pipeline<RecordType>` bindings check schema output
|
|
885
|
+
compatibility at compile time. Select the stream through trusted configuration;
|
|
886
|
+
the writer does not accept a stream name or endpoint from a record or request.
|
|
887
|
+
|
|
888
|
+
Each nonempty `send(records)` validates all records before making one native
|
|
889
|
+
call. A failure rejects without sending any records; validation may stop at the
|
|
890
|
+
first error. Standard Schema failures use `SchemaValidationError` from
|
|
891
|
+
`@velajs/vela/validation`, with the record index prefixed to each issue path.
|
|
892
|
+
Validator exceptions and native failures propagate. There is no automatic retry,
|
|
893
|
+
batch splitting, rate limiter, or buffering. Empty batches reject.
|
|
894
|
+
|
|
895
|
+
After schema transforms, each record must be a plain JSON object. Nested objects
|
|
896
|
+
and dense arrays may contain strings, booleans, null, and finite numbers. The
|
|
897
|
+
writer rejects undefined values (including explicitly undefined optional fields),
|
|
898
|
+
functions, symbols, bigint, non-finite numbers, cycles, class instances, `Date`,
|
|
899
|
+
`Map`, `Set`, typed arrays, getters, non-enumerable or symbol properties, extra
|
|
900
|
+
array properties, and `toJSON` functions. Convert special values in your schema.
|
|
901
|
+
Validated outputs are copied before the next asynchronous validation, so later
|
|
902
|
+
mutations cannot alter already checked records. Callers must not mutate inputs
|
|
903
|
+
while their schema is validating them.
|
|
904
|
+
|
|
905
|
+
The writer measures the UTF-8 encoding of compact JSON outputs, including escapes,
|
|
906
|
+
commas and array brackets, against a conservative **5,000,000-byte request
|
|
907
|
+
ceiling**. A single record must fit inside that same JSON array (at most
|
|
908
|
+
4,999,998 bytes). The current [Cloudflare limits](https://developers.cloudflare.com/pipelines/platform/limits/)
|
|
909
|
+
document 5 MB per ingestion request without a separate record size cap; this
|
|
910
|
+
adapter does not invent one. Oversize records or batches reject with `RangeError`;
|
|
911
|
+
non-JSON output rejects with `TypeError`.
|
|
912
|
+
|
|
913
|
+
`send()` resolves to `void` only after native ingestion acceptance. Cloudflare
|
|
914
|
+
[accepts but later drops invalid structured events](https://developers.cloudflare.com/pipelines/streams/writing-to-streams/#schema-validation),
|
|
915
|
+
so keep your producer schema aligned with the configured stream. Resolution
|
|
916
|
+
provides no query visibility, transaction, application exactly-once, or terminal
|
|
917
|
+
storage guarantee. A failed native request may have reached the service; any
|
|
918
|
+
retry and deduplication policy belongs to the application.
|
|
919
|
+
|
|
920
|
+
Tests cover producer behavior and native type compatibility. Workerd tests also
|
|
921
|
+
exercise Miniflare's local Pipelines binding, whose `send()` is a no-op; they
|
|
922
|
+
provide no remote ingestion, schema enforcement, or downstream storage proof.
|
|
923
|
+
|
|
727
924
|
## Development
|
|
728
925
|
|
|
729
926
|
From the repository root:
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
//#region \0@oxc-project+runtime@0.150.0/helpers/esm/decorate.js
|
|
2
|
+
function __decorate(decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
}
|
|
8
|
+
//#endregion
|
|
9
|
+
export { __decorate as default };
|
package/dist/bindings.js
CHANGED
|
@@ -87,7 +87,31 @@ function workflow(ref) {
|
|
|
87
87
|
accepts: (value) => hasOperations(value, ["create", "get"])
|
|
88
88
|
})(ref);
|
|
89
89
|
}
|
|
90
|
+
/** A native Flagship binding declared under `flagship`. No flag values are cached. */
|
|
91
|
+
const FLAGSHIP = {
|
|
92
|
+
name: "Flagship",
|
|
93
|
+
configKey: "flagship",
|
|
94
|
+
accepts: (value) => hasOperations(value, [
|
|
95
|
+
"get",
|
|
96
|
+
"getBooleanValue",
|
|
97
|
+
"getStringValue",
|
|
98
|
+
"getNumberValue",
|
|
99
|
+
"getObjectValue",
|
|
100
|
+
"getBooleanDetails",
|
|
101
|
+
"getStringDetails",
|
|
102
|
+
"getNumberDetails",
|
|
103
|
+
"getObjectDetails"
|
|
104
|
+
])
|
|
105
|
+
};
|
|
106
|
+
const flagship = /* @__PURE__ */ defineBinding(FLAGSHIP);
|
|
107
|
+
/** A secret handle declared under `secrets_store_secrets`; resolve its value with `get()`. */
|
|
108
|
+
const SECRETS_STORE_SECRET = {
|
|
109
|
+
name: "Secrets Store secret",
|
|
110
|
+
configKey: "secrets_store_secrets",
|
|
111
|
+
accepts: (value) => hasOperations(value, ["get"])
|
|
112
|
+
};
|
|
113
|
+
const secretsStoreSecret = /* @__PURE__ */ defineBinding(SECRETS_STORE_SECRET);
|
|
90
114
|
//#endregion
|
|
91
|
-
export { D1_DATABASE, DURABLE_OBJECT_NAMESPACE, KV_NAMESPACE, QUEUE_PRODUCER, R2_BUCKET, RATE_LIMITER, d1, durableObject, kv, queue, r2, rateLimit, workflow };
|
|
115
|
+
export { D1_DATABASE, DURABLE_OBJECT_NAMESPACE, FLAGSHIP, KV_NAMESPACE, QUEUE_PRODUCER, R2_BUCKET, RATE_LIMITER, SECRETS_STORE_SECRET, d1, durableObject, flagship, kv, queue, r2, rateLimit, secretsStoreSecret, workflow };
|
|
92
116
|
|
|
93
117
|
//# sourceMappingURL=bindings.js.map
|
package/dist/bindings.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindings.js","names":[],"sources":["../src/bindings.ts"],"sourcesContent":["import {\n defineBinding,\n type Binding,\n type BindingKind,\n type BindingRef,\n} from '@velajs/vela/module-kit';\n\n/** Whether a value exposes every named operation as a function. */\nfunction hasOperations(value: unknown, operations: readonly string[]): boolean {\n if (typeof value !== 'object' || value === null) return false;\n return operations.every((operation) => typeof Reflect.get(value, operation) === 'function');\n}\n\n/**\n * Name-based Workers binding factories. Each takes `{ binding }`, the name\n * declared in the Wrangler configuration, and returns a reference that reads\n * and validates the native binding from an application's `ENV` when called.\n * Declaring one reads no environment, so references belong in static module\n * options: `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }) })`.\n */\n\n/** A KV namespace declared under `kv_namespaces`. */\nexport const KV_NAMESPACE: BindingKind<KVNamespace> = {\n name: 'KV namespace',\n configKey: 'kv_namespaces',\n accepts: (value): value is KVNamespace =>\n hasOperations(value, ['get', 'put', 'delete', 'list', 'getWithMetadata']),\n};\nexport const kv = /* @__PURE__ */ defineBinding(KV_NAMESPACE);\n\n/** An R2 bucket declared under `r2_buckets`. */\nexport const R2_BUCKET: BindingKind<R2Bucket> = {\n name: 'R2 bucket',\n configKey: 'r2_buckets',\n accepts: (value): value is R2Bucket =>\n hasOperations(value, ['get', 'put', 'head', 'delete', 'list', 'createMultipartUpload']),\n};\nexport const r2 = /* @__PURE__ */ defineBinding(R2_BUCKET);\n\n/** A D1 database declared under `d1_databases`. */\nexport const D1_DATABASE: BindingKind<D1Database> = {\n name: 'D1 database',\n configKey: 'd1_databases',\n accepts: (value): value is D1Database => hasOperations(value, ['prepare', 'batch', 'exec']),\n};\nexport const d1 = /* @__PURE__ */ defineBinding(D1_DATABASE);\n\n/** A queue producer declared under `queues.producers`. */\nexport const QUEUE_PRODUCER: BindingKind<Queue> = {\n name: 'queue producer',\n configKey: 'queues.producers',\n accepts: (value): value is Queue => hasOperations(value, ['send']),\n};\nexport const queue = /* @__PURE__ */ defineBinding(QUEUE_PRODUCER);\n\n/** A Durable Object namespace declared under `durable_objects.bindings`. */\nexport const DURABLE_OBJECT_NAMESPACE: BindingKind<DurableObjectNamespace> = {\n name: 'Durable Object namespace',\n configKey: 'durable_objects.bindings',\n accepts: (value): value is DurableObjectNamespace => hasOperations(value, ['idFromName', 'get']),\n};\nexport const durableObject = /* @__PURE__ */ defineBinding(DURABLE_OBJECT_NAMESPACE);\n\n/** A Workers Rate Limiting binding declared under `ratelimits`. */\nexport const RATE_LIMITER: BindingKind<RateLimit> = {\n name: 'rate limiter',\n configKey: 'ratelimits',\n accepts: (value): value is RateLimit => hasOperations(value, ['limit']),\n};\nexport const rateLimit = /* @__PURE__ */ defineBinding(RATE_LIMITER);\n\n/**\n * A reference to a Workflow binding declared under `workflows`, whose\n * instances take `Params`: for a class from `VelaWorkflow()`,\n * `workflow<WorkflowParams<SignupWorkflow>>({ binding: 'SIGNUP_WORKFLOW' })`.\n * Called with an application's ENV, it returns the native binding typed with\n * those params: `await signups(env).create({ params: { email } })`. The\n * runtime checks that the binding is a Workflow; its params are what the\n * Workflow class declares.\n */\nexport function workflow<Params = unknown>(ref: BindingRef): Binding<Workflow<Params>> {\n return defineBinding<Workflow<Params>>({\n name: 'Workflow',\n configKey: 'workflows',\n accepts: (value): value is Workflow<Params> => hasOperations(value, ['create', 'get']),\n })(ref);\n}\n"],"mappings":";;;AAQA,SAAS,cAAc,OAAgB,YAAwC;CAC7E,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,OAAO,WAAW,OAAO,cAAc,OAAO,QAAQ,IAAI,OAAO,SAAS,MAAM,UAAU;AAC5F;;;;;;;;;AAWA,MAAa,eAAyC;CACpD,MAAM;CACN,WAAW;CACX,UAAU,UACR,cAAc,OAAO;EAAC;EAAO;EAAO;EAAU;EAAQ;CAAiB,CAAC;AAC5E;AACA,MAAa,KAAqB,8BAAc,YAAY;;AAG5D,MAAa,YAAmC;CAC9C,MAAM;CACN,WAAW;CACX,UAAU,UACR,cAAc,OAAO;EAAC;EAAO;EAAO;EAAQ;EAAU;EAAQ;CAAuB,CAAC;AAC1F;AACA,MAAa,KAAqB,8BAAc,SAAS;;AAGzD,MAAa,cAAuC;CAClD,MAAM;CACN,WAAW;CACX,UAAU,UAA+B,cAAc,OAAO;EAAC;EAAW;EAAS;CAAM,CAAC;AAC5F;AACA,MAAa,KAAqB,8BAAc,WAAW;;AAG3D,MAAa,iBAAqC;CAChD,MAAM;CACN,WAAW;CACX,UAAU,UAA0B,cAAc,OAAO,CAAC,MAAM,CAAC;AACnE;AACA,MAAa,QAAwB,8BAAc,cAAc;;AAGjE,MAAa,2BAAgE;CAC3E,MAAM;CACN,WAAW;CACX,UAAU,UAA2C,cAAc,OAAO,CAAC,cAAc,KAAK,CAAC;AACjG;AACA,MAAa,gBAAgC,8BAAc,wBAAwB;;AAGnF,MAAa,eAAuC;CAClD,MAAM;CACN,WAAW;CACX,UAAU,UAA8B,cAAc,OAAO,CAAC,OAAO,CAAC;AACxE;AACA,MAAa,YAA4B,8BAAc,YAAY;;;;;;;;;;AAWnE,SAAgB,SAA2B,KAA4C;CACrF,OAAO,cAAgC;EACrC,MAAM;EACN,WAAW;EACX,UAAU,UAAqC,cAAc,OAAO,CAAC,UAAU,KAAK,CAAC;CACvF,CAAC,CAAC,CAAC,GAAG;AACR"}
|
|
1
|
+
{"version":3,"file":"bindings.js","names":[],"sources":["../src/bindings.ts"],"sourcesContent":["import {\n defineBinding,\n type Binding,\n type BindingKind,\n type BindingRef,\n} from '@velajs/vela/module-kit';\n\n/** Whether a value exposes every named operation as a function. */\nfunction hasOperations(value: unknown, operations: readonly string[]): boolean {\n if (typeof value !== 'object' || value === null) return false;\n return operations.every((operation) => typeof Reflect.get(value, operation) === 'function');\n}\n\n/**\n * Name-based Workers binding factories. Each takes `{ binding }`, the name\n * declared in the Wrangler configuration, and returns a reference that reads\n * and validates the native binding from an application's `ENV` when called.\n * Declaring one reads no environment, so references belong in static module\n * options: `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }) })`.\n */\n\n/** A KV namespace declared under `kv_namespaces`. */\nexport const KV_NAMESPACE: BindingKind<KVNamespace> = {\n name: 'KV namespace',\n configKey: 'kv_namespaces',\n accepts: (value): value is KVNamespace =>\n hasOperations(value, ['get', 'put', 'delete', 'list', 'getWithMetadata']),\n};\nexport const kv = /* @__PURE__ */ defineBinding(KV_NAMESPACE);\n\n/** An R2 bucket declared under `r2_buckets`. */\nexport const R2_BUCKET: BindingKind<R2Bucket> = {\n name: 'R2 bucket',\n configKey: 'r2_buckets',\n accepts: (value): value is R2Bucket =>\n hasOperations(value, ['get', 'put', 'head', 'delete', 'list', 'createMultipartUpload']),\n};\nexport const r2 = /* @__PURE__ */ defineBinding(R2_BUCKET);\n\n/** A D1 database declared under `d1_databases`. */\nexport const D1_DATABASE: BindingKind<D1Database> = {\n name: 'D1 database',\n configKey: 'd1_databases',\n accepts: (value): value is D1Database => hasOperations(value, ['prepare', 'batch', 'exec']),\n};\nexport const d1 = /* @__PURE__ */ defineBinding(D1_DATABASE);\n\n/** A queue producer declared under `queues.producers`. */\nexport const QUEUE_PRODUCER: BindingKind<Queue> = {\n name: 'queue producer',\n configKey: 'queues.producers',\n accepts: (value): value is Queue => hasOperations(value, ['send']),\n};\nexport const queue = /* @__PURE__ */ defineBinding(QUEUE_PRODUCER);\n\n/** A Durable Object namespace declared under `durable_objects.bindings`. */\nexport const DURABLE_OBJECT_NAMESPACE: BindingKind<DurableObjectNamespace> = {\n name: 'Durable Object namespace',\n configKey: 'durable_objects.bindings',\n accepts: (value): value is DurableObjectNamespace => hasOperations(value, ['idFromName', 'get']),\n};\nexport const durableObject = /* @__PURE__ */ defineBinding(DURABLE_OBJECT_NAMESPACE);\n\n/** A Workers Rate Limiting binding declared under `ratelimits`. */\nexport const RATE_LIMITER: BindingKind<RateLimit> = {\n name: 'rate limiter',\n configKey: 'ratelimits',\n accepts: (value): value is RateLimit => hasOperations(value, ['limit']),\n};\nexport const rateLimit = /* @__PURE__ */ defineBinding(RATE_LIMITER);\n\n/**\n * A reference to a Workflow binding declared under `workflows`, whose\n * instances take `Params`: for a class from `VelaWorkflow()`,\n * `workflow<WorkflowParams<SignupWorkflow>>({ binding: 'SIGNUP_WORKFLOW' })`.\n * Called with an application's ENV, it returns the native binding typed with\n * those params: `await signups(env).create({ params: { email } })`. The\n * runtime checks that the binding is a Workflow; its params are what the\n * Workflow class declares.\n */\nexport function workflow<Params = unknown>(ref: BindingRef): Binding<Workflow<Params>> {\n return defineBinding<Workflow<Params>>({\n name: 'Workflow',\n configKey: 'workflows',\n accepts: (value): value is Workflow<Params> => hasOperations(value, ['create', 'get']),\n })(ref);\n}\n\n/** A native Flagship binding declared under `flagship`. No flag values are cached. */\nexport const FLAGSHIP: BindingKind<Flagship> = {\n name: 'Flagship',\n configKey: 'flagship',\n accepts: (value): value is Flagship =>\n hasOperations(value, [\n 'get',\n 'getBooleanValue',\n 'getStringValue',\n 'getNumberValue',\n 'getObjectValue',\n 'getBooleanDetails',\n 'getStringDetails',\n 'getNumberDetails',\n 'getObjectDetails',\n ]),\n};\nexport const flagship = /* @__PURE__ */ defineBinding(FLAGSHIP);\n\n/** A secret handle declared under `secrets_store_secrets`; resolve its value with `get()`. */\nexport const SECRETS_STORE_SECRET: BindingKind<SecretsStoreSecret> = {\n name: 'Secrets Store secret',\n configKey: 'secrets_store_secrets',\n accepts: (value): value is SecretsStoreSecret => hasOperations(value, ['get']),\n};\nexport const secretsStoreSecret = /* @__PURE__ */ defineBinding(SECRETS_STORE_SECRET);\n"],"mappings":";;;AAQA,SAAS,cAAc,OAAgB,YAAwC;CAC7E,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,OAAO,WAAW,OAAO,cAAc,OAAO,QAAQ,IAAI,OAAO,SAAS,MAAM,UAAU;AAC5F;;;;;;;;;AAWA,MAAa,eAAyC;CACpD,MAAM;CACN,WAAW;CACX,UAAU,UACR,cAAc,OAAO;EAAC;EAAO;EAAO;EAAU;EAAQ;CAAiB,CAAC;AAC5E;AACA,MAAa,KAAqB,8BAAc,YAAY;;AAG5D,MAAa,YAAmC;CAC9C,MAAM;CACN,WAAW;CACX,UAAU,UACR,cAAc,OAAO;EAAC;EAAO;EAAO;EAAQ;EAAU;EAAQ;CAAuB,CAAC;AAC1F;AACA,MAAa,KAAqB,8BAAc,SAAS;;AAGzD,MAAa,cAAuC;CAClD,MAAM;CACN,WAAW;CACX,UAAU,UAA+B,cAAc,OAAO;EAAC;EAAW;EAAS;CAAM,CAAC;AAC5F;AACA,MAAa,KAAqB,8BAAc,WAAW;;AAG3D,MAAa,iBAAqC;CAChD,MAAM;CACN,WAAW;CACX,UAAU,UAA0B,cAAc,OAAO,CAAC,MAAM,CAAC;AACnE;AACA,MAAa,QAAwB,8BAAc,cAAc;;AAGjE,MAAa,2BAAgE;CAC3E,MAAM;CACN,WAAW;CACX,UAAU,UAA2C,cAAc,OAAO,CAAC,cAAc,KAAK,CAAC;AACjG;AACA,MAAa,gBAAgC,8BAAc,wBAAwB;;AAGnF,MAAa,eAAuC;CAClD,MAAM;CACN,WAAW;CACX,UAAU,UAA8B,cAAc,OAAO,CAAC,OAAO,CAAC;AACxE;AACA,MAAa,YAA4B,8BAAc,YAAY;;;;;;;;;;AAWnE,SAAgB,SAA2B,KAA4C;CACrF,OAAO,cAAgC;EACrC,MAAM;EACN,WAAW;EACX,UAAU,UAAqC,cAAc,OAAO,CAAC,UAAU,KAAK,CAAC;CACvF,CAAC,CAAC,CAAC,GAAG;AACR;;AAGA,MAAa,WAAkC;CAC7C,MAAM;CACN,WAAW;CACX,UAAU,UACR,cAAc,OAAO;EACnB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;AACL;AACA,MAAa,WAA2B,8BAAc,QAAQ;;AAG9D,MAAa,uBAAwD;CACnE,MAAM;CACN,WAAW;CACX,UAAU,UAAuC,cAAc,OAAO,CAAC,KAAK,CAAC;AAC/E;AACA,MAAa,qBAAqC,8BAAc,oBAAoB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CorsOptions, InjectionToken, VelaApplication, VelaEnv } from "@velajs/vela";
|
|
2
2
|
import "@velajs/vela/module-kit";
|
|
3
|
-
import { ExecutionContext } from "hono";
|
|
3
|
+
import { ExecutionContext as ExecutionContext$1 } from "hono";
|
|
4
4
|
//#region src/scheduled-event.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* The event a Worker's `scheduled()` export receives. The native
|
|
@@ -97,7 +97,7 @@ declare class CloudflareApplication {
|
|
|
97
97
|
#private;
|
|
98
98
|
readonly env: VelaEnv;
|
|
99
99
|
constructor(app: VelaApplication, env: VelaEnv);
|
|
100
|
-
readonly fetch: (request: Request, env: VelaEnv, ctx?: ExecutionContext) => Promise<Response>;
|
|
100
|
+
readonly fetch: (request: Request, env: VelaEnv, ctx?: ExecutionContext$1) => Promise<Response>;
|
|
101
101
|
getHonoApp(): ReturnType<VelaApplication['getHonoApp']>;
|
|
102
102
|
/**
|
|
103
103
|
* Resolve a provider from the application's DI container (delegates to
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { a as ScheduledEvent, t as CloudflareApplication } from "./cloudflare-application-
|
|
1
|
+
import { a as ScheduledEvent, t as CloudflareApplication } from "./cloudflare-application-Dsscb3Mo.js";
|
|
2
2
|
import { CorsOptions, DynamicModule, GlobalPrefixOptions, Type, VelaApplication, VelaCreateOptions, VelaEnv, VelaSecurityOptions, VersioningOptions } from "@velajs/vela";
|
|
3
3
|
import { RuntimeAdapter } from "@velajs/vela/module-kit";
|
|
4
|
-
import { ExecutionContext } from "hono";
|
|
4
|
+
import { ExecutionContext as ExecutionContext$1 } from "hono";
|
|
5
5
|
//#region src/root-module.d.ts
|
|
6
6
|
/**
|
|
7
7
|
* The root a Worker or Durable Object is built from: a module class or a
|
|
@@ -149,7 +149,7 @@ interface CloudflareWorkerDescriptor {
|
|
|
149
149
|
}
|
|
150
150
|
/** The exported handlers of a Worker entry (`defineCloudflareApp().worker`, `createCloudflareWorker()`). */
|
|
151
151
|
interface CloudflareWorker {
|
|
152
|
-
fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response>;
|
|
152
|
+
fetch(request: Request, env: VelaEnv, ctx: ExecutionContext$1): Promise<Response>;
|
|
153
153
|
scheduled(event: ScheduledEvent, env: VelaEnv, ctx?: {
|
|
154
154
|
waitUntil: (promise: Promise<unknown>) => void;
|
|
155
155
|
}): Promise<void>;
|
|
@@ -164,14 +164,14 @@ interface CloudflareWorker {
|
|
|
164
164
|
* `@velajs/cloudflare/email`: it runs the application's `@OnEmail()`
|
|
165
165
|
* handlers, and rejects a message none of them accepts.
|
|
166
166
|
*/
|
|
167
|
-
readonly email?: (message: ForwardableEmailMessage, env: VelaEnv, ctx?: ExecutionContext) => Promise<void>;
|
|
167
|
+
readonly email?: (message: ForwardableEmailMessage, env: VelaEnv, ctx?: ExecutionContext$1) => Promise<void>;
|
|
168
168
|
/**
|
|
169
169
|
* The Tail Workers handler, present once a module imports `OnTail` from
|
|
170
170
|
* `@velajs/cloudflare/tail`: it runs the application's `@OnTail()` handlers
|
|
171
171
|
* and never rejects, even when the application fails to start (the error is
|
|
172
172
|
* logged to the console, and the next batch retries).
|
|
173
173
|
*/
|
|
174
|
-
readonly tail?: (events: TraceItem[], env: VelaEnv, ctx?: ExecutionContext) => Promise<void>;
|
|
174
|
+
readonly tail?: (events: TraceItem[], env: VelaEnv, ctx?: ExecutionContext$1) => Promise<void>;
|
|
175
175
|
/**
|
|
176
176
|
* Symbol-keyed, so the platform, which reads string-keyed handlers, ignores
|
|
177
177
|
* it; enumerable, so `{ ...worker, email }` keeps it for the CLI.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./vela-env-DFvyoNT3.js";
|
|
2
|
-
import { a as CloudflareApp, y as CloudflareRoot } from "./cloudflare-factory-
|
|
2
|
+
import { a as CloudflareApp, y as CloudflareRoot } from "./cloudflare-factory-DM9CBvNH.js";
|
|
3
3
|
import { n as RpcMethods, t as RpcMethodOf } from "./host-members-DECj_4yz.js";
|
|
4
4
|
import { l as VelaDoPitrRpc, t as VelaNonceDurableObject } from "./nonce.durable-object-Bg1e0BMD.js";
|
|
5
5
|
import { DurableObject } from "cloudflare:workers";
|
package/dist/email.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./vela-env-DFvyoNT3.js";
|
|
2
|
-
import "./cloudflare-application-
|
|
2
|
+
import "./cloudflare-application-Dsscb3Mo.js";
|
|
3
3
|
import { EntrypointExecutionContext } from "@velajs/vela/module-kit";
|
|
4
4
|
//#region src/email/on-email.d.ts
|
|
5
5
|
/** Options of {@link OnEmail}. */
|
package/dist/entrypoints.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./vela-env-DFvyoNT3.js";
|
|
2
|
-
import { a as CloudflareApp } from "./cloudflare-factory-
|
|
2
|
+
import { a as CloudflareApp } from "./cloudflare-factory-DM9CBvNH.js";
|
|
3
3
|
import { n as RpcMethods, t as RpcMethodOf } from "./host-members-DECj_4yz.js";
|
|
4
4
|
import { WorkerEntrypoint } from "cloudflare:workers";
|
|
5
5
|
import { InjectionToken, Type, VelaEnv } from "@velajs/vela";
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import "./vela-env-DFvyoNT3.js";
|
|
2
|
-
import { a as ScheduledEvent, i as CloudflareScheduledEvent, n as MountOpenApiOptions, r as CLOUDFLARE_SCHEDULED_EVENT, t as CloudflareApplication } from "./cloudflare-application-
|
|
3
|
-
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-
|
|
2
|
+
import { a as ScheduledEvent, i as CloudflareScheduledEvent, n as MountOpenApiOptions, r as CLOUDFLARE_SCHEDULED_EVENT, t as CloudflareApplication } from "./cloudflare-application-Dsscb3Mo.js";
|
|
3
|
+
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-DM9CBvNH.js";
|
|
4
4
|
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-Bg1e0BMD.js";
|
|
5
5
|
import { DynamicModule, Type, VelaEnv } from "@velajs/vela";
|
|
6
6
|
import { Binding, BindingRef, EnvFactory, RuntimeAdapter } from "@velajs/vela/module-kit";
|
|
7
7
|
import { CommitStamp, CursorLog, InvalidationCommand, LiveDriver, LiveInvalidationSink, ResumeVerdict } from "@velajs/vela/live";
|
|
8
8
|
import { BroadcastCommand } from "@velajs/vela/websocket";
|
|
9
9
|
import { CacheEntry, CacheEntryReader, CacheEntryWriter, CacheInvalidationStore, CacheStore } from "@velajs/vela/cache";
|
|
10
|
-
import { FeatureFlagDriver, FlagContext } from "@velajs/feature-flags";
|
|
10
|
+
import { FeatureFlagDriver, FlagContext, FlagEvaluationDetails } from "@velajs/feature-flags";
|
|
11
11
|
import { ThrottlerStore } from "@velajs/vela/throttler";
|
|
12
12
|
import { NonceStore } from "@velajs/vela/security";
|
|
13
13
|
//#region src/websocket/room-id.d.ts
|
|
@@ -82,6 +82,8 @@ export declare const rateLimit: (ref: BindingRef) => Binding<RateLimit>;
|
|
|
82
82
|
* Workflow class declares.
|
|
83
83
|
*/
|
|
84
84
|
export declare function workflow<Params = unknown>(ref: BindingRef): Binding<Workflow<Params>>;
|
|
85
|
+
export declare const flagship: (ref: BindingRef) => Binding<Flagship>;
|
|
86
|
+
export declare const secretsStoreSecret: (ref: BindingRef) => Binding<SecretsStoreSecret>;
|
|
85
87
|
//#endregion
|
|
86
88
|
//#region src/services/kv-cache.store.d.ts
|
|
87
89
|
/** A KV namespace, or a function that reads it when an operation needs it. */
|
|
@@ -139,17 +141,24 @@ export declare function kvCacheInvalidation(ref: {
|
|
|
139
141
|
//#region src/services/flagship-flag.driver.d.ts
|
|
140
142
|
/**
|
|
141
143
|
* The subset of a Cloudflare **Flagship** binding this driver evaluates against
|
|
142
|
-
* —
|
|
144
|
+
* — typed value methods and optional evaluation details. The binding itself returns the supplied
|
|
143
145
|
* `defaultValue` on evaluation errors; transport-level failures reject and are
|
|
144
146
|
* left to propagate (never-throw is the service layer's job, not the driver's).
|
|
145
147
|
*
|
|
146
148
|
* @see https://developers.cloudflare.com/flagship/binding/
|
|
147
149
|
*/
|
|
150
|
+
type NativeFlagDetails<T> = Omit<FlagEvaluationDetails<T>, 'reason'> & {
|
|
151
|
+
reason?: string;
|
|
152
|
+
};
|
|
148
153
|
interface FlagshipBinding {
|
|
149
|
-
getBooleanValue(key: string, defaultValue: boolean, context?:
|
|
150
|
-
getStringValue(key: string, defaultValue: string, context?:
|
|
151
|
-
getNumberValue(key: string, defaultValue: number, context?:
|
|
152
|
-
getObjectValue(key: string, defaultValue: object, context?:
|
|
154
|
+
getBooleanValue(key: string, defaultValue: boolean, context?: Record<string, string | number | boolean>): Promise<boolean>;
|
|
155
|
+
getStringValue(key: string, defaultValue: string, context?: Record<string, string | number | boolean>): Promise<string>;
|
|
156
|
+
getNumberValue(key: string, defaultValue: number, context?: Record<string, string | number | boolean>): Promise<number>;
|
|
157
|
+
getObjectValue(key: string, defaultValue: object, context?: Record<string, string | number | boolean>): Promise<unknown>;
|
|
158
|
+
getBooleanDetails?(key: string, defaultValue: boolean, context?: Record<string, string | number | boolean>): Promise<NativeFlagDetails<boolean>>;
|
|
159
|
+
getStringDetails?(key: string, defaultValue: string, context?: Record<string, string | number | boolean>): Promise<NativeFlagDetails<string>>;
|
|
160
|
+
getNumberDetails?(key: string, defaultValue: number, context?: Record<string, string | number | boolean>): Promise<NativeFlagDetails<number>>;
|
|
161
|
+
getObjectDetails?(key: string, defaultValue: object, context?: Record<string, string | number | boolean>): Promise<NativeFlagDetails<unknown>>;
|
|
153
162
|
}
|
|
154
163
|
interface FlagshipFlagDriverOptions {
|
|
155
164
|
/** Driver name used for `use(name)` / default-driver selection. Default `"flagship"`. */
|
|
@@ -159,8 +168,9 @@ interface FlagshipFlagDriverOptions {
|
|
|
159
168
|
* {@link FeatureFlagDriver} backed by a Cloudflare Flagship binding.
|
|
160
169
|
*
|
|
161
170
|
* A thin, honest wrapper: each contract method maps 1:1 onto the binding's
|
|
162
|
-
* corresponding
|
|
163
|
-
* `defaultValue`) and evaluation context.
|
|
171
|
+
* corresponding native method, forwarding the caller's `fallback` (the binding's
|
|
172
|
+
* `defaultValue`) and validated scalar evaluation context. Optional detail methods
|
|
173
|
+
* preserve native reasons, variants and error codes; value-only bindings report UNKNOWN. The binding resolves the fallback on
|
|
164
174
|
* evaluation errors; anything the binding *rejects* with (e.g. a `remote: true`
|
|
165
175
|
* dev-proxy tunnel dropping) propagates — `@velajs/feature-flags`'s service owns
|
|
166
176
|
* the never-throw guarantee.
|
|
@@ -186,6 +196,11 @@ export declare class FlagshipFlagDriver implements FeatureFlagDriver {
|
|
|
186
196
|
getString(key: string, fallback: string, ctx?: FlagContext): Promise<string>;
|
|
187
197
|
getNumber(key: string, fallback: number, ctx?: FlagContext): Promise<number>;
|
|
188
198
|
getObject(key: string, fallback: object, ctx?: FlagContext): Promise<unknown>;
|
|
199
|
+
getBooleanDetails(key: string, fallback: boolean, ctx?: FlagContext): Promise<FlagEvaluationDetails<boolean>>;
|
|
200
|
+
getStringDetails(key: string, fallback: string, ctx?: FlagContext): Promise<FlagEvaluationDetails<string>>;
|
|
201
|
+
getNumberDetails(key: string, fallback: number, ctx?: FlagContext): Promise<FlagEvaluationDetails<number>>;
|
|
202
|
+
getObjectDetails(key: string, fallback: object, ctx?: FlagContext): Promise<FlagEvaluationDetails<unknown>>;
|
|
203
|
+
private details;
|
|
189
204
|
}
|
|
190
205
|
/** Convenience factory for {@link FlagshipFlagDriver}. */
|
|
191
206
|
export declare function flagshipFlagDriver(binding: FlagshipBinding | (() => FlagshipBinding), options?: FlagshipFlagDriverOptions): FlagshipFlagDriver;
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { durableObjectRoomName } from "./websocket/room-id.js";
|
|
2
2
|
import { CLOUDFLARE_SCHEDULED_EVENT } from "./scheduled-event.js";
|
|
3
3
|
import { CloudflareApplication } from "./cloudflare-application.js";
|
|
4
|
-
import { d1, durableObject, kv, queue, r2, rateLimit, workflow } from "./bindings.js";
|
|
4
|
+
import { d1, durableObject, flagship, kv, queue, r2, rateLimit, secretsStoreSecret, workflow } from "./bindings.js";
|
|
5
5
|
import { durableObjectLive } from "./websocket/live-driver.js";
|
|
6
6
|
import { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, defineCloudflareApp, isCloudflareApp } from "./cloudflare-factory.js";
|
|
7
7
|
import { EntrypointError, isEntrypointError } from "./rpc/entrypoint-error.js";
|
|
@@ -13,4 +13,4 @@ import { DoPitrUnavailableError, armDoPitr, isDoPitrUnavailable, readDoPitrBookm
|
|
|
13
13
|
import { DoCursorLog, liveInvalidateToRoom } from "./websocket/do-live.js";
|
|
14
14
|
import { rateLimitStore } from "./rate-limit/cloudflare-rate-limit.store.js";
|
|
15
15
|
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, flagshipFlagDriver, isCloudflareApp, isDoPitrUnavailable, isEntrypointError, kv, kvCache, kvCacheInvalidation, kvFlagDriver, liveInvalidateToRoom, queue, r2, rateLimit, rateLimitStore, readDoPitrBookmark, workflow };
|
|
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 };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { StandardSchemaV1 } from "@velajs/vela/validation";
|
|
2
|
+
//#region src/pipelines.d.ts
|
|
3
|
+
/** The native stream handle remains usable independently of the writer. */
|
|
4
|
+
export interface PipelinesBinding<Output = Record<string, unknown>> {
|
|
5
|
+
readonly send: (records: Output[]) => Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
export interface PipelinesWriter<Input> {
|
|
8
|
+
/** Validate the entire nonempty batch, then await one native ingestion request. */
|
|
9
|
+
send(records: readonly Input[]): Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Bind a Standard Schema producer to one trusted, configured stream. Schema
|
|
13
|
+
* outputs must fit the binding's record type; send() accepts schema inputs.
|
|
14
|
+
* Resolution means ingestion acceptance only, not downstream delivery or query
|
|
15
|
+
* visibility. There is no retry, splitting, buffering, or cross-writer state.
|
|
16
|
+
*/
|
|
17
|
+
export declare function createPipelinesWriter<S extends StandardSchemaV1<unknown, Record<string, unknown>>>(binding: PipelinesBinding<NoInfer<StandardSchemaV1.InferOutput<S>>>, { schema }: {
|
|
18
|
+
readonly schema: S;
|
|
19
|
+
}): PipelinesWriter<StandardSchemaV1.InferInput<S>>;
|
|
20
|
+
//#endregion
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { SchemaValidationError, isStandardSchema, parseSchemaAsync } from "@velajs/vela/validation";
|
|
2
|
+
//#region src/pipelines.ts
|
|
3
|
+
const MAX_BATCH_BYTES = 5e6;
|
|
4
|
+
const encoder = new TextEncoder();
|
|
5
|
+
/**
|
|
6
|
+
* Bind a Standard Schema producer to one trusted, configured stream. Schema
|
|
7
|
+
* outputs must fit the binding's record type; send() accepts schema inputs.
|
|
8
|
+
* Resolution means ingestion acceptance only, not downstream delivery or query
|
|
9
|
+
* visibility. There is no retry, splitting, buffering, or cross-writer state.
|
|
10
|
+
*/
|
|
11
|
+
function createPipelinesWriter(binding, { schema }) {
|
|
12
|
+
if (!binding || typeof binding.send !== "function") throw new TypeError("Pipelines requires a stream binding with send(records).");
|
|
13
|
+
if (!isStandardSchema(schema)) throw new TypeError("Pipelines requires a Standard Schema validator.");
|
|
14
|
+
return { async send(records) {
|
|
15
|
+
if (!Array.isArray(records) || records.length === 0) throw new TypeError("Pipelines requires a nonempty array of records.");
|
|
16
|
+
const inputs = [];
|
|
17
|
+
for (let index = 0; index < records.length; index++) {
|
|
18
|
+
const descriptor = Object.getOwnPropertyDescriptor(records, String(index));
|
|
19
|
+
if (!descriptor || !("value" in descriptor)) throw new TypeError(`Pipelines record ${index} must be an array element, not an accessor or hole.`);
|
|
20
|
+
inputs.push(descriptor.value);
|
|
21
|
+
}
|
|
22
|
+
const outputs = [];
|
|
23
|
+
let batchBytes = 2;
|
|
24
|
+
for (const [index, input] of inputs.entries()) {
|
|
25
|
+
let output;
|
|
26
|
+
try {
|
|
27
|
+
output = await parseSchemaAsync(schema, input);
|
|
28
|
+
} catch (error) {
|
|
29
|
+
if (error instanceof SchemaValidationError) throw new SchemaValidationError(error.issues.map((issue) => ({
|
|
30
|
+
...issue,
|
|
31
|
+
path: [index, ...issue.path ?? []]
|
|
32
|
+
})));
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
if (output === null || typeof output !== "object" || Array.isArray(output)) throw new TypeError(`Pipelines record ${index} must validate to a JSON object.`);
|
|
36
|
+
const snapshot = snapshotJson(output, [index], /* @__PURE__ */ new Set());
|
|
37
|
+
const bytes = encoder.encode(JSON.stringify(snapshot)).byteLength;
|
|
38
|
+
if (bytes > 4999998) throw new RangeError(`Pipelines record ${index} exceeds 4999998 JSON bytes.`);
|
|
39
|
+
batchBytes += bytes + (index === 0 ? 0 : 1);
|
|
40
|
+
if (batchBytes > MAX_BATCH_BYTES) throw new RangeError(`Pipelines batch exceeds ${MAX_BATCH_BYTES} JSON bytes.`);
|
|
41
|
+
outputs.push(snapshot);
|
|
42
|
+
}
|
|
43
|
+
await binding.send(outputs);
|
|
44
|
+
} };
|
|
45
|
+
}
|
|
46
|
+
function snapshotJson(value, path, ancestors) {
|
|
47
|
+
const invalid = (reason) => {
|
|
48
|
+
throw new TypeError(`Pipelines JSON value at ${JSON.stringify(path)} ${reason}.`);
|
|
49
|
+
};
|
|
50
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
51
|
+
if (typeof value === "number") {
|
|
52
|
+
if (!Number.isFinite(value)) invalid("must be finite");
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
if (typeof value !== "object") return invalid("is not representable");
|
|
56
|
+
if (ancestors.has(value)) return invalid("is circular");
|
|
57
|
+
const array = Array.isArray(value);
|
|
58
|
+
const prototype = Object.getPrototypeOf(value);
|
|
59
|
+
if (prototype !== null && prototype !== (array ? Array.prototype : Object.prototype)) return invalid("must use a plain object or array");
|
|
60
|
+
ancestors.add(value);
|
|
61
|
+
try {
|
|
62
|
+
const copy = array ? [] : {};
|
|
63
|
+
const keys = Reflect.ownKeys(value);
|
|
64
|
+
if (array && keys.length !== value.length + 1) return invalid("must be a dense array");
|
|
65
|
+
for (const key of keys) {
|
|
66
|
+
if (array && key === "length") continue;
|
|
67
|
+
if (typeof key !== "string") return invalid("cannot have symbol keys");
|
|
68
|
+
if (array && (!/^(0|[1-9]\d*)$/.test(key) || Number(key) >= value.length)) return invalid("cannot have extra array properties");
|
|
69
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
70
|
+
if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) return invalid("must contain only enumerable data properties");
|
|
71
|
+
const child = snapshotJson(descriptor.value, [...path, array ? Number(key) : key], ancestors);
|
|
72
|
+
Object.defineProperty(copy, key, {
|
|
73
|
+
value: child,
|
|
74
|
+
enumerable: true,
|
|
75
|
+
writable: true,
|
|
76
|
+
configurable: true
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
return copy;
|
|
80
|
+
} finally {
|
|
81
|
+
ancestors.delete(value);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
//#endregion
|
|
85
|
+
export { createPipelinesWriter };
|
|
86
|
+
|
|
87
|
+
//# sourceMappingURL=pipelines.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pipelines.js","names":[],"sources":["../src/pipelines.ts"],"sourcesContent":["import {\n isStandardSchema,\n parseSchemaAsync,\n SchemaValidationError,\n type StandardSchemaV1,\n} from '@velajs/vela/validation';\n\n/** The native stream handle remains usable independently of the writer. */\nexport interface PipelinesBinding<Output = Record<string, unknown>> {\n readonly send: (records: Output[]) => Promise<void>;\n}\n\nexport interface PipelinesWriter<Input> {\n /** Validate the entire nonempty batch, then await one native ingestion request. */\n send(records: readonly Input[]): Promise<void>;\n}\n\n// Current streams document 5 MB per ingestion request, without a separate record\n// cap. Use decimal MB conservatively, including JSON array brackets and commas.\n// https://developers.cloudflare.com/pipelines/platform/limits/\nconst MAX_BATCH_BYTES = 5_000_000;\nconst encoder = new TextEncoder();\n\n/**\n * Bind a Standard Schema producer to one trusted, configured stream. Schema\n * outputs must fit the binding's record type; send() accepts schema inputs.\n * Resolution means ingestion acceptance only, not downstream delivery or query\n * visibility. There is no retry, splitting, buffering, or cross-writer state.\n */\nexport function createPipelinesWriter<S extends StandardSchemaV1<unknown, Record<string, unknown>>>(\n binding: PipelinesBinding<NoInfer<StandardSchemaV1.InferOutput<S>>>,\n { schema }: { readonly schema: S },\n): PipelinesWriter<StandardSchemaV1.InferInput<S>> {\n if (!binding || typeof binding.send !== 'function') {\n throw new TypeError('Pipelines requires a stream binding with send(records).');\n }\n if (!isStandardSchema(schema)) {\n throw new TypeError('Pipelines requires a Standard Schema validator.');\n }\n\n return {\n async send(records) {\n if (!Array.isArray(records) || records.length === 0) {\n throw new TypeError('Pipelines requires a nonempty array of records.');\n }\n // Capture batch membership before the first asynchronous validation.\n const inputs: unknown[] = [];\n for (let index = 0; index < records.length; index++) {\n const descriptor = Object.getOwnPropertyDescriptor(records, String(index));\n if (!descriptor || !('value' in descriptor)) {\n throw new TypeError(\n `Pipelines record ${index} must be an array element, not an accessor or hole.`,\n );\n }\n inputs.push(descriptor.value);\n }\n\n const outputs: StandardSchemaV1.InferOutput<S>[] = [];\n let batchBytes = 2;\n for (const [index, input] of inputs.entries()) {\n let output: unknown;\n try {\n output = await parseSchemaAsync(schema, input);\n } catch (error) {\n if (error instanceof SchemaValidationError) {\n throw new SchemaValidationError(\n error.issues.map((issue) => ({ ...issue, path: [index, ...(issue.path ?? [])] })),\n );\n }\n throw error;\n }\n if (output === null || typeof output !== 'object' || Array.isArray(output)) {\n throw new TypeError(`Pipelines record ${index} must validate to a JSON object.`);\n }\n // Snapshot now: later async validators or callers may mutate earlier\n // outputs. The native send must receive exactly the JSON we checked.\n const snapshot = snapshotJson(output, [index], new Set());\n const bytes = encoder.encode(JSON.stringify(snapshot)).byteLength;\n if (bytes > MAX_BATCH_BYTES - 2) {\n throw new RangeError(\n `Pipelines record ${index} exceeds ${MAX_BATCH_BYTES - 2} JSON bytes.`,\n );\n }\n batchBytes += bytes + (index === 0 ? 0 : 1);\n if (batchBytes > MAX_BATCH_BYTES) {\n throw new RangeError(`Pipelines batch exceeds ${MAX_BATCH_BYTES} JSON bytes.`);\n }\n // The schema checked the shape; snapshotJson only copies JSON data and\n // rejects values JSON would silently drop or coerce.\n outputs.push(snapshot as StandardSchemaV1.InferOutput<S>);\n }\n await binding.send(outputs);\n },\n };\n}\n\nfunction snapshotJson(value: unknown, path: (string | number)[], ancestors: Set<object>): unknown {\n const invalid = (reason: string): never => {\n throw new TypeError(`Pipelines JSON value at ${JSON.stringify(path)} ${reason}.`);\n };\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) invalid('must be finite');\n return value;\n }\n if (typeof value !== 'object') return invalid('is not representable');\n if (ancestors.has(value)) return invalid('is circular');\n const array = Array.isArray(value);\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== null && prototype !== (array ? Array.prototype : Object.prototype)) {\n return invalid('must use a plain object or array');\n }\n ancestors.add(value);\n try {\n // Native RPC bindings require ordinary objects, including when the input\n // has a null prototype. Define own properties below to preserve __proto__.\n const copy: Record<string, unknown> | unknown[] = array ? [] : {};\n const keys = Reflect.ownKeys(value);\n if (array && keys.length !== value.length + 1) return invalid('must be a dense array');\n for (const key of keys) {\n if (array && key === 'length') continue;\n if (typeof key !== 'string') return invalid('cannot have symbol keys');\n if (array && (!/^(0|[1-9]\\d*)$/.test(key) || Number(key) >= value.length)) {\n return invalid('cannot have extra array properties');\n }\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (!descriptor || !('value' in descriptor) || !descriptor.enumerable) {\n return invalid('must contain only enumerable data properties');\n }\n const child = snapshotJson(descriptor.value, [...path, array ? Number(key) : key], ancestors);\n Object.defineProperty(copy, key, {\n value: child,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n return copy;\n } finally {\n ancestors.delete(value);\n }\n}\n"],"mappings":";;AAoBA,MAAM,kBAAkB;AACxB,MAAM,UAAU,IAAI,YAAY;;;;;;;AAQhC,SAAgB,sBACd,SACA,EAAE,UAC+C;CACjD,IAAI,CAAC,WAAW,OAAO,QAAQ,SAAS,YACtC,MAAM,IAAI,UAAU,yDAAyD;CAE/E,IAAI,CAAC,iBAAiB,MAAM,GAC1B,MAAM,IAAI,UAAU,iDAAiD;CAGvE,OAAO,EACL,MAAM,KAAK,SAAS;EAClB,IAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW,GAChD,MAAM,IAAI,UAAU,iDAAiD;EAGvE,MAAM,SAAoB,CAAC;EAC3B,KAAK,IAAI,QAAQ,GAAG,QAAQ,QAAQ,QAAQ,SAAS;GACnD,MAAM,aAAa,OAAO,yBAAyB,SAAS,OAAO,KAAK,CAAC;GACzE,IAAI,CAAC,cAAc,EAAE,WAAW,aAC9B,MAAM,IAAI,UACR,oBAAoB,MAAM,oDAC5B;GAEF,OAAO,KAAK,WAAW,KAAK;EAC9B;EAEA,MAAM,UAA6C,CAAC;EACpD,IAAI,aAAa;EACjB,KAAK,MAAM,CAAC,OAAO,UAAU,OAAO,QAAQ,GAAG;GAC7C,IAAI;GACJ,IAAI;IACF,SAAS,MAAM,iBAAiB,QAAQ,KAAK;GAC/C,SAAS,OAAO;IACd,IAAI,iBAAiB,uBACnB,MAAM,IAAI,sBACR,MAAM,OAAO,KAAK,WAAW;KAAE,GAAG;KAAO,MAAM,CAAC,OAAO,GAAI,MAAM,QAAQ,CAAC,CAAE;IAAE,EAAE,CAClF;IAEF,MAAM;GACR;GACA,IAAI,WAAW,QAAQ,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GACvE,MAAM,IAAI,UA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S,QAAQ,UAAU;GAC/B,IAAI,OAAO,QAAQ,UAAU,OAAO,QAAQ,yBAAyB;GACrE,IAAI,UAAU,CAAC,iBAAiB,KAAK,GAAG,KAAK,OAAO,GAAG,KAAK,MAAM,SAChE,OAAO,QAAQ,oCAAoC;GAErD,MAAM,aAAa,OAAO,yBAAyB,OAAO,GAAG;GAC7D,IAAI,CAAC,cAAc,EAAE,WAAW,eAAe,CAAC,WAAW,YACzD,OAAO,QAAQ,8CAA8C;GAE/D,MAAM,QAAQ,aAAa,WAAW,OAAO,CAAC,GAAG,MAAM,QAAQ,OAAO,GAAG,IAAI,GAAG,GAAG,SAAS;GAC5F,OAAO,eAAe,MAAM,KAAK;IAC/B,OAAO;IACP,YAAY;IACZ,UAAU;IACV,cAAc;GAChB,CAAC;EACH;EACA,OAAO;CACT,UAAU;EACR,UAAU,OAAO,KAAK;CACxB;AACF"}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { isStandardSchema, validateSchema } from "@velajs/vela/validation";
|
|
2
|
+
//#region src/queue-events/consume.ts
|
|
3
|
+
var QueueEventError = class extends Error {
|
|
4
|
+
code;
|
|
5
|
+
constructor(code, options) {
|
|
6
|
+
super(`Queue event ${code}`, options);
|
|
7
|
+
this.code = code;
|
|
8
|
+
this.name = "QueueEventError";
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
/** Successful siblings are already acknowledged; failures have requested native retries. */
|
|
12
|
+
var QueueEventsBatchError = class extends AggregateError {
|
|
13
|
+
failures;
|
|
14
|
+
constructor(failures) {
|
|
15
|
+
super(failures.map(({ error }) => error), `${failures.length} queue event(s) failed`);
|
|
16
|
+
this.failures = failures;
|
|
17
|
+
this.name = "QueueEventsBatchError";
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
const dispatch = Symbol("queue-event-dispatch");
|
|
21
|
+
function nonempty(value) {
|
|
22
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
23
|
+
}
|
|
24
|
+
/** No module registration or global state: define handlers alongside their consuming provider. */
|
|
25
|
+
function defineQueueEvent(options) {
|
|
26
|
+
if (!nonempty(options.type) || !nonempty(options.source.type) || !Object.values(options.source).every(nonempty)) throw new TypeError("Queue event type and source expectations must be nonempty strings");
|
|
27
|
+
if (!isStandardSchema(options.schema)) throw new TypeError("Expected a Standard Schema validator");
|
|
28
|
+
const { type, schema, handle } = options;
|
|
29
|
+
const source = Object.entries(options.source);
|
|
30
|
+
return Object.freeze({
|
|
31
|
+
type,
|
|
32
|
+
async [dispatch](event, context) {
|
|
33
|
+
if (!source.every(([key, value]) => event.source[key] === value)) throw new QueueEventError("unexpected-source");
|
|
34
|
+
let payload;
|
|
35
|
+
try {
|
|
36
|
+
payload = await validateSchema(schema, event.payload);
|
|
37
|
+
} catch (cause) {
|
|
38
|
+
throw new QueueEventError("invalid-payload", { cause });
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
await handle({
|
|
42
|
+
...event,
|
|
43
|
+
payload
|
|
44
|
+
}, context);
|
|
45
|
+
} catch (cause) {
|
|
46
|
+
throw new QueueEventError("handler-failed", { cause });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
function record(value) {
|
|
52
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
53
|
+
}
|
|
54
|
+
function parseEvent(value) {
|
|
55
|
+
if (!record(value) || !nonempty(value.type) || !record(value.source) || !nonempty(value.source.type) || !Object.hasOwn(value, "payload") || !record(value.metadata)) throw new QueueEventError("invalid-envelope");
|
|
56
|
+
const { source, metadata } = value;
|
|
57
|
+
if (!nonempty(metadata.accountId) || !nonempty(metadata.eventSubscriptionId) || !Number.isInteger(metadata.eventSchemaVersion) || !nonempty(metadata.eventTimestamp) || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(metadata.eventTimestamp) || !Number.isFinite(Date.parse(metadata.eventTimestamp)) || new Date(metadata.eventTimestamp.slice(0, 10)).toISOString().slice(0, 10) !== metadata.eventTimestamp.slice(0, 10)) throw new QueueEventError("invalid-envelope");
|
|
58
|
+
if (metadata.eventSchemaVersion !== 1) throw new QueueEventError("unsupported-version");
|
|
59
|
+
return {
|
|
60
|
+
type: value.type,
|
|
61
|
+
source: {
|
|
62
|
+
...source,
|
|
63
|
+
type: value.source.type
|
|
64
|
+
},
|
|
65
|
+
payload: value.payload,
|
|
66
|
+
metadata: {
|
|
67
|
+
...metadata,
|
|
68
|
+
accountId: metadata.accountId,
|
|
69
|
+
eventSubscriptionId: metadata.eventSubscriptionId,
|
|
70
|
+
eventSchemaVersion: 1,
|
|
71
|
+
eventTimestamp: metadata.eventTimestamp
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Await each validated handler, then acknowledge that message. Every malformed,
|
|
77
|
+
* unmatched or failing message requests retry; all siblings are attempted before
|
|
78
|
+
* throwing QueueEventsBatchError. Cloudflare owns retry limits, delays and DLQ routing.
|
|
79
|
+
* Do not acknowledge the batch elsewhere or convert these bodies into Vela jobs.
|
|
80
|
+
*/
|
|
81
|
+
async function consumeQueueEvents(batch, options) {
|
|
82
|
+
if (!nonempty(options.queue) || !nonempty(options.accountId) || options.eventSubscriptionIds.length === 0 || !options.eventSubscriptionIds.every(nonempty)) throw new TypeError("Expected a physical queue, account and nonempty subscription allowlist");
|
|
83
|
+
if (batch.queue !== options.queue) throw new Error("Unexpected physical queue for platform events");
|
|
84
|
+
const handlers = /* @__PURE__ */ new Map();
|
|
85
|
+
for (const handler of options.handlers) {
|
|
86
|
+
if (handlers.has(handler.type)) throw new TypeError(`Duplicate queue event handler: ${handler.type}`);
|
|
87
|
+
handlers.set(handler.type, handler);
|
|
88
|
+
}
|
|
89
|
+
const accountId = options.accountId;
|
|
90
|
+
const subscriptions = new Set(options.eventSubscriptionIds);
|
|
91
|
+
const failures = [];
|
|
92
|
+
for (const message of batch.messages) {
|
|
93
|
+
try {
|
|
94
|
+
const event = parseEvent(message.body);
|
|
95
|
+
if (event.metadata.accountId !== accountId) throw new QueueEventError("unexpected-account");
|
|
96
|
+
if (!subscriptions.has(event.metadata.eventSubscriptionId)) throw new QueueEventError("unexpected-subscription");
|
|
97
|
+
const handler = handlers.get(event.type);
|
|
98
|
+
if (!handler) throw new QueueEventError("unhandled-type");
|
|
99
|
+
await handler[dispatch](event, {
|
|
100
|
+
queue: batch.queue,
|
|
101
|
+
messageId: message.id,
|
|
102
|
+
timestamp: message.timestamp,
|
|
103
|
+
attempts: message.attempts
|
|
104
|
+
});
|
|
105
|
+
} catch (error) {
|
|
106
|
+
message.retry();
|
|
107
|
+
failures.push({
|
|
108
|
+
messageId: message.id,
|
|
109
|
+
error: error instanceof QueueEventError ? error : new QueueEventError("handler-failed", { cause: error })
|
|
110
|
+
});
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
message.ack();
|
|
114
|
+
}
|
|
115
|
+
if (failures.length > 0) throw new QueueEventsBatchError(failures);
|
|
116
|
+
}
|
|
117
|
+
//#endregion
|
|
118
|
+
export { QueueEventError, QueueEventsBatchError, consumeQueueEvents, defineQueueEvent };
|
|
119
|
+
|
|
120
|
+
//# sourceMappingURL=consume.js.map
|
|
@@ -0,0 +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,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|
+
interface QueueEvent<Payload = unknown> {
|
|
4
|
+
readonly type: string;
|
|
5
|
+
readonly source: Readonly<Record<string, unknown>> & {
|
|
6
|
+
readonly type: string;
|
|
7
|
+
};
|
|
8
|
+
readonly payload: Payload;
|
|
9
|
+
readonly metadata: Readonly<Record<string, unknown>> & {
|
|
10
|
+
readonly accountId: string;
|
|
11
|
+
readonly eventSubscriptionId: string;
|
|
12
|
+
readonly eventSchemaVersion: 1;
|
|
13
|
+
readonly eventTimestamp: string;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/** Native delivery identity, not a universal platform event ID or an idempotency guarantee. */
|
|
17
|
+
interface QueueEventContext {
|
|
18
|
+
readonly queue: string;
|
|
19
|
+
readonly messageId: string;
|
|
20
|
+
readonly timestamp: Date;
|
|
21
|
+
readonly attempts: number;
|
|
22
|
+
}
|
|
23
|
+
type QueueEventErrorCode = 'invalid-envelope' | 'unsupported-version' | 'unexpected-account' | 'unexpected-subscription' | 'unhandled-type' | 'unexpected-source' | 'invalid-payload' | 'handler-failed';
|
|
24
|
+
export declare class QueueEventError extends Error {
|
|
25
|
+
readonly code: QueueEventErrorCode;
|
|
26
|
+
constructor(code: QueueEventErrorCode, options?: ErrorOptions);
|
|
27
|
+
}
|
|
28
|
+
interface QueueEventFailure {
|
|
29
|
+
readonly messageId: string;
|
|
30
|
+
readonly error: QueueEventError;
|
|
31
|
+
}
|
|
32
|
+
/** Successful siblings are already acknowledged; failures have requested native retries. */
|
|
33
|
+
export declare class QueueEventsBatchError extends AggregateError {
|
|
34
|
+
readonly failures: readonly QueueEventFailure[];
|
|
35
|
+
constructor(failures: readonly QueueEventFailure[]);
|
|
36
|
+
}
|
|
37
|
+
interface QueueEventOptions<Payload> {
|
|
38
|
+
/** The full documented event type, for example cf.workersBuilds.worker.build.succeeded. */
|
|
39
|
+
readonly type: string;
|
|
40
|
+
/** Exact matches for source.type and any source selectors required by the application. */
|
|
41
|
+
readonly source: Readonly<Record<string, string>> & {
|
|
42
|
+
readonly type: string;
|
|
43
|
+
};
|
|
44
|
+
readonly schema: StandardSchemaV1<unknown, Payload>;
|
|
45
|
+
readonly handle: (event: QueueEvent<Payload>, context: QueueEventContext) => void | Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
declare const dispatch: unique symbol;
|
|
48
|
+
/** Created with defineQueueEvent so each heterogeneous payload retains its validated type. */
|
|
49
|
+
interface QueueEventHandler {
|
|
50
|
+
readonly type: string;
|
|
51
|
+
readonly [dispatch]: (event: QueueEvent, context: QueueEventContext) => Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
/** No module registration or global state: define handlers alongside their consuming provider. */
|
|
54
|
+
export declare function defineQueueEvent<Payload>(options: QueueEventOptions<Payload>): QueueEventHandler;
|
|
55
|
+
interface ConsumeQueueEventsOptions {
|
|
56
|
+
/** Dedicated physical queue name, also claimed by @QueueConsumer. */
|
|
57
|
+
readonly queue: string;
|
|
58
|
+
readonly accountId: string;
|
|
59
|
+
readonly eventSubscriptionIds: readonly string[];
|
|
60
|
+
/** One handler per exact event type; each may require source selectors. */
|
|
61
|
+
readonly handlers: readonly QueueEventHandler[];
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Await each validated handler, then acknowledge that message. Every malformed,
|
|
65
|
+
* unmatched or failing message requests retry; all siblings are attempted before
|
|
66
|
+
* throwing QueueEventsBatchError. Cloudflare owns retry limits, delays and DLQ routing.
|
|
67
|
+
* Do not acknowledge the batch elsewhere or convert these bodies into Vela jobs.
|
|
68
|
+
*/
|
|
69
|
+
export declare function consumeQueueEvents(batch: MessageBatch<unknown>, options: ConsumeQueueEventsOptions): Promise<void>;
|
|
70
|
+
//#endregion
|
|
71
|
+
export type { ConsumeQueueEventsOptions, QueueEvent, QueueEventContext, QueueEventErrorCode, QueueEventFailure, QueueEventHandler, QueueEventOptions };
|
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
* {@link FeatureFlagDriver} backed by a Cloudflare Flagship binding.
|
|
4
4
|
*
|
|
5
5
|
* A thin, honest wrapper: each contract method maps 1:1 onto the binding's
|
|
6
|
-
* corresponding
|
|
7
|
-
* `defaultValue`) and evaluation context.
|
|
6
|
+
* corresponding native method, forwarding the caller's `fallback` (the binding's
|
|
7
|
+
* `defaultValue`) and validated scalar evaluation context. Optional detail methods
|
|
8
|
+
* preserve native reasons, variants and error codes; value-only bindings report UNKNOWN. The binding resolves the fallback on
|
|
8
9
|
* evaluation errors; anything the binding *rejects* with (e.g. a `remote: true`
|
|
9
10
|
* dev-proxy tunnel dropping) propagates — `@velajs/feature-flags`'s service owns
|
|
10
11
|
* the never-throw guarantee.
|
|
@@ -30,22 +31,79 @@ var FlagshipFlagDriver = class {
|
|
|
30
31
|
this.name = options.name ?? "flagship";
|
|
31
32
|
}
|
|
32
33
|
getBoolean(key, fallback, ctx) {
|
|
33
|
-
return this.resolve().getBooleanValue(key, fallback, ctx);
|
|
34
|
+
return this.resolve().getBooleanValue(key, fallback, nativeContext(ctx));
|
|
34
35
|
}
|
|
35
36
|
getString(key, fallback, ctx) {
|
|
36
|
-
return this.resolve().getStringValue(key, fallback, ctx);
|
|
37
|
+
return this.resolve().getStringValue(key, fallback, nativeContext(ctx));
|
|
37
38
|
}
|
|
38
39
|
getNumber(key, fallback, ctx) {
|
|
39
|
-
return this.resolve().getNumberValue(key, fallback, ctx);
|
|
40
|
+
return this.resolve().getNumberValue(key, fallback, nativeContext(ctx));
|
|
40
41
|
}
|
|
41
42
|
getObject(key, fallback, ctx) {
|
|
42
|
-
return this.resolve().getObjectValue(key, fallback, ctx);
|
|
43
|
+
return this.resolve().getObjectValue(key, fallback, nativeContext(ctx));
|
|
44
|
+
}
|
|
45
|
+
getBooleanDetails(key, fallback, ctx) {
|
|
46
|
+
return this.details(key, fallback, ctx, (binding, context) => binding.getBooleanDetails ? binding.getBooleanDetails(key, fallback, context) : binding.getBooleanValue(key, fallback, context).then((value) => ({
|
|
47
|
+
flagKey: key,
|
|
48
|
+
value,
|
|
49
|
+
reason: "UNKNOWN"
|
|
50
|
+
})));
|
|
51
|
+
}
|
|
52
|
+
getStringDetails(key, fallback, ctx) {
|
|
53
|
+
return this.details(key, fallback, ctx, (binding, context) => binding.getStringDetails ? binding.getStringDetails(key, fallback, context) : binding.getStringValue(key, fallback, context).then((value) => ({
|
|
54
|
+
flagKey: key,
|
|
55
|
+
value,
|
|
56
|
+
reason: "UNKNOWN"
|
|
57
|
+
})));
|
|
58
|
+
}
|
|
59
|
+
getNumberDetails(key, fallback, ctx) {
|
|
60
|
+
return this.details(key, fallback, ctx, (binding, context) => binding.getNumberDetails ? binding.getNumberDetails(key, fallback, context) : binding.getNumberValue(key, fallback, context).then((value) => ({
|
|
61
|
+
flagKey: key,
|
|
62
|
+
value,
|
|
63
|
+
reason: "UNKNOWN"
|
|
64
|
+
})));
|
|
65
|
+
}
|
|
66
|
+
getObjectDetails(key, fallback, ctx) {
|
|
67
|
+
return this.details(key, fallback, ctx, (binding, context) => binding.getObjectDetails ? binding.getObjectDetails(key, fallback, context) : binding.getObjectValue(key, fallback, context).then((value) => ({
|
|
68
|
+
flagKey: key,
|
|
69
|
+
value,
|
|
70
|
+
reason: "UNKNOWN"
|
|
71
|
+
})));
|
|
72
|
+
}
|
|
73
|
+
async details(key, fallback, ctx, read) {
|
|
74
|
+
let context;
|
|
75
|
+
try {
|
|
76
|
+
context = nativeContext(ctx);
|
|
77
|
+
} catch {
|
|
78
|
+
return {
|
|
79
|
+
flagKey: key,
|
|
80
|
+
value: fallback,
|
|
81
|
+
reason: "ERROR",
|
|
82
|
+
errorCode: "INVALID_CONTEXT"
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
const details = await read(this.resolve(), context);
|
|
86
|
+
return {
|
|
87
|
+
...details,
|
|
88
|
+
reason: details.reason === void 0 ? "UNKNOWN" : details.reason
|
|
89
|
+
};
|
|
43
90
|
}
|
|
44
91
|
};
|
|
45
92
|
/** Convenience factory for {@link FlagshipFlagDriver}. */
|
|
46
93
|
function flagshipFlagDriver(binding, options) {
|
|
47
94
|
return new FlagshipFlagDriver(binding, options);
|
|
48
95
|
}
|
|
96
|
+
/** Copy only validated scalar attributes; never coerce nested or non-finite values. */
|
|
97
|
+
function nativeContext(ctx) {
|
|
98
|
+
if (ctx === void 0) return void 0;
|
|
99
|
+
if (ctx === null || typeof ctx !== "object" || Array.isArray(ctx) || Object.getPrototypeOf(ctx) !== Object.prototype && Object.getPrototypeOf(ctx) !== null) throw new TypeError("Invalid Flagship evaluation context");
|
|
100
|
+
const entries = [];
|
|
101
|
+
for (const [key, value] of Object.entries(ctx)) {
|
|
102
|
+
if (typeof value !== "string" && typeof value !== "boolean" && !(typeof value === "number" && Number.isFinite(value))) throw new TypeError("Invalid Flagship evaluation context");
|
|
103
|
+
entries.push([key, value]);
|
|
104
|
+
}
|
|
105
|
+
return Object.fromEntries(entries);
|
|
106
|
+
}
|
|
49
107
|
//#endregion
|
|
50
108
|
export { FlagshipFlagDriver, flagshipFlagDriver };
|
|
51
109
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flagship-flag.driver.js","names":[],"sources":["../../src/services/flagship-flag.driver.ts"],"sourcesContent":["import type { FeatureFlagDriver, FlagContext } from '@velajs/feature-flags';\n\n/**\n * The subset of a Cloudflare **Flagship** binding this driver evaluates against\n * — the four typed value methods. The binding itself returns the supplied\n * `defaultValue` on evaluation errors; transport-level failures reject and are\n * left to propagate (never-throw is the service layer's job, not the driver's).\n *\n * @see https://developers.cloudflare.com/flagship/binding/\n */\nexport interface FlagshipBinding {\n getBooleanValue(key: string, defaultValue: boolean, context?: FlagContext): Promise<boolean>;\n getStringValue(key: string, defaultValue: string, context?: FlagContext): Promise<string>;\n getNumberValue(key: string, defaultValue: number, context?: FlagContext): Promise<number>;\n getObjectValue(key: string, defaultValue: object, context?: FlagContext): Promise<unknown>;\n}\n\nexport interface FlagshipFlagDriverOptions {\n /** Driver name used for `use(name)` / default-driver selection. Default `\"flagship\"`. */\n name?: string;\n}\n\n/**\n * {@link FeatureFlagDriver} backed by a Cloudflare Flagship binding.\n *\n * A thin, honest wrapper: each contract method maps 1:1 onto the binding's\n * corresponding value method, forwarding the caller's `fallback` (the binding's\n * `defaultValue`) and evaluation context. The binding resolves the fallback on\n * evaluation errors; anything the binding *rejects* with (e.g. a `remote: true`\n * dev-proxy tunnel dropping) propagates — `@velajs/feature-flags`'s service owns\n * the never-throw guarantee.\n *\n * Build the driver inside a provider factory with the native environment:\n *\n * ```ts\n * FeatureFlagsModule.forRootAsync({\n * inject: [ENV],\n * useFactory: (env: WorkerEnv) => ({ drivers: [flagshipFlagDriver(env.FLAGS)] }),\n * });\n * ```\n *\n * Evaluation ergonomics (the 1:1 binding-method mapping) are ported from the\n * Stratal feature-flags service (MIT, © Temitayo Fadojutimi), reshaped as a\n * bare driver.\n */\nexport class FlagshipFlagDriver implements FeatureFlagDriver {\n readonly name: string;\n private readonly resolve: () => FlagshipBinding;\n\n constructor(\n binding: FlagshipBinding | (() => FlagshipBinding),\n options: FlagshipFlagDriverOptions = {},\n ) {\n this.resolve = typeof binding === 'function' ? binding : () => binding;\n this.name = options.name ?? 'flagship';\n }\n\n getBoolean(key: string, fallback: boolean, ctx?: FlagContext): Promise<boolean> {\n return this.resolve().getBooleanValue(key, fallback, ctx);\n }\n\n getString(key: string, fallback: string, ctx?: FlagContext): Promise<string> {\n return this.resolve().getStringValue(key, fallback, ctx);\n }\n\n getNumber(key: string, fallback: number, ctx?: FlagContext): Promise<number> {\n return this.resolve().getNumberValue(key, fallback, ctx);\n }\n\n getObject(key: string, fallback: object, ctx?: FlagContext): Promise<unknown> {\n return this.resolve().getObjectValue(key, fallback, ctx);\n }\n}\n\n/** Convenience factory for {@link FlagshipFlagDriver}. */\nexport function flagshipFlagDriver(\n binding: FlagshipBinding | (() => FlagshipBinding),\n options?: FlagshipFlagDriverOptions,\n): FlagshipFlagDriver {\n return new FlagshipFlagDriver(binding, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA6CA,IAAa,qBAAb,MAA6D;CAC3D;CACA;CAEA,YACE,SACA,UAAqC,CAAC,GACtC;EACA,KAAK,UAAU,OAAO,YAAY,aAAa,gBAAgB;EAC/D,KAAK,OAAO,QAAQ,QAAQ;CAC9B;CAEA,WAAW,KAAa,UAAmB,KAAqC;EAC9E,OAAO,KAAK,QAAQ,CAAC,CAAC,gBAAgB,KAAK,UAAU,GAAG;CAC1D;CAEA,UAAU,KAAa,UAAkB,KAAoC;EAC3E,OAAO,KAAK,QAAQ,CAAC,CAAC,eAAe,KAAK,UAAU,GAAG;CACzD;CAEA,UAAU,KAAa,UAAkB,KAAoC;EAC3E,OAAO,KAAK,QAAQ,CAAC,CAAC,eAAe,KAAK,UAAU,GAAG;CACzD;CAEA,UAAU,KAAa,UAAkB,KAAqC;EAC5E,OAAO,KAAK,QAAQ,CAAC,CAAC,eAAe,KAAK,UAAU,GAAG;CACzD;AACF;;AAGA,SAAgB,mBACd,SACA,SACoB;CACpB,OAAO,IAAI,mBAAmB,SAAS,OAAO;AAChD"}
|
|
1
|
+
{"version":3,"file":"flagship-flag.driver.js","names":[],"sources":["../../src/services/flagship-flag.driver.ts"],"sourcesContent":["import type { FeatureFlagDriver, FlagContext, FlagEvaluationDetails } from '@velajs/feature-flags';\n\n/**\n * The subset of a Cloudflare **Flagship** binding this driver evaluates against\n * — typed value methods and optional evaluation details. The binding itself returns the supplied\n * `defaultValue` on evaluation errors; transport-level failures reject and are\n * left to propagate (never-throw is the service layer's job, not the driver's).\n *\n * @see https://developers.cloudflare.com/flagship/binding/\n */\ntype NativeFlagDetails<T> = Omit<FlagEvaluationDetails<T>, 'reason'> & { reason?: string };\n\nexport interface FlagshipBinding {\n getBooleanValue(\n key: string,\n defaultValue: boolean,\n context?: Record<string, string | number | boolean>,\n ): Promise<boolean>;\n getStringValue(\n key: string,\n defaultValue: string,\n context?: Record<string, string | number | boolean>,\n ): Promise<string>;\n getNumberValue(\n key: string,\n defaultValue: number,\n context?: Record<string, string | number | boolean>,\n ): Promise<number>;\n getObjectValue(\n key: string,\n defaultValue: object,\n context?: Record<string, string | number | boolean>,\n ): Promise<unknown>;\n getBooleanDetails?(\n key: string,\n defaultValue: boolean,\n context?: Record<string, string | number | boolean>,\n ): Promise<NativeFlagDetails<boolean>>;\n getStringDetails?(\n key: string,\n defaultValue: string,\n context?: Record<string, string | number | boolean>,\n ): Promise<NativeFlagDetails<string>>;\n getNumberDetails?(\n key: string,\n defaultValue: number,\n context?: Record<string, string | number | boolean>,\n ): Promise<NativeFlagDetails<number>>;\n getObjectDetails?(\n key: string,\n defaultValue: object,\n context?: Record<string, string | number | boolean>,\n ): Promise<NativeFlagDetails<unknown>>;\n}\n\nexport interface FlagshipFlagDriverOptions {\n /** Driver name used for `use(name)` / default-driver selection. Default `\"flagship\"`. */\n name?: string;\n}\n\n/**\n * {@link FeatureFlagDriver} backed by a Cloudflare Flagship binding.\n *\n * A thin, honest wrapper: each contract method maps 1:1 onto the binding's\n * corresponding native method, forwarding the caller's `fallback` (the binding's\n * `defaultValue`) and validated scalar evaluation context. Optional detail methods\n * preserve native reasons, variants and error codes; value-only bindings report UNKNOWN. The binding resolves the fallback on\n * evaluation errors; anything the binding *rejects* with (e.g. a `remote: true`\n * dev-proxy tunnel dropping) propagates — `@velajs/feature-flags`'s service owns\n * the never-throw guarantee.\n *\n * Build the driver inside a provider factory with the native environment:\n *\n * ```ts\n * FeatureFlagsModule.forRootAsync({\n * inject: [ENV],\n * useFactory: (env: WorkerEnv) => ({ drivers: [flagshipFlagDriver(env.FLAGS)] }),\n * });\n * ```\n *\n * Evaluation ergonomics (the 1:1 binding-method mapping) are ported from the\n * Stratal feature-flags service (MIT, © Temitayo Fadojutimi), reshaped as a\n * bare driver.\n */\nexport class FlagshipFlagDriver implements FeatureFlagDriver {\n readonly name: string;\n private readonly resolve: () => FlagshipBinding;\n\n constructor(\n binding: FlagshipBinding | (() => FlagshipBinding),\n options: FlagshipFlagDriverOptions = {},\n ) {\n this.resolve = typeof binding === 'function' ? binding : () => binding;\n this.name = options.name ?? 'flagship';\n }\n\n getBoolean(key: string, fallback: boolean, ctx?: FlagContext): Promise<boolean> {\n return this.resolve().getBooleanValue(key, fallback, nativeContext(ctx));\n }\n\n getString(key: string, fallback: string, ctx?: FlagContext): Promise<string> {\n return this.resolve().getStringValue(key, fallback, nativeContext(ctx));\n }\n\n getNumber(key: string, fallback: number, ctx?: FlagContext): Promise<number> {\n return this.resolve().getNumberValue(key, fallback, nativeContext(ctx));\n }\n\n getObject(key: string, fallback: object, ctx?: FlagContext): Promise<unknown> {\n return this.resolve().getObjectValue(key, fallback, nativeContext(ctx));\n }\n getBooleanDetails(\n key: string,\n fallback: boolean,\n ctx?: FlagContext,\n ): Promise<FlagEvaluationDetails<boolean>> {\n return this.details(key, fallback, ctx, (binding, context) =>\n binding.getBooleanDetails\n ? binding.getBooleanDetails(key, fallback, context)\n : binding\n .getBooleanValue(key, fallback, context)\n .then((value) => ({ flagKey: key, value, reason: 'UNKNOWN' })),\n );\n }\n\n getStringDetails(\n key: string,\n fallback: string,\n ctx?: FlagContext,\n ): Promise<FlagEvaluationDetails<string>> {\n return this.details(key, fallback, ctx, (binding, context) =>\n binding.getStringDetails\n ? binding.getStringDetails(key, fallback, context)\n : binding\n .getStringValue(key, fallback, context)\n .then((value) => ({ flagKey: key, value, reason: 'UNKNOWN' })),\n );\n }\n\n getNumberDetails(\n key: string,\n fallback: number,\n ctx?: FlagContext,\n ): Promise<FlagEvaluationDetails<number>> {\n return this.details(key, fallback, ctx, (binding, context) =>\n binding.getNumberDetails\n ? binding.getNumberDetails(key, fallback, context)\n : binding\n .getNumberValue(key, fallback, context)\n .then((value) => ({ flagKey: key, value, reason: 'UNKNOWN' })),\n );\n }\n\n getObjectDetails(\n key: string,\n fallback: object,\n ctx?: FlagContext,\n ): Promise<FlagEvaluationDetails<unknown>> {\n return this.details(key, fallback, ctx, (binding, context) =>\n binding.getObjectDetails\n ? binding.getObjectDetails(key, fallback, context)\n : binding\n .getObjectValue(key, fallback, context)\n .then((value) => ({ flagKey: key, value, reason: 'UNKNOWN' })),\n );\n }\n\n private async details<T>(\n key: string,\n fallback: T,\n ctx: FlagContext | undefined,\n read: (\n binding: FlagshipBinding,\n context: Record<string, string | number | boolean> | undefined,\n ) => Promise<NativeFlagDetails<T>>,\n ): Promise<FlagEvaluationDetails<T>> {\n let context: Record<string, string | number | boolean> | undefined;\n try {\n context = nativeContext(ctx);\n } catch {\n return { flagKey: key, value: fallback, reason: 'ERROR', errorCode: 'INVALID_CONTEXT' };\n }\n const details = await read(this.resolve(), context);\n return { ...details, reason: details.reason === undefined ? 'UNKNOWN' : details.reason };\n }\n}\n\n/** Convenience factory for {@link FlagshipFlagDriver}. */\nexport function flagshipFlagDriver(\n binding: FlagshipBinding | (() => FlagshipBinding),\n options?: FlagshipFlagDriverOptions,\n): FlagshipFlagDriver {\n return new FlagshipFlagDriver(binding, options);\n}\n\n/** Copy only validated scalar attributes; never coerce nested or non-finite values. */\nfunction nativeContext(\n ctx: FlagContext | undefined,\n): Record<string, string | number | boolean> | undefined {\n if (ctx === undefined) return undefined;\n if (\n ctx === null ||\n typeof ctx !== 'object' ||\n Array.isArray(ctx) ||\n (Object.getPrototypeOf(ctx) !== Object.prototype && Object.getPrototypeOf(ctx) !== null)\n )\n throw new TypeError('Invalid Flagship evaluation context');\n const entries: [string, string | number | boolean][] = [];\n for (const [key, value] of Object.entries(ctx)) {\n if (\n typeof value !== 'string' &&\n typeof value !== 'boolean' &&\n !(typeof value === 'number' && Number.isFinite(value))\n )\n throw new TypeError('Invalid Flagship evaluation context');\n entries.push([key, value]);\n }\n return Object.fromEntries(entries);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAoFA,IAAa,qBAAb,MAA6D;CAC3D;CACA;CAEA,YACE,SACA,UAAqC,CAAC,GACtC;EACA,KAAK,UAAU,OAAO,YAAY,aAAa,gBAAgB;EAC/D,KAAK,OAAO,QAAQ,QAAQ;CAC9B;CAEA,W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-
|
|
2
|
+
import "./cloudflare-application-Dsscb3Mo.js";
|
|
3
3
|
import { EntrypointExecutionContext } from "@velajs/vela/module-kit";
|
|
4
4
|
//#region src/tail/on-tail.d.ts
|
|
5
5
|
/** A method decorator whose method receives a batch of Tail Workers events. */
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./vela-env-DFvyoNT3.js";
|
|
2
|
-
import { d as CloudflareWorkerOptions, y as CloudflareRoot } from "./cloudflare-factory-
|
|
2
|
+
import { d as CloudflareWorkerOptions, y as CloudflareRoot } from "./cloudflare-factory-DM9CBvNH.js";
|
|
3
3
|
import { VelaEnv } from "@velajs/vela";
|
|
4
4
|
import { QueueJob, QueueJobDefinition, QueueJobInput } from "@velajs/vela/queue";
|
|
5
5
|
import { TestingModule, TestingModuleBuilder } from "@velajs/testing";
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { CallHandler, ExecutionContext, NestInterceptor } from "@velajs/vela";
|
|
2
|
+
//#region src/tracing.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Native Workers spans around awaited HTTP/RPC handler work. Register through
|
|
5
|
+
* `@UseInterceptors(CloudflareTracingInterceptor)` on a controller or RPC host.
|
|
6
|
+
*
|
|
7
|
+
* The callback establishes the native async parent for inner interceptors,
|
|
8
|
+
* handler code and awaited platform calls. Guards/pipes run before it; response
|
|
9
|
+
* streams, deferred work and scope disposal can outlive it. Cloudflare owns
|
|
10
|
+
* sampling, ending and export. This is not a portable Telemetry recorder.
|
|
11
|
+
*/
|
|
12
|
+
export declare class CloudflareTracingInterceptor implements NestInterceptor {
|
|
13
|
+
intercept(context: ExecutionContext, next: CallHandler): Promise<unknown>;
|
|
14
|
+
}
|
|
15
|
+
//#endregion
|
package/dist/tracing.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import __decorate from "./_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js";
|
|
2
|
+
import { Injectable } from "@velajs/vela";
|
|
3
|
+
import { tracing } from "cloudflare:workers";
|
|
4
|
+
//#region src/tracing.ts
|
|
5
|
+
const MAX_LABEL_LENGTH = 128;
|
|
6
|
+
let CloudflareTracingInterceptor = class CloudflareTracingInterceptor {
|
|
7
|
+
intercept(context, next) {
|
|
8
|
+
const kind = context.getType();
|
|
9
|
+
if (kind !== "http" && kind !== "rpc") return next.handle();
|
|
10
|
+
return tracing.enterSpan(kind === "http" ? "vela.http.handler" : "vela.rpc.handler", (span) => {
|
|
11
|
+
if (span.isTraced) {
|
|
12
|
+
span.setAttribute("vela.handler.class", context.getClass().name.slice(0, MAX_LABEL_LENGTH));
|
|
13
|
+
const method = context.getHandlerName();
|
|
14
|
+
if (typeof method === "string") span.setAttribute("vela.handler.method", method.slice(0, MAX_LABEL_LENGTH));
|
|
15
|
+
}
|
|
16
|
+
return next.handle();
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
CloudflareTracingInterceptor = __decorate([Injectable()], CloudflareTracingInterceptor);
|
|
21
|
+
//#endregion
|
|
22
|
+
export { CloudflareTracingInterceptor };
|
|
23
|
+
|
|
24
|
+
//# sourceMappingURL=tracing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tracing.js","names":[],"sources":["../src/tracing.ts"],"sourcesContent":["import { tracing } from 'cloudflare:workers';\nimport {\n Injectable,\n type CallHandler,\n type ExecutionContext,\n type NestInterceptor,\n} from '@velajs/vela';\n\nconst MAX_LABEL_LENGTH = 128;\n\n/**\n * Native Workers spans around awaited HTTP/RPC handler work. Register through\n * `@UseInterceptors(CloudflareTracingInterceptor)` on a controller or RPC host.\n *\n * The callback establishes the native async parent for inner interceptors,\n * handler code and awaited platform calls. Guards/pipes run before it; response\n * streams, deferred work and scope disposal can outlive it. Cloudflare owns\n * sampling, ending and export. This is not a portable Telemetry recorder.\n */\n@Injectable()\nexport class CloudflareTracingInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, next: CallHandler): Promise<unknown> {\n const kind = context.getType();\n if (kind !== 'http' && kind !== 'rpc') return next.handle();\n\n return tracing.enterSpan(kind === 'http' ? 'vela.http.handler' : 'vela.rpc.handler', (span) => {\n if (span.isTraced) {\n span.setAttribute('vela.handler.class', context.getClass().name.slice(0, MAX_LABEL_LENGTH));\n const method = context.getHandlerName();\n // Symbol descriptions may contain caller data; only declared string\n // method names belong in these fixed, bounded instrumentation labels.\n if (typeof method === 'string') {\n span.setAttribute('vela.handler.method', method.slice(0, MAX_LABEL_LENGTH));\n }\n }\n // Return the actual handler promise from INSIDE enterSpan. Starting a\n // span in an onStart observer would lose native parent-child nesting.\n return next.handle();\n });\n }\n}\n"],"mappings":";;;;AAQA,MAAM,mBAAmB;AAYlB,IAAM,+BAAN,MAAM,6BAAwD;CACnE,UAAU,SAA2B,MAAqC;EACxE,MAAM,OAAO,QAAQ,QAAQ;EAC7B,IAAI,SAAS,UAAU,SAAS,OAAO,OAAO,KAAK,OAAO;EAE1D,OAAO,QAAQ,UAAU,SAAS,SAAS,sBAAsB,qBAAqB,SAAS;GAC7F,IAAI,KAAK,UAAU;IACjB,KAAK,aAAa,sBAAsB,QAAQ,SAAS,CAAC,CAAC,KAAK,MAAM,GAAG,gBAAgB,CAAC;IAC1F,MAAM,SAAS,QAAQ,eAAe;IAGtC,IAAI,OAAO,WAAW,UACpB,KAAK,aAAa,uBAAuB,OAAO,MAAM,GAAG,gBAAgB,CAAC;GAE9E;GAGA,OAAO,KAAK,OAAO;EACrB,CAAC;CACH;AACF;AArBC,+BAAA,WAAA,CAAA,WAAW,CAAA,GAAA,4BAAA"}
|
package/dist/workflows.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./vela-env-DFvyoNT3.js";
|
|
2
|
-
import { a as CloudflareApp } from "./cloudflare-factory-
|
|
2
|
+
import { a as CloudflareApp } from "./cloudflare-factory-DM9CBvNH.js";
|
|
3
3
|
import { WorkflowEntrypoint, WorkflowEvent, WorkflowStep } from "cloudflare:workers";
|
|
4
4
|
import { Type, VelaEnv } from "@velajs/vela";
|
|
5
5
|
import { EntrypointExecutionContext } from "@velajs/vela/module-kit";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@velajs/cloudflare",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.34.0",
|
|
4
4
|
"description": "Cloudflare Workers integration for Vela framework",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -52,6 +52,14 @@
|
|
|
52
52
|
"types": "./dist/entrypoints.d.ts",
|
|
53
53
|
"import": "./dist/entrypoints.js"
|
|
54
54
|
},
|
|
55
|
+
"./pipelines": {
|
|
56
|
+
"types": "./dist/pipelines.d.ts",
|
|
57
|
+
"import": "./dist/pipelines.js"
|
|
58
|
+
},
|
|
59
|
+
"./queue-events": {
|
|
60
|
+
"types": "./dist/queue-events.d.ts",
|
|
61
|
+
"import": "./dist/queue-events.js"
|
|
62
|
+
},
|
|
55
63
|
"./queues": {
|
|
56
64
|
"types": "./dist/queues.d.ts",
|
|
57
65
|
"import": "./dist/queues.js"
|
|
@@ -68,6 +76,10 @@
|
|
|
68
76
|
"types": "./dist/testing.d.ts",
|
|
69
77
|
"import": "./dist/testing.js"
|
|
70
78
|
},
|
|
79
|
+
"./tracing": {
|
|
80
|
+
"types": "./dist/tracing.d.ts",
|
|
81
|
+
"import": "./dist/tracing.js"
|
|
82
|
+
},
|
|
71
83
|
"./workflows": {
|
|
72
84
|
"types": "./dist/workflows.d.ts",
|
|
73
85
|
"import": "./dist/workflows.js"
|
|
@@ -91,15 +103,15 @@
|
|
|
91
103
|
"unplugin-swc": "1.5.9",
|
|
92
104
|
"vitest": "4.1.11",
|
|
93
105
|
"zod": "^3.25.76",
|
|
94
|
-
"@velajs/feature-flags": "1.
|
|
95
|
-
"@velajs/storage": "1.33.0",
|
|
106
|
+
"@velajs/feature-flags": "1.32.0",
|
|
96
107
|
"@velajs/testing": "1.33.0",
|
|
97
|
-
"@velajs/vela": "1.33.0"
|
|
108
|
+
"@velajs/vela": "1.33.0",
|
|
109
|
+
"@velajs/storage": "1.33.0"
|
|
98
110
|
},
|
|
99
111
|
"peerDependencies": {
|
|
100
112
|
"@cloudflare/workers-types": ">=4",
|
|
101
113
|
"hono": ">=4",
|
|
102
|
-
"@velajs/feature-flags": "^1.
|
|
114
|
+
"@velajs/feature-flags": "^1.32.0",
|
|
103
115
|
"@velajs/storage": "^1.33.0",
|
|
104
116
|
"@velajs/vela": "^1.33.0",
|
|
105
117
|
"@velajs/testing": "^1.33.0"
|