| 1 | import * as Effect from "effect/Effect"; |
| 2 | |
| 3 | type TypeId = typeof TypeId; |
| 4 | const TypeId = "Cloudflare.AnalyticsEngine.Dataset" as const; |
| 5 | |
| 6 | export type DatasetProps = { |
| 7 | /** |
| 8 | * Dataset name. If omitted, the logical ID is used. |
| 9 | */ |
| 10 | dataset?: string; |
| 11 | }; |
| 12 | |
| 13 | /** |
| 14 | * A Cloudflare Workers Analytics Engine dataset binding. |
| 15 | * |
| 16 | * Analytics Engine datasets are configured as Worker bindings. The binding |
| 17 | * exposes `writeDataPoint()` at runtime and does not require separate |
| 18 | * provisioning through the Cloudflare API. |
| 19 | * |
| 20 | * |
| 21 | * ### Binding to a Worker |
| 22 | * **Example:** Basic Analytics Engine binding |
| 23 | * ```typescript |
| 24 | * const Analytics = yield* Cloudflare.AnalyticsEngine.Dataset("Analytics", { |
| 25 | * dataset: "app-events", |
| 26 | * }); |
| 27 | * |
| 28 | * export const Worker = Cloudflare.Worker("Worker", { |
| 29 | * main: "./src/worker.ts", |
| 30 | * bindings: { Analytics }, |
| 31 | * }); |
| 32 | * ``` |
| 33 | * |
| 34 | * **Example:** Effect-style worker |
| 35 | * ```typescript |
| 36 | * const analytics = yield* Cloudflare.AnalyticsEngine.WriteDataset(Analytics); |
| 37 | * yield* analytics.writeDataPoint({ blobs: ["signup"] }); |
| 38 | * ``` |
| 39 | * |
| 40 | * @resource |
| 41 | */ |
| 42 | export type Dataset = { |
| 43 | kind: TypeId; |
| 44 | name: string; |
| 45 | dataset: string; |
| 46 | }; |
| 47 | |
| 48 | export const isDataset = (value: unknown): value is Dataset => |
| 49 | typeof value === "object" && |
| 50 | value !== null && |
| 51 | "kind" in value && |
| 52 | (value as Dataset).kind === TypeId; |
| 53 | |
| 54 | export const Dataset: { |
| 55 | (name: string, props?: DatasetProps): Effect.Effect<Dataset>; |
| 56 | } = Effect.fn(function* (name: string, props?: DatasetProps) { |
| 57 | return { |
| 58 | kind: TypeId, |
| 59 | name, |
| 60 | dataset: props?.dataset ?? name, |
| 61 | } satisfies Dataset; |
| 62 | }); |