#!/usr/bin/env node // ───────────────────────────────────────────────────────────────────────────── // Livtec / AIDO white-label overlay for Onyx Community Edition. // // Applies all branding to a clean upstream Onyx checkout, driven entirely by // branding/branding.config.json. Re-runnable and deterministic: to upgrade Onyx, // check out the new upstream tag into ./onyx and run this script again, then // rebuild the web image. // // Usage: node branding/apply-branding.mjs [--dry-run] [--no-fetch] // // CE-ONLY: this rebrands at the open-source default level (the `|| "Onyx"` // fallbacks, hardcoded strings, logo components and favicon). It does NOT enable // or depend on Onyx's Enterprise white-label feature (enterprise-settings). // ───────────────────────────────────────────────────────────────────────────── import { readFile, writeFile, copyFile, mkdir, readdir, stat } from "node:fs/promises"; import { existsSync } from "node:fs"; import { fileURLToPath } from "node:url"; import path from "node:path"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT = path.resolve(__dirname, ".."); // project root const BRANDING = __dirname; // branding/ const CONFIG = JSON.parse(await readFile(path.join(BRANDING, "branding.config.json"), "utf8")); const argv = process.argv.slice(2); const DRY = argv.includes("--dry-run"); const NO_FETCH = argv.includes("--no-fetch"); const WEB = path.join(ROOT, CONFIG.upstream.webSrcRoot); // onyx/web const PUBLIC = path.join(WEB, "public"); const PUBLIC_BRANDING = path.join(PUBLIC, "branding"); const SRC = path.join(WEB, "src"); const OPAL_LOGOS = path.join(WEB, "lib/opal/src/logos"); const OPAL_ICONS = path.join(WEB, "lib/opal/src/icons"); const c = { gray: "\x1b[90m", green: "\x1b[32m", yellow: "\x1b[33m", red: "\x1b[31m", bold: "\x1b[1m", reset: "\x1b[0m" }; const log = (m) => console.log(m); const ok = (m) => log(`${c.green}✓${c.reset} ${m}`); const warn = (m) => log(`${c.yellow}!${c.reset} ${m}`); const step = (m) => log(`\n${c.bold}${m}${c.reset}`); let filesChanged = 0; let totalReplacements = 0; if (!existsSync(WEB)) { console.error(`${c.red}✗ Onyx web source not found at ${WEB}. Clone/checkout Onyx into ./onyx first.${c.reset}`); process.exit(1); } log(`${c.bold}Livtec white-label → ${CONFIG.brand.name}${c.reset} ${c.gray}(${DRY ? "dry-run" : "apply"}${NO_FETCH ? ", no-fetch" : ""})${c.reset}`); log(`${c.gray}web source: ${WEB}${c.reset}`); // ── 1. Assets: fetch brand images, repoint favicon ────────────────────────── step("1/4 Assets"); if (!DRY) await mkdir(PUBLIC_BRANDING, { recursive: true }); async function placeAsset(key) { const a = CONFIG.assets[key]; const destPublic = path.join(PUBLIC, a.dest); // onyx/web/public/branding/ const cache = path.join(BRANDING, "assets", path.basename(a.dest)); if (!NO_FETCH) { try { const res = await fetch(a.url, { signal: AbortSignal.timeout(20000) }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const buf = Buffer.from(await res.arrayBuffer()); if (buf.length < 100) throw new Error("suspiciously small"); if (!DRY) { await writeFile(destPublic, buf); await writeFile(cache, buf); // refresh offline fallback } ok(`${key}: fetched ${buf.length}b → public/${a.dest}`); return; } catch (e) { warn(`${key}: fetch failed (${e.message}); trying committed fallback`); } } if (existsSync(cache)) { if (!DRY) await copyFile(cache, destPublic); ok(`${key}: copied committed fallback → public/${a.dest}`); } else { warn(`${key}: NO asset available (no network + no fallback in branding/assets/). Drop a file at ${cache} and re-run.`); } } for (const key of Object.keys(CONFIG.assets)) { if (key.startsWith("$")) continue; await placeAsset(key); } // Repoint the default favicon: overwrite /onyx.ico so even un-patched refs work, // and update DynamicMetadata's fallback to the branded PNG. const favSrc = path.join(PUBLIC, CONFIG.assets.favicon.dest); if (existsSync(favSrc) && !DRY) { await copyFile(favSrc, path.join(PUBLIC, "onyx.ico")); ok("favicon: overwrote public/onyx.ico with branded icon"); } // ── 2. Logo components ────────────────────────────────────────────────────── step("2/4 Logo components"); const MARK_SRC = "/" + CONFIG.assets.mark.dest; const WORDMARK_SRC = "/" + CONFIG.assets.wordmark.dest; function fillTemplate(tpl) { return tpl .replaceAll("__BRAND_NAME__", CONFIG.brand.name) .replaceAll("__MARK_SRC__", MARK_SRC) .replaceAll("__WORDMARK_SRC__", WORDMARK_SRC); } const logoInstalls = [ ["onyx-logo.tsx", path.join(OPAL_LOGOS, "onyx-logo.tsx")], ["onyx-typed.tsx", path.join(OPAL_LOGOS, "onyx-typed.tsx")], ["onyx-logo-typed.tsx", path.join(OPAL_LOGOS, "onyx-logo-typed.tsx")], ["onyx-logo.tsx", path.join(OPAL_ICONS, "onyx-logo.tsx")], // 16px icon → brand mark ]; for (const [tplName, dest] of logoInstalls) { if (!existsSync(dest)) { warn(`logo target missing (upstream moved it?): ${path.relative(WEB, dest)}`); continue; } const filled = fillTemplate(await readFile(path.join(BRANDING, "templates", tplName), "utf8")); if (!DRY) await writeFile(dest, filled); ok(`installed ${tplName} → ${path.relative(WEB, dest)}`); } // ── 2b. Targeted source patches ───────────────────────────────────────────── // Surgical, anchored edits for branding that the bulk string codemod can't reach: // an inline SVG wordmark, and backend-generated notification content that is only // rebrandable at render time in the web image. Each patch warns (does not fail) if // its anchor is missing after an upstream change — same maintenance model as logos. step("2b/4 Targeted patches"); async function patchFile(rel, edits) { const fp = path.join(SRC, rel); if (!existsSync(fp)) { warn(`patch target missing (upstream moved it?): ${rel}`); return; } let src = await readFile(fp, "utf8"); let applied = 0; for (const e of edits) { if (e.done && src.includes(e.done)) { applied++; continue; } // idempotent: already patched const present = e.find instanceof RegExp ? e.find.test(src) : src.includes(e.find); if (!present) { warn(`anchor not found in ${rel}: ${e.desc}`); continue; } src = e.find instanceof RegExp ? src.replace(e.find, e.replace) : src.split(e.find).join(e.replace); applied++; } if (applied && !DRY) await writeFile(fp, src); if (applied) ok(`patched ${rel} (${applied}/${edits.length} edit(s))`); } // (a) Error page / craft wordmark: inline SVG → AIDO image asset. const onyxTypeIcon = fillTemplate(await readFile(path.join(BRANDING, "templates", "icons-OnyxLogoTypeIcon.tsx"), "utf8")); await patchFile("components/icons/icons.tsx", [{ desc: "OnyxLogoTypeIcon inline SVG wordmark", find: /export const OnyxLogoTypeIcon = \(\{[\s\S]*?\n\};\n/, replace: onyxTypeIcon.endsWith("\n") ? onyxTypeIcon : onyxTypeIcon + "\n", }]); // (b) Notifications: their text is generated by the backend (official image we do // NOT rebuild), so rebrand/suppress it at render time. Generate a tiny runtime // helper from config, then route the notifications list through it. const N = CONFIG.notifications ?? { sanitize: true, suppressTypes: [] }; const runtime = `// AUTO-GENERATED by branding/apply-branding.mjs — do not edit by hand. // Runtime rebranding for backend-generated content (notification bell) that the // build-time codemod cannot reach. Driven by branding.config.json → notifications. const WORD_PAIRS: [string, string][] = ${JSON.stringify(Object.entries(CONFIG.rename.word))}; const SANITIZE = ${N.sanitize ? "true" : "false"}; const SUPPRESS_TYPES = new Set(${JSON.stringify(N.suppressTypes ?? [])}); export function brandText(text: T): T { if (!text || !SANITIZE) return text; let out: string = text; for (const [from, to] of WORD_PAIRS) { out = out.replace(new RegExp(\`\\\\b\${from}\\\\b\`, "g"), to); } return out as T; } export function filterBrandedNotifications< N extends { notif_type: string; title: string; description: string | null }, >(list: N[]): N[] { return list .filter((n) => !SUPPRESS_TYPES.has(n.notif_type)) .map((n) => ({ ...n, title: brandText(n.title), description: brandText(n.description) })); } `; if (!DRY) await writeFile(path.join(SRC, "lib/branding-runtime.ts"), runtime); ok(`generated lib/branding-runtime.ts (sanitize=${!!N.sanitize}, suppress=${(N.suppressTypes ?? []).length})`); await patchFile("hooks/useNotifications.ts", [ { desc: "import branding runtime", done: `import { filterBrandedNotifications } from "@/lib/branding-runtime";`, find: `import { useCallback, useMemo, useRef } from "react";`, replace: `import { useCallback, useMemo, useRef } from "react";\nimport { filterBrandedNotifications } from "@/lib/branding-runtime";`, }, { desc: "route notifications list through branding filter", done: `return filterBrandedNotifications(`, find: ` return data.flatMap((page) =>\n page.notifications.filter((notification) => {\n if (seenNotificationIds.has(notification.id)) {\n return false;\n }\n seenNotificationIds.add(notification.id);\n return true;\n })\n );`, replace: ` return filterBrandedNotifications(\n data.flatMap((page) =>\n page.notifications.filter((notification) => {\n if (seenNotificationIds.has(notification.id)) {\n return false;\n }\n seenNotificationIds.add(notification.id);\n return true;\n })\n )\n );`, }, ]); // ── 3. String codemod (user-visible references) ───────────────────────────── step("3/4 String codemod"); const literals = Object.entries(CONFIG.rename.literals); const wordPairs = Object.entries(CONFIG.rename.word); const ASSET_PATH_EDITS = [["/onyx.ico", `/${CONFIG.assets.favicon.dest}`]]; // favicon ref in DynamicMetadata const SKIP = /(\.test\.|\.spec\.|\.stories\.|__tests__|__mocks__|\/node_modules\/)/; const EXT = /\.(ts|tsx)$/; // Never rebrand these whole files (logos handled above; types declare identifiers). // branding-runtime.ts is excluded because it holds the "Onyx"→brand rename rule // itself — the word pass must not rewrite its own needle. const SKIP_FILES = new Set([ ...logoInstalls.map(([, d]) => path.resolve(d)), path.resolve(path.join(SRC, "lib/branding-runtime.ts")), ]); async function* walk(dir) { for (const e of await readdir(dir, { withFileTypes: true })) { const p = path.join(dir, e.name); if (e.isDirectory()) { yield* walk(p); continue; } if (EXT.test(e.name) && !SKIP.test(p)) yield p; } } for await (const file of walk(SRC)) { if (SKIP_FILES.has(path.resolve(file))) continue; const before = await readFile(file, "utf8"); let after = before; let n = 0; // 3a. exact-string literals (URLs etc.) — applied first for (const [from, to] of [...literals, ...ASSET_PATH_EDITS]) { if (after.includes(from)) { const parts = after.split(from); n += parts.length - 1; after = parts.join(to); } } // 3b. whole-word, case-sensitive brand name. \bOnyx\b never matches camelCase // identifiers (OnyxDocument, SvgOnyxLogo) or lowercase refs (@onyx, onyx.app). for (const [from, to] of wordPairs) { const re = new RegExp(`\\b${from.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "g"); after = after.replace(re, () => { n++; return to; }); } if (n > 0) { if (!DRY) await writeFile(file, after); filesChanged++; totalReplacements += n; if (DRY || process.env.VERBOSE) log(` ${c.gray}${path.relative(WEB, file)} (${n})${c.reset}`); } } ok(`${totalReplacements} replacement(s) across ${filesChanged} file(s)`); // ── 4. Summary ────────────────────────────────────────────────────────────── step("4/4 Done"); log(`${c.green}White-label applied for ${c.bold}${CONFIG.brand.name}${c.reset}${c.green} (${CONFIG.brand.legalName}).${c.reset}`); log(`${c.gray}Next: docker compose build web_server && docker compose up -d${c.reset}`); if (DRY) warn("dry-run: no files were written.");