anhedral 0.11.2 → 0.13.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 +171 -18
- package/dist/bin.js +48 -493
- package/dist/capabilities.d.ts +3 -3
- package/dist/capability-contract.js +16 -1
- package/dist/cli-arguments.d.ts +8 -0
- package/dist/cli-arguments.js +32 -0
- package/dist/cli-commands.d.ts +3 -0
- package/dist/cli-commands.js +114 -0
- package/dist/cli-delivery.d.ts +3 -0
- package/dist/cli-delivery.js +172 -0
- package/dist/cli-output.js +231 -205
- package/dist/command-schema.js +8 -2
- package/dist/command.js +9 -11
- package/dist/delivery-evidence.d.ts +62 -0
- package/dist/delivery-evidence.js +186 -0
- package/dist/delivery.d.ts +3 -40
- package/dist/delivery.js +7 -182
- package/dist/dependencies.d.ts +7 -1
- package/dist/dependencies.js +15 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/mobile-delivery.d.ts +21 -44
- package/dist/mobile-delivery.js +127 -80
- package/dist/platforms/mobile.d.ts +1 -1
- package/dist/platforms/mobile.js +44 -3
- package/dist/project-state.js +4 -1
- package/dist/provider-auth.js +9 -3
- package/dist/providers/adapters.js +9 -3
- package/dist/providers/runtime.js +11 -0
- package/dist/readiness.js +4 -2
- package/dist/registry/add.js +40 -7
- package/dist/registry/options.js +12 -0
- package/dist/registry/presets.d.ts +4 -0
- package/dist/registry/presets.js +41 -0
- package/dist/registry/resolve.d.ts +3 -1
- package/dist/registry/resolve.js +40 -14
- package/dist/registry/types.d.ts +1 -0
- package/dist/registry/usage.js +1 -1
- package/dist/runtime-policy.js +4 -1
- package/dist/scaffold/api.js +10 -2
- package/dist/scaffold/auth.d.ts +1 -1
- package/dist/scaffold/auth.js +22 -6
- package/dist/scaffold/backend.d.ts +6 -0
- package/dist/scaffold/backend.js +224 -0
- package/dist/scaffold/billing-config.d.ts +1 -0
- package/dist/scaffold/billing-config.js +73 -0
- package/dist/scaffold/billing-contracts.d.ts +2 -0
- package/dist/scaffold/billing-contracts.js +48 -0
- package/dist/scaffold/billing-providers.d.ts +1 -0
- package/dist/scaffold/billing-providers.js +249 -0
- package/dist/scaffold/billing-schema.d.ts +1 -0
- package/dist/scaffold/billing-schema.js +34 -0
- package/dist/scaffold/billing-security.d.ts +1 -0
- package/dist/scaffold/billing-security.js +46 -0
- package/dist/scaffold/billing-server.d.ts +1 -0
- package/dist/scaffold/billing-server.js +139 -0
- package/dist/scaffold/billing-store.d.ts +1 -0
- package/dist/scaffold/billing-store.js +72 -0
- package/dist/scaffold/billing.d.ts +2 -0
- package/dist/scaffold/billing.js +216 -0
- package/dist/scaffold/cloudflare-services.d.ts +8 -0
- package/dist/scaffold/cloudflare-services.js +198 -0
- package/dist/scaffold/compose.js +2 -0
- package/dist/scaffold/database.js +19 -2
- package/dist/scaffold/documentation.js +11 -6
- package/dist/scaffold/expo-auth.d.ts +3 -0
- package/dist/scaffold/expo-auth.js +192 -0
- package/dist/scaffold/expo-billing.d.ts +3 -0
- package/dist/scaffold/expo-billing.js +292 -0
- package/dist/scaffold/expo-runtime.d.ts +3 -0
- package/dist/scaffold/expo-runtime.js +134 -0
- package/dist/scaffold/integrations.d.ts +2 -1
- package/dist/scaffold/integrations.js +7 -2
- package/dist/scaffold/stream.d.ts +2 -0
- package/dist/scaffold/stream.js +114 -0
- package/dist/scaffold/void.js +13 -5
- package/dist/scaffold/web.js +2 -0
- package/dist/scaffold/workspace.js +6 -1
- package/dist/service-readers.js +1 -1
- package/dist/services-command.js +8 -6
- package/dist/ship.d.ts +15 -15
- package/dist/ship.js +3 -1
- package/dist/stack-registry.d.ts +13 -2
- package/dist/stack-registry.js +152 -16
- package/dist/transaction-lock.d.ts +15 -0
- package/dist/transaction-lock.js +227 -0
- package/dist/transaction.js +2 -208
- package/dist/vercel-project.d.ts +101 -0
- package/dist/vercel-project.js +305 -0
- package/dist/vercel.d.ts +3 -36
- package/dist/vercel.js +3 -300
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/docs/anhedral-stack.md +122 -0
- package/docs/software-factory.md +402 -7
- package/docs/stack-standard.md +226 -49
- package/docs/verification.md +557 -0
- package/package.json +7 -7
- package/docs/cli-design.md +0 -67
- package/docs/plugin-ui.md +0 -102
- package/docs/provider-configuration.md +0 -116
- package/docs/void-verification.md +0 -185
|
@@ -0,0 +1,72 @@
|
|
|
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
|
+
`;
|
|
@@ -0,0 +1,216 @@
|
|
|
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
|
+
`;
|
|
@@ -0,0 +1,8 @@
|
|
|
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;
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
2
|
+
import { rmSync, readFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { patchPackage, put, sharedPackage } from './files.js';
|
|
5
|
+
import { writeEnvironmentFile } from './environment.js';
|
|
6
|
+
/** Server-only packages are linked to their owner, never to client manifests. */
|
|
7
|
+
function serverPackage(context, name, source, guide, secrets = []) {
|
|
8
|
+
const { root, runtimeApp } = context;
|
|
9
|
+
sharedPackage(root, name, '', {});
|
|
10
|
+
rmSync(path.join(root, `packages/${name}/src/index.ts`));
|
|
11
|
+
patchPackage(root, `packages/${name}/package.json`, {
|
|
12
|
+
exports: { './server': './src/server.ts' },
|
|
13
|
+
});
|
|
14
|
+
put(root, `packages/${name}/src/server.ts`, source);
|
|
15
|
+
put(root, `packages/${name}/README.md`, guide);
|
|
16
|
+
patchPackage(root, `apps/${runtimeApp}/package.json`, {
|
|
17
|
+
dependencies: { [`@workspace/${name}`]: 'workspace:*' },
|
|
18
|
+
});
|
|
19
|
+
if (['video', 'realtimekit'].includes(name))
|
|
20
|
+
patchPackage(root, `packages/${name}/package.json`, {
|
|
21
|
+
dependencies: { '@workspace/cloudflare-api': 'workspace:*', zod: STACK_DEPENDENCIES.zod },
|
|
22
|
+
});
|
|
23
|
+
if (secrets.length) {
|
|
24
|
+
writeEnvironmentFile(root, `apps/${runtimeApp}/.dev.vars.example`, Object.fromEntries(secrets.map((key) => [key, ''])));
|
|
25
|
+
put(root, `apps/${runtimeApp}/src/${name}-secrets.d.ts`, `interface Env { ${secrets.map((key) => `${key}: string;`).join(' ')} }\n`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export function scaffoldAnalyticsEngine(context) {
|
|
29
|
+
serverPackage(context, 'analytics-engine', `export interface AnalyticsBinding {
|
|
30
|
+
writeDataPoint(point: { indexes: string[]; blobs: string[]; doubles: number[] }): void;
|
|
31
|
+
}
|
|
32
|
+
// Use a stable, non-sensitive tenant key. Never log credentials or raw user content.
|
|
33
|
+
export function recordEvent(binding: AnalyticsBinding, tenantKey: string, event: string, value = 1): void {
|
|
34
|
+
if (!tenantKey || !event || !Number.isFinite(value)) throw new Error('Invalid analytics event.');
|
|
35
|
+
binding.writeDataPoint({ indexes: [tenantKey], blobs: [event], doubles: [value] });
|
|
36
|
+
}
|
|
37
|
+
`, `# Workers Analytics Engine
|
|
38
|
+
|
|
39
|
+
In Hono product routes, use c.get('services').analytics(tenant, event, value), or import recordEvent from @workspace/analytics-engine/server and pass env.EVENTS, an authorized non-sensitive tenant key, a server-controlled event name and a numeric value. Define consent, retention and event semantics before recording production events. The helper does not create a public ingestion route. writeDataPoint is non-blocking; analytics is not a billing ledger or transactional quota authority. Verify dataset receipt and sampled SQL query semantics with the selected account. Dataset binding is configured on deployment; account activation and analytics read credentials remain explicit.
|
|
40
|
+
|
|
41
|
+
https://developers.cloudflare.com/analytics/analytics-engine/get-started/
|
|
42
|
+
`);
|
|
43
|
+
}
|
|
44
|
+
export function scaffoldImages(context) {
|
|
45
|
+
serverPackage(context, 'images', `export interface ImagesBinding {
|
|
46
|
+
input(stream: ReadableStream<Uint8Array>): {
|
|
47
|
+
transform(options: { width: number; fit: 'scale-down' }): {
|
|
48
|
+
output(options: { format: 'image/webp' }): Promise<{ response(): Response }>;
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
// Pass bytes from an already authorized R2 object, not an arbitrary caller URL.
|
|
53
|
+
export async function resizeImage(images: ImagesBinding, body: ReadableStream<Uint8Array>, width: number): Promise<Response> {
|
|
54
|
+
if (!Number.isInteger(width) || width < 1 || width > 2048) throw new Error('Invalid image width.');
|
|
55
|
+
const result = await images.input(body).transform({ width, fit: 'scale-down' }).output({ format: 'image/webp' });
|
|
56
|
+
const response = result.response();
|
|
57
|
+
response.headers.set('cache-control', 'private, no-store');
|
|
58
|
+
return response;
|
|
59
|
+
}
|
|
60
|
+
`, `# Cloudflare Images
|
|
61
|
+
|
|
62
|
+
In Hono product routes, use c.get('services').images(body, width) after authorizing source access, or import resizeImage from @workspace/images/server with env.IMAGES and an R2 object's body. The binding transforms raw bytes; it is not an Images hosted-upload service or an R2 replacement. Public image caching requires a separate reviewed visibility/cache policy; private responses are no-store. Enforce upload size/type, allowed dimensions and usage limits in product routes. No public transform/upload endpoint is generated. Activate the selected account's Images entitlement and verify actual transforms before claiming acceptance.
|
|
63
|
+
|
|
64
|
+
https://developers.cloudflare.com/images/optimization/binding/
|
|
65
|
+
`);
|
|
66
|
+
}
|
|
67
|
+
// Both services use fixed provider origins and redact provider responses in errors.
|
|
68
|
+
export function scaffoldCloudflareTransport({ root }) {
|
|
69
|
+
sharedPackage(root, 'cloudflare-api', '', { zod: STACK_DEPENDENCIES.zod });
|
|
70
|
+
rmSync(path.join(root, 'packages/cloudflare-api/src/index.ts'));
|
|
71
|
+
patchPackage(root, 'packages/cloudflare-api/package.json', {
|
|
72
|
+
exports: { './server': './src/server.ts' },
|
|
73
|
+
});
|
|
74
|
+
put(root, 'packages/cloudflare-api/src/server.ts', `import { z } from 'zod';
|
|
75
|
+
const account = z.string().regex(/^[a-f0-9]{32}$/i);
|
|
76
|
+
const payload = z.record(z.string(), z.unknown());
|
|
77
|
+
const envelope = z.object({ success: z.literal(true), result: payload.optional(), data: payload.optional() });
|
|
78
|
+
function readResult(value: unknown): Record<string, unknown> {
|
|
79
|
+
const parsed = envelope.safeParse(value);
|
|
80
|
+
if (!parsed.success) throw new Error('Invalid Cloudflare service response.');
|
|
81
|
+
const result = parsed.data.result ?? parsed.data.data;
|
|
82
|
+
if (!result) throw new Error('Missing Cloudflare service response.');
|
|
83
|
+
return result;
|
|
84
|
+
}
|
|
85
|
+
export function cloudflareClient(accountId: string, apiToken: string, service: string) {
|
|
86
|
+
account.parse(accountId);
|
|
87
|
+
z.string().trim().min(1).parse(apiToken);
|
|
88
|
+
const base = 'https://api.cloudflare.com/client/v4/accounts/' + accountId + '/' + service;
|
|
89
|
+
return async (route: string, body: unknown): Promise<Record<string, unknown>> => {
|
|
90
|
+
const response = await fetch(base + route, { method: 'POST', redirect: 'error',
|
|
91
|
+
headers: { authorization: 'Bearer ' + apiToken, 'content-type': 'application/json' },
|
|
92
|
+
body: JSON.stringify(body), signal: AbortSignal.timeout(15000) });
|
|
93
|
+
if (!response.ok) throw new Error('Cloudflare service request failed (' + response.status + ').');
|
|
94
|
+
const value = await response.json().catch(() => { throw new Error('Invalid Cloudflare JSON response.'); });
|
|
95
|
+
return readResult(value);
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
`);
|
|
99
|
+
}
|
|
100
|
+
const cloudflareRequest = "import { cloudflareClient } from '@workspace/cloudflare-api/server';\nimport { z } from 'zod';\n";
|
|
101
|
+
export function scaffoldRealtimeKit(context) {
|
|
102
|
+
serverPackage(context, 'realtimekit', cloudflareRequest +
|
|
103
|
+
`
|
|
104
|
+
export function createRealtimeKit(options: { accountId: string; appId: string; apiToken: string }) {
|
|
105
|
+
z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/).parse(options.appId);
|
|
106
|
+
const request = cloudflareClient(options.accountId, options.apiToken, 'realtime/kit/' + options.appId);
|
|
107
|
+
return {
|
|
108
|
+
// Authorize meeting creation and persist its ID/owner. Reconcile uncertain creates before retrying.
|
|
109
|
+
async createMeeting(title: string): Promise<{ id: string }> {
|
|
110
|
+
z.string().trim().min(1).max(256).parse(title);
|
|
111
|
+
const result = await request('/meetings', { title });
|
|
112
|
+
return z.object({ id: z.string().min(1) }).parse(result);
|
|
113
|
+
},
|
|
114
|
+
// Derive subject and preset on the server after checking membership; never trust a requested role.
|
|
115
|
+
async addParticipant(meetingId: string, subject: string, preset: string): Promise<{ id: string; token: string }> {
|
|
116
|
+
z.uuid().parse(meetingId);
|
|
117
|
+
z.string().min(1).parse(subject);
|
|
118
|
+
z.string().min(1).parse(preset);
|
|
119
|
+
const result = await request('/meetings/' + meetingId + '/participants', { custom_participant_id: subject, preset_name: preset });
|
|
120
|
+
return z.object({ id: z.string().min(1), token: z.string().min(1) }).parse(result);
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
`, `# Cloudflare RealtimeKit
|
|
125
|
+
|
|
126
|
+
In Hono product routes, c.get('services').realtimekit() creates the server client lazily. Alternatively import createRealtimeKit from @workspace/realtimekit/server. Configure REALTIMEKIT_ACCOUNT_ID, REALTIMEKIT_APP_ID and server-only REALTIMEKIT_API_TOKEN (scoped Realtime permission). Activate/select the app and configure participant presets manually. After authenticating and authorizing membership, derive the participant subject/preset server-side, call addParticipant, and return only that participant's token with Cache-Control: no-store. Store meeting IDs with their tenant owner; reconcile uncertain creates before retrying. No public meeting/token endpoint is generated.
|
|
127
|
+
|
|
128
|
+
Install the platform-supported RealtimeKit client SDK and implement media UI separately. Media travels between clients and Cloudflare RealtimeKit, not through Hono or D1. Verify camera/microphone permissions, tenant isolation, token revocation/expiry, reconnect and track teardown on actual target devices. RealtimeKit conferencing is distinct from Durable Object messaging (--realtime) and Stream one-to-many video (--stream / --video). Source helpers do not activate the provider or establish working calls.
|
|
129
|
+
|
|
130
|
+
https://developers.cloudflare.com/realtime/realtimekit/quickstart/
|
|
131
|
+
`, ['REALTIMEKIT_ACCOUNT_ID', 'REALTIMEKIT_APP_ID', 'REALTIMEKIT_API_TOKEN']);
|
|
132
|
+
}
|
|
133
|
+
export function scaffoldVideo(context) {
|
|
134
|
+
serverPackage(context, 'video', cloudflareRequest +
|
|
135
|
+
`
|
|
136
|
+
export function createVideo(options: { accountId: string; apiToken: string }) {
|
|
137
|
+
const request = cloudflareClient(options.accountId, options.apiToken, 'stream');
|
|
138
|
+
return {
|
|
139
|
+
// Authorize uploads and enforce tenant quotas before reserving Stream capacity.
|
|
140
|
+
async createUpload(maxDurationSeconds: number): Promise<{ uid: string; uploadURL: string }> {
|
|
141
|
+
z.number().int().min(1).max(3600).parse(maxDurationSeconds);
|
|
142
|
+
const result = await request('/direct_upload', { maxDurationSeconds, requireSignedURLs: true,
|
|
143
|
+
expiry: new Date(Date.now() + 15 * 60 * 1000).toISOString() });
|
|
144
|
+
const value = z.object({ uid: z.string().min(1), uploadURL: z.url() }).parse(result);
|
|
145
|
+
const url = new URL(value.uploadURL);
|
|
146
|
+
z.literal('https:').parse(url.protocol);
|
|
147
|
+
z.string().endsWith('.videodelivery.net').parse(url.hostname);
|
|
148
|
+
z.literal('').parse(url.username + url.password);
|
|
149
|
+
return value;
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
`, `# Cloudflare Stream video uploads
|
|
154
|
+
|
|
155
|
+
In Hono product routes, use c.get('services').video() after authorization. Alternatively import createVideo from @workspace/video/server with STREAM_ACCOUNT_ID and STREAM_API_TOKEN (Stream Write). This is on-demand uploaded video, separate from --stream's WHIP/WHEP live input helper. Authenticate/authorize creators, enforce tenant quotas, then issue a one-time direct upload URL; persist uid and ownership and return it only to the authorized creator with no-store. Basic POST uploads are limited to 200 MB; implement TUS separately for larger/unreliable uploads. Processing completion/webhooks, video UI, retention/deletion and private playback token issuance remain product work. Upload completion is not processing readiness. Signed playback is required by this helper; implement and verify short-lived viewer tokens before exposing playback. Do not proxy video bytes through Hono or expose the management token. Stream account activation and stored/delivered video billing are explicit owner setup, not init side effects.
|
|
156
|
+
|
|
157
|
+
https://developers.cloudflare.com/stream/uploading-videos/direct-creator-uploads/
|
|
158
|
+
`, ['STREAM_ACCOUNT_ID', 'STREAM_API_TOKEN']);
|
|
159
|
+
}
|
|
160
|
+
/** Lazy Hono adapters wire selected helpers without exposing generic public routes. */
|
|
161
|
+
export function scaffoldCloudflareServiceContext({ root, has }) {
|
|
162
|
+
const selected = ['analytics-engine', 'images', 'realtimekit', 'video'].filter(has);
|
|
163
|
+
if (!selected.length)
|
|
164
|
+
return;
|
|
165
|
+
const imports = [];
|
|
166
|
+
const adapters = [];
|
|
167
|
+
if (has('analytics-engine')) {
|
|
168
|
+
imports.push("import { recordEvent } from '@workspace/analytics-engine/server';");
|
|
169
|
+
adapters.push('analytics: (tenant: string, event: string, value = 1) => recordEvent(env.EVENTS, tenant, event, value)');
|
|
170
|
+
}
|
|
171
|
+
if (has('images')) {
|
|
172
|
+
imports.push("import { resizeImage } from '@workspace/images/server';");
|
|
173
|
+
adapters.push('images: (body: ReadableStream<Uint8Array>, width: number) => resizeImage(env.IMAGES, body, width)');
|
|
174
|
+
}
|
|
175
|
+
if (has('realtimekit')) {
|
|
176
|
+
imports.push("import { createRealtimeKit } from '@workspace/realtimekit/server';");
|
|
177
|
+
adapters.push('realtimekit: () => createRealtimeKit({ accountId: env.REALTIMEKIT_ACCOUNT_ID, appId: env.REALTIMEKIT_APP_ID, apiToken: env.REALTIMEKIT_API_TOKEN })');
|
|
178
|
+
}
|
|
179
|
+
if (has('video')) {
|
|
180
|
+
imports.push("import { createVideo } from '@workspace/video/server';");
|
|
181
|
+
adapters.push('video: () => createVideo({ accountId: env.STREAM_ACCOUNT_ID, apiToken: env.STREAM_API_TOKEN })');
|
|
182
|
+
}
|
|
183
|
+
put(root, 'apps/api/src/services.ts', imports.join('\n') +
|
|
184
|
+
'\n\n// Call after product authorization and quota checks; no service is activated at startup.\nexport function createServices(env: Env) {\n return {\n ' +
|
|
185
|
+
adapters.join(',\n ') +
|
|
186
|
+
',\n };\n}\n');
|
|
187
|
+
const file = 'apps/api/src/index.ts';
|
|
188
|
+
let source = readFileSync(path.join(root, file), 'utf8');
|
|
189
|
+
if (source.includes("import { createServices } from './services';"))
|
|
190
|
+
return;
|
|
191
|
+
source = "import { createServices } from './services';\n" + source;
|
|
192
|
+
if (source.includes('Variables: {'))
|
|
193
|
+
source = source.replace('Variables: {', 'Variables: { services: ReturnType<typeof createServices>;');
|
|
194
|
+
else
|
|
195
|
+
source = source.replace('Bindings: Env', 'Bindings: Env; Variables: { services: ReturnType<typeof createServices> }');
|
|
196
|
+
source = source.replace('const health = createRoute({', "// Product routes use c.get('services') after authorization.\napp.use('/api/*', async (c, next) => {\n c.set('services', createServices(c.env));\n await next();\n});\nconst health = createRoute({");
|
|
197
|
+
put(root, file, source);
|
|
198
|
+
}
|
package/dist/scaffold/compose.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { scaffoldCloudflareServiceContext } from './cloudflare-services.js';
|
|
1
2
|
import { writeProjectSection } from '../project-config.js';
|
|
2
3
|
import { existsSync, rmSync } from 'node:fs';
|
|
3
4
|
import path from 'node:path';
|
|
@@ -20,6 +21,7 @@ export async function composeStack(root, options, registry) {
|
|
|
20
21
|
if (item.installer === 'recipe')
|
|
21
22
|
await installStackItem(item, context);
|
|
22
23
|
}
|
|
24
|
+
scaffoldCloudflareServiceContext(context);
|
|
23
25
|
normalizeSharedLint(root);
|
|
24
26
|
writeStandardRoot(root, options, registry);
|
|
25
27
|
configureVoidDelivery(root);
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
1
3
|
import { writeEnvironmentFile } from './environment.js';
|
|
2
4
|
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
3
5
|
import { put, patchPackage, readJson, json, sharedPackage } from './files.js';
|
|
@@ -115,8 +117,23 @@ process.exitCode = result.status ?? 1;
|
|
|
115
117
|
const tsconfig = readJson(root, `${directory}/tsconfig.json`);
|
|
116
118
|
tsconfig.include = [...new Set([...(tsconfig.include ?? []), 'drizzle.config.ts'])];
|
|
117
119
|
json(root, `${directory}/tsconfig.json`, tsconfig);
|
|
118
|
-
|
|
119
|
-
|
|
120
|
+
if (has('hono')) {
|
|
121
|
+
patchPackage(root, 'apps/api/package.json', {
|
|
122
|
+
dependencies: { '@workspace/db': 'workspace:*' },
|
|
123
|
+
});
|
|
124
|
+
const source = readFileSync(path.join(root, 'apps/api/src/index.ts'), 'utf8');
|
|
125
|
+
put(root, 'apps/api/src/index.ts', "import { createDatabase } from '@workspace/db';\n" +
|
|
126
|
+
source
|
|
127
|
+
.replace(source.includes('Variables: {') ? 'Variables: {' : 'Bindings: Env', source.includes('Variables: {')
|
|
128
|
+
? 'Variables: { database: () => ReturnType<typeof createDatabase>;'
|
|
129
|
+
: 'Bindings: Env; Variables: { database: () => ReturnType<typeof createDatabase> }')
|
|
130
|
+
.replace('const health = createRoute({', `// Construct the database only when a route needs it: c.get('database')().
|
|
131
|
+
app.use('/api/*', async (c, next) => {
|
|
132
|
+
c.set('database', () => createDatabase(${postgres ? 'c.env.DATABASE_URL' : 'c.env.DB'}));
|
|
133
|
+
await next();
|
|
134
|
+
});
|
|
135
|
+
const health = createRoute({`));
|
|
136
|
+
}
|
|
120
137
|
if (postgres) {
|
|
121
138
|
const native = runtimeApp === 'web' && options.hosting === 'vercel';
|
|
122
139
|
writeEnvironmentFile(root, `${app}/${native ? '.env.example' : '.dev.vars.example'}`, {
|