The best way to control Claude Code, Codex and more from any computer or phone

main
ts 315 lines 10.6 KB
Raw
1 import * as stream from "@distilled.cloud/cloudflare/stream";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Predicate from "effect/Predicate";
8 import * as Stream from "effect/Stream";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 const TypeId = "Cloudflare.Stream.Watermark" as const;
13 type TypeId = typeof TypeId;
14
15 /**
16 * Location of the watermark image on the video.
17 */
18 export type WatermarkPosition = "upperRight" | "upperLeft" | "lowerLeft" | "lowerRight" | "center";
19
20 export type WatermarkProps = {
21 /**
22 * A short description of the watermark profile. If omitted, a unique
23 * name is generated from the app, stage, and logical ID. Watermark
24 * profiles have no update endpoint — changing the name triggers a
25 * replacement.
26 * @default ${app}-${stage}-${id}
27 */
28 name?: string;
29 /**
30 * URL of the watermark image (a PNG up to 2 MiB) for Cloudflare to
31 * download. Changing the URL triggers a replacement.
32 */
33 url: string;
34 /**
35 * The translucency of the image. `0.0` is completely transparent and
36 * `1.0` is completely opaque. Changing the opacity triggers a
37 * replacement.
38 * @default 1.0
39 */
40 opacity?: number;
41 /**
42 * The whitespace between the adjacent edges (determined by position)
43 * of the video and the image. `0.0` is no padding, `1.0` is a fully
44 * padded video width or length. Changing the padding triggers a
45 * replacement.
46 * @default 0.05
47 */
48 padding?: number;
49 /**
50 * The location of the image. Note that `center` ignores the `padding`
51 * parameter. Changing the position triggers a replacement.
52 * @default "upperRight"
53 */
54 position?: WatermarkPosition;
55 /**
56 * The size of the image relative to the overall size of the video.
57 * `0.0` means no scaling, `1.0` fills the entire video. Changing the
58 * scale triggers a replacement.
59 * @default 0.15
60 */
61 scale?: number;
62 };
63
64 export type WatermarkAttributes = {
65 /**
66 * The unique identifier for the watermark profile (Cloudflare `uid`).
67 */
68 watermarkId: string;
69 /**
70 * The Cloudflare account the watermark profile belongs to.
71 */
72 accountId: string;
73 /**
74 * A short description of the watermark profile.
75 */
76 name: string;
77 /**
78 * The date and time the watermark profile was created.
79 */
80 created: string | undefined;
81 /**
82 * The source URL the watermark image was downloaded from.
83 */
84 downloadedFrom: string | undefined;
85 /**
86 * The translucency of the image.
87 */
88 opacity: number;
89 /**
90 * The whitespace between the video edges and the image.
91 */
92 padding: number;
93 /**
94 * The location of the image.
95 */
96 position: WatermarkPosition;
97 /**
98 * The size of the image relative to the overall size of the video.
99 */
100 scale: number;
101 /**
102 * The size of the image in bytes.
103 */
104 size: number | undefined;
105 /**
106 * The height of the image in pixels.
107 */
108 height: number | undefined;
109 /**
110 * The width of the image in pixels.
111 */
112 width: number | undefined;
113 };
114
115 export type Watermark = Resource<TypeId, WatermarkProps, WatermarkAttributes, never, Providers>;
116
117 /**
118 * A Cloudflare Stream watermark profile — a PNG image stamped onto
119 * videos at upload time.
120 *
121 * Watermark profiles are create-only: Cloudflare exposes no update
122 * endpoint, so **every** prop change triggers a replacement (a new
123 * profile is created and the old one deleted). The image is downloaded
124 * by Cloudflare from the given URL at creation time.
125 *
126 * Requires the Stream subscription to be enabled on the account.
127 * ### Creating a watermark
128 * **Example:** Default watermark from an image URL
129 * ```typescript
130 * const watermark = yield* Cloudflare.Stream.Watermark("Logo", {
131 * url: "https://example.com/logo.png",
132 * });
133 * ```
134 *
135 * **Example:** Centered semi-transparent watermark
136 * ```typescript
137 * const watermark = yield* Cloudflare.Stream.Watermark("Logo", {
138 * url: "https://example.com/logo.png",
139 * position: "center",
140 * opacity: 0.5,
141 * scale: 0.3,
142 * });
143 * ```
144 *
145 * @see https://developers.cloudflare.com/stream/edit-videos/applying-watermarks/
146 *
147 * @resource
148 * @product Stream
149 * @category Media
150 */
151 export const Watermark = Resource<Watermark>(TypeId);
152
153 /**
154 * Returns true if the given value is a Watermark resource.
155 */
156 export const isWatermark = (value: unknown): value is Watermark =>
157 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
158
159 export const WatermarkProvider = () =>
160 Provider.succeed(Watermark, {
161 stables: ["watermarkId", "accountId", "created", "downloadedFrom", "size", "height", "width"],
162
163 diff: Effect.fn(function* ({ id, olds, news, output }) {
164 const { accountId } = yield* yield* CloudflareEnvironment;
165 if (output !== undefined && output.accountId !== accountId) {
166 return { action: "replace" } as const;
167 }
168 if (olds === undefined) return undefined;
169 // `news` may still contain unresolved Outputs at plan time — let
170 // the engine apply the default update logic in that case.
171 if (!isResolved(news)) return undefined;
172 // No update endpoint — any prop change is a replacement. Compare
173 // against the observed output where the API echoes the value, and
174 // against olds for the create-only `url`.
175 const oldName = output?.name ?? olds.name ?? (yield* watermarkName(id, olds.name));
176 const newName = yield* watermarkName(id, news.name);
177 if (
178 newName !== oldName ||
179 news.url !== olds.url ||
180 (news.opacity ?? 1.0) !== (output?.opacity ?? olds.opacity ?? 1.0) ||
181 (news.padding ?? 0.05) !== (output?.padding ?? olds.padding ?? 0.05) ||
182 (news.position ?? "upperRight") !== (output?.position ?? olds.position ?? "upperRight") ||
183 (news.scale ?? 0.15) !== (output?.scale ?? olds.scale ?? 0.15)
184 ) {
185 return { action: "replace" } as const;
186 }
187 return undefined;
188 }),
189
190 read: Effect.fn(function* ({ id, output, olds, previous }) {
191 const { accountId } = yield* yield* CloudflareEnvironment;
192 const acct = output?.accountId ?? accountId;
193
194 if (output?.watermarkId) {
195 const observed = yield* getWatermark(acct, output.watermarkId);
196 return observed ? toAttributes(observed, acct) : undefined;
197 }
198 // Cold read — recover from lost state by matching the
199 // deterministic physical name. Names are not unique on
200 // Cloudflare's side; an exact match on our generated/explicit
201 // name is the best identity we have.
202 const name = yield* watermarkName(id, olds?.name);
203 const match = yield* findByName(acct, name);
204 // A replacement reuses the name: the watermark it is replacing is not
205 // the replacement.
206 if (!match || match.uid === previous?.watermarkId) return undefined;
207 return toAttributes(match, acct);
208 }),
209
210 reconcile: Effect.fn(function* ({ id, news, output }) {
211 const { accountId } = yield* yield* CloudflareEnvironment;
212 const name = yield* watermarkName(id, news.name);
213
214 // Observe — the uid cached on `output` is a hint, not a
215 // guarantee: a not-found falls through to "missing" and we
216 // recreate.
217 const observed = output?.watermarkId
218 ? yield* getWatermark(output.accountId ?? accountId, output.watermarkId)
219 : undefined;
220
221 if (observed) {
222 // Create-only resource — prop drift is handled as a replacement
223 // by `diff`; nothing to sync here.
224 return toAttributes(observed, output?.accountId ?? accountId);
225 }
226
227 // Ensure — create with the full desired body. uids are
228 // auto-assigned so there is no AlreadyExists race to tolerate.
229 const created = yield* stream.createWatermark({
230 accountId,
231 name,
232 url: news.url,
233 opacity: news.opacity,
234 padding: news.padding,
235 position: news.position,
236 scale: news.scale,
237 });
238 return toAttributes(created, accountId);
239 }),
240
241 list: Effect.fn(function* () {
242 // Account-scoped collection — watermark profiles are enumerated
243 // per account. `listWatermarks` is paginated (items: "result");
244 // collect every page and hydrate into the `read` Attributes shape.
245 const { accountId } = yield* yield* CloudflareEnvironment;
246 return yield* stream.listWatermarks.pages({ accountId }).pipe(
247 Stream.runCollect,
248 Effect.map((chunk) =>
249 Array.from(chunk).flatMap((page) =>
250 (page.result ?? []).map((w) => toAttributes(w, accountId)),
251 ),
252 ),
253 );
254 }),
255
256 delete: Effect.fn(function* ({ output }) {
257 // Idempotent — a watermark already deleted out-of-band surfaces
258 // as `WatermarkNotFound` (Cloudflare error code 10003).
259 yield* stream
260 .deleteWatermark({
261 accountId: output.accountId,
262 identifier: output.watermarkId,
263 })
264 .pipe(Effect.catchTag("WatermarkNotFound", () => Effect.void));
265 }),
266 });
267
268 /**
269 * Read a watermark by uid, mapping "gone" (`WatermarkNotFound`,
270 * Cloudflare error code 10003) to `undefined`.
271 */
272 const getWatermark = (accountId: string, watermarkId: string) =>
273 stream
274 .getWatermark({ accountId, identifier: watermarkId })
275 .pipe(Effect.catchTag("WatermarkNotFound", () => Effect.undefined));
276
277 /**
278 * Find a watermark by exact name. Names are not unique — if several
279 * watermarks carry the same name, pick the oldest for determinism.
280 */
281 const findByName = (accountId: string, name: string) =>
282 stream.listWatermarks({ accountId }).pipe(
283 Effect.map((list) =>
284 [...list.result]
285 .filter((w) => w.name === name)
286 .sort((a, b) => (a.created ?? "").localeCompare(b.created ?? ""))
287 .at(0),
288 ),
289 );
290
291 const watermarkName = (id: string, name: string | undefined) =>
292 Effect.gen(function* () {
293 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
294 });
295
296 const toAttributes = (
297 watermark:
298 | stream.GetWatermarkResponse
299 | stream.CreateWatermarkResponse
300 | stream.ListWatermarksResponse["result"][number],
301 accountId: string,
302 ): WatermarkAttributes => ({
303 watermarkId: watermark.uid ?? "",
304 accountId,
305 name: watermark.name ?? "",
306 created: watermark.created ?? undefined,
307 downloadedFrom: watermark.downloadedFrom ?? undefined,
308 opacity: watermark.opacity ?? 1.0,
309 padding: watermark.padding ?? 0.05,
310 position: (watermark.position ?? "upperRight") as WatermarkPosition,
311 scale: watermark.scale ?? 0.15,
312 size: watermark.size ?? undefined,
313 height: watermark.height ?? undefined,
314 width: watermark.width ?? undefined,
315 });