robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

bfredlMerge pull request #40628 from Rawan10101/wasm-runtime-bundlingc1e09659b4

master
10.9 KiB213 linesraw
1<!DOCTYPE html>
2<html>
3<head><meta charset="utf-8"><title>nvim.wasm runtime + persistence test</title></head>
4<body style="font-family: monospace; white-space: pre-wrap">
5<h3>nvim.wasm runtime bundling</h3>
6<button id="persistBtn">Persist now</button>
7<script src="../zig-out/bin/nvim.js"></script>
8<script>
9const log = (msg) => document.body.append(msg + "\n");
10const sleep = (ms) => new Promise(r => setTimeout(r, ms));
11const ok = (label, cond, hint) => label + (cond ? "  OK" : "  FAIL" + (hint ? " " + hint : ""));
12
13// Builds a C-style argv array in wasm memory for _nvim_main
14function makeArgv(M, args) {
15  const ptrs = args.map(s => {
16    const len = M.lengthBytesUTF8(s) + 1, p = M._malloc(len);
17    M.stringToUTF8(s, p, len);
18    return p;
19  });
20  const argv = M._malloc((ptrs.length + 1) * 4);
21  ptrs.forEach((p, i) => M.setValue(argv + i * 4, p, '*'));
22  M.setValue(argv + ptrs.length * 4, 0, '*');
23  return { argc: ptrs.length, argv };
24}
25// Test only helper. Runs the WASM nvim build headlessly with a scripted
26// set of -c commands, by calling its exported _nvim_main directly
27async function runNvimCommands(m, cmds, opts = {}) {
28  const args = ["nvim", "--headless", ...(opts.noPlugin ? ["-u", "NONE"] : []), ...(opts.extraArgs ?? [])];
29  cmds.forEach(c => args.push("-c", c));
30  const { argc, argv } = makeArgv(m, args);
31  const ret = m._nvim_main(argc, argv);
32  await sleep(opts.settleMs ?? 300);
33  return ret;
34}
35
36async function waitForFile(m, path, timeoutMs = 2000, intervalMs = 50) {
37  const start = Date.now();
38  while (Date.now() - start < timeoutMs) {
39    try { return m.FS.readFile(path, { encoding: 'utf8' }); }
40    catch (e) { await sleep(intervalMs); }
41  }
42  return m.FS.readFile(path, { encoding: 'utf8' });
43}
44
45async function freshNvim() {
46  const m = await createNvim({
47    locateFile: (p, prefix) => p.endsWith('.data') ? '/zig-out/bin/nvim.data' : prefix + p,
48    noInitialRun: true,
49    print: t => log("[stdout] " + t),
50    printErr: t => log("[stderr] " + t),
51    preRun: [m => {
52      m.ENV.TERM = "dumb"; m.ENV.HOME = "/home/user"; m.ENV.VIMRUNTIME = "/runtime";
53      try { m.FS.mkdir('/tmp'); } catch (e) {}
54      m.FS.mkdir('/home/user');
55      m.FS.mkdir('/home/user/.config');
56      m.FS.mkdir('/home/user/.local');
57      m.FS.mkdir('/home/user/.local/share');
58      m.FS.mount(m.IDBFS, {}, '/home/user/.config');
59      m.FS.mount(m.IDBFS, {}, '/home/user/.local/share');
60    }],
61  });
62  await new Promise((res, rej) => m.FS.syncfs(true, e => e ? rej(e) : res())); // restore from IndexedDB
63
64  try { m.FS.mkdir('/home/user/.config/nvim'); } catch (e) {}
65  try { m.FS.mkdir('/home/user/.local/share/nvim'); } catch (e) {}
66  try { m.FS.mkdir('/runtime/parser'); } catch (e) {}
67  ['lua', 'c', 'vim', 'vimdoc', 'query', 'markdown', 'markdown_inline'].forEach(p => {
68    try { m.FS.writeFile(`/runtime/parser/${p}.so`, ''); } catch (e) {}
69  });
70  return m;
71}
72
73const tests = [
74  ["filetype detection", ["e test.lua", "call writefile([&filetype], '/tmp/ft.txt')", "q"], "/tmp/ft.txt", { noPlugin: false },
75    ft => [ok(`filetype: '${ft}'`, ft === 'lua', "expected 'lua'")]],
76
77  [":help (no args)", ["help", "redir! > /tmp/help.txt", "silent! echo bufname('%').'---'.line('$')", "redir END", "qa!"], "/tmp/help.txt", {},
78    raw => { const [b, n] = raw.split('---'); return [
79      ok(`help buffer: '${b}'`, b?.includes('help.txt'), "expected 'help.txt'"),
80      ok(`help.txt lines: '${n}'`, parseInt(n) > 0, "expected > 0")]; }],
81
82  [":help <topic>", ["help autocmd", "redir! > /tmp/help_topic.txt", "silent! echo bufname('%').'---'.line('.')", "redir END", "qa!"], "/tmp/help_topic.txt", {},
83    raw => { const [b, n] = raw.split('---'); return [
84      ok(`help autocmd -> buffer: '${b}'`, b?.includes('autocmd.txt'), "expected 'autocmd.txt'"),
85      ok(`help autocmd -> line: '${n}'`, parseInt(n) > 1, "(tag unresolved)")]; }],
86
87  [":q smoke test", ["e test.md", "q"], null, {},
88    ret => [`:q returned ${ret}`]],
89
90  [":qa! smoke test", ["e test.md", "sp test2.md", "qa!"], null, {},
91    ret => [`:qa! returned ${ret}`]],
92
93  ["require() builtin", ["lua local ok,mod=pcall(require,'vim.fs'); vim.fn.writefile({tostring(ok),type(mod)}, '/tmp/req_builtin.txt')", "qa!"], "/tmp/req_builtin.txt", {},
94    raw => { const [o, t] = raw.split('\n'); return [ok(`require('vim.fs') -> ok=${o}, type=${t}`, o === 'true' && t === 'table')]; }],
95
96  ["require() user module", ["lua local ok,mod=pcall(require,'mymod'); local msg=ok and mod.greet() or tostring(mod); vim.fn.writefile({tostring(ok),msg}, '/tmp/req_user.txt')", "qa!"], "/tmp/req_user.txt",
97    { setup: m => m.FS.writeFile('/runtime/lua/mymod.lua', "return { greet = function() return 'hi from mymod' end }") },
98    raw => { const [o, msg] = raw.split('\n'); return [ok(`require('mymod') -> ok=${o}, result='${msg}'`, o === 'true' && msg === 'hi from mymod')]; }],
99
100  ["syntax highlighting", ["e /home/user/synhl.lua", "syntax on", "lua local id=vim.fn.synID(1,7,1); vim.fn.writefile({vim.fn.synIDattr(id,'name')}, '/tmp/syn.txt')", "qa!"], "/tmp/syn.txt",
101    { setup: m => m.FS.writeFile('/home/user/synhl.lua', 'local function foo()\n  return 1\nend\n') },
102    name => [ok(`syntax group at 'function': '${name}'`, name.length > 0, "(no group / syntax off)")]],
103
104  ["tree-sitter parsing", ["e /home/user/ts.lua", "lua local ok,r=pcall(function() return vim.treesitter.get_parser(0,'lua'):parse()[1]:root():type() end); vim.fn.writefile({tostring(ok),tostring(r)}, '/tmp/ts.txt')", "qa!"], "/tmp/ts.txt",
105    { setup: m => m.FS.writeFile('/home/user/ts.lua', 'local x = 1\nprint(x)\n') },
106    raw => { const [o, msg] = raw.split('\n'); return [ok(`tree-sitter parse -> ok=${o}, result='${msg}'`, o === 'true', "(see error above)")]; }],
107
108  [":w write test", ["e /home/user/write.txt", "call setline(1, 'hello wasm write test')", "w", "q"], "/home/user/write.txt", {},
109    txt => [ok(`:w result: '${txt}'`, txt === 'hello wasm write test')]],
110
111  [":edit existing file", ["e /home/user/existing.txt", "call writefile([getline(1)], '/tmp/edit.txt')", "q"], "/tmp/edit.txt",
112    { setup: m => m.FS.writeFile('/home/user/existing.txt', 'pre-existing content here') },
113    txt => [ok(`:edit read back: '${txt}'`, txt === 'pre-existing content here')]],
114
115  [":split window", ["e /home/user/split_a.txt", "split /home/user/split_b.txt", "call writefile([winnr('$')], '/tmp/split.txt')", "qa!"], "/tmp/split.txt", {},
116    n => [ok(`window count: '${n}'`, parseInt(n) === 2, "expected 2")]],
117
118  [":set number", ["set number", "call writefile([&number], '/tmp/set.txt')", "qa!"], "/tmp/set.txt", {},
119    n => [ok(`&number = '${n}'`, n === '1', "expected 1")]],
120];
121
122async function runTest([name, cmds, file, opts, check]) {
123  log(name);
124  const m = await freshNvim();
125  try {
126    if (opts.setup) opts.setup(m);
127    const ret = await runNvimCommands(m, cmds, { noPlugin: true, ...opts });
128    const raw = file ? (await waitForFile(m, file)).trim() : ret;
129    check(raw).forEach(log);
130  } catch (e) { log("ERROR in " + name + ": " + e); }
131  return m;
132}
133
134// checks the runtime files bundled into the wasm image are actually there
135async function runtimeSanityCheck() {
136  log("runtime sanity check");
137  const m = await freshNvim();
138  try { log("/runtime contents: " + m.FS.readdir('/runtime').join(', ')); }
139  catch (e) { log("ERROR reading /runtime: " + e); }
140  try {
141    m.FS.writeFile('/home/user/.local/share/nvim/test.txt', 'hello from session ' + Date.now());
142    log("wrote+read dynamic test file: " + m.FS.readFile('/home/user/.local/share/nvim/test.txt', { encoding: 'utf8' }));
143  } catch (e) { log("ERROR writing dynamic test file: " + e); }
144  try { log("/runtime/doc contains " + m.FS.readdir('/runtime/doc').length + " entries"); }
145  catch (e) { log("ERROR reading /runtime/doc: " + e); }
146  try {
147    const n = m.FS.readFile('/runtime/doc/tags', { encoding: 'utf8' }).split('\n').filter(Boolean).length;
148    log(ok(`doc/tags found, ${n} lines`, n > 0, "(empty)"));
149  } catch (e) { log("ERROR: /runtime/doc/tags missing: " + e + "  FAIL"); }
150  return m;
151}
152
153// verifies tree-sitter
154async function treesitterHighlightCapturesTest() {
155  log("tree-sitter highlight captures test");
156  const m1 = await freshNvim();
157  try { log("/runtime/queries: " + m1.FS.readdir('/runtime/queries').join(', ')); }
158  catch (e) { log("ERROR reading /runtime/queries: " + e); }
159  try { log("/runtime/queries/lua: " + m1.FS.readdir('/runtime/queries/lua').join(', ')); }
160  catch (e) { log("ERROR reading /runtime/queries/lua: " + e + "  <-- likely root cause if missing"); }
161
162  try {
163    m1.FS.writeFile('/home/user/ts_hl.lua', 'local x = 1\nprint(x)\n');
164    await runNvimCommands(m1, [
165      "e /home/user/ts_hl.lua",
166      "lua local qok,q=pcall(vim.treesitter.query.get,'lua','highlights'); vim.fn.writefile({tostring(qok),tostring(q~=nil)}, '/tmp/query_check.txt')",
167      "qa!",
168    ], { noPlugin: true });
169    log("query.get('lua','highlights') -> " + (await waitForFile(m1, '/tmp/query_check.txt')).trim().replace('\n', ', loaded='));
170  } catch (e) { log("ERROR checking highlights query: " + e); }
171
172  const m2 = await freshNvim();
173  try {
174    m2.FS.writeFile('/home/user/ts_hl2.lua', 'local x = 1\nprint(x)\n');
175    await runNvimCommands(m2, [
176      "e /home/user/ts_hl2.lua",
177      "lua " +
178      "local sok,serr=pcall(vim.treesitter.start,0,'lua'); " +
179      "local hlok,hlmod=pcall(require,'vim.treesitter.highlighter'); " +
180      "local active=hlok and (hlmod.active[vim.api.nvim_get_current_buf()]~=nil); " +
181      "local pok,perr=pcall(function() vim.treesitter.get_parser(0,'lua'):parse() end); " +
182      "local cok,caps=pcall(vim.treesitter.get_captures_at_pos,0,0,6); " +
183      "local names='none'; " +
184      "if cok and type(caps)=='table' and #caps>0 then " +
185      "  local l={}; for _,c in ipairs(caps) do table.insert(l,c.capture) end; names=table.concat(l,','); end; " +
186      "vim.fn.writefile({tostring(sok),tostring(serr),tostring(active),tostring(pok),tostring(perr),tostring(cok),names}, '/tmp/ts_hl.txt')",
187      "qa!",
188    ], { noPlugin: true });
189
190    const [sok, serr, active, pok, perr, cok, caps] = (await waitForFile(m2, '/tmp/ts_hl.txt')).trim().split('\n');
191    log("treesitter.start -> ok=" + sok + (serr !== 'nil' ? `, err='${serr}'` : ""));
192    log("highlighter.active[bufnr] registered: " + active);
193    log("parser:parse() -> ok=" + pok + (perr !== 'nil' ? `, err='${perr}'` : ""));
194    log(ok(`get_captures_at_pos -> ok=${cok}, captures='${caps}'`, cok === 'true' && caps !== 'none', "(no captures)"));
195  } catch (e) { log("ERROR in tree-sitter highlight captures test: " + e); }
196}
197
198let moduleRef = null;
199document.getElementById('persistBtn').addEventListener('click', () => {
200  if (!moduleRef) return log("module not ready yet");
201  moduleRef.FS.syncfs(false, e => log(e ? "persist error: " + e : "persisted dynamic data to IndexedDB"));
202});
203
204(async () => {
205  await runtimeSanityCheck();
206  for (const t of tests) await runTest(t);
207  await treesitterHighlightCapturesTest();
208  moduleRef = await freshNvim();
209  log("persistent session ready (use 'Persist now' button to sync IDBFS)");
210})().catch(e => log("test run failed: " + e));
211</script>
212</body>
213</html>