@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 201 lines 7.57 KB
Raw
1 import { createPhysicalName } from "alchemy/PhysicalName";
2 import * as Effect from "effect/Effect";
3 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
4
5 export const DEFAULT_PRODUCT = "IP";
6 export const MAX_ID_LENGTH = 63;
7 export const MAX_DISPLAY_NAME_LENGTH = 255;
8 export const MAX_DESCRIPTION_LENGTH = 8000;
9 export const MAX_TEMPLATE_DESCRIPTION_LENGTH = 255;
10
11 export const lastSegment = (value: string) => {
12 const trimmed = value.replace(/\/+$/, "");
13 const parts = trimmed.split("/");
14 return parts[parts.length - 1] || trimmed;
15 };
16
17 export const locationOf = (name: string, fallback: string) => {
18 const parts = name.split("/");
19 const index = parts.indexOf("locations");
20 return index >= 0 ? (parts[index + 1] ?? fallback) : fallback;
21 };
22
23 export const projectOf = (name: string) => {
24 const parts = name.split("/");
25 const index = parts.indexOf("projects");
26 return index >= 0 ? (parts[index + 1] ?? "") : "";
27 };
28
29 // Integrations returns names keyed by project number, which later get calls
30 // reject ("Found zero or more than one active project"); key them by id.
31 export const withProjectId = (name: string, project: string) =>
32 name.replace(/^projects\/[^/]+/, `projects/${project}`);
33
34 export const productOf = (name: string, fallback = DEFAULT_PRODUCT) => {
35 const parts = name.split("/");
36 const index = parts.indexOf("products");
37 return index >= 0 ? (parts[index + 1] ?? fallback) : fallback;
38 };
39
40 export const parentOf = (name: string) => {
41 const parts = name.split("/").filter((part) => part.length > 0);
42 return parts.slice(0, -2).join("/");
43 };
44
45 export const locationParent = (project: string, location: string) =>
46 `projects/${project}/locations/${location}`;
47
48 export const expandSfdcInstance = (value: string, project: string, location: string) =>
49 value.includes("/") ? value : `${locationParent(project, location)}/sfdcInstances/${value}`;
50
51 export const isDeleted = (resource: { deleteTime?: string }) =>
52 (resource.deleteTime ?? "").length > 0;
53
54 export const productParent = (project: string, location: string, product: string) =>
55 `${locationParent(project, location)}/products/${product}`;
56
57 export const normalizeLocation = (location: string | undefined, defaultLocation: string) =>
58 lastSegment(location ?? defaultLocation).toLowerCase();
59
60 export const normalizeProduct = (product: string | undefined) =>
61 lastSegment(product ?? DEFAULT_PRODUCT);
62
63 export const sameText = (left: string | undefined, right: string | undefined) =>
64 (left ?? "") === (right ?? "");
65
66 export const canonical = (value: unknown): unknown => {
67 if (value === undefined || value === null) return undefined;
68 if (typeof value === "boolean" || typeof value === "number") return value;
69 if (typeof value === "string") {
70 return value.length === 0 ? undefined : value;
71 }
72 if (Array.isArray(value)) {
73 const items = value.map(canonical).filter((item) => item !== undefined);
74 return items.length === 0 ? undefined : items;
75 }
76 if (typeof value === "object") {
77 const entries = Object.entries(value as Record<string, unknown>)
78 .map(([key, item]) => [key, canonical(item)] as const)
79 .filter(([, item]) => item !== undefined)
80 .sort(([left], [right]) => left.localeCompare(right));
81 if (entries.length === 0) return undefined;
82 return Object.fromEntries(entries);
83 }
84 return undefined;
85 };
86
87 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
88
89 export const jsonEqual = (left: unknown, right: unknown) =>
90 fingerprint(left) === fingerprint(right);
91
92 export const replaceOnIdentity = (changed: boolean) =>
93 changed ? ({ action: "replace" as const, deleteFirst: false } as const) : undefined;
94
95 export const updateMaskOf = (...fields: Array<string | undefined>) =>
96 fields.filter((field): field is string => field !== undefined).join(",");
97
98 export const toResourceId = (
99 id: string,
100 requested: string | undefined,
101 existing: string | undefined,
102 maxLength = MAX_ID_LENGTH,
103 ) =>
104 Effect.gen(function* () {
105 if (requested !== undefined) return requested;
106 if (existing !== undefined) return existing;
107 const generated = yield* createPhysicalName({
108 id,
109 maxLength,
110 lowercase: true,
111 });
112 const next = /^[a-z]/.test(generated) ? generated : `i${generated}`.slice(0, maxLength);
113 return next.length >= 4 ? next : `${next}xxxx`.slice(0, maxLength);
114 });
115
116 const markerOf = (labels: Record<string, string>, stack: string, stage: string, id: string) =>
117 `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`;
118
119 const fitMarker = (labels: Record<string, string>, maxLength: number) => {
120 let stack = labels[alchemyLabelKeys.stack] ?? "x";
121 let stage = labels[alchemyLabelKeys.stage] ?? "x";
122 let id = labels[alchemyLabelKeys.id] ?? "x";
123 let marker = markerOf(labels, stack, stage, id);
124 while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) {
125 if (stack.length >= stage.length && stack.length >= id.length) {
126 stack = stack.slice(0, -1);
127 } else if (stage.length >= id.length) {
128 stage = stage.slice(0, -1);
129 } else {
130 id = id.slice(0, -1);
131 }
132 marker = markerOf(labels, stack, stage, id);
133 }
134 return marker.slice(0, maxLength);
135 };
136
137 export const encodeOwnership = (
138 labels: Record<string, string>,
139 text: string | undefined,
140 maxLength = MAX_DESCRIPTION_LENGTH,
141 ): string => {
142 const marker = fitMarker(labels, maxLength);
143 const trimmed = text?.trim();
144 if (!trimmed) return marker.slice(0, maxLength);
145 return `${marker}\n${trimmed}`.slice(0, maxLength);
146 };
147
148 export const encodeOwnershipLine = (
149 labels: Record<string, string>,
150 text: string | undefined,
151 maxLength = MAX_DISPLAY_NAME_LENGTH,
152 ): string => {
153 const trimmed = text?.replace(/[\r\n]+/g, " ").trim();
154 if (!trimmed) return fitMarker(labels, maxLength);
155 const minMarker = 24;
156 const reserved = Math.min(trimmed.length + 1, Math.max(0, maxLength - minMarker));
157 const marker = fitMarker(labels, maxLength - reserved);
158 return `${marker} ${trimmed}`.slice(0, maxLength);
159 };
160
161 export const parseOwnership = (
162 text: string | undefined,
163 ): {
164 labels: Record<string, string>;
165 text: string | undefined;
166 } => {
167 if (!text?.startsWith("[alchemy ")) {
168 return { labels: {}, text };
169 }
170 const end = text.indexOf("]");
171 if (end < 0) return { labels: {}, text };
172 const labels: Record<string, string> = {};
173 for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) {
174 const eq = part.indexOf("=");
175 if (eq > 0) {
176 labels[part.slice(0, eq)] = part.slice(eq + 1);
177 }
178 }
179 const rest = text.slice(end + 1).replace(/^[\s\n]+/, "");
180 return { labels, text: rest.length > 0 ? rest : undefined };
181 };
182
183 export const hasOwnershipMarker = (text: string | undefined) =>
184 Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-"));
185
186 const prefixMatch = (expected: string, observed: string) =>
187 expected === observed || expected.startsWith(observed) || observed.startsWith(expected);
188
189 export const ownedByAlchemy = (id: string, text: string | undefined) =>
190 Effect.gen(function* () {
191 const expected = yield* createInternalLabels(id);
192 const { labels } = parseOwnership(text);
193 if (!hasOwnershipMarker(text)) return false;
194 const exact = yield* hasAlchemyLabels(id, labels);
195 if (exact) return true;
196 return (
197 prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") &&
198 prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") &&
199 prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "")
200 );
201 });