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

composerTrigger.ts

185 lines6.2 KB

1import { parseMarkdownFileLink } from "./markdownLinks.ts";
2​
3export type ComposerTriggerKind = "path" | "pull-request" | "slash-command" | "skill";
4export type ComposerSlashCommand = "model" | "plan" | "default";
5​
6export interface ComposerTrigger {
7 kind: ComposerTriggerKind;
8 query: string;
9 rangeStart: number;
10 rangeEnd: number;
12​
13function composerFileLinkBasename(path: string): string {
14 const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
15 return separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
17​
18// Numeric bracket entities avoid TeX `\[…\]` math delimiters; inline formatting, HTML and autolink starts stay escaped.
19function escapeMarkdownLinkLabel(label: string): string {
20 return label.replace(/[\\[\]*_~&`<]/g, (char) =>
21 char === "[" ? "&#91;" : char === "]" ? "&#93;" : `\\${char}`,
22 );
24​
25function encodeMarkdownLinkDestination(path: string): string {
26 return encodeURI(path)
27 .replaceAll("(", "%28")
28 .replaceAll(")", "%29")
29 .replaceAll("&", "%26")
30 .replaceAll("#", "%23")
31 .replaceAll("?", "%3F")
32 .replaceAll("\\", "%5C");
34​
35const DRIVE_OR_ROOTED_PATH_PATTERN = /^(?:[a-z]:[\\/]|[\\/])/i;
36const URI_SCHEME_PREFIX_PATTERN = /^[a-z][a-z\d+.-]*:/i;
37​
38// Relative paths need `./` when the parser rejects them or reads their prefix as a URI scheme.
39function needsDotSlashPrefix(path: string): boolean {
40 return (
41 path.length > 0 &&
42 !DRIVE_OR_ROOTED_PATH_PATTERN.test(path) &&
43 (URI_SCHEME_PREFIX_PATTERN.test(path) ||
44 !parseMarkdownFileLink(encodeMarkdownLinkDestination(path)))
45 );
47​
48export function serializeComposerFileLink(path: string): string {
49 const label = escapeMarkdownLinkLabel(composerFileLinkBasename(path));
50 const destination = encodeMarkdownLinkDestination(path);
51 return `[${label}](${needsDotSlashPrefix(path) ? `./${destination}` : destination})`;
53​
54/** The file a composer link names. Drops only the `./` serializeComposerFileLink adds, not one the author wrote. */
55export function composerFileLinkPath(encodedDestination: string, decodedPath: string): string {
56 if (!encodedDestination.startsWith("./")) return decodedPath;
57 const bare = decodedPath.slice(2);
58 return needsDotSlashPrefix(bare) &&
59 encodeMarkdownLinkDestination(bare) === encodedDestination.slice(2)
60 ? bare
61 : decodedPath;
63​
64function clampCursor(text: string, cursor: number): number {
65 if (!Number.isFinite(cursor)) return text.length;
66 return Math.max(0, Math.min(text.length, Math.floor(cursor)));
68​
69function isWhitespace(char: string): boolean {
70 return /\s/.test(char);
72​
73/** A second slash or backslash makes the whole word a path, even when the caret precedes it. */
74export function isPathWord(
75 text: string,
76 wordStart: number,
77 cursor: number,
78 isWhitespaceChar: (char: string) => boolean,
79): boolean {
80 let wordEnd = cursor;
81 while (wordEnd < text.length && !isWhitespaceChar(text[wordEnd] ?? "")) {
82 wordEnd += 1;
83 }
84 return /[/\\]/.test(text.slice(wordStart + 1, wordEnd));
86​
87/**
88 * `$5`, `€9.99` and `$10k` are money, not skills. Matches the amounts the inline skill
89 * token regexes already refuse to render as skills, plus the punctuation prose puts after
90 * one (`$10k.`, `($5)`).
91 */
92export function isCurrencyAmountQuery(query: string): boolean {
93 return /^\.?[0-9][0-9,._]*(?:[kKmMbBtT]|[eE][0-9]+)?[.,;:!?)]*$/.test(query);
95​
96export function detectComposerPullRequestTrigger(token: string, cursor: number) {
97 if (/^[@\p{Sc}]/u.test(token)) return null;
98 const match = /(?:^|\p{Ps})#([\p{L}\p{N}][\p{L}\p{M}\p{N}_-]*)?$/u.exec(token);
99 if (!match) return null;
100 const query = match[1] ?? "";
101 return {
102 kind: "pull-request" as const,
103 query,
104 rangeStart: cursor - query.length - 1,
105 rangeEnd: cursor,
106 };
108​
109export function detectComposerTrigger(
110 text: string,
111 cursorInput: number,
112 isWhitespaceChar?: (char: string) => boolean,
113): ComposerTrigger | null {
114 const cursor = clampCursor(text, cursorInput);
115 const wsCheck = isWhitespaceChar ?? isWhitespace;
116 let tokenIdx = cursor - 1;
117 while (tokenIdx >= 0 && !wsCheck(text[tokenIdx] ?? "")) {
118 tokenIdx -= 1;
119 }
120 const tokenStart = tokenIdx + 1;
121​
122 const token = text.slice(tokenStart, cursor);
123 if (token.startsWith("/")) {
124 if (isPathWord(text, tokenStart, cursor, wsCheck)) return null;
125 return {
126 kind: "slash-command",
127 query: token.slice(1),
128 rangeStart: tokenStart,
129 rangeEnd: cursor,
130 };
131 }
132 const pullRequestTrigger = detectComposerPullRequestTrigger(token, cursor);
133 if (pullRequestTrigger) return pullRequestTrigger;
134 const skillPrefix = /^\p{Sc}/u.exec(token);
135 if (skillPrefix) {
136 if (isCurrencyAmountQuery(token.slice(skillPrefix[0].length))) return null;
137 return {
138 kind: "skill",
139 query: token.slice(skillPrefix[0].length),
140 rangeStart: tokenStart,
141 rangeEnd: cursor,
142 };
143 }
144 if (!token.startsWith("@")) {
145 return null;
146 }
147​
148 return {
149 kind: "path",
150 query: token.slice(1),
151 rangeStart: tokenStart,
152 rangeEnd: cursor,
153 };
155​
156export function replaceTextRange(
157 text: string,
158 rangeStart: number,
159 rangeEnd: number,
160 replacement: string,
161): { text: string; cursor: number } {
162 const safeStart = Math.max(0, Math.min(text.length, rangeStart));
163 const safeEnd = Math.max(safeStart, Math.min(text.length, rangeEnd));
164 const nextText = `${text.slice(0, safeStart)}${replacement}${text.slice(safeEnd)}`;
165 return { text: nextText, cursor: safeStart + replacement.length };
167​
168/** A message that only invokes a slash command, such as `/context all`, not a path like `/src/a.ts`. */
169export function isSlashCommand(message: {
170 readonly text: string;
171 readonly attachments: ReadonlyArray<unknown>;
172}): boolean {
173 return message.attachments.length === 0 && /^\/[\w:-]+(?:\s|$)/u.test(message.text.trim());
175​
176/** `/clear` as the whole message arms a fresh session instead of sending. */
177export function isClearComposerCommand(text: string): boolean {
178 return /^\/clear\s*$/i.test(text.trim());
180​
181/** `/side [prompt]`, or its alias `/btw [prompt]`, as the whole message. */
182export function parseSideChatCommand(text: string): { prompt: string } | null {
183 const match = /^\/(?:side|btw)(?:\s+([\s\S]*))?$/i.exec(text.trim());
184 return match ? { prompt: match[1]?.trim() ?? "" } : null;