feat: implement phase one iceberg build tool

This commit is contained in:
2026-10-31 00:31:06 +01:00
commit af89662161
25 changed files with 949 additions and 0 deletions
+11
View File
@@ -0,0 +1,11 @@
import path from 'node:path';
import { mkdir, readdir, rm, writeFile } from 'node:fs/promises';
import { bundleCss, bundleJavaScript } from './rolldown.js';
import { loadConfig, type IcebergConfig } from '../core/config.js';
import { readHtmlEntry, rewriteHtml } from '../core/html.js';
import { logger } from '../core/logger.js';
export interface BuildResult { root: string; outDir: string; files: string[]; duration: number; }
export async function build(inlineConfig?: IcebergConfig): Promise<BuildResult> { const started = Date.now(); const config = await loadConfig(process.cwd(), inlineConfig); const outDir = path.resolve(config.root, config.build.outDir); const { html, entry } = await readHtmlEntry(config.root); if (config.build.emptyOutDir) await emptyDirectory(outDir); await mkdir(outDir, { recursive: true }); const jsResult = await bundleJavaScript(config, resolveHtmlPath(config.root, entry.script)); const linkedCssFiles: string[] = []; for (const style of entry.styles) { const result = await bundleCss(resolveHtmlPath(config.root, style), config); const target = path.join(outDir, result.fileName); await mkdir(path.dirname(target), { recursive: true }); await writeFile(target, result.code); linkedCssFiles.push(result.fileName); } await writeFile(path.join(outDir, 'index.html'), rewriteHtml(html, jsResult.jsFile, jsResult.cssFiles, linkedCssFiles, config.base)); const files = await listFiles(outDir); logger.info(`built ${files.length} files in ${Date.now() - started}ms`); return { root: config.root, outDir, files, duration: Date.now() - started }; }
function resolveHtmlPath(root: string, value: string) { if (value.startsWith('/')) return path.resolve(root, value.slice(1)); if (/^https?:\/\//.test(value)) throw new Error(`Remote asset is not supported: ${value}`); return path.resolve(root, value); }
async function emptyDirectory(dir: string) { await mkdir(dir, { recursive: true }); for (const item of await readdir(dir)) await rm(path.join(dir, item), { recursive: true, force: true }); }
async function listFiles(dir: string, prefix = ''): Promise<string[]> { const result: string[] = []; for (const entry of await readdir(dir, { withFileTypes: true })) { const relative = path.join(prefix, entry.name); if (entry.isDirectory()) result.push(...await listFiles(path.join(dir, entry.name), relative)); else result.push(relative); } return result; }
+16
View File
@@ -0,0 +1,16 @@
import path from 'node:path';
import { readFile } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import { rolldown, type Plugin, type RolldownOutput } from 'rolldown';
import { bundleAsync } from 'lightningcss';
import type { ResolvedIcebergConfig } from '../core/config.js';
const cssExtensions = /\.css$/i; const assetExtensions = /\.(png|jpe?g|gif|svg|webp|avif|woff2?|ttf|otf|ico)$/i;
export interface BundleResult { output: RolldownOutput; jsFile: string; cssFiles: string[]; }
export async function bundleJavaScript(config: ResolvedIcebergConfig, input: string): Promise<BundleResult> {
let css = ''; const cssFiles: string[] = [];
const virtualFiles = new Map<string, { kind: 'css' | 'asset'; file: string }>();
const plugin: Plugin = { name: 'iceberg-css-and-assets', async resolveId(source, importer) { const resolved = importer ? await this.resolve(source, importer, { skipSelf: true }) : null; const file = resolved?.id ?? ((cssExtensions.test(source) || assetExtensions.test(source)) ? path.resolve(config.root, source) : null); if (!file || (!cssExtensions.test(file) && !assetExtensions.test(file))) return null; const kind = cssExtensions.test(file) ? 'css' : 'asset'; const virtual = `\0iceberg-${kind}:${virtualFiles.size}`; virtualFiles.set(virtual, { kind, file }); return virtual; }, async load(id) { const virtual = virtualFiles.get(id); if (!virtual) return null; if (virtual.kind === 'css') { const result = await bundleAsync({ filename: virtual.file, minify: config.build.minify, sourceMap: config.build.sourcemap }); css += Buffer.from(result.code).toString('utf8') + '\n'; return 'export default undefined;'; } const reference = this.emitFile({ type: 'asset', name: path.basename(virtual.file), source: await readFile(virtual.file) }); return `export default import.meta.ROLLUP_FILE_URL_${reference};`; }, generateBundle() { if (css) { const hash = createHash('sha256').update(css).digest('hex').slice(0, 8); const fileName = `assets/index-${hash}.css`; this.emitFile({ type: 'asset', fileName, source: css }); cssFiles.push(fileName); } } };
const bundle = await rolldown({ input, plugins: [plugin], treeshake: true, moduleTypes: { '.ts': 'ts', '.tsx': 'tsx', '.jsx': 'jsx', '.json': 'json' } });
try { const output = await bundle.write({ dir: config.build.outDir, format: 'esm', sourcemap: config.build.sourcemap, minify: config.build.minify, entryFileNames: 'assets/[name]-[hash].js', chunkFileNames: 'assets/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]' }); const jsChunk = output.output.find(item => item.type === 'chunk' && item.isEntry); if (!jsChunk) throw new Error('Rolldown did not produce an entry chunk.'); return { output, jsFile: jsChunk.fileName, cssFiles }; } finally { await bundle.close(); }
}
export async function bundleCss(file: string, config: ResolvedIcebergConfig) { const result = await bundleAsync({ filename: file, minify: config.build.minify, sourceMap: config.build.sourcemap }); return { fileName: `assets/${path.basename(file, '.css')}.css`, code: Buffer.from(result.code).toString('utf8') }; }
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env node
import { build } from '../index.js';
import { logger } from '../core/logger.js';
const args = process.argv.slice(2);
if (args.includes('--help') || args.length === 0) { console.log('Usage: iceberg build\n\nCommands:\n build Build index.html and its module graph\n\nOptions:\n --help Show this help\n --version Show the installed version'); process.exit(0); }
if (args.includes('--version')) { const packageJson = await import('../../package.json', { with: { type: 'json' } }); console.log(packageJson.default.version); process.exit(0); }
if (args[0] !== 'build' || args.length > 1) { logger.error('Unknown command. Only `iceberg build` is implemented in Phase 1.'); process.exit(1); }
try { await build(); } catch (error) { logger.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; }
+20
View File
@@ -0,0 +1,20 @@
import { access } from 'node:fs/promises';
import path from 'node:path';
export interface IcebergBuildOptions { outDir?: string; minify?: boolean; sourcemap?: boolean; emptyOutDir?: boolean; }
export interface IcebergConfig { root?: string; base?: string; build?: IcebergBuildOptions; }
export interface ResolvedIcebergConfig { root: string; base: string; build: Required<IcebergBuildOptions>; }
export function defineConfig(config: IcebergConfig): IcebergConfig { return config; }
export async function loadConfig(cwd: string, inline?: IcebergConfig): Promise<ResolvedIcebergConfig> {
const configPath = path.join(cwd, 'iceberg.config.js'); let fileConfig: IcebergConfig = {};
try { await access(configPath); const loaded = await import(`${new URL(`file://${configPath.replace(/\\/g, '/')}`).href}?t=${Date.now()}`); fileConfig = loaded.default ?? loaded; }
catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
const merged = { ...fileConfig, ...inline, build: { ...fileConfig.build, ...inline?.build } };
const root = path.resolve(cwd, merged.root ?? '.');
const build = { outDir: merged.build?.outDir ?? 'dist', minify: merged.build?.minify ?? true, sourcemap: merged.build?.sourcemap ?? false, emptyOutDir: merged.build?.emptyOutDir ?? true };
if (merged.base !== undefined && typeof merged.base !== 'string') throw new Error('Iceberg config: base must be a string.');
if (typeof build.outDir !== 'string' || !build.outDir) throw new Error('Iceberg config: build.outDir must be a non-empty string.');
for (const key of ['minify', 'sourcemap', 'emptyOutDir'] as const) if (typeof build[key] !== 'boolean') throw new Error(`Iceberg config: build.${key} must be a boolean.`);
return { root, base: normalizeBase(merged.base ?? '/'), build };
}
function normalizeBase(base: string) { const normalized = base.replace(/\\/g, '/'); return `/${normalized.replace(/^\/+|\/+$/g, '')}/`.replace(/^\/\/$/, '/'); }
+1
View File
@@ -0,0 +1 @@
export class IcebergError extends Error { constructor(message: string, options?: { cause?: unknown }) { super(message, options); this.name = 'IcebergError'; } }
+27
View File
@@ -0,0 +1,27 @@
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { parse, serialize } from 'parse5';
import { IcebergError } from './errors.js';
type Node = { nodeName?: string; tagName?: string; attrs?: Array<{ name: string; value: string }>; childNodes?: Node[]; parentNode?: Node };
export interface HtmlEntry { file: string; script: string; styles: string[]; }
export async function readHtmlEntry(root: string): Promise<{ html: string; entry: HtmlEntry }> {
const htmlFile = path.join(root, 'index.html'); let html: string;
try { html = await readFile(htmlFile, 'utf8'); } catch { throw new IcebergError(`Could not find HTML entry point: ${htmlFile}`); }
const document = parse(html) as unknown as Node; const scripts: string[] = []; const styles: string[] = [];
walk(document, node => { if (node.tagName === 'script') { const type = attr(node, 'type'); const src = attr(node, 'src'); if (src && (!type || type === 'module')) scripts.push(src); else if (src && type !== 'module') throw new IcebergError(`Unsupported script type in ${htmlFile}: ${type}`); } if (node.tagName === 'link' && attr(node, 'rel')?.toLowerCase() === 'stylesheet') { const href = attr(node, 'href'); if (href) styles.push(href); } });
if (!scripts.length) throw new IcebergError('index.html must contain a module script with a src attribute.');
if (scripts.length > 1) throw new IcebergError('Phase 1 supports one module script entry in index.html.');
if (/^https?:\/\//.test(scripts[0]!)) throw new IcebergError('Remote module scripts are not supported.');
return { html, entry: { file: htmlFile, script: scripts[0]!, styles } };
}
export function rewriteHtml(html: string, jsFile: string, importedCssFiles: string[], linkedCssFiles: string[], base: string): string {
const document = parse(html) as unknown as Node; let linkedIndex = 0;
walk(document, node => { if (node.tagName === 'script' && attr(node, 'src')) setAttr(node, 'src', joinBase(base, jsFile)); if (node.tagName === 'link' && attr(node, 'rel')?.toLowerCase() === 'stylesheet') { const replacement = linkedCssFiles[linkedIndex++]; if (replacement) setAttr(node, 'href', joinBase(base, replacement)); } });
const head = find(document, 'head'); if (head) for (const css of importedCssFiles) head.childNodes!.push({ nodeName: 'link', tagName: 'link', attrs: [{ name: 'rel', value: 'stylesheet' }, { name: 'href', value: joinBase(base, css) }], childNodes: [], parentNode: head });
return serialize(document as any);
}
function walk(node: Node, visit: (node: Node) => void) { visit(node); for (const child of node.childNodes ?? []) { child.parentNode = node; walk(child, visit); } }
function find(node: Node, tag: string): Node | undefined { if (node.tagName === tag) return node; for (const child of node.childNodes ?? []) { const found = find(child, tag); if (found) return found; } }
function attr(node: Node, name: string) { return node.attrs?.find(item => item.name === name)?.value; }
function setAttr(node: Node, name: string, value: string) { const found = node.attrs?.find(item => item.name === name); if (found) found.value = value; else node.attrs?.push({ name, value }); }
function joinBase(base: string, file: string) { return `${base.replace(/\/$/, '')}/${file.replace(/^\//, '')}`; }
+1
View File
@@ -0,0 +1 @@
export const logger = { info: (message: string) => console.log(`[iceberg] ${message}`), error: (message: string) => console.error(`[iceberg] ${message}`) };
+4
View File
@@ -0,0 +1,4 @@
export { build } from './bundler/index.js';
export { defineConfig } from './core/config.js';
export type { BuildResult } from './bundler/index.js';
export type { IcebergConfig, IcebergBuildOptions, ResolvedIcebergConfig } from './core/config.js';