dsh-token-dash 2.6.0 → 2.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client.js +14 -2
- package/index.js +38 -5
- package/locale/en.json +3 -1
- package/locale/zh.json +3 -1
- package/package.json +2 -2
- package/src/core.js +5 -3
- package/src/pricing.js +101 -1
- package/src/store.js +30 -0
package/client.js
CHANGED
|
@@ -72,7 +72,7 @@ window.__ModuleLoader__.load({
|
|
|
72
72
|
const EN = {
|
|
73
73
|
'当天': 'Today', '近7天': 'Last 7 days', '近30天': 'Last 30 days', '全部': 'All',
|
|
74
74
|
'30秒': '30s', '1分钟': '1m', '5分钟': '5m',
|
|
75
|
-
'社区': 'Community', '内置兜底': 'Built-in fallback',
|
|
75
|
+
'社区': 'Community', '内置兜底': 'Built-in fallback', '离线缓存': 'Offline cache', '内置目录': 'Built-in catalog',
|
|
76
76
|
'查询失败': 'Query failed', '套餐查询失败': 'Quota query failed',
|
|
77
77
|
'不限量': 'Unlimited', '自动': 'Auto', '手动': 'Manual', '国内': 'China', '国际': 'Global',
|
|
78
78
|
'中国': 'China', '海外': 'Global', '切换区域:中国 / 海外': 'Switch region: China / global',
|
|
@@ -2349,7 +2349,19 @@ window.__ModuleLoader__.load({
|
|
|
2349
2349
|
`v${version} · ${tr('价格表')} ${formatCatalogTime(catalog?.updatedAt)}`,
|
|
2350
2350
|
catalog?.url
|
|
2351
2351
|
? h('a', { href: catalog.url, target: '_blank', rel: 'noopener', style: { ...styles.link, color: T.muted, marginLeft: 4 } }, tr('社区'))
|
|
2352
|
-
: h('span', { style: { marginLeft: 4 } }, sourceLabel(catalog?.source))
|
|
2352
|
+
: h('span', { style: { marginLeft: 4 } }, sourceLabel(catalog?.source)),
|
|
2353
|
+
// 离线 / 内置时把来源说清楚:此刻的估算用哪份目录算的,用户一眼能分辨
|
|
2354
|
+
catalog?.degraded === true
|
|
2355
|
+
? h('span', {
|
|
2356
|
+
'data-testid': 'token-dash-catalog-degraded',
|
|
2357
|
+
title: catalog?.reason === 'offline-cache'
|
|
2358
|
+
? tr('离线启动,使用上一次成功拉取的价目表')
|
|
2359
|
+
: tr('未能联网,使用内置目录,部分模型会显示未定价'),
|
|
2360
|
+
style: { marginLeft: 4, color: T.weak },
|
|
2361
|
+
}, catalog?.reason === 'offline-cache'
|
|
2362
|
+
? `· ${tr('离线缓存')}${catalog?.fetchedAt ? ` ${formatCatalogTime(catalog.fetchedAt)}` : ''}`
|
|
2363
|
+
: `· ${tr('内置目录')}`)
|
|
2364
|
+
: null),
|
|
2353
2365
|
h('span', { style: { flex: 1 } }),
|
|
2354
2366
|
h('span', {
|
|
2355
2367
|
'data-testid': 'token-dash-settings-status', role: 'status', 'aria-live': 'polite',
|
package/index.js
CHANGED
|
@@ -7,11 +7,11 @@ import { spawn } from 'node:child_process'
|
|
|
7
7
|
import { dirname, join } from 'node:path'
|
|
8
8
|
import { buildSummary, buildUsage, emptyState, localMonthKey, num, repriceState, repriceUnpriced, resolveProviderKind, stampProviderKinds } from './src/core.js'
|
|
9
9
|
import { ingest, backfill } from './src/collect.js'
|
|
10
|
-
import { REFRESH_OPTIONS, createFlusher, dataDir, loadPrefs, loadState, logsDir, normalizeCurrencyMap, normalizeOverrides, normalizeRegionMap, recoverState, resolveHome, saveJson, saveMonths } from './src/store.js'
|
|
10
|
+
import { CATALOG_CACHE_NAMES, REFRESH_OPTIONS, createFlusher, dataDir, loadCatalogCache, loadPrefs, loadState, logsDir, normalizeCurrencyMap, normalizeOverrides, normalizeRegionMap, recoverState, resolveHome, saveCatalogCache, saveJson, saveMonths } from './src/store.js'
|
|
11
11
|
import { buildExport, mergeImportDays, validateBundle } from './src/backup.js'
|
|
12
12
|
import { logAdapterEvents, logAdapterFailures, missSignature, readProviders, readSubscriptions, resetRegionPins } from './src/adapters.js'
|
|
13
13
|
import { PROVIDER_SOURCES } from './src/quota-sources.js'
|
|
14
|
-
import { catalogInfo, configurePricing, loadCommunityPricing, loadRouterPricing } from './src/pricing.js'
|
|
14
|
+
import { catalogInfo, configurePricing, loadCommunityPricing, loadRouterPricing, restoreCatalogCache } from './src/pricing.js'
|
|
15
15
|
import { providerCurrency } from './src/providers.js'
|
|
16
16
|
import { clearLog, createLogger, exportLog, pruneLogs } from './src/diagnostics.js'
|
|
17
17
|
import { isNewer, sameBase } from './src/version.js'
|
|
@@ -258,7 +258,14 @@ export function apply(ctx) {
|
|
|
258
258
|
const currencyOf = (id) => prefs?.providerCurrency?.[id] ?? metaOf(id)?.currency ?? providerCurrency(id)
|
|
259
259
|
let pricingConfigLogged = ''
|
|
260
260
|
const applyPricingConfig = () => {
|
|
261
|
-
configurePricing({
|
|
261
|
+
configurePricing({
|
|
262
|
+
overrides: prefs?.priceOverrides ?? {},
|
|
263
|
+
currencyOf,
|
|
264
|
+
// 只有联网成功路径会调用;离线启动不覆盖上一次成功的缓存
|
|
265
|
+
persistCatalog: (kind, payload) => {
|
|
266
|
+
void saveCatalogCache(dir, kind, payload, logger).catch(() => {})
|
|
267
|
+
},
|
|
268
|
+
})
|
|
262
269
|
const overrides = Object.keys(prefs?.priceOverrides ?? {}).length
|
|
263
270
|
const currencies = Object.keys(prefs?.providerCurrency ?? {}).length
|
|
264
271
|
const signature = `${overrides}/${currencies}`
|
|
@@ -299,16 +306,42 @@ export function apply(ctx) {
|
|
|
299
306
|
}
|
|
300
307
|
}, 'dsh-token-dash: store')
|
|
301
308
|
|
|
302
|
-
//
|
|
309
|
+
// 价格表必须先于重算就绪。三级回退:本次联网 → 上次成功的盘上缓存 → 内置目录。
|
|
303
310
|
const pricingReady = ready.then(async () => {
|
|
311
|
+
// 先读缓存,离线重启也能按上一次成功的目录估算,而不是直接跌回 14 个内置模型
|
|
312
|
+
try {
|
|
313
|
+
const [community, router] = await Promise.all([
|
|
314
|
+
loadCatalogCache(dir, 'community', logger),
|
|
315
|
+
loadCatalogCache(dir, 'router', logger),
|
|
316
|
+
])
|
|
317
|
+
const restored = restoreCatalogCache({ community, router })
|
|
318
|
+
logger.info('pricing', 'catalog.cache.restore', {
|
|
319
|
+
community: community !== null,
|
|
320
|
+
router: router !== null,
|
|
321
|
+
restored,
|
|
322
|
+
fetchedAt: community?.fetchedAt ?? null,
|
|
323
|
+
})
|
|
324
|
+
} catch (error) {
|
|
325
|
+
logger.warn('pricing', 'catalog.cache.fail', { message: String(error?.message ?? error) })
|
|
326
|
+
}
|
|
327
|
+
applyPricingConfig()
|
|
304
328
|
await Promise.allSettled([
|
|
305
329
|
loadCommunityPricing()
|
|
306
330
|
.then((info) => logger.info('pricing', 'catalog.loaded', info))
|
|
307
331
|
.catch((error) => logger.warn('pricing', 'catalog.fail', { message: String(error?.message ?? error) })),
|
|
308
332
|
loadRouterPricing()
|
|
309
|
-
.then((ok) =>
|
|
333
|
+
.then((ok) => {
|
|
334
|
+
logger.info('pricing', 'router.loaded', { ok })
|
|
335
|
+
// 联网失败不丢上一次成功的表:缓存已在 restore 阶段载入
|
|
336
|
+
if (!ok) logger.warn('pricing', 'router.degraded', { origin: catalogInfo().routerOrigin })
|
|
337
|
+
})
|
|
310
338
|
.catch((error) => logger.warn('pricing', 'router.fail', { message: String(error?.message ?? error) })),
|
|
311
339
|
])
|
|
340
|
+
const info = catalogInfo()
|
|
341
|
+
logger.info('pricing', 'catalog.ready', {
|
|
342
|
+
source: info.source, origin: info.origin, models: info.models,
|
|
343
|
+
routerModels: info.routerModels, degraded: info.degraded, reason: info.reason,
|
|
344
|
+
})
|
|
312
345
|
applyPricingConfig()
|
|
313
346
|
})
|
|
314
347
|
|
package/locale/en.json
CHANGED
|
@@ -153,5 +153,7 @@
|
|
|
153
153
|
"切换区域:自动 / 国内 / 国际": "Switch region: auto / China / global",
|
|
154
154
|
"中国": "China",
|
|
155
155
|
"海外": "Global",
|
|
156
|
-
"切换区域:中国 / 海外": "Switch region: China / global"
|
|
156
|
+
"切换区域:中国 / 海外": "Switch region: China / global",
|
|
157
|
+
"离线缓存": "Offline cache",
|
|
158
|
+
"内置目录": "Built-in catalog"
|
|
157
159
|
}
|
package/locale/zh.json
CHANGED
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-token-dash",
|
|
3
|
-
"version": "2.6.
|
|
4
|
-
"description": "DeepSeek Harness Token 与费用看板:9 家供应商开箱即用,按供应商查看预算、订阅配额(GLM / Kimi / OpenCode Go / Command Code / MiniMax)与账户余额,MiniMax 自动识别国内 / 国际站并支持按量 Key 余额,GLM / Kimi / Qwen 可在卡顶切换中国 / 海外区域;Pill、浮层、整页三处呈现费用与真实 Tokens
|
|
3
|
+
"version": "2.6.1",
|
|
4
|
+
"description": "DeepSeek Harness Token 与费用看板:9 家供应商开箱即用,按供应商查看预算、订阅配额(GLM / Kimi / OpenCode Go / Command Code / MiniMax)与账户余额,MiniMax 自动识别国内 / 国际站并支持按量 Key 余额,GLM / Kimi / Qwen 可在卡顶切换中国 / 海外区域;Pill、浮层、整页三处呈现费用与真实 Tokens、缓存命中率与用量趋势,成本趋势双币种双轴;价目表支持离线复用,断网重启用上一次成功的价格继续估算;填第三方 API Key 的自建 / 中转 / 本地兼容服务同样能记账,未定价模型不按 0 元计,可导出 / 导入本地 JSON 备份。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
|
7
7
|
"exports": {
|
package/src/core.js
CHANGED
|
@@ -497,8 +497,10 @@ export function buildUsage(state, prefs, range, now, providerInfoInput) {
|
|
|
497
497
|
let rowEstimate = null
|
|
498
498
|
if (!billable) {
|
|
499
499
|
const estimatePrice = resolvePrice(modelId, providerId, ts)
|
|
500
|
-
|
|
501
|
-
|
|
500
|
+
// 币种不匹配的报价只等于「没有可用价目」:宁可显示未定价,也不把 CNY 数字写进 USD 桶
|
|
501
|
+
const estimateUsable = estimatePrice !== null && estimatePrice.mismatch !== true
|
|
502
|
+
entry.estimatePriced = (entry.estimatePriced ?? true) && estimateUsable
|
|
503
|
+
if (estimateUsable) {
|
|
502
504
|
rowEstimate = costOf({
|
|
503
505
|
ts, provider: providerId, model: modelId,
|
|
504
506
|
input: row.input, cacheRead: row.cacheRead, cacheWrite: row.cacheWrite, output: row.output,
|
|
@@ -753,7 +755,7 @@ export function buildSummary(state, prefs, now, providerInfoInput, activeProvide
|
|
|
753
755
|
// 改为与 buildUsage · add 完全同口径——按当日 ts 现算估算,缺价行跳过不计。
|
|
754
756
|
if (!billable) {
|
|
755
757
|
const estimatePrice = resolvePrice(modelId, providerId, dayTs)
|
|
756
|
-
if (estimatePrice !== null) {
|
|
758
|
+
if (estimatePrice !== null && estimatePrice.mismatch !== true) {
|
|
757
759
|
provider.usage.monthEstimate += costOf({
|
|
758
760
|
ts: dayTs, provider: providerId, model: modelId,
|
|
759
761
|
input: row.input, cacheRead: row.cacheRead, cacheWrite: row.cacheWrite, output: row.output,
|
package/src/pricing.js
CHANGED
|
@@ -19,6 +19,14 @@ let catalog = loadCatalog(BUNDLED, 'bundled')
|
|
|
19
19
|
let routerCatalog = { entries: [], currency: 'USD', source: 'router', updatedAt: null }
|
|
20
20
|
let catalogUrl = null
|
|
21
21
|
let communityCache = { at: 0, value: null }
|
|
22
|
+
/** 当前表从哪来:bundled(内置)/ cache(上次成功)/ live(本次联网命中)。 */
|
|
23
|
+
let catalogOrigin = 'bundled'
|
|
24
|
+
let routerOrigin = 'bundled'
|
|
25
|
+
/** 上一次成功拿到社区 / 路由表的时间;内置目录时保持 null。 */
|
|
26
|
+
let catalogFetchedAt = null
|
|
27
|
+
let routerFetchedAt = null
|
|
28
|
+
/** 持久化钩子,由 configurePricing 注入;没有钩子时(单测)跳过写盘。 */
|
|
29
|
+
let persistCatalog = null
|
|
22
30
|
/** `provider:model` / `model` → normalized override quote (set by `configurePricing`). */
|
|
23
31
|
let overrides = new Map()
|
|
24
32
|
/** `(providerId) => 'CNY' | 'USD'`; declared prefs first, registry as fallback. */
|
|
@@ -88,7 +96,28 @@ export function resolvePrice(model, provider, ts = Date.now()) {
|
|
|
88
96
|
}
|
|
89
97
|
|
|
90
98
|
const matched = resolveMatch(modelId, catalog.entries)
|
|
91
|
-
|
|
99
|
+
// USD provider 命中不到社区表时,路由表本身也是一份有效价源:
|
|
100
|
+
// 订阅行(OpenCode Go / MiniMax 等)的模型常常不在国内社区表里,但 OpenRouter 有美元价
|
|
101
|
+
if (matched === null) {
|
|
102
|
+
if (currency !== 'USD') return null
|
|
103
|
+
const routed = routerCatalog.entries.find((item) => item.modelId === modelId)
|
|
104
|
+
if (routed === undefined) return null
|
|
105
|
+
const routedPrices = effectivePrices(routed, ts)
|
|
106
|
+
if (routedPrices === null || routedPrices.input === null || routedPrices.output === null) return null
|
|
107
|
+
return {
|
|
108
|
+
input: routedPrices.input,
|
|
109
|
+
cacheRead: routedPrices.cacheRead,
|
|
110
|
+
cacheWrite: routedPrices.cacheWrite,
|
|
111
|
+
output: routedPrices.output,
|
|
112
|
+
currency: 'USD',
|
|
113
|
+
mismatch: false,
|
|
114
|
+
confidence: 'exact',
|
|
115
|
+
approximate: false,
|
|
116
|
+
catalogModel: routed.modelId,
|
|
117
|
+
table: 'router',
|
|
118
|
+
source: 'router',
|
|
119
|
+
}
|
|
120
|
+
}
|
|
92
121
|
const table = selectTable(matched.entry, currency)
|
|
93
122
|
const prices = effectivePrices(table.entry, ts)
|
|
94
123
|
if (prices === null || prices.input === null || prices.output === null) return null
|
|
@@ -130,6 +159,7 @@ export function configurePricing(input = {}) {
|
|
|
130
159
|
}
|
|
131
160
|
overrides = next
|
|
132
161
|
if (typeof input.currencyOf === 'function') currencyOf = input.currencyOf
|
|
162
|
+
if (typeof input.persistCatalog === 'function') persistCatalog = input.persistCatalog
|
|
133
163
|
}
|
|
134
164
|
|
|
135
165
|
function normalizeOverride(raw) {
|
|
@@ -150,7 +180,59 @@ function normalizeOverride(raw) {
|
|
|
150
180
|
}
|
|
151
181
|
}
|
|
152
182
|
|
|
183
|
+
/**
|
|
184
|
+
* 内部 entry → 可落盘的原始形状:正则不入盘(重编译即可),其余价格字段原样保留,
|
|
185
|
+
* 读回时再经 loadCatalog 归一,保证「写盘—读盘—匹配」与联网路径同源。
|
|
186
|
+
*/
|
|
187
|
+
function storableEntry(entry) {
|
|
188
|
+
return {
|
|
189
|
+
modelId: entry.modelId,
|
|
190
|
+
displayName: entry.displayName,
|
|
191
|
+
family: entry.family,
|
|
192
|
+
aliases: entry.aliases,
|
|
193
|
+
currency: entry.currency,
|
|
194
|
+
// 峰谷条目 peak/offPeak 同时存在;其余一律平坦价。不能用 != null 判峰谷:
|
|
195
|
+
// 缓存条目字段缺失时 undefined !== null 会误判成峰谷,展开出空价格而丢整行
|
|
196
|
+
...(entry.peak && entry.offPeak
|
|
197
|
+
? { peak: entry.peak, offPeak: entry.offPeak }
|
|
198
|
+
: { prices: entry.prices }),
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** 联网成功后真正落盘的内容:只存归一化后的模型行,不存原始响应。 */
|
|
203
|
+
function serializableEntries(entries) {
|
|
204
|
+
return entries.map(storableEntry)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* 启动即调用:把上一次成功的价目表读回内存,离线时也能按真实目录估算。
|
|
209
|
+
* 任何一级失败都不抛错,最终仍可退回内置目录。
|
|
210
|
+
*/
|
|
211
|
+
export function restoreCatalogCache({ community = null, router = null } = {}) {
|
|
212
|
+
let restored = 0
|
|
213
|
+
if (community !== null && Array.isArray(community.entries) && community.entries.length > 0) {
|
|
214
|
+
catalog = loadCatalog({ models: community.entries.map(storableEntry), updatedAt: community.updatedAt ?? null }, community.source ?? 'cache')
|
|
215
|
+
catalogUrl = community.url ?? null
|
|
216
|
+
catalogOrigin = 'cache'
|
|
217
|
+
catalogFetchedAt = typeof community.fetchedAt === 'number' ? community.fetchedAt : null
|
|
218
|
+
communityCache = { at: catalogFetchedAt ?? 0, value: null }
|
|
219
|
+
restored += 1
|
|
220
|
+
}
|
|
221
|
+
if (router !== null && Array.isArray(router.entries) && router.entries.length > 0) {
|
|
222
|
+
routerCatalog = loadCatalog({ models: router.entries.map(storableEntry), currency: 'USD' }, 'router')
|
|
223
|
+
routerOrigin = 'cache'
|
|
224
|
+
routerFetchedAt = typeof router.fetchedAt === 'number' ? router.fetchedAt : null
|
|
225
|
+
restored += 1
|
|
226
|
+
}
|
|
227
|
+
return restored
|
|
228
|
+
}
|
|
229
|
+
|
|
153
230
|
export function catalogInfo() {
|
|
231
|
+
// degraded=true 表示此刻用的不是本次联网拿到的表:缓存或内置,界面上要看得见
|
|
232
|
+
const degraded = catalogOrigin !== 'live' || routerOrigin !== 'live'
|
|
233
|
+
const reason = catalogOrigin === 'live' && routerOrigin === 'live'
|
|
234
|
+
? null
|
|
235
|
+
: (catalogOrigin === 'cache' || routerOrigin === 'cache' ? 'offline-cache' : 'bundled-fallback')
|
|
154
236
|
return {
|
|
155
237
|
version: catalog.version ?? null,
|
|
156
238
|
source: catalog.source,
|
|
@@ -159,6 +241,12 @@ export function catalogInfo() {
|
|
|
159
241
|
models: catalog.entries.length,
|
|
160
242
|
routerModels: routerCatalog.entries.length,
|
|
161
243
|
overrides: overrides.size,
|
|
244
|
+
origin: catalogOrigin,
|
|
245
|
+
routerOrigin,
|
|
246
|
+
fetchedAt: catalogFetchedAt,
|
|
247
|
+
routerFetchedAt,
|
|
248
|
+
degraded,
|
|
249
|
+
reason,
|
|
162
250
|
}
|
|
163
251
|
}
|
|
164
252
|
|
|
@@ -187,7 +275,10 @@ export async function loadCommunityPricing({ force = false } = {}) {
|
|
|
187
275
|
if (parsed.entries.length === 0) throw new Error('empty-catalog')
|
|
188
276
|
catalog = parsed
|
|
189
277
|
catalogUrl = page
|
|
278
|
+
catalogOrigin = 'live'
|
|
279
|
+
catalogFetchedAt = Date.now()
|
|
190
280
|
communityCache = { at: Date.now(), value: catalogInfo() }
|
|
281
|
+
persistCatalog?.('community', { entries: serializableEntries(catalog.entries), currency: catalog.currency, source: catalog.source, updatedAt: catalog.updatedAt, url: page, fetchedAt: catalogFetchedAt })
|
|
191
282
|
return catalogInfo()
|
|
192
283
|
} catch {
|
|
193
284
|
// try next mirror, then keep the bundled catalog
|
|
@@ -203,6 +294,9 @@ export async function loadRouterPricing() {
|
|
|
203
294
|
const parsed = loadCatalog({ models: routerModels(raw), currency: 'USD' }, 'router')
|
|
204
295
|
if (parsed.entries.length > 0) {
|
|
205
296
|
routerCatalog = parsed
|
|
297
|
+
routerOrigin = 'live'
|
|
298
|
+
routerFetchedAt = Date.now()
|
|
299
|
+
persistCatalog?.('router', { entries: serializableEntries(routerCatalog.entries), currency: 'USD', source: 'router', updatedAt: routerCatalog.updatedAt, fetchedAt: routerFetchedAt })
|
|
206
300
|
return true
|
|
207
301
|
}
|
|
208
302
|
} catch {
|
|
@@ -216,6 +310,12 @@ export function resetPricingForTests() {
|
|
|
216
310
|
routerCatalog = { entries: [], currency: 'USD', source: 'router', updatedAt: null }
|
|
217
311
|
catalogUrl = null
|
|
218
312
|
communityCache = { at: 0, value: null }
|
|
313
|
+
// 上面已把 catalog 重置为内置表,缓存窗口不清会让下一次加载直接复用旧快照
|
|
314
|
+
catalogOrigin = 'bundled'
|
|
315
|
+
routerOrigin = 'bundled'
|
|
316
|
+
catalogFetchedAt = null
|
|
317
|
+
routerFetchedAt = null
|
|
219
318
|
overrides = new Map()
|
|
220
319
|
currencyOf = (providerId) => providerCurrency(providerId)
|
|
320
|
+
persistCatalog = null
|
|
221
321
|
}
|
package/src/store.js
CHANGED
|
@@ -319,6 +319,36 @@ export async function saveJson(dir, name, value) {
|
|
|
319
319
|
await rename(tmp, file)
|
|
320
320
|
}
|
|
321
321
|
|
|
322
|
+
|
|
323
|
+
/** 价目表缓存:社区表与路由表各一份,供离线启动复用上一次成功的结果。 */
|
|
324
|
+
export const CATALOG_CACHE_NAMES = { community: 'catalog.cache.json', router: 'router.cache.json' }
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* 读取价目表缓存。文件缺失或损坏都返回 null(损坏文件改名留证),
|
|
328
|
+
* 由调用方回退下一级:本次联网结果 → 缓存 → 内置目录。
|
|
329
|
+
*/
|
|
330
|
+
export async function loadCatalogCache(dir, kind, logger) {
|
|
331
|
+
const name = CATALOG_CACHE_NAMES[kind]
|
|
332
|
+
if (name === undefined) return null
|
|
333
|
+
const cached = await readJson(join(dir, name), null, (file, backup) => {
|
|
334
|
+
logger?.warn('pricing', 'catalog.cache.corrupt', { file, backup })
|
|
335
|
+
})
|
|
336
|
+
if (cached === null || typeof cached !== 'object') return null
|
|
337
|
+
if (!Array.isArray(cached.entries) || cached.entries.length === 0) return null
|
|
338
|
+
return cached
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** 只由联网成功路径调用:离线启动绝不覆盖上一次成功的缓存。 */
|
|
342
|
+
export async function saveCatalogCache(dir, kind, payload, logger) {
|
|
343
|
+
const name = CATALOG_CACHE_NAMES[kind]
|
|
344
|
+
if (name === undefined) return
|
|
345
|
+
try {
|
|
346
|
+
await saveJson(dir, name, payload)
|
|
347
|
+
} catch (error) {
|
|
348
|
+
logger?.warn('pricing', 'catalog.cache.write-fail', { kind, message: String(error?.message ?? error) })
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
322
352
|
export function createFlusher(dir, state, delay = 2000, logger) {
|
|
323
353
|
let timer
|
|
324
354
|
let saving
|