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

composerContextLegacy.ts

444 lines15.8 KB

1import {
2 type ComposerContextId,
3 ComposerContextRecord,
4 type ElementContextRecord,
5 type PreviewAnnotationContextRecord,
6 ReviewCommentContextRecord,
7 type TerminalContextRecord,
8} from "@t3tools/contracts";
9import * as Schema from "effect/Schema";
10​
11import { formatComposerContextReference } from "./composerContextReferences.ts";
12​
13/**
14 * Event history is never rewritten; this runs in memory on read.
15 */
16​
17export interface UpgradedLegacyContext {
18 text: string;
19 records: ComposerContextRecord[];
21​
22const PLACEHOLDER = "";
23const TRAILING_TERMINAL =
24 /\n*<terminal_context>\n((?:(?!\n<\/terminal_context>)[\s\S])*)\n<\/terminal_context>\s*$/;
25const TRAILING_ELEMENT =
26 /\n*<element_context>\n((?:(?!\n<\/element_context>)[\s\S])*)\n<\/element_context>\s*$/;
27const TRAILING_PREVIEW =
28 /\n*<preview_annotation>\n((?:(?!\n<\/preview_annotation>)[\s\S])*)\n<\/preview_annotation>\s*$/;
29const REVIEW_OR_CONTEXT_BLOCK =
30 /<review_comment\b([^>]*)>|^<(terminal_context|element_context|preview_annotation)>\n[\s\S]*?\n<\/\2>/gm;
31const REVIEW_ATTRIBUTE = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g;
32const REVIEW_FENCE = /(`{3,})([^\s`]*)[^\n]*\n([\s\S]*?)\n\1/g;
33const REVIEW_TOKEN = "\uE000";
34const LEGACY_MARKERS =
35 /<(?:terminal_context|element_context|preview_annotation|review_comment)\b|/;
36const isReviewCommentContextRecord = Schema.is(ReviewCommentContextRecord);
37const isLegacyContextRecords = Schema.is(
38 Schema.Array(ComposerContextRecord).check(Schema.isMaxLength(200)),
39);
40​
41interface ParsedEntry {
42 header: string;
43 body: string;
45​
46function parseEntries(block: string): ParsedEntry[] | null {
47 const entries: ParsedEntry[] = [];
48 let current: { header: string; bodyLines: string[] } | null = null;
49 const commit = () => {
50 if (!current) return;
51 entries.push({ header: current.header, body: current.bodyLines.join("\n").trimEnd() });
52 current = null;
53 };
54 for (const line of block.split("\n")) {
55 const headerMatch = /^- (.+):$/.exec(line);
56 if (headerMatch) {
57 commit();
58 current = { header: headerMatch[1]!, bodyLines: [] };
59 continue;
60 }
61 if (current && line.startsWith(" ")) current.bodyLines.push(line.slice(2));
62 else if (line.trim().length > 0) return null;
63 else if (current) current.bodyLines.push("");
64 }
65 commit();
66 return entries;
68​
69function inlineTerminalLabel(record: TerminalContextRecord): string {
70 const slug = record.terminalLabel.trim().toLowerCase().replace(/\s+/g, "-");
71 const range =
72 record.lineStart === record.lineEnd
73 ? `${record.lineStart}`
74 : `${record.lineStart}-${record.lineEnd}`;
75 return `@${slug}:${range}`;
77​
78function legacyId(kind: string, index: number): ComposerContextId {
79 return `legacy_${kind}_${index}` as ComposerContextId;
81​
82function terminalRecord(entry: ParsedEntry, index: number): TerminalContextRecord | null {
83 const header = /^(.*?) (?:line (\d+)|lines (\d+)-(\d+))$/.exec(entry.header);
84 if (!header) return null;
85 const terminalLabel = header[1]!.trim();
86 if (!terminalLabel) return null;
87 const lineStart = Number(header[2] ?? header[3]);
88 const lineEnd = Number(header[2] ?? header[4]);
89 const text = entry.body
90 .split("\n")
91 .map((line) => line.replace(/^\d+ \| ?/, ""))
92 .join("\n");
93 return {
94 version: 1,
95 contextId: legacyId("terminal", index),
96 kind: "terminal",
97 label: entry.header,
98 terminalId: terminalLabel.toLowerCase().replace(/\s+/g, "-"),
99 terminalLabel,
100 lineStart,
101 lineEnd,
102 text,
103 };
105​
106function parseSource(location: string): ElementContextRecord["source"] {
107 const match = /^(.*?)(?::(\d+))?(?::(\d+))?$/.exec(location);
108 if (!match || !match[1]) return null;
109 return {
110 functionName: null,
111 fileName: match[1],
112 lineNumber: match[2] === undefined ? null : Number(match[2]),
113 columnNumber: match[3] === undefined ? null : Number(match[3]),
114 };
116​
117function elementRecord(entry: ParsedEntry, index: number): ElementContextRecord | null {
118 const header = /^<([^>]+)>/.exec(entry.header);
119 if (!header) return null;
120 const inner = header[1]!;
121 const fields: Record<string, string> = {};
122 const sections: Record<string, string[]> = {};
123 let section: string | null = null;
124 for (const line of entry.body.split("\n")) {
125 if (section && (line.startsWith(" ") || line.length === 0)) {
126 sections[section]!.push(line.slice(2));
127 continue;
128 }
129 section = null;
130 const field = /^([a-z]+): (.*)$/.exec(line);
131 if (field) {
132 fields[field[1]!] = field[2]!;
133 continue;
134 }
135 const sectionStart = /^(html|styles):$/.exec(line);
136 if (sectionStart) {
137 section = sectionStart[1]!;
138 sections[section] = [];
139 }
140 }
141 return {
142 version: 1,
143 contextId: legacyId("element", index),
144 kind: "element",
145 label: `<${inner}>`,
146 pageUrl: fields.url ?? "",
147 pageTitle: null,
148 tagName: inner.toLowerCase(),
149 selector: fields.selector ?? null,
150 htmlPreview: (sections.html ?? []).join("\n").trimEnd(),
151 componentName: /[A-Z]/.test(inner) ? inner : null,
152 source: fields.source ? parseSource(fields.source) : null,
153 styles: (sections.styles ?? []).join("\n").trimEnd(),
154 };
156​
157function previewRecord(body: string, index: number): PreviewAnnotationContextRecord | null {
158 const lines = body.split("\n");
159 // A legacy comment was written verbatim, so it can run over several lines and hold blank
160 // lines and markup of its own. Its value is every line up to the next field or the block that
161 // follows it — anything else is text the author typed, and dropping it loses instructions the
162 // chip that replaces this block cannot show.
163 const FIELD_PREFIXES = ["Preview annotation:", "Id: ", "Page: ", "Comment: ", "Targets: "];
164 const BLOCK_DELIMITER =
165 /^<\/?(?:terminal_context|element_context|preview_annotation|review_comment)\b/;
166 const isFieldStart = (line: string) =>
167 FIELD_PREFIXES.some((candidate) => line.startsWith(candidate)) ||
168 line === "Requested visual changes:" ||
169 BLOCK_DELIMITER.test(line) ||
170 line === "The attached screenshot is the annotated preview crop.";
171 const read = (prefix: string) => {
172 const start = lines.findIndex((line) => line.startsWith(prefix));
173 if (start < 0) return "";
174 let end = start + 1;
175 while (end < lines.length && !isFieldStart(lines[end]!)) end += 1;
176 return [lines[start]!.slice(prefix.length), ...lines.slice(start + 1, end)].join("\n").trim();
177 };
178 const styleHeading = lines.indexOf("Requested visual changes:");
179 const styleChanges: string[] = [];
180 if (styleHeading >= 0) {
181 for (const line of lines.slice(styleHeading + 1)) {
182 if (!line.startsWith("- ")) break;
183 styleChanges.push(line.slice(2));
184 }
185 }
186 const page = read("Page: ");
187 const pageIsUrl = /^https?:\/\//i.test(page);
188 const elements: NonNullable<PreviewAnnotationContextRecord["elements"]>[number][] = [];
189 for (const match of body.matchAll(/<element_context>\n([\s\S]*?)\n<\/element_context>/g)) {
190 const entries = parseEntries(match[1] ?? "");
191 if (entries === null) return null;
192 for (const entry of entries) {
193 const record = elementRecord(entry, elements.length + 1);
194 if (record === null) return null;
195 const {
196 version: _version,
197 contextId: _contextId,
198 kind: _kind,
199 label: _label,
200 ...details
201 } = record;
202 elements.push(details);
203 }
204 }
205 return {
206 version: 1,
207 contextId: legacyId("preview-annotation", index),
208 kind: "preview-annotation",
209 label: page || "Preview annotation",
210 annotationId: read("Id: "),
211 pageUrl: pageIsUrl ? page : (elements[0]?.pageUrl ?? ""),
212 pageTitle: pageIsUrl ? null : page || null,
213 comment: read("Comment: "),
214 targetSummary: read("Targets: "),
215 styleChanges,
216 ...(elements.length > 0 ? { elements } : {}),
217 };
219​
220function unescapeAttribute(value: string): string {
221 return value
222 .replace(/&lt;/g, "<")
223 .replace(/&gt;/g, ">")
224 .replace(/&quot;/g, '"')
225 .replace(/&amp;/g, "&");
227​
228function reviewRecord(
229 rawAttributes: string,
230 rawBody: string,
231 index: number,
232): ReviewCommentContextRecord | null {
233 const attributes: Record<string, string> = {};
234 for (const match of rawAttributes.matchAll(REVIEW_ATTRIBUTE)) {
235 attributes[match[1]!] = unescapeAttribute(match[2] ?? "");
236 }
237 const filePath = attributes.filePath?.trim();
238 const sectionId = attributes.sectionId?.trim();
239 const startIndex = attributes.startIndex;
240 const endIndex = attributes.endIndex;
241 if (!filePath || !sectionId || !/^\d+$/.test(startIndex ?? "") || !/^\d+$/.test(endIndex ?? "")) {
242 return null;
243 }
244 const fences = Array.from(rawBody.matchAll(REVIEW_FENCE));
245 const fence = fences.at(-1);
246 const rangeLabel = attributes.rangeLabel?.trim() || "line";
247 const basename = filePath.split(/[\\/]/).at(-1) ?? filePath;
248 return {
249 version: 1,
250 contextId: legacyId("review-comment", index),
251 kind: "review-comment",
252 label: `${basename} ${rangeLabel}`,
253 sectionId,
254 sectionTitle: attributes.sectionTitle?.trim() || "Review",
255 filePath,
256 startIndex: Math.min(Number(startIndex), Number(endIndex)),
257 endIndex: Math.max(Number(startIndex), Number(endIndex)),
258 rangeLabel,
259 text: rawBody.slice(0, fence?.index ?? rawBody.length).trim(),
260 diff: fence?.[3] ?? "",
261 fenceLanguage: fence?.[2]?.trim() || "diff",
262 };
264​
265function stripTrailing(
266 text: string,
267 pattern: RegExp,
268): { text: string; match: RegExpExecArray } | null {
269 const match = pattern.exec(text);
270 if (!match) return null;
271 return { text: text.slice(0, match.index).replace(/\n+$/, ""), match };
273​
274/** Review source can contain literal closing tags inside its dynamically sized code fence. */
275function replaceReviewBlocks(
276 text: string,
277 replace: (whole: string, attributes: string, body: string) => string,
278): string {
279 const parts: string[] = [];
280 const openings = new RegExp(REVIEW_OR_CONTEXT_BLOCK);
281 let consumed = 0;
282 for (let opening = openings.exec(text); opening; opening = openings.exec(text)) {
283 // Other context blocks own their payload, including any review-shaped source text.
284 if (opening[2]) continue;
285 const bodyStart = openings.lastIndex;
286 const boundaries = /^(`{3,})([^\n]*)$|<\/review_comment>/gm;
287 boundaries.lastIndex = bodyStart;
288 let fenceLength = 0;
289 for (let boundary = boundaries.exec(text); boundary; boundary = boundaries.exec(text)) {
290 if (boundary[1]) {
291 if (fenceLength === 0) fenceLength = boundary[1].length;
292 else if (boundary[1].length >= fenceLength && !boundary[2]?.trim()) fenceLength = 0;
293 } else if (fenceLength === 0) {
294 parts.push(text.slice(consumed, opening.index));
295 consumed = boundaries.lastIndex;
296 parts.push(
297 replace(
298 text.slice(opening.index, consumed),
299 opening[1]!,
300 text.slice(bodyStart, boundary.index),
301 ),
302 );
303 openings.lastIndex = consumed;
304 break;
305 }
306 }
307 if (consumed < bodyStart) break;
308 }
309 parts.push(text.slice(consumed));
310 return parts.join("");
312​
313export function upgradeLegacyContextMessage(text: string): UpgradedLegacyContext {
314 if (!LEGACY_MARKERS.test(text)) return { text, records: [] };
315​
316 const terminalEntries: ParsedEntry[] = [];
317 const elementEntries: ParsedEntry[] = [];
318 const previewBodies: string[] = [];
319 const reviews: ReviewCommentContextRecord[] = [];
320​
321 // A literal private-use token in the message must never be mistaken for our placeholder.
322 let reviewToken = REVIEW_TOKEN;
323 while (text.includes(reviewToken)) reviewToken += reviewToken;
324 const reviewTokenPattern = new RegExp(`${reviewToken}(\\d+)${reviewToken}`, "g");
325 const trailingReviewTokenPattern = new RegExp(`(?:\\s*${reviewToken}\\d+${reviewToken})+\\s*$`);
326​
327 let rest = replaceReviewBlocks(text, (whole, attributes, rawBody) => {
328 const record = reviewRecord(attributes, rawBody, reviews.length + 1);
329 if (!record || !isReviewCommentContextRecord(record)) return whole;
330 reviews.push(record);
331 return `${reviewToken}${reviews.length - 1}${reviewToken}`;
332 });
333​
334 // Blocks were appended in send order (terminal, element, preview, review), so they peel
335 // off the end in reverse. Each peel exposes the next block as trailing.
336 // Peel reviews only when they hide another trailing context block. A review at the end
337 // of ordinary prose can still be inline; keep its original spacing and line breaks.
338 const trailingReviewTokens: number[] = [];
339 const tokens = trailingReviewTokenPattern.exec(rest);
340 if (tokens && tokens[0].length > 0) {
341 const preceding = rest.slice(0, tokens.index);
342 if (
343 TRAILING_PREVIEW.test(preceding) ||
344 TRAILING_ELEMENT.test(preceding) ||
345 TRAILING_TERMINAL.test(preceding)
346 ) {
347 trailingReviewTokens.push(
348 ...Array.from(tokens[0].matchAll(reviewTokenPattern), (m) => Number(m[1])),
349 );
350 rest = preceding;
351 }
352 }
353 for (;;) {
354 const preview = stripTrailing(rest, TRAILING_PREVIEW);
355 if (preview) {
356 rest = preview.text;
357 previewBodies.unshift(preview.match[1] ?? "");
358 continue;
359 }
360 const element = stripTrailing(rest, TRAILING_ELEMENT);
361 if (element) {
362 const entries = parseEntries(element.match[1] ?? "");
363 if (!entries?.length || entries.some((entry) => elementRecord(entry, 1) === null))
364 return { text, records: [] };
365 rest = element.text;
366 elementEntries.unshift(...entries);
367 continue;
368 }
369 const terminal = stripTrailing(rest, TRAILING_TERMINAL);
370 if (terminal) {
371 const entries = parseEntries(terminal.match[1] ?? "");
372 if (!entries?.length || entries.some((entry) => terminalRecord(entry, 1) === null))
373 return { text, records: [] };
374 rest = terminal.text;
375 terminalEntries.unshift(...entries);
376 continue;
377 }
378 break;
379 }
380​
381 const terminals = terminalEntries
382 .map((entry, index) => terminalRecord(entry, index + 1))
383 .filter((record) => record !== null);
384 const elements = elementEntries
385 .map((entry, index) => elementRecord(entry, index + 1))
386 .filter((record) => record !== null);
387 const previews: PreviewAnnotationContextRecord[] = [];
388 for (const [index, previewBody] of previewBodies.entries()) {
389 const record = previewRecord(previewBody, index + 1);
390 if (record === null) return { text, records: [] };
391 previews.push(record);
392 }
393 const appendedReviews = trailingReviewTokens.map((index) => reviews[index]!);
394​
395 let body = rest.replace(reviewTokenPattern, (_whole, index: string) =>
396 formatComposerContextReference(reviews[Number(index)]!),
397 );
398​
399 let placeholderIndex = 0;
400 body = body.replace(new RegExp(PLACEHOLDER, "g"), () => {
401 const record = terminals[placeholderIndex];
402 placeholderIndex += 1;
403 return record ? formatComposerContextReference(record) : "";
404 });
405​
406 const placedTerminals = new Set(terminals.slice(0, placeholderIndex));
407 for (const record of terminals) {
408 if (placedTerminals.has(record)) continue;
409 const label = inlineTerminalLabel(record);
410 let at = body.indexOf(label);
411 while (
412 at !== -1 &&
413 (/[\p{L}\p{N}\p{M}_@.-]$/u.test(body.slice(0, at)) ||
414 /^(?:[\p{L}\p{N}\p{M}_-]|[.@]+[\p{L}\p{N}\p{M}_-])/u.test(body.slice(at + label.length)))
415 ) {
416 at = body.indexOf(label, at + 1);
417 }
418 if (at === -1) continue;
419 body = `${body.slice(0, at)}${formatComposerContextReference(record)}${body.slice(at + label.length)}`;
420 placedTerminals.add(record);
421 }
422 body = body.trimEnd();
423​
424 const appended = [
425 ...terminals.filter((record) => !placedTerminals.has(record)),
426 ...elements,
427 ...previews,
428 ...appendedReviews,
429 ].map((record) => formatComposerContextReference(record));
430 const upgradedText =
431 appended.length === 0
432 ? body
433 : body.length > 0
434 ? `${body}\n\n${appended.join(" ")}`
435 : appended.join(" ");
436​
437 const records = [...terminals, ...elements, ...previews, ...reviews];
438 // Conversion is atomic: keep the source if any record would be dropped on the wire.
439 if (!isLegacyContextRecords(records)) return { text, records: [] };
440 return {
441 text: upgradedText,
442 records,
443 };