@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, 06:00 UTC

main
ts 217 lines 7.4 KB
Raw
1 import * as b2bi from "@distilled.cloud/aws/b2bi";
2 import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import { readB2biTags, syncB2biTags } from "./internal.ts";
11
12 export interface PartnershipProps {
13 /**
14 * The unique identifier for the profile connected to this partnership.
15 * May reference a {@link Profile}'s `profileId` output. Changing the
16 * profile replaces the partnership.
17 */
18 profileId: string;
19 /**
20 * The name of the partnership.
21 */
22 name: string;
23 /**
24 * The email address associated with the trading partner.
25 */
26 email: string;
27 /**
28 * The phone number associated with the trading partner, in E.164 format.
29 */
30 phone?: string;
31 /**
32 * A list of capability IDs (see {@link Capability}) enabled for this
33 * partnership.
34 */
35 capabilities?: string[];
36 /**
37 * Inbound/outbound EDI options that override the defaults for this
38 * partnership.
39 */
40 capabilityOptions?: b2bi.CapabilityOptions;
41 /**
42 * User-defined tags for the partnership.
43 */
44 tags?: Record<string, string>;
45 }
46
47 export interface Partnership extends Resource<
48 "AWS.B2BI.Partnership",
49 PartnershipProps,
50 {
51 /**
52 * Service-assigned unique ID of the partnership.
53 */
54 partnershipId: string;
55 /**
56 * ARN of the partnership.
57 */
58 partnershipArn: string;
59 /**
60 * ID of the profile the partnership belongs to.
61 */
62 profileId: string;
63 /**
64 * Service-assigned ID of the trading partner.
65 */
66 tradingPartnerId: string | undefined;
67 },
68 never,
69 Providers
70 > {}
71
72 /**
73 * An AWS B2B Data Interchange (B2BI) partnership. A partnership connects a
74 * customer {@link Profile} to a trading partner and enables a set of
75 * {@link Capability | capabilities} for exchanging EDI documents.
76 * ### Creating a Partnership
77 * **Example:** Basic Partnership
78 * ```typescript
79 * const partnership = yield* B2BI.Partnership("AcmeToPartner", {
80 * profileId: profile.profileId,
81 * name: "acme-partner",
82 * email: "edi@partner.example",
83 * capabilities: [capability.capabilityId],
84 * });
85 * ```
86 *
87 * @resource
88 */
89 export const Partnership = Resource<Partnership>("AWS.B2BI.Partnership");
90
91 const toAttrs = (
92 r: b2bi.GetPartnershipResponse | b2bi.CreatePartnershipResponse | b2bi.UpdatePartnershipResponse,
93 ) => ({
94 partnershipId: r.partnershipId,
95 partnershipArn: r.partnershipArn,
96 profileId: r.profileId,
97 tradingPartnerId: r.tradingPartnerId,
98 });
99
100 export const PartnershipProvider = () =>
101 Provider.effect(
102 Partnership,
103 Effect.gen(function* () {
104 const findByName = (name: string) =>
105 b2bi.listPartnerships.items({}).pipe(
106 Stream.filter((s) => s.name === name),
107 Stream.runHead,
108 Effect.flatMap((head) =>
109 head._tag === "Some"
110 ? b2bi
111 .getPartnership({ partnershipId: head.value.partnershipId })
112 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined))
113 : Effect.undefined,
114 ),
115 );
116
117 return {
118 stables: ["partnershipId", "partnershipArn", "profileId"],
119
120 diff: Effect.fn(function* ({ olds = {}, news }) {
121 if (!isResolved(news)) return undefined;
122 // The profile a partnership belongs to is immutable. Delete-first:
123 // the replacement keeps the same user-facing name, which is how
124 // lost state is recovered (findByName), so the old instance must
125 // be gone before the new one is created.
126 if (olds.profileId !== undefined && olds.profileId !== news.profileId) {
127 return { action: "replace", deleteFirst: true } as const;
128 }
129 }),
130
131 read: Effect.fn(function* ({ id, olds, output, previous }) {
132 const found = output?.partnershipId
133 ? yield* b2bi
134 .getPartnership({ partnershipId: output.partnershipId })
135 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined))
136 : yield* findByName(olds?.name ?? "");
137 if (found === undefined) return undefined;
138 const attrs = toAttrs(found);
139 const tags = yield* readB2biTags(attrs.partnershipArn);
140 return (yield* hasAlchemyTags(id, tags))
141 ? attrs
142 : unownedUnlessPrevious(attrs, previous, "partnershipId");
143 }),
144
145 reconcile: Effect.fn(function* ({ id, news, output, session }) {
146 const internalTags = yield* createInternalTags(id);
147 const desiredTags = { ...internalTags, ...news.tags };
148
149 // 1. Observe.
150 let live = output?.partnershipId
151 ? yield* b2bi
152 .getPartnership({ partnershipId: output.partnershipId })
153 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined))
154 : yield* findByName(news.name);
155
156 // 2. Ensure.
157 if (live === undefined) {
158 const created = yield* b2bi.createPartnership({
159 profileId: news.profileId,
160 name: news.name,
161 email: news.email,
162 phone: news.phone,
163 capabilities: news.capabilities ?? [],
164 capabilityOptions: news.capabilityOptions,
165 });
166 live = yield* b2bi.getPartnership({
167 partnershipId: created.partnershipId,
168 });
169 } else {
170 // 3. Sync — converge name, capabilities, and capability options
171 // (email/phone/profile are set only at create time).
172 const nameDrift = live.name !== news.name;
173 const capsDrift =
174 JSON.stringify([...(live.capabilities ?? [])].sort()) !==
175 JSON.stringify([...(news.capabilities ?? [])].sort());
176 const optsDrift =
177 JSON.stringify(live.capabilityOptions ?? null) !==
178 JSON.stringify(news.capabilityOptions ?? null);
179 if (nameDrift || capsDrift || optsDrift) {
180 const updated = yield* b2bi.updatePartnership({
181 partnershipId: live.partnershipId,
182 name: news.name,
183 capabilities: news.capabilities,
184 capabilityOptions: news.capabilityOptions,
185 });
186 live = { ...live, ...updated };
187 }
188 }
189
190 // 3b. Sync tags.
191 yield* syncB2biTags(live.partnershipArn, desiredTags);
192
193 yield* session.note(live.partnershipId);
194 return toAttrs(live);
195 }),
196
197 delete: Effect.fn(function* ({ output }) {
198 yield* b2bi
199 .deletePartnership({ partnershipId: output.partnershipId })
200 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
201 }),
202
203 list: () =>
204 b2bi.listPartnerships.items({}).pipe(
205 Stream.mapEffect((s) =>
206 b2bi.getPartnership({ partnershipId: s.partnershipId }).pipe(
207 Effect.map(toAttrs),
208 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
209 ),
210 ),
211 Stream.filter((item) => item !== undefined),
212 Stream.runCollect,
213 Effect.map((chunk) => Array.from(chunk)),
214 ),
215 };
216 }),
217 );