@xiangyixie/dsh-superagent 0.12.0 → 0.14.0

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/lib/cost.js CHANGED
@@ -1,267 +1,327 @@
1
- /**
2
- * Cost accounting for recorded token usage.
3
- *
4
- * Prices are list prices per 1M tokens, supplied by the operator as
5
- * `pricing: { "provider/model": { input, output, cacheRead, currency } }`.
6
- * A bare model id is accepted as a fallback, and an exact `provider/model`
7
- * key always wins, so usage logged as `dashscope/qwen-flash` can be priced by
8
- * `"qwen-flash"` without guessing the provider.
9
- *
10
- * Money is accumulated as integer micro-units (1e-6 of the currency), never as
11
- * floating point. Each model line is rounded once to the nearest micro-unit,
12
- * the total is a plain integer sum, and presentation rounds that integer once
13
- * more. A model absent from the table is reported as unpriced — it is never
14
- * silently priced at zero, because "we do not know" and "it was free" are
15
- * different answers.
16
- *
17
- * @module dsh-superagent/cost
18
- */
19
-
20
- /** Micro-units per currency unit. */
21
- const MICRO = 1_000_000
22
- /** Tokens per price unit: the table is quoted per million tokens. */
23
- const TOKENS_PER_PRICE = 1_000_000
24
- /** The smallest amount the report will print instead of "less than". */
25
- const SMALLEST_SHOWN_MICROS = 100
26
-
27
- /**
28
- * Currency symbol for a three-letter code.
29
- * @param {string} code - ISO currency code.
30
- * @returns {string} symbol, or the code plus a space when unknown.
31
- */
32
- export function currencySymbol(code) {
33
- if (code === 'CNY' || code === 'RMB') return '¥'
34
- if (code === 'USD') return '$'
35
- if (code === 'EUR') return '€'
36
- return `${code ?? ''} `
37
- }
38
-
39
- /**
40
- * Convert one configured price to integer micro-units per million tokens.
41
- * @param {unknown} rate - price quoted per 1M tokens.
42
- * @returns {number | null} micro-units, or null when the value is unusable.
43
- */
44
- function rateMicros(rate) {
45
- if (typeof rate !== 'number' || !Number.isFinite(rate) || rate < 0) return null
46
- return Math.round(rate * MICRO)
47
- }
48
-
49
- /**
50
- * Validate and normalise one pricing row.
51
- * @param {unknown} entry - configured `{ input, output, cacheRead?, cache?, currency? }`.
52
- * @returns {{ input: number, output: number, cacheRead: number, currency: string,
53
- * inputMicros: number, outputMicros: number, cacheMicros: number } | null}
54
- */
55
- function normalizeEntry(entry) {
56
- if (!entry || typeof entry !== 'object') return null
57
- const inputMicros = rateMicros(entry.input)
58
- const outputMicros = rateMicros(entry.output)
59
- if (inputMicros === null || outputMicros === null) return null
60
- // A separate cache rate is optional. Without one, cache reads are priced as
61
- // ordinary input, which over-reports rather than under-reports the spend.
62
- const configuredCache = rateMicros(entry.cacheRead ?? entry.cache)
63
- const cacheRead = configuredCache === null ? entry.input : (entry.cacheRead ?? entry.cache)
64
- return {
65
- input: entry.input,
66
- output: entry.output,
67
- cacheRead,
68
- currency: typeof entry.currency === 'string' && entry.currency.trim()
69
- ? entry.currency.trim().toUpperCase()
70
- : 'USD',
71
- inputMicros,
72
- outputMicros,
73
- cacheMicros: configuredCache ?? inputMicros,
74
- }
75
- }
76
-
77
- /**
78
- * Find the price row for one usage model key.
79
- *
80
- * Lookup order: exact `provider/model`, nested `provider: { model: {...} }`,
81
- * then the bare model id. The first usable row wins.
82
- *
83
- * @param {object} table - configured pricing map.
84
- * @param {string} model - usage model key, usually `provider/model`.
85
- * @returns {object | null} normalised price row.
86
- */
87
- function priceFor(table, model) {
88
- const exact = normalizeEntry(table[model])
89
- if (exact) return exact
90
- const slash = model.indexOf('/')
91
- if (slash > 0) {
92
- const provider = model.slice(0, slash)
93
- const bare = model.slice(slash + 1)
94
- const nested = table[provider]
95
- const nestedEntry = nested && typeof nested === 'object' && !Array.isArray(nested)
96
- ? normalizeEntry(nested[bare])
97
- : null
98
- if (nestedEntry) return nestedEntry
99
- const bareEntry = normalizeEntry(table[bare])
100
- if (bareEntry) return bareEntry
101
- }
102
- return null
103
- }
104
-
105
- /**
106
- * Billed micro-units for one token count at one price.
107
- *
108
- * Integer arithmetic with a single half-up rounding keeps a long bill free of
109
- * the drift that accumulates when fractional currency is added in floats.
110
- *
111
- * @param {number} tokens - token count.
112
- * @param {number} priceMicros - micro-currency per 1M tokens.
113
- * @returns {number} micro-units, rounded half-up.
114
- */
115
- function amountMicros(tokens, priceMicros) {
116
- const count = Math.max(0, Math.trunc(Number(tokens) || 0))
117
- if (count === 0 || priceMicros <= 0) return 0
118
- const numerator = BigInt(count) * BigInt(priceMicros)
119
- const denominator = BigInt(TOKENS_PER_PRICE)
120
- const whole = numerator / denominator
121
- const rest = numerator % denominator
122
- const rounded = rest * 2n >= denominator ? whole + 1n : whole
123
- return Number(rounded)
124
- }
125
-
126
- /**
127
- * Price recorded usage with an explicit per-model table.
128
- *
129
- * @param {object | null} usage - summed usage for one run (or subtask).
130
- * @param {Record<string, object> | undefined} pricing - configured price table.
131
- * @returns {{
132
- * currency: string,
133
- * totalMicros: number,
134
- * total: number,
135
- * byModel: Record<string, number>,
136
- * byModelMicros: Record<string, number>,
137
- * records: object[],
138
- * unpriced: string[],
139
- * complete: boolean,
140
- * } | null} cost, or null when there is nothing to price.
141
- */
142
- export function computeCost(usage, pricing) {
143
- if (!usage || !usage.modelCalls) return null
144
- const table = pricing && typeof pricing === 'object' ? pricing : {}
145
- const byModel = {}
146
- const byModelMicros = {}
147
- const records = []
148
- const unpriced = []
149
- let totalMicros = 0
150
- let currency = null
151
-
152
- for (const [model, entry] of Object.entries(usage.models ?? {})) {
153
- const record = {
154
- model,
155
- calls: entry.calls ?? 0,
156
- inputTokens: entry.inputTokens ?? 0,
157
- outputTokens: entry.outputTokens ?? 0,
158
- cacheReadTokens: entry.cacheReadTokens ?? 0,
159
- inputPrice: null,
160
- outputPrice: null,
161
- cachePrice: null,
162
- amountMicros: null,
163
- }
164
- const price = priceFor(table, model)
165
- if (!price) {
166
- // Named, not zero: a caller can see exactly which route has no price.
167
- unpriced.push(model)
168
- records.push(record)
169
- continue
170
- }
171
- record.inputPrice = price.input
172
- record.outputPrice = price.output
173
- record.cachePrice = price.cacheRead
174
- const amount = amountMicros(record.inputTokens, price.inputMicros)
175
- + amountMicros(record.cacheReadTokens, price.cacheMicros)
176
- + amountMicros(record.outputTokens, price.outputMicros)
177
- record.amountMicros = amount
178
- byModelMicros[model] = amount
179
- byModel[model] = amount / MICRO
180
- totalMicros += amount
181
- records.push(record)
182
- currency = currency ?? price.currency
183
- }
184
-
185
- return {
186
- currency: currency ?? 'USD',
187
- totalMicros,
188
- total: totalMicros / MICRO,
189
- byModel,
190
- byModelMicros,
191
- records,
192
- unpriced,
193
- // "Complete" means every recorded model has a price. A usage record with no
194
- // model attribution at all also cannot be called complete.
195
- complete: unpriced.length === 0 && records.length > 0,
196
- }
197
- }
198
-
199
- /**
200
- * Price a run and each of its subtasks.
201
- *
202
- * Subtask costs cover only the worker children; planner and aggregator calls
203
- * are part of the run total but belong to no subtask. A subtask without a
204
- * readable usage log keeps `cost: null` rather than a fabricated zero.
205
- *
206
- * @param {object} run - run record with `usage`, `subtasks`.
207
- * @param {object | undefined} pricing - configured price table.
208
- * @returns {object | null} the run cost.
209
- */
210
- export function applyCost(run, pricing) {
211
- if (!run || typeof run !== 'object') return null
212
- run.cost = computeCost(run.usage, pricing)
213
- for (const subtask of run.subtasks ?? []) {
214
- subtask.cost = computeCost(subtask?.usage, pricing)
215
- }
216
- return run.cost
217
- }
218
-
219
- /**
220
- * Integer micro-units for a cost object, accepting a legacy `total` number.
221
- * @param {{ totalMicros?: number, total?: number } | number} cost - cost record.
222
- * @returns {number} micro-units, or NaN.
223
- */
224
- function microsOf(cost) {
225
- if (typeof cost === 'number') {
226
- return Number.isFinite(cost) ? Math.round(cost * MICRO) : Number.NaN
227
- }
228
- if (cost && Number.isFinite(cost.totalMicros)) return Math.trunc(cost.totalMicros)
229
- if (cost && Number.isFinite(cost.total)) return Math.round(cost.total * MICRO)
230
- return Number.NaN
231
- }
232
-
233
- /**
234
- * Render integer micro-units with one rounding, half-up, at the shown precision.
235
- *
236
- * Four decimals below one currency unit, two above it; a positive amount
237
- * smaller than the smallest shown value is marked as such instead of printed
238
- * as zero.
239
- *
240
- * @param {number} micros - integer micro-units.
241
- * @param {string} [currency] - ISO currency code.
242
- * @returns {string} e.g. `¥0.1016`, `$1.24`, `<¥0.0001`, `—`.
243
- */
244
- export function moneyOfMicros(micros, currency = 'USD') {
245
- const symbol = currencySymbol(currency)
246
- if (!Number.isFinite(micros)) return '—'
247
- if (micros === 0) return `${symbol}0`
248
- const value = Math.abs(micros)
249
- if (value < SMALLEST_SHOWN_MICROS) return `<${symbol}0.0001`
250
- const digits = value < MICRO ? 4 : 2
251
- const step = 10 ** (6 - digits)
252
- const rounded = Math.floor((value + step / 2) / step) * step
253
- const whole = Math.floor(rounded / MICRO)
254
- const fraction = String(rounded % MICRO).padStart(6, '0').slice(0, digits)
255
- return `${micros < 0 ? '-' : ''}${symbol}${whole}.${fraction}`
256
- }
257
-
258
- /**
259
- * Format a cost record (or a bare amount) for display.
260
- * @param {{ totalMicros?: number, total?: number, currency?: string } | number | null} cost - cost.
261
- * @param {string} [currency] - fallback currency code.
262
- * @returns {string} formatted money, or `—` when unknown.
263
- */
264
- export function formatMoney(cost, currency) {
265
- const code = (cost && typeof cost === 'object' && cost.currency) || currency || 'USD'
266
- return moneyOfMicros(microsOf(cost), code)
267
- }
1
+ /**
2
+ * Cost accounting for recorded token usage.
3
+ *
4
+ * Prices are list prices per 1M tokens, supplied by the operator as
5
+ * `pricing: { "provider/model": { input, output, cacheRead, currency } }`.
6
+ * A bare model id is accepted as a fallback, and an exact `provider/model`
7
+ * key always wins, so usage logged as `dashscope/qwen-flash` can be priced by
8
+ * `"qwen-flash"` without guessing the provider.
9
+ *
10
+ * Money is accumulated as integer micro-units (1e-6 of the currency), never as
11
+ * floating point. Each model line is rounded once to the nearest micro-unit,
12
+ * the total is a plain integer sum, and presentation rounds that integer once
13
+ * more. A model absent from the table is reported as unpriced — it is never
14
+ * silently priced at zero, because "we do not know" and "it was free" are
15
+ * different answers.
16
+ *
17
+ * Currencies never add. A run that used a USD route and a CNY route has one
18
+ * subtotal per currency; a cross-currency "total" would be a number whose unit
19
+ * is undefined. Single-currency runs keep the flat `currency` / `totalMicros` /
20
+ * `total` fields callers already read.
21
+ *
22
+ * @module dsh-superagent/cost
23
+ */
24
+
25
+ /** Micro-units per currency unit. */
26
+ const MICRO = 1_000_000
27
+ /** Tokens per price unit: the table is quoted per million tokens. */
28
+ const TOKENS_PER_PRICE = 1_000_000
29
+ /** The smallest amount the report will print instead of "less than". */
30
+ const SMALLEST_SHOWN_MICROS = 100
31
+
32
+ /**
33
+ * Currency symbol for a three-letter code.
34
+ * @param {string} code - ISO currency code.
35
+ * @returns {string} symbol, or the code plus a space when unknown.
36
+ */
37
+ export function currencySymbol(code) {
38
+ if (code === 'CNY' || code === 'RMB') return '¥'
39
+ if (code === 'USD') return '$'
40
+ if (code === 'EUR') return '€'
41
+ return `${code ?? ''} `
42
+ }
43
+
44
+ /**
45
+ * Add one amount to a currency-keyed tally of integer micro-units.
46
+ * @param {Record<string, number>} tally - currency code -> micro-units.
47
+ * @param {string | null | undefined} currency - ISO currency code.
48
+ * @param {number} micros - integer micro-units in that currency.
49
+ * @returns {Record<string, number>} the same tally.
50
+ */
51
+ export function addCurrencyMicros(tally, currency, micros) {
52
+ if (!Number.isFinite(micros)) return tally
53
+ const code = currency || 'USD'
54
+ tally[code] = (tally[code] ?? 0) + micros
55
+ return tally
56
+ }
57
+
58
+ /**
59
+ * Reduce a currency tally to the flat fields callers already use.
60
+ *
61
+ * One currency keeps `currency` / `totalMicros` / `total` exactly as before.
62
+ * More than one yields null for the scalar fields: there is no meaningful sum
63
+ * of ¥ and $, so callers must render `byCurrency` instead of adding.
64
+ *
65
+ * @param {Record<string, number>} tally - currency code -> micro-units.
66
+ * @returns {{ currency: string | null, totalMicros: number | null, total: number | null, mixedCurrency: boolean }}
67
+ */
68
+ export function currencyTotals(tally) {
69
+ const codes = Object.keys(tally ?? {})
70
+ if (codes.length === 0) return { currency: 'USD', totalMicros: 0, total: 0, mixedCurrency: false }
71
+ if (codes.length === 1) {
72
+ const totalMicros = tally[codes[0]]
73
+ return { currency: codes[0], totalMicros, total: totalMicros / MICRO, mixedCurrency: false }
74
+ }
75
+ return { currency: null, totalMicros: null, total: null, mixedCurrency: true }
76
+ }
77
+
78
+ /**
79
+ * Render a currency tally. One currency reads exactly like `formatMoney`;
80
+ * several are joined with `+`, each under its own symbol.
81
+ * @param {Record<string, number>} tally - currency code -> integer micro-units.
82
+ * @returns {string} e.g. `¥0.0952 + $0.0248`.
83
+ */
84
+ export function formatCurrencyTally(tally) {
85
+ const codes = Object.keys(tally ?? {}).sort()
86
+ if (codes.length === 0) return '—'
87
+ return codes.map(code => moneyOfMicros(tally[code], code)).join(' + ')
88
+ }
89
+
90
+ /**
91
+ * Convert one configured price to integer micro-units per million tokens.
92
+ * @param {unknown} rate - price quoted per 1M tokens.
93
+ * @returns {number | null} micro-units, or null when the value is unusable.
94
+ */
95
+ function rateMicros(rate) {
96
+ if (typeof rate !== 'number' || !Number.isFinite(rate) || rate < 0) return null
97
+ return Math.round(rate * MICRO)
98
+ }
99
+
100
+ /**
101
+ * Validate and normalise one pricing row.
102
+ * @param {unknown} entry - configured `{ input, output, cacheRead?, cache?, currency? }`.
103
+ * @returns {{ input: number, output: number, cacheRead: number, currency: string,
104
+ * inputMicros: number, outputMicros: number, cacheMicros: number } | null}
105
+ */
106
+ function normalizeEntry(entry) {
107
+ if (!entry || typeof entry !== 'object') return null
108
+ const inputMicros = rateMicros(entry.input)
109
+ const outputMicros = rateMicros(entry.output)
110
+ if (inputMicros === null || outputMicros === null) return null
111
+ // A separate cache rate is optional. Without one, cache reads are priced as
112
+ // ordinary input, which over-reports rather than under-reports the spend.
113
+ const configuredCache = rateMicros(entry.cacheRead ?? entry.cache)
114
+ const cacheRead = configuredCache === null ? entry.input : (entry.cacheRead ?? entry.cache)
115
+ return {
116
+ input: entry.input,
117
+ output: entry.output,
118
+ cacheRead,
119
+ currency: typeof entry.currency === 'string' && entry.currency.trim()
120
+ ? entry.currency.trim().toUpperCase()
121
+ : 'USD',
122
+ inputMicros,
123
+ outputMicros,
124
+ cacheMicros: configuredCache ?? inputMicros,
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Find the price row for one usage model key.
130
+ *
131
+ * Lookup order: exact `provider/model`, nested `provider: { model: {...} }`,
132
+ * then the bare model id. The first usable row wins.
133
+ *
134
+ * @param {object} table - configured pricing map.
135
+ * @param {string} model - usage model key, usually `provider/model`.
136
+ * @returns {object | null} normalised price row.
137
+ */
138
+ function priceFor(table, model) {
139
+ const exact = normalizeEntry(table[model])
140
+ if (exact) return exact
141
+ const slash = model.indexOf('/')
142
+ if (slash > 0) {
143
+ const provider = model.slice(0, slash)
144
+ const bare = model.slice(slash + 1)
145
+ const nested = table[provider]
146
+ const nestedEntry = nested && typeof nested === 'object' && !Array.isArray(nested)
147
+ ? normalizeEntry(nested[bare])
148
+ : null
149
+ if (nestedEntry) return nestedEntry
150
+ const bareEntry = normalizeEntry(table[bare])
151
+ if (bareEntry) return bareEntry
152
+ }
153
+ return null
154
+ }
155
+
156
+ /**
157
+ * Billed micro-units for one token count at one price.
158
+ *
159
+ * Integer arithmetic with a single half-up rounding keeps a long bill free of
160
+ * the drift that accumulates when fractional currency is added in floats.
161
+ *
162
+ * @param {number} tokens - token count.
163
+ * @param {number} priceMicros - micro-currency per 1M tokens.
164
+ * @returns {number} micro-units, rounded half-up.
165
+ */
166
+ function amountMicros(tokens, priceMicros) {
167
+ const count = Math.max(0, Math.trunc(Number(tokens) || 0))
168
+ if (count === 0 || priceMicros <= 0) return 0
169
+ const numerator = BigInt(count) * BigInt(priceMicros)
170
+ const denominator = BigInt(TOKENS_PER_PRICE)
171
+ const whole = numerator / denominator
172
+ const rest = numerator % denominator
173
+ const rounded = rest * 2n >= denominator ? whole + 1n : whole
174
+ return Number(rounded)
175
+ }
176
+
177
+ /**
178
+ * Price recorded usage with an explicit per-model table.
179
+ *
180
+ * @param {object | null} usage - summed usage for one run (or subtask).
181
+ * @param {Record<string, object> | undefined} pricing - configured price table.
182
+ * @returns {{
183
+ * currency: string | null,
184
+ * totalMicros: number | null,
185
+ * total: number | null,
186
+ * mixedCurrency: boolean,
187
+ * byCurrency: Record<string, number>,
188
+ * byModel: Record<string, number>,
189
+ * byModelMicros: Record<string, number>,
190
+ * records: object[],
191
+ * unpriced: string[],
192
+ * complete: boolean,
193
+ * } | null} cost, or null when there is nothing to price.
194
+ */
195
+ export function computeCost(usage, pricing) {
196
+ if (!usage || !usage.modelCalls) return null
197
+ const table = pricing && typeof pricing === 'object' ? pricing : {}
198
+ const byModel = {}
199
+ const byModelMicros = {}
200
+ const byCurrency = {}
201
+ const records = []
202
+ const unpriced = []
203
+
204
+ for (const [model, entry] of Object.entries(usage.models ?? {})) {
205
+ const record = {
206
+ model,
207
+ calls: entry.calls ?? 0,
208
+ inputTokens: entry.inputTokens ?? 0,
209
+ outputTokens: entry.outputTokens ?? 0,
210
+ cacheReadTokens: entry.cacheReadTokens ?? 0,
211
+ inputPrice: null,
212
+ outputPrice: null,
213
+ cachePrice: null,
214
+ amountMicros: null,
215
+ }
216
+ const price = priceFor(table, model)
217
+ if (!price) {
218
+ // Named, not zero: a caller can see exactly which route has no price.
219
+ unpriced.push(model)
220
+ records.push(record)
221
+ continue
222
+ }
223
+ record.inputPrice = price.input
224
+ record.outputPrice = price.output
225
+ record.cachePrice = price.cacheRead
226
+ const amount = amountMicros(record.inputTokens, price.inputMicros)
227
+ + amountMicros(record.cacheReadTokens, price.cacheMicros)
228
+ + amountMicros(record.outputTokens, price.outputMicros)
229
+ record.amountMicros = amount
230
+ byModelMicros[model] = amount
231
+ byModel[model] = amount / MICRO
232
+ addCurrencyMicros(byCurrency, price.currency, amount)
233
+ records.push(record)
234
+ }
235
+
236
+ const totals = currencyTotals(byCurrency)
237
+ return {
238
+ currency: totals.currency,
239
+ totalMicros: totals.totalMicros,
240
+ total: totals.total,
241
+ mixedCurrency: totals.mixedCurrency,
242
+ byCurrency,
243
+ byModel,
244
+ byModelMicros,
245
+ records,
246
+ unpriced,
247
+ // "Complete" means every recorded model has a price. A usage record with no
248
+ // model attribution at all also cannot be called complete.
249
+ complete: unpriced.length === 0 && records.length > 0,
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Price a run and each of its subtasks.
255
+ *
256
+ * Subtask costs cover only the worker children; planner and aggregator calls
257
+ * are part of the run total but belong to no subtask. A subtask without a
258
+ * readable usage log keeps `cost: null` rather than a fabricated zero.
259
+ *
260
+ * @param {object} run - run record with `usage`, `subtasks`.
261
+ * @param {object | undefined} pricing - configured price table.
262
+ * @returns {object | null} the run cost.
263
+ */
264
+ export function applyCost(run, pricing) {
265
+ if (!run || typeof run !== 'object') return null
266
+ run.cost = computeCost(run.usage, pricing)
267
+ for (const subtask of run.subtasks ?? []) {
268
+ subtask.cost = computeCost(subtask?.usage, pricing)
269
+ }
270
+ return run.cost
271
+ }
272
+
273
+ /**
274
+ * Integer micro-units for a cost object, accepting a legacy `total` number.
275
+ * @param {{ totalMicros?: number, total?: number } | number} cost - cost record.
276
+ * @returns {number} micro-units, or NaN.
277
+ */
278
+ function microsOf(cost) {
279
+ if (typeof cost === 'number') {
280
+ return Number.isFinite(cost) ? Math.round(cost * MICRO) : Number.NaN
281
+ }
282
+ if (cost && Number.isFinite(cost.totalMicros)) return Math.trunc(cost.totalMicros)
283
+ if (cost && Number.isFinite(cost.total)) return Math.round(cost.total * MICRO)
284
+ return Number.NaN
285
+ }
286
+
287
+ /**
288
+ * Render integer micro-units with one rounding, half-up, at the shown precision.
289
+ *
290
+ * Four decimals below one currency unit, two above it; a positive amount
291
+ * smaller than the smallest shown value is marked as such instead of printed
292
+ * as zero.
293
+ *
294
+ * @param {number} micros - integer micro-units.
295
+ * @param {string} [currency] - ISO currency code.
296
+ * @returns {string} e.g. `¥0.1016`, `$1.24`, `<¥0.0001`, `—`.
297
+ */
298
+ export function moneyOfMicros(micros, currency = 'USD') {
299
+ const symbol = currencySymbol(currency)
300
+ if (!Number.isFinite(micros)) return '—'
301
+ if (micros === 0) return `${symbol}0`
302
+ const value = Math.abs(micros)
303
+ if (value < SMALLEST_SHOWN_MICROS) return `<${symbol}0.0001`
304
+ const digits = value < MICRO ? 4 : 2
305
+ const step = 10 ** (6 - digits)
306
+ const rounded = Math.floor((value + step / 2) / step) * step
307
+ const whole = Math.floor(rounded / MICRO)
308
+ const fraction = String(rounded % MICRO).padStart(6, '0').slice(0, digits)
309
+ return `${micros < 0 ? '-' : ''}${symbol}${whole}.${fraction}`
310
+ }
311
+
312
+ /**
313
+ * Format a cost record (or a bare amount) for display.
314
+ *
315
+ * A cost that holds more than one currency is shown as one amount per
316
+ * currency; it is never collapsed into a single cross-currency number.
317
+ *
318
+ * @param {{ totalMicros?: number, total?: number, currency?: string, byCurrency?: Record<string, number> } | number | null} cost - cost.
319
+ * @param {string} [currency] - fallback currency code.
320
+ * @returns {string} formatted money, or `—` when unknown.
321
+ */
322
+ export function formatMoney(cost, currency) {
323
+ const tally = cost && typeof cost === 'object' ? cost.byCurrency : null
324
+ if (tally && typeof tally === 'object' && Object.keys(tally).length > 1) return formatCurrencyTally(tally)
325
+ const code = (cost && typeof cost === 'object' && cost.currency) || currency || 'USD'
326
+ return moneyOfMicros(microsOf(cost), code)
327
+ }