Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

captureConfigKdl.ts

173 lines5.5 KB

1import * as Schema from "effect/Schema";
2​
3const decodeString = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.String));
4​
5type Token = { value: string; start: number; end: number; quoted: boolean };
6export type KdlNode = {
7 name: string;
8 header: Token[];
9 children: KdlNode[];
10 start: number;
11 end: number;
12 close: number | undefined;
13 kept?: string;
14};
15​
16export function readKdlNodes(source: string): KdlNode[] {
17 const tokens: Token[] = [];
18 const comments: Token[] = [];
19 let offset = 0;
20 const invalid = () =>
21 new Error("Couldn't read this Niri config. Use Advanced to configure it manually.");
22 while (offset < source.length) {
23 const start = offset;
24 const rest = source.slice(offset);
25 if (/^[\t \r\uFEFF\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]/.test(rest)) {
26 offset++;
27 continue;
28 }
29 if (rest.startsWith("//")) {
30 const end = source.indexOf("\n", offset);
31 offset = end < 0 ? source.length : end;
32 continue;
33 }
34 if (rest.startsWith("/*")) {
35 offset += 2;
36 let depth = 1;
37 while (depth && offset < source.length) {
38 if (source.startsWith("/*", offset)) {
39 depth++;
40 offset += 2;
41 } else if (source.startsWith("*/", offset)) {
42 depth--;
43 offset += 2;
44 } else offset++;
45 }
46 if (depth) throw invalid();
47 comments.push({ value: source.slice(start, offset), start, end: offset, quoted: false });
48 continue;
49 }
50 const continuation = /^\\[\t \r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]*\n/.exec(rest);
51 if (continuation) {
52 offset += continuation[0].length;
53 continue;
54 }
55 const raw = /^r(#{0,32})"/.exec(rest);
56 if (raw) {
57 const terminator = `"${raw[1]}`;
58 const end = source.indexOf(terminator, offset + raw[0].length);
59 if (end < 0) throw invalid();
60 offset = end + terminator.length;
61 tokens.push({
62 value: source.slice(start + raw[0].length, end),
63 start,
64 end: offset,
65 quoted: true,
66 });
67 continue;
68 }
69 if (rest[0] === '"') {
70 offset++;
71 while (offset < source.length && source[offset] !== '"') {
72 if (source[offset] === "\\") offset++;
73 offset++;
74 }
75 if (offset === source.length) throw invalid();
76 offset++;
77 // KDL's unicode escapes differ from JSON; names needing those stay on the manual path.
78 let value: string;
79 try {
80 value = decodeString(source.slice(start, offset));
81 } catch {
82 throw invalid();
83 }
84 tokens.push({ value, start, end: offset, quoted: true });
85 continue;
86 }
87 if (rest.startsWith("/-")) offset += 2;
88 else if ("{};\n=()".includes(rest[0]!)) offset++;
89 else {
90 while (offset < source.length && !/[\s{};="()]/.test(source[offset]!)) {
91 if (["//", "/*", "/-"].some((prefix) => source.startsWith(prefix, offset))) break;
92 offset++;
93 }
94 }
95 if (offset === start) throw invalid();
96 tokens.push({ value: source.slice(start, offset), start, end: offset, quoted: false });
97 }
98 let cursor = 0;
99 let seenComments = 0;
100 const is = (token: Token | undefined, value: string) =>
101 token && !token.quoted && token.value === value;
102 const skipValue = () => {
103 if (is(tokens[cursor], "(")) while (cursor < tokens.length && !is(tokens[cursor++], ")"));
104 const value = tokens[cursor++];
105 if (!value || ["{", "}", ";", "\n", "=", "("].some((stop) => is(value, stop))) throw invalid();
106 };
107 const nodes = (nested: boolean): KdlNode[] => {
108 const result: KdlNode[] = [];
109 while (cursor < tokens.length) {
110 if (is(tokens[cursor], "\n") || is(tokens[cursor], ";")) {
111 cursor++;
112 continue;
113 }
114 if (is(tokens[cursor], "}")) {
115 if (!nested) throw invalid();
116 return result;
117 }
118 const disabled = is(tokens[cursor], "/-");
119 if (disabled) cursor++;
120 const name = tokens[cursor++];
121 if (!name || ["{", "}", "=", ";", "\n", "("].includes(name.value)) throw invalid();
122 const node: KdlNode = {
123 name: name.value,
124 header: [name],
125 children: [],
126 start: name.start,
127 end: name.end,
128 close: undefined,
129 };
130 while (
131 cursor < tokens.length &&
132 !is(tokens[cursor], "\n") &&
133 !is(tokens[cursor], ";") &&
134 !is(tokens[cursor], "}")
135 ) {
136 const token = tokens[cursor++]!;
137 if (is(token, "/-") && !is(tokens[cursor], "{")) {
138 skipValue();
139 if (is(tokens[cursor], "=")) {
140 cursor++;
141 skipValue();
142 }
143 node.end = tokens[cursor - 1]!.end;
144 continue;
145 }
146 if (is(token, "{")) {
147 node.children = nodes(true);
148 const close = tokens[cursor++];
149 if (!is(close, "}")) throw invalid();
150 node.close = close!.start;
151 node.end = close!.end;
152 break;
153 }
154 node.header.push(token);
155 node.end = token.end;
156 }
157 const terminator = tokens[cursor];
158 if (terminator?.value === ";" && !terminator.quoted) {
159 const gap: string[] = [];
160 while (seenComments < comments.length && comments[seenComments]!.end <= terminator.start) {
161 const comment = comments[seenComments++]!;
162 if (comment.start >= node.end) gap.push(comment.value);
163 }
164 node.kept = gap.join(" ");
165 node.end = terminator.end;
166 }
167 if (!disabled) result.push(node);
168 }
169 if (nested) throw invalid();
170 return result;
171 };
172 return nodes(false);