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

main
ts 58 lines 1.95 KB
Raw
1 import {
2 COMPOSER_CONTEXT_CLIPBOARD_MIME,
3 ComposerContextClipboardFragment,
4 } from "@t3tools/contracts";
5 import * as Option from "effect/Option";
6 import * as Schema from "effect/Schema";
7
8 export { COMPOSER_CONTEXT_CLIPBOARD_MIME };
9
10 const MAX_FRAGMENT_CHARS = 16_000_000;
11 const decodeFragment = Schema.decodeUnknownOption(ComposerContextClipboardFragment);
12
13 export function encodeComposerContextFragment(
14 fragment: ComposerContextClipboardFragment,
15 ): string | null {
16 const encoded = JSON.stringify(fragment);
17 return encoded.length <= MAX_FRAGMENT_CHARS ? encoded : null;
18 }
19
20 const HTML_WRAPPER_SLACK_CHARS = 4096;
21
22 export function encodeComposerContextClipboardHtml(
23 text: string,
24 fragment: string,
25 html?: string,
26 ): string {
27 if (html !== undefined)
28 return `<div data-t3-context-fragment="${encodeURIComponent(fragment)}">${html}</div>`;
29 const escaped = text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
30 return `<pre data-t3-context-fragment="${encodeURIComponent(fragment)}">${escaped}</pre>`;
31 }
32
33 export function decodeComposerContextClipboardHtml(
34 html: string | null | undefined,
35 ): ComposerContextClipboardFragment | null {
36 // Percent encoding can expand each UTF-16 code unit to nine characters.
37 if (!html || html.length > MAX_FRAGMENT_CHARS * 9 + HTML_WRAPPER_SLACK_CHARS) return null;
38 // `encodeURIComponent` leaves `'` as is, so each quote style must end only at its own quote.
39 const match = /data-t3-context-fragment=(?:"([^"]+)"|'([^']+)')/.exec(html);
40 const encoded = match?.[1] ?? match?.[2];
41 if (!encoded) return null;
42 try {
43 return decodeComposerContextFragment(decodeURIComponent(encoded));
44 } catch {
45 return null;
46 }
47 }
48
49 export function decodeComposerContextFragment(
50 raw: string | null | undefined,
51 ): ComposerContextClipboardFragment | null {
52 if (!raw || raw.length > MAX_FRAGMENT_CHARS) return null;
53 try {
54 return Option.getOrNull(decodeFragment(JSON.parse(raw)));
55 } catch {
56 return null;
57 }
58 }