dsh-token-receipt 1.0.0 → 1.1.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/index.js CHANGED
@@ -6,13 +6,29 @@
6
6
  * half renders the receipt printer; only the public model price catalogue is fetched.
7
7
  */
8
8
 
9
- import { statSync } from 'node:fs'
9
+ import { readFileSync, statSync } from 'node:fs'
10
10
  import { createPricingCatalog, createPricingAccumulator } from './pricing.js'
11
11
 
12
12
  const ROUTE = '/api/token-receipt'
13
+ /** The installed package version, served to the browser half for update detection. */
14
+ export const PACKAGE_VERSION = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version
13
15
  const DAY_MS = 24 * 60 * 60 * 1000
16
+ const MAX_TS = 8_640_000_000_000_000
14
17
  const CACHE_TTL_MS = 10_000
15
18
  const RECENT_DAYS = 3
19
+ const VALID_PERIODS = new Set(['day', 'week', 'month', 'days30', 'days90', 'all'])
20
+ const PERIOD_CODES = new Map([
21
+ ['day', 'D'],
22
+ ['week', 'W'],
23
+ ['month', 'M'],
24
+ ['days30', '30D'],
25
+ ['days90', '90D'],
26
+ ['all', 'ALL'],
27
+ ])
28
+ const PERIOD_LOOKBACK_DAYS = new Map([
29
+ ['days30', 29],
30
+ ['days90', 89],
31
+ ])
16
32
 
17
33
  export const name = 'token-receipt'
18
34
  export const inject = ['webServer']
@@ -28,9 +44,44 @@ function sendJson(res, status, body, headOnly = false) {
28
44
  res.end(payload)
29
45
  }
30
46
 
47
+ function nextLocalDay(timestamp) {
48
+ const d = new Date(timestamp)
49
+ d.setDate(d.getDate() + 1)
50
+ return d.getTime()
51
+ }
52
+
31
53
  function localDayBounds(now = new Date()) {
32
- const start = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()
33
- return { from: start, to: start + DAY_MS }
54
+ const from = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()
55
+ const to = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1).getTime()
56
+ return { from, to }
57
+ }
58
+
59
+ /** Compute default [from, to) local-time bounds for a validated receipt period. */
60
+ function defaultPeriodBounds(period, nowDate) {
61
+ const dayBounds = localDayBounds(nowDate)
62
+ const lookback = PERIOD_LOOKBACK_DAYS.get(period)
63
+ if (lookback !== undefined) {
64
+ return {
65
+ from: new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate() - lookback).getTime(),
66
+ to: dayBounds.to,
67
+ }
68
+ }
69
+ if (period === 'all') return { from: 1, to: dayBounds.to }
70
+ return dayBounds
71
+ }
72
+
73
+ /** Resolve the fallback YYYY-MM-DD label using the inclusive end date for rolling/all-time windows. */
74
+ function defaultDateLabel(period, from, to) {
75
+ if (period === 'days30' || period === 'days90' || period === 'all') {
76
+ return compactDate(to - 1)
77
+ }
78
+ return compactDate(from)
79
+ }
80
+
81
+ function parseTs(raw) {
82
+ if (raw === null || raw.trim() === '') return NaN
83
+ const ts = Number(raw)
84
+ return Number.isFinite(ts) && ts > 0 && ts <= MAX_TS ? ts : NaN
34
85
  }
35
86
 
36
87
  function compactDate(timestamp) {
@@ -57,8 +108,11 @@ function hashSuffix(input) {
57
108
  function messageText(message) {
58
109
  const content = message && Array.isArray(message.content) ? message.content : []
59
110
  for (const block of content) {
60
- if (block && block.type === 'text' && typeof block.text === 'string' && block.text.trim() !== '') {
61
- return block.text.trim().replace(/\s+/g, ' ')
111
+ if (block && block.type === 'text' && typeof block.text === 'string') {
112
+ const trimmed = block.text.trim()
113
+ if (trimmed !== '' && !trimmed.startsWith('<')) {
114
+ return trimmed.replace(/\s+/g, ' ')
115
+ }
62
116
  }
63
117
  }
64
118
  return ''
@@ -66,7 +120,8 @@ function messageText(message) {
66
120
 
67
121
  function shortTitle(text) {
68
122
  if (!text) return 'Untitled session'
69
- return text.length > 46 ? `${text.slice(0, 45)}…` : text
123
+ const chars = Array.from(text)
124
+ return chars.length > 46 ? `${chars.slice(0, 45).join('')}…` : text
70
125
  }
71
126
 
72
127
  async function mapLimit(items, limit, worker) {
@@ -98,14 +153,14 @@ async function loadSessionUsage(query, record) {
98
153
  return null
99
154
  }
100
155
  if (!snapshot || !Array.isArray(snapshot.events)) return null
101
- const inherited = Number(snapshot.inheritedEventCount) || 0
156
+ const inherited = finite(snapshot.inheritedEventCount)
102
157
  let title = ''
103
158
 
104
159
  for (const candidate of snapshot.events) {
105
160
  if (candidate && candidate.type === 'user/message') {
106
161
  const body = candidate.data && candidate.data.message ? candidate.data.message : candidate.data
107
162
  const text = messageText(body)
108
- if (text !== '' && !text.startsWith('<')) {
163
+ if (text !== '') {
109
164
  title = text
110
165
  break
111
166
  }
@@ -115,8 +170,8 @@ async function loadSessionUsage(query, record) {
115
170
  const messages = []
116
171
  for (const event of snapshot.events) {
117
172
  if (!event || event.type !== 'assistant/message') continue
118
- if (typeof event.seq === 'number' && event.seq < inherited) continue
119
- if (typeof event.time !== 'number') continue
173
+ if (Number.isFinite(event.seq) && event.seq < inherited) continue
174
+ if (!Number.isFinite(event.time)) continue
120
175
  const usage = event.data && event.data.usage
121
176
  if (!usage) continue
122
177
  const message = event.data.message || {}
@@ -148,9 +203,14 @@ async function cachedSessionUsage(query, record, revision, sessionUsageCache) {
148
203
  const id = record.header.id
149
204
  const hit = sessionUsageCache.get(id)
150
205
  const key = revision == null ? null : String(revision)
151
- if (hit && key !== null && hit.revision === key) return hit.value
206
+ if (hit && key !== null && hit.revision === key) {
207
+ sessionUsageCache.delete(id)
208
+ sessionUsageCache.set(id, hit)
209
+ return hit.value
210
+ }
152
211
  const value = await loadSessionUsage(query, record)
153
212
  if (key !== null) {
213
+ sessionUsageCache.delete(id)
154
214
  sessionUsageCache.set(id, { revision: key, value })
155
215
  if (sessionUsageCache.size > 512) {
156
216
  const oldest = sessionUsageCache.keys().next().value
@@ -165,14 +225,20 @@ async function cachedSessionUsage(query, record, revision, sessionUsageCache) {
165
225
  * long ago can still be used today, so recency uses the persisted log's
166
226
  * modification time and the live-session set rather than creation time alone.
167
227
  */
168
- async function candidateRecords(ctx, query, from, to) {
169
- const records = await query.listSessions()
228
+ async function candidateRecords(ctx, query, from, to, sessionUsageCache) {
229
+ const rawRecords = await query.listSessions()
230
+ const records = Array.isArray(rawRecords) ? rawRecords : []
170
231
  const persistence = ctx.get('sessionPersistence')
171
232
  const live = ctx.get('sessions')
172
233
  const liveIds = new Set()
173
234
  if (live && typeof live.list === 'function') {
174
235
  try {
175
- for (const session of live.list()) liveIds.add(session.id)
236
+ const liveList = live.list()
237
+ if (liveList) {
238
+ for (const session of liveList) {
239
+ if (session && typeof session.id === 'string') liveIds.add(session.id)
240
+ }
241
+ }
176
242
  } catch {
177
243
  /* the live set is an optimization only */
178
244
  }
@@ -182,11 +248,13 @@ async function candidateRecords(ctx, query, from, to) {
182
248
  if (persistence && typeof persistence.list === 'function') {
183
249
  try {
184
250
  const snapshots = await persistence.list()
185
- for (const snapshot of snapshots) {
186
- if (!snapshot || !snapshot.header) continue
187
- revisions.set(snapshot.header.id, snapshot.revision)
188
- const path = snapshot.location && snapshot.location.path
189
- if (typeof path === 'string') paths.set(snapshot.header.id, path)
251
+ if (Array.isArray(snapshots)) {
252
+ for (const snapshot of snapshots) {
253
+ if (!snapshot || !snapshot.header || typeof snapshot.header.id !== 'string') continue
254
+ revisions.set(snapshot.header.id, snapshot.revision)
255
+ const path = snapshot.location && snapshot.location.path
256
+ if (typeof path === 'string') paths.set(snapshot.header.id, path)
257
+ }
190
258
  }
191
259
  } catch {
192
260
  /* fall back to reading whatever the query returns */
@@ -200,6 +268,8 @@ async function candidateRecords(ctx, query, from, to) {
200
268
  if (header.createdAt && header.createdAt >= to) return false
201
269
  if (liveIds.has(header.id)) return true
202
270
  if (!header.createdAt || header.createdAt >= recentFloor) return true
271
+ const rev = revisions.get(header.id)
272
+ if (rev != null && sessionUsageCache?.get(header.id)?.revision === String(rev)) return true
203
273
  const path = paths.get(header.id)
204
274
  if (path !== undefined) {
205
275
  try {
@@ -221,7 +291,7 @@ async function computeBill(ctx, from, to, dateLabel, period, state, snapshot) {
221
291
  throw error
222
292
  }
223
293
 
224
- const candidates = await candidateRecords(ctx, query, from, to)
294
+ const candidates = await candidateRecords(ctx, query, from, to, state.sessionUsageCache)
225
295
  const loaded = await mapLimit(candidates, 6, ({ record, revision }) => cachedSessionUsage(query, record, revision, state.sessionUsageCache))
226
296
  const rows = loaded.filter((row) => row && row.messages.length > 0)
227
297
 
@@ -239,6 +309,8 @@ async function computeBill(ctx, from, to, dateLabel, period, state, snapshot) {
239
309
  const modelMap = new Map()
240
310
  const pricing = createPricingAccumulator(snapshot)
241
311
  const sessionRows = []
312
+ let billFirstAt = 0
313
+ let billLastAt = 0
242
314
 
243
315
  for (const row of rows) {
244
316
  let requests = 0
@@ -261,6 +333,8 @@ async function computeBill(ctx, from, to, dateLabel, period, state, snapshot) {
261
333
  reasoning += message.reasoning
262
334
  firstAt = firstAt === 0 || message.time < firstAt ? message.time : firstAt
263
335
  lastAt = message.time > lastAt ? message.time : lastAt
336
+ billFirstAt = billFirstAt === 0 || message.time < billFirstAt ? message.time : billFirstAt
337
+ billLastAt = message.time > billLastAt ? message.time : billLastAt
264
338
  const key = `${message.provider}\u0000${message.model}`
265
339
  const existing = modelMap.get(key) || {
266
340
  provider: message.provider, model: message.model, total: 0, input: 0, output: 0,
@@ -301,8 +375,8 @@ async function computeBill(ctx, from, to, dateLabel, period, state, snapshot) {
301
375
 
302
376
  }
303
377
 
304
- const date = dateLabel || compactDate(from)
305
- const periodCode = period === 'week' ? 'W' : period === 'month' ? 'M' : 'D'
378
+ const date = dateLabel || defaultDateLabel(period, from, to)
379
+ const periodCode = PERIOD_CODES.get(period) || 'D'
306
380
  const billNo = `TR-${periodCode}-${date.replaceAll('-', '')}-${hashSuffix(`${period}:${date}:${totals.totalTokens}:${totals.requests}`)}`
307
381
 
308
382
  return {
@@ -311,6 +385,8 @@ async function computeBill(ctx, from, to, dateLabel, period, state, snapshot) {
311
385
  period,
312
386
  from,
313
387
  to,
388
+ firstAt: billFirstAt > 0 ? billFirstAt : null,
389
+ lastAt: billLastAt > 0 ? billLastAt : null,
314
390
  generatedAt: state.now(),
315
391
  billNo,
316
392
  totals,
@@ -336,7 +412,7 @@ async function cachedBill(ctx, state, key, from, to, dateLabel, period, snapshot
336
412
  const bill = await promise
337
413
  entry.pending = false
338
414
  entry.at = state.now()
339
- if (bill.pricing.status === 'unavailable' && billCache.get(key) === entry) billCache.delete(key)
415
+ if (snapshot.book === null && billCache.get(key) === entry) billCache.delete(key)
340
416
  return bill
341
417
  } catch (error) {
342
418
  if (billCache.get(key) === entry) billCache.delete(key)
@@ -350,8 +426,8 @@ export function createReceiptService(ctx, options = {}) {
350
426
  const catalog = options.catalog || createPricingCatalog({ fetchImpl: options.fetchImpl, now })
351
427
  const state = { now, billCache: new Map(), sessionUsageCache: new Map() }
352
428
 
353
- async function getBill({ from, to, date, period = 'day' }) {
354
- const snapshot = await catalog.read()
429
+ async function getBill({ from, to, date, period = 'day', force = false }) {
430
+ const snapshot = await catalog.read({ force: Boolean(force) })
355
431
  // Include labels and price state: a previously unavailable price can recover
356
432
  // without waiting for a session revision or an unrelated date to change.
357
433
  const key = JSON.stringify([from, to, date, period, snapshot.version, snapshot.stale])
@@ -370,18 +446,29 @@ export function createReceiptService(ctx, options = {}) {
370
446
  } catch {
371
447
  return sendJson(res, 400, { ok: false, error: 'Invalid request.' }, headOnly)
372
448
  }
373
- const defaultBounds = localDayBounds(new Date(now()))
374
- const fromParam = url.searchParams.get('from')
375
- const toParam = url.searchParams.get('to')
376
- const from = fromParam === null ? NaN : Number(fromParam)
377
- const to = toParam === null ? NaN : Number(toParam)
378
- const safeFrom = Number.isFinite(from) ? from : defaultBounds.from
379
- const safeTo = Number.isFinite(to) && to > safeFrom ? to : safeFrom + DAY_MS
380
- const dateLabel = url.searchParams.get('date') || compactDate(safeFrom)
449
+ // A tiny, cache-free probe used by the browser half to notice a package update
450
+ // while the WebView still holds an older client bundle.
451
+ if (url.searchParams.get('version') === '1') {
452
+ return sendJson(res, 200, { ok: true, version: PACKAGE_VERSION }, headOnly)
453
+ }
381
454
  const requestedPeriod = url.searchParams.get('period')
382
- const period = requestedPeriod === 'week' || requestedPeriod === 'month' ? requestedPeriod : 'day'
455
+ const period = VALID_PERIODS.has(requestedPeriod) ? requestedPeriod : 'day'
456
+ const defaultBounds = defaultPeriodBounds(period, new Date(now()))
457
+ const from = parseTs(url.searchParams.get('from'))
458
+ const to = parseTs(url.searchParams.get('to'))
459
+ let safeFrom = Number.isFinite(from) ? from : defaultBounds.from
460
+ let safeTo = Number.isFinite(to) && to > safeFrom
461
+ ? to
462
+ : safeFrom === defaultBounds.from ? defaultBounds.to : nextLocalDay(safeFrom)
463
+ if (!Number.isFinite(safeTo) || safeTo <= safeFrom) {
464
+ safeFrom = defaultBounds.from
465
+ safeTo = defaultBounds.to
466
+ }
467
+ const rawDate = url.searchParams.get('date')?.trim() ?? ''
468
+ const dateLabel = /^[A-Za-z0-9-]{1,32}$/.test(rawDate) ? rawDate : defaultDateLabel(period, safeFrom, safeTo)
469
+ const refresh = url.searchParams.get('refresh')
383
470
  try {
384
- const bill = await getBill({ from: safeFrom, to: safeTo, date: dateLabel, period })
471
+ const bill = await getBill({ from: safeFrom, to: safeTo, date: dateLabel, period, force: refresh === '1' })
385
472
  return sendJson(res, 200, bill, headOnly)
386
473
  } catch (error) {
387
474
  const statusCode = error && Number.isInteger(error.statusCode) ? error.statusCode : 500
package/locale/en.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Token receipt",
4
- "description": "Print daily, weekly, or monthly token usage and estimated costs as a receipt. Currency follows the language, with manual USD/CNY/JPY selection. Replay printing and save a PNG. Usage stays local; only public model prices are fetched from models.dev.",
5
- "detail": "docs/DETAIL.md"
4
+ "description": "Print daily, weekly, monthly, 30-day, 90-day, or all-time token usage and estimated costs as a receipt. Currency follows the language, with manual USD/CNY/JPY selection. Replay printing, and copy the image or save a PNG. Usage stays local; only public model prices are fetched from models.dev.",
5
+ "detail": "assets/detail/DETAIL.md"
6
6
  }
7
7
  }
package/locale/ja.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "トークン明細",
4
- "description": "日・週・月ごとのトークン使用量と推定料金をレシートとして印刷できます。通貨は言語に連動し、USD/CNY/JPY に手動で切り替えることもできます。印刷アニメーションと PNG 保存に対応。使用量は端末内に保管し、models.dev の公開料金のみを取得します。会話データは送信しません。",
5
- "detail": "docs/DETAIL.ja.md"
4
+ "description": "日・週・月・直近30日・直近90日・全期間のトークン使用量と推定料金をレシートとして印刷できます。通貨は言語に連動し、USD/CNY/JPY に手動で切り替えることもできます。印刷アニメーションに加え、画像のコピーと PNG 保存に対応。使用量は端末内に保管し、models.dev の公開料金のみを取得します。会話データは送信しません。",
5
+ "detail": "assets/detail/DETAIL.ja.md"
6
6
  }
7
7
  }
package/locale/zh.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Token 账单",
4
- "description": "把日、周、月的 token 用量与预估费用打印成小票,币种跟随语言,支持 USD/CNY/JPY 手动切换、打印动画和 PNG 保存。用量从本机 DSH 会话读取,仅联网获取 models.dev 公开价格,不上传会话数据。",
5
- "detail": "docs/DETAIL.zh.md"
4
+ "description": "把日、周、月、近 30 天、近 90 天与全部的 token 用量及预估费用打印成小票,币种跟随语言,支持 USD/CNY/JPY 手动切换、打印动画,以及复制图片或保存 PNG。用量从本机 DSH 会话读取,仅联网获取 models.dev 公开价格,不上传会话数据。",
5
+ "detail": "assets/detail/DETAIL.zh.md"
6
6
  }
7
7
  }
package/package.json CHANGED
@@ -1,30 +1,30 @@
1
1
  {
2
2
  "name": "dsh-token-receipt",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
4
4
  "private": false,
5
- "description": "Print daily, weekly, or monthly token usage and estimated model costs as a tactile receipt, with PNG export.",
5
+ "description": "Print daily, weekly, monthly, 30-day, 90-day, or all-time token usage and estimated model costs as a tactile receipt, with clipboard copy and PNG export.",
6
6
  "type": "module",
7
7
  "main": "index.js",
8
8
  "exports": {
9
9
  ".": "./index.js",
10
10
  "./client": "./client.js",
11
11
  "./locale/*.json": "./locale/*.json",
12
- "./icon": "./icon.svg"
12
+ "./icon": "./icon.svg",
13
+ "./package.json": "./package.json"
13
14
  },
14
15
  "files": [
15
16
  "index.js",
17
+ "pricing.js",
16
18
  "client.js",
17
19
  "cordis.patch.yml",
18
20
  "locale/*.json",
19
- "docs",
20
- "assets",
21
+ "assets/detail",
21
22
  "icon.svg",
22
23
  "README.md",
24
+ "README.zh.md",
25
+ "README.ja.md",
23
26
  "LICENSE",
24
27
  "CHANGELOG.md",
25
- "README.zh.md",
26
- "RELEASING.md",
27
- "pricing.js",
28
28
  "THIRD_PARTY_NOTICES.md",
29
29
  "licenses"
30
30
  ],
@@ -74,6 +74,6 @@
74
74
  "scripts": {
75
75
  "check": "node --check index.js && node --check pricing.js && node --check client.js",
76
76
  "prepublishOnly": "npm run check && npm test",
77
- "test": "node --test tests/*.test.js"
77
+ "test": "node --test \"tests/*.test.js\""
78
78
  }
79
79
  }
package/pricing.js CHANGED
@@ -64,11 +64,6 @@ function orgOf(id) {
64
64
  return slash > 0 ? id.slice(0, slash).toLowerCase() : undefined
65
65
  }
66
66
 
67
- function labOf(canonical) {
68
- const slash = canonical.indexOf('/')
69
- return slash > 0 ? canonical.slice(0, slash).toLowerCase() : undefined
70
- }
71
-
72
67
  function stripPrefixes(input, prefixes) {
73
68
  let out = input
74
69
  let changed = true
@@ -123,7 +118,7 @@ function familyVendorOf(model) {
123
118
  return FAMILY_VENDORS.find(([prefix]) => bare.startsWith(prefix))?.[1]
124
119
  }
125
120
 
126
- const MODELS_DEV_PROVIDER_IDS = {
121
+ const MODELS_DEV_PROVIDER_IDS = Object.assign(Object.create(null), {
127
122
  'deepseek-official': 'deepseek',
128
123
  'deepseek-account': 'deepseek',
129
124
  'kimi-coding': 'moonshotai',
@@ -143,10 +138,12 @@ const MODELS_DEV_PROVIDER_IDS = {
143
138
  'xiaomi-token-plan-sgp': 'xiaomi',
144
139
  'minimax-coding-plan': 'minimax',
145
140
  'minimax-cn-coding-plan': 'minimax-cn',
146
- }
141
+ })
147
142
 
148
143
  function modelsDevProviderOf(dshProviderId) {
149
- return MODELS_DEV_PROVIDER_IDS[dshProviderId] ?? dshProviderId
144
+ return Object.hasOwn(MODELS_DEV_PROVIDER_IDS, dshProviderId)
145
+ ? MODELS_DEV_PROVIDER_IDS[dshProviderId]
146
+ : dshProviderId
150
147
  }
151
148
 
152
149
  function isDeepSeekProvider(dshProviderId) {
@@ -154,14 +151,13 @@ function isDeepSeekProvider(dshProviderId) {
154
151
  }
155
152
 
156
153
  function sameRate(a, b) {
157
- const close = (x, y) => Math.abs(x - y) <= 1e-9 * Math.max(1, Math.abs(x))
154
+ const close = (x, y) => Math.abs(x - y) <= 1e-9 * Math.max(1, Math.abs(x), Math.abs(y))
158
155
  return close(a.hit, b.hit) && close(a.miss, b.miss) && close(a.write, b.write) && close(a.out, b.out)
159
156
  }
160
157
 
161
158
  function rateOfEntry(value) {
162
- const v = value
163
- if (v === null || typeof v !== 'object') return null
164
- const r = v
159
+ const r = asRecord(value)
160
+ if (r === null) return null
165
161
  const num = (x) => typeof x === 'number' && Number.isFinite(x)
166
162
  return num(r.hit) && num(r.miss) && num(r.write) && num(r.out)
167
163
  ? { hit: r.hit, miss: r.miss, write: r.write, out: r.out }
@@ -180,30 +176,38 @@ function pushForms(map, forms, candidate) {
180
176
 
181
177
  export function priceIndexOf(
182
178
  prices,
183
- canonicalOf = {},
179
+ canonicalOf = Object.create(null),
184
180
  ) {
185
181
  const byModel = new Map()
186
182
  const byNormalized = new Map()
187
183
  const branches = new Map()
184
+ if (!prices || typeof prices !== 'object') return { byModel, byNormalized, branches }
188
185
  for (const pid of Object.keys(prices)) {
189
186
  if (isSubscriptionPlanProvider(pid)) continue
190
187
  const branchPrices = branchOf(prices, pid)
191
188
  if (branchPrices === null) continue
189
+ const canonicalBranch = canonicalOf && typeof canonicalOf === 'object' && Object.hasOwn(canonicalOf, pid)
190
+ ? asRecord(canonicalOf[pid])
191
+ : null
192
192
  const exact = new Map()
193
193
  const suffix = new Map()
194
194
  const normalized = new Map()
195
195
  const normalizedSuffix = new Map()
196
196
  const labs = new Set()
197
197
  for (const mid of Object.keys(branchPrices)) {
198
- const rate = branchPrices[mid]
199
- if (rateOfEntry(rate) === null) continue
200
- const canonical = canonicalOf[pid]?.[mid]
201
- const lab = canonical === undefined || canonical.length === 0 ? undefined : labOf(canonical)
198
+ if (!Object.hasOwn(branchPrices, mid)) continue
199
+ const rate = rateOfEntry(branchPrices[mid])
200
+ if (rate === null) continue
201
+ const rawCanonical = canonicalBranch !== null && Object.hasOwn(canonicalBranch, mid)
202
+ ? canonicalBranch[mid]
203
+ : undefined
204
+ const canonical = typeof rawCanonical === 'string' && rawCanonical.length > 0 ? rawCanonical : undefined
205
+ const lab = canonical === undefined ? undefined : orgOf(canonical)
202
206
  const candidate = {
203
207
  pid,
204
208
  mid,
205
209
  rate,
206
- ...canonical === undefined || canonical.length === 0 ? {} : { canonical },
210
+ ...canonical === undefined ? {} : { canonical },
207
211
  ...lab === undefined ? {} : { lab },
208
212
  }
209
213
  const lower = lowerModelId(mid)
@@ -259,9 +263,7 @@ function faceOf(candidate, via, confidence) {
259
263
  function lookupBranch(branch, model) {
260
264
  const exact = lowerModelId(model)
261
265
  const normalized = normalizeModelId(model)
262
- const stages
263
-
264
- = [
266
+ const stages = [
265
267
  { map: branch.byExact, keys: [exact], via: 'direct', confidence: 'high' },
266
268
  { map: branch.bySuffix, keys: [exact], via: 'branch-suffix', confidence: 'high' },
267
269
  { map: branch.byNormalized, keys: [normalized], via: 'branch-normalized', confidence: 'medium' },
@@ -402,32 +404,23 @@ function resolvePriceOf(book, provider, model) {
402
404
  return unpriced('no-entry')
403
405
  }
404
406
 
405
- function priceFaceOf(book, provider, model) {
406
- const resolution = priceResolutionOf(book, provider, model)
407
- return resolution.kind === 'priced' ? resolution.face : null
408
- }
409
-
410
- function priceOf(book, provider, model) {
411
- return priceFaceOf(book, provider, model)?.rate ?? null
412
- }
413
-
414
407
  function branchOf(book, id) {
415
- const value = book[id]
416
- return value !== null && typeof value === 'object' ? value : null
408
+ if (!book || typeof book !== 'object' || !Object.hasOwn(book, id)) return null
409
+ return asRecord(book[id])
417
410
  }
418
411
 
419
412
  export function pricesBookOf(value) {
420
413
  const data = asRecord(value)
421
- if (data === null || Array.isArray(data)) return null
422
- const book = {}
423
- const canonicalOf = {}
414
+ if (data === null) return null
415
+ const book = Object.create(null)
416
+ const canonicalOf = Object.create(null)
424
417
  for (const providerId of Object.keys(data)) {
425
418
  if (providerId === '__proto__' || providerId === 'constructor' || providerId === 'prototype') continue
426
419
  const provider = asRecord(data[providerId])
427
420
  if (provider === null) continue
428
421
  const modelList = asRecord(provider.models)
429
422
  if (modelList === null) continue
430
- const models = {}
423
+ const models = Object.create(null)
431
424
  for (const id of Object.keys(modelList)) {
432
425
  if (id === '__proto__' || id === 'constructor' || id === 'prototype') continue
433
426
  const model = asRecord(modelList[id])
@@ -442,9 +435,11 @@ export function pricesBookOf(value) {
442
435
  write: rateNum(cost.cache_write) ?? miss,
443
436
  out,
444
437
  }
445
- const canonical = model?.['canonical_model_id']
438
+ const canonical = model.canonical_model_id
446
439
  if (typeof canonical === 'string' && canonical.length > 0) {
447
- const branch = canonicalOf[providerId] ?? (canonicalOf[providerId] = {})
440
+ const branch = Object.hasOwn(canonicalOf, providerId)
441
+ ? canonicalOf[providerId]
442
+ : (canonicalOf[providerId] = Object.create(null))
448
443
  branch[id] = canonical
449
444
  }
450
445
  }
@@ -460,6 +455,7 @@ function rateNum(value) {
460
455
  export const PRICE_SOURCE = 'https://models.dev/api.json'
461
456
  export const PRICE_TTL_MS = 60 * 60 * 1000
462
457
  export const PRICE_FAILURE_BACKOFF_MS = 30_000
458
+ export const PRICE_FORCE_COOLDOWN_MS = 1_000
463
459
  export const PRICE_TIMEOUT_MS = 8_000
464
460
 
465
461
  /** The provider prefix is stripped only when it is the supplied source provider. */
@@ -494,12 +490,14 @@ export function createPricingCatalog(options = {}) {
494
490
  const now = options.now || Date.now
495
491
  const ttlMs = options.ttlMs ?? PRICE_TTL_MS
496
492
  const failureBackoffMs = options.failureBackoffMs ?? PRICE_FAILURE_BACKOFF_MS
493
+ const forceCooldownMs = Math.min(failureBackoffMs, options.forceCooldownMs ?? PRICE_FORCE_COOLDOWN_MS)
497
494
  const timeoutMs = options.timeoutMs ?? PRICE_TIMEOUT_MS
498
495
  let book = null
499
496
  let fetchedAt = null
500
497
  let version = 0
501
498
  let failed = false
502
499
  let retryAt = 0
500
+ let forceRetryAt = 0
503
501
  let inflight = null
504
502
  let controller = null
505
503
  let disposed = false
@@ -514,21 +512,33 @@ export function createPricingCatalog(options = {}) {
514
512
  })
515
513
 
516
514
  async function refresh() {
517
- controller = new AbortController()
515
+ const requestController = new AbortController()
516
+ controller = requestController
517
+ const { signal } = requestController
518
518
  let timer
519
+ let onAbort
519
520
  try {
520
521
  // Race explicitly: a custom fetcher might not implement AbortSignal.
521
522
  const next = await Promise.race([
522
523
  Promise.resolve().then(async () => {
523
524
  const response = await fetchImpl(PRICE_SOURCE, {
524
525
  headers: { accept: 'application/json', 'user-agent': 'Mozilla/5.0 TokenReceipt/1.0 (+https://github.com/maxlee/dsh-token-receipt)' },
525
- signal: controller.signal,
526
+ signal,
526
527
  })
527
528
  if (!response || !response.ok) throw new Error(`Model price request failed (${response?.status ?? 'no response'})`)
528
529
  return pricesBookOf(await response.json())
529
530
  }),
530
531
  new Promise((_, reject) => {
531
- timer = setTimeout(() => { controller?.abort(); reject(new Error('Model price request timed out')) }, timeoutMs)
532
+ if (signal.aborted) {
533
+ reject(new Error('Model price request aborted'))
534
+ return
535
+ }
536
+ onAbort = () => reject(new Error('Model price request aborted'))
537
+ signal.addEventListener('abort', onAbort, { once: true })
538
+ timer = setTimeout(() => {
539
+ reject(new Error('Model price request timed out'))
540
+ requestController.abort()
541
+ }, timeoutMs)
532
542
  }),
533
543
  ])
534
544
  if (next === null || next.index.branches.size === 0) throw new Error('Model price catalog contains no usable rates')
@@ -538,22 +548,29 @@ export function createPricingCatalog(options = {}) {
538
548
  version += 1
539
549
  failed = false
540
550
  retryAt = 0
551
+ forceRetryAt = 0
541
552
  } catch {
542
553
  if (disposed) return
554
+ const failedAt = now()
543
555
  failed = true
544
- retryAt = now() + failureBackoffMs
556
+ retryAt = failedAt + failureBackoffMs
557
+ forceRetryAt = failedAt + forceCooldownMs
545
558
  } finally {
546
559
  clearTimeout(timer)
547
- controller = null
560
+ if (onAbort) signal.removeEventListener('abort', onAbort)
561
+ if (controller === requestController) controller = null
548
562
  }
549
563
  }
550
564
 
551
565
  return {
552
- async read() {
566
+ async read(options = {}) {
553
567
  if (disposed) return snapshot()
554
568
  if (inflight !== null) { await inflight; return snapshot() }
555
- const fresh = book !== null && fetchedAt !== null && now() - fetchedAt < ttlMs
556
- if ((!fresh || failed) && now() >= retryAt) {
569
+ const currentNow = now()
570
+ const force = Boolean(options?.force)
571
+ const stale = book !== null && (failed || fetchedAt === null || currentNow - fetchedAt >= ttlMs)
572
+ const needsRefresh = book === null || stale
573
+ if (needsRefresh && currentNow >= (force ? forceRetryAt : retryAt)) {
557
574
  inflight = refresh()
558
575
  try { await inflight } finally { inflight = null }
559
576
  }
package/RELEASING.md DELETED
@@ -1,31 +0,0 @@
1
- # Releasing
2
-
3
- This repository is set up for a public npm package and a GitHub repository.
4
-
5
- ## Before the first publish
6
-
7
- 1. Confirm the package name in `package.json` is still available:
8
- `npm view dsh-token-receipt version`.
9
- 2. Log in to npm with the account that owns `@maxlee`:
10
- `npm login`.
11
- 3. Run the local checks:
12
- `npm run check && npm pack --dry-run`.
13
-
14
- ## Publish a version
15
-
16
- ```bash
17
- npm version patch # or minor / major
18
- git push origin main --tags
19
- npm publish --access public
20
- ```
21
-
22
- For a trusted-publishing release from GitHub Actions, create an
23
- `NPM_TOKEN` repository secret (or configure npm trusted publishing) and push a
24
- `v*` tag. The `release.yml` workflow publishes with provenance.
25
-
26
- ## Push the repository
27
-
28
- ```bash
29
- git remote add origin git@github.com:maxlee/dsh-token-receipt.git
30
- git push -u origin main --tags
31
- ```