@zonastery/bursar 2.0.4 → 2.0.5
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 +1 -1
- package/dist/billing/auto-recharge-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-service.d.ts.map +1 -1
- package/dist/billing/billing-store.d.ts.map +1 -1
- package/dist/billing/event-handlers.d.ts.map +1 -1
- package/dist/billing/event-handlers.js.map +1 -1
- package/dist/billing/event-processor.d.ts.map +1 -1
- package/dist/billing/event-processor.js.map +1 -1
- package/dist/billing/financial-event-handlers.d.ts.map +1 -1
- package/dist/billing/financial-event-handlers.js.map +1 -1
- package/dist/billing/management.d.ts.map +1 -1
- package/dist/billing/management.js.map +1 -1
- package/dist/billing/policy-window.js.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
- package/dist/billing/postgres/repositories/customer.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/customer.js.map +1 -1
- package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/dispute.js.map +1 -1
- package/dist/billing/postgres/repositories/event.d.ts +2 -2
- package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/event.js.map +1 -1
- package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/invoice.js.map +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/offer.js.map +1 -1
- package/dist/billing/postgres/repositories/payment.d.ts +3 -3
- package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/payment.js.map +1 -1
- package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/preferences.js.map +1 -1
- package/dist/billing/postgres/repositories/refund.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/refund.js.map +1 -1
- package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
- package/dist/billing/postgres/repositories/subscription.d.ts +5 -5
- package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/subscription.js.map +1 -1
- package/dist/billing/postgres/repositories/topup.d.ts +1 -1
- package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/topup.js.map +1 -1
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/types/auto-recharge.d.ts.map +1 -1
- package/dist/billing/types/events.d.ts.map +1 -1
- package/dist/billing/types/subscriptions.d.ts.map +1 -1
- package/dist/bursar.d.ts.map +1 -1
- package/dist/bursar.js.map +1 -1
- package/dist/commerce/errors.d.ts.map +1 -1
- package/dist/commerce/errors.js.map +1 -1
- package/dist/commerce/provider-registry.d.ts.map +1 -1
- package/dist/commerce/provider-registry.js.map +1 -1
- package/dist/commerce/service.d.ts +1 -1
- package/dist/commerce/service.d.ts.map +1 -1
- package/dist/commerce/service.js.map +1 -1
- package/dist/config/parse-access.js.map +1 -1
- package/dist/config/parse-pricing.js.map +1 -1
- package/dist/config/parse-utils.js.map +1 -1
- package/dist/credits/catalog-runtime.d.ts.map +1 -1
- package/dist/credits/catalog-runtime.js.map +1 -1
- package/dist/credits/events.d.ts.map +1 -1
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.d.ts.map +1 -1
- package/dist/credits/low-balance-monitor.js.map +1 -1
- package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/analytics.js.map +1 -1
- package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/balance.js.map +1 -1
- package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/bucket.js.map +1 -1
- package/dist/credits/postgres/repositories/catalog.d.ts +1 -1
- package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/catalog.js.map +1 -1
- package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/deduction.js.map +1 -1
- package/dist/credits/postgres/repositories/lease.d.ts +2 -2
- package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/lease.js.map +1 -1
- package/dist/credits/postgres/repositories/plan.d.ts +10 -10
- package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/plan.js.map +1 -1
- package/dist/credits/postgres/repositories/team.d.ts +2 -2
- package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/team.js.map +1 -1
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/queries.d.ts.map +1 -1
- package/dist/credits/queries.js.map +1 -1
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/expr/evaluator.js.map +1 -1
- package/dist/expr/parser.d.ts.map +1 -1
- package/dist/expr/parser.js.map +1 -1
- package/dist/generated/pricing-config.schema.json +0 -12
- package/dist/generated/pricing-config.types.d.ts +2 -8
- package/dist/generated/pricing-config.types.d.ts.map +1 -1
- package/dist/generated/pricing-config.types.js.map +1 -1
- package/dist/providers/dodo/better-auth-core.d.ts +0 -2
- package/dist/providers/dodo/better-auth-core.d.ts.map +1 -1
- package/dist/providers/dodo/better-auth.d.ts +0 -2
- package/dist/providers/dodo/better-auth.d.ts.map +1 -1
- package/dist/providers/dodo/client-contract.d.ts +2 -1
- package/dist/providers/dodo/client-contract.d.ts.map +1 -1
- package/dist/providers/dodo/client-contract.js.map +1 -1
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/environment.d.ts.map +1 -1
- package/dist/providers/mock/provider.d.ts.map +1 -1
- package/dist/providers/stripe/event-mapper.js.map +1 -1
- package/dist/providers/stripe/provider.d.ts.map +1 -1
- package/dist/providers/stripe/provider.js +1 -1
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/retry.js.map +1 -1
- package/dist/shared/idempotency.js.map +1 -1
- package/dist/shared/logger.d.ts.map +1 -1
- package/dist/shared/logger.js +28 -4
- package/dist/shared/logger.js.map +1 -1
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js.map +1 -1
- package/dist/shared/postgres-errors.js.map +1 -1
- package/dist/shared/postgres-validation.js.map +1 -1
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
- package/dist/storage/adapters/clickhouse.js.map +1 -1
- package/dist/storage/adapters/s3.d.ts.map +1 -1
- package/dist/storage/diagnostics.d.ts.map +1 -1
- package/dist/storage/diagnostics.js.map +1 -1
- package/dist/storage/maintenance.d.ts.map +1 -1
- package/dist/storage/maintenance.js.map +1 -1
- package/dist/storage/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js.map +1 -1
- package/dist/telemetry/index.d.ts +1 -1
- package/dist/telemetry/index.d.ts.map +1 -1
- package/dist/telemetry/index.js +1 -1
- package/dist/telemetry/index.js.map +1 -1
- package/dist/telemetry/opentelemetry.d.ts.map +1 -1
- package/dist/telemetry/opentelemetry.js.map +1 -1
- package/package.json +30 -30
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parse-pricing.js","sourceRoot":"","sources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AAI,OAAO,CAAC,OAAO,IAAI,IAAI;YAAE,QAAQ,CAAC,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QAC1E,SAAS,CAAC,OAAO,CAAC,GAAG,QAAQ,CAAC;IAChC,CAAC;IAED,2BAA2B,CAAC,SAAS,CAAC,CAAC;IACvC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC;AACnC,CAAC;AAED,MAAM,UAAU,iBAAiB,CAC/B,OAAsB,EACtB,OAAe,EACf,SAAiB;IAEjB,MAAM,IAAI,GAAG,OAAO,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IACxC,IAAI,CAAC,IAAI;QAAE,OAAO,KAAK,CAAC;IACxB,OAAO,CACL,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,SAAS,CAAC;QAChE,CAAC,IAAI,CAAC,OAAO,IAAI,IAAI,IAAI,iBAAiB,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC,CAC9E,CAAC;AACJ,CAAC","sourcesContent":["import { validateExpression } from \"../expr.js\";\nimport { z } from \"zod\";\nimport {\n asArray,\n asBoolean,\n asDecimal,\n asObject,\n asString,\n identifier,\n semanticError,\n validateIdentifiers,\n} from \"./parse-utils.js\";\nimport type { JsonValue } from \"../shared/json.js\";\nimport type {\n Charge,\n DimensionDefinition,\n DimensionMatcher,\n GraduatedTier,\n MatcherScalar,\n OperationDefinition,\n OperationPricing,\n PricingConfig,\n RateCard,\n} from \"./types.js\";\n\nconst roundingSchema = z.enum([\"ceil\", \"floor\", \"nearest\"]);\nconst dimensionTypeSchema = z.enum([\"string\", \"number\", \"boolean\"]);\n\nfunction parseMatcherScalar(\n value: JsonValue | undefined,\n definition: DimensionDefinition,\n path: string,\n): MatcherScalar {\n if (definition.type === \"boolean\") {\n const parsed = z.boolean().safeParse(value);\n if (!parsed.success) semanticError(`${path} matcher values must be booleans`);\n return parsed.data;\n }\n if (definition.type === \"number\") {\n const parsed = z.union([z.number(), z.string()]).safeParse(value);\n if (!parsed.success) semanticError(`${path} matcher values must be decimal strings or numbers`);\n return asDecimal(parsed.data, path);\n }\n const parsed = z.string().safeParse(value);\n if (!parsed.success) semanticError(`${path} matcher values must be strings`);\n return parsed.data;\n}\n\nfunction parseMatcher(\n value: JsonValue,\n definition: DimensionDefinition,\n path: string,\n): DimensionMatcher {\n const raw = asObject(value);\n switch (raw.op) {\n case \"in\":\n case \"not_in\":\n return {\n op: raw.op,\n values: asArray(raw.values, `${path}.values`).map((item) =>\n parseMatcherScalar(item, definition, path),\n ),\n };\n case \"prefix\":\n if (definition.type !== \"string\") {\n semanticError(`${path} prefix matcher requires a string dimension`);\n }\n return { op: \"prefix\", value: asString(raw.value) };\n case \"range\": {\n if (definition.type !== \"number\") {\n semanticError(`${path} range matcher requires a number dimension`);\n }\n const parsed: Extract<DimensionMatcher, { op: \"range\" }> = { op: \"range\" };\n if (raw.gt != null) parsed.gt = asDecimal(raw.gt);\n if (raw.gte != null) parsed.gte = asDecimal(raw.gte);\n if (raw.lt != null) parsed.lt = asDecimal(raw.lt);\n if (raw.lte != null) parsed.lte = asDecimal(raw.lte);\n if (parsed.gt == null && parsed.gte == null && parsed.lt == null && parsed.lte == null) {\n semanticError(`${path} range matcher requires at least one bound`);\n }\n if (parsed.gt != null && parsed.gte != null) {\n semanticError(`${path} range matcher cannot combine gt and gte`);\n }\n if (parsed.lt != null && parsed.lte != null) {\n semanticError(`${path} range matcher cannot combine lt and lte`);\n }\n const lower = parsed.gt ?? parsed.gte;\n const upper = parsed.lt ?? parsed.lte;\n if (lower != null && upper != null && lower.gte(upper)) {\n semanticError(`${path} range matcher lower bound must be less than upper bound`);\n }\n return parsed;\n }\n default:\n return { op: \"eq\", value: parseMatcherScalar(raw.value, definition, path) };\n }\n}\n\nfunction parseTiers(value: JsonValue | undefined): GraduatedTier[] {\n const tiers = asArray(value, \"pricing.tiers\").map((item) => {\n const tier = asObject(item);\n const parsedTier: GraduatedTier = { rate: asDecimal(tier.rate) };\n if (tier.up_to != null) parsedTier.upTo = asDecimal(tier.up_to);\n return parsedTier;\n });\n if (tiers.at(-1)?.upTo != null || tiers.slice(0, -1).some((tier) => tier.upTo == null)) {\n semanticError(\"graduated and volume tiers must end with exactly one open-ended tier\");\n }\n const finite = tiers.flatMap((tier) => (tier.upTo == null ? [] : [tier.upTo]));\n if (\n finite.some((bound, index) => {\n const previous = finite[index - 1];\n return index > 0 && previous !== undefined && bound.lte(previous);\n })\n ) {\n semanticError(\"graduated and volume tier bounds must be strictly increasing\");\n }\n return tiers;\n}\n\nfunction parseCharge(value: JsonValue): Charge {\n const raw = asObject(value);\n switch (raw.type) {\n case \"flat\":\n return { type: \"flat\", amount: asDecimal(raw.amount) };\n case \"per_unit\":\n return {\n type: \"per_unit\",\n measure: asString(raw.measure),\n rate: asDecimal(raw.rate),\n unitSize: asDecimal(raw.unit_size ?? 1),\n };\n case \"package\":\n return {\n type: \"package\",\n measure: asString(raw.measure),\n units: asDecimal(raw.units),\n amount: asDecimal(raw.amount),\n rounding: roundingSchema.parse(raw.rounding ?? \"ceil\"),\n };\n case \"graduated\":\n case \"volume\":\n return {\n type: raw.type,\n measure: asString(raw.measure),\n tiers: parseTiers(raw.tiers),\n };\n case \"expression\":\n return { type: \"expression\", formula: asString(raw.formula) };\n case \"sum\":\n return {\n type: \"sum\",\n components: asArray(raw.components, \"pricing.sum.components\").map(parseCharge),\n };\n default:\n return semanticError(`unsupported charge type '${asString(raw.type)}'`);\n }\n}\n\nfunction chargeMeasures(value: Charge): Set<string> {\n if (\"measure\" in value) return new Set([value.measure]);\n if (value.type === \"sum\") {\n return new Set(value.components.flatMap((component) => [...chargeMeasures(component)]));\n }\n return new Set();\n}\n\nfunction expressionCharges(value: Charge): Extract<Charge, { type: \"expression\" }>[] {\n if (value.type === \"expression\") return [value];\n if (value.type === \"sum\") return value.components.flatMap(expressionCharges);\n return [];\n}\n\nfunction validateCharge(\n parsed: Charge,\n definition: OperationDefinition,\n operationKey: string,\n): void {\n const unknownMeasures = [...chargeMeasures(parsed)].filter((name) => !definition.measures[name]);\n if (unknownMeasures.length) {\n semanticError(\n `pricing for operation '${operationKey}' references undeclared measures ${unknownMeasures.join(\", \")}`,\n );\n }\n for (const expression of expressionCharges(parsed)) {\n validateExpression(expression.formula, new Set(Object.keys(definition.measures)));\n }\n}\n\nfunction validateRateCardInheritance(rateCards: Record<string, RateCard>): void {\n const visiting = new Set<string>();\n const visited = new Set<string>();\n const visit = (key: string): void => {\n if (visiting.has(key)) semanticError(`pricing rate-card inheritance cycle includes '${key}'`);\n if (visited.has(key)) return;\n const card = rateCards[key];\n if (!card) semanticError(`unknown rate card '${key}'`);\n visiting.add(key);\n if (card.extends) visit(card.extends);\n visiting.delete(key);\n visited.add(key);\n };\n Object.keys(rateCards).forEach(visit);\n}\n\nexport function parsePricing(value: JsonValue): PricingConfig {\n const raw = asObject(value);\n const operationsRaw = asObject(raw.operations);\n const cardsRaw = asObject(raw.rate_cards);\n validateIdentifiers(operationsRaw, \"pricing.operations\");\n validateIdentifiers(cardsRaw, \"pricing.rate_cards\");\n if (Object.keys(operationsRaw).length === 0) {\n semanticError(\"pricing.operations must not be empty\");\n }\n if (Object.keys(cardsRaw).length === 0) {\n semanticError(\"pricing.rate_cards must not be empty\");\n }\n\n const operations: Record<string, OperationDefinition> = {};\n for (const [operationKey, input] of Object.entries(operationsRaw)) {\n const operation = asObject(input);\n const measuresRaw = asObject(operation.measures);\n const dimensionsRaw = asObject(operation.dimensions ?? {});\n validateIdentifiers(measuresRaw, `pricing.operations.${operationKey}.measures`);\n validateIdentifiers(dimensionsRaw, `pricing.operations.${operationKey}.dimensions`);\n if (Object.keys(measuresRaw).length === 0) {\n semanticError(`pricing.operations.${operationKey}.measures must not be empty`);\n }\n const overlap = Object.keys(measuresRaw).filter((key) =>\n Object.prototype.hasOwnProperty.call(dimensionsRaw, key),\n );\n if (overlap.length) {\n semanticError(`operation '${operationKey}' reuses names as measures and dimensions`);\n }\n operations[operationKey] = {\n measures: Object.fromEntries(\n Object.entries(measuresRaw).map(([key, definition]) => [\n key,\n { unit: identifier(asString(asObject(definition).unit), `${operationKey}.${key}.unit`) },\n ]),\n ),\n dimensions: Object.fromEntries(\n Object.entries(dimensionsRaw).map(([key, definition]) => {\n const item = asObject(definition);\n return [\n key,\n {\n type: dimensionTypeSchema.parse(item.type),\n required: asBoolean(item.required ?? true),\n },\n ];\n }),\n ),\n };\n }\n\n const rateCards: Record<string, RateCard> = {};\n for (const [cardKey, input] of Object.entries(cardsRaw)) {\n const rawCard = asObject(input);\n const operationPricesRaw = asObject(rawCard.operations ?? {});\n const operationPrices: Record<string, OperationPricing> = {};\n for (const [operationKey, operationInput] of Object.entries(operationPricesRaw)) {\n const definition = operations[operationKey];\n if (!definition) {\n semanticError(`rate card '${cardKey}' references unknown operation '${operationKey}'`);\n }\n const operationPriceRaw = asObject(operationInput);\n const rules = asArray(operationPriceRaw.rules ?? [], \"pricing.rules\").map(\n (ruleInput, index) => {\n const ruleRaw = asObject(ruleInput);\n const whenRaw = asObject(ruleRaw.when);\n const unknownDimensions = Object.keys(whenRaw).filter(\n (name) => !definition.dimensions[name],\n );\n if (unknownDimensions.length) {\n semanticError(\n `pricing.rate_cards.${cardKey}.operations.${operationKey}.rules[${index}] matches undeclared dimensions ${unknownDimensions.join(\", \")}`,\n );\n }\n const parsedCharge = parseCharge(\n asObject(\n ruleRaw.charge,\n `pricing.rate_cards.${cardKey}.operations.${operationKey}.rules[${index}].charge`,\n ),\n );\n validateCharge(parsedCharge, definition, operationKey);\n return {\n when: Object.fromEntries(\n Object.entries(whenRaw).map(([key, item]) => {\n const dimension = definition.dimensions[key];\n if (!dimension) {\n semanticError(\n `pricing.rate_cards.${cardKey}.operations.${operationKey}.rules[${index}] matches undeclared dimension '${key}'`,\n );\n }\n return [\n key,\n parseMatcher(\n item,\n dimension,\n `pricing.rate_cards.${cardKey}.operations.${operationKey}.rules[${index}].when.${key}`,\n ),\n ];\n }),\n ),\n charge: parsedCharge,\n };\n },\n );\n const unmatchedRaw = asObject(operationPriceRaw.unmatched);\n const unmatched =\n unmatchedRaw.action === \"charge\"\n ? ({ action: \"charge\", charge: parseCharge(asObject(unmatchedRaw.charge)) } as const)\n : ({ action: \"reject\" } as const);\n if (unmatched.action === \"charge\") {\n validateCharge(unmatched.charge, definition, operationKey);\n }\n operationPrices[operationKey] = { rules, unmatched };\n }\n const rateCard: RateCard = { operations: operationPrices };\n if (rawCard.extends != null) rateCard.extends = asString(rawCard.extends);\n rateCards[cardKey] = rateCard;\n }\n\n validateRateCardInheritance(rateCards);\n return { operations, rateCards };\n}\n\nexport function resolvesOperation(\n pricing: PricingConfig,\n cardKey: string,\n operation: string,\n): boolean {\n const card = pricing.rateCards[cardKey];\n if (!card) return false;\n return (\n Object.prototype.hasOwnProperty.call(card.operations, operation) ||\n (card.extends != null && resolvesOperation(pricing, card.extends, operation))\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"parse-pricing.js","sourceRoot":"","sources":["../../src/config/parse-pricing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,OAAO,EACP,SAAS,EACT,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,UAAU,EACV,aAAa,EACb,mBAAmB,GACpB,MAAM,kBAAkB,CAAC;AAc1B,MAAM,cAAc,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC,CAAC;AAC5D,MAAM,mBAAmB,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC,CAAC;AAEpE,SAAS,kBAAkB,CACzB,KAA4B,EAC5B,UAA+B,EAC/B,IAAY;IAEZ,IAAI,UAAU,CA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,CAAC,OAAO,IAAI,IAAI,IAAI,iBAAiB,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC,CAC9E,CAAC;AACJ,CAAC","sourcesContent":["import { validateExpression } from \"../expr.js\";\nimport { z } from \"zod\";\nimport {\n asArray,\n asBoolean,\n asDecimal,\n asObject,\n asString,\n identifier,\n semanticError,\n validateIdentifiers,\n} from \"./parse-utils.js\";\nimport type { JsonValue } from \"../shared/json.js\";\nimport type {\n Charge,\n DimensionDefinition,\n DimensionMatcher,\n GraduatedTier,\n MatcherScalar,\n OperationDefinition,\n OperationPricing,\n PricingConfig,\n RateCard,\n} from \"./types.js\";\n\nconst roundingSchema = z.enum([\"ceil\", \"floor\", \"nearest\"]);\nconst dimensionTypeSchema = z.enum([\"string\", \"number\", \"boolean\"]);\n\nfunction parseMatcherScalar(\n value: JsonValue | undefined,\n definition: DimensionDefinition,\n path: string,\n): MatcherScalar {\n if (definition.type === \"boolean\") {\n const parsed = z.boolean().safeParse(value);\n if (!parsed.success) semanticError(`${path} matcher values must be booleans`);\n return parsed.data;\n }\n if (definition.type === \"number\") {\n const parsed = z.union([z.number(), z.string()]).safeParse(value);\n if (!parsed.success) semanticError(`${path} matcher values must be decimal strings or numbers`);\n return asDecimal(parsed.data, path);\n }\n const parsed = z.string().safeParse(value);\n if (!parsed.success) semanticError(`${path} matcher values must be strings`);\n return parsed.data;\n}\n\nfunction parseMatcher(\n value: JsonValue,\n definition: DimensionDefinition,\n path: string,\n): DimensionMatcher {\n const raw = asObject(value);\n switch (raw.op) {\n case \"in\":\n case \"not_in\":\n return {\n op: raw.op,\n values: asArray(raw.values, `${path}.values`).map((item) =>\n parseMatcherScalar(item, definition, path),\n ),\n };\n case \"prefix\":\n if (definition.type !== \"string\") {\n semanticError(`${path} prefix matcher requires a string dimension`);\n }\n return { op: \"prefix\", value: asString(raw.value) };\n case \"range\": {\n if (definition.type !== \"number\") {\n semanticError(`${path} range matcher requires a number dimension`);\n }\n const parsed: Extract<DimensionMatcher, { op: \"range\" }> = { op: \"range\" };\n if (raw.gt != null) parsed.gt = asDecimal(raw.gt);\n if (raw.gte != null) parsed.gte = asDecimal(raw.gte);\n if (raw.lt != null) parsed.lt = asDecimal(raw.lt);\n if (raw.lte != null) parsed.lte = asDecimal(raw.lte);\n if (parsed.gt == null && parsed.gte == null && parsed.lt == null && parsed.lte == null) {\n semanticError(`${path} range matcher requires at least one bound`);\n }\n if (parsed.gt != null && parsed.gte != null) {\n semanticError(`${path} range matcher cannot combine gt and gte`);\n }\n if (parsed.lt != null && parsed.lte != null) {\n semanticError(`${path} range matcher cannot combine lt and lte`);\n }\n const lower = parsed.gt ?? parsed.gte;\n const upper = parsed.lt ?? parsed.lte;\n if (lower != null && upper != null && lower.gte(upper)) {\n semanticError(`${path} range matcher lower bound must be less than upper bound`);\n }\n return parsed;\n }\n default:\n return { op: \"eq\", value: parseMatcherScalar(raw.value, definition, path) };\n }\n}\n\nfunction parseTiers(value: JsonValue | undefined): GraduatedTier[] {\n const tiers = asArray(value, \"pricing.tiers\").map((item) => {\n const tier = asObject(item);\n const parsedTier: GraduatedTier = { rate: asDecimal(tier.rate) };\n if (tier.up_to != null) parsedTier.upTo = asDecimal(tier.up_to);\n return parsedTier;\n });\n if (tiers.at(-1)?.upTo != null || tiers.slice(0, -1).some((tier) => tier.upTo == null)) {\n semanticError(\"graduated and volume tiers must end with exactly one open-ended tier\");\n }\n const finite = tiers.flatMap((tier) => (tier.upTo == null ? [] : [tier.upTo]));\n if (\n finite.some((bound, index) => {\n const previous = finite[index - 1];\n return index > 0 && previous !== undefined && bound.lte(previous);\n })\n ) {\n semanticError(\"graduated and volume tier bounds must be strictly increasing\");\n }\n return tiers;\n}\n\nfunction parseCharge(value: JsonValue): Charge {\n const raw = asObject(value);\n switch (raw.type) {\n case \"flat\":\n return { type: \"flat\", amount: asDecimal(raw.amount) };\n case \"per_unit\":\n return {\n type: \"per_unit\",\n measure: asString(raw.measure),\n rate: asDecimal(raw.rate),\n unitSize: asDecimal(raw.unit_size ?? 1),\n };\n case \"package\":\n return {\n type: \"package\",\n measure: asString(raw.measure),\n units: asDecimal(raw.units),\n amount: asDecimal(raw.amount),\n rounding: roundingSchema.parse(raw.rounding ?? \"ceil\"),\n };\n case \"graduated\":\n case \"volume\":\n return {\n type: raw.type,\n measure: asString(raw.measure),\n tiers: parseTiers(raw.tiers),\n };\n case \"expression\":\n return { type: \"expression\", formula: asString(raw.formula) };\n case \"sum\":\n return {\n type: \"sum\",\n components: asArray(raw.components, \"pricing.sum.components\").map(parseCharge),\n };\n default:\n return semanticError(`unsupported charge type '${asString(raw.type)}'`);\n }\n}\n\nfunction chargeMeasures(value: Charge): Set<string> {\n if (\"measure\" in value) return new Set([value.measure]);\n if (value.type === \"sum\") {\n return new Set(value.components.flatMap((component) => [...chargeMeasures(component)]));\n }\n return new Set();\n}\n\nfunction expressionCharges(value: Charge): Extract<Charge, { type: \"expression\" }>[] {\n if (value.type === \"expression\") return [value];\n if (value.type === \"sum\") return value.components.flatMap(expressionCharges);\n return [];\n}\n\nfunction validateCharge(\n parsed: Charge,\n definition: OperationDefinition,\n operationKey: string,\n): void {\n const unknownMeasures = [...chargeMeasures(parsed)].filter((name) => !definition.measures[name]);\n if (unknownMeasures.length) {\n semanticError(\n `pricing for operation '${operationKey}' references undeclared measures ${unknownMeasures.join(\", \")}`,\n );\n }\n for (const expression of expressionCharges(parsed)) {\n validateExpression(expression.formula, new Set(Object.keys(definition.measures)));\n }\n}\n\nfunction validateRateCardInheritance(rateCards: Record<string, RateCard>): void {\n const visiting = new Set<string>();\n const visited = new Set<string>();\n const visit = (key: string): void => {\n if (visiting.has(key)) semanticError(`pricing rate-card inheritance cycle includes '${key}'`);\n if (visited.has(key)) return;\n const card = rateCards[key];\n if (!card) semanticError(`unknown rate card '${key}'`);\n visiting.add(key);\n if (card.extends) visit(card.extends);\n visiting.delete(key);\n visited.add(key);\n };\n Object.keys(rateCards).forEach(visit);\n}\n\nexport function parsePricing(value: JsonValue): PricingConfig {\n const raw = asObject(value);\n const operationsRaw = asObject(raw.operations);\n const cardsRaw = asObject(raw.rate_cards);\n validateIdentifiers(operationsRaw, \"pricing.operations\");\n validateIdentifiers(cardsRaw, \"pricing.rate_cards\");\n if (Object.keys(operationsRaw).length === 0) {\n semanticError(\"pricing.operations must not be empty\");\n }\n if (Object.keys(cardsRaw).length === 0) {\n semanticError(\"pricing.rate_cards must not be empty\");\n }\n\n const operations: Record<string, OperationDefinition> = {};\n for (const [operationKey, input] of Object.entries(operationsRaw)) {\n const operation = asObject(input);\n const measuresRaw = asObject(operation.measures);\n const dimensionsRaw = asObject(operation.dimensions ?? {});\n validateIdentifiers(measuresRaw, `pricing.operations.${operationKey}.measures`);\n validateIdentifiers(dimensionsRaw, `pricing.operations.${operationKey}.dimensions`);\n if (Object.keys(measuresRaw).length === 0) {\n semanticError(`pricing.operations.${operationKey}.measures must not be empty`);\n }\n const overlap = Object.keys(measuresRaw).filter((key) =>\n Object.prototype.hasOwnProperty.call(dimensionsRaw, key),\n );\n if (overlap.length) {\n semanticError(`operation '${operationKey}' reuses names as measures and dimensions`);\n }\n operations[operationKey] = {\n measures: Object.fromEntries(\n Object.entries(measuresRaw).map(([key, definition]) => [\n key,\n { unit: identifier(asString(asObject(definition).unit), `${operationKey}.${key}.unit`) },\n ]),\n ),\n dimensions: Object.fromEntries(\n Object.entries(dimensionsRaw).map(([key, definition]) => {\n const item = asObject(definition);\n return [\n key,\n {\n type: dimensionTypeSchema.parse(item.type),\n required: asBoolean(item.required ?? true),\n },\n ];\n }),\n ),\n };\n }\n\n const rateCards: Record<string, RateCard> = {};\n for (const [cardKey, input] of Object.entries(cardsRaw)) {\n const rawCard = asObject(input);\n const operationPricesRaw = asObject(rawCard.operations ?? {});\n const operationPrices: Record<string, OperationPricing> = {};\n for (const [operationKey, operationInput] of Object.entries(operationPricesRaw)) {\n const definition = operations[operationKey];\n if (!definition) {\n semanticError(`rate card '${cardKey}' references unknown operation '${operationKey}'`);\n }\n const operationPriceRaw = asObject(operationInput);\n const rules = asArray(operationPriceRaw.rules ?? [], \"pricing.rules\").map(\n (ruleInput, index) => {\n const ruleRaw = asObject(ruleInput);\n const whenRaw = asObject(ruleRaw.when);\n const unknownDimensions = Object.keys(whenRaw).filter(\n (name) => !definition.dimensions[name],\n );\n if (unknownDimensions.length) {\n semanticError(\n `pricing.rate_cards.${cardKey}.operations.${operationKey}.rules[${index}] matches undeclared dimensions ${unknownDimensions.join(\", \")}`,\n );\n }\n const parsedCharge = parseCharge(\n asObject(\n ruleRaw.charge,\n `pricing.rate_cards.${cardKey}.operations.${operationKey}.rules[${index}].charge`,\n ),\n );\n validateCharge(parsedCharge, definition, operationKey);\n return {\n when: Object.fromEntries(\n Object.entries(whenRaw).map(([key, item]) => {\n const dimension = definition.dimensions[key];\n if (!dimension) {\n semanticError(\n `pricing.rate_cards.${cardKey}.operations.${operationKey}.rules[${index}] matches undeclared dimension '${key}'`,\n );\n }\n return [\n key,\n parseMatcher(\n item,\n dimension,\n `pricing.rate_cards.${cardKey}.operations.${operationKey}.rules[${index}].when.${key}`,\n ),\n ];\n }),\n ),\n charge: parsedCharge,\n };\n },\n );\n const unmatchedRaw = asObject(operationPriceRaw.unmatched);\n const unmatched =\n unmatchedRaw.action === \"charge\"\n ? ({ action: \"charge\", charge: parseCharge(asObject(unmatchedRaw.charge)) } as const)\n : ({ action: \"reject\" } as const);\n if (unmatched.action === \"charge\") {\n validateCharge(unmatched.charge, definition, operationKey);\n }\n operationPrices[operationKey] = { rules, unmatched };\n }\n const rateCard: RateCard = { operations: operationPrices };\n if (rawCard.extends != null) rateCard.extends = asString(rawCard.extends);\n rateCards[cardKey] = rateCard;\n }\n\n validateRateCardInheritance(rateCards);\n return { operations, rateCards };\n}\n\nexport function resolvesOperation(\n pricing: PricingConfig,\n cardKey: string,\n operation: string,\n): boolean {\n const card = pricing.rateCards[cardKey];\n if (!card) return false;\n return (\n Object.prototype.hasOwnProperty.call(card.operations, operation) ||\n (card.extends != null && resolvesOperation(pricing, card.extends, operation))\n );\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parse-utils.js","sourceRoot":"","sources":["../../src/config/parse-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAmC,MAAM,mBAAmB,CAAC;AAGlF,MAAM,UAAU,GAAG,mBAAmB,CAAC;AACvC,MAAM,MAAM,GAAG,+BAA+B,CAAC;AAM/C,MAAM,cAAc,GAAG,CAAC,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAU,CAAC;AAC5E,MAAM,sBAAsB,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAU,CAAC;AACzE,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAU,CAAC;AAEjE,SAAS,aAAa,CAAC,KAAkB,EAAE,IAAY;IACrD,IAAI,KAAK,KAAK,SAAS;QAAE,aAAa,CAAC,GAAG,IAAI,cAAc,CAAC,CAAC;IAC9D,OAAO,KAAK,CAAC;AACf,CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,KAAkB,EAAE,IAAI,GAAG,OAAO;IACzD,MAAM,SAAS,GAAG,aAAa,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IAC7C,IAAI,CAAC,YAAY,CAAC,SAAS,CAAC;QAAE,aAAa,CAAC,GAAG,IAAI,oBAAoB,CAAC,CAAC;IACzE,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,OAAO,CAAC,KAAkB,EAAE,IAAI,GAAG,OAAO;IACxD,MAAM,SAAS,GAAG,aAAa,CAAC,KAAK,EAAE,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,KAAK,kBAAkB;YACrB,OAAO,EAAE,IAAI,EAAE,kBAAkB,EAAE,CAAC;QACtC;YACE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IAC7B,CAAC;AACH,CAAC","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\n\nimport { ConfigError } from \"../errors.js\";\nimport { isJsonObject, type JsonObject, type JsonValue } from \"../shared/json.js\";\nimport type { Availability, BillingInterval, Duration, ExpiryPolicy, Window } from \"./types.js\";\n\nconst IDENTIFIER = /^[a-z][a-z0-9_]*$/;\nconst REGION = /^[A-Z]{2}(?:-[A-Z0-9]{1,3})?$/;\n\nexport type { JsonObject, JsonValue } from \"../shared/json.js\";\n\ntype ConfigValue = JsonValue | undefined;\n\nconst DURATION_UNITS = [\"second\", \"minute\", \"hour\", \"day\", \"week\"] as const;\nconst BILLING_INTERVAL_UNITS = [\"day\", \"week\", \"month\", \"year\"] as const;\nconst CALENDAR_UNITS = [\"day\", \"week\", \"month\", \"year\"] as const;\n\nfunction requiredValue(value: ConfigValue, path: string): JsonValue {\n if (value === undefined) semanticError(`${path} is required`);\n return value;\n}\n\nexport function asObject(value: ConfigValue, path = \"value\"): JsonObject {\n const candidate = requiredValue(value, path);\n if (!isJsonObject(candidate)) semanticError(`${path} must be an object`);\n return candidate;\n}\n\nexport function asArray(value: ConfigValue, path = \"value\"): JsonValue[] {\n const candidate = requiredValue(value, path);\n if (!Array.isArray(candidate)) semanticError(`${path} must be an array`);\n return candidate;\n}\n\nexport function asStringArray(value: ConfigValue, path = \"value\"): string[] {\n return asArray(value, path).map((item, index) => asString(item, `${path}[${index}]`));\n}\n\nexport function semanticError(message: string): never {\n throw new ConfigError(message);\n}\n\nexport function identifier(value: string, path: string): string {\n if (!IDENTIFIER.test(value)) semanticError(`${path} must be a non-empty snake_case identifier`);\n return value;\n}\n\nexport function validateIdentifiers(value: JsonObject, path: string): void {\n for (const key of Object.keys(value)) identifier(key, `${path}.${key}`);\n}\n\nexport function validateRegions(values: string[], path: string): void {\n if (new Set(values).size !== values.length) {\n semanticError(`${path} must not contain duplicates`);\n }\n if (values.some((value) => !REGION.test(value))) {\n semanticError(`${path} must contain uppercase ISO-style region codes`);\n }\n}\n\nexport function asDecimal(value: ConfigValue, path = \"value\"): Decimal {\n const candidate = requiredValue(value, path);\n const parsed = z.union([z.string(), z.number()]).safeParse(candidate);\n if (!parsed.success) {\n semanticError(`${path} must be a decimal string or number`);\n }\n try {\n return new Decimal(parsed.data);\n } catch {\n semanticError(`${path} must be a valid decimal`);\n }\n}\n\nexport function asInteger(value: ConfigValue, path = \"value\"): number {\n const candidate = requiredValue(value, path);\n const parsed = z.number().int().safeParse(candidate);\n if (!parsed.success) {\n semanticError(`${path} must be an integer`);\n }\n return parsed.data;\n}\n\nexport function asString(value: ConfigValue, path = \"value\"): string {\n const candidate = requiredValue(value, path);\n const parsed = z.string().safeParse(candidate);\n if (!parsed.success) semanticError(`${path} must be a string`);\n return parsed.data;\n}\n\nexport function asBoolean(value: ConfigValue, path = \"value\"): boolean {\n const candidate = requiredValue(value, path);\n const parsed = z.boolean().safeParse(candidate);\n if (!parsed.success) semanticError(`${path} must be a boolean`);\n return parsed.data;\n}\n\nfunction enumValue<const T extends string>(\n value: ConfigValue,\n allowed: readonly T[],\n path: string,\n): T {\n const candidate = asString(value, path);\n const match = allowed.find((item) => item === candidate);\n if (match === undefined) semanticError(`${path} has an invalid value`);\n return match;\n}\n\nfunction asTimezone(value: ConfigValue, path: string): string {\n const candidate = asString(value, path);\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: candidate }).format();\n } catch {\n semanticError(`${path} must be a valid IANA timezone`);\n }\n return candidate;\n}\n\nexport function parseDuration(value: ConfigValue): Duration {\n const raw = asObject(value, \"duration\");\n return {\n unit: enumValue(raw.unit, DURATION_UNITS, \"duration.unit\"),\n count: asInteger(raw.count, \"duration.count\"),\n };\n}\n\nexport function parseBillingInterval(value: ConfigValue): BillingInterval {\n const raw = asObject(value, \"billing_interval\");\n return {\n unit: enumValue(raw.unit, BILLING_INTERVAL_UNITS, \"billing_interval.unit\"),\n count: asInteger(raw.count ?? 1, \"billing_interval.count\"),\n };\n}\n\nexport function parseWindow(value: ConfigValue, path: string): Window {\n const raw = asObject(value);\n if (raw.type === \"rolling\") {\n return { type: \"rolling\", duration: parseDuration(raw.duration) };\n }\n if (raw.type === \"plan_assignment\") {\n return {\n type: \"plan_assignment\",\n interval: parseBillingInterval(raw.interval),\n timezone: asTimezone(raw.timezone ?? \"UTC\", `${path}.timezone`),\n };\n }\n if (raw.type !== \"calendar\") semanticError(`${path}.type must be a supported window type`);\n return {\n type: \"calendar\",\n unit: enumValue(raw.unit, CALENDAR_UNITS, `${path}.unit`),\n count: asInteger(raw.count ?? 1, `${path}.count`),\n timezone: asTimezone(raw.timezone ?? \"UTC\", `${path}.timezone`),\n };\n}\n\nexport function parseAvailability(value: ConfigValue): Availability {\n const raw = asObject(value, \"availability\");\n const startsAt =\n raw.starts_at == null ? undefined : asString(raw.starts_at, \"availability.starts_at\");\n const endsAt = raw.ends_at == null ? undefined : asString(raw.ends_at, \"availability.ends_at\");\n const regions = Array.isArray(raw.regions)\n ? raw.regions.map((region, index) => asString(region, `availability.regions[${index}]`))\n : [];\n if (raw.regions != null && !Array.isArray(raw.regions)) {\n semanticError(\"availability.regions must be an array\");\n }\n validateRegions(regions, \"availability.regions\");\n if (startsAt != null && endsAt != null && Date.parse(endsAt) <= Date.parse(startsAt)) {\n semanticError(\"availability.ends_at must be later than starts_at\");\n }\n const result: Availability = { regions };\n if (startsAt != null) result.startsAt = startsAt;\n if (endsAt != null) result.endsAt = endsAt;\n return result;\n}\n\nexport function parseExpiry(value: ConfigValue, path: string): ExpiryPolicy {\n const raw = asObject(value);\n switch (raw.type) {\n case \"after_grant\":\n return {\n type: \"after_grant\",\n interval: parseBillingInterval(raw.interval),\n timezone: asTimezone(raw.timezone ?? \"UTC\", `${path}.timezone`),\n };\n case \"end_of_window\": {\n const parsed = parseWindow(raw.window, `${path}.window`);\n if (parsed.type === \"rolling\") semanticError(`${path} cannot use a rolling window`);\n return { type: \"end_of_window\", window: parsed };\n }\n case \"fixed_at\":\n return { type: \"fixed_at\", at: asString(raw.at, `${path}.at`) };\n case \"subscription_end\":\n return { type: \"subscription_end\" };\n default:\n return { type: \"never\" };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"parse-utils.js","sourceRoot":"","sources":["../../src/config/parse-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAmC,MAAM,mBAAmB,CAAC;AAGlF,MAAM,UAAU,GAAG,mBAAmB,CAAC;AACvC,MAAM,MAAM,GAAG,+BAA+B,CAAC;AAM/C,MAAM,cAAc,GAAG,CAAC,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAU,CAAC;AAC5E,MAAM,sBAAsB,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAU,CAAC;AACzE,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAU,CAAC;AAEjE,SAAS,aAAa,CAAC,KAAkB,EAAE,IAAY;IACrD,IAAI,KAAK,KAAK,SAAS;QAAE,aAAa,CAAC,GAAG,IAAI,cAAc,CAAC,CAAC;IAC9D,OAAO,KAAK,CAAC;AACf,CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,KAAkB,EAAE,IAAI,GAAG,OAAO;IACzD,MAAM,SAAS,GAAG,aAAa,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IAC7C,IAAI,CAAC,YAAY,CAAC,SAAS,CAAC;QAAE,aAAa,CAAC,GAAG,IAAI,oBAAoB,CAAC,CAAC;I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UAAU;YACb,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,EAAE,QAAQ,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,IAAI,KAAK,CAAC,EAAE,CAAC;QAClE,KAAK,kBAAkB;YACrB,OAAO,EAAE,IAAI,EAAE,kBAAkB,EAAE,CAAC;QACtC;YACE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IAC7B,CAAC;AACH,CAAC","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\n\nimport { ConfigError } from \"../errors.js\";\nimport { isJsonObject, type JsonObject, type JsonValue } from \"../shared/json.js\";\nimport type { Availability, BillingInterval, Duration, ExpiryPolicy, Window } from \"./types.js\";\n\nconst IDENTIFIER = /^[a-z][a-z0-9_]*$/;\nconst REGION = /^[A-Z]{2}(?:-[A-Z0-9]{1,3})?$/;\n\nexport type { JsonObject, JsonValue } from \"../shared/json.js\";\n\ntype ConfigValue = JsonValue | undefined;\n\nconst DURATION_UNITS = [\"second\", \"minute\", \"hour\", \"day\", \"week\"] as const;\nconst BILLING_INTERVAL_UNITS = [\"day\", \"week\", \"month\", \"year\"] as const;\nconst CALENDAR_UNITS = [\"day\", \"week\", \"month\", \"year\"] as const;\n\nfunction requiredValue(value: ConfigValue, path: string): JsonValue {\n if (value === undefined) semanticError(`${path} is required`);\n return value;\n}\n\nexport function asObject(value: ConfigValue, path = \"value\"): JsonObject {\n const candidate = requiredValue(value, path);\n if (!isJsonObject(candidate)) semanticError(`${path} must be an object`);\n return candidate;\n}\n\nexport function asArray(value: ConfigValue, path = \"value\"): JsonValue[] {\n const candidate = requiredValue(value, path);\n if (!Array.isArray(candidate)) semanticError(`${path} must be an array`);\n return candidate;\n}\n\nexport function asStringArray(value: ConfigValue, path = \"value\"): string[] {\n return asArray(value, path).map((item, index) => asString(item, `${path}[${index}]`));\n}\n\nexport function semanticError(message: string): never {\n throw new ConfigError(message);\n}\n\nexport function identifier(value: string, path: string): string {\n if (!IDENTIFIER.test(value)) semanticError(`${path} must be a non-empty snake_case identifier`);\n return value;\n}\n\nexport function validateIdentifiers(value: JsonObject, path: string): void {\n for (const key of Object.keys(value)) identifier(key, `${path}.${key}`);\n}\n\nexport function validateRegions(values: string[], path: string): void {\n if (new Set(values).size !== values.length) {\n semanticError(`${path} must not contain duplicates`);\n }\n if (values.some((value) => !REGION.test(value))) {\n semanticError(`${path} must contain uppercase ISO-style region codes`);\n }\n}\n\nexport function asDecimal(value: ConfigValue, path = \"value\"): Decimal {\n const candidate = requiredValue(value, path);\n const parsed = z.union([z.string(), z.number()]).safeParse(candidate);\n if (!parsed.success) {\n semanticError(`${path} must be a decimal string or number`);\n }\n try {\n return new Decimal(parsed.data);\n } catch {\n semanticError(`${path} must be a valid decimal`);\n }\n}\n\nexport function asInteger(value: ConfigValue, path = \"value\"): number {\n const candidate = requiredValue(value, path);\n const parsed = z.number().int().safeParse(candidate);\n if (!parsed.success) {\n semanticError(`${path} must be an integer`);\n }\n return parsed.data;\n}\n\nexport function asString(value: ConfigValue, path = \"value\"): string {\n const candidate = requiredValue(value, path);\n const parsed = z.string().safeParse(candidate);\n if (!parsed.success) semanticError(`${path} must be a string`);\n return parsed.data;\n}\n\nexport function asBoolean(value: ConfigValue, path = \"value\"): boolean {\n const candidate = requiredValue(value, path);\n const parsed = z.boolean().safeParse(candidate);\n if (!parsed.success) semanticError(`${path} must be a boolean`);\n return parsed.data;\n}\n\nfunction enumValue<const T extends string>(\n value: ConfigValue,\n allowed: readonly T[],\n path: string,\n): T {\n const candidate = asString(value, path);\n const match = allowed.find((item) => item === candidate);\n if (match === undefined) semanticError(`${path} has an invalid value`);\n return match;\n}\n\nfunction asTimezone(value: ConfigValue, path: string): string {\n const candidate = asString(value, path);\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: candidate }).format();\n } catch {\n semanticError(`${path} must be a valid IANA timezone`);\n }\n return candidate;\n}\n\nexport function parseDuration(value: ConfigValue): Duration {\n const raw = asObject(value, \"duration\");\n return {\n unit: enumValue(raw.unit, DURATION_UNITS, \"duration.unit\"),\n count: asInteger(raw.count, \"duration.count\"),\n };\n}\n\nexport function parseBillingInterval(value: ConfigValue): BillingInterval {\n const raw = asObject(value, \"billing_interval\");\n return {\n unit: enumValue(raw.unit, BILLING_INTERVAL_UNITS, \"billing_interval.unit\"),\n count: asInteger(raw.count ?? 1, \"billing_interval.count\"),\n };\n}\n\nexport function parseWindow(value: ConfigValue, path: string): Window {\n const raw = asObject(value);\n if (raw.type === \"rolling\") {\n return { type: \"rolling\", duration: parseDuration(raw.duration) };\n }\n if (raw.type === \"plan_assignment\") {\n return {\n type: \"plan_assignment\",\n interval: parseBillingInterval(raw.interval),\n timezone: asTimezone(raw.timezone ?? \"UTC\", `${path}.timezone`),\n };\n }\n if (raw.type !== \"calendar\") semanticError(`${path}.type must be a supported window type`);\n return {\n type: \"calendar\",\n unit: enumValue(raw.unit, CALENDAR_UNITS, `${path}.unit`),\n count: asInteger(raw.count ?? 1, `${path}.count`),\n timezone: asTimezone(raw.timezone ?? \"UTC\", `${path}.timezone`),\n };\n}\n\nexport function parseAvailability(value: ConfigValue): Availability {\n const raw = asObject(value, \"availability\");\n const startsAt =\n raw.starts_at == null ? undefined : asString(raw.starts_at, \"availability.starts_at\");\n const endsAt = raw.ends_at == null ? undefined : asString(raw.ends_at, \"availability.ends_at\");\n const regions = Array.isArray(raw.regions)\n ? raw.regions.map((region, index) => asString(region, `availability.regions[${index}]`))\n : [];\n if (raw.regions != null && !Array.isArray(raw.regions)) {\n semanticError(\"availability.regions must be an array\");\n }\n validateRegions(regions, \"availability.regions\");\n if (startsAt != null && endsAt != null && Date.parse(endsAt) <= Date.parse(startsAt)) {\n semanticError(\"availability.ends_at must be later than starts_at\");\n }\n const result: Availability = { regions };\n if (startsAt != null) result.startsAt = startsAt;\n if (endsAt != null) result.endsAt = endsAt;\n return result;\n}\n\nexport function parseExpiry(value: ConfigValue, path: string): ExpiryPolicy {\n const raw = asObject(value);\n switch (raw.type) {\n case \"after_grant\":\n return {\n type: \"after_grant\",\n interval: parseBillingInterval(raw.interval),\n timezone: asTimezone(raw.timezone ?? \"UTC\", `${path}.timezone`),\n };\n case \"end_of_window\": {\n const parsed = parseWindow(raw.window, `${path}.window`);\n if (parsed.type === \"rolling\") semanticError(`${path} cannot use a rolling window`);\n return { type: \"end_of_window\", window: parsed };\n }\n case \"fixed_at\":\n return { type: \"fixed_at\", at: asString(raw.at, `${path}.at`) };\n case \"subscription_end\":\n return { type: \"subscription_end\" };\n default:\n return { type: \"never\" };\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"catalog-runtime.d.ts","sourceRoot":"","sources":["../../src/credits/catalog-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAGrC,OAAO,EAEL,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACpB,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAGlD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,KAAK,EAAe,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAWvE,mFAAmF;AACnF,qBAAa,cAAc;IAMvB,OAAO,CAAC,QAAQ,CAAC,KAAK;IAEtB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,UAAU;IAR7B,OAAO,CAAC,MAAM,CAAuB;IACrC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAkC;IACxD,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAoC;
|
|
1
|
+
{"version":3,"file":"catalog-runtime.d.ts","sourceRoot":"","sources":["../../src/credits/catalog-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAA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MAAM,EAAE,CAAC;YACpB,MAAM,IAAI,qBAAqB,CAC7B,oBAAoB,cAAc,qCAAqC,CACxE,CAAC;QACJ,CAAC;QAED,MAAM,MAAM,GAAG,kBAAkB,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC1D,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC;QAChD,OAAO,MAAM,CAAC;IAChB,CAAC;IAEO,aAAa;QACnB,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,MAAM,IAAI,qBAAqB,CAC7B,kFAAkF,CACnF,CAAC;QACJ,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { LRUCache } from \"lru-cache\";\nimport { z } from \"zod\";\nimport {\n canonicalBursarConfigDict,\n type BursarConfigData,\n type CatalogRollout,\n} from \"../config.js\";\nimport type { PricingEngine } from \"../engine.js\";\nimport { PricingEngine as PricingEngineClass } from \"../engine.js\";\nimport { LeaseNotFoundError, CatalogNotLoadedError } from \"../errors.js\";\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type { ExactAmount, MetricsOrAmount } from \"./service-types.js\";\nimport { isAmount, rejectNativeCreditAmount, toDecimal } from \"./amount.js\";\n\nfunction toNonNegativeAmount(value: ExactAmount): Decimal {\n const amount = toDecimal(value);\n if (!amount.isFinite() || amount.isNegative()) {\n throw new RangeError(\"amount must be finite and non-negative\");\n }\n return amount;\n}\n\n/** Owns catalog publication, cache refresh, and revision-aware pricing engines. */\nexport class CatalogRuntime {\n private engine: PricingEngine | null;\n private readonly cache: LRUCache<string, PricingEngine>;\n private readonly versionEngines = new Map<number, PricingEngine>();\n\n constructor(\n private readonly store: CreditStore,\n engine: PricingEngine | null,\n private readonly logger: NormalizedLogger,\n private readonly cacheTtlMs: number,\n ) {\n this.engine = engine;\n this.cache = new LRUCache<string, PricingEngine>({\n max: 1,\n ttl: cacheTtlMs,\n // Consumers must never proceed against a known-stale catalog. The cache\n // still deduplicates concurrent refreshes, but every caller awaits the\n // same fresh value just like the Python SDK's refresh lock.\n allowStale: false,\n fetchMethod: async () => {\n const engine = await this.fetchEngineFromStore();\n // `lru-cache` installs the returned value when the fetch completes.\n // Calling cache.set() from inside fetchMethod aborts the in-flight\n // refresh with a \"replaced\" error.\n this.engine = engine;\n this.versionEngines.clear();\n return engine;\n },\n });\n if (engine) this.cache.set(\"catalog\", engine);\n }\n\n get currentEngine(): PricingEngine | null {\n return this.engine;\n }\n\n async loadFromStore(): Promise<void> {\n this.setEngine(await this.fetchEngineFromStore());\n }\n\n private async fetchEngineFromStore(): Promise<PricingEngine> {\n this.logger.info(\"[CatalogService] loading active catalog\");\n const active = await this.store.getActiveCatalog();\n if (!active) {\n this.logger.warn(\"[CatalogService] no active catalog revision in store\");\n throw new CatalogNotLoadedError(\"No active catalog revision is available\");\n }\n return PricingEngineClass.fromDict(active.config);\n }\n\n async refreshIfStale(): Promise<void> {\n if (this.cacheTtlMs === 0) return;\n await this.cache.fetch(\"catalog\");\n }\n\n invalidate(): void {\n this.cache.delete(\"catalog\");\n }\n\n async publishAndActivate(\n config: BursarConfigData,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string> {\n this.logger.info(\"[CatalogService] publishing and activating catalog\", { label });\n const canonical = canonicalBursarConfigDict(config);\n const nextEngine = PricingEngineClass.fromDict(canonical);\n const revisionId = await this.store.publishAndActivateCatalog(canonical, label, rollout);\n this.setEngine(nextEngine);\n return revisionId;\n }\n\n async publishDraft(config: BursarConfigData, label?: string | null): Promise<string> {\n return this.store.publishCatalogDraft(canonicalBursarConfigDict(config), label);\n }\n\n async activateRevision(version: number, rollout?: CatalogRollout | null): Promise<string> {\n const id = await this.store.activateCatalogRevision(version, rollout);\n await this.loadFromStore();\n return id;\n }\n\n async costOf(\n metricsOrAmount: MetricsOrAmount,\n userId?: string | null,\n leaseId?: string | null,\n ): Promise<{ amount: Decimal; model: string | null }> {\n rejectNativeCreditAmount(metricsOrAmount);\n if (isAmount(metricsOrAmount)) {\n return { amount: toNonNegativeAmount(metricsOrAmount), model: null };\n }\n let engine: PricingEngine;\n let rateCard: string | undefined;\n if (leaseId != null) {\n if (userId == null) throw new TypeError(\"userId is required when pricing a lease\");\n const context = await this.store.getLeasePricingContext(userId, leaseId);\n if (!context) throw new LeaseNotFoundError(`Lease not found. User=${userId}`);\n engine = await this.engineForCatalogVersion(context.catalogVersion);\n rateCard = context.rateCard ?? engine.getRateCardForPlan(context.planKey);\n } else {\n engine = await this.engineForUser(userId ?? null);\n const plan = userId == null ? null : await this.store.getUserPlan(userId);\n rateCard = plan?.rateCard ?? undefined;\n }\n const breakdown = engine.calculate(metricsOrAmount, {\n rateCard,\n });\n return {\n amount: breakdown.total,\n model: z.string().safeParse(metricsOrAmount.dimensions?.model).data ?? null,\n };\n }\n\n private setEngine(engine: PricingEngine): void {\n this.engine = engine;\n this.versionEngines.clear();\n this.cache.set(\"catalog\", engine);\n }\n\n async engineForUser(userId: string | null): Promise<PricingEngine> {\n if (userId == null) return this.requireEngine();\n\n const plan = await this.store.getUserPlan(userId);\n const catalogVersion = plan.catalogVersion ?? null;\n if (catalogVersion == null) {\n await this.refreshIfStale();\n return this.requireEngine();\n }\n\n return this.engineForCatalogVersion(catalogVersion);\n }\n\n private async engineForCatalogVersion(catalogVersion: number): Promise<PricingEngine> {\n const cached = this.versionEngines.get(catalogVersion);\n if (cached) return cached;\n\n const config = await this.store.getCatalogRevision(catalogVersion);\n if (!config?.config) {\n throw new CatalogNotLoadedError(\n `Catalog revision ${catalogVersion} is unavailable for the pinned plan`,\n );\n }\n\n const engine = PricingEngineClass.fromDict(config.config);\n this.versionEngines.set(catalogVersion, engine);\n return engine;\n }\n\n private requireEngine(): PricingEngine {\n if (!this.engine) {\n throw new CatalogNotLoadedError(\n \"Catalog is not loaded; call catalog.load() or catalog.publishAndActivate() first\",\n );\n }\n return this.engine;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"catalog-runtime.js","sourceRoot":"","sources":["../../src/credits/catalog-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,yBAAyB,GAG1B,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,aAAa,IAAI,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAIzE,OAAO,EAAE,QAAQ,EAAE,wBAAwB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE5E,SAAS,mBAAmB,CAAC,KAAkB;IAC7C,MAAM,MAAM,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;IAChC,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,IAAI,MAAM,CAAC,UAAU,EAAE,EAAE,CAAC;QAC9C,MAAM,IAAI,UAAU,CAAC,wCAAwC,CAAC,CAAC;IACjE,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,mFAAmF;AACnF,MAAM,OAAO,cAAc;IAMN,KAAK;IAEL,MAAM;IACN,UAAU;IARrB,MAAM,CAAuB;IACpB,KAAK,CAAkC;IACvC,cAAc,GAAG,IAAI,GAAG,EAAyB,CAAC;IAEnE,YACmB,KAAkB,EACnC,MAA4B,EACX,MAAwB,EACxB,UAAkB;qBAHlB,KAAK;sBAEL,MAAM;0BACN,UAAU;QAE3B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,KAAK,GAAG,IAAI,QAAQ,CAAwB;YAC/C,GAAG,EAAE,CAAC;YACN,GAAG,EAAE,UAAU;YACf,wEAAwE;YACxE,uEAAuE;Y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;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { LRUCache } from \"lru-cache\";\nimport { z } from \"zod\";\nimport {\n canonicalBursarConfigDict,\n type BursarConfigData,\n type CatalogRollout,\n} from \"../config.js\";\nimport type { PricingEngine } from \"../engine.js\";\nimport { PricingEngine as PricingEngineClass } from \"../engine.js\";\nimport { LeaseNotFoundError, CatalogNotLoadedError } from \"../errors.js\";\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type { ExactAmount, MetricsOrAmount } from \"./service-types.js\";\nimport { isAmount, rejectNativeCreditAmount, toDecimal } from \"./amount.js\";\n\nfunction toNonNegativeAmount(value: ExactAmount): Decimal {\n const amount = toDecimal(value);\n if (!amount.isFinite() || amount.isNegative()) {\n throw new RangeError(\"amount must be finite and non-negative\");\n }\n return amount;\n}\n\n/** Owns catalog publication, cache refresh, and revision-aware pricing engines. */\nexport class CatalogRuntime {\n private engine: PricingEngine | null;\n private readonly cache: LRUCache<string, PricingEngine>;\n private readonly versionEngines = new Map<number, PricingEngine>();\n\n constructor(\n private readonly store: CreditStore,\n engine: PricingEngine | null,\n private readonly logger: NormalizedLogger,\n private readonly cacheTtlMs: number,\n ) {\n this.engine = engine;\n this.cache = new LRUCache<string, PricingEngine>({\n max: 1,\n ttl: cacheTtlMs,\n // Consumers must never proceed against a known-stale catalog. The cache\n // still deduplicates concurrent refreshes, but every caller awaits the\n // same fresh value just like the Python SDK's refresh lock.\n allowStale: false,\n fetchMethod: async () => {\n const engine = await this.fetchEngineFromStore();\n // `lru-cache` installs the returned value when the fetch completes.\n // Calling cache.set() from inside fetchMethod aborts the in-flight\n // refresh with a \"replaced\" error.\n this.engine = engine;\n this.versionEngines.clear();\n return engine;\n },\n });\n if (engine) this.cache.set(\"catalog\", engine);\n }\n\n get currentEngine(): PricingEngine | null {\n return this.engine;\n }\n\n async loadFromStore(): Promise<void> {\n this.setEngine(await this.fetchEngineFromStore());\n }\n\n private async fetchEngineFromStore(): Promise<PricingEngine> {\n this.logger.info(\"[CatalogService] loading active catalog\");\n const active = await this.store.getActiveCatalog();\n if (!active) {\n this.logger.warn(\"[CatalogService] no active catalog revision in store\");\n throw new CatalogNotLoadedError(\"No active catalog revision is available\");\n }\n return PricingEngineClass.fromDict(active.config);\n }\n\n async refreshIfStale(): Promise<void> {\n if (this.cacheTtlMs === 0) return;\n await this.cache.fetch(\"catalog\");\n }\n\n invalidate(): void {\n this.cache.delete(\"catalog\");\n }\n\n async publishAndActivate(\n config: BursarConfigData,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string> {\n this.logger.info(\"[CatalogService] publishing and activating catalog\", { label });\n const canonical = canonicalBursarConfigDict(config);\n const nextEngine = PricingEngineClass.fromDict(canonical);\n const revisionId = await this.store.publishAndActivateCatalog(canonical, label, rollout);\n this.setEngine(nextEngine);\n return revisionId;\n }\n\n async publishDraft(config: BursarConfigData, label?: string | null): Promise<string> {\n return this.store.publishCatalogDraft(canonicalBursarConfigDict(config), label);\n }\n\n async activateRevision(version: number, rollout?: CatalogRollout | null): Promise<string> {\n const id = await this.store.activateCatalogRevision(version, rollout);\n await this.loadFromStore();\n return id;\n }\n\n async costOf(\n metricsOrAmount: MetricsOrAmount,\n userId?: string | null,\n leaseId?: string | null,\n ): Promise<{ amount: Decimal; model: string | null }> {\n rejectNativeCreditAmount(metricsOrAmount);\n if (isAmount(metricsOrAmount)) {\n return { amount: toNonNegativeAmount(metricsOrAmount), model: null };\n }\n let engine: PricingEngine;\n let rateCard: string | undefined;\n if (leaseId != null) {\n if (userId == null) throw new TypeError(\"userId is required when pricing a lease\");\n const context = await this.store.getLeasePricingContext(userId, leaseId);\n if (!context) throw new LeaseNotFoundError(`Lease not found. User=${userId}`);\n engine = await this.engineForCatalogVersion(context.catalogVersion);\n rateCard = context.rateCard ?? engine.getRateCardForPlan(context.planKey);\n } else {\n engine = await this.engineForUser(userId ?? null);\n const plan = userId == null ? null : await this.store.getUserPlan(userId);\n rateCard = plan?.rateCard ?? undefined;\n }\n const breakdown = engine.calculate(metricsOrAmount, {\n rateCard,\n });\n return {\n amount: breakdown.total,\n model: z.string().safeParse(metricsOrAmount.dimensions?.model).data ?? null,\n };\n }\n\n private setEngine(engine: PricingEngine): void {\n this.engine = engine;\n this.versionEngines.clear();\n this.cache.set(\"catalog\", engine);\n }\n\n async engineForUser(userId: string | null): Promise<PricingEngine> {\n if (userId == null) return this.requireEngine();\n\n const plan = await this.store.getUserPlan(userId);\n const catalogVersion = plan.catalogVersion ?? null;\n if (catalogVersion == null) {\n await this.refreshIfStale();\n return this.requireEngine();\n }\n\n return this.engineForCatalogVersion(catalogVersion);\n }\n\n private async engineForCatalogVersion(catalogVersion: number): Promise<PricingEngine> {\n const cached = this.versionEngines.get(catalogVersion);\n if (cached) return cached;\n\n const config = await this.store.getCatalogRevision(catalogVersion);\n if (!config?.config) {\n throw new CatalogNotLoadedError(\n `Catalog revision ${catalogVersion} is unavailable for the pinned plan`,\n );\n }\n\n const engine = PricingEngineClass.fromDict(config.config);\n this.versionEngines.set(catalogVersion, engine);\n return engine;\n }\n\n private requireEngine(): PricingEngine {\n if (!this.engine) {\n throw new CatalogNotLoadedError(\n \"Catalog is not loaded; call catalog.load() or catalog.publishAndActivate() first\",\n );\n }\n return this.engine;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../src/credits/events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAmB,KAAK,MAAM,EAAyB,MAAM,qBAAqB,CAAC;AAE1F;;;;;;;;;;;;;;;GAeG;AAEH;;;;;;;;GAQG;AACH,MAAM,MAAM,eAAe,GACvB,kBAAkB,GAClB,uBAAuB,GACvB,eAAe,GACf,kBAAkB,GAClB,uBAAuB,GACvB,iBAAiB,GACjB,qBAAqB,GACrB,sBAAsB,GACtB,kBAAkB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AAE,KAAK,IAAI,EAAE;gBAClB,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;YAC5C,CAAC;SACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\nimport { retryBursarOperation } from \"../retry.js\";\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditEventType } from \"./events.js\";\nimport { LowBalanceMonitor } from \"./low-balance-monitor.js\";\nimport { CatalogRuntime } from \"./catalog-runtime.js\";\nimport { isAmount, rejectNativeCreditAmount } from \"./amount.js\";\nimport { raiseLeaseError } from \"./service-errors.js\";\nimport { requireStableKey, scopedStableKey } from \"../shared/idempotency.js\";\nimport type {\n CanAffordOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n MetricsOrAmount,\n PolicyPreset,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type { StructuredObject } from \"../shared/json.js\";\nimport type {\n AllowanceResult,\n BillingMode,\n BucketBalancesResult,\n CanAffordResult,\n CreditMetadata,\n DeductionResult,\n DeductionSuccess,\n LeaseSuccess,\n ReleaseResult,\n} from \"./types/index.js\";\n\nexport class CreditLeaseWorkflow {\n constructor(\n private readonly store: CreditStore,\n private readonly catalogRuntime: CatalogRuntime,\n private readonly logger: NormalizedLogger,\n private readonly balanceMonitor: LowBalanceMonitor,\n private readonly policy: PolicyPreset,\n private readonly overdraftFloor: Decimal | null,\n private readonly defaultMaxConcurrent: number | null,\n private readonly defaultTtl: number,\n private readonly emit: (type: CreditEventType, userId: string, data?: StructuredObject) => void,\n private readonly emitQuotaEvents: (userId: string, idempotencyKey: string) => Promise<void>,\n private readonly maybeLazyExpire: (userId: string) => Promise<void>,\n private readonly afterDeduction: (userId: string, result: DeductionSuccess) => Promise<void>,\n ) {}\n\n private async expectedAdmissionPolicy(\n userId: string,\n operationType: string,\n billingModeOverride?: BillingMode | null,\n ): Promise<{\n billingMode: BillingMode;\n floor: Decimal;\n maxConcurrent: number | null;\n }> {\n const plan = await this.store.getUserPlan(userId);\n const creditPolicy = plan.planId == null ? null : plan.creditPolicy;\n const planMode: BillingMode =\n plan.planId == null\n ? this.policy === \"overdraft\"\n ? \"overdraft\"\n : \"strict\"\n : creditPolicy?.type === \"credit_line\"\n ? \"overdraft\"\n : \"strict\";\n const operationAdmission =\n plan.planId == null ? null : (plan.admission?.operations[operationType] ?? null);\n const billingMode = billingModeOverride ?? planMode;\n const floor =\n billingMode === \"overdraft\"\n ? (creditPolicy?.creditLimit?.negated() ?? this.overdraftFloor ?? new Decimal(0))\n : new Decimal(0);\n return {\n billingMode,\n floor,\n maxConcurrent:\n plan.planId == null\n ? this.defaultMaxConcurrent\n : (operationAdmission?.maxInFlight ?? plan.admission?.maxInFlight ?? null),\n };\n }\n\n /**\n * Compute the credit cost and model from metrics, or pass a raw amount through.\n *\n * For {@link UsageMetrics} the cost is ``engine.calculate(...).total`` (exact\n * `Decimal`, no truncation); a raw amount is used as-is with no model.\n */\n private async costOf(\n metricsOrAmount: MetricsOrAmount,\n userId?: string | null,\n leaseId?: string | null,\n ): Promise<{ amount: Decimal; model: string | null }> {\n return this.catalogRuntime.costOf(metricsOrAmount, userId, leaseId);\n }\n\n /**\n * Atomically acquire a lease — the only authoritative admission control.\n *\n * Prices the estimate and delegates entitlement, quota, allowance, credit\n * policy, and concurrency enforcement to the database in one atomic call.\n */\n async reserve(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options: ReserveOptions,\n ): Promise<LeaseSuccess> {\n rejectNativeCreditAmount(metricsOrAmount);\n const leaseIdempotencyKey = requireStableKey(options?.idempotencyKey);\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] reserve\", {\n feature: options.feature,\n operationType: options.operationType,\n });\n const operationType =\n options.operationType ?? (isAmount(metricsOrAmount) ? \"usage\" : metricsOrAmount.operation);\n const expectedPolicy = await this.expectedAdmissionPolicy(\n userId,\n operationType,\n options.billingMode,\n );\n const priced = await this.costOf(metricsOrAmount, userId);\n const amount = priced.amount;\n const model = priced.model ?? options.model ?? null;\n const ttlSeconds = options.ttl != null ? options.ttl : this.defaultTtl;\n const feature = options.feature ?? null;\n const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };\n const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };\n const region = z.string().safeParse(dimensions.region).data ?? null;\n\n const result = await this.store.createLease(userId, amount, operationType, {\n idempotencyKey: leaseIdempotencyKey,\n billingMode: expectedPolicy.billingMode,\n floor: expectedPolicy.floor,\n maxConcurrent: expectedPolicy.maxConcurrent,\n ttlSeconds,\n model,\n metadata: options.metadata,\n feature,\n region,\n measures,\n dimensions,\n });\n\n if (result.error !== null) {\n if (result.error === \"quota_exceeded\") {\n await this.emitQuotaEvents(userId, leaseIdempotencyKey);\n }\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount,\n stage: \"reserve\",\n operationType,\n });\n raiseLeaseError(result.error, userId, amount);\n }\n\n this.logger.info(\"[CreditsService] reservation acquired\", {\n leaseId: result.leaseId,\n amount: result.amount,\n minimumBalance: result.minimumBalance,\n });\n this.emit(\"credits.reserved\", userId, {\n leaseId: result.leaseId,\n amount: result.amount,\n available: result.available,\n minimumBalance: result.minimumBalance,\n operationType,\n expiresAt: result.expiresAt,\n });\n await this.emitQuotaEvents(userId, leaseIdempotencyKey);\n return result;\n }\n\n /**\n * Charge the actual cost against a lease and finalize it.\n *\n * De-clamped: bills the full actual cost even if it exceeds the lease hold\n * (overdraft). Emits ``credits.deducted``, then low-balance and overdraft\n * signals as applicable.\n */\n async settle(\n userId: string,\n leaseId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: SettleOptions,\n ): Promise<DeductionResult> {\n rejectNativeCreditAmount(metricsOrAmount);\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] settle\", { leaseId });\n const idempotencyKey =\n options?.idempotencyKey === undefined\n ? `lease:${leaseId}:settle`\n : requireStableKey(options.idempotencyKey);\n const feature = options?.feature ?? null;\n const { amount, model } = await this.costOf(metricsOrAmount, userId, leaseId);\n const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };\n const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };\n const region = z.string().safeParse(dimensions.region).data ?? null;\n\n // Build ledger metadata with caller fields first and protected system fields last.\n const txMeta: CreditMetadata = {};\n if (isAmount(metricsOrAmount)) {\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) txMeta[k] = v;\n }\n }\n if (idempotencyKey) txMeta[\"idempotencyKey\"] = idempotencyKey;\n } else {\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) txMeta[k] = v;\n }\n }\n txMeta[\"operation\"] = metricsOrAmount.operation;\n txMeta[\"measures\"] = { ...(metricsOrAmount.measures ?? {}) };\n txMeta[\"dimensions\"] = { ...(metricsOrAmount.dimensions ?? {}) };\n txMeta[\"breakdownTotal\"] = amount.toString();\n if (idempotencyKey) txMeta[\"idempotencyKey\"] = idempotencyKey;\n }\n\n const result = await this.store.settleLease(userId, leaseId, amount, {\n idempotencyKey,\n feature,\n model,\n region,\n measures,\n dimensions,\n metadata: txMeta,\n });\n\n if (result.error !== null) {\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount,\n stage: \"settle\",\n leaseId,\n });\n if (result.error === \"expired_lease\") {\n this.emit(\"credits.lease_expired\", userId, { leaseId });\n }\n raiseLeaseError(result.error, userId, amount);\n }\n\n this.logger.info(\"[CreditsService] settled\", {\n leaseId,\n amount: result.amount,\n balanceAfter: result.balanceAfter,\n idempotent: result.idempotent,\n });\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n allowanceConsumed: result.allowanceConsumed,\n balanceAfter: result.balanceAfter,\n model,\n leaseId,\n idempotent: result.idempotent,\n });\n\n await this.balanceMonitor.afterCharge(userId, result);\n if (!result.idempotent) {\n await this.emitQuotaEvents(userId, idempotencyKey);\n await this.afterDeduction(userId, result);\n }\n return result;\n }\n\n /** Release a lease without charging; safe to repeat after failed or aborted work. */\n async release(userId: string, leaseId: string): Promise<ReleaseResult> {\n this.logger.debug(\"[CreditsService] release\", { leaseId });\n const result = await this.store.releaseLease(userId, leaseId);\n if (result.released) {\n this.logger.info(\"[CreditsService] lease released\", { leaseId, reason: result.reason });\n this.emit(\"credits.reservation_released\", userId, {\n leaseId,\n reason: result.reason,\n });\n }\n return result;\n }\n\n /** Extend an active lease's expiry without changing its captured policy. */\n async renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseSuccess> {\n const ttlSeconds = ttl ?? this.defaultTtl;\n this.logger.debug(\"[CreditsService] renew\", { leaseId, ttlSeconds });\n const result = await this.store.renewLease(userId, leaseId, ttlSeconds);\n if (result.error !== null) {\n if (result.error === \"expired_lease\") {\n this.emit(\"credits.lease_expired\", userId, { leaseId });\n }\n raiseLeaseError(result.error, userId, new Decimal(0));\n }\n return result;\n }\n\n /**\n * Advisory affordability check — UI only, non-locking, and potentially stale.\n *\n * Never use this as an admission gate; only ``reserve`` is authoritative.\n */\n async canAfford(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: CanAffordOptions,\n ): Promise<CanAffordResult> {\n rejectNativeCreditAmount(metricsOrAmount);\n await this.maybeLazyExpire(userId);\n const feature = options?.feature ?? null;\n const { amount: worstCase } = await this.costOf(metricsOrAmount, userId);\n const avail = await this.store.getAvailable(userId);\n let expectedPolicy;\n try {\n expectedPolicy = await this.expectedAdmissionPolicy(\n userId,\n options?.operationType ?? \"usage\",\n options?.billingMode,\n );\n } catch {\n return {\n affordable: false,\n spendable: avail.available,\n worstCase,\n reason: \"policy_unavailable\",\n };\n }\n let allowanceRemaining = new Decimal(0);\n try {\n allowanceRemaining =\n (await this.store.checkAllowance(userId))?.allowanceRemaining ?? new Decimal(0);\n } catch (error) {\n this.logger.debug(\"[CreditsService] allowance fetch failed in canAfford\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n const spendable = avail.available.plus(allowanceRemaining).minus(expectedPolicy.floor);\n\n let affordable = true;\n let reason: string | null = null;\n if (feature != null) {\n const check = await this.store.checkFeature(userId, feature);\n if (!check.hasFeature) {\n affordable = false;\n reason = \"feature_not_entitled\";\n }\n }\n if (affordable && spendable.lt(worstCase)) {\n affordable = false;\n reason = \"insufficient_credits\";\n }\n\n return { affordable, spendable, worstCase, reason };\n }\n\n /** Get a user's per-bucket credit balances (credit buckets). Thin pass-through, no event emission. */\n async getBucketBalances(userId: string): Promise<BucketBalancesResult> {\n await this.maybeLazyExpire(userId);\n return await this.store.getBucketBalances(userId);\n }\n\n /**\n * Get remaining free allowance for the current billing period.\n *\n * Convenience wrapper that routes through the manager so callers never need\n * to reach past it into the raw store. Returns `null` when the subject has no\n * active allowance policy.\n *\n * Window calculation is database-owned and supports the full normalized\n * policy tuple, including timezone and arbitrary interval counts.\n */\n async checkAllowance(userId: string): Promise<AllowanceResult | null> {\n return await this.store.checkAllowance(userId);\n }\n\n /**\n * One-call shortcut wiring reserve → doWork → settle.\n *\n * ``doWork`` runs the operation and returns ``{ result, actual }`` where\n * ``actual`` is the real usage metrics (or amount) to settle. On any exception\n * from ``doWork`` the lease is released and the error re-raised. For long jobs\n * ``doWork`` may call the configured lease TTL. A crash between reserve and settle is\n * covered by the lease TTL (and the store's reaper).\n */\n async runBilled<T>(\n userId: string,\n options: RunBilledOptions<T>,\n ): Promise<{ result: T; deduction: DeductionResult }> {\n const operationKey = requireStableKey(options.operationKey, \"operationKey\");\n const operation = await this.beginBilledOperation(userId, {\n estimate: options.estimate,\n operationKey,\n operationType: options.operationType,\n billingMode: options.billingMode,\n ttl: options.ttl,\n feature: options.feature,\n metadata: options.metadata,\n });\n\n let workResult: T;\n let actual: MetricsOrAmount;\n try {\n ({ result: workResult, actual } = await options.doWork());\n } catch (err) {\n await operation.release();\n throw err;\n }\n\n // Never release after work succeeds. A settlement failure may be a\n // transient/unknown-commit outcome and is safe to replay with operationKey.\n const deduction = await retryBursarOperation(() => operation.settle(actual), {\n maxAttempts: options.settlementAttempts,\n });\n return { result: workResult, deduction };\n }\n\n /**\n * Begin a replay-safe billable operation that can span framework callbacks.\n *\n * The operation key is namespaced into distinct reserve and settle keys, so\n * replaying the whole lifecycle cannot acquire a second hold.\n */\n async beginBilledOperation(\n userId: string,\n options: BeginBilledOperationOptions,\n ): Promise<BilledOperation> {\n const operationKey = requireStableKey(options.operationKey, \"operationKey\");\n const lease = await this.reserve(userId, options.estimate, {\n operationType: options.operationType,\n billingMode: options.billingMode,\n ttl: options.ttl,\n feature: options.feature,\n metadata: options.metadata,\n idempotencyKey: scopedStableKey(operationKey, \"reserve\"),\n });\n return {\n leaseId: lease.leaseId,\n operationKey,\n settle: async (actual, metadata) =>\n this.settle(userId, lease.leaseId, actual, {\n idempotencyKey: scopedStableKey(operationKey, \"settle\"),\n feature: options.feature,\n metadata: metadata ?? options.metadata,\n }),\n renew: async (ttl) => {\n await this.renew(userId, lease.leaseId, ttl);\n },\n release: async () => {\n await this.release(userId, lease.leaseId);\n },\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"lease-workflow.js","sourceRoot":"","sources":["../../src/credits/lease-workflow.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAGnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,q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ACL,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,YAAY;YACZ,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,CACjC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE;gBACzC,cAAc,EAAE,eAAe,CAAC,YAAY,EAAE,QAAQ,CAAC;gBACvD,OAAO,EAAE,OAAO,CAAC,OAAO;gBACxB,QAAQ,EAAE,QAAQ,IAAI,OAAO,CAAC,QAAQ;aACvC,CAAC;YACJ,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE;gBACnB,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;YAC/C,CAAC;YACD,OAAO,EAAE,KAAK,IAAI,EAAE;gBAClB,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;YAC5C,CAAC;SACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\nimport { retryBursarOperation } from \"../retry.js\";\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditEventType } from \"./events.js\";\nimport { LowBalanceMonitor } from \"./low-balance-monitor.js\";\nimport { CatalogRuntime } from \"./catalog-runtime.js\";\nimport { isAmount, rejectNativeCreditAmount } from \"./amount.js\";\nimport { raiseLeaseError } from \"./service-errors.js\";\nimport { requireStableKey, scopedStableKey } from \"../shared/idempotency.js\";\nimport type {\n CanAffordOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n MetricsOrAmount,\n PolicyPreset,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type { StructuredObject } from \"../shared/json.js\";\nimport type {\n AllowanceResult,\n BillingMode,\n BucketBalancesResult,\n CanAffordResult,\n CreditMetadata,\n DeductionResult,\n DeductionSuccess,\n LeaseSuccess,\n ReleaseResult,\n} from \"./types/index.js\";\n\nexport class CreditLeaseWorkflow {\n constructor(\n private readonly store: CreditStore,\n private readonly catalogRuntime: CatalogRuntime,\n private readonly logger: NormalizedLogger,\n private readonly balanceMonitor: LowBalanceMonitor,\n private readonly policy: PolicyPreset,\n private readonly overdraftFloor: Decimal | null,\n private readonly defaultMaxConcurrent: number | null,\n private readonly defaultTtl: number,\n private readonly emit: (type: CreditEventType, userId: string, data?: StructuredObject) => void,\n private readonly emitQuotaEvents: (userId: string, idempotencyKey: string) => Promise<void>,\n private readonly maybeLazyExpire: (userId: string) => Promise<void>,\n private readonly afterDeduction: (userId: string, result: DeductionSuccess) => Promise<void>,\n ) {}\n\n private async expectedAdmissionPolicy(\n userId: string,\n operationType: string,\n billingModeOverride?: BillingMode | null,\n ): Promise<{\n billingMode: BillingMode;\n floor: Decimal;\n maxConcurrent: number | null;\n }> {\n const plan = await this.store.getUserPlan(userId);\n const creditPolicy = plan.planId == null ? null : plan.creditPolicy;\n const planMode: BillingMode =\n plan.planId == null\n ? this.policy === \"overdraft\"\n ? \"overdraft\"\n : \"strict\"\n : creditPolicy?.type === \"credit_line\"\n ? \"overdraft\"\n : \"strict\";\n const operationAdmission =\n plan.planId == null ? null : (plan.admission?.operations[operationType] ?? null);\n const billingMode = billingModeOverride ?? planMode;\n const floor =\n billingMode === \"overdraft\"\n ? (creditPolicy?.creditLimit?.negated() ?? this.overdraftFloor ?? new Decimal(0))\n : new Decimal(0);\n return {\n billingMode,\n floor,\n maxConcurrent:\n plan.planId == null\n ? this.defaultMaxConcurrent\n : (operationAdmission?.maxInFlight ?? plan.admission?.maxInFlight ?? null),\n };\n }\n\n /**\n * Compute the credit cost and model from metrics, or pass a raw amount through.\n *\n * For {@link UsageMetrics} the cost is ``engine.calculate(...).total`` (exact\n * `Decimal`, no truncation); a raw amount is used as-is with no model.\n */\n private async costOf(\n metricsOrAmount: MetricsOrAmount,\n userId?: string | null,\n leaseId?: string | null,\n ): Promise<{ amount: Decimal; model: string | null }> {\n return this.catalogRuntime.costOf(metricsOrAmount, userId, leaseId);\n }\n\n /**\n * Atomically acquire a lease — the only authoritative admission control.\n *\n * Prices the estimate and delegates entitlement, quota, allowance, credit\n * policy, and concurrency enforcement to the database in one atomic call.\n */\n async reserve(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options: ReserveOptions,\n ): Promise<LeaseSuccess> {\n rejectNativeCreditAmount(metricsOrAmount);\n const leaseIdempotencyKey = requireStableKey(options?.idempotencyKey);\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] reserve\", {\n feature: options.feature,\n operationType: options.operationType,\n });\n const operationType =\n options.operationType ?? (isAmount(metricsOrAmount) ? \"usage\" : metricsOrAmount.operation);\n const expectedPolicy = await this.expectedAdmissionPolicy(\n userId,\n operationType,\n options.billingMode,\n );\n const priced = await this.costOf(metricsOrAmount, userId);\n const amount = priced.amount;\n const model = priced.model ?? options.model ?? null;\n const ttlSeconds = options.ttl != null ? options.ttl : this.defaultTtl;\n const feature = options.feature ?? null;\n const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };\n const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };\n const region = z.string().safeParse(dimensions.region).data ?? null;\n\n const result = await this.store.createLease(userId, amount, operationType, {\n idempotencyKey: leaseIdempotencyKey,\n billingMode: expectedPolicy.billingMode,\n floor: expectedPolicy.floor,\n maxConcurrent: expectedPolicy.maxConcurrent,\n ttlSeconds,\n model,\n metadata: options.metadata,\n feature,\n region,\n measures,\n dimensions,\n });\n\n if (result.error !== null) {\n if (result.error === \"quota_exceeded\") {\n await this.emitQuotaEvents(userId, leaseIdempotencyKey);\n }\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount,\n stage: \"reserve\",\n operationType,\n });\n raiseLeaseError(result.error, userId, amount);\n }\n\n this.logger.info(\"[CreditsService] reservation acquired\", {\n leaseId: result.leaseId,\n amount: result.amount,\n minimumBalance: result.minimumBalance,\n });\n this.emit(\"credits.reserved\", userId, {\n leaseId: result.leaseId,\n amount: result.amount,\n available: result.available,\n minimumBalance: result.minimumBalance,\n operationType,\n expiresAt: result.expiresAt,\n });\n await this.emitQuotaEvents(userId, leaseIdempotencyKey);\n return result;\n }\n\n /**\n * Charge the actual cost against a lease and finalize it.\n *\n * De-clamped: bills the full actual cost even if it exceeds the lease hold\n * (overdraft). Emits ``credits.deducted``, then low-balance and overdraft\n * signals as applicable.\n */\n async settle(\n userId: string,\n leaseId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: SettleOptions,\n ): Promise<DeductionResult> {\n rejectNativeCreditAmount(metricsOrAmount);\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] settle\", { leaseId });\n const idempotencyKey =\n options?.idempotencyKey === undefined\n ? `lease:${leaseId}:settle`\n : requireStableKey(options.idempotencyKey);\n const feature = options?.feature ?? null;\n const { amount, model } = await this.costOf(metricsOrAmount, userId, leaseId);\n const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };\n const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };\n const region = z.string().safeParse(dimensions.region).data ?? null;\n\n // Build ledger metadata with caller fields first and protected system fields last.\n const txMeta: CreditMetadata = {};\n if (isAmount(metricsOrAmount)) {\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) txMeta[k] = v;\n }\n }\n if (idempotencyKey) txMeta[\"idempotencyKey\"] = idempotencyKey;\n } else {\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) txMeta[k] = v;\n }\n }\n txMeta[\"operation\"] = metricsOrAmount.operation;\n txMeta[\"measures\"] = { ...(metricsOrAmount.measures ?? {}) };\n txMeta[\"dimensions\"] = { ...(metricsOrAmount.dimensions ?? {}) };\n txMeta[\"breakdownTotal\"] = amount.toString();\n if (idempotencyKey) txMeta[\"idempotencyKey\"] = idempotencyKey;\n }\n\n const result = await this.store.settleLease(userId, leaseId, amount, {\n idempotencyKey,\n feature,\n model,\n region,\n measures,\n dimensions,\n metadata: txMeta,\n });\n\n if (result.error !== null) {\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount,\n stage: \"settle\",\n leaseId,\n });\n if (result.error === \"expired_lease\") {\n this.emit(\"credits.lease_expired\", userId, { leaseId });\n }\n raiseLeaseError(result.error, userId, amount);\n }\n\n this.logger.info(\"[CreditsService] settled\", {\n leaseId,\n amount: result.amount,\n balanceAfter: result.balanceAfter,\n idempotent: result.idempotent,\n });\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n allowanceConsumed: result.allowanceConsumed,\n balanceAfter: result.balanceAfter,\n model,\n leaseId,\n idempotent: result.idempotent,\n });\n\n await this.balanceMonitor.afterCharge(userId, result);\n if (!result.idempotent) {\n await this.emitQuotaEvents(userId, idempotencyKey);\n await this.afterDeduction(userId, result);\n }\n return result;\n }\n\n /** Release a lease without charging; safe to repeat after failed or aborted work. */\n async release(userId: string, leaseId: string): Promise<ReleaseResult> {\n this.logger.debug(\"[CreditsService] release\", { leaseId });\n const result = await this.store.releaseLease(userId, leaseId);\n if (result.released) {\n this.logger.info(\"[CreditsService] lease released\", { leaseId, reason: result.reason });\n this.emit(\"credits.reservation_released\", userId, {\n leaseId,\n reason: result.reason,\n });\n }\n return result;\n }\n\n /** Extend an active lease's expiry without changing its captured policy. */\n async renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseSuccess> {\n const ttlSeconds = ttl ?? this.defaultTtl;\n this.logger.debug(\"[CreditsService] renew\", { leaseId, ttlSeconds });\n const result = await this.store.renewLease(userId, leaseId, ttlSeconds);\n if (result.error !== null) {\n if (result.error === \"expired_lease\") {\n this.emit(\"credits.lease_expired\", userId, { leaseId });\n }\n raiseLeaseError(result.error, userId, new Decimal(0));\n }\n return result;\n }\n\n /**\n * Advisory affordability check — UI only, non-locking, and potentially stale.\n *\n * Never use this as an admission gate; only ``reserve`` is authoritative.\n */\n async canAfford(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: CanAffordOptions,\n ): Promise<CanAffordResult> {\n rejectNativeCreditAmount(metricsOrAmount);\n await this.maybeLazyExpire(userId);\n const feature = options?.feature ?? null;\n const { amount: worstCase } = await this.costOf(metricsOrAmount, userId);\n const avail = await this.store.getAvailable(userId);\n let expectedPolicy;\n try {\n expectedPolicy = await this.expectedAdmissionPolicy(\n userId,\n options?.operationType ?? \"usage\",\n options?.billingMode,\n );\n } catch {\n return {\n affordable: false,\n spendable: avail.available,\n worstCase,\n reason: \"policy_unavailable\",\n };\n }\n let allowanceRemaining = new Decimal(0);\n try {\n allowanceRemaining =\n (await this.store.checkAllowance(userId))?.allowanceRemaining ?? new Decimal(0);\n } catch (error) {\n this.logger.debug(\"[CreditsService] allowance fetch failed in canAfford\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n const spendable = avail.available.plus(allowanceRemaining).minus(expectedPolicy.floor);\n\n let affordable = true;\n let reason: string | null = null;\n if (feature != null) {\n const check = await this.store.checkFeature(userId, feature);\n if (!check.hasFeature) {\n affordable = false;\n reason = \"feature_not_entitled\";\n }\n }\n if (affordable && spendable.lt(worstCase)) {\n affordable = false;\n reason = \"insufficient_credits\";\n }\n\n return { affordable, spendable, worstCase, reason };\n }\n\n /** Get a user's per-bucket credit balances (credit buckets). Thin pass-through, no event emission. */\n async getBucketBalances(userId: string): Promise<BucketBalancesResult> {\n await this.maybeLazyExpire(userId);\n return await this.store.getBucketBalances(userId);\n }\n\n /**\n * Get remaining free allowance for the current billing period.\n *\n * Convenience wrapper that routes through the manager so callers never need\n * to reach past it into the raw store. Returns `null` when the subject has no\n * active allowance policy.\n *\n * Window calculation is database-owned and supports the full normalized\n * policy tuple, including timezone and arbitrary interval counts.\n */\n async checkAllowance(userId: string): Promise<AllowanceResult | null> {\n return await this.store.checkAllowance(userId);\n }\n\n /**\n * One-call shortcut wiring reserve → doWork → settle.\n *\n * ``doWork`` runs the operation and returns ``{ result, actual }`` where\n * ``actual`` is the real usage metrics (or amount) to settle. On any exception\n * from ``doWork`` the lease is released and the error re-raised. For long jobs\n * ``doWork`` may call the configured lease TTL. A crash between reserve and settle is\n * covered by the lease TTL (and the store's reaper).\n */\n async runBilled<T>(\n userId: string,\n options: RunBilledOptions<T>,\n ): Promise<{ result: T; deduction: DeductionResult }> {\n const operationKey = requireStableKey(options.operationKey, \"operationKey\");\n const operation = await this.beginBilledOperation(userId, {\n estimate: options.estimate,\n operationKey,\n operationType: options.operationType,\n billingMode: options.billingMode,\n ttl: options.ttl,\n feature: options.feature,\n metadata: options.metadata,\n });\n\n let workResult: T;\n let actual: MetricsOrAmount;\n try {\n ({ result: workResult, actual } = await options.doWork());\n } catch (err) {\n await operation.release();\n throw err;\n }\n\n // Never release after work succeeds. A settlement failure may be a\n // transient/unknown-commit outcome and is safe to replay with operationKey.\n const deduction = await retryBursarOperation(() => operation.settle(actual), {\n maxAttempts: options.settlementAttempts,\n });\n return { result: workResult, deduction };\n }\n\n /**\n * Begin a replay-safe billable operation that can span framework callbacks.\n *\n * The operation key is namespaced into distinct reserve and settle keys, so\n * replaying the whole lifecycle cannot acquire a second hold.\n */\n async beginBilledOperation(\n userId: string,\n options: BeginBilledOperationOptions,\n ): Promise<BilledOperation> {\n const operationKey = requireStableKey(options.operationKey, \"operationKey\");\n const lease = await this.reserve(userId, options.estimate, {\n operationType: options.operationType,\n billingMode: options.billingMode,\n ttl: options.ttl,\n feature: options.feature,\n metadata: options.metadata,\n idempotencyKey: scopedStableKey(operationKey, \"reserve\"),\n });\n return {\n leaseId: lease.leaseId,\n operationKey,\n settle: async (actual, metadata) =>\n this.settle(userId, lease.leaseId, actual, {\n idempotencyKey: scopedStableKey(operationKey, \"settle\"),\n feature: options.feature,\n metadata: metadata ?? options.metadata,\n }),\n renew: async (ttl) => {\n await this.renew(userId, lease.leaseId, ttl);\n },\n release: async () => {\n await this.release(userId, lease.leaseId);\n },\n };\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"low-balance-monitor.d.ts","sourceRoot":"","sources":["../../src/credits/low-balance-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAGrC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,KAAK,EAAe,eAAe,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAK3D,KAAK,eAAe,GAAG,CAAC,IAAI,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,gBAAgB,KAAK,IAAI,CAAC;AAEhG;;;;;GAKG;AACH,qBAAa,iBAAiB;IAO1B,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAPzB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAmB;IAC9C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAwD;IAChF,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAgC;
|
|
1
|
+
{"version":3,"file":"low-balance-monitor.d.ts","sourceRoot":"","sources":["../../src/credits/low-balance-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAGrC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,KAAK,EAAe,eAAe,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,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AAC;YACF,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,CAAC,CAAC;QAChD,CAAC;IACH,CAAC;IAEO,KAAK,CAAC,IAAI,CAAC,MAAc,EAAE,OAAgB,EAAE,SAAkB;QACrE,MAAM,IAAI,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;QACpC,IAAI,CAAC,IAAI,CAAC,qBAAqB,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;QAC/C,IAAI,CAAC,IAAI,CAAC,OAAO;YAAE,OAAO;QAE1B,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,OAAO,CAAC;gBACjB,IAAI,EAAE,qBAAqB;gBAC3B,SAAS,EAAE,IAAI,IAAI,EAAE;gBACrB,MAAM;gBACN,IAAI;aACL,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,8CAA8C,EAAE;gBAChE,MAAM;gBACN,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;aAC9D,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { LRUCache } from \"lru-cache\";\n\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { StructuredObject } from \"../shared/json.js\";\nimport type { CreditEvent, CreditEventType } from \"./events.js\";\nimport type { DeductionSuccess } from \"./types/index.js\";\nimport type { LowBalanceConfig } from \"./service-types.js\";\nimport { toDecimal } from \"./amount.js\";\n\nconst DEFAULT_MAX_TRACKED_USERS = 100_000;\n\ntype EmitCreditEvent = (type: CreditEventType, userId: string, data?: StructuredObject) => void;\n\n/**\n * Owns edge-trigger state for low-balance and overdraft notifications.\n *\n * Keeping this state outside CreditsService makes the event semantics\n * independently testable and keeps the service focused on orchestration.\n */\nexport class LowBalanceMonitor {\n private readonly thresholds: Decimal[] | null;\n private readonly handler: ((event: CreditEvent) => void | Promise<void>) | null;\n private readonly breachedByUser: LRUCache<string, Set<string>>;\n\n constructor(\n config: LowBalanceConfig | null | undefined,\n private readonly emit: EmitCreditEvent,\n private readonly logger: NormalizedLogger,\n ) {\n this.thresholds = config?.thresholds?.length\n ? config.thresholds.map(toDecimal).sort((left, right) => right.comparedTo(left))\n : null;\n this.handler = config?.onTrigger ?? null;\n const maxTrackedUsers = config?.maxTrackedUsers ?? DEFAULT_MAX_TRACKED_USERS;\n if (!Number.isSafeInteger(maxTrackedUsers) || maxTrackedUsers < 1) {\n throw new RangeError(\"lowBalance.maxTrackedUsers must be a positive safe integer\");\n }\n this.breachedByUser = new LRUCache({ max: maxTrackedUsers });\n }\n\n rearmAfterCredit(userId: string, balance: Decimal): void {\n if (!this.thresholds) return;\n const breached = this.breachedByUser.get(userId) ?? new Set<string>();\n for (const threshold of this.thresholds) {\n if (balance.gt(threshold)) breached.delete(threshold.toString());\n }\n if (breached.size === 0) {\n this.breachedByUser.delete(userId);\n } else {\n this.breachedByUser.set(userId, breached);\n }\n }\n\n async afterCharge(userId: string, result: DeductionSuccess): Promise<void> {\n if (result.idempotent) return;\n if (result.balanceAfter.lt(0)) {\n this.emit(\"credits.overdraft\", userId, {\n balance: result.balanceAfter,\n amount: result.amount,\n });\n }\n await this.signalCrossing(userId, result.balanceAfter.plus(result.amount), result.balanceAfter);\n }\n\n async signalCrossing(\n userId: string,\n balanceBefore: Decimal,\n balanceAfter: Decimal,\n ): Promise<void> {\n if (!this.thresholds) {\n const threshold = new Decimal(0);\n if (balanceBefore.gt(threshold) && balanceAfter.lte(threshold)) {\n await this.fire(userId, balanceAfter, threshold);\n }\n return;\n }\n\n const breached = this.breachedByUser.get(userId) ?? new Set<string>();\n const newlyCrossed: Decimal[] = [];\n for (const threshold of this.thresholds) {\n if (balanceAfter.lte(threshold)) {\n if (!breached.has(threshold.toString())) {\n breached.add(threshold.toString());\n newlyCrossed.push(threshold);\n }\n } else {\n breached.delete(threshold.toString());\n }\n }\n if (breached.size === 0) {\n this.breachedByUser.delete(userId);\n } else {\n this.breachedByUser.set(userId, breached);\n }\n if (newlyCrossed.length > 0) {\n const lowest = newlyCrossed.reduce((minimum, threshold) =>\n threshold.lt(minimum) ? threshold : minimum,\n );\n await this.fire(userId, balanceAfter, lowest);\n }\n }\n\n private async fire(userId: string, balance: Decimal, threshold: Decimal): Promise<void> {\n const data = { balance, threshold };\n this.emit(\"credits.low_balance\", userId, data);\n if (!this.handler) return;\n\n try {\n await this.handler({\n type: \"credits.low_balance\",\n timestamp: new Date(),\n userId,\n data,\n });\n } catch (error) {\n this.logger.error(\"[CreditsService] onLowBalance handler failed\", {\n userId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analytics.d.ts","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/analytics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AAelE,QAAA,MAAM,oBAAoB;;;;kBAMf,CAAC;AAEZ,QAAA,MAAM,qBAAqB;;;;kBAMhB,CAAC;AAEZ,QAAA,MAAM,gBAAgB;;;kBAA0E,CAAC;AAEjG,QAAA,MAAM,mBAAmB;;;;kBAMd,CAAC;AAEZ,QAAA,MAAM,uBAAuB;;;;;;kBAQlB,CAAC;AAEZ,QAAA,MAAM,oBAAoB;;;;;;;;;;;kBAaf,CAAC;AAEZ,QAAA,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;kBAkBf,CAAC;AAEZ,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAClE,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,C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../errors.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { isPostgresRow, type PostgresRow, type PostgresValue } from \"../../../shared/json.js\";\nimport { optionalRecordRow, requireRow, safeParse } from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst count = z.union([\n z.number().int().nonnegative(),\n z.string().regex(/^\\d+$/).transform(Number),\n]);\nconst timestamp = z.union([z.string().min(1), z.date().transform((value) => value.toISOString())]);\nconst calendarDate = z.union([\n z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),\n z.date().transform((value) => value.toISOString().slice(0, 10)),\n]);\n\nconst SpendByUserRowSchema = z\n .object({\n user_id: z.string().min(1),\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst SpendByModelRowSchema = z\n .object({\n model: z.string().min(1),\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst TopUserRowSchema = z.object({ user_id: z.string().min(1), total_spend: decimal }).strict();\n\nconst DailySpendRowSchema = z\n .object({\n date: calendarDate,\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst AggregateStatsRowSchema = z\n .object({\n total_credits_consumed: decimal,\n active_users: count,\n avg_daily_spend: decimal,\n top_model: z.string().min(1).nullable(),\n top_user: z.string().min(1).nullable(),\n })\n .strict();\n\nconst LedgerEntryRowSchema = z\n .object({\n entry_id: z.string(),\n account_id: z.string(),\n actor_user_id: z.string().nullable(),\n amount: decimal,\n entry_type: z.string(),\n operation: z.string(),\n reference_entry_id: z.string().nullable(),\n idempotency_key: z.string().nullable(),\n metadata: z.record(z.string(), z.json()).nullable(),\n created_at: timestamp,\n })\n .strict();\n\nconst UsageChargeRowSchema = z\n .object({\n usage_id: z.string(),\n account_id: z.string(),\n operation: z.string(),\n requested: decimal,\n charged: decimal,\n allowance_requested: decimal,\n allowance_covered: decimal,\n billing_disposition: z.enum([\"billable\", \"record_only\"]),\n feature: z.string().nullable(),\n model: z.string().nullable(),\n region: z.string().nullable(),\n event_at: timestamp,\n idempotency_key: z.string(),\n metadata: z.record(z.string(), z.json()).nullable(),\n created_at: timestamp,\n })\n .strict();\n\nexport type SpendByUserRow = z.infer<typeof SpendByUserRowSchema>;\nexport type SpendByModelRow = z.infer<typeof SpendByModelRowSchema>;\nexport type TopUserRow = z.infer<typeof TopUserRowSchema>;\nexport type DailySpendRow = z.infer<typeof DailySpendRowSchema>;\nexport type AggregateStatsRow = z.infer<typeof AggregateStatsRowSchema>;\nexport type LedgerEntryRow = z.infer<typeof LedgerEntryRowSchema>;\nexport type UsageChargeRow = z.infer<typeof UsageChargeRowSchema>;\n\nfunction requireAnalyticsRow(value: PostgresValue, context: string): PostgresRow {\n if (!isPostgresRow(value)) {\n throw new StoreError(`${context}: expected an object result row`);\n }\n return value;\n}\n\nexport class AnalyticsRepository {\n constructor(private readonly callproc: CallProc) {}\n\n async spendByUser(start: string, end: string): Promise<SpendByUserRow[]> {\n const rows = await this.callproc(\"spend_by_user\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.spendByUser\");\n return safeParse(\n SpendByUserRowSchema,\n { user_id: row.subject_id, total_spend: row.total_spend, entry_count: row.charge_count },\n \"AnalyticsRepository.spendByUser\",\n );\n });\n }\n\n async spendByModel(start: string, end: string): Promise<SpendByModelRow[]> {\n const rows = await this.callproc(\"spend_by_model\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.spendByModel\");\n return safeParse(\n SpendByModelRowSchema,\n { model: row.model, total_spend: row.total_spend, entry_count: row.charge_count },\n \"AnalyticsRepository.spendByModel\",\n );\n });\n }\n\n async topUsers(limit: number, start: string, end: string): Promise<TopUserRow[]> {\n const rows = await this.callproc(\"spend_by_user\", [start, end]);\n return (rows ?? []).slice(0, limit).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.topUsers\");\n return safeParse(\n TopUserRowSchema,\n { user_id: row.subject_id, total_spend: row.total_spend },\n \"AnalyticsRepository.topUsers\",\n );\n });\n }\n\n async dailySpend(start: string, end: string): Promise<DailySpendRow[]> {\n const rows = await this.callproc(\"daily_spend\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.dailySpend\");\n return safeParse(\n DailySpendRowSchema,\n { date: row.day, total_spend: row.total_spend, entry_count: row.charge_count },\n \"AnalyticsRepository.dailySpend\",\n );\n });\n }\n\n async aggregateStats(start: string, end: string): Promise<AggregateStatsRow> {\n const rows = await this.callproc(\"aggregate_usage_stats\", [start, end]);\n return safeParse(\n AggregateStatsRowSchema,\n requireRow(rows, \"AnalyticsRepository.aggregateStats\"),\n \"AnalyticsRepository.aggregateStats\",\n );\n }\n\n async listLedgerEntries(\n userId: string,\n entryTypes: string[] | null,\n fromDate: string | null,\n toDate: string | null,\n limit: number,\n cursorCreatedAt: string | null,\n cursorEntryId: string | null,\n usageOnly = false,\n ): Promise<LedgerEntryRow[]> {\n if ((cursorCreatedAt == null) !== (cursorEntryId == null)) {\n throw new Error(\"ledger cursor requires both createdAt and entryId\");\n }\n const rows = await this.callproc(\"list_ledger\", [\n userId,\n cursorCreatedAt,\n cursorEntryId,\n limit,\n entryTypes,\n fromDate,\n toDate,\n usageOnly,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(LedgerEntryRowSchema, row, \"AnalyticsRepository.listLedgerEntries\"),\n );\n }\n\n async getLedgerEntry(userId: string, entryId: string): Promise<LedgerEntryRow | null> {\n const rows = await this.callproc(\"get_ledger_entry\", [userId, entryId]);\n const row = optionalRecordRow(rows, \"AnalyticsRepository.getLedgerEntry\");\n return row === null\n ? null\n : safeParse(LedgerEntryRowSchema, row, \"AnalyticsRepository.getLedgerEntry\");\n }\n\n async listUsageCharges(\n userId: string,\n fromDate: string | null,\n toDate: string | null,\n limit: number,\n cursorEventAt: string | null,\n cursorUsageId: string | null,\n includeRecordOnly: boolean,\n ): Promise<UsageChargeRow[]> {\n if ((cursorEventAt == null) !== (cursorUsageId == null)) {\n throw new Error(\"usage charge cursor requires both eventAt and usageId\");\n }\n const rows = await this.callproc(\"list_usage_charges\", [\n userId,\n cursorEventAt,\n cursorUsageId,\n limit,\n fromDate,\n toDate,\n includeRecordOnly,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(UsageChargeRowSchema, row, \"AnalyticsRepository.listUsageCharges\"),\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"analytics.js","sourceRoot":"","sources":["../../../../src/credits/postgres/repositories/analytics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EAAE,aAAa,EAAwC,MAAM,yBAAyB,CAAC;AAC9F,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,wCAAwC,CAAC;AAElG,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,CAAU,CAAC,CAAC;AAC3E,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC;IACpB,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE;IAC9B,CAAC,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,SAAS,CAAC,MAAM,CAAC;CAC5C,CAAC,CAAC;AACH,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,CAAC;AACnG,MAAM,Y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EAAE,OAAe;QAClD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,kBAAkB,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;QACxE,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,EAAE,oCAAoC,CAAC,CAAC;QAC1E,OAAO,GAAG,KAAK,IAAI;YACjB,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,SAAS,CAAC,oBAAoB,EAAE,GAAG,EAAE,oCAAoC,CAAC,CAAC;IACjF,CAAC;IAED,KAAK,CAAC,gBAAgB,CACpB,MAAc,EACd,QAAuB,EACvB,MAAqB,EACrB,KAAa,EACb,aAA4B,EAC5B,aAA4B,EAC5B,iBAA0B;QAE1B,IAAI,CAAC,aAAa,IAAI,IAAI,CAAC,KAAK,CAAC,aAAa,IAAI,IAAI,CAAC,EAAE,CAAC;YACxD,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;QAC3E,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,oBAAoB,EAAE;YACrD,MAAM;YACN,aAAa;YACb,aAAa;YACb,KAAK;YACL,QAAQ;YACR,MAAM;YACN,iBAAiB;SAClB,CAAC,CAAC;QACH,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAC9B,SAAS,CAAC,oBAAoB,EAAE,GAAG,EAAE,sCAAsC,CAAC,CAC7E,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\nimport { StoreError } from \"../../../errors.js\";\nimport type { CallProc } from \"../../../shared/postgres-types.js\";\nimport { isPostgresRow, type PostgresRow, type PostgresValue } from \"../../../shared/json.js\";\nimport { optionalRecordRow, requireRow, safeParse } from \"../../../shared/postgres-validation.js\";\n\nconst decimal = z.union([z.string().min(1), z.number().finite()] as const);\nconst count = z.union([\n z.number().int().nonnegative(),\n z.string().regex(/^\\d+$/).transform(Number),\n]);\nconst timestamp = z.union([z.string().min(1), z.date().transform((value) => value.toISOString())]);\nconst calendarDate = z.union([\n z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),\n z.date().transform((value) => value.toISOString().slice(0, 10)),\n]);\n\nconst SpendByUserRowSchema = z\n .object({\n user_id: z.string().min(1),\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst SpendByModelRowSchema = z\n .object({\n model: z.string().min(1),\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst TopUserRowSchema = z.object({ user_id: z.string().min(1), total_spend: decimal }).strict();\n\nconst DailySpendRowSchema = z\n .object({\n date: calendarDate,\n total_spend: decimal,\n entry_count: count,\n })\n .strict();\n\nconst AggregateStatsRowSchema = z\n .object({\n total_credits_consumed: decimal,\n active_users: count,\n avg_daily_spend: decimal,\n top_model: z.string().min(1).nullable(),\n top_user: z.string().min(1).nullable(),\n })\n .strict();\n\nconst LedgerEntryRowSchema = z\n .object({\n entry_id: z.string(),\n account_id: z.string(),\n actor_user_id: z.string().nullable(),\n amount: decimal,\n entry_type: z.string(),\n operation: z.string(),\n reference_entry_id: z.string().nullable(),\n idempotency_key: z.string().nullable(),\n metadata: z.record(z.string(), z.json()).nullable(),\n created_at: timestamp,\n })\n .strict();\n\nconst UsageChargeRowSchema = z\n .object({\n usage_id: z.string(),\n account_id: z.string(),\n operation: z.string(),\n requested: decimal,\n charged: decimal,\n allowance_requested: decimal,\n allowance_covered: decimal,\n billing_disposition: z.enum([\"billable\", \"record_only\"]),\n feature: z.string().nullable(),\n model: z.string().nullable(),\n region: z.string().nullable(),\n event_at: timestamp,\n idempotency_key: z.string(),\n metadata: z.record(z.string(), z.json()).nullable(),\n created_at: timestamp,\n })\n .strict();\n\nexport type SpendByUserRow = z.infer<typeof SpendByUserRowSchema>;\nexport type SpendByModelRow = z.infer<typeof SpendByModelRowSchema>;\nexport type TopUserRow = z.infer<typeof TopUserRowSchema>;\nexport type DailySpendRow = z.infer<typeof DailySpendRowSchema>;\nexport type AggregateStatsRow = z.infer<typeof AggregateStatsRowSchema>;\nexport type LedgerEntryRow = z.infer<typeof LedgerEntryRowSchema>;\nexport type UsageChargeRow = z.infer<typeof UsageChargeRowSchema>;\n\nfunction requireAnalyticsRow(value: PostgresValue, context: string): PostgresRow {\n if (!isPostgresRow(value)) {\n throw new StoreError(`${context}: expected an object result row`);\n }\n return value;\n}\n\nexport class AnalyticsRepository {\n constructor(private readonly callproc: CallProc) {}\n\n async spendByUser(start: string, end: string): Promise<SpendByUserRow[]> {\n const rows = await this.callproc(\"spend_by_user\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.spendByUser\");\n return safeParse(\n SpendByUserRowSchema,\n { user_id: row.subject_id, total_spend: row.total_spend, entry_count: row.charge_count },\n \"AnalyticsRepository.spendByUser\",\n );\n });\n }\n\n async spendByModel(start: string, end: string): Promise<SpendByModelRow[]> {\n const rows = await this.callproc(\"spend_by_model\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.spendByModel\");\n return safeParse(\n SpendByModelRowSchema,\n { model: row.model, total_spend: row.total_spend, entry_count: row.charge_count },\n \"AnalyticsRepository.spendByModel\",\n );\n });\n }\n\n async topUsers(limit: number, start: string, end: string): Promise<TopUserRow[]> {\n const rows = await this.callproc(\"spend_by_user\", [start, end]);\n return (rows ?? []).slice(0, limit).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.topUsers\");\n return safeParse(\n TopUserRowSchema,\n { user_id: row.subject_id, total_spend: row.total_spend },\n \"AnalyticsRepository.topUsers\",\n );\n });\n }\n\n async dailySpend(start: string, end: string): Promise<DailySpendRow[]> {\n const rows = await this.callproc(\"daily_spend\", [start, end]);\n return (rows ?? []).map((raw) => {\n const row = requireAnalyticsRow(raw, \"AnalyticsRepository.dailySpend\");\n return safeParse(\n DailySpendRowSchema,\n { date: row.day, total_spend: row.total_spend, entry_count: row.charge_count },\n \"AnalyticsRepository.dailySpend\",\n );\n });\n }\n\n async aggregateStats(start: string, end: string): Promise<AggregateStatsRow> {\n const rows = await this.callproc(\"aggregate_usage_stats\", [start, end]);\n return safeParse(\n AggregateStatsRowSchema,\n requireRow(rows, \"AnalyticsRepository.aggregateStats\"),\n \"AnalyticsRepository.aggregateStats\",\n );\n }\n\n async listLedgerEntries(\n userId: string,\n entryTypes: string[] | null,\n fromDate: string | null,\n toDate: string | null,\n limit: number,\n cursorCreatedAt: string | null,\n cursorEntryId: string | null,\n usageOnly = false,\n ): Promise<LedgerEntryRow[]> {\n if ((cursorCreatedAt == null) !== (cursorEntryId == null)) {\n throw new Error(\"ledger cursor requires both createdAt and entryId\");\n }\n const rows = await this.callproc(\"list_ledger\", [\n userId,\n cursorCreatedAt,\n cursorEntryId,\n limit,\n entryTypes,\n fromDate,\n toDate,\n usageOnly,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(LedgerEntryRowSchema, row, \"AnalyticsRepository.listLedgerEntries\"),\n );\n }\n\n async getLedgerEntry(userId: string, entryId: string): Promise<LedgerEntryRow | null> {\n const rows = await this.callproc(\"get_ledger_entry\", [userId, entryId]);\n const row = optionalRecordRow(rows, \"AnalyticsRepository.getLedgerEntry\");\n return row === null\n ? null\n : safeParse(LedgerEntryRowSchema, row, \"AnalyticsRepository.getLedgerEntry\");\n }\n\n async listUsageCharges(\n userId: string,\n fromDate: string | null,\n toDate: string | null,\n limit: number,\n cursorEventAt: string | null,\n cursorUsageId: string | null,\n includeRecordOnly: boolean,\n ): Promise<UsageChargeRow[]> {\n if ((cursorEventAt == null) !== (cursorUsageId == null)) {\n throw new Error(\"usage charge cursor requires both eventAt and usageId\");\n }\n const rows = await this.callproc(\"list_usage_charges\", [\n userId,\n cursorEventAt,\n cursorUsageId,\n limit,\n fromDate,\n toDate,\n includeRecordOnly,\n ]);\n return (rows ?? []).map((row) =>\n safeParse(UsageChargeRowSchema, row, \"AnalyticsRepository.listUsageCharges\"),\n );\n }\n}\n"]}
|