@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 472 lines 17.3 KB
Raw
1 import * as rtb from "@distilled.cloud/gcp/realtimebidding_v1";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Effect from "effect/Effect";
4 import * as Stream from "effect/Stream";
5 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
6
7 export const MAX_DISPLAY_NAME_LENGTH = 255;
8 export const PROBE_PARENT = "bidders/1";
9 export const PROBE_NAME = `${PROBE_PARENT}/pretargetingConfigs/0`;
10
11 export type TargetingMode = rtb.StringTargetingDimensionTargetingModeEnum | (string & {});
12
13 export type StringTargetingDimensionValue = {
14 targetingMode?: TargetingMode;
15 values?: string[];
16 };
17
18 export type NumericTargetingDimensionValue = {
19 includedIds?: string[];
20 excludedIds?: string[];
21 };
22
23 export type CreativeDimensionsValue = {
24 width?: string;
25 height?: string;
26 };
27
28 export type AppTargetingValue = {
29 mobileAppTargeting?: StringTargetingDimensionValue;
30 mobileAppCategoryTargeting?: NumericTargetingDimensionValue;
31 };
32
33 export type PretargetingState = rtb.PretargetingConfigStateEnum | (string & {});
34
35 export type PretargetingSpec = {
36 allowedUserTargetingModes?: string[];
37 excludedContentLabelIds?: string[];
38 includedLanguages?: string[];
39 webTargeting?: StringTargetingDimensionValue;
40 includedPlatforms?: string[];
41 includedFormats?: string[];
42 maximumQps?: string;
43 geoTargeting?: NumericTargetingDimensionValue;
44 includedEnvironments?: string[];
45 userListTargeting?: NumericTargetingDimensionValue;
46 publisherTargeting?: StringTargetingDimensionValue;
47 includedUserIdTypes?: string[];
48 minimumViewabilityDecile?: number;
49 verticalTargeting?: NumericTargetingDimensionValue;
50 includedCreativeDimensions?: CreativeDimensionsValue[];
51 interstitialTargeting?: string;
52 appTargeting?: AppTargetingValue;
53 includedMobileOperatingSystemIds?: string[];
54 };
55
56 export const lastSegment = (value: string) => {
57 const trimmed = value.replace(/\/+$/, "");
58 const parts = trimmed.split("/");
59 return parts[parts.length - 1] || trimmed;
60 };
61
62 export const normalizeResourceName = (value: string) => value.replace(/\/+$/, "").trim();
63
64 export const expandParent = (value: string) => {
65 const trimmed = normalizeResourceName(value);
66 if (trimmed.length === 0) return trimmed;
67 return trimmed.startsWith("bidders/") ? trimmed : `bidders/${trimmed}`;
68 };
69
70 export const parentOfName = (name: string) => {
71 const parts = name.split("/").filter((part) => part.length > 0);
72 const plural = parts.lastIndexOf("pretargetingConfigs");
73 const singular = parts.lastIndexOf("pretargetingConfig");
74 const index = Math.max(plural, singular);
75 if (index > 0) return parts.slice(0, index).join("/");
76 return "";
77 };
78
79 export const resourceName = (parent: string, configId: string) =>
80 `${expandParent(parent)}/pretargetingConfigs/${configId}`;
81
82 export const configIdOf = (name: string) => lastSegment(name);
83
84 export const sameText = (left: string | undefined, right: string | undefined) =>
85 (left ?? "") === (right ?? "");
86
87 const canonical = (value: unknown): unknown => {
88 if (value === undefined || value === null) return undefined;
89 if (typeof value === "boolean" || typeof value === "number") return value;
90 if (typeof value === "string") {
91 return value.length === 0 ? undefined : value;
92 }
93 if (Array.isArray(value)) {
94 const items = value.map(canonical).filter((item) => item !== undefined);
95 if (items.length === 0) return undefined;
96 const allScalar = items.every((item) => item === undefined || typeof item !== "object");
97 return allScalar
98 ? [...items].sort((left, right) =>
99 String(left as string | number | boolean).localeCompare(
100 String(right as string | number | boolean),
101 ),
102 )
103 : items;
104 }
105 if (typeof value === "object") {
106 const entries = Object.entries(value as Record<string, unknown>)
107 .map(([key, item]) => [key, canonical(item)] as const)
108 .filter(([, item]) => item !== undefined)
109 .sort(([left], [right]) => left.localeCompare(right));
110 if (entries.length === 0) return undefined;
111 return Object.fromEntries(entries);
112 }
113 return undefined;
114 };
115
116 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
117
118 export const jsonEqual = (left: unknown, right: unknown) =>
119 fingerprint(left) === fingerprint(right);
120
121 export const replaceOnIdentity = (input: {
122 previousParent?: string;
123 nextParent: string;
124 previousId?: string;
125 nextId?: string;
126 }) => {
127 if (
128 input.previousParent !== undefined &&
129 input.previousParent.length > 0 &&
130 input.nextParent.length > 0 &&
131 input.previousParent !== input.nextParent
132 ) {
133 return { action: "replace" as const, deleteFirst: false };
134 }
135 if (
136 input.previousId !== undefined &&
137 input.nextId !== undefined &&
138 input.previousId !== input.nextId
139 ) {
140 return { action: "replace" as const, deleteFirst: true };
141 }
142 return undefined;
143 };
144
145 const markerOf = (stack: string, stage: string, id: string) =>
146 `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`;
147
148 export const fitMarker = (labels: Record<string, string>, maxLength: number) => {
149 let stack = labels[alchemyLabelKeys.stack] ?? "x";
150 let stage = labels[alchemyLabelKeys.stage] ?? "x";
151 let id = labels[alchemyLabelKeys.id] ?? "x";
152 let marker = markerOf(stack, stage, id);
153 while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) {
154 if (id.length >= stack.length && id.length >= stage.length) {
155 id = id.slice(0, -1);
156 } else if (stack.length >= stage.length) {
157 stack = stack.slice(0, -1);
158 } else {
159 stage = stage.slice(0, -1);
160 }
161 marker = markerOf(stack, stage, id);
162 }
163 return marker.slice(0, maxLength);
164 };
165
166 export const encodeDisplayName = (
167 labels: Record<string, string>,
168 displayName: string | undefined,
169 maxLength = MAX_DISPLAY_NAME_LENGTH,
170 ): string => {
171 const trimmed = displayName?.replace(/[\r\n]+/g, " ").trim();
172 if (!trimmed) return fitMarker(labels, maxLength);
173 const minMarker = 24;
174 const reserved = Math.min(trimmed.length + 1, Math.max(0, maxLength - minMarker));
175 const marker = fitMarker(labels, maxLength - reserved);
176 return `${marker} ${trimmed}`.slice(0, maxLength);
177 };
178
179 export const parseDisplayName = (
180 displayName: string | undefined,
181 ): {
182 labels: Record<string, string>;
183 displayName: string | undefined;
184 } => {
185 if (!displayName?.startsWith("[alchemy ")) {
186 return { labels: {}, displayName };
187 }
188 const end = displayName.indexOf("]");
189 if (end < 0) return { labels: {}, displayName };
190 const labels: Record<string, string> = {};
191 for (const part of displayName.slice("[alchemy ".length, end).split(/\s+/)) {
192 const eq = part.indexOf("=");
193 if (eq > 0) {
194 labels[part.slice(0, eq)] = part.slice(eq + 1);
195 }
196 }
197 const rest = displayName.slice(end + 1).replace(/^[\s\n]+/, "");
198 return { labels, displayName: rest.length > 0 ? rest : undefined };
199 };
200
201 export const hasOwnershipMarker = (displayName: string | undefined) =>
202 Object.keys(parseDisplayName(displayName).labels).some((key) => key.startsWith("alchemy-"));
203
204 const prefixMatch = (expected: string, observed: string) =>
205 expected === observed || expected.startsWith(observed) || observed.startsWith(expected);
206
207 export const ownedByAlchemy = (id: string, displayName: string | undefined) =>
208 Effect.gen(function* () {
209 const expected = yield* createInternalLabels(id);
210 const { labels } = parseDisplayName(displayName);
211 if (!hasOwnershipMarker(displayName)) return false;
212 if (yield* hasAlchemyLabels(id, labels)) return true;
213 return (
214 prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") &&
215 prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") &&
216 prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "")
217 );
218 });
219
220 export const ownershipLabels = (id: string) => createInternalLabels(id);
221
222 export const toDisplayName = (
223 id: string,
224 requested: string | undefined,
225 existing: string | undefined,
226 ) =>
227 Effect.gen(function* () {
228 if (requested !== undefined && requested.length > 0) {
229 return parseDisplayName(requested).displayName ?? requested;
230 }
231 if (existing !== undefined && existing.length > 0) {
232 return parseDisplayName(existing).displayName ?? existing;
233 }
234 const generated = yield* createPhysicalName({
235 id,
236 maxLength: 40,
237 lowercase: true,
238 });
239 return /^[a-z]/.test(generated) ? generated : `c${generated}`.slice(0, 40);
240 });
241
242 const emptyList = <A>() => Effect.succeed([] as A[]);
243
244 export const collectPages = <A, Page, E, R>(
245 pages: Stream.Stream<Page, E, R>,
246 pick: (page: Page) => readonly A[] | undefined,
247 ) =>
248 pages.pipe(
249 Stream.flatMap((page) => Stream.fromIterable(pick(page) ?? [])),
250 Stream.runCollect,
251 Effect.map((chunk) => Array.from(chunk)),
252 );
253
254 const isMissing = <E extends { readonly _tag: string }>(
255 error: E,
256 ): error is Extract<E, { readonly _tag: "NotFound" }> => error._tag === "NotFound";
257
258 export const ignoreList =
259 <A>(fallback: A) =>
260 <A1, E extends { readonly _tag: string }, R>(
261 self: Effect.Effect<A1, E, R>,
262 ): Effect.Effect<A1 | A, E, R> =>
263 self.pipe(Effect.catchIf(isMissing, () => Effect.succeed(fallback)));
264
265 export const ignoreMissing = <E extends { readonly _tag: string }, R>(
266 effect: Effect.Effect<unknown, E, R>,
267 ) => effect.pipe(Effect.catchIf(isMissing, () => Effect.void));
268
269 export const getConfig = (name: string) =>
270 name.length === 0
271 ? Effect.undefined
272 : rtb
273 .getBiddersPretargetingConfigs({ name })
274 .pipe(Effect.catchIf(isMissing, () => Effect.undefined));
275
276 export const listConfigs = (parent: string) =>
277 parent.length === 0
278 ? emptyList<rtb.PretargetingConfig>()
279 : collectPages(
280 rtb.listBiddersPretargetingConfigs.pages({
281 parent,
282 pageSize: 100,
283 }),
284 (page) => page.pretargetingConfigs,
285 ).pipe(ignoreList([] as rtb.PretargetingConfig[]));
286
287 export const listBidderAccounts = () =>
288 collectPages(rtb.listBidders.pages({ pageSize: 100 }), (page) => page.bidders).pipe(
289 ignoreList([] as rtb.Bidder[]),
290 );
291
292 export const listParentsForNuke = () =>
293 Effect.gen(function* () {
294 const bidders = yield* listBidderAccounts();
295 const listed = bidders
296 .map((bidder) => bidder.name)
297 .filter((name): name is string => !!name)
298 .map(expandParent);
299 return [...new Set(listed)];
300 });
301
302 export const listOwnedConfigs = () =>
303 Effect.gen(function* () {
304 const parents = yield* listParentsForNuke();
305 const pages = yield* Effect.forEach(parents, listConfigs, {
306 concurrency: 4,
307 });
308 return pages.flat().filter((row) => hasOwnershipMarker(row.displayName));
309 });
310
311 export const findOwnedConfig = (id: string, parent?: string, name?: string, displayName?: string) =>
312 Effect.gen(function* () {
313 const rows =
314 parent && parent.length > 0 ? yield* listConfigs(parent) : yield* listOwnedConfigs();
315 if (name) {
316 const exact = rows.find((row) => row.name === name);
317 if (exact) return exact;
318 }
319 if (displayName) {
320 const named = rows.find((row) => sameText(row.displayName, displayName));
321 if (named) return named;
322 }
323 for (const row of rows) {
324 if (yield* ownedByAlchemy(id, row.displayName)) {
325 return row;
326 }
327 }
328 return undefined;
329 });
330
331 const keep = <T>(news: T | undefined, current: T | undefined) =>
332 news !== undefined ? news : current;
333
334 export const specOf = (input: PretargetingSpec): PretargetingSpec => ({
335 allowedUserTargetingModes: input.allowedUserTargetingModes,
336 excludedContentLabelIds: input.excludedContentLabelIds,
337 includedLanguages: input.includedLanguages,
338 webTargeting: input.webTargeting,
339 includedPlatforms: input.includedPlatforms,
340 includedFormats: input.includedFormats,
341 maximumQps: input.maximumQps,
342 geoTargeting: input.geoTargeting,
343 includedEnvironments: input.includedEnvironments,
344 userListTargeting: input.userListTargeting,
345 publisherTargeting: input.publisherTargeting,
346 includedUserIdTypes: input.includedUserIdTypes,
347 minimumViewabilityDecile: input.minimumViewabilityDecile,
348 verticalTargeting: input.verticalTargeting,
349 includedCreativeDimensions: input.includedCreativeDimensions,
350 interstitialTargeting: input.interstitialTargeting,
351 appTargeting: input.appTargeting,
352 includedMobileOperatingSystemIds: input.includedMobileOperatingSystemIds,
353 });
354
355 export const specFromRow = (row: rtb.PretargetingConfig): PretargetingSpec =>
356 specOf({
357 allowedUserTargetingModes: row.allowedUserTargetingModes,
358 excludedContentLabelIds: row.excludedContentLabelIds,
359 includedLanguages: row.includedLanguages,
360 webTargeting: row.webTargeting,
361 includedPlatforms: row.includedPlatforms,
362 includedFormats: row.includedFormats,
363 maximumQps: row.maximumQps,
364 geoTargeting: row.geoTargeting,
365 includedEnvironments: row.includedEnvironments,
366 userListTargeting: row.userListTargeting,
367 publisherTargeting: row.publisherTargeting,
368 includedUserIdTypes: row.includedUserIdTypes,
369 minimumViewabilityDecile: row.minimumViewabilityDecile,
370 verticalTargeting: row.verticalTargeting,
371 includedCreativeDimensions: row.includedCreativeDimensions,
372 interstitialTargeting: row.interstitialTargeting,
373 appTargeting: row.appTargeting,
374 includedMobileOperatingSystemIds: row.includedMobileOperatingSystemIds,
375 });
376
377 export const mergeSpec = (
378 news: PretargetingSpec,
379 current: PretargetingSpec | undefined,
380 ): PretargetingSpec => ({
381 allowedUserTargetingModes: keep(
382 news.allowedUserTargetingModes,
383 current?.allowedUserTargetingModes,
384 ),
385 excludedContentLabelIds: keep(news.excludedContentLabelIds, current?.excludedContentLabelIds),
386 includedLanguages: keep(news.includedLanguages, current?.includedLanguages),
387 webTargeting: keep(news.webTargeting, current?.webTargeting),
388 includedPlatforms: keep(news.includedPlatforms, current?.includedPlatforms),
389 includedFormats: keep(news.includedFormats, current?.includedFormats),
390 maximumQps: keep(news.maximumQps, current?.maximumQps),
391 geoTargeting: keep(news.geoTargeting, current?.geoTargeting),
392 includedEnvironments: keep(news.includedEnvironments, current?.includedEnvironments),
393 userListTargeting: keep(news.userListTargeting, current?.userListTargeting),
394 publisherTargeting: keep(news.publisherTargeting, current?.publisherTargeting),
395 includedUserIdTypes: keep(news.includedUserIdTypes, current?.includedUserIdTypes),
396 minimumViewabilityDecile: keep(news.minimumViewabilityDecile, current?.minimumViewabilityDecile),
397 verticalTargeting: keep(news.verticalTargeting, current?.verticalTargeting),
398 includedCreativeDimensions: keep(
399 news.includedCreativeDimensions,
400 current?.includedCreativeDimensions,
401 ),
402 interstitialTargeting: keep(news.interstitialTargeting, current?.interstitialTargeting),
403 appTargeting: keep(news.appTargeting, current?.appTargeting),
404 includedMobileOperatingSystemIds: keep(
405 news.includedMobileOperatingSystemIds,
406 current?.includedMobileOperatingSystemIds,
407 ),
408 });
409
410 export const toConfigBody = (
411 displayName: string,
412 spec: PretargetingSpec,
413 ): rtb.PretargetingConfig => ({
414 displayName,
415 allowedUserTargetingModes: spec.allowedUserTargetingModes,
416 excludedContentLabelIds: spec.excludedContentLabelIds,
417 includedLanguages: spec.includedLanguages,
418 webTargeting: spec.webTargeting,
419 includedPlatforms: spec.includedPlatforms,
420 includedFormats: spec.includedFormats,
421 maximumQps: spec.maximumQps,
422 geoTargeting: spec.geoTargeting,
423 includedEnvironments: spec.includedEnvironments,
424 userListTargeting: spec.userListTargeting,
425 publisherTargeting: spec.publisherTargeting,
426 includedUserIdTypes: spec.includedUserIdTypes,
427 minimumViewabilityDecile: spec.minimumViewabilityDecile,
428 verticalTargeting: spec.verticalTargeting,
429 includedCreativeDimensions: spec.includedCreativeDimensions,
430 interstitialTargeting: spec.interstitialTargeting,
431 appTargeting: spec.appTargeting,
432 includedMobileOperatingSystemIds: spec.includedMobileOperatingSystemIds,
433 });
434
435 const PATCH_FIELDS = [
436 ["allowedUserTargetingModes", "allowedUserTargetingModes"],
437 ["excludedContentLabelIds", "excludedContentLabelIds"],
438 ["includedLanguages", "includedLanguages"],
439 ["webTargeting", "webTargeting"],
440 ["includedPlatforms", "includedPlatforms"],
441 ["includedFormats", "includedFormats"],
442 ["maximumQps", "maximumQps"],
443 ["geoTargeting", "geoTargeting"],
444 ["includedEnvironments", "includedEnvironments"],
445 ["userListTargeting", "userListTargeting"],
446 ["publisherTargeting", "publisherTargeting"],
447 ["includedUserIdTypes", "includedUserIdTypes"],
448 ["minimumViewabilityDecile", "minimumViewabilityDecile"],
449 ["verticalTargeting", "verticalTargeting"],
450 ["includedCreativeDimensions", "includedCreativeDimensions"],
451 ["interstitialTargeting", "interstitialTargeting"],
452 ["appTargeting", "appTargeting"],
453 ["includedMobileOperatingSystemIds", "includedMobileOperatingSystemIds"],
454 ] as const satisfies ReadonlyArray<readonly [keyof PretargetingSpec, keyof PretargetingSpec]>;
455
456 export const updateMaskOf = (
457 current: rtb.PretargetingConfig,
458 desired: PretargetingSpec,
459 displayName: string,
460 ) => {
461 const fields: string[] = [];
462 if (!sameText(current.displayName, displayName)) {
463 fields.push("displayName");
464 }
465 const observed = specFromRow(current);
466 for (const [key, mask] of PATCH_FIELDS) {
467 if (!jsonEqual(observed[key], desired[key])) {
468 fields.push(mask);
469 }
470 }
471 return fields.join(",");
472 };