182 lines
9.8 KiB
JavaScript
182 lines
9.8 KiB
JavaScript
/* 配置/模型数据的**形状规范化**纯函数(自 app.js 收编,P1 拆分批 2,2026-10-28)
|
||
*
|
||
* - wClone(v) 深拷贝(JSON 往返;配置里只有 JSON 可表达的数据)
|
||
* - mergeDeep(base, extra) 递归合并;数组/原始值直接替换
|
||
* - wMask(v) 密钥掩码(只露尾部若干位)
|
||
* - wShapeProviderFields(pr) 服务商形状字段收敛(kind / requestShape / modelRules)
|
||
* - wNormalizeImageModels(list) 图片模型列表:去重保序、visible 三态、质量能力三态
|
||
* - wNormalizeLayerModels(list) 分层模型列表:去重保序
|
||
* - wMigrateLlm(cfg) LLM 配置老形状 → 新形状迁移
|
||
* - storageResult(ok, extra) 统一存储结果 { ok, ...extra }
|
||
* - wStripDerived(cfg) 剥掉派生键(只读展示用,不写盘)
|
||
*
|
||
* ── 边界(本批的核心设计)──────────────────────────────────────────────────
|
||
* 本模块只管「数据长什么样」,**不碰 I/O**。
|
||
* 「从哪读 / 写到哪」(LocalStore / StorageContract / IndexedDB)留在 app.js。
|
||
* ⇒ wRawCfg / wRawStoredCfg / wCfgSave / wCfgPublic 仍留在 app.js,它们调用本模块。
|
||
*
|
||
* 依赖:注入 2 个常量 —— W_SHAPE_KINDS(服务商分类白名单)与 BUILTIN_LAYER_MODEL(内置图层分离模型名,
|
||
* wNormalizeLayerModels 必须保证它永远在列、不可删不可隐藏,见规范 §13.26)。
|
||
* 宿主只经 window.IWBStorageConfigShape 使用。
|
||
*/
|
||
;(function (global) {
|
||
'use strict'
|
||
|
||
const create = (deps) => {
|
||
const D = deps || {}
|
||
const W_SHAPE_KINDS = D.W_SHAPE_KINDS
|
||
if (!Array.isArray(W_SHAPE_KINDS)) throw new Error('IWBStorageConfigShape 缺少注入依赖: W_SHAPE_KINDS(数组)')
|
||
// 内置图层分离模型名:wNormalizeLayerModels 必须保证它永远在列、不可删不可隐藏(规范 §13.26)
|
||
const BUILTIN_LAYER_MODEL = D.BUILTIN_LAYER_MODEL
|
||
if (typeof BUILTIN_LAYER_MODEL !== 'string' || !BUILTIN_LAYER_MODEL) {
|
||
throw new Error('IWBStorageConfigShape 缺少注入依赖: BUILTIN_LAYER_MODEL(非空字符串)')
|
||
}
|
||
|
||
// 派生键:只读展示用,写盘前必须剥掉(原在 app.js 模块级,仅供 wStripDerived 使用)
|
||
const W_CFG_DERIVED_KEYS = ['masked', 'filled', 'qwenName', 'configured', 'hasPassword']
|
||
|
||
function wClone(v) { return JSON.parse(JSON.stringify(v)) }
|
||
|
||
function mergeDeep(base, extra) {
|
||
if (extra === undefined || extra === null) return wClone(base)
|
||
if (Array.isArray(base) || typeof base !== 'object') return wClone(extra)
|
||
const out = wClone(base)
|
||
for (const k of Object.keys(extra)) {
|
||
if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue
|
||
const bv = out[k], ev = extra[k]
|
||
if (ev && typeof ev === 'object' && !Array.isArray(ev) && bv && typeof bv === 'object') out[k] = mergeDeep(bv, ev)
|
||
else out[k] = wClone(ev)
|
||
}
|
||
return out
|
||
}
|
||
|
||
function wMask(v) {
|
||
if (!v) return ''
|
||
const str = String(v)
|
||
return str.length <= 8 ? '••••' + str.slice(-2) : str.slice(0, 3) + '••••' + str.slice(-4)
|
||
}
|
||
|
||
// 鉴权方式白名单(2026-11-24,v3.26.65):此前只支持 Bearer,接不了要 x-api-key / URL 参数的中转站。
|
||
// 缺省(无 auth 字段)= bearer,保持老配置行为不变。
|
||
const AUTH_TYPES = ['bearer', 'header', 'query', 'none']
|
||
function wShapeAuth(auth) {
|
||
if (!auth || typeof auth !== 'object') return null
|
||
const t = String(auth.type || '').trim().toLowerCase()
|
||
if (AUTH_TYPES.indexOf(t) < 0) return null
|
||
const out = { type: t }
|
||
if (t === 'header') {
|
||
const hn = String(auth.headerName || '').trim().slice(0, 64)
|
||
if (hn) out.headerName = hn
|
||
}
|
||
if (t === 'query') {
|
||
const qn = String(auth.queryName || '').trim().slice(0, 64)
|
||
if (qn) out.queryName = qn
|
||
}
|
||
return out
|
||
}
|
||
|
||
function wShapeProviderFields(pr) {
|
||
const out = {}
|
||
if (pr && W_SHAPE_KINDS.indexOf(pr.kind) >= 0) out.kind = pr.kind
|
||
if (pr) { const a = wShapeAuth(pr.auth); if (a) out.auth = a }
|
||
if (pr && pr.requestShape && pr.requestShape.body && typeof pr.requestShape.body === 'object' && !Array.isArray(pr.requestShape.body)) out.requestShape = { body: pr.requestShape.body }
|
||
if (pr && Array.isArray(pr.modelRules)) {
|
||
const rules = pr.modelRules
|
||
.filter((r) => r && typeof r.match === 'string' && r.match && W_SHAPE_KINDS.indexOf(r.kind) >= 0)
|
||
.slice(0, 20)
|
||
.map((r) => ({ match: r.match, kind: r.kind }))
|
||
if (rules.length) out.modelRules = rules
|
||
}
|
||
return out
|
||
}
|
||
|
||
function wNormalizeImageModels(models) {
|
||
const list = Array.isArray(models) ? models : []
|
||
const seen = new Set(), out = []
|
||
for (const raw of list) {
|
||
const m = typeof raw === 'string' ? { name: raw } : (raw || {})
|
||
const name = String(m.name || '').trim()
|
||
if (!name || seen.has(name.toLowerCase())) continue
|
||
seen.add(name.toLowerCase())
|
||
const entry = { name, visible: m.visible !== false, source: m.source === 'builtin' || m.builtin === true || m.custom === false ? 'builtin' : 'custom' }
|
||
// 质量能力是三态:只在用户显式表态时写盘;undefined = 没表过态 → 运行时用内置种子判定(不写回,便于以后扩种子)
|
||
if (typeof m.supportsQuality === 'boolean') entry.supportsQuality = m.supportsQuality
|
||
// 模型级「厂商分类」覆盖(缺省跟随服务商;见 wShapeProviderFields)
|
||
if (typeof m.kind === 'string' && W_SHAPE_KINDS.indexOf(m.kind) >= 0) entry.kind = m.kind
|
||
out.push(entry)
|
||
}
|
||
return out
|
||
}
|
||
|
||
function wNormalizeLayerModels(models) {
|
||
const list = [{ name: BUILTIN_LAYER_MODEL, visible: true, source: 'builtin' }].concat(Array.isArray(models) ? models : [])
|
||
return wNormalizeImageModels(list).map((m) => (m.source === 'builtin' ? { ...m, visible: true } : m))
|
||
}
|
||
|
||
function wMigrateLlm(llm) {
|
||
llm = llm || {}
|
||
if (Array.isArray(llm.providers)) {
|
||
// 已是渠道结构:归一化
|
||
return {
|
||
providers: llm.providers.map((p, pi) => ({
|
||
id: p.id || ('l' + pi), name: p.name || ('渠道 ' + (pi + 1)), baseUrl: normalizeEndpointBase(p.baseUrl), fallbacks: (p.fallbacks || []).map((u) => normalizeEndpointBase(u)).filter(Boolean),
|
||
keys: (p.keys || []).map((k, ki) => ({ id: k.id || ('lk' + pi + '_' + ki), name: k.name || ('Key ' + (ki + 1)), value: (k.value && k.value !== '__KEEP__') ? String(k.value) : '' })),
|
||
models: (p.models || []).map((m) => (typeof m === 'string' ? { name: m } : m)).filter((m) => m && m.name).map((m) => ({ name: String(m.name), default: !!m.default })),
|
||
defaultModel: (p.defaultModel || ((p.models || []).find((m) => m && m.default && m.name) ? String((p.models || []).find((m) => m && m.default && m.name).name) : (p.models || [])[0] ? (typeof (p.models || [])[0] === 'string' ? String((p.models || [])[0]) : String((p.models || [])[0].name || '')) : '')) || '',
|
||
})),
|
||
defaultProviderId: llm.defaultProviderId || ((llm.providers[0] && (llm.providers[0].id || 'l0')) || ''),
|
||
defaultInstruction: llm.defaultInstruction || '',
|
||
}
|
||
}
|
||
// 旧格式 { baseUrl, apiKey, model, models } → 单渠道(兼容迁移)
|
||
const oldModels = (Array.isArray(llm.models) && llm.models.length) ? llm.models.map((m) => String(m).trim()).filter(Boolean) : (llm.model ? [String(llm.model).trim()] : [])
|
||
return {
|
||
providers: [{
|
||
id: 'l0', name: '默认渠道',
|
||
baseUrl: llm.baseUrl || '', fallbacks: [],
|
||
keys: llm.apiKey ? [{ id: 'lk0_0', name: '默认', value: String(llm.apiKey) }] : [],
|
||
models: oldModels.map((n) => ({ name: n, default: n === String(llm.model || '').trim() })),
|
||
defaultModel: oldModels.find((n) => n === String(llm.model || '').trim()) || oldModels[0] || '',
|
||
}],
|
||
defaultProviderId: 'l0',
|
||
defaultInstruction: llm.defaultInstruction || '',
|
||
}
|
||
}
|
||
|
||
function storageResult(ok, extra) {
|
||
return Object.assign({ ok: !!ok }, extra || {})
|
||
}
|
||
|
||
function wStripDerived(obj) {
|
||
const out = Object.assign({}, obj || {})
|
||
for (const k of W_CFG_DERIVED_KEYS) delete out[k]
|
||
return out
|
||
}
|
||
|
||
return { normalizeEndpointBase, wClone, mergeDeep, wMask, wShapeAuth, wShapeProviderFields, wNormalizeImageModels, wNormalizeLayerModels, wMigrateLlm, storageResult, wStripDerived }
|
||
}
|
||
|
||
// 地址归一化(2026-11-05):用户常把「完整接口地址」粘进 Base URL 输入框,而调用方还会再拼一次
|
||
// `/chat/completions`、`/models`、`/images/generations`…(线上实测:填 .../v1/chat/completions ⇒ 404 Invalid URL)。
|
||
// 这里统一剥掉尾部的接口路径,只保留到版本段(/v1 之类)。
|
||
// 纯字符串处理,不做网络/配置判断,供配置迁移与运行时共用。
|
||
const ENDPOINT_SUFFIXES = ['/chat/completions', '/chat/completion', '/completions', '/models',
|
||
'/images/generations', '/images/edits', '/images/edit', '/images/generation']
|
||
const normalizeEndpointBase = (url) => {
|
||
let u = String(url == null ? '' : url).trim()
|
||
if (!u) return ''
|
||
u = u.replace(/\/+$/, '')
|
||
let changed = true
|
||
while (changed) {
|
||
changed = false
|
||
const low = u.toLowerCase()
|
||
for (const suf of ENDPOINT_SUFFIXES) {
|
||
if (low.endsWith(suf)) { u = u.slice(0, u.length - suf.length).replace(/\/+$/, ''); changed = true; break }
|
||
}
|
||
}
|
||
return u
|
||
}
|
||
|
||
global.IWBStorageConfigShape = { create, normalizeEndpointBase }
|
||
})(typeof window !== 'undefined' ? window : globalThis)
|