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

composerContextLegacySend.ts

154 lines6.0 KB

1import type { ComposerContextRecord, ElementContextDetails } from "@t3tools/contracts";
2​
3import { collectComposerContextReferences } from "./composerContextReferences.ts";
4​
5/**
6 * Serializes a canonical message (inline reference links plus records) into the pre-inline-context
7 * wire shape, for servers that do not advertise `inlineMessageContext`. Those servers drop the
8 * records and forward the links as literal text, so the payload has to travel inside the message.
9 */
10export function serializeLegacyContextMessage(input: {
11 text: string;
12 records: ReadonlyArray<ComposerContextRecord>;
13}): string {
14 const recordsById = new Map(input.records.map((record) => [record.contextId, record]));
15 const used = new Set<string>();
16​
17 let text = input.text;
18 const occurrences = collectComposerContextReferences(text);
19 for (const occurrence of [...occurrences].reverse()) {
20 const record = recordsById.get(occurrence.contextId);
21 if (!record) continue;
22 used.add(occurrence.contextId);
23 const replacement =
24 record.kind === "review-comment" ? renderReviewComment(record) : inlineLabel(record);
25 text = `${text.slice(0, occurrence.start)}${replacement}${text.slice(occurrence.end)}`;
26 }
27​
28 const blocks = [
29 renderBlock(
30 "terminal_context",
31 input.records.filter((record) => record.kind === "terminal").map(renderTerminalEntry),
32 ),
33 renderBlock(
34 "element_context",
35 input.records.filter((record) => record.kind === "element").map(renderElementEntry),
36 ),
37 ...input.records
38 .filter((record) => record.kind === "preview-annotation")
39 .map((record) => `<preview_annotation>\n${renderPreviewBody(record)}\n</preview_annotation>`),
40 ...input.records
41 .filter((record) => record.kind === "review-comment" && !used.has(record.contextId))
42 .map(renderReviewComment),
43 ].filter((block) => block.length > 0);
44​
45 return [text.trimEnd(), ...blocks].filter((part) => part.length > 0).join("\n\n");
47​
48function inlineLabel(record: ComposerContextRecord): string {
49 if (record.kind === "terminal" && "terminalLabel" in record) {
50 const slug = record.terminalLabel.trim().toLowerCase().replace(/\s+/g, "-");
51 const range =
52 record.lineStart === record.lineEnd
53 ? `${record.lineStart}`
54 : `${record.lineStart}-${record.lineEnd}`;
55 return `@${slug}:${range}`;
56 }
57 return record.label;
59​
60function renderBlock(tag: string, entries: ReadonlyArray<string>): string {
61 const body = entries.filter((entry) => entry.length > 0).join("\n");
62 return body.length === 0 ? "" : `<${tag}>\n${body}\n</${tag}>`;
64​
65function indent(value: string): string {
66 return value
67 .split("\n")
68 .map((line) => (line.length === 0 ? "" : ` ${line}`))
69 .join("\n");
71​
72function renderTerminalEntry(record: ComposerContextRecord): string {
73 if (!("terminalLabel" in record)) return "";
74 const range =
75 record.lineStart === record.lineEnd
76 ? `line ${record.lineStart}`
77 : `lines ${record.lineStart}-${record.lineEnd}`;
78 const body = record.text
79 .split("\n")
80 // A trailing newline would otherwise number a line past the range the label declares.
81 .slice(0, record.lineEnd - record.lineStart + 1)
82 .map((line, index) => `${record.lineStart + index} | ${line}`)
83 .join("\n");
84 return `- ${record.terminalLabel} ${range}:\n${indent(body)}`;
86​
87function renderElementEntry(record: ComposerContextRecord): string {
88 if (!("tagName" in record)) return "";
89 return renderElementDetailsEntry(record);
91​
92function renderElementDetailsEntry(record: ElementContextDetails): string {
93 const lines: string[] = [];
94 if (record.pageUrl) lines.push(`url: ${record.pageUrl}`);
95 if (record.selector) lines.push(`selector: ${record.selector}`);
96 const source = record.source;
97 if (source?.fileName) {
98 const position = [source.lineNumber, source.columnNumber].filter(
99 (part) => part !== null && part !== undefined,
100 );
101 lines.push(`source: ${[source.fileName, ...position].join(":")}`);
102 }
103 if (record.htmlPreview) lines.push(`html:\n${indent(record.htmlPreview)}`);
104 if (record.styles) lines.push(`styles:\n${indent(record.styles)}`);
105 return `- <${record.componentName ?? record.tagName}>:\n${indent(lines.join("\n"))}`;
107​
108function renderPreviewBody(record: ComposerContextRecord): string {
109 if (!("annotationId" in record)) return "";
110 const lines = [`Id: ${record.annotationId}`, `Page: ${record.pageUrl || record.pageTitle || ""}`];
111 if (record.comment) lines.push(`Comment: ${record.comment}`);
112 if (record.targetSummary) lines.push(`Targets: ${record.targetSummary}`);
113 if (record.styleChanges.length > 0) {
114 lines.push("Requested visual changes:", ...record.styleChanges.map((change) => `- ${change}`));
115 }
116 if (record.elements && record.elements.length > 0) {
117 lines.push(
118 "<element_context>",
119 record.elements.map(renderElementDetailsEntry).join("\n"),
120 "</element_context>",
121 );
122 }
123 return lines.join("\n");
125​
126function escapeAttribute(value: string): string {
127 return value
128 .replace(/&/g, "&amp;")
129 .replace(/</g, "&lt;")
130 .replace(/>/g, "&gt;")
131 .replace(/"/g, "&quot;");
133​
134function renderReviewComment(record: ComposerContextRecord): string {
135 if (!("sectionId" in record)) return record.label;
136 const attributes = [
137 `sectionId="${escapeAttribute(record.sectionId)}"`,
138 `sectionTitle="${escapeAttribute(record.sectionTitle)}"`,
139 `filePath="${escapeAttribute(record.filePath)}"`,
140 `rangeLabel="${escapeAttribute(record.rangeLabel)}"`,
141 `startIndex="${record.startIndex}"`,
142 `endIndex="${record.endIndex}"`,
143 ].join(" ");
144 // The fence must be longer than any run of backticks inside the diff so the body stays intact.
145 const longestRun = Math.max(
146 0,
147 ...[...record.diff.matchAll(/`+/g)].map((match) => match[0].length),
148 );
149 const fence = "`".repeat(Math.max(3, longestRun + 1));
150 const body = record.diff
151 ? `${record.text}\n\n${fence}${record.fenceLanguage ?? "diff"}\n${record.diff}\n${fence}`
152 : record.text;
153 return `<review_comment ${attributes}>\n${body}\n</review_comment>`;