dsh-model-allowance 1.1.1 → 1.2.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/README.md +9 -3
- package/README.zh.md +7 -3
- package/client.js +282 -118
- package/index.js +69 -0
- package/lib/providers/openai_codex.js +334 -0
- package/lib/providers/promotions.js +169 -0
- package/lib/providers/qwen_promotions.js +223 -0
- package/lib/providers/qwen_token_plan.js +3 -0
- package/lib/providers/shared.js +14 -0
- package/lib/providers/zai.js +25 -0
- package/lib/providers.js +6 -2
- package/lib/remote.js +14 -0
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -10,6 +10,7 @@ import { Service } from '@deepseek-ai/cordis'
|
|
|
10
10
|
import z from '@deepseek-ai/schemastery'
|
|
11
11
|
import { BalanceService } from './lib/balance.js'
|
|
12
12
|
import { describeError, logDebug } from './lib/debug.js'
|
|
13
|
+
import { promotionExpired } from './lib/providers/promotions.js'
|
|
13
14
|
import { holidayCoverage } from './lib/providers/schedule.js'
|
|
14
15
|
import { findAdapter, KIND_AMOUNT, KIND_QUOTA, PROVIDER_ADAPTERS } from './lib/providers.js'
|
|
15
16
|
import { BalanceController } from './lib/remote.js'
|
|
@@ -38,6 +39,12 @@ function modelOf(model) {
|
|
|
38
39
|
return typeof model === 'string' && model !== '' ? model : undefined
|
|
39
40
|
}
|
|
40
41
|
|
|
42
|
+
/** How long a successful live promotions read is reused: offers change rarely. */
|
|
43
|
+
const PROMOTIONS_TTL_MS = 60 * 60 * 1000
|
|
44
|
+
|
|
45
|
+
/** How long a failed live promotions read is remembered before trying again. */
|
|
46
|
+
const PROMOTIONS_FAILURE_TTL_MS = 5 * 60 * 1000
|
|
47
|
+
|
|
41
48
|
/**
|
|
42
49
|
* The resolved plugin configuration.
|
|
43
50
|
* @typedef {object} ModelAllowanceConfig
|
|
@@ -92,6 +99,14 @@ class ModelAllowanceService extends Service {
|
|
|
92
99
|
*/
|
|
93
100
|
this.active = new Map()
|
|
94
101
|
|
|
102
|
+
/**
|
|
103
|
+
* Live promotions reads, keyed by route: the last outcome and when it
|
|
104
|
+
* landed. A success is reused for an hour; a failure is remembered briefly
|
|
105
|
+
* so a catalog outage costs one request per backoff, not one per open.
|
|
106
|
+
* @type {Map<string, {at: number, ok: boolean, value?: readonly object[]}>}
|
|
107
|
+
*/
|
|
108
|
+
this.promotionReads = new Map()
|
|
109
|
+
|
|
95
110
|
/**
|
|
96
111
|
* Platform status readings. Every source is a public page, so this half
|
|
97
112
|
* needs no credential — only the vendor's status URL.
|
|
@@ -233,6 +248,49 @@ class ModelAllowanceService extends Service {
|
|
|
233
248
|
return schedule === undefined ? null : { provider, ...schedule }
|
|
234
249
|
}
|
|
235
250
|
|
|
251
|
+
/**
|
|
252
|
+
* The model-scoped usage promotions a vendor has, when it has any.
|
|
253
|
+
*
|
|
254
|
+
* A static declaration is returned as-is: the browser decides which date
|
|
255
|
+
* windows its own clock falls inside, so a badge appears and disappears
|
|
256
|
+
* without another round trip. A live source (a public catalog) is read on
|
|
257
|
+
* a slow cache and returned without a window — its badge is its own truth.
|
|
258
|
+
* Either way a promotion never changes a balance reading: the allowance is
|
|
259
|
+
* the same; what it buys on the covered models is what differs.
|
|
260
|
+
*
|
|
261
|
+
* @param {string} provider Provider route.
|
|
262
|
+
* @returns {Promise<object | null>} The promotions, or null when there are none.
|
|
263
|
+
*/
|
|
264
|
+
async promotions(provider) {
|
|
265
|
+
const adapter = findAdapter(provider)
|
|
266
|
+
if (adapter === undefined) return null
|
|
267
|
+
if (adapter.promotions !== undefined) {
|
|
268
|
+
return { provider, promotions: adapter.promotions }
|
|
269
|
+
}
|
|
270
|
+
if (typeof adapter.readPromotions !== 'function') return null
|
|
271
|
+
const now = Date.now()
|
|
272
|
+
const cached = this.promotionReads.get(provider)
|
|
273
|
+
const ttl = cached?.ok === true ? PROMOTIONS_TTL_MS : PROMOTIONS_FAILURE_TTL_MS
|
|
274
|
+
if (cached !== undefined && now - cached.at < ttl) {
|
|
275
|
+
return cached.ok === true && cached.value.length > 0
|
|
276
|
+
? { provider, promotions: cached.value }
|
|
277
|
+
: null
|
|
278
|
+
}
|
|
279
|
+
try {
|
|
280
|
+
const value = await adapter.readPromotions({
|
|
281
|
+
signal: AbortSignal.timeout(this.config.requestTimeoutMs),
|
|
282
|
+
})
|
|
283
|
+
this.promotionReads.set(provider, { at: now, ok: true, value })
|
|
284
|
+
return value.length > 0 ? { provider, promotions: value } : null
|
|
285
|
+
} catch (error) {
|
|
286
|
+
this.promotionReads.set(provider, { at: now, ok: false })
|
|
287
|
+
if (this.config.debug === true) {
|
|
288
|
+
await logDebug(`promotions route=${provider} failed: ${describeError(error)}`)
|
|
289
|
+
}
|
|
290
|
+
return null
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
236
294
|
/**
|
|
237
295
|
* The provider a session with no model selection would use.
|
|
238
296
|
*
|
|
@@ -318,6 +376,17 @@ class ModelAllowanceService extends Service {
|
|
|
318
376
|
`extend it for ${String(thisYear)}`,
|
|
319
377
|
)
|
|
320
378
|
}
|
|
379
|
+
// A promotion is a dated event: once its last day has passed in the
|
|
380
|
+
// vendor's own zone, the declaration is dead weight. The browser already
|
|
381
|
+
// stops showing it; this warns the maintainer to remove it.
|
|
382
|
+
for (const promotion of adapter.promotions ?? []) {
|
|
383
|
+
if (promotion.to !== undefined && promotionExpired(promotion, Date.now())) {
|
|
384
|
+
console.warn(
|
|
385
|
+
`[model-allowance] ${adapter.id} promotion for ${promotion.models.join(', ')} ` +
|
|
386
|
+
`ended ${promotion.to}; remove the declaration`,
|
|
387
|
+
)
|
|
388
|
+
}
|
|
389
|
+
}
|
|
321
390
|
}
|
|
322
391
|
|
|
323
392
|
// Both listeners are `global`. `session/event` is emitted from the
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI Codex (ChatGPT subscription) adapter.
|
|
3
|
+
*
|
|
4
|
+
* Shun-mao ("with the grain") by construction:
|
|
5
|
+
* - The data source is the vendor's OWN usage endpoint
|
|
6
|
+
* `GET https://chatgpt.com/backend-api/wham/usage` — the same one the official
|
|
7
|
+
* Codex CLI polls. One cheap metadata GET; it spends no plan quota, runs no
|
|
8
|
+
* inference and bills no turn (even an exhausted plan answers 200).
|
|
9
|
+
* - Authorization reuses the grant the host already owns and refreshes:
|
|
10
|
+
* pi-ai stores the ChatGPT OAuth under the credential record
|
|
11
|
+
* `llm-pi-ai/openai-codex` (kind `grant`, payload {access, refresh, expires,
|
|
12
|
+
* accountId}). This adapter only READS that record; it never refreshes a
|
|
13
|
+
* token itself, never spoofs a browser, and never posts a billed probe.
|
|
14
|
+
* - The request carries the official Codex client headers (bearer +
|
|
15
|
+
* ChatGPT-Account-Id + codex_cli_rs originator), matching what DSH's own
|
|
16
|
+
* pi-ai Codex provider sends.
|
|
17
|
+
*
|
|
18
|
+
* The plan meters a short rolling window (primary, usually 5 h) and a long one
|
|
19
|
+
* (secondary, usually weekly). Each reports `used_percent`; the shared shape
|
|
20
|
+
* carries the share LEFT, so this projects `100 - used_percent`. Window length
|
|
21
|
+
* is read from `limit_window_seconds` rather than assumed, because Plus plans
|
|
22
|
+
* have been seen to report a single seven-day primary window with no secondary.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { asObject, bindingWindow, defineAdapter, KIND_QUOTA, parseAmount } from './shared.js'
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The host credential service widened to the record half of the seam: the
|
|
29
|
+
* Codex OAuth is a `grant` record read via readRecord, not an env resolve.
|
|
30
|
+
* @typedef {{ readRecord?: (key: string) => Promise<{ payload?: Record<string, unknown> } | undefined> }} GrantReader
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
/** The official Codex usage endpoint (same one the Codex CLI polls). */
|
|
34
|
+
const USAGE_ENDPOINT = 'https://chatgpt.com/backend-api/wham/usage'
|
|
35
|
+
|
|
36
|
+
/** Subscription side, where the plan itself lives — not the API billing console. */
|
|
37
|
+
const CONSOLE = 'https://chatgpt.com/'
|
|
38
|
+
|
|
39
|
+
/** pi-ai owns the Codex OAuth grant under this credential scope. */
|
|
40
|
+
const CREDENTIAL_SCOPE = 'llm-pi-ai'
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Name a window length from its duration in seconds, preferring whole weeks for
|
|
44
|
+
* the long window so a 7-day plan reads as "1 week", not "7 days".
|
|
45
|
+
* @param {number | undefined} seconds
|
|
46
|
+
* @returns {{unit: 'hour'|'day'|'week'|'month'|'unknown', count?: number}}
|
|
47
|
+
*/
|
|
48
|
+
function windowShape(seconds) {
|
|
49
|
+
if (seconds === undefined || !Number.isFinite(seconds) || seconds <= 0) return { unit: 'unknown' }
|
|
50
|
+
const hours = seconds / 3600
|
|
51
|
+
if (hours < 24) return { unit: 'hour', count: Math.round(hours) }
|
|
52
|
+
const days = seconds / 86400
|
|
53
|
+
if (days >= 7 && days < 28 && Number.isInteger(days / 7)) return { unit: 'week', count: days / 7 }
|
|
54
|
+
if (days < 28) return { unit: 'day', count: Math.round(days) }
|
|
55
|
+
return { unit: 'month', count: Math.round(days / 30) }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Project one rate-limit window onto the shared BalanceWindow shape.
|
|
60
|
+
* @param {unknown} raw The vendor window node.
|
|
61
|
+
* @param {string} id Stable positional identity (`session` / `weekly`).
|
|
62
|
+
* @returns {import('./shared.js').BalanceWindow | undefined}
|
|
63
|
+
*/
|
|
64
|
+
function projectWindow(raw, id) {
|
|
65
|
+
const node = asObject(raw)
|
|
66
|
+
const used = parseAmount(node.used_percent)
|
|
67
|
+
if (used === undefined) return undefined
|
|
68
|
+
const shape = windowShape(parseAmount(node.limit_window_seconds))
|
|
69
|
+
// reset_at is epoch SECONDS; fall back to the relative reset_after_seconds.
|
|
70
|
+
const resetAtSec = parseAmount(node.reset_at)
|
|
71
|
+
const resetAfter = parseAmount(node.reset_after_seconds)
|
|
72
|
+
const resetAt =
|
|
73
|
+
resetAtSec !== undefined
|
|
74
|
+
? resetAtSec * 1000
|
|
75
|
+
: resetAfter !== undefined
|
|
76
|
+
? Date.now() + resetAfter * 1000
|
|
77
|
+
: undefined
|
|
78
|
+
return {
|
|
79
|
+
id,
|
|
80
|
+
unit: shape.unit,
|
|
81
|
+
...(shape.count === undefined ? {} : { count: shape.count }),
|
|
82
|
+
remainingPercent: Math.max(0, Math.round((100 - used) * 100) / 100),
|
|
83
|
+
...(resetAt === undefined ? {} : { resetAt }),
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Read the Codex subscription rate-limit windows through the host's own grant.
|
|
89
|
+
* @param {import('../providers.js').AdapterEnv} env Query context.
|
|
90
|
+
* @returns {Promise<import('../providers.js').BalanceView>} The reading.
|
|
91
|
+
*/
|
|
92
|
+
async function readCodexUsage({ route, ctx, signal }) {
|
|
93
|
+
const credentials = /** @type {GrantReader | undefined} */ (
|
|
94
|
+
typeof ctx?.get === 'function' ? ctx.get('credentials') : undefined
|
|
95
|
+
)
|
|
96
|
+
if (credentials === undefined || typeof credentials.readRecord !== 'function') {
|
|
97
|
+
return { provider: route, status: 'unconfigured', kind: KIND_QUOTA }
|
|
98
|
+
}
|
|
99
|
+
// The grant key is deterministic from the route: <pi-ai scope>/<route>.
|
|
100
|
+
let record
|
|
101
|
+
try {
|
|
102
|
+
record = await credentials.readRecord(`${CREDENTIAL_SCOPE}/${route}`)
|
|
103
|
+
} catch {
|
|
104
|
+
record = undefined
|
|
105
|
+
}
|
|
106
|
+
const payload = asObject(record?.payload)
|
|
107
|
+
const access = typeof payload.access === 'string' ? payload.access : ''
|
|
108
|
+
const accountId = typeof payload.accountId === 'string' ? payload.accountId : ''
|
|
109
|
+
if (access === '' || accountId === '') {
|
|
110
|
+
return { provider: route, status: 'unconfigured', kind: KIND_QUOTA }
|
|
111
|
+
}
|
|
112
|
+
// Never refresh the token here — the host (pi-ai) owns refresh. An expired
|
|
113
|
+
// grant is reported so the user knows one Codex request will renew it.
|
|
114
|
+
const expires = parseAmount(payload.expires)
|
|
115
|
+
if (expires !== undefined && expires <= Date.now()) {
|
|
116
|
+
return {
|
|
117
|
+
provider: route,
|
|
118
|
+
status: 'failed',
|
|
119
|
+
kind: KIND_QUOTA,
|
|
120
|
+
error: 'Codex 登录态已过期,在 DSH 里用一次 Codex 模型即可自动刷新',
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const response = await fetch(USAGE_ENDPOINT, {
|
|
125
|
+
headers: {
|
|
126
|
+
authorization: `Bearer ${access}`,
|
|
127
|
+
'ChatGPT-Account-Id': accountId,
|
|
128
|
+
'User-Agent': 'codex_cli_rs/0.164.0',
|
|
129
|
+
originator: 'codex_cli_rs',
|
|
130
|
+
accept: 'application/json',
|
|
131
|
+
},
|
|
132
|
+
signal,
|
|
133
|
+
})
|
|
134
|
+
if (response.status === 401 || response.status === 403) {
|
|
135
|
+
return {
|
|
136
|
+
provider: route,
|
|
137
|
+
status: 'failed',
|
|
138
|
+
kind: KIND_QUOTA,
|
|
139
|
+
error: `Codex 授权被拒(HTTP ${String(response.status)}),请重新登录 ChatGPT/Codex`,
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (!response.ok) {
|
|
143
|
+
return {
|
|
144
|
+
provider: route,
|
|
145
|
+
status: 'failed',
|
|
146
|
+
kind: KIND_QUOTA,
|
|
147
|
+
error: `HTTP ${String(response.status)}`,
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const body = asObject(await response.json())
|
|
151
|
+
const rateLimit = asObject(body.rate_limit)
|
|
152
|
+
/** @type {import('./shared.js').BalanceWindow[]} */
|
|
153
|
+
const windows = []
|
|
154
|
+
const primary = projectWindow(rateLimit.primary_window, 'session')
|
|
155
|
+
if (primary !== undefined) windows.push(primary)
|
|
156
|
+
const secondary = projectWindow(rateLimit.secondary_window, 'weekly')
|
|
157
|
+
if (secondary !== undefined) windows.push(secondary)
|
|
158
|
+
if (windows.length === 0) {
|
|
159
|
+
return {
|
|
160
|
+
provider: route,
|
|
161
|
+
status: 'failed',
|
|
162
|
+
kind: KIND_QUOTA,
|
|
163
|
+
error: 'wham/usage 未返回限流窗口(上游接口可能已变更)',
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
const binding = bindingWindow(windows)
|
|
167
|
+
return {
|
|
168
|
+
provider: route,
|
|
169
|
+
status: 'ready',
|
|
170
|
+
kind: KIND_QUOTA,
|
|
171
|
+
...(binding?.remainingPercent === undefined ? {} : { percent: binding.remainingPercent }),
|
|
172
|
+
...(binding?.resetAt === undefined ? {} : { resetsAt: binding.resetAt }),
|
|
173
|
+
windows,
|
|
174
|
+
consoleUrl: CONSOLE,
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** A recorded future expiry so fixtures read as a live grant. */
|
|
179
|
+
const RECORDED_EXPIRES = 4102444800000 // 2100-01-01
|
|
180
|
+
|
|
181
|
+
/** The host grant record, as pi-ai stores it (values recorded, not real). */
|
|
182
|
+
const RECORDED_CREDENTIALS = {
|
|
183
|
+
readRecord: async (key) =>
|
|
184
|
+
key === 'llm-pi-ai/openai-codex'
|
|
185
|
+
? {
|
|
186
|
+
kind: 'grant',
|
|
187
|
+
payload: {
|
|
188
|
+
type: 'oauth',
|
|
189
|
+
access: 'recorded-access',
|
|
190
|
+
refresh: 'recorded-refresh',
|
|
191
|
+
expires: RECORDED_EXPIRES,
|
|
192
|
+
accountId: 'recorded-account',
|
|
193
|
+
},
|
|
194
|
+
}
|
|
195
|
+
: undefined,
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** An exhausted Plus plan: 5 h window full, weekly window 78 % used. PII stripped. */
|
|
199
|
+
const RECORDED_EXHAUSTED = {
|
|
200
|
+
plan_type: 'plus',
|
|
201
|
+
rate_limit: {
|
|
202
|
+
allowed: false,
|
|
203
|
+
limit_reached: true,
|
|
204
|
+
primary_window: {
|
|
205
|
+
used_percent: 100,
|
|
206
|
+
limit_window_seconds: 18000,
|
|
207
|
+
reset_after_seconds: 12650,
|
|
208
|
+
reset_at: 1796495712,
|
|
209
|
+
},
|
|
210
|
+
secondary_window: {
|
|
211
|
+
used_percent: 78,
|
|
212
|
+
limit_window_seconds: 604800,
|
|
213
|
+
reset_after_seconds: 426554,
|
|
214
|
+
reset_at: 1796909616,
|
|
215
|
+
},
|
|
216
|
+
},
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** A healthy plan: 5 h window 30 % used, weekly 10 % used. */
|
|
220
|
+
const RECORDED_HEALTHY = {
|
|
221
|
+
plan_type: 'plus',
|
|
222
|
+
rate_limit: {
|
|
223
|
+
allowed: true,
|
|
224
|
+
limit_reached: false,
|
|
225
|
+
primary_window: {
|
|
226
|
+
used_percent: 30,
|
|
227
|
+
limit_window_seconds: 18000,
|
|
228
|
+
reset_after_seconds: 9000,
|
|
229
|
+
reset_at: 1796495712,
|
|
230
|
+
},
|
|
231
|
+
secondary_window: {
|
|
232
|
+
used_percent: 10,
|
|
233
|
+
limit_window_seconds: 604800,
|
|
234
|
+
reset_after_seconds: 500000,
|
|
235
|
+
reset_at: 1796909616,
|
|
236
|
+
},
|
|
237
|
+
},
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** A single seven-day primary window, no secondary (seen on some Plus plans). */
|
|
241
|
+
const RECORDED_SINGLE = {
|
|
242
|
+
plan_type: 'plus',
|
|
243
|
+
rate_limit: {
|
|
244
|
+
allowed: true,
|
|
245
|
+
limit_reached: false,
|
|
246
|
+
primary_window: {
|
|
247
|
+
used_percent: 60,
|
|
248
|
+
limit_window_seconds: 604800,
|
|
249
|
+
reset_after_seconds: 300000,
|
|
250
|
+
reset_at: 1796909616,
|
|
251
|
+
},
|
|
252
|
+
secondary_window: null,
|
|
253
|
+
},
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** The declared adapters this module serves. */
|
|
257
|
+
export const openaiCodexAdapters = [
|
|
258
|
+
defineAdapter({
|
|
259
|
+
id: 'openai-codex',
|
|
260
|
+
routes: ['openai-codex'],
|
|
261
|
+
kind: KIND_QUOTA,
|
|
262
|
+
consoleUrl: CONSOLE,
|
|
263
|
+
display: {
|
|
264
|
+
name: { zh: 'OpenAI Codex', en: 'OpenAI Codex' },
|
|
265
|
+
mark: { icon: 'openai', color: '#10A37F' },
|
|
266
|
+
},
|
|
267
|
+
readWithEnv: readCodexUsage,
|
|
268
|
+
fixtures: [
|
|
269
|
+
{
|
|
270
|
+
name: 'exhausted five-hour window pins the badge at zero',
|
|
271
|
+
services: { credentials: RECORDED_CREDENTIALS },
|
|
272
|
+
responses: [RECORDED_EXHAUSTED],
|
|
273
|
+
expect: {
|
|
274
|
+
status: 'ready',
|
|
275
|
+
kind: KIND_QUOTA,
|
|
276
|
+
percent: 0,
|
|
277
|
+
resetsAt: 1796495712000,
|
|
278
|
+
windows: [
|
|
279
|
+
{ id: 'session', unit: 'hour', count: 5, remainingPercent: 0, resetAt: 1796495712000 },
|
|
280
|
+
{ id: 'weekly', unit: 'week', count: 1, remainingPercent: 22, resetAt: 1796909616000 },
|
|
281
|
+
],
|
|
282
|
+
},
|
|
283
|
+
},
|
|
284
|
+
{
|
|
285
|
+
name: 'healthy plan reports the share left in both windows',
|
|
286
|
+
services: { credentials: RECORDED_CREDENTIALS },
|
|
287
|
+
responses: [RECORDED_HEALTHY],
|
|
288
|
+
expect: {
|
|
289
|
+
status: 'ready',
|
|
290
|
+
percent: 70,
|
|
291
|
+
windows: [
|
|
292
|
+
{ id: 'session', remainingPercent: 70 },
|
|
293
|
+
{ id: 'weekly', remainingPercent: 90 },
|
|
294
|
+
],
|
|
295
|
+
},
|
|
296
|
+
},
|
|
297
|
+
{
|
|
298
|
+
name: 'a single seven-day primary window reads as one week',
|
|
299
|
+
services: { credentials: RECORDED_CREDENTIALS },
|
|
300
|
+
responses: [RECORDED_SINGLE],
|
|
301
|
+
expect: {
|
|
302
|
+
status: 'ready',
|
|
303
|
+
percent: 40,
|
|
304
|
+
windows: [{ id: 'session', unit: 'week', count: 1, remainingPercent: 40 }],
|
|
305
|
+
},
|
|
306
|
+
absent: ['windows[1]'],
|
|
307
|
+
},
|
|
308
|
+
{
|
|
309
|
+
name: 'no host grant configured',
|
|
310
|
+
services: {},
|
|
311
|
+
expect: { status: 'unconfigured', kind: KIND_QUOTA },
|
|
312
|
+
},
|
|
313
|
+
{
|
|
314
|
+
name: 'an expired grant is reported, never self-refreshed',
|
|
315
|
+
services: {
|
|
316
|
+
credentials: {
|
|
317
|
+
readRecord: async () => ({
|
|
318
|
+
kind: 'grant',
|
|
319
|
+
payload: { type: 'oauth', access: 'a', accountId: 'b', expires: 1 },
|
|
320
|
+
}),
|
|
321
|
+
},
|
|
322
|
+
},
|
|
323
|
+
expect: { status: 'failed', kind: KIND_QUOTA },
|
|
324
|
+
},
|
|
325
|
+
{
|
|
326
|
+
name: 'an authorization refusal names the status',
|
|
327
|
+
services: { credentials: RECORDED_CREDENTIALS },
|
|
328
|
+
responses: [RECORDED_EXHAUSTED],
|
|
329
|
+
httpStatus: 401,
|
|
330
|
+
expect: { status: 'failed', kind: KIND_QUOTA },
|
|
331
|
+
},
|
|
332
|
+
],
|
|
333
|
+
}),
|
|
334
|
+
]
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model-scoped usage promotions.
|
|
3
|
+
*
|
|
4
|
+
* A vendor occasionally declares that the same plan allowance supports more
|
|
5
|
+
* usage of specific models — for a dated window, or for as long as its catalog
|
|
6
|
+
* says so. The card's only statement of that is a small badge on the covered
|
|
7
|
+
* model's row in the switch menu; hovering the badge reads the vendor's
|
|
8
|
+
* one-line announcement. Nothing else is written out: the allowance itself
|
|
9
|
+
* never changes, so no reading, panel block, or countdown is involved.
|
|
10
|
+
*
|
|
11
|
+
* Two sources share one shape. A static declaration carries its own date
|
|
12
|
+
* window, and the browser evaluates it against its own clock, so the badge
|
|
13
|
+
* appears and disappears with no extra round trips. A live source (a public
|
|
14
|
+
* catalog API) carries no window: its badge is its own truth, and the Host
|
|
15
|
+
* re-reads it on a slow cache.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** ISO calendar date, in the promotion's own zone. */
|
|
19
|
+
const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/
|
|
20
|
+
|
|
21
|
+
/** HH:MM in 24-hour wall time; `24:00` is the day's end. */
|
|
22
|
+
const TIME_PATTERN = /^(?:(?:[01]\d|2[0-3]):[0-5]\d|24:00)$/
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Minutes since midnight for one `HH:MM` wall time.
|
|
26
|
+
* @param {string} time Wall-clock time.
|
|
27
|
+
* @returns {number} Minutes since midnight.
|
|
28
|
+
*/
|
|
29
|
+
export function timeToMinutes(time) {
|
|
30
|
+
const [hour, minute] = time.split(':').map(Number)
|
|
31
|
+
return hour * 60 + minute
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* One promotion, as {@link definePromotions} normalizes it.
|
|
36
|
+
* @typedef {object} Promotion
|
|
37
|
+
* @property {readonly string[]} models Provider-owned model ids the promotion
|
|
38
|
+
* covers. The browser matches them case-insensitively against the catalog.
|
|
39
|
+
* @property {{zh: string, en: string}} chip The badge label, in the vendor's
|
|
40
|
+
* own words, e.g. `×2` or `限时夜间4折`.
|
|
41
|
+
* @property {{zh: string, en: string}} note The vendor's one-line announcement,
|
|
42
|
+
* shown when the pointer rests on the badge.
|
|
43
|
+
* @property {string} [timezone] IANA zone the date range and daily window refer to.
|
|
44
|
+
* @property {string} [from] First covered calendar date, inclusive, ISO in that
|
|
45
|
+
* zone. Absent together with `to` for a live source.
|
|
46
|
+
* @property {string} [to] Last covered calendar date, inclusive, ISO in that zone.
|
|
47
|
+
* @property {{from: string, to: string}} [daily] The hours of each covered day
|
|
48
|
+
* the offer runs, `HH:MM` in that zone. A `to` earlier than `from` crosses
|
|
49
|
+
* midnight (22:00–08:00 is the night). Absent means the whole day.
|
|
50
|
+
*/
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Declare promotions, refusing an unusable declaration.
|
|
54
|
+
*
|
|
55
|
+
* Both windows are optional — a live source's badge may need neither — but
|
|
56
|
+
* each is facts together: a date range is a zone and two calendar days in it,
|
|
57
|
+
* both ends inclusive; a daily window is a zone and two wall times in it.
|
|
58
|
+
*
|
|
59
|
+
* @param {Array<{models: string[], chip: {zh: string, en: string}, note: {zh: string, en: string}, timezone?: string, from?: string, to?: string, daily?: {from: string, to: string}}>} specs The declarations.
|
|
60
|
+
* @returns {readonly Promotion[]} The frozen promotions.
|
|
61
|
+
*/
|
|
62
|
+
export function definePromotions(specs) {
|
|
63
|
+
const where = 'promotions'
|
|
64
|
+
if (!Array.isArray(specs)) throw new Error(`${where} must be a list`)
|
|
65
|
+
return Object.freeze(
|
|
66
|
+
specs.map((spec, index) => {
|
|
67
|
+
const at = `${where}[${String(index)}]`
|
|
68
|
+
const models = spec?.models
|
|
69
|
+
if (!Array.isArray(models) || models.length === 0) {
|
|
70
|
+
throw new Error(`${at} names no model`)
|
|
71
|
+
}
|
|
72
|
+
for (const model of models) {
|
|
73
|
+
if (typeof model !== 'string' || model.trim() === '') {
|
|
74
|
+
throw new Error(`${at} has an empty model id`)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
for (const field of ['chip', 'note']) {
|
|
78
|
+
for (const key of ['zh', 'en']) {
|
|
79
|
+
const text = spec?.[field]?.[key]
|
|
80
|
+
if (typeof text !== 'string' || text === '') {
|
|
81
|
+
throw new Error(`${at} needs a ${field} for ${key}`)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const hasDates = spec.from !== undefined || spec.to !== undefined
|
|
86
|
+
const hasDaily = spec.daily !== undefined
|
|
87
|
+
if (hasDates || hasDaily) {
|
|
88
|
+
if (typeof spec.timezone !== 'string' || spec.timezone === '') {
|
|
89
|
+
throw new Error(`${at} needs an IANA time zone`)
|
|
90
|
+
}
|
|
91
|
+
try {
|
|
92
|
+
new Intl.DateTimeFormat('en-US', { timeZone: spec.timezone })
|
|
93
|
+
} catch {
|
|
94
|
+
throw new Error(`${at} names an unknown time zone "${spec.timezone}"`)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (hasDates) {
|
|
98
|
+
for (const key of ['from', 'to']) {
|
|
99
|
+
const date = spec[key]
|
|
100
|
+
if (typeof date !== 'string' || !DATE_PATTERN.test(date)) {
|
|
101
|
+
throw new Error(`${at} has a ${key} date that is not YYYY-MM-DD`)
|
|
102
|
+
}
|
|
103
|
+
if (Number.isNaN(Date.parse(`${date}T00:00:00Z`))) {
|
|
104
|
+
throw new Error(`${at} has an invalid ${key} date ${date}`)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (spec.to < spec.from) throw new Error(`${at} ends before it starts`)
|
|
108
|
+
}
|
|
109
|
+
if (hasDaily) {
|
|
110
|
+
for (const key of ['from', 'to']) {
|
|
111
|
+
const time = spec.daily?.[key]
|
|
112
|
+
if (typeof time !== 'string' || !TIME_PATTERN.test(time)) {
|
|
113
|
+
throw new Error(`${at} has a daily ${key} that is not HH:MM`)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return Object.freeze({
|
|
118
|
+
models: Object.freeze(models.map((model) => model.trim())),
|
|
119
|
+
chip: Object.freeze({ zh: spec.chip.zh, en: spec.chip.en }),
|
|
120
|
+
note: Object.freeze({ zh: spec.note.zh, en: spec.note.en }),
|
|
121
|
+
...(hasDates || hasDaily ? { timezone: spec.timezone } : {}),
|
|
122
|
+
...(hasDates ? { from: spec.from, to: spec.to } : {}),
|
|
123
|
+
...(hasDaily ? { daily: Object.freeze({ from: spec.daily.from, to: spec.daily.to }) } : {}),
|
|
124
|
+
})
|
|
125
|
+
}),
|
|
126
|
+
)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Zone date formatters, built once: constructing one is not free. */
|
|
130
|
+
const ZONE_DATE_FORMATTERS = new Map()
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The calendar date of one instant in a named zone, as `YYYY-MM-DD`.
|
|
134
|
+
* @param {number} ms The instant.
|
|
135
|
+
* @param {string} timeZone IANA zone.
|
|
136
|
+
* @returns {string} The zone's date.
|
|
137
|
+
*/
|
|
138
|
+
export function zoneDateOf(ms, timeZone) {
|
|
139
|
+
let formatter = ZONE_DATE_FORMATTERS.get(timeZone)
|
|
140
|
+
if (formatter === undefined) {
|
|
141
|
+
formatter = new Intl.DateTimeFormat('en-US', {
|
|
142
|
+
timeZone,
|
|
143
|
+
year: 'numeric',
|
|
144
|
+
month: '2-digit',
|
|
145
|
+
day: '2-digit',
|
|
146
|
+
})
|
|
147
|
+
ZONE_DATE_FORMATTERS.set(timeZone, formatter)
|
|
148
|
+
}
|
|
149
|
+
const parts = formatter.formatToParts(new Date(ms))
|
|
150
|
+
const value = (type) => parts.find((part) => part.type === type)?.value ?? ''
|
|
151
|
+
return `${value('year')}-${value('month')}-${value('day')}`
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Whether a dated promotion's last covered day has wholly passed in its zone.
|
|
156
|
+
*
|
|
157
|
+
* Startup diagnostics use this to surface a declaration nobody removed after
|
|
158
|
+
* the event ended; the browser needs no such check, since an expired
|
|
159
|
+
* promotion simply stops matching its date range. A windowless promotion
|
|
160
|
+
* never expires this way — its source decides when it ends.
|
|
161
|
+
*
|
|
162
|
+
* @param {Promotion} promotion The declaration.
|
|
163
|
+
* @param {number} ms The instant to judge at.
|
|
164
|
+
* @returns {boolean} True once the zone's date is past `to`.
|
|
165
|
+
*/
|
|
166
|
+
export function promotionExpired(promotion, ms) {
|
|
167
|
+
if (promotion.to === undefined || promotion.timezone === undefined) return false
|
|
168
|
+
return zoneDateOf(ms, promotion.timezone) > promotion.to
|
|
169
|
+
}
|