rob-revisited/ide/ui/js/http-preview-model.js

80 lines
4 KiB
JavaScript

// The HTTP Client's response preview, pure parts (no DOM, tested with node --test): a link resolved against the response's
// address, what a stylesheet refers to (@import, url()), the stylesheet rewritten with what was fetched.
const MIME = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', avif: 'image/avif', bmp: 'image/bmp',
ico: 'image/x-icon', svg: 'image/svg+xml', woff: 'font/woff', woff2: 'font/woff2', ttf: 'font/ttf', otf: 'font/otf', eot: 'application/vnd.ms-fontobject',
mp4: 'video/mp4', webm: 'video/webm', mp3: 'audio/mpeg', ogg: 'audio/ogg', wav: 'audio/wav', css: 'text/css', js: 'text/javascript' };
/** the mime type of an answer: its Content-Type when it is a usable one, else the address's extension */
export function mimeOfAnswer(type, url) {
const t = String(type || '').split(';')[0].trim().toLowerCase();
if (t && t !== 'application/octet-stream' && t !== 'text/plain' && t !== 'text/html') return t;
const ext = (String(url).split(/[?#]/)[0].split('.').pop() || '').toLowerCase();
return MIME[ext] || t || 'application/octet-stream';
}
/** a link of the page or of a stylesheet -> its absolute http(s) address (hash dropped), or null (data:, #anchor, javascript:, mailto:...) */
export function resolveUrl(base, link) {
const l = String(link ?? '').trim();
if (!l || l.startsWith('#') || /^(data|javascript|mailto|tel|about|blob):/i.test(l)) return null;
try {
const u = new URL(l, base);
if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;
u.hash = '';
return u.href;
} catch { return null; }
}
/** the candidates of a srcset: [{url, rest}] */
export function srcsetParts(srcset) {
return String(srcset || '').split(',').map((c) => c.trim()).filter(Boolean).map((c) => { const [url, ...rest] = c.split(/\s+/); return { url, rest: rest.join(' ') }; });
}
const IMPORT = /@import\s+(?:url\(\s*)?(['"]?)([^'")\s;]+)\1\s*\)?([^;]*);/gi;
const URL_FN = /url\(\s*(['"]?)([^'")]+)\1\s*\)/gi;
/** what a stylesheet refers to: @import (url, media, raw text) and url(...) (url, raw text), in order */
export function cssRefs(text) {
const src = String(text || '');
const imports = [...src.matchAll(IMPORT)].map((m) => ({ raw: m[0], url: m[2], media: m[3].trim() }));
const rest = src.replace(IMPORT, '');
const urls = [...rest.matchAll(URL_FN)].map((m) => ({ raw: m[0], url: m[2] }));
return { imports, urls };
}
/**
* The stylesheet with its @import replaced by the imported text and its url(...) by data: URLs.
* @param {string} text
* @param {string} base address of the stylesheet
* @param {(absoluteUrl: string, kind: 'import'|'asset') => ?string} lookup the fetched text (import) or data: URL (asset), null when missing
* @param {(absoluteUrl: string, why: string) => void} [fail]
* @param {number} [depth]
*/
export function rewriteCss(text, base, lookup, fail = () => {}, depth = 0) {
let out = String(text || '');
for (const imp of cssRefs(out).imports) {
const abs = resolveUrl(base, imp.url);
let body = '';
if (abs && depth < 4) {
const inner = lookup(abs, 'import');
if (inner === null || inner === undefined) { fail(abs, 'not loaded'); body = `/* ${abs}: not loaded */`; }
else body = rewriteCss(inner, abs, lookup, fail, depth + 1);
} else if (abs) body = `/* ${abs}: too deep */`;
else body = '';
out = out.replace(imp.raw, imp.media ? `@media ${imp.media} {\n${body}\n}` : body);
}
for (const ref of cssRefs(out).urls) {
const abs = resolveUrl(base, ref.url);
if (!abs) continue;
const data = lookup(abs, 'asset');
if (data) out = out.split(ref.raw).join(`url("${data}")`);
else fail(abs, 'not loaded');
}
return out;
}
/** the addresses to fetch next for stylesheets whose text is known: their @import and url() (absolute, deduplicated) */
export function cssNeeds(text, base) {
const { imports, urls } = cssRefs(text);
return [...new Set([...imports, ...urls].map((r) => resolveUrl(base, r.url)).filter(Boolean))];
}