Files
0pt/src/document-workbench/trial-credits.ts
T

41 lines
1.2 KiB
TypeScript

/**
* One-time trial credits.
*
* A new tenant can be granted a fixed, server-owned amount so the credit
* ledger (reserve → settle) works in production without a card charge. It is
* idempotent per tenant: the ledger's unique (tenant, idempotency_key) makes
* every repeat a replay, never a second grant. The amount is never read from a
* client; `OPT_TRIAL_CREDITS=0` (default) disables it entirely.
*/
export interface CreditCommandSink {
apply(command: {
tenantId: string;
idempotencyKey: string;
kind: 'grant';
reference: string;
amount: number;
}): Promise<unknown>;
}
export function readTrialCredits(env: NodeJS.ProcessEnv = process.env): number {
const parsed = Number(env.OPT_TRIAL_CREDITS ?? '0');
if (!Number.isSafeInteger(parsed) || parsed < 0 || parsed > 1_000_000) return 0;
return parsed;
}
export async function ensureTrialCredits(
ledger: CreditCommandSink,
tenantId: string,
amount: number,
): Promise<void> {
if (!Number.isSafeInteger(amount) || amount <= 0) return;
if (typeof tenantId !== 'string' || !tenantId.trim()) return;
await ledger.apply({
tenantId,
idempotencyKey: `trial:${tenantId}`,
kind: 'grant',
reference: `trial:${tenantId}`,
amount,
});
}