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

runtime.ts

259 lines8.9 KB

1import ghosttyWasmUrl from "./vendor/ghostty-vt.wasm?url";
2import ghosttyWritePtyWasmUrl from "./vendor/ghostty-write-pty.wasm?url&no-inline";
3​
4type WasmFunction = (...args: Array<number | bigint>) => number;
5​
6interface TypeField {
7 readonly offset: number;
8 readonly size: number;
9 readonly type: string;
11​
12interface TypeLayout {
13 readonly kind: "struct" | "union" | "enum";
14 readonly size: number;
15 readonly align: number;
16 readonly fields: Readonly<Record<string, TypeField>>;
18​
19type TypeLayouts = Readonly<Record<string, TypeLayout>>;
20​
21const TERMINAL_OPT_USERDATA = 1;
22const TERMINAL_OPT_WRITE_PTY = 2;
23​
24const textDecoder = new TextDecoder();
25​
26export class GhosttyRuntime {
27 readonly memory: WebAssembly.Memory;
28 readonly layouts: TypeLayouts;
29 private readonly exports: WebAssembly.Exports;
30 private memoryView: DataView;
31 private memoryU8: Uint8Array;
32 private readonly ptyWriters = new Map<number, (data: string) => void>();
33 private nextPtyWriterId = 1;
34 private writePtyFunctionIndex = 0;
35​
36 private constructor(instance: WebAssembly.Instance) {
37 this.exports = instance.exports;
38 const memory = instance.exports.memory;
39 if (!(memory instanceof WebAssembly.Memory)) {
40 throw new Error("libghostty-vt did not export WebAssembly memory");
41 }
42 this.memory = memory;
43 this.memoryView = new DataView(memory.buffer);
44 this.memoryU8 = new Uint8Array(memory.buffer);
45 const jsonPointer = this.call("ghostty_type_json");
46 const bytes = new Uint8Array(memory.buffer);
47 let end = jsonPointer;
48 while (end < bytes.length && bytes[end] !== 0) end += 1;
49 const schema = JSON.parse(textDecoder.decode(bytes.subarray(jsonPointer, end))) as {
50 readonly types: TypeLayouts;
51 };
52 this.layouts = schema.types;
53 }
54​
55 static async load(): Promise<GhosttyRuntime> {
56 const response = await fetch(ghosttyWasmUrl);
57 if (!response.ok) {
58 throw new Error(`Unable to load libghostty-vt (${response.status})`);
59 }
60 let instance: WebAssembly.Instance | undefined;
61 const imports = {
62 env: {
63 log: (pointer: number, length: number) => {
64 if (!instance) return;
65 const memory = instance.exports.memory;
66 if (!(memory instanceof WebAssembly.Memory)) return;
67 const message = textDecoder.decode(new Uint8Array(memory.buffer, pointer, length));
68 console.debug("[libghostty-vt]", message);
69 },
70 },
71 };
72 const result = await WebAssembly.instantiate(await response.arrayBuffer(), imports);
73 instance = result.instance;
74 const runtime = new GhosttyRuntime(result.instance);
75 await runtime.installWritePtyTrampoline();
76 return runtime;
77 }
78​
79 call(name: string, ...args: Array<number | bigint>): number {
80 return this.fn(name)(...args);
81 }
82​
83 fn(name: string): WasmFunction {
84 const fn = this.exports[name];
85 if (typeof fn !== "function") {
86 throw new Error(`libghostty-vt export is unavailable: ${name}`);
87 }
88 return fn as WasmFunction;
89 }
90​
91 layout(name: string): TypeLayout {
92 const layout = this.layouts[name];
93 if (!layout) throw new Error(`libghostty-vt type layout is unavailable: ${name}`);
94 return layout;
95 }
96​
97 alloc(size: number): number {
98 const pointer = this.call("ghostty_wasm_alloc", size);
99 if (pointer === 0) throw new Error(`libghostty-vt failed to allocate ${size} bytes`);
100 new Uint8Array(this.memory.buffer, pointer, size).fill(0);
101 return pointer;
102 }
103​
104 free(pointer: number, size: number): void {
105 if (pointer !== 0) this.call("ghostty_wasm_free", pointer, size);
106 }
107​
108 allocOpaque(): number {
109 const pointer = this.call("ghostty_wasm_alloc_opaque");
110 if (pointer === 0) throw new Error("libghostty-vt failed to allocate an opaque pointer");
111 // Zero before *_new so partial-initialization cleanup cannot free a garbage pointer.
112 new DataView(this.memory.buffer).setUint32(pointer, 0, true);
113 return pointer;
114 }
115​
116 freeOpaque(pointer: number): void {
117 if (pointer !== 0) this.call("ghostty_wasm_free_opaque", pointer);
118 }
119​
120 readPointer(slot: number): number {
121 return this.memoryDataView().getUint32(slot, true);
122 }
123​
124 attachPtyWriter(terminal: number, writer: (data: string) => void): number {
125 if (this.writePtyFunctionIndex === 0) {
126 throw new Error("libghostty-vt PTY callback trampoline is unavailable");
127 }
128 const id = this.nextPtyWriterId++;
129 this.ptyWriters.set(id, writer);
130 this.call("ghostty_terminal_set", terminal, TERMINAL_OPT_USERDATA, id);
131 this.call("ghostty_terminal_set", terminal, TERMINAL_OPT_WRITE_PTY, this.writePtyFunctionIndex);
132 return id;
133 }
134​
135 detachPtyWriter(terminal: number, id: number): void {
136 this.call("ghostty_terminal_set", terminal, TERMINAL_OPT_WRITE_PTY, 0);
137 this.call("ghostty_terminal_set", terminal, TERMINAL_OPT_USERDATA, 0);
138 this.ptyWriters.delete(id);
139 }
140​
141 view(pointer: number, size?: number): DataView {
142 return new DataView(this.memoryDataView().buffer, pointer, size);
143 }
144​
145 bytes(pointer: number, size: number): Uint8Array {
146 return new Uint8Array(this.memoryDataView().buffer, pointer, size);
147 }
148​
149 memoryDataView(): DataView {
150 this.refreshMemoryViews();
151 return this.memoryView;
152 }
153​
154 memoryBytes(): Uint8Array {
155 this.refreshMemoryViews();
156 return this.memoryU8;
157 }
158​
159 private refreshMemoryViews(): void {
160 // Growing memory detaches the old buffer. Reading `memory.buffer` costs far more than this check.
161 if (this.memoryU8.byteLength === 0) {
162 this.memoryView = new DataView(this.memory.buffer);
163 this.memoryU8 = new Uint8Array(this.memory.buffer);
164 }
165 }
166​
167 // Enum-typed fields name their enum; every libghostty-vt enum is a 32-bit integer.
168 private scalarType(structName: string, fieldName: string): { offset: number; type: string } {
169 const field = this.layout(structName).fields[fieldName];
170 if (!field) throw new Error(`libghostty-vt field is unavailable: ${structName}.${fieldName}`);
171 const type = this.layouts[field.type]?.kind === "enum" ? "u32" : field.type;
172 return { offset: field.offset, type };
173 }
174​
175 setField(pointer: number, structName: string, fieldName: string, value: number): void {
176 const field = this.scalarType(structName, fieldName);
177 const view = this.memoryDataView();
178 const offset = pointer + field.offset;
179 switch (field.type) {
180 case "bool":
181 case "u8":
182 view.setUint8(offset, value);
183 return;
184 case "u16":
185 view.setUint16(offset, value, true);
186 return;
187 case "i32":
188 view.setInt32(offset, value, true);
189 return;
190 case "u32":
191 case "enum":
192 view.setUint32(offset, value, true);
193 return;
194 case "u64":
195 view.setBigUint64(offset, BigInt(value), true);
196 return;
197 default:
198 throw new Error(`Unsupported libghostty-vt field type: ${field.type}`);
199 }
200 }
201​
202 readField(pointer: number, structName: string, fieldName: string): number {
203 const field = this.scalarType(structName, fieldName);
204 const view = this.memoryDataView();
205 const offset = pointer + field.offset;
206 switch (field.type) {
207 case "bool":
208 case "u8":
209 return view.getUint8(offset);
210 case "u16":
211 return view.getUint16(offset, true);
212 case "i32":
213 return view.getInt32(offset, true);
214 case "u32":
215 case "enum":
216 return view.getUint32(offset, true);
217 case "u64":
218 return Number(view.getBigUint64(offset, true));
219 default:
220 throw new Error(`Unsupported libghostty-vt field type: ${field.type}`);
221 }
222 }
223​
224 private async installWritePtyTrampoline(): Promise<void> {
225 const response = await fetch(ghosttyWritePtyWasmUrl);
226 if (!response.ok) {
227 throw new Error(`Unable to load the libghostty-vt PTY trampoline (${response.status})`);
228 }
229 const result = await WebAssembly.instantiate(await response.arrayBuffer(), {
230 env: {
231 t3_write_pty: (_terminal: number, userdata: number, pointer: number, length: number) => {
232 const writer = this.ptyWriters.get(userdata);
233 if (!writer || length === 0) return;
234 writer(textDecoder.decode(new Uint8Array(this.memory.buffer, pointer, length)));
235 },
236 },
237 });
238 const trampoline = result.instance.exports.ghostty_write_pty;
239 const table = this.exports.__indirect_function_table;
240 if (typeof trampoline !== "function" || !(table instanceof WebAssembly.Table)) {
241 throw new Error("libghostty-vt did not expose its callback table");
242 }
243 const index = table.length;
244 // WebKit grow(1, fn) stores broken type info and traps on call_indirect; table.set canonicalizes it.
245 table.grow(1);
246 table.set(index, trampoline);
247 this.writePtyFunctionIndex = index;
248 }
250​
251let runtimePromise: Promise<GhosttyRuntime> | null = null;
252​
253export function loadGhosttyRuntime(): Promise<GhosttyRuntime> {
254 runtimePromise ??= GhosttyRuntime.load().catch((error) => {
255 runtimePromise = null;
256 throw error;
257 });
258 return runtimePromise;