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

main
ts 53 lines 1.41 KB
Raw
1 /**
2 * Tagged template literal for removing indentation from a block of text.
3 *
4 * If the first line is empty, it will be ignored.
5 */
6 export function dedent(strings: TemplateStringsArray, ...values: unknown[]): string;
7 export function dedent(text: string): string;
8 export function dedent(stringsOrText: TemplateStringsArray | string, ...values: unknown[]): string {
9 const raw =
10 typeof stringsOrText === "string"
11 ? stringsOrText
12 : String.raw({ raw: stringsOrText }, ...values);
13
14 let lines = raw.split("\n");
15
16 while (lines.length > 0 && lines[0].trim() === "") {
17 lines = lines.slice(1);
18 }
19
20 while (lines.length > 0 && lines[lines.length - 1].trim() === "") {
21 lines = lines.slice(0, lines.length - 1);
22 }
23
24 if (lines.length === 0) {
25 return "";
26 }
27
28 let minIndentLength = Number.POSITIVE_INFINITY;
29 for (const line of lines) {
30 if (line.trim() !== "") {
31 const indent = line.match(/^[ \t]*/)?.[0];
32 if (indent != null && indent.length < minIndentLength) {
33 minIndentLength = indent.length;
34 }
35 }
36 }
37
38 if (minIndentLength === Number.POSITIVE_INFINITY) {
39 return lines.join("\n");
40 }
41
42 lines = lines.map((line) => {
43 if (line.trim() === "") {
44 return line;
45 }
46 return line.startsWith(" ".repeat(minIndentLength)) ||
47 line.startsWith("\t".repeat(minIndentLength))
48 ? line.substring(minIndentLength)
49 : line;
50 });
51
52 return lines.join("\n");
53 }