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

main
ts 71 lines 2.34 KB
Raw
1 import * as schemas from "@distilled.cloud/aws/schemas";
2 import { createInternalTags, diffTags, tagRecord } from "alchemy/Tags";
3 import * as Effect from "effect/Effect";
4
5 /**
6 * Reads the observed tag map for an EventBridge Schemas resource ARN. A
7 * missing resource yields `{}` so callers treat it as "no tags observed".
8 */
9 export const readSchemasTags = Effect.fn(function* (resourceArn: string) {
10 const { Tags } = yield* schemas.listTagsForResource({ ResourceArn: resourceArn }).pipe(
11 Effect.catchTag("NotFoundException", () =>
12 Effect.succeed({
13 Tags: {} as Record<string, string | undefined>,
14 }),
15 ),
16 );
17 return tagRecord(Tags);
18 });
19
20 /**
21 * Reconciles the tags on a Schemas resource to `{ ...user, ...internal }`,
22 * diffing against the OBSERVED cloud tags (so adoption converges). Applies
23 * only the delta: `tagResource` for upserts, `untagResource` for removals.
24 */
25 export const syncSchemasTags = Effect.fn(function* (
26 resourceArn: string,
27 id: string,
28 userTags: Record<string, string> | undefined,
29 ) {
30 const internalTags = yield* createInternalTags(id);
31 const desired = { ...userTags, ...internalTags };
32 const observed = yield* readSchemasTags(resourceArn);
33 const { upsert, removed } = diffTags(observed, desired);
34 if (upsert.length > 0) {
35 yield* schemas.tagResource({
36 ResourceArn: resourceArn,
37 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
38 });
39 }
40 if (removed.length > 0) {
41 yield* schemas.untagResource({
42 ResourceArn: resourceArn,
43 TagKeys: removed,
44 });
45 }
46 });
47
48 /**
49 * Canonicalizes a JSON document string for comparison: parses and re-stringifies
50 * with recursively sorted object keys so semantically-equal documents compare
51 * equal regardless of key order or whitespace. Non-JSON content is returned
52 * verbatim.
53 */
54 export const canonicalJson = (content: string): string => {
55 const sortKeys = (value: unknown): unknown => {
56 if (Array.isArray(value)) return value.map(sortKeys);
57 if (value !== null && typeof value === "object") {
58 return Object.fromEntries(
59 Object.entries(value as Record<string, unknown>)
60 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
61 .map(([k, v]) => [k, sortKeys(v)]),
62 );
63 }
64 return value;
65 };
66 try {
67 return JSON.stringify(sortKeys(JSON.parse(content)));
68 } catch {
69 return content;
70 }
71 };