Files
Iceberg/src/core/html.ts
T

97 lines
3.6 KiB
TypeScript

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(/^\//, '')}`;
}