openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
284 lines (283 loc) • 11.3 kB
JavaScript
import { f as normalizeStringEntries } from "./string-normalization-DLmfYZXI.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs";
import { c as readFileDescriptorBoundedSync, o as openRootFileSync } from "./boundary-file-read-BfaFLDqt.mjs";
import { i as stripAnsi } from "./ansi-CZa2t0Hf.mjs";
import { n as sanitizeTerminalText } from "./safe-text-C80HAQ2e.mjs";
import { t as FsSafeError } from "./fs-safe-BbWvmdVn.mjs";
import { r as resolveExternalPackageRuntimeEntrypointUrl } from "./runtime-process-url-CoHTemu-.mjs";
import { n as resolveOpenClawPackageRoot, r as resolveOpenClawPackageRootSync } from "./openclaw-root-C-ayo09z.mjs";
import { n as quotePowerShellArg, t as quoteCliArg } from "./quote-cli-arg-J7A9UE6m.mjs";
import { t as CONTROL_UI_BUILD_ID_ATTRIBUTE } from "./control-ui-root-assets-DCkhn9fm.mjs";
import fs from "node:fs";
import { fileURLToPath } from "node:url";
import path from "node:path";
//#region src/gateway/control-ui-route-preloads.ts
const CONTROL_UI_ROUTE_PRELOAD_ATTRIBUTE = "data-openclaw-route-preloads";
const routePreloadTemplate = new RegExp(`<template ${CONTROL_UI_ROUTE_PRELOAD_ATTRIBUTE}="([^"]+)">([\\s\\S]*?)</template>`, "g");
/** Activate only the requested route's build-emitted preload hints. */
function selectControlUiRoutePreloads(e, t) {
return e.replace(routePreloadTemplate, (e, n, r) => n === t ? r : "");
}
/** Reuse build-emitted hints; optional interactions must not compete with first paint. */
function controlUiPreloadLinks(e) {
const t = [];
for (const n of e.matchAll(/<(?:link|script)\b[^>]*>/g)) {
const e = n[0];
if (/\bfetchpriority="low"/.test(e)) continue;
const r = /\b(?:href|src)="(\/[^"<>?#]*\/assets\/[\w.-]+|\/assets\/[\w.-]+)"/.exec(e)?.[1];
if (!r) continue;
if (/\brel="modulepreload"|\btype="module"/.test(e)) t.push(`<${r}>; rel=modulepreload; crossorigin`);
else if (/\brel="stylesheet"|\bas="style"/.test(e)) t.push(`<${r}>; rel=preload; as=style; crossorigin`);
}
return [...new Set(t)];
}
//#endregion
//#region src/infra/control-ui-assets.ts
function formatControlUiSourceCommand(e, t) {
return `pnpm --dir ${process.platform === "win32" ? quotePowerShellArg(e) : quoteCliArg(e)} ui:${t}`;
}
function resolveControlUiDistIndexPathForRoot(e) {
return path.join(e, "dist", "control-ui", "index.html");
}
async function resolveControlUiAssetHealth(e) {
return inspectControlUiAssetHealth(resolveControlUiDistIndexPathForRoot(e.root), e.expectedBuildId);
}
function tryRealpath(e) {
try {
return fs.realpathSync(e);
} catch {
return null;
}
}
function resolveControlUiEntrypointPaths(e) {
const t = path.resolve(e);
const n = tryRealpath(t);
return n && n !== t ? [t, n] : [t];
}
async function resolveControlUiDistIndexPath(e) {
const t = process.argv[1];
const n = e.moduleUrl;
if (!t) return null;
const r = resolveControlUiEntrypointPaths(t);
for (const e of r) {
const t = path.dirname(e);
if (path.basename(t) === "dist") return path.join(t, "control-ui", "index.html");
}
const i = await resolveOpenClawPackageRoot({
argv1: path.resolve(t),
moduleUrl: n
});
return i ? resolveControlUiDistIndexPathForRoot(i) : null;
}
function pathsMatchByRealpathOrResolve(e, t) {
return (tryRealpath(e) ?? path.resolve(e)) === (tryRealpath(t) ?? path.resolve(t));
}
function resolveControlUiRootOverrideSync(e) {
const t = path.resolve(e);
try {
const e = fs.statSync(t);
if (e.isFile()) return path.basename(t) === "index.html" ? path.dirname(t) : null;
if (e.isDirectory()) {
const e = path.join(t, "index.html");
return fs.existsSync(e) ? t : null;
}
} catch {
return null;
}
return null;
}
function resolveControlUiRootSync(e = {}) {
const t = /* @__PURE__ */ new Set();
const addCandidate = (e) => {
if (e) t.add(path.resolve(e));
};
const n = e.argv1 ?? process.argv[1];
const r = e.cwd ?? process.cwd();
const i = e.moduleUrl ? path.dirname(fileURLToPath(e.moduleUrl)) : null;
const a = n ? resolveControlUiEntrypointPaths(n) : [];
const o = tryRealpath(e.execPath ?? process.execPath);
const s = resolveOpenClawPackageRootSync({
argv1: n,
moduleUrl: e.moduleUrl,
cwd: r
});
addCandidate(o ? path.join(path.dirname(o), "control-ui") : null);
if (i) for (const e of [
"control-ui",
"../control-ui",
"../../dist/control-ui"
]) addCandidate(path.join(i, e));
for (const e of a) {
const t = path.dirname(e);
addCandidate(path.join(t, "dist", "control-ui"));
addCandidate(path.join(t, "control-ui"));
}
addCandidate(s ? path.join(s, "dist", "control-ui") : null);
addCandidate(path.join(r, "dist", "control-ui"));
for (const e of t) {
const t = path.join(e, "index.html");
if (fs.existsSync(t)) return e;
}
return null;
}
function isPackageProvenControlUiRootSync(e, t = {}) {
const n = t.argv1 ?? process.argv[1];
const r = t.cwd ?? process.cwd();
const i = resolveOpenClawPackageRootSync({
argv1: n,
moduleUrl: t.moduleUrl,
cwd: r
});
if (!i) return false;
return pathsMatchByRealpathOrResolve(e, path.join(i, "dist", "control-ui"));
}
const CONTROL_UI_ASSETS_BUILD_TIMEOUT_MS = 6e5;
function controlUiAssetsFailure(e) {
return {
ok: false,
message: e
};
}
function inspectControlUiAssetHealth(e, t) {
if (!e) return {
kind: "missing-index",
indexPath: e
};
let n;
try {
const t = openRootFileSync({
absolutePath: e,
rootPath: path.dirname(e),
boundaryLabel: "control ui root",
rejectSymlinks: false,
rejectHardlinks: false,
maxBytes: 262144
});
if (!t.ok) {
if (t.error instanceof FsSafeError && t.error.code === "too-large") throw t.error;
return {
kind: "missing-index",
indexPath: e
};
}
try {
n = readFileDescriptorBoundedSync(t.fd, 262144).toString("utf8");
} finally {
fs.closeSync(t.fd);
}
} catch (t) {
if (t instanceof RangeError || t instanceof FsSafeError && t.code === "too-large") return {
kind: "incomplete",
indexPath: e,
missingAsset: "index.html exceeds its size limit"
};
return {
kind: "missing-index",
indexPath: e
};
}
const r = new Set([
null,
"chat",
"new"
].map((e) => selectControlUiRoutePreloads(n, e)));
for (const t of r) {
let n = 0;
for (const r of t.matchAll(/<(?:link|script)\b[^>]*>/giu)) {
const t = r[0].match(/\s(?:href|src)\s*=\s*["']([^"']+)["']/iu)?.[1]?.split(/[?#]/u, 1)[0]?.replace(/\\/gu, "/");
if (!t || /^(?:[a-z][a-z\d+.-]*:|\/\/|#)/iu.test(t)) continue;
const i = t.lastIndexOf("assets/");
if (i === -1 || !/\.(?:css|js)$/iu.test(t)) continue;
const a = t.slice(i);
if (++n > 128 || t.split("/").includes("..")) return {
kind: "incomplete",
indexPath: e,
missingAsset: n > 128 ? "too many startup assets" : a
};
if (!fs.existsSync(path.join(path.dirname(e), a))) return {
kind: "incomplete",
indexPath: e,
missingAsset: a
};
}
}
const i = new RegExp(`${CONTROL_UI_BUILD_ID_ATTRIBUTE}="([a-zA-Z0-9._-]{1,161})"`).exec(n)?.[1];
const a = i?.match(/^([a-zA-Z0-9._-]{1,96})-[a-f0-9]{64}$/u)?.[1] ?? null;
if (t && a !== "dev" && a !== t) return {
kind: "stale",
indexPath: e,
buildId: a
};
return {
kind: "ready",
indexPath: e,
...i ? { publicAssetBuildId: i } : {}
};
}
function inspectControlUiRootAssets(e, t) {
return inspectControlUiAssetHealth(path.join(e, "index.html"), t);
}
function summarizeCommandOutput(e) {
const t = normalizeStringEntries(stripAnsi(e).split(/\r?\n/g).map((e) => sanitizeTerminalText(e.trim())));
if (!t.length) return;
const n = t.findIndex((e) => /^(?:\[[^\]]+\]\s*)?(?:\w*error|fatal)\b/iu.test(e));
const r = t.slice(Math.max(0, n)).join(" ");
return r.length > 240 ? `${truncateUtf16Safe(r, 239)}…` : r;
}
async function ensureControlUiAssetsBuilt(e = defaultRuntime, t = {}) {
const n = t.assetRoot ?? (t.root ? path.dirname(resolveControlUiDistIndexPathForRoot(t.root)) : resolveControlUiRootSync(t));
const r = n ? path.join(n, "index.html") : await resolveControlUiDistIndexPath(t);
const i = inspectControlUiAssetHealth(r, t.expectedBuildId);
if (!t.force && i.kind === "ready") return {
ok: true,
assets: i
};
const a = process.cwd();
const o = (t.root ? [path.resolve(t.root)] : [resolveOpenClawPackageRootSync({
argv1: process.argv[1],
moduleUrl: t.moduleUrl ?? import.meta.url,
cwd: a
}), resolveOpenClawPackageRootSync({ cwd: a })]).find((e) => e !== null && fs.existsSync(path.join(e, "ui", "vite.config.ts"))) ?? null;
const s = o ? resolveControlUiDistIndexPathForRoot(o) : null;
if (!o || !s || n && !pathsMatchByRealpathOrResolve(n, path.dirname(s))) {
const e = r ? ` at ${r}` : "";
return controlUiAssetsFailure(`${i.kind === "stale" ? `Stale Control UI assets${e} (build ${i.buildId ?? "unknown"}; expected ${t.expectedBuildId})` : i.kind === "incomplete" ? `Incomplete Control UI assets${e} (missing ${i.missingAsset})` : `Missing Control UI assets${e}`}. Reinstall OpenClaw to restore bundled Control UI assets.`);
}
const c = fileURLToPath(resolveExternalPackageRuntimeEntrypointUrl("sourceUiBuild", o));
if (!fs.existsSync(c)) return controlUiAssetsFailure(`Control UI assets missing but ${c} is unavailable.`);
if (t.signal?.aborted) return controlUiAssetsFailure("Control UI build canceled.");
if (t.onBuildStart) t.onBuildStart();
else {
const t = formatControlUiSourceCommand(o, "build");
const n = formatControlUiSourceCommand(o, "dev");
e.log(`Control UI assets need rebuilding; building them now (rerun \`${t}\` after UI changes, or use \`${n}\` while developing the Control UI)…`);
}
let l;
try {
const { runCommandWithTimeout: e } = await import("./exec-Df6gUJ1h.mjs");
l = await e([
process.execPath,
c,
"build"
], {
cwd: o,
timeoutMs: CONTROL_UI_ASSETS_BUILD_TIMEOUT_MS,
killGraceMs: 15e3,
...t.signal ? { signal: t.signal } : {}
});
} catch (e) {
return controlUiAssetsFailure(`Control UI build failed: ${summarizeCommandOutput(e instanceof Error ? e.message : String(e)) ?? "unknown error"}`);
}
if (l.termination === "signal") return controlUiAssetsFailure("Control UI build canceled.");
if (l.termination === "timeout" || l.termination === "no-output-timeout") return controlUiAssetsFailure("Control UI build timed out.");
if (l.code !== 0) return controlUiAssetsFailure(`Control UI build failed: ${summarizeCommandOutput(l.stderr) ?? `exit ${l.code}`}`);
const u = inspectControlUiAssetHealth(s, t.expectedBuildId);
if (u.kind !== "ready") return controlUiAssetsFailure(`Control UI build completed but ${u.kind === "missing-index" ? `${s} is still missing.` : u.kind === "incomplete" ? `startup asset ${u.missingAsset} is missing.` : `its identity is ${u.buildId ?? "unknown"}; expected ${t.expectedBuildId}. Restart the Gateway after rebuilding its runtime and UI together.`}`);
return {
ok: true,
assets: u
};
}
//#endregion
export { isPackageProvenControlUiRootSync as a, resolveControlUiRootOverrideSync as c, selectControlUiRoutePreloads as d, inspectControlUiRootAssets as i, resolveControlUiRootSync as l, ensureControlUiAssetsBuilt as n, resolveControlUiAssetHealth as o, formatControlUiSourceCommand as r, resolveControlUiDistIndexPathForRoot as s, CONTROL_UI_ASSETS_BUILD_TIMEOUT_MS as t, controlUiPreloadLinks as u };