UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

222 lines (221 loc) • 8.15 kB
import { F as resolveTimerTimeoutMs, a as resolveStateDir, g as resolveEffectiveHomeDir, h as normalizeHomeDirValue, i as normalizeWindowsPathPreservingCase, n as isPathInside, p as resolveUserPath } from "./path-guards-quCEQx1i.mjs"; import { n as createAbortError, o as sleepWithAbort } from "./src-DIZdnDBl.mjs"; import fsSync from "node:fs"; import path from "node:path"; import "@openclaw/fs-safe/advanced"; import os from "node:os"; //#region packages/normalization-core/src/record-coerce.ts /** Type guard for non-array object records at browser-safe boundaries. */ function isRecord(e) { return e !== null && typeof e === "object" && !Array.isArray(e); } function isStringArray(e) { return Array.isArray(e) && e.every((e) => typeof e === "string"); } /** Coerces object-like values to records, falling back to an empty record. */ function asRecord(e) { return asOptionalObjectRecord(e) ?? {}; } /** Returns a non-array record or undefined. */ function asOptionalRecord(e) { return isRecord(e) ? e : void 0; } /** Returns a non-array record or null. */ function asNullableRecord(e) { return isRecord(e) ? e : null; } /** Returns any object-backed record, including arrays, or undefined. */ function asOptionalObjectRecord(e) { return e && typeof e === "object" ? e : void 0; } /** Removes undefined fields from a fresh projection in place, retaining its identity. */ function omitUndefinedFields(e) { for (const t in e) if (e[t] === void 0) delete e[t]; return e; } //#endregion //#region src/infra/abort-signal.ts function isAbortError(e) { if (!e || typeof e !== "object") return false; try { if (("name" in e ? String(e.name) : "") === "AbortError") return true; return ("message" in e && typeof e.message === "string" ? e.message : "") === "This operation was aborted"; } catch { return false; } } //#endregion //#region src/utils/sleep.ts /** Promise-based sleep that clamps timer inputs through the shared timeout resolver. */ function sleep(e, t) { const n = resolveTimerTimeoutMs(e, 0, 0); if (t) { if (t.aborted) return Promise.reject(createAbortError("aborted", { cause: t.reason ?? /* @__PURE__ */ new Error("aborted") })); return sleepWithAbort(n, t); } return new Promise((e) => { setTimeout(e, n); }); } //#endregion //#region packages/terminal-core/src/ansi-sequences.ts const ANSI_OSC_INTRODUCER_PATTERN = "(?:\\x1b\\]|\\x9d)"; const ANSI_STRING_TERMINATOR_PATTERN = "(?:\\x1b\\\\|\\x07|\\x9c)"; const ANSI_OSC_PATTERN = `${ANSI_OSC_INTRODUCER_PATTERN}[^\\x07\\x1b\\x9c]*${ANSI_STRING_TERMINATOR_PATTERN}`; const ANSI_COMPAT_CONTROL_SEQUENCE_PATTERN = "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]"; const ansiOscAtIndexRegex = new RegExp(ANSI_OSC_PATTERN, "y"); function matchAnsiOscAt(e, t) { ansiOscAtIndexRegex.lastIndex = t; return ansiOscAtIndexRegex.exec(e)?.[0]; } /** Scan one CSI parser pass, retaining independently executed C0 controls. */ function scanAnsiCsiAt(e, t) { const n = e.charCodeAt(t); if (n !== 155 && (n !== 27 || e.charCodeAt(t + 1) !== 91)) return; let r = t + (n === 155 ? 1 : 2); const i = []; let a = false; while (r < e.length) { const t = e.charCodeAt(r); if (t === 24 || t === 26) { r += 1; a = true; break; } if (t === 27 || t === 155) { a = true; break; } if (t <= 31 || t === 127) { i.push(e.charAt(r)); r += 1; continue; } if (t >= 32 && t <= 63) { r += 1; continue; } if (t >= 64 && t <= 126) r += 1; a = true; break; } return { controls: i, ended: a, value: e.slice(t, r) }; } //#endregion //#region packages/terminal-core/src/ansi.ts const ANSI_OSC_SEQUENCE_PATTERN = `${ANSI_OSC_INTRODUCER_PATTERN}[\\s\\S]*?${ANSI_STRING_TERMINATOR_PATTERN}`; const ANSI_COMPAT_SEQUENCE_AT_INDEX_REGEX = new RegExp(`${ANSI_OSC_SEQUENCE_PATTERN}|${ANSI_COMPAT_CONTROL_SEQUENCE_PATTERN}`, "y"); const graphemeSegmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" }); function hasAnsiIntroducer(e) { return e.includes("\x1B") || e.includes("›") || e.includes(""); } /** * Strip ANSI against original input positions so one removal cannot synthesize * a second sequence. C0 controls execute without ending CSI, CAN/SUB cancel it, * and ESC restarts escape parsing. */ function stripAnsiInternal(e, t) { if (!hasAnsiIntroducer(e)) return e; const n = []; let r = 0; let i = 0; while (i < e.length) { const a = e.charCodeAt(i); if (a !== 27 && a !== 155 && a !== 157) { i += 1; continue; } const o = matchAnsiOscAt(e, i); const s = o ? void 0 : scanAnsiCsiAt(e, i); ANSI_COMPAT_SEQUENCE_AT_INDEX_REGEX.lastIndex = i; const c = !o && t.compatibilityGrammar ? ANSI_COMPAT_SEQUENCE_AT_INDEX_REGEX.exec(e)?.[0] : void 0; let l = o?.length ?? s?.value.length ?? c?.length; if (l === void 0) { i += 1; continue; } if (s && !s.ended && t.preserveIncompleteCsi) break; if (s?.controls.length === 0 && c) l = Math.max(l, c.length); n.push(e.slice(r, i), ...s?.controls ?? []); i += l; r = i; } n.push(e.slice(r)); return n.join(""); } function stripAnsi(e) { return stripAnsiInternal(e, { compatibilityGrammar: false }); } const LOG_CONTROL_CHARS_REGEX = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(31)}${String.fromCharCode(127)}-${String.fromCharCode(159)}]`, "g"); /** * Sanitize a value for safe interpolation into log messages. * Strips ANSI escape sequences, C0/C1 control characters, and DEL to * prevent log forging / terminal escape injection (CWE-117). */ function sanitizeForLog(e) { return stripAnsi(e).replace(LOG_CONTROL_CHARS_REGEX, ""); } //#endregion //#region packages/terminal-core/src/safe-text.ts /** * Normalize untrusted text for single-line rendering, including bidirectional controls. */ function sanitizeTerminalText(e) { return stripAnsi(e).replace(/[\p{Cc}\p{Bidi_Control}]/gu, (e) => e === "\r" ? "\\r" : e === "\n" ? "\\n" : e === " " ? "\\t" : ""); } //#endregion //#region src/infra/config-dir.ts /** Resolves the OpenClaw config directory from state/config env overrides or home. */ function resolveConfigDir(e = process.env, t = os.homedir) { const n = e.OPENCLAW_STATE_DIR?.trim(); if (n) return resolveUserPath(n, e, t); const r = e.OPENCLAW_CONFIG_PATH?.trim(); if (r) return path.dirname(resolveUserPath(r, e, t)); return resolveStateDir(e, t); } //#endregion //#region src/infra/home-display.ts /** Replace an absolute home path with its display prefix without clipping sibling paths. */ function shortenPathWithHome(e, { home: t, prefix: n }) { if (e === t) return n; if (e.startsWith(`${t}/`) || process.platform === "win32" && e.startsWith(`${t}\\`)) return `${n}${e.slice(t.length)}`; if (process.platform === "win32" && path.win32.isAbsolute(e) && isPathInside(t, e)) { const r = path.win32.relative(normalizeWindowsPathPreservingCase(t), normalizeWindowsPathPreservingCase(e)); return path.win32.join(n, r); } return e; } //#endregion //#region src/utils.ts /** Resolves the effective OpenClaw home directory, if one can be determined. */ function resolveHomeDir() { return resolveEffectiveHomeDir(process.env, os.homedir); } const HOME_TEXT_START = String.raw`(?<=^|[\s"'\x60(\[{<=:;]|file://)`; const HOME_TEXT_DELIMITER = String.raw`[\s"'\x60)\]}>]`; const HOME_TEXT_LIST_NEXT = String.raw`[:;](?=[/\\~$]|[A-Za-z]:)`; function resolveHomeDisplayPrefix() { const e = resolveHomeDir(); if (!e) return; if (normalizeHomeDirValue(process.env.OPENCLAW_HOME)) return { home: e, prefix: "$OPENCLAW_HOME" }; return { home: e, prefix: "~" }; } /** Replaces the leading home directory in a path with `~` or `$OPENCLAW_HOME`. */ function shortenHomePath(e) { const t = resolveHomeDisplayPrefix(); if (!t) return e; return shortenPathWithHome(e, t); } let CONFIG_DIR = resolveConfigDir(); //#endregion export { sanitizeForLog as a, isAbortError as c, asOptionalRecord as d, asRecord as f, omitUndefinedFields as h, sanitizeTerminalText as i, asNullableRecord as l, isStringArray as m, shortenHomePath as n, stripAnsi as o, isRecord as p, resolveConfigDir as r, sleep as s, CONFIG_DIR as t, asOptionalObjectRecord as u };