@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 316 lines 11 KB
Raw
1 import * as datamanager from "@distilled.cloud/gcp/datamanager_v1";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Effect from "effect/Effect";
4 import * as Stream from "effect/Stream";
5
6 export const DEFAULT_ACCOUNT_TYPE = "GOOGLE_ADS";
7 export const DEFAULT_MEMBERSHIP_STATUS = "OPEN";
8 export const DEFAULT_UPLOAD_KEY_TYPES: datamanager.IngestedUserListInfoUploadKeyTypesItemEnumList =
9 ["CONTACT_ID"];
10 export const PROBE_PARENT = "accountTypes/GOOGLE_ADS/accounts/0";
11 export const PROBE_NAME = `${PROBE_PARENT}/userLists/0`;
12
13 export type AccountType = datamanager.ProductAccountAccountTypeEnum | (string & {});
14
15 export type MembershipStatus = datamanager.UserListMembershipStatusEnum | (string & {});
16
17 export type AccountAccessStatus = datamanager.UserListAccountAccessStatusEnum | (string & {});
18
19 export type UploadKeyType = datamanager.IngestedUserListInfoUploadKeyTypesItemEnum | (string & {});
20
21 export type TargetNetworkInfoProps = {
22 /** Whether the list is eligible for the Google Display Network. */
23 eligibleForDisplay?: boolean;
24 /** Whether the list is eligible for Google Search. */
25 eligibleForSearch?: boolean;
26 };
27
28 export type PartnerAudienceInfoProps = {
29 /** Immutable source of the partner audience. */
30 partnerAudienceSource?: datamanager.PartnerAudienceInfoPartnerAudienceSourceEnum | (string & {});
31 /** Commerce partner name. Only for `COMMERCE_AUDIENCE`. */
32 commercePartner?: string;
33 };
34
35 export type MobileIdInfoProps = {
36 /** Immutable mobile ID key space (`IOS` or `ANDROID`). */
37 keySpace?: datamanager.MobileIdInfoKeySpaceEnum | (string & {});
38 /** Immutable app id the mobile IDs were collected from. */
39 appId?: string;
40 /** Immutable source of the upload data. */
41 dataSourceType?: datamanager.MobileIdInfoDataSourceTypeEnum | (string & {});
42 };
43
44 export type PairIdInfoProps = {
45 /** Immutable publisher id in the clean room. */
46 publisherId?: string;
47 /** Membership match percentage (0-100). */
48 matchRatePercentage?: number;
49 /** Publisher display name. */
50 publisherName?: string;
51 /** Count of advertiser first-party records uploaded. */
52 advertiserIdentifierCount?: string;
53 /** Immutable advertiser-to-publisher clean room identifier. */
54 cleanRoomIdentifier?: string;
55 };
56
57 export type ContactIdInfoProps = {
58 /** Immutable source of the upload data. */
59 dataSourceType?: datamanager.ContactIdInfoDataSourceTypeEnum | (string & {});
60 };
61
62 export type UserIdInfoProps = {
63 /** Immutable source of the upload data. */
64 dataSourceType?: datamanager.UserIdInfoDataSourceTypeEnum | (string & {});
65 };
66
67 export type IngestedUserListInfoProps = {
68 /**
69 * Immutable upload key types (`CONTACT_ID`, `MOBILE_ID`, `USER_ID`,
70 * `PAIR_ID`, `PSEUDONYMOUS_ID`).
71 * @default ["CONTACT_ID"]
72 */
73 uploadKeyTypes?: UploadKeyType[];
74 /** Partner-audience metadata. Data partners only. */
75 partnerAudienceInfo?: PartnerAudienceInfoProps;
76 /** Extra fields when `MOBILE_ID` is an upload key type. */
77 mobileIdInfo?: MobileIdInfoProps;
78 /** Extra fields when `PAIR_ID` is an upload key type. Data partners only. */
79 pairIdInfo?: PairIdInfoProps;
80 /** Extra fields when `CONTACT_ID` is an upload key type. */
81 contactIdInfo?: ContactIdInfoProps;
82 /** Extra fields when `USER_ID` is an upload key type. */
83 userIdInfo?: UserIdInfoProps;
84 };
85
86 export const lastSegment = (value: string) => {
87 const trimmed = value.replace(/\/+$/, "");
88 const parts = trimmed.split("/");
89 return parts[parts.length - 1] || trimmed;
90 };
91
92 export const normalizeResourceName = (value: string) => value.replace(/\/+$/, "").trim();
93
94 export const sameText = (left: string | undefined, right: string | undefined) =>
95 (left ?? "") === (right ?? "");
96
97 export const jsonEqual = (left: unknown, right: unknown) =>
98 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
99
100 export const updateMaskOf = (...fields: Array<string | undefined>) =>
101 fields.filter((field): field is string => field !== undefined).join(",");
102
103 export const accountIdOf = (value: string) => lastSegment(value).replace(/-/g, "");
104
105 export const parentOf = (name: string) => {
106 const parts = name.split("/").filter((part) => part.length > 0);
107 const index = parts.lastIndexOf("userLists");
108 if (index <= 0) return "";
109 return parts.slice(0, index).join("/");
110 };
111
112 export const accountTypeOf = (parent: string) => {
113 const parts = parent.split("/").filter((part) => part.length > 0);
114 const index = parts.indexOf("accountTypes");
115 if (index < 0 || parts[index + 1] === undefined) return DEFAULT_ACCOUNT_TYPE;
116 return parts[index + 1]!;
117 };
118
119 export const accountOf = (parent: string) => {
120 const parts = parent.split("/").filter((part) => part.length > 0);
121 const index = parts.indexOf("accounts");
122 if (index < 0 || parts[index + 1] === undefined) return "";
123 return parts[index + 1]!;
124 };
125
126 export const resourceName = (parent: string, userListId: string) =>
127 `${normalizeResourceName(parent)}/userLists/${userListId}`;
128
129 export const parentName = (accountType: string, account: string) => {
130 const trimmed = normalizeResourceName(account);
131 if (trimmed.includes("/accounts/")) return trimmed;
132 return `accountTypes/${accountType}/accounts/${accountIdOf(trimmed)}`;
133 };
134
135 export const resolveParent = (input: {
136 parent?: string;
137 accountType?: string;
138 account?: string;
139 }) => {
140 if (input.parent && input.parent.length > 0) {
141 return normalizeResourceName(input.parent);
142 }
143 if (input.account && input.account.length > 0) {
144 return parentName(input.accountType ?? DEFAULT_ACCOUNT_TYPE, input.account);
145 }
146 return "";
147 };
148
149 export const replaceOnIdentity = (input: {
150 previousParent?: string;
151 nextParent: string;
152 previousId?: string;
153 nextId?: string;
154 previousIngested?: unknown;
155 nextIngested?: unknown;
156 }) => {
157 if (
158 input.previousParent !== undefined &&
159 input.previousParent.length > 0 &&
160 input.nextParent.length > 0 &&
161 input.previousParent !== input.nextParent
162 ) {
163 return { action: "replace" as const, deleteFirst: false };
164 }
165 if (
166 input.previousId !== undefined &&
167 input.nextId !== undefined &&
168 input.previousId !== input.nextId
169 ) {
170 return { action: "replace" as const, deleteFirst: false };
171 }
172 if (
173 input.nextIngested !== undefined &&
174 input.previousIngested !== undefined &&
175 !jsonEqual(input.previousIngested, input.nextIngested)
176 ) {
177 return { action: "replace" as const, deleteFirst: false };
178 }
179 return undefined;
180 };
181
182 export const toDisplayName = (
183 id: string,
184 requested: string | undefined,
185 existing: string | undefined,
186 ) =>
187 Effect.gen(function* () {
188 if (requested !== undefined && requested.length > 0) return requested;
189 if (existing !== undefined && existing.length > 0) return existing;
190 return yield* createPhysicalName({
191 id,
192 maxLength: 63,
193 lowercase: true,
194 });
195 });
196
197 const emptyList = <A>() => Effect.succeed([] as A[]);
198
199 export const collectPages = <A, Page, E, R>(
200 pages: Stream.Stream<Page, E, R>,
201 pick: (page: Page) => readonly A[] | undefined,
202 ) =>
203 pages.pipe(
204 Stream.flatMap((page) => Stream.fromIterable(pick(page) ?? [])),
205 Stream.runCollect,
206 Effect.map((chunk) => Array.from(chunk)),
207 );
208
209 export const ignoreMissing = <A, R>(
210 effect: Effect.Effect<A, datamanager.DeleteAccountTypesAccountsUserListsError, R>,
211 ) => effect.pipe(Effect.catchTag("NotFound", () => Effect.void));
212
213 export const getUserList = (name: string) =>
214 name.length === 0
215 ? Effect.undefined
216 : datamanager
217 .getAccountTypesAccountsUserLists({ name })
218 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
219
220 export const listUserLists = (parent: string) =>
221 parent.length === 0
222 ? emptyList<datamanager.UserList>()
223 : collectPages(
224 datamanager.listAccountTypesAccountsUserLists.pages({
225 parent,
226 pageSize: 200,
227 }),
228 (page) => page.userLists,
229 ).pipe(
230 // A missing account has no lists.
231 Effect.catchTag("NotFound", () => emptyList<datamanager.UserList>()),
232 );
233
234 export const findUserListByDisplayName = (displayName: string, parent: string) =>
235 listUserLists(parent).pipe(
236 Effect.map((rows) => rows.find((row) => row.displayName === displayName)),
237 );
238
239 export const ingestedIdentity = (info: IngestedUserListInfoProps | undefined) => {
240 if (info === undefined) return undefined;
241 return {
242 uploadKeyTypes: [...(info.uploadKeyTypes ?? [])].slice().sort(),
243 partnerAudienceInfo: info.partnerAudienceInfo
244 ? {
245 partnerAudienceSource: info.partnerAudienceInfo.partnerAudienceSource,
246 commercePartner: info.partnerAudienceInfo.commercePartner,
247 }
248 : undefined,
249 mobileIdInfo: info.mobileIdInfo
250 ? {
251 keySpace: info.mobileIdInfo.keySpace,
252 appId: info.mobileIdInfo.appId,
253 dataSourceType: info.mobileIdInfo.dataSourceType,
254 }
255 : undefined,
256 pairIdInfo: info.pairIdInfo
257 ? {
258 publisherId: info.pairIdInfo.publisherId,
259 publisherName: info.pairIdInfo.publisherName,
260 matchRatePercentage: info.pairIdInfo.matchRatePercentage,
261 advertiserIdentifierCount: info.pairIdInfo.advertiserIdentifierCount,
262 cleanRoomIdentifier: info.pairIdInfo.cleanRoomIdentifier,
263 }
264 : undefined,
265 contactIdInfo: info.contactIdInfo
266 ? { dataSourceType: info.contactIdInfo.dataSourceType }
267 : undefined,
268 userIdInfo: info.userIdInfo ? { dataSourceType: info.userIdInfo.dataSourceType } : undefined,
269 };
270 };
271
272 export const ingestedFromRow = (
273 info: datamanager.IngestedUserListInfo | undefined,
274 ): IngestedUserListInfoProps | undefined => {
275 if (info === undefined) return undefined;
276 return {
277 uploadKeyTypes: info.uploadKeyTypes,
278 partnerAudienceInfo: info.partnerAudienceInfo
279 ? {
280 partnerAudienceSource: info.partnerAudienceInfo.partnerAudienceSource,
281 commercePartner: info.partnerAudienceInfo.commercePartner,
282 }
283 : undefined,
284 mobileIdInfo: info.mobileIdInfo
285 ? {
286 keySpace: info.mobileIdInfo.keySpace,
287 appId: info.mobileIdInfo.appId,
288 dataSourceType: info.mobileIdInfo.dataSourceType,
289 }
290 : undefined,
291 pairIdInfo: info.pairIdInfo
292 ? {
293 publisherId: info.pairIdInfo.publisherId,
294 matchRatePercentage: info.pairIdInfo.matchRatePercentage,
295 publisherName: info.pairIdInfo.publisherName,
296 advertiserIdentifierCount: info.pairIdInfo.advertiserIdentifierCount,
297 cleanRoomIdentifier: info.pairIdInfo.cleanRoomIdentifier,
298 }
299 : undefined,
300 contactIdInfo: info.contactIdInfo
301 ? { dataSourceType: info.contactIdInfo.dataSourceType }
302 : undefined,
303 userIdInfo: info.userIdInfo ? { dataSourceType: info.userIdInfo.dataSourceType } : undefined,
304 };
305 };
306
307 export const toIngestedBody = (
308 info: IngestedUserListInfoProps | undefined,
309 ): datamanager.IngestedUserListInfo => ({
310 uploadKeyTypes: info?.uploadKeyTypes ?? DEFAULT_UPLOAD_KEY_TYPES,
311 partnerAudienceInfo: info?.partnerAudienceInfo,
312 mobileIdInfo: info?.mobileIdInfo,
313 pairIdInfo: info?.pairIdInfo,
314 contactIdInfo: info?.contactIdInfo,
315 userIdInfo: info?.userIdInfo,
316 });