Line data Source code
1 : import type {
2 : ComfyNodeDef,
3 : PriceBadge,
4 : WidgetDependency
5 : } from '@comfyorg/object-info-parser'
6 : import { memoize } from 'es-toolkit'
7 : import type { Expression } from 'jsonata'
8 : import jsonata from 'jsonata'
9 :
10 : import { CREDITS_PER_USD, formatCredits } from './creditsUtil'
11 :
12 : /**
13 : * Determine if a number should display 1 decimal place.
14 : * Shows decimal only when the first decimal digit is non-zero.
15 : */
16 2356 : const shouldShowDecimal = (value: number): boolean => {
17 : const rounded = Math.round(value * 10) / 10
18 34 : return rounded % 1 !== 0
19 : }
20 :
21 2356 : const getNumberOptions = (credits: number): Intl.NumberFormatOptions => ({
22 : minimumFractionDigits: 0,
23 : maximumFractionDigits: shouldShowDecimal(credits) ? 1 : 0
24 : })
25 :
26 : type CreditFormatOptions = {
27 : suffix?: string
28 : note?: string
29 : approximate?: boolean
30 : separator?: string
31 : }
32 :
33 2356 : export const formatCreditsValue = (usd: number): string => {
34 : // Use raw credits value (before rounding) to determine decimal display
35 34 : const rawCredits = usd * CREDITS_PER_USD
36 34 : return formatCredits({
37 : value: rawCredits,
38 : numberOptions: getNumberOptions(rawCredits)
39 : })
40 : }
41 :
42 2356 : const makePrefix = (approximate?: boolean) => (approximate ? '~' : '')
43 :
44 2356 : const makeSuffix = (suffix?: string) => suffix ?? '/Run'
45 :
46 2356 : const appendNote = (note?: string) => (note ? ` ${note}` : '')
47 :
48 2356 : const formatCreditsLabel = (
49 : usd: number,
50 : { suffix, note, approximate }: CreditFormatOptions = {}
51 : ): string =>
52 : `${makePrefix(approximate)}${formatCreditsValue(usd)} credits${makeSuffix(suffix)}${appendNote(note)}`
53 :
54 2356 : export const formatCreditsRangeValue = (
55 : minUsd: number,
56 : maxUsd: number
57 : ): string => {
58 3 : const min = formatCreditsValue(minUsd)
59 3 : const max = formatCreditsValue(maxUsd)
60 3 : return min === max ? min : `${min}-${max}`
61 : }
62 :
63 2356 : const formatCreditsRangeLabel = (
64 : minUsd: number,
65 : maxUsd: number,
66 : { suffix, note, approximate }: CreditFormatOptions = {}
67 : ): string => {
68 3 : const rangeValue = formatCreditsRangeValue(minUsd, maxUsd)
69 3 : return `${makePrefix(approximate)}${rangeValue} credits${makeSuffix(suffix)}${appendNote(note)}`
70 : }
71 :
72 2356 : export const formatCreditsListValue = (
73 : usdValues: number[],
74 : separator = '/'
75 : ): string => {
76 : const parts = usdValues.map((value) => formatCreditsValue(value))
77 1 : return parts.join(separator)
78 : }
79 :
80 2356 : const formatCreditsListLabel = (
81 : usdValues: number[],
82 : { suffix, note, approximate, separator }: CreditFormatOptions = {}
83 : ): string => {
84 1 : const value = formatCreditsListValue(usdValues, separator)
85 1 : return `${makePrefix(approximate)}${value} credits${makeSuffix(suffix)}${appendNote(note)}`
86 : }
87 :
88 : // -----------------------------
89 : // JSONata pricing types
90 : // -----------------------------
91 : type PricingResult =
92 : | { type: 'text'; text: string }
93 : | { type: 'usd'; usd: number; format?: CreditFormatOptions }
94 : | {
95 : type: 'range_usd'
96 : min_usd: number
97 : max_usd: number
98 : format?: CreditFormatOptions
99 : }
100 : | { type: 'list_usd'; usd: number[]; format?: CreditFormatOptions }
101 :
102 : /** Type guard to validate that a value is a PricingResult. */
103 2356 : const isPricingResult = (value: unknown): value is PricingResult => {
104 32 : if (typeof value !== 'object' || value === null || !('type' in value)) {
105 0 : return false
106 : }
107 :
108 32 : switch (value.type) {
109 : case 'text':
110 2 : return 'text' in value && typeof value.text === 'string'
111 : case 'usd':
112 26 : return 'usd' in value && typeof value.usd === 'number'
113 : case 'range_usd':
114 3 : return (
115 : 'min_usd' in value &&
116 : typeof value.min_usd === 'number' &&
117 : 'max_usd' in value &&
118 : typeof value.max_usd === 'number'
119 : )
120 : case 'list_usd':
121 1 : return (
122 : 'usd' in value &&
123 : Array.isArray(value.usd) &&
124 : value.usd.every((usd) => typeof usd === 'number')
125 : )
126 : default:
127 0 : return false
128 : }
129 : }
130 :
131 : /**
132 : * Widget values are normalized based on their declared type:
133 : * - INT/FLOAT → number (or null if not parseable)
134 : * - BOOLEAN → boolean (or null if not parseable)
135 : * - STRING/COMBO/other → string (lowercased, trimmed)
136 : */
137 : export type NormalizedWidgetValue = string | number | boolean | null
138 :
139 : export type JsonataPricingRule = {
140 : engine: 'jsonata'
141 : depends_on: {
142 : widgets: WidgetDependency[]
143 : inputs: string[]
144 : input_groups: string[]
145 : }
146 : expr: string
147 : }
148 :
149 : export type CompiledJsonataPricingRule = JsonataPricingRule & {
150 : _compiled: Expression | null
151 : }
152 :
153 : export type JsonataEvalContext = {
154 : widgets: Record<string, NormalizedWidgetValue>
155 : inputs: Record<string, { connected: boolean }>
156 : /** Count of connected inputs per autogrow group */
157 : inputGroups: Record<string, number>
158 : }
159 :
160 : // -----------------------------
161 : // Normalization helpers
162 : // -----------------------------
163 2356 : const asFiniteNumber = (v: unknown): number | null => {
164 144 : if (v === null || v === undefined) return null
165 :
166 144 : if (typeof v === 'number') return Number.isFinite(v) ? v : null
167 :
168 0 : if (typeof v === 'string') {
169 0 : const t = v.trim()
170 0 : if (t === '') return null
171 0 : const n = Number(t)
172 0 : return Number.isFinite(n) ? n : null
173 : }
174 :
175 : // Do not coerce booleans/objects into numbers for pricing purposes.
176 0 : return null
177 : }
178 :
179 : /**
180 : * Normalize widget value based on its declared type.
181 : * Returns the value in its natural type for simpler JSONata expressions.
182 : */
183 2356 : export const normalizeWidgetValue = (
184 : raw: unknown,
185 : declaredType: string
186 : ): NormalizedWidgetValue => {
187 180 : if (raw === undefined || raw === null) {
188 0 : return null
189 : }
190 :
191 180 : const upperType = declaredType.toUpperCase()
192 :
193 : // Numeric types
194 180 : if (upperType === 'INT' || upperType === 'FLOAT') {
195 110 : return asFiniteNumber(raw)
196 : }
197 :
198 : // Boolean type
199 180 : if (upperType === 'BOOLEAN') {
200 0 : if (typeof raw === 'boolean') return raw
201 0 : if (typeof raw === 'string') {
202 0 : const ls = raw.trim().toLowerCase()
203 0 : if (ls === 'true') return true
204 0 : if (ls === 'false') return false
205 : }
206 0 : return null
207 : }
208 :
209 : // COMBO type - preserve string/numeric values (for options like [5, "10"])
210 180 : if (upperType === 'COMBO') {
211 15 : if (typeof raw === 'number') return raw
212 9 : if (typeof raw === 'boolean') return raw
213 9 : return String(raw).trim().toLowerCase()
214 : }
215 :
216 : // String/other types - return as lowercase trimmed string
217 55 : return String(raw).trim().toLowerCase()
218 : }
219 :
220 : type FormatPricingResultOptions = {
221 : /** If true, return only the value without "credits/Run" suffix */
222 : valueOnly?: boolean
223 : defaults?: CreditFormatOptions
224 : }
225 :
226 : /**
227 : * Format a PricingResult into a display string.
228 : * @param result - The pricing result from JSONata evaluation
229 : * @param options - Formatting options
230 : * @returns Formatted string, e.g. "10 credits/Run" or "10" if valueOnly
231 : */
232 2356 : export const formatPricingResult = (
233 : result: unknown,
234 : options: FormatPricingResultOptions = {}
235 : ): string => {
236 32 : const { valueOnly = false, defaults = {} } = options
237 :
238 : // Handle legacy format: { usd: number } without type field
239 32 : if (
240 : result &&
241 : typeof result === 'object' &&
242 : !('type' in result) &&
243 : 'usd' in result
244 : ) {
245 0 : const usd = asFiniteNumber(result.usd)
246 0 : if (usd === null) return ''
247 0 : if (valueOnly) return formatCreditsValue(usd)
248 0 : return formatCreditsLabel(usd, defaults)
249 : }
250 :
251 32 : if (!isPricingResult(result)) {
252 0 : if (result !== undefined && result !== null) {
253 0 : console.warn('[pricing/jsonata] invalid result format:', result)
254 : }
255 0 : return ''
256 : }
257 :
258 32 : if (result.type === 'text') {
259 2 : return result.text
260 : }
261 :
262 30 : if (result.type === 'usd') {
263 26 : const usd = asFiniteNumber(result.usd)
264 26 : if (usd === null) return ''
265 26 : const fmt = { ...defaults, ...result.format }
266 26 : if (valueOnly) {
267 : const prefix = fmt.approximate ? '~' : ''
268 0 : return `${prefix}${formatCreditsValue(usd)}`
269 : }
270 26 : return formatCreditsLabel(usd, fmt)
271 : }
272 :
273 4 : if (result.type === 'range_usd') {
274 3 : const minUsd = asFiniteNumber(result.min_usd)
275 3 : const maxUsd = asFiniteNumber(result.max_usd)
276 3 : if (minUsd === null || maxUsd === null) return ''
277 3 : const fmt = { ...defaults, ...result.format }
278 3 : if (valueOnly) {
279 : const prefix = fmt.approximate ? '~' : ''
280 0 : return `${prefix}${formatCreditsRangeValue(minUsd, maxUsd)}`
281 : }
282 3 : return formatCreditsRangeLabel(minUsd, maxUsd, fmt)
283 : }
284 :
285 : {
286 1 : const usdValues = result.usd
287 : .map(asFiniteNumber)
288 : .filter((x): x is number => x != null)
289 :
290 1 : if (usdValues.length === 0) return ''
291 :
292 1 : const fmt = { ...defaults, ...result.format }
293 1 : if (valueOnly) {
294 : const prefix = fmt.approximate ? '~' : ''
295 0 : return `${prefix}${formatCreditsListValue(usdValues, fmt.separator)}`
296 : }
297 1 : return formatCreditsListLabel(usdValues, fmt)
298 : }
299 : }
300 :
301 : // -----------------------------
302 : // Compile rules (non-fatal)
303 : // -----------------------------
304 2356 : const compileRule = (rule: JsonataPricingRule): CompiledJsonataPricingRule => {
305 24 : try {
306 24 : return { ...rule, _compiled: jsonata(rule.expr) }
307 : } catch (e) {
308 : // Do not crash app on bad expressions; just disable rule.
309 0 : console.error('[pricing/jsonata] failed to compile expr:', rule.expr, e)
310 0 : return { ...rule, _compiled: null }
311 : }
312 : }
313 :
314 : // -----------------------------
315 : // Rule cache (per-node-type)
316 : // -----------------------------
317 2356 : const compiledRulesCache = new Map<
318 : string,
319 : { signature: string; rule: CompiledJsonataPricingRule }
320 : >()
321 :
322 : /**
323 : * Convert a PriceBadge from node definition to a JsonataPricingRule.
324 : */
325 2356 : const priceBadgeToRule = (priceBadge: PriceBadge): JsonataPricingRule => ({
326 : engine: priceBadge.engine,
327 : depends_on: priceBadge.depends_on,
328 : expr: priceBadge.expr
329 : })
330 :
331 : /**
332 : * Get or compile a pricing rule for a node type.
333 : */
334 2356 : export const getCompiledRuleForNodeType = (
335 : nodeName: string,
336 : priceBadge: PriceBadge | undefined
337 : ): CompiledJsonataPricingRule | null => {
338 98 : if (!priceBadge) return null
339 :
340 98 : const rule = priceBadgeToRule(priceBadge)
341 98 : const signature = JSON.stringify(rule)
342 98 : const cached = compiledRulesCache.get(nodeName)
343 98 : if (cached?.signature === signature) return cached.rule
344 :
345 24 : const compiled = compileRule(rule)
346 24 : compiledRulesCache.set(nodeName, { signature, rule: compiled })
347 24 : return compiled
348 : }
349 :
350 : export async function evaluatePricingContext(
351 : name: string,
352 : badge: PriceBadge,
353 : context: JsonataEvalContext,
354 : options: FormatPricingResultOptions = {}
355 : ): Promise<string> {
356 : const rule = getCompiledRuleForNodeType(name, badge)
357 : if (!rule?._compiled) return ''
358 : try {
359 : const result: unknown = await rule._compiled.evaluate(context)
360 : return formatPricingResult(result, options)
361 : } catch {
362 : return ''
363 : }
364 : }
365 :
366 : /**
367 : * Extract default value from an input spec.
368 : */
369 0 : function extractDefaultFromSpec(spec: unknown[]): unknown {
370 0 : const specOptions = spec[1]
371 :
372 : // Check for explicit default
373 0 : if (
374 : typeof specOptions === 'object' &&
375 : specOptions &&
376 : 'default' in specOptions
377 : ) {
378 0 : return specOptions.default
379 : }
380 : // COMBO/DYNAMICCOMBO type with options array
381 0 : if (
382 : typeof specOptions === 'object' &&
383 : specOptions &&
384 : 'options' in specOptions &&
385 : Array.isArray(specOptions.options) &&
386 : specOptions.options.length > 0
387 : ) {
388 0 : const firstOption = specOptions.options[0]
389 : // Dynamic combo: options are objects with 'key' property
390 0 : if (
391 : typeof firstOption === 'object' &&
392 : firstOption !== null &&
393 : 'key' in firstOption
394 : ) {
395 0 : return firstOption.key
396 : }
397 : // Standard combo: options are primitive values
398 0 : return firstOption
399 : }
400 : // COMBO type (old format): [["option1", "option2"], {...}]
401 0 : if (Array.isArray(spec[0]) && spec[0].length > 0) {
402 0 : return spec[0][0]
403 : }
404 0 : return null
405 : }
406 :
407 : /**
408 : * Evaluate pricing for a node definition using default widget values.
409 : * Used for NodePricingBadge where no LGraphNode instance exists.
410 : * Results are memoized by the pricing rule and input definitions.
411 : */
412 2356 : export const evaluateNodeDefPricing = memoize(
413 : async (nodeDef: ComfyNodeDef): Promise<string> => {
414 0 : const priceBadge = nodeDef.price_badge
415 0 : if (!priceBadge?.expr) return ''
416 :
417 : // Reuse compiled expression cache
418 0 : const rule = getCompiledRuleForNodeType(nodeDef.name, priceBadge)
419 0 : if (!rule?._compiled) return ''
420 :
421 0 : try {
422 : // Merge all inputs for lookup
423 0 : const allInputs = {
424 : ...nodeDef.input?.required,
425 : ...nodeDef.input?.optional
426 : }
427 :
428 : // Build widgets context using depends_on.widgets (matches buildJsonataContext)
429 0 : const widgets: Record<string, NormalizedWidgetValue> = {}
430 0 : for (const dep of priceBadge.depends_on.widgets) {
431 0 : const spec = allInputs[dep.name]
432 0 : let rawValue: unknown = null
433 0 : if (Array.isArray(spec)) {
434 0 : rawValue = extractDefaultFromSpec(spec)
435 : }
436 0 : widgets[dep.name] = normalizeWidgetValue(rawValue, dep.type)
437 : }
438 0 : if (Object.values(widgets).some((value) => value === null)) return ''
439 :
440 : // Build inputs context: assume all inputs are disconnected in preview
441 0 : const inputs: Record<string, { connected: boolean }> = {}
442 0 : for (const name of priceBadge.depends_on.inputs) {
443 0 : inputs[name] = { connected: false }
444 : }
445 :
446 : // Build inputGroups context: assume 0 connected inputs in preview
447 0 : const inputGroups: Record<string, number> = {}
448 0 : for (const groupName of priceBadge.depends_on.input_groups) {
449 0 : inputGroups[groupName] = 0
450 : }
451 :
452 0 : const context: JsonataEvalContext = { widgets, inputs, inputGroups }
453 : const result = await rule._compiled.evaluate(context)
454 0 : return formatPricingResult(result, { valueOnly: true })
455 : } catch (e) {
456 0 : console.error('[evaluateNodeDefPricing] error:', e)
457 0 : return ''
458 : }
459 : },
460 : {
461 : getCacheKey: (nodeDef: ComfyNodeDef) =>
462 : JSON.stringify([nodeDef.name, nodeDef.price_badge, nodeDef.input])
463 : }
464 : )
465 :
466 : const PER_RUN_SUFFIX = '/Run'
467 :
468 : /**
469 : * What one evaluated price result contributes to a per-run total: `per-run` is
470 : * summable, `per-unit` carries its unit, `unpriced` contributes nothing.
471 : */
472 : export type NodeRunPrice =
473 : | {
474 : basis: 'per-run'
475 : minUsd: number
476 : maxUsd: number
477 : approximate: boolean
478 : }
479 : | {
480 : basis: 'per-unit'
481 : unit: string
482 : minUsd: number
483 : maxUsd: number
484 : approximate: boolean
485 : }
486 : | {
487 : basis: 'unpriced'
488 : reason: 'descriptive' | 'ambiguous' | 'invalid'
489 : }
490 :
491 : const INVALID_PRICE: NodeRunPrice = { basis: 'unpriced', reason: 'invalid' }
492 : const AMBIGUOUS_PRICE: NodeRunPrice = { basis: 'unpriced', reason: 'ambiguous' }
493 :
494 : function declaredUnit(suffix: string | undefined): string {
495 : return (suffix ?? PER_RUN_SUFFIX).trim().replace(/^\//, '')
496 : }
497 :
498 : function isUsableBound(usd: number | null): usd is number {
499 : return usd !== null && usd >= 0
500 : }
501 :
502 : function numericBasis(
503 : minUsd: number,
504 : maxUsd: number,
505 : format: CreditFormatOptions | undefined
506 : ): NodeRunPrice {
507 : const suffix = format?.suffix
508 : if (suffix !== undefined && typeof suffix !== 'string') return INVALID_PRICE
509 : const unit = declaredUnit(suffix)
510 : if (unit === '') return AMBIGUOUS_PRICE
511 :
512 : const approximate = !!format?.approximate
513 : if (unit.toLowerCase() === 'run') {
514 : return format?.note === undefined
515 : ? { basis: 'per-run', minUsd, maxUsd, approximate }
516 : : AMBIGUOUS_PRICE
517 : }
518 : return { basis: 'per-unit', unit, minUsd, maxUsd, approximate }
519 : }
520 :
521 : function classifyScalar(
522 : usd: unknown,
523 : format: CreditFormatOptions | undefined
524 : ): NodeRunPrice {
525 : const value = asFiniteNumber(usd)
526 : if (!isUsableBound(value)) return INVALID_PRICE
527 : return numericBasis(value, value, format)
528 : }
529 :
530 : function classifyRange(
531 : result: Extract<PricingResult, { type: 'range_usd' }>
532 : ): NodeRunPrice {
533 : const minUsd = asFiniteNumber(result.min_usd)
534 : const maxUsd = asFiniteNumber(result.max_usd)
535 : if (!isUsableBound(minUsd) || !isUsableBound(maxUsd)) return INVALID_PRICE
536 : return numericBasis(
537 : Math.min(minUsd, maxUsd),
538 : Math.max(minUsd, maxUsd),
539 : result.format
540 : )
541 : }
542 :
543 : function classifyList(
544 : result: Extract<PricingResult, { type: 'list_usd' }>
545 : ): NodeRunPrice {
546 : if (result.usd.length === 0) return INVALID_PRICE
547 : let minUsd = Number.POSITIVE_INFINITY
548 : let maxUsd = Number.NEGATIVE_INFINITY
549 : for (const entry of result.usd) {
550 : const usd = asFiniteNumber(entry)
551 : if (!isUsableBound(usd)) return INVALID_PRICE
552 : minUsd = Math.min(minUsd, usd)
553 : maxUsd = Math.max(maxUsd, usd)
554 : }
555 : const basis = numericBasis(minUsd, maxUsd, result.format)
556 : if (basis.basis === 'per-run' && result.usd.length > 1) {
557 : return AMBIGUOUS_PRICE
558 : }
559 : return basis
560 : }
561 :
562 : function isLegacyUsdResult(result: unknown): result is { usd: unknown } {
563 : return (
564 : !!result &&
565 : typeof result === 'object' &&
566 : !('type' in result) &&
567 : 'usd' in result
568 : )
569 : }
570 :
571 : /** Read an evaluated pricing result as a per-run cost basis, failing closed. */
572 : export function classifyPricingResult(result: unknown): NodeRunPrice {
573 : if (isLegacyUsdResult(result)) return classifyScalar(result.usd, undefined)
574 : if (!isPricingResult(result)) return INVALID_PRICE
575 :
576 : switch (result.type) {
577 : case 'text':
578 : return { basis: 'unpriced', reason: 'descriptive' }
579 : case 'usd':
580 : return classifyScalar(result.usd, result.format)
581 : case 'range_usd':
582 : return classifyRange(result)
583 : default:
584 : return classifyList(result)
585 : }
586 : }
587 :
588 : /** One cost-bearing node, already evaluated against its current state. */
589 : export type ApiNodeCostEntry = {
590 : nodeType: string
591 : nodeId?: string | number
592 : price: NodeRunPrice
593 : }
594 :
595 : /**
596 : * API-node per-run cost bounds in USD and unrounded credits, excluding cloud
597 : * GPU/execution cost; presentable only as a floor while `isLowerBound` holds.
598 : */
599 : export type ApiNodeCostEstimate = {
600 : minUsd: number
601 : maxUsd: number
602 : minCredits: number
603 : maxCredits: number
604 : pricedCount: number
605 : perUnit: ApiNodeCostEntry[]
606 : unpriced: ApiNodeCostEntry[]
607 : coverage: 'complete' | 'partial' | 'none'
608 : isLowerBound: boolean
609 : approximate: boolean
610 : }
611 :
612 : function isSummableEntry(entry: ApiNodeCostEntry): boolean {
613 : return (
614 : entry.price.basis === 'per-run' &&
615 : Number.isFinite(entry.price.minUsd) &&
616 : Number.isFinite(entry.price.maxUsd) &&
617 : entry.price.minUsd >= 0 &&
618 : entry.price.minUsd <= entry.price.maxUsd
619 : )
620 : }
621 :
622 : /** Sum the per-run entries and return what was excluded from the bounds. */
623 : export function estimateApiNodeRunCost(
624 : entries: readonly ApiNodeCostEntry[]
625 : ): ApiNodeCostEstimate {
626 : let minUsd = 0
627 : let maxUsd = 0
628 : let pricedCount = 0
629 : let approximate = false
630 : const perUnit: ApiNodeCostEntry[] = []
631 : const unpriced: ApiNodeCostEntry[] = []
632 :
633 : for (const entry of entries) {
634 : if (isSummableEntry(entry) && entry.price.basis === 'per-run') {
635 : minUsd += entry.price.minUsd
636 : maxUsd += entry.price.maxUsd
637 : pricedCount++
638 : approximate = approximate || entry.price.approximate
639 : } else if (entry.price.basis === 'per-unit') {
640 : perUnit.push(entry)
641 : } else {
642 : unpriced.push(entry)
643 : }
644 : }
645 :
646 : const hasFiniteTotals =
647 : Number.isFinite(minUsd) &&
648 : Number.isFinite(maxUsd) &&
649 : Number.isFinite(minUsd * CREDITS_PER_USD) &&
650 : Number.isFinite(maxUsd * CREDITS_PER_USD)
651 : if (!hasFiniteTotals) {
652 : unpriced.push(...entries.filter(isSummableEntry))
653 : minUsd = 0
654 : maxUsd = 0
655 : pricedCount = 0
656 : }
657 :
658 : const excluded = perUnit.length + unpriced.length
659 : const coverage: ApiNodeCostEstimate['coverage'] =
660 : excluded === 0 ? 'complete' : pricedCount === 0 ? 'none' : 'partial'
661 :
662 : return {
663 : minUsd,
664 : maxUsd,
665 : minCredits: minUsd * CREDITS_PER_USD,
666 : maxCredits: maxUsd * CREDITS_PER_USD,
667 : pricedCount,
668 : perUnit,
669 : unpriced,
670 : coverage,
671 : isLowerBound: excluded > 0,
672 : approximate
673 : }
674 : }
675 :
676 : /**
677 : * Evaluate one node's badge and report its per-run basis; an absent or
678 : * uncompilable badge is `unpriced`, never free.
679 : */
680 : export async function evaluatePricingBasis(
681 : name: string,
682 : badge: PriceBadge | undefined,
683 : context: JsonataEvalContext
684 : ): Promise<NodeRunPrice> {
685 : const rule = badge ? getCompiledRuleForNodeType(name, badge) : null
686 : if (!rule?._compiled) return INVALID_PRICE
687 : try {
688 : return classifyPricingResult(await rule._compiled.evaluate(context))
689 : } catch {
690 : return INVALID_PRICE
691 : }
692 : }
|