@zonastery/bursar 2.0.2 → 2.0.4
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 -0
- 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 +1 -1
- package/dist/billing/auto-recharge-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js +5 -4
- 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 +7 -7
- 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 +10 -8
- 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 +42 -21
- 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/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 +59 -41
- package/dist/billing/postgres/repositories/auto-recharge.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.map +1 -1
- package/dist/billing/postgres/repositories/event.js +33 -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 +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/offer.js +6 -1
- package/dist/billing/postgres/repositories/offer.js.map +1 -1
- package/dist/billing/postgres/repositories/payment.d.ts +1 -1
- 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/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 +6 -6
- 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 +1 -1
- package/dist/billing/postgres/repositories/topup.js.map +1 -1
- package/dist/billing/postgres/store.d.ts +7 -6
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +31 -19
- package/dist/billing/postgres/store.js.map +1 -1
- package/dist/billing/types/auto-recharge.d.ts +3 -2
- 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/catalog.d.ts +1 -1
- package/dist/billing/types/catalog.d.ts.map +1 -1
- package/dist/billing/types/catalog.js.map +1 -1
- package/dist/billing/types/documents.d.ts +3 -2
- 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 +11 -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 +4 -3
- package/dist/breakdown.d.ts.map +1 -1
- package/dist/breakdown.js +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/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.map +1 -1
- package/dist/commerce/service.js +70 -68
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts +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 +16 -12
- package/dist/config/parse-utils.d.ts.map +1 -1
- package/dist/config/parse-utils.js +91 -28
- package/dist/config/parse-utils.js.map +1 -1
- package/dist/config/types.d.ts +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 +66 -36
- package/dist/config.js.map +1 -1
- package/dist/credits/amount.d.ts +2 -2
- package/dist/credits/amount.d.ts.map +1 -1
- package/dist/credits/amount.js +6 -5
- package/dist/credits/amount.js.map +1 -1
- package/dist/credits/catalog-runtime.d.ts +1 -1
- package/dist/credits/catalog-runtime.d.ts.map +1 -1
- package/dist/credits/catalog-runtime.js +3 -4
- 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 +3 -2
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js +4 -3
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.d.ts +3 -2
- package/dist/credits/low-balance-monitor.d.ts.map +1 -1
- package/dist/credits/low-balance-monitor.js +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 +7 -7
- package/dist/credits/postgres/repositories/balance.js.map +1 -1
- package/dist/credits/postgres/repositories/bucket.js +1 -1
- package/dist/credits/postgres/repositories/bucket.js.map +1 -1
- package/dist/credits/postgres/repositories/catalog.d.ts +4 -3
- 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.map +1 -1
- package/dist/credits/postgres/repositories/lease.js +4 -2
- package/dist/credits/postgres/repositories/lease.js.map +1 -1
- package/dist/credits/postgres/repositories/plan.d.ts +1 -1
- package/dist/credits/postgres/repositories/team.d.ts +2 -1
- package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/team.js +19 -5
- package/dist/credits/postgres/repositories/team.js.map +1 -1
- package/dist/credits/postgres/store.d.ts +6 -5
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +23 -13
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/postgres/value-mappers.d.ts +5 -4
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
- package/dist/credits/postgres/value-mappers.js +11 -12
- package/dist/credits/postgres/value-mappers.js.map +1 -1
- package/dist/credits/service-errors.d.ts +1 -1
- package/dist/credits/service-errors.d.ts.map +1 -1
- package/dist/credits/service-errors.js +1 -1
- package/dist/credits/service-errors.js.map +1 -1
- package/dist/credits/service-types.d.ts +4 -1
- package/dist/credits/service-types.d.ts.map +1 -1
- package/dist/credits/service-types.js.map +1 -1
- package/dist/credits/service.d.ts +5 -0
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +30 -10
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +15 -5
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js +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/credits/types/teams.d.ts +1 -0
- package/dist/credits/types/teams.d.ts.map +1 -1
- package/dist/credits/types/teams.js.map +1 -1
- package/dist/engine.d.ts +2 -2
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +40 -11
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +10 -3
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +50 -9
- 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.d.ts +1 -1
- package/dist/expr/evaluator.d.ts.map +1 -1
- package/dist/expr/evaluator.js +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 +1 -1
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +13 -7
- package/dist/expr.js.map +1 -1
- package/dist/generated/pricing-config.types.d.ts.map +1 -1
- package/dist/generated/pricing-config.types.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.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 +3 -2
- package/dist/metrics.d.ts.map +1 -1
- package/dist/metrics.js.map +1 -1
- package/dist/node.d.ts +6 -3
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +1 -0
- package/dist/node.js.map +1 -1
- package/dist/providers/_shared.d.ts +11 -8
- package/dist/providers/_shared.d.ts.map +1 -1
- package/dist/providers/_shared.js +26 -17
- package/dist/providers/_shared.js.map +1 -1
- package/dist/providers/dodo/better-auth-core.d.ts +32 -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 -7
- 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 +16 -22
- 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 +130 -106
- 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 +76 -58
- 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 +104 -12
- 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 +100 -60
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/providers/types.d.ts +0 -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 +10 -2
- package/dist/shared/diagnostics.d.ts.map +1 -1
- package/dist/shared/diagnostics.js +65 -6
- 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.map +1 -1
- package/dist/shared/postgres-client.d.ts +10 -5
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +80 -45
- 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 +20 -6
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
- package/dist/storage/adapters/clickhouse.js +150 -42
- package/dist/storage/adapters/clickhouse.js.map +1 -1
- package/dist/storage/adapters/s3.d.ts +67 -6
- package/dist/storage/adapters/s3.d.ts.map +1 -1
- package/dist/storage/adapters/s3.js +79 -26
- package/dist/storage/adapters/s3.js.map +1 -1
- package/dist/storage/diagnostics.d.ts +105 -0
- package/dist/storage/diagnostics.d.ts.map +1 -0
- package/dist/storage/diagnostics.js +228 -0
- package/dist/storage/diagnostics.js.map +1 -0
- package/dist/storage/maintenance.d.ts +88 -0
- package/dist/storage/maintenance.d.ts.map +1 -0
- package/dist/storage/maintenance.js +272 -0
- package/dist/storage/maintenance.js.map +1 -0
- package/dist/storage/outbox-worker.d.ts +21 -1
- package/dist/storage/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js +157 -28
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/ports.d.ts +52 -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 +9 -2
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js +97 -11
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts +20 -3
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +326 -156
- package/dist/storage/runtime.js.map +1 -1
- package/dist/telemetry/index.d.ts +41 -0
- package/dist/telemetry/index.d.ts.map +1 -0
- package/dist/telemetry/index.js +118 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/telemetry/opentelemetry.d.ts +25 -0
- package/dist/telemetry/opentelemetry.d.ts.map +1 -0
- package/dist/telemetry/opentelemetry.js +74 -0
- package/dist/telemetry/opentelemetry.js.map +1 -0
- package/package.json +24 -14
|
@@ -28,6 +28,7 @@ export declare class CreditsService {
|
|
|
28
28
|
private balanceMonitor;
|
|
29
29
|
private lazyExpiry;
|
|
30
30
|
private logger;
|
|
31
|
+
private readonly instrumentation;
|
|
31
32
|
private readonly postDeductionHooks;
|
|
32
33
|
constructor(store: CreditStore, engine?: PricingEngine | null, emitter?: CreditEventEmitter | null, options?: CreditsServiceOptions | null);
|
|
33
34
|
/**
|
|
@@ -110,6 +111,7 @@ export declare class CreditsService {
|
|
|
110
111
|
getBalance(userId: string): Promise<BalanceResult>;
|
|
111
112
|
/** Add credits to a user's account. */
|
|
112
113
|
addCredits(userId: string, amount: ExactAmount, options: AddCreditsOptions): Promise<AddCreditsResult>;
|
|
114
|
+
private addCreditsUninstrumented;
|
|
113
115
|
/**
|
|
114
116
|
* Deduct a raw credit amount from a user's account.
|
|
115
117
|
*
|
|
@@ -137,6 +139,7 @@ export declare class CreditsService {
|
|
|
137
139
|
* 6. Emits ``credits.cycle_renewed`` and returns the grant result.
|
|
138
140
|
*/
|
|
139
141
|
grantSubscriptionCycle(userId: string, amount: ExactAmount, options: GrantSubscriptionCycleOptions): Promise<AddCreditsResult>;
|
|
142
|
+
private grantSubscriptionCycleUninstrumented;
|
|
140
143
|
reserve(userId: string, metricsOrAmount: MetricsOrAmount, options: ReserveOptions): Promise<LeaseSuccess>;
|
|
141
144
|
settle(userId: string, leaseId: string, metricsOrAmount: MetricsOrAmount, options?: SettleOptions): Promise<DeductionResult>;
|
|
142
145
|
release(userId: string, leaseId: string): Promise<ReleaseResult>;
|
|
@@ -161,6 +164,7 @@ export declare class CreditsService {
|
|
|
161
164
|
* typed exception is thrown. No success event is emitted on error.
|
|
162
165
|
*/
|
|
163
166
|
deduct(userId: string, metrics: UsageMetrics, options: DeductOptions): Promise<DeductionResult>;
|
|
167
|
+
private deductUninstrumented;
|
|
164
168
|
/**
|
|
165
169
|
* Record priced usage for a workflow without debiting the account again.
|
|
166
170
|
*
|
|
@@ -179,6 +183,7 @@ export declare class CreditsService {
|
|
|
179
183
|
/** Deduct the configured fixed cost for one named job. */
|
|
180
184
|
deductFlatJob(userId: string, jobName: string, options: DeductFlatJobOptions): Promise<DeductionResult>;
|
|
181
185
|
refundCredits(entryId: string, options: RefundCreditsOptions): Promise<RefundSuccess>;
|
|
186
|
+
private refundCreditsUninstrumented;
|
|
182
187
|
/**
|
|
183
188
|
* Deduct from a team's shared balance pool.
|
|
184
189
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/credits/service.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/credits/service.ts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AoEjB,QAAQ;IAYtB;;;;;OAKG;IACG,mBAAmB,CAAC,MAAM,UAAQ,GAAG,OAAO,CAAC,WAAW,CAAC;CAGhE"}
|
package/dist/credits/service.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import Decimal from "decimal.js";
|
|
1
|
+
import { Decimal } from "decimal.js";
|
|
2
|
+
import { z } from "zod";
|
|
2
3
|
import { CapReachedError, ConfigError, InsufficientCreditsError, RefundError, StoreError, } from "../errors.js";
|
|
3
4
|
import { raiseDeductError } from "./service-errors.js";
|
|
4
5
|
import { LowBalanceMonitor } from "./low-balance-monitor.js";
|
|
@@ -7,6 +8,7 @@ import { CatalogRuntime } from "./catalog-runtime.js";
|
|
|
7
8
|
import { toDecimal } from "./amount.js";
|
|
8
9
|
import { CreditLeaseWorkflow } from "./lease-workflow.js";
|
|
9
10
|
import { requireStableKey } from "../shared/idempotency.js";
|
|
11
|
+
import { getDefaultInstrumentation } from "../telemetry/index.js";
|
|
10
12
|
/**
|
|
11
13
|
* Default lease TTL (seconds) for ``reserve`` and ``runBilled``.
|
|
12
14
|
* Long batch/agentic jobs call the configured lease TTL before this elapses.
|
|
@@ -46,9 +48,11 @@ export class CreditsService {
|
|
|
46
48
|
// behaviour; explicit `sweepExpiredCredits`/cron remains required.
|
|
47
49
|
lazyExpiry;
|
|
48
50
|
logger;
|
|
51
|
+
instrumentation;
|
|
49
52
|
postDeductionHooks = new Set();
|
|
50
53
|
constructor(store, engine, emitter, options) {
|
|
51
54
|
this.store = store;
|
|
55
|
+
this.instrumentation = options?.instrumentation ?? getDefaultInstrumentation();
|
|
52
56
|
this.queries = new CreditQueries(store, options?.analytics ?? store, options?.usageStore ?? store);
|
|
53
57
|
const policy = options?.policy ?? "strict_prepaid";
|
|
54
58
|
if (!POLICY_PRESETS.has(policy)) {
|
|
@@ -121,7 +125,7 @@ export class CreditsService {
|
|
|
121
125
|
}
|
|
122
126
|
/** Execute an application-driven catalog grant program. */
|
|
123
127
|
async executeGrantProgram(request) {
|
|
124
|
-
return this.store.executeGrantProgram(request);
|
|
128
|
+
return this.instrumentation.run("credits.grant_program", undefined, () => this.store.executeGrantProgram(request));
|
|
125
129
|
}
|
|
126
130
|
async getLedgerEntry(userId, entryId) {
|
|
127
131
|
return this.queries.getLedgerEntry(userId, entryId);
|
|
@@ -238,7 +242,7 @@ export class CreditsService {
|
|
|
238
242
|
this.emit("credits.plan_changed", userId, {
|
|
239
243
|
userId,
|
|
240
244
|
planKey,
|
|
241
|
-
planAssignedAt: result.planAssignedAt,
|
|
245
|
+
planAssignedAt: result.planAssignedAt?.toISOString() ?? null,
|
|
242
246
|
assignmentState: result.assignmentState,
|
|
243
247
|
timestamp: new Date().toISOString(),
|
|
244
248
|
});
|
|
@@ -274,6 +278,9 @@ export class CreditsService {
|
|
|
274
278
|
}
|
|
275
279
|
/** Add credits to a user's account. */
|
|
276
280
|
async addCredits(userId, amount, options) {
|
|
281
|
+
return this.instrumentation.run("credits.grant", undefined, () => this.addCreditsUninstrumented(userId, amount, options));
|
|
282
|
+
}
|
|
283
|
+
async addCreditsUninstrumented(userId, amount, options) {
|
|
277
284
|
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
278
285
|
const type = options.type ?? "adjustment";
|
|
279
286
|
this.logger.info("[CreditsService] addCredits", { amount, type, bucket: options.bucket });
|
|
@@ -354,6 +361,9 @@ export class CreditsService {
|
|
|
354
361
|
* 6. Emits ``credits.cycle_renewed`` and returns the grant result.
|
|
355
362
|
*/
|
|
356
363
|
async grantSubscriptionCycle(userId, amount, options) {
|
|
364
|
+
return this.instrumentation.run("credits.grant_subscription_cycle", undefined, () => this.grantSubscriptionCycleUninstrumented(userId, amount, options));
|
|
365
|
+
}
|
|
366
|
+
async grantSubscriptionCycleUninstrumented(userId, amount, options) {
|
|
357
367
|
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
358
368
|
this.logger.info("[CreditsService] grantSubscriptionCycle", {
|
|
359
369
|
amount,
|
|
@@ -399,13 +409,13 @@ export class CreditsService {
|
|
|
399
409
|
}
|
|
400
410
|
// ── Lease lifecycle: atomic admission ───────────────────────────────
|
|
401
411
|
async reserve(userId, metricsOrAmount, options) {
|
|
402
|
-
return this.leases.reserve(userId, metricsOrAmount, options);
|
|
412
|
+
return this.instrumentation.run("credits.reserve", undefined, () => this.leases.reserve(userId, metricsOrAmount, options));
|
|
403
413
|
}
|
|
404
414
|
async settle(userId, leaseId, metricsOrAmount, options) {
|
|
405
|
-
return this.leases.settle(userId, leaseId, metricsOrAmount, options);
|
|
415
|
+
return this.instrumentation.run("credits.settle", undefined, () => this.leases.settle(userId, leaseId, metricsOrAmount, options));
|
|
406
416
|
}
|
|
407
417
|
async release(userId, leaseId) {
|
|
408
|
-
return this.leases.release(userId, leaseId);
|
|
418
|
+
return this.instrumentation.run("credits.release", undefined, () => this.leases.release(userId, leaseId));
|
|
409
419
|
}
|
|
410
420
|
async renew(userId, leaseId, ttl) {
|
|
411
421
|
return this.leases.renew(userId, leaseId, ttl);
|
|
@@ -437,6 +447,9 @@ export class CreditsService {
|
|
|
437
447
|
* typed exception is thrown. No success event is emitted on error.
|
|
438
448
|
*/
|
|
439
449
|
async deduct(userId, metrics, options) {
|
|
450
|
+
return this.instrumentation.run("credits.deduct", undefined, () => this.deductUninstrumented(userId, metrics, options));
|
|
451
|
+
}
|
|
452
|
+
async deductUninstrumented(userId, metrics, options) {
|
|
440
453
|
await this.maybeLazyExpire(userId);
|
|
441
454
|
this.logger.debug("[CreditsService] deduct", {
|
|
442
455
|
model: metrics.dimensions?.model,
|
|
@@ -445,6 +458,8 @@ export class CreditsService {
|
|
|
445
458
|
const engine = await this.catalogRuntime.engineForUser(userId);
|
|
446
459
|
const plan = await this.store.getUserPlan(userId);
|
|
447
460
|
const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
461
|
+
const model = z.string().safeParse(metrics.dimensions?.model).data ?? null;
|
|
462
|
+
const region = z.string().safeParse(metrics.dimensions?.region).data ?? null;
|
|
448
463
|
// 1) Calculate cost as an exact Decimal, never truncated.
|
|
449
464
|
const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
|
|
450
465
|
const cost = breakdown.total;
|
|
@@ -466,8 +481,8 @@ export class CreditsService {
|
|
|
466
481
|
idempotencyKey: effectiveIdempotencyKey,
|
|
467
482
|
operation: metrics.operation,
|
|
468
483
|
feature: options.feature ?? null,
|
|
469
|
-
model
|
|
470
|
-
region
|
|
484
|
+
model,
|
|
485
|
+
region,
|
|
471
486
|
measures: { ...(metrics.measures ?? {}) },
|
|
472
487
|
dimensions: { ...(metrics.dimensions ?? {}) },
|
|
473
488
|
metadata: meta,
|
|
@@ -522,6 +537,8 @@ export class CreditsService {
|
|
|
522
537
|
const engine = await this.catalogRuntime.engineForUser(userId);
|
|
523
538
|
const plan = await this.store.getUserPlan(userId);
|
|
524
539
|
const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
540
|
+
const model = z.string().safeParse(metrics.dimensions?.model).data ?? null;
|
|
541
|
+
const region = z.string().safeParse(metrics.dimensions?.region).data ?? null;
|
|
525
542
|
const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
|
|
526
543
|
const meta = {};
|
|
527
544
|
if (options.metadata) {
|
|
@@ -538,8 +555,8 @@ export class CreditsService {
|
|
|
538
555
|
const result = await this.store.recordUsage(userId, metrics.operation, breakdown.total, {
|
|
539
556
|
idempotencyKey: effectiveIdempotencyKey,
|
|
540
557
|
operation: metrics.operation,
|
|
541
|
-
model
|
|
542
|
-
region
|
|
558
|
+
model,
|
|
559
|
+
region,
|
|
543
560
|
measures: { ...(metrics.measures ?? {}) },
|
|
544
561
|
dimensions: { ...(metrics.dimensions ?? {}) },
|
|
545
562
|
metadata: meta,
|
|
@@ -562,6 +579,9 @@ export class CreditsService {
|
|
|
562
579
|
return this.deduct(userId, { operation: jobName, measures: { jobs: 1 } }, options);
|
|
563
580
|
}
|
|
564
581
|
async refundCredits(entryId, options) {
|
|
582
|
+
return this.instrumentation.run("credits.refund", undefined, () => this.refundCreditsUninstrumented(entryId, options));
|
|
583
|
+
}
|
|
584
|
+
async refundCreditsUninstrumented(entryId, options) {
|
|
565
585
|
const idempotencyKey = requireStableKey(options?.idempotencyKey);
|
|
566
586
|
const refundAmount = options.amount != null ? positiveAmount(options.amount, "refundCredits") : undefined;
|
|
567
587
|
this.logger.info("[CreditsService] refundCredits", {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.js","sourceRoot":"","sources":["../../src/credits/service.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACjC,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;AA2C5D;;;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,EAAE,CAAC;QACxC,MAAM,IAAI,UAAU,CA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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 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 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.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.store.executeGrantProgram(request);\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 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 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.leases.reserve(userId, metricsOrAmount, options);\n }\n\n async settle(\n userId: string,\n leaseId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: SettleOptions,\n ): Promise<DeductionResult> {\n return this.leases.settle(userId, leaseId, metricsOrAmount, options);\n }\n\n async release(userId: string, leaseId: string): Promise<ReleaseResult> {\n return this.leases.release(userId, leaseId);\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 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 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,C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E,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 { 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 {
|
|
@@ -25,6 +26,15 @@ export interface CreateLeaseOptions extends OperationUsageOptions {
|
|
|
25
26
|
ttlSeconds?: number;
|
|
26
27
|
metadata?: CreditMetadata | null;
|
|
27
28
|
}
|
|
29
|
+
/** Options for replay-safe team creation. */
|
|
30
|
+
export interface CreateTeamOptions {
|
|
31
|
+
/**
|
|
32
|
+
* Caller-owned operation key. Reusing it with the same request returns the
|
|
33
|
+
* original team; changing the owner, name, or balance is rejected.
|
|
34
|
+
*/
|
|
35
|
+
idempotencyKey: string;
|
|
36
|
+
initialBalance?: Decimal;
|
|
37
|
+
}
|
|
28
38
|
/** Options for charging the actual cost against a lease. */
|
|
29
39
|
export interface SettleLeaseOptions extends OperationUsageOptions {
|
|
30
40
|
idempotencyKey?: string;
|
|
@@ -101,8 +111,8 @@ export declare abstract class CreditStore {
|
|
|
101
111
|
*/
|
|
102
112
|
abstract getAvailable(userId: string): Promise<AvailableResult>;
|
|
103
113
|
abstract getActiveCatalog(): Promise<CatalogRevision | null>;
|
|
104
|
-
abstract publishAndActivateCatalog(config: BursarConfigData, label?: string | null, rollout?: CatalogRollout | null): Promise<string>;
|
|
105
|
-
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>;
|
|
106
116
|
abstract getCatalogHistory(): Promise<CatalogRevisionSummary[]>;
|
|
107
117
|
abstract getCatalogRevision(version: number): Promise<CatalogRevision | null>;
|
|
108
118
|
abstract activateCatalogRevision(version: number, rollout?: CatalogRollout | null): Promise<string>;
|
|
@@ -154,7 +164,7 @@ export declare abstract class CreditStore {
|
|
|
154
164
|
* does not exist or belongs to a different user.
|
|
155
165
|
*/
|
|
156
166
|
getLedgerEntry(_userId: string, _entryId: string): Promise<LedgerEntry | null>;
|
|
157
|
-
createTeam(_ownerSubjectId: string, _name: string,
|
|
167
|
+
createTeam(_ownerSubjectId: string, _name: string, _options: CreateTeamOptions): Promise<CreateTeamResult>;
|
|
158
168
|
getTeamBalance(_teamId: string): Promise<TeamBalanceResult | null>;
|
|
159
169
|
addTeamMember(_teamId: string, _userId: string, _role?: TeamRole, _spendCap?: Decimal | null): Promise<AddTeamMemberResult>;
|
|
160
170
|
getTeamMembers(_teamId: string): Promise<TeamMember[]>;
|
|
@@ -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,wBAAwB,EACxB,UAAU,EACV,UAAU,EACV,WAAW,EACX,mBAAmB,EACnB,wBAAwB,EACxB,uBAAuB,EACvB,uBAAuB,EACvB,UAAU,EACV,eAAe,EACf,iBAAiB,EACjB,sBAAsB,EACtB,eAAe,EACf,YAAY,EACZ,mBAAmB,EACnB,aAAa,EACb,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,cAAc,EACd,WAAW,EACX,iBAAiB,EACjB,mBAAmB,EACnB,UAAU,EACV,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nB,QAAQ,EAAE,0BAA0B,GACnC,OAAO,CAAC,iBAAiB,CAAC;IAK7B;;;OAGG;IACG,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC;IAK9E,UAAU,CACd,eAAe,EAAE,MAAM,EACvB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,iBAAiB,GAC1B,OAAO,CAAC,gBAAgB,CAAC;IAGtB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC;IAGlE,aAAa,CACjB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,KAAK,CAAC,EAAE,QAAQ,EAChB,SAAS,CAAC,EAAE,OAAO,GAAG,IAAI,GACzB,OAAO,CAAC,mBAAmB,CAAC;IAGzB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC;IAGtD,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAGpE,UAAU,CACd,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,OAAO,EAChB,QAAQ,EAAE,iBAAiB,GAC1B,OAAO,CAAC,mBAAmB,CAAC;CAGhC"}
|
package/dist/credits/store.js
CHANGED
|
@@ -60,7 +60,7 @@ export class CreditStore {
|
|
|
60
60
|
throw new CapabilityNotSupportedError("getLedgerEntry is not supported by this store");
|
|
61
61
|
}
|
|
62
62
|
// ── Team/shared balance pools (optional capability) ──────────────────
|
|
63
|
-
async createTeam(_ownerSubjectId, _name,
|
|
63
|
+
async createTeam(_ownerSubjectId, _name, _options) {
|
|
64
64
|
throw new CapabilityNotSupportedError("createTeam is not supported by this store");
|
|
65
65
|
}
|
|
66
66
|
async getTeamBalance(_teamId) {
|