@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 922 lines 28.5 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 DeleteTerminalConfiguration,
4 GetTerminalConfigurations,
5 GetTerminalConfiguration,
6 CreateTerminalConfiguration,
7 UpdateTerminalConfiguration,
8 type DeletedTerminalConfiguration,
9 type CreateTerminalConfigurationRequest,
10 type CreateTerminalConfigurationRequestTippingCase0,
11 type CreateTerminalConfigurationRequestWifiCase0,
12 type TerminalConfiguration as StripeTerminalConfiguration,
13 type TerminalConfigurationConfigurationResourceCurrencySpecificConfig,
14 type TerminalConfigurationConfigurationResourceDeviceTypeSpecificConfig,
15 type TerminalConfigurationConfigurationResourceTipping,
16 type TerminalConfigurationConfigurationResourceWifiConfig,
17 } from "@distilled.cloud/stripe/stripe";
18 import { Unowned } from "alchemy/AdoptPolicy";
19 import { deepEqual, isResolved } from "alchemy/Diff";
20 import { createPhysicalName } from "alchemy/PhysicalName";
21 import * as Provider from "alchemy/Provider";
22 import { Resource } from "alchemy/Resource";
23 import * as Data from "effect/Data";
24 import * as Effect from "effect/Effect";
25 import { isMissingStripeResource } from "./missing.ts";
26 import type { Providers } from "./Providers.ts";
27
28 const NAME_MAX_LENGTH = 250;
29 const LIST_PAGE_SIZE = 100;
30 const LIST_MAX_PAGES = 100;
31
32 /** Fixed amounts / percentages shown when collecting an on-reader tip. */
33 export interface TerminalTippingCurrency {
34 /**
35 * Fixed amounts (in the currency's minor units) displayed when
36 * collecting a tip.
37 */
38 fixedAmounts?: number[];
39 /**
40 * Percentages displayed when collecting a tip.
41 */
42 percentages?: number[];
43 /**
44 * Below this amount (minor units), fixed amounts are shown; above it,
45 * percentages are shown. Requires both `fixedAmounts` and `percentages`.
46 */
47 smartTipThreshold?: number;
48 }
49
50 /** Per-currency on-reader tipping. Keys are lowercase ISO 4217 codes. */
51 export interface TerminalTipping {
52 /** Tipping configuration for AED. */
53 aed?: TerminalTippingCurrency;
54 /** Tipping configuration for AUD. */
55 aud?: TerminalTippingCurrency;
56 /** Tipping configuration for CAD. */
57 cad?: TerminalTippingCurrency;
58 /** Tipping configuration for CHF. */
59 chf?: TerminalTippingCurrency;
60 /** Tipping configuration for CZK. */
61 czk?: TerminalTippingCurrency;
62 /** Tipping configuration for DKK. */
63 dkk?: TerminalTippingCurrency;
64 /** Tipping configuration for EUR. */
65 eur?: TerminalTippingCurrency;
66 /** Tipping configuration for GBP. */
67 gbp?: TerminalTippingCurrency;
68 /** Tipping configuration for GIP. */
69 gip?: TerminalTippingCurrency;
70 /** Tipping configuration for HKD. */
71 hkd?: TerminalTippingCurrency;
72 /** Tipping configuration for HUF. */
73 huf?: TerminalTippingCurrency;
74 /** Tipping configuration for JPY. */
75 jpy?: TerminalTippingCurrency;
76 /** Tipping configuration for MXN. */
77 mxn?: TerminalTippingCurrency;
78 /** Tipping configuration for MYR. */
79 myr?: TerminalTippingCurrency;
80 /** Tipping configuration for NOK. */
81 nok?: TerminalTippingCurrency;
82 /** Tipping configuration for NZD. */
83 nzd?: TerminalTippingCurrency;
84 /** Tipping configuration for PLN. */
85 pln?: TerminalTippingCurrency;
86 /** Tipping configuration for RON. */
87 ron?: TerminalTippingCurrency;
88 /** Tipping configuration for SEK. */
89 sek?: TerminalTippingCurrency;
90 /** Tipping configuration for SGD. */
91 sgd?: TerminalTippingCurrency;
92 /** Tipping configuration for USD. */
93 usd?: TerminalTippingCurrency;
94 }
95
96 /** Device-specific splash screen. */
97 export interface TerminalDeviceConfig {
98 /**
99 * Stripe File id of an image to display on the reader. Empty string
100 * clears it on update.
101 */
102 splashscreen?: string;
103 }
104
105 /** Offline-mode collection. */
106 export interface TerminalOffline {
107 /**
108 * Whether the reader may collect transactions while offline.
109 */
110 enabled: boolean;
111 }
112
113 /** Cellular connectivity. */
114 export interface TerminalCellular {
115 /**
116 * Whether a cellular-capable reader may connect over cellular.
117 */
118 enabled: boolean;
119 }
120
121 /** Daily reboot window (hours in 0–23). */
122 export interface TerminalRebootWindow {
123 /**
124 * Start hour of the reboot window (0–23).
125 */
126 startHour: number;
127 /**
128 * End hour of the reboot window (0–23). Must differ from `startHour`.
129 */
130 endHour: number;
131 }
132
133 /** Wi-Fi security type. */
134 export type TerminalWifiType = "enterprise_eap_peap" | "enterprise_eap_tls" | "personal_psk";
135
136 /** WPA-Enterprise EAP-PEAP credentials. */
137 export interface TerminalWifiEnterprisePeap {
138 /**
139 * Wi-Fi network name.
140 */
141 ssid: string;
142 /**
143 * Username for the network.
144 */
145 username: string;
146 /**
147 * Password for the network. Never returned on read.
148 */
149 password: string;
150 /**
151 * Stripe File id of a PEM containing the server certificate.
152 */
153 caCertificateFile?: string;
154 }
155
156 /** WPA-Enterprise EAP-TLS credentials. */
157 export interface TerminalWifiEnterpriseTls {
158 /**
159 * Wi-Fi network name.
160 */
161 ssid: string;
162 /**
163 * Stripe File id of a PEM containing the client certificate.
164 */
165 clientCertificateFile: string;
166 /**
167 * Stripe File id of a PEM containing the client RSA private key.
168 */
169 privateKeyFile: string;
170 /**
171 * Stripe File id of a PEM containing the server certificate.
172 */
173 caCertificateFile?: string;
174 /**
175 * Password for the private key file. Never returned on read.
176 */
177 privateKeyFilePassword?: string;
178 }
179
180 /** WPA-Personal PSK credentials. */
181 export interface TerminalWifiPersonalPsk {
182 /**
183 * Wi-Fi network name.
184 */
185 ssid: string;
186 /**
187 * Password for the network. Never returned on read.
188 */
189 password: string;
190 }
191
192 /** Reader Wi-Fi configuration. */
193 export interface TerminalWifi {
194 /**
195 * Security type. The matching nested object holds the credentials.
196 */
197 type: TerminalWifiType;
198 /**
199 * EAP-PEAP credentials. Required when `type` is `enterprise_eap_peap`.
200 */
201 enterpriseEapPeap?: TerminalWifiEnterprisePeap;
202 /**
203 * EAP-TLS credentials. Required when `type` is `enterprise_eap_tls`.
204 */
205 enterpriseEapTls?: TerminalWifiEnterpriseTls;
206 /**
207 * Personal PSK credentials. Required when `type` is `personal_psk`.
208 */
209 personalPsk?: TerminalWifiPersonalPsk;
210 }
211
212 /** Observed Wi-Fi state with secrets stripped. */
213 export interface TerminalWifiState {
214 /**
215 * Security type currently configured.
216 */
217 type: TerminalWifiType;
218 /**
219 * Observed EAP-PEAP settings (password omitted).
220 */
221 enterpriseEapPeap?: {
222 ssid: string;
223 username: string;
224 caCertificateFile: string | undefined;
225 };
226 /**
227 * Observed EAP-TLS settings (private-key password omitted).
228 */
229 enterpriseEapTls?: {
230 ssid: string;
231 clientCertificateFile: string;
232 privateKeyFile: string;
233 caCertificateFile: string | undefined;
234 };
235 /**
236 * Observed personal PSK settings (password omitted).
237 */
238 personalPsk?: {
239 ssid: string;
240 };
241 }
242
243 export interface TerminalConfigurationProps {
244 /**
245 * Display name of the configuration. If omitted, a unique name is
246 * generated from the stack, stage, and logical id. Mutable. Used as the
247 * lookup key when the Stripe id is missing — this object has no
248 * metadata.
249 */
250 name?: string;
251 /**
252 * Offline transaction collection. `null` clears it on update.
253 */
254 offline?: TerminalOffline | null;
255 /**
256 * On-reader tipping by currency. `null` clears it on update.
257 */
258 tipping?: TerminalTipping | null;
259 /**
260 * Daily reboot window. `null` clears it on update.
261 */
262 rebootWindow?: TerminalRebootWindow | null;
263 /**
264 * Cellular connectivity. `null` clears it on update.
265 */
266 cellular?: TerminalCellular | null;
267 /**
268 * Reader Wi-Fi. `null` clears it on update. Passwords are write-only.
269 */
270 wifi?: TerminalWifi | null;
271 /**
272 * BBPOS WisePad 3 splash screen. `null` clears it on update.
273 */
274 bbposWisepad3?: TerminalDeviceConfig | null;
275 /**
276 * BBPOS WisePOS E splash screen. `null` clears it on update.
277 */
278 bbposWiseposE?: TerminalDeviceConfig | null;
279 /**
280 * Stripe S700 splash screen. `null` clears it on update.
281 */
282 stripeS700?: TerminalDeviceConfig | null;
283 /**
284 * Stripe S710 splash screen. `null` clears it on update.
285 */
286 stripeS710?: TerminalDeviceConfig | null;
287 /**
288 * Verifone M425 splash screen. `null` clears it on update.
289 */
290 verifoneM425?: TerminalDeviceConfig | null;
291 /**
292 * Verifone P400 splash screen. `null` clears it on update.
293 */
294 verifoneP400?: TerminalDeviceConfig | null;
295 /**
296 * Verifone P630 splash screen. `null` clears it on update.
297 */
298 verifoneP630?: TerminalDeviceConfig | null;
299 /**
300 * Verifone UX700 splash screen. `null` clears it on update.
301 */
302 verifoneUx700?: TerminalDeviceConfig | null;
303 /**
304 * Verifone V660p splash screen. `null` clears it on update.
305 */
306 verifoneV660p?: TerminalDeviceConfig | null;
307 }
308
309 type DeviceKey = (typeof DEVICE_MAP)[number][0];
310 type SnakeDeviceKey = (typeof DEVICE_MAP)[number][1];
311
312 const DEVICE_MAP = [
313 ["bbposWisepad3", "bbpos_wisepad3"],
314 ["bbposWiseposE", "bbpos_wisepos_e"],
315 ["stripeS700", "stripe_s700"],
316 ["stripeS710", "stripe_s710"],
317 ["verifoneM425", "verifone_m425"],
318 ["verifoneP400", "verifone_p400"],
319 ["verifoneP630", "verifone_p630"],
320 ["verifoneUx700", "verifone_ux700"],
321 ["verifoneV660p", "verifone_v660p"],
322 ] as const satisfies ReadonlyArray<readonly [string, string]>;
323
324 const TIPPING_CURRENCIES = [
325 "aed",
326 "aud",
327 "cad",
328 "chf",
329 "czk",
330 "dkk",
331 "eur",
332 "gbp",
333 "gip",
334 "hkd",
335 "huf",
336 "jpy",
337 "mxn",
338 "myr",
339 "nok",
340 "nzd",
341 "pln",
342 "ron",
343 "sek",
344 "sgd",
345 "usd",
346 ] as const satisfies ReadonlyArray<keyof TerminalTipping>;
347
348 type DeviceAttributes = {
349 [K in DeviceKey]: TerminalDeviceConfig | undefined;
350 };
351
352 export type TerminalConfiguration = Resource<
353 "Stripe.TerminalConfiguration",
354 TerminalConfigurationProps,
355 {
356 /** Stripe Terminal configuration id (`tmc_…`). */
357 id: string;
358 /** Display name of the configuration, if set. */
359 name: string | undefined;
360 /** Whether this is the account's default configuration. */
361 isAccountDefault: boolean;
362 /** Offline transaction collection, if configured. */
363 offline: TerminalOffline | undefined;
364 /** On-reader tipping by currency, if configured. */
365 tipping: TerminalTipping | undefined;
366 /** Daily reboot window, if configured. */
367 rebootWindow: TerminalRebootWindow | undefined;
368 /** Cellular connectivity, if configured. */
369 cellular: TerminalCellular | undefined;
370 /** Observed Wi-Fi (passwords omitted). */
371 wifi: TerminalWifiState | undefined;
372 /** Whether the configuration exists in live mode. */
373 livemode: boolean;
374 } & DeviceAttributes,
375 never,
376 Providers
377 >;
378
379 /**
380 * A Stripe Terminal Configuration — splash screens, tipping, offline
381 * mode, reboot window, cellular, and Wi-Fi for smart readers. Name and
382 * nested settings update in place. Destroy hard-deletes the
383 * configuration. The account default configuration is never adopted or
384 * listed.
385 *
386 * Terminal configurations have no metadata field. Identity is the Stripe
387 * id plus the unique name. Account-wide `list()` (nuke) enumerates every
388 * non-default configuration on the account.
389 *
390 * @see https://docs.stripe.com/api/terminal/configuration
391 *
392 * ### Creating a Configuration
393 * **Example:** Named configuration with USD tipping
394 * ```typescript
395 * const config = yield* Stripe.TerminalConfiguration("storefront", {
396 * name: "Storefront",
397 * offline: { enabled: true },
398 * tipping: {
399 * usd: {
400 * fixedAmounts: [100, 200, 300],
401 * percentages: [15, 20, 25],
402 * smartTipThreshold: 1000,
403 * },
404 * },
405 * });
406 * ```
407 *
408 * **Example:** Reboot window
409 * ```typescript
410 * const config = yield* Stripe.TerminalConfiguration("storefront", {
411 * name: "Storefront",
412 * rebootWindow: { startHour: 2, endHour: 4 },
413 * });
414 * ```
415 *
416 * ### Updating a Configuration
417 * **Example:** Rename and change tipping
418 * ```typescript
419 * const config = yield* Stripe.TerminalConfiguration("storefront", {
420 * name: "Storefront (updated)",
421 * offline: { enabled: false },
422 * tipping: {
423 * usd: {
424 * fixedAmounts: [200, 300, 400],
425 * percentages: [10, 15, 20],
426 * smartTipThreshold: 2000,
427 * },
428 * },
429 * });
430 * ```
431 *
432 * ### Deleting a Configuration
433 * **Example:** Destroy deletes the configuration
434 * ```typescript
435 * // stack.destroy() / resource removal hard-deletes the configuration
436 * const config = yield* Stripe.TerminalConfiguration("storefront", {
437 * name: "Storefront",
438 * });
439 * ```
440 *
441 * @resource
442 * @product Terminal
443 */
444 export const TerminalConfiguration = Resource<TerminalConfiguration>(
445 "Stripe.TerminalConfiguration",
446 );
447
448 export class TerminalConfigurationNotResolved extends Data.TaggedError(
449 "Stripe.TerminalConfigurationNotResolved",
450 )<{
451 configurationId: string | undefined;
452 resourceName: string;
453 }> {}
454
455 type ConfigurationAttributes = TerminalConfiguration["Attributes"];
456
457 const toName = (id: string, name: string | undefined, existing?: string) =>
458 Effect.gen(function* () {
459 return name ?? existing ?? (yield* createPhysicalName({ id, maxLength: NAME_MAX_LENGTH }));
460 });
461
462 const isDeletedConfiguration = (
463 value: StripeTerminalConfiguration | DeletedTerminalConfiguration,
464 ): value is DeletedTerminalConfiguration => "deleted" in value && value.deleted === true;
465
466 const asConfiguration = (
467 value: StripeTerminalConfiguration | DeletedTerminalConfiguration | undefined,
468 ): StripeTerminalConfiguration | undefined => {
469 if (value === undefined || isDeletedConfiguration(value)) return undefined;
470 return value;
471 };
472
473 const isAccountDefault = (configuration: StripeTerminalConfiguration) =>
474 configuration.is_account_default === true;
475
476 const toFileId = (value: unknown): string | undefined => {
477 if (value === undefined || value === null) return undefined;
478 if (typeof value === "string") return value === "" ? undefined : value;
479 if (
480 typeof value === "object" &&
481 "id" in value &&
482 typeof (value as { id: unknown }).id === "string"
483 ) {
484 return (value as { id: string }).id;
485 }
486 return undefined;
487 };
488
489 const toDeviceState = (
490 value: TerminalConfigurationConfigurationResourceDeviceTypeSpecificConfig | undefined,
491 ): TerminalDeviceConfig | undefined => {
492 if (value === undefined) return undefined;
493 const splashscreen = toFileId(value.splashscreen);
494 return splashscreen === undefined ? {} : { splashscreen };
495 };
496
497 const toTippingCurrency = (
498 value: TerminalConfigurationConfigurationResourceCurrencySpecificConfig | undefined,
499 ): TerminalTippingCurrency | undefined => {
500 if (value === undefined) return undefined;
501 return {
502 ...(value.fixed_amounts != null ? { fixedAmounts: value.fixed_amounts } : {}),
503 ...(value.percentages != null ? { percentages: value.percentages } : {}),
504 ...(value.smart_tip_threshold !== undefined
505 ? { smartTipThreshold: value.smart_tip_threshold }
506 : {}),
507 };
508 };
509
510 const toTipping = (
511 tipping: TerminalConfigurationConfigurationResourceTipping | undefined,
512 ): TerminalTipping | undefined => {
513 if (tipping === undefined) return undefined;
514 const out: TerminalTipping = {};
515 for (const currency of TIPPING_CURRENCIES) {
516 const mapped = toTippingCurrency(tipping[currency]);
517 if (mapped !== undefined) out[currency] = mapped;
518 }
519 return Object.keys(out).length > 0 ? out : undefined;
520 };
521
522 const toWifiState = (
523 wifi: TerminalConfigurationConfigurationResourceWifiConfig | undefined,
524 ): TerminalWifiState | undefined => {
525 if (wifi === undefined) return undefined;
526 return {
527 type: wifi.type,
528 ...(wifi.enterprise_eap_peap !== undefined
529 ? {
530 enterpriseEapPeap: {
531 ssid: wifi.enterprise_eap_peap.ssid,
532 username: wifi.enterprise_eap_peap.username,
533 caCertificateFile: wifi.enterprise_eap_peap.ca_certificate_file,
534 },
535 }
536 : {}),
537 ...(wifi.enterprise_eap_tls !== undefined
538 ? {
539 enterpriseEapTls: {
540 ssid: wifi.enterprise_eap_tls.ssid,
541 clientCertificateFile: wifi.enterprise_eap_tls.client_certificate_file,
542 privateKeyFile: wifi.enterprise_eap_tls.private_key_file,
543 caCertificateFile: wifi.enterprise_eap_tls.ca_certificate_file,
544 },
545 }
546 : {}),
547 ...(wifi.personal_psk !== undefined ? { personalPsk: { ssid: wifi.personal_psk.ssid } } : {}),
548 };
549 };
550
551 const toAttrs = (configuration: StripeTerminalConfiguration): ConfigurationAttributes => {
552 const devices = {} as DeviceAttributes;
553 for (const [camel, snake] of DEVICE_MAP) {
554 devices[camel] = toDeviceState(configuration[snake]);
555 }
556 return {
557 id: configuration.id,
558 name: configuration.name ?? undefined,
559 isAccountDefault: isAccountDefault(configuration),
560 offline:
561 configuration.offline?.enabled == null
562 ? undefined
563 : { enabled: configuration.offline.enabled },
564 tipping: toTipping(configuration.tipping),
565 rebootWindow:
566 configuration.reboot_window === undefined
567 ? undefined
568 : {
569 startHour: configuration.reboot_window.start_hour,
570 endHour: configuration.reboot_window.end_hour,
571 },
572 cellular:
573 configuration.cellular === undefined
574 ? undefined
575 : { enabled: configuration.cellular.enabled },
576 wifi: toWifiState(configuration.wifi),
577 livemode: configuration.livemode,
578 ...devices,
579 };
580 };
581
582 const toWireTippingCurrency = (value: TerminalTippingCurrency) => ({
583 ...(value.fixedAmounts !== undefined ? { fixed_amounts: value.fixedAmounts } : {}),
584 ...(value.percentages !== undefined ? { percentages: value.percentages } : {}),
585 ...(value.smartTipThreshold !== undefined
586 ? { smart_tip_threshold: value.smartTipThreshold }
587 : {}),
588 });
589
590 const toWireTipping = (
591 tipping: TerminalTipping,
592 ): CreateTerminalConfigurationRequestTippingCase0 => {
593 const out: CreateTerminalConfigurationRequestTippingCase0 = {};
594 for (const currency of TIPPING_CURRENCIES) {
595 const value = tipping[currency];
596 if (value !== undefined) {
597 out[currency] = toWireTippingCurrency(value);
598 }
599 }
600 return out;
601 };
602
603 const toWireWifi = (wifi: TerminalWifi): CreateTerminalConfigurationRequestWifiCase0 => ({
604 type: wifi.type,
605 ...(wifi.enterpriseEapPeap !== undefined
606 ? {
607 enterprise_eap_peap: {
608 ssid: wifi.enterpriseEapPeap.ssid,
609 username: wifi.enterpriseEapPeap.username,
610 password: wifi.enterpriseEapPeap.password,
611 ...(wifi.enterpriseEapPeap.caCertificateFile !== undefined
612 ? { ca_certificate_file: wifi.enterpriseEapPeap.caCertificateFile }
613 : {}),
614 },
615 }
616 : {}),
617 ...(wifi.enterpriseEapTls !== undefined
618 ? {
619 enterprise_eap_tls: {
620 ssid: wifi.enterpriseEapTls.ssid,
621 client_certificate_file: wifi.enterpriseEapTls.clientCertificateFile,
622 private_key_file: wifi.enterpriseEapTls.privateKeyFile,
623 ...(wifi.enterpriseEapTls.caCertificateFile !== undefined
624 ? { ca_certificate_file: wifi.enterpriseEapTls.caCertificateFile }
625 : {}),
626 ...(wifi.enterpriseEapTls.privateKeyFilePassword !== undefined
627 ? {
628 private_key_file_password: wifi.enterpriseEapTls.privateKeyFilePassword,
629 }
630 : {}),
631 },
632 }
633 : {}),
634 ...(wifi.personalPsk !== undefined
635 ? {
636 personal_psk: {
637 ssid: wifi.personalPsk.ssid,
638 password: wifi.personalPsk.password,
639 },
640 }
641 : {}),
642 });
643
644 const toWireDevice = (device: TerminalDeviceConfig) =>
645 device.splashscreen !== undefined ? { splashscreen: device.splashscreen } : {};
646
647 const wifiComparable = (wifi: TerminalWifi | TerminalWifiState | undefined): unknown => {
648 if (wifi === undefined) return undefined;
649 return {
650 type: wifi.type,
651 enterpriseEapPeap:
652 wifi.enterpriseEapPeap === undefined
653 ? undefined
654 : {
655 ssid: wifi.enterpriseEapPeap.ssid,
656 username:
657 "username" in wifi.enterpriseEapPeap ? wifi.enterpriseEapPeap.username : undefined,
658 caCertificateFile: wifi.enterpriseEapPeap.caCertificateFile,
659 },
660 enterpriseEapTls:
661 wifi.enterpriseEapTls === undefined
662 ? undefined
663 : {
664 ssid: wifi.enterpriseEapTls.ssid,
665 clientCertificateFile: wifi.enterpriseEapTls.clientCertificateFile,
666 privateKeyFile: wifi.enterpriseEapTls.privateKeyFile,
667 caCertificateFile: wifi.enterpriseEapTls.caCertificateFile,
668 },
669 personalPsk: wifi.personalPsk === undefined ? undefined : { ssid: wifi.personalPsk.ssid },
670 };
671 };
672
673 const pickSpecified = (desired: unknown, observed: unknown): unknown => {
674 if (desired === undefined) return undefined;
675 if (Array.isArray(desired)) {
676 if (!Array.isArray(observed)) return observed;
677 return desired.map((item, index) => pickSpecified(item, observed[index]));
678 }
679 if (
680 desired !== null &&
681 typeof desired === "object" &&
682 observed !== null &&
683 typeof observed === "object"
684 ) {
685 const out: Record<string, unknown> = {};
686 for (const key of Object.keys(desired as Record<string, unknown>)) {
687 out[key] = pickSpecified(
688 (desired as Record<string, unknown>)[key],
689 (observed as Record<string, unknown>)[key],
690 );
691 }
692 return out;
693 }
694 return observed;
695 };
696
697 const nestedNeedSync = (desired: unknown, observed: unknown): boolean => {
698 if (desired === undefined) return false;
699 if (desired === null) return observed !== undefined;
700 return !deepEqual(desired, pickSpecified(desired, observed), {
701 stripNullish: true,
702 });
703 };
704
705 const isMissingConfiguration = isMissingStripeResource;
706
707 const getById = (configuration: string) =>
708 GetTerminalConfiguration({ configuration }).pipe(
709 Effect.map(asConfiguration),
710 Effect.catchIf(isMissingConfiguration, () => Effect.undefined),
711 );
712
713 const listNonDefault = Effect.fn(function* () {
714 const configurations: StripeTerminalConfiguration[] = [];
715 let startingAfter: string | undefined;
716 for (let page = 0; page < LIST_MAX_PAGES; page++) {
717 const response = yield* GetTerminalConfigurations({
718 is_account_default: false,
719 limit: LIST_PAGE_SIZE,
720 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
721 });
722 configurations.push(...response.data);
723 if (!response.has_more || response.data.length === 0) {
724 break;
725 }
726 startingAfter = response.data[response.data.length - 1]?.id;
727 if (startingAfter === undefined) {
728 break;
729 }
730 }
731 return configurations.filter((configuration) => !isAccountDefault(configuration));
732 });
733
734 const findByName = Effect.fn(function* (name: string) {
735 const configurations = yield* listNonDefault();
736 return configurations.find((configuration) => (configuration.name ?? "") === name);
737 });
738
739 const observe = Effect.fn(function* (input: { id?: string; name?: string }) {
740 if (input.id !== undefined) {
741 const byId = yield* getById(input.id);
742 if (byId !== undefined) return byId;
743 }
744 if (input.name !== undefined) {
745 return yield* findByName(input.name);
746 }
747 return undefined;
748 });
749
750 type DeviceWire = { splashscreen?: string };
751
752 const specifiedDevices = (
753 news: TerminalConfigurationProps,
754 ): Partial<Record<SnakeDeviceKey, DeviceWire | "">> => {
755 const payload: Partial<Record<SnakeDeviceKey, DeviceWire | "">> = {};
756 for (const [camel, snake] of DEVICE_MAP) {
757 const value = news[camel];
758 if (value === undefined) continue;
759 payload[snake] = value === null ? "" : toWireDevice(value);
760 }
761 return payload;
762 };
763
764 const toCreatePayload = (
765 name: string,
766 news: TerminalConfigurationProps,
767 ): CreateTerminalConfigurationRequest => {
768 const devices = specifiedDevices(news);
769 const createDevices: Partial<Record<SnakeDeviceKey, DeviceWire>> = {};
770 for (const [snake, value] of Object.entries(devices) as Array<
771 [SnakeDeviceKey, DeviceWire | ""]
772 >) {
773 if (value !== "") createDevices[snake] = value;
774 }
775 return {
776 name,
777 ...(news.offline != null ? { offline: news.offline } : {}),
778 ...(news.tipping != null ? { tipping: toWireTipping(news.tipping) } : {}),
779 ...(news.rebootWindow != null
780 ? {
781 reboot_window: {
782 start_hour: news.rebootWindow.startHour,
783 end_hour: news.rebootWindow.endHour,
784 },
785 }
786 : {}),
787 ...(news.cellular != null ? { cellular: news.cellular } : {}),
788 ...(news.wifi != null ? { wifi: toWireWifi(news.wifi) } : {}),
789 ...createDevices,
790 };
791 };
792
793 export const TerminalConfigurationProvider = () =>
794 Provider.succeed(TerminalConfiguration, {
795 stables: ["id", "livemode", "isAccountDefault"],
796
797 diff: Effect.fn(function* ({ news }) {
798 if (!isResolved(news)) return undefined;
799 return undefined;
800 }),
801
802 read: Effect.fn(function* ({ output }) {
803 const existing = yield* observe({
804 id: output?.id,
805 name: output?.name,
806 });
807 if (existing === undefined) return undefined;
808 const attrs = toAttrs(existing);
809 // No metadata. Identity is the Stripe id and unique name. Never
810 // take over the account default configuration.
811 return isAccountDefault(existing) ? Unowned(attrs) : attrs;
812 }),
813
814 list: Effect.fn(function* () {
815 // No metadata on this resource. Account-wide list is every
816 // non-default configuration so nuke can drain the account.
817 const configurations = yield* listNonDefault();
818 return configurations.map(toAttrs);
819 }),
820
821 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
822 const name = yield* toName(id, news.name, output?.name);
823
824 let current = yield* observe({
825 id: output?.id,
826 name,
827 });
828 if (current !== undefined && isAccountDefault(current)) {
829 current = undefined;
830 }
831
832 if (current === undefined) {
833 current = yield* CreateTerminalConfiguration(toCreatePayload(name, news)).pipe(
834 withRequestOptions({
835 idempotencyKey: `alchemy-terminal-configuration-${instanceId}`,
836 }),
837 );
838 }
839
840 if (current === undefined) {
841 return yield* new TerminalConfigurationNotResolved({
842 configurationId: output?.id,
843 resourceName: name,
844 });
845 }
846
847 const attrs = toAttrs(current);
848 const nameChanged = (current.name ?? "") !== name;
849 const offlineChanged = nestedNeedSync(news.offline, attrs.offline);
850 const tippingChanged = nestedNeedSync(news.tipping, attrs.tipping);
851 const rebootWindowChanged = nestedNeedSync(news.rebootWindow, attrs.rebootWindow);
852 const cellularChanged = nestedNeedSync(news.cellular, attrs.cellular);
853 const wifiChanged =
854 news.wifi === null
855 ? attrs.wifi !== undefined
856 : news.wifi !== undefined &&
857 nestedNeedSync(wifiComparable(news.wifi), wifiComparable(attrs.wifi));
858
859 const changedDevices: Partial<Record<SnakeDeviceKey, DeviceWire | "">> = {};
860 for (const [camel, snake] of DEVICE_MAP) {
861 const desired = news[camel];
862 if (desired === undefined) continue;
863 if (nestedNeedSync(desired, attrs[camel])) {
864 changedDevices[snake] = desired === null ? "" : toWireDevice(desired);
865 }
866 }
867 const devicesChanged = Object.keys(changedDevices).length > 0;
868
869 if (
870 !nameChanged &&
871 !offlineChanged &&
872 !tippingChanged &&
873 !rebootWindowChanged &&
874 !cellularChanged &&
875 !wifiChanged &&
876 !devicesChanged
877 ) {
878 return attrs;
879 }
880
881 const updated = yield* UpdateTerminalConfiguration({
882 configuration: current.id,
883 ...(nameChanged ? { name } : {}),
884 ...(offlineChanged ? { offline: news.offline === null ? "" : news.offline! } : {}),
885 ...(tippingChanged
886 ? {
887 tipping: news.tipping === null ? "" : toWireTipping(news.tipping!),
888 }
889 : {}),
890 ...(rebootWindowChanged
891 ? {
892 reboot_window:
893 news.rebootWindow === null
894 ? ""
895 : {
896 start_hour: news.rebootWindow!.startHour,
897 end_hour: news.rebootWindow!.endHour,
898 },
899 }
900 : {}),
901 ...(cellularChanged ? { cellular: news.cellular === null ? "" : news.cellular! } : {}),
902 ...(wifiChanged ? { wifi: news.wifi === null ? "" : toWireWifi(news.wifi!) } : {}),
903 ...changedDevices,
904 });
905 const next = asConfiguration(updated);
906 if (next === undefined) {
907 return yield* new TerminalConfigurationNotResolved({
908 configurationId: current.id,
909 resourceName: name,
910 });
911 }
912 return toAttrs(next);
913 }),
914
915 delete: Effect.fn(function* ({ output }) {
916 const existing = yield* getById(output.id);
917 if (existing === undefined || isAccountDefault(existing)) return;
918 yield* DeleteTerminalConfiguration({
919 configuration: existing.id,
920 }).pipe(Effect.catchIf(isMissingConfiguration, () => Effect.void));
921 }),
922 });