@zonastery/bursar 2.0.3 → 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-port.d.ts +3 -2
- package/dist/billing/auto-recharge-port.d.ts.map +1 -1
- package/dist/billing/auto-recharge-port.js.map +1 -1
- package/dist/billing/auto-recharge-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js +3 -3
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-service.d.ts +3 -2
- package/dist/billing/billing-service.d.ts.map +1 -1
- package/dist/billing/billing-service.js +2 -10
- package/dist/billing/billing-service.js.map +1 -1
- package/dist/billing/billing-store.d.ts +6 -6
- package/dist/billing/billing-store.d.ts.map +1 -1
- package/dist/billing/billing-store.js.map +1 -1
- package/dist/billing/contracts.d.ts +8 -7
- package/dist/billing/contracts.d.ts.map +1 -1
- package/dist/billing/contracts.js.map +1 -1
- package/dist/billing/event-handlers.d.ts +5 -9
- package/dist/billing/event-handlers.d.ts.map +1 -1
- package/dist/billing/event-handlers.js +191 -285
- package/dist/billing/event-handlers.js.map +1 -1
- package/dist/billing/event-processor.d.ts +1 -1
- package/dist/billing/event-processor.d.ts.map +1 -1
- package/dist/billing/event-processor.js +32 -23
- package/dist/billing/event-processor.js.map +1 -1
- package/dist/billing/financial-event-handlers.d.ts +3 -9
- package/dist/billing/financial-event-handlers.d.ts.map +1 -1
- package/dist/billing/financial-event-handlers.js +10 -12
- package/dist/billing/financial-event-handlers.js.map +1 -1
- package/dist/billing/index.d.ts +1 -1
- package/dist/billing/index.d.ts.map +1 -1
- package/dist/billing/index.js.map +1 -1
- package/dist/billing/management.d.ts +3 -2
- 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 +2 -1
- package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js +58 -40
- 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 +2 -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 +2 -1
- package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/invoice.js +8 -12
- 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 +5 -0
- package/dist/billing/postgres/repositories/offer.js.map +1 -1
- package/dist/billing/postgres/repositories/payment.d.ts +4 -4
- package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/payment.js +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 +1 -9
- package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
- package/dist/billing/postgres/repositories/subscription.d.ts +11 -11
- package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/subscription.js +29 -30
- 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 +6 -5
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +15 -13
- package/dist/billing/postgres/store.js.map +1 -1
- package/dist/billing/types/auto-recharge.d.ts +2 -1
- package/dist/billing/types/auto-recharge.d.ts.map +1 -1
- package/dist/billing/types/auto-recharge.js.map +1 -1
- package/dist/billing/types/documents.d.ts +2 -1
- package/dist/billing/types/documents.d.ts.map +1 -1
- package/dist/billing/types/documents.js.map +1 -1
- package/dist/billing/types/events.d.ts +3 -2
- package/dist/billing/types/events.d.ts.map +1 -1
- package/dist/billing/types/events.js +73 -39
- package/dist/billing/types/events.js.map +1 -1
- package/dist/billing/types/subscriptions.d.ts +4 -1
- package/dist/billing/types/subscriptions.d.ts.map +1 -1
- package/dist/billing/types/subscriptions.js.map +1 -1
- package/dist/breakdown.d.ts +3 -2
- package/dist/breakdown.d.ts.map +1 -1
- package/dist/breakdown.js.map +1 -1
- package/dist/bursar.d.ts.map +1 -1
- package/dist/bursar.js +4 -3
- package/dist/bursar.js.map +1 -1
- package/dist/catalog.d.ts.map +1 -1
- package/dist/catalog.js +45 -42
- package/dist/catalog.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 +11 -6
- 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 +16 -22
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts.map +1 -1
- package/dist/commerce/types.js.map +1 -1
- package/dist/config/parse-access.d.ts +5 -2
- package/dist/config/parse-access.d.ts.map +1 -1
- package/dist/config/parse-access.js +60 -41
- package/dist/config/parse-access.js.map +1 -1
- package/dist/config/parse-commerce.d.ts +2 -1
- package/dist/config/parse-commerce.d.ts.map +1 -1
- package/dist/config/parse-commerce.js +49 -29
- package/dist/config/parse-commerce.js.map +1 -1
- package/dist/config/parse-credits.d.ts +2 -1
- package/dist/config/parse-credits.d.ts.map +1 -1
- package/dist/config/parse-credits.js +39 -23
- package/dist/config/parse-credits.js.map +1 -1
- package/dist/config/parse-plans.d.ts +7 -2
- package/dist/config/parse-plans.d.ts.map +1 -1
- package/dist/config/parse-plans.js +49 -22
- package/dist/config/parse-plans.js.map +1 -1
- package/dist/config/parse-pricing.d.ts +2 -1
- package/dist/config/parse-pricing.d.ts.map +1 -1
- package/dist/config/parse-pricing.js +41 -31
- package/dist/config/parse-pricing.js.map +1 -1
- package/dist/config/parse-utils.d.ts +15 -11
- package/dist/config/parse-utils.d.ts.map +1 -1
- package/dist/config/parse-utils.js +90 -27
- package/dist/config/parse-utils.js.map +1 -1
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/config.d.ts +6 -5
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +65 -35
- package/dist/config.js.map +1 -1
- package/dist/credits/amount.d.ts +1 -1
- package/dist/credits/amount.d.ts.map +1 -1
- package/dist/credits/amount.js +5 -4
- package/dist/credits/amount.js.map +1 -1
- package/dist/credits/catalog-runtime.d.ts.map +1 -1
- package/dist/credits/catalog-runtime.js +2 -3
- package/dist/credits/catalog-runtime.js.map +1 -1
- package/dist/credits/events.d.ts +12 -1
- package/dist/credits/events.d.ts.map +1 -1
- package/dist/credits/events.js +35 -21
- package/dist/credits/events.js.map +1 -1
- package/dist/credits/lease-workflow.d.ts +2 -1
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js +3 -2
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.d.ts +2 -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 +2 -2
- package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/analytics.js +14 -6
- 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 +6 -6
- 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 +5 -4
- package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/catalog.js +4 -3
- 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 +2 -2
- 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 +11 -11
- 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 +3 -2
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +17 -10
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/postgres/value-mappers.d.ts +4 -3
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
- package/dist/credits/postgres/value-mappers.js +10 -11
- package/dist/credits/postgres/value-mappers.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/service.js +10 -5
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +5 -4
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js.map +1 -1
- package/dist/credits/types/account.d.ts +5 -4
- package/dist/credits/types/account.d.ts.map +1 -1
- package/dist/credits/types/account.js.map +1 -1
- package/dist/credits/types/catalog.d.ts +2 -1
- package/dist/credits/types/catalog.d.ts.map +1 -1
- package/dist/credits/types/catalog.js.map +1 -1
- package/dist/credits/types/grants.d.ts.map +1 -1
- package/dist/credits/types/grants.js.map +1 -1
- package/dist/credits/types/ledger.d.ts +3 -2
- package/dist/credits/types/ledger.d.ts.map +1 -1
- package/dist/credits/types/ledger.js.map +1 -1
- package/dist/engine.d.ts +2 -2
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +39 -10
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +7 -4
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +18 -11
- package/dist/errors.js.map +1 -1
- package/dist/expr/ast.d.ts.map +1 -1
- package/dist/expr/ast.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/expr/tokenizer.d.ts.map +1 -1
- package/dist/expr/tokenizer.js +34 -12
- package/dist/expr/tokenizer.js.map +1 -1
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +12 -6
- package/dist/expr.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/integrations/better-auth.d.ts +4 -1
- package/dist/integrations/better-auth.d.ts.map +1 -1
- package/dist/integrations/better-auth.js +7 -4
- package/dist/integrations/better-auth.js.map +1 -1
- package/dist/load-config-file.d.ts +2 -1
- package/dist/load-config-file.d.ts.map +1 -1
- package/dist/load-config-file.js +19 -13
- package/dist/load-config-file.js.map +1 -1
- package/dist/metrics.d.ts +2 -1
- package/dist/metrics.d.ts.map +1 -1
- package/dist/metrics.js.map +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js.map +1 -1
- package/dist/providers/_shared.d.ts +8 -5
- package/dist/providers/_shared.d.ts.map +1 -1
- package/dist/providers/_shared.js +15 -11
- package/dist/providers/_shared.js.map +1 -1
- package/dist/providers/dodo/better-auth-core.d.ts +30 -0
- package/dist/providers/dodo/better-auth-core.d.ts.map +1 -0
- package/dist/providers/dodo/better-auth-core.js +14 -0
- package/dist/providers/dodo/better-auth-core.js.map +1 -0
- package/dist/providers/dodo/better-auth.d.ts +5 -9
- package/dist/providers/dodo/better-auth.d.ts.map +1 -1
- package/dist/providers/dodo/better-auth.js +16 -13
- package/dist/providers/dodo/better-auth.js.map +1 -1
- package/dist/providers/dodo/client-contract.d.ts +12 -10
- 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.d.ts +7 -4
- package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
- package/dist/providers/dodo/event-mapper.js +121 -113
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/nextjs-core.d.ts +22 -0
- package/dist/providers/dodo/nextjs-core.d.ts.map +1 -0
- package/dist/providers/dodo/nextjs-core.js +14 -0
- package/dist/providers/dodo/nextjs-core.js.map +1 -0
- package/dist/providers/dodo/nextjs.d.ts +5 -7
- package/dist/providers/dodo/nextjs.d.ts.map +1 -1
- package/dist/providers/dodo/nextjs.js +11 -10
- package/dist/providers/dodo/nextjs.js.map +1 -1
- package/dist/providers/dodo/provider.d.ts +3 -3
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js +42 -35
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/dodo/react-native-core.d.ts +56 -0
- package/dist/providers/dodo/react-native-core.d.ts.map +1 -0
- package/dist/providers/dodo/react-native-core.js +56 -0
- package/dist/providers/dodo/react-native-core.js.map +1 -0
- package/dist/providers/dodo/react-native.d.ts +6 -50
- package/dist/providers/dodo/react-native.d.ts.map +1 -1
- package/dist/providers/dodo/react-native.js +5 -49
- package/dist/providers/dodo/react-native.js.map +1 -1
- package/dist/providers/dodo/webhook-bridge.d.ts +4 -2
- package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
- package/dist/providers/dodo/webhook-bridge.js.map +1 -1
- package/dist/providers/environment.d.ts +1 -1
- package/dist/providers/environment.d.ts.map +1 -1
- package/dist/providers/environment.js +4 -2
- package/dist/providers/environment.js.map +1 -1
- package/dist/providers/mock/provider.d.ts.map +1 -1
- package/dist/providers/mock/provider.js +5 -10
- package/dist/providers/mock/provider.js.map +1 -1
- package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
- package/dist/providers/stripe/event-mapper.js +33 -9
- 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 +101 -61
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.js.map +1 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +16 -9
- package/dist/retry.js.map +1 -1
- package/dist/shared/diagnostics.d.ts +5 -5
- package/dist/shared/diagnostics.d.ts.map +1 -1
- package/dist/shared/diagnostics.js +32 -22
- package/dist/shared/diagnostics.js.map +1 -1
- package/dist/shared/idempotency.d.ts +4 -3
- package/dist/shared/idempotency.d.ts.map +1 -1
- package/dist/shared/idempotency.js +21 -10
- package/dist/shared/idempotency.js.map +1 -1
- package/dist/shared/json.d.ts +28 -0
- package/dist/shared/json.d.ts.map +1 -0
- package/dist/shared/json.js +41 -0
- package/dist/shared/json.js.map +1 -0
- package/dist/shared/logger.d.ts +10 -4
- 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 +8 -6
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +69 -47
- package/dist/shared/postgres-client.js.map +1 -1
- package/dist/shared/postgres-errors.d.ts +1 -1
- package/dist/shared/postgres-errors.d.ts.map +1 -1
- package/dist/shared/postgres-errors.js +32 -31
- package/dist/shared/postgres-errors.js.map +1 -1
- package/dist/shared/postgres-types.d.ts +3 -2
- package/dist/shared/postgres-types.d.ts.map +1 -1
- package/dist/shared/postgres-types.js.map +1 -1
- package/dist/shared/postgres-validation.d.ts +7 -6
- package/dist/shared/postgres-validation.d.ts.map +1 -1
- package/dist/shared/postgres-validation.js +17 -10
- package/dist/shared/postgres-validation.js.map +1 -1
- package/dist/storage/adapters/clickhouse.d.ts +11 -4
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
- package/dist/storage/adapters/clickhouse.js +8 -6
- package/dist/storage/adapters/clickhouse.js.map +1 -1
- package/dist/storage/adapters/s3.d.ts +28 -5
- package/dist/storage/adapters/s3.d.ts.map +1 -1
- package/dist/storage/adapters/s3.js +48 -33
- package/dist/storage/adapters/s3.js.map +1 -1
- package/dist/storage/diagnostics.d.ts +1 -1
- package/dist/storage/diagnostics.d.ts.map +1 -1
- package/dist/storage/diagnostics.js +13 -12
- package/dist/storage/diagnostics.js.map +1 -1
- package/dist/storage/maintenance.d.ts.map +1 -1
- package/dist/storage/maintenance.js +31 -25
- package/dist/storage/maintenance.js.map +1 -1
- package/dist/storage/outbox-worker.d.ts +1 -1
- package/dist/storage/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js +18 -18
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/ports.d.ts +10 -7
- package/dist/storage/ports.d.ts.map +1 -1
- package/dist/storage/ports.js.map +1 -1
- package/dist/storage/postgres-repository.d.ts +3 -1
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js +10 -4
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts +1 -1
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +165 -182
- package/dist/storage/runtime.js.map +1 -1
- package/dist/telemetry/index.d.ts +10 -6
- package/dist/telemetry/index.d.ts.map +1 -1
- package/dist/telemetry/index.js +26 -23
- package/dist/telemetry/index.js.map +1 -1
- package/dist/telemetry/opentelemetry.d.ts.map +1 -1
- package/dist/telemetry/opentelemetry.js +3 -3
- package/dist/telemetry/opentelemetry.js.map +1 -1
- package/package.json +40 -40
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.js","sourceRoot":"","sources":["../../src/credits/service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EACL,eAAe,EACf,WAAW,EACX,wBAAwB,EACxB,WAAW,EACX,UAAU,GACX,MAAM,cAAc,CAAC;AA+CtB,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,yBAAyB,EAAwB,MAAM,uBAAuB,CAAC;AA2CxF;;;GAGG;AACH,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAEtC,MAAM,cAAc,GAAG,IAAI,GAAG,CAAe,CAAC,gBAAgB,EAAE,WAAW,CAAC,CAAC,CAAC;AAE9E,SAAS,cAAc,CAAC,KAAkB,EAAE,SAAiB;IAC3D,MAAM,MAA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AE,MAAM,EAAE;YACpC,OAAO,EAAE,MAAM,CAAC,OAAO;YACvB,MAAM,EAAE,MAAM,CAAC,MAAM;YACrB,gBAAgB,EAAE,MAAM,CAAC,gBAAgB;YACzC,MAAM;YACN,UAAU,EAAE,MAAM;SACnB,CAAC,CAAC;QACH,OAAO,MAAM,CAAC;IAChB,CAAC;IACO,KAAK,CAAC,QAAQ,CAAC,MAAe,EAAE,MAAe;QACrD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,mBAAmB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACpE,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,YAAY,GAAG,CAAC,EAAE,CAAC;YACvC,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,MAAM,IAAI,QAAQ,EAAE;gBAC/C,YAAY,EAAE,MAAM,CAAC,YAAY;gBACjC,aAAa,EAAE,MAAM,CAAC,aAAa;gBACnC,eAAe,EAAE,MAAM,CAAC,eAAe,IAAI,IAAI;aAChD,CAAC,CAAC;QACL,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,mBAAmB,CAAC,MAAM,GAAG,KAAK;QACtC,OAAO,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport {\n CapReachedError,\n ConfigError,\n InsufficientCreditsError,\n RefundError,\n StoreError,\n} from \"../errors.js\";\nimport type { PricingEngine } from \"../engine.js\";\nimport type { BursarConfigData, CatalogRollout } from \"../config.js\";\nimport type {\n AddCreditsResult,\n AggregateStats,\n AllowanceResult,\n AvailableResult,\n BalanceResult,\n CatalogRevision,\n BucketBalancesResult,\n CanAffordResult,\n CheckFeatureResult,\n CreditMetadata,\n DailySpendRow,\n DeductionResult,\n DeductWithAllowanceOptions,\n ExecuteGrantProgramRequest,\n GetUserPlanResult,\n GrantProgramAwardResult,\n LedgerEntry,\n LedgerPage,\n LeaseSuccess,\n ListLedgerEntriesOptions,\n ListQuotaEventsOptions,\n ListUsageChargesOptions,\n ListUsageEntriesOptions,\n PlanMigrationBatchResult,\n PlanMigrationStartResult,\n QuotaEvent,\n QuotaState,\n RefundSuccess,\n RevokeCreditsResult,\n ReleaseResult,\n SetUserPlanResult,\n UnsetUserPlanResult,\n SpendByModelRow,\n SpendByUserRow,\n SweepResult,\n TeamDeductionResult,\n TopUserRow,\n UsageChargePage,\n UsageRecordResult,\n} from \"./types/index.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type { CreditEventEmitter, CreditEventType } from \"./events.js\";\nimport type { UsageMetrics } from \"../metrics.js\";\nimport { raiseDeductError } from \"./service-errors.js\";\nimport { LowBalanceMonitor } from \"./low-balance-monitor.js\";\nimport { CreditQueries } from \"./queries.js\";\nimport { CatalogRuntime } from \"./catalog-runtime.js\";\nimport { toDecimal } from \"./amount.js\";\nimport { CreditLeaseWorkflow } from \"./lease-workflow.js\";\nimport { requireStableKey } from \"../shared/idempotency.js\";\nimport { getDefaultInstrumentation, type Instrumentation } from \"../telemetry/index.js\";\nimport type {\n AddCreditsOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n CanAffordOptions,\n CreditsServiceOptions,\n DeductCreditsOptions,\n DeductFlatJobOptions,\n DeductOptions,\n DeductTeamOptions,\n ExactAmount,\n GrantSubscriptionCycleOptions,\n MetricsOrAmount,\n PolicyPreset,\n PostDeductionContext,\n RecordUsageOptions,\n RefundCreditsOptions,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\nexport type {\n AddCreditsOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n CanAffordOptions,\n CreditsServiceOptions,\n DeductCreditsOptions,\n DeductFlatJobOptions,\n DeductOptions,\n DeductTeamOptions,\n ExactAmount,\n GrantSubscriptionCycleOptions,\n LowBalanceConfig,\n PolicyPreset,\n PostDeductionContext,\n RecordUsageOptions,\n RefundCreditsOptions,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\n/**\n * Default lease TTL (seconds) for ``reserve`` and ``runBilled``.\n * Long batch/agentic jobs call the configured lease TTL before this elapses.\n */\nconst DEFAULT_LEASE_TTL_SECONDS = 600;\n\nconst POLICY_PRESETS = new Set<PolicyPreset>([\"strict_prepaid\", \"overdraft\"]);\n\nfunction positiveAmount(value: ExactAmount, operation: string): Decimal {\n const amount = toDecimal(value);\n if (!amount.isFinite() || !amount.gt(0)) {\n throw new RangeError(`${operation} amount must be finite and greater than zero`);\n }\n return amount;\n}\n\nimport { type NormalizedLogger, normalizeLogger } from \"../shared/logger.js\";\n\n/**\n * Orchestrates credit operations.\n *\n * The deduction path is a single atomic, idempotency-keyed store call\n * (``deductWithAllowance``) that consumes free allowance, enforces plan policy,\n * and debits the net amount in one transaction. The service calculates the cost, maps\n * the store's typed ``error`` codes to exceptions, and emits lifecycle events\n * **only after** the operation has succeeded.\n *\n * Optionally accepts a ``CreditEventEmitter`` to emit lifecycle events\n * (deducted, deduct_failed, added, refunded, refund_failed, expired,\n * low_balance).\n */\nexport class CreditsService {\n private readonly store: CreditStore;\n private readonly queries: CreditQueries;\n private readonly catalogRuntime: CatalogRuntime;\n private readonly leases: CreditLeaseWorkflow;\n private emitter: CreditEventEmitter | null = null;\n private balanceMonitor: LowBalanceMonitor;\n // Lazy-on-read credit expiry (closes the gap with allowance windows/lease\n // TTLs, which are already lazy-on-read). Default `false` — unchanged\n // behaviour; explicit `sweepExpiredCredits`/cron remains required.\n private lazyExpiry: boolean;\n private logger: NormalizedLogger;\n private readonly instrumentation: Instrumentation;\n private readonly postDeductionHooks = new Set<\n (context: PostDeductionContext) => void | Promise<void>\n >();\n constructor(\n store: CreditStore,\n engine?: PricingEngine | null,\n emitter?: CreditEventEmitter | null,\n options?: CreditsServiceOptions | null,\n ) {\n this.store = store;\n this.instrumentation = options?.instrumentation ?? getDefaultInstrumentation();\n this.queries = new CreditQueries(\n store,\n options?.analytics ?? store,\n options?.usageStore ?? store,\n );\n const policy = options?.policy ?? \"strict_prepaid\";\n if (!POLICY_PRESETS.has(policy)) {\n throw new ConfigError(\n `unknown policy preset '${policy}'; expected one of ${[...POLICY_PRESETS].sort().join(\", \")}`,\n );\n }\n if (emitter) this.emitter = emitter;\n this.logger = normalizeLogger(options?.logger);\n if (options?.postDeduction) this.postDeductionHooks.add(options.postDeduction);\n this.catalogRuntime = new CatalogRuntime(\n store,\n engine ?? null,\n this.logger,\n options?.catalogCacheTtlMs ?? 300_000,\n );\n this.balanceMonitor = new LowBalanceMonitor(\n options?.lowBalance,\n (type, userId, data) => this.emit(type, userId, data),\n this.logger,\n );\n this.lazyExpiry = options?.lazyExpiry ?? false;\n this.leases = new CreditLeaseWorkflow(\n store,\n this.catalogRuntime,\n this.logger,\n this.balanceMonitor,\n policy,\n options?.overdraftFloor != null ? toDecimal(options.overdraftFloor) : null,\n options?.maxConcurrent ?? null,\n options?.defaultTtlSeconds ?? DEFAULT_LEASE_TTL_SECONDS,\n (type, userId, data) => this.emit(type, userId, data),\n (userId, idempotencyKey) => this.emitQuotaEvents(userId, idempotencyKey),\n (userId) => this.maybeLazyExpire(userId),\n (userId, result) => this.afterDeduction(userId, \"settle\", result),\n );\n }\n\n /**\n * Register an awaited post-commit deduction hook. A failing hook is logged\n * and isolated so it can never roll back an already committed charge.\n */\n addPostDeductionHook(hook: (context: PostDeductionContext) => void | Promise<void>): () => void {\n this.postDeductionHooks.add(hook);\n return () => this.postDeductionHooks.delete(hook);\n }\n\n private async afterDeduction(\n userId: string,\n source: PostDeductionContext[\"source\"],\n deduction: PostDeductionContext[\"deduction\"],\n ): Promise<void> {\n for (const hook of this.postDeductionHooks) {\n try {\n await hook({ userId, source, deduction });\n } catch (error) {\n this.logger.warn(\"[CreditsService] post-deduction hook failed\", {\n userId,\n source,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n async getActiveCatalog(): Promise<CatalogRevision | null> {\n return this.queries.getActiveCatalog();\n }\n\n async getUserPlan(userId: string): Promise<GetUserPlanResult> {\n return this.queries.getUserPlan(userId);\n }\n\n async checkFeature(userId: string, feature: string): Promise<CheckFeatureResult> {\n return this.queries.checkFeature(userId, feature);\n }\n\n async getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaState[]> {\n return this.queries.getQuotaState(userId, quotaKey);\n }\n\n async listQuotaEvents(userId: string, options?: ListQuotaEventsOptions): Promise<QuotaEvent[]> {\n return this.queries.listQuotaEvents(userId, options);\n }\n\n async startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartResult> {\n return this.queries.startPlanMigration(fromPlanId, toPlanId);\n }\n\n async migratePlanBatch(\n migrationId: string,\n batchSize?: number,\n ): Promise<PlanMigrationBatchResult> {\n return this.queries.migratePlanBatch(migrationId, batchSize);\n }\n\n async revokeCreditsByEntryType(userId: string, entryType: string): Promise<RevokeCreditsResult> {\n const result = await this.queries.revokeCreditsByEntryType(userId, entryType);\n if (result.revoked.gt(0)) {\n this.emit(\"credits.revoked\", userId, {\n userId,\n entryType,\n amount: result.revoked,\n balanceAfter: result.balanceAfter,\n });\n }\n return result;\n }\n\n /** Execute an application-driven catalog grant program. */\n async executeGrantProgram(\n request: ExecuteGrantProgramRequest,\n ): Promise<GrantProgramAwardResult[]> {\n return this.instrumentation.run(\"credits.grant_program\", undefined, () =>\n this.store.executeGrantProgram(request),\n );\n }\n\n async getLedgerEntry(userId: string, entryId: string): Promise<LedgerEntry | null> {\n return this.queries.getLedgerEntry(userId, entryId);\n }\n\n async getAvailable(userId: string): Promise<AvailableResult> {\n return this.queries.getAvailable(userId);\n }\n\n async aggregateStats(start: Date, end: Date): Promise<AggregateStats> {\n return this.queries.aggregateStats(start, end);\n }\n\n async spendByUser(start: Date, end: Date): Promise<SpendByUserRow[]> {\n return this.queries.spendByUser(start, end);\n }\n\n async spendByModel(start: Date, end: Date): Promise<SpendByModelRow[]> {\n return this.queries.spendByModel(start, end);\n }\n\n async listLedgerEntries(userId: string, options?: ListLedgerEntriesOptions): Promise<LedgerPage> {\n return this.queries.listLedgerEntries(userId, options);\n }\n\n async listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage> {\n return this.queries.listUsageEntries(userId, options);\n }\n\n async listUsageCharges(\n userId: string,\n options?: ListUsageChargesOptions,\n ): Promise<UsageChargePage> {\n return this.queries.listUsageCharges(userId, options);\n }\n\n async topUsers(limit: number, start: Date, end: Date): Promise<TopUserRow[]> {\n return this.queries.topUsers(limit, start, end);\n }\n\n async dailySpend(start: Date, end: Date): Promise<DailySpendRow[]> {\n return this.queries.dailySpend(start, end);\n }\n\n /** Emit a credit lifecycle event. No-op if no emitter is configured. */\n private emit(type: CreditEventType, userId: string, data?: Record<string, unknown>): void {\n this.emitter?.emit({ type, timestamp: new Date(), userId, data });\n }\n\n private async emitQuotaEvents(userId: string, idempotencyKey: string): Promise<void> {\n const events = await this.store.listQuotaEvents(userId, {\n idempotencyKey,\n limit: 100,\n });\n for (const event of events) {\n const data = {\n quotaKey: event.quotaKey,\n operation: event.operation,\n measure: event.measure,\n thresholdPercent: event.thresholdPercent,\n usageChargeId: event.usageChargeId,\n idempotencyKey: event.idempotencyKey,\n };\n if (event.eventType === \"blocked\") {\n this.emit(\"credits.quota_blocked\", userId, data);\n } else {\n this.emit(\"credits.quota_threshold\", userId, data);\n }\n }\n }\n\n /** Load the active catalog revision from the store. */\n async loadCatalogFromStore(): Promise<void> {\n await this.catalogRuntime.loadFromStore();\n }\n\n /**\n * If the cached PricingEngine is stale (TTL expired), reload it from the\n * store. Concurrent callers are deduplicated via the underlying\n * ``lru-cache.fetch()`` — only one ``loadCatalogFromStore`` runs and all\n * callers await the same result.\n *\n * When ``catalogCacheTtlMs`` is ``0``, this is a no-op (the consumer must call\n * ``loadCatalogFromStore`` manually).\n */\n async refreshCatalogIfStale(): Promise<void> {\n await this.catalogRuntime.refreshIfStale();\n }\n\n /**\n * Invalidate the catalog cache so the next ``refreshCatalogIfStale`` call\n * reloads from the store. Useful after a manual ``loadCatalogFromStore``\n * that bypasses the cache, or when the consumer knows the remote config\n * has changed.\n */\n invalidateCatalog(): void {\n this.catalogRuntime.invalidate();\n }\n\n /**\n * Publish and activate a catalog revision, then update the local engine.\n *\n * The store write is awaited, so\n * a persistence failure surfaces to the caller instead of becoming an\n * unhandled promise rejection.\n */\n async publishAndActivateCatalog(\n config: BursarConfigData,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string> {\n return this.catalogRuntime.publishAndActivate(config, label, rollout);\n }\n\n /** Publish a validated, inactive catalog draft. */\n async publishCatalogDraft(config: BursarConfigData, label?: string | null): Promise<string> {\n return this.catalogRuntime.publishDraft(config, label);\n }\n\n /** Activate an existing catalog version and reload the local engine. */\n async activateCatalogRevision(version: number, rollout?: CatalogRollout | null): Promise<string> {\n return this.catalogRuntime.activateRevision(version, rollout);\n }\n\n /** The current PricingEngine, or null if not loaded. */\n get pricingEngine(): PricingEngine | null {\n return this.catalogRuntime.currentEngine;\n }\n\n /**\n * Set a user's subscription plan and emit ``credits.plan_changed``.\n *\n * The store call is awaited so a persistence failure surfaces to the caller.\n * The event is emitted only after the store write succeeds.\n */\n async setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt?: Date | null,\n ): Promise<SetUserPlanResult> {\n this.logger.info(\"[CreditsService] setUserPlan\", { planKey, planAssignedAt });\n const result = await this.store.setUserPlan(userId, planKey, planAssignedAt);\n this.emit(\"credits.plan_changed\", userId, {\n userId,\n planKey,\n planAssignedAt: result.planAssignedAt,\n assignmentState: result.assignmentState,\n timestamp: new Date().toISOString(),\n });\n return result;\n }\n\n /** Unset a user's subscription plan and emit the plan-change event. */\n async unsetUserPlan(userId: string): Promise<UnsetUserPlanResult> {\n const result = await this.store.unsetUserPlan(userId);\n this.emit(\"credits.plan_changed\", userId, {\n userId,\n planKey: null,\n timestamp: new Date().toISOString(),\n });\n return result;\n }\n\n /** Pin or unpin the user's current assignment revision. */\n async setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean> {\n return this.store.setPlanRevisionPin(userId, pinned);\n }\n\n /** Apply one bounded batch of renewal-effective plan changes. */\n async applyDuePlanChanges(limit = 100): Promise<number> {\n return this.store.applyDuePlanChanges(limit);\n }\n\n /** Sweep this user's expired lots when lazy expiry is enabled. */\n private async maybeLazyExpire(userId: string): Promise<void> {\n if (!this.lazyExpiry) return;\n await this.runSweep(false, userId);\n }\n\n async getBalance(userId: string): Promise<BalanceResult> {\n await this.maybeLazyExpire(userId);\n return await this.store.getBalance(userId);\n }\n\n /** Add credits to a user's account. */\n async addCredits(\n userId: string,\n amount: ExactAmount,\n options: AddCreditsOptions,\n ): Promise<AddCreditsResult> {\n return this.instrumentation.run(\"credits.grant\", undefined, () =>\n this.addCreditsUninstrumented(userId, amount, options),\n );\n }\n\n private async addCreditsUninstrumented(\n userId: string,\n amount: ExactAmount,\n options: AddCreditsOptions,\n ): Promise<AddCreditsResult> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n const type = options.type ?? \"adjustment\";\n this.logger.info(\"[CreditsService] addCredits\", { amount, type, bucket: options.bucket });\n const result = await this.store.addCredits(userId, positiveAmount(amount, \"addCredits\"), {\n ...options,\n type,\n idempotencyKey,\n });\n this.emit(\"credits.added\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n newBalance: result.newBalance,\n type,\n idempotent: result.idempotent ?? false,\n });\n this.balanceMonitor.rearmAfterCredit(userId, result.newBalance);\n return result;\n }\n\n /**\n * Deduct a raw credit amount from a user's account.\n *\n * Uses the store's `addCredits` with `type='adjustment'` and a negated\n * amount — the existing validation path for negative/zero adjustments.\n * Use this for refund clawbacks and other administrative deductions that\n * bypass the usage-based `deduct()` flow.\n */\n async deductCredits(\n userId: string,\n amount: ExactAmount,\n options: DeductCreditsOptions,\n ): Promise<AddCreditsResult> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n const entryType = options.entryType ?? \"adjustment\";\n this.logger.info(\"[CreditsService] deductCredits\", {\n amount,\n entryType,\n bucket: options.bucket,\n });\n const result = await this.store.addCredits(\n userId,\n positiveAmount(amount, \"deductCredits\").neg(),\n {\n type: entryType,\n metadata: options.metadata,\n bucket: options.bucket,\n idempotencyKey,\n },\n );\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n newBalance: result.newBalance,\n entryType,\n idempotent: result.idempotent ?? false,\n });\n if (!result.idempotent) {\n await this.afterDeduction(userId, \"raw\", {\n entryId: result.entryId,\n userId,\n amount: result.amount.abs(),\n allowanceConsumed: new Decimal(0),\n balanceAfter: result.newBalance,\n idempotent: false,\n usageChargeId: null,\n error: null,\n bucketBreakdown: null,\n });\n }\n return result;\n }\n\n /**\n * Grant one billing-cycle's worth of credits — idempotent-safe for a\n * payment-provider webhook handler (Stripe, etc. — bursar stays\n * provider-agnostic) to call even on webhook redelivery.\n *\n * 1. At most one of ``expiresAt``/``ttlDays`` may be given (throws\n * ``ConfigError`` otherwise).\n * 2. When ``ttlDays`` is given, ``expiresAt = now + ttlDays`` days.\n * 3. The new cycle is granted via a direct ``store.addCredits`` call\n * (bypassing {@link addCredits} so only ``credits.cycle_renewed`` fires,\n * not a duplicate ``credits.added``), threading ``idempotencyKey`` so a\n * redelivered webhook replays the prior grant instead of double-crediting.\n * 4. Existing bucket credits are never removed here. Subscription renewal\n * policies that replace prior lots run atomically through BillingService.\n * 5. When ``planKey`` is given, assigns it via {@link setUserPlan}.\n * 6. Emits ``credits.cycle_renewed`` and returns the grant result.\n */\n async grantSubscriptionCycle(\n userId: string,\n amount: ExactAmount,\n options: GrantSubscriptionCycleOptions,\n ): Promise<AddCreditsResult> {\n return this.instrumentation.run(\"credits.grant_subscription_cycle\", undefined, () =>\n this.grantSubscriptionCycleUninstrumented(userId, amount, options),\n );\n }\n\n private async grantSubscriptionCycleUninstrumented(\n userId: string,\n amount: ExactAmount,\n options: GrantSubscriptionCycleOptions,\n ): Promise<AddCreditsResult> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n this.logger.info(\"[CreditsService] grantSubscriptionCycle\", {\n amount,\n bucket: options.bucket,\n planKey: options.planKey,\n });\n if (options.expiresAt != null && options.ttlDays != null) {\n throw new ConfigError(\n \"grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both\",\n );\n }\n const bucket = options.bucket ?? \"subscription\";\n const expiresAt: Date | undefined =\n options.ttlDays != null\n ? new Date(Date.now() + options.ttlDays * 86_400_000)\n : options.expiresAt;\n const amountDec = positiveAmount(amount, \"grantSubscriptionCycle\");\n\n const result = await this.store.addCredits(userId, amountDec, {\n type: \"purchase\",\n metadata: options.metadata,\n expiresAt,\n bucket,\n idempotencyKey,\n });\n\n // The store contract exposes the mutation's replay result directly, avoiding\n // a racy lifetime-balance comparison and an extra database round trip.\n const isFreshGrant = !result.idempotent;\n if (options.planKey) {\n // A fresh cycle intentionally re-anchors plan-assignment windows. On a\n // webhook replay, repair a previously interrupted grant->assignment saga\n // without re-anchoring an assignment that already succeeded.\n if (isFreshGrant || (await this.getUserPlan(userId)).planKey !== options.planKey) {\n await this.setUserPlan(userId, options.planKey);\n }\n }\n\n this.emit(\"credits.cycle_renewed\", userId, {\n entryId: result.entryId,\n amount: amountDec,\n newBalance: result.newBalance,\n bucket,\n planKey: options.planKey ?? null,\n idempotencyKey,\n idempotent: result.idempotent,\n });\n\n return result;\n }\n\n // ── Lease lifecycle: atomic admission ───────────────────────────────\n\n async reserve(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options: ReserveOptions,\n ): Promise<LeaseSuccess> {\n return this.instrumentation.run(\"credits.reserve\", undefined, () =>\n this.leases.reserve(userId, metricsOrAmount, options),\n );\n }\n\n async settle(\n userId: string,\n leaseId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: SettleOptions,\n ): Promise<DeductionResult> {\n return this.instrumentation.run(\"credits.settle\", undefined, () =>\n this.leases.settle(userId, leaseId, metricsOrAmount, options),\n );\n }\n\n async release(userId: string, leaseId: string): Promise<ReleaseResult> {\n return this.instrumentation.run(\"credits.release\", undefined, () =>\n this.leases.release(userId, leaseId),\n );\n }\n\n async renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseSuccess> {\n return this.leases.renew(userId, leaseId, ttl);\n }\n\n async canAfford(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: CanAffordOptions,\n ): Promise<CanAffordResult> {\n return this.leases.canAfford(userId, metricsOrAmount, options);\n }\n\n async getBucketBalances(userId: string): Promise<BucketBalancesResult> {\n return this.leases.getBucketBalances(userId);\n }\n\n async checkAllowance(userId: string): Promise<AllowanceResult | null> {\n return this.leases.checkAllowance(userId);\n }\n\n async runBilled<T>(\n userId: string,\n options: RunBilledOptions<T>,\n ): Promise<{ result: T; deduction: DeductionResult }> {\n return this.leases.runBilled(userId, options);\n }\n\n async beginBilledOperation(\n userId: string,\n options: BeginBilledOperationOptions,\n ): Promise<BilledOperation> {\n return this.leases.beginBilledOperation(userId, options);\n }\n\n /**\n * Full deduction flow as one atomic store call.\n *\n * 1. ``breakdown = engine.calculate(metrics)``; ``cost = breakdown.total``\n * (exact `Decimal`, **no truncation**).\n * 2. ``store.deductWithAllowance`` records the usage, enforces policy, consumes\n * allowance, and debits any remainder — idempotency-keyed end-to-end.\n *\n * On a store ``error`` a ``credits.deduct_failed`` event is emitted and a\n * typed exception is thrown. No success event is emitted on error.\n */\n async deduct(\n userId: string,\n metrics: UsageMetrics,\n options: DeductOptions,\n ): Promise<DeductionResult> {\n return this.instrumentation.run(\"credits.deduct\", undefined, () =>\n this.deductUninstrumented(userId, metrics, options),\n );\n }\n\n private async deductUninstrumented(\n userId: string,\n metrics: UsageMetrics,\n options: DeductOptions,\n ): Promise<DeductionResult> {\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] deduct\", {\n model: metrics.dimensions?.model,\n feature: options.feature,\n });\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);\n\n // 1) Calculate cost as an exact Decimal, never truncated.\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const cost = breakdown.total;\n\n // Build ledger metadata: caller fields FIRST, system fields LAST so the\n // protected system fields win.\n const meta: Record<string, unknown> = {};\n if (options.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) meta[k] = v;\n }\n }\n meta[\"operation\"] = metrics.operation;\n meta[\"measures\"] = { ...(metrics.measures ?? {}) };\n meta[\"dimensions\"] = { ...(metrics.dimensions ?? {}) };\n meta[\"breakdownTotal\"] = breakdown.total.toString();\n meta[\"idempotencyKey\"] = effectiveIdempotencyKey;\n\n const deductionOptions: DeductWithAllowanceOptions = {\n idempotencyKey: effectiveIdempotencyKey,\n operation: metrics.operation,\n feature: options.feature ?? null,\n model: typeof metrics.dimensions?.model === \"string\" ? metrics.dimensions.model : null,\n region: typeof metrics.dimensions?.region === \"string\" ? metrics.dimensions.region : null,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: { ...(metrics.dimensions ?? {}) },\n metadata: meta as CreditMetadata,\n };\n\n // 2) Atomic charge. This records zero-cost usage too, so authorization,\n // quotas, and usage history cannot be bypassed by a free rate.\n const result = await this.store.deductWithAllowance(userId, cost, deductionOptions);\n\n if (result.error !== null) {\n if (result.error === \"quota_exceeded\") {\n await this.emitQuotaEvents(userId, effectiveIdempotencyKey);\n }\n this.logger.warn(\"[CreditsService] deduct failed\", {\n error: result.error,\n amount: cost,\n model: metrics.dimensions?.model,\n feature: options.feature,\n });\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount: cost,\n model: metrics.dimensions?.model ?? null,\n });\n raiseDeductError(result.error, userId, cost);\n }\n\n // Success — emit deducted, then any cap warning, then edge-triggered low-balance.\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n allowanceConsumed: result.allowanceConsumed,\n balanceAfter: result.balanceAfter,\n model: metrics.dimensions?.model ?? null,\n idempotent: result.idempotent,\n });\n\n // low_balance is edge-triggered: only fire when this deduction crossed\n // the threshold. A replayed (idempotent) result did not move the balance, so\n // it never crosses. balanceBefore = balanceAfter + amount charged.\n if (!result.idempotent) {\n const balanceBefore = result.balanceAfter.plus(result.amount);\n await this.balanceMonitor.signalCrossing(userId, balanceBefore, result.balanceAfter);\n await this.emitQuotaEvents(userId, effectiveIdempotencyKey);\n await this.afterDeduction(userId, \"deduct\", result);\n }\n\n return result;\n }\n\n /**\n * Record priced usage for a workflow without debiting the account again.\n *\n * This supports priced usage receipts that should be retained without\n * affecting the account balance, such as externally billed usage.\n */\n async recordUsage(\n userId: string,\n metrics: UsageMetrics,\n options: RecordUsageOptions,\n ): Promise<UsageRecordResult> {\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const meta: Record<string, unknown> = {};\n if (options.metadata) {\n for (const [key, value] of Object.entries(options.metadata)) {\n if (value != null) meta[key] = value;\n }\n }\n meta.operation = metrics.operation;\n meta.measures = { ...(metrics.measures ?? {}) };\n meta.dimensions = { ...(metrics.dimensions ?? {}) };\n meta.breakdownTotal = breakdown.total.toString();\n meta.idempotencyKey = effectiveIdempotencyKey;\n\n const result = await this.store.recordUsage(userId, metrics.operation, breakdown.total, {\n idempotencyKey: effectiveIdempotencyKey,\n operation: metrics.operation,\n model: typeof metrics.dimensions?.model === \"string\" ? metrics.dimensions.model : null,\n region: typeof metrics.dimensions?.region === \"string\" ? metrics.dimensions.region : null,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: { ...(metrics.dimensions ?? {}) },\n metadata: meta as CreditMetadata,\n });\n if (result.error !== null) {\n throw new StoreError(`Usage record failed: ${result.error}`);\n }\n return result;\n }\n\n /**\n * Refund a previous credit deduction.\n *\n * Returns the RefundResult. A successful refund\n * emits ``credits.refunded``; a failed/duplicate/over-refund emits\n * ``credits.refund_failed`` (no success event is ever emitted for a failed\n * refund).\n */\n /** Deduct the configured fixed cost for one named job. */\n async deductFlatJob(\n userId: string,\n jobName: string,\n options: DeductFlatJobOptions,\n ): Promise<DeductionResult> {\n return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } }, options);\n }\n\n async refundCredits(entryId: string, options: RefundCreditsOptions): Promise<RefundSuccess> {\n return this.instrumentation.run(\"credits.refund\", undefined, () =>\n this.refundCreditsUninstrumented(entryId, options),\n );\n }\n\n private async refundCreditsUninstrumented(\n entryId: string,\n options: RefundCreditsOptions,\n ): Promise<RefundSuccess> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n const refundAmount =\n options.amount != null ? positiveAmount(options.amount, \"refundCredits\") : undefined;\n this.logger.info(\"[CreditsService] refundCredits\", {\n entryId,\n refundAmount,\n reason: options.reason,\n });\n const result = await this.store.refundCredits(entryId, {\n ...options,\n amount: refundAmount,\n idempotencyKey,\n });\n\n if (result.error !== null) {\n this.logger.warn(\"[CreditsService] refundCredits failed\", {\n entryId,\n error: result.error,\n });\n if (result.userId !== null) {\n this.emit(\"credits.refund_failed\", result.userId, {\n entryId,\n error: result.error,\n reason: options.reason ?? null,\n });\n }\n throw new RefundError(`Refund rejected: ${result.error}`);\n }\n\n this.emit(\"credits.refunded\", result.userId, {\n entryId,\n refundEntryId: result.refundEntryId,\n amount: result.amount,\n newBalance: result.newBalance,\n reason: options.reason ?? null,\n });\n return result;\n }\n\n /**\n * Deduct from a team's shared balance pool.\n *\n * Calculates the cost via the pricing engine (exact `Decimal`, no truncation),\n * then debits the team balance. Threads a required ``idempotencyKey`` through\n * to the store so retried team charges are not double-counted.\n */\n async deductTeam(\n teamId: string,\n userId: string,\n metrics: UsageMetrics,\n options: DeductTeamOptions,\n ): Promise<TeamDeductionResult> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n await this.maybeLazyExpire(userId);\n // Lazy expiry is scoped to the individual member's credits, not the team's\n // shared pool — there's no per-team expiry concept.\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const cost = breakdown.total;\n\n if (cost.lte(0)) {\n const teamBal = await this.store.getTeamBalance(teamId);\n if (teamBal === null) {\n throw new StoreError(`Team not found: ${teamId}`);\n }\n return {\n entryId: null,\n teamId,\n userId,\n amount: new Decimal(0),\n teamBalanceAfter: teamBal.balance,\n idempotent: false,\n error: null,\n };\n }\n\n const teamMetadata: CreditMetadata = {\n ...(options.metadata ?? {}),\n operation: metrics.operation,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: Object.fromEntries(\n Object.entries(metrics.dimensions ?? {}).map(([key, value]) => [key, String(value)]),\n ),\n breakdownTotal: breakdown.total.toString(),\n };\n const result = await this.store.deductTeam(teamId, userId, cost, {\n metadata: teamMetadata,\n idempotencyKey,\n });\n // Surface store errors: emit credits.deduct_failed and throw,\n // mirroring the Python credit service implementation. Previously returned a silent\n // success-shaped object with an .error field, so failed charges looked OK.\n if (result.error !== null) {\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount: cost,\n teamId,\n deductType: \"team\",\n });\n if (result.error === \"member_spend_cap_exceeded\") {\n throw new CapReachedError(\n `Team member spend cap exceeded. Team=${teamId}, user=${userId}, requested=${cost}`,\n );\n }\n throw new InsufficientCreditsError(\n `Team deduction failed: ${result.error}. Team=${teamId}, user=${userId}, requested=${cost}`,\n );\n }\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n teamBalanceAfter: result.teamBalanceAfter,\n teamId,\n deductType: \"team\",\n });\n return result;\n }\n private async runSweep(dryRun: boolean, userId?: string): Promise<SweepResult> {\n const result = await this.store.sweepExpiredCredits(dryRun, userId);\n if (!dryRun && result.expiredCount > 0) {\n this.emit(\"credits.expired\", userId ?? \"system\", {\n expiredCount: result.expiredCount,\n expiredAmount: result.expiredAmount,\n expiredByBucket: result.expiredByBucket ?? null,\n });\n }\n return result;\n }\n\n /**\n * Sweep expired credits from all users' balances.\n *\n * When ``dryRun`` is true, reports what would expire without mutating\n * balances. Automatic lazy sweeps remain scoped to one subject.\n */\n async sweepExpiredCredits(dryRun = false): Promise<SweepResult> {\n return await this.runSweep(dryRun);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"service.js","sourceRoot":"","sources":["../../src/credits/service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACL,eAAe,EACf,WAAW,EACX,wBAAwB,EACxB,WAAW,EACX,UAAU,GACX,MAAM,cAAc,CAAC;AA+CtB,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,yBAAyB,EAAwB,MAAM,uBAAuB,CAAC;AA4CxF;;;GAGG;AACH,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAEtC,MAAM,cAAc,GAAG,IAAI,GAAG,CAAe,CAAC,gBAAgB,EAAE,WAAW,CAAC,CAAC,CAAC;AAE9E,SAAS,cAAc,CAAC,KAAkB,EAAE,SAAiB;IAC3D,MAAM,MAAM,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;IAChC,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC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AAM;YACrB,gBAAgB,EAAE,MAAM,CAAC,gBAAgB;YACzC,MAAM;YACN,UAAU,EAAE,MAAM;SACnB,CAAC,CAAC;QACH,OAAO,MAAM,CAAC;IAChB,CAAC;IACO,KAAK,CAAC,QAAQ,CAAC,MAAe,EAAE,MAAe;QACrD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,mBAAmB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACpE,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,YAAY,GAAG,CAAC,EAAE,CAAC;YACvC,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,MAAM,IAAI,QAAQ,EAAE;gBAC/C,YAAY,EAAE,MAAM,CAAC,YAAY;gBACjC,aAAa,EAAE,MAAM,CAAC,aAAa;gBACnC,eAAe,EAAE,MAAM,CAAC,eAAe,IAAI,IAAI;aAChD,CAAC,CAAC;QACL,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,mBAAmB,CAAC,MAAM,GAAG,KAAK;QACtC,OAAO,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\nimport {\n CapReachedError,\n ConfigError,\n InsufficientCreditsError,\n RefundError,\n StoreError,\n} from \"../errors.js\";\nimport type { PricingEngine } from \"../engine.js\";\nimport type { BursarConfigData, CatalogRollout } from \"../config.js\";\nimport type {\n AddCreditsResult,\n AggregateStats,\n AllowanceResult,\n AvailableResult,\n BalanceResult,\n CatalogRevision,\n BucketBalancesResult,\n CanAffordResult,\n CheckFeatureResult,\n CreditMetadata,\n DailySpendRow,\n DeductionResult,\n DeductWithAllowanceOptions,\n ExecuteGrantProgramRequest,\n GetUserPlanResult,\n GrantProgramAwardResult,\n LedgerEntry,\n LedgerPage,\n LeaseSuccess,\n ListLedgerEntriesOptions,\n ListQuotaEventsOptions,\n ListUsageChargesOptions,\n ListUsageEntriesOptions,\n PlanMigrationBatchResult,\n PlanMigrationStartResult,\n QuotaEvent,\n QuotaState,\n RefundSuccess,\n RevokeCreditsResult,\n ReleaseResult,\n SetUserPlanResult,\n UnsetUserPlanResult,\n SpendByModelRow,\n SpendByUserRow,\n SweepResult,\n TeamDeductionResult,\n TopUserRow,\n UsageChargePage,\n UsageRecordResult,\n} from \"./types/index.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type { CreditEventEmitter, CreditEventType } from \"./events.js\";\nimport type { UsageMetrics } from \"../metrics.js\";\nimport { raiseDeductError } from \"./service-errors.js\";\nimport { LowBalanceMonitor } from \"./low-balance-monitor.js\";\nimport { CreditQueries } from \"./queries.js\";\nimport { CatalogRuntime } from \"./catalog-runtime.js\";\nimport { toDecimal } from \"./amount.js\";\nimport { CreditLeaseWorkflow } from \"./lease-workflow.js\";\nimport { requireStableKey } from \"../shared/idempotency.js\";\nimport { getDefaultInstrumentation, type Instrumentation } from \"../telemetry/index.js\";\nimport type { StructuredObject } from \"../shared/json.js\";\nimport type {\n AddCreditsOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n CanAffordOptions,\n CreditsServiceOptions,\n DeductCreditsOptions,\n DeductFlatJobOptions,\n DeductOptions,\n DeductTeamOptions,\n ExactAmount,\n GrantSubscriptionCycleOptions,\n MetricsOrAmount,\n PolicyPreset,\n PostDeductionContext,\n RecordUsageOptions,\n RefundCreditsOptions,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\nexport type {\n AddCreditsOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n CanAffordOptions,\n CreditsServiceOptions,\n DeductCreditsOptions,\n DeductFlatJobOptions,\n DeductOptions,\n DeductTeamOptions,\n ExactAmount,\n GrantSubscriptionCycleOptions,\n LowBalanceConfig,\n PolicyPreset,\n PostDeductionContext,\n RecordUsageOptions,\n RefundCreditsOptions,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\n/**\n * Default lease TTL (seconds) for ``reserve`` and ``runBilled``.\n * Long batch/agentic jobs call the configured lease TTL before this elapses.\n */\nconst DEFAULT_LEASE_TTL_SECONDS = 600;\n\nconst POLICY_PRESETS = new Set<PolicyPreset>([\"strict_prepaid\", \"overdraft\"]);\n\nfunction positiveAmount(value: ExactAmount, operation: string): Decimal {\n const amount = toDecimal(value);\n if (!amount.isFinite() || !amount.gt(0)) {\n throw new RangeError(`${operation} amount must be finite and greater than zero`);\n }\n return amount;\n}\n\nimport { type NormalizedLogger, normalizeLogger } from \"../shared/logger.js\";\n\n/**\n * Orchestrates credit operations.\n *\n * The deduction path is a single atomic, idempotency-keyed store call\n * (``deductWithAllowance``) that consumes free allowance, enforces plan policy,\n * and debits the net amount in one transaction. The service calculates the cost, maps\n * the store's typed ``error`` codes to exceptions, and emits lifecycle events\n * **only after** the operation has succeeded.\n *\n * Optionally accepts a ``CreditEventEmitter`` to emit lifecycle events\n * (deducted, deduct_failed, added, refunded, refund_failed, expired,\n * low_balance).\n */\nexport class CreditsService {\n private readonly store: CreditStore;\n private readonly queries: CreditQueries;\n private readonly catalogRuntime: CatalogRuntime;\n private readonly leases: CreditLeaseWorkflow;\n private emitter: CreditEventEmitter | null = null;\n private balanceMonitor: LowBalanceMonitor;\n // Lazy-on-read credit expiry (closes the gap with allowance windows/lease\n // TTLs, which are already lazy-on-read). Default `false` — unchanged\n // behaviour; explicit `sweepExpiredCredits`/cron remains required.\n private lazyExpiry: boolean;\n private logger: NormalizedLogger;\n private readonly instrumentation: Instrumentation;\n private readonly postDeductionHooks = new Set<\n (context: PostDeductionContext) => void | Promise<void>\n >();\n constructor(\n store: CreditStore,\n engine?: PricingEngine | null,\n emitter?: CreditEventEmitter | null,\n options?: CreditsServiceOptions | null,\n ) {\n this.store = store;\n this.instrumentation = options?.instrumentation ?? getDefaultInstrumentation();\n this.queries = new CreditQueries(\n store,\n options?.analytics ?? store,\n options?.usageStore ?? store,\n );\n const policy = options?.policy ?? \"strict_prepaid\";\n if (!POLICY_PRESETS.has(policy)) {\n throw new ConfigError(\n `unknown policy preset '${policy}'; expected one of ${[...POLICY_PRESETS].sort().join(\", \")}`,\n );\n }\n if (emitter) this.emitter = emitter;\n this.logger = normalizeLogger(options?.logger);\n if (options?.postDeduction) this.postDeductionHooks.add(options.postDeduction);\n this.catalogRuntime = new CatalogRuntime(\n store,\n engine ?? null,\n this.logger,\n options?.catalogCacheTtlMs ?? 300_000,\n );\n this.balanceMonitor = new LowBalanceMonitor(\n options?.lowBalance,\n (type, userId, data) => this.emit(type, userId, data),\n this.logger,\n );\n this.lazyExpiry = options?.lazyExpiry ?? false;\n this.leases = new CreditLeaseWorkflow(\n store,\n this.catalogRuntime,\n this.logger,\n this.balanceMonitor,\n policy,\n options?.overdraftFloor != null ? toDecimal(options.overdraftFloor) : null,\n options?.maxConcurrent ?? null,\n options?.defaultTtlSeconds ?? DEFAULT_LEASE_TTL_SECONDS,\n (type, userId, data) => this.emit(type, userId, data),\n (userId, idempotencyKey) => this.emitQuotaEvents(userId, idempotencyKey),\n (userId) => this.maybeLazyExpire(userId),\n (userId, result) => this.afterDeduction(userId, \"settle\", result),\n );\n }\n\n /**\n * Register an awaited post-commit deduction hook. A failing hook is logged\n * and isolated so it can never roll back an already committed charge.\n */\n addPostDeductionHook(hook: (context: PostDeductionContext) => void | Promise<void>): () => void {\n this.postDeductionHooks.add(hook);\n return () => this.postDeductionHooks.delete(hook);\n }\n\n private async afterDeduction(\n userId: string,\n source: PostDeductionContext[\"source\"],\n deduction: PostDeductionContext[\"deduction\"],\n ): Promise<void> {\n for (const hook of this.postDeductionHooks) {\n try {\n await hook({ userId, source, deduction });\n } catch (error) {\n this.logger.warn(\"[CreditsService] post-deduction hook failed\", {\n userId,\n source,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n async getActiveCatalog(): Promise<CatalogRevision | null> {\n return this.queries.getActiveCatalog();\n }\n\n async getUserPlan(userId: string): Promise<GetUserPlanResult> {\n return this.queries.getUserPlan(userId);\n }\n\n async checkFeature(userId: string, feature: string): Promise<CheckFeatureResult> {\n return this.queries.checkFeature(userId, feature);\n }\n\n async getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaState[]> {\n return this.queries.getQuotaState(userId, quotaKey);\n }\n\n async listQuotaEvents(userId: string, options?: ListQuotaEventsOptions): Promise<QuotaEvent[]> {\n return this.queries.listQuotaEvents(userId, options);\n }\n\n async startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartResult> {\n return this.queries.startPlanMigration(fromPlanId, toPlanId);\n }\n\n async migratePlanBatch(\n migrationId: string,\n batchSize?: number,\n ): Promise<PlanMigrationBatchResult> {\n return this.queries.migratePlanBatch(migrationId, batchSize);\n }\n\n async revokeCreditsByEntryType(userId: string, entryType: string): Promise<RevokeCreditsResult> {\n const result = await this.queries.revokeCreditsByEntryType(userId, entryType);\n if (result.revoked.gt(0)) {\n this.emit(\"credits.revoked\", userId, {\n userId,\n entryType,\n amount: result.revoked,\n balanceAfter: result.balanceAfter,\n });\n }\n return result;\n }\n\n /** Execute an application-driven catalog grant program. */\n async executeGrantProgram(\n request: ExecuteGrantProgramRequest,\n ): Promise<GrantProgramAwardResult[]> {\n return this.instrumentation.run(\"credits.grant_program\", undefined, () =>\n this.store.executeGrantProgram(request),\n );\n }\n\n async getLedgerEntry(userId: string, entryId: string): Promise<LedgerEntry | null> {\n return this.queries.getLedgerEntry(userId, entryId);\n }\n\n async getAvailable(userId: string): Promise<AvailableResult> {\n return this.queries.getAvailable(userId);\n }\n\n async aggregateStats(start: Date, end: Date): Promise<AggregateStats> {\n return this.queries.aggregateStats(start, end);\n }\n\n async spendByUser(start: Date, end: Date): Promise<SpendByUserRow[]> {\n return this.queries.spendByUser(start, end);\n }\n\n async spendByModel(start: Date, end: Date): Promise<SpendByModelRow[]> {\n return this.queries.spendByModel(start, end);\n }\n\n async listLedgerEntries(userId: string, options?: ListLedgerEntriesOptions): Promise<LedgerPage> {\n return this.queries.listLedgerEntries(userId, options);\n }\n\n async listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage> {\n return this.queries.listUsageEntries(userId, options);\n }\n\n async listUsageCharges(\n userId: string,\n options?: ListUsageChargesOptions,\n ): Promise<UsageChargePage> {\n return this.queries.listUsageCharges(userId, options);\n }\n\n async topUsers(limit: number, start: Date, end: Date): Promise<TopUserRow[]> {\n return this.queries.topUsers(limit, start, end);\n }\n\n async dailySpend(start: Date, end: Date): Promise<DailySpendRow[]> {\n return this.queries.dailySpend(start, end);\n }\n\n /** Emit a credit lifecycle event. No-op if no emitter is configured. */\n private emit(type: CreditEventType, userId: string, data?: StructuredObject): void {\n this.emitter?.emit({ type, timestamp: new Date(), userId, data });\n }\n\n private async emitQuotaEvents(userId: string, idempotencyKey: string): Promise<void> {\n const events = await this.store.listQuotaEvents(userId, {\n idempotencyKey,\n limit: 100,\n });\n for (const event of events) {\n const data = {\n quotaKey: event.quotaKey,\n operation: event.operation,\n measure: event.measure,\n thresholdPercent: event.thresholdPercent,\n usageChargeId: event.usageChargeId,\n idempotencyKey: event.idempotencyKey,\n };\n if (event.eventType === \"blocked\") {\n this.emit(\"credits.quota_blocked\", userId, data);\n } else {\n this.emit(\"credits.quota_threshold\", userId, data);\n }\n }\n }\n\n /** Load the active catalog revision from the store. */\n async loadCatalogFromStore(): Promise<void> {\n await this.catalogRuntime.loadFromStore();\n }\n\n /**\n * If the cached PricingEngine is stale (TTL expired), reload it from the\n * store. Concurrent callers are deduplicated via the underlying\n * ``lru-cache.fetch()`` — only one ``loadCatalogFromStore`` runs and all\n * callers await the same result.\n *\n * When ``catalogCacheTtlMs`` is ``0``, this is a no-op (the consumer must call\n * ``loadCatalogFromStore`` manually).\n */\n async refreshCatalogIfStale(): Promise<void> {\n await this.catalogRuntime.refreshIfStale();\n }\n\n /**\n * Invalidate the catalog cache so the next ``refreshCatalogIfStale`` call\n * reloads from the store. Useful after a manual ``loadCatalogFromStore``\n * that bypasses the cache, or when the consumer knows the remote config\n * has changed.\n */\n invalidateCatalog(): void {\n this.catalogRuntime.invalidate();\n }\n\n /**\n * Publish and activate a catalog revision, then update the local engine.\n *\n * The store write is awaited, so\n * a persistence failure surfaces to the caller instead of becoming an\n * unhandled promise rejection.\n */\n async publishAndActivateCatalog(\n config: BursarConfigData,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string> {\n return this.catalogRuntime.publishAndActivate(config, label, rollout);\n }\n\n /** Publish a validated, inactive catalog draft. */\n async publishCatalogDraft(config: BursarConfigData, label?: string | null): Promise<string> {\n return this.catalogRuntime.publishDraft(config, label);\n }\n\n /** Activate an existing catalog version and reload the local engine. */\n async activateCatalogRevision(version: number, rollout?: CatalogRollout | null): Promise<string> {\n return this.catalogRuntime.activateRevision(version, rollout);\n }\n\n /** The current PricingEngine, or null if not loaded. */\n get pricingEngine(): PricingEngine | null {\n return this.catalogRuntime.currentEngine;\n }\n\n /**\n * Set a user's subscription plan and emit ``credits.plan_changed``.\n *\n * The store call is awaited so a persistence failure surfaces to the caller.\n * The event is emitted only after the store write succeeds.\n */\n async setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt?: Date | null,\n ): Promise<SetUserPlanResult> {\n this.logger.info(\"[CreditsService] setUserPlan\", { planKey, planAssignedAt });\n const result = await this.store.setUserPlan(userId, planKey, planAssignedAt);\n this.emit(\"credits.plan_changed\", userId, {\n userId,\n planKey,\n planAssignedAt: result.planAssignedAt?.toISOString() ?? null,\n assignmentState: result.assignmentState,\n timestamp: new Date().toISOString(),\n });\n return result;\n }\n\n /** Unset a user's subscription plan and emit the plan-change event. */\n async unsetUserPlan(userId: string): Promise<UnsetUserPlanResult> {\n const result = await this.store.unsetUserPlan(userId);\n this.emit(\"credits.plan_changed\", userId, {\n userId,\n planKey: null,\n timestamp: new Date().toISOString(),\n });\n return result;\n }\n\n /** Pin or unpin the user's current assignment revision. */\n async setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean> {\n return this.store.setPlanRevisionPin(userId, pinned);\n }\n\n /** Apply one bounded batch of renewal-effective plan changes. */\n async applyDuePlanChanges(limit = 100): Promise<number> {\n return this.store.applyDuePlanChanges(limit);\n }\n\n /** Sweep this user's expired lots when lazy expiry is enabled. */\n private async maybeLazyExpire(userId: string): Promise<void> {\n if (!this.lazyExpiry) return;\n await this.runSweep(false, userId);\n }\n\n async getBalance(userId: string): Promise<BalanceResult> {\n await this.maybeLazyExpire(userId);\n return await this.store.getBalance(userId);\n }\n\n /** Add credits to a user's account. */\n async addCredits(\n userId: string,\n amount: ExactAmount,\n options: AddCreditsOptions,\n ): Promise<AddCreditsResult> {\n return this.instrumentation.run(\"credits.grant\", undefined, () =>\n this.addCreditsUninstrumented(userId, amount, options),\n );\n }\n\n private async addCreditsUninstrumented(\n userId: string,\n amount: ExactAmount,\n options: AddCreditsOptions,\n ): Promise<AddCreditsResult> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n const type = options.type ?? \"adjustment\";\n this.logger.info(\"[CreditsService] addCredits\", { amount, type, bucket: options.bucket });\n const result = await this.store.addCredits(userId, positiveAmount(amount, \"addCredits\"), {\n ...options,\n type,\n idempotencyKey,\n });\n this.emit(\"credits.added\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n newBalance: result.newBalance,\n type,\n idempotent: result.idempotent ?? false,\n });\n this.balanceMonitor.rearmAfterCredit(userId, result.newBalance);\n return result;\n }\n\n /**\n * Deduct a raw credit amount from a user's account.\n *\n * Uses the store's `addCredits` with `type='adjustment'` and a negated\n * amount — the existing validation path for negative/zero adjustments.\n * Use this for refund clawbacks and other administrative deductions that\n * bypass the usage-based `deduct()` flow.\n */\n async deductCredits(\n userId: string,\n amount: ExactAmount,\n options: DeductCreditsOptions,\n ): Promise<AddCreditsResult> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n const entryType = options.entryType ?? \"adjustment\";\n this.logger.info(\"[CreditsService] deductCredits\", {\n amount,\n entryType,\n bucket: options.bucket,\n });\n const result = await this.store.addCredits(\n userId,\n positiveAmount(amount, \"deductCredits\").neg(),\n {\n type: entryType,\n metadata: options.metadata,\n bucket: options.bucket,\n idempotencyKey,\n },\n );\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n newBalance: result.newBalance,\n entryType,\n idempotent: result.idempotent ?? false,\n });\n if (!result.idempotent) {\n await this.afterDeduction(userId, \"raw\", {\n entryId: result.entryId,\n userId,\n amount: result.amount.abs(),\n allowanceConsumed: new Decimal(0),\n balanceAfter: result.newBalance,\n idempotent: false,\n usageChargeId: null,\n error: null,\n bucketBreakdown: null,\n });\n }\n return result;\n }\n\n /**\n * Grant one billing-cycle's worth of credits — idempotent-safe for a\n * payment-provider webhook handler (Stripe, etc. — bursar stays\n * provider-agnostic) to call even on webhook redelivery.\n *\n * 1. At most one of ``expiresAt``/``ttlDays`` may be given (throws\n * ``ConfigError`` otherwise).\n * 2. When ``ttlDays`` is given, ``expiresAt = now + ttlDays`` days.\n * 3. The new cycle is granted via a direct ``store.addCredits`` call\n * (bypassing {@link addCredits} so only ``credits.cycle_renewed`` fires,\n * not a duplicate ``credits.added``), threading ``idempotencyKey`` so a\n * redelivered webhook replays the prior grant instead of double-crediting.\n * 4. Existing bucket credits are never removed here. Subscription renewal\n * policies that replace prior lots run atomically through BillingService.\n * 5. When ``planKey`` is given, assigns it via {@link setUserPlan}.\n * 6. Emits ``credits.cycle_renewed`` and returns the grant result.\n */\n async grantSubscriptionCycle(\n userId: string,\n amount: ExactAmount,\n options: GrantSubscriptionCycleOptions,\n ): Promise<AddCreditsResult> {\n return this.instrumentation.run(\"credits.grant_subscription_cycle\", undefined, () =>\n this.grantSubscriptionCycleUninstrumented(userId, amount, options),\n );\n }\n\n private async grantSubscriptionCycleUninstrumented(\n userId: string,\n amount: ExactAmount,\n options: GrantSubscriptionCycleOptions,\n ): Promise<AddCreditsResult> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n this.logger.info(\"[CreditsService] grantSubscriptionCycle\", {\n amount,\n bucket: options.bucket,\n planKey: options.planKey,\n });\n if (options.expiresAt != null && options.ttlDays != null) {\n throw new ConfigError(\n \"grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both\",\n );\n }\n const bucket = options.bucket ?? \"subscription\";\n const expiresAt: Date | undefined =\n options.ttlDays != null\n ? new Date(Date.now() + options.ttlDays * 86_400_000)\n : options.expiresAt;\n const amountDec = positiveAmount(amount, \"grantSubscriptionCycle\");\n\n const result = await this.store.addCredits(userId, amountDec, {\n type: \"purchase\",\n metadata: options.metadata,\n expiresAt,\n bucket,\n idempotencyKey,\n });\n\n // The store contract exposes the mutation's replay result directly, avoiding\n // a racy lifetime-balance comparison and an extra database round trip.\n const isFreshGrant = !result.idempotent;\n if (options.planKey) {\n // A fresh cycle intentionally re-anchors plan-assignment windows. On a\n // webhook replay, repair a previously interrupted grant->assignment saga\n // without re-anchoring an assignment that already succeeded.\n if (isFreshGrant || (await this.getUserPlan(userId)).planKey !== options.planKey) {\n await this.setUserPlan(userId, options.planKey);\n }\n }\n\n this.emit(\"credits.cycle_renewed\", userId, {\n entryId: result.entryId,\n amount: amountDec,\n newBalance: result.newBalance,\n bucket,\n planKey: options.planKey ?? null,\n idempotencyKey,\n idempotent: result.idempotent,\n });\n\n return result;\n }\n\n // ── Lease lifecycle: atomic admission ───────────────────────────────\n\n async reserve(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options: ReserveOptions,\n ): Promise<LeaseSuccess> {\n return this.instrumentation.run(\"credits.reserve\", undefined, () =>\n this.leases.reserve(userId, metricsOrAmount, options),\n );\n }\n\n async settle(\n userId: string,\n leaseId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: SettleOptions,\n ): Promise<DeductionResult> {\n return this.instrumentation.run(\"credits.settle\", undefined, () =>\n this.leases.settle(userId, leaseId, metricsOrAmount, options),\n );\n }\n\n async release(userId: string, leaseId: string): Promise<ReleaseResult> {\n return this.instrumentation.run(\"credits.release\", undefined, () =>\n this.leases.release(userId, leaseId),\n );\n }\n\n async renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseSuccess> {\n return this.leases.renew(userId, leaseId, ttl);\n }\n\n async canAfford(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: CanAffordOptions,\n ): Promise<CanAffordResult> {\n return this.leases.canAfford(userId, metricsOrAmount, options);\n }\n\n async getBucketBalances(userId: string): Promise<BucketBalancesResult> {\n return this.leases.getBucketBalances(userId);\n }\n\n async checkAllowance(userId: string): Promise<AllowanceResult | null> {\n return this.leases.checkAllowance(userId);\n }\n\n async runBilled<T>(\n userId: string,\n options: RunBilledOptions<T>,\n ): Promise<{ result: T; deduction: DeductionResult }> {\n return this.leases.runBilled(userId, options);\n }\n\n async beginBilledOperation(\n userId: string,\n options: BeginBilledOperationOptions,\n ): Promise<BilledOperation> {\n return this.leases.beginBilledOperation(userId, options);\n }\n\n /**\n * Full deduction flow as one atomic store call.\n *\n * 1. ``breakdown = engine.calculate(metrics)``; ``cost = breakdown.total``\n * (exact `Decimal`, **no truncation**).\n * 2. ``store.deductWithAllowance`` records the usage, enforces policy, consumes\n * allowance, and debits any remainder — idempotency-keyed end-to-end.\n *\n * On a store ``error`` a ``credits.deduct_failed`` event is emitted and a\n * typed exception is thrown. No success event is emitted on error.\n */\n async deduct(\n userId: string,\n metrics: UsageMetrics,\n options: DeductOptions,\n ): Promise<DeductionResult> {\n return this.instrumentation.run(\"credits.deduct\", undefined, () =>\n this.deductUninstrumented(userId, metrics, options),\n );\n }\n\n private async deductUninstrumented(\n userId: string,\n metrics: UsageMetrics,\n options: DeductOptions,\n ): Promise<DeductionResult> {\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] deduct\", {\n model: metrics.dimensions?.model,\n feature: options.feature,\n });\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);\n const model = z.string().safeParse(metrics.dimensions?.model).data ?? null;\n const region = z.string().safeParse(metrics.dimensions?.region).data ?? null;\n\n // 1) Calculate cost as an exact Decimal, never truncated.\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const cost = breakdown.total;\n\n // Build ledger metadata: caller fields FIRST, system fields LAST so the\n // protected system fields win.\n const meta: CreditMetadata = {};\n if (options.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) meta[k] = v;\n }\n }\n meta[\"operation\"] = metrics.operation;\n meta[\"measures\"] = { ...(metrics.measures ?? {}) };\n meta[\"dimensions\"] = { ...(metrics.dimensions ?? {}) };\n meta[\"breakdownTotal\"] = breakdown.total.toString();\n meta[\"idempotencyKey\"] = effectiveIdempotencyKey;\n\n const deductionOptions: DeductWithAllowanceOptions = {\n idempotencyKey: effectiveIdempotencyKey,\n operation: metrics.operation,\n feature: options.feature ?? null,\n model,\n region,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: { ...(metrics.dimensions ?? {}) },\n metadata: meta,\n };\n\n // 2) Atomic charge. This records zero-cost usage too, so authorization,\n // quotas, and usage history cannot be bypassed by a free rate.\n const result = await this.store.deductWithAllowance(userId, cost, deductionOptions);\n\n if (result.error !== null) {\n if (result.error === \"quota_exceeded\") {\n await this.emitQuotaEvents(userId, effectiveIdempotencyKey);\n }\n this.logger.warn(\"[CreditsService] deduct failed\", {\n error: result.error,\n amount: cost,\n model: metrics.dimensions?.model,\n feature: options.feature,\n });\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount: cost,\n model: metrics.dimensions?.model ?? null,\n });\n raiseDeductError(result.error, userId, cost);\n }\n\n // Success — emit deducted, then any cap warning, then edge-triggered low-balance.\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n allowanceConsumed: result.allowanceConsumed,\n balanceAfter: result.balanceAfter,\n model: metrics.dimensions?.model ?? null,\n idempotent: result.idempotent,\n });\n\n // low_balance is edge-triggered: only fire when this deduction crossed\n // the threshold. A replayed (idempotent) result did not move the balance, so\n // it never crosses. balanceBefore = balanceAfter + amount charged.\n if (!result.idempotent) {\n const balanceBefore = result.balanceAfter.plus(result.amount);\n await this.balanceMonitor.signalCrossing(userId, balanceBefore, result.balanceAfter);\n await this.emitQuotaEvents(userId, effectiveIdempotencyKey);\n await this.afterDeduction(userId, \"deduct\", result);\n }\n\n return result;\n }\n\n /**\n * Record priced usage for a workflow without debiting the account again.\n *\n * This supports priced usage receipts that should be retained without\n * affecting the account balance, such as externally billed usage.\n */\n async recordUsage(\n userId: string,\n metrics: UsageMetrics,\n options: RecordUsageOptions,\n ): Promise<UsageRecordResult> {\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);\n const model = z.string().safeParse(metrics.dimensions?.model).data ?? null;\n const region = z.string().safeParse(metrics.dimensions?.region).data ?? null;\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const meta: CreditMetadata = {};\n if (options.metadata) {\n for (const [key, value] of Object.entries(options.metadata)) {\n if (value != null) meta[key] = value;\n }\n }\n meta.operation = metrics.operation;\n meta.measures = { ...(metrics.measures ?? {}) };\n meta.dimensions = { ...(metrics.dimensions ?? {}) };\n meta.breakdownTotal = breakdown.total.toString();\n meta.idempotencyKey = effectiveIdempotencyKey;\n\n const result = await this.store.recordUsage(userId, metrics.operation, breakdown.total, {\n idempotencyKey: effectiveIdempotencyKey,\n operation: metrics.operation,\n model,\n region,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: { ...(metrics.dimensions ?? {}) },\n metadata: meta,\n });\n if (result.error !== null) {\n throw new StoreError(`Usage record failed: ${result.error}`);\n }\n return result;\n }\n\n /**\n * Refund a previous credit deduction.\n *\n * Returns the RefundResult. A successful refund\n * emits ``credits.refunded``; a failed/duplicate/over-refund emits\n * ``credits.refund_failed`` (no success event is ever emitted for a failed\n * refund).\n */\n /** Deduct the configured fixed cost for one named job. */\n async deductFlatJob(\n userId: string,\n jobName: string,\n options: DeductFlatJobOptions,\n ): Promise<DeductionResult> {\n return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } }, options);\n }\n\n async refundCredits(entryId: string, options: RefundCreditsOptions): Promise<RefundSuccess> {\n return this.instrumentation.run(\"credits.refund\", undefined, () =>\n this.refundCreditsUninstrumented(entryId, options),\n );\n }\n\n private async refundCreditsUninstrumented(\n entryId: string,\n options: RefundCreditsOptions,\n ): Promise<RefundSuccess> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n const refundAmount =\n options.amount != null ? positiveAmount(options.amount, \"refundCredits\") : undefined;\n this.logger.info(\"[CreditsService] refundCredits\", {\n entryId,\n refundAmount,\n reason: options.reason,\n });\n const result = await this.store.refundCredits(entryId, {\n ...options,\n amount: refundAmount,\n idempotencyKey,\n });\n\n if (result.error !== null) {\n this.logger.warn(\"[CreditsService] refundCredits failed\", {\n entryId,\n error: result.error,\n });\n if (result.userId !== null) {\n this.emit(\"credits.refund_failed\", result.userId, {\n entryId,\n error: result.error,\n reason: options.reason ?? null,\n });\n }\n throw new RefundError(`Refund rejected: ${result.error}`);\n }\n\n this.emit(\"credits.refunded\", result.userId, {\n entryId,\n refundEntryId: result.refundEntryId,\n amount: result.amount,\n newBalance: result.newBalance,\n reason: options.reason ?? null,\n });\n return result;\n }\n\n /**\n * Deduct from a team's shared balance pool.\n *\n * Calculates the cost via the pricing engine (exact `Decimal`, no truncation),\n * then debits the team balance. Threads a required ``idempotencyKey`` through\n * to the store so retried team charges are not double-counted.\n */\n async deductTeam(\n teamId: string,\n userId: string,\n metrics: UsageMetrics,\n options: DeductTeamOptions,\n ): Promise<TeamDeductionResult> {\n const idempotencyKey = requireStableKey(options?.idempotencyKey);\n await this.maybeLazyExpire(userId);\n // Lazy expiry is scoped to the individual member's credits, not the team's\n // shared pool — there's no per-team expiry concept.\n const engine = await this.catalogRuntime.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const cost = breakdown.total;\n\n if (cost.lte(0)) {\n const teamBal = await this.store.getTeamBalance(teamId);\n if (teamBal === null) {\n throw new StoreError(`Team not found: ${teamId}`);\n }\n return {\n entryId: null,\n teamId,\n userId,\n amount: new Decimal(0),\n teamBalanceAfter: teamBal.balance,\n idempotent: false,\n error: null,\n };\n }\n\n const teamMetadata: CreditMetadata = {\n ...(options.metadata ?? {}),\n operation: metrics.operation,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: Object.fromEntries(\n Object.entries(metrics.dimensions ?? {}).map(([key, value]) => [key, String(value)]),\n ),\n breakdownTotal: breakdown.total.toString(),\n };\n const result = await this.store.deductTeam(teamId, userId, cost, {\n metadata: teamMetadata,\n idempotencyKey,\n });\n // Surface store errors: emit credits.deduct_failed and throw,\n // mirroring the Python credit service implementation. Previously returned a silent\n // success-shaped object with an .error field, so failed charges looked OK.\n if (result.error !== null) {\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount: cost,\n teamId,\n deductType: \"team\",\n });\n if (result.error === \"member_spend_cap_exceeded\") {\n throw new CapReachedError(\n `Team member spend cap exceeded. Team=${teamId}, user=${userId}, requested=${cost}`,\n );\n }\n throw new InsufficientCreditsError(\n `Team deduction failed: ${result.error}. Team=${teamId}, user=${userId}, requested=${cost}`,\n );\n }\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n teamBalanceAfter: result.teamBalanceAfter,\n teamId,\n deductType: \"team\",\n });\n return result;\n }\n private async runSweep(dryRun: boolean, userId?: string): Promise<SweepResult> {\n const result = await this.store.sweepExpiredCredits(dryRun, userId);\n if (!dryRun && result.expiredCount > 0) {\n this.emit(\"credits.expired\", userId ?? \"system\", {\n expiredCount: result.expiredCount,\n expiredAmount: result.expiredAmount,\n expiredByBucket: result.expiredByBucket ?? null,\n });\n }\n return result;\n }\n\n /**\n * Sweep expired credits from all users' balances.\n *\n * When ``dryRun`` is true, reports what would expire without mutating\n * balances. Automatic lazy sweeps remain scoped to one subject.\n */\n async sweepExpiredCredits(dryRun = false): Promise<SweepResult> {\n return await this.runSweep(dryRun);\n }\n}\n"]}
|
package/dist/credits/store.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Decimal } from "decimal.js";
|
|
2
|
+
import type { JsonObject } from "../shared/json.js";
|
|
2
3
|
import type { AddCreditsResult, AddTeamMemberResult, AggregateStats, AllowanceResult, AvailableResult, BalanceResult, BillingMode, BucketBalancesResult, CheckFeatureResult, CreateTeamResult, CreditMetadata, DailySpendRow, DeductionResult, DeductWithAllowanceOptions, ExecuteGrantProgramRequest, GrantProgramAwardResult, GetUserPlanResult, ListQuotaEventsOptions, PlanMigrationBatchResult, PlanMigrationStartResult, QuotaEvent, QuotaState, LeaseResult, LeasePricingContext, ListLedgerEntriesOptions, ListUsageChargesOptions, ListUsageEntriesOptions, LedgerPage, UsageChargePage, UsageRecordResult, CatalogRevisionSummary, CatalogRevision, RefundResult, RevokeCreditsResult, ReleaseResult, SetUserPlanResult, UnsetUserPlanResult, SpendByModelRow, SpendByUserRow, SweepResult, TeamBalanceResult, TeamDeductionResult, TeamMember, TeamRole, TopUserRow, LedgerEntry } from "./types/index.js";
|
|
3
4
|
import type { BursarConfigData, CatalogRollout } from "../config.js";
|
|
4
5
|
import type { ProviderEnvironment } from "../providers/environment.js";
|
|
@@ -8,8 +9,8 @@ export interface OperationUsageOptions {
|
|
|
8
9
|
feature?: string | null;
|
|
9
10
|
model?: string | null;
|
|
10
11
|
region?: string | null;
|
|
11
|
-
measures?: Record<string,
|
|
12
|
-
dimensions?: Record<string,
|
|
12
|
+
measures?: Record<string, string | number | boolean | Decimal.Value> | null;
|
|
13
|
+
dimensions?: Record<string, string | number | boolean | Decimal.Value> | null;
|
|
13
14
|
}
|
|
14
15
|
/** Options for atomically acquiring a lease. */
|
|
15
16
|
export interface CreateLeaseOptions extends OperationUsageOptions {
|
|
@@ -110,8 +111,8 @@ export declare abstract class CreditStore {
|
|
|
110
111
|
*/
|
|
111
112
|
abstract getAvailable(userId: string): Promise<AvailableResult>;
|
|
112
113
|
abstract getActiveCatalog(): Promise<CatalogRevision | null>;
|
|
113
|
-
abstract publishAndActivateCatalog(config: BursarConfigData, label?: string | null, rollout?: CatalogRollout | null): Promise<string>;
|
|
114
|
-
abstract publishCatalogDraft(config: BursarConfigData, label?: string | null): Promise<string>;
|
|
114
|
+
abstract publishAndActivateCatalog(config: BursarConfigData | JsonObject, label?: string | null, rollout?: CatalogRollout | null): Promise<string>;
|
|
115
|
+
abstract publishCatalogDraft(config: BursarConfigData | JsonObject, label?: string | null): Promise<string>;
|
|
115
116
|
abstract getCatalogHistory(): Promise<CatalogRevisionSummary[]>;
|
|
116
117
|
abstract getCatalogRevision(version: number): Promise<CatalogRevision | null>;
|
|
117
118
|
abstract activateCatalogRevision(version: number, rollout?: CatalogRollout | null): Promise<string>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/credits/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/credits/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD,OAAO,KAAK,EACV,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,eAAe,EACf,aAAa,EACb,WAAW,EACX,oBAAoB,EACpB,kBAAkB,EAClB,gBAAgB,EAChB,cAAc,EACd,aAAa,EACb,eAAe,EACf,0BAA0B,EAC1B,0BAA0B,EAC1B,uBAAuB,EACvB,iBAAiB,EACjB,sBAAsB,EACtB,wBAAwB,EACxB,wB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U,CACd,OAAe,EACf,OAAe,EACf,OAAgB,EAChB,QAA2B;QAE3B,MAAM,IAAI,2BAA2B,CAAC,2CAA2C,CAAC,CAAC;IACrF,CAAC;CACF","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport { CapabilityNotSupportedError } from \"../errors.js\";\nimport type {\n AddCreditsResult,\n AddTeamMemberResult,\n AggregateStats,\n AllowanceResult,\n AvailableResult,\n BalanceResult,\n BillingMode,\n BucketBalancesResult,\n CheckFeatureResult,\n CreateTeamResult,\n CreditMetadata,\n DailySpendRow,\n DeductionResult,\n DeductWithAllowanceOptions,\n ExecuteGrantProgramRequest,\n GrantProgramAwardResult,\n GetUserPlanResult,\n ListQuotaEventsOptions,\n PlanMigrationBatchResult,\n PlanMigrationStartResult,\n QuotaEvent,\n QuotaState,\n LeaseResult,\n LeasePricingContext,\n ListLedgerEntriesOptions,\n ListUsageChargesOptions,\n ListUsageEntriesOptions,\n LedgerPage,\n UsageChargePage,\n UsageRecordResult,\n CatalogRevisionSummary,\n CatalogRevision,\n RefundResult,\n RevokeCreditsResult,\n ReleaseResult,\n SetUserPlanResult,\n UnsetUserPlanResult,\n SpendByModelRow,\n SpendByUserRow,\n SweepResult,\n TeamBalanceResult,\n TeamDeductionResult,\n TeamMember,\n TeamRole,\n TopUserRow,\n LedgerEntry,\n} from \"./types/index.js\";\nimport type { BursarConfigData, CatalogRollout } from \"../config.js\";\nimport type { ProviderEnvironment } from \"../providers/environment.js\";\nimport type {\n AddCreditsOptions,\n DeductTeamOptions,\n RefundCreditsOptions,\n} from \"./service-types.js\";\n\nexport interface OperationUsageOptions {\n /** Entitlement feature that must be enabled for the operation. */\n feature?: string | null;\n model?: string | null;\n region?: string | null;\n measures?: Record<string, unknown> | null;\n dimensions?: Record<string, unknown> | null;\n}\n\n/** Options for atomically acquiring a lease. */\nexport interface CreateLeaseOptions extends OperationUsageOptions {\n /**\n * Replay-safe acquisition key. Supplying the same key with the same request\n * returns the original lease; conflicting reuse is rejected.\n */\n idempotencyKey: string;\n billingMode?: BillingMode;\n floor?: Decimal;\n maxConcurrent?: number | null;\n overdraftFloor?: Decimal | null;\n ttlSeconds?: number;\n metadata?: CreditMetadata | null;\n}\n\n/** Options for replay-safe team creation. */\nexport interface CreateTeamOptions {\n /**\n * Caller-owned operation key. Reusing it with the same request returns the\n * original team; changing the owner, name, or balance is rejected.\n */\n idempotencyKey: string;\n initialBalance?: Decimal;\n}\n\n/** Options for charging the actual cost against a lease. */\nexport interface SettleLeaseOptions extends OperationUsageOptions {\n idempotencyKey?: string;\n metadata?: CreditMetadata | null;\n}\n\n/**\n * Abstract base for credit storage backends.\n *\n * Split into two tiers:\n * - **Core** (abstract, must be implemented): balance/credit ops, the atomic\n * lease lifecycle, bursar-config versioning, plan management,\n * refunds, and expiry sweeping. Every backend needs these.\n * - **Optional capabilities** (concrete, default-throwing): usage analytics,\n * ledger listing, and shared team-balance pools. A custom store that\n * doesn't need these can skip them entirely — the default implementation\n * throws {@link CapabilityNotSupportedError} instead of forcing a stub.\n */\nexport abstract class CreditStore {\n /** Optional provider namespace exposed by environment-aware stores. */\n readonly providerEnvironment?: ProviderEnvironment;\n constructor() {}\n\n abstract getBalance(userId: string): Promise<BalanceResult>;\n abstract addCredits(\n userId: string,\n amount: Decimal,\n options: AddCreditsOptions,\n ): Promise<AddCreditsResult>;\n /**\n * Atomically calculate-and-charge in one server-side transaction:\n * consume free allowance, enforce plan policy and quotas, and debit the net\n * amount, idempotency-keyed end-to-end.\n */\n abstract deductWithAllowance(\n userId: string,\n amount: Decimal,\n options: DeductWithAllowanceOptions,\n ): Promise<DeductionResult>;\n\n // ── Lease lifecycle (atomic admission) ─────────────────────────────\n //\n // The lease is the canonical admission primitive.\n // ``reserve``/``settle``/``release`` on the manager map onto these.\n // Leases reuse the credit_reservations table/records extended with a status\n // (active → settled | released | expired), a billing mode, and an overdraft\n // floor. ``available = balance − Σ(amount WHERE status='active' AND unexpired)``.\n\n /**\n * Atomically acquire a lease (hold) — the only authoritative admission control.\n *\n * Under one critical section the store: (1) ensures the balance row exists;\n * (2) enforces ``maxConcurrent`` by counting active leases for ``(userId,\n * operationType)``; (3) enforces plan entitlements and quotas; (4) computes\n * ``available = balance − Σ active holds`` and rejects with\n * ``error=\"insufficient_credits\"`` if ``available − amount < floor``; (5) inserts\n * an ``active`` lease expiring after ``ttlSeconds``. Business failures are\n * returned via ``LeaseResult.error``; the store never raises domain exceptions.\n */\n abstract createLease(\n userId: string,\n amount: Decimal,\n operationType: string,\n options: CreateLeaseOptions,\n ): Promise<LeaseResult>;\n\n /**\n * Charge the actual cost against a lease, then mark it settled.\n *\n * De-clamped: charges ``amount`` even if it exceeds the lease hold (overdraft)\n * and never clamps to the reserved ceiling. The balance may go negative in\n * overdraft. ``amount === 0`` releases the lease without charging.\n * Lease-state failures (``lease_not_found``/``lease_expired``) are returned via\n * ``DeductionResult.error``; a replay returns the original result idempotently.\n */\n abstract settleLease(\n userId: string,\n leaseId: string,\n amount: Decimal,\n options?: SettleLeaseOptions,\n ): Promise<DeductionResult>;\n\n /** Read the immutable catalog and rate card captured at lease admission. */\n abstract getLeasePricingContext(\n userId: string,\n leaseId: string,\n ): Promise<LeasePricingContext | null>;\n\n /**\n * Release a lease without charging; safe to repeat after failed or aborted work.\n *\n * Transitions an ``active``/``expired`` lease to ``released`` and reports\n * ``released=true``; otherwise reports ``released=false`` with a ``reason``.\n */\n abstract releaseLease(userId: string, leaseId: string): Promise<ReleaseResult>;\n\n /**\n * Extend an active lease's TTL (long batch/agentic jobs, resolves B4).\n *\n * Returns ``error=\"lease_expired\"`` if the TTL already elapsed and\n * ``error=\"lease_not_found\"`` if missing/other-user/finalized.\n */\n abstract renewLease(userId: string, leaseId: string, ttlSeconds: number): Promise<LeaseResult>;\n\n /** Expire a bounded batch of abandoned leases and release their reservations. */\n async expireLeases(_limit?: number): Promise<number> {\n throw new CapabilityNotSupportedError(\"expireLeases is not supported by this store\");\n }\n\n /**\n * Advisory, non-locking read of ``available = balance − Σ active holds``.\n *\n * For UI only — never an admission gate; may be stale the instant it is read.\n */\n\n abstract getAvailable(userId: string): Promise<AvailableResult>;\n\n abstract getActiveCatalog(): Promise<CatalogRevision | null>;\n abstract publishAndActivateCatalog(\n config: BursarConfigData,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string>;\n abstract publishCatalogDraft(config: BursarConfigData, label?: string | null): Promise<string>;\n\n // Catalog revision history and activation.\n abstract getCatalogHistory(): Promise<CatalogRevisionSummary[]>;\n abstract getCatalogRevision(version: number): Promise<CatalogRevision | null>;\n abstract activateCatalogRevision(\n version: number,\n rollout?: CatalogRollout | null,\n ): Promise<string>;\n\n abstract getUserPlan(userId: string): Promise<GetUserPlanResult>;\n abstract setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt?: Date | null,\n ): Promise<SetUserPlanResult>;\n abstract unsetUserPlan(userId: string): Promise<UnsetUserPlanResult>;\n abstract setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean>;\n abstract applyDuePlanChanges(limit?: number): Promise<number>;\n abstract startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartResult>;\n abstract migratePlanBatch(\n migrationId: string,\n batchSize?: number,\n ): Promise<PlanMigrationBatchResult>;\n abstract checkFeature(userId: string, feature: string): Promise<CheckFeatureResult>;\n abstract getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaState[]>;\n abstract listQuotaEvents(userId: string, options?: ListQuotaEventsOptions): Promise<QuotaEvent[]>;\n abstract checkAllowance(userId: string): Promise<AllowanceResult | null>;\n\n abstract revokeCreditsByEntryType(\n userId: string,\n entryType: string,\n ): Promise<RevokeCreditsResult>;\n\n // ── Refunds ────────────────────────────────────────────────────────\n abstract refundCredits(entryId: string, options: RefundCreditsOptions): Promise<RefundResult>;\n\n // ── Credit expiry ────────────────────────────────────────────────────\n /**\n * Sweep expired credit grants and debit the aggregate/tier balances.\n *\n * When `userId` is omitted (default), sweeps globally across every user —\n * unchanged behaviour/output shape from before this parameter existed. When\n * given, restricts the scan/expiry to that user's transactions only (used by\n * bounded expiry sweep operation).\n */\n abstract sweepExpiredCredits(\n dryRun?: boolean,\n userId?: string,\n limit?: number,\n ): Promise<SweepResult>;\n\n // ── Credit buckets ─────────────────────────────────────────────────────\n /**\n * Per-bucket credit balances for a user (credit buckets).\n *\n * Sorted by `priority` ascending. When no buckets are configured, synthesizes\n * a single `\"default\"` entry from the aggregate balance so the shape is\n * uniform either way.\n */\n abstract getBucketBalances(userId: string): Promise<BucketBalancesResult>;\n\n /** Execute one configured grant-program event. */\n async executeGrantProgram(\n _request: ExecuteGrantProgramRequest,\n ): Promise<GrantProgramAwardResult[]> {\n throw new CapabilityNotSupportedError(\"executeGrantProgram is not supported by this store\");\n }\n\n // ── Usage analytics (optional capability) ────────────────────────────\n async spendByUser(_start: Date, _end: Date): Promise<SpendByUserRow[]> {\n throw new CapabilityNotSupportedError(\"spendByUser is not supported by this store\");\n }\n async spendByModel(_start: Date, _end: Date): Promise<SpendByModelRow[]> {\n throw new CapabilityNotSupportedError(\"spendByModel is not supported by this store\");\n }\n async topUsers(_limit: number, _start: Date, _end: Date): Promise<TopUserRow[]> {\n throw new CapabilityNotSupportedError(\"topUsers is not supported by this store\");\n }\n async dailySpend(_start: Date, _end: Date): Promise<DailySpendRow[]> {\n throw new CapabilityNotSupportedError(\"dailySpend is not supported by this store\");\n }\n async aggregateStats(_start: Date, _end: Date): Promise<AggregateStats> {\n throw new CapabilityNotSupportedError(\"aggregateStats is not supported by this store\");\n }\n\n // ── Transaction listing (optional capability) ────────────────────────\n async listLedgerEntries(\n _userId: string,\n _options?: ListLedgerEntriesOptions,\n ): Promise<LedgerPage> {\n throw new CapabilityNotSupportedError(\"listLedgerEntries is not supported by this store\");\n }\n abstract listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage>;\n\n /** Read metered usage charges, including allowance-covered events. */\n async listUsageCharges(\n _userId: string,\n _options?: ListUsageChargesOptions,\n ): Promise<UsageChargePage> {\n throw new CapabilityNotSupportedError(\"listUsageCharges is not supported by this store\");\n }\n\n /** Append priced usage telemetry without debiting the account again. */\n async recordUsage(\n _userId: string,\n _operation: string,\n _requested: Decimal,\n _options: DeductWithAllowanceOptions,\n ): Promise<UsageRecordResult> {\n throw new CapabilityNotSupportedError(\"recordUsage is not supported by this store\");\n }\n\n // ── Single transaction lookup (optional capability) ──────────────────\n /**\n * Fetch a single transaction by ID. Returns `null` when the transaction\n * does not exist or belongs to a different user.\n */\n async getLedgerEntry(_userId: string, _entryId: string): Promise<LedgerEntry | null> {\n throw new CapabilityNotSupportedError(\"getLedgerEntry is not supported by this store\");\n }\n\n // ── Team/shared balance pools (optional capability) ──────────────────\n async createTeam(\n _ownerSubjectId: string,\n _name: string,\n _options: CreateTeamOptions,\n ): Promise<CreateTeamResult> {\n throw new CapabilityNotSupportedError(\"createTeam is not supported by this store\");\n }\n async getTeamBalance(_teamId: string): Promise<TeamBalanceResult | null> {\n throw new CapabilityNotSupportedError(\"getTeamBalance is not supported by this store\");\n }\n async addTeamMember(\n _teamId: string,\n _userId: string,\n _role?: TeamRole,\n _spendCap?: Decimal | null,\n ): Promise<AddTeamMemberResult> {\n throw new CapabilityNotSupportedError(\"addTeamMember is not supported by this store\");\n }\n async getTeamMembers(_teamId: string): Promise<TeamMember[]> {\n throw new CapabilityNotSupportedError(\"getTeamMembers is not supported by this store\");\n }\n async removeTeamMember(_teamId: string, _userId: string): Promise<boolean> {\n throw new CapabilityNotSupportedError(\"removeTeamMember is not supported by this store\");\n }\n async deductTeam(\n _teamId: string,\n _userId: string,\n _amount: Decimal,\n _options: DeductTeamOptions,\n ): Promise<TeamDeductionResult> {\n throw new CapabilityNotSupportedError(\"deductTeam is not supported by this store\");\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/credits/store.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAiG3D;;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OAAe,EACf,UAAkB,EAClB,UAAmB,EACnB,QAAoC;QAEpC,MAAM,IAAI,2BAA2B,CAAC,4CAA4C,CAAC,CAAC;IACtF,CAAC;IAED,wEAAwE;IACxE;;;OAGG;IACH,KAAK,CAAC,cAAc,CAAC,OAAe,EAAE,QAAgB;QACpD,MAAM,IAAI,2BAA2B,CAAC,+CAA+C,CAAC,CAAC;IACzF,CAAC;IAED,wEAAwE;IACxE,KAAK,CAAC,UAAU,CACd,eAAuB,EACvB,KAAa,EACb,QAA2B;QAE3B,MAAM,IAAI,2BAA2B,CAAC,2CAA2C,CAAC,CAAC;IACrF,CAAC;IACD,KAAK,CAAC,cAAc,CAAC,OAAe;QAClC,MAAM,IAAI,2BAA2B,CAAC,+CAA+C,CAAC,CAAC;IACzF,CAAC;IACD,KAAK,CAAC,aAAa,CACjB,OAAe,EACf,OAAe,EACf,KAAgB,EAChB,SAA0B;QAE1B,MAAM,IAAI,2BAA2B,CAAC,8CAA8C,CAAC,CAAC;IACxF,CAAC;IACD,KAAK,CAAC,cAAc,CAAC,OAAe;QAClC,MAAM,IAAI,2BAA2B,CAAC,+CAA+C,CAAC,CAAC;IACzF,CAAC;IACD,KAAK,CAAC,gBAAgB,CAAC,OAAe,EAAE,OAAe;QACrD,MAAM,IAAI,2BAA2B,CAAC,iDAAiD,CAAC,CAAC;IAC3F,CAAC;IACD,KAAK,CAAC,UAAU,CACd,OAAe,EACf,OAAe,EACf,OAAgB,EAChB,QAA2B;QAE3B,MAAM,IAAI,2BAA2B,CAAC,2CAA2C,CAAC,CAAC;IACrF,CAAC;CACF","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport type { JsonObject } from \"../shared/json.js\";\nimport { CapabilityNotSupportedError } from \"../errors.js\";\nimport type {\n AddCreditsResult,\n AddTeamMemberResult,\n AggregateStats,\n AllowanceResult,\n AvailableResult,\n BalanceResult,\n BillingMode,\n BucketBalancesResult,\n CheckFeatureResult,\n CreateTeamResult,\n CreditMetadata,\n DailySpendRow,\n DeductionResult,\n DeductWithAllowanceOptions,\n ExecuteGrantProgramRequest,\n GrantProgramAwardResult,\n GetUserPlanResult,\n ListQuotaEventsOptions,\n PlanMigrationBatchResult,\n PlanMigrationStartResult,\n QuotaEvent,\n QuotaState,\n LeaseResult,\n LeasePricingContext,\n ListLedgerEntriesOptions,\n ListUsageChargesOptions,\n ListUsageEntriesOptions,\n LedgerPage,\n UsageChargePage,\n UsageRecordResult,\n CatalogRevisionSummary,\n CatalogRevision,\n RefundResult,\n RevokeCreditsResult,\n ReleaseResult,\n SetUserPlanResult,\n UnsetUserPlanResult,\n SpendByModelRow,\n SpendByUserRow,\n SweepResult,\n TeamBalanceResult,\n TeamDeductionResult,\n TeamMember,\n TeamRole,\n TopUserRow,\n LedgerEntry,\n} from \"./types/index.js\";\nimport type { BursarConfigData, CatalogRollout } from \"../config.js\";\nimport type { ProviderEnvironment } from \"../providers/environment.js\";\nimport type {\n AddCreditsOptions,\n DeductTeamOptions,\n RefundCreditsOptions,\n} from \"./service-types.js\";\n\nexport interface OperationUsageOptions {\n /** Entitlement feature that must be enabled for the operation. */\n feature?: string | null;\n model?: string | null;\n region?: string | null;\n measures?: Record<string, string | number | boolean | Decimal.Value> | null;\n dimensions?: Record<string, string | number | boolean | Decimal.Value> | null;\n}\n\n/** Options for atomically acquiring a lease. */\nexport interface CreateLeaseOptions extends OperationUsageOptions {\n /**\n * Replay-safe acquisition key. Supplying the same key with the same request\n * returns the original lease; conflicting reuse is rejected.\n */\n idempotencyKey: string;\n billingMode?: BillingMode;\n floor?: Decimal;\n maxConcurrent?: number | null;\n overdraftFloor?: Decimal | null;\n ttlSeconds?: number;\n metadata?: CreditMetadata | null;\n}\n\n/** Options for replay-safe team creation. */\nexport interface CreateTeamOptions {\n /**\n * Caller-owned operation key. Reusing it with the same request returns the\n * original team; changing the owner, name, or balance is rejected.\n */\n idempotencyKey: string;\n initialBalance?: Decimal;\n}\n\n/** Options for charging the actual cost against a lease. */\nexport interface SettleLeaseOptions extends OperationUsageOptions {\n idempotencyKey?: string;\n metadata?: CreditMetadata | null;\n}\n\n/**\n * Abstract base for credit storage backends.\n *\n * Split into two tiers:\n * - **Core** (abstract, must be implemented): balance/credit ops, the atomic\n * lease lifecycle, bursar-config versioning, plan management,\n * refunds, and expiry sweeping. Every backend needs these.\n * - **Optional capabilities** (concrete, default-throwing): usage analytics,\n * ledger listing, and shared team-balance pools. A custom store that\n * doesn't need these can skip them entirely — the default implementation\n * throws {@link CapabilityNotSupportedError} instead of forcing a stub.\n */\nexport abstract class CreditStore {\n /** Optional provider namespace exposed by environment-aware stores. */\n readonly providerEnvironment?: ProviderEnvironment;\n constructor() {}\n\n abstract getBalance(userId: string): Promise<BalanceResult>;\n abstract addCredits(\n userId: string,\n amount: Decimal,\n options: AddCreditsOptions,\n ): Promise<AddCreditsResult>;\n /**\n * Atomically calculate-and-charge in one server-side transaction:\n * consume free allowance, enforce plan policy and quotas, and debit the net\n * amount, idempotency-keyed end-to-end.\n */\n abstract deductWithAllowance(\n userId: string,\n amount: Decimal,\n options: DeductWithAllowanceOptions,\n ): Promise<DeductionResult>;\n\n // ── Lease lifecycle (atomic admission) ─────────────────────────────\n //\n // The lease is the canonical admission primitive.\n // ``reserve``/``settle``/``release`` on the manager map onto these.\n // Leases reuse the credit_reservations table/records extended with a status\n // (active → settled | released | expired), a billing mode, and an overdraft\n // floor. ``available = balance − Σ(amount WHERE status='active' AND unexpired)``.\n\n /**\n * Atomically acquire a lease (hold) — the only authoritative admission control.\n *\n * Under one critical section the store: (1) ensures the balance row exists;\n * (2) enforces ``maxConcurrent`` by counting active leases for ``(userId,\n * operationType)``; (3) enforces plan entitlements and quotas; (4) computes\n * ``available = balance − Σ active holds`` and rejects with\n * ``error=\"insufficient_credits\"`` if ``available − amount < floor``; (5) inserts\n * an ``active`` lease expiring after ``ttlSeconds``. Business failures are\n * returned via ``LeaseResult.error``; the store never raises domain exceptions.\n */\n abstract createLease(\n userId: string,\n amount: Decimal,\n operationType: string,\n options: CreateLeaseOptions,\n ): Promise<LeaseResult>;\n\n /**\n * Charge the actual cost against a lease, then mark it settled.\n *\n * De-clamped: charges ``amount`` even if it exceeds the lease hold (overdraft)\n * and never clamps to the reserved ceiling. The balance may go negative in\n * overdraft. ``amount === 0`` releases the lease without charging.\n * Lease-state failures (``lease_not_found``/``lease_expired``) are returned via\n * ``DeductionResult.error``; a replay returns the original result idempotently.\n */\n abstract settleLease(\n userId: string,\n leaseId: string,\n amount: Decimal,\n options?: SettleLeaseOptions,\n ): Promise<DeductionResult>;\n\n /** Read the immutable catalog and rate card captured at lease admission. */\n abstract getLeasePricingContext(\n userId: string,\n leaseId: string,\n ): Promise<LeasePricingContext | null>;\n\n /**\n * Release a lease without charging; safe to repeat after failed or aborted work.\n *\n * Transitions an ``active``/``expired`` lease to ``released`` and reports\n * ``released=true``; otherwise reports ``released=false`` with a ``reason``.\n */\n abstract releaseLease(userId: string, leaseId: string): Promise<ReleaseResult>;\n\n /**\n * Extend an active lease's TTL (long batch/agentic jobs, resolves B4).\n *\n * Returns ``error=\"lease_expired\"`` if the TTL already elapsed and\n * ``error=\"lease_not_found\"`` if missing/other-user/finalized.\n */\n abstract renewLease(userId: string, leaseId: string, ttlSeconds: number): Promise<LeaseResult>;\n\n /** Expire a bounded batch of abandoned leases and release their reservations. */\n async expireLeases(_limit?: number): Promise<number> {\n throw new CapabilityNotSupportedError(\"expireLeases is not supported by this store\");\n }\n\n /**\n * Advisory, non-locking read of ``available = balance − Σ active holds``.\n *\n * For UI only — never an admission gate; may be stale the instant it is read.\n */\n\n abstract getAvailable(userId: string): Promise<AvailableResult>;\n\n abstract getActiveCatalog(): Promise<CatalogRevision | null>;\n abstract publishAndActivateCatalog(\n config: BursarConfigData | JsonObject,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string>;\n abstract publishCatalogDraft(\n config: BursarConfigData | JsonObject,\n label?: string | null,\n ): Promise<string>;\n\n // Catalog revision history and activation.\n abstract getCatalogHistory(): Promise<CatalogRevisionSummary[]>;\n abstract getCatalogRevision(version: number): Promise<CatalogRevision | null>;\n abstract activateCatalogRevision(\n version: number,\n rollout?: CatalogRollout | null,\n ): Promise<string>;\n\n abstract getUserPlan(userId: string): Promise<GetUserPlanResult>;\n abstract setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt?: Date | null,\n ): Promise<SetUserPlanResult>;\n abstract unsetUserPlan(userId: string): Promise<UnsetUserPlanResult>;\n abstract setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean>;\n abstract applyDuePlanChanges(limit?: number): Promise<number>;\n abstract startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartResult>;\n abstract migratePlanBatch(\n migrationId: string,\n batchSize?: number,\n ): Promise<PlanMigrationBatchResult>;\n abstract checkFeature(userId: string, feature: string): Promise<CheckFeatureResult>;\n abstract getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaState[]>;\n abstract listQuotaEvents(userId: string, options?: ListQuotaEventsOptions): Promise<QuotaEvent[]>;\n abstract checkAllowance(userId: string): Promise<AllowanceResult | null>;\n\n abstract revokeCreditsByEntryType(\n userId: string,\n entryType: string,\n ): Promise<RevokeCreditsResult>;\n\n // ── Refunds ────────────────────────────────────────────────────────\n abstract refundCredits(entryId: string, options: RefundCreditsOptions): Promise<RefundResult>;\n\n // ── Credit expiry ────────────────────────────────────────────────────\n /**\n * Sweep expired credit grants and debit the aggregate/tier balances.\n *\n * When `userId` is omitted (default), sweeps globally across every user —\n * unchanged behaviour/output shape from before this parameter existed. When\n * given, restricts the scan/expiry to that user's transactions only (used by\n * bounded expiry sweep operation).\n */\n abstract sweepExpiredCredits(\n dryRun?: boolean,\n userId?: string,\n limit?: number,\n ): Promise<SweepResult>;\n\n // ── Credit buckets ─────────────────────────────────────────────────────\n /**\n * Per-bucket credit balances for a user (credit buckets).\n *\n * Sorted by `priority` ascending. When no buckets are configured, synthesizes\n * a single `\"default\"` entry from the aggregate balance so the shape is\n * uniform either way.\n */\n abstract getBucketBalances(userId: string): Promise<BucketBalancesResult>;\n\n /** Execute one configured grant-program event. */\n async executeGrantProgram(\n _request: ExecuteGrantProgramRequest,\n ): Promise<GrantProgramAwardResult[]> {\n throw new CapabilityNotSupportedError(\"executeGrantProgram is not supported by this store\");\n }\n\n // ── Usage analytics (optional capability) ────────────────────────────\n async spendByUser(_start: Date, _end: Date): Promise<SpendByUserRow[]> {\n throw new CapabilityNotSupportedError(\"spendByUser is not supported by this store\");\n }\n async spendByModel(_start: Date, _end: Date): Promise<SpendByModelRow[]> {\n throw new CapabilityNotSupportedError(\"spendByModel is not supported by this store\");\n }\n async topUsers(_limit: number, _start: Date, _end: Date): Promise<TopUserRow[]> {\n throw new CapabilityNotSupportedError(\"topUsers is not supported by this store\");\n }\n async dailySpend(_start: Date, _end: Date): Promise<DailySpendRow[]> {\n throw new CapabilityNotSupportedError(\"dailySpend is not supported by this store\");\n }\n async aggregateStats(_start: Date, _end: Date): Promise<AggregateStats> {\n throw new CapabilityNotSupportedError(\"aggregateStats is not supported by this store\");\n }\n\n // ── Transaction listing (optional capability) ────────────────────────\n async listLedgerEntries(\n _userId: string,\n _options?: ListLedgerEntriesOptions,\n ): Promise<LedgerPage> {\n throw new CapabilityNotSupportedError(\"listLedgerEntries is not supported by this store\");\n }\n abstract listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage>;\n\n /** Read metered usage charges, including allowance-covered events. */\n async listUsageCharges(\n _userId: string,\n _options?: ListUsageChargesOptions,\n ): Promise<UsageChargePage> {\n throw new CapabilityNotSupportedError(\"listUsageCharges is not supported by this store\");\n }\n\n /** Append priced usage telemetry without debiting the account again. */\n async recordUsage(\n _userId: string,\n _operation: string,\n _requested: Decimal,\n _options: DeductWithAllowanceOptions,\n ): Promise<UsageRecordResult> {\n throw new CapabilityNotSupportedError(\"recordUsage is not supported by this store\");\n }\n\n // ── Single transaction lookup (optional capability) ──────────────────\n /**\n * Fetch a single transaction by ID. Returns `null` when the transaction\n * does not exist or belongs to a different user.\n */\n async getLedgerEntry(_userId: string, _entryId: string): Promise<LedgerEntry | null> {\n throw new CapabilityNotSupportedError(\"getLedgerEntry is not supported by this store\");\n }\n\n // ── Team/shared balance pools (optional capability) ──────────────────\n async createTeam(\n _ownerSubjectId: string,\n _name: string,\n _options: CreateTeamOptions,\n ): Promise<CreateTeamResult> {\n throw new CapabilityNotSupportedError(\"createTeam is not supported by this store\");\n }\n async getTeamBalance(_teamId: string): Promise<TeamBalanceResult | null> {\n throw new CapabilityNotSupportedError(\"getTeamBalance is not supported by this store\");\n }\n async addTeamMember(\n _teamId: string,\n _userId: string,\n _role?: TeamRole,\n _spendCap?: Decimal | null,\n ): Promise<AddTeamMemberResult> {\n throw new CapabilityNotSupportedError(\"addTeamMember is not supported by this store\");\n }\n async getTeamMembers(_teamId: string): Promise<TeamMember[]> {\n throw new CapabilityNotSupportedError(\"getTeamMembers is not supported by this store\");\n }\n async removeTeamMember(_teamId: string, _userId: string): Promise<boolean> {\n throw new CapabilityNotSupportedError(\"removeTeamMember is not supported by this store\");\n }\n async deductTeam(\n _teamId: string,\n _userId: string,\n _amount: Decimal,\n _options: DeductTeamOptions,\n ): Promise<TeamDeductionResult> {\n throw new CapabilityNotSupportedError(\"deductTeam is not supported by this store\");\n }\n}\n"]}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import type { Decimal } from "decimal.js";
|
|
2
|
+
import type { StructuredValue } from "../../shared/json.js";
|
|
2
3
|
export type BillingMode = "strict" | "overdraft";
|
|
3
4
|
export interface CreditMetadata {
|
|
4
5
|
operation?: string | null;
|
|
5
|
-
measures?: Record<string,
|
|
6
|
+
measures?: Record<string, string | number | boolean | Decimal.Value> | null;
|
|
6
7
|
dimensions?: Record<string, string | number | boolean | Decimal.Value> | null;
|
|
7
8
|
breakdownTotal?: string | null;
|
|
8
9
|
referenceType?: string | null;
|
|
@@ -11,7 +12,7 @@ export interface CreditMetadata {
|
|
|
11
12
|
providerRequestId?: string | null;
|
|
12
13
|
traceId?: string | null;
|
|
13
14
|
spanId?: string | null;
|
|
14
|
-
[key: string]:
|
|
15
|
+
[key: string]: StructuredValue;
|
|
15
16
|
}
|
|
16
17
|
export interface BucketDefinition {
|
|
17
18
|
label: string;
|
|
@@ -79,8 +80,8 @@ export interface DeductWithAllowanceOptions {
|
|
|
79
80
|
feature?: string | null;
|
|
80
81
|
model?: string | null;
|
|
81
82
|
region?: string | null;
|
|
82
|
-
measures?: Record<string,
|
|
83
|
-
dimensions?: Record<string,
|
|
83
|
+
measures?: Record<string, string | number | boolean | Decimal.Value> | null;
|
|
84
|
+
dimensions?: Record<string, string | number | boolean | Decimal.Value> | null;
|
|
84
85
|
metadata?: CreditMetadata | null;
|
|
85
86
|
}
|
|
86
87
|
interface RefundResultBase {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../../../src/credits/types/account.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../../../src/credits/types/account.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE5D,MAAM,MAAM,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;AAEjD,MAAM,WAAW,cAAc;IAC7B,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC;IAC5E,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC;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-
{"version":3,"file":"account.js","sourceRoot":"","sources":["../../../src/credits/types/account.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\nexport type BillingMode = \"strict\" | \"overdraft\";\n\nexport interface CreditMetadata {\n operation?: string | null;\n measures?: Record<string,
|
|
1
|
+
{"version":3,"file":"account.js","sourceRoot":"","sources":["../../../src/credits/types/account.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport type { StructuredValue } from \"../../shared/json.js\";\n\nexport type BillingMode = \"strict\" | \"overdraft\";\n\nexport interface CreditMetadata {\n operation?: string | null;\n measures?: Record<string, string | number | boolean | Decimal.Value> | null;\n dimensions?: Record<string, string | number | boolean | Decimal.Value> | null;\n breakdownTotal?: string | null;\n referenceType?: string | null;\n referenceId?: string | null;\n idempotencyKey?: string | null;\n providerRequestId?: string | null;\n traceId?: string | null;\n spanId?: string | null;\n [key: string]: StructuredValue;\n}\n\nexport interface BucketDefinition {\n label: string;\n priority: number;\n expires: boolean;\n ttlDays?: number | null;\n allowOverdraft?: boolean;\n default?: boolean;\n}\n\nexport interface BucketBalance {\n bucketKey: string;\n label: string;\n priority: number;\n expires: boolean;\n balance: Decimal;\n}\n\nexport interface BucketBalancesResult {\n userId: string;\n buckets: BucketBalance[];\n totalBalance: Decimal;\n}\n\nexport interface BalanceResult {\n userId: string;\n balance: Decimal;\n lifetimePurchased: Decimal;\n}\n\nexport interface AddCreditsResult {\n entryId: string;\n userId: string;\n amount: Decimal;\n newBalance: Decimal;\n lifetimePurchased: Decimal;\n /** Destination bucket for grants; `null` when a debit spans one or more lots. */\n bucket: string | null;\n idempotent: boolean;\n}\n\ninterface DeductionResultBase {\n userId: string;\n amount: Decimal;\n allowanceConsumed: Decimal;\n idempotent: boolean;\n}\n\n/** A committed usage charge. Allowance-only charges legitimately have no ledger entry. */\nexport interface DeductionSuccess extends DeductionResultBase {\n error: null;\n entryId: string | null;\n /** Canonical usage receipt, including zero-cost or allowance-only charges. */\n usageChargeId: string | null;\n balanceAfter: Decimal;\n bucketBreakdown: Record<string, Decimal> | null;\n}\n\n/** An expected database rejection. Nullable fields were not committed and are not fabricated. */\nexport interface DeductionFailure extends DeductionResultBase {\n error: string;\n entryId: null;\n usageChargeId: string | null;\n balanceAfter: Decimal | null;\n idempotent: false;\n bucketBreakdown: null;\n}\n\nexport type DeductionResult = DeductionSuccess | DeductionFailure;\n\nexport interface DeductWithAllowanceOptions {\n idempotencyKey: string;\n operation?: string | null;\n feature?: string | null;\n model?: string | null;\n region?: string | null;\n measures?: Record<string, string | number | boolean | Decimal.Value> | null;\n dimensions?: Record<string, string | number | boolean | Decimal.Value> | null;\n metadata?: CreditMetadata | null;\n}\n\ninterface RefundResultBase {\n originalEntryId: string;\n userId: string | null;\n}\n\nexport interface RefundSuccess extends RefundResultBase {\n error: null;\n refundEntryId: string;\n userId: string;\n amount: Decimal;\n newBalance: Decimal;\n bucketBreakdown: Record<string, Decimal> | null;\n}\n\nexport interface RefundFailure extends RefundResultBase {\n error: string;\n refundEntryId: null;\n amount: Decimal | null;\n newBalance: Decimal | null;\n bucketBreakdown: null;\n}\n\nexport type RefundResult = RefundSuccess | RefundFailure;\n\n/** Credits removed from all remaining lots created by one ledger operation. */\nexport interface RevokeCreditsResult {\n userId: string;\n entryType: string;\n revoked: Decimal;\n balanceAfter: Decimal;\n}\n\nexport interface SweepResult {\n expiredCount: number;\n expiredAmount: Decimal;\n dryRun: boolean;\n expiredByBucket: Record<string, Decimal>;\n}\n"]}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { Decimal } from "decimal.js";
|
|
2
|
+
import type { JsonObject } from "../../shared/json.js";
|
|
2
3
|
export interface CatalogRevision {
|
|
3
4
|
id: string;
|
|
4
|
-
config:
|
|
5
|
+
config: JsonObject;
|
|
5
6
|
version: number;
|
|
6
7
|
}
|
|
7
8
|
export interface CatalogRevisionSummary {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../../../src/credits/types/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../../../src/credits/types/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAEvD,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,UAAU,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,sBAAsB;IACrC,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,MAAM,EAAE,OAAO,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,OAAO,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,QAAQ,GAAG,QAAQ,GAAG,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;IAC5E,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,UAAU,GAAG,iBAAiB,GAAG,SAAS,CAAC;IACxD,aAAa,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,SAAS,GAAG,aAAa,CAAC;IAChC,WAAW,EAAE,OAAO,GAAG,IAAI,CAAC;CAC7B;AAED,MAAM,WAAW,mBAAmB;IAClC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC,CAAC;CAC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,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,wBAAwB;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,OAAO,CAAC;IACd,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../../src/credits/types/catalog.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\nexport interface CatalogRevision {\n id: string;\n config:
|
|
1
|
+
{"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../../src/credits/types/catalog.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport type { JsonObject } from \"../../shared/json.js\";\n\nexport interface CatalogRevision {\n id: string;\n config: JsonObject;\n version: number;\n}\n\nexport interface CatalogRevisionSummary {\n id: string;\n version: number;\n label: string | null;\n active: boolean;\n createdAt: string;\n}\n\nexport interface PlanAllowancePolicy {\n amount: Decimal;\n priority: number;\n resetUnit: \"second\" | \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"year\";\n resetCount: number;\n resetAnchor: \"calendar\" | \"plan_assignment\" | \"rolling\";\n resetTimezone: string;\n}\n\nexport interface PlanCreditPolicy {\n type: \"prepaid\" | \"credit_line\";\n creditLimit: Decimal | null;\n}\n\nexport interface PlanAdmissionPolicy {\n maxInFlight: number | null;\n operations: Record<string, { maxInFlight: number | null }>;\n}\n\nexport interface AllowanceResult {\n planId: string;\n allowanceRemaining: Decimal;\n periodStart: string;\n periodEnd: string;\n}\n\nexport interface GetUserPlanResult {\n userId: string;\n planId: string | null;\n planKey: string | null;\n planLabel: string | null;\n allowance: PlanAllowancePolicy | null;\n entitlements: Record<string, { value: unknown }>;\n rateCard: string | null;\n creditPolicy: PlanCreditPolicy | null;\n admission: PlanAdmissionPolicy | null;\n allowedOperations: string[];\n planAssignedAt: Date | null;\n planAssignmentEndsAt: Date | null;\n assignmentSourceType: \"manual\" | \"subscription\" | \"migration\" | \"system\" | null;\n assignmentSourceId: string | null;\n catalogRevisionPinned: boolean;\n catalogVersion: number | null;\n}\n\nexport interface SetUserPlanResult {\n userId: string;\n planId: string;\n planKey: string;\n planAssignedAt: Date;\n assignmentState: \"applied\" | \"scheduled\";\n}\n\nexport interface UnsetUserPlanResult {\n userId: string;\n}\n\nexport interface PlanMigrationStartResult {\n migrationId: string;\n}\n\nexport interface PlanMigrationBatchResult {\n migrated: number;\n done: boolean;\n nextCursor: string | null;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"grants.d.ts","sourceRoot":"","sources":["../../../src/credits/types/grants.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAEnD,MAAM,MAAM,mBAAmB,
|
|
1
|
+
{"version":3,"file":"grants.d.ts","sourceRoot":"","sources":["../../../src/credits/types/grants.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAEnD,MAAM,MAAM,mBAAmB,GAC3B,iBAAiB,GACjB,oBAAoB,GACpB,qBAAqB,GACrB,QAAQ,CAAC;AAEb,uEAAuE;AACvE,MAAM,WAAW,0BAA0B;IACzC,OAAO,EAAE,mBAAmB,CAAC;IAC7B,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,QAAQ,CAAC,EAAE,cAAc,GAAG,IAAI,CAAC;CAClC;AAED,UAAU,qBAAqB;IAC7B,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,iEAAiE;AACjE,MAAM,WAAW,wBAAyB,SAAQ,qBAAqB;IACrE,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;IACrB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,OAAO,CAAC;IAChB,KAAK,EAAE,IAAI,CAAC;CACb;AAED,mFAAmF;AACnF,MAAM,WAAW,wBAAyB,SAAQ,qBAAqB;IACrE,YAAY,EAAE,IAAI,CAAC;IACnB,YAAY,EAAE,IAAI,CAAC;IACnB,kBAAkB,EAAE,IAAI,CAAC;IACzB,aAAa,EAAE,IAAI,CAAC;IACpB,MAAM,EAAE,IAAI,CAAC;IACb,QAAQ,EAAE,KAAK,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,MAAM,uBAAuB,GAAG,wBAAwB,GAAG,wBAAwB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"grants.js","sourceRoot":"","sources":["../../../src/credits/types/grants.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport type { CreditMetadata } from \"./account.js\";\n\nexport type GrantProgramTrigger =\n \"account_created\"
|
|
1
|
+
{"version":3,"file":"grants.js","sourceRoot":"","sources":["../../../src/credits/types/grants.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport type { CreditMetadata } from \"./account.js\";\n\nexport type GrantProgramTrigger =\n | \"account_created\"\n | \"referral_completed\"\n | \"promo_code_redeemed\"\n | \"manual\";\n\n/** One application event that may award one or more catalog grants. */\nexport interface ExecuteGrantProgramRequest {\n trigger: GrantProgramTrigger;\n programKey: string;\n subjectId: string;\n eventKey: string;\n referrerSubjectId?: string | null;\n region?: string | null;\n metadata?: CreditMetadata | null;\n}\n\ninterface GrantProgramAwardBase {\n replayed: boolean;\n}\n\n/** One committed award produced by a grant-program execution. */\nexport interface GrantProgramAwardSuccess extends GrantProgramAwardBase {\n grantEventId: string;\n grantAwardId: string;\n recipientSubjectId: string;\n ledgerEntryId: string;\n amount: Decimal;\n error: null;\n}\n\n/** A rejected grant-program execution. No financial identifiers are fabricated. */\nexport interface GrantProgramAwardFailure extends GrantProgramAwardBase {\n grantEventId: null;\n grantAwardId: null;\n recipientSubjectId: null;\n ledgerEntryId: null;\n amount: null;\n replayed: false;\n error: string;\n}\n\nexport type GrantProgramAwardResult = GrantProgramAwardSuccess | GrantProgramAwardFailure;\n"]}
|