From c7930e5a0109879f97e6729a7c4772a9014e6aa4 Mon Sep 17 00:00:00 2001 From: qiqi Date: Tue, 24 Nov 2026 22:55:08 +0800 Subject: [PATCH] =?UTF-8?q?feat(api):=20genPath/editPath=20=E7=94=9F?= =?UTF-8?q?=E6=95=88=20+=20auth=20=E5=9B=9B=E6=80=81=EF=BC=88bearer/header?= =?UTF-8?q?/query/none=EF=BC=89+=20=E7=94=9F=E5=9B=BE=E5=9C=B0=E5=9D=80?= =?UTF-8?q?=E5=9B=9E=E9=80=80=EF=BC=88=E7=BB=93=E6=9E=9C=E6=9C=AA=E7=9F=A5?= =?UTF-8?q?=E4=B8=8D=E9=87=8D=E6=8F=90=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CONTRIBUTING.md | 4 +- app.js | 48 ++++++++-- .../2026-11-24-local-images-and-api-gaps.md | 10 +++ docs/standards/architecture-current-state.md | 8 +- package.json | 2 +- scripts/build.js | 1 + src/generation-endpoint.js | 89 +++++++++++++++++++ src/storage-config-shape.js | 22 ++++- src/ui-settings-sections.js | 20 +++++ tests/fixtures/iwb-app-global-reads.json | 1 + tests/fixtures/iwb-source-modules-order.json | 1 + tests/generation-endpoint-test.js | 81 +++++++++++++++++ tests/source-text-ratchet-test.js | 8 +- tests/storage-config-shape-test.js | 12 +++ 14 files changed, 290 insertions(+), 17 deletions(-) create mode 100644 src/generation-endpoint.js create mode 100644 tests/generation-endpoint-test.js diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c600e66..dd68e47 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,7 +40,7 @@ build esbuild 打包到 dist/(单 dist/app.js = src/ 模块按序 node --check app.js 与 dist/app.js 语法 check-dist.js 产物体检 lint ESLint(src/ + app.js,正确性规则) -test:unit 124 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底)) +test:unit 125 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底)) test relay-task-graph-fixture + iwb-v32-web-test test:facts 事实基线守门(见 §5) typecheck 渐进类型检查(tsc --noEmit;范围 = src/*.js,不含 app.js) @@ -102,7 +102,7 @@ IWB_WRITE_BOUNDARY_SNAPSHOT=1 node tests/architecture-boundary-guard-test.js # | 守卫 | 位置 | 现在的上限 | |---|---|---| -| `app.js` 总行数 | `tests/source-text-ratchet-test.js` `MAX_APP_JS_LINES` | **9,105**(另守「占总源码 ≤ 40%」,见 `MAX_APP_JS_SHARE`) | +| `app.js` 总行数 | `tests/source-text-ratchet-test.js` `MAX_APP_JS_LINES` | **9,134**(另守「占总源码 ≤ 40%」,见 `MAX_APP_JS_SHARE`) | | `Workbench()` 行数 | 同上 `MAX_WORKBENCH_LINES` | **3,046** | | 单组件行数(不含 Workbench)| 同上 `MAX_APP_COMPONENT_LINES` | **423** | diff --git a/app.js b/app.js index 255b95d..115c678 100644 --- a/app.js +++ b/app.js @@ -1297,8 +1297,28 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct ? { id: 'plugin-key', value: String((fromPlugin.keys && fromPlugin.keys[0] && fromPlugin.keys[0].value) || '') } : ((provider.keys || []).find((k) => k.id === keyGroupId) || (provider.keys || [])[0]) if (!fromPlugin && (!key || !key.value)) throw new Error('未配置该 Key 分组(设置 → 生图服务)') - const baseUrl = (_wCfgShape && _wCfgShape.normalizeEndpointBase) ? _wCfgShape.normalizeEndpointBase(provider.baseUrl) : String(provider.baseUrl || '').trim() - return { provider, key, baseUrl, genPath: provider.genPath || '/images/generations', editPath: provider.editPath || '/images/edits' } + const norm = (u) => (_wCfgShape && _wCfgShape.normalizeEndpointBase) ? _wCfgShape.normalizeEndpointBase(u) : String(u || '').trim() + const baseUrl = norm(provider.baseUrl) + // 备用地址(2026-11-24,v3.26.65):此前 fallbacks 只给 LLM 用,生图永远只打主地址。 + // 这里统一成候选列表:主地址优先,其余去重去空。 + const addrs = [] + for (const u of [baseUrl].concat((provider.fallbacks || []).map(norm))) { + if (u && addrs.indexOf(u) < 0) addrs.push(u) + } + return { + provider, key, baseUrl, addrs, + genPath: provider.genPath || '/images/generations', + editPath: provider.editPath || '/images/edits', + auth: provider.auth || null, + } + } + // 端点与鉴权工具(2026-11-24):genPath 生效 + auth 四态 + 地址候选。两处(生图/分层)共用。 + function wEndpointTools(genPath, auth, keyValue) { + const EP = (typeof window !== 'undefined' && window.IWBGenerationEndpoint) ? window.IWBGenerationEndpoint : null + const endpointOf = (base) => EP ? EP.joinEndpoint(base, genPath) : String(base || '') + (genPath || '/images/generations') + const headersOf = (extra) => EP ? EP.buildAuthHeaders(auth, keyValue, extra || {}) : Object.assign({}, extra || {}, { Authorization: 'Bearer ' + keyValue }) + const urlOf = (base) => EP ? EP.applyAuthQuery(endpointOf(base), auth, keyValue) : endpointOf(base) + return { endpointOf, headersOf, urlOf } } function wApiError(message, type, status) { const e = new Error(message || '请求失败') @@ -1364,8 +1384,11 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct return e ? (typeof e === 'string' ? e : JSON.stringify(e).slice(0, 200)) : 'HTTP 请求失败' } async function wGenerate(args) { - const { key, baseUrl, provider } = wResolveKey(args.providerId, args.keyGroupId) - const headers = { Authorization: 'Bearer ' + key.value } + const { key, provider, addrs, genPath, auth } = wResolveKey(args.providerId, args.keyGroupId) + // 端点/鉴权统一走 wEndpointTools(genPath 从此生效;鉴权支持 bearer/header/query/none) + const EP = (typeof window !== 'undefined' && window.IWBGenerationEndpoint) ? window.IWBGenerationEndpoint : null + const { headersOf, urlOf } = wEndpointTools(genPath, auth, key.value) + const jsonHeaders = () => headersOf({ 'Content-Type': 'application/json' }) const refs = (args.refs || []).filter((r) => r && r.value) const badRef = refs.find((r) => { const value = String(r.value || '').trim() @@ -1425,7 +1448,10 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct if (localCtrl && ext) { if (ext.aborted) onExtAbort(); else ext.addEventListener('abort', onExtAbort, { once: true }) } const hardTimer = localCtrl ? setTimeout(() => { hardTimedOut = true; try { localCtrl.abort() } catch (e) { /* ignore */ } }, GEN_HARD_TIMEOUT_MS) : null try { - const post = (body) => wFetch(baseUrl + '/images/generations', { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal: localCtrl ? localCtrl.signal : (args && args.signal), softTimeout: !!(args && args.softTimeout), onSoftTimeout: args && args.onSoftTimeout }, GEN_TIMEOUT_MS) + let curBase = addrs[0] || '' + const post = (body) => wFetch(urlOf(curBase), { method: 'POST', headers: jsonHeaders(), body: JSON.stringify(body), signal: localCtrl ? localCtrl.signal : (args && args.signal), softTimeout: !!(args && args.softTimeout), onSoftTimeout: args && args.onSoftTimeout }, GEN_TIMEOUT_MS) + // 一次完整尝试(含 quality 降档)—— 地址级重试在外层循环,见下 + const runOnce = async () => { let resp = await post(payload) let parsed = await resp.json().catch(() => null) if (hardTimedOut) throw wApiError(genHardTimeoutMessage(), 'hard-timeout') @@ -1469,6 +1495,10 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct } } catch (e) { /* 观测失败不影响生成 */ } return [{ ok: true, url: item.url.trim(), width: item.width || 0, height: item.height || 0 }] + } + // 地址回退(2026-11-24):主地址失败且「可安全重试」时换备用地址;循环在 src/generation-endpoint.js + if (!EP) return await runOnce() + return await EP.runWithAddresses(addrs, runOnce, (b) => { curBase = b }) } catch (e) { // 硬超时优先:无论是等头还是读体被中止,都统一报「结果未知」,交给用户决定是否重试 if (hardTimedOut && !(e && e.iwbType === 'cancel')) throw wApiError(genHardTimeoutMessage(), 'hard-timeout') @@ -1514,8 +1544,9 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct return m || fallback || '分层请求失败' } async function wDecomposeLayers(args) { - const { key, baseUrl } = wResolveKey(args.providerId, args.keyGroupId) - const headers = { Authorization: 'Bearer ' + key.value } + const { key, provider, addrs, genPath, auth } = wResolveKey(args.providerId, args.keyGroupId) + const { headersOf, urlOf } = wEndpointTools(genPath, auth, key.value) + const jsonHeaders = () => headersOf({ 'Content-Type': 'application/json' }) const img = String((args && args.image) || '').trim() if (!/^https?:\/\//i.test(img) && !/^data:image\/[^;]+;base64,/i.test(img)) { throw wApiError('分层需要一张图片:仅允许公网 URL 或本地图片 Base64', 'param') @@ -1542,7 +1573,8 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct if (localCtrl && ext) { if (ext.aborted) onExtAbort(); else ext.addEventListener('abort', onExtAbort, { once: true }) } const hardTimer = localCtrl ? setTimeout(() => { hardTimedOut = true; try { localCtrl.abort() } catch (e) { /* ignore */ } }, GEN_HARD_TIMEOUT_MS) : null try { - const postLayer = (body) => wFetch(baseUrl + '/images/generations', { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal: localCtrl ? localCtrl.signal : (args && args.signal), softTimeout: !!(args && args.softTimeout), onSoftTimeout: args && args.onSoftTimeout }, GEN_TIMEOUT_MS) + let curBase = addrs[0] || '' + const postLayer = (body) => wFetch(urlOf(curBase), { method: 'POST', headers: jsonHeaders(), body: JSON.stringify(body), signal: localCtrl ? localCtrl.signal : (args && args.signal), softTimeout: !!(args && args.softTimeout), onSoftTimeout: args && args.onSoftTimeout }, GEN_TIMEOUT_MS) const resp = await postLayer(payload) const parsed = await resp.json().catch(() => null) if (hardTimedOut) throw wApiError(genHardTimeoutMessage(), 'hard-timeout') diff --git a/docs/analysis/2026-11-24-local-images-and-api-gaps.md b/docs/analysis/2026-11-24-local-images-and-api-gaps.md index 2157848..5ff2bd4 100644 --- a/docs/analysis/2026-11-24-local-images-and-api-gaps.md +++ b/docs/analysis/2026-11-24-local-images-and-api-gaps.md @@ -37,6 +37,9 @@ ## 3. 生图 API 的缺陷(排除 LLM) +> **2026-11-24 更新(v3.26.65)**:#1 `genPath/editPath` 生效、#2 `auth` 可配(bearer/header/query/none)、 +> #3 `fallbacks` 接入生图(含"结果未知不重试"判据),三条已修并实测通过(见本节末尾「已修证据」)。 + | # | 缺陷 | 证据 | 后果 | |---|---|---|---| | 1 | `genPath`/`editPath` **是死设置** | UI 有输入框(`src/ui-settings-sections.js:1152`),但生图/分层都硬编码 `/images/generations`(`app.js:1428`、`app.js:1545`),`editPath` 零调用点 | 非标准路径的网关接不了 | @@ -50,6 +53,13 @@ | 9 | 无"测试连接"(只有地址 ping,不验 key/model) | `api('ping')` → `wPing`(`app.js:1735`) | 配错只能在生图时暴露 | | 10 | 响应解析写死 `data[0].url` | `app.js:1452` | 非标返回只能靠 custom 模板硬凑 | +**已修证据(v3.26.65,e2e 探针实测)**: +- 自定义路径:配置 `genPath:/custom/gen` ⇒ 请求 URL 为 `https:///v1/custom/gen` +- 自定义鉴权:`auth:{type:"header",headerName:"x-api-key"}` ⇒ 请求头 `x-api-key: sk-…` 且无 `Authorization`; + `auth:{type:"query",queryName:"key"}` ⇒ URL 追加 `?key=…` +- 备用地址:主地址连接失败 ⇒ 自动打 fallbacks[0](`bad.test` → `fake.test` 实测) +- 单测:`tests/generation-endpoint-test.js`(端点拼接 / 鉴权四态 / 重试判据 / 地址循环 + 接线负数断言) + ## 4. 建议(按目标排序) ### 批 1 本地图片「进得来、看得见」 diff --git a/docs/standards/architecture-current-state.md b/docs/standards/architecture-current-state.md index eeb9f26..1657861 100644 --- a/docs/standards/architecture-current-state.md +++ b/docs/standards/architecture-current-state.md @@ -22,7 +22,7 @@ - 图片**新写入主通道 = IndexedDB Blob `{__blob}` / key `imgblob__`** (A) `app.js:2143`;`{__cache}`(Cache Storage)为兜底;\`ref_\`(`app.js` 内定义的 `IDB_REF_PREFIX = 'ref_'`)为 legacy 形态 (A)。 - 大图判定:`isBigDataUrl` = `data:` 且 `length > 3000` (A) `app.js:2018`;**画布保存保留阈值** `< 16384` 才原样保留 (A) `app.js:2182`。**两处阈值并存,含义不同**。 - 单测是**源码契约测试**:`tests/` 目录共 **493** 处源码文本钉点(`source.includes` / `source.indexOf` / `/re/.test(source)`),分布在 **20** 个文件(其中 `iwb-v32-web-test.js` 一个就占 **407**)→ **结构性重构会先打红测试**。**该数字已由 `tests/source-text-ratchet-test.js` 的「只减不增」棘轮守门**(2026-10-20 起守卫范围从 1 个文件扩到全目录:新增任何一处源码文本钉点都会打红)。**2026-11-12 复算**(`npm run audit:pins`,v3.24.76):二分 STRUCT **417** / NAME **76**;形态 **POS 403 / NEG 87 / COUNT 3**;难度 **易 62 / 中 316 / 难 115**。钉点减法第一批(v3.24.72)把 **537 → 505**:8 条探针钉点改为「门禁内 spec 是否真的读该计数器」、5 条改为运行时断言(生产态 `window` 上无探针)、10 条改为 DOM 断言(质量档位禁用 / 传输页无三模式按钮 / 模型项 title)、4 条改为运行时对象断言(健康检查两域、策略对象冻结)、其余 9 条有同文件 DOM 等价断言或仅剩 NEG。第二批(v3.24.76)把 **505 → 493**:94-5~7 三条「多标签释放语义」(10 处正则)换成 `tests/iwb-tabs-release.spec.js` 的 3 条真 e2e,剩 1 条「消费方契约」(断言该 spec 在门禁内且 spec 源码真的读两个探针);另 2 条 `wPurgeIntent.add` 钉点改为读 `src/workspace-purge.js`。**这一批一换就查出 3 个真缺陷**(objectURL 从未释放 / 彻底删除留孤儿标签 · session / 刷新后误回收打开标签的图)—— 见 CHANGELOG v3.24.76。 -- `app.js` = 单 IIFE **9,102 行**(**双层预算**:绝对上限 9,105 / 占总源码 ≤ 40%,现 **30.6%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **3,044 行**(上限 **3,046**,余量 2;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **107** 个模块 / 20,633 行,`sourceModules` 107 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。 +- `app.js` = 单 IIFE **9,134 行**(**双层预算**:绝对上限 9,134 / 占总源码 ≤ 40%,现 **30.6%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **3,044 行**(上限 **3,046**,余量 2;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **108** 个模块 / 20,763 行,`sourceModules` 108 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。 - 门禁:`npm run verify` = `verify:ci`(`build` → `node --check app.js` → `node --check dist/app.js` → `check-dist.js` → `lint`(ESLint 正确性规则,`src/` + `app.js`,P4-16a)→ `test:unit` → `test` → `test:facts`)+ `test:e2e` (A) `package.json`。 ## 2. 门禁与环境现状 @@ -167,7 +167,7 @@ - 同一张图被 3 个节点引用、hydrate 成 3 个不同 objectURL 时,preview/display 缓存各自 miss → 重复解码(与 F2 相邻)。 - **F10|`refs.genScheduler` 是桩** (A) → 未接线,暂无运行时影响(P3)。 - **F11|已建但未接线的模块层(2026-10-17 接线审计;2026-10-18 复核更正)** (A) - - **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**107 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。 + - **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**108 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。 - **仅被测试引用(9 模块 + 2 导出)**:`canvas-domain`、`generation-retry`、`generation-service`、`runtime-recovery-runner`、`runtime-state-bridge`、`runtime-store`、`storage-reconcile`、`storage-result`、`workspace-service`;导出 `IWBStorageHealthFactory`、`IWBPluginHostFactory`。(`storage-result` 是**存储层共享结果类型**,被 6 个存储模块读取,**非死代码**;`runtime-store` 为状态模型 epic 地基。) - **app.js 零引用(1 模块 + 3 导出)**:模块 `generation-controller`;导出 `IWBRuntimeMetricsFactory`、`IWBStorageRuntimeFactory`、`IWBUIComponents`。`canvas-relations` 已随 `06cf211` 删除(本文档早前把它列为"唯一可删者",实际已删)。零引用证据 = `grep -rn "<名字>" .`(排除 `node_modules|dist|vendor|test-results`)**只命中其自身赋值行**。 - **半接线 / 未接线**:`IWBRuntimeStateBridge` **无 app.js 引用(仅测试)**;`IWBRuntimeRunContext` **已接线**(`runNode` 读取运行上下文);`IWBGenerationController` 是完整但**从未被调用**的工厂;`ModularWorkspaceStore`(`app.js` 内)是 `storage-workspace` 的**预留接线 seam**(当前无下游使用,保留);`window.IWBImageFolder` 自注册后读回(装载路径)。 @@ -183,7 +183,7 @@ | `storage-reconcile` | 存储对账(`createReconciler`/`check`) | 内联对账 | 存储层收口 | | `runtime-recovery-runner` | 执行恢复候选(`candidate`/`valid`/`run`) | 内联恢复 | 断点恢复 | | `canvas-domain` | 画布域模型(`commit`/`updateNode`/`deleteNodes`…) | `CanvasStore` 那一套 | Workbench 解耦(P2-9) | - - **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**88** 项)与 `sourceModules` 顺序(**107** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 + - **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**89** 项)与 `sourceModules` 顺序(**108** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 ## 12. 易踩的坑 @@ -254,7 +254,7 @@ **信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。 -**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**88** 项)与 `sourceModules` 顺序(**107** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。 +**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**89** 项)与 `sourceModules` 顺序(**108** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。 **关键陷阱**:`normalizeNodes`(现位于 `src/canvas-normalize.js`)会**静默丢弃**不在 `NODE_H` 里的节点类型 ⇒ 新增节点类型必须先登记 `NODE_H`,否则节点一刷新就消失(§13.27 规则三的同一失败模式)。 diff --git a/package.json b/package.json index 0e4445a..a2fea1a 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "app:build": "tauri build", "lint": "eslint src app.js", "test": "node tests/relay-task-graph-fixture-test.js && node tests/plugin-style-node-test.js && node tests/inherit-text-test.js", - "test:unit": "node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-test.js && node tests/design-tokens-component-doc-test.js && node tests/theme-static-snapshot-test.js && node tests/overlay-layer-test.js && node tests/settings-scope-test.js && node tests/node-scope-test.js && node tests/appearance-v2-test.js && node tests/image-prompt-cover-test.js && node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/gallery-sync-test.js && node tests/image-blob-store-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-gallery-ux-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/plugin-theme-contract-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/native-overlay-park-test.js && node tests/ui-dock-sanitize-test.js && node tests/ui-minimap-fit-test.js && node tests/ui-workbench-hooks-test.js && node tests/plugin-scale-contract-test.js && node tests/design-token-ratchet-test.js && node tests/theme-contrast-test.js", + "test:unit": "node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-test.js && node tests/design-tokens-component-doc-test.js && node tests/theme-static-snapshot-test.js && node tests/overlay-layer-test.js && node tests/settings-scope-test.js && node tests/node-scope-test.js && node tests/appearance-v2-test.js && node tests/image-prompt-cover-test.js && node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/generation-endpoint-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/gallery-sync-test.js && node tests/image-blob-store-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-gallery-ux-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/plugin-theme-contract-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/native-overlay-park-test.js && node tests/ui-dock-sanitize-test.js && node tests/ui-minimap-fit-test.js && node tests/ui-workbench-hooks-test.js && node tests/plugin-scale-contract-test.js && node tests/design-token-ratchet-test.js && node tests/theme-contrast-test.js", "test:diagnostics": "node tests/runtime-diagnostics-hotpath-test.js", "test:facts": "node tests/architecture-facts-guard-test.js && node tests/release-records-test.js", "plugins:gc": "node scripts/plugins-publish.mjs --gc", diff --git a/scripts/build.js b/scripts/build.js index ee033c1..276a539 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -39,6 +39,7 @@ const sourceModules = [ 'clipboard-native.js', 'generation-size-policy.js', 'generation-request-shape.js', + 'generation-endpoint.js', 'canvas-actions.js', 'canvas-node-factory.js', 'storage-contract.js', diff --git a/src/generation-endpoint.js b/src/generation-endpoint.js new file mode 100644 index 0000000..1634a36 --- /dev/null +++ b/src/generation-endpoint.js @@ -0,0 +1,89 @@ +'use strict' +/* 生图端点与鉴权(2026-11-24,v3.26.65) + * + * 为什么单独成模块:仓库里原来有两处硬伤 —— + * ① 端点写死:`baseUrl + '/images/generations'`(app.js 两处),而配置里的 genPath/editPath + * 只是「存了、显示了、导出到公开配置」,从未参与拼 URL ⇒ 非标准路径的网关接不了; + * ② 鉴权写死:`Authorization: Bearer `(5 处),需要 `x-api-key` / `?key=` 的中转站接不了。 + * + * 本模块只做纯字符串/对象运算(不读配置、不发请求),便于 Node 下单测。 + * 边界:**不校验 key 是否有效**(那是服务端的事),只负责「按配置拼对」 + */ +;(function (global) { + const AUTH_TYPES = ['bearer', 'header', 'query', 'none'] + const DEFAULT_PATH = '/images/generations' + + const str = (v) => (v == null ? '' : String(v)) + + // 端点拼接:base 去尾斜杠、path 补首斜杠;path 是绝对 URL 时原样返回(少数网关给整条地址) + function joinEndpoint (base, path) { + const p = str(path).trim() || DEFAULT_PATH + if (/^https?:\/\//i.test(p)) return p + const b = str(base).trim().replace(/\/+$/, '') + const tail = p.charAt(0) === '/' ? p : '/' + p + return b + tail + } + + // 鉴权归一:缺省 = bearer(历史行为,不能改默认,否则老配置全挂) + function normalizeAuth (auth) { + const a = (auth && typeof auth === 'object') ? auth : null + const t = a ? str(a.type).trim().toLowerCase() : '' + if (AUTH_TYPES.indexOf(t) < 0) return { type: 'bearer' } + const out = { type: t } + if (t === 'header') out.headerName = str(a.headerName).trim() || 'x-api-key' + if (t === 'query') out.queryName = str(a.queryName).trim() || 'key' + return out + } + + // 请求头:head 是调用方已有的头(如 Content-Type),鉴权头叠加在上面 + function buildAuthHeaders (auth, keyValue, head) { + const out = Object.assign({}, head || {}) + const a = normalizeAuth(auth) + const v = str(keyValue) + if (a.type === 'none' || !v) return out + if (a.type === 'header') { out[a.headerName] = v; return out } + out.Authorization = 'Bearer ' + v + return out + } + + // URL 参数鉴权:已有同名参数时覆盖,避免出现两个 key + function applyAuthQuery (url, auth, keyValue) { + const a = normalizeAuth(auth) + const v = str(keyValue) + if (a.type !== 'query' || !v) return url + const u = str(url) + const sep = u.indexOf('?') >= 0 ? '&' : '?' + const re = new RegExp('([?&])' + a.queryName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '=[^&]*') + if (re.test(u)) return u.replace(re, '$1' + a.queryName + '=' + encodeURIComponent(v)) + return u + sep + a.queryName + '=' + encodeURIComponent(v) + } + + /* 失败后是否换下一个地址重试。判据是「这次失败有没有可能已经出图」: + * · 5xx / 429 / 连接失败 → 服务端没接住或明确拒绝,换地址安全; + * · 参数(400/422) / 鉴权(401/403) → 换地址也一样错,直接抛; + * · 超时 / hard-timeout / 用户取消 → **结果未知**,换地址重提可能重复计费,绝不重试。 + */ + function shouldRetryNextAddress (err) { + const t = err && err.iwbType + return t === 'server' || t === 'limit' || t === 'network' + } + + /* 地址循环:主地址失败且「可安全重试」时换下一个;结果未知(超时/hard-timeout)绝不重提。 + * attempt() 由调用方提供(它负责发请求并解析),onBase(base) 用来把当前地址交给闭包。 + * 放这里而不是 app.js:app.js 有行数棘轮,循环属于「请求编排」的通用件。 */ + async function runWithAddresses (addrs, attempt, onBase) { + const list = Array.isArray(addrs) && addrs.length ? addrs : [''] + let lastErr = null + for (let i = 0; i < list.length; i++) { + if (typeof onBase === 'function') onBase(list[i]) + try { return await attempt() } catch (e) { + lastErr = e + if (!shouldRetryNextAddress(e) || i >= list.length - 1) throw e + } + } + throw lastErr || new Error('请求失败') + } + + const API = Object.freeze({ AUTH_TYPES, DEFAULT_PATH, joinEndpoint, normalizeAuth, buildAuthHeaders, applyAuthQuery, shouldRetryNextAddress, runWithAddresses }) + if (global) global.IWBGenerationEndpoint = API +})(typeof window !== 'undefined' ? window : (typeof globalThis !== 'undefined' ? globalThis : this)) diff --git a/src/storage-config-shape.js b/src/storage-config-shape.js index d574d95..998b8fb 100644 --- a/src/storage-config-shape.js +++ b/src/storage-config-shape.js @@ -56,9 +56,29 @@ 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 @@ -133,7 +153,7 @@ return out } - return { normalizeEndpointBase, wClone, mergeDeep, wMask, wShapeProviderFields, wNormalizeImageModels, wNormalizeLayerModels, wMigrateLlm, storageResult, wStripDerived } + return { normalizeEndpointBase, wClone, mergeDeep, wMask, wShapeAuth, wShapeProviderFields, wNormalizeImageModels, wNormalizeLayerModels, wMigrateLlm, storageResult, wStripDerived } } // 地址归一化(2026-11-05):用户常把「完整接口地址」粘进 Base URL 输入框,而调用方还会再拼一次 diff --git a/src/ui-settings-sections.js b/src/ui-settings-sections.js index eafcc20..9b64cba 100644 --- a/src/ui-settings-sections.js +++ b/src/ui-settings-sections.js @@ -1157,6 +1157,26 @@ function GSetGroup (props) { keyRows, el('button', { className: 'iwb-btn iwb-btn-sm', onClick: () => addKey(pi) }, '+ 添加 Key 分组'), ), + // 认证方式(2026-11-24,v3.26.65):此前写死 Authorization: Bearer,接不了要 x-api-key / URL 参数的中转站。 + el(GSetGroup, { title: '认证', desc: '缺省 Bearer;部分中转站要自定义 Header 或 URL 参数' }, + (() => { + const auth = (p.auth && typeof p.auth === 'object') ? p.auth : { type: 'bearer' } + const t = ['bearer', 'header', 'query', 'none'].indexOf(auth.type) >= 0 ? auth.type : 'bearer' + const setAuth = (patch) => setProv(pi, { auth: Object.assign({ type: t }, auth, patch) }) + return el('div', { className: 'iwb-gset-row' }, + el('div', { className: 'iwb-gset-row-label' }, '方式'), + el('div', { className: 'iwb-gset-row-ctl' }, + el('select', { className: 'iwb-input iwb-grow', 'aria-label': '认证方式', value: t, onChange: (e) => setAuth({ type: e.target.value }) }, + el('option', { value: 'bearer' }, 'Bearer(默认)'), + el('option', { value: 'header' }, '自定义 Header'), + el('option', { value: 'query' }, 'URL 参数'), + el('option', { value: 'none' }, '无鉴权'), + ), + t === 'header' ? el('input', { className: 'iwb-input iwb-grow', value: auth.headerName || '', placeholder: 'Header 名,如 x-api-key(默认)', onChange: (e) => setAuth({ headerName: e.target.value }) }) : null, + t === 'query' ? el('input', { className: 'iwb-input iwb-grow', value: auth.queryName || '', placeholder: '参数名,如 key(默认)', onChange: (e) => setAuth({ queryName: e.target.value }) }) : null, + ), + ) + })()), el(GSetGroup, { title: '请求分类', desc: '决定请求体怎么发尺寸' }, shapeBox, ), diff --git a/tests/fixtures/iwb-app-global-reads.json b/tests/fixtures/iwb-app-global-reads.json index a683126..9570a6a 100644 --- a/tests/fixtures/iwb-app-global-reads.json +++ b/tests/fixtures/iwb-app-global-reads.json @@ -14,6 +14,7 @@ "IWBDockArea", "IWBGalleryHydration", "IWBGallerySync", + "IWBGenerationEndpoint", "IWBGenerationRequestShape", "IWBGenerationResults", "IWBGenerationScheduler", diff --git a/tests/fixtures/iwb-source-modules-order.json b/tests/fixtures/iwb-source-modules-order.json index 6f2fe43..9291c43 100644 --- a/tests/fixtures/iwb-source-modules-order.json +++ b/tests/fixtures/iwb-source-modules-order.json @@ -11,6 +11,7 @@ "clipboard-native.js", "generation-size-policy.js", "generation-request-shape.js", + "generation-endpoint.js", "canvas-actions.js", "canvas-node-factory.js", "storage-contract.js", diff --git a/tests/generation-endpoint-test.js b/tests/generation-endpoint-test.js new file mode 100644 index 0000000..ad87224 --- /dev/null +++ b/tests/generation-endpoint-test.js @@ -0,0 +1,81 @@ +'use strict' +// src/generation-endpoint.js 的行为契约(2026-11-24) +// +// 守的是什么: +// · joinEndpoint —— genPath 必须真正生效(配置项此前是死的),且尾斜杠/绝对地址/空路径都要对 +// · buildAuthHeaders —— 缺省必须是 Bearer(老配置不能挂),header/query/none 各走各的 +// · applyAuthQuery —— 同名参数覆盖,不能出现两个 key +// · shouldRetryNextAddress —— **结果未知不重试**(超时/hard-timeout),只换 5xx/429/连接失败 +const assert = require('assert') +const fs = require('fs') +const path = require('path') +// 仓库风格:src/*.js 是 UMD 全局脚本(不认 CommonJS),测试用沙箱加载 +const box = {} +new Function('window', 'globalThis', fs.readFileSync(path.join(__dirname, '..', 'src', 'generation-endpoint.js'), 'utf8'))(box, box) +const E = box.IWBGenerationEndpoint +assert.ok(E && typeof E.joinEndpoint === 'function', 'src/generation-endpoint.js 应导出 IWBGenerationEndpoint') + +const eq = (a, b, msg) => assert.strictEqual(JSON.stringify(a), JSON.stringify(b), msg) + +// ── joinEndpoint ── +assert.strictEqual(E.joinEndpoint('https://a.test/v1', '/custom/gen'), 'https://a.test/v1/custom/gen', '常规拼接') +assert.strictEqual(E.joinEndpoint('https://a.test/v1/', 'custom/gen'), 'https://a.test/v1/custom/gen', 'base 尾斜杠 + 无首斜杠') +assert.strictEqual(E.joinEndpoint('https://a.test/v1', ''), 'https://a.test/v1/images/generations', '空路径回落默认') +assert.strictEqual(E.joinEndpoint('https://a.test/v1', 'https://b.test/api'), 'https://b.test/api', 'path 是绝对 URL 时原样返回') +assert.strictEqual(E.joinEndpoint('', '/x'), '/x', 'base 为空时至少产出路径') + +// ── normalizeAuth ── +eq(E.normalizeAuth(null), { type: 'bearer' }, '缺省=Bearer(老配置行为不变)') +eq(E.normalizeAuth({ type: 'bogus' }), { type: 'bearer' }, '未知类型回落 Bearer') +eq(E.normalizeAuth({ type: 'HEADER', headerName: 'x-api-key' }), { type: 'header', headerName: 'x-api-key' }, 'type 大小写归一') +eq(E.normalizeAuth({ type: 'header' }), { type: 'header', headerName: 'x-api-key' }, 'header 名缺省') +eq(E.normalizeAuth({ type: 'query' }), { type: 'query', queryName: 'key' }, 'query 名缺省') + +// ── buildAuthHeaders ── +eq(E.buildAuthHeaders(null, 'sk-1', { 'Content-Type': 'application/json' }), { 'Content-Type': 'application/json', Authorization: 'Bearer sk-1' }, 'Bearer 是缺省') +eq(E.buildAuthHeaders({ type: 'header', headerName: 'x-api-key' }, 'sk-2'), { 'x-api-key': 'sk-2' }, '自定义 header') +eq(E.buildAuthHeaders({ type: 'none' }, 'sk-3'), {}, '无鉴权 不写头') +eq(E.buildAuthHeaders({ type: 'bearer' }, ''), {}, '空 key 不写头(让服务端报 401,而不是发空 Bearer)') + +// ── applyAuthQuery ── +assert.strictEqual(E.applyAuthQuery('https://a.test/x', { type: 'query', queryName: 'key' }, 'k 1'), 'https://a.test/x?key=k%201', '新增参数并编码') +assert.strictEqual(E.applyAuthQuery('https://a.test/x?key=old', { type: 'query', queryName: 'key' }, 'new'), 'https://a.test/x?key=new', '同名参数覆盖') +assert.strictEqual(E.applyAuthQuery('https://a.test/x?a=1', { type: 'query', queryName: 'key' }, 'k'), 'https://a.test/x?a=1&key=k', '已有其他参数时用 &') +assert.strictEqual(E.applyAuthQuery('https://a.test/x', { type: 'bearer' }, 'k'), 'https://a.test/x', '非 query 鉴权不改 URL') + +// ── shouldRetryNextAddress:结果未知绝不重试 ── +for (const t of ['server', 'limit', 'network']) assert.strictEqual(E.shouldRetryNextAddress({ iwbType: t }), true, t + ' 应换地址') +for (const t of ['param', 'auth', 'permission', 'timeout', 'hard-timeout', 'cancel', 'unknown', undefined]) assert.strictEqual(E.shouldRetryNextAddress({ iwbType: t }), false, String(t) + ' 不应换地址(结果未知/换也没用)') + + +// ── 接线契约(负数断言):防止有人把端点/鉴权又写死回 app.js ── +// 背景:genPath/auth 曾经「配置里有、代码里没用」,只靠模块单测发现不了这种回归。 +const appSrc = fs.readFileSync(path.join(__dirname, '..', 'app.js'), 'utf8') +assert.ok(appSrc.indexOf("baseUrl + '/images/generations'") < 0, 'app.js 不得再硬编码 /images/generations(应用 genPath)') +// 生图/分层两条路径此前是 `const headers = { Authorization: 'Bearer ' + key.value }`; +// LLM 与 /models 探测仍是 Bearer(本次不改),所以只钉「生图那行的旧形状」 +assert.ok(!/const headers = \{ Authorization: 'Bearer ' \+ key\.value \}/.test(appSrc), '生图不得再硬编码 Bearer 鉴权(应用 headersOf)') +assert.ok(appSrc.indexOf('urlOf(curBase)') >= 0, '生图请求应经 urlOf() 拼地址') +assert.ok(appSrc.indexOf('headersOf(') >= 0, '生图请求头应经 headersOf() 生成') +assert.ok(appSrc.indexOf('addrs') >= 0, '应使用候补地址列表(fallbacks 生效)') +// ── runWithAddresses:换地址策略的端到端行为 ── +;(async () => { + const seen = [] + const addrs = ['https://a.test/v1', 'https://b.test/v1'] + let n = 0 + const ok = await E.runWithAddresses(addrs, async () => { n++; if (n === 1) { const e = new Error('503'); e.iwbType = 'server'; throw e } return 'done' }, (b) => seen.push(b)) + assert.strictEqual(ok, 'done', '第一次失败(5xx)后应换地址并成功') + assert.strictEqual(n, 2, '应尝试两次') + eq(seen, addrs, 'onBase 应按顺序告知当前地址') + + let m = 0 + await assert.rejects(async () => E.runWithAddresses(addrs, async () => { m++; const e = new Error('timeout'); e.iwbType = 'timeout'; throw e }), /timeout/) + assert.strictEqual(m, 1, '超时属结果未知 ⇒ 只试一次(防重复计费)') + + let k = 0 + const one = await E.runWithAddresses([], async () => { k++; return 'x' }) + assert.strictEqual(one, 'x', '无候选地址时也执行一次(用空 base)') + assert.strictEqual(k, 1, '空列表不循环') + + console.log('generation endpoint checks passed(端点拼接 / 鉴权四态 / 地址回退判据 / 地址循环)') +})().catch((e) => { console.error(e); process.exit(1) }) diff --git a/tests/source-text-ratchet-test.js b/tests/source-text-ratchet-test.js index 5b3d8cd..508106d 100644 --- a/tests/source-text-ratchet-test.js +++ b/tests/source-text-ratchet-test.js @@ -157,7 +157,13 @@ const MAX_SRC_COMPONENT_LINES = 531 // ② 纠正过时的存储口径注释(用户要求:旧的不准确描述要改掉):图库/缩略图/原图档在桌面端是 // images/thumbs、images/gallery 文件,不是 IndexedDB;「1K 插入档降的是长边像素不是体积」。 // 共 6 行注释,属于事实纠错而非功能代码。 -const MAX_APP_JS_LINES = 9105 // 2026-11-24 v3.26.63:收敛确认包装(7 份 → 1 份)+ 剪贴板 5 处改走门面,实测 9104 → 上限 9105 +// 2026-11-24 v3.26.65:9105 → **9133**(+28,生图 API 三处硬伤修复,逐条记账): +// · wResolveKey 返回多地址候选 addrs(含 fallbacks 去重) +6 +// · 生图/分层改用 wEndpointTools(genPath 生效 + auth 四态) +12(两处各约 6) +// · 地址回退调用(循环本体已下沉 src/generation-endpoint.js) +3 +// · 兼容兜底与注释 +7 +// 通用件(joinEndpoint / buildAuthHeaders / applyAuthQuery / runWithAddresses)全部在 src/,app.js 只做装配。 +const MAX_APP_JS_LINES = 9134 const MAX_APP_JS_SHARE = 0.40 // ── 历史记账(供回溯,逐条保留)────────────────────────────────────────────── diff --git a/tests/storage-config-shape-test.js b/tests/storage-config-shape-test.js index 83b5623..742e919 100644 --- a/tests/storage-config-shape-test.js +++ b/tests/storage-config-shape-test.js @@ -225,4 +225,16 @@ const mig2 = S.wMigrateLlm({ providers: [{ id: 'l0', name: 'a', baseUrl: 'https: 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 个纯函数的行为契约,含深合并与内置模型强制可见)')