@rpcbase/billing 0.20.0 → 0.22.0
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/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["SubscriptionIntervalUnit","assertValidDate","value","Date","field","date","Number","isNaN","getTime","Error","normalizeIntervalCount","isInteger","getDaysInUtcMonth","year","month","UTC","getUTCDate","createClampedUtcDate","source","day","Math","min","getUTCHours","getUTCMinutes","getUTCSeconds","getUTCMilliseconds","addBillingInterval","intervalUnit","intervalCount","count","getUTCFullYear","getUTCMonth","absoluteMonth","floor","getEstimatedPeriodIndex","anchor","asOf","rawDifference","max","resolveBillingPeriod","params","billingAnchor","start","end","periodIndex","assertValidDate","value","Date","field","date","Number","isNaN","getTime","Error","calculateProratedAmount","params","unitAmount","segmentStart","segmentEnd","periodStart","periodEnd","isSafeInteger","periodDuration","overlapStart","Math","max","overlapEnd","min","overlapDuration","round","resolveBillingPeriod","ScheduledPlanChange","SubscriptionCreatedEvent","SubscriptionEvent","SubscriptionProjection","SubscriptionStatus","assertValidDate","value","Date","field","date","Number","isNaN","getTime","Error","compareEvents","left","right","effectiveDelta","effectiveAt","occurredDelta","occurredAt","id","localeCompare","sortSubscriptionEvents","events","map","event","dates","type","billingAnchor","undefined","sort","getEffectiveEvents","ordered","supersededIds","Set","supersedesEventId","filter","eventId","Boolean","has","assertSingleSubscription","length","subscriptionIds","subscriptionId","size","tenantIds","tenantId","assertNonEmptyString","trim","assertPositiveInteger","isInteger","assertCreatedEvent","subscriptionType","scope","parentSubscriptionId","scopeId","toPlanKey","toStatus","Array","isArray","toModules","toIntervalUnit","toIntervalCount","assertTransitionEvent","idempotencyKey","fromPlanKey","fromModules","fromIntervalUnit","fromIntervalCount","fromStatus","assertConsistentEventEnvelope","created","projectSubscription","options","asOf","forEach","index","applicable","planKey","priceId","status","intervalUnit","intervalCount","modules","provider","canceledAt","slice","toPriceId","futureEvents","scheduledCancellation","find","scheduledPlanEvent","scheduledPlan","periodAsOf","period","currentPeriodStart","start","currentPeriodEnd","end","cancelAtPeriodEnd","cancelAt","getSubscriptionTransitionDates","params","after","before","time","getSubscriptionTransitionDates","projectSubscription","BillableSubscriptionSegment","SubscriptionEvent","SubscriptionStatus","DEFAULT_BILLABLE_STATUSES","assertValidWindow","from","Date","to","normalizedFrom","normalizedTo","Number","isNaN","getTime","Error","buildBillableSegments","events","params","billableStatuses","length","window","Set","transitionDates","after","before","segments","cursor","projection","asOf","nextTransition","find","date","nextPeriodEnd","currentPeriodEnd","candidateTimes","POSITIVE_INFINITY","nextTime","Math","min","isFinite","next","has","status","push","subscriptionId","planKey","priceId","modules","start","end","periodStart","currentPeriodStart","periodEnd","projectSubscription","PersistedSubscriptionEvent","StoredSubscriptionProjection","SubscriptionEvent","SubscriptionProjection","BillingStorageTransaction","BillingStorage","runInTransaction","operation","transaction","Promise","T","createEvent","event","listEvents","tenantId","subscriptionId","upsertProjection","projection","runWithOptionalTransaction","storage","buildStoredProjection","params","latestEvent","projectedAt","Date","latestEventId","id","latestEventAt","occurredAt","projectAndStore","asOf","events","sort","left","right","occurredDelta","getTime","localeCompare","storedProjection","appendSubscriptionEvent","Error","rebuildSubscriptionProjection","SUBSCRIPTION_STATUSES","const","SubscriptionStatus","SUBSCRIPTION_INTERVAL_UNITS","SubscriptionIntervalUnit","SUBSCRIPTION_TYPES","SubscriptionType","SUBSCRIPTION_SCOPES","SubscriptionScope","SUBSCRIPTION_EVENT_TYPES","SubscriptionEventType","SUBSCRIPTION_CHANGE_DIRECTIONS","SubscriptionChangeDirection","SubscriptionEventBase","id","tenantId","subscriptionId","occurredAt","Date","effectiveAt","subscriptionType","parentSubscriptionId","scope","scopeId","fromPlanKey","toPlanKey","fromStatus","toStatus","fromModules","toModules","fromIntervalUnit","toIntervalUnit","fromIntervalCount","toIntervalCount","fromPriceId","toPriceId","billingAnchor","supersedesEventId","idempotencyKey","direction","actorUserId","source","reason","provider","providerEventId","providerPayload","metadata","Record","SubscriptionCreatedEvent","type","SubscriptionPlanChangedEvent","SubscriptionStatusChangedEvent","SubscriptionResumedEvent","SubscriptionCanceledEvent","SubscriptionRenewedEvent","SubscriptionEvent","PersistedSubscriptionEvent","ScheduledPlanChange","planKey","SubscriptionProjection","priceId","status","intervalUnit","intervalCount","modules","currentPeriodStart","currentPeriodEnd","cancelAtPeriodEnd","cancelAt","canceledAt","scheduledPlan","BillableSubscriptionSegment","start","end","periodStart","periodEnd","StoredSubscriptionProjection","latestEventId","latestEventAt","projectedAt"],"sources":["../src/calendar.ts","../src/proration.ts","../src/projection.ts","../src/segments.ts","../src/storage.ts","../src/types.ts"],"sourcesContent":["import type { SubscriptionIntervalUnit } from \"./types\"\n\n\nconst assertValidDate = (value: Date, field: string): Date => {\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) throw new Error(`${field} must be a valid date`)\n return date\n}\n\nconst normalizeIntervalCount = (value: number): number => {\n if (!Number.isInteger(value) || value < 1) throw new Error(\"intervalCount must be a positive integer\")\n return value\n}\n\nconst getDaysInUtcMonth = (year: number, month: number): number =>\n new Date(Date.UTC(year, month + 1, 0)).getUTCDate()\n\nconst createClampedUtcDate = (source: Date, year: number, month: number): Date => {\n const day = Math.min(source.getUTCDate(), getDaysInUtcMonth(year, month))\n return new Date(Date.UTC(\n year,\n month,\n day,\n source.getUTCHours(),\n source.getUTCMinutes(),\n source.getUTCSeconds(),\n source.getUTCMilliseconds(),\n ))\n}\n\nexport const addBillingInterval = (\n value: Date,\n intervalUnit: SubscriptionIntervalUnit,\n intervalCount = 1,\n): Date => {\n const date = assertValidDate(value, \"value\")\n const count = normalizeIntervalCount(intervalCount)\n\n if (intervalUnit === \"year\") {\n return createClampedUtcDate(date, date.getUTCFullYear() + count, date.getUTCMonth())\n }\n\n const absoluteMonth = date.getUTCFullYear() * 12 + date.getUTCMonth() + count\n const year = Math.floor(absoluteMonth / 12)\n const month = ((absoluteMonth % 12) + 12) % 12\n return createClampedUtcDate(date, year, month)\n}\n\nconst getEstimatedPeriodIndex = (\n anchor: Date,\n asOf: Date,\n intervalUnit: SubscriptionIntervalUnit,\n intervalCount: number,\n): number => {\n if (asOf.getTime() <= anchor.getTime()) return 0\n\n const rawDifference = intervalUnit === \"year\"\n ? asOf.getUTCFullYear() - anchor.getUTCFullYear()\n : (asOf.getUTCFullYear() - anchor.getUTCFullYear()) * 12 + asOf.getUTCMonth() - anchor.getUTCMonth()\n\n return Math.max(0, Math.floor(rawDifference / intervalCount))\n}\n\nexport const resolveBillingPeriod = (params: {\n billingAnchor: Date\n intervalUnit: SubscriptionIntervalUnit\n intervalCount?: number\n asOf: Date\n}): { start: Date; end: Date } => {\n const anchor = assertValidDate(params.billingAnchor, \"billingAnchor\")\n const asOf = assertValidDate(params.asOf, \"asOf\")\n const intervalCount = normalizeIntervalCount(params.intervalCount ?? 1)\n\n let periodIndex = getEstimatedPeriodIndex(anchor, asOf, params.intervalUnit, intervalCount)\n let start = addBillingInterval(anchor, params.intervalUnit, Math.max(1, periodIndex * intervalCount))\n\n if (periodIndex === 0) start = new Date(anchor)\n\n while (start.getTime() > asOf.getTime() && periodIndex > 0) {\n periodIndex -= 1\n start = periodIndex === 0\n ? new Date(anchor)\n : addBillingInterval(anchor, params.intervalUnit, periodIndex * intervalCount)\n }\n\n let end = addBillingInterval(anchor, params.intervalUnit, (periodIndex + 1) * intervalCount)\n while (end.getTime() <= asOf.getTime()) {\n periodIndex += 1\n start = new Date(end)\n end = addBillingInterval(anchor, params.intervalUnit, (periodIndex + 1) * intervalCount)\n }\n\n return { start, end }\n}\n","const assertValidDate = (value: Date, field: string): Date => {\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) throw new Error(`${field} must be a valid date`)\n return date\n}\n\nexport const calculateProratedAmount = (params: {\n unitAmount: number\n segmentStart: Date\n segmentEnd: Date\n periodStart: Date\n periodEnd: Date\n}): number => {\n if (!Number.isSafeInteger(params.unitAmount) || params.unitAmount < 0) {\n throw new Error(\"unitAmount must be a non-negative safe integer\")\n }\n\n const segmentStart = assertValidDate(params.segmentStart, \"segmentStart\")\n const segmentEnd = assertValidDate(params.segmentEnd, \"segmentEnd\")\n const periodStart = assertValidDate(params.periodStart, \"periodStart\")\n const periodEnd = assertValidDate(params.periodEnd, \"periodEnd\")\n const periodDuration = periodEnd.getTime() - periodStart.getTime()\n if (periodDuration <= 0) throw new Error(\"Billing period end must be after its start\")\n\n const overlapStart = Math.max(segmentStart.getTime(), periodStart.getTime())\n const overlapEnd = Math.min(segmentEnd.getTime(), periodEnd.getTime())\n const overlapDuration = Math.max(0, overlapEnd - overlapStart)\n\n return Math.round(params.unitAmount * overlapDuration / periodDuration)\n}\n","import { resolveBillingPeriod } from \"./calendar\"\nimport type {\n ScheduledPlanChange,\n SubscriptionCreatedEvent,\n SubscriptionEvent,\n SubscriptionProjection,\n SubscriptionStatus,\n} from \"./types\"\n\n\nconst assertValidDate = (value: Date, field: string): Date => {\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) throw new Error(`${field} must be a valid date`)\n return date\n}\n\nconst compareEvents = (left: SubscriptionEvent, right: SubscriptionEvent): number => {\n const effectiveDelta = left.effectiveAt.getTime() - right.effectiveAt.getTime()\n if (effectiveDelta !== 0) return effectiveDelta\n\n const occurredDelta = left.occurredAt.getTime() - right.occurredAt.getTime()\n if (occurredDelta !== 0) return occurredDelta\n\n return (left.id ?? \"\").localeCompare(right.id ?? \"\")\n}\n\nexport const sortSubscriptionEvents = (events: readonly SubscriptionEvent[]): SubscriptionEvent[] =>\n events\n .map((event): SubscriptionEvent => {\n const dates = {\n occurredAt: assertValidDate(event.occurredAt, \"occurredAt\"),\n effectiveAt: assertValidDate(event.effectiveAt, \"effectiveAt\"),\n }\n if (event.type === \"created\") {\n return {\n ...event,\n ...dates,\n billingAnchor: assertValidDate(event.billingAnchor, \"billingAnchor\"),\n }\n }\n return {\n ...event,\n ...dates,\n billingAnchor: event.billingAnchor\n ? assertValidDate(event.billingAnchor, \"billingAnchor\")\n : undefined,\n }\n })\n .sort(compareEvents)\n\nconst getEffectiveEvents = (events: readonly SubscriptionEvent[]): SubscriptionEvent[] => {\n const ordered = sortSubscriptionEvents(events)\n const supersededIds = new Set(\n ordered\n .map((event) => event.supersedesEventId)\n .filter((eventId): eventId is string => Boolean(eventId)),\n )\n\n return ordered.filter((event) =>\n !(event.id && supersededIds.has(event.id)),\n )\n}\n\nconst assertSingleSubscription = (events: readonly SubscriptionEvent[]): string => {\n if (events.length === 0) throw new Error(\"At least one subscription event is required\")\n const subscriptionIds = new Set(events.map((event) => event.subscriptionId))\n if (subscriptionIds.size > 1) throw new Error(\"Events from multiple subscriptions cannot be projected together\")\n const tenantIds = new Set(events.map((event) => event.tenantId))\n if (tenantIds.size > 1) throw new Error(\"Events from multiple tenants cannot be projected together\")\n return events[0]!.subscriptionId\n}\n\nconst assertNonEmptyString = (value: unknown, field: string): void => {\n if (typeof value !== \"string\" || !value.trim()) throw new Error(`${field} is required`)\n}\n\nconst assertPositiveInteger = (value: unknown, field: string): void => {\n if (!Number.isInteger(value) || Number(value) < 1) throw new Error(`${field} must be a positive integer`)\n}\n\nfunction assertCreatedEvent(\n event: SubscriptionEvent,\n): asserts event is SubscriptionCreatedEvent {\n if (event.type !== \"created\") throw new Error(\"The first subscription event must be created\")\n assertNonEmptyString(event.tenantId, \"tenantId\")\n assertNonEmptyString(event.subscriptionId, \"subscriptionId\")\n if (!event.subscriptionType) throw new Error(\"subscriptionType is required\")\n if (!event.scope) throw new Error(\"scope is required\")\n if (event.subscriptionType === \"addon\") assertNonEmptyString(event.parentSubscriptionId, \"parentSubscriptionId\")\n if (event.scope !== \"tenant\") assertNonEmptyString(event.scopeId, \"scopeId\")\n assertNonEmptyString(event.toPlanKey, \"toPlanKey\")\n if (!event.toStatus) throw new Error(\"Created subscription events require toStatus\")\n if (!Array.isArray(event.toModules)) throw new Error(\"Created subscription events require toModules\")\n if (!event.toIntervalUnit) throw new Error(\"Created subscription events require toIntervalUnit\")\n assertPositiveInteger(event.toIntervalCount, \"toIntervalCount\")\n assertValidDate(event.billingAnchor, \"billingAnchor\")\n}\n\nconst assertTransitionEvent = (event: SubscriptionEvent): void => {\n assertNonEmptyString(event.idempotencyKey, \"idempotencyKey\")\n switch (event.type) {\n case \"created\":\n assertCreatedEvent(event)\n return\n case \"plan_changed\":\n assertNonEmptyString(event.fromPlanKey, \"fromPlanKey\")\n assertNonEmptyString(event.toPlanKey, \"toPlanKey\")\n if (!Array.isArray(event.fromModules)) throw new Error(\"Plan changes require fromModules\")\n if (!Array.isArray(event.toModules)) throw new Error(\"Plan changes require toModules\")\n if (!event.fromIntervalUnit) throw new Error(\"Plan changes require fromIntervalUnit\")\n if (!event.toIntervalUnit) throw new Error(\"Plan changes require toIntervalUnit\")\n assertPositiveInteger(event.fromIntervalCount, \"fromIntervalCount\")\n assertPositiveInteger(event.toIntervalCount, \"toIntervalCount\")\n return\n case \"status_changed\":\n if (!event.fromStatus || !event.toStatus) throw new Error(\"Status changes require fromStatus and toStatus\")\n return\n case \"resumed\":\n if (!event.fromStatus || event.toStatus !== \"active\") {\n throw new Error(\"Resumed events require fromStatus and active toStatus\")\n }\n return\n case \"canceled\":\n if (!event.fromStatus || event.toStatus !== \"canceled\") {\n throw new Error(\"Canceled events require fromStatus and canceled toStatus\")\n }\n return\n case \"renewed\":\n if (!event.fromStatus || !event.toStatus) throw new Error(\"Renewed events require fromStatus and toStatus\")\n }\n}\n\nconst assertConsistentEventEnvelope = (\n event: SubscriptionEvent,\n created: SubscriptionCreatedEvent,\n): void => {\n if (event.tenantId !== created.tenantId) throw new Error(\"Subscription event tenantId cannot change\")\n if (event.subscriptionType !== created.subscriptionType) {\n throw new Error(\"Subscription event subscriptionType cannot change\")\n }\n if ((event.parentSubscriptionId ?? null) !== (created.parentSubscriptionId ?? null)) {\n throw new Error(\"Subscription event parentSubscriptionId cannot change\")\n }\n if (event.scope !== created.scope) throw new Error(\"Subscription event scope cannot change\")\n if ((event.scopeId ?? null) !== (created.scopeId ?? null)) {\n throw new Error(\"Subscription event scopeId cannot change\")\n }\n}\n\nexport const projectSubscription = (\n events: readonly SubscriptionEvent[],\n options: { asOf?: Date } = {},\n): SubscriptionProjection | null => {\n if (events.length === 0) return null\n\n const subscriptionId = assertSingleSubscription(events)\n const ordered = getEffectiveEvents(events)\n const created = ordered[0]!\n assertCreatedEvent(created)\n ordered.forEach((event, index) => {\n if (index > 0 && event.type === \"created\") {\n throw new Error(\"A subscription event stream cannot contain multiple created events\")\n }\n assertTransitionEvent(event)\n assertConsistentEventEnvelope(event, created)\n })\n\n const asOf = assertValidDate(options.asOf ?? new Date(), \"asOf\")\n const applicable = ordered.filter((event) => event.effectiveAt.getTime() <= asOf.getTime())\n if (applicable.length === 0) return null\n\n const type = created.subscriptionType\n const parentSubscriptionId = created.parentSubscriptionId ?? null\n const scope = created.scope\n const scopeId = created.scopeId ?? null\n let planKey = created.toPlanKey\n let priceId: string | null = null\n let status: SubscriptionStatus = created.toStatus\n let intervalUnit = created.toIntervalUnit\n let intervalCount = created.toIntervalCount\n let modules = [...created.toModules]\n let billingAnchor = created.billingAnchor\n let provider: string | null = null\n let canceledAt: Date | null = null\n\n for (const event of applicable.slice(1)) {\n planKey = event.toPlanKey ?? planKey\n priceId = event.toPriceId ?? priceId\n status = event.toStatus ?? status\n intervalUnit = event.toIntervalUnit ?? intervalUnit\n intervalCount = event.toIntervalCount ?? intervalCount\n modules = event.toModules ? [...event.toModules] : modules\n billingAnchor = event.billingAnchor ?? billingAnchor\n provider = event.provider ?? provider\n\n if (event.type === \"canceled\") {\n canceledAt = new Date(event.effectiveAt)\n } else if (event.type === \"resumed\") {\n canceledAt = null\n }\n }\n\n const futureEvents = ordered.filter((event) => event.effectiveAt.getTime() > asOf.getTime())\n const scheduledCancellation = futureEvents.find((event) => event.type === \"canceled\") ?? null\n const scheduledPlanEvent = futureEvents.find((event) => event.type === \"plan_changed\") ?? null\n const scheduledPlan: ScheduledPlanChange | null = scheduledPlanEvent\n ? {\n planKey: scheduledPlanEvent.toPlanKey,\n effectiveAt: new Date(scheduledPlanEvent.effectiveAt),\n }\n : null\n\n const periodAsOf = canceledAt && canceledAt.getTime() <= asOf.getTime()\n ? new Date(canceledAt.getTime() - 1)\n : asOf\n const period = resolveBillingPeriod({\n billingAnchor,\n intervalUnit,\n intervalCount,\n asOf: periodAsOf,\n })\n\n return {\n subscriptionId,\n type,\n parentSubscriptionId,\n scope,\n scopeId,\n planKey,\n priceId,\n status,\n intervalUnit,\n intervalCount,\n modules,\n billingAnchor: new Date(billingAnchor),\n currentPeriodStart: period.start,\n currentPeriodEnd: period.end,\n cancelAtPeriodEnd: status !== \"canceled\" && Boolean(scheduledCancellation),\n cancelAt: scheduledCancellation\n ? new Date(scheduledCancellation.effectiveAt)\n : canceledAt\n ? new Date(canceledAt)\n : null,\n canceledAt: canceledAt ? new Date(canceledAt) : null,\n scheduledPlan,\n provider,\n }\n}\n\nexport const getSubscriptionTransitionDates = (\n events: readonly SubscriptionEvent[],\n params: { after: Date; before: Date },\n): Date[] => {\n assertSingleSubscription(events)\n const after = assertValidDate(params.after, \"after\")\n const before = assertValidDate(params.before, \"before\")\n\n return [...new Set(\n getEffectiveEvents(events)\n .map((event) => event.effectiveAt.getTime())\n .filter((time) => time > after.getTime() && time < before.getTime()),\n )]\n .sort((left, right) => left - right)\n .map((time) => new Date(time))\n}\n","import { getSubscriptionTransitionDates, projectSubscription } from \"./projection\"\nimport type {\n BillableSubscriptionSegment,\n SubscriptionEvent,\n SubscriptionStatus,\n} from \"./types\"\n\n\nconst DEFAULT_BILLABLE_STATUSES: readonly SubscriptionStatus[] = [\"active\"]\n\nconst assertValidWindow = (from: Date, to: Date): { from: Date; to: Date } => {\n const normalizedFrom = new Date(from)\n const normalizedTo = new Date(to)\n if (Number.isNaN(normalizedFrom.getTime()) || Number.isNaN(normalizedTo.getTime())) {\n throw new Error(\"Billing segment window must contain valid dates\")\n }\n if (normalizedTo.getTime() <= normalizedFrom.getTime()) {\n throw new Error(\"Billing segment window end must be after its start\")\n }\n return { from: normalizedFrom, to: normalizedTo }\n}\n\nexport const buildBillableSegments = (\n events: readonly SubscriptionEvent[],\n params: {\n from: Date\n to: Date\n billableStatuses?: readonly SubscriptionStatus[]\n },\n): BillableSubscriptionSegment[] => {\n if (events.length === 0) return []\n\n const window = assertValidWindow(params.from, params.to)\n const billableStatuses = new Set(params.billableStatuses ?? DEFAULT_BILLABLE_STATUSES)\n const transitionDates = getSubscriptionTransitionDates(events, {\n after: window.from,\n before: window.to,\n })\n const segments: BillableSubscriptionSegment[] = []\n let cursor = new Date(window.from)\n\n while (cursor.getTime() < window.to.getTime()) {\n const projection = projectSubscription(events, { asOf: cursor })\n const nextTransition = transitionDates.find((date) => date.getTime() > cursor.getTime()) ?? null\n const nextPeriodEnd = projection && projection.currentPeriodEnd.getTime() > cursor.getTime()\n ? projection.currentPeriodEnd\n : null\n const candidateTimes = [\n window.to.getTime(),\n nextTransition?.getTime() ?? Number.POSITIVE_INFINITY,\n nextPeriodEnd?.getTime() ?? Number.POSITIVE_INFINITY,\n ]\n const nextTime = Math.min(...candidateTimes)\n\n if (!Number.isFinite(nextTime) || nextTime <= cursor.getTime()) {\n throw new Error(\"Unable to advance while building billing segments\")\n }\n\n const next = new Date(nextTime)\n if (projection && billableStatuses.has(projection.status)) {\n segments.push({\n subscriptionId: projection.subscriptionId,\n planKey: projection.planKey,\n priceId: projection.priceId,\n status: projection.status,\n modules: [...projection.modules],\n start: new Date(cursor),\n end: next,\n periodStart: new Date(projection.currentPeriodStart),\n periodEnd: new Date(projection.currentPeriodEnd),\n })\n }\n\n cursor = next\n }\n\n return segments\n}\n","import { projectSubscription } from \"./projection\"\nimport type {\n PersistedSubscriptionEvent,\n StoredSubscriptionProjection,\n SubscriptionEvent,\n SubscriptionProjection,\n} from \"./types\"\n\n\nexport type BillingStorageTransaction = unknown\n\nexport type BillingStorage = {\n runInTransaction?: <T>(operation: (transaction: BillingStorageTransaction) => Promise<T>) => Promise<T>\n createEvent: (\n event: SubscriptionEvent,\n transaction?: BillingStorageTransaction,\n ) => Promise<PersistedSubscriptionEvent>\n listEvents: (\n tenantId: string,\n subscriptionId: string,\n transaction?: BillingStorageTransaction,\n ) => Promise<PersistedSubscriptionEvent[]>\n upsertProjection: (\n projection: StoredSubscriptionProjection,\n transaction?: BillingStorageTransaction,\n ) => Promise<void>\n}\n\nconst runWithOptionalTransaction = async <T>(\n storage: BillingStorage,\n operation: (transaction?: BillingStorageTransaction) => Promise<T>,\n): Promise<T> => {\n if (!storage.runInTransaction) return operation()\n return storage.runInTransaction((transaction) => operation(transaction))\n}\n\nconst buildStoredProjection = (params: {\n tenantId: string\n projection: SubscriptionProjection\n latestEvent: PersistedSubscriptionEvent\n projectedAt: Date\n}): StoredSubscriptionProjection => {\n return {\n ...params.projection,\n tenantId: params.tenantId,\n latestEventId: params.latestEvent.id,\n latestEventAt: new Date(params.latestEvent.occurredAt),\n projectedAt: new Date(params.projectedAt),\n }\n}\n\nconst projectAndStore = async (params: {\n storage: BillingStorage\n tenantId: string\n subscriptionId: string\n asOf: Date\n transaction?: BillingStorageTransaction\n}): Promise<StoredSubscriptionProjection | null> => {\n const events = await params.storage.listEvents(\n params.tenantId,\n params.subscriptionId,\n params.transaction,\n )\n const projection = projectSubscription(events, { asOf: params.asOf })\n if (!projection) return null\n\n const latestEvent = [...events].sort((left, right) => {\n const occurredDelta = right.occurredAt.getTime() - left.occurredAt.getTime()\n if (occurredDelta !== 0) return occurredDelta\n return right.id.localeCompare(left.id)\n })[0]!\n\n const storedProjection = buildStoredProjection({\n tenantId: params.tenantId,\n projection,\n latestEvent,\n projectedAt: params.asOf,\n })\n await params.storage.upsertProjection(storedProjection, params.transaction)\n return storedProjection\n}\n\nexport const appendSubscriptionEvent = async (params: {\n storage: BillingStorage\n tenantId: string\n event: SubscriptionEvent\n asOf?: Date\n}): Promise<{\n event: PersistedSubscriptionEvent\n projection: StoredSubscriptionProjection | null\n}> => {\n if (params.event.tenantId !== params.tenantId) {\n throw new Error(\"Billing event tenantId does not match the requested tenant\")\n }\n\n return runWithOptionalTransaction(params.storage, async (transaction) => {\n const event = await params.storage.createEvent(params.event, transaction)\n const projection = await projectAndStore({\n storage: params.storage,\n tenantId: params.tenantId,\n subscriptionId: event.subscriptionId,\n asOf: params.asOf ?? new Date(),\n transaction,\n })\n\n return { event, projection }\n })\n}\n\nexport const rebuildSubscriptionProjection = async (params: {\n storage: BillingStorage\n tenantId: string\n subscriptionId: string\n asOf?: Date\n}): Promise<StoredSubscriptionProjection | null> => runWithOptionalTransaction(\n params.storage,\n (transaction) => projectAndStore({\n storage: params.storage,\n tenantId: params.tenantId,\n subscriptionId: params.subscriptionId,\n asOf: params.asOf ?? new Date(),\n transaction,\n }),\n)\n","export const SUBSCRIPTION_STATUSES = [\n \"trialing\",\n \"active\",\n \"past_due\",\n \"paused\",\n \"canceled\",\n \"expired\",\n] as const\n\nexport type SubscriptionStatus = typeof SUBSCRIPTION_STATUSES[number]\n\nexport const SUBSCRIPTION_INTERVAL_UNITS = [\"month\", \"year\"] as const\n\nexport type SubscriptionIntervalUnit = typeof SUBSCRIPTION_INTERVAL_UNITS[number]\n\nexport const SUBSCRIPTION_TYPES = [\"primary\", \"addon\"] as const\n\nexport type SubscriptionType = typeof SUBSCRIPTION_TYPES[number]\n\nexport const SUBSCRIPTION_SCOPES = [\"tenant\", \"workspace\", \"shop\", \"custom\"] as const\n\nexport type SubscriptionScope = typeof SUBSCRIPTION_SCOPES[number]\n\nexport const SUBSCRIPTION_EVENT_TYPES = [\n \"created\",\n \"plan_changed\",\n \"status_changed\",\n \"resumed\",\n \"canceled\",\n \"renewed\",\n] as const\n\nexport type SubscriptionEventType = typeof SUBSCRIPTION_EVENT_TYPES[number]\n\nexport const SUBSCRIPTION_CHANGE_DIRECTIONS = [\n \"upgrade\",\n \"downgrade\",\n \"lateral\",\n] as const\n\nexport type SubscriptionChangeDirection = typeof SUBSCRIPTION_CHANGE_DIRECTIONS[number]\n\nexport type SubscriptionEventBase = {\n id?: string\n tenantId: string\n subscriptionId: string\n occurredAt: Date\n effectiveAt: Date\n subscriptionType: SubscriptionType\n parentSubscriptionId?: string\n scope: SubscriptionScope\n scopeId?: string\n fromPlanKey?: string\n toPlanKey?: string\n fromStatus?: SubscriptionStatus\n toStatus?: SubscriptionStatus\n fromModules?: string[]\n toModules?: string[]\n fromIntervalUnit?: SubscriptionIntervalUnit\n toIntervalUnit?: SubscriptionIntervalUnit\n fromIntervalCount?: number\n toIntervalCount?: number\n fromPriceId?: string\n toPriceId?: string\n billingAnchor?: Date\n supersedesEventId?: string\n idempotencyKey: string\n direction?: SubscriptionChangeDirection\n actorUserId?: string\n source?: \"admin\" | \"system\" | \"webhook\" | \"user\"\n reason?: string\n provider?: string\n providerEventId?: string\n providerPayload?: unknown\n metadata?: Record<string, unknown>\n}\n\nexport type SubscriptionCreatedEvent = SubscriptionEventBase & {\n type: \"created\"\n toPlanKey: string\n toStatus: SubscriptionStatus\n toModules: string[]\n toIntervalUnit: SubscriptionIntervalUnit\n toIntervalCount: number\n billingAnchor: Date\n}\n\nexport type SubscriptionPlanChangedEvent = SubscriptionEventBase & {\n type: \"plan_changed\"\n fromPlanKey: string\n toPlanKey: string\n fromModules: string[]\n toModules: string[]\n fromIntervalUnit: SubscriptionIntervalUnit\n toIntervalUnit: SubscriptionIntervalUnit\n fromIntervalCount: number\n toIntervalCount: number\n}\n\nexport type SubscriptionStatusChangedEvent = SubscriptionEventBase & {\n type: \"status_changed\"\n fromStatus: SubscriptionStatus\n toStatus: SubscriptionStatus\n}\n\nexport type SubscriptionResumedEvent = SubscriptionEventBase & {\n type: \"resumed\"\n fromStatus: SubscriptionStatus\n toStatus: \"active\"\n}\n\nexport type SubscriptionCanceledEvent = SubscriptionEventBase & {\n type: \"canceled\"\n fromStatus: SubscriptionStatus\n toStatus: \"canceled\"\n}\n\nexport type SubscriptionRenewedEvent = SubscriptionEventBase & {\n type: \"renewed\"\n fromStatus: SubscriptionStatus\n toStatus: SubscriptionStatus\n}\n\nexport type SubscriptionEvent =\n | SubscriptionCreatedEvent\n | SubscriptionPlanChangedEvent\n | SubscriptionStatusChangedEvent\n | SubscriptionResumedEvent\n | SubscriptionCanceledEvent\n | SubscriptionRenewedEvent\n\nexport type PersistedSubscriptionEvent = SubscriptionEvent & {\n id: string\n}\n\nexport type ScheduledPlanChange = {\n planKey: string\n effectiveAt: Date\n}\n\nexport type SubscriptionProjection = {\n subscriptionId: string\n type: SubscriptionType\n parentSubscriptionId: string | null\n scope: SubscriptionScope\n scopeId: string | null\n planKey: string\n priceId: string | null\n status: SubscriptionStatus\n intervalUnit: SubscriptionIntervalUnit\n intervalCount: number\n modules: string[]\n billingAnchor: Date\n currentPeriodStart: Date\n currentPeriodEnd: Date\n cancelAtPeriodEnd: boolean\n cancelAt: Date | null\n canceledAt: Date | null\n scheduledPlan: ScheduledPlanChange | null\n provider: string | null\n}\n\nexport type BillableSubscriptionSegment = {\n subscriptionId: string\n planKey: string\n priceId: string | null\n status: SubscriptionStatus\n modules: string[]\n start: Date\n end: Date\n periodStart: Date\n periodEnd: Date\n}\n\nexport type StoredSubscriptionProjection = SubscriptionProjection & {\n tenantId: string\n latestEventId: string\n latestEventAt: Date\n projectedAt: Date\n}\n"],"mappings":";AAGA,IAAMC,qBAAmBC,OAAaE,UAAwB;CAC5D,MAAMC,OAAO,IAAIF,KAAKD,KAAK;CAC3B,IAAII,OAAOC,MAAMF,KAAKG,QAAQ,CAAC,GAAG,MAAM,IAAIC,MAAM,GAAGL,MAAK,sBAAuB;CACjF,OAAOC;AACT;AAEA,IAAMK,0BAA0BR,UAA0B;CACxD,IAAI,CAACI,OAAOK,UAAUT,KAAK,KAAKA,QAAQ,GAAG,MAAM,IAAIO,MAAM,0CAA0C;CACrG,OAAOP;AACT;AAEA,IAAMU,qBAAqBC,MAAcC,UACvC,IAAIX,KAAKA,KAAKY,IAAIF,MAAM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AAgBM,OAAON;CACvBe,MAAMT,OAAOS,wBAAQ,IAAIN,KAAK;CAC9BhB;AACF,CAAC,CACH;;;AC3HA,IAAakC,wBAAwB;CACnC;CACA;CACA;CACA;CACA;CACA;AAAS;AAKX,IAAaG,8BAA8B,CAAC,SAAS,MAAM;AAI3D,IAAaE,qBAAqB,CAAC,WAAW,OAAO;AAIrD,IAAaE,sBAAsB;CAAC;CAAU;CAAa;CAAQ;AAAQ;AAI3E,IAAaE,2BAA2B;CACtC;CACA;CACA;CACA;CACA;CACA;AAAS;AAKX,IAAaE,iCAAiC;CAC5C;CACA;CACA;AAAS"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/calendar.ts","../src/proration.ts","../src/projection.ts","../src/segments.ts","../src/storage.ts","../src/types.ts"],"sourcesContent":["import type { SubscriptionIntervalUnit } from \"./types\"\n\n\nconst assertValidDate = (value: Date, field: string): Date => {\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) throw new Error(`${field} must be a valid date`)\n return date\n}\n\nconst normalizeIntervalCount = (value: number): number => {\n if (!Number.isInteger(value) || value < 1) throw new Error(\"intervalCount must be a positive integer\")\n return value\n}\n\nconst getDaysInUtcMonth = (year: number, month: number): number =>\n new Date(Date.UTC(year, month + 1, 0)).getUTCDate()\n\nconst createClampedUtcDate = (source: Date, year: number, month: number): Date => {\n const day = Math.min(source.getUTCDate(), getDaysInUtcMonth(year, month))\n return new Date(Date.UTC(\n year,\n month,\n day,\n source.getUTCHours(),\n source.getUTCMinutes(),\n source.getUTCSeconds(),\n source.getUTCMilliseconds(),\n ))\n}\n\nexport const addBillingInterval = (\n value: Date,\n intervalUnit: SubscriptionIntervalUnit,\n intervalCount = 1,\n): Date => {\n const date = assertValidDate(value, \"value\")\n const count = normalizeIntervalCount(intervalCount)\n\n if (intervalUnit === \"year\") {\n return createClampedUtcDate(date, date.getUTCFullYear() + count, date.getUTCMonth())\n }\n\n const absoluteMonth = date.getUTCFullYear() * 12 + date.getUTCMonth() + count\n const year = Math.floor(absoluteMonth / 12)\n const month = ((absoluteMonth % 12) + 12) % 12\n return createClampedUtcDate(date, year, month)\n}\n\nconst getEstimatedPeriodIndex = (\n anchor: Date,\n asOf: Date,\n intervalUnit: SubscriptionIntervalUnit,\n intervalCount: number,\n): number => {\n if (asOf.getTime() <= anchor.getTime()) return 0\n\n const rawDifference = intervalUnit === \"year\"\n ? asOf.getUTCFullYear() - anchor.getUTCFullYear()\n : (asOf.getUTCFullYear() - anchor.getUTCFullYear()) * 12 + asOf.getUTCMonth() - anchor.getUTCMonth()\n\n return Math.max(0, Math.floor(rawDifference / intervalCount))\n}\n\nexport const resolveBillingPeriod = (params: {\n billingAnchor: Date\n intervalUnit: SubscriptionIntervalUnit\n intervalCount?: number\n asOf: Date\n}): { start: Date; end: Date } => {\n const anchor = assertValidDate(params.billingAnchor, \"billingAnchor\")\n const asOf = assertValidDate(params.asOf, \"asOf\")\n const intervalCount = normalizeIntervalCount(params.intervalCount ?? 1)\n\n let periodIndex = getEstimatedPeriodIndex(anchor, asOf, params.intervalUnit, intervalCount)\n let start = addBillingInterval(anchor, params.intervalUnit, Math.max(1, periodIndex * intervalCount))\n\n if (periodIndex === 0) start = new Date(anchor)\n\n while (start.getTime() > asOf.getTime() && periodIndex > 0) {\n periodIndex -= 1\n start = periodIndex === 0\n ? new Date(anchor)\n : addBillingInterval(anchor, params.intervalUnit, periodIndex * intervalCount)\n }\n\n let end = addBillingInterval(anchor, params.intervalUnit, (periodIndex + 1) * intervalCount)\n while (end.getTime() <= asOf.getTime()) {\n periodIndex += 1\n start = new Date(end)\n end = addBillingInterval(anchor, params.intervalUnit, (periodIndex + 1) * intervalCount)\n }\n\n return { start, end }\n}\n","const assertValidDate = (value: Date, field: string): Date => {\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) throw new Error(`${field} must be a valid date`)\n return date\n}\n\nexport const calculateProratedAmount = (params: {\n unitAmount: number\n segmentStart: Date\n segmentEnd: Date\n periodStart: Date\n periodEnd: Date\n}): number => {\n if (!Number.isSafeInteger(params.unitAmount) || params.unitAmount < 0) {\n throw new Error(\"unitAmount must be a non-negative safe integer\")\n }\n\n const segmentStart = assertValidDate(params.segmentStart, \"segmentStart\")\n const segmentEnd = assertValidDate(params.segmentEnd, \"segmentEnd\")\n const periodStart = assertValidDate(params.periodStart, \"periodStart\")\n const periodEnd = assertValidDate(params.periodEnd, \"periodEnd\")\n const periodDuration = periodEnd.getTime() - periodStart.getTime()\n if (periodDuration <= 0) throw new Error(\"Billing period end must be after its start\")\n\n const overlapStart = Math.max(segmentStart.getTime(), periodStart.getTime())\n const overlapEnd = Math.min(segmentEnd.getTime(), periodEnd.getTime())\n const overlapDuration = Math.max(0, overlapEnd - overlapStart)\n\n return Math.round(params.unitAmount * overlapDuration / periodDuration)\n}\n","import { resolveBillingPeriod } from \"./calendar\"\nimport type {\n ScheduledPlanChange,\n SubscriptionCreatedEvent,\n SubscriptionEvent,\n SubscriptionProjection,\n SubscriptionStatus,\n} from \"./types\"\n\n\nconst assertValidDate = (value: Date, field: string): Date => {\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) throw new Error(`${field} must be a valid date`)\n return date\n}\n\nconst compareEvents = (left: SubscriptionEvent, right: SubscriptionEvent): number => {\n const effectiveDelta = left.effectiveAt.getTime() - right.effectiveAt.getTime()\n if (effectiveDelta !== 0) return effectiveDelta\n\n const occurredDelta = left.occurredAt.getTime() - right.occurredAt.getTime()\n if (occurredDelta !== 0) return occurredDelta\n\n return (left.id ?? \"\").localeCompare(right.id ?? \"\")\n}\n\nexport const sortSubscriptionEvents = (events: readonly SubscriptionEvent[]): SubscriptionEvent[] =>\n events\n .map((event): SubscriptionEvent => {\n const dates = {\n occurredAt: assertValidDate(event.occurredAt, \"occurredAt\"),\n effectiveAt: assertValidDate(event.effectiveAt, \"effectiveAt\"),\n }\n if (event.type === \"created\") {\n return {\n ...event,\n ...dates,\n billingAnchor: assertValidDate(event.billingAnchor, \"billingAnchor\"),\n }\n }\n return {\n ...event,\n ...dates,\n billingAnchor: event.billingAnchor\n ? assertValidDate(event.billingAnchor, \"billingAnchor\")\n : undefined,\n }\n })\n .sort(compareEvents)\n\nconst getEffectiveEvents = (events: readonly SubscriptionEvent[]): SubscriptionEvent[] => {\n const ordered = sortSubscriptionEvents(events)\n const supersededIds = new Set(\n ordered\n .map((event) => event.supersedesEventId)\n .filter((eventId): eventId is string => Boolean(eventId)),\n )\n\n return ordered.filter((event) =>\n !(event.id && supersededIds.has(event.id)),\n )\n}\n\nconst assertSingleSubscription = (events: readonly SubscriptionEvent[]): string => {\n if (events.length === 0) throw new Error(\"At least one subscription event is required\")\n const subscriptionIds = new Set(events.map((event) => event.subscriptionId))\n if (subscriptionIds.size > 1) throw new Error(\"Events from multiple subscriptions cannot be projected together\")\n const tenantIds = new Set(events.map((event) => event.tenantId))\n if (tenantIds.size > 1) throw new Error(\"Events from multiple tenants cannot be projected together\")\n return events[0]!.subscriptionId\n}\n\nconst assertNonEmptyString = (value: unknown, field: string): void => {\n if (typeof value !== \"string\" || !value.trim()) throw new Error(`${field} is required`)\n}\n\nconst assertPositiveInteger = (value: unknown, field: string): void => {\n if (!Number.isInteger(value) || Number(value) < 1) throw new Error(`${field} must be a positive integer`)\n}\n\nfunction assertCreatedEvent(\n event: SubscriptionEvent,\n): asserts event is SubscriptionCreatedEvent {\n if (event.type !== \"created\") throw new Error(\"The first subscription event must be created\")\n assertNonEmptyString(event.tenantId, \"tenantId\")\n assertNonEmptyString(event.subscriptionId, \"subscriptionId\")\n if (!event.subscriptionType) throw new Error(\"subscriptionType is required\")\n if (!event.scope) throw new Error(\"scope is required\")\n if (event.subscriptionType === \"addon\") assertNonEmptyString(event.parentSubscriptionId, \"parentSubscriptionId\")\n if (event.scope !== \"tenant\") assertNonEmptyString(event.scopeId, \"scopeId\")\n assertNonEmptyString(event.toPlanKey, \"toPlanKey\")\n if (!event.toStatus) throw new Error(\"Created subscription events require toStatus\")\n if (!Array.isArray(event.toModules)) throw new Error(\"Created subscription events require toModules\")\n if (!event.toIntervalUnit) throw new Error(\"Created subscription events require toIntervalUnit\")\n assertPositiveInteger(event.toIntervalCount, \"toIntervalCount\")\n assertValidDate(event.billingAnchor, \"billingAnchor\")\n}\n\nconst assertTransitionEvent = (event: SubscriptionEvent): void => {\n assertNonEmptyString(event.idempotencyKey, \"idempotencyKey\")\n switch (event.type) {\n case \"created\":\n assertCreatedEvent(event)\n return\n case \"plan_changed\":\n assertNonEmptyString(event.fromPlanKey, \"fromPlanKey\")\n assertNonEmptyString(event.toPlanKey, \"toPlanKey\")\n if (!Array.isArray(event.fromModules)) throw new Error(\"Plan changes require fromModules\")\n if (!Array.isArray(event.toModules)) throw new Error(\"Plan changes require toModules\")\n if (!event.fromIntervalUnit) throw new Error(\"Plan changes require fromIntervalUnit\")\n if (!event.toIntervalUnit) throw new Error(\"Plan changes require toIntervalUnit\")\n assertPositiveInteger(event.fromIntervalCount, \"fromIntervalCount\")\n assertPositiveInteger(event.toIntervalCount, \"toIntervalCount\")\n return\n case \"status_changed\":\n if (!event.fromStatus || !event.toStatus) throw new Error(\"Status changes require fromStatus and toStatus\")\n return\n case \"resumed\":\n if (!event.fromStatus || event.toStatus !== \"active\") {\n throw new Error(\"Resumed events require fromStatus and active toStatus\")\n }\n return\n case \"canceled\":\n if (!event.fromStatus || event.toStatus !== \"canceled\") {\n throw new Error(\"Canceled events require fromStatus and canceled toStatus\")\n }\n return\n case \"renewed\":\n if (!event.fromStatus || !event.toStatus) throw new Error(\"Renewed events require fromStatus and toStatus\")\n }\n}\n\nconst assertConsistentEventEnvelope = (\n event: SubscriptionEvent,\n created: SubscriptionCreatedEvent,\n): void => {\n if (event.tenantId !== created.tenantId) throw new Error(\"Subscription event tenantId cannot change\")\n if (event.subscriptionType !== created.subscriptionType) {\n throw new Error(\"Subscription event subscriptionType cannot change\")\n }\n if ((event.parentSubscriptionId ?? null) !== (created.parentSubscriptionId ?? null)) {\n throw new Error(\"Subscription event parentSubscriptionId cannot change\")\n }\n if (event.scope !== created.scope) throw new Error(\"Subscription event scope cannot change\")\n if ((event.scopeId ?? null) !== (created.scopeId ?? null)) {\n throw new Error(\"Subscription event scopeId cannot change\")\n }\n}\n\nexport const projectSubscription = (\n events: readonly SubscriptionEvent[],\n options: { asOf?: Date } = {},\n): SubscriptionProjection | null => {\n if (events.length === 0) return null\n\n const subscriptionId = assertSingleSubscription(events)\n const ordered = getEffectiveEvents(events)\n const created = ordered[0]!\n assertCreatedEvent(created)\n ordered.forEach((event, index) => {\n if (index > 0 && event.type === \"created\") {\n throw new Error(\"A subscription event stream cannot contain multiple created events\")\n }\n assertTransitionEvent(event)\n assertConsistentEventEnvelope(event, created)\n })\n\n const asOf = assertValidDate(options.asOf ?? new Date(), \"asOf\")\n const applicable = ordered.filter((event) => event.effectiveAt.getTime() <= asOf.getTime())\n if (applicable.length === 0) return null\n\n const type = created.subscriptionType\n const parentSubscriptionId = created.parentSubscriptionId ?? null\n const scope = created.scope\n const scopeId = created.scopeId ?? null\n let planKey = created.toPlanKey\n let priceId: string | null = null\n let status: SubscriptionStatus = created.toStatus\n let intervalUnit = created.toIntervalUnit\n let intervalCount = created.toIntervalCount\n let modules = [...created.toModules]\n let billingAnchor = created.billingAnchor\n let provider: string | null = null\n let canceledAt: Date | null = null\n\n for (const event of applicable.slice(1)) {\n planKey = event.toPlanKey ?? planKey\n priceId = event.toPriceId ?? priceId\n status = event.toStatus ?? status\n intervalUnit = event.toIntervalUnit ?? intervalUnit\n intervalCount = event.toIntervalCount ?? intervalCount\n modules = event.toModules ? [...event.toModules] : modules\n billingAnchor = event.billingAnchor ?? billingAnchor\n provider = event.provider ?? provider\n\n if (event.type === \"canceled\") {\n canceledAt = new Date(event.effectiveAt)\n } else if (event.type === \"resumed\") {\n canceledAt = null\n }\n }\n\n const futureEvents = ordered.filter((event) => event.effectiveAt.getTime() > asOf.getTime())\n const scheduledCancellation = futureEvents.find((event) => event.type === \"canceled\") ?? null\n const scheduledPlanEvent = futureEvents.find((event) => event.type === \"plan_changed\") ?? null\n const scheduledPlan: ScheduledPlanChange | null = scheduledPlanEvent\n ? {\n planKey: scheduledPlanEvent.toPlanKey,\n effectiveAt: new Date(scheduledPlanEvent.effectiveAt),\n }\n : null\n\n const periodAsOf = canceledAt && canceledAt.getTime() <= asOf.getTime()\n ? new Date(canceledAt.getTime() - 1)\n : asOf\n const period = resolveBillingPeriod({\n billingAnchor,\n intervalUnit,\n intervalCount,\n asOf: periodAsOf,\n })\n\n return {\n subscriptionId,\n type,\n parentSubscriptionId,\n scope,\n scopeId,\n planKey,\n priceId,\n status,\n intervalUnit,\n intervalCount,\n modules,\n billingAnchor: new Date(billingAnchor),\n currentPeriodStart: period.start,\n currentPeriodEnd: period.end,\n cancelAtPeriodEnd: status !== \"canceled\" && Boolean(scheduledCancellation),\n cancelAt: scheduledCancellation\n ? new Date(scheduledCancellation.effectiveAt)\n : canceledAt\n ? new Date(canceledAt)\n : null,\n canceledAt: canceledAt ? new Date(canceledAt) : null,\n scheduledPlan,\n provider,\n }\n}\n\nexport const getSubscriptionTransitionDates = (\n events: readonly SubscriptionEvent[],\n params: { after: Date; before: Date },\n): Date[] => {\n assertSingleSubscription(events)\n const after = assertValidDate(params.after, \"after\")\n const before = assertValidDate(params.before, \"before\")\n\n return [...new Set(\n getEffectiveEvents(events)\n .map((event) => event.effectiveAt.getTime())\n .filter((time) => time > after.getTime() && time < before.getTime()),\n )]\n .sort((left, right) => left - right)\n .map((time) => new Date(time))\n}\n","import { getSubscriptionTransitionDates, projectSubscription } from \"./projection\"\nimport type {\n BillableSubscriptionSegment,\n SubscriptionEvent,\n SubscriptionStatus,\n} from \"./types\"\n\n\nconst DEFAULT_BILLABLE_STATUSES: readonly SubscriptionStatus[] = [\"active\"]\n\nconst assertValidWindow = (from: Date, to: Date): { from: Date; to: Date } => {\n const normalizedFrom = new Date(from)\n const normalizedTo = new Date(to)\n if (Number.isNaN(normalizedFrom.getTime()) || Number.isNaN(normalizedTo.getTime())) {\n throw new Error(\"Billing segment window must contain valid dates\")\n }\n if (normalizedTo.getTime() <= normalizedFrom.getTime()) {\n throw new Error(\"Billing segment window end must be after its start\")\n }\n return { from: normalizedFrom, to: normalizedTo }\n}\n\nexport const buildBillableSegments = (\n events: readonly SubscriptionEvent[],\n params: {\n from: Date\n to: Date\n billableStatuses?: readonly SubscriptionStatus[]\n },\n): BillableSubscriptionSegment[] => {\n if (events.length === 0) return []\n\n const window = assertValidWindow(params.from, params.to)\n const billableStatuses = new Set(params.billableStatuses ?? DEFAULT_BILLABLE_STATUSES)\n const transitionDates = getSubscriptionTransitionDates(events, {\n after: window.from,\n before: window.to,\n })\n const segments: BillableSubscriptionSegment[] = []\n let cursor = new Date(window.from)\n\n while (cursor.getTime() < window.to.getTime()) {\n const projection = projectSubscription(events, { asOf: cursor })\n const nextTransition = transitionDates.find((date) => date.getTime() > cursor.getTime()) ?? null\n const nextPeriodEnd = projection && projection.currentPeriodEnd.getTime() > cursor.getTime()\n ? projection.currentPeriodEnd\n : null\n const candidateTimes = [\n window.to.getTime(),\n nextTransition?.getTime() ?? Number.POSITIVE_INFINITY,\n nextPeriodEnd?.getTime() ?? Number.POSITIVE_INFINITY,\n ]\n const nextTime = Math.min(...candidateTimes)\n\n if (!Number.isFinite(nextTime) || nextTime <= cursor.getTime()) {\n throw new Error(\"Unable to advance while building billing segments\")\n }\n\n const next = new Date(nextTime)\n if (projection && billableStatuses.has(projection.status)) {\n segments.push({\n subscriptionId: projection.subscriptionId,\n planKey: projection.planKey,\n priceId: projection.priceId,\n status: projection.status,\n modules: [...projection.modules],\n start: new Date(cursor),\n end: next,\n periodStart: new Date(projection.currentPeriodStart),\n periodEnd: new Date(projection.currentPeriodEnd),\n })\n }\n\n cursor = next\n }\n\n return segments\n}\n","import { projectSubscription } from \"./projection\"\nimport type {\n PersistedSubscriptionEvent,\n StoredSubscriptionProjection,\n SubscriptionEvent,\n SubscriptionProjection,\n} from \"./types\"\n\n\nexport type BillingStorageTransaction = unknown\n\nexport type BillingStorage = {\n runInTransaction?: <T>(operation: (transaction: BillingStorageTransaction) => Promise<T>) => Promise<T>\n createEvent: (\n event: SubscriptionEvent,\n transaction?: BillingStorageTransaction,\n ) => Promise<PersistedSubscriptionEvent>\n listEvents: (\n tenantId: string,\n subscriptionId: string,\n transaction?: BillingStorageTransaction,\n ) => Promise<PersistedSubscriptionEvent[]>\n upsertProjection: (\n projection: StoredSubscriptionProjection,\n transaction?: BillingStorageTransaction,\n ) => Promise<void>\n}\n\nconst runWithOptionalTransaction = async <T>(\n storage: BillingStorage,\n operation: (transaction?: BillingStorageTransaction) => Promise<T>,\n): Promise<T> => {\n if (!storage.runInTransaction) return operation()\n return storage.runInTransaction((transaction) => operation(transaction))\n}\n\nconst buildStoredProjection = (params: {\n tenantId: string\n projection: SubscriptionProjection\n latestEvent: PersistedSubscriptionEvent\n projectedAt: Date\n}): StoredSubscriptionProjection => {\n return {\n ...params.projection,\n tenantId: params.tenantId,\n latestEventId: params.latestEvent.id,\n latestEventAt: new Date(params.latestEvent.occurredAt),\n projectedAt: new Date(params.projectedAt),\n }\n}\n\nconst projectAndStore = async (params: {\n storage: BillingStorage\n tenantId: string\n subscriptionId: string\n asOf: Date\n transaction?: BillingStorageTransaction\n}): Promise<StoredSubscriptionProjection | null> => {\n const events = await params.storage.listEvents(\n params.tenantId,\n params.subscriptionId,\n params.transaction,\n )\n const projection = projectSubscription(events, { asOf: params.asOf })\n if (!projection) return null\n\n const latestEvent = [...events].sort((left, right) => {\n const occurredDelta = right.occurredAt.getTime() - left.occurredAt.getTime()\n if (occurredDelta !== 0) return occurredDelta\n return right.id.localeCompare(left.id)\n })[0]!\n\n const storedProjection = buildStoredProjection({\n tenantId: params.tenantId,\n projection,\n latestEvent,\n projectedAt: params.asOf,\n })\n await params.storage.upsertProjection(storedProjection, params.transaction)\n return storedProjection\n}\n\nexport const appendSubscriptionEvent = async (params: {\n storage: BillingStorage\n tenantId: string\n event: SubscriptionEvent\n asOf?: Date\n}): Promise<{\n event: PersistedSubscriptionEvent\n projection: StoredSubscriptionProjection | null\n}> => {\n if (params.event.tenantId !== params.tenantId) {\n throw new Error(\"Billing event tenantId does not match the requested tenant\")\n }\n\n return runWithOptionalTransaction(params.storage, async (transaction) => {\n const event = await params.storage.createEvent(params.event, transaction)\n const projection = await projectAndStore({\n storage: params.storage,\n tenantId: params.tenantId,\n subscriptionId: event.subscriptionId,\n asOf: params.asOf ?? new Date(),\n transaction,\n })\n\n return { event, projection }\n })\n}\n\nexport const rebuildSubscriptionProjection = async (params: {\n storage: BillingStorage\n tenantId: string\n subscriptionId: string\n asOf?: Date\n}): Promise<StoredSubscriptionProjection | null> => runWithOptionalTransaction(\n params.storage,\n (transaction) => projectAndStore({\n storage: params.storage,\n tenantId: params.tenantId,\n subscriptionId: params.subscriptionId,\n asOf: params.asOf ?? new Date(),\n transaction,\n }),\n)\n","export const SUBSCRIPTION_STATUSES = [\n \"trialing\",\n \"active\",\n \"past_due\",\n \"paused\",\n \"canceled\",\n \"expired\",\n] as const\n\nexport type SubscriptionStatus = typeof SUBSCRIPTION_STATUSES[number]\n\nexport const SUBSCRIPTION_INTERVAL_UNITS = [\"month\", \"year\"] as const\n\nexport type SubscriptionIntervalUnit = typeof SUBSCRIPTION_INTERVAL_UNITS[number]\n\nexport const SUBSCRIPTION_TYPES = [\"primary\", \"addon\"] as const\n\nexport type SubscriptionType = typeof SUBSCRIPTION_TYPES[number]\n\nexport const SUBSCRIPTION_SCOPES = [\"tenant\", \"workspace\", \"shop\", \"custom\"] as const\n\nexport type SubscriptionScope = typeof SUBSCRIPTION_SCOPES[number]\n\nexport const SUBSCRIPTION_EVENT_TYPES = [\n \"created\",\n \"plan_changed\",\n \"status_changed\",\n \"resumed\",\n \"canceled\",\n \"renewed\",\n] as const\n\nexport type SubscriptionEventType = typeof SUBSCRIPTION_EVENT_TYPES[number]\n\nexport const SUBSCRIPTION_CHANGE_DIRECTIONS = [\n \"upgrade\",\n \"downgrade\",\n \"lateral\",\n] as const\n\nexport type SubscriptionChangeDirection = typeof SUBSCRIPTION_CHANGE_DIRECTIONS[number]\n\nexport type SubscriptionEventBase = {\n id?: string\n tenantId: string\n subscriptionId: string\n occurredAt: Date\n effectiveAt: Date\n subscriptionType: SubscriptionType\n parentSubscriptionId?: string\n scope: SubscriptionScope\n scopeId?: string\n fromPlanKey?: string\n toPlanKey?: string\n fromStatus?: SubscriptionStatus\n toStatus?: SubscriptionStatus\n fromModules?: string[]\n toModules?: string[]\n fromIntervalUnit?: SubscriptionIntervalUnit\n toIntervalUnit?: SubscriptionIntervalUnit\n fromIntervalCount?: number\n toIntervalCount?: number\n fromPriceId?: string\n toPriceId?: string\n billingAnchor?: Date\n supersedesEventId?: string\n idempotencyKey: string\n direction?: SubscriptionChangeDirection\n actorUserId?: string\n source?: \"admin\" | \"system\" | \"webhook\" | \"user\"\n reason?: string\n provider?: string\n providerEventId?: string\n providerPayload?: unknown\n metadata?: Record<string, unknown>\n}\n\nexport type SubscriptionCreatedEvent = SubscriptionEventBase & {\n type: \"created\"\n toPlanKey: string\n toStatus: SubscriptionStatus\n toModules: string[]\n toIntervalUnit: SubscriptionIntervalUnit\n toIntervalCount: number\n billingAnchor: Date\n}\n\nexport type SubscriptionPlanChangedEvent = SubscriptionEventBase & {\n type: \"plan_changed\"\n fromPlanKey: string\n toPlanKey: string\n fromModules: string[]\n toModules: string[]\n fromIntervalUnit: SubscriptionIntervalUnit\n toIntervalUnit: SubscriptionIntervalUnit\n fromIntervalCount: number\n toIntervalCount: number\n}\n\nexport type SubscriptionStatusChangedEvent = SubscriptionEventBase & {\n type: \"status_changed\"\n fromStatus: SubscriptionStatus\n toStatus: SubscriptionStatus\n}\n\nexport type SubscriptionResumedEvent = SubscriptionEventBase & {\n type: \"resumed\"\n fromStatus: SubscriptionStatus\n toStatus: \"active\"\n}\n\nexport type SubscriptionCanceledEvent = SubscriptionEventBase & {\n type: \"canceled\"\n fromStatus: SubscriptionStatus\n toStatus: \"canceled\"\n}\n\nexport type SubscriptionRenewedEvent = SubscriptionEventBase & {\n type: \"renewed\"\n fromStatus: SubscriptionStatus\n toStatus: SubscriptionStatus\n}\n\nexport type SubscriptionEvent =\n | SubscriptionCreatedEvent\n | SubscriptionPlanChangedEvent\n | SubscriptionStatusChangedEvent\n | SubscriptionResumedEvent\n | SubscriptionCanceledEvent\n | SubscriptionRenewedEvent\n\nexport type PersistedSubscriptionEvent = SubscriptionEvent & {\n id: string\n}\n\nexport type ScheduledPlanChange = {\n planKey: string\n effectiveAt: Date\n}\n\nexport type SubscriptionProjection = {\n subscriptionId: string\n type: SubscriptionType\n parentSubscriptionId: string | null\n scope: SubscriptionScope\n scopeId: string | null\n planKey: string\n priceId: string | null\n status: SubscriptionStatus\n intervalUnit: SubscriptionIntervalUnit\n intervalCount: number\n modules: string[]\n billingAnchor: Date\n currentPeriodStart: Date\n currentPeriodEnd: Date\n cancelAtPeriodEnd: boolean\n cancelAt: Date | null\n canceledAt: Date | null\n scheduledPlan: ScheduledPlanChange | null\n provider: string | null\n}\n\nexport type BillableSubscriptionSegment = {\n subscriptionId: string\n planKey: string\n priceId: string | null\n status: SubscriptionStatus\n modules: string[]\n start: Date\n end: Date\n periodStart: Date\n periodEnd: Date\n}\n\nexport type StoredSubscriptionProjection = SubscriptionProjection & {\n tenantId: string\n latestEventId: string\n latestEventAt: Date\n projectedAt: Date\n}\n"],"mappings":";AAGA,IAAM,qBAAmB,OAAa,UAAwB;CAC5D,MAAM,OAAO,IAAI,KAAK,KAAK;CAC3B,IAAI,OAAO,MAAM,KAAK,QAAQ,CAAC,GAAG,MAAM,IAAI,MAAM,GAAG,MAAM,sBAAsB;CACjF,OAAO;AACT;AAEA,IAAM,0BAA0B,UAA0B;CACxD,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GAAG,MAAM,IAAI,MAAM,0CAA0C;CACrG,OAAO;AACT;AAEA,IAAM,qBAAqB,MAAc,UACvC,IAAI,KAAK,KAAK,IAAI,MAAM,QAAQ,GAAG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