@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 443 lines 16.3 KB
Raw
1 import { promises as fs } from "node:fs";
2 import type { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "node:http";
3 import path from "node:path";
4 import { fileURLToPath } from "node:url";
5 import type { Plugin, ResolvedConfig, ViteDevServer } from "vite";
6 import { annotate, applyEdit, ATTR, inlineSource, strip, writeInline } from "./source.ts";
7 import { CopyEditError, type TextEdit } from "./text.ts";
8
9 export { CopyEditError, applyRuns, htmlDialect, normalize } from "./text.ts";
10 export type { Dialect, EscapeContext, Run, RunKind, TextEdit, TextToken } from "./text.ts";
11 export { markdownDialect, markdownRuns } from "./markdown.ts";
12 export type { Atomic, MarkdownOptions } from "./markdown.ts";
13 export { MARKDOWN_FILE_SCHEME, markdownBlocks, markdownFiles } from "./markdown-files.ts";
14 export type { MarkdownFilesOptions } from "./markdown-files.ts";
15
16 const CLIENT_ID = "virtual:copy-editor/client";
17 const CONFIG_ID = "virtual:copy-editor/config";
18 const RESOLVED_CONFIG_ID = `\0${CONFIG_ID}`;
19 const SAVE_ENDPOINT = "/__copy-editor/save";
20 const SOURCE_ENDPOINT = "/__copy-editor/source";
21 /** Sent once a handler's follow-up work settles, so previews can refresh. */
22 const REFRESH_EVENT = "copy-editor:refresh";
23 /** Time for watchers (e.g. a content layer) to pick up regenerated files. */
24 const REFRESH_DELAY_MS = 1500;
25 const CLIENT_FILE = fileURLToPath(new URL("./client.ts", import.meta.url));
26
27 /** How long after a save to swallow the full-page reload it triggers. */
28 const RELOAD_SUPPRESS_MS = 1500;
29
30 export interface CopyEditContext {
31 /** The Vite project root. */
32 root: string;
33 logger: ResolvedConfig["logger"];
34 /**
35 * Swallows full-page reloads until `work` settles (plus a short grace
36 * period), for follow-up work such as regenerating derived files whose
37 * content the page already shows.
38 */
39 suppressReloads(work: Promise<unknown>): void;
40 }
41
42 export interface SaveResult {
43 /** Display path of the file that was written. */
44 file: string;
45 changed: boolean;
46 /**
47 * The edit changed the page's structure (e.g. added a section), so other
48 * editable ids on the page are stale: reload once follow-up work settles.
49 */
50 reload?: boolean;
51 }
52
53 /**
54 * Saves edits for ids of the form `<scheme>:<rest>`. Throw a
55 * {@link CopyEditError} to reject an edit with a message for the browser.
56 */
57 export interface CopyEditHandler {
58 /** Saves an inline text edit to a `data-copy` element. */
59 edit?(edit: TextEdit & { id: string }, context: CopyEditContext): Promise<SaveResult>;
60 /** Returns the markdown behind a `data-copy-format="markdown"` section. */
61 readSource?(id: string, context: CopyEditContext): Promise<string>;
62 /**
63 * Replaces the markdown behind a section. `base` is the source the editor
64 * started from; reject with a 409 {@link CopyEditError} if it's stale.
65 */
66 writeSource?(
67 edit: { id: string; source: string; base: string },
68 context: CopyEditContext,
69 ): Promise<SaveResult>;
70 }
71
72 /** Elements a markdown preview can style, keyed like CSS selectors. */
73 export type MarkdownElement =
74 | "p"
75 | "h1"
76 | "h2"
77 | "h3"
78 | "h4"
79 | "h5"
80 | "h6"
81 | "a"
82 | "strong"
83 | "em"
84 | "del"
85 /** Inline code (not inside a code block). */
86 | "code"
87 /** Code blocks. */
88 | "pre"
89 | "ul"
90 | "ol"
91 | "li"
92 | "blockquote"
93 | "hr"
94 | "img"
95 | "table"
96 | "th"
97 | "td";
98
99 /**
100 * How a markdown section renders its preview after an edit, until the page's
101 * own renderer catches up. A section picks a style with
102 * `data-copy-style="<name>"`.
103 */
104 export interface MarkdownStyle {
105 /** Attributes set on rendered elements; `class` values are appended. */
106 elements?: Partial<Record<MarkdownElement, Record<string, string>>>;
107 /** CSS added to the page in dev (scope it with `[data-copy-style="<name>"]`). */
108 css?: string;
109 /**
110 * Regex rewrites applied to the markdown before previewing, for syntax the
111 * page's renderer understands but plain markdown doesn't.
112 */
113 rewrite?: Array<[pattern: string, replacement: string]>;
114 }
115
116 export interface CopyEditorOptions {
117 /**
118 * Source files that may contain `data-copy` elements.
119 * @default /\.(astro|html|jsx|tsx|vue|svelte)$/
120 */
121 include?: RegExp;
122 /**
123 * Handlers for copy that isn't a `data-copy` element in a template, keyed
124 * by id scheme. Content rendered without Vite transforms (markdown, a CMS)
125 * marks its element with a trailing `<!--copy:<scheme>:<rest>-->` comment,
126 * and edits to it are saved by `handlers[<scheme>]`.
127 */
128 handlers?: Record<string, CopyEditHandler>;
129 /** Named preview styles for markdown sections. */
130 markdownStyles?: Record<string, MarkdownStyle>;
131 /**
132 * Which dev-server pages load the editor, by URL pathname. Pages it
133 * rejects render normally with nothing editable.
134 * @default every page
135 */
136 pages?: (pathname: string) => boolean;
137 }
138
139 /**
140 * Inline copy editing for any Vite app.
141 *
142 * Mark a hardcoded piece of copy with a bare attribute:
143 *
144 * ```html
145 * <h1 data-copy>Reach for the better primitives.</h1>
146 * ```
147 *
148 * - **Dev** (`vite serve`): every `data-copy` element is editable in the
149 * browser. Each edit is written back to the source file and flows through
150 * the normal HMR pipeline.
151 * - **Build**: the attribute is stripped and no editor code ships.
152 *
153 * The element must contain only text and plain HTML tags (no expressions or
154 * components). Register the plugin before framework plugins so it sees the
155 * raw source. Copy from other sources (markdown, generated docs) plugs in
156 * through {@link CopyEditorOptions.handlers}.
157 */
158 export const copyEditor = (options: CopyEditorOptions = {}): Plugin => {
159 const include = options.include ?? /\.(astro|html|jsx|tsx|vue|svelte)$/;
160 let config: ResolvedConfig;
161 let dev = false;
162
163 const fileOf = (id: string) => id.split("?", 1)[0];
164 const matches = (id: string) =>
165 !id.startsWith("\0") &&
166 !id.includes("/node_modules/") &&
167 include.test(fileOf(id)) &&
168 !/[?&](raw|url)\b/.test(id);
169 const relative = (file: string) => path.relative(config.root, file).split(path.sep).join("/");
170
171 const rewrite = (code: string, file: string) =>
172 dev ? annotate(code, relative(file)) : strip(code);
173
174 return {
175 name: "copy-editor",
176 enforce: "pre",
177
178 configResolved(resolved) {
179 config = resolved;
180 dev = resolved.command === "serve";
181 },
182
183 resolveId(id) {
184 if (dev && id === CLIENT_ID) return CLIENT_FILE;
185 if (dev && id === CONFIG_ID) return RESOLVED_CONFIG_ID;
186 },
187
188 load(id) {
189 if (id === RESOLVED_CONFIG_ID) {
190 return `export default ${JSON.stringify({ styles: options.markdownStyles ?? {} })};`;
191 }
192 },
193
194 transform(code, id) {
195 if (!code.includes(ATTR) || !matches(id)) return;
196 return { code: rewrite(code, fileOf(id)), map: null };
197 },
198
199 transformIndexHtml: {
200 order: "pre",
201 handler(html, ctx) {
202 if (!html.includes(ATTR)) return;
203 return rewrite(html, ctx.filename);
204 },
205 },
206
207 configureServer(server) {
208 let suppressReloadUntil = 0;
209 let pendingWork = 0;
210 suppressFullReloads(server, () => pendingWork > 0 || Date.now() < suppressReloadUntil);
211 const context: CopyEditContext = {
212 root: config.root,
213 logger: config.logger,
214 suppressReloads(work) {
215 pendingWork++;
216 work
217 .catch(() => {})
218 .finally(() => {
219 pendingWork--;
220 suppressReloadUntil = Math.max(
221 suppressReloadUntil,
222 Date.now() + REFRESH_DELAY_MS + RELOAD_SUPPRESS_MS,
223 );
224 // One refresh once everything saved so far has been processed.
225 if (pendingWork > 0) return;
226 setTimeout(() => {
227 if (pendingWork === 0) {
228 server.ws.send({ type: "custom", event: REFRESH_EVENT });
229 }
230 }, REFRESH_DELAY_MS);
231 });
232 },
233 };
234 const handlerFor = (id: string) => {
235 const scheme = /^([a-z][\w-]*):/.exec(id)?.[1];
236 return scheme ? options.handlers?.[scheme] : undefined;
237 };
238 const respond = (res: ServerResponse, work: () => Promise<object>) =>
239 work().then(
240 (body) => {
241 res.statusCode = 200;
242 res.setHeader("content-type", "application/json");
243 res.end(JSON.stringify(body));
244 },
245 (error: unknown) => {
246 const status = error instanceof CopyEditError ? error.status : 500;
247 const message = error instanceof Error ? error.message : String(error);
248 config.logger.warn(`copy-editor: ${message}`, { timestamp: true });
249 res.statusCode = status;
250 res.setHeader("content-type", "application/json");
251 res.end(JSON.stringify({ error: message }));
252 },
253 );
254 const logSave = (result: SaveResult) => {
255 if (result.changed) {
256 config.logger.info(`copy-editor: saved ${result.file}`, {
257 timestamp: true,
258 });
259 }
260 return result;
261 };
262
263 /** Resolves a template element id (`<file>#<n>`) to its file. */
264 const templateElement = (id: string) => {
265 const hash = id.lastIndexOf("#");
266 const rel = id.slice(0, hash);
267 const index = Number(id.slice(hash + 1));
268 const file = path.resolve(config.root, rel);
269 if (
270 hash === -1 ||
271 !Number.isInteger(index) ||
272 !file.startsWith(path.resolve(config.root) + path.sep) ||
273 !matches(file)
274 ) {
275 throw new CopyEditError(`Invalid copy id: ${id}`);
276 }
277 return { rel, index, file };
278 };
279
280 server.middlewares.use(SOURCE_ENDPOINT, (req, res) =>
281 respond(res, async () => {
282 if (req.method === "GET") {
283 const id = new URL(req.url ?? "", "http://x").searchParams.get("id") ?? "";
284 const handler = handlerFor(id);
285 if (!handler) {
286 const { index, file } = templateElement(id);
287 const code = await fs.readFile(file, "utf8");
288 return { source: inlineSource(code, index).markdown };
289 }
290 if (!handler.readSource) {
291 throw new CopyEditError(`No markdown source for ${id}`);
292 }
293 return { source: await handler.readSource(id, context) };
294 }
295 if (req.method !== "POST") throw new CopyEditError("GET or POST only", 405);
296 const edit = JSON.parse(await readBody(req)) as {
297 id: string;
298 source: string;
299 base: string;
300 };
301 const handler = handlerFor(edit.id);
302 if (!handler) {
303 const { rel, index, file } = templateElement(edit.id);
304 const code = await fs.readFile(file, "utf8");
305 const next = writeInline(code, index, {
306 markdown: edit.source,
307 base: edit.base,
308 });
309 if (next === code) return { file: rel, changed: false };
310 // The page shows the preview; skip the full reload it triggers.
311 suppressReloadUntil = Date.now() + RELOAD_SUPPRESS_MS;
312 await fs.writeFile(file, next);
313 return logSave({ file: rel, changed: true });
314 }
315 if (!handler.writeSource) {
316 throw new CopyEditError(`No markdown source for ${edit.id}`);
317 }
318 suppressReloadUntil = Date.now() + RELOAD_SUPPRESS_MS;
319 return logSave(await handler.writeSource(edit, context));
320 }),
321 );
322
323 const clientTag = `<script type="module" src="${config.base}@id/${CLIENT_ID}"></script>`;
324 server.middlewares.use((req, res, next) => {
325 const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
326 if (!options.pages || options.pages(pathname)) injectIntoHtml(res, clientTag);
327 next();
328 });
329
330 server.middlewares.use(SAVE_ENDPOINT, async (req, res) => {
331 const reply = (status: number, body: object) => {
332 res.statusCode = status;
333 res.setHeader("content-type", "application/json");
334 res.end(JSON.stringify(body));
335 };
336 if (req.method !== "POST") return reply(405, { error: "POST only" });
337 try {
338 const { id, before, after } = JSON.parse(await readBody(req)) as {
339 id: string;
340 before: string[];
341 after: string[];
342 };
343 const handler = handlerFor(id);
344 if (handler) {
345 if (!handler.edit) throw new CopyEditError(`${id} can't be edited inline`);
346 suppressReloadUntil = Date.now() + RELOAD_SUPPRESS_MS;
347 return reply(200, logSave(await handler.edit({ id, before, after }, context)));
348 }
349 const hash = id.lastIndexOf("#");
350 const rel = id.slice(0, hash);
351 const index = Number(id.slice(hash + 1));
352 const file = path.resolve(config.root, rel);
353 if (
354 hash === -1 ||
355 !Number.isInteger(index) ||
356 !file.startsWith(path.resolve(config.root) + path.sep) ||
357 !matches(file)
358 ) {
359 throw new CopyEditError(`Invalid copy id: ${id}`);
360 }
361 const code = await fs.readFile(file, "utf8");
362 const next = applyEdit(code, { index, before, after });
363 if (next !== code) {
364 // The DOM already shows the edit, so a full-page reload would only
365 // cost the editor their place. Module-level HMR still applies.
366 suppressReloadUntil = Date.now() + RELOAD_SUPPRESS_MS;
367 await fs.writeFile(file, next);
368 config.logger.info(`copy-editor: saved ${rel}`, {
369 timestamp: true,
370 });
371 }
372 reply(200, { file: rel, changed: next !== code });
373 } catch (error) {
374 const status = error instanceof CopyEditError ? error.status : 500;
375 const message = error instanceof Error ? error.message : String(error);
376 config.logger.warn(`copy-editor: ${message}`, { timestamp: true });
377 reply(status, { error: message });
378 }
379 });
380 },
381 };
382 };
383
384 const readBody = (req: IncomingMessage) =>
385 new Promise<string>((resolve, reject) => {
386 let body = "";
387 req.on("data", (chunk) => (body += chunk));
388 req.on("end", () => resolve(body));
389 req.on("error", reject);
390 });
391
392 /**
393 * Appends `tag` to any HTML response, whichever middleware produces it
394 * (Vite's index.html handler or a framework's SSR handler).
395 */
396 const injectIntoHtml = (res: ServerResponse, tag: string) => {
397 let html: boolean | undefined;
398 const isHtml = () => (html ??= String(res.getHeader("content-type") ?? "").includes("text/html"));
399
400 const writeHead = res.writeHead.bind(res);
401 res.writeHead = function (this: ServerResponse, ...args: unknown[]) {
402 const headers = args.find(
403 (a): a is OutgoingHttpHeaders => typeof a === "object" && a !== null && !Array.isArray(a),
404 );
405 if (headers) {
406 for (const key of Object.keys(headers)) {
407 const lower = key.toLowerCase();
408 if (lower === "content-type") html = String(headers[key]).includes("text/html");
409 }
410 if (isHtml()) {
411 for (const key of Object.keys(headers)) {
412 if (key.toLowerCase() === "content-length") delete headers[key];
413 }
414 }
415 }
416 if (isHtml()) res.removeHeader("content-length");
417 return (writeHead as (...a: unknown[]) => ServerResponse).apply(this, args);
418 } as typeof res.writeHead;
419
420 const end = res.end.bind(res);
421 res.end = function (this: ServerResponse, ...args: unknown[]) {
422 if (!isHtml()) return (end as (...a: unknown[]) => ServerResponse).apply(this, args);
423 if (!res.headersSent) res.removeHeader("content-length");
424 const cb = typeof args[args.length - 1] === "function" ? (args.pop() as () => void) : undefined;
425 const [chunk, encoding] = args as [unknown, BufferEncoding | undefined];
426 if (chunk != null) res.write(chunk, encoding as BufferEncoding);
427 res.write(tag);
428 return (end as (...a: unknown[]) => ServerResponse).call(this, cb);
429 } as typeof res.end;
430 };
431
432 /** Drops `full-reload` HMR messages while `active()` is true. */
433 const suppressFullReloads = (server: ViteDevServer, active: () => boolean) => {
434 const channels = new Set([server.ws, server.environments.client.hot]);
435 for (const channel of channels) {
436 const send = channel.send.bind(channel) as (...args: unknown[]) => void;
437 channel.send = ((...args: unknown[]) => {
438 const payload = args[0] as { type?: string } | undefined;
439 if (active() && payload?.type === "full-reload") return;
440 send(...args);
441 }) as typeof channel.send;
442 }
443 };