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

main
ts 364 lines 11.3 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 DeleteTerminalReader,
4 GetTerminalReaders,
5 GetTerminalReader,
6 CreateTerminalReader,
7 UpdateTerminalReader,
8 type DeletedTerminalReader,
9 type TerminalReader as StripeTerminalReader,
10 type TerminalReaderDeviceType,
11 type TerminalReaderLocation,
12 type TerminalReaderStatus,
13 } from "@distilled.cloud/stripe/stripe";
14 import { Unowned } from "alchemy/AdoptPolicy";
15 import { isResolved } from "alchemy/Diff";
16 import * as Provider from "alchemy/Provider";
17 import { Resource } from "alchemy/Resource";
18 import { tagRecord } from "alchemy/Tags";
19 import * as Data from "effect/Data";
20 import * as Effect from "effect/Effect";
21 import {
22 alchemyMetadataKeys,
23 createInternalMetadata,
24 diffMetadata,
25 hasAlchemyMetadata,
26 stripInternalMetadata,
27 toMetadata,
28 } from "./Metadata.ts";
29 import { isMissingStripeResource } from "./missing.ts";
30 import type { Providers } from "./Providers.ts";
31
32 export type { TerminalReaderDeviceType, TerminalReaderStatus };
33
34 const LIST_PAGE_SIZE = 100;
35 const LIST_MAX_PAGES = 100;
36
37 export interface TerminalReaderProps {
38 /**
39 * Pairing code generated by the reader (or a simulated-reader code in
40 * test mode such as `"simulated-wpe"`, `"simulated-s700"`, or
41 * `"simulated-s710"`). Create-only — used when the reader is missing;
42 * changing it on an existing reader is ignored.
43 */
44 registrationCode: string;
45 /**
46 * Custom label for easier identification. If omitted on create, Stripe
47 * uses the registration code. Mutable.
48 */
49 label?: string;
50 /**
51 * Id of the Terminal Location to assign the reader to (`tml_…`).
52 * Create-only — changing it replaces the reader. Simulated readers
53 * typically require a location.
54 */
55 location?: string;
56 /**
57 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
58 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
59 * not contain `:`. Mutable.
60 */
61 metadata?: Record<string, string>;
62 }
63
64 export type TerminalReader = Resource<
65 "Stripe.TerminalReader",
66 TerminalReaderProps,
67 {
68 /** Stripe Terminal reader id (`tmr_…`). */
69 id: string;
70 /** Custom label for easier identification. */
71 label: string;
72 /** Assigned Terminal Location id (`tml_…`), if any. */
73 location: string | undefined;
74 /** Device type of the reader (e.g. `simulated_wisepos_e`). */
75 deviceType: TerminalReaderDeviceType;
76 /** Serial number of the reader. */
77 serialNumber: string;
78 /** Networking status, if reported. */
79 status: TerminalReaderStatus | undefined;
80 /** Local IP address of the reader, if known. */
81 ipAddress: string | undefined;
82 /** Current software version of the reader, if known. */
83 deviceSwVersion: string | undefined;
84 /**
85 * Last time this reader reported to Stripe, in milliseconds since the
86 * Unix epoch.
87 */
88 lastSeenAt: number | undefined;
89 /** User-defined metadata (Alchemy ownership keys stripped). */
90 metadata: Record<string, string>;
91 /** Whether the reader exists in live mode. */
92 livemode: boolean;
93 },
94 never,
95 Providers
96 >;
97
98 /**
99 * A Stripe Terminal Reader — a physical or simulated card reader that
100 * accepts in-person payments. `registrationCode` and `location` are
101 * create-only; changing `location` replaces the reader. `label` and
102 * `metadata` update in place. Destroy deletes the reader.
103 *
104 * In test mode, register a simulated WisePOS E with
105 * `registrationCode: "simulated-wpe"` (or `"simulated-s700"` /
106 * `"simulated-s710"`). Simulated readers typically need a Terminal
107 * Location.
108 *
109 * @see https://docs.stripe.com/api/terminal/readers
110 *
111 * ### Creating a Reader
112 * **Example:** Simulated WisePOS E
113 * ```typescript
114 * const reader = yield* Stripe.TerminalReader("front-counter", {
115 * registrationCode: "simulated-wpe",
116 * label: "Front counter",
117 * location: locationId,
118 * });
119 * ```
120 *
121 * **Example:** Physical reader with metadata
122 * ```typescript
123 * const reader = yield* Stripe.TerminalReader("pos-1", {
124 * registrationCode: pairingCode,
125 * label: "POS 1",
126 * location: location.id,
127 * metadata: { station: "1" },
128 * });
129 * ```
130 *
131 * ### Updating a Reader
132 * **Example:** Relabel and retag
133 * ```typescript
134 * const reader = yield* Stripe.TerminalReader("front-counter", {
135 * registrationCode: "simulated-wpe",
136 * label: "Front counter (updated)",
137 * location: locationId,
138 * metadata: { station: "1", floor: "lobby" },
139 * });
140 * ```
141 *
142 * ### Deleting a Reader
143 * **Example:** Destroy deletes the reader
144 * ```typescript
145 * const reader = yield* Stripe.TerminalReader("front-counter", {
146 * registrationCode: "simulated-wpe",
147 * location: locationId,
148 * });
149 * // stack.destroy() deletes the reader
150 * ```
151 *
152 * @resource
153 * @product Terminal
154 */
155 export const TerminalReader = Resource<TerminalReader>("Stripe.TerminalReader");
156
157 export class TerminalReaderNotResolved extends Data.TaggedError(
158 "Stripe.TerminalReaderNotResolved",
159 )<{
160 reader: string;
161 }> {}
162
163 type TerminalReaderAttributes = TerminalReader["Attributes"];
164
165 const userMetadata = (
166 metadata: Record<string, string | undefined> | null | undefined,
167 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
168
169 const isDeletedReader = (
170 value: StripeTerminalReader | DeletedTerminalReader,
171 ): value is DeletedTerminalReader => "deleted" in value && value.deleted === true;
172
173 const asReader = (
174 value: StripeTerminalReader | DeletedTerminalReader | undefined,
175 ): StripeTerminalReader | undefined => {
176 if (value === undefined || isDeletedReader(value)) return undefined;
177 return value;
178 };
179
180 const locationIdOf = (location: TerminalReaderLocation | null | undefined): string | undefined => {
181 if (location == null) return undefined;
182 if (typeof location === "string") return location;
183 return location.id;
184 };
185
186 const toAttrs = (reader: StripeTerminalReader): TerminalReaderAttributes => ({
187 id: reader.id,
188 label: reader.label,
189 location: locationIdOf(reader.location),
190 deviceType: reader.device_type,
191 serialNumber: reader.serial_number,
192 status: reader.status ?? undefined,
193 ipAddress: reader.ip_address ?? undefined,
194 deviceSwVersion: reader.device_sw_version ?? undefined,
195 lastSeenAt: reader.last_seen_at ?? undefined,
196 metadata: userMetadata(reader.metadata),
197 livemode: reader.livemode,
198 });
199
200 const isMissingReader = isMissingStripeResource;
201
202 const getById = (reader: string) =>
203 GetTerminalReader({ reader }).pipe(
204 Effect.map(asReader),
205 Effect.catchIf(isMissingReader, () => Effect.undefined),
206 );
207
208 const listAllReaders = Effect.fn(function* () {
209 const readers: StripeTerminalReader[] = [];
210 let startingAfter: string | undefined;
211 for (let page = 0; page < LIST_MAX_PAGES; page++) {
212 const response = yield* GetTerminalReaders({
213 limit: LIST_PAGE_SIZE,
214 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
215 });
216 readers.push(...response.data);
217 if (!response.has_more || response.data.length === 0) {
218 break;
219 }
220 startingAfter = response.data[response.data.length - 1]?.id;
221 if (startingAfter === undefined) {
222 break;
223 }
224 }
225 return readers;
226 });
227
228 const findByAlchemyId = Effect.fn(function* (id: string) {
229 const readers = yield* listAllReaders();
230 const matches: StripeTerminalReader[] = [];
231 for (const reader of readers) {
232 if (yield* hasAlchemyMetadata(id, tagRecord(reader.metadata))) {
233 matches.push(reader);
234 }
235 }
236 matches.sort((a, b) => (b.last_seen_at ?? 0) - (a.last_seen_at ?? 0));
237 return matches[0];
238 });
239
240 const observe = Effect.fn(function* (input: { id?: string; logicalId: string }) {
241 if (input.id !== undefined) {
242 const byId = yield* getById(input.id);
243 if (byId !== undefined) return byId;
244 }
245 return yield* findByAlchemyId(input.logicalId);
246 });
247
248 const desiredMetadata = Effect.fn(function* (
249 id: string,
250 metadata: Record<string, string> | undefined,
251 ) {
252 return {
253 ...toMetadata(metadata),
254 ...(yield* createInternalMetadata(id)),
255 };
256 });
257
258 const shouldReplace = (
259 news: TerminalReaderProps,
260 output: TerminalReaderAttributes | undefined,
261 ): boolean => {
262 if (output === undefined) return false;
263 if (news.location !== undefined && news.location !== (output.location ?? undefined)) {
264 return true;
265 }
266 return false;
267 };
268
269 export const TerminalReaderProvider = () =>
270 Provider.succeed(TerminalReader, {
271 stables: ["id", "deviceType", "serialNumber", "location", "livemode"],
272
273 diff: Effect.fn(function* ({ news, output }) {
274 if (!isResolved(news)) return undefined;
275 if (shouldReplace(news, output)) {
276 return { action: "replace" } as const;
277 }
278 return undefined;
279 }),
280
281 read: Effect.fn(function* ({ id, output }) {
282 const existing = yield* observe({
283 id: output?.id,
284 logicalId: id,
285 });
286 if (existing === undefined) return undefined;
287 const attrs = toAttrs(existing);
288 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
289 }),
290
291 list: Effect.fn(function* () {
292 const readers = yield* listAllReaders();
293 return readers
294 .filter((reader) => {
295 const metadata = tagRecord(reader.metadata);
296 return metadata[alchemyMetadataKeys.stack] !== undefined;
297 })
298 .map(toAttrs);
299 }),
300
301 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
302 const metadata = yield* desiredMetadata(id, news.metadata);
303
304 let current: StripeTerminalReader | undefined = yield* observe({
305 id: output?.id,
306 logicalId: id,
307 });
308 if (current !== undefined && shouldReplace(news, toAttrs(current))) {
309 current = undefined;
310 }
311
312 if (current === undefined) {
313 current = yield* CreateTerminalReader({
314 registration_code: news.registrationCode,
315 metadata,
316 ...(news.label !== undefined ? { label: news.label } : {}),
317 ...(news.location !== undefined ? { location: news.location } : {}),
318 }).pipe(
319 withRequestOptions({
320 idempotencyKey: `alchemy-terminal-reader-${instanceId}`,
321 }),
322 );
323 }
324
325 if (current === undefined) {
326 return yield* new TerminalReaderNotResolved({
327 reader: output?.id ?? news.registrationCode,
328 });
329 }
330
331 const observedMetadata = tagRecord(current.metadata);
332 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
333 const metadataChanged = upsert.length > 0 || removed.length > 0;
334 const labelChanged = news.label !== undefined && current.label !== news.label;
335
336 if (!labelChanged && !metadataChanged) {
337 return toAttrs(current);
338 }
339
340 const updated = yield* UpdateTerminalReader({
341 reader: current.id,
342 ...(labelChanged ? { label: news.label } : {}),
343 ...(metadataChanged
344 ? {
345 metadata: {
346 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
347 ...Object.fromEntries(removed.map((key) => [key, ""])),
348 },
349 }
350 : {}),
351 });
352 const reader = asReader(updated);
353 if (reader === undefined) {
354 return yield* new TerminalReaderNotResolved({ reader: current.id });
355 }
356 return toAttrs(reader);
357 }),
358
359 delete: Effect.fn(function* ({ output }) {
360 yield* DeleteTerminalReader({ reader: output.id }).pipe(
361 Effect.catchIf(isMissingReader, () => Effect.void),
362 );
363 }),
364 });