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

main
ts 206 lines 6.6 KB
Raw
1 import * as Effect from "effect/Effect";
2 import * as Redacted from "effect/Redacted";
3 import { stringify } from "yaml";
4 import { havePropsChanged } from "../Diff.ts";
5 import * as Output from "../Output.ts";
6 import { isPlainData } from "../Util/data.ts";
7
8 export type YamlDisplayValue =
9 | string
10 | number
11 | boolean
12 | null
13 | YamlDisplayValue[]
14 | { readonly [key: string]: YamlDisplayValue };
15
16 export interface DeclaredPropertyYaml {
17 readonly kind: "create" | "change" | "drift";
18 readonly lines: ReadonlyArray<string>;
19 }
20
21 const unifiedDriftLines = (
22 expected: YamlDisplayValue,
23 actual: YamlDisplayValue,
24 depth = 0,
25 ): string[] => {
26 const padding = " ".repeat(depth);
27 if (JSON.stringify(expected) === JSON.stringify(actual)) {
28 return indent(formatYamlLines(expected), depth);
29 }
30 if (
31 expected !== null &&
32 actual !== null &&
33 !Array.isArray(expected) &&
34 !Array.isArray(actual) &&
35 typeof expected === "object" &&
36 typeof actual === "object"
37 ) {
38 const lines: string[] = [];
39 for (const key of [...new Set([...Object.keys(expected), ...Object.keys(actual)])].sort(
40 (a, b) => a.localeCompare(b),
41 )) {
42 const hasExpected = Object.hasOwn(expected, key);
43 const hasActual = Object.hasOwn(actual, key);
44 const expectedValue = hasExpected ? expected[key]! : UNDEFINED;
45 const actualValue = hasActual ? actual[key]! : UNDEFINED;
46 if (
47 hasExpected &&
48 hasActual &&
49 expectedValue !== null &&
50 actualValue !== null &&
51 !Array.isArray(expectedValue) &&
52 !Array.isArray(actualValue) &&
53 typeof expectedValue === "object" &&
54 typeof actualValue === "object" &&
55 JSON.stringify(expectedValue) !== JSON.stringify(actualValue)
56 ) {
57 lines.push(`${padding}${key}:`);
58 lines.push(...unifiedDriftLines(expectedValue, actualValue, depth + 2));
59 } else if (JSON.stringify(expectedValue) === JSON.stringify(actualValue)) {
60 lines.push(...indent(formatYamlLines({ [key]: expectedValue }), depth));
61 } else {
62 if (hasExpected) {
63 lines.push(...indent(formatYamlLines({ [key]: expectedValue }), depth).map(mark("-")));
64 }
65 if (hasActual) {
66 lines.push(...indent(formatYamlLines({ [key]: actualValue }), depth).map(mark("+")));
67 }
68 }
69 }
70 return lines;
71 }
72 return [
73 ...indent(formatYamlLines(expected), depth).map(mark("-")),
74 ...indent(formatYamlLines(actual), depth).map(mark("+")),
75 ];
76 };
77
78 const mark = (marker: "-" | "+") => (line: string) => `${marker} ${line}`;
79
80 export interface YamlChangeMatch {
81 readonly marker: "-" | "+";
82 readonly content: string;
83 }
84
85 /** Match a `- `/`+ ` change marker emitted by {@link unifiedDriftLines}. */
86 export const matchYamlChange = (line: string): YamlChangeMatch | undefined => {
87 const match = line.match(/^([+-]) (.*)$/);
88 return match === null ? undefined : { marker: match[1] as "-" | "+", content: match[2]! };
89 };
90
91 export interface YamlKeyMatch {
92 readonly indent: string;
93 /** The key including its trailing colon. */
94 readonly key: string;
95 readonly value: string;
96 }
97
98 /** Match an `indent` + `key:` + rest display-YAML line for colorizing. */
99 export const matchYamlKey = (line: string): YamlKeyMatch | undefined => {
100 const match = line.match(/^(\s*)([A-Za-z_][\w .-]*:)(.*)$/);
101 return match === null ? undefined : { indent: match[1]!, key: match[2]!, value: match[3]! };
102 };
103
104 /** Format the changed cloud attributes carried by a drift-repair plan. */
105 export const formatDriftPropertyYaml = (
106 expected: unknown,
107 actual: unknown,
108 missing = false,
109 ): DeclaredPropertyYaml => {
110 const expectedValue = toYamlDisplayValue(expected);
111 const actualValue = missing ? "(missing)" : toYamlDisplayValue(actual);
112 return {
113 kind: "drift",
114 lines: unifiedDriftLines(expectedValue, actualValue),
115 };
116 };
117
118 const REDACTED = "(redacted)";
119 const KNOWN_AFTER_APPLY = "(known after apply)";
120 const COMPUTED = "(computed)";
121 const UNDEFINED = "(undefined)";
122 const OPAQUE = "(opaque)";
123 const CIRCULAR = "(circular)";
124
125 /**
126 * Turn arbitrary declared inputs or persisted state into safe, deterministic
127 * plain data for terminal display. Deferred values are described, never run,
128 * and Redacted values are replaced before their contents can reach YAML.
129 */
130 export const toYamlDisplayValue = (
131 value: unknown,
132 ancestors: WeakSet<object> = new WeakSet(),
133 ): YamlDisplayValue => {
134 // Output expressions are Effects too, so this order is security-sensitive.
135 if (Redacted.isRedacted(value)) return REDACTED;
136 if (Output.isExpr(value)) return KNOWN_AFTER_APPLY;
137 if (Effect.isEffect(value) || typeof value === "function") return COMPUTED;
138 if (value === undefined) return UNDEFINED;
139 if (value === null || typeof value === "string") return value;
140 if (typeof value === "boolean" || typeof value === "number") return value;
141 if (typeof value === "bigint") return `${value}n`;
142 if (!isPlainData(value)) return OPAQUE;
143 if (ancestors.has(value)) return CIRCULAR;
144
145 ancestors.add(value);
146 try {
147 if (Array.isArray(value)) {
148 return value.map((item) => toYamlDisplayValue(item, ancestors));
149 }
150 return Object.fromEntries(
151 Object.keys(value)
152 .sort((a, b) => a.localeCompare(b))
153 .map((key) => [
154 key,
155 toYamlDisplayValue((value as Record<string, unknown>)[key], ancestors),
156 ]),
157 );
158 } finally {
159 ancestors.delete(value);
160 }
161 };
162
163 /** Format a value as stable, unadorned YAML lines for terminal renderers. */
164 export const formatYamlLines = (value: unknown): string[] => {
165 const yaml = stringify(toYamlDisplayValue(value), {
166 lineWidth: 0,
167 sortMapEntries: true,
168 });
169 return (yaml || `${UNDEFINED}\n`).trimEnd().split("\n");
170 };
171
172 /**
173 * Build the detailed property document for a plan resource. This compares
174 * persisted declared props to desired declared props; it is not cloud drift.
175 */
176 export const formatDeclaredPropertyYaml = (
177 oldProps: unknown,
178 newProps: unknown,
179 action: "create" | "update" | "replace",
180 ): DeclaredPropertyYaml | undefined => {
181 const desired = newProps ?? {};
182 if (action === "create") {
183 return {
184 kind: "create",
185 lines: ["properties:", ...indent(formatYamlLines(desired))],
186 };
187 }
188 if (
189 !havePropsChanged(
190 (oldProps ?? {}) as Record<string, unknown>,
191 desired as Record<string, unknown>,
192 )
193 ) {
194 return undefined;
195 }
196 return {
197 kind: "change",
198 lines: [
199 "properties:",
200 ...unifiedDriftLines(toYamlDisplayValue(oldProps ?? {}), toYamlDisplayValue(desired), 2),
201 ],
202 };
203 };
204
205 const indent = (lines: ReadonlyArray<string>, spaces = 2): string[] =>
206 lines.map((line) => `${" ".repeat(spaces)}${line}`);