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

main
ts 573 lines 18.8 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 DeleteTerminalLocation,
4 GetTerminalLocations,
5 GetTerminalLocation,
6 CreateTerminalLocation,
7 UpdateTerminalLocation,
8 type Address,
9 type DeletedTerminalLocation,
10 type LegalEntityJapanAddress,
11 type CreateAccountRequestCompanyAddressKana,
12 type CreateTerminalLocationRequestAddress,
13 type TerminalLocation as StripeTerminalLocation,
14 } from "@distilled.cloud/stripe/stripe";
15 import { Unowned } from "alchemy/AdoptPolicy";
16 import { deepEqual, isResolved } from "alchemy/Diff";
17 import { createPhysicalName } from "alchemy/PhysicalName";
18 import * as Provider from "alchemy/Provider";
19 import { Resource } from "alchemy/Resource";
20 import { tagRecord } from "alchemy/Tags";
21 import * as Data from "effect/Data";
22 import * as Effect from "effect/Effect";
23 import {
24 alchemyMetadataKeys,
25 createInternalMetadata,
26 diffMetadata,
27 hasAlchemyMetadata,
28 stripInternalMetadata,
29 toMetadata,
30 } from "./Metadata.ts";
31 import { isMissingStripeResource } from "./missing.ts";
32 import type { Providers } from "./Providers.ts";
33
34 const NAME_MAX_LENGTH = 1000;
35 const LIST_PAGE_SIZE = 100;
36 const LIST_MAX_PAGES = 100;
37
38 export interface TerminalLocationAddress {
39 /**
40 * City, district, suburb, town, or village. Required in most countries.
41 */
42 city?: string;
43 /**
44 * Two-letter ISO 3166-1 alpha-2 country code. Create-only — changing
45 * it replaces the location.
46 */
47 country: string;
48 /**
49 * Address line 1 (street, PO Box, or company name).
50 */
51 line1?: string;
52 /**
53 * Address line 2 (apartment, suite, unit, or building).
54 */
55 line2?: string;
56 /**
57 * ZIP or postal code. Required in most countries.
58 */
59 postalCode?: string;
60 /**
61 * State, county, province, or region (ISO 3166-2). Required in the US
62 * and Canada.
63 */
64 state?: string;
65 }
66
67 export interface TerminalLocationJapanAddress {
68 /**
69 * City or ward.
70 */
71 city?: string;
72 /**
73 * Two-letter ISO 3166-1 alpha-2 country code.
74 */
75 country?: string;
76 /**
77 * Block or building number.
78 */
79 line1?: string;
80 /**
81 * Building details.
82 */
83 line2?: string;
84 /**
85 * Postal code.
86 */
87 postalCode?: string;
88 /**
89 * Prefecture.
90 */
91 state?: string;
92 /**
93 * Town or cho-me.
94 */
95 town?: string;
96 }
97
98 export interface TerminalLocationProps {
99 /**
100 * Display name of the location. If omitted, a unique name is generated
101 * from the stack, stage, and logical id. Maximum length is 1000
102 * characters. Mutable.
103 */
104 displayName?: string;
105 /**
106 * Full address of the location. `country` is required and create-only —
107 * changing it replaces the location. Other fields update in place;
108 * required fields vary by country.
109 */
110 address: TerminalLocationAddress;
111 /**
112 * Kana variation of the full address (Japan only). Mutable.
113 */
114 addressKana?: TerminalLocationJapanAddress;
115 /**
116 * Kanji variation of the full address (Japan only). Mutable.
117 */
118 addressKanji?: TerminalLocationJapanAddress;
119 /**
120 * Id of a Terminal Configuration applied to every reader at this
121 * location. Empty string unsets. Mutable.
122 */
123 configurationOverrides?: string;
124 /**
125 * Kana variation of the display name (Japan only). Mutable.
126 */
127 displayNameKana?: string;
128 /**
129 * Kanji variation of the display name (Japan only). Mutable.
130 */
131 displayNameKanji?: string;
132 /**
133 * Phone number for the location. Empty string unsets. Mutable.
134 */
135 phone?: string;
136 /**
137 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
138 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
139 * not contain `:`. Mutable.
140 */
141 metadata?: Record<string, string>;
142 }
143
144 export type TerminalLocation = Resource<
145 "Stripe.TerminalLocation",
146 TerminalLocationProps,
147 {
148 /** Stripe Terminal Location id (`tml_…`). */
149 id: string;
150 /** Display name of the location. */
151 displayName: string;
152 /** Full address of the location. */
153 address: TerminalLocationAddress;
154 /** Kana variation of the full address, if set. */
155 addressKana: TerminalLocationJapanAddress | undefined;
156 /** Kanji variation of the full address, if set. */
157 addressKanji: TerminalLocationJapanAddress | undefined;
158 /** Terminal Configuration id applied to readers at this location. */
159 configurationOverrides: string | undefined;
160 /** Kana variation of the display name, if set. */
161 displayNameKana: string | undefined;
162 /** Kanji variation of the display name, if set. */
163 displayNameKanji: string | undefined;
164 /** Phone number for the location, if set. */
165 phone: string | undefined;
166 /** User-defined metadata (Alchemy ownership keys stripped). */
167 metadata: Record<string, string>;
168 /** Whether the location exists in live mode. */
169 livemode: boolean;
170 },
171 never,
172 Providers
173 >;
174
175 /**
176 * A Stripe Terminal Location — a grouping of Terminal readers at a
177 * physical site. Display name, phone, metadata, configuration overrides,
178 * and address fields other than `country` update in place. Changing
179 * `address.country` replaces the location; re-register readers on the
180 * new one.
181 *
182 * Destroy hard-deletes the location.
183 *
184 * @see https://docs.stripe.com/api/terminal/locations
185 *
186 * ### Creating a Location
187 * **Example:** US storefront
188 * ```typescript
189 * const store = yield* Stripe.TerminalLocation("storefront", {
190 * displayName: "Market Street",
191 * address: {
192 * line1: "123 Market Street",
193 * city: "San Francisco",
194 * state: "CA",
195 * postalCode: "94105",
196 * country: "US",
197 * },
198 * });
199 * ```
200 *
201 * **Example:** Generated name with phone and metadata
202 * ```typescript
203 * const kiosk = yield* Stripe.TerminalLocation("kiosk", {
204 * address: {
205 * line1: "1 Infinite Loop",
206 * city: "Cupertino",
207 * state: "CA",
208 * postalCode: "95014",
209 * country: "US",
210 * },
211 * phone: "+14085551234",
212 * metadata: { region: "west" },
213 * });
214 * ```
215 *
216 * ### Updating a Location
217 * **Example:** Rename and retag
218 * ```typescript
219 * const store = yield* Stripe.TerminalLocation("storefront", {
220 * displayName: "Market Street Annex",
221 * address: {
222 * line1: "125 Market Street",
223 * city: "San Francisco",
224 * state: "CA",
225 * postalCode: "94105",
226 * country: "US",
227 * },
228 * metadata: { region: "west" },
229 * });
230 * ```
231 *
232 * ### Deleting a Location
233 * **Example:** Destroy deletes the location
234 * ```typescript
235 * // stack.destroy() / resource removal calls DELETE
236 * const store = yield* Stripe.TerminalLocation("storefront", {
237 * address: {
238 * line1: "123 Market Street",
239 * city: "San Francisco",
240 * state: "CA",
241 * postalCode: "94105",
242 * country: "US",
243 * },
244 * });
245 * ```
246 *
247 * @resource
248 * @product Terminal
249 */
250 export const TerminalLocation = Resource<TerminalLocation>("Stripe.TerminalLocation");
251
252 export class TerminalLocationNotResolved extends Data.TaggedError(
253 "Stripe.TerminalLocationNotResolved",
254 )<{
255 displayName: string;
256 }> {}
257
258 type TerminalLocationAttributes = TerminalLocation["Attributes"];
259
260 const userMetadata = (
261 metadata: Record<string, string | undefined> | null | undefined,
262 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
263
264 const optionalString = (value: string | null | undefined): string | undefined =>
265 value == null || value === "" ? undefined : value;
266
267 const fromObservedAddress = (address: Address): TerminalLocationAddress => ({
268 country: address.country ?? "",
269 ...(optionalString(address.city) !== undefined ? { city: optionalString(address.city) } : {}),
270 ...(optionalString(address.line1) !== undefined ? { line1: optionalString(address.line1) } : {}),
271 ...(optionalString(address.line2) !== undefined ? { line2: optionalString(address.line2) } : {}),
272 ...(optionalString(address.postal_code) !== undefined
273 ? { postalCode: optionalString(address.postal_code) }
274 : {}),
275 ...(optionalString(address.state) !== undefined ? { state: optionalString(address.state) } : {}),
276 });
277
278 const fromObservedJapanAddress = (
279 address: LegalEntityJapanAddress | undefined,
280 ): TerminalLocationJapanAddress | undefined => {
281 if (address === undefined) return undefined;
282 const mapped: TerminalLocationJapanAddress = {
283 ...(optionalString(address.city) !== undefined ? { city: optionalString(address.city) } : {}),
284 ...(optionalString(address.country) !== undefined
285 ? { country: optionalString(address.country) }
286 : {}),
287 ...(optionalString(address.line1) !== undefined
288 ? { line1: optionalString(address.line1) }
289 : {}),
290 ...(optionalString(address.line2) !== undefined
291 ? { line2: optionalString(address.line2) }
292 : {}),
293 ...(optionalString(address.postal_code) !== undefined
294 ? { postalCode: optionalString(address.postal_code) }
295 : {}),
296 ...(optionalString(address.state) !== undefined
297 ? { state: optionalString(address.state) }
298 : {}),
299 ...(optionalString(address.town) !== undefined ? { town: optionalString(address.town) } : {}),
300 };
301 return Object.keys(mapped).length > 0 ? mapped : undefined;
302 };
303
304 const toWireAddress = (address: TerminalLocationAddress): CreateTerminalLocationRequestAddress => ({
305 country: address.country,
306 ...(address.city !== undefined ? { city: address.city } : {}),
307 ...(address.line1 !== undefined ? { line1: address.line1 } : {}),
308 ...(address.line2 !== undefined ? { line2: address.line2 } : {}),
309 ...(address.postalCode !== undefined ? { postal_code: address.postalCode } : {}),
310 ...(address.state !== undefined ? { state: address.state } : {}),
311 });
312
313 const toWireJapanAddress = (
314 address: TerminalLocationJapanAddress,
315 ): CreateAccountRequestCompanyAddressKana => ({
316 ...(address.city !== undefined ? { city: address.city } : {}),
317 ...(address.country !== undefined ? { country: address.country } : {}),
318 ...(address.line1 !== undefined ? { line1: address.line1 } : {}),
319 ...(address.line2 !== undefined ? { line2: address.line2 } : {}),
320 ...(address.postalCode !== undefined ? { postal_code: address.postalCode } : {}),
321 ...(address.state !== undefined ? { state: address.state } : {}),
322 ...(address.town !== undefined ? { town: address.town } : {}),
323 });
324
325 const isDeletedLocation = (
326 value: StripeTerminalLocation | DeletedTerminalLocation,
327 ): value is DeletedTerminalLocation => "deleted" in value && value.deleted === true;
328
329 const asLocation = (
330 value: StripeTerminalLocation | DeletedTerminalLocation | undefined,
331 ): StripeTerminalLocation | undefined => {
332 if (value === undefined || isDeletedLocation(value)) return undefined;
333 return value;
334 };
335
336 const toAttrs = (location: StripeTerminalLocation): TerminalLocationAttributes => ({
337 id: location.id,
338 displayName: location.display_name,
339 address: fromObservedAddress(location.address),
340 addressKana: fromObservedJapanAddress(location.address_kana),
341 addressKanji: fromObservedJapanAddress(location.address_kanji),
342 configurationOverrides: optionalString(location.configuration_overrides),
343 displayNameKana: optionalString(location.display_name_kana),
344 displayNameKanji: optionalString(location.display_name_kanji),
345 phone: optionalString(location.phone),
346 metadata: userMetadata(location.metadata),
347 livemode: location.livemode,
348 });
349
350 const toDisplayName = (id: string, displayName: string | undefined, existing?: string) =>
351 Effect.gen(function* () {
352 return (
353 displayName ?? existing ?? (yield* createPhysicalName({ id, maxLength: NAME_MAX_LENGTH }))
354 );
355 });
356
357 const isMissingLocation = isMissingStripeResource;
358
359 const getById = (location: string) =>
360 GetTerminalLocation({ location }).pipe(
361 Effect.map(asLocation),
362 Effect.catchIf(isMissingLocation, () => Effect.undefined),
363 );
364
365 const listAllLocations = Effect.fn(function* () {
366 const locations: StripeTerminalLocation[] = [];
367 let startingAfter: string | undefined;
368 for (let page = 0; page < LIST_MAX_PAGES; page++) {
369 const response = yield* GetTerminalLocations({
370 limit: LIST_PAGE_SIZE,
371 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
372 });
373 locations.push(...response.data);
374 if (!response.has_more || response.data.length === 0) {
375 break;
376 }
377 startingAfter = response.data[response.data.length - 1]?.id;
378 if (startingAfter === undefined) {
379 break;
380 }
381 }
382 return locations;
383 });
384
385 const findByAlchemyId = Effect.fn(function* (id: string) {
386 const locations = yield* listAllLocations();
387 const matches: StripeTerminalLocation[] = [];
388 for (const location of locations) {
389 if (yield* hasAlchemyMetadata(id, tagRecord(location.metadata))) {
390 matches.push(location);
391 }
392 }
393 return matches[0];
394 });
395
396 const observe = Effect.fn(function* (input: { id?: string; logicalId: string }) {
397 if (input.id !== undefined) {
398 const byId = yield* getById(input.id);
399 if (byId !== undefined) return byId;
400 }
401 return yield* findByAlchemyId(input.logicalId);
402 });
403
404 const desiredMetadata = Effect.fn(function* (
405 id: string,
406 metadata: Record<string, string> | undefined,
407 ) {
408 return {
409 ...toMetadata(metadata),
410 ...(yield* createInternalMetadata(id)),
411 };
412 });
413
414 const shouldReplace = (
415 news: TerminalLocationProps,
416 output: TerminalLocationAttributes | undefined,
417 ): boolean => {
418 if (output === undefined) return false;
419 return news.address.country !== output.address.country;
420 };
421
422 export const TerminalLocationProvider = () =>
423 Provider.succeed(TerminalLocation, {
424 stables: ["id", "livemode"],
425
426 diff: Effect.fn(function* ({ news, output }) {
427 if (!isResolved(news)) return undefined;
428 if (shouldReplace(news, output)) {
429 return { action: "replace" } as const;
430 }
431 return undefined;
432 }),
433
434 read: Effect.fn(function* ({ id, output }) {
435 const existing = yield* observe({
436 id: output?.id,
437 logicalId: id,
438 });
439 if (existing === undefined) return undefined;
440 const attrs = toAttrs(existing);
441 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
442 }),
443
444 list: Effect.fn(function* () {
445 const locations = yield* listAllLocations();
446 return locations
447 .filter((location) => {
448 const metadata = tagRecord(location.metadata);
449 return metadata[alchemyMetadataKeys.stack] !== undefined;
450 })
451 .map(toAttrs);
452 }),
453
454 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
455 const displayName = yield* toDisplayName(id, news.displayName, output?.displayName);
456 const metadata = yield* desiredMetadata(id, news.metadata);
457 const desiredPhone = news.phone ?? "";
458 const desiredConfig = news.configurationOverrides ?? "";
459 const desiredDisplayNameKana = news.displayNameKana ?? "";
460 const desiredDisplayNameKanji = news.displayNameKanji ?? "";
461 const address = toWireAddress(news.address);
462
463 let current: StripeTerminalLocation | undefined = yield* observe({
464 id: output?.id,
465 logicalId: id,
466 });
467 if (current !== undefined && shouldReplace(news, toAttrs(current))) {
468 current = undefined;
469 }
470
471 if (current === undefined) {
472 current = yield* CreateTerminalLocation({
473 display_name: displayName,
474 address,
475 metadata,
476 ...(news.addressKana !== undefined
477 ? { address_kana: toWireJapanAddress(news.addressKana) }
478 : {}),
479 ...(news.addressKanji !== undefined
480 ? { address_kanji: toWireJapanAddress(news.addressKanji) }
481 : {}),
482 ...(desiredConfig.length > 0 ? { configuration_overrides: desiredConfig } : {}),
483 ...(desiredDisplayNameKana.length > 0
484 ? { display_name_kana: desiredDisplayNameKana }
485 : {}),
486 ...(desiredDisplayNameKanji.length > 0
487 ? { display_name_kanji: desiredDisplayNameKanji }
488 : {}),
489 ...(desiredPhone.length > 0 ? { phone: desiredPhone } : {}),
490 }).pipe(
491 withRequestOptions({
492 idempotencyKey: `alchemy-terminal-location-${instanceId}`,
493 }),
494 );
495 }
496
497 if (current === undefined) {
498 return yield* new TerminalLocationNotResolved({ displayName });
499 }
500
501 const observedMetadata = tagRecord(current.metadata);
502 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
503 const metadataChanged = upsert.length > 0 || removed.length > 0;
504 const displayNameChanged = current.display_name !== displayName;
505 const addressChanged = !deepEqual(fromObservedAddress(current.address), news.address, {
506 stripNullish: true,
507 });
508 const addressKanaChanged =
509 news.addressKana !== undefined &&
510 !deepEqual(fromObservedJapanAddress(current.address_kana), news.addressKana, {
511 stripNullish: true,
512 });
513 const addressKanjiChanged =
514 news.addressKanji !== undefined &&
515 !deepEqual(fromObservedJapanAddress(current.address_kanji), news.addressKanji, {
516 stripNullish: true,
517 });
518 const phoneChanged = (current.phone ?? "") !== desiredPhone;
519 const configChanged = (current.configuration_overrides ?? "") !== desiredConfig;
520 const displayNameKanaChanged = (current.display_name_kana ?? "") !== desiredDisplayNameKana;
521 const displayNameKanjiChanged =
522 (current.display_name_kanji ?? "") !== desiredDisplayNameKanji;
523
524 if (
525 !displayNameChanged &&
526 !addressChanged &&
527 !addressKanaChanged &&
528 !addressKanjiChanged &&
529 !phoneChanged &&
530 !configChanged &&
531 !displayNameKanaChanged &&
532 !displayNameKanjiChanged &&
533 !metadataChanged
534 ) {
535 return toAttrs(current);
536 }
537
538 const updated = yield* UpdateTerminalLocation({
539 location: current.id,
540 ...(displayNameChanged ? { display_name: displayName } : {}),
541 ...(addressChanged ? { address } : {}),
542 ...(addressKanaChanged && news.addressKana !== undefined
543 ? { address_kana: toWireJapanAddress(news.addressKana) }
544 : {}),
545 ...(addressKanjiChanged && news.addressKanji !== undefined
546 ? { address_kanji: toWireJapanAddress(news.addressKanji) }
547 : {}),
548 ...(configChanged ? { configuration_overrides: desiredConfig } : {}),
549 ...(displayNameKanaChanged ? { display_name_kana: desiredDisplayNameKana } : {}),
550 ...(displayNameKanjiChanged ? { display_name_kanji: desiredDisplayNameKanji } : {}),
551 ...(phoneChanged ? { phone: desiredPhone } : {}),
552 ...(metadataChanged
553 ? {
554 metadata: {
555 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
556 ...Object.fromEntries(removed.map((key) => [key, ""])),
557 },
558 }
559 : {}),
560 });
561 const location = asLocation(updated);
562 if (location === undefined) {
563 return yield* new TerminalLocationNotResolved({ displayName });
564 }
565 return toAttrs(location);
566 }),
567
568 delete: Effect.fn(function* ({ output }) {
569 yield* DeleteTerminalLocation({ location: output.id }).pipe(
570 Effect.catchIf(isMissingLocation, () => Effect.void),
571 );
572 }),
573 });