@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
package/dist/bursar.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bursar.js","sourceRoot":"","sources":["../src/bursar.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,IAAI,mBAAmB,GAEtC,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,cAAc,IAAI,kBAAkB,GAErC,MAAM,sBAAsB,CAAC;AAK9B,OAAO,EAAE,eAAe,IAAI,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAElE,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,OAA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ACrC,CAAC,CAAC,IAAI,mBAAmB,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,eAAe,CAAC;gBAC/E,CAAC,CAAC,IAAI,CAAC;QACX,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAClB,OAAO,CAAC,oBAAoB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE;gBAChD,MAAM,IAAI,CAAC,QAAS,CAAC,YAAY,CAAC,eAAe,CAAC,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;YAC3E,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,uDAAuD;IACvD,KAAK,CAAC,WAAW;QACf,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;IAC5B,CAAC;IAED,mEAAmE;IACnE,cAAc;QACZ,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAClB,MAAM,IAAI,4BAA4B,CAAC,SAAS,CAAC,CAAC;QACpD,CAAC;QACD,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED,oEAAoE;IACpE,eAAe;QACb,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACnB,MAAM,IAAI,0BAA0B,CAAC,8CAA8C,CAAC,CAAC;QACvF,CAAC;QACD,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,kBAAkB,CAAC,KAAmB;QAC1C,OAAO,IAAI,CAAC,cAAc,EAAE,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;IACzD,CAAC;CACF","sourcesContent":["import {\n BillingService as BillingEventService,\n type BillingServiceOptions,\n} from \"./billing/billing-service.js\";\nimport type { BillingStore } from \"./billing/billing-store.js\";\nimport {\n CreditsService as CreditsServiceImpl,\n type CreditsServiceOptions,\n} from \"./credits/service.js\";\nimport type { CreditStore } from \"./credits/store.js\";\nimport type { CreditEventEmitter } from \"./credits/events.js\";\nimport type { BillingEvent, BillingEventResult } from \"./billing/types/index.js\";\nimport type { BillingCapability, BillingEventSink } from \"./billing/contracts.js\";\nimport { CommerceService as CommerceServiceImpl } from \"./commerce/service.js\";\nimport { CommerceNotConfiguredError } from \"./commerce/errors.js\";\nimport type { CommerceOptions } from \"./commerce/types.js\";\nimport { loadConfigFromDict } from \"./config.js\";\nimport type { BursarConfigData, CatalogRollout, ParsedBursarConfig } from \"./config/types.js\";\nimport { CapabilityNotConfiguredError, ConfigError, CatalogNotLoadedError } from \"./errors.js\";\nimport { projectPublicCatalog, type PublicCatalog } from \"./catalog.js\";\nimport type { CreditMetadata, GrantProgramAwardResult } from \"./credits/types/index.js\";\nimport { retryBursarOperation } from \"./retry.js\";\nexport type { BillingCapability, BillingEventSink } from \"./billing/contracts.js\";\nexport type { CommerceOptions } from \"./commerce/types.js\";\n\n/**\n * Stable public credit capability exposed by {@link Bursar}.\n *\n * The explicit method list prevents implementation helpers added to\n * `CreditsServiceImpl` from silently becoming public API.\n */\nexport type CreditsService = Pick<\n CreditsServiceImpl,\n | \"getUserPlan\"\n | \"checkFeature\"\n | \"getQuotaState\"\n | \"listQuotaEvents\"\n | \"startPlanMigration\"\n | \"migratePlanBatch\"\n | \"revokeCreditsByEntryType\"\n | \"executeGrantProgram\"\n | \"getLedgerEntry\"\n | \"getAvailable\"\n | \"aggregateStats\"\n | \"spendByUser\"\n | \"spendByModel\"\n | \"listLedgerEntries\"\n | \"listUsageEntries\"\n | \"listUsageCharges\"\n | \"topUsers\"\n | \"dailySpend\"\n | \"setUserPlan\"\n | \"unsetUserPlan\"\n | \"getBalance\"\n | \"addCredits\"\n | \"deductCredits\"\n | \"grantSubscriptionCycle\"\n | \"reserve\"\n | \"settle\"\n | \"release\"\n | \"renew\"\n | \"canAfford\"\n | \"getBucketBalances\"\n | \"checkAllowance\"\n | \"runBilled\"\n | \"beginBilledOperation\"\n | \"deduct\"\n | \"recordUsage\"\n | \"deductFlatJob\"\n | \"refundCredits\"\n | \"deductTeam\"\n | \"sweepExpiredCredits\"\n>;\n\ntype CatalogCreditsService = Pick<\n CreditsServiceImpl,\n | \"getActiveCatalog\"\n | \"loadCatalogFromStore\"\n | \"refreshCatalogIfStale\"\n | \"invalidateCatalog\"\n | \"publishAndActivateCatalog\"\n | \"publishCatalogDraft\"\n | \"activateCatalogRevision\"\n | \"pricingEngine\"\n | \"setPlanRevisionPin\"\n | \"applyDuePlanChanges\"\n>;\n\ninterface BaseBursarOptions {\n creditStore: CreditStore;\n creditsOptions?: CreditsServiceOptions;\n emitter?: CreditEventEmitter;\n}\n\n/** Credits-only construction rejects billing options that would otherwise be ignored. */\nexport interface CreditsOnlyBursarOptions extends BaseBursarOptions {\n billingStore?: undefined;\n billingOptions?: never;\n commerceOptions?: never;\n}\n\n/** Billing construction owns provisioning and may optionally enable commerce. */\nexport interface BillingBursarOptions extends BaseBursarOptions {\n billingStore: BillingStore;\n billingOptions?: Omit<BillingServiceOptions, \"provisioning\">;\n commerceOptions?: CommerceOptions;\n}\n\n/** Options for constructing the single application-facing Bursar service. */\nexport type BursarOptions = CreditsOnlyBursarOptions | BillingBursarOptions;\n\n/** Catalog operations. Configuration writes live here, never in BillingService. */\nexport class CatalogService {\n constructor(private readonly credits: CatalogCreditsService) {}\n\n /** Return the active persisted catalog revision, if one exists. */\n getActive() {\n return this.credits.getActiveCatalog();\n }\n\n /** Whether this process currently has a pricing engine loaded. */\n get isLoaded(): boolean {\n return this.credits.pricingEngine !== null;\n }\n\n /** Load the active persisted catalog into this process. */\n load(): Promise<void> {\n return this.credits.loadCatalogFromStore();\n }\n\n /** Block until a stale in-process catalog has been refreshed. */\n refresh(): Promise<void> {\n return this.credits.refreshCatalogIfStale();\n }\n\n /** Force the next refresh to reload the active catalog. */\n invalidate(): void {\n this.credits.invalidateCatalog();\n }\n\n async getConfig(): Promise<ParsedBursarConfig> {\n const active = await this.getActive();\n if (!active) throw new CatalogNotLoadedError(\"No active Bursar catalog is available\");\n return loadConfigFromDict(active.config);\n }\n\n async publicView(): Promise<PublicCatalog> {\n return projectPublicCatalog(await this.getConfig());\n }\n\n publishDraft(config: BursarConfigData, label?: string | null): Promise<string> {\n return this.credits.publishCatalogDraft(config, label);\n }\n\n activate(version: number, rollout?: CatalogRollout | null): Promise<string> {\n return this.credits.activateCatalogRevision(version, rollout);\n }\n\n publishAndActivate(\n config: BursarConfigData,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string> {\n return this.credits.publishAndActivateCatalog(config, label, rollout);\n }\n\n /** Pin or unpin one current assignment from automatic catalog rollout. */\n setRevisionPin(userId: string, pinned: boolean): Promise<boolean> {\n return this.credits.setPlanRevisionPin(userId, pinned);\n }\n\n /** Apply one bounded batch of renewal-effective plan changes. */\n applyDueChanges(limit = 100): Promise<number> {\n return this.credits.applyDuePlanChanges(limit);\n }\n}\n\nexport interface AccountCreatedInput {\n accountId: string;\n eventKey: string;\n region?: string | null;\n metadata?: CreditMetadata | null;\n}\n\nexport interface AccountCreatedResult {\n accountId: string;\n planKey: string;\n planAssigned: boolean;\n grants: GrantProgramAwardResult[];\n}\n\n/** Generic financial lifecycle operations for SaaS accounts. */\nexport class AccountService {\n constructor(\n private readonly credits: CreditsService,\n private readonly catalog: CatalogService,\n ) {}\n\n async onAccountCreated(input: AccountCreatedInput): Promise<AccountCreatedResult> {\n if (typeof input.accountId !== \"string\" || !input.accountId.trim()) {\n throw new TypeError(\"accountId must be a non-empty string\");\n }\n if (typeof input.eventKey !== \"string\" || !input.eventKey.trim()) {\n throw new TypeError(\"eventKey must be a non-empty string\");\n }\n const config = await retryBursarOperation(() => this.catalog.getConfig());\n const planKey = config.catalog.defaultPlan;\n if (!planKey) throw new ConfigError(\"The active catalog has no default account plan\");\n\n const current = await retryBursarOperation(() => this.credits.getUserPlan(input.accountId));\n const planAssigned = current.planKey == null;\n if (planAssigned) {\n await retryBursarOperation(() => this.credits.setUserPlan(input.accountId, planKey));\n }\n\n const grants: GrantProgramAwardResult[] = [];\n for (const [programKey, program] of Object.entries(config.credits.grantPrograms).sort(\n ([a], [b]) => a.localeCompare(b),\n )) {\n if (program.trigger !== \"account_created\") continue;\n grants.push(\n ...(await retryBursarOperation(() =>\n this.credits.executeGrantProgram({\n trigger: \"account_created\",\n programKey,\n subjectId: input.accountId,\n eventKey: input.eventKey,\n region: input.region,\n metadata: input.metadata,\n }),\n )),\n );\n }\n return {\n accountId: input.accountId,\n planKey: current.planKey ?? planKey,\n planAssigned,\n grants,\n };\n }\n}\n\n/**\n * The application-facing Bursar boundary.\n *\n * Credit and billing services are deliberately created together so consumers\n * cannot accidentally construct unrelated services for the same account\n * lifecycle. Provider and application integrations use this facade rather\n * than constructing lifecycle services independently.\n */\nexport class Bursar implements BillingEventSink {\n readonly credits: CreditsService;\n readonly billing: BillingCapability | null;\n readonly commerce: CommerceServiceImpl | null;\n readonly catalog: CatalogService;\n readonly accounts: AccountService;\n\n constructor(options: BursarOptions) {\n if (typeof options !== \"object\" || options === null) {\n throw new TypeError(\"Bursar options are required\");\n }\n if (options.billingStore === null) {\n throw new TypeError(\"billingStore must be a BillingStore when provided\");\n }\n for (const optionName of [\n \"creditsOptions\",\n \"billingOptions\",\n \"commerceOptions\",\n \"emitter\",\n ] as const) {\n if (options[optionName] === null) {\n throw new TypeError(`${optionName} must not be null`);\n }\n }\n if (\n options.billingStore === undefined &&\n (options.billingOptions !== undefined || options.commerceOptions !== undefined)\n ) {\n throw new TypeError(\"billingOptions and commerceOptions require billingStore\");\n }\n if (options.billingOptions && \"provisioning\" in options.billingOptions) {\n throw new TypeError(\"billingOptions.provisioning is owned by Bursar\");\n }\n const environments = [\n [\"creditStore\", options.creditStore.providerEnvironment],\n [\"billingStore\", options.billingStore?.providerEnvironment],\n [\"commerceOptions\", options.commerceOptions?.providerEnvironment],\n ].filter((entry): entry is [string, NonNullable<(typeof entry)[1]>] => entry[1] !== undefined);\n if (new Set(environments.map(([, environment]) => environment)).size > 1) {\n throw new TypeError(\n `Bursar provider environments must match: ${environments\n .map(([name, environment]) => `${name}=${environment}`)\n .join(\", \")}`,\n );\n }\n const credits = new CreditsServiceImpl(\n options.creditStore,\n undefined,\n options.emitter ?? undefined,\n options.creditsOptions ?? undefined,\n );\n this.credits = credits;\n this.catalog = new CatalogService(credits);\n this.accounts = new AccountService(credits, this.catalog);\n\n this.billing = options.billingStore\n ? new BillingEventService(options.billingStore, {\n ...(options.billingOptions ?? {}),\n provisioning: credits,\n })\n : null;\n this.commerce =\n this.billing && options.commerceOptions\n ? new CommerceServiceImpl(this.billing, credits, this, options.commerceOptions)\n : null;\n if (this.commerce) {\n credits.addPostDeductionHook(async ({ userId }) => {\n await this.commerce!.autoRecharge.processIfNeeded({ accountId: userId });\n });\n }\n }\n\n /** Load the active catalog into the pricing engine. */\n async loadCatalog(): Promise<void> {\n await this.catalog.load();\n }\n\n /** Return billing or raise the SDK's typed configuration error. */\n requireBilling(): BillingCapability {\n if (!this.billing) {\n throw new CapabilityNotConfiguredError(\"billing\");\n }\n return this.billing;\n }\n\n /** Return commerce or raise the SDK's typed configuration error. */\n requireCommerce(): CommerceServiceImpl {\n if (!this.commerce) {\n throw new CommerceNotConfiguredError(\"Bursar commerce capability is not configured\");\n }\n return this.commerce;\n }\n\n /**\n * Ingest a normalized provider event through the facade-owned billing\n * lifecycle. Providers must not depend on BillingService directly.\n */\n async ingestBillingEvent(event: BillingEvent): Promise<BillingEventResult> {\n return this.requireBilling().ingestBillingEvent(event);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bursar.js","sourceRoot":"","sources":["../src/bursar.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,IAAI,mBAAmB,GAEtC,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,cAAc,IAAI,kBAAkB,GAErC,MAAM,sBAAsB,CAAC;AAK9B,OAAO,EAAE,eAAe,IAAI,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,0BAA0B,EAAE,MAAM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BAAkB,CAAC,KAAK,CAAC,CAAC;IACzD,CAAC;CACF","sourcesContent":["import {\n BillingService as BillingEventService,\n type BillingServiceOptions,\n} from \"./billing/billing-service.js\";\nimport type { BillingStore } from \"./billing/billing-store.js\";\nimport {\n CreditsService as CreditsServiceImpl,\n type CreditsServiceOptions,\n} from \"./credits/service.js\";\nimport type { CreditStore } from \"./credits/store.js\";\nimport type { CreditEventEmitter } from \"./credits/events.js\";\nimport type { BillingEvent, BillingEventResult } from \"./billing/types/index.js\";\nimport type { BillingCapability, BillingEventSink } from \"./billing/contracts.js\";\nimport { CommerceService as CommerceServiceImpl } from \"./commerce/service.js\";\nimport { CommerceNotConfiguredError } from \"./commerce/errors.js\";\nimport type { CommerceOptions } from \"./commerce/types.js\";\nimport { loadConfigFromDict } from \"./config.js\";\nimport type { BursarConfigData, CatalogRollout, ParsedBursarConfig } from \"./config/types.js\";\nimport { CapabilityNotConfiguredError, ConfigError, CatalogNotLoadedError } from \"./errors.js\";\nimport { projectPublicCatalog, type PublicCatalog } from \"./catalog.js\";\nimport type { CreditMetadata, GrantProgramAwardResult } from \"./credits/types/index.js\";\nimport { retryBursarOperation } from \"./retry.js\";\nimport { z } from \"zod\";\nexport type { BillingCapability, BillingEventSink } from \"./billing/contracts.js\";\nexport type { CommerceOptions } from \"./commerce/types.js\";\n\n/**\n * Stable public credit capability exposed by {@link Bursar}.\n *\n * The explicit method list prevents implementation helpers added to\n * `CreditsServiceImpl` from silently becoming public API.\n */\nexport type CreditsService = Pick<\n CreditsServiceImpl,\n | \"getUserPlan\"\n | \"checkFeature\"\n | \"getQuotaState\"\n | \"listQuotaEvents\"\n | \"startPlanMigration\"\n | \"migratePlanBatch\"\n | \"revokeCreditsByEntryType\"\n | \"executeGrantProgram\"\n | \"getLedgerEntry\"\n | \"getAvailable\"\n | \"aggregateStats\"\n | \"spendByUser\"\n | \"spendByModel\"\n | \"listLedgerEntries\"\n | \"listUsageEntries\"\n | \"listUsageCharges\"\n | \"topUsers\"\n | \"dailySpend\"\n | \"setUserPlan\"\n | \"unsetUserPlan\"\n | \"getBalance\"\n | \"addCredits\"\n | \"deductCredits\"\n | \"grantSubscriptionCycle\"\n | \"reserve\"\n | \"settle\"\n | \"release\"\n | \"renew\"\n | \"canAfford\"\n | \"getBucketBalances\"\n | \"checkAllowance\"\n | \"runBilled\"\n | \"beginBilledOperation\"\n | \"deduct\"\n | \"recordUsage\"\n | \"deductFlatJob\"\n | \"refundCredits\"\n | \"deductTeam\"\n | \"sweepExpiredCredits\"\n>;\n\ntype CatalogCreditsService = Pick<\n CreditsServiceImpl,\n | \"getActiveCatalog\"\n | \"loadCatalogFromStore\"\n | \"refreshCatalogIfStale\"\n | \"invalidateCatalog\"\n | \"publishAndActivateCatalog\"\n | \"publishCatalogDraft\"\n | \"activateCatalogRevision\"\n | \"pricingEngine\"\n | \"setPlanRevisionPin\"\n | \"applyDuePlanChanges\"\n>;\n\ninterface BaseBursarOptions {\n creditStore: CreditStore;\n creditsOptions?: CreditsServiceOptions;\n emitter?: CreditEventEmitter;\n}\n\n/** Credits-only construction rejects billing options that would otherwise be ignored. */\nexport interface CreditsOnlyBursarOptions extends BaseBursarOptions {\n billingStore?: undefined;\n billingOptions?: never;\n commerceOptions?: never;\n}\n\n/** Billing construction owns provisioning and may optionally enable commerce. */\nexport interface BillingBursarOptions extends BaseBursarOptions {\n billingStore: BillingStore;\n billingOptions?: Omit<BillingServiceOptions, \"provisioning\">;\n commerceOptions?: CommerceOptions;\n}\n\n/** Options for constructing the single application-facing Bursar service. */\nexport type BursarOptions = CreditsOnlyBursarOptions | BillingBursarOptions;\n\n/** Catalog operations. Configuration writes live here, never in BillingService. */\nexport class CatalogService {\n constructor(private readonly credits: CatalogCreditsService) {}\n\n /** Return the active persisted catalog revision, if one exists. */\n getActive() {\n return this.credits.getActiveCatalog();\n }\n\n /** Whether this process currently has a pricing engine loaded. */\n get isLoaded(): boolean {\n return this.credits.pricingEngine !== null;\n }\n\n /** Load the active persisted catalog into this process. */\n load(): Promise<void> {\n return this.credits.loadCatalogFromStore();\n }\n\n /** Block until a stale in-process catalog has been refreshed. */\n refresh(): Promise<void> {\n return this.credits.refreshCatalogIfStale();\n }\n\n /** Force the next refresh to reload the active catalog. */\n invalidate(): void {\n this.credits.invalidateCatalog();\n }\n\n async getConfig(): Promise<ParsedBursarConfig> {\n const active = await this.getActive();\n if (!active) throw new CatalogNotLoadedError(\"No active Bursar catalog is available\");\n return loadConfigFromDict(active.config);\n }\n\n async publicView(): Promise<PublicCatalog> {\n return projectPublicCatalog(await this.getConfig());\n }\n\n publishDraft(config: BursarConfigData, label?: string | null): Promise<string> {\n return this.credits.publishCatalogDraft(config, label);\n }\n\n activate(version: number, rollout?: CatalogRollout | null): Promise<string> {\n return this.credits.activateCatalogRevision(version, rollout);\n }\n\n publishAndActivate(\n config: BursarConfigData,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string> {\n return this.credits.publishAndActivateCatalog(config, label, rollout);\n }\n\n /** Pin or unpin one current assignment from automatic catalog rollout. */\n setRevisionPin(userId: string, pinned: boolean): Promise<boolean> {\n return this.credits.setPlanRevisionPin(userId, pinned);\n }\n\n /** Apply one bounded batch of renewal-effective plan changes. */\n applyDueChanges(limit = 100): Promise<number> {\n return this.credits.applyDuePlanChanges(limit);\n }\n}\n\nexport interface AccountCreatedInput {\n accountId: string;\n eventKey: string;\n region?: string | null;\n metadata?: CreditMetadata | null;\n}\n\nexport interface AccountCreatedResult {\n accountId: string;\n planKey: string;\n planAssigned: boolean;\n grants: GrantProgramAwardResult[];\n}\n\n/** Generic financial lifecycle operations for SaaS accounts. */\nexport class AccountService {\n constructor(\n private readonly credits: CreditsService,\n private readonly catalog: CatalogService,\n ) {}\n\n async onAccountCreated(input: AccountCreatedInput): Promise<AccountCreatedResult> {\n if (!z.string().trim().min(1).safeParse(input.accountId).success) {\n throw new TypeError(\"accountId must be a non-empty string\");\n }\n if (!z.string().trim().min(1).safeParse(input.eventKey).success) {\n throw new TypeError(\"eventKey must be a non-empty string\");\n }\n const config = await retryBursarOperation(() => this.catalog.getConfig());\n const planKey = config.catalog.defaultPlan;\n if (!planKey) throw new ConfigError(\"The active catalog has no default account plan\");\n\n const current = await retryBursarOperation(() => this.credits.getUserPlan(input.accountId));\n const planAssigned = current.planKey == null;\n if (planAssigned) {\n await retryBursarOperation(() => this.credits.setUserPlan(input.accountId, planKey));\n }\n\n const grants: GrantProgramAwardResult[] = [];\n for (const [programKey, program] of Object.entries(config.credits.grantPrograms).sort(\n ([a], [b]) => a.localeCompare(b),\n )) {\n if (program.trigger !== \"account_created\") continue;\n grants.push(\n ...(await retryBursarOperation(() =>\n this.credits.executeGrantProgram({\n trigger: \"account_created\",\n programKey,\n subjectId: input.accountId,\n eventKey: input.eventKey,\n region: input.region,\n metadata: input.metadata,\n }),\n )),\n );\n }\n return {\n accountId: input.accountId,\n planKey: current.planKey ?? planKey,\n planAssigned,\n grants,\n };\n }\n}\n\n/**\n * The application-facing Bursar boundary.\n *\n * Credit and billing services are deliberately created together so consumers\n * cannot accidentally construct unrelated services for the same account\n * lifecycle. Provider and application integrations use this facade rather\n * than constructing lifecycle services independently.\n */\nexport class Bursar implements BillingEventSink {\n readonly credits: CreditsService;\n readonly billing: BillingCapability | null;\n readonly commerce: CommerceServiceImpl | null;\n readonly catalog: CatalogService;\n readonly accounts: AccountService;\n\n constructor(options: BursarOptions) {\n if (!z.object({}).safeParse(options).success) {\n throw new TypeError(\"Bursar options are required\");\n }\n if (options.billingStore === null) {\n throw new TypeError(\"billingStore must be a BillingStore when provided\");\n }\n for (const optionName of [\n \"creditsOptions\",\n \"billingOptions\",\n \"commerceOptions\",\n \"emitter\",\n ] as const) {\n if (options[optionName] === null) {\n throw new TypeError(`${optionName} must not be null`);\n }\n }\n if (\n options.billingStore === undefined &&\n (options.billingOptions !== undefined || options.commerceOptions !== undefined)\n ) {\n throw new TypeError(\"billingOptions and commerceOptions require billingStore\");\n }\n if (options.billingOptions && \"provisioning\" in options.billingOptions) {\n throw new TypeError(\"billingOptions.provisioning is owned by Bursar\");\n }\n const environments = [\n [\"creditStore\", options.creditStore.providerEnvironment],\n [\"billingStore\", options.billingStore?.providerEnvironment],\n [\"commerceOptions\", options.commerceOptions?.providerEnvironment],\n ].filter((entry): entry is [string, NonNullable<(typeof entry)[1]>] => entry[1] !== undefined);\n if (new Set(environments.map(([, environment]) => environment)).size > 1) {\n throw new TypeError(\n `Bursar provider environments must match: ${environments\n .map(([name, environment]) => `${name}=${environment}`)\n .join(\", \")}`,\n );\n }\n const credits = new CreditsServiceImpl(\n options.creditStore,\n undefined,\n options.emitter ?? undefined,\n options.creditsOptions ?? undefined,\n );\n this.credits = credits;\n this.catalog = new CatalogService(credits);\n this.accounts = new AccountService(credits, this.catalog);\n\n this.billing = options.billingStore\n ? new BillingEventService(options.billingStore, {\n ...(options.billingOptions ?? {}),\n provisioning: credits,\n })\n : null;\n this.commerce =\n this.billing && options.commerceOptions\n ? new CommerceServiceImpl(this.billing, credits, this, options.commerceOptions)\n : null;\n if (this.commerce) {\n credits.addPostDeductionHook(async ({ userId }) => {\n await this.commerce!.autoRecharge.processIfNeeded({ accountId: userId });\n });\n }\n }\n\n /** Load the active catalog into the pricing engine. */\n async loadCatalog(): Promise<void> {\n await this.catalog.load();\n }\n\n /** Return billing or raise the SDK's typed configuration error. */\n requireBilling(): BillingCapability {\n if (!this.billing) {\n throw new CapabilityNotConfiguredError(\"billing\");\n }\n return this.billing;\n }\n\n /** Return commerce or raise the SDK's typed configuration error. */\n requireCommerce(): CommerceServiceImpl {\n if (!this.commerce) {\n throw new CommerceNotConfiguredError(\"Bursar commerce capability is not configured\");\n }\n return this.commerce;\n }\n\n /**\n * Ingest a normalized provider event through the facade-owned billing\n * lifecycle. Providers must not depend on BillingService directly.\n */\n async ingestBillingEvent(event: BillingEvent): Promise<BillingEventResult> {\n return this.requireBilling().ingestBillingEvent(event);\n }\n}\n"]}
|
package/dist/catalog.d.ts.map
CHANGED
|
@@ -1 +1 @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9B;AA+CD,8EAA8E;AAC9E,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,kBAAkB,GAAG,aAAa,CA2D9E"}
|
package/dist/catalog.js
CHANGED
|
@@ -22,60 +22,63 @@ function publicWindow(window) {
|
|
|
22
22
|
};
|
|
23
23
|
}
|
|
24
24
|
function publicOffer(key, offer) {
|
|
25
|
-
|
|
25
|
+
const result = {
|
|
26
26
|
key,
|
|
27
27
|
type: offer.type,
|
|
28
28
|
displayName: offer.displayName,
|
|
29
|
-
...(offer.description ? { description: offer.description } : {}),
|
|
30
29
|
sortOrder: offer.sortOrder,
|
|
31
30
|
price: { ...offer.price },
|
|
32
|
-
...(offer.type === "subscription"
|
|
33
|
-
? {
|
|
34
|
-
billingInterval: {
|
|
35
|
-
unit: offer.billingInterval.unit,
|
|
36
|
-
count: offer.billingInterval.count,
|
|
37
|
-
},
|
|
38
|
-
}
|
|
39
|
-
: {
|
|
40
|
-
creditsPerUnit: offer.creditsPerUnit.toString(),
|
|
41
|
-
quantity: { ...offer.quantity },
|
|
42
|
-
}),
|
|
43
31
|
};
|
|
32
|
+
if (offer.description)
|
|
33
|
+
result.description = offer.description;
|
|
34
|
+
if (offer.type === "subscription") {
|
|
35
|
+
result.billingInterval = {
|
|
36
|
+
unit: offer.billingInterval.unit,
|
|
37
|
+
count: offer.billingInterval.count,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
result.creditsPerUnit = offer.creditsPerUnit.toString();
|
|
42
|
+
result.quantity = { ...offer.quantity };
|
|
43
|
+
}
|
|
44
|
+
return result;
|
|
44
45
|
}
|
|
45
46
|
/** Produce a provider-secret-free, JSON-safe catalog for product surfaces. */
|
|
46
47
|
export function projectPublicCatalog(config) {
|
|
47
48
|
const offers = Object.entries(config.commerce.offers);
|
|
48
49
|
const plans = Object.entries(config.plans)
|
|
49
|
-
.map(([key, plan]) =>
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
50
|
+
.map(([key, plan]) => {
|
|
51
|
+
const publicPlan = {
|
|
52
|
+
key,
|
|
53
|
+
displayName: plan.displayName,
|
|
54
|
+
rank: plan.rank,
|
|
55
|
+
features: { ...plan.features },
|
|
56
|
+
quotas: Object.fromEntries(Object.entries(plan.quotas).map(([quotaKey, quota]) => [
|
|
57
|
+
quotaKey,
|
|
58
|
+
{
|
|
59
|
+
operation: quota.operation,
|
|
60
|
+
measure: quota.measure,
|
|
61
|
+
limit: quota.limit.toString(),
|
|
62
|
+
window: publicWindow(quota.window),
|
|
63
|
+
enforcement: quota.enforcement,
|
|
61
64
|
},
|
|
62
|
-
|
|
63
|
-
:
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
})
|
|
65
|
+
])),
|
|
66
|
+
offers: offers
|
|
67
|
+
.filter((entry) => entry[1].type === "subscription" && entry[1].plan === key)
|
|
68
|
+
.map(([offerKey, offer]) => publicOffer(offerKey, offer))
|
|
69
|
+
.sort((a, b) => a.sortOrder - b.sortOrder || a.key.localeCompare(b.key)),
|
|
70
|
+
};
|
|
71
|
+
if (plan.description)
|
|
72
|
+
publicPlan.description = plan.description;
|
|
73
|
+
if (plan.creditAllowance) {
|
|
74
|
+
publicPlan.allowance = {
|
|
75
|
+
amount: plan.creditAllowance.amount.toString(),
|
|
76
|
+
priority: plan.creditAllowance.priority,
|
|
77
|
+
window: publicWindow(plan.creditAllowance.window),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
return publicPlan;
|
|
81
|
+
})
|
|
79
82
|
.sort((a, b) => a.rank - b.rank || a.key.localeCompare(b.key));
|
|
80
83
|
return {
|
|
81
84
|
version: 1,
|
package/dist/catalog.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"catalog.js","sourceRoot":"","sources":["../src/catalog.ts"],"names":[],"mappings":"AA4DA,SAAS,YAAY,CAAC,MAAc;IAClC,IAAI,MAAM,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;QAC/B,OAAO;YACL,IAAI,EAAE,MAAM,CAAC,IAAI;YACjB,IAAI,EAAE,MAAM,CAAC,IAAI;YACjB,KAAK,EAAE,MAAM,CAAC,KAAK;YACnB,QAAQ,EAAE,MAAM,CAAC,QAAQ;SAC1B,CAAC;IACJ,CAAC;IACD,IAAI,MAAM,CAAC,IAAI,KAAK,iBAAiB,EAAE,CAAC;QACtC,OAAO;YACL,IAAI,EAAE,MAAM,CAAC,IAAI;YACjB,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,IAAI;YAC1B,KAAK,EAAE,MAAM,CAAC,QAAQ,CAAC,KAAK;YAC5B,QAAQ,EAAE,MAAM,CAAC,QAAQ;SAC1B,CAAC;IACJ,CAAC;IACD,OAAO;QACL,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,IAAI;QAC1B,KAAK,EAAE,MAAM,CAAC,QAAQ,CAAC,KAAK;KAC7B,CAAC;AACJ,CAAC;AAED,SAAS,WAAW,CAAC,GAAW,EAAE,KAAoB;IACpD,
|
|
1
|
+
{"version":3,"file":"catalog.js","sourceRoot":"","sources":["../src/catalog.ts"],"names":[],"mappings":"AA4DA,SAAS,YAAY,CAAC,MAAc;IAClC,IAAI,MAAM,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;QAC/B,OAAO;YACL,IAAI,EAAE,MAAM,CAAC,IAAI;YACjB,IAAI,EAAE,MAAM,CAAC,IAAI;YACjB,KAAK,EAAE,MAAM,CAAC,KAAK;YACnB,QAAQ,EAAE,MAAM,CAAC,QAAQ;SAC1B,CAAC;IACJ,CAAC;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AW,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;aAC9C,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAC3E,CAAC;AACJ,CAAC","sourcesContent":["import type { CommerceOffer, FeatureValue, ParsedBursarConfig, Window } from \"./config/types.js\";\n\nexport interface PublicCatalogWindow {\n type: Window[\"type\"];\n unit: string;\n count: number;\n timezone?: string;\n}\n\nexport interface PublicCatalogOffer {\n key: string;\n type: CommerceOffer[\"type\"];\n displayName: string;\n description?: string;\n sortOrder: number;\n price: {\n amountMinor: number;\n currency: string;\n taxBehavior: \"inclusive\" | \"exclusive\" | \"unspecified\";\n };\n billingInterval?: { unit: string; count: number };\n creditsPerUnit?: string;\n quantity?: { minimum: number; maximum: number; default: number };\n}\n\nexport interface PublicCatalogPlan {\n key: string;\n displayName: string;\n description?: string;\n rank: number;\n features: Record<string, FeatureValue>;\n allowance?: {\n amount: string;\n priority: number;\n window: PublicCatalogWindow;\n };\n quotas: Record<\n string,\n {\n operation: string;\n measure: string;\n limit: string;\n window: PublicCatalogWindow;\n enforcement: \"block\" | \"allow\";\n }\n >;\n offers: PublicCatalogOffer[];\n}\n\nexport interface PublicCatalog {\n version: 1;\n defaultPlan: string | null;\n creditDisplay: {\n currency: string;\n unitsPerMajor: string;\n } | null;\n plans: PublicCatalogPlan[];\n topups: PublicCatalogOffer[];\n}\n\nfunction publicWindow(window: Window): PublicCatalogWindow {\n if (window.type === \"calendar\") {\n return {\n type: window.type,\n unit: window.unit,\n count: window.count,\n timezone: window.timezone,\n };\n }\n if (window.type === \"plan_assignment\") {\n return {\n type: window.type,\n unit: window.interval.unit,\n count: window.interval.count,\n timezone: window.timezone,\n };\n }\n return {\n type: window.type,\n unit: window.duration.unit,\n count: window.duration.count,\n };\n}\n\nfunction publicOffer(key: string, offer: CommerceOffer): PublicCatalogOffer {\n const result: PublicCatalogOffer = {\n key,\n type: offer.type,\n displayName: offer.displayName,\n sortOrder: offer.sortOrder,\n price: { ...offer.price },\n };\n if (offer.description) result.description = offer.description;\n if (offer.type === \"subscription\") {\n result.billingInterval = {\n unit: offer.billingInterval.unit,\n count: offer.billingInterval.count,\n };\n } else {\n result.creditsPerUnit = offer.creditsPerUnit.toString();\n result.quantity = { ...offer.quantity };\n }\n return result;\n}\n\n/** Produce a provider-secret-free, JSON-safe catalog for product surfaces. */\nexport function projectPublicCatalog(config: ParsedBursarConfig): PublicCatalog {\n const offers = Object.entries(config.commerce.offers);\n const plans = Object.entries(config.plans)\n .map(([key, plan]): PublicCatalogPlan => {\n const publicPlan: PublicCatalogPlan = {\n key,\n displayName: plan.displayName,\n rank: plan.rank,\n features: { ...plan.features },\n quotas: Object.fromEntries(\n Object.entries(plan.quotas).map(([quotaKey, quota]) => [\n quotaKey,\n {\n operation: quota.operation,\n measure: quota.measure,\n limit: quota.limit.toString(),\n window: publicWindow(quota.window),\n enforcement: quota.enforcement,\n },\n ]),\n ),\n offers: offers\n .filter(\n (entry): entry is [string, Extract<CommerceOffer, { type: \"subscription\" }>] =>\n entry[1].type === \"subscription\" && entry[1].plan === key,\n )\n .map(([offerKey, offer]) => publicOffer(offerKey, offer))\n .sort((a, b) => a.sortOrder - b.sortOrder || a.key.localeCompare(b.key)),\n };\n if (plan.description) publicPlan.description = plan.description;\n if (plan.creditAllowance) {\n publicPlan.allowance = {\n amount: plan.creditAllowance.amount.toString(),\n priority: plan.creditAllowance.priority,\n window: publicWindow(plan.creditAllowance.window),\n };\n }\n return publicPlan;\n })\n .sort((a, b) => a.rank - b.rank || a.key.localeCompare(b.key));\n\n return {\n version: 1,\n defaultPlan: config.catalog.defaultPlan ?? null,\n creditDisplay: config.credits.display\n ? {\n currency: config.credits.display.currency,\n unitsPerMajor: config.credits.display.unitsPerMajor.toString(),\n }\n : null,\n plans,\n topups: offers\n .filter(\n (entry): entry is [string, Extract<CommerceOffer, { type: \"topup\" }>] =>\n entry[1].type === \"topup\",\n )\n .map(([key, offer]) => publicOffer(key, offer))\n .sort((a, b) => a.sortOrder - b.sortOrder || a.key.localeCompare(b.key)),\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-registry.d.ts","sourceRoot":"","sources":["../../src/commerce/provider-registry.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"provider-registry.d.ts","sourceRoot":"","sources":["../../src/commerce/provider-registry.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE7D,OAAO,KAAK,EAAE,eAAe,EAAE,8BAA8B,EAAE,MAAM,YAAY,CAAC;AAgBlF,qBAAa,wBAAwB;IAIjC,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAJ1B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA+C;gBAGtD,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,8BAA8B;IAsB1D,IAAI,mBAAmB,IAAI,MAAM,EAAE,CAElC;IAED,KAAK,IAAI,IAAI;IAIP,GAAG,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC;IAiCnD,MAAM,CAAC,KAAK,EAAE;QAClB,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QAC1B,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QACxB,KAAK,CAAC,EAAE,aAAa,GAAG,IAAI,CAAC;KAC9B,GAAG,OAAO,CAAC,eAAe,CAAC;CAgC7B"}
|
|
@@ -1,12 +1,17 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
1
2
|
import { ProviderSelectionError } from "./errors.js";
|
|
3
|
+
const paymentProviderSchema = z.object({
|
|
4
|
+
provider: z.string().trim().min(1),
|
|
5
|
+
createCheckoutSession: z.function(),
|
|
6
|
+
handleWebhook: z.function(),
|
|
7
|
+
});
|
|
2
8
|
function isPaymentProvider(value) {
|
|
3
|
-
|
|
9
|
+
try {
|
|
10
|
+
return paymentProviderSchema.safeParse(value).success;
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
4
13
|
return false;
|
|
5
|
-
|
|
6
|
-
return (typeof candidate.provider === "string" &&
|
|
7
|
-
candidate.provider.trim().length > 0 &&
|
|
8
|
-
typeof candidate.createCheckoutSession === "function" &&
|
|
9
|
-
typeof candidate.handleWebhook === "function");
|
|
14
|
+
}
|
|
10
15
|
}
|
|
11
16
|
export class CommerceProviderRegistry {
|
|
12
17
|
options;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-registry.js","sourceRoot":"","sources":["../../src/commerce/provider-registry.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"provider-registry.js","sourceRoot":"","sources":["../../src/commerce/provider-registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAGrD,MAAM,qBAAqB,GAAG,CAAC,CAAC,MAAM,CAAC;IACrC,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IAClC,qBAAqB,EAAE,CAAC,CAAC,QAAQ,EAAE;IACnC,aAAa,EAAE,CAAC,CAAC,QAAQ,EAAE;CAC5B,CAAC,CAAC;AAEH,SAAS,iBAAiB,CAAI,KAAQ;IACpC,IAAI,CAAC;QACH,OAAO,qBAAqB,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC;IACxD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED,MAAM,OAAO,wBAAwB;I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AE,CAAC,CAAC;QAC7D,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC5B,MAAM,IAAI,sBAAsB,CAAC,8CAA8C,CAAC,CAAC;QACnF,CAAC;QACD,MAAM,IAAI,sBAAsB,CAC9B,oCAAoC,UAAU,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CACnE,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { z } from \"zod\";\n\nimport type { CommerceOffer } from \"../config/types.js\";\nimport type { PaymentProvider } from \"../providers/types.js\";\nimport { ProviderSelectionError } from \"./errors.js\";\nimport type { CommerceOptions, CommerceProviderFactoryContext } from \"./types.js\";\n\nconst paymentProviderSchema = z.object({\n provider: z.string().trim().min(1),\n createCheckoutSession: z.function(),\n handleWebhook: z.function(),\n});\n\nfunction isPaymentProvider<T>(value: T): value is T & PaymentProvider {\n try {\n return paymentProviderSchema.safeParse(value).success;\n } catch {\n return false;\n }\n}\n\nexport class CommerceProviderRegistry {\n private readonly instances = new Map<string, Promise<PaymentProvider>>();\n\n constructor(\n private readonly options: CommerceOptions,\n private readonly context: CommerceProviderFactoryContext,\n ) {\n const providerNames = Object.keys(options.providers);\n if (providerNames.length === 0) {\n throw new ProviderSelectionError(\"At least one payment provider must be registered\");\n }\n if (providerNames.some((name) => !name.trim())) {\n throw new ProviderSelectionError(\"Payment provider names must not be empty\");\n }\n if (options.defaultProvider !== undefined && !options.defaultProvider.trim()) {\n throw new ProviderSelectionError(\"Default payment provider must not be empty\");\n }\n if (\n options.defaultProvider != null &&\n !Object.prototype.hasOwnProperty.call(options.providers, options.defaultProvider)\n ) {\n throw new ProviderSelectionError(\n `Default payment provider '${options.defaultProvider}' is not registered`,\n );\n }\n }\n\n get configuredProviders(): string[] {\n return Object.keys(this.options.providers);\n }\n\n clear(): void {\n this.instances.clear();\n }\n\n async get(providerName: string): Promise<PaymentProvider> {\n const factory = this.options.providers[providerName];\n if (!factory) {\n throw new ProviderSelectionError(`Payment provider '${providerName}' is not registered`);\n }\n let loading = this.instances.get(providerName);\n if (!loading) {\n const created = Promise.resolve(factory(this.context))\n .then((provider) => {\n if (!isPaymentProvider(provider)) {\n throw new ProviderSelectionError(\n `Provider factory '${providerName}' did not return a valid payment provider`,\n );\n }\n if (provider.provider !== providerName) {\n throw new ProviderSelectionError(\n `Provider factory '${providerName}' returned provider '${provider.provider}'`,\n );\n }\n return provider;\n })\n .catch((error) => {\n if (this.instances.get(providerName) === created) {\n this.instances.delete(providerName);\n }\n throw error;\n });\n loading = created;\n this.instances.set(providerName, loading);\n }\n return loading;\n }\n\n async select(input: {\n requested?: string | null;\n current?: string | null;\n offer?: CommerceOffer | null;\n }): Promise<PaymentProvider> {\n const compatible = input.offer\n ? Object.keys(input.offer.providers).filter((name) =>\n Object.prototype.hasOwnProperty.call(this.options.providers, name),\n )\n : this.configuredProviders;\n\n const assertCompatible = (name: string): string => {\n if (!this.options.providers[name]) {\n throw new ProviderSelectionError(`Payment provider '${name}' is not registered`);\n }\n if (input.offer && !input.offer.providers[name]) {\n throw new ProviderSelectionError(\n `Offer is not available through payment provider '${name}'`,\n );\n }\n return name;\n };\n\n if (input.requested) return this.get(assertCompatible(input.requested));\n if (input.current) return this.get(assertCompatible(input.current));\n if (this.options.defaultProvider && compatible.includes(this.options.defaultProvider)) {\n return this.get(this.options.defaultProvider);\n }\n if (compatible.length === 1) return this.get(compatible[0]!);\n if (compatible.length === 0) {\n throw new ProviderSelectionError(\"No compatible payment provider is registered\");\n }\n throw new ProviderSelectionError(\n `Provider selection is ambiguous: ${compatible.sort().join(\", \")}`,\n );\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/commerce/service.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AACnF,OAAO,KAAK,EAAE,kBAAkB,EAA4B,MAAM,2BAA2B,CAAC;AAG9F,OAAO,KAAK,EACV,aAAa,EAKd,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,aAAa,EACb,oBAAoB,EACpB,iBAAiB,EACjB,WAAW,EACX,UAAU,EACV,wBAAwB,EACxB,uBAAuB,EACvB,eAAe,EAChB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/commerce/service.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AACnF,OAAO,KAAK,EAAE,kBAAkB,EAA4B,MAAM,2BAA2B,CAAC;AAG9F,OAAO,KAAK,EACV,aAAa,EAKd,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,aAAa,EACb,oBAAoB,EACpB,iBAAiB,EACjB,WAAW,EACX,UAAU,EACV,wBAAwB,EACxB,uBAAuB,EACvB,eAAe,EAChB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,KAAK,EAIV,eAAe,EAEhB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAkBtD,OAAO,KAAK,EACV,uBAAuB,EACvB,0BAA0B,EAG1B,oBAAoB,EAEpB,eAAe,EACf,oBAAoB,EACpB,qBAAqB,EACrB,sBAAsB,EACtB,uBAAuB,EAEvB,mBAAmB,EACnB,oBAAoB,EACpB,mBAAmB,EAEnB,uBAAuB,EACvB,kBAAkB,EAClB,eAAe,EACf,sBAAsB,EACtB,yBAAyB,EACzB,4BAA4B,EAC7B,MAAM,YAAY,CAAC;AAgLpB,kEAAkE;AAClE,MAAM,WAAW,eAAe;IAC9B,UAAU,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;IACtD,YAAY,CAAC,SAAS,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Ae,CAAC;KACxB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAO/B,OAAO,CAAC,cAAc;IAoBhB,kBAAkB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,uBAAuB,CAAC;IA8LvE,cAAc,CAAC,KAAK,EAAE,mBAAmB,GAAG,OAAO,CAAC;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;IAqCpE,aAAa,CAAC,KAAK,EAAE,oBAAoB,GAAG,OAAO,CAAC,qBAAqB,CAAC;CAcjF"}
|
package/dist/commerce/service.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { z } from "zod";
|
|
3
|
-
import Decimal from "decimal.js";
|
|
3
|
+
import { Decimal } from "decimal.js";
|
|
4
4
|
import { loadConfigFromDict } from "../config.js";
|
|
5
5
|
import { ProviderResponseError } from "../errors.js";
|
|
6
6
|
import { normalizeLogger } from "../shared/logger.js";
|
|
7
7
|
import { requireStableKey, scopedStableKey } from "../shared/idempotency.js";
|
|
8
8
|
import { normalizeProviderEnvironment } from "../providers/environment.js";
|
|
9
|
+
import { persistedDiagnosticSummary } from "../shared/diagnostics.js";
|
|
9
10
|
import { ActiveSubscriptionError, CheckoutCompletedError, CheckoutConflictError, CommerceResourceNotFoundError, CoreBillingDataUnavailableError, InvalidOfferQuantityError, ProviderCapabilityNotSupportedError, QuoteChangedError, UnknownOfferError, } from "./errors.js";
|
|
10
11
|
import { CommerceProviderRegistry } from "./provider-registry.js";
|
|
11
12
|
import { classifySubscriptionChange } from "./plan-change.js";
|
|
@@ -18,7 +19,7 @@ const DEFAULT_PREFERENCES = {
|
|
|
18
19
|
invoiceReminders: false,
|
|
19
20
|
};
|
|
20
21
|
function requireNonEmptyText(value, field) {
|
|
21
|
-
if (
|
|
22
|
+
if (!z.string().trim().min(1).safeParse(value).success) {
|
|
22
23
|
throw new TypeError(`${field} must be a non-empty string`);
|
|
23
24
|
}
|
|
24
25
|
}
|
|
@@ -39,15 +40,9 @@ function assertCreateCheckoutInput(input) {
|
|
|
39
40
|
throw new TypeError("type must be 'subscription' or 'credit_pack'");
|
|
40
41
|
}
|
|
41
42
|
if (input.metadata !== undefined) {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
throw new TypeError("metadata must be an object of string values");
|
|
46
|
-
}
|
|
47
|
-
for (const [key, value] of Object.entries(input.metadata)) {
|
|
48
|
-
if (!key.trim() || typeof value !== "string") {
|
|
49
|
-
throw new TypeError("metadata must contain non-empty keys and string values");
|
|
50
|
-
}
|
|
43
|
+
const metadata = z.record(z.string().trim().min(1), z.string()).safeParse(input.metadata);
|
|
44
|
+
if (!metadata.success) {
|
|
45
|
+
throw new TypeError("metadata must contain non-empty keys and string values");
|
|
51
46
|
}
|
|
52
47
|
}
|
|
53
48
|
}
|
|
@@ -331,81 +326,91 @@ export class CommerceService {
|
|
|
331
326
|
metadata.credits = resolved.offer.creditsPerUnit.mul(quantity).toString();
|
|
332
327
|
metadata.quantity = String(quantity);
|
|
333
328
|
}
|
|
334
|
-
const
|
|
335
|
-
.
|
|
329
|
+
const digestValue = {
|
|
330
|
+
accountId: input.accountId,
|
|
336
331
|
checkoutKind: resolved.offer.type,
|
|
337
332
|
offerKey: resolved.offerKey,
|
|
338
333
|
provider: provider.provider,
|
|
339
334
|
quantity,
|
|
340
|
-
|
|
341
|
-
|
|
335
|
+
};
|
|
336
|
+
const requestDigest = createHash("sha256")
|
|
337
|
+
.update(JSON.stringify(digestValue, Object.keys(digestValue).sort()))
|
|
342
338
|
.digest("hex");
|
|
343
339
|
const expiresAt = () => new Date(Date.now() + (this.options.checkoutIntentTtlMs ?? DEFAULT_CHECKOUT_INTENT_TTL_MS)).toISOString();
|
|
344
340
|
const createIntent = () => this.billing.createOrGetCheckoutIntent({
|
|
345
341
|
subjectId: input.subjectId,
|
|
346
342
|
provider: provider.provider,
|
|
343
|
+
operationKey: input.operationKey,
|
|
347
344
|
checkoutKind: resolved.offer.type === "subscription" ? "subscription" : "credit_topup",
|
|
348
345
|
productKey: resolved.offerKey,
|
|
349
346
|
requestDigest,
|
|
350
347
|
expiresAt: expiresAt(),
|
|
351
348
|
});
|
|
352
|
-
|
|
349
|
+
const intent = await createIntent();
|
|
353
350
|
if (intent.requestDigest !== requestDigest) {
|
|
354
|
-
throw new CheckoutConflictError("
|
|
351
|
+
throw new CheckoutConflictError("This operation key is already bound to a different checkout request");
|
|
352
|
+
}
|
|
353
|
+
if (intent.status === "completed")
|
|
354
|
+
throw new CheckoutCompletedError();
|
|
355
|
+
if (intent.status !== "open") {
|
|
356
|
+
throw new CheckoutConflictError("This checkout operation is terminal; start a new checkout with a new operation key");
|
|
355
357
|
}
|
|
356
358
|
if (intent.checkoutUrl) {
|
|
357
359
|
const locallyExpired = new Date(intent.expiresAt).getTime() <= Date.now();
|
|
358
|
-
if (
|
|
359
|
-
|
|
360
|
+
if (locallyExpired) {
|
|
361
|
+
await this.billing.updateCheckoutIntent(intent.id, { status: "expired" });
|
|
362
|
+
throw new CheckoutConflictError("This checkout operation expired; start a new checkout with a new operation key");
|
|
360
363
|
}
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
}
|
|
373
|
-
await this.billing.updateCheckoutIntent(intent.id, {
|
|
374
|
-
status: providerState === null ? "expired" : "failed",
|
|
375
|
-
});
|
|
376
|
-
intent = await createIntent();
|
|
377
|
-
}
|
|
378
|
-
try {
|
|
379
|
-
const session = await provider.createCheckoutSession({
|
|
380
|
-
accountId: input.accountId,
|
|
381
|
-
...(customer?.providerCustomerId ? { customerId: customer.providerCustomerId } : {}),
|
|
382
|
-
...(input.email ? { email: input.email } : {}),
|
|
383
|
-
productId,
|
|
384
|
-
type: resolved.offer.type === "subscription" ? "subscription" : "credit_pack",
|
|
385
|
-
quantity,
|
|
386
|
-
returnUrl: checkoutRedirectUrl(input.returnUrl, intent.id),
|
|
387
|
-
cancelUrl: checkoutRedirectUrl(input.cancelUrl, intent.id),
|
|
388
|
-
metadata: { ...metadata, checkout_intent_id: intent.id },
|
|
389
|
-
idempotencyKey: input.operationKey,
|
|
390
|
-
});
|
|
391
|
-
await this.billing.updateCheckoutIntent(intent.id, {
|
|
392
|
-
providerSessionId: session.providerSessionId,
|
|
393
|
-
checkoutUrl: session.url,
|
|
394
|
-
});
|
|
395
|
-
if (session.customerId && session.customerId !== customer?.providerCustomerId) {
|
|
396
|
-
await this.billing.upsertCustomer(provider.provider, session.customerId, input.accountId, input.email ?? null);
|
|
364
|
+
if (intent.providerSessionId && provider.getCheckoutSessionStatus) {
|
|
365
|
+
const providerState = await provider.getCheckoutSessionStatus(intent.providerSessionId);
|
|
366
|
+
if (providerState?.paymentStatus === "succeeded") {
|
|
367
|
+
await this.billing.updateCheckoutIntent(intent.id, { status: "completed" });
|
|
368
|
+
throw new CheckoutCompletedError();
|
|
369
|
+
}
|
|
370
|
+
if (providerState !== null &&
|
|
371
|
+
TERMINAL_CHECKOUT_STATUSES.has(providerState.paymentStatus ?? "")) {
|
|
372
|
+
await this.billing.updateCheckoutIntent(intent.id, { status: "failed" });
|
|
373
|
+
throw new CheckoutConflictError("This checkout operation is no longer active; start a new checkout with a new operation key");
|
|
374
|
+
}
|
|
397
375
|
}
|
|
398
376
|
return {
|
|
399
377
|
intentId: intent.id,
|
|
400
|
-
url:
|
|
378
|
+
url: intent.checkoutUrl,
|
|
401
379
|
provider: provider.provider,
|
|
402
380
|
offerKey: resolved.offerKey,
|
|
403
381
|
};
|
|
404
382
|
}
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
383
|
+
const checkoutParams = {
|
|
384
|
+
accountId: input.accountId,
|
|
385
|
+
productId,
|
|
386
|
+
type: resolved.offer.type === "subscription" ? "subscription" : "credit_pack",
|
|
387
|
+
quantity,
|
|
388
|
+
returnUrl: checkoutRedirectUrl(input.returnUrl, intent.id),
|
|
389
|
+
cancelUrl: checkoutRedirectUrl(input.cancelUrl, intent.id),
|
|
390
|
+
metadata: { ...metadata, checkout_intent_id: intent.id },
|
|
391
|
+
idempotencyKey: input.operationKey,
|
|
392
|
+
};
|
|
393
|
+
if (customer?.providerCustomerId)
|
|
394
|
+
checkoutParams.customerId = customer.providerCustomerId;
|
|
395
|
+
if (input.email)
|
|
396
|
+
checkoutParams.email = input.email;
|
|
397
|
+
const session = await provider.createCheckoutSession(checkoutParams);
|
|
398
|
+
// Complete every fallible local write before publishing the session on the
|
|
399
|
+
// intent. If either write fails, an exact replay reaches the provider with
|
|
400
|
+
// the same idempotency key and can repair the open intent.
|
|
401
|
+
if (session.customerId && session.customerId !== customer?.providerCustomerId) {
|
|
402
|
+
await this.billing.upsertCustomer(provider.provider, session.customerId, input.accountId, input.email ?? null);
|
|
408
403
|
}
|
|
404
|
+
await this.billing.updateCheckoutIntent(intent.id, {
|
|
405
|
+
providerSessionId: session.providerSessionId,
|
|
406
|
+
checkoutUrl: session.url,
|
|
407
|
+
});
|
|
408
|
+
return {
|
|
409
|
+
intentId: intent.id,
|
|
410
|
+
url: session.url,
|
|
411
|
+
provider: provider.provider,
|
|
412
|
+
offerKey: resolved.offerKey,
|
|
413
|
+
};
|
|
409
414
|
}
|
|
410
415
|
async getCheckoutStatus(input) {
|
|
411
416
|
const intent = await this.billing.getCheckoutIntent(input.intentId, input.subjectId);
|
|
@@ -757,7 +762,7 @@ export class CommerceService {
|
|
|
757
762
|
}
|
|
758
763
|
await this.billing.updateBillingSubscriptionChange(change.id, {
|
|
759
764
|
state: "failed",
|
|
760
|
-
errorMessage: failure
|
|
765
|
+
errorMessage: persistedDiagnosticSummary(failure, "subscription_change_failed"),
|
|
761
766
|
});
|
|
762
767
|
throw failure;
|
|
763
768
|
}
|
|
@@ -838,14 +843,11 @@ export class CommerceService {
|
|
|
838
843
|
}
|
|
839
844
|
ledgerDocument(entry) {
|
|
840
845
|
const metadata = entry.metadata ?? {};
|
|
841
|
-
const
|
|
842
|
-
const
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
: typeof metadata.provider_payment_id === "string"
|
|
847
|
-
? metadata.provider_payment_id
|
|
848
|
-
: undefined;
|
|
846
|
+
const text = z.string();
|
|
847
|
+
const normalizedProvider = text.safeParse(metadata.provider).data;
|
|
848
|
+
const normalizedDocumentId = text.safeParse(metadata.provider_document_id).data ??
|
|
849
|
+
text.safeParse(metadata.provider_invoice_id).data ??
|
|
850
|
+
text.safeParse(metadata.provider_payment_id).data;
|
|
849
851
|
if (!normalizedDocumentId)
|
|
850
852
|
return null;
|
|
851
853
|
return {
|