Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,9 @@ jobs:
- name: Install dependencies
run: npm ci

- name: Fetch Clang WASM artifacts
run: npm run fetch-clang

- name: Verify manifest-driven version sync
run: npm run version:check

Expand All@@ -38,5 +41,8 @@ jobs:
- name: Run end-to-end session tests
run: npm run test:e2e

- name: Run compiler linker end-to-end tests
run: npm run test:e2e:compiler

- name: Run Firefox packaging smoke
run: npm run test:browser:firefox
4 changes: 4 additions & 0 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -543,6 +543,10 @@ Copy the resulting `clang.js` and `clang.wasm` into `dist/clang/`.
socket support.
- **Standard library**: Only the subset of libc/libc++ compiled into the WASM
sysroot is available.
- **C++ exceptions**: `try`, `catch`, and `throw` are not supported. The bundled
WASI C++ runtime has no exception-unwinding support, so use return values,
error-state checks (such as `stream.fail()`), or other non-throwing error
handling instead.
- **Execution time**: Long-running programs may trigger the browser's "unresponsive
script" dialog. The compiler runs in a dedicated Web Worker to avoid blocking
the UI.
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,7 +3,7 @@
"name": "browser.cpp",
"short_name": "browser.cpp",
"description": "In-browser C++20 IDE powered by Monaco Editor and WASM Clang",
"version": "0.4.5",
"version": "0.4.6",
"minimum_chrome_version": "105",
"icons": {
"16": "icons/icon16.png",
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
{
"name": "browser.cpp",
"version": "0.4.5",
"version": "0.4.6",
"description": "In-browser C++20 IDE with WASM Clang toolchain",
"private": true,
"scripts": {
Expand All@@ -11,8 +11,9 @@
"build": "npm run build:webpack && npm run build:targets",
"build:firefox": "npm run build",
"test:e2e": "node --experimental-detect-module --test scripts/e2e-session-persistence.test.mjs scripts/e2e-session-restore-choice.test.mjs scripts/e2e-multifile-build.test.mjs scripts/e2e-workspace-file-tracking.test.mjs scripts/e2e-terminal-mkdir.test.mjs scripts/e2e-terminal-stop.test.mjs scripts/e2e-terminal-git-removal.test.mjs scripts/e2e-terminal-stop-icon.test.mjs scripts/e2e-browser-compatibility.test.mjs scripts/e2e-firefox-compatibility.test.mjs scripts/e2e-firefox-jspi-stdin.test.mjs scripts/e2e-wasi-shim.test.mjs scripts/e2e-run-request.test.mjs scripts/e2e-release-packaging.test.mjs",
"test:e2e:compiler": "npm run test:preflight-clang && node --experimental-detect-module --test scripts/e2e-compiler-link.test.mjs",
"test:preflight-clang": "node scripts/preflight-clang-artifacts.js",
"test:browser:chrome": "npm run test:preflight-clang && node scripts/smoke-browser.mjs chrome",
"test:browser:chrome": "npm run test:e2e:compiler && node scripts/smoke-browser.mjs chrome",
"test:browser:edge": "npm run test:preflight-clang && node scripts/smoke-browser.mjs edge",
"test:browser:brave": "npm run test:preflight-clang && node scripts/smoke-browser.mjs brave",
"test:browser:chromium": "npm run test:preflight-clang && node scripts/smoke-browser.mjs chromium",
Expand Down
159 changes: 159 additions & 0 deletions scripts/e2e-compiler-link.test.mjs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath, pathToFileURL } from 'node:url';

import { parseCompilePlan } from '../src/workers/compile-plan.mjs';
import { createWasiRuntime } from '../src/workers/wasi-shim.mjs';

const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const clangDir = path.join(repoRoot, 'dist', 'clang');

globalThis.self = globalThis;
let toolsReady = null;

function ensureTools() {
toolsReady ||= (async () => {
process.type = 'renderer';
await import(pathToFileURL(path.join(clangDir, 'clang.js')).href);
await import(pathToFileURL(path.join(clangDir, 'lld.js')).href);
})();
return toolsReady;
}

function callMain(module, args) {
try {
return module.callMain(args);
} catch (error) {
if (error?.name === 'ExitStatus') return error.status;
throw error;
}
}

function* tarContents(buffer) {
const data = new Uint8Array(buffer);
const decode = new TextDecoder();
let offset = 0;

while (offset + 512 <= data.length) {
const header = data.slice(offset, offset + 512);
const name = decode.decode(header.slice(0, 100)).replace(/\0.*$/, '');
if (!name) return;
const size = parseInt(decode.decode(header.slice(124, 136)).replace(/\0.*$/, '').trim(), 8) || 0;
yield { name, content: data.slice(offset + 512, offset + 512 + size) };
offset += 512 + Math.ceil(size / 512) * 512;
}
}

const sysroot = fs.readFileSync(path.join(clangDir, 'sysroot.tar'));

function setUpSysroot(module) {
for (const { name, content } of tarContents(sysroot)) {
if (name.endsWith('/')) continue;
const directory = name.split('/').slice(0, -1).join('/');
if (directory && !module.FS.analyzePath(directory).exists) module.FS.mkdirTree(directory);
module.FS.writeFile(name, content);
}
}

async function createTool(factory, wasmName, program, capture) {
return factory({
thisProgram: program,
wasmBinary: fs.readFileSync(path.join(clangDir, wasmName)),
locateFile: (name) => path.join(clangDir, name),
print: capture,
printErr: capture,
});
}

async function compileAndLink(source) {
await ensureTools();
let driverOutput = '';
const driver = await createTool(globalThis.createClangModule, 'clang.wasm', 'clang++', (line) => {
driverOutput += `${line}\n`;
});
driver.FS.writeFile('main.cpp', source);
driver.FS.mkdirTree('/lib/wasm32-wasi');
driver.FS.mkdirTree('/include/c++/v1');
driver.FS.writeFile('/lib/wasm32-wasi/crt1-command.o', new Uint8Array(0));
driver.FS.writeFile('/lib/wasm32-wasi/crt1-reactor.o', new Uint8Array(0));
assert.equal(callMain(driver, ['main.cpp', '-std=c++20', '-Wall', '-Wextra', '-fno-exceptions', '-###']), 0);

const plan = parseCompilePlan(driverOutput);
let compilerOutput = '';
const compiler = await createTool(globalThis.createClangModule, 'clang.wasm', 'clang++', (line) => {
compilerOutput += `${line}\n`;
});
compiler.FS.writeFile('main.cpp', source);
setUpSysroot(compiler);
compiler.FS.mkdirTree('/tmp');
assert.equal(callMain(compiler, plan.compileSteps[0].args), 0, compilerOutput);

let linkerOutput = '';
const linker = await createTool(globalThis.createLLDModule, 'lld.wasm', 'wasm-ld', (line) => {
linkerOutput += `${line}\n`;
});
setUpSysroot(linker);
linker.FS.mkdirTree('/tmp');
linker.FS.writeFile(plan.compileSteps[0].objectPath, compiler.FS.readFile(plan.compileSteps[0].objectPath));

const status = callMain(linker, plan.linkStep.args);
return {
status,
diagnostics: linkerOutput,
output: status === 0 ? linker.FS.readFile(plan.linkStep.outputPath) : null,
};
}

async function run(binary) {
let stdout = '';
const runtime = createWasiRuntime({
stdin: { mode: 'none' },
onStdout: (text) => { stdout += text; },
});
runtime.initRunVfs();
const { instance } = await WebAssembly.instantiate(binary, {
wasi_snapshot_preview1: runtime.wasi,
});
runtime.setMemory(instance.exports.memory);
try {
instance.exports._start();
} catch (error) {
if (!error?.__wasi_exit__) throw error;
assert.equal(error.code, 0);
}
return stdout;
}

test('e2e: stream insertion of defined int and string return values links without C++ exception symbols', async () => {
const result = await compileAndLink(`#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::cout << val() << ' ' << label() << std::endl;
}
`);

assert.equal(result.status, 0, result.diagnostics);
assert.doesNotMatch(result.diagnostics, /undefined symbol: __cxa_/);
assert.match(await run(result.output), /5 stream/);
});

test('e2e: an undefined streamed function reports the user symbol at link time', async () => {
const result = await compileAndLink(`#include <iostream>

int missing();

int main() {
std::cout << missing() << std::endl;
}
`);

assert.notEqual(result.status, 0);
assert.match(result.diagnostics, /undefined symbol: .*missing/);
assert.doesNotMatch(result.diagnostics, /undefined symbol: __cxa_/);
});
50 changes: 47 additions & 3 deletions scripts/smoke-browser.mjs
Original file line numberDiff line numberDiff line change
Expand Up@@ -287,6 +287,33 @@ async function evaluate(cdp, sessionId, expression, { awaitPromise = false } = {
return result.result?.value;
}

async function replaceEditorText(cdp, sessionId, source) {
const focused = await evaluate(
cdp,
sessionId,
`(() => {
const input = document.querySelector('.monaco-editor textarea.inputarea');
if (!input) return false;
input.focus();
return document.activeElement === input;
})()`
);
assert(focused, 'Could not focus the Monaco editor input area');
const selectAllModifier = await evaluate(
cdp,
sessionId,
`navigator.platform.includes('Mac') ? 4 : 2`
);

await cdp.send('Input.dispatchKeyEvent', {
type: 'keyDown', key: 'a', code: 'KeyA', modifiers: selectAllModifier,
}, sessionId);
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyUp', key: 'a', code: 'KeyA', modifiers: selectAllModifier,
}, sessionId);
await cdp.send('Input.insertText', { text: source }, sessionId);
}

async function openExtensionPage(cdp, extensionId) {
const { targetId } = await cdp.send('Target.createTarget', {
url: 'about:blank',
Expand DownExpand Up@@ -708,6 +735,10 @@ async function runHostedSmoke(cdp, { realRun = false } = {}) {
await cdp.send('Runtime.enable', {}, sessionId);
const runtimeProgram = `#include <fstream>
#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::fstream out;
Expand All@@ -718,7 +749,7 @@ int main() {
}
out << "hello from fstream\\n";
out.close();
std::cout << "wrote output.txt\\n";
std::cout << val() << ' ' << label() << " wrote output.txt\\n";
return 0;
}
`;
Expand DownExpand Up@@ -819,6 +850,7 @@ int main() {

const createdFileText = await evaluate(cdp, sessionId, `globalThis.__browserCppTestFs.readText('output.txt')`);
assert(createdFileText === 'hello from fstream\n', `Expected output.txt to be created, got: ${JSON.stringify(createdFileText)}`);
assert(terminalText.includes('5 stream wrote output.txt'), `Expected stream-insertion output, got: ${JSON.stringify(terminalText)}`);

const explorerPath = await waitFor(async () => {
return evaluate(
Expand DownExpand Up@@ -954,13 +986,25 @@ async function runSmoke(cdp, sessionId) {
const hasEditor = await evaluate(cdp, sessionId, `!!document.querySelector('.monaco-editor')`);
assert(hasEditor, 'Monaco editor did not render');

await replaceEditorText(cdp, sessionId, `#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::cout << val() << ' ' << label() << std::endl;
return 0;
}
`);

await evaluate(cdp, sessionId, `document.getElementById('btn-compile-run').click()`);

try {
await waitFor(async () => {
const text = await evaluate(cdp, sessionId, `document.body.textContent || ''`);
return text.includes('Compilation successful.') && text.includes('Hello, World!') ? text : null;
}, 'default C++ compile-and-run output', 120_000);
return text.includes('Compilation successful.') && text.includes('5 stream') ? text : null;
}, 'stream insertion compile-and-run output', 120_000);
} catch (err) {
const status = await evaluate(cdp, sessionId, `document.getElementById('status-compiler')?.textContent || ''`);
const terminalText = await evaluate(cdp, sessionId, `document.getElementById('terminal-container')?.textContent || ''`);
Expand Down
5 changes: 4 additions & 1 deletion src/workers/compiler.worker.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -376,7 +376,10 @@ async function compile(request) {

if (sources.length === 0) return fail('No source files to compile.');

const userFlags = [`-std=${std}`, '-Wall', '-Wextra', ...flags];
// The bundled WASI libc++abi is built without C++ exception support. Clang
// otherwise enables exceptions for C++ sources, producing unresolved
// __cxa_* symbols when stream operations instantiate throwing paths.
const userFlags = [`-std=${std}`, '-Wall', '-Wextra', ...flags, '-fno-exceptions'];

// ── Step 1: Build-plan discovery ─────────────────────────────────────────
let plan;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,9 @@ jobs:
- name: Install dependencies
run: npm ci

- name: Fetch Clang WASM artifacts
run: npm run fetch-clang

- name: Verify manifest-driven version sync
run: npm run version:check

Expand All@@ -38,5 +41,8 @@ jobs:
- name: Run end-to-end session tests
run: npm run test:e2e

- name: Run compiler linker end-to-end tests
run: npm run test:e2e:compiler

- name: Run Firefox packaging smoke
run: npm run test:browser:firefox
4 changes: 4 additions & 0 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -543,6 +543,10 @@ Copy the resulting `clang.js` and `clang.wasm` into `dist/clang/`.
socket support.
- **Standard library**: Only the subset of libc/libc++ compiled into the WASM
sysroot is available.
- **C++ exceptions**: `try`, `catch`, and `throw` are not supported. The bundled
WASI C++ runtime has no exception-unwinding support, so use return values,
error-state checks (such as `stream.fail()`), or other non-throwing error
handling instead.
- **Execution time**: Long-running programs may trigger the browser's "unresponsive
script" dialog. The compiler runs in a dedicated Web Worker to avoid blocking
the UI.
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,7 +3,7 @@
"name": "browser.cpp",
"short_name": "browser.cpp",
"description": "In-browser C++20 IDE powered by Monaco Editor and WASM Clang",
"version": "0.4.5",
"version": "0.4.6",
"minimum_chrome_version": "105",
"icons": {
"16": "icons/icon16.png",
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
{
"name": "browser.cpp",
"version": "0.4.5",
"version": "0.4.6",
"description": "In-browser C++20 IDE with WASM Clang toolchain",
"private": true,
"scripts": {
Expand All@@ -11,8 +11,9 @@
"build": "npm run build:webpack && npm run build:targets",
"build:firefox": "npm run build",
"test:e2e": "node --experimental-detect-module --test scripts/e2e-session-persistence.test.mjs scripts/e2e-session-restore-choice.test.mjs scripts/e2e-multifile-build.test.mjs scripts/e2e-workspace-file-tracking.test.mjs scripts/e2e-terminal-mkdir.test.mjs scripts/e2e-terminal-stop.test.mjs scripts/e2e-terminal-git-removal.test.mjs scripts/e2e-terminal-stop-icon.test.mjs scripts/e2e-browser-compatibility.test.mjs scripts/e2e-firefox-compatibility.test.mjs scripts/e2e-firefox-jspi-stdin.test.mjs scripts/e2e-wasi-shim.test.mjs scripts/e2e-run-request.test.mjs scripts/e2e-release-packaging.test.mjs",
"test:e2e:compiler": "npm run test:preflight-clang && node --experimental-detect-module --test scripts/e2e-compiler-link.test.mjs",
"test:preflight-clang": "node scripts/preflight-clang-artifacts.js",
"test:browser:chrome": "npm run test:preflight-clang && node scripts/smoke-browser.mjs chrome",
"test:browser:chrome": "npm run test:e2e:compiler && node scripts/smoke-browser.mjs chrome",
"test:browser:edge": "npm run test:preflight-clang && node scripts/smoke-browser.mjs edge",
"test:browser:brave": "npm run test:preflight-clang && node scripts/smoke-browser.mjs brave",
"test:browser:chromium": "npm run test:preflight-clang && node scripts/smoke-browser.mjs chromium",
Expand Down
159 changes: 159 additions & 0 deletions scripts/e2e-compiler-link.test.mjs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath, pathToFileURL } from 'node:url';

import { parseCompilePlan } from '../src/workers/compile-plan.mjs';
import { createWasiRuntime } from '../src/workers/wasi-shim.mjs';

const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const clangDir = path.join(repoRoot, 'dist', 'clang');

globalThis.self = globalThis;
let toolsReady = null;

function ensureTools() {
toolsReady ||= (async () => {
process.type = 'renderer';
await import(pathToFileURL(path.join(clangDir, 'clang.js')).href);
await import(pathToFileURL(path.join(clangDir, 'lld.js')).href);
})();
return toolsReady;
}

function callMain(module, args) {
try {
return module.callMain(args);
} catch (error) {
if (error?.name === 'ExitStatus') return error.status;
throw error;
}
}

function* tarContents(buffer) {
const data = new Uint8Array(buffer);
const decode = new TextDecoder();
let offset = 0;

while (offset + 512 <= data.length) {
const header = data.slice(offset, offset + 512);
const name = decode.decode(header.slice(0, 100)).replace(/\0.*$/, '');
if (!name) return;
const size = parseInt(decode.decode(header.slice(124, 136)).replace(/\0.*$/, '').trim(), 8) || 0;
yield { name, content: data.slice(offset + 512, offset + 512 + size) };
offset += 512 + Math.ceil(size / 512) * 512;
}
}

const sysroot = fs.readFileSync(path.join(clangDir, 'sysroot.tar'));

function setUpSysroot(module) {
for (const { name, content } of tarContents(sysroot)) {
if (name.endsWith('/')) continue;
const directory = name.split('/').slice(0, -1).join('/');
if (directory && !module.FS.analyzePath(directory).exists) module.FS.mkdirTree(directory);
module.FS.writeFile(name, content);
}
}

async function createTool(factory, wasmName, program, capture) {
return factory({
thisProgram: program,
wasmBinary: fs.readFileSync(path.join(clangDir, wasmName)),
locateFile: (name) => path.join(clangDir, name),
print: capture,
printErr: capture,
});
}

async function compileAndLink(source) {
await ensureTools();
let driverOutput = '';
const driver = await createTool(globalThis.createClangModule, 'clang.wasm', 'clang++', (line) => {
driverOutput += `${line}\n`;
});
driver.FS.writeFile('main.cpp', source);
driver.FS.mkdirTree('/lib/wasm32-wasi');
driver.FS.mkdirTree('/include/c++/v1');
driver.FS.writeFile('/lib/wasm32-wasi/crt1-command.o', new Uint8Array(0));
driver.FS.writeFile('/lib/wasm32-wasi/crt1-reactor.o', new Uint8Array(0));
assert.equal(callMain(driver, ['main.cpp', '-std=c++20', '-Wall', '-Wextra', '-fno-exceptions', '-###']), 0);

const plan = parseCompilePlan(driverOutput);
let compilerOutput = '';
const compiler = await createTool(globalThis.createClangModule, 'clang.wasm', 'clang++', (line) => {
compilerOutput += `${line}\n`;
});
compiler.FS.writeFile('main.cpp', source);
setUpSysroot(compiler);
compiler.FS.mkdirTree('/tmp');
assert.equal(callMain(compiler, plan.compileSteps[0].args), 0, compilerOutput);

let linkerOutput = '';
const linker = await createTool(globalThis.createLLDModule, 'lld.wasm', 'wasm-ld', (line) => {
linkerOutput += `${line}\n`;
});
setUpSysroot(linker);
linker.FS.mkdirTree('/tmp');
linker.FS.writeFile(plan.compileSteps[0].objectPath, compiler.FS.readFile(plan.compileSteps[0].objectPath));

const status = callMain(linker, plan.linkStep.args);
return {
status,
diagnostics: linkerOutput,
output: status === 0 ? linker.FS.readFile(plan.linkStep.outputPath) : null,
};
}

async function run(binary) {
let stdout = '';
const runtime = createWasiRuntime({
stdin: { mode: 'none' },
onStdout: (text) => { stdout += text; },
});
runtime.initRunVfs();
const { instance } = await WebAssembly.instantiate(binary, {
wasi_snapshot_preview1: runtime.wasi,
});
runtime.setMemory(instance.exports.memory);
try {
instance.exports._start();
} catch (error) {
if (!error?.__wasi_exit__) throw error;
assert.equal(error.code, 0);
}
return stdout;
}

test('e2e: stream insertion of defined int and string return values links without C++ exception symbols', async () => {
const result = await compileAndLink(`#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::cout << val() << ' ' << label() << std::endl;
}
`);

assert.equal(result.status, 0, result.diagnostics);
assert.doesNotMatch(result.diagnostics, /undefined symbol: __cxa_/);
assert.match(await run(result.output), /5 stream/);
});

test('e2e: an undefined streamed function reports the user symbol at link time', async () => {
const result = await compileAndLink(`#include <iostream>

int missing();

int main() {
std::cout << missing() << std::endl;
}
`);

assert.notEqual(result.status, 0);
assert.match(result.diagnostics, /undefined symbol: .*missing/);
assert.doesNotMatch(result.diagnostics, /undefined symbol: __cxa_/);
});
50 changes: 47 additions & 3 deletions scripts/smoke-browser.mjs
Original file line numberDiff line numberDiff line change
Expand Up@@ -287,6 +287,33 @@ async function evaluate(cdp, sessionId, expression, { awaitPromise = false } = {
return result.result?.value;
}

async function replaceEditorText(cdp, sessionId, source) {
const focused = await evaluate(
cdp,
sessionId,
`(() => {
const input = document.querySelector('.monaco-editor textarea.inputarea');
if (!input) return false;
input.focus();
return document.activeElement === input;
})()`
);
assert(focused, 'Could not focus the Monaco editor input area');
const selectAllModifier = await evaluate(
cdp,
sessionId,
`navigator.platform.includes('Mac') ? 4 : 2`
);

await cdp.send('Input.dispatchKeyEvent', {
type: 'keyDown', key: 'a', code: 'KeyA', modifiers: selectAllModifier,
}, sessionId);
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyUp', key: 'a', code: 'KeyA', modifiers: selectAllModifier,
}, sessionId);
await cdp.send('Input.insertText', { text: source }, sessionId);
}

async function openExtensionPage(cdp, extensionId) {
const { targetId } = await cdp.send('Target.createTarget', {
url: 'about:blank',
Expand DownExpand Up@@ -708,6 +735,10 @@ async function runHostedSmoke(cdp, { realRun = false } = {}) {
await cdp.send('Runtime.enable', {}, sessionId);
const runtimeProgram = `#include <fstream>
#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::fstream out;
Expand All@@ -718,7 +749,7 @@ int main() {
}
out << "hello from fstream\\n";
out.close();
std::cout << "wrote output.txt\\n";
std::cout << val() << ' ' << label() << " wrote output.txt\\n";
return 0;
}
`;
Expand DownExpand Up@@ -819,6 +850,7 @@ int main() {

const createdFileText = await evaluate(cdp, sessionId, `globalThis.__browserCppTestFs.readText('output.txt')`);
assert(createdFileText === 'hello from fstream\n', `Expected output.txt to be created, got: ${JSON.stringify(createdFileText)}`);
assert(terminalText.includes('5 stream wrote output.txt'), `Expected stream-insertion output, got: ${JSON.stringify(terminalText)}`);

const explorerPath = await waitFor(async () => {
return evaluate(
Expand DownExpand Up@@ -954,13 +986,25 @@ async function runSmoke(cdp, sessionId) {
const hasEditor = await evaluate(cdp, sessionId, `!!document.querySelector('.monaco-editor')`);
assert(hasEditor, 'Monaco editor did not render');

await replaceEditorText(cdp, sessionId, `#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::cout << val() << ' ' << label() << std::endl;
return 0;
}
`);

await evaluate(cdp, sessionId, `document.getElementById('btn-compile-run').click()`);

try {
await waitFor(async () => {
const text = await evaluate(cdp, sessionId, `document.body.textContent || ''`);
return text.includes('Compilation successful.') && text.includes('Hello, World!') ? text : null;
}, 'default C++ compile-and-run output', 120_000);
return text.includes('Compilation successful.') && text.includes('5 stream') ? text : null;
}, 'stream insertion compile-and-run output', 120_000);
} catch (err) {
const status = await evaluate(cdp, sessionId, `document.getElementById('status-compiler')?.textContent || ''`);
const terminalText = await evaluate(cdp, sessionId, `document.getElementById('terminal-container')?.textContent || ''`);
Expand Down
5 changes: 4 additions & 1 deletion src/workers/compiler.worker.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -376,7 +376,10 @@ async function compile(request) {

if (sources.length === 0) return fail('No source files to compile.');

const userFlags = [`-std=${std}`, '-Wall', '-Wextra', ...flags];
// The bundled WASI libc++abi is built without C++ exception support. Clang
// otherwise enables exceptions for C++ sources, producing unresolved
// __cxa_* symbols when stream operations instantiate throwing paths.
const userFlags = [`-std=${std}`, '-Wall', '-Wextra', ...flags, '-fno-exceptions'];

// ── Step 1: Build-plan discovery ─────────────────────────────────────────
let plan;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,9 @@ jobs:
- name: Install dependencies
run: npm ci

- name: Fetch Clang WASM artifacts
run: npm run fetch-clang

- name: Verify manifest-driven version sync
run: npm run version:check

Expand All@@ -38,5 +41,8 @@ jobs:
- name: Run end-to-end session tests
run: npm run test:e2e

- name: Run compiler linker end-to-end tests
run: npm run test:e2e:compiler

- name: Run Firefox packaging smoke
run: npm run test:browser:firefox
4 changes: 4 additions & 0 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -543,6 +543,10 @@ Copy the resulting `clang.js` and `clang.wasm` into `dist/clang/`.
socket support.
- **Standard library**: Only the subset of libc/libc++ compiled into the WASM
sysroot is available.
- **C++ exceptions**: `try`, `catch`, and `throw` are not supported. The bundled
WASI C++ runtime has no exception-unwinding support, so use return values,
error-state checks (such as `stream.fail()`), or other non-throwing error
handling instead.
- **Execution time**: Long-running programs may trigger the browser's "unresponsive
script" dialog. The compiler runs in a dedicated Web Worker to avoid blocking
the UI.
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,7 +3,7 @@
"name": "browser.cpp",
"short_name": "browser.cpp",
"description": "In-browser C++20 IDE powered by Monaco Editor and WASM Clang",
"version": "0.4.5",
"version": "0.4.6",
"minimum_chrome_version": "105",
"icons": {
"16": "icons/icon16.png",
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
{
"name": "browser.cpp",
"version": "0.4.5",
"version": "0.4.6",
"description": "In-browser C++20 IDE with WASM Clang toolchain",
"private": true,
"scripts": {
Expand All@@ -11,8 +11,9 @@
"build": "npm run build:webpack && npm run build:targets",
"build:firefox": "npm run build",
"test:e2e": "node --experimental-detect-module --test scripts/e2e-session-persistence.test.mjs scripts/e2e-session-restore-choice.test.mjs scripts/e2e-multifile-build.test.mjs scripts/e2e-workspace-file-tracking.test.mjs scripts/e2e-terminal-mkdir.test.mjs scripts/e2e-terminal-stop.test.mjs scripts/e2e-terminal-git-removal.test.mjs scripts/e2e-terminal-stop-icon.test.mjs scripts/e2e-browser-compatibility.test.mjs scripts/e2e-firefox-compatibility.test.mjs scripts/e2e-firefox-jspi-stdin.test.mjs scripts/e2e-wasi-shim.test.mjs scripts/e2e-run-request.test.mjs scripts/e2e-release-packaging.test.mjs",
"test:e2e:compiler": "npm run test:preflight-clang && node --experimental-detect-module --test scripts/e2e-compiler-link.test.mjs",
"test:preflight-clang": "node scripts/preflight-clang-artifacts.js",
"test:browser:chrome": "npm run test:preflight-clang && node scripts/smoke-browser.mjs chrome",
"test:browser:chrome": "npm run test:e2e:compiler && node scripts/smoke-browser.mjs chrome",
"test:browser:edge": "npm run test:preflight-clang && node scripts/smoke-browser.mjs edge",
"test:browser:brave": "npm run test:preflight-clang && node scripts/smoke-browser.mjs brave",
"test:browser:chromium": "npm run test:preflight-clang && node scripts/smoke-browser.mjs chromium",
Expand Down
159 changes: 159 additions & 0 deletions scripts/e2e-compiler-link.test.mjs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath, pathToFileURL } from 'node:url';

import { parseCompilePlan } from '../src/workers/compile-plan.mjs';
import { createWasiRuntime } from '../src/workers/wasi-shim.mjs';

const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const clangDir = path.join(repoRoot, 'dist', 'clang');

globalThis.self = globalThis;
let toolsReady = null;

function ensureTools() {
toolsReady ||= (async () => {
process.type = 'renderer';
await import(pathToFileURL(path.join(clangDir, 'clang.js')).href);
await import(pathToFileURL(path.join(clangDir, 'lld.js')).href);
})();
return toolsReady;
}

function callMain(module, args) {
try {
return module.callMain(args);
} catch (error) {
if (error?.name === 'ExitStatus') return error.status;
throw error;
}
}

function* tarContents(buffer) {
const data = new Uint8Array(buffer);
const decode = new TextDecoder();
let offset = 0;

while (offset + 512 <= data.length) {
const header = data.slice(offset, offset + 512);
const name = decode.decode(header.slice(0, 100)).replace(/\0.*$/, '');
if (!name) return;
const size = parseInt(decode.decode(header.slice(124, 136)).replace(/\0.*$/, '').trim(), 8) || 0;
yield { name, content: data.slice(offset + 512, offset + 512 + size) };
offset += 512 + Math.ceil(size / 512) * 512;
}
}

const sysroot = fs.readFileSync(path.join(clangDir, 'sysroot.tar'));

function setUpSysroot(module) {
for (const { name, content } of tarContents(sysroot)) {
if (name.endsWith('/')) continue;
const directory = name.split('/').slice(0, -1).join('/');
if (directory && !module.FS.analyzePath(directory).exists) module.FS.mkdirTree(directory);
module.FS.writeFile(name, content);
}
}

async function createTool(factory, wasmName, program, capture) {
return factory({
thisProgram: program,
wasmBinary: fs.readFileSync(path.join(clangDir, wasmName)),
locateFile: (name) => path.join(clangDir, name),
print: capture,
printErr: capture,
});
}

async function compileAndLink(source) {
await ensureTools();
let driverOutput = '';
const driver = await createTool(globalThis.createClangModule, 'clang.wasm', 'clang++', (line) => {
driverOutput += `${line}\n`;
});
driver.FS.writeFile('main.cpp', source);
driver.FS.mkdirTree('/lib/wasm32-wasi');
driver.FS.mkdirTree('/include/c++/v1');
driver.FS.writeFile('/lib/wasm32-wasi/crt1-command.o', new Uint8Array(0));
driver.FS.writeFile('/lib/wasm32-wasi/crt1-reactor.o', new Uint8Array(0));
assert.equal(callMain(driver, ['main.cpp', '-std=c++20', '-Wall', '-Wextra', '-fno-exceptions', '-###']), 0);

const plan = parseCompilePlan(driverOutput);
let compilerOutput = '';
const compiler = await createTool(globalThis.createClangModule, 'clang.wasm', 'clang++', (line) => {
compilerOutput += `${line}\n`;
});
compiler.FS.writeFile('main.cpp', source);
setUpSysroot(compiler);
compiler.FS.mkdirTree('/tmp');
assert.equal(callMain(compiler, plan.compileSteps[0].args), 0, compilerOutput);

let linkerOutput = '';
const linker = await createTool(globalThis.createLLDModule, 'lld.wasm', 'wasm-ld', (line) => {
linkerOutput += `${line}\n`;
});
setUpSysroot(linker);
linker.FS.mkdirTree('/tmp');
linker.FS.writeFile(plan.compileSteps[0].objectPath, compiler.FS.readFile(plan.compileSteps[0].objectPath));

const status = callMain(linker, plan.linkStep.args);
return {
status,
diagnostics: linkerOutput,
output: status === 0 ? linker.FS.readFile(plan.linkStep.outputPath) : null,
};
}

async function run(binary) {
let stdout = '';
const runtime = createWasiRuntime({
stdin: { mode: 'none' },
onStdout: (text) => { stdout += text; },
});
runtime.initRunVfs();
const { instance } = await WebAssembly.instantiate(binary, {
wasi_snapshot_preview1: runtime.wasi,
});
runtime.setMemory(instance.exports.memory);
try {
instance.exports._start();
} catch (error) {
if (!error?.__wasi_exit__) throw error;
assert.equal(error.code, 0);
}
return stdout;
}

test('e2e: stream insertion of defined int and string return values links without C++ exception symbols', async () => {
const result = await compileAndLink(`#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::cout << val() << ' ' << label() << std::endl;
}
`);

assert.equal(result.status, 0, result.diagnostics);
assert.doesNotMatch(result.diagnostics, /undefined symbol: __cxa_/);
assert.match(await run(result.output), /5 stream/);
});

test('e2e: an undefined streamed function reports the user symbol at link time', async () => {
const result = await compileAndLink(`#include <iostream>

int missing();

int main() {
std::cout << missing() << std::endl;
}
`);

assert.notEqual(result.status, 0);
assert.match(result.diagnostics, /undefined symbol: .*missing/);
assert.doesNotMatch(result.diagnostics, /undefined symbol: __cxa_/);
});
50 changes: 47 additions & 3 deletions scripts/smoke-browser.mjs
Original file line numberDiff line numberDiff line change
Expand Up@@ -287,6 +287,33 @@ async function evaluate(cdp, sessionId, expression, { awaitPromise = false } = {
return result.result?.value;
}

async function replaceEditorText(cdp, sessionId, source) {
const focused = await evaluate(
cdp,
sessionId,
`(() => {
const input = document.querySelector('.monaco-editor textarea.inputarea');
if (!input) return false;
input.focus();
return document.activeElement === input;
})()`
);
assert(focused, 'Could not focus the Monaco editor input area');
const selectAllModifier = await evaluate(
cdp,
sessionId,
`navigator.platform.includes('Mac') ? 4 : 2`
);

await cdp.send('Input.dispatchKeyEvent', {
type: 'keyDown', key: 'a', code: 'KeyA', modifiers: selectAllModifier,
}, sessionId);
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyUp', key: 'a', code: 'KeyA', modifiers: selectAllModifier,
}, sessionId);
await cdp.send('Input.insertText', { text: source }, sessionId);
}

async function openExtensionPage(cdp, extensionId) {
const { targetId } = await cdp.send('Target.createTarget', {
url: 'about:blank',
Expand DownExpand Up@@ -708,6 +735,10 @@ async function runHostedSmoke(cdp, { realRun = false } = {}) {
await cdp.send('Runtime.enable', {}, sessionId);
const runtimeProgram = `#include <fstream>
#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::fstream out;
Expand All@@ -718,7 +749,7 @@ int main() {
}
out << "hello from fstream\\n";
out.close();
std::cout << "wrote output.txt\\n";
std::cout << val() << ' ' << label() << " wrote output.txt\\n";
return 0;
}
`;
Expand DownExpand Up@@ -819,6 +850,7 @@ int main() {

const createdFileText = await evaluate(cdp, sessionId, `globalThis.__browserCppTestFs.readText('output.txt')`);
assert(createdFileText === 'hello from fstream\n', `Expected output.txt to be created, got: ${JSON.stringify(createdFileText)}`);
assert(terminalText.includes('5 stream wrote output.txt'), `Expected stream-insertion output, got: ${JSON.stringify(terminalText)}`);

const explorerPath = await waitFor(async () => {
return evaluate(
Expand DownExpand Up@@ -954,13 +986,25 @@ async function runSmoke(cdp, sessionId) {
const hasEditor = await evaluate(cdp, sessionId, `!!document.querySelector('.monaco-editor')`);
assert(hasEditor, 'Monaco editor did not render');

await replaceEditorText(cdp, sessionId, `#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::cout << val() << ' ' << label() << std::endl;
return 0;
}
`);

await evaluate(cdp, sessionId, `document.getElementById('btn-compile-run').click()`);

try {
await waitFor(async () => {
const text = await evaluate(cdp, sessionId, `document.body.textContent || ''`);
return text.includes('Compilation successful.') && text.includes('Hello, World!') ? text : null;
}, 'default C++ compile-and-run output', 120_000);
return text.includes('Compilation successful.') && text.includes('5 stream') ? text : null;
}, 'stream insertion compile-and-run output', 120_000);
} catch (err) {
const status = await evaluate(cdp, sessionId, `document.getElementById('status-compiler')?.textContent || ''`);
const terminalText = await evaluate(cdp, sessionId, `document.getElementById('terminal-container')?.textContent || ''`);
Expand Down
5 changes: 4 additions & 1 deletion src/workers/compiler.worker.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -376,7 +376,10 @@ async function compile(request) {

if (sources.length === 0) return fail('No source files to compile.');

const userFlags = [`-std=${std}`, '-Wall', '-Wextra', ...flags];
// The bundled WASI libc++abi is built without C++ exception support. Clang
// otherwise enables exceptions for C++ sources, producing unresolved
// __cxa_* symbols when stream operations instantiate throwing paths.
const userFlags = [`-std=${std}`, '-Wall', '-Wextra', ...flags, '-fno-exceptions'];

// ── Step 1: Build-plan discovery ─────────────────────────────────────────
let plan;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,9 @@ jobs:
- name: Install dependencies
run: npm ci

- name: Fetch Clang WASM artifacts
run: npm run fetch-clang

- name: Verify manifest-driven version sync
run: npm run version:check

Expand All@@ -38,5 +41,8 @@ jobs:
- name: Run end-to-end session tests
run: npm run test:e2e

- name: Run compiler linker end-to-end tests
run: npm run test:e2e:compiler

- name: Run Firefox packaging smoke
run: npm run test:browser:firefox
4 changes: 4 additions & 0 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -543,6 +543,10 @@ Copy the resulting `clang.js` and `clang.wasm` into `dist/clang/`.
socket support.
- **Standard library**: Only the subset of libc/libc++ compiled into the WASM
sysroot is available.
- **C++ exceptions**: `try`, `catch`, and `throw` are not supported. The bundled
WASI C++ runtime has no exception-unwinding support, so use return values,
error-state checks (such as `stream.fail()`), or other non-throwing error
handling instead.
- **Execution time**: Long-running programs may trigger the browser's "unresponsive
script" dialog. The compiler runs in a dedicated Web Worker to avoid blocking
the UI.
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,7 +3,7 @@
"name": "browser.cpp",
"short_name": "browser.cpp",
"description": "In-browser C++20 IDE powered by Monaco Editor and WASM Clang",
"version": "0.4.5",
"version": "0.4.6",
"minimum_chrome_version": "105",
"icons": {
"16": "icons/icon16.png",
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
{
"name": "browser.cpp",
"version": "0.4.5",
"version": "0.4.6",
"description": "In-browser C++20 IDE with WASM Clang toolchain",
"private": true,
"scripts": {
Expand All@@ -11,8 +11,9 @@
"build": "npm run build:webpack && npm run build:targets",
"build:firefox": "npm run build",
"test:e2e": "node --experimental-detect-module --test scripts/e2e-session-persistence.test.mjs scripts/e2e-session-restore-choice.test.mjs scripts/e2e-multifile-build.test.mjs scripts/e2e-workspace-file-tracking.test.mjs scripts/e2e-terminal-mkdir.test.mjs scripts/e2e-terminal-stop.test.mjs scripts/e2e-terminal-git-removal.test.mjs scripts/e2e-terminal-stop-icon.test.mjs scripts/e2e-browser-compatibility.test.mjs scripts/e2e-firefox-compatibility.test.mjs scripts/e2e-firefox-jspi-stdin.test.mjs scripts/e2e-wasi-shim.test.mjs scripts/e2e-run-request.test.mjs scripts/e2e-release-packaging.test.mjs",
"test:e2e:compiler": "npm run test:preflight-clang && node --experimental-detect-module --test scripts/e2e-compiler-link.test.mjs",
"test:preflight-clang": "node scripts/preflight-clang-artifacts.js",
"test:browser:chrome": "npm run test:preflight-clang && node scripts/smoke-browser.mjs chrome",
"test:browser:chrome": "npm run test:e2e:compiler && node scripts/smoke-browser.mjs chrome",
"test:browser:edge": "npm run test:preflight-clang && node scripts/smoke-browser.mjs edge",
"test:browser:brave": "npm run test:preflight-clang && node scripts/smoke-browser.mjs brave",
"test:browser:chromium": "npm run test:preflight-clang && node scripts/smoke-browser.mjs chromium",
Expand Down
159 changes: 159 additions & 0 deletions scripts/e2e-compiler-link.test.mjs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath, pathToFileURL } from 'node:url';

import { parseCompilePlan } from '../src/workers/compile-plan.mjs';
import { createWasiRuntime } from '../src/workers/wasi-shim.mjs';

const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const clangDir = path.join(repoRoot, 'dist', 'clang');

globalThis.self = globalThis;
let toolsReady = null;

function ensureTools() {
toolsReady ||= (async () => {
process.type = 'renderer';
await import(pathToFileURL(path.join(clangDir, 'clang.js')).href);
await import(pathToFileURL(path.join(clangDir, 'lld.js')).href);
})();
return toolsReady;
}

function callMain(module, args) {
try {
return module.callMain(args);
} catch (error) {
if (error?.name === 'ExitStatus') return error.status;
throw error;
}
}

function* tarContents(buffer) {
const data = new Uint8Array(buffer);
const decode = new TextDecoder();
let offset = 0;

while (offset + 512 <= data.length) {
const header = data.slice(offset, offset + 512);
const name = decode.decode(header.slice(0, 100)).replace(/\0.*$/, '');
if (!name) return;
const size = parseInt(decode.decode(header.slice(124, 136)).replace(/\0.*$/, '').trim(), 8) || 0;
yield { name, content: data.slice(offset + 512, offset + 512 + size) };
offset += 512 + Math.ceil(size / 512) * 512;
}
}

const sysroot = fs.readFileSync(path.join(clangDir, 'sysroot.tar'));

function setUpSysroot(module) {
for (const { name, content } of tarContents(sysroot)) {
if (name.endsWith('/')) continue;
const directory = name.split('/').slice(0, -1).join('/');
if (directory && !module.FS.analyzePath(directory).exists) module.FS.mkdirTree(directory);
module.FS.writeFile(name, content);
}
}

async function createTool(factory, wasmName, program, capture) {
return factory({
thisProgram: program,
wasmBinary: fs.readFileSync(path.join(clangDir, wasmName)),
locateFile: (name) => path.join(clangDir, name),
print: capture,
printErr: capture,
});
}

async function compileAndLink(source) {
await ensureTools();
let driverOutput = '';
const driver = await createTool(globalThis.createClangModule, 'clang.wasm', 'clang++', (line) => {
driverOutput += `${line}\n`;
});
driver.FS.writeFile('main.cpp', source);
driver.FS.mkdirTree('/lib/wasm32-wasi');
driver.FS.mkdirTree('/include/c++/v1');
driver.FS.writeFile('/lib/wasm32-wasi/crt1-command.o', new Uint8Array(0));
driver.FS.writeFile('/lib/wasm32-wasi/crt1-reactor.o', new Uint8Array(0));
assert.equal(callMain(driver, ['main.cpp', '-std=c++20', '-Wall', '-Wextra', '-fno-exceptions', '-###']), 0);

const plan = parseCompilePlan(driverOutput);
let compilerOutput = '';
const compiler = await createTool(globalThis.createClangModule, 'clang.wasm', 'clang++', (line) => {
compilerOutput += `${line}\n`;
});
compiler.FS.writeFile('main.cpp', source);
setUpSysroot(compiler);
compiler.FS.mkdirTree('/tmp');
assert.equal(callMain(compiler, plan.compileSteps[0].args), 0, compilerOutput);

let linkerOutput = '';
const linker = await createTool(globalThis.createLLDModule, 'lld.wasm', 'wasm-ld', (line) => {
linkerOutput += `${line}\n`;
});
setUpSysroot(linker);
linker.FS.mkdirTree('/tmp');
linker.FS.writeFile(plan.compileSteps[0].objectPath, compiler.FS.readFile(plan.compileSteps[0].objectPath));

const status = callMain(linker, plan.linkStep.args);
return {
status,
diagnostics: linkerOutput,
output: status === 0 ? linker.FS.readFile(plan.linkStep.outputPath) : null,
};
}

async function run(binary) {
let stdout = '';
const runtime = createWasiRuntime({
stdin: { mode: 'none' },
onStdout: (text) => { stdout += text; },
});
runtime.initRunVfs();
const { instance } = await WebAssembly.instantiate(binary, {
wasi_snapshot_preview1: runtime.wasi,
});
runtime.setMemory(instance.exports.memory);
try {
instance.exports._start();
} catch (error) {
if (!error?.__wasi_exit__) throw error;
assert.equal(error.code, 0);
}
return stdout;
}

test('e2e: stream insertion of defined int and string return values links without C++ exception symbols', async () => {
const result = await compileAndLink(`#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::cout << val() << ' ' << label() << std::endl;
}
`);

assert.equal(result.status, 0, result.diagnostics);
assert.doesNotMatch(result.diagnostics, /undefined symbol: __cxa_/);
assert.match(await run(result.output), /5 stream/);
});

test('e2e: an undefined streamed function reports the user symbol at link time', async () => {
const result = await compileAndLink(`#include <iostream>

int missing();

int main() {
std::cout << missing() << std::endl;
}
`);

assert.notEqual(result.status, 0);
assert.match(result.diagnostics, /undefined symbol: .*missing/);
assert.doesNotMatch(result.diagnostics, /undefined symbol: __cxa_/);
});
50 changes: 47 additions & 3 deletions scripts/smoke-browser.mjs
Original file line numberDiff line numberDiff line change
Expand Up@@ -287,6 +287,33 @@ async function evaluate(cdp, sessionId, expression, { awaitPromise = false } = {
return result.result?.value;
}

async function replaceEditorText(cdp, sessionId, source) {
const focused = await evaluate(
cdp,
sessionId,
`(() => {
const input = document.querySelector('.monaco-editor textarea.inputarea');
if (!input) return false;
input.focus();
return document.activeElement === input;
})()`
);
assert(focused, 'Could not focus the Monaco editor input area');
const selectAllModifier = await evaluate(
cdp,
sessionId,
`navigator.platform.includes('Mac') ? 4 : 2`
);

await cdp.send('Input.dispatchKeyEvent', {
type: 'keyDown', key: 'a', code: 'KeyA', modifiers: selectAllModifier,
}, sessionId);
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyUp', key: 'a', code: 'KeyA', modifiers: selectAllModifier,
}, sessionId);
await cdp.send('Input.insertText', { text: source }, sessionId);
}

async function openExtensionPage(cdp, extensionId) {
const { targetId } = await cdp.send('Target.createTarget', {
url: 'about:blank',
Expand DownExpand Up@@ -708,6 +735,10 @@ async function runHostedSmoke(cdp, { realRun = false } = {}) {
await cdp.send('Runtime.enable', {}, sessionId);
const runtimeProgram = `#include <fstream>
#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::fstream out;
Expand All@@ -718,7 +749,7 @@ int main() {
}
out << "hello from fstream\\n";
out.close();
std::cout << "wrote output.txt\\n";
std::cout << val() << ' ' << label() << " wrote output.txt\\n";
return 0;
}
`;
Expand DownExpand Up@@ -819,6 +850,7 @@ int main() {

const createdFileText = await evaluate(cdp, sessionId, `globalThis.__browserCppTestFs.readText('output.txt')`);
assert(createdFileText === 'hello from fstream\n', `Expected output.txt to be created, got: ${JSON.stringify(createdFileText)}`);
assert(terminalText.includes('5 stream wrote output.txt'), `Expected stream-insertion output, got: ${JSON.stringify(terminalText)}`);

const explorerPath = await waitFor(async () => {
return evaluate(
Expand DownExpand Up@@ -954,13 +986,25 @@ async function runSmoke(cdp, sessionId) {
const hasEditor = await evaluate(cdp, sessionId, `!!document.querySelector('.monaco-editor')`);
assert(hasEditor, 'Monaco editor did not render');

await replaceEditorText(cdp, sessionId, `#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::cout << val() << ' ' << label() << std::endl;
return 0;
}
`);

await evaluate(cdp, sessionId, `document.getElementById('btn-compile-run').click()`);

try {
await waitFor(async () => {
const text = await evaluate(cdp, sessionId, `document.body.textContent || ''`);
return text.includes('Compilation successful.') && text.includes('Hello, World!') ? text : null;
}, 'default C++ compile-and-run output', 120_000);
return text.includes('Compilation successful.') && text.includes('5 stream') ? text : null;
}, 'stream insertion compile-and-run output', 120_000);
} catch (err) {
const status = await evaluate(cdp, sessionId, `document.getElementById('status-compiler')?.textContent || ''`);
const terminalText = await evaluate(cdp, sessionId, `document.getElementById('terminal-container')?.textContent || ''`);
Expand Down
5 changes: 4 additions & 1 deletion src/workers/compiler.worker.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -376,7 +376,10 @@ async function compile(request) {

if (sources.length === 0) return fail('No source files to compile.');

const userFlags = [`-std=${std}`, '-Wall', '-Wextra', ...flags];
// The bundled WASI libc++abi is built without C++ exception support. Clang
// otherwise enables exceptions for C++ sources, producing unresolved
// __cxa_* symbols when stream operations instantiate throwing paths.
const userFlags = [`-std=${std}`, '-Wall', '-Wextra', ...flags, '-fno-exceptions'];

// ── Step 1: Build-plan discovery ─────────────────────────────────────────
let plan;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,9 @@ jobs:
- name: Install dependencies
run: npm ci

- name: Fetch Clang WASM artifacts
run: npm run fetch-clang

- name: Verify manifest-driven version sync
run: npm run version:check

Expand All@@ -38,5 +41,8 @@ jobs:
- name: Run end-to-end session tests
run: npm run test:e2e

- name: Run compiler linker end-to-end tests
run: npm run test:e2e:compiler

- name: Run Firefox packaging smoke
run: npm run test:browser:firefox
4 changes: 4 additions & 0 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -543,6 +543,10 @@ Copy the resulting `clang.js` and `clang.wasm` into `dist/clang/`.
socket support.
- **Standard library**: Only the subset of libc/libc++ compiled into the WASM
sysroot is available.
- **C++ exceptions**: `try`, `catch`, and `throw` are not supported. The bundled
WASI C++ runtime has no exception-unwinding support, so use return values,
error-state checks (such as `stream.fail()`), or other non-throwing error
handling instead.
- **Execution time**: Long-running programs may trigger the browser's "unresponsive
script" dialog. The compiler runs in a dedicated Web Worker to avoid blocking
the UI.
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,7 +3,7 @@
"name": "browser.cpp",
"short_name": "browser.cpp",
"description": "In-browser C++20 IDE powered by Monaco Editor and WASM Clang",
"version": "0.4.5",
"version": "0.4.6",
"minimum_chrome_version": "105",
"icons": {
"16": "icons/icon16.png",
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
{
"name": "browser.cpp",
"version": "0.4.5",
"version": "0.4.6",
"description": "In-browser C++20 IDE with WASM Clang toolchain",
"private": true,
"scripts": {
Expand All@@ -11,8 +11,9 @@
"build": "npm run build:webpack && npm run build:targets",
"build:firefox": "npm run build",
"test:e2e": "node --experimental-detect-module --test scripts/e2e-session-persistence.test.mjs scripts/e2e-session-restore-choice.test.mjs scripts/e2e-multifile-build.test.mjs scripts/e2e-workspace-file-tracking.test.mjs scripts/e2e-terminal-mkdir.test.mjs scripts/e2e-terminal-stop.test.mjs scripts/e2e-terminal-git-removal.test.mjs scripts/e2e-terminal-stop-icon.test.mjs scripts/e2e-browser-compatibility.test.mjs scripts/e2e-firefox-compatibility.test.mjs scripts/e2e-firefox-jspi-stdin.test.mjs scripts/e2e-wasi-shim.test.mjs scripts/e2e-run-request.test.mjs scripts/e2e-release-packaging.test.mjs",
"test:e2e:compiler": "npm run test:preflight-clang && node --experimental-detect-module --test scripts/e2e-compiler-link.test.mjs",
"test:preflight-clang": "node scripts/preflight-clang-artifacts.js",
"test:browser:chrome": "npm run test:preflight-clang && node scripts/smoke-browser.mjs chrome",
"test:browser:chrome": "npm run test:e2e:compiler && node scripts/smoke-browser.mjs chrome",
"test:browser:edge": "npm run test:preflight-clang && node scripts/smoke-browser.mjs edge",
"test:browser:brave": "npm run test:preflight-clang && node scripts/smoke-browser.mjs brave",
"test:browser:chromium": "npm run test:preflight-clang && node scripts/smoke-browser.mjs chromium",
Expand Down
159 changes: 159 additions & 0 deletions scripts/e2e-compiler-link.test.mjs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath, pathToFileURL } from 'node:url';

import { parseCompilePlan } from '../src/workers/compile-plan.mjs';
import { createWasiRuntime } from '../src/workers/wasi-shim.mjs';

const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const clangDir = path.join(repoRoot, 'dist', 'clang');

globalThis.self = globalThis;
let toolsReady = null;

function ensureTools() {
toolsReady ||= (async () => {
process.type = 'renderer';
await import(pathToFileURL(path.join(clangDir, 'clang.js')).href);
await import(pathToFileURL(path.join(clangDir, 'lld.js')).href);
})();
return toolsReady;
}

function callMain(module, args) {
try {
return module.callMain(args);
} catch (error) {
if (error?.name === 'ExitStatus') return error.status;
throw error;
}
}

function* tarContents(buffer) {
const data = new Uint8Array(buffer);
const decode = new TextDecoder();
let offset = 0;

while (offset + 512 <= data.length) {
const header = data.slice(offset, offset + 512);
const name = decode.decode(header.slice(0, 100)).replace(/\0.*$/, '');
if (!name) return;
const size = parseInt(decode.decode(header.slice(124, 136)).replace(/\0.*$/, '').trim(), 8) || 0;
yield { name, content: data.slice(offset + 512, offset + 512 + size) };
offset += 512 + Math.ceil(size / 512) * 512;
}
}

const sysroot = fs.readFileSync(path.join(clangDir, 'sysroot.tar'));

function setUpSysroot(module) {
for (const { name, content } of tarContents(sysroot)) {
if (name.endsWith('/')) continue;
const directory = name.split('/').slice(0, -1).join('/');
if (directory && !module.FS.analyzePath(directory).exists) module.FS.mkdirTree(directory);
module.FS.writeFile(name, content);
}
}

async function createTool(factory, wasmName, program, capture) {
return factory({
thisProgram: program,
wasmBinary: fs.readFileSync(path.join(clangDir, wasmName)),
locateFile: (name) => path.join(clangDir, name),
print: capture,
printErr: capture,
});
}

async function compileAndLink(source) {
await ensureTools();
let driverOutput = '';
const driver = await createTool(globalThis.createClangModule, 'clang.wasm', 'clang++', (line) => {
driverOutput += `${line}\n`;
});
driver.FS.writeFile('main.cpp', source);
driver.FS.mkdirTree('/lib/wasm32-wasi');
driver.FS.mkdirTree('/include/c++/v1');
driver.FS.writeFile('/lib/wasm32-wasi/crt1-command.o', new Uint8Array(0));
driver.FS.writeFile('/lib/wasm32-wasi/crt1-reactor.o', new Uint8Array(0));
assert.equal(callMain(driver, ['main.cpp', '-std=c++20', '-Wall', '-Wextra', '-fno-exceptions', '-###']), 0);

const plan = parseCompilePlan(driverOutput);
let compilerOutput = '';
const compiler = await createTool(globalThis.createClangModule, 'clang.wasm', 'clang++', (line) => {
compilerOutput += `${line}\n`;
});
compiler.FS.writeFile('main.cpp', source);
setUpSysroot(compiler);
compiler.FS.mkdirTree('/tmp');
assert.equal(callMain(compiler, plan.compileSteps[0].args), 0, compilerOutput);

let linkerOutput = '';
const linker = await createTool(globalThis.createLLDModule, 'lld.wasm', 'wasm-ld', (line) => {
linkerOutput += `${line}\n`;
});
setUpSysroot(linker);
linker.FS.mkdirTree('/tmp');
linker.FS.writeFile(plan.compileSteps[0].objectPath, compiler.FS.readFile(plan.compileSteps[0].objectPath));

const status = callMain(linker, plan.linkStep.args);
return {
status,
diagnostics: linkerOutput,
output: status === 0 ? linker.FS.readFile(plan.linkStep.outputPath) : null,
};
}

async function run(binary) {
let stdout = '';
const runtime = createWasiRuntime({
stdin: { mode: 'none' },
onStdout: (text) => { stdout += text; },
});
runtime.initRunVfs();
const { instance } = await WebAssembly.instantiate(binary, {
wasi_snapshot_preview1: runtime.wasi,
});
runtime.setMemory(instance.exports.memory);
try {
instance.exports._start();
} catch (error) {
if (!error?.__wasi_exit__) throw error;
assert.equal(error.code, 0);
}
return stdout;
}

test('e2e: stream insertion of defined int and string return values links without C++ exception symbols', async () => {
const result = await compileAndLink(`#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::cout << val() << ' ' << label() << std::endl;
}
`);

assert.equal(result.status, 0, result.diagnostics);
assert.doesNotMatch(result.diagnostics, /undefined symbol: __cxa_/);
assert.match(await run(result.output), /5 stream/);
});

test('e2e: an undefined streamed function reports the user symbol at link time', async () => {
const result = await compileAndLink(`#include <iostream>

int missing();

int main() {
std::cout << missing() << std::endl;
}
`);

assert.notEqual(result.status, 0);
assert.match(result.diagnostics, /undefined symbol: .*missing/);
assert.doesNotMatch(result.diagnostics, /undefined symbol: __cxa_/);
});
50 changes: 47 additions & 3 deletions scripts/smoke-browser.mjs
Original file line numberDiff line numberDiff line change
Expand Up@@ -287,6 +287,33 @@ async function evaluate(cdp, sessionId, expression, { awaitPromise = false } = {
return result.result?.value;
}

async function replaceEditorText(cdp, sessionId, source) {
const focused = await evaluate(
cdp,
sessionId,
`(() => {
const input = document.querySelector('.monaco-editor textarea.inputarea');
if (!input) return false;
input.focus();
return document.activeElement === input;
})()`
);
assert(focused, 'Could not focus the Monaco editor input area');
const selectAllModifier = await evaluate(
cdp,
sessionId,
`navigator.platform.includes('Mac') ? 4 : 2`
);

await cdp.send('Input.dispatchKeyEvent', {
type: 'keyDown', key: 'a', code: 'KeyA', modifiers: selectAllModifier,
}, sessionId);
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyUp', key: 'a', code: 'KeyA', modifiers: selectAllModifier,
}, sessionId);
await cdp.send('Input.insertText', { text: source }, sessionId);
}

async function openExtensionPage(cdp, extensionId) {
const { targetId } = await cdp.send('Target.createTarget', {
url: 'about:blank',
Expand DownExpand Up@@ -708,6 +735,10 @@ async function runHostedSmoke(cdp, { realRun = false } = {}) {
await cdp.send('Runtime.enable', {}, sessionId);
const runtimeProgram = `#include <fstream>
#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::fstream out;
Expand All@@ -718,7 +749,7 @@ int main() {
}
out << "hello from fstream\\n";
out.close();
std::cout << "wrote output.txt\\n";
std::cout << val() << ' ' << label() << " wrote output.txt\\n";
return 0;
}
`;
Expand DownExpand Up@@ -819,6 +850,7 @@ int main() {

const createdFileText = await evaluate(cdp, sessionId, `globalThis.__browserCppTestFs.readText('output.txt')`);
assert(createdFileText === 'hello from fstream\n', `Expected output.txt to be created, got: ${JSON.stringify(createdFileText)}`);
assert(terminalText.includes('5 stream wrote output.txt'), `Expected stream-insertion output, got: ${JSON.stringify(terminalText)}`);

const explorerPath = await waitFor(async () => {
return evaluate(
Expand DownExpand Up@@ -954,13 +986,25 @@ async function runSmoke(cdp, sessionId) {
const hasEditor = await evaluate(cdp, sessionId, `!!document.querySelector('.monaco-editor')`);
assert(hasEditor, 'Monaco editor did not render');

await replaceEditorText(cdp, sessionId, `#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::cout << val() << ' ' << label() << std::endl;
return 0;
}
`);

await evaluate(cdp, sessionId, `document.getElementById('btn-compile-run').click()`);

try {
await waitFor(async () => {
const text = await evaluate(cdp, sessionId, `document.body.textContent || ''`);
return text.includes('Compilation successful.') && text.includes('Hello, World!') ? text : null;
}, 'default C++ compile-and-run output', 120_000);
return text.includes('Compilation successful.') && text.includes('5 stream') ? text : null;
}, 'stream insertion compile-and-run output', 120_000);
} catch (err) {
const status = await evaluate(cdp, sessionId, `document.getElementById('status-compiler')?.textContent || ''`);
const terminalText = await evaluate(cdp, sessionId, `document.getElementById('terminal-container')?.textContent || ''`);
Expand Down
5 changes: 4 additions & 1 deletion src/workers/compiler.worker.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -376,7 +376,10 @@ async function compile(request) {

if (sources.length === 0) return fail('No source files to compile.');

const userFlags = [`-std=${std}`, '-Wall', '-Wextra', ...flags];
// The bundled WASI libc++abi is built without C++ exception support. Clang
// otherwise enables exceptions for C++ sources, producing unresolved
// __cxa_* symbols when stream operations instantiate throwing paths.
const userFlags = [`-std=${std}`, '-Wall', '-Wextra', ...flags, '-fno-exceptions'];

// ── Step 1: Build-plan discovery ─────────────────────────────────────────
let plan;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,9 @@ jobs:
- name: Install dependencies
run: npm ci

- name: Fetch Clang WASM artifacts
run: npm run fetch-clang

- name: Verify manifest-driven version sync
run: npm run version:check

Expand All@@ -38,5 +41,8 @@ jobs:
- name: Run end-to-end session tests
run: npm run test:e2e

- name: Run compiler linker end-to-end tests
run: npm run test:e2e:compiler

- name: Run Firefox packaging smoke
run: npm run test:browser:firefox
4 changes: 4 additions & 0 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -543,6 +543,10 @@ Copy the resulting `clang.js` and `clang.wasm` into `dist/clang/`.
socket support.
- **Standard library**: Only the subset of libc/libc++ compiled into the WASM
sysroot is available.
- **C++ exceptions**: `try`, `catch`, and `throw` are not supported. The bundled
WASI C++ runtime has no exception-unwinding support, so use return values,
error-state checks (such as `stream.fail()`), or other non-throwing error
handling instead.
- **Execution time**: Long-running programs may trigger the browser's "unresponsive
script" dialog. The compiler runs in a dedicated Web Worker to avoid blocking
the UI.
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,7 +3,7 @@
"name": "browser.cpp",
"short_name": "browser.cpp",
"description": "In-browser C++20 IDE powered by Monaco Editor and WASM Clang",
"version": "0.4.5",
"version": "0.4.6",
"minimum_chrome_version": "105",
"icons": {
"16": "icons/icon16.png",
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
{
"name": "browser.cpp",
"version": "0.4.5",
"version": "0.4.6",
"description": "In-browser C++20 IDE with WASM Clang toolchain",
"private": true,
"scripts": {
Expand All@@ -11,8 +11,9 @@
"build": "npm run build:webpack && npm run build:targets",
"build:firefox": "npm run build",
"test:e2e": "node --experimental-detect-module --test scripts/e2e-session-persistence.test.mjs scripts/e2e-session-restore-choice.test.mjs scripts/e2e-multifile-build.test.mjs scripts/e2e-workspace-file-tracking.test.mjs scripts/e2e-terminal-mkdir.test.mjs scripts/e2e-terminal-stop.test.mjs scripts/e2e-terminal-git-removal.test.mjs scripts/e2e-terminal-stop-icon.test.mjs scripts/e2e-browser-compatibility.test.mjs scripts/e2e-firefox-compatibility.test.mjs scripts/e2e-firefox-jspi-stdin.test.mjs scripts/e2e-wasi-shim.test.mjs scripts/e2e-run-request.test.mjs scripts/e2e-release-packaging.test.mjs",
"test:e2e:compiler": "npm run test:preflight-clang && node --experimental-detect-module --test scripts/e2e-compiler-link.test.mjs",
"test:preflight-clang": "node scripts/preflight-clang-artifacts.js",
"test:browser:chrome": "npm run test:preflight-clang && node scripts/smoke-browser.mjs chrome",
"test:browser:chrome": "npm run test:e2e:compiler && node scripts/smoke-browser.mjs chrome",
"test:browser:edge": "npm run test:preflight-clang && node scripts/smoke-browser.mjs edge",
"test:browser:brave": "npm run test:preflight-clang && node scripts/smoke-browser.mjs brave",
"test:browser:chromium": "npm run test:preflight-clang && node scripts/smoke-browser.mjs chromium",
Expand Down
159 changes: 159 additions & 0 deletions scripts/e2e-compiler-link.test.mjs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath, pathToFileURL } from 'node:url';

import { parseCompilePlan } from '../src/workers/compile-plan.mjs';
import { createWasiRuntime } from '../src/workers/wasi-shim.mjs';

const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const clangDir = path.join(repoRoot, 'dist', 'clang');

globalThis.self = globalThis;
let toolsReady = null;

function ensureTools() {
toolsReady ||= (async () => {
process.type = 'renderer';
await import(pathToFileURL(path.join(clangDir, 'clang.js')).href);
await import(pathToFileURL(path.join(clangDir, 'lld.js')).href);
})();
return toolsReady;
}

function callMain(module, args) {
try {
return module.callMain(args);
} catch (error) {
if (error?.name === 'ExitStatus') return error.status;
throw error;
}
}

function* tarContents(buffer) {
const data = new Uint8Array(buffer);
const decode = new TextDecoder();
let offset = 0;

while (offset + 512 <= data.length) {
const header = data.slice(offset, offset + 512);
const name = decode.decode(header.slice(0, 100)).replace(/\0.*$/, '');
if (!name) return;
const size = parseInt(decode.decode(header.slice(124, 136)).replace(/\0.*$/, '').trim(), 8) || 0;
yield { name, content: data.slice(offset + 512, offset + 512 + size) };
offset += 512 + Math.ceil(size / 512) * 512;
}
}

const sysroot = fs.readFileSync(path.join(clangDir, 'sysroot.tar'));

function setUpSysroot(module) {
for (const { name, content } of tarContents(sysroot)) {
if (name.endsWith('/')) continue;
const directory = name.split('/').slice(0, -1).join('/');
if (directory && !module.FS.analyzePath(directory).exists) module.FS.mkdirTree(directory);
module.FS.writeFile(name, content);
}
}

async function createTool(factory, wasmName, program, capture) {
return factory({
thisProgram: program,
wasmBinary: fs.readFileSync(path.join(clangDir, wasmName)),
locateFile: (name) => path.join(clangDir, name),
print: capture,
printErr: capture,
});
}

async function compileAndLink(source) {
await ensureTools();
let driverOutput = '';
const driver = await createTool(globalThis.createClangModule, 'clang.wasm', 'clang++', (line) => {
driverOutput += `${line}\n`;
});
driver.FS.writeFile('main.cpp', source);
driver.FS.mkdirTree('/lib/wasm32-wasi');
driver.FS.mkdirTree('/include/c++/v1');
driver.FS.writeFile('/lib/wasm32-wasi/crt1-command.o', new Uint8Array(0));
driver.FS.writeFile('/lib/wasm32-wasi/crt1-reactor.o', new Uint8Array(0));
assert.equal(callMain(driver, ['main.cpp', '-std=c++20', '-Wall', '-Wextra', '-fno-exceptions', '-###']), 0);

const plan = parseCompilePlan(driverOutput);
let compilerOutput = '';
const compiler = await createTool(globalThis.createClangModule, 'clang.wasm', 'clang++', (line) => {
compilerOutput += `${line}\n`;
});
compiler.FS.writeFile('main.cpp', source);
setUpSysroot(compiler);
compiler.FS.mkdirTree('/tmp');
assert.equal(callMain(compiler, plan.compileSteps[0].args), 0, compilerOutput);

let linkerOutput = '';
const linker = await createTool(globalThis.createLLDModule, 'lld.wasm', 'wasm-ld', (line) => {
linkerOutput += `${line}\n`;
});
setUpSysroot(linker);
linker.FS.mkdirTree('/tmp');
linker.FS.writeFile(plan.compileSteps[0].objectPath, compiler.FS.readFile(plan.compileSteps[0].objectPath));

const status = callMain(linker, plan.linkStep.args);
return {
status,
diagnostics: linkerOutput,
output: status === 0 ? linker.FS.readFile(plan.linkStep.outputPath) : null,
};
}

async function run(binary) {
let stdout = '';
const runtime = createWasiRuntime({
stdin: { mode: 'none' },
onStdout: (text) => { stdout += text; },
});
runtime.initRunVfs();
const { instance } = await WebAssembly.instantiate(binary, {
wasi_snapshot_preview1: runtime.wasi,
});
runtime.setMemory(instance.exports.memory);
try {
instance.exports._start();
} catch (error) {
if (!error?.__wasi_exit__) throw error;
assert.equal(error.code, 0);
}
return stdout;
}

test('e2e: stream insertion of defined int and string return values links without C++ exception symbols', async () => {
const result = await compileAndLink(`#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::cout << val() << ' ' << label() << std::endl;
}
`);

assert.equal(result.status, 0, result.diagnostics);
assert.doesNotMatch(result.diagnostics, /undefined symbol: __cxa_/);
assert.match(await run(result.output), /5 stream/);
});

test('e2e: an undefined streamed function reports the user symbol at link time', async () => {
const result = await compileAndLink(`#include <iostream>

int missing();

int main() {
std::cout << missing() << std::endl;
}
`);

assert.notEqual(result.status, 0);
assert.match(result.diagnostics, /undefined symbol: .*missing/);
assert.doesNotMatch(result.diagnostics, /undefined symbol: __cxa_/);
});
50 changes: 47 additions & 3 deletions scripts/smoke-browser.mjs
Original file line numberDiff line numberDiff line change
Expand Up@@ -287,6 +287,33 @@ async function evaluate(cdp, sessionId, expression, { awaitPromise = false } = {
return result.result?.value;
}

async function replaceEditorText(cdp, sessionId, source) {
const focused = await evaluate(
cdp,
sessionId,
`(() => {
const input = document.querySelector('.monaco-editor textarea.inputarea');
if (!input) return false;
input.focus();
return document.activeElement === input;
})()`
);
assert(focused, 'Could not focus the Monaco editor input area');
const selectAllModifier = await evaluate(
cdp,
sessionId,
`navigator.platform.includes('Mac') ? 4 : 2`
);

await cdp.send('Input.dispatchKeyEvent', {
type: 'keyDown', key: 'a', code: 'KeyA', modifiers: selectAllModifier,
}, sessionId);
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyUp', key: 'a', code: 'KeyA', modifiers: selectAllModifier,
}, sessionId);
await cdp.send('Input.insertText', { text: source }, sessionId);
}

async function openExtensionPage(cdp, extensionId) {
const { targetId } = await cdp.send('Target.createTarget', {
url: 'about:blank',
Expand DownExpand Up@@ -708,6 +735,10 @@ async function runHostedSmoke(cdp, { realRun = false } = {}) {
await cdp.send('Runtime.enable', {}, sessionId);
const runtimeProgram = `#include <fstream>
#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::fstream out;
Expand All@@ -718,7 +749,7 @@ int main() {
}
out << "hello from fstream\\n";
out.close();
std::cout << "wrote output.txt\\n";
std::cout << val() << ' ' << label() << " wrote output.txt\\n";
return 0;
}
`;
Expand DownExpand Up@@ -819,6 +850,7 @@ int main() {

const createdFileText = await evaluate(cdp, sessionId, `globalThis.__browserCppTestFs.readText('output.txt')`);
assert(createdFileText === 'hello from fstream\n', `Expected output.txt to be created, got: ${JSON.stringify(createdFileText)}`);
assert(terminalText.includes('5 stream wrote output.txt'), `Expected stream-insertion output, got: ${JSON.stringify(terminalText)}`);

const explorerPath = await waitFor(async () => {
return evaluate(
Expand DownExpand Up@@ -954,13 +986,25 @@ async function runSmoke(cdp, sessionId) {
const hasEditor = await evaluate(cdp, sessionId, `!!document.querySelector('.monaco-editor')`);
assert(hasEditor, 'Monaco editor did not render');

await replaceEditorText(cdp, sessionId, `#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::cout << val() << ' ' << label() << std::endl;
return 0;
}
`);

await evaluate(cdp, sessionId, `document.getElementById('btn-compile-run').click()`);

try {
await waitFor(async () => {
const text = await evaluate(cdp, sessionId, `document.body.textContent || ''`);
return text.includes('Compilation successful.') && text.includes('Hello, World!') ? text : null;
}, 'default C++ compile-and-run output', 120_000);
return text.includes('Compilation successful.') && text.includes('5 stream') ? text : null;
}, 'stream insertion compile-and-run output', 120_000);
} catch (err) {
const status = await evaluate(cdp, sessionId, `document.getElementById('status-compiler')?.textContent || ''`);
const terminalText = await evaluate(cdp, sessionId, `document.getElementById('terminal-container')?.textContent || ''`);
Expand Down
5 changes: 4 additions & 1 deletion src/workers/compiler.worker.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -376,7 +376,10 @@ async function compile(request) {

if (sources.length === 0) return fail('No source files to compile.');

const userFlags = [`-std=${std}`, '-Wall', '-Wextra', ...flags];
// The bundled WASI libc++abi is built without C++ exception support. Clang
// otherwise enables exceptions for C++ sources, producing unresolved
// __cxa_* symbols when stream operations instantiate throwing paths.
const userFlags = [`-std=${std}`, '-Wall', '-Wextra', ...flags, '-fno-exceptions'];

// ── Step 1: Build-plan discovery ─────────────────────────────────────────
let plan;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,9 @@ jobs:
- name: Install dependencies
run: npm ci

- name: Fetch Clang WASM artifacts
run: npm run fetch-clang

- name: Verify manifest-driven version sync
run: npm run version:check

Expand All@@ -38,5 +41,8 @@ jobs:
- name: Run end-to-end session tests
run: npm run test:e2e

- name: Run compiler linker end-to-end tests
run: npm run test:e2e:compiler

- name: Run Firefox packaging smoke
run: npm run test:browser:firefox
4 changes: 4 additions & 0 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -543,6 +543,10 @@ Copy the resulting `clang.js` and `clang.wasm` into `dist/clang/`.
socket support.
- **Standard library**: Only the subset of libc/libc++ compiled into the WASM
sysroot is available.
- **C++ exceptions**: `try`, `catch`, and `throw` are not supported. The bundled
WASI C++ runtime has no exception-unwinding support, so use return values,
error-state checks (such as `stream.fail()`), or other non-throwing error
handling instead.
- **Execution time**: Long-running programs may trigger the browser's "unresponsive
script" dialog. The compiler runs in a dedicated Web Worker to avoid blocking
the UI.
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,7 +3,7 @@
"name": "browser.cpp",
"short_name": "browser.cpp",
"description": "In-browser C++20 IDE powered by Monaco Editor and WASM Clang",
"version": "0.4.5",
"version": "0.4.6",
"minimum_chrome_version": "105",
"icons": {
"16": "icons/icon16.png",
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
{
"name": "browser.cpp",
"version": "0.4.5",
"version": "0.4.6",
"description": "In-browser C++20 IDE with WASM Clang toolchain",
"private": true,
"scripts": {
Expand All@@ -11,8 +11,9 @@
"build": "npm run build:webpack && npm run build:targets",
"build:firefox": "npm run build",
"test:e2e": "node --experimental-detect-module --test scripts/e2e-session-persistence.test.mjs scripts/e2e-session-restore-choice.test.mjs scripts/e2e-multifile-build.test.mjs scripts/e2e-workspace-file-tracking.test.mjs scripts/e2e-terminal-mkdir.test.mjs scripts/e2e-terminal-stop.test.mjs scripts/e2e-terminal-git-removal.test.mjs scripts/e2e-terminal-stop-icon.test.mjs scripts/e2e-browser-compatibility.test.mjs scripts/e2e-firefox-compatibility.test.mjs scripts/e2e-firefox-jspi-stdin.test.mjs scripts/e2e-wasi-shim.test.mjs scripts/e2e-run-request.test.mjs scripts/e2e-release-packaging.test.mjs",
"test:e2e:compiler": "npm run test:preflight-clang && node --experimental-detect-module --test scripts/e2e-compiler-link.test.mjs",
"test:preflight-clang": "node scripts/preflight-clang-artifacts.js",
"test:browser:chrome": "npm run test:preflight-clang && node scripts/smoke-browser.mjs chrome",
"test:browser:chrome": "npm run test:e2e:compiler && node scripts/smoke-browser.mjs chrome",
"test:browser:edge": "npm run test:preflight-clang && node scripts/smoke-browser.mjs edge",
"test:browser:brave": "npm run test:preflight-clang && node scripts/smoke-browser.mjs brave",
"test:browser:chromium": "npm run test:preflight-clang && node scripts/smoke-browser.mjs chromium",
Expand Down
159 changes: 159 additions & 0 deletions scripts/e2e-compiler-link.test.mjs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath, pathToFileURL } from 'node:url';

import { parseCompilePlan } from '../src/workers/compile-plan.mjs';
import { createWasiRuntime } from '../src/workers/wasi-shim.mjs';

const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const clangDir = path.join(repoRoot, 'dist', 'clang');

globalThis.self = globalThis;
let toolsReady = null;

function ensureTools() {
toolsReady ||= (async () => {
process.type = 'renderer';
await import(pathToFileURL(path.join(clangDir, 'clang.js')).href);
await import(pathToFileURL(path.join(clangDir, 'lld.js')).href);
})();
return toolsReady;
}

function callMain(module, args) {
try {
return module.callMain(args);
} catch (error) {
if (error?.name === 'ExitStatus') return error.status;
throw error;
}
}

function* tarContents(buffer) {
const data = new Uint8Array(buffer);
const decode = new TextDecoder();
let offset = 0;

while (offset + 512 <= data.length) {
const header = data.slice(offset, offset + 512);
const name = decode.decode(header.slice(0, 100)).replace(/\0.*$/, '');
if (!name) return;
const size = parseInt(decode.decode(header.slice(124, 136)).replace(/\0.*$/, '').trim(), 8) || 0;
yield { name, content: data.slice(offset + 512, offset + 512 + size) };
offset += 512 + Math.ceil(size / 512) * 512;
}
}

const sysroot = fs.readFileSync(path.join(clangDir, 'sysroot.tar'));

function setUpSysroot(module) {
for (const { name, content } of tarContents(sysroot)) {
if (name.endsWith('/')) continue;
const directory = name.split('/').slice(0, -1).join('/');
if (directory && !module.FS.analyzePath(directory).exists) module.FS.mkdirTree(directory);
module.FS.writeFile(name, content);
}
}

async function createTool(factory, wasmName, program, capture) {
return factory({
thisProgram: program,
wasmBinary: fs.readFileSync(path.join(clangDir, wasmName)),
locateFile: (name) => path.join(clangDir, name),
print: capture,
printErr: capture,
});
}

async function compileAndLink(source) {
await ensureTools();
let driverOutput = '';
const driver = await createTool(globalThis.createClangModule, 'clang.wasm', 'clang++', (line) => {
driverOutput += `${line}\n`;
});
driver.FS.writeFile('main.cpp', source);
driver.FS.mkdirTree('/lib/wasm32-wasi');
driver.FS.mkdirTree('/include/c++/v1');
driver.FS.writeFile('/lib/wasm32-wasi/crt1-command.o', new Uint8Array(0));
driver.FS.writeFile('/lib/wasm32-wasi/crt1-reactor.o', new Uint8Array(0));
assert.equal(callMain(driver, ['main.cpp', '-std=c++20', '-Wall', '-Wextra', '-fno-exceptions', '-###']), 0);

const plan = parseCompilePlan(driverOutput);
let compilerOutput = '';
const compiler = await createTool(globalThis.createClangModule, 'clang.wasm', 'clang++', (line) => {
compilerOutput += `${line}\n`;
});
compiler.FS.writeFile('main.cpp', source);
setUpSysroot(compiler);
compiler.FS.mkdirTree('/tmp');
assert.equal(callMain(compiler, plan.compileSteps[0].args), 0, compilerOutput);

let linkerOutput = '';
const linker = await createTool(globalThis.createLLDModule, 'lld.wasm', 'wasm-ld', (line) => {
linkerOutput += `${line}\n`;
});
setUpSysroot(linker);
linker.FS.mkdirTree('/tmp');
linker.FS.writeFile(plan.compileSteps[0].objectPath, compiler.FS.readFile(plan.compileSteps[0].objectPath));

const status = callMain(linker, plan.linkStep.args);
return {
status,
diagnostics: linkerOutput,
output: status === 0 ? linker.FS.readFile(plan.linkStep.outputPath) : null,
};
}

async function run(binary) {
let stdout = '';
const runtime = createWasiRuntime({
stdin: { mode: 'none' },
onStdout: (text) => { stdout += text; },
});
runtime.initRunVfs();
const { instance } = await WebAssembly.instantiate(binary, {
wasi_snapshot_preview1: runtime.wasi,
});
runtime.setMemory(instance.exports.memory);
try {
instance.exports._start();
} catch (error) {
if (!error?.__wasi_exit__) throw error;
assert.equal(error.code, 0);
}
return stdout;
}

test('e2e: stream insertion of defined int and string return values links without C++ exception symbols', async () => {
const result = await compileAndLink(`#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::cout << val() << ' ' << label() << std::endl;
}
`);

assert.equal(result.status, 0, result.diagnostics);
assert.doesNotMatch(result.diagnostics, /undefined symbol: __cxa_/);
assert.match(await run(result.output), /5 stream/);
});

test('e2e: an undefined streamed function reports the user symbol at link time', async () => {
const result = await compileAndLink(`#include <iostream>

int missing();

int main() {
std::cout << missing() << std::endl;
}
`);

assert.notEqual(result.status, 0);
assert.match(result.diagnostics, /undefined symbol: .*missing/);
assert.doesNotMatch(result.diagnostics, /undefined symbol: __cxa_/);
});
50 changes: 47 additions & 3 deletions scripts/smoke-browser.mjs
Original file line numberDiff line numberDiff line change
Expand Up@@ -287,6 +287,33 @@ async function evaluate(cdp, sessionId, expression, { awaitPromise = false } = {
return result.result?.value;
}

async function replaceEditorText(cdp, sessionId, source) {
const focused = await evaluate(
cdp,
sessionId,
`(() => {
const input = document.querySelector('.monaco-editor textarea.inputarea');
if (!input) return false;
input.focus();
return document.activeElement === input;
})()`
);
assert(focused, 'Could not focus the Monaco editor input area');
const selectAllModifier = await evaluate(
cdp,
sessionId,
`navigator.platform.includes('Mac') ? 4 : 2`
);

await cdp.send('Input.dispatchKeyEvent', {
type: 'keyDown', key: 'a', code: 'KeyA', modifiers: selectAllModifier,
}, sessionId);
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyUp', key: 'a', code: 'KeyA', modifiers: selectAllModifier,
}, sessionId);
await cdp.send('Input.insertText', { text: source }, sessionId);
}

async function openExtensionPage(cdp, extensionId) {
const { targetId } = await cdp.send('Target.createTarget', {
url: 'about:blank',
Expand DownExpand Up@@ -708,6 +735,10 @@ async function runHostedSmoke(cdp, { realRun = false } = {}) {
await cdp.send('Runtime.enable', {}, sessionId);
const runtimeProgram = `#include <fstream>
#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::fstream out;
Expand All@@ -718,7 +749,7 @@ int main() {
}
out << "hello from fstream\\n";
out.close();
std::cout << "wrote output.txt\\n";
std::cout << val() << ' ' << label() << " wrote output.txt\\n";
return 0;
}
`;
Expand DownExpand Up@@ -819,6 +850,7 @@ int main() {

const createdFileText = await evaluate(cdp, sessionId, `globalThis.__browserCppTestFs.readText('output.txt')`);
assert(createdFileText === 'hello from fstream\n', `Expected output.txt to be created, got: ${JSON.stringify(createdFileText)}`);
assert(terminalText.includes('5 stream wrote output.txt'), `Expected stream-insertion output, got: ${JSON.stringify(terminalText)}`);

const explorerPath = await waitFor(async () => {
return evaluate(
Expand DownExpand Up@@ -954,13 +986,25 @@ async function runSmoke(cdp, sessionId) {
const hasEditor = await evaluate(cdp, sessionId, `!!document.querySelector('.monaco-editor')`);
assert(hasEditor, 'Monaco editor did not render');

await replaceEditorText(cdp, sessionId, `#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::cout << val() << ' ' << label() << std::endl;
return 0;
}
`);

await evaluate(cdp, sessionId, `document.getElementById('btn-compile-run').click()`);

try {
await waitFor(async () => {
const text = await evaluate(cdp, sessionId, `document.body.textContent || ''`);
return text.includes('Compilation successful.') && text.includes('Hello, World!') ? text : null;
}, 'default C++ compile-and-run output', 120_000);
return text.includes('Compilation successful.') && text.includes('5 stream') ? text : null;
}, 'stream insertion compile-and-run output', 120_000);
} catch (err) {
const status = await evaluate(cdp, sessionId, `document.getElementById('status-compiler')?.textContent || ''`);
const terminalText = await evaluate(cdp, sessionId, `document.getElementById('terminal-container')?.textContent || ''`);
Expand Down
5 changes: 4 additions & 1 deletion src/workers/compiler.worker.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -376,7 +376,10 @@ async function compile(request) {

if (sources.length === 0) return fail('No source files to compile.');

const userFlags = [`-std=${std}`, '-Wall', '-Wextra', ...flags];
// The bundled WASI libc++abi is built without C++ exception support. Clang
// otherwise enables exceptions for C++ sources, producing unresolved
// __cxa_* symbols when stream operations instantiate throwing paths.
const userFlags = [`-std=${std}`, '-Wall', '-Wextra', ...flags, '-fno-exceptions'];

// ── Step 1: Build-plan discovery ─────────────────────────────────────────
let plan;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,6 +23,9 @@ jobs:
- name: Install dependencies
run: npm ci

- name: Fetch Clang WASM artifacts
run: npm run fetch-clang

- name: Verify manifest-driven version sync
run: npm run version:check

Expand All@@ -38,5 +41,8 @@ jobs:
- name: Run end-to-end session tests
run: npm run test:e2e

- name: Run compiler linker end-to-end tests
run: npm run test:e2e:compiler

- name: Run Firefox packaging smoke
run: npm run test:browser:firefox
4 changes: 4 additions & 0 deletions README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -543,6 +543,10 @@ Copy the resulting `clang.js` and `clang.wasm` into `dist/clang/`.
socket support.
- **Standard library**: Only the subset of libc/libc++ compiled into the WASM
sysroot is available.
- **C++ exceptions**: `try`, `catch`, and `throw` are not supported. The bundled
WASI C++ runtime has no exception-unwinding support, so use return values,
error-state checks (such as `stream.fail()`), or other non-throwing error
handling instead.
- **Execution time**: Long-running programs may trigger the browser's "unresponsive
script" dialog. The compiler runs in a dedicated Web Worker to avoid blocking
the UI.
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,7 +3,7 @@
"name": "browser.cpp",
"short_name": "browser.cpp",
"description": "In-browser C++20 IDE powered by Monaco Editor and WASM Clang",
"version": "0.4.5",
"version": "0.4.6",
"minimum_chrome_version": "105",
"icons": {
"16": "icons/icon16.png",
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
{
"name": "browser.cpp",
"version": "0.4.5",
"version": "0.4.6",
"description": "In-browser C++20 IDE with WASM Clang toolchain",
"private": true,
"scripts": {
Expand All@@ -11,8 +11,9 @@
"build": "npm run build:webpack && npm run build:targets",
"build:firefox": "npm run build",
"test:e2e": "node --experimental-detect-module --test scripts/e2e-session-persistence.test.mjs scripts/e2e-session-restore-choice.test.mjs scripts/e2e-multifile-build.test.mjs scripts/e2e-workspace-file-tracking.test.mjs scripts/e2e-terminal-mkdir.test.mjs scripts/e2e-terminal-stop.test.mjs scripts/e2e-terminal-git-removal.test.mjs scripts/e2e-terminal-stop-icon.test.mjs scripts/e2e-browser-compatibility.test.mjs scripts/e2e-firefox-compatibility.test.mjs scripts/e2e-firefox-jspi-stdin.test.mjs scripts/e2e-wasi-shim.test.mjs scripts/e2e-run-request.test.mjs scripts/e2e-release-packaging.test.mjs",
"test:e2e:compiler": "npm run test:preflight-clang && node --experimental-detect-module --test scripts/e2e-compiler-link.test.mjs",
"test:preflight-clang": "node scripts/preflight-clang-artifacts.js",
"test:browser:chrome": "npm run test:preflight-clang && node scripts/smoke-browser.mjs chrome",
"test:browser:chrome": "npm run test:e2e:compiler && node scripts/smoke-browser.mjs chrome",
"test:browser:edge": "npm run test:preflight-clang && node scripts/smoke-browser.mjs edge",
"test:browser:brave": "npm run test:preflight-clang && node scripts/smoke-browser.mjs brave",
"test:browser:chromium": "npm run test:preflight-clang && node scripts/smoke-browser.mjs chromium",
Expand Down
159 changes: 159 additions & 0 deletions scripts/e2e-compiler-link.test.mjs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath, pathToFileURL } from 'node:url';

import { parseCompilePlan } from '../src/workers/compile-plan.mjs';
import { createWasiRuntime } from '../src/workers/wasi-shim.mjs';

const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const clangDir = path.join(repoRoot, 'dist', 'clang');

globalThis.self = globalThis;
let toolsReady = null;

function ensureTools() {
toolsReady ||= (async () => {
process.type = 'renderer';
await import(pathToFileURL(path.join(clangDir, 'clang.js')).href);
await import(pathToFileURL(path.join(clangDir, 'lld.js')).href);
})();
return toolsReady;
}

function callMain(module, args) {
try {
return module.callMain(args);
} catch (error) {
if (error?.name === 'ExitStatus') return error.status;
throw error;
}
}

function* tarContents(buffer) {
const data = new Uint8Array(buffer);
const decode = new TextDecoder();
let offset = 0;

while (offset + 512 <= data.length) {
const header = data.slice(offset, offset + 512);
const name = decode.decode(header.slice(0, 100)).replace(/\0.*$/, '');
if (!name) return;
const size = parseInt(decode.decode(header.slice(124, 136)).replace(/\0.*$/, '').trim(), 8) || 0;
yield { name, content: data.slice(offset + 512, offset + 512 + size) };
offset += 512 + Math.ceil(size / 512) * 512;
}
}

const sysroot = fs.readFileSync(path.join(clangDir, 'sysroot.tar'));

function setUpSysroot(module) {
for (const { name, content } of tarContents(sysroot)) {
if (name.endsWith('/')) continue;
const directory = name.split('/').slice(0, -1).join('/');
if (directory && !module.FS.analyzePath(directory).exists) module.FS.mkdirTree(directory);
module.FS.writeFile(name, content);
}
}

async function createTool(factory, wasmName, program, capture) {
return factory({
thisProgram: program,
wasmBinary: fs.readFileSync(path.join(clangDir, wasmName)),
locateFile: (name) => path.join(clangDir, name),
print: capture,
printErr: capture,
});
}

async function compileAndLink(source) {
await ensureTools();
let driverOutput = '';
const driver = await createTool(globalThis.createClangModule, 'clang.wasm', 'clang++', (line) => {
driverOutput += `${line}\n`;
});
driver.FS.writeFile('main.cpp', source);
driver.FS.mkdirTree('/lib/wasm32-wasi');
driver.FS.mkdirTree('/include/c++/v1');
driver.FS.writeFile('/lib/wasm32-wasi/crt1-command.o', new Uint8Array(0));
driver.FS.writeFile('/lib/wasm32-wasi/crt1-reactor.o', new Uint8Array(0));
assert.equal(callMain(driver, ['main.cpp', '-std=c++20', '-Wall', '-Wextra', '-fno-exceptions', '-###']), 0);

const plan = parseCompilePlan(driverOutput);
let compilerOutput = '';
const compiler = await createTool(globalThis.createClangModule, 'clang.wasm', 'clang++', (line) => {
compilerOutput += `${line}\n`;
});
compiler.FS.writeFile('main.cpp', source);
setUpSysroot(compiler);
compiler.FS.mkdirTree('/tmp');
assert.equal(callMain(compiler, plan.compileSteps[0].args), 0, compilerOutput);

let linkerOutput = '';
const linker = await createTool(globalThis.createLLDModule, 'lld.wasm', 'wasm-ld', (line) => {
linkerOutput += `${line}\n`;
});
setUpSysroot(linker);
linker.FS.mkdirTree('/tmp');
linker.FS.writeFile(plan.compileSteps[0].objectPath, compiler.FS.readFile(plan.compileSteps[0].objectPath));

const status = callMain(linker, plan.linkStep.args);
return {
status,
diagnostics: linkerOutput,
output: status === 0 ? linker.FS.readFile(plan.linkStep.outputPath) : null,
};
}

async function run(binary) {
let stdout = '';
const runtime = createWasiRuntime({
stdin: { mode: 'none' },
onStdout: (text) => { stdout += text; },
});
runtime.initRunVfs();
const { instance } = await WebAssembly.instantiate(binary, {
wasi_snapshot_preview1: runtime.wasi,
});
runtime.setMemory(instance.exports.memory);
try {
instance.exports._start();
} catch (error) {
if (!error?.__wasi_exit__) throw error;
assert.equal(error.code, 0);
}
return stdout;
}

test('e2e: stream insertion of defined int and string return values links without C++ exception symbols', async () => {
const result = await compileAndLink(`#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::cout << val() << ' ' << label() << std::endl;
}
`);

assert.equal(result.status, 0, result.diagnostics);
assert.doesNotMatch(result.diagnostics, /undefined symbol: __cxa_/);
assert.match(await run(result.output), /5 stream/);
});

test('e2e: an undefined streamed function reports the user symbol at link time', async () => {
const result = await compileAndLink(`#include <iostream>

int missing();

int main() {
std::cout << missing() << std::endl;
}
`);

assert.notEqual(result.status, 0);
assert.match(result.diagnostics, /undefined symbol: .*missing/);
assert.doesNotMatch(result.diagnostics, /undefined symbol: __cxa_/);
});
50 changes: 47 additions & 3 deletions scripts/smoke-browser.mjs
Original file line numberDiff line numberDiff line change
Expand Up@@ -287,6 +287,33 @@ async function evaluate(cdp, sessionId, expression, { awaitPromise = false } = {
return result.result?.value;
}

async function replaceEditorText(cdp, sessionId, source) {
const focused = await evaluate(
cdp,
sessionId,
`(() => {
const input = document.querySelector('.monaco-editor textarea.inputarea');
if (!input) return false;
input.focus();
return document.activeElement === input;
})()`
);
assert(focused, 'Could not focus the Monaco editor input area');
const selectAllModifier = await evaluate(
cdp,
sessionId,
`navigator.platform.includes('Mac') ? 4 : 2`
);

await cdp.send('Input.dispatchKeyEvent', {
type: 'keyDown', key: 'a', code: 'KeyA', modifiers: selectAllModifier,
}, sessionId);
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyUp', key: 'a', code: 'KeyA', modifiers: selectAllModifier,
}, sessionId);
await cdp.send('Input.insertText', { text: source }, sessionId);
}

async function openExtensionPage(cdp, extensionId) {
const { targetId } = await cdp.send('Target.createTarget', {
url: 'about:blank',
Expand DownExpand Up@@ -708,6 +735,10 @@ async function runHostedSmoke(cdp, { realRun = false } = {}) {
await cdp.send('Runtime.enable', {}, sessionId);
const runtimeProgram = `#include <fstream>
#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::fstream out;
Expand All@@ -718,7 +749,7 @@ int main() {
}
out << "hello from fstream\\n";
out.close();
std::cout << "wrote output.txt\\n";
std::cout << val() << ' ' << label() << " wrote output.txt\\n";
return 0;
}
`;
Expand DownExpand Up@@ -819,6 +850,7 @@ int main() {

const createdFileText = await evaluate(cdp, sessionId, `globalThis.__browserCppTestFs.readText('output.txt')`);
assert(createdFileText === 'hello from fstream\n', `Expected output.txt to be created, got: ${JSON.stringify(createdFileText)}`);
assert(terminalText.includes('5 stream wrote output.txt'), `Expected stream-insertion output, got: ${JSON.stringify(terminalText)}`);

const explorerPath = await waitFor(async () => {
return evaluate(
Expand DownExpand Up@@ -954,13 +986,25 @@ async function runSmoke(cdp, sessionId) {
const hasEditor = await evaluate(cdp, sessionId, `!!document.querySelector('.monaco-editor')`);
assert(hasEditor, 'Monaco editor did not render');

await replaceEditorText(cdp, sessionId, `#include <iostream>
#include <string>

int val() { return 5; }
std::string label() { return "stream"; }

int main() {
std::cout << val() << ' ' << label() << std::endl;
return 0;
}
`);

await evaluate(cdp, sessionId, `document.getElementById('btn-compile-run').click()`);

try {
await waitFor(async () => {
const text = await evaluate(cdp, sessionId, `document.body.textContent || ''`);
return text.includes('Compilation successful.') && text.includes('Hello, World!') ? text : null;
}, 'default C++ compile-and-run output', 120_000);
return text.includes('Compilation successful.') && text.includes('5 stream') ? text : null;
}, 'stream insertion compile-and-run output', 120_000);
} catch (err) {
const status = await evaluate(cdp, sessionId, `document.getElementById('status-compiler')?.textContent || ''`);
const terminalText = await evaluate(cdp, sessionId, `document.getElementById('terminal-container')?.textContent || ''`);
Expand Down
5 changes: 4 additions & 1 deletion src/workers/compiler.worker.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -376,7 +376,10 @@ async function compile(request) {

if (sources.length === 0) return fail('No source files to compile.');

const userFlags = [`-std=${std}`, '-Wall', '-Wextra', ...flags];
// The bundled WASI libc++abi is built without C++ exception support. Clang
// otherwise enables exceptions for C++ sources, producing unresolved
// __cxa_* symbols when stream operations instantiate throwing paths.
const userFlags = [`-std=${std}`, '-Wall', '-Wextra', ...flags, '-fno-exceptions'];

// ── Step 1: Build-plan discovery ─────────────────────────────────────────
let plan;
Expand Down
Loading