Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOURCE FILE4 * =============================================================================5 * Project : MacLustr LLM API6 * File : web/assets/site/highlight.js7 * Author : Simon-Pierre Boucher | https://spboucher.ai8 * Contact : admin@spboucher.ai9 * Copyright : (c) 2026 Simon-Pierre Boucher10 * License : None specified (no license file in this repository)11 * =============================================================================12 * END OF SP BOUCHER SOURCE HEADER13 * =============================================================================14 */1516// Tiny dependency-free syntax highlighter. Output is HTML built only from escaped source text.17import { esc } from "/assets/site/core.js";1819const kw = (s) => new Set(s.split(" "));2021const DQ = `"(?:\\\\.|[^"\\\\\\n])*"`;22const SQ = `'(?:\\\\.|[^'\\\\\\n])*'`;23const NUM = `\\b\\d[\\d_]*(?:\\.\\d+)?(?:[eE][+-]?\\d+)?\\b`;24const IDENT = `[A-Za-z_$][\\w$]*`;2526const LANG = {27 python: {28 comment: `#[^\\n]*`,29 string: `[fFrRbB]{0,2}"""[\\s\\S]*?"""|[fFrRbB]{0,2}${DQ}|[fFrRbB]{0,2}${SQ}`,30 keywords: kw("import from as def class return if elif else for while in not and or is None True False try except finally raise with async await lambda pass break continue yield global del assert"),31 },32 typescript: {33 comment: `//[^\\n]*|/\\*[\\s\\S]*?\\*/`,34 string: "`(?:\\\\.|[^`\\\\])*`|" + DQ + "|" + SQ,35 keywords: kw("import from export default const let var function return if else for while of in new await async try catch finally throw class extends interface type as typeof instanceof null undefined true false break continue switch case this void"),36 },37 swift: {38 comment: `//[^\\n]*|/\\*[\\s\\S]*?\\*/`,39 string: `"""[\\s\\S]*?"""|${DQ}`,40 keywords: kw("import let var func return if else guard for while in do try catch throw throws rethrows async await struct class enum actor protocol extension case switch default break continue nil true false self Self init static private public internal fileprivate final defer where as is some any typealias mutating"),41 },42 bash: {43 comment: `(?:^|(?<=\\s))#[^\\n]*`,44 string: `${DQ}|'[^']*'`,45 keywords: kw("curl export echo if then else fi for do done while in"),46 extra: `(?<=\\s)--?[A-Za-z][\\w-]*|\\$\\{?[A-Za-z_]\\w*\\}?`,47 },48 json: { comment: null, string: DQ, keywords: kw("true false null") },49};50LANG.javascript = LANG.typescript;5152const cache = new Map();53function matcher(def) {54 if (cache.has(def)) return cache.get(def);55 const parts = [56 def.comment ? `(${def.comment})` : `((?!))`,57 `(${def.string})`,58 def.extra ? `(${def.extra})` : `((?!))`,59 `(${NUM})`,60 `(${IDENT})`,61 `([{}()\\[\\];,.:=<>+\\-*/!?&|\\\\@]+)`,62 ];63 const re = new RegExp(parts.join("|"), "gm");64 cache.set(def, re);65 return re;66}6768function span(cls, text) { return `<span class="tok-${cls}">${esc(text)}</span>`; }6970function generic(code, def, isJson) {71 const re = matcher(def);72 re.lastIndex = 0;73 let out = "";74 let last = 0;75 let m;76 while ((m = re.exec(code)) !== null) {77 if (m[0] === "") { re.lastIndex++; continue; }78 out += esc(code.slice(last, m.index));79 last = m.index + m[0].length;80 const rest = code.slice(last);81 if (m[1] !== undefined) out += span("c", m[1]);82 else if (m[2] !== undefined) out += span(isJson && /^\s*:/.test(rest) ? "f" : "s", m[2]);83 else if (m[3] !== undefined) out += span(m[3][0] === "$" ? "n" : "k", m[3]);84 else if (m[4] !== undefined) out += span("n", m[4]);85 else if (m[5] !== undefined) {86 if (def.keywords.has(m[5])) out += span("k", m[5]);87 else if (!isJson && /^\(/.test(rest)) out += span("f", m[5]);88 else if (!isJson && /^[A-Z]/.test(m[5]) && def !== LANG.bash) out += span("f", m[5]);89 else out += esc(m[5]);90 } else out += span("p", m[0]);91 }92 return out + esc(code.slice(last));93}9495// Server-sent events and raw HTTP exchanges: highlight per line.96function lines(code, fn) { return code.split("\n").map(fn).join("\n"); }9798function sse(code) {99 return lines(code, (line) => {100 if (line.startsWith(":")) return span("c", line);101 const m = /^(data|event|id|retry)(:\s?)(.*)$/.exec(line);102 if (!m) return esc(line);103 const payload = m[3].startsWith("{") ? generic(m[3], LANG.json, true) : span("n", m[3]);104 return span("k", m[1]) + span("p", m[2]) + payload;105 });106}107108function http(code) {109 let body = false;110 return lines(code, (line) => {111 if (body) return /^\s*[{}\[\]"]/.test(line) ? generic(line, LANG.json, true) : esc(line);112 if (line === "") { body = true; return ""; }113 if (/^(HTTP\/[\d.]+ \d+|(GET|POST|PUT|PATCH|DELETE|OPTIONS) )/.test(line)) return span("k", line);114 const m = /^([\w-]+)(:\s*)(.*)$/.exec(line);115 return m ? span("f", m[1]) + span("p", m[2]) + span("s", m[3]) : esc(line);116 });117}118119export function highlight(code, lang) {120 try {121 if (lang === "sse") return sse(code);122 if (lang === "http") return http(code);123 const def = LANG[lang];124 if (!def) return esc(code);125 return generic(code, def, lang === "json");126 } catch {127 return esc(code);128 }129}130