feat: add shared util helpers and config

This commit is contained in:
2026-08-14 10:38:42 -06:00
parent fde5fc75af
commit 953be547f0
2 changed files with 69 additions and 0 deletions
+37
View File
@@ -0,0 +1,37 @@
export const DEFAULT_BASE_URL = "http://localhost:9292";
export interface CfgSettings {
baseUrl?: string;
apiKey?: string;
}
export interface LlamaSwapConfig {
baseUrl: string;
apiKey?: string;
}
export function cfgFromSettings(settings: CfgSettings): LlamaSwapConfig {
return {
baseUrl: normalizeBaseUrl(settings.baseUrl ?? DEFAULT_BASE_URL),
apiKey: settings.apiKey || undefined,
};
}
export function normalizeBaseUrl(baseUrl: string): string {
return baseUrl.trim().replace(/\/+$/, "");
}
export function shorten(name: string, max = 14): string {
if (name.length <= max) return name;
const head = Math.floor((max - 1) * 0.7);
return `${name.slice(0, head)}${name.slice(name.length - (max - head - 1))}`;
}
export function escapeXml(text: string): string {
return text
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&apos;");
}
+32
View File
@@ -0,0 +1,32 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import {
cfgFromSettings,
escapeXml,
normalizeBaseUrl,
shorten,
} from "../src/lib/util";
test("normalizeBaseUrl strips trailing slashes", () => {
assert.equal(normalizeBaseUrl("http://localhost:9292/"), "http://localhost:9292");
assert.equal(normalizeBaseUrl("http://localhost:9292"), "http://localhost:9292");
});
test("cfgFromSettings defaults baseUrl and omits empty apiKey", () => {
const cfg = cfgFromSettings({});
assert.equal(cfg.baseUrl, "http://localhost:9292");
assert.equal(cfg.apiKey, undefined);
assert.deepEqual(cfgFromSettings({ baseUrl: "http://x/", apiKey: "abc" }), {
baseUrl: "http://x",
apiKey: "abc",
});
});
test("shorten keeps short names and truncates long ones", () => {
assert.equal(shorten("Qwen3.8-27B"), "Qwen3.8-27B");
assert.equal(shorten("DeepSeek-V4-Flash-0731"), "DeepSeek-…0731");
});
test("escapeXml escapes XML special characters", () => {
assert.equal(escapeXml(`A&B <C> "D" 'E'`), "A&amp;B &lt;C&gt; &quot;D&quot; &apos;E&apos;");
});