anhedral 0.13.0 → 0.16.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/README.md +23 -229
- package/assets/patches/audit-deps.mjs +12 -2
- package/assets/stack/ai-schema.ts.txt +5 -0
- package/assets/stack/ai.ts.txt +30 -0
- package/assets/stack/api-index.ts.txt +15 -0
- package/assets/stack/auth-features.ts.txt +4 -0
- package/assets/stack/auth-journal.json.txt +13 -0
- package/assets/stack/auth-migration.sql.txt +53 -0
- package/assets/stack/auth-routes.ts.txt +11 -0
- package/assets/stack/auth-schema.ts.txt +64 -0
- package/assets/stack/auth-snapshot.json.txt +346 -0
- package/assets/stack/auth.ts.txt +32 -0
- package/assets/stack/billing-mode.ts.txt +8 -0
- package/assets/stack/billing-schema.ts.txt +11 -0
- package/assets/stack/desktop.rs.txt +21 -0
- package/assets/stack/entitlement-guard.ts.txt +32 -0
- package/assets/stack/entitlements.ts.txt +8 -0
- package/assets/stack/events-schema.ts.txt +12 -0
- package/assets/stack/events.ts.txt +59 -0
- package/assets/stack/mobile-auth.ts.txt +25 -0
- package/assets/stack/mobile-billing.tsx.txt +63 -0
- package/assets/stack/mobile-session.tsx.txt +83 -0
- package/assets/stack/native-button.tsx.txt +108 -0
- package/assets/stack/native-global.css.txt +4 -0
- package/assets/stack/native-lib-utils.ts.txt +5 -0
- package/assets/stack/native-metro.config.js.txt +6 -0
- package/assets/stack/native-nativewind-env.d.ts.txt +1 -0
- package/assets/stack/native-tailwind.config.js.txt +73 -0
- package/assets/stack/native-text.tsx.txt +89 -0
- package/assets/stack/purchases.ts.txt +65 -0
- package/assets/stack/revenuecat.ts.txt +88 -0
- package/assets/stack/rtc-schema.ts.txt +10 -0
- package/assets/stack/rtc.ts.txt +122 -0
- package/assets/stack/security.ts.txt +31 -0
- package/assets/stack/storage.ts.txt +36 -0
- package/assets/stack/stripe.ts.txt +126 -0
- package/assets/stack/web-sign-in.tsx.txt +51 -0
- package/assets/ui/LICENSE.react-native-reusables +21 -0
- package/assets/ui/LICENSE.shadcn +21 -0
- package/assets/ui/UPSTREAM.json +39 -0
- package/assets/ui/catalog.json +891 -0
- package/assets/ui/extensions/registry.json +6 -0
- package/assets/ui/native/_controls.tsx +521 -0
- package/assets/ui/native/_core.tsx +118 -0
- package/assets/ui/native/_data.tsx +200 -0
- package/assets/ui/native/_display.tsx +453 -0
- package/assets/ui/native/_feedback.tsx +242 -0
- package/assets/ui/native/_legacy-dialog.tsx +38 -0
- package/assets/ui/native/_motion.tsx +520 -0
- package/assets/ui/native/_overlay.tsx +402 -0
- package/assets/ui/native/_selection.tsx +366 -0
- package/assets/ui/native/accordion.tsx +1 -0
- package/assets/ui/native/alert-dialog.tsx +11 -0
- package/assets/ui/native/alert.tsx +1 -0
- package/assets/ui/native/aspect-ratio.tsx +1 -0
- package/assets/ui/native/attachment.tsx +8 -0
- package/assets/ui/native/avatar.tsx +8 -0
- package/assets/ui/native/badge.tsx +1 -0
- package/assets/ui/native/breadcrumb.tsx +9 -0
- package/assets/ui/native/bubble.tsx +1 -0
- package/assets/ui/native/button-group.tsx +1 -0
- package/assets/ui/native/button.tsx +86 -0
- package/assets/ui/native/calendar.tsx +170 -0
- package/assets/ui/native/card.tsx +44 -0
- package/assets/ui/native/carousel.tsx +1 -0
- package/assets/ui/native/chart.tsx +193 -0
- package/assets/ui/native/checkbox.tsx +1 -0
- package/assets/ui/native/code-block.tsx +137 -0
- package/assets/ui/native/collapsible.tsx +1 -0
- package/assets/ui/native/combobox.tsx +1 -0
- package/assets/ui/native/command.tsx +11 -0
- package/assets/ui/native/context-menu.tsx +16 -0
- package/assets/ui/native/data-table.tsx +1 -0
- package/assets/ui/native/date-picker.tsx +43 -0
- package/assets/ui/native/dialog.tsx +15 -0
- package/assets/ui/native/direction.tsx +1 -0
- package/assets/ui/native/drawer.tsx +10 -0
- package/assets/ui/native/dropdown-menu.tsx +16 -0
- package/assets/ui/native/empty.tsx +8 -0
- package/assets/ui/native/field.tsx +13 -0
- package/assets/ui/native/hover-card.tsx +1 -0
- package/assets/ui/native/input-group.tsx +8 -0
- package/assets/ui/native/input-otp.tsx +1 -0
- package/assets/ui/native/input.tsx +28 -0
- package/assets/ui/native/item.tsx +12 -0
- package/assets/ui/native/kbd.tsx +1 -0
- package/assets/ui/native/label.tsx +4 -0
- package/assets/ui/native/layout.tsx +26 -0
- package/assets/ui/native/marker.tsx +1 -0
- package/assets/ui/native/menubar.tsx +17 -0
- package/assets/ui/native/message-scroller.tsx +6 -0
- package/assets/ui/native/message.tsx +10 -0
- package/assets/ui/native/native-select.tsx +1 -0
- package/assets/ui/native/navigation-menu.tsx +10 -0
- package/assets/ui/native/pagination.tsx +9 -0
- package/assets/ui/native/popover.tsx +1 -0
- package/assets/ui/native/progress.tsx +1 -0
- package/assets/ui/native/questionnaire.tsx +130 -0
- package/assets/ui/native/radio-group.tsx +1 -0
- package/assets/ui/native/registry.json +1103 -0
- package/assets/ui/native/resizable.tsx +1 -0
- package/assets/ui/native/scroll-area.tsx +1 -0
- package/assets/ui/native/select.tsx +11 -0
- package/assets/ui/native/separator.tsx +1 -0
- package/assets/ui/native/sheet.tsx +10 -0
- package/assets/ui/native/sidebar.tsx +22 -0
- package/assets/ui/native/skeleton.tsx +1 -0
- package/assets/ui/native/slider.tsx +1 -0
- package/assets/ui/native/spinner.tsx +1 -0
- package/assets/ui/native/switch.tsx +1 -0
- package/assets/ui/native/table.tsx +10 -0
- package/assets/ui/native/tabs.tsx +1 -0
- package/assets/ui/native/text.tsx +20 -0
- package/assets/ui/native/textarea.tsx +1 -0
- package/assets/ui/native/theme-switcher.tsx +22 -0
- package/assets/ui/native/toast.tsx +11 -0
- package/assets/ui/native/toggle-group.tsx +1 -0
- package/assets/ui/native/toggle.tsx +1 -0
- package/assets/ui/native/tooltip.tsx +1 -0
- package/assets/ui/native/trace.tsx +20 -0
- package/assets/ui/native/typography.tsx +15 -0
- package/assets/ui/theme-storage.ts +25 -0
- package/assets/ui/theme.tsx +66 -0
- package/assets/ui/web/button.tsx +59 -0
- package/assets/ui/web/input.tsx +21 -0
- package/assets/ui/web/label.tsx +19 -0
- package/dist/bin.js +7 -12
- package/dist/capabilities.d.ts +4 -33
- package/dist/capabilities.js +2 -84
- package/dist/capability-catalog.d.ts +83 -0
- package/dist/capability-catalog.js +121 -0
- package/dist/capability-command.d.ts +3 -0
- package/dist/capability-command.js +188 -0
- package/dist/capability-editor.d.ts +17 -0
- package/dist/capability-editor.js +97 -0
- package/dist/capability-recipes.d.ts +4 -0
- package/dist/capability-recipes.js +520 -0
- package/dist/capability-references.d.ts +4 -0
- package/dist/capability-references.js +7 -0
- package/dist/cli-commands.d.ts +1 -2
- package/dist/cli-commands.js +10 -104
- package/dist/cli-output.d.ts +1 -2
- package/dist/cli-output.js +6 -251
- package/dist/command-schema.js +40 -374
- package/dist/dependencies.d.ts +34 -62
- package/dist/dependencies.js +112 -199
- package/dist/index.d.ts +1 -45
- package/dist/index.js +1 -30
- package/dist/platforms/mobile.js +29 -139
- package/dist/platforms/web.d.ts +3 -0
- package/dist/platforms/web.js +251 -0
- package/dist/project-config.d.ts +2 -13
- package/dist/project-config.js +10 -83
- package/dist/registry/context.js +0 -1
- package/dist/registry/options.js +6 -40
- package/dist/registry/resolve.d.ts +3 -4
- package/dist/registry/resolve.js +18 -108
- package/dist/registry/types.d.ts +1 -7
- package/dist/registry/usage.js +3 -9
- package/dist/runtime-policy.d.ts +0 -2
- package/dist/runtime-policy.js +0 -16
- package/dist/scaffold/backend.d.ts +0 -4
- package/dist/scaffold/backend.js +1 -189
- package/dist/scaffold/bootstrap.d.ts +2 -3
- package/dist/scaffold/bootstrap.js +37 -43
- package/dist/scaffold/compose.js +2 -14
- package/dist/scaffold/database.d.ts +1 -1
- package/dist/scaffold/database.js +19 -126
- package/dist/scaffold/documentation.d.ts +0 -1
- package/dist/scaffold/documentation.js +82 -84
- package/dist/scaffold/expo-runtime.d.ts +2 -2
- package/dist/scaffold/expo-runtime.js +9 -101
- package/dist/scaffold/native-ui.d.ts +2 -0
- package/dist/scaffold/native-ui.js +74 -0
- package/dist/scaffold/stack-documentation.d.ts +0 -1
- package/dist/scaffold/stack-documentation.js +3 -49
- package/dist/scaffold/storage.d.ts +2 -0
- package/dist/scaffold/storage.js +21 -0
- package/dist/scaffold/styling.d.ts +1 -1
- package/dist/scaffold/styling.js +20 -28
- package/dist/scaffold/workspace.js +63 -199
- package/dist/stack-registry.d.ts +2 -58
- package/dist/stack-registry.js +22 -446
- package/dist/standard.js +7 -24
- package/dist/ui-catalog.d.ts +26 -0
- package/dist/ui-catalog.js +31 -0
- package/dist/ui-command.d.ts +3 -0
- package/dist/ui-command.js +219 -0
- package/dist/ui-project.d.ts +22 -0
- package/dist/ui-project.js +110 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/docs/anhedral-stack.md +4 -119
- package/docs/capabilities.md +110 -0
- package/docs/native-ui.md +102 -0
- package/docs/software-factory.md +16 -577
- package/docs/stack-standard.md +11 -307
- package/docs/ui.md +33 -0
- package/docs/verification.md +511 -0
- package/package.json +26 -27
- package/dist/access.d.ts +0 -10
- package/dist/access.js +0 -93
- package/dist/auth-schema-snapshot.d.ts +0 -346
- package/dist/auth-schema-snapshot.js +0 -347
- package/dist/auth-schema.d.ts +0 -1
- package/dist/auth-schema.js +0 -57
- package/dist/capability-contract.d.ts +0 -47
- package/dist/capability-contract.js +0 -168
- package/dist/catalog-model.d.ts +0 -24
- package/dist/catalog-model.js +0 -1
- package/dist/catalog-registration.d.ts +0 -16
- package/dist/catalog-registration.js +0 -22
- package/dist/catalog-snapshot.d.ts +0 -5
- package/dist/catalog-snapshot.js +0 -97
- package/dist/cli-delivery.d.ts +0 -3
- package/dist/cli-delivery.js +0 -172
- package/dist/cloudflare.d.ts +0 -25
- package/dist/cloudflare.js +0 -226
- package/dist/delivery-evidence.d.ts +0 -62
- package/dist/delivery-evidence.js +0 -186
- package/dist/delivery.d.ts +0 -88
- package/dist/delivery.js +0 -570
- package/dist/inspector-model.d.ts +0 -123
- package/dist/inspector-model.js +0 -1
- package/dist/integration-service-readers.d.ts +0 -13
- package/dist/integration-service-readers.js +0 -173
- package/dist/lifecycle-model.d.ts +0 -15
- package/dist/lifecycle-model.js +0 -20
- package/dist/lifecycle.d.ts +0 -11
- package/dist/lifecycle.js +0 -91
- package/dist/management.d.ts +0 -3
- package/dist/management.js +0 -47
- package/dist/mobile-delivery.d.ts +0 -77
- package/dist/mobile-delivery.js +0 -366
- package/dist/neon-service-data.d.ts +0 -8
- package/dist/neon-service-data.js +0 -117
- package/dist/platforms/desktop.d.ts +0 -2
- package/dist/platforms/desktop.js +0 -415
- package/dist/platforms/extension.d.ts +0 -2
- package/dist/platforms/extension.js +0 -328
- package/dist/project-catalog.d.ts +0 -41
- package/dist/project-catalog.js +0 -288
- package/dist/project-inspector.d.ts +0 -4
- package/dist/project-inspector.js +0 -702
- package/dist/project-lifecycle.d.ts +0 -25
- package/dist/project-lifecycle.js +0 -57
- package/dist/project-state.d.ts +0 -49
- package/dist/project-state.js +0 -563
- package/dist/provider-auth.d.ts +0 -41
- package/dist/provider-auth.js +0 -215
- package/dist/provider-readiness.d.ts +0 -30
- package/dist/provider-readiness.js +0 -104
- package/dist/providers/adapters.d.ts +0 -17
- package/dist/providers/adapters.js +0 -278
- package/dist/providers/api.d.ts +0 -29
- package/dist/providers/api.js +0 -253
- package/dist/providers/config.d.ts +0 -15
- package/dist/providers/config.js +0 -182
- package/dist/providers/definitions.d.ts +0 -318
- package/dist/providers/definitions.js +0 -127
- package/dist/providers/provision.d.ts +0 -24
- package/dist/providers/provision.js +0 -76
- package/dist/providers/receipts.d.ts +0 -20
- package/dist/providers/receipts.js +0 -66
- package/dist/providers/recovery-verification.d.ts +0 -7
- package/dist/providers/recovery-verification.js +0 -112
- package/dist/providers/recovery.d.ts +0 -30
- package/dist/providers/recovery.js +0 -34
- package/dist/providers/runtime.d.ts +0 -10
- package/dist/providers/runtime.js +0 -265
- package/dist/providers/schema.d.ts +0 -28
- package/dist/providers/schema.js +0 -49
- package/dist/providers/state.d.ts +0 -55
- package/dist/providers/state.js +0 -289
- package/dist/provision.d.ts +0 -55
- package/dist/provision.js +0 -284
- package/dist/r2-service-data.d.ts +0 -2
- package/dist/r2-service-data.js +0 -136
- package/dist/readiness.d.ts +0 -23
- package/dist/readiness.js +0 -122
- package/dist/registry/add.d.ts +0 -24
- package/dist/registry/add.js +0 -270
- package/dist/registry/bootstrap.d.ts +0 -2
- package/dist/registry/bootstrap.js +0 -14
- package/dist/registry/commands.d.ts +0 -3
- package/dist/registry/commands.js +0 -85
- package/dist/registry/presets.d.ts +0 -4
- package/dist/registry/presets.js +0 -41
- package/dist/registry/preview.d.ts +0 -11
- package/dist/registry/preview.js +0 -91
- package/dist/registry/receipt.d.ts +0 -3
- package/dist/registry/receipt.js +0 -68
- package/dist/repository.d.ts +0 -24
- package/dist/repository.js +0 -96
- package/dist/scaffold/auth.d.ts +0 -3
- package/dist/scaffold/auth.js +0 -151
- package/dist/scaffold/billing-config.d.ts +0 -1
- package/dist/scaffold/billing-config.js +0 -73
- package/dist/scaffold/billing-contracts.d.ts +0 -2
- package/dist/scaffold/billing-contracts.js +0 -48
- package/dist/scaffold/billing-providers.d.ts +0 -1
- package/dist/scaffold/billing-providers.js +0 -249
- package/dist/scaffold/billing-schema.d.ts +0 -1
- package/dist/scaffold/billing-schema.js +0 -34
- package/dist/scaffold/billing-security.d.ts +0 -1
- package/dist/scaffold/billing-security.js +0 -46
- package/dist/scaffold/billing-server.d.ts +0 -1
- package/dist/scaffold/billing-server.js +0 -139
- package/dist/scaffold/billing-store.d.ts +0 -1
- package/dist/scaffold/billing-store.js +0 -72
- package/dist/scaffold/billing.d.ts +0 -2
- package/dist/scaffold/billing.js +0 -216
- package/dist/scaffold/cloudflare-services.d.ts +0 -8
- package/dist/scaffold/cloudflare-services.js +0 -198
- package/dist/scaffold/expo-auth.d.ts +0 -3
- package/dist/scaffold/expo-auth.js +0 -192
- package/dist/scaffold/expo-billing.d.ts +0 -3
- package/dist/scaffold/expo-billing.js +0 -292
- package/dist/scaffold/integrations.d.ts +0 -4
- package/dist/scaffold/integrations.js +0 -12
- package/dist/scaffold/lint.d.ts +0 -4
- package/dist/scaffold/lint.js +0 -56
- package/dist/scaffold/neon-realtime.d.ts +0 -2
- package/dist/scaffold/neon-realtime.js +0 -97
- package/dist/scaffold/services.d.ts +0 -5
- package/dist/scaffold/services.js +0 -108
- package/dist/scaffold/stream.d.ts +0 -2
- package/dist/scaffold/stream.js +0 -114
- package/dist/scaffold/void.d.ts +0 -4
- package/dist/scaffold/void.js +0 -264
- package/dist/scaffold/web.d.ts +0 -2
- package/dist/scaffold/web.js +0 -130
- package/dist/service-deletion.d.ts +0 -29
- package/dist/service-deletion.js +0 -195
- package/dist/service-descriptor.d.ts +0 -10
- package/dist/service-descriptor.js +0 -78
- package/dist/service-model.d.ts +0 -49
- package/dist/service-model.js +0 -8
- package/dist/service-operations.d.ts +0 -29
- package/dist/service-operations.js +0 -78
- package/dist/service-readers.d.ts +0 -8
- package/dist/service-readers.js +0 -247
- package/dist/services-command.d.ts +0 -39
- package/dist/services-command.js +0 -102
- package/dist/ship.d.ts +0 -348
- package/dist/ship.js +0 -239
- package/dist/vercel-project.d.ts +0 -101
- package/dist/vercel-project.js +0 -305
- package/dist/vercel.d.ts +0 -67
- package/dist/vercel.js +0 -581
- package/dist/vinext.d.ts +0 -2
- package/dist/vinext.js +0 -86
- package/dist/void-execution.d.ts +0 -10
- package/dist/void-execution.js +0 -94
- package/dist/void-migrations.d.ts +0 -6
- package/dist/void-migrations.js +0 -110
- package/dist/void-state.d.ts +0 -16
- package/dist/void-state.js +0 -65
- package/dist/void.d.ts +0 -3
- package/dist/void.js +0 -5
|
@@ -1,139 +0,0 @@
|
|
|
1
|
-
export const BILLING_SERVER = `import { z } from 'zod';
|
|
2
|
-
import Stripe from 'stripe';
|
|
3
|
-
import { billingEntitlementsSchema } from '@workspace/contracts';
|
|
4
|
-
import { billingConfig, requireValue, type BillingEnv } from './config';
|
|
5
|
-
import { createStore, type Account, type Database, type InboxEvent } from './store';
|
|
6
|
-
import { BillingConflict, createCheckout, createPortal, revenueCatGrants, stripeClient, stripeEventCustomer, stripeGrants, verifyMode, type Grant } from './providers';
|
|
7
|
-
import { rcEventSchema, revenueCatUsers, stripeEventTypes, verifyRevenueCat, verifyRevenueCatScope } from './security';
|
|
8
|
-
|
|
9
|
-
export class BillingError extends Error {
|
|
10
|
-
constructor(public status: 400 | 401 | 403 | 409 | 503, message: string) { super(message); }
|
|
11
|
-
}
|
|
12
|
-
const freshFor = 60_000;
|
|
13
|
-
const grantsSchema = z.array(z.object({ key: z.string(), expiresAt: z.number().nullable(), source: z.enum(['stripe', 'revenuecat']) })).max(1000);
|
|
14
|
-
function future(grant: Grant): boolean { return grant.expiresAt === null || grant.expiresAt > Date.now(); }
|
|
15
|
-
function longest(grants: Grant[]): number | null {
|
|
16
|
-
if (grants.some((grant) => grant.expiresAt === null)) return null;
|
|
17
|
-
return Math.max(...grants.map((grant) => grant.expiresAt!));
|
|
18
|
-
}
|
|
19
|
-
function summary(key: string, grants: Grant[]) {
|
|
20
|
-
const matches = grants.filter((grant) => grant.key === key).filter(future);
|
|
21
|
-
return { key, active: matches.length > 0, expiresAt: matches.length ? date(longest(matches)) : null, sources: [...new Set(matches.map((grant) => grant.source))] };
|
|
22
|
-
}
|
|
23
|
-
function date(value: number | null): string | null { return value === null ? null : new Date(value).toISOString(); }
|
|
24
|
-
function fresh(account: Account): boolean {
|
|
25
|
-
const age = Date.now() - account.checkedAt;
|
|
26
|
-
return account.checkedAt > 0 && age >= 0 && age < freshFor;
|
|
27
|
-
}
|
|
28
|
-
function idempotency(value: string): string {
|
|
29
|
-
const result = z.uuid().safeParse(value);
|
|
30
|
-
if (!result.success) throw new BillingError(400, 'A UUID Idempotency-Key is required.');
|
|
31
|
-
return result.data;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export function createBilling(options: { database: Database; env: BillingEnv; stripeEnabled: boolean; revenueCatEnabled: boolean }) {
|
|
35
|
-
const { env, stripeEnabled, revenueCatEnabled } = options;
|
|
36
|
-
const config = billingConfig(env);
|
|
37
|
-
const store = createStore(options.database);
|
|
38
|
-
const stripe = stripeEnabled ? stripeClient(env) : undefined;
|
|
39
|
-
|
|
40
|
-
function report(account: Account) {
|
|
41
|
-
const grants = grantsSchema.parse(JSON.parse(account.snapshot));
|
|
42
|
-
return billingEntitlementsSchema.parse({ entitlements: config.entitlements.map((key) => summary(key, grants)), checkedAt: new Date(account.checkedAt).toISOString() });
|
|
43
|
-
}
|
|
44
|
-
async function canonical(account: Account): Promise<Grant[]> {
|
|
45
|
-
const web = stripe ? await stripeGrants(stripe, account, config) : [];
|
|
46
|
-
const native = revenueCatEnabled ? await revenueCatGrants(account.userId, env, config, stripeEnabled) : [];
|
|
47
|
-
return [...web, ...native];
|
|
48
|
-
}
|
|
49
|
-
async function withLease<T>(userId: string, action: (account: Account) => Promise<T>): Promise<T> {
|
|
50
|
-
const account = await store.acquire(userId);
|
|
51
|
-
if (!account) throw new BillingError(409, 'Billing reconciliation is already running. Retry shortly.');
|
|
52
|
-
try { return await action(account); }
|
|
53
|
-
finally { await store.release(account); }
|
|
54
|
-
}
|
|
55
|
-
async function reconcile(userId: string) {
|
|
56
|
-
return withLease(userId, async (account) => {
|
|
57
|
-
const grants = await canonical(account);
|
|
58
|
-
const checkedAt = Date.now();
|
|
59
|
-
await store.commit(account, JSON.stringify(grants), checkedAt);
|
|
60
|
-
return report({ ...account, snapshot: JSON.stringify(grants), checkedAt });
|
|
61
|
-
});
|
|
62
|
-
}
|
|
63
|
-
async function entitlements(userId: string, force = false) {
|
|
64
|
-
const account = await store.ensure(userId);
|
|
65
|
-
if (!force && fresh(account)) return report(account);
|
|
66
|
-
// No provider response means no new grant; expired projections fail closed.
|
|
67
|
-
return reconcile(userId);
|
|
68
|
-
}
|
|
69
|
-
async function identity(userId: string) {
|
|
70
|
-
await store.ensure(userId);
|
|
71
|
-
return { appUserId: userId, providers: { stripe: stripeEnabled, revenuecat: revenueCatEnabled }, plans: Object.entries(config.plans).map(([id, plan]) => ({ id, label: plan.label })) };
|
|
72
|
-
}
|
|
73
|
-
async function checkout(userId: string, plan: string, requestId: string) {
|
|
74
|
-
if (!stripe) throw new BillingError(400, 'Web checkout is unavailable.');
|
|
75
|
-
if (!Object.hasOwn(config.plans, plan)) throw new BillingError(400, 'Unknown billing plan.');
|
|
76
|
-
const key = idempotency(requestId);
|
|
77
|
-
return withLease(userId, async (account) => {
|
|
78
|
-
try { return { url: await createCheckout(stripe, account, plan, key, store, config) }; }
|
|
79
|
-
catch (error) {
|
|
80
|
-
if (error instanceof BillingConflict) throw new BillingError(409, error.message);
|
|
81
|
-
throw error;
|
|
82
|
-
}
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
async function portal(userId: string) {
|
|
86
|
-
if (!stripe) throw new BillingError(400, 'Web billing portal is unavailable.');
|
|
87
|
-
return withLease(userId, async (account) => ({ url: await createPortal(stripe, account, config) }));
|
|
88
|
-
}
|
|
89
|
-
async function assertEntitled(userId: string, key: string): Promise<void> {
|
|
90
|
-
const state = await entitlements(userId);
|
|
91
|
-
if (!state.entitlements.some((value) => value.key === key && value.active)) throw new BillingError(403, 'An active entitlement is required.');
|
|
92
|
-
}
|
|
93
|
-
async function process(event: InboxEvent): Promise<void> {
|
|
94
|
-
if (event.state === 'done') return;
|
|
95
|
-
const users = z.array(z.string()).max(50).parse(JSON.parse(event.users));
|
|
96
|
-
try {
|
|
97
|
-
for (const user of users) await reconcile(user);
|
|
98
|
-
await store.complete(event.id);
|
|
99
|
-
} catch {
|
|
100
|
-
await store.failed(event.id);
|
|
101
|
-
throw new BillingError(503, 'Billing reconciliation pending.');
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
async function stripeEvent(raw: string, headers: Headers) {
|
|
105
|
-
if (!stripe) throw new BillingError(400, 'Stripe is not selected.');
|
|
106
|
-
let event: Stripe.Event;
|
|
107
|
-
try {
|
|
108
|
-
event = await stripe.webhooks.constructEventAsync(raw, headers.get('stripe-signature') ?? '', requireValue(env.STRIPE_WEBHOOK_SECRET), 300, Stripe.createSubtleCryptoProvider());
|
|
109
|
-
} catch { throw new BillingError(401, 'Invalid Stripe webhook.'); }
|
|
110
|
-
verifyMode(event.livemode, config);
|
|
111
|
-
return event;
|
|
112
|
-
}
|
|
113
|
-
async function stripeWebhook(raw: string, headers: Headers): Promise<void> {
|
|
114
|
-
const event = await stripeEvent(raw, headers);
|
|
115
|
-
if (!stripeEventTypes.has(event.type)) return;
|
|
116
|
-
const customerId = await stripeEventCustomer(stripe!, event);
|
|
117
|
-
const owner = customerId ? await store.customerOwner(customerId) : undefined;
|
|
118
|
-
const users = owner ? [owner.userId] : [];
|
|
119
|
-
await process(await store.inbox('stripe:' + config.environment, event.id, users));
|
|
120
|
-
}
|
|
121
|
-
async function revenueCatWebhook(raw: string, headers: Headers): Promise<void> {
|
|
122
|
-
if (!revenueCatEnabled) throw new BillingError(400, 'RevenueCat is not selected.');
|
|
123
|
-
try { await verifyRevenueCat(raw, headers, env); }
|
|
124
|
-
catch { throw new BillingError(401, 'Invalid RevenueCat webhook.'); }
|
|
125
|
-
const { event } = rcEventSchema.parse(JSON.parse(raw));
|
|
126
|
-
verifyRevenueCatScope(event, config);
|
|
127
|
-
const users = await store.known(revenueCatUsers(event));
|
|
128
|
-
await process(await store.inbox('revenuecat:' + config.environment, event.id, users));
|
|
129
|
-
}
|
|
130
|
-
async function drainPending(): Promise<void> {
|
|
131
|
-
for (const event of await store.pending()) {
|
|
132
|
-
try { await process(event); }
|
|
133
|
-
catch { /* Persisted retry remains pending; never log provider bodies or secrets. */ }
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
return { identity, entitlements, checkout, portal, assertEntitled, stripeWebhook, revenueCatWebhook, drainPending, config };
|
|
137
|
-
}
|
|
138
|
-
export type Billing = ReturnType<typeof createBilling>;
|
|
139
|
-
`;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const BILLING_STORE = "import { and, eq, lt, gt, sql } from 'drizzle-orm';\nimport type { createDatabase } from '@workspace/db';\nimport { billingAccounts, billingEvents } from '@workspace/db/schema';\n\nexport type Database = ReturnType<typeof createDatabase>;\nexport type Account = typeof billingAccounts.$inferSelect;\nexport type InboxEvent = typeof billingEvents.$inferSelect;\nconst leaseDuration = 90_000;\n\nexport function createStore(db: Database) {\n async function account(userId: string): Promise<Account | undefined> {\n return (await db.select().from(billingAccounts).where(eq(billingAccounts.userId, userId)).limit(1))[0];\n }\n async function ensure(userId: string): Promise<Account> {\n await db.insert(billingAccounts).values({ userId }).onConflictDoNothing();\n const value = await account(userId);\n if (!value) throw new Error('Billing account unavailable.');\n return value;\n }\n async function acquire(userId: string): Promise<Account | undefined> {\n await ensure(userId);\n return (await db.update(billingAccounts).set({ leaseToken: crypto.randomUUID(), leaseUntil: Date.now() + leaseDuration })\n .where(and(eq(billingAccounts.userId, userId), lt(billingAccounts.leaseUntil, Date.now())))\n .returning())[0];\n }\n function owned(value: Account) {\n if (!value.leaseToken) throw new Error('Billing lease required.');\n return and(eq(billingAccounts.userId, value.userId), eq(billingAccounts.leaseToken, value.leaseToken), gt(billingAccounts.leaseUntil, Date.now()));\n }\n async function customer(value: Account, customerId: string): Promise<void> {\n const saved = await db.update(billingAccounts).set({ stripeCustomerId: customerId }).where(owned(value)).returning();\n if (!saved.length) throw new Error('Billing lease expired.');\n }\n async function commit(value: Account, snapshot: string, checkedAt: number): Promise<void> {\n const saved = await db.update(billingAccounts).set({ snapshot, checkedAt, leaseToken: null, leaseUntil: 0 }).where(owned(value)).returning();\n if (!saved.length) throw new Error('Billing lease expired.');\n }\n async function release(value: Account): Promise<void> {\n if (!value.leaseToken) return;\n await db.update(billingAccounts).set({ leaseToken: null, leaseUntil: 0 })\n .where(and(eq(billingAccounts.userId, value.userId), eq(billingAccounts.leaseToken, value.leaseToken)));\n }\n async function known(userIds: string[]): Promise<string[]> {\n const result: string[] = [];\n for (const userId of [...new Set(userIds)].slice(0, 50)) {\n if (await account(userId)) result.push(userId);\n }\n return result;\n }\n async function customerOwner(customerId: string): Promise<Account | undefined> {\n return (await db.select().from(billingAccounts).where(eq(billingAccounts.stripeCustomerId, customerId)).limit(1))[0];\n }\n async function inbox(provider: string, eventId: string, userIds: string[]): Promise<InboxEvent> {\n const id = provider + ':' + eventId;\n await db.insert(billingEvents).values({ id, provider, users: JSON.stringify(userIds), createdAt: Date.now() }).onConflictDoNothing();\n const result = (await db.select().from(billingEvents).where(eq(billingEvents.id, id)).limit(1))[0];\n if (!result) throw new Error('Billing inbox unavailable.');\n return result;\n }\n async function complete(id: string): Promise<void> {\n await db.update(billingEvents).set({ state: 'done' }).where(eq(billingEvents.id, id));\n }\n async function failed(id: string): Promise<void> {\n await db.update(billingEvents).set({ attempts: sql`${billingEvents.attempts} + 1`, nextAttemptAt: Date.now() + 60_000 }).where(eq(billingEvents.id, id));\n }\n async function pending(): Promise<InboxEvent[]> {\n return db.select().from(billingEvents).where(and(eq(billingEvents.state, 'pending'), lt(billingEvents.nextAttemptAt, Date.now()))).limit(10);\n }\n return { account, ensure, acquire, customer, commit, release, known, customerOwner, inbox, complete, failed, pending };\n}\nexport type Store = ReturnType<typeof createStore>;\n";
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
export const BILLING_STORE = `import { and, eq, lt, gt, sql } from 'drizzle-orm';
|
|
2
|
-
import type { createDatabase } from '@workspace/db';
|
|
3
|
-
import { billingAccounts, billingEvents } from '@workspace/db/schema';
|
|
4
|
-
|
|
5
|
-
export type Database = ReturnType<typeof createDatabase>;
|
|
6
|
-
export type Account = typeof billingAccounts.$inferSelect;
|
|
7
|
-
export type InboxEvent = typeof billingEvents.$inferSelect;
|
|
8
|
-
const leaseDuration = 90_000;
|
|
9
|
-
|
|
10
|
-
export function createStore(db: Database) {
|
|
11
|
-
async function account(userId: string): Promise<Account | undefined> {
|
|
12
|
-
return (await db.select().from(billingAccounts).where(eq(billingAccounts.userId, userId)).limit(1))[0];
|
|
13
|
-
}
|
|
14
|
-
async function ensure(userId: string): Promise<Account> {
|
|
15
|
-
await db.insert(billingAccounts).values({ userId }).onConflictDoNothing();
|
|
16
|
-
const value = await account(userId);
|
|
17
|
-
if (!value) throw new Error('Billing account unavailable.');
|
|
18
|
-
return value;
|
|
19
|
-
}
|
|
20
|
-
async function acquire(userId: string): Promise<Account | undefined> {
|
|
21
|
-
await ensure(userId);
|
|
22
|
-
return (await db.update(billingAccounts).set({ leaseToken: crypto.randomUUID(), leaseUntil: Date.now() + leaseDuration })
|
|
23
|
-
.where(and(eq(billingAccounts.userId, userId), lt(billingAccounts.leaseUntil, Date.now())))
|
|
24
|
-
.returning())[0];
|
|
25
|
-
}
|
|
26
|
-
function owned(value: Account) {
|
|
27
|
-
if (!value.leaseToken) throw new Error('Billing lease required.');
|
|
28
|
-
return and(eq(billingAccounts.userId, value.userId), eq(billingAccounts.leaseToken, value.leaseToken), gt(billingAccounts.leaseUntil, Date.now()));
|
|
29
|
-
}
|
|
30
|
-
async function customer(value: Account, customerId: string): Promise<void> {
|
|
31
|
-
const saved = await db.update(billingAccounts).set({ stripeCustomerId: customerId }).where(owned(value)).returning();
|
|
32
|
-
if (!saved.length) throw new Error('Billing lease expired.');
|
|
33
|
-
}
|
|
34
|
-
async function commit(value: Account, snapshot: string, checkedAt: number): Promise<void> {
|
|
35
|
-
const saved = await db.update(billingAccounts).set({ snapshot, checkedAt, leaseToken: null, leaseUntil: 0 }).where(owned(value)).returning();
|
|
36
|
-
if (!saved.length) throw new Error('Billing lease expired.');
|
|
37
|
-
}
|
|
38
|
-
async function release(value: Account): Promise<void> {
|
|
39
|
-
if (!value.leaseToken) return;
|
|
40
|
-
await db.update(billingAccounts).set({ leaseToken: null, leaseUntil: 0 })
|
|
41
|
-
.where(and(eq(billingAccounts.userId, value.userId), eq(billingAccounts.leaseToken, value.leaseToken)));
|
|
42
|
-
}
|
|
43
|
-
async function known(userIds: string[]): Promise<string[]> {
|
|
44
|
-
const result: string[] = [];
|
|
45
|
-
for (const userId of [...new Set(userIds)].slice(0, 50)) {
|
|
46
|
-
if (await account(userId)) result.push(userId);
|
|
47
|
-
}
|
|
48
|
-
return result;
|
|
49
|
-
}
|
|
50
|
-
async function customerOwner(customerId: string): Promise<Account | undefined> {
|
|
51
|
-
return (await db.select().from(billingAccounts).where(eq(billingAccounts.stripeCustomerId, customerId)).limit(1))[0];
|
|
52
|
-
}
|
|
53
|
-
async function inbox(provider: string, eventId: string, userIds: string[]): Promise<InboxEvent> {
|
|
54
|
-
const id = provider + ':' + eventId;
|
|
55
|
-
await db.insert(billingEvents).values({ id, provider, users: JSON.stringify(userIds), createdAt: Date.now() }).onConflictDoNothing();
|
|
56
|
-
const result = (await db.select().from(billingEvents).where(eq(billingEvents.id, id)).limit(1))[0];
|
|
57
|
-
if (!result) throw new Error('Billing inbox unavailable.');
|
|
58
|
-
return result;
|
|
59
|
-
}
|
|
60
|
-
async function complete(id: string): Promise<void> {
|
|
61
|
-
await db.update(billingEvents).set({ state: 'done' }).where(eq(billingEvents.id, id));
|
|
62
|
-
}
|
|
63
|
-
async function failed(id: string): Promise<void> {
|
|
64
|
-
await db.update(billingEvents).set({ attempts: sql\`\${billingEvents.attempts} + 1\`, nextAttemptAt: Date.now() + 60_000 }).where(eq(billingEvents.id, id));
|
|
65
|
-
}
|
|
66
|
-
async function pending(): Promise<InboxEvent[]> {
|
|
67
|
-
return db.select().from(billingEvents).where(and(eq(billingEvents.state, 'pending'), lt(billingEvents.nextAttemptAt, Date.now()))).limit(10);
|
|
68
|
-
}
|
|
69
|
-
return { account, ensure, acquire, customer, commit, release, known, customerOwner, inbox, complete, failed, pending };
|
|
70
|
-
}
|
|
71
|
-
export type Store = ReturnType<typeof createStore>;
|
|
72
|
-
`;
|
package/dist/scaffold/billing.js
DELETED
|
@@ -1,216 +0,0 @@
|
|
|
1
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
4
|
-
import { scaffoldBillingContracts } from './billing-contracts.js';
|
|
5
|
-
import { scaffoldExpoBilling } from './expo-billing.js';
|
|
6
|
-
import { scaffoldBillingSchema } from './billing-schema.js';
|
|
7
|
-
import { BILLING_CONFIG } from './billing-config.js';
|
|
8
|
-
import { BILLING_SECURITY } from './billing-security.js';
|
|
9
|
-
import { BILLING_STORE } from './billing-store.js';
|
|
10
|
-
import { BILLING_PROVIDERS } from './billing-providers.js';
|
|
11
|
-
import { BILLING_SERVER } from './billing-server.js';
|
|
12
|
-
import { writeEnvironmentFile } from './environment.js';
|
|
13
|
-
import { json, patchPackage, put, readJson, sharedPackage } from './files.js';
|
|
14
|
-
function applicationBilling(context) {
|
|
15
|
-
const { has } = context;
|
|
16
|
-
const database = has('neon') ? 'env.DATABASE_URL' : 'env.DB';
|
|
17
|
-
const authenticate = has('clerk')
|
|
18
|
-
? `const state = await authenticate(request, env.CLERK_SECRET_KEY, env.CLERK_PUBLISHABLE_KEY, [new URL(env.BILLING_ORIGIN).origin]);
|
|
19
|
-
const subject = state.toAuth()?.userId;
|
|
20
|
-
if (!subject) throw new BillingError(401, 'Sign in to access billing.');
|
|
21
|
-
return subject;`
|
|
22
|
-
: `const session = await createAuth(createDatabase(${database}), env.BETTER_AUTH_SECRET, env.BETTER_AUTH_URL).api.getSession({ headers: request.headers });
|
|
23
|
-
if (!session) throw new BillingError(401, 'Sign in to access billing.');
|
|
24
|
-
return session.user.id;`;
|
|
25
|
-
return `import { Hono, type Context } from 'hono';
|
|
26
|
-
import { z } from 'zod';
|
|
27
|
-
import { createDatabase } from '@workspace/db';
|
|
28
|
-
import { ${has('clerk') ? 'authenticate' : 'createAuth'} } from '@workspace/auth';
|
|
29
|
-
import { createBilling, BillingError, type Billing } from '@workspace/billing/server';
|
|
30
|
-
|
|
31
|
-
type BillingContext = Context<{ Bindings: Env }>;
|
|
32
|
-
function billing(env: Env): Billing {
|
|
33
|
-
return createBilling({ database: createDatabase(${database}), env, stripeEnabled: ${has('stripe')}, revenueCatEnabled: ${has('revenuecat')} });
|
|
34
|
-
}
|
|
35
|
-
async function subject(request: Request, env: Env): Promise<string> {
|
|
36
|
-
${authenticate}
|
|
37
|
-
}
|
|
38
|
-
function originAllowed(request: Request, env: Env): void {
|
|
39
|
-
if (!trustedOrigin(request, env)) throw new BillingError(403, 'Unexpected billing request origin.');
|
|
40
|
-
if (request.headers.get('sec-fetch-site') === 'cross-site') throw new BillingError(403, 'Cross-site billing requests are denied.');
|
|
41
|
-
if (!jsonRequest(request)) throw new BillingError(400, 'A JSON request is required.');
|
|
42
|
-
}
|
|
43
|
-
function jsonRequest(request: Request): boolean {
|
|
44
|
-
const contentType = request.headers.get('content-type') ?? '';
|
|
45
|
-
return contentType.split(';')[0].trim() === 'application/json';
|
|
46
|
-
}
|
|
47
|
-
function trustedOrigin(request: Request, env: Env): boolean {
|
|
48
|
-
const origin = request.headers.get('origin');
|
|
49
|
-
return !origin || origin === new URL(env.BILLING_ORIGIN).origin;
|
|
50
|
-
}
|
|
51
|
-
function handle(action: (context: BillingContext) => Promise<unknown>) {
|
|
52
|
-
return async (context: BillingContext) => {
|
|
53
|
-
context.header('cache-control', 'private, no-store');
|
|
54
|
-
try { return context.body(JSON.stringify(await action(context)), 200, { 'content-type': 'application/json' }); }
|
|
55
|
-
catch (error) {
|
|
56
|
-
if (error instanceof BillingError) return context.json({ error: error.message }, error.status);
|
|
57
|
-
if (error instanceof z.ZodError) return context.json({ error: 'Invalid billing request or configuration.' }, 400);
|
|
58
|
-
return context.json({ error: 'Billing is temporarily unavailable.' }, 503);
|
|
59
|
-
}
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
async function signedIn(context: BillingContext) {
|
|
63
|
-
const userId = await subject(context.req.raw, context.env);
|
|
64
|
-
return { userId, service: billing(context.env) };
|
|
65
|
-
}
|
|
66
|
-
async function mutation(context: BillingContext) {
|
|
67
|
-
originAllowed(context.req.raw, context.env);
|
|
68
|
-
return signedIn(context);
|
|
69
|
-
}
|
|
70
|
-
export const billingRoutes = new Hono<{ Bindings: Env }>();
|
|
71
|
-
billingRoutes.get('/billing/identity', handle(async (context) => {
|
|
72
|
-
const { service, userId } = await signedIn(context);
|
|
73
|
-
return service.identity(userId);
|
|
74
|
-
}));
|
|
75
|
-
billingRoutes.get('/billing/entitlements', handle(async (context) => {
|
|
76
|
-
const { service, userId } = await signedIn(context);
|
|
77
|
-
return service.entitlements(userId);
|
|
78
|
-
}));
|
|
79
|
-
billingRoutes.post('/billing/refresh', handle(async (context) => {
|
|
80
|
-
const { service, userId } = await mutation(context);
|
|
81
|
-
z.object({}).strict().parse(await context.req.json());
|
|
82
|
-
return service.entitlements(userId, true);
|
|
83
|
-
}));
|
|
84
|
-
billingRoutes.post('/billing/checkout', handle(async (context) => {
|
|
85
|
-
const { service, userId } = await mutation(context);
|
|
86
|
-
const { plan } = z.object({ plan: z.string().min(1).max(100) }).strict().parse(await context.req.json());
|
|
87
|
-
return service.checkout(userId, plan, context.req.header('idempotency-key') ?? '');
|
|
88
|
-
}));
|
|
89
|
-
billingRoutes.post('/billing/portal', handle(async (context) => {
|
|
90
|
-
const { service, userId } = await mutation(context);
|
|
91
|
-
z.object({}).strict().parse(await context.req.json());
|
|
92
|
-
return service.portal(userId);
|
|
93
|
-
}));
|
|
94
|
-
billingRoutes.get('/billing/premium', handle(async (context) => {
|
|
95
|
-
const { service, userId } = await signedIn(context);
|
|
96
|
-
await service.assertEntitled(userId, service.config.demoEntitlement);
|
|
97
|
-
return { ok: true, entitlement: service.config.demoEntitlement };
|
|
98
|
-
}));
|
|
99
|
-
billingRoutes.post('/webhooks/stripe', handle(async (context) => {
|
|
100
|
-
await billing(context.env).stripeWebhook(await context.req.text(), context.req.raw.headers);
|
|
101
|
-
return { received: true };
|
|
102
|
-
}));
|
|
103
|
-
billingRoutes.post('/webhooks/revenuecat', handle(async (context) => {
|
|
104
|
-
await billing(context.env).revenueCatWebhook(await context.req.text(), context.req.raw.headers);
|
|
105
|
-
return { received: true };
|
|
106
|
-
}));
|
|
107
|
-
export async function drainBilling(env: Env): Promise<void> {
|
|
108
|
-
try { await billing(env).drainPending(); }
|
|
109
|
-
catch { /* Missing configuration or provider outage grants nothing; inbox stays durable. */ }
|
|
110
|
-
}
|
|
111
|
-
`;
|
|
112
|
-
}
|
|
113
|
-
function connectApi(context) {
|
|
114
|
-
const { root } = context;
|
|
115
|
-
put(root, 'apps/api/src/billing.ts', applicationBilling(context));
|
|
116
|
-
put(root, 'apps/api/src/billing-env.d.ts', `import type { BillingEnv } from '@workspace/billing/config';
|
|
117
|
-
declare global { interface Env extends BillingEnv {} }
|
|
118
|
-
export {};
|
|
119
|
-
`);
|
|
120
|
-
patchPackage(root, 'apps/api/package.json', {
|
|
121
|
-
dependencies: { '@workspace/billing': 'workspace:*', zod: STACK_DEPENDENCIES.zod },
|
|
122
|
-
});
|
|
123
|
-
const file = 'apps/api/src/index.ts';
|
|
124
|
-
const source = readFileSync(path.join(root, file), 'utf8');
|
|
125
|
-
if (!source.includes('import { billingRoutes, drainBilling }'))
|
|
126
|
-
put(root, file, "import { billingRoutes, drainBilling } from './billing';\n" +
|
|
127
|
-
source.replace('export default app;', `app.route('/api', billingRoutes);
|
|
128
|
-
// Retry a bounded batch of durable webhook records independently of client activity.
|
|
129
|
-
export default {
|
|
130
|
-
fetch: app.fetch,
|
|
131
|
-
scheduled(_event: ScheduledController, env: Env, context: ExecutionContext) {
|
|
132
|
-
context.waitUntil(drainBilling(env));
|
|
133
|
-
},
|
|
134
|
-
};`));
|
|
135
|
-
const voidSelected = existsSync(path.join(root, 'apps/api/void.config.ts'));
|
|
136
|
-
const configuration = `apps/api/${voidSelected ? 'anhedral.cloudflare.json' : 'wrangler.jsonc'}`;
|
|
137
|
-
const config = readJson(root, configuration);
|
|
138
|
-
const triggers = (config.triggers ?? {});
|
|
139
|
-
config.triggers = {
|
|
140
|
-
...triggers,
|
|
141
|
-
crons: [...new Set([...(triggers.crons ?? []), '*/5 * * * *'])],
|
|
142
|
-
};
|
|
143
|
-
json(root, configuration, config);
|
|
144
|
-
if (voidSelected)
|
|
145
|
-
put(root, 'apps/api/crons/scheduled.ts', `import application from '../src/index';
|
|
146
|
-
export const cron = ['*/5 * * * *'];
|
|
147
|
-
export default application.scheduled;
|
|
148
|
-
`);
|
|
149
|
-
}
|
|
150
|
-
export function scaffoldBilling(context) {
|
|
151
|
-
const { root, has } = context;
|
|
152
|
-
if (!has('hono'))
|
|
153
|
-
throw new Error('Billing requires the shared Hono runtime.');
|
|
154
|
-
if (!has('d1') && !has('neon'))
|
|
155
|
-
throw new Error('Billing requires a selected database.');
|
|
156
|
-
scaffoldBillingContracts(root);
|
|
157
|
-
scaffoldBillingSchema(root, has('neon'));
|
|
158
|
-
sharedPackage(root, 'billing', "export { createBilling, BillingError } from './server';\n", {
|
|
159
|
-
'@workspace/contracts': 'workspace:*',
|
|
160
|
-
'@workspace/db': 'workspace:*',
|
|
161
|
-
stripe: STACK_DEPENDENCIES.stripe,
|
|
162
|
-
zod: STACK_DEPENDENCIES.zod,
|
|
163
|
-
'drizzle-orm': STACK_DEPENDENCIES['drizzle-orm'],
|
|
164
|
-
});
|
|
165
|
-
patchPackage(root, 'packages/billing/package.json', {
|
|
166
|
-
exports: {
|
|
167
|
-
'.': './src/index.ts',
|
|
168
|
-
'./server': './src/server.ts',
|
|
169
|
-
'./config': './src/config.ts',
|
|
170
|
-
},
|
|
171
|
-
});
|
|
172
|
-
for (const [name, source] of Object.entries({
|
|
173
|
-
config: BILLING_CONFIG,
|
|
174
|
-
security: BILLING_SECURITY,
|
|
175
|
-
store: BILLING_STORE,
|
|
176
|
-
providers: BILLING_PROVIDERS,
|
|
177
|
-
server: BILLING_SERVER,
|
|
178
|
-
}))
|
|
179
|
-
put(root, `packages/billing/src/${name}.ts`, source);
|
|
180
|
-
connectApi(context);
|
|
181
|
-
writeEnvironmentFile(root, 'apps/api/.dev.vars.example', {
|
|
182
|
-
BILLING_ORIGIN: '',
|
|
183
|
-
BILLING_ENVIRONMENT: 'sandbox',
|
|
184
|
-
BILLING_PLANS_JSON: '{}',
|
|
185
|
-
BILLING_ENTITLEMENTS_JSON: '["premium"]',
|
|
186
|
-
BILLING_PREMIUM_ENTITLEMENT: 'premium',
|
|
187
|
-
...(has('stripe') ? { STRIPE_SECRET_KEY: '', STRIPE_WEBHOOK_SECRET: '' } : {}),
|
|
188
|
-
...(has('revenuecat')
|
|
189
|
-
? {
|
|
190
|
-
REVENUECAT_SECRET_KEY: '',
|
|
191
|
-
REVENUECAT_WEBHOOK_AUTHORIZATION: '',
|
|
192
|
-
REVENUECAT_WEBHOOK_SIGNING_SECRET: '',
|
|
193
|
-
REVENUECAT_APP_IDS_JSON: '[]',
|
|
194
|
-
REVENUECAT_PROJECT_ID: '',
|
|
195
|
-
}
|
|
196
|
-
: {}),
|
|
197
|
-
});
|
|
198
|
-
scaffoldExpoBilling(context);
|
|
199
|
-
put(root, 'packages/billing/README.md', BILLING_README);
|
|
200
|
-
}
|
|
201
|
-
const BILLING_README = `# Shared billing
|
|
202
|
-
|
|
203
|
-
Hono owns authenticated Checkout, customer portal and entitlement decisions. Clients use the public contracts and never select a user/customer ID, raw Stripe price or return URL. Stripe web subscriptions and RevenueCat native subscriptions are independent provider projections; Hono unions their allowed entitlements. When both are enabled, RevenueCat Stripe receipts do not grant access, preventing stale Stripe mirrors from restoring a revoked web grant. Web purchases are not automatically imported into RevenueCat. Native clients query Hono for unified product access.
|
|
204
|
-
|
|
205
|
-
Generate and review SQL from packages/db/src/billing-schema.ts with pnpm db:generate, then migrate the selected development database explicitly. Builds and checks never migrate configured data. Billing accounts intentionally do not foreign-key a provider-specific user table. Use the verified auth subject as RevenueCat appUserID everywhere; identify through /api/billing/identity before purchasing. Account changes must switch RevenueCat identity and clear client entitlement state. Unknown webhook users are ignored; email never links accounts.
|
|
206
|
-
|
|
207
|
-
Set BILLING_ORIGIN to the exact product origin. HTTPS is required in production; sandbox development also permits HTTP on localhost, 127.0.0.1 or [::1] only. LAN HTTP is denied; physical devices require a reachable HTTPS origin. BILLING_PLANS_JSON maps a public plan ID to {label,stripePriceId,entitlement}; BILLING_ENTITLEMENTS_JSON lists allowed entitlement keys. Example: {"monthly":{"label":"Monthly","stripePriceId":"price_example","entitlement":"premium"}}. Return paths are /billing?result=success and /billing?result=cancelled; portal returns /billing. Configure the Stripe Customer Portal and required Stripe webhook event types from src/security.ts. POST Checkout requires a UUID Idempotency-Key; preserve the same UUID for retries of one intent. Under the account lease, an existing open checkout for the same configured plan is reused even for a distinct intent UUID. Another pending configured plan returns HTTP 409: finish that checkout before choosing another plan, or have the owner expire it in Stripe. Sessions use Stripe's default expiration; no retry-dependent expires_at parameter is sent. Nonterminal configured subscriptions, including payment failures and refunded active subscriptions, must be managed in the portal and cannot start a duplicate subscription. No access is granted by the return URL. Successful active or trial subscriptions grant until the verified item period ends; past_due is denied. Paid invoices with partial/full refunds or disputes deny web access. This conservative policy excludes out-of-band positive-value invoices without verified payment-intent charges.
|
|
208
|
-
|
|
209
|
-
Select BILLING_ENVIRONMENT explicitly for the intended sandbox/production backend. Keep Stripe test/live keys and webhook signing secrets isolated. Configure a dedicated RevenueCat project and allowed app IDs using REVENUECAT_PROJECT_ID and REVENUECAT_APP_IDS_JSON. RevenueCat webhook payloads normally omit project_id: the dedicated server API key and project-scoped webhook integration establish that boundary; a present mismatching project_id is rejected. REVENUECAT_SECRET_KEY is a server API v1 key, distinct from CLI management credentials. Require the configured Authorization header and enable HMAC signing with REVENUECAT_WEBHOOK_SIGNING_SECRET when available. Production never honors sandbox receipts, even when client keys or webhook payloads claim otherwise. Use separate RevenueCat projects for staging and production.
|
|
210
|
-
|
|
211
|
-
Webhook metadata is durably inserted before processing, with a unique provider/environment/event ID. Retries reconcile canonical provider state rather than replaying entitlement deltas. Per-account leases fence stale concurrent writes. Cached access lasts at most sixty seconds and never past a grant's expiry; an outage after that window fails closed. Failed records remain pending; the API's five-minute scheduled handler retries at most ten records per invocation. Inspect pending state/attempts operationally and repair configuration/provider access before retries. Code rollback does not reverse billing events or database migrations. Prune completed event records only under a reviewed retention policy long enough for provider replay windows.
|
|
212
|
-
|
|
213
|
-
GET /api/billing/premium demonstrates server enforcement through assertEntitled. It is a product example, not a substitute for placing guards on every actual paid operation. Review cross-account restore/transfer behavior and reconcile both source/destination accounts. Public SDK CustomerInfo is display state, never a server authorization claim. Digital consumables/credit balances, metered billing, tax registrations, refunds initiation and store publication are outside this subscription foundation.
|
|
214
|
-
|
|
215
|
-
Validate signup/session isolation, purchase/restore, renewal, failed payment, refund/dispute, cancellation versus expiry, duplicate/out-of-order webhooks, concurrent refresh, cross-user denial, environment isolation, invalid signatures and provider outage recovery. Local mocks/builds do not establish store purchases, configured provider acceptance or production billing. No services or payments are activated during generation.
|
|
216
|
-
`;
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import type { RecipeContext } from '../registry/types.js';
|
|
2
|
-
export declare function scaffoldAnalyticsEngine(context: RecipeContext): void;
|
|
3
|
-
export declare function scaffoldImages(context: RecipeContext): void;
|
|
4
|
-
export declare function scaffoldCloudflareTransport({ root }: RecipeContext): void;
|
|
5
|
-
export declare function scaffoldRealtimeKit(context: RecipeContext): void;
|
|
6
|
-
export declare function scaffoldVideo(context: RecipeContext): void;
|
|
7
|
-
/** Lazy Hono adapters wire selected helpers without exposing generic public routes. */
|
|
8
|
-
export declare function scaffoldCloudflareServiceContext({ root, has }: RecipeContext): void;
|