Files
image-workbench-desktop/tests/storage-config-shape-test.js

241 lines
16 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict'
// 配置形状纯函数模块的行为契约:`src/storage-config-shape.js`
//
// ── 为什么有这个文件(2026-10-28,P1 拆分批 2)────────────────────────────────
// 这 9 个函数从 app.js 迁出后,负例验证暴露了一个**空缺**:
// 把 `mergeDeep` 的递归分支删掉(深合并退化为浅覆盖),**全部测试依然通过** ——
// 也就是说深合并从来没被真正验证过。
//
// 这批函数守的是很要命的东西:
// · wMask —— 密钥必须掩码,不能明文出现在界面/日志里
// · mergeDeep —— 配置合并不能丢字段(丢一个就是"设置保存后没生效")
// · wNormalizeImageModels —— 模型列表去重保序 + 质量能力三态(undefined=没表过态)
// · wNormalizeLayerModels —— 内置图层模型**永远在列且强制可见**(规范 §13.26)
// · wMigrateLlm —— 老版 LLM 配置要能迁移过来(否则用户升级后配置全丢)
//
// 所以这里做**直接行为断言**(不是源码文本),比原来的"源码里有这行字"强得多。
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const vm = require('vm')
const root = path.resolve(__dirname, '..')
// 与 app.js 注入的常量保持一致(值变了这里会一起暴露出来)
const W_SHAPE_KINDS = ['openai', 'gemini', 'doubao', 'custom']
const BUILTIN_LAYER_MODEL = 'doubao-seedream-4-0-250828'
const box = { console: { log() {}, warn() {}, error() {} } }
vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'storage-config-shape.js'), 'utf8'), box)
assert.ok(box.IWBStorageConfigShape && typeof box.IWBStorageConfigShape.create === 'function',
'src/storage-config-shape.js 应导出 window.IWBStorageConfigShape.create')
const S = box.IWBStorageConfigShape.create({ W_SHAPE_KINDS, BUILTIN_LAYER_MODEL })
// ⚠️ 跨 realm 比较:模块在 vm 沙箱里创建对象,原型与本文件不同,
// 直接用 assert.deepStrictEqual 会因「原型不一致」误报。统一走 JSON 比较。
const eq = (actual, expected, msg) => assert.strictEqual(JSON.stringify(actual), JSON.stringify(expected), msg)
// ── 0. 缺依赖必须显式报错(不许静默降级)─────────────────────────────────────
assert.throws(() => box.IWBStorageConfigShape.create({}), /缺少注入依赖: W_SHAPE_KINDS/,
'create() 缺 W_SHAPE_KINDS 时应抛错')
assert.throws(() => box.IWBStorageConfigShape.create({ W_SHAPE_KINDS }), /缺少注入依赖: BUILTIN_LAYER_MODEL/,
'create() 缺 BUILTIN_LAYER_MODEL 时应抛错')
// ── 1. wClone:深拷贝且不共享引用 ─────────────────────────────────────────────
{
const src = { a: 1, b: { c: [1, 2] } }
const copy = S.wClone(src)
eq(copy, src, 'wClone 应产出等值副本')
copy.b.c.push(3)
eq(src.b.c, [1, 2], 'wClone 必须是深拷贝(改副本不能影响原对象)')
}
// ── 2. mergeDeep:**深合并**(这是本次补测的核心)──────────────────────────────
{
const base = { a: 1, nested: { x: 1, y: 2 }, arr: [1, 2] }
const merged = S.mergeDeep(base, { nested: { y: 9, z: 3 }, arr: [9] })
// 关键:nested 里的 x 必须被保留下来(浅覆盖会丢它 —— 删掉递归分支就会在这里红)
assert.strictEqual(merged.nested.x, 1, 'mergeDeep 必须保留 base 里未被覆盖的嵌套字段(浅覆盖会丢)')
assert.strictEqual(merged.nested.y, 9, 'mergeDeep 应用 extra 覆盖同名字段')
assert.strictEqual(merged.nested.z, 3, 'mergeDeep 应带入 extra 新增字段')
eq(merged.arr, [9], 'mergeDeep 对数组应整体替换(不逐项合并)')
assert.strictEqual(merged.a, 1, 'mergeDeep 应保留 base 的顶层字段')
// base 不能被改动
assert.strictEqual(base.nested.y, 2, 'mergeDeep 不得修改入参 base')
// null / undefined 的语义
eq(S.mergeDeep({ a: 1 }, null), { a: 1 }, 'extra 为 null 时返回 base 副本')
eq(S.mergeDeep({ a: 1 }, undefined), { a: 1 }, 'extra 为 undefined 时返回 base 副本')
eq(S.mergeDeep(5, { a: 1 }), { a: 1 }, 'base 非对象时应直接取 extra')
// B:mergeDeep 必须丢弃 __proto__/constructor/prototype,防原型污染
{
const dirty = JSON.parse('{"__proto__":{"polluted":1},"constructor":{"x":1},"okField":2}')
const m = S.mergeDeep({}, dirty)
assert.strictEqual(m.okField, 2)
assert.strictEqual(Object.prototype.hasOwnProperty.call(m, '__proto__'), false, '不得设入 __proto__ 自有键')
assert.strictEqual({}.polluted, undefined, '不得污染 Object.prototype')
}
}
// ── 3. wMask:密钥必须掩码 ────────────────────────────────────────────────────
{
assert.strictEqual(S.wMask(''), '', '空值掩码后仍是空')
assert.strictEqual(S.wMask(null), '', 'null 掩码后是空')
// 核准的实际语义(2026-10-28):≤8 位露末 2 位(帮用户辨认是哪个),>8 位露首 3 + 末 4。
// 关键契约是「中间部分永远被 •••• 遮住」,不是"完全不露"。
const short = S.wMask('abc123')
assert.strictEqual(short, '••••23', '短密钥(≤8)应遮住前缀、只露末 2 位')
const long = S.wMask('sk-1234567890abcdef')
assert.strictEqual(long, 'sk-••••cdef', '长密钥(>8)应露首 3 + 末 4,中间遮住')
// 无论长短,都不得原样返回
for (const v of ['abc123', 'sk-1234567890abcdef', 'a'.repeat(40)]) {
assert.notStrictEqual(S.wMask(v), v, '掩码结果不得等于原文:' + v.slice(0, 8))
assert.ok(S.wMask(v).indexOf('••••') >= 0, '掩码结果必须含 •••• 遮挡:' + v.slice(0, 8))
}
}
// ── 4. storageResult:统一 { ok, ...extra } ──────────────────────────────────
{
eq(S.storageResult(true), { ok: true }, 'storageResult(true) 应只含 ok')
eq(S.storageResult(false, { error: 'x' }), { ok: false, error: 'x' }, '应合并 extra')
assert.strictEqual(S.storageResult(1).ok, true, 'ok 应被强制转成布尔')
assert.strictEqual(S.storageResult('').ok, false, '空字符串应转成 false')
}
// ── 5. wStripDerived:写盘前剥掉派生键 ───────────────────────────────────────
{
const dirty = { keep: 1, masked: true, filled: 1, qwenName: 'q', configured: true, hasPassword: 1 }
const clean = S.wStripDerived(dirty)
eq(clean, { keep: 1 }, 'wStripDerived 应只保留非派生键')
eq(S.wStripDerived({ a: 1 }), { a: 1 }, '没有派生键时应原样返回')
}
// ── 6. wShapeProviderFields:只收敛白名单字段 ────────────────────────────────
{
const ok = S.wShapeProviderFields({ kind: 'openai', requestShape: { body: { a: 1 } }, modelRules: [{ match: 'm', kind: 'gemini' }], junk: 'drop-me' })
assert.strictEqual(ok.kind, 'openai', '合法 kind 应保留')
eq(ok.requestShape, { body: { a: 1 } }, 'requestShape.body 应保留')
eq(ok.modelRules, [{ match: 'm', kind: 'gemini' }], '合法 modelRules 应保留')
assert.strictEqual(ok.junk, undefined, '非白名单字段应被丢弃')
assert.strictEqual(S.wShapeProviderFields({ kind: '不存在的分类' }).kind, undefined, '非法 kind 应被丢弃')
eq(S.wShapeProviderFields(null), {}, 'null 应返回空对象')
// 非法 modelRules 条目要被过滤
const filtered = S.wShapeProviderFields({ modelRules: [{ match: 'm', kind: 'bad' }, { match: '', kind: 'openai' }, { match: 'ok', kind: 'doubao' }] })
eq(filtered.modelRules, [{ match: 'ok', kind: 'doubao' }], '非法 modelRules 条目应被过滤')
}
// ── 7. wNormalizeImageModels:去重保序 + 质量能力三态 ────────────────────────
{
const list = S.wNormalizeImageModels([{ name: 'a' }, 'b', { name: 'A' }, 'b', { name: '' }, null])
eq(list.map((m) => m.name), ['a', 'b'],
'应去重(大小写不敏感)+ 保序 + 丢掉空名')
// 三态:只有显式 boolean 才写盘
const tri = S.wNormalizeImageModels([
{ name: 'x', supportsQuality: true },
{ name: 'y' }, // undefined = 没表过态
{ name: 'z', supportsQuality: false },
])
assert.strictEqual(tri[0].supportsQuality, true, '显式 true 应保留')
assert.strictEqual('supportsQuality' in tri[1], false, 'undefined(没表过态)不应写盘')
assert.strictEqual(tri[2].supportsQuality, false, '显式 false 应保留')
// 默认可见,显式 false 才不可见
const vis = S.wNormalizeImageModels([{ name: 'p' }, { name: 'q', visible: false }])
assert.strictEqual(vis[0].visible, true, '默认应可见')
assert.strictEqual(vis[1].visible, false, '显式 false 应不可见')
// 空输入
eq(S.wNormalizeImageModels(null), [], 'null 应返回空数组')
}
// ── 8. wNormalizeLayerModels:内置图层模型**永远在列且强制可见**(规范 §13.26)──
{
// 核准的实际语义:内置项**总是被无条件加入**(不是"仅当用户列表里有才保留"),
// 且强制 visible: true —— 这是「隐藏它会让分层节点没有模型可选」的兜底。
const list = S.wNormalizeLayerModels([{ name: BUILTIN_LAYER_MODEL, visible: false }])
assert.strictEqual(list.length, 1, '内置项已在用户列表里时不应重复加入')
assert.strictEqual(list[0].name, BUILTIN_LAYER_MODEL, '内置图层模型名应保留')
assert.strictEqual(list[0].visible, true,
'内置图层模型必须**强制可见** —— 隐藏它会让分层节点没有模型可选(规范 §13.26)')
const withOthers = S.wNormalizeLayerModels([{ name: 'other' }, { name: 'other' }])
assert.strictEqual(withOthers[0].name, BUILTIN_LAYER_MODEL, '内置项应排在第一位')
eq(withOthers.map((m) => m.name), [BUILTIN_LAYER_MODEL, 'other'], '非内置项应去重')
const empty = S.wNormalizeLayerModels([])
assert.strictEqual(empty.length, 1, '空列表也应自动带上内置项(否则分层节点没模型可选)')
assert.strictEqual(empty[0].name, BUILTIN_LAYER_MODEL, '空列表时内置项必须在列')
assert.strictEqual(empty[0].visible, true, '空列表时内置项必须可见')
}
// ── 9. wMigrateLlm:老形状能迁移(否则升级后配置全丢)───────────────────────
// 核准的真实结构(2026-10-28):产出 `{ providers: [...], defaultProviderId, defaultInstruction }`
// (不是 channels/activeChannelId —— 那是别处的叫法;这里必须按实际实现断言)。
{
// 9a. 旧格式 { baseUrl, apiKey, model } → 单渠道
const migrated = S.wMigrateLlm({ baseUrl: 'https://x', model: 'm', apiKey: 'k' })
assert.ok(Array.isArray(migrated.providers), 'wMigrateLlm 旧格式应产出 providers 数组')
assert.strictEqual(migrated.providers.length, 1, '旧格式应迁移成单个渠道')
const ch = migrated.providers[0]
assert.strictEqual(ch.baseUrl, 'https://x', '迁移应保留 baseUrl')
assert.strictEqual(ch.defaultModel, 'm', '迁移应把 model 落成 defaultModel')
eq(ch.models.map((x) => x.name), ['m'], '迁移应把 model 收进 models 列表')
assert.strictEqual(ch.models[0].default, true, '当前 model 应标记为 default')
assert.strictEqual(ch.keys.length, 1, '旧格式的 apiKey 应迁移成 1 个 key')
assert.strictEqual(ch.keys[0].value, 'k', 'apiKey 值应保留')
assert.strictEqual(migrated.defaultProviderId, 'l0', '旧格式迁移后默认渠道 id 应为 l0')
// 9b. 已是渠道结构 → 归一化保留
const alreadyNew = S.wMigrateLlm({
providers: [{ id: 'c1', name: 'n', baseUrl: 'u', keys: [{ id: 'k1', value: 'v' }], models: [{ name: 'm1', default: true }] }],
defaultProviderId: 'c1',
})
assert.strictEqual(alreadyNew.providers.length, 1, '新形状应原样保留渠道数')
assert.strictEqual(alreadyNew.providers[0].id, 'c1', '新形状的渠道 id 应保留')
assert.strictEqual(alreadyNew.defaultProviderId, 'c1', '新形状的 defaultProviderId 应保留')
assert.strictEqual(alreadyNew.providers[0].keys[0].value, 'v', '新形状的 key 值应保留')
// 9c. 关键安全契约:`__KEEP__` 占位符不得当成真密钥写回
const keep = S.wMigrateLlm({ providers: [{ id: 'c2', keys: [{ id: 'k2', value: '__KEEP__' }] }] })
assert.strictEqual(keep.providers[0].keys[0].value, '',
'__KEEP__ 是「保持原值」的占位符,迁移时必须清空(否则会把占位符当密钥存盘)')
// 9d. 空配置不抛错
assert.doesNotThrow(() => S.wMigrateLlm({}), '空配置不应抛错')
assert.doesNotThrow(() => S.wMigrateLlm(null), 'null 不应抛错')
}
// ── 10. normalizeEndpointBase:粘"完整接口地址"必须被纠正(2026-11-05 线上实测:填 .../v1/chat/completions ⇒ 404)
const N = S.normalizeEndpointBase
assert.strictEqual(typeof N, 'function', 'create() 实例必须暴露 normalizeEndpointBase')
const cases = [
['https://api.tu-zi.com/v1/chat/completions', 'https://api.tu-zi.com/v1'],
['https://api.tu-zi.com/v1/chat/completions/', 'https://api.tu-zi.com/v1'],
['https://api.tu-zi.com/v1/models', 'https://api.tu-zi.com/v1'],
['https://api.tu-zi.com/v1/completions', 'https://api.tu-zi.com/v1'],
['https://x.test/v1/images/generations', 'https://x.test/v1'],
['https://x.test/v1/images/edits', 'https://x.test/v1'],
[' https://api.tu-zi.com/v1/ ', 'https://api.tu-zi.com/v1'],
['https://api.tu-zi.com/v1', 'https://api.tu-zi.com/v1'],
['https://api.tu-zi.com', 'https://api.tu-zi.com'],
['', ''],
[null, ''],
]
for (const [inp, want] of cases) assert.strictEqual(N(inp), want, 'normalizeEndpointBase(' + JSON.stringify(inp) + ') 应为 ' + JSON.stringify(want))
const mig2 = S.wMigrateLlm({ providers: [{ id: 'l0', name: 'a', baseUrl: 'https://api.tu-zi.com/v1/chat/completions', fallbacks: ['https://b.test/v1/models'], keys: [], models: [] }] })
assert.strictEqual(mig2.providers[0].baseUrl, 'https://api.tu-zi.com/v1', 'LLM 渠道 baseUrl 迁移应剥掉接口路径')
assert.strictEqual(mig2.providers[0].fallbacks[0], 'https://b.test/v1', 'LLM 备用地址迁移应剥掉接口路径')
// ── 10. wShapeProviderFields:鉴权方式白名单(2026-11-24,v3.26.65)────────────
// 背景:认证此前写死 Bearer,接不了要 x-api-key / URL 参数的中转站。白名单必须:
// · 无 auth 字段 ⇒ 不写字段(老配置保持"缺省 Bearer"语义,不能凭空插一个 auth)
// · 未知类型 ⇒ 丢弃(不能把拼错的类型写进配置)
// · header/query 的字段名要能存下来,否则 UI 填了也白填
eq(S.wShapeProviderFields({}), {}, "无 auth 时不写字段")
eq(S.wShapeProviderFields({ kind: 'openai', auth: { type: 'header', headerName: 'x-api-key' } }),
{ kind: 'openai', auth: { type: 'header', headerName: 'x-api-key' } }, '自定义 header 要保留')
eq(S.wShapeProviderFields({ auth: { type: 'query', queryName: 'tk' } }), { auth: { type: 'query', queryName: 'tk' } }, 'URL 参数名要保留')
eq(S.wShapeProviderFields({ auth: { type: 'nope' } }), {}, '未知鉴权类型丢弃')
eq(S.wShapeProviderFields({ auth: { type: 'NONE' } }), { auth: { type: 'none' } }, '类型大小写归一')
console.log('storage config shape checks passed(9 个纯函数的行为契约,含深合并与内置模型强制可见)')