@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 317 lines 9.84 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 GetFileLinks,
4 GetFileLink,
5 CreateFileLink,
6 UpdateFileLink,
7 type FileLink as StripeFileLink,
8 } from "@distilled.cloud/stripe/stripe";
9 import { Unowned } from "alchemy/AdoptPolicy";
10 import { isResolved } from "alchemy/Diff";
11 import * as Provider from "alchemy/Provider";
12 import { Resource } from "alchemy/Resource";
13 import { tagRecord } from "alchemy/Tags";
14 import * as Effect from "effect/Effect";
15 import {
16 alchemyMetadataKeys,
17 createInternalMetadata,
18 diffMetadata,
19 hasAlchemyMetadata,
20 stripInternalMetadata,
21 toMetadata,
22 } from "./Metadata.ts";
23 import { isMissingStripeResource } from "./missing.ts";
24 import type { Providers } from "./Providers.ts";
25
26 const LIST_PAGE_SIZE = 100;
27 const LIST_MAX_PAGES = 100;
28
29 export interface FileLinkProps {
30 /**
31 * Id of the Stripe File this link points at (`file_…`). The file's
32 * `purpose` must allow links (for example `dispute_evidence` or
33 * `tax_document_user_upload`). Create-only — changing it replaces
34 * the file link.
35 */
36 file: string;
37 /**
38 * Unix timestamp after which the link is unusable. Omit for a link
39 * that never expires. Mutable — pass `undefined` to clear a previously
40 * set expiry. Expired links cannot be updated.
41 */
42 expiresAt?: number;
43 /**
44 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
45 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
46 * not contain `:`. Mutable.
47 */
48 metadata?: Record<string, string>;
49 }
50
51 export type FileLink = Resource<
52 "Stripe.FileLink",
53 FileLinkProps,
54 {
55 /** Stripe file link id (`link_…`). */
56 id: string;
57 /** Id of the File this link points at (`file_…`). */
58 file: string;
59 /** Public URL to download the file, if the link is still valid. */
60 url: string | undefined;
61 /** Whether the link has already expired. */
62 expired: boolean;
63 /** Unix timestamp after which the link is unusable, if set. */
64 expiresAt: number | undefined;
65 /** User-defined metadata (Alchemy ownership keys stripped). */
66 metadata: Record<string, string>;
67 /** Unix timestamp when the file link was created. */
68 created: number;
69 /** Whether the file link exists in live mode. */
70 livemode: boolean;
71 },
72 never,
73 Providers
74 >;
75
76 /**
77 * A Stripe File Link — a public URL for a File that does not require
78 * Stripe authentication. `file` is create-only; changing it replaces the
79 * link. `expiresAt` and `metadata` update in place. Expired links cannot
80 * be updated. Destroy expires the link (`expires_at: "now"`) rather than
81 * deleting it — Stripe has no file-link delete API.
82 *
83 * @see https://docs.stripe.com/api/file_links
84 *
85 * ### Creating a File Link
86 * **Example:** Link a file
87 * ```typescript
88 * const link = yield* Stripe.FileLink("report", {
89 * file: "file_123",
90 * });
91 * ```
92 *
93 * **Example:** Expiring link with metadata
94 * ```typescript
95 * const link = yield* Stripe.FileLink("report", {
96 * file: "file_123",
97 * expiresAt: 1900000000,
98 * metadata: { kind: "report" },
99 * });
100 * ```
101 *
102 * ### Updating a File Link
103 * **Example:** Extend expiry and retag
104 * ```typescript
105 * const link = yield* Stripe.FileLink("report", {
106 * file: "file_123",
107 * expiresAt: 1920000000,
108 * metadata: { kind: "report", env: "prod" },
109 * });
110 * ```
111 *
112 * ### Expiring a File Link
113 * **Example:** Destroy expires rather than deleting
114 * ```typescript
115 * const link = yield* Stripe.FileLink("report", {
116 * file: "file_123",
117 * });
118 * // stack.destroy() sets expires_at to now
119 * ```
120 *
121 * @resource
122 * @product Files
123 */
124 export const FileLink = Resource<FileLink>("Stripe.FileLink");
125
126 const userMetadata = (
127 metadata: Record<string, string | undefined> | null | undefined,
128 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
129
130 const fileIdOf = (file: StripeFileLink["file"]): string => {
131 if (typeof file === "string") return file;
132 return file.id;
133 };
134
135 const toAttrs = (link: StripeFileLink) => ({
136 id: link.id,
137 file: fileIdOf(link.file),
138 url: link.url ?? undefined,
139 expired: link.expired,
140 expiresAt: link.expires_at ?? undefined,
141 metadata: userMetadata(link.metadata),
142 created: link.created,
143 livemode: link.livemode,
144 });
145
146 const isMissingFileLink = isMissingStripeResource;
147
148 const getById = (link: string) =>
149 GetFileLink({ link }).pipe(Effect.catchIf(isMissingFileLink, () => Effect.undefined));
150
151 const paginateFileLinks = Effect.fn(function* (query: { expired?: boolean; file?: string }) {
152 const links: StripeFileLink[] = [];
153 let startingAfter: string | undefined;
154 for (let page = 0; page < LIST_MAX_PAGES; page++) {
155 const response = yield* GetFileLinks({
156 ...(query.expired !== undefined ? { expired: query.expired } : {}),
157 ...(query.file !== undefined ? { file: query.file } : {}),
158 limit: LIST_PAGE_SIZE,
159 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
160 });
161 links.push(...response.data);
162 if (!response.has_more || response.data.length === 0) {
163 break;
164 }
165 startingAfter = response.data[response.data.length - 1]?.id;
166 if (startingAfter === undefined) {
167 break;
168 }
169 }
170 return links;
171 });
172
173 const listUnexpired = () => paginateFileLinks({ expired: false });
174
175 const findByAlchemyId = Effect.fn(function* (id: string, links: ReadonlyArray<StripeFileLink>) {
176 const matches: StripeFileLink[] = [];
177 for (const link of links) {
178 if (link.expired) continue;
179 if (yield* hasAlchemyMetadata(id, tagRecord(link.metadata))) {
180 matches.push(link);
181 }
182 }
183 matches.sort((a, b) => b.created - a.created);
184 return matches[0];
185 });
186
187 const observe = Effect.fn(function* (input: { id?: string; logicalId: string; file?: string }) {
188 if (input.id !== undefined) {
189 const byId = yield* getById(input.id);
190 if (byId !== undefined && !byId.expired) return byId;
191 }
192 if (input.file !== undefined) {
193 const byFile = yield* findByAlchemyId(
194 input.logicalId,
195 yield* paginateFileLinks({ expired: false, file: input.file }),
196 );
197 if (byFile !== undefined) return byFile;
198 }
199 return yield* findByAlchemyId(input.logicalId, yield* listUnexpired());
200 });
201
202 const desiredMetadata = Effect.fn(function* (
203 id: string,
204 metadata: Record<string, string> | undefined,
205 ) {
206 return {
207 ...toMetadata(metadata),
208 ...(yield* createInternalMetadata(id)),
209 };
210 });
211
212 export const FileLinkProvider = () =>
213 Provider.succeed(FileLink, {
214 stables: ["id", "file", "created", "livemode"],
215
216 diff: Effect.fn(function* ({ news, output }) {
217 if (!isResolved(news)) return undefined;
218 if (output !== undefined && news.file !== output.file) {
219 return { action: "replace" as const };
220 }
221 return undefined;
222 }),
223
224 read: Effect.fn(function* ({ id, olds, output }) {
225 const existing = yield* observe({
226 id: output?.id,
227 logicalId: id,
228 file: olds?.file ?? output?.file,
229 });
230 if (existing === undefined || existing.expired) return undefined;
231 const attrs = toAttrs(existing);
232 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
233 }),
234
235 list: Effect.fn(function* () {
236 // Default list API includes expired links; those are already
237 // "deleted" (expire-on-destroy) and must not re-enter nuke.
238 const links = yield* listUnexpired();
239 return links
240 .filter((link) => {
241 const metadata = tagRecord(link.metadata);
242 return metadata[alchemyMetadataKeys.stack] !== undefined;
243 })
244 .map(toAttrs);
245 }),
246
247 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
248 const metadata = yield* desiredMetadata(id, news.metadata);
249 const desiredExpiresAt = news.expiresAt;
250
251 let current: StripeFileLink | undefined = yield* observe({
252 id: output?.id,
253 logicalId: id,
254 file: news.file,
255 });
256 // Expired links cannot be updated, and the File on a link is
257 // immutable. Treat either as missing so ensure creates a new link.
258 if (current !== undefined && current.expired) {
259 current = undefined;
260 }
261 if (current !== undefined && fileIdOf(current.file) !== news.file) {
262 current = undefined;
263 }
264
265 if (current === undefined) {
266 current = yield* CreateFileLink({
267 file: news.file,
268 metadata,
269 ...(desiredExpiresAt !== undefined ? { expires_at: desiredExpiresAt } : {}),
270 }).pipe(
271 withRequestOptions({
272 idempotencyKey: `alchemy-file-link-${instanceId}`,
273 }),
274 );
275 }
276
277 const observedMetadata = tagRecord(current.metadata);
278 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
279 const metadataChanged = upsert.length > 0 || removed.length > 0;
280 const observedExpiresAt = current.expires_at ?? undefined;
281 const expiresAtChanged = observedExpiresAt !== desiredExpiresAt;
282
283 if (!metadataChanged && !expiresAtChanged) {
284 return toAttrs(current);
285 }
286
287 const updated = yield* UpdateFileLink({
288 link: current.id,
289 ...(expiresAtChanged
290 ? {
291 expires_at: desiredExpiresAt !== undefined ? desiredExpiresAt : "",
292 }
293 : {}),
294 ...(metadataChanged
295 ? {
296 metadata: {
297 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
298 ...Object.fromEntries(removed.map((key) => [key, ""])),
299 },
300 }
301 : {}),
302 });
303 return toAttrs(updated);
304 }),
305
306 delete: Effect.fn(function* ({ output }) {
307 const existing = yield* getById(output.id);
308 if (existing === undefined || existing.expired) return;
309 yield* UpdateFileLink({
310 link: existing.id,
311 expires_at: "now",
312 }).pipe(
313 Effect.catchIf(isMissingFileLink, () => Effect.void),
314 Effect.catchTag("InvalidRequestError", () => Effect.void),
315 );
316 }),
317 });