refactor: reformat code for improved readability and consistent style

This commit is contained in:
2026-10-31 01:24:04 +01:00
parent 000baf912d
commit 53945a56df
14 changed files with 477 additions and 97 deletions
+55 -7
View File
@@ -1,12 +1,60 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
import {mkdtemp, mkdir, readFile, readdir, writeFile} from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { build } from '../dist/index.js';
import {build} from '../dist/index.js';
async function fixture(files) { const root = await mkdtemp(path.join(os.tmpdir(), 'iceberg-')); for (const [name, content] of Object.entries(files)) { const file = path.join(root, name); await mkdir(path.dirname(file), { recursive: true }); await writeFile(file, content); } return root; }
async function inRoot(root, fn) { const previous = process.cwd(); process.chdir(root); try { return await fn(); } finally { process.chdir(previous); } }
test('builds JavaScript and CSS and rewrites HTML', async () => { const root = await fixture({ 'index.html': '<!doctype html><head><title>Keep me</title></head><body><script type="module" src="/src/main.js"></script></body>', 'src/main.js': "import './style.css'; document.body.dataset.ready = 'yes';", 'src/style.css': '.unused { color: red } body { color: blue; }' }); await inRoot(root, () => build()); const html = await readFile(path.join(root, 'dist/index.html'), 'utf8'); assert.match(html, /<title>Keep me<\/title>/); assert.match(html, /assets\/main-[^"/]+\.js/); assert.match(html, /assets\/index-[^"/]+\.css/); const assets = await readdir(path.join(root, 'dist/assets')); const css = await readFile(path.join(root, 'dist/assets', assets.find(file => file.endsWith('.css'))), 'utf8'); assert.match(css, /body/); });
test('supports TypeScript and custom output configuration', async () => { const root = await fixture({ 'index.html': '<script type="module" src="/src/main.ts"></script>', 'src/main.ts': 'const answer: number = 42; console.log(answer);', 'iceberg.config.js': "export default { build: { outDir: 'build', minify: false, sourcemap: true } };" }); await inRoot(root, () => build()); const files = await readdir(path.join(root, 'build/assets')); assert.ok(files.some(file => file.endsWith('.js'))); assert.ok(files.some(file => file.endsWith('.js.map'))); const js = await readFile(path.join(root, 'build/assets', files.find(file => file.endsWith('.js'))), 'utf8'); assert.match(js, /42/); assert.doesNotMatch(js, /: number/); });
test('rejects an HTML entry without a module script', async () => { const root = await fixture({ 'index.html': '<h1>No script</h1>' }); await assert.rejects(() => inRoot(root, () => build()), /module script/); });
async function fixture(files) {
const root = await mkdtemp(path.join(os.tmpdir(), 'iceberg-'));
for (const [name, content] of Object.entries(files)) {
const file = path.join(root, name);
await mkdir(path.dirname(file), {recursive: true});
await writeFile(file, content);
}
return root;
}
async function inRoot(root, fn) {
const previous = process.cwd();
process.chdir(root);
try {
return await fn();
} finally {
process.chdir(previous);
}
}
test('builds JavaScript and CSS and rewrites HTML', async () => {
const root = await fixture({
'index.html': '<!doctype html><head><title>Keep me</title></head><body><script type="module" src="/src/main.js"></script></body>',
'src/main.js': "import './style.css'; document.body.dataset.ready = 'yes';",
'src/style.css': '.unused { color: red } body { color: blue; }'
});
await inRoot(root, () => build());
const html = await readFile(path.join(root, 'dist/index.html'), 'utf8');
assert.match(html, /<title>Keep me<\/title>/);
assert.match(html, /assets\/main-[^"/]+\.js/);
assert.match(html, /assets\/index-[^"/]+\.css/);
const assets = await readdir(path.join(root, 'dist/assets'));
const css = await readFile(path.join(root, 'dist/assets', assets.find(file => file.endsWith('.css'))), 'utf8');
assert.match(css, /body/);
});
test('supports TypeScript and custom output configuration', async () => {
const root = await fixture({
'index.html': '<script type="module" src="/src/main.ts"></script>',
'src/main.ts': 'const answer: number = 42; console.log(answer);',
'iceberg.config.js': "export default { build: { outDir: 'build', minify: false, sourcemap: true } };"
});
await inRoot(root, () => build());
const files = await readdir(path.join(root, 'build/assets'));
assert.ok(files.some(file => file.endsWith('.js')));
assert.ok(files.some(file => file.endsWith('.js.map')));
const js = await readFile(path.join(root, 'build/assets', files.find(file => file.endsWith('.js'))), 'utf8');
assert.match(js, /42/);
assert.doesNotMatch(js, /: number/);
});
test('rejects an HTML entry without a module script', async () => {
const root = await fixture({'index.html': '<h1>No script</h1>'});
await assert.rejects(() => inRoot(root, () => build()), /module script/);
});
+93 -14
View File
@@ -1,24 +1,103 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, mkdir, readFile, writeFile } from 'node:fs/promises';
import {mkdtemp, mkdir, readFile, writeFile} from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import WebSocket from 'ws';
import { createServer } from '../dist/index.js';
import {createServer} from '../dist/index.js';
async function fixture() {
const root = await mkdtemp(path.join(os.tmpdir(), 'iceberg-dev-'));
await mkdir(path.join(root, 'src'), { recursive: true }); await mkdir(path.join(root, 'public'), { recursive: true });
await writeFile(path.join(root, 'index.html'), '<!doctype html><html><head><title>Dev</title></head><body><div id="app"></div><script type="module" src="/src/main.ts"></script></body></html>');
await writeFile(path.join(root, 'src/main.ts'), "import './style.css'; import { value } from './value.ts'; import logo from './logo.svg'; document.querySelector('#app').textContent = value + logo;");
await writeFile(path.join(root, 'src/value.ts'), 'export const value: string = "ready";'); await writeFile(path.join(root, 'src/style.css'), 'body { color: blue; }'); await writeFile(path.join(root, 'public/robots.txt'), 'User-agent: *');
await writeFile(path.join(root, 'src/logo.svg'), '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"><path d="M0 0h1v1H0z"/></svg>');
return root;
const root = await mkdtemp(path.join(os.tmpdir(), 'iceberg-dev-'));
await mkdir(path.join(root, 'src'), {recursive: true});
await mkdir(path.join(root, 'public'), {recursive: true});
await writeFile(path.join(root, 'index.html'), '<!doctype html><html><head><title>Dev</title></head><body><div id="app"></div><script type="module" src="/src/main.ts"></script></body></html>');
await writeFile(path.join(root, 'src/main.ts'), "import './style.css'; import { value } from './value.ts'; import logo from './logo.svg'; document.querySelector('#app').textContent = value + logo;");
await writeFile(path.join(root, 'src/value.ts'), 'export const value: string = "ready";');
await writeFile(path.join(root, 'src/style.css'), 'body { color: blue; }');
await writeFile(path.join(root, 'public/robots.txt'), 'User-agent: *');
await writeFile(path.join(root, 'src/logo.svg'), '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"><path d="M0 0h1v1H0z"/></svg>');
return root;
}
async function withServer(fn) { const root = await fixture(); const previous = process.cwd(); process.chdir(root); const server = await createServer({ server: { host: '127.0.0.1', port: 0 } }); try { await server.listen(); return await fn(server, root); } finally { await server.close(); process.chdir(previous); } }
function waitForMessage(socket, predicate) { return new Promise((resolve, reject) => { const timeout = setTimeout(() => reject(new Error('Timed out waiting for WebSocket message')), 3000); socket.on('message', data => { const message = JSON.parse(data.toString()); if (predicate(message)) { clearTimeout(timeout); resolve(message); } }); }); }
test('serves HTML, transformed TypeScript, CSS, public files, and WebSocket reload events', async () => { await withServer(async (server, root) => { const base = server.url; const html = await (await fetch(base)).text(); assert.match(html, /@iceberg\/client\.js/); const js = await (await fetch(`${base}src/main.ts`)).text(); assert.match(js, /@iceberg\/asset-module/); assert.doesNotMatch(js, /: string/); const assetModuleUrl = `${base}${js.match(/\/\@iceberg\/asset-module\?file=[^"']+/)[0].slice(1)}`; assert.match(await (await fetch(assetModuleUrl)).text(), /export default/); const css = await (await fetch(`${base}src/style.css`)).text(); assert.match(css, /color:\s*(blue|#00f)/); assert.equal(await (await fetch(`${base}robots.txt`)).text(), 'User-agent: *'); assert.equal((await fetch(`${base}.env`)).status, 404); const socket = new WebSocket(`${base.replace('http', 'ws')}__iceberg_ws`); const connected = waitForMessage(socket, message => message.type === 'connected'); await new Promise((resolve, reject) => { socket.once('open', resolve); socket.once('error', reject); }); await connected; const reload = waitForMessage(socket, message => message.type === 'reload'); await writeFile(path.join(root, 'src/main.ts'), 'document.body.dataset.changed = "yes";'); await reload; socket.close(); }); });
async function withServer(fn) {
const root = await fixture();
const previous = process.cwd();
process.chdir(root);
const server = await createServer({server: {host: '127.0.0.1', port: 0}});
try {
await server.listen();
return await fn(server, root);
} finally {
await server.close();
process.chdir(previous);
}
}
test('sends CSS updates without requiring a page reload', async () => { await withServer(async (server, root) => { const socket = new WebSocket(`${server.url.replace('http', 'ws')}__iceberg_ws`); const connected = waitForMessage(socket, message => message.type === 'connected'); await new Promise((resolve, reject) => { socket.once('open', resolve); socket.once('error', reject); }); await connected; const updatePromise = waitForMessage(socket, message => message.type === 'css-update'); await writeFile(path.join(root, 'src/style.css'), 'body { color: red; }'); const update = await updatePromise; assert.match(update.path, /src[\\/]style\.css/); socket.close(); }); });
test('falls back to the next port when strictPort is disabled', async () => { await withServer(async (server, root) => { const second = await createServer({ root, server: { host: '127.0.0.1', port: server.port } }); try { await second.listen(); assert.notEqual(second.port, server.port); } finally { await second.close(); } }); });
function waitForMessage(socket, predicate) {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error('Timed out waiting for WebSocket message')), 3000);
socket.on('message', data => {
const message = JSON.parse(data.toString());
if (predicate(message)) {
clearTimeout(timeout);
resolve(message);
}
});
});
}
test('serves HTML, transformed TypeScript, CSS, public files, and WebSocket reload events', async () => {
await withServer(async (server, root) => {
const base = server.url;
const html = await (await fetch(base)).text();
assert.match(html, /@iceberg\/client\.js/);
const js = await (await fetch(`${base}src/main.ts`)).text();
assert.match(js, /@iceberg\/asset-module/);
assert.doesNotMatch(js, /: string/);
const assetModuleUrl = `${base}${js.match(/\/\@iceberg\/asset-module\?file=[^"']+/)[0].slice(1)}`;
assert.match(await (await fetch(assetModuleUrl)).text(), /export default/);
const css = await (await fetch(`${base}src/style.css`)).text();
assert.match(css, /color:\s*(blue|#00f)/);
assert.equal(await (await fetch(`${base}robots.txt`)).text(), 'User-agent: *');
assert.equal((await fetch(`${base}.env`)).status, 404);
const socket = new WebSocket(`${base.replace('http', 'ws')}__iceberg_ws`);
const connected = waitForMessage(socket, message => message.type === 'connected');
await new Promise((resolve, reject) => {
socket.once('open', resolve);
socket.once('error', reject);
});
await connected;
const reload = waitForMessage(socket, message => message.type === 'reload');
await writeFile(path.join(root, 'src/main.ts'), 'document.body.dataset.changed = "yes";');
await reload;
socket.close();
});
});
test('sends CSS updates without requiring a page reload', async () => {
await withServer(async (server, root) => {
const socket = new WebSocket(`${server.url.replace('http', 'ws')}__iceberg_ws`);
const connected = waitForMessage(socket, message => message.type === 'connected');
await new Promise((resolve, reject) => {
socket.once('open', resolve);
socket.once('error', reject);
});
await connected;
const updatePromise = waitForMessage(socket, message => message.type === 'css-update');
await writeFile(path.join(root, 'src/style.css'), 'body { color: red; }');
const update = await updatePromise;
assert.match(update.path, /src[\\/]style\.css/);
socket.close();
});
});
test('falls back to the next port when strictPort is disabled', async () => {
await withServer(async (server, root) => {
const second = await createServer({root, server: {host: '127.0.0.1', port: server.port}});
try {
await second.listen();
assert.notEqual(second.port, server.port);
} finally {
await second.close();
}
});
});