@farm.js/cli 0.1.0-beta.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.
@@ -0,0 +1,2528 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ //#region src/ui-feature-registry.ts
5
+ async function installUIFeature(input) {
6
+ const feature = input.definition.ui;
7
+ if (!feature) {
8
+ input.result.notes.push(`No --ui feature pack is available for ${input.definition.provider} yet.`);
9
+ return;
10
+ }
11
+ input.result.ui = {
12
+ feature: feature.name,
13
+ components: [...feature.components],
14
+ files: []
15
+ };
16
+ input.result.notes.push(`Installed ${feature.description} with shadcn-style local source components.`, ...feature.notes || []);
17
+ await ensureComponentsJson({
18
+ root: input.root,
19
+ dryRun: input.dryRun,
20
+ result: input.result
21
+ });
22
+ await ensureShadcnGlobals({
23
+ root: input.root,
24
+ dryRun: input.dryRun,
25
+ result: input.result
26
+ });
27
+ await ensureTsconfigAlias({
28
+ root: input.root,
29
+ dryRun: input.dryRun,
30
+ result: input.result
31
+ });
32
+ if (!input.skipPackageJson) await updateUIPackageJson({
33
+ root: input.root,
34
+ dryRun: input.dryRun,
35
+ result: input.result
36
+ });
37
+ await writeGeneratedFile({
38
+ root: input.root,
39
+ relativePath: path.join("src", "lib", "utils.ts"),
40
+ source: shadcnUtilsTemplate(),
41
+ dryRun: input.dryRun,
42
+ force: input.force,
43
+ result: input.result
44
+ });
45
+ for (const component of feature.components) await writeGeneratedFile({
46
+ root: input.root,
47
+ relativePath: path.join("src", "components", "ui", `${component}.tsx`),
48
+ source: shadcnComponentTemplate(component),
49
+ dryRun: input.dryRun,
50
+ force: input.force,
51
+ result: input.result
52
+ });
53
+ if (feature.needsApiClient !== false) await writeGeneratedFile({
54
+ root: input.root,
55
+ relativePath: path.join("src", "lib", "api.ts"),
56
+ source: apiClientTemplate(),
57
+ dryRun: input.dryRun,
58
+ force: input.force,
59
+ result: input.result
60
+ });
61
+ for (const file of feature.files({
62
+ key: input.key,
63
+ provider: input.definition.provider
64
+ })) await writeGeneratedFile({
65
+ root: input.root,
66
+ relativePath: file.path,
67
+ source: file.source,
68
+ dryRun: input.dryRun,
69
+ force: input.force,
70
+ result: input.result
71
+ });
72
+ }
73
+ function stripeBillingUIFeature() {
74
+ return billingUIFeature({
75
+ provider: "stripe",
76
+ label: "Stripe"
77
+ });
78
+ }
79
+ function polarBillingUIFeature() {
80
+ return billingUIFeature({
81
+ provider: "polar",
82
+ label: "Polar"
83
+ });
84
+ }
85
+ function autumnBillingUIFeature() {
86
+ return billingUIFeature({
87
+ provider: "autumn",
88
+ label: "Autumn"
89
+ });
90
+ }
91
+ function aiChatUIFeature() {
92
+ return {
93
+ name: "ai-chat",
94
+ description: "AI chat UI",
95
+ components: [
96
+ "badge",
97
+ "button",
98
+ "card",
99
+ "input"
100
+ ],
101
+ needsApiClient: false,
102
+ notes: ["Open \"/integrations/ai\" to try the generated chat UI."],
103
+ files: () => [componentFile("ai-chat.tsx", aiChatTemplate()), integrationPageFile("ai", "AIChat")]
104
+ };
105
+ }
106
+ function supabaseAuthUIFeature() {
107
+ return {
108
+ name: "supabase-auth",
109
+ description: "Supabase auth UI",
110
+ components: [
111
+ "badge",
112
+ "button",
113
+ "card",
114
+ "input",
115
+ "label"
116
+ ],
117
+ notes: ["Open \"/integrations/supabase\" to try the generated auth UI."],
118
+ files: (input) => [componentFile("supabase-auth-panel.tsx", supabaseAuthTemplate(input.key)), integrationPageFile("supabase", "SupabaseAuthPanel")]
119
+ };
120
+ }
121
+ function workosAuthUIFeature() {
122
+ return {
123
+ name: "workos-auth",
124
+ description: "WorkOS auth UI",
125
+ components: [
126
+ "badge",
127
+ "button",
128
+ "card"
129
+ ],
130
+ notes: ["Open \"/integrations/workos\" to try the generated auth UI."],
131
+ files: (input) => [componentFile("workos-auth-panel.tsx", hostedAuthTemplate({
132
+ key: input.key,
133
+ provider: "WorkOS",
134
+ componentName: "WorkOSAuthPanel",
135
+ statusCall: "session.get",
136
+ logoutCall: "logout.post",
137
+ loginHref: "/login?returnTo=/dashboard",
138
+ signupHref: "/signup?returnTo=/dashboard",
139
+ statusLabel: "Session"
140
+ })), integrationPageFile("workos", "WorkOSAuthPanel")]
141
+ };
142
+ }
143
+ function auth0AuthUIFeature() {
144
+ return {
145
+ name: "auth0-auth",
146
+ description: "Auth0 auth UI",
147
+ components: [
148
+ "badge",
149
+ "button",
150
+ "card"
151
+ ],
152
+ notes: ["Open \"/integrations/auth0\" to try the generated auth UI."],
153
+ files: (input) => [componentFile("auth0-auth-panel.tsx", hostedAuthTemplate({
154
+ key: input.key,
155
+ provider: "Auth0",
156
+ componentName: "Auth0AuthPanel",
157
+ statusCall: "profile.get",
158
+ logoutCall: "logout.get",
159
+ loginHref: "/auth/login?returnTo=/dashboard",
160
+ signupHref: "/auth/signup?returnTo=/dashboard",
161
+ statusLabel: "Profile"
162
+ })), integrationPageFile("auth0", "Auth0AuthPanel")]
163
+ };
164
+ }
165
+ function clerkAuthUIFeature() {
166
+ return authRouteShellUIFeature({
167
+ provider: "clerk",
168
+ label: "Clerk",
169
+ componentName: "ClerkAuthPanel",
170
+ signInHref: "/sign-in",
171
+ signUpHref: "/sign-up",
172
+ sessionHref: "/dashboard"
173
+ });
174
+ }
175
+ function betterAuthUIFeature() {
176
+ return {
177
+ name: "better-auth-auth",
178
+ description: "Better Auth email and password UI",
179
+ components: [
180
+ "badge",
181
+ "button",
182
+ "card",
183
+ "input",
184
+ "label"
185
+ ],
186
+ needsApiClient: false,
187
+ notes: ["Open \"/integrations/better-auth\" to try the generated auth UI."],
188
+ files: () => [
189
+ {
190
+ path: path.join("src", "lib", "auth-client.ts"),
191
+ source: betterAuthClientTemplate()
192
+ },
193
+ componentFile("better-auth-panel.tsx", betterAuthPanelTemplate()),
194
+ integrationPageFile("better-auth", "BetterAuthPanel")
195
+ ]
196
+ };
197
+ }
198
+ function authjsUIFeature() {
199
+ return authRouteShellUIFeature({
200
+ provider: "authjs",
201
+ label: "Auth.js",
202
+ componentName: "AuthJsPanel",
203
+ signInHref: "/api/auth/signin",
204
+ signUpHref: "/api/auth/signin",
205
+ sessionHref: "/api/auth/session"
206
+ });
207
+ }
208
+ function resendEmailUIFeature() {
209
+ return {
210
+ name: "resend-email",
211
+ description: "Resend email console UI",
212
+ components: [
213
+ "badge",
214
+ "button",
215
+ "card",
216
+ "input",
217
+ "label"
218
+ ],
219
+ notes: ["Open \"/integrations/resend\" to try the generated email UI."],
220
+ files: (input) => [componentFile("resend-email-console.tsx", resendEmailTemplate(input.key)), integrationPageFile("resend", "ResendEmailConsole")]
221
+ };
222
+ }
223
+ function jobsUIFeature(provider) {
224
+ const label = provider === "inngest" ? "Inngest" : "Trigger.dev";
225
+ return {
226
+ name: `${provider}-jobs`,
227
+ description: `${label} jobs console UI`,
228
+ components: [
229
+ "badge",
230
+ "button",
231
+ "card",
232
+ "input",
233
+ "label"
234
+ ],
235
+ notes: [`Open "/integrations/jobs-${provider}" to try the generated jobs UI.`],
236
+ files: (input) => [componentFile(`${provider}-jobs-console.tsx`, jobsConsoleTemplate(input.key, label, provider)), integrationPageFile(`jobs-${provider}`, `${pascalCase(provider)}JobsConsole`)]
237
+ };
238
+ }
239
+ function unkeyApiKeysUIFeature() {
240
+ return {
241
+ name: "unkey-api-keys",
242
+ description: "Unkey API key console UI",
243
+ components: [
244
+ "badge",
245
+ "button",
246
+ "card",
247
+ "input",
248
+ "label"
249
+ ],
250
+ notes: ["Open \"/integrations/unkey\" to try the generated API key UI."],
251
+ files: (input) => [componentFile("unkey-api-keys-console.tsx", unkeyApiKeysTemplate(input.key)), integrationPageFile("unkey", "UnkeyApiKeysConsole")]
252
+ };
253
+ }
254
+ function billingUIFeature(input) {
255
+ return {
256
+ name: `${input.provider}-billing`,
257
+ description: `${input.label} pricing and checkout UI`,
258
+ components: [
259
+ "badge",
260
+ "button",
261
+ "card"
262
+ ],
263
+ notes: [`Open "/integrations/${input.provider}" to try the generated ${input.label} billing UI.`],
264
+ files: (templateInput) => [componentFile(`${input.provider}-billing.tsx`, billingPricingTemplate({
265
+ key: templateInput.key,
266
+ provider: input.provider,
267
+ label: input.label,
268
+ componentName: `${pascalCase(input.provider)}Billing`
269
+ })), integrationPageFile(input.provider, `${pascalCase(input.provider)}Billing`)]
270
+ };
271
+ }
272
+ function authRouteShellUIFeature(input) {
273
+ return {
274
+ name: `${input.provider}-auth`,
275
+ description: `${input.label} auth UI`,
276
+ components: [
277
+ "badge",
278
+ "button",
279
+ "card"
280
+ ],
281
+ notes: [`Open "/integrations/${input.provider}" to try the generated auth UI.`],
282
+ files: () => [componentFile(`${input.provider}-auth-panel.tsx`, authRouteShellTemplate({
283
+ provider: input.label,
284
+ componentName: input.componentName,
285
+ signInHref: input.signInHref,
286
+ signUpHref: input.signUpHref,
287
+ sessionHref: input.sessionHref
288
+ })), integrationPageFile(input.provider, input.componentName)]
289
+ };
290
+ }
291
+ function componentFile(fileName, source) {
292
+ return {
293
+ path: path.join("src", "components", "farm", fileName),
294
+ source
295
+ };
296
+ }
297
+ function integrationPageFile(provider, componentName) {
298
+ const fileName = kebabCase(componentName);
299
+ return {
300
+ path: path.join("src", "app", "integrations", provider, "page.tsx"),
301
+ source: `import { ${componentName} } from "@/components/farm/${fileName}";
302
+
303
+ export default function ${componentName}Page() {
304
+ return <${componentName} />;
305
+ }
306
+ `
307
+ };
308
+ }
309
+ async function writeGeneratedFile(input) {
310
+ const absolutePath = path.join(input.root, input.relativePath);
311
+ const exists = existsSync(absolutePath);
312
+ const source = resolveGeneratedAliases(input.source, input.relativePath);
313
+ input.result.ui?.files.push(absolutePath);
314
+ if (exists && !input.force) {
315
+ pushResultPath(input.result.skipped, absolutePath);
316
+ return;
317
+ }
318
+ if (!input.dryRun) {
319
+ await mkdir(path.dirname(absolutePath), { recursive: true });
320
+ await writeFile(absolutePath, source, "utf8");
321
+ }
322
+ pushResultPath(exists ? input.result.updated : input.result.created, absolutePath);
323
+ }
324
+ function resolveGeneratedAliases(source, relativePath) {
325
+ const sourceDirectory = path.dirname(relativePath);
326
+ return source.replace(/(["'])@\/([^"']+)\1/g, (_match, quote, target) => {
327
+ const relativeTarget = path.relative(sourceDirectory, path.join("src", target)).split(path.sep).join("/");
328
+ return `${quote}${relativeTarget.startsWith(".") ? relativeTarget : `./${relativeTarget}`}${quote}`;
329
+ });
330
+ }
331
+ async function ensureComponentsJson(input) {
332
+ const componentsJsonPath = path.join(input.root, "components.json");
333
+ input.result.ui?.files.push(componentsJsonPath);
334
+ const defaults = createComponentsJson();
335
+ if (!existsSync(componentsJsonPath)) {
336
+ if (!input.dryRun) await writeFile(componentsJsonPath, `${JSON.stringify(defaults, null, 2)}\n`, "utf8");
337
+ pushResultPath(input.result.created, componentsJsonPath);
338
+ return;
339
+ }
340
+ let current;
341
+ try {
342
+ current = JSON.parse(await readFile(componentsJsonPath, "utf8"));
343
+ } catch {
344
+ pushResultPath(input.result.skipped, componentsJsonPath);
345
+ input.result.notes.push("components.json could not be parsed. Keep shadcn aliases pointed at src/components and src/lib/utils.");
346
+ return;
347
+ }
348
+ const next = mergeComponentsJson(current, defaults);
349
+ if (JSON.stringify(current) === JSON.stringify(next)) {
350
+ pushResultPath(input.result.skipped, componentsJsonPath);
351
+ return;
352
+ }
353
+ if (!input.dryRun) await writeFile(componentsJsonPath, `${JSON.stringify(next, null, 2)}\n`, "utf8");
354
+ pushResultPath(input.result.updated, componentsJsonPath);
355
+ }
356
+ async function ensureShadcnGlobals(input) {
357
+ const globalsPath = path.join(input.root, "src", "app", "globals.css");
358
+ input.result.ui?.files.push(globalsPath);
359
+ if (!existsSync(globalsPath)) {
360
+ const source = `@import "tailwindcss";
361
+
362
+ ${SHADCN_THEME_CSS}
363
+ `;
364
+ if (!input.dryRun) {
365
+ await mkdir(path.dirname(globalsPath), { recursive: true });
366
+ await writeFile(globalsPath, source, "utf8");
367
+ }
368
+ pushResultPath(input.result.created, globalsPath);
369
+ return;
370
+ }
371
+ const source = await readFile(globalsPath, "utf8");
372
+ const hasTailwindImport = source.includes("@import \"tailwindcss\"");
373
+ const hasTheme = source.includes("--color-background") || source.includes("--background:");
374
+ if (hasTailwindImport && hasTheme) {
375
+ pushResultPath(input.result.skipped, globalsPath);
376
+ return;
377
+ }
378
+ const nextSource = `${hasTailwindImport ? "" : "@import \"tailwindcss\";\n\n"}${source.trimEnd()}${hasTheme ? "\n" : `
379
+
380
+ ${SHADCN_THEME_CSS}
381
+ `}`;
382
+ if (!input.dryRun) await writeFile(globalsPath, nextSource, "utf8");
383
+ pushResultPath(input.result.updated, globalsPath);
384
+ }
385
+ async function ensureTsconfigAlias(input) {
386
+ const tsconfigPath = path.join(input.root, "tsconfig.json");
387
+ input.result.ui?.files.push(tsconfigPath);
388
+ const defaults = { compilerOptions: {
389
+ baseUrl: ".",
390
+ paths: { "@/*": ["./src/*"] }
391
+ } };
392
+ if (!existsSync(tsconfigPath)) {
393
+ if (!input.dryRun) await writeFile(tsconfigPath, `${JSON.stringify(defaults, null, 2)}\n`, "utf8");
394
+ pushResultPath(input.result.created, tsconfigPath);
395
+ return;
396
+ }
397
+ let tsconfig;
398
+ try {
399
+ tsconfig = JSON.parse(await readFile(tsconfigPath, "utf8"));
400
+ } catch {
401
+ pushResultPath(input.result.skipped, tsconfigPath);
402
+ input.result.notes.push("tsconfig.json could not be parsed. Add paths: { \"@/*\": [\"./src/*\"] } manually.");
403
+ return;
404
+ }
405
+ const compilerOptions = readObject(tsconfig.compilerOptions);
406
+ const paths = readObject(compilerOptions.paths);
407
+ const nextCompilerOptions = {
408
+ ...compilerOptions,
409
+ baseUrl: typeof compilerOptions.baseUrl === "string" ? compilerOptions.baseUrl : ".",
410
+ paths: {
411
+ ...paths,
412
+ "@/*": ["./src/*"]
413
+ }
414
+ };
415
+ const nextTsconfig = {
416
+ ...tsconfig,
417
+ compilerOptions: nextCompilerOptions
418
+ };
419
+ if (JSON.stringify(tsconfig) === JSON.stringify(nextTsconfig)) {
420
+ pushResultPath(input.result.skipped, tsconfigPath);
421
+ return;
422
+ }
423
+ if (!input.dryRun) await writeFile(tsconfigPath, `${JSON.stringify(nextTsconfig, null, 2)}\n`, "utf8");
424
+ pushResultPath(input.result.updated, tsconfigPath);
425
+ }
426
+ async function updateUIPackageJson(input) {
427
+ const packageJsonPath = path.join(input.root, "package.json");
428
+ input.result.ui?.files.push(packageJsonPath);
429
+ if (!existsSync(packageJsonPath)) {
430
+ pushResultPath(input.result.skipped, packageJsonPath);
431
+ return;
432
+ }
433
+ const source = await readFile(packageJsonPath, "utf8");
434
+ const manifest = JSON.parse(source);
435
+ let changed = false;
436
+ for (const [dependency, version] of Object.entries(UI_DEPENDENCIES)) {
437
+ if (hasPackageDependency$1(manifest, dependency)) continue;
438
+ manifest.dependencies = {
439
+ ...manifest.dependencies,
440
+ [dependency]: version
441
+ };
442
+ changed = true;
443
+ }
444
+ if (!changed) {
445
+ pushResultPath(input.result.skipped, packageJsonPath);
446
+ return;
447
+ }
448
+ if (!input.dryRun) await writeFile(packageJsonPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
449
+ input.result.packageJson = packageJsonPath;
450
+ pushResultPath(input.result.updated, packageJsonPath);
451
+ }
452
+ const UI_DEPENDENCIES = {
453
+ "class-variance-authority": "^0.7.1",
454
+ clsx: "^2.1.1",
455
+ "tailwind-merge": "^3.3.1",
456
+ tailwindcss: "^4.1.18"
457
+ };
458
+ const SHADCN_THEME_CSS = `@custom-variant dark (&:is(.dark *));
459
+
460
+ @theme inline {
461
+ --color-background: var(--background);
462
+ --color-foreground: var(--foreground);
463
+ --color-card: var(--card);
464
+ --color-card-foreground: var(--card-foreground);
465
+ --color-popover: var(--popover);
466
+ --color-popover-foreground: var(--popover-foreground);
467
+ --color-primary: var(--primary);
468
+ --color-primary-foreground: var(--primary-foreground);
469
+ --color-secondary: var(--secondary);
470
+ --color-secondary-foreground: var(--secondary-foreground);
471
+ --color-muted: var(--muted);
472
+ --color-muted-foreground: var(--muted-foreground);
473
+ --color-accent: var(--accent);
474
+ --color-accent-foreground: var(--accent-foreground);
475
+ --color-destructive: var(--destructive);
476
+ --color-border: var(--border);
477
+ --color-input: var(--input);
478
+ --color-ring: var(--ring);
479
+ --radius-sm: calc(var(--radius) - 4px);
480
+ --radius-md: calc(var(--radius) - 2px);
481
+ --radius-lg: var(--radius);
482
+ }
483
+
484
+ :root {
485
+ --radius: 0.5rem;
486
+ --background: oklch(1 0 0);
487
+ --foreground: oklch(0.145 0 0);
488
+ --card: oklch(1 0 0);
489
+ --card-foreground: oklch(0.145 0 0);
490
+ --popover: oklch(1 0 0);
491
+ --popover-foreground: oklch(0.145 0 0);
492
+ --primary: oklch(0.205 0 0);
493
+ --primary-foreground: oklch(0.985 0 0);
494
+ --secondary: oklch(0.97 0 0);
495
+ --secondary-foreground: oklch(0.205 0 0);
496
+ --muted: oklch(0.97 0 0);
497
+ --muted-foreground: oklch(0.556 0 0);
498
+ --accent: oklch(0.97 0 0);
499
+ --accent-foreground: oklch(0.205 0 0);
500
+ --destructive: oklch(0.577 0.245 27.325);
501
+ --border: oklch(0.922 0 0);
502
+ --input: oklch(0.922 0 0);
503
+ --ring: oklch(0.708 0 0);
504
+ }
505
+
506
+ .dark {
507
+ --background: oklch(0.145 0 0);
508
+ --foreground: oklch(0.985 0 0);
509
+ --card: oklch(0.205 0 0);
510
+ --card-foreground: oklch(0.985 0 0);
511
+ --popover: oklch(0.205 0 0);
512
+ --popover-foreground: oklch(0.985 0 0);
513
+ --primary: oklch(0.922 0 0);
514
+ --primary-foreground: oklch(0.205 0 0);
515
+ --secondary: oklch(0.269 0 0);
516
+ --secondary-foreground: oklch(0.985 0 0);
517
+ --muted: oklch(0.269 0 0);
518
+ --muted-foreground: oklch(0.708 0 0);
519
+ --accent: oklch(0.269 0 0);
520
+ --accent-foreground: oklch(0.985 0 0);
521
+ --destructive: oklch(0.704 0.191 22.216);
522
+ --border: oklch(1 0 0 / 10%);
523
+ --input: oklch(1 0 0 / 15%);
524
+ --ring: oklch(0.556 0 0);
525
+ }
526
+
527
+ @layer base {
528
+ * {
529
+ @apply border-border outline-ring/50;
530
+ }
531
+
532
+ body {
533
+ @apply bg-background text-foreground;
534
+ }
535
+ }`;
536
+ function createComponentsJson() {
537
+ return {
538
+ $schema: "https://ui.shadcn.com/schema.json",
539
+ style: "new-york",
540
+ rsc: true,
541
+ tsx: true,
542
+ tailwind: {
543
+ config: "",
544
+ css: "src/app/globals.css",
545
+ baseColor: "zinc",
546
+ cssVariables: true
547
+ },
548
+ aliases: {
549
+ components: "@/components",
550
+ utils: "@/lib/utils",
551
+ ui: "@/components/ui",
552
+ lib: "@/lib",
553
+ hooks: "@/hooks"
554
+ },
555
+ registries: { farm: { url: "https://farmjs.dev/r/{name}.json" } }
556
+ };
557
+ }
558
+ function mergeComponentsJson(current, defaults) {
559
+ const aliases = readObject(current.aliases);
560
+ const tailwind = readObject(current.tailwind);
561
+ const registries = readObject(current.registries);
562
+ return {
563
+ ...current,
564
+ $schema: typeof current.$schema === "string" ? current.$schema : defaults.$schema,
565
+ style: typeof current.style === "string" ? current.style : defaults.style,
566
+ rsc: typeof current.rsc === "boolean" ? current.rsc : defaults.rsc,
567
+ tsx: typeof current.tsx === "boolean" ? current.tsx : defaults.tsx,
568
+ tailwind: {
569
+ ...defaults.tailwind,
570
+ ...tailwind
571
+ },
572
+ aliases: {
573
+ ...defaults.aliases,
574
+ ...aliases
575
+ },
576
+ registries: {
577
+ ...registries,
578
+ farm: readObject(registries.farm).url ? registries.farm : defaults.registries.farm
579
+ }
580
+ };
581
+ }
582
+ function shadcnUtilsTemplate() {
583
+ return `import { clsx, type ClassValue } from "clsx";
584
+ import { twMerge } from "tailwind-merge";
585
+
586
+ export function cn(...inputs: ClassValue[]) {
587
+ return twMerge(clsx(inputs));
588
+ }
589
+ `;
590
+ }
591
+ function apiClientTemplate() {
592
+ return `import { createIntegrations } from "@farm.js/core/client";
593
+ import type { AppIntegrations } from "./integrations";
594
+
595
+ export const { api, apiClient } = createIntegrations<AppIntegrations>();
596
+ `;
597
+ }
598
+ function shadcnComponentTemplate(component) {
599
+ switch (component) {
600
+ case "badge": return `import * as React from "react";
601
+ import { cva, type VariantProps } from "class-variance-authority";
602
+ import { cn } from "@/lib/utils";
603
+
604
+ const badgeVariants = cva(
605
+ "inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
606
+ {
607
+ variants: {
608
+ variant: {
609
+ default: "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
610
+ secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
611
+ outline: "text-foreground",
612
+ },
613
+ },
614
+ defaultVariants: {
615
+ variant: "default",
616
+ },
617
+ },
618
+ );
619
+
620
+ export interface BadgeProps
621
+ extends React.HTMLAttributes<HTMLDivElement>,
622
+ VariantProps<typeof badgeVariants> {}
623
+
624
+ export function Badge({ className, variant, ...props }: BadgeProps) {
625
+ return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
626
+ }
627
+
628
+ export { badgeVariants };
629
+ `;
630
+ case "button": return `import * as React from "react";
631
+ import { cva, type VariantProps } from "class-variance-authority";
632
+ import { cn } from "@/lib/utils";
633
+
634
+ const buttonVariants = cva(
635
+ "inline-flex h-9 items-center justify-center whitespace-nowrap rounded-md px-4 py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",
636
+ {
637
+ variants: {
638
+ variant: {
639
+ default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
640
+ secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
641
+ outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
642
+ ghost: "hover:bg-accent hover:text-accent-foreground",
643
+ },
644
+ size: {
645
+ default: "h-9 px-4 py-2",
646
+ sm: "h-8 rounded-md px-3 text-xs",
647
+ lg: "h-10 rounded-md px-8",
648
+ },
649
+ },
650
+ defaultVariants: {
651
+ variant: "default",
652
+ size: "default",
653
+ },
654
+ },
655
+ );
656
+
657
+ export interface ButtonProps
658
+ extends React.ButtonHTMLAttributes<HTMLButtonElement>,
659
+ VariantProps<typeof buttonVariants> {}
660
+
661
+ export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
662
+ ({ className, variant, size, ...props }, ref) => {
663
+ return (
664
+ <button
665
+ className={cn(buttonVariants({ variant, size, className }))}
666
+ ref={ref}
667
+ {...props}
668
+ />
669
+ );
670
+ },
671
+ );
672
+ Button.displayName = "Button";
673
+
674
+ export { buttonVariants };
675
+ `;
676
+ case "card": return `import * as React from "react";
677
+ import { cn } from "@/lib/utils";
678
+
679
+ export const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
680
+ ({ className, ...props }, ref) => (
681
+ <div
682
+ ref={ref}
683
+ className={cn("rounded-lg border bg-card text-card-foreground shadow-sm", className)}
684
+ {...props}
685
+ />
686
+ ),
687
+ );
688
+ Card.displayName = "Card";
689
+
690
+ export const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
691
+ ({ className, ...props }, ref) => (
692
+ <div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
693
+ ),
694
+ );
695
+ CardHeader.displayName = "CardHeader";
696
+
697
+ export const CardTitle = React.forwardRef<HTMLHeadingElement, React.HTMLAttributes<HTMLHeadingElement>>(
698
+ ({ className, ...props }, ref) => (
699
+ <h3 ref={ref} className={cn("text-2xl font-semibold leading-none tracking-normal", className)} {...props} />
700
+ ),
701
+ );
702
+ CardTitle.displayName = "CardTitle";
703
+
704
+ export const CardDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
705
+ ({ className, ...props }, ref) => (
706
+ <p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
707
+ ),
708
+ );
709
+ CardDescription.displayName = "CardDescription";
710
+
711
+ export const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
712
+ ({ className, ...props }, ref) => (
713
+ <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
714
+ ),
715
+ );
716
+ CardContent.displayName = "CardContent";
717
+
718
+ export const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
719
+ ({ className, ...props }, ref) => (
720
+ <div ref={ref} className={cn("flex items-center p-6 pt-0", className)} {...props} />
721
+ ),
722
+ );
723
+ CardFooter.displayName = "CardFooter";
724
+ `;
725
+ case "input": return `import * as React from "react";
726
+ import { cn } from "@/lib/utils";
727
+
728
+ export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}
729
+
730
+ export const Input = React.forwardRef<HTMLInputElement, InputProps>(
731
+ ({ className, type, ...props }, ref) => (
732
+ <input
733
+ type={type}
734
+ className={cn(
735
+ "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
736
+ className,
737
+ )}
738
+ ref={ref}
739
+ {...props}
740
+ />
741
+ ),
742
+ );
743
+ Input.displayName = "Input";
744
+ `;
745
+ case "label": return `import * as React from "react";
746
+ import { cn } from "@/lib/utils";
747
+
748
+ export const Label = React.forwardRef<HTMLLabelElement, React.LabelHTMLAttributes<HTMLLabelElement>>(
749
+ ({ className, ...props }, ref) => (
750
+ <label
751
+ ref={ref}
752
+ className={cn("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70", className)}
753
+ {...props}
754
+ />
755
+ ),
756
+ );
757
+ Label.displayName = "Label";
758
+ `;
759
+ }
760
+ }
761
+ function billingPricingTemplate(input) {
762
+ return `"use client";
763
+
764
+ import * as React from "react";
765
+ import { Badge } from "@/components/ui/badge";
766
+ import { Button } from "@/components/ui/button";
767
+ import {
768
+ Card,
769
+ CardContent,
770
+ CardDescription,
771
+ CardFooter,
772
+ CardHeader,
773
+ CardTitle,
774
+ } from "@/components/ui/card";
775
+ import { apiClient } from "@/lib/api";
776
+
777
+ type BillingProduct = NonNullable<Awaited<ReturnType<typeof apiClient.${input.key}.products>>["data"]>[number];
778
+
779
+ export function ${input.componentName}() {
780
+ const [products, setProducts] = React.useState<BillingProduct[]>([]);
781
+ const [loading, setLoading] = React.useState(true);
782
+ const [checkingOut, setCheckingOut] = React.useState<string | null>(null);
783
+ const [error, setError] = React.useState<string | null>(null);
784
+
785
+ React.useEffect(() => {
786
+ let active = true;
787
+
788
+ async function loadProducts() {
789
+ setLoading(true);
790
+ setError(null);
791
+
792
+ try {
793
+ const response = await apiClient.${input.key}.products();
794
+ if (response.error) {
795
+ throw new Error(readErrorMessage(response.error, "${input.label} request failed."));
796
+ }
797
+
798
+ if (active) {
799
+ setProducts(Array.from(response.data ?? []));
800
+ }
801
+ } catch (cause) {
802
+ if (active) {
803
+ setError(cause instanceof Error ? cause.message : "Could not load ${input.label} products.");
804
+ }
805
+ } finally {
806
+ if (active) {
807
+ setLoading(false);
808
+ }
809
+ }
810
+ }
811
+
812
+ void loadProducts();
813
+
814
+ return () => {
815
+ active = false;
816
+ };
817
+ }, []);
818
+
819
+ async function startCheckout(product: BillingProduct) {
820
+ const productId = String(readProductField(product, "id") ?? "");
821
+ if (!productId) {
822
+ setError("This Stripe product is missing an id.");
823
+ return;
824
+ }
825
+
826
+ setCheckingOut(productId);
827
+ setError(null);
828
+
829
+ try {
830
+ const response = await apiClient.${input.key}.checkout({
831
+ body: {
832
+ productId,
833
+ successPath: "/billing/success",
834
+ cancelPath: "/integrations/${input.provider}",
835
+ },
836
+ });
837
+ if (response.error) {
838
+ throw new Error(readErrorMessage(response.error, "${input.label} checkout failed."));
839
+ }
840
+
841
+ const redirectTo = response.data?.redirectTo;
842
+ if (!redirectTo) {
843
+ throw new Error("${input.label} checkout did not return a redirect URL.");
844
+ }
845
+
846
+ window.location.assign(redirectTo);
847
+ } catch (cause) {
848
+ setError(cause instanceof Error ? cause.message : "Could not start ${input.label} checkout.");
849
+ setCheckingOut(null);
850
+ }
851
+ }
852
+
853
+ return (
854
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
855
+ <section className="mx-auto flex w-full max-w-5xl flex-col gap-8">
856
+ <div className="max-w-2xl space-y-3">
857
+ <Badge variant="secondary">${input.label}</Badge>
858
+ <h1 className="text-3xl font-semibold tracking-normal">${input.label} billing</h1>
859
+ <p className="text-sm leading-6 text-muted-foreground">
860
+ Plans, checkout, and customer billing actions in one place.
861
+ </p>
862
+ </div>
863
+
864
+ {error ? (
865
+ <div className="rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
866
+ {error}
867
+ </div>
868
+ ) : null}
869
+
870
+ {loading ? (
871
+ <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
872
+ {Array.from({ length: 3 }).map((_, index) => (
873
+ <Card key={index} className="min-h-[220px] animate-pulse" />
874
+ ))}
875
+ </div>
876
+ ) : products.length ? (
877
+ <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
878
+ {products.map((product) => {
879
+ const productId = String(readProductField(product, "id") ?? "");
880
+ const fallbackName = productId || "Product";
881
+ const name = String(readProductField(product, "name") ?? fallbackName);
882
+ const description =
883
+ readProductField(product, "description") ?? "Connected to your Stripe catalog.";
884
+
885
+ return (
886
+ <Card key={productId || name} className="flex min-h-[260px] flex-col">
887
+ <CardHeader>
888
+ <CardTitle className="text-xl">{name}</CardTitle>
889
+ <CardDescription>{String(description)}</CardDescription>
890
+ </CardHeader>
891
+ <CardContent className="flex-1">
892
+ <div className="text-3xl font-semibold">{formatProductPrice(product)}</div>
893
+ </CardContent>
894
+ <CardFooter>
895
+ <Button
896
+ className="w-full"
897
+ disabled={!productId || checkingOut === productId}
898
+ onClick={() => void startCheckout(product)}
899
+ >
900
+ {checkingOut === productId ? "Starting checkout..." : "Checkout"}
901
+ </Button>
902
+ </CardFooter>
903
+ </Card>
904
+ );
905
+ })}
906
+ </div>
907
+ ) : (
908
+ <Card>
909
+ <CardHeader>
910
+ <CardTitle>No products yet</CardTitle>
911
+ <CardDescription>
912
+ Add products to the generated ${input.label} integration template or provider dashboard.
913
+ </CardDescription>
914
+ </CardHeader>
915
+ </Card>
916
+ )}
917
+ </section>
918
+ </main>
919
+ );
920
+ }
921
+
922
+ function readProductField(product: BillingProduct, field: string) {
923
+ return (product as Record<string, unknown>)[field];
924
+ }
925
+
926
+ function formatProductPrice(product: BillingProduct) {
927
+ const amount = readProductField(product, "amount") ?? readProductField(product, "unitAmount");
928
+ const currency = String(readProductField(product, "currency") ?? "USD").toUpperCase();
929
+ const interval = readProductField(product, "interval");
930
+
931
+ if (typeof amount === "number" && Number.isFinite(amount)) {
932
+ const formatted = new Intl.NumberFormat("en", {
933
+ style: "currency",
934
+ currency,
935
+ }).format(amount / 100);
936
+
937
+ return interval ? \`\${formatted}/\${String(interval)}\` : formatted;
938
+ }
939
+
940
+ return "Custom";
941
+ }
942
+
943
+ function readErrorMessage(error: unknown, fallback: string) {
944
+ if (error && typeof error === "object" && "message" in error) {
945
+ return String((error as { message?: unknown }).message);
946
+ }
947
+
948
+ return fallback;
949
+ }
950
+ `;
951
+ }
952
+ function aiChatTemplate() {
953
+ return `"use client";
954
+
955
+ import * as React from "react";
956
+ import { Badge } from "@/components/ui/badge";
957
+ import { Button } from "@/components/ui/button";
958
+ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
959
+ import { Input } from "@/components/ui/input";
960
+
961
+ type ChatMessage = {
962
+ role: "user" | "assistant";
963
+ content: string;
964
+ };
965
+
966
+ export function AIChat() {
967
+ const [messages, setMessages] = React.useState<ChatMessage[]>([]);
968
+ const [input, setInput] = React.useState("");
969
+ const [pending, setPending] = React.useState(false);
970
+ const [error, setError] = React.useState<string | null>(null);
971
+
972
+ async function sendMessage(event: React.FormEvent<HTMLFormElement>) {
973
+ event.preventDefault();
974
+ const nextInput = input.trim();
975
+ if (!nextInput) {
976
+ return;
977
+ }
978
+
979
+ const nextMessages: ChatMessage[] = [...messages, { role: "user", content: nextInput }];
980
+ setMessages(nextMessages);
981
+ setInput("");
982
+ setPending(true);
983
+ setError(null);
984
+
985
+ try {
986
+ const response = await fetch("/api/chat", {
987
+ method: "POST",
988
+ headers: {
989
+ "content-type": "application/json",
990
+ },
991
+ body: JSON.stringify({
992
+ messages: nextMessages.map((message) => ({
993
+ role: message.role,
994
+ parts: [{ type: "text", text: message.content }],
995
+ })),
996
+ }),
997
+ });
998
+
999
+ const text = await response.text();
1000
+ if (!response.ok) {
1001
+ throw new Error(text || "AI request failed.");
1002
+ }
1003
+
1004
+ setMessages([...nextMessages, { role: "assistant", content: text || "Done." }]);
1005
+ } catch (cause) {
1006
+ setError(cause instanceof Error ? cause.message : "AI request failed.");
1007
+ } finally {
1008
+ setPending(false);
1009
+ }
1010
+ }
1011
+
1012
+ return (
1013
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1014
+ <section className="mx-auto flex w-full max-w-3xl flex-col gap-6">
1015
+ <div className="space-y-3">
1016
+ <Badge variant="secondary">AI</Badge>
1017
+ <h1 className="text-3xl font-semibold tracking-normal">Chat</h1>
1018
+ </div>
1019
+
1020
+ <Card>
1021
+ <CardHeader>
1022
+ <CardTitle className="text-xl">Conversation</CardTitle>
1023
+ </CardHeader>
1024
+ <CardContent className="space-y-4">
1025
+ <div className="min-h-[320px] space-y-3 rounded-md border bg-muted/30 p-4">
1026
+ {messages.length ? (
1027
+ messages.map((message, index) => (
1028
+ <div
1029
+ key={index}
1030
+ className={message.role === "user" ? "ml-auto max-w-[85%] rounded-md bg-primary px-3 py-2 text-sm text-primary-foreground" : "max-w-[85%] rounded-md bg-background px-3 py-2 text-sm"}
1031
+ >
1032
+ {message.content}
1033
+ </div>
1034
+ ))
1035
+ ) : (
1036
+ <p className="text-sm text-muted-foreground">Start a conversation.</p>
1037
+ )}
1038
+ </div>
1039
+
1040
+ {error ? <p className="text-sm text-destructive">{error}</p> : null}
1041
+
1042
+ <form className="flex gap-2" onSubmit={sendMessage}>
1043
+ <Input
1044
+ value={input}
1045
+ onChange={(event) => setInput(event.target.value)}
1046
+ placeholder="Ask something..."
1047
+ />
1048
+ <Button disabled={pending} type="submit">
1049
+ {pending ? "Sending..." : "Send"}
1050
+ </Button>
1051
+ </form>
1052
+ </CardContent>
1053
+ </Card>
1054
+ </section>
1055
+ </main>
1056
+ );
1057
+ }
1058
+ `;
1059
+ }
1060
+ function supabaseAuthTemplate(key) {
1061
+ return `"use client";
1062
+
1063
+ import * as React from "react";
1064
+ import { Badge } from "@/components/ui/badge";
1065
+ import { Button } from "@/components/ui/button";
1066
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1067
+ import { Input } from "@/components/ui/input";
1068
+ import { Label } from "@/components/ui/label";
1069
+ import { apiClient } from "@/lib/api";
1070
+
1071
+ export function SupabaseAuthPanel() {
1072
+ const [email, setEmail] = React.useState("");
1073
+ const [password, setPassword] = React.useState("");
1074
+ const [mode, setMode] = React.useState<"login" | "signup">("login");
1075
+ const [pending, setPending] = React.useState(false);
1076
+ const [status, setStatus] = React.useState<string | null>(null);
1077
+
1078
+ async function submit(event: React.FormEvent<HTMLFormElement>) {
1079
+ event.preventDefault();
1080
+ setPending(true);
1081
+ setStatus(null);
1082
+
1083
+ const response =
1084
+ mode === "login"
1085
+ ? await apiClient.${key}.login.post({ body: { email, password, returnTo: "/dashboard" } })
1086
+ : await apiClient.${key}.signup.post({ body: { email, password, returnTo: "/dashboard" } });
1087
+
1088
+ if (response.error) {
1089
+ setStatus(response.error.message);
1090
+ setPending(false);
1091
+ return;
1092
+ }
1093
+
1094
+ if (response.data?.redirectTo) {
1095
+ window.location.assign(response.data.redirectTo);
1096
+ return;
1097
+ }
1098
+
1099
+ setStatus(response.data?.message ?? "Check your email to continue.");
1100
+ setPending(false);
1101
+ }
1102
+
1103
+ async function loadSession() {
1104
+ const response = await apiClient.${key}.session.get();
1105
+ setStatus(response.error ? response.error.message : response.data?.authenticated ? "Authenticated" : "No active session");
1106
+ }
1107
+
1108
+ async function logout() {
1109
+ const response = await apiClient.${key}.logout.post({ body: { returnTo: "/" } });
1110
+ if (response.data?.redirectTo) {
1111
+ window.location.assign(response.data.redirectTo);
1112
+ return;
1113
+ }
1114
+ setStatus(response.error?.message ?? "Signed out");
1115
+ }
1116
+
1117
+ return (
1118
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1119
+ <section className="mx-auto flex w-full max-w-xl flex-col gap-6">
1120
+ <div className="space-y-3">
1121
+ <Badge variant="secondary">Supabase</Badge>
1122
+ <h1 className="text-3xl font-semibold tracking-normal">Auth</h1>
1123
+ </div>
1124
+
1125
+ <Card>
1126
+ <CardHeader>
1127
+ <CardTitle className="text-xl">{mode === "login" ? "Sign in" : "Create account"}</CardTitle>
1128
+ <CardDescription>Email and password access for this app.</CardDescription>
1129
+ </CardHeader>
1130
+ <CardContent>
1131
+ <form className="space-y-4" onSubmit={submit}>
1132
+ <div className="space-y-2">
1133
+ <Label htmlFor="email">Email</Label>
1134
+ <Input id="email" value={email} onChange={(event) => setEmail(event.target.value)} type="email" />
1135
+ </div>
1136
+ <div className="space-y-2">
1137
+ <Label htmlFor="password">Password</Label>
1138
+ <Input id="password" value={password} onChange={(event) => setPassword(event.target.value)} type="password" />
1139
+ </div>
1140
+ {status ? <p className="text-sm text-muted-foreground">{status}</p> : null}
1141
+ <div className="flex flex-wrap gap-2">
1142
+ <Button disabled={pending} type="submit">{pending ? "Working..." : mode === "login" ? "Sign in" : "Sign up"}</Button>
1143
+ <Button type="button" variant="outline" onClick={() => setMode(mode === "login" ? "signup" : "login")}>
1144
+ {mode === "login" ? "Use sign up" : "Use sign in"}
1145
+ </Button>
1146
+ <Button type="button" variant="ghost" onClick={() => void loadSession()}>Session</Button>
1147
+ <Button type="button" variant="ghost" onClick={() => void logout()}>Logout</Button>
1148
+ </div>
1149
+ </form>
1150
+ </CardContent>
1151
+ </Card>
1152
+ </section>
1153
+ </main>
1154
+ );
1155
+ }
1156
+ `;
1157
+ }
1158
+ function hostedAuthTemplate(input) {
1159
+ return `"use client";
1160
+
1161
+ import * as React from "react";
1162
+ import { Badge } from "@/components/ui/badge";
1163
+ import { Button } from "@/components/ui/button";
1164
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1165
+ import { apiClient } from "@/lib/api";
1166
+
1167
+ export function ${input.componentName}() {
1168
+ const [status, setStatus] = React.useState<string>("Idle");
1169
+ const [pending, setPending] = React.useState(false);
1170
+
1171
+ async function refreshStatus() {
1172
+ setPending(true);
1173
+ const response = await apiClient.${input.key}.${input.statusCall}();
1174
+ if (response.error) {
1175
+ setStatus(response.error.message);
1176
+ } else {
1177
+ setStatus(response.data?.authenticated ? "Authenticated" : "No active session");
1178
+ }
1179
+ setPending(false);
1180
+ }
1181
+
1182
+ async function logout() {
1183
+ setPending(true);
1184
+ const response = await apiClient.${input.key}.${input.logoutCall}();
1185
+ if (response.data?.redirectTo) {
1186
+ window.location.assign(response.data.redirectTo);
1187
+ return;
1188
+ }
1189
+ setStatus(response.error?.message ?? "Signed out");
1190
+ setPending(false);
1191
+ }
1192
+
1193
+ return (
1194
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1195
+ <section className="mx-auto flex w-full max-w-3xl flex-col gap-6">
1196
+ <div className="space-y-3">
1197
+ <Badge variant="secondary">${input.provider}</Badge>
1198
+ <h1 className="text-3xl font-semibold tracking-normal">Auth</h1>
1199
+ </div>
1200
+
1201
+ <Card>
1202
+ <CardHeader>
1203
+ <CardTitle className="text-xl">${input.provider} session</CardTitle>
1204
+ <CardDescription>Hosted auth, account session, and sign-out controls.</CardDescription>
1205
+ </CardHeader>
1206
+ <CardContent className="space-y-4">
1207
+ <p className="rounded-md border bg-muted/30 px-3 py-2 text-sm">{status}</p>
1208
+ <div className="flex flex-wrap gap-2">
1209
+ <Button type="button" onClick={() => window.location.assign("${input.loginHref}")}>Sign in</Button>
1210
+ <Button type="button" variant="outline" onClick={() => window.location.assign("${input.signupHref}")}>Sign up</Button>
1211
+ <Button type="button" variant="ghost" disabled={pending} onClick={() => void refreshStatus()}>Refresh</Button>
1212
+ <Button type="button" variant="ghost" disabled={pending} onClick={() => void logout()}>Logout</Button>
1213
+ </div>
1214
+ </CardContent>
1215
+ </Card>
1216
+ </section>
1217
+ </main>
1218
+ );
1219
+ }
1220
+ `;
1221
+ }
1222
+ function authRouteShellTemplate(input) {
1223
+ return `"use client";
1224
+
1225
+ import { Badge } from "@/components/ui/badge";
1226
+ import { Button } from "@/components/ui/button";
1227
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1228
+
1229
+ export function ${input.componentName}() {
1230
+ return (
1231
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1232
+ <section className="mx-auto flex w-full max-w-3xl flex-col gap-6">
1233
+ <div className="space-y-3">
1234
+ <Badge variant="secondary">${input.provider}</Badge>
1235
+ <h1 className="text-3xl font-semibold tracking-normal">Auth</h1>
1236
+ </div>
1237
+
1238
+ <Card>
1239
+ <CardHeader>
1240
+ <CardTitle className="text-xl">${input.provider} routes</CardTitle>
1241
+ <CardDescription>Account entry points and session route.</CardDescription>
1242
+ </CardHeader>
1243
+ <CardContent className="flex flex-wrap gap-2">
1244
+ <Button type="button" onClick={() => window.location.assign("${input.signInHref}")}>Sign in</Button>
1245
+ <Button type="button" variant="outline" onClick={() => window.location.assign("${input.signUpHref}")}>Sign up</Button>
1246
+ <Button type="button" variant="ghost" onClick={() => window.location.assign("${input.sessionHref}")}>Session</Button>
1247
+ </CardContent>
1248
+ </Card>
1249
+ </section>
1250
+ </main>
1251
+ );
1252
+ }
1253
+ `;
1254
+ }
1255
+ function betterAuthClientTemplate() {
1256
+ return `import { createAuthClient } from "better-auth/react";
1257
+
1258
+ export const authClient = createAuthClient({
1259
+ baseURL: "",
1260
+ });
1261
+ `;
1262
+ }
1263
+ function betterAuthPanelTemplate() {
1264
+ return `"use client";
1265
+
1266
+ import * as React from "react";
1267
+ import { Badge } from "@/components/ui/badge";
1268
+ import { Button } from "@/components/ui/button";
1269
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1270
+ import { Input } from "@/components/ui/input";
1271
+ import { Label } from "@/components/ui/label";
1272
+ import { authClient } from "@/lib/auth-client";
1273
+
1274
+ type Mode = "sign-in" | "sign-up";
1275
+
1276
+ export function BetterAuthPanel() {
1277
+ const [mode, setMode] = React.useState<Mode>("sign-in");
1278
+ const [pending, setPending] = React.useState(false);
1279
+ const [message, setMessage] = React.useState("Ready");
1280
+ const [sessionEmail, setSessionEmail] = React.useState<string | null>(null);
1281
+
1282
+ async function submit(event: React.FormEvent<HTMLFormElement>) {
1283
+ event.preventDefault();
1284
+ setPending(true);
1285
+ setMessage(mode === "sign-in" ? "Signing in…" : "Creating account…");
1286
+
1287
+ const form = new FormData(event.currentTarget);
1288
+ const email = String(form.get("email") || "");
1289
+ const password = String(form.get("password") || "");
1290
+ const name = String(form.get("name") || "");
1291
+ try {
1292
+ const response =
1293
+ mode === "sign-in"
1294
+ ? await authClient.signIn.email({ email, password })
1295
+ : await authClient.signUp.email({ email, password, name });
1296
+
1297
+ if (response.error) {
1298
+ setMessage(response.error.message || "Authentication failed.");
1299
+ return;
1300
+ }
1301
+
1302
+ setSessionEmail(email);
1303
+ setMessage(mode === "sign-in" ? "Signed in." : "Account created.");
1304
+ } catch (cause) {
1305
+ setMessage(cause instanceof Error ? cause.message : "Could not reach the auth server.");
1306
+ } finally {
1307
+ setPending(false);
1308
+ }
1309
+ }
1310
+
1311
+ async function refreshSession() {
1312
+ setPending(true);
1313
+ try {
1314
+ const response = await authClient.getSession();
1315
+ setSessionEmail(response.data?.user.email || null);
1316
+ setMessage(response.error?.message || (response.data ? "Session active." : "No active session."));
1317
+ } catch (cause) {
1318
+ setMessage(cause instanceof Error ? cause.message : "Could not read the session.");
1319
+ } finally {
1320
+ setPending(false);
1321
+ }
1322
+ }
1323
+
1324
+ async function signOut() {
1325
+ setPending(true);
1326
+ try {
1327
+ const response = await authClient.signOut();
1328
+ if (response.error) {
1329
+ setMessage(response.error.message || "Could not sign out.");
1330
+ return;
1331
+ }
1332
+ setSessionEmail(null);
1333
+ setMessage("Signed out.");
1334
+ } catch (cause) {
1335
+ setMessage(cause instanceof Error ? cause.message : "Could not reach the auth server.");
1336
+ } finally {
1337
+ setPending(false);
1338
+ }
1339
+ }
1340
+
1341
+ return (
1342
+ <main className="min-h-screen bg-background px-5 py-12 text-foreground sm:px-8">
1343
+ <section className="mx-auto grid w-full max-w-5xl gap-8 lg:grid-cols-[1fr_420px] lg:items-start">
1344
+ <div className="space-y-5 py-4">
1345
+ <Badge variant="secondary">Better Auth × Farm.js</Badge>
1346
+ <div className="space-y-3">
1347
+ <h1 className="max-w-xl text-4xl font-semibold tracking-tight sm:text-5xl">
1348
+ Authentication that starts ready.
1349
+ </h1>
1350
+ <p className="max-w-xl text-base leading-7 text-muted-foreground">
1351
+ Test account creation, email sign-in, session reads, and sign-out through Farm’s
1352
+ generated Better Auth integration.
1353
+ </p>
1354
+ </div>
1355
+ <div aria-live="polite" className="border-l-2 border-primary pl-4 text-sm">
1356
+ <p className="font-medium">{message}</p>
1357
+ <p className="mt-1 text-muted-foreground">
1358
+ {sessionEmail ? \`Signed in as \${sessionEmail}\` : "No authenticated user"}
1359
+ </p>
1360
+ </div>
1361
+ </div>
1362
+
1363
+ <Card>
1364
+ <CardHeader>
1365
+ <CardTitle>{mode === "sign-in" ? "Welcome back" : "Create an account"}</CardTitle>
1366
+ <CardDescription>
1367
+ {mode === "sign-in"
1368
+ ? "Enter your credentials to start a secure session."
1369
+ : "Use an email and password to create your local account."}
1370
+ </CardDescription>
1371
+ </CardHeader>
1372
+ <CardContent>
1373
+ <form className="space-y-4" onSubmit={submit}>
1374
+ {mode === "sign-up" ? (
1375
+ <div className="space-y-2">
1376
+ <Label htmlFor="name">Name</Label>
1377
+ <Input autoComplete="name" id="name" name="name" required />
1378
+ </div>
1379
+ ) : null}
1380
+ <div className="space-y-2">
1381
+ <Label htmlFor="email">Email</Label>
1382
+ <Input autoComplete="email" id="email" name="email" required type="email" />
1383
+ </div>
1384
+ <div className="space-y-2">
1385
+ <Label htmlFor="password">Password</Label>
1386
+ <Input
1387
+ autoComplete={mode === "sign-in" ? "current-password" : "new-password"}
1388
+ id="password"
1389
+ minLength={8}
1390
+ name="password"
1391
+ required
1392
+ type="password"
1393
+ />
1394
+ </div>
1395
+ <Button className="w-full" disabled={pending} type="submit">
1396
+ {pending ? "Working…" : mode === "sign-in" ? "Sign in" : "Create account"}
1397
+ </Button>
1398
+ </form>
1399
+
1400
+ <div className="mt-4 grid gap-2 sm:grid-cols-2">
1401
+ <Button
1402
+ disabled={pending}
1403
+ type="button"
1404
+ variant="outline"
1405
+ onClick={() => {
1406
+ setMode(mode === "sign-in" ? "sign-up" : "sign-in");
1407
+ setMessage("Ready");
1408
+ }}
1409
+ >
1410
+ {mode === "sign-in" ? "Create account" : "Use sign in"}
1411
+ </Button>
1412
+ <Button disabled={pending} type="button" variant="outline" onClick={() => void refreshSession()}>
1413
+ Check session
1414
+ </Button>
1415
+ </div>
1416
+ <Button
1417
+ className="mt-2 w-full"
1418
+ disabled={pending || !sessionEmail}
1419
+ type="button"
1420
+ variant="ghost"
1421
+ onClick={() => void signOut()}
1422
+ >
1423
+ Sign out
1424
+ </Button>
1425
+ </CardContent>
1426
+ </Card>
1427
+ </section>
1428
+ </main>
1429
+ );
1430
+ }
1431
+ `;
1432
+ }
1433
+ function resendEmailTemplate(key) {
1434
+ return `"use client";
1435
+
1436
+ import * as React from "react";
1437
+ import { Badge } from "@/components/ui/badge";
1438
+ import { Button } from "@/components/ui/button";
1439
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1440
+ import { Input } from "@/components/ui/input";
1441
+ import { Label } from "@/components/ui/label";
1442
+ import { apiClient } from "@/lib/api";
1443
+
1444
+ export function ResendEmailConsole() {
1445
+ const [to, setTo] = React.useState("");
1446
+ const [name, setName] = React.useState("Ada");
1447
+ const [templateId, setTemplateId] = React.useState("welcome");
1448
+ const [status, setStatus] = React.useState("Idle");
1449
+ const [previewHtml, setPreviewHtml] = React.useState("");
1450
+
1451
+ async function loadTemplates() {
1452
+ const response = await apiClient.${key}.templates.get();
1453
+ setStatus(response.error ? response.error.message : "Templates: " + (response.data ?? []).map((item) => item.id).join(", "));
1454
+ }
1455
+
1456
+ async function preview() {
1457
+ const response = await apiClient.${key}.preview.post({
1458
+ body: {
1459
+ templateId,
1460
+ data: { name },
1461
+ },
1462
+ });
1463
+ if (response.error) {
1464
+ setStatus(response.error.message);
1465
+ return;
1466
+ }
1467
+ setPreviewHtml(response.data?.html ?? "");
1468
+ setStatus(response.data?.subject ?? "Preview loaded");
1469
+ }
1470
+
1471
+ async function send() {
1472
+ const response = await apiClient.${key}.send.post({
1473
+ body: {
1474
+ templateId,
1475
+ to,
1476
+ data: { name },
1477
+ },
1478
+ });
1479
+ setStatus(response.error ? response.error.message : "Sent " + (response.data?.id ?? "email"));
1480
+ }
1481
+
1482
+ return (
1483
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1484
+ <section className="mx-auto flex w-full max-w-3xl flex-col gap-6">
1485
+ <div className="space-y-3">
1486
+ <Badge variant="secondary">Resend</Badge>
1487
+ <h1 className="text-3xl font-semibold tracking-normal">Email console</h1>
1488
+ </div>
1489
+ <Card>
1490
+ <CardHeader>
1491
+ <CardTitle className="text-xl">Send template</CardTitle>
1492
+ <CardDescription>Template previews and delivery controls.</CardDescription>
1493
+ </CardHeader>
1494
+ <CardContent className="space-y-4">
1495
+ <div className="grid gap-4 sm:grid-cols-3">
1496
+ <div className="space-y-2">
1497
+ <Label htmlFor="templateId">Template</Label>
1498
+ <Input id="templateId" value={templateId} onChange={(event) => setTemplateId(event.target.value)} />
1499
+ </div>
1500
+ <div className="space-y-2">
1501
+ <Label htmlFor="to">To</Label>
1502
+ <Input id="to" value={to} onChange={(event) => setTo(event.target.value)} />
1503
+ </div>
1504
+ <div className="space-y-2">
1505
+ <Label htmlFor="name">Name</Label>
1506
+ <Input id="name" value={name} onChange={(event) => setName(event.target.value)} />
1507
+ </div>
1508
+ </div>
1509
+ <p className="rounded-md border bg-muted/30 px-3 py-2 text-sm">{status}</p>
1510
+ {previewHtml ? <div className="max-h-64 overflow-auto rounded-md border p-3 text-sm" dangerouslySetInnerHTML={{ __html: previewHtml }} /> : null}
1511
+ <div className="flex flex-wrap gap-2">
1512
+ <Button type="button" variant="outline" onClick={() => void loadTemplates()}>Templates</Button>
1513
+ <Button type="button" variant="outline" onClick={() => void preview()}>Preview</Button>
1514
+ <Button type="button" onClick={() => void send()}>Send</Button>
1515
+ </div>
1516
+ </CardContent>
1517
+ </Card>
1518
+ </section>
1519
+ </main>
1520
+ );
1521
+ }
1522
+ `;
1523
+ }
1524
+ function jobsConsoleTemplate(key, label, provider) {
1525
+ return `"use client";
1526
+
1527
+ import * as React from "react";
1528
+ import { Badge } from "@/components/ui/badge";
1529
+ import { Button } from "@/components/ui/button";
1530
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1531
+ import { Input } from "@/components/ui/input";
1532
+ import { Label } from "@/components/ui/label";
1533
+ import { apiClient } from "@/lib/api";
1534
+
1535
+ type JobTask = {
1536
+ key: string;
1537
+ description?: string | null;
1538
+ };
1539
+
1540
+ export function ${`${pascalCase(provider)}JobsConsole`}() {
1541
+ const [tasks, setTasks] = React.useState<JobTask[]>([]);
1542
+ const [taskKey, setTaskKey] = React.useState("");
1543
+ const [runId, setRunId] = React.useState("");
1544
+ const [status, setStatus] = React.useState("Idle");
1545
+
1546
+ async function loadTasks() {
1547
+ const response = await apiClient.${key}.tasks.list();
1548
+ if (response.error) {
1549
+ setStatus(response.error.message);
1550
+ return;
1551
+ }
1552
+ const nextTasks = Array.from(response.data ?? []);
1553
+ setTasks(nextTasks);
1554
+ setTaskKey(nextTasks[0]?.key ?? "");
1555
+ setStatus(nextTasks.length ? "Tasks loaded" : "No tasks registered yet");
1556
+ }
1557
+
1558
+ async function triggerTask() {
1559
+ const task = (apiClient.${key} as Record<string, any>)[taskKey];
1560
+ if (!task?.trigger) {
1561
+ setStatus("Select a task first.");
1562
+ return;
1563
+ }
1564
+ const response = await task.trigger({ body: { input: {} } });
1565
+ setStatus(response.error ? response.error.message : "Triggered " + (response.data?.runId ?? response.data?.id ?? taskKey));
1566
+ }
1567
+
1568
+ async function checkStatus() {
1569
+ const task = (apiClient.${key} as Record<string, any>)[taskKey];
1570
+ if (!task?.status || !runId) {
1571
+ setStatus("Enter a task and run id.");
1572
+ return;
1573
+ }
1574
+ const response = await task.status({ query: { runId } });
1575
+ setStatus(response.error ? response.error.message : JSON.stringify(response.data));
1576
+ }
1577
+
1578
+ return (
1579
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1580
+ <section className="mx-auto flex w-full max-w-4xl flex-col gap-6">
1581
+ <div className="space-y-3">
1582
+ <Badge variant="secondary">${label}</Badge>
1583
+ <h1 className="text-3xl font-semibold tracking-normal">Jobs console</h1>
1584
+ </div>
1585
+ <Card>
1586
+ <CardHeader>
1587
+ <CardTitle className="text-xl">Tasks</CardTitle>
1588
+ <CardDescription>Task runs and status checks.</CardDescription>
1589
+ </CardHeader>
1590
+ <CardContent className="space-y-4">
1591
+ <div className="grid gap-4 sm:grid-cols-2">
1592
+ <div className="space-y-2">
1593
+ <Label htmlFor="taskKey">Task key</Label>
1594
+ <Input id="taskKey" value={taskKey} onChange={(event) => setTaskKey(event.target.value)} />
1595
+ </div>
1596
+ <div className="space-y-2">
1597
+ <Label htmlFor="runId">Run id</Label>
1598
+ <Input id="runId" value={runId} onChange={(event) => setRunId(event.target.value)} />
1599
+ </div>
1600
+ </div>
1601
+ <p className="rounded-md border bg-muted/30 px-3 py-2 text-sm">{status}</p>
1602
+ <div className="flex flex-wrap gap-2">
1603
+ <Button type="button" variant="outline" onClick={() => void loadTasks()}>Load tasks</Button>
1604
+ <Button type="button" onClick={() => void triggerTask()}>Trigger</Button>
1605
+ <Button type="button" variant="ghost" onClick={() => void checkStatus()}>Status</Button>
1606
+ </div>
1607
+ {tasks.length ? (
1608
+ <div className="grid gap-2">
1609
+ {tasks.map((task) => (
1610
+ <button key={task.key} className="rounded-md border px-3 py-2 text-left text-sm" onClick={() => setTaskKey(task.key)} type="button">
1611
+ {task.key}
1612
+ </button>
1613
+ ))}
1614
+ </div>
1615
+ ) : null}
1616
+ </CardContent>
1617
+ </Card>
1618
+ </section>
1619
+ </main>
1620
+ );
1621
+ }
1622
+ `;
1623
+ }
1624
+ function unkeyApiKeysTemplate(key) {
1625
+ return `"use client";
1626
+
1627
+ import * as React from "react";
1628
+ import { Badge } from "@/components/ui/badge";
1629
+ import { Button } from "@/components/ui/button";
1630
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1631
+ import { Input } from "@/components/ui/input";
1632
+ import { Label } from "@/components/ui/label";
1633
+ import { apiClient } from "@/lib/api";
1634
+
1635
+ export function UnkeyApiKeysConsole() {
1636
+ const [name, setName] = React.useState("Development key");
1637
+ const [prefix, setPrefix] = React.useState("farm");
1638
+ const [apiKey, setApiKey] = React.useState("");
1639
+ const [status, setStatus] = React.useState("Idle");
1640
+
1641
+ async function createKey() {
1642
+ const response = await apiClient.${key}.createKey.post({
1643
+ body: {
1644
+ name,
1645
+ prefix,
1646
+ },
1647
+ });
1648
+ if (response.error) {
1649
+ setStatus(response.error.message);
1650
+ return;
1651
+ }
1652
+ setApiKey(response.data?.key ?? "");
1653
+ setStatus("Created " + (response.data?.keyId ?? "key"));
1654
+ }
1655
+
1656
+ async function verifyKey() {
1657
+ const response = await apiClient.${key}.verifyKey.post({
1658
+ body: {
1659
+ key: apiKey,
1660
+ },
1661
+ });
1662
+ setStatus(response.error ? response.error.message : response.data?.valid ? "Valid key" : "Invalid key");
1663
+ }
1664
+
1665
+ return (
1666
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1667
+ <section className="mx-auto flex w-full max-w-3xl flex-col gap-6">
1668
+ <div className="space-y-3">
1669
+ <Badge variant="secondary">Unkey</Badge>
1670
+ <h1 className="text-3xl font-semibold tracking-normal">API keys</h1>
1671
+ </div>
1672
+ <Card>
1673
+ <CardHeader>
1674
+ <CardTitle className="text-xl">Key console</CardTitle>
1675
+ <CardDescription>API key lifecycle controls.</CardDescription>
1676
+ </CardHeader>
1677
+ <CardContent className="space-y-4">
1678
+ <div className="grid gap-4 sm:grid-cols-2">
1679
+ <div className="space-y-2">
1680
+ <Label htmlFor="name">Name</Label>
1681
+ <Input id="name" value={name} onChange={(event) => setName(event.target.value)} />
1682
+ </div>
1683
+ <div className="space-y-2">
1684
+ <Label htmlFor="prefix">Prefix</Label>
1685
+ <Input id="prefix" value={prefix} onChange={(event) => setPrefix(event.target.value)} />
1686
+ </div>
1687
+ </div>
1688
+ <div className="space-y-2">
1689
+ <Label htmlFor="apiKey">API key</Label>
1690
+ <Input id="apiKey" value={apiKey} onChange={(event) => setApiKey(event.target.value)} />
1691
+ </div>
1692
+ <p className="rounded-md border bg-muted/30 px-3 py-2 text-sm">{status}</p>
1693
+ <div className="flex flex-wrap gap-2">
1694
+ <Button type="button" onClick={() => void createKey()}>Create key</Button>
1695
+ <Button type="button" variant="outline" onClick={() => void verifyKey()}>Verify</Button>
1696
+ </div>
1697
+ </CardContent>
1698
+ </Card>
1699
+ </section>
1700
+ </main>
1701
+ );
1702
+ }
1703
+ `;
1704
+ }
1705
+ function pascalCase(input) {
1706
+ return input.split(/[^A-Za-z0-9]+/g).filter(Boolean).map((part) => `${part.charAt(0).toUpperCase()}${part.slice(1)}`).join("");
1707
+ }
1708
+ function kebabCase(input) {
1709
+ return input.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[^A-Za-z0-9]+/g, "-").replace(/^-+|-+$/g, "").toLowerCase();
1710
+ }
1711
+ function hasPackageDependency$1(manifest, dependency) {
1712
+ return dependency in (manifest.dependencies || {}) || dependency in (manifest.devDependencies || {}) || dependency in (manifest.peerDependencies || {}) || dependency in (manifest.optionalDependencies || {});
1713
+ }
1714
+ function readObject(value) {
1715
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1716
+ }
1717
+ function pushResultPath(list, filePath) {
1718
+ if (!list.includes(filePath)) list.push(filePath);
1719
+ }
1720
+ //#endregion
1721
+ //#region src/add-integration.ts
1722
+ const PROVIDERS = [
1723
+ {
1724
+ provider: "ai",
1725
+ aliases: [
1726
+ "ai-sdk",
1727
+ "vercel-ai",
1728
+ "vercel-ai-sdk",
1729
+ "chat"
1730
+ ],
1731
+ defaultKey: "chat",
1732
+ fileName: "chat",
1733
+ exportName: "POST",
1734
+ description: "Vercel AI SDK chat route",
1735
+ env: ["AI_GATEWAY_API_KEY"],
1736
+ notes: [
1737
+ "Use @ai-sdk/react useChat with api: \"/api/chat\" on the client.",
1738
+ "Replace model with any AI SDK provider model or Vercel AI Gateway model id.",
1739
+ "No farm.config integration wiring is required for this route."
1740
+ ],
1741
+ ui: aiChatUIFeature(),
1742
+ template: () => `import { aiChatRoute } from "@farm.js/integrations/ai";
1743
+
1744
+ export const POST = aiChatRoute({
1745
+ model: "openai/gpt-4o-mini",
1746
+ system: "You are a helpful assistant.",
1747
+ });
1748
+ `
1749
+ },
1750
+ {
1751
+ provider: "stripe",
1752
+ aliases: [
1753
+ "billing-stripe",
1754
+ "payments",
1755
+ "stripe-billing"
1756
+ ],
1757
+ defaultKey: "billing",
1758
+ fileName: "stripe",
1759
+ exportName: "stripeIntegration",
1760
+ description: "Stripe billing and checkout routes",
1761
+ env: ["STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET"],
1762
+ template: () => `import { stripe } from "@farm.js/integrations/stripe";
1763
+
1764
+ export const stripeIntegration = stripe({
1765
+ secretKey: process.env.STRIPE_SECRET_KEY,
1766
+ webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
1767
+ products: [],
1768
+ log(event) {
1769
+ console.log("[stripe]", event.phase, event.route?.path || "none");
1770
+ },
1771
+ });
1772
+ `,
1773
+ ui: stripeBillingUIFeature()
1774
+ },
1775
+ {
1776
+ provider: "supabase",
1777
+ aliases: ["auth-supabase", "supabase-auth"],
1778
+ defaultKey: "auth",
1779
+ fileName: "supabase",
1780
+ exportName: "supabaseIntegration",
1781
+ description: "Supabase auth routes and middleware",
1782
+ env: [
1783
+ "SUPABASE_URL",
1784
+ "SUPABASE_ANON_KEY",
1785
+ "APP_BASE_URL"
1786
+ ],
1787
+ ui: supabaseAuthUIFeature(),
1788
+ template: () => `import { supabase } from "@farm.js/integrations/supabase";
1789
+
1790
+ export const supabaseIntegration = supabase({
1791
+ callbackUrl: \`\${process.env.APP_BASE_URL || "http://localhost:3000"}/auth/callback\`,
1792
+ protectedRoutes: ["/dashboard(.*)"],
1793
+ pages: {
1794
+ signIn: "/sign-in",
1795
+ signUp: "/sign-up",
1796
+ },
1797
+ log(event) {
1798
+ console.log("[supabase]", event.phase, event.route?.path || "none");
1799
+ },
1800
+ });
1801
+ `
1802
+ },
1803
+ {
1804
+ provider: "workos",
1805
+ aliases: ["auth-workos", "workos-auth"],
1806
+ defaultKey: "auth",
1807
+ fileName: "workos",
1808
+ exportName: "workosIntegration",
1809
+ description: "WorkOS auth routes and protected route middleware",
1810
+ env: [
1811
+ "WORKOS_CLIENT_ID",
1812
+ "WORKOS_API_KEY",
1813
+ "WORKOS_COOKIE_PASSWORD"
1814
+ ],
1815
+ ui: workosAuthUIFeature(),
1816
+ template: () => `import { workos } from "@farm.js/integrations/workos";
1817
+
1818
+ export const workosIntegration = workos({
1819
+ protectedRoutes: ["/dashboard(.*)"],
1820
+ log(event) {
1821
+ console.log("[workos]", event.phase, event.route?.path || "none");
1822
+ },
1823
+ });
1824
+ `
1825
+ },
1826
+ {
1827
+ provider: "auth0",
1828
+ aliases: ["auth-auth0", "auth0-auth"],
1829
+ defaultKey: "auth",
1830
+ fileName: "auth0",
1831
+ exportName: "auth0Integration",
1832
+ description: "Auth0 login, callback, logout, and profile routes",
1833
+ env: [
1834
+ "AUTH0_DOMAIN",
1835
+ "AUTH0_CLIENT_ID",
1836
+ "AUTH0_CLIENT_SECRET",
1837
+ "AUTH0_SECRET"
1838
+ ],
1839
+ ui: auth0AuthUIFeature(),
1840
+ template: () => `import { auth0 } from "@farm.js/integrations/auth0";
1841
+
1842
+ export const auth0Integration = auth0({
1843
+ callbackUrl: \`\${process.env.APP_BASE_URL || "http://localhost:3000"}/auth/callback\`,
1844
+ protectedRoutes: ["/dashboard(.*)"],
1845
+ log(event) {
1846
+ console.log("[auth0]", event.phase, event.route?.path || "none");
1847
+ },
1848
+ });
1849
+ `
1850
+ },
1851
+ {
1852
+ provider: "clerk",
1853
+ aliases: ["auth-clerk", "clerk-auth"],
1854
+ defaultKey: "auth",
1855
+ fileName: "clerk",
1856
+ exportName: "clerkIntegration",
1857
+ description: "Clerk auth provider and protected route middleware",
1858
+ env: ["NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY", "CLERK_SECRET_KEY"],
1859
+ ui: clerkAuthUIFeature(),
1860
+ template: () => `import { clerk } from "@farm.js/integrations/clerk";
1861
+
1862
+ export const clerkIntegration = clerk({
1863
+ signInUrl: "/sign-in",
1864
+ signUpUrl: "/sign-up",
1865
+ protectedRoutes: ["/dashboard(.*)"],
1866
+ log(event) {
1867
+ console.log("[clerk]", event.phase, event.route?.path || "none");
1868
+ },
1869
+ });
1870
+ `
1871
+ },
1872
+ {
1873
+ provider: "resend",
1874
+ aliases: ["email", "resend-email"],
1875
+ defaultKey: "email",
1876
+ fileName: "resend",
1877
+ exportName: "resendIntegration",
1878
+ description: "Resend email send, preview, schedule, and webhook routes",
1879
+ env: [
1880
+ "RESEND_API_KEY",
1881
+ "RESEND_FROM_EMAIL",
1882
+ "RESEND_WEBHOOK_SECRET"
1883
+ ],
1884
+ ui: resendEmailUIFeature(),
1885
+ template: () => `import { createElement } from "react";
1886
+ import { resend, template } from "@farm.js/integrations/email";
1887
+
1888
+ function WelcomeEmail(props: { name: string }) {
1889
+ return createElement("div", null, \`Welcome \${props.name}\`);
1890
+ }
1891
+
1892
+ WelcomeEmail.PreviewProps = {
1893
+ name: "Ada",
1894
+ };
1895
+
1896
+ export const emailTemplates = {
1897
+ welcome: template(WelcomeEmail, {
1898
+ subject: ({ name }) => \`Welcome, \${name}\`,
1899
+ previewText: () => "Welcome to the app",
1900
+ }),
1901
+ } as const;
1902
+
1903
+ export const resendIntegration = resend({
1904
+ apiKey: process.env.RESEND_API_KEY,
1905
+ defaults: {
1906
+ from: process.env.RESEND_FROM_EMAIL,
1907
+ replyTo: process.env.RESEND_REPLY_TO_EMAIL ?? process.env.RESEND_FROM_EMAIL,
1908
+ },
1909
+ templates: emailTemplates,
1910
+ webhooks: process.env.RESEND_WEBHOOK_SECRET
1911
+ ? {
1912
+ secret: process.env.RESEND_WEBHOOK_SECRET,
1913
+ }
1914
+ : undefined,
1915
+ log(event) {
1916
+ console.log("[resend]", event.phase, event.route?.path || "none");
1917
+ },
1918
+ });
1919
+ `
1920
+ },
1921
+ {
1922
+ provider: "jobs-inngest",
1923
+ aliases: ["inngest", "jobs"],
1924
+ defaultKey: "jobs",
1925
+ fileName: "jobs-inngest",
1926
+ exportName: "jobsIntegration",
1927
+ description: "Jobs integration backed by Inngest",
1928
+ env: [
1929
+ "INNGEST_APP_ID",
1930
+ "INNGEST_EVENT_KEY",
1931
+ "INNGEST_SIGNING_KEY"
1932
+ ],
1933
+ notes: ["Add tasks to jobTasks before using the generated jobs API."],
1934
+ ui: jobsUIFeature("inngest"),
1935
+ template: () => `import { defineTasks, inngest, jobs } from "@farm.js/integrations/jobs";
1936
+
1937
+ export const jobTasks = defineTasks({});
1938
+
1939
+ export const jobsIntegration = jobs({
1940
+ runtime: inngest({
1941
+ appId: process.env.INNGEST_APP_ID,
1942
+ eventKey: process.env.INNGEST_EVENT_KEY,
1943
+ signingKey: process.env.INNGEST_SIGNING_KEY,
1944
+ }),
1945
+ tasks: jobTasks,
1946
+ log(event) {
1947
+ console.log("[jobs:inngest]", event.phase, event.route?.path || "none");
1948
+ },
1949
+ });
1950
+ `
1951
+ },
1952
+ {
1953
+ provider: "jobs-trigger",
1954
+ aliases: [
1955
+ "trigger",
1956
+ "trigger-dev",
1957
+ "jobs-triggerdev"
1958
+ ],
1959
+ defaultKey: "jobs",
1960
+ fileName: "jobs-trigger",
1961
+ exportName: "jobsIntegration",
1962
+ description: "Jobs integration backed by Trigger.dev",
1963
+ env: [
1964
+ "TRIGGER_PROJECT_REF",
1965
+ "TRIGGER_SECRET_KEY",
1966
+ "TRIGGER_WEBHOOK_SECRET"
1967
+ ],
1968
+ notes: ["Add tasks to jobTasks before using the generated jobs API."],
1969
+ ui: jobsUIFeature("trigger"),
1970
+ template: () => `import { defineTasks, jobs, trigger } from "@farm.js/integrations/jobs";
1971
+
1972
+ export const jobTasks = defineTasks({});
1973
+
1974
+ export const jobsIntegration = jobs({
1975
+ runtime: trigger({
1976
+ projectRef: process.env.TRIGGER_PROJECT_REF,
1977
+ apiKey: process.env.TRIGGER_SECRET_KEY,
1978
+ webhookSecret: process.env.TRIGGER_WEBHOOK_SECRET,
1979
+ }),
1980
+ tasks: jobTasks,
1981
+ log(event) {
1982
+ console.log("[jobs:trigger]", event.phase, event.route?.path || "none");
1983
+ },
1984
+ });
1985
+ `
1986
+ },
1987
+ {
1988
+ provider: "polar",
1989
+ aliases: ["polar-billing", "billing-polar"],
1990
+ defaultKey: "billing",
1991
+ fileName: "polar",
1992
+ exportName: "polarIntegration",
1993
+ description: "Polar billing and checkout routes",
1994
+ env: [
1995
+ "POLAR_ACCESS_TOKEN",
1996
+ "POLAR_WEBHOOK_SECRET",
1997
+ "APP_BASE_URL"
1998
+ ],
1999
+ notes: ["Replace resolveBillingOwner with your app user or organization lookup."],
2000
+ ui: polarBillingUIFeature(),
2001
+ template: () => `import type { FarmIntegrationHandlerContext } from "@farm.js/core";
2002
+ import { polar } from "@farm.js/integrations/polar";
2003
+
2004
+ async function resolveBillingOwner(_context: FarmIntegrationHandlerContext) {
2005
+ throw new Error("Configure Polar billing owner resolution for your app.");
2006
+ }
2007
+
2008
+ export const polarIntegration = polar({
2009
+ accessToken: process.env.POLAR_ACCESS_TOKEN,
2010
+ server: (process.env.POLAR_SERVER as "sandbox" | "production" | undefined) ?? "sandbox",
2011
+ appBaseUrl: process.env.APP_BASE_URL,
2012
+ webhooks: process.env.POLAR_WEBHOOK_SECRET
2013
+ ? {
2014
+ secret: process.env.POLAR_WEBHOOK_SECRET,
2015
+ }
2016
+ : undefined,
2017
+ billing: {
2018
+ resolveOwner: resolveBillingOwner,
2019
+ plans: {},
2020
+ products: {},
2021
+ },
2022
+ log(event) {
2023
+ console.log("[polar]", event.phase, event.route?.path || "none");
2024
+ },
2025
+ });
2026
+ `
2027
+ },
2028
+ {
2029
+ provider: "autumn",
2030
+ aliases: ["autumn-billing", "billing-autumn"],
2031
+ defaultKey: "billing",
2032
+ fileName: "autumn",
2033
+ exportName: "autumnIntegration",
2034
+ description: "Autumn billing and checkout routes",
2035
+ env: [
2036
+ "AUTUMN_SECRET_KEY",
2037
+ "AUTUMN_WEBHOOK_SECRET",
2038
+ "APP_BASE_URL"
2039
+ ],
2040
+ notes: ["Replace resolveBillingOwner with your app user or organization lookup."],
2041
+ ui: autumnBillingUIFeature(),
2042
+ template: () => `import type { FarmIntegrationHandlerContext } from "@farm.js/core";
2043
+ import { autumn } from "@farm.js/integrations/autumn";
2044
+
2045
+ async function resolveBillingOwner(_context: FarmIntegrationHandlerContext) {
2046
+ throw new Error("Configure Autumn billing owner resolution for your app.");
2047
+ }
2048
+
2049
+ export const autumnIntegration = autumn({
2050
+ secretKey: process.env.AUTUMN_SECRET_KEY,
2051
+ appBaseUrl: process.env.APP_BASE_URL,
2052
+ webhooks: process.env.AUTUMN_WEBHOOK_SECRET
2053
+ ? {
2054
+ secret: process.env.AUTUMN_WEBHOOK_SECRET,
2055
+ }
2056
+ : undefined,
2057
+ billing: {
2058
+ resolveOwner: resolveBillingOwner,
2059
+ plans: {},
2060
+ products: {},
2061
+ },
2062
+ log(event) {
2063
+ console.log("[autumn]", event.phase, event.route?.path || "none");
2064
+ },
2065
+ });
2066
+ `
2067
+ },
2068
+ {
2069
+ provider: "better-auth",
2070
+ aliases: ["betterauth", "auth-better-auth"],
2071
+ defaultKey: "auth",
2072
+ fileName: "better-auth",
2073
+ exportName: "betterAuthIntegration",
2074
+ description: "Better Auth route adapter",
2075
+ env: [
2076
+ "BETTER_AUTH_SECRET",
2077
+ "BETTER_AUTH_URL",
2078
+ "BETTER_AUTH_DATABASE_PATH"
2079
+ ],
2080
+ dependencies: {
2081
+ "better-auth": "^1.5.5",
2082
+ "better-sqlite3": "^12.6.2"
2083
+ },
2084
+ devDependencies: { "@types/better-sqlite3": "^7.6.13" },
2085
+ notes: ["The generated SQLite database is intended for local development. Configure a persistent production database before deploying.", "Set BETTER_AUTH_SECRET to a high-entropy value of at least 32 characters."],
2086
+ setupFiles: [
2087
+ {
2088
+ path: "src/lib/auth.ts",
2089
+ source: () => `import Database from "better-sqlite3";
2090
+ import { betterAuth as createBetterAuth } from "better-auth";
2091
+ import { getMigrations } from "better-auth/db/migration";
2092
+
2093
+ const baseURL = process.env.BETTER_AUTH_URL || "http://localhost:3000";
2094
+ export const auth = createBetterAuth({
2095
+ database: new Database(process.env.BETTER_AUTH_DATABASE_PATH || "better-auth.sqlite"),
2096
+ secret: process.env.BETTER_AUTH_SECRET,
2097
+ baseURL,
2098
+ trustedOrigins: [baseURL],
2099
+ emailAndPassword: {
2100
+ enabled: true,
2101
+ },
2102
+ });
2103
+
2104
+ const migrations = await getMigrations(auth.options);
2105
+ await migrations.runMigrations();
2106
+ `
2107
+ },
2108
+ {
2109
+ path: ".env.example",
2110
+ merge: "lines",
2111
+ source: () => `BETTER_AUTH_SECRET=replace-with-at-least-32-random-characters
2112
+ BETTER_AUTH_URL=http://localhost:3000
2113
+ BETTER_AUTH_DATABASE_PATH=better-auth.sqlite
2114
+ `
2115
+ },
2116
+ {
2117
+ path: ".gitignore",
2118
+ merge: "lines",
2119
+ source: () => `better-auth.sqlite
2120
+ better-auth.sqlite-shm
2121
+ better-auth.sqlite-wal
2122
+ `
2123
+ }
2124
+ ],
2125
+ ui: betterAuthUIFeature(),
2126
+ template: () => `import { betterAuth } from "@farm.js/integrations/better-auth";
2127
+ import { auth } from "../auth.ts";
2128
+
2129
+ export const betterAuthIntegration = betterAuth({
2130
+ instance: auth,
2131
+ log(event) {
2132
+ console.log("[better-auth]", event.phase, event.route?.path || "none");
2133
+ },
2134
+ });
2135
+ `
2136
+ },
2137
+ {
2138
+ provider: "authjs",
2139
+ aliases: [
2140
+ "auth-js",
2141
+ "nextauth",
2142
+ "next-auth"
2143
+ ],
2144
+ defaultKey: "auth",
2145
+ fileName: "authjs",
2146
+ exportName: "authjsIntegration",
2147
+ description: "Auth.js route adapter",
2148
+ env: [],
2149
+ notes: ["This template expects src/lib/auth.ts to export an Auth.js instance named auth."],
2150
+ ui: authjsUIFeature(),
2151
+ template: () => `import { authjs } from "@farm.js/integrations/authjs";
2152
+ import { auth } from "../auth.ts";
2153
+
2154
+ export const authjsIntegration = authjs({
2155
+ instance: auth,
2156
+ log(event) {
2157
+ console.log("[authjs]", event.phase, event.route?.path || "none");
2158
+ },
2159
+ });
2160
+ `
2161
+ },
2162
+ {
2163
+ provider: "unkey",
2164
+ aliases: [
2165
+ "api-keys",
2166
+ "apikeys",
2167
+ "keys",
2168
+ "unkey-api-keys"
2169
+ ],
2170
+ defaultKey: "apiKeys",
2171
+ fileName: "unkey",
2172
+ exportName: "unkeyIntegration",
2173
+ description: "Unkey API key creation, verification, and route protection",
2174
+ env: [
2175
+ "UNKEY_ROOT_KEY",
2176
+ "UNKEY_API_ID",
2177
+ "UNKEY_BASE_URL"
2178
+ ],
2179
+ ui: unkeyApiKeysUIFeature(),
2180
+ template: () => `import { unkey } from "@farm.js/integrations/unkey";
2181
+
2182
+ export const unkeyIntegration = unkey({
2183
+ rootKey: process.env.UNKEY_ROOT_KEY,
2184
+ apiId: process.env.UNKEY_API_ID,
2185
+ baseUrl: process.env.UNKEY_BASE_URL,
2186
+ protectedRoutes: ["/api/protected(.*)"],
2187
+ log(event) {
2188
+ console.log("[unkey]", event.phase, event.route?.path || "none");
2189
+ },
2190
+ });
2191
+ `
2192
+ }
2193
+ ];
2194
+ function listFarmIntegrationProviders() {
2195
+ return PROVIDERS.map((provider) => ({
2196
+ name: provider.provider,
2197
+ aliases: [...provider.aliases],
2198
+ defaultKey: provider.defaultKey,
2199
+ description: provider.description,
2200
+ env: [...provider.env],
2201
+ ui: provider.ui ? {
2202
+ feature: provider.ui.name,
2203
+ description: provider.ui.description,
2204
+ components: [...provider.ui.components]
2205
+ } : void 0
2206
+ }));
2207
+ }
2208
+ async function addFarmIntegration(options) {
2209
+ const root = path.resolve(options.root || process.cwd());
2210
+ const definition = resolveProvider(options.provider);
2211
+ if (definition.provider === "ai") return addAIRouteIntegration({
2212
+ root,
2213
+ definition,
2214
+ routeFile: options.routeFile,
2215
+ ui: options.ui,
2216
+ skipPackageJson: options.skipPackageJson,
2217
+ dryRun: options.dryRun,
2218
+ force: options.force
2219
+ });
2220
+ const key = options.key || definition.defaultKey;
2221
+ assertValidIntegrationKey(key);
2222
+ const registryFile = path.resolve(root, options.integrationsFile || path.join("src", "lib", "integrations.ts"));
2223
+ const integrationFile = path.join(path.dirname(registryFile), "integrations", `${definition.fileName}.ts`);
2224
+ const result = {
2225
+ provider: definition.provider,
2226
+ key,
2227
+ mode: "integration",
2228
+ integrationFile,
2229
+ registryFile,
2230
+ created: [],
2231
+ updated: [],
2232
+ skipped: [],
2233
+ env: [...definition.env],
2234
+ notes: [...definition.notes || []]
2235
+ };
2236
+ await writeIntegrationComponent({
2237
+ path: integrationFile,
2238
+ definition,
2239
+ force: options.force,
2240
+ dryRun: options.dryRun,
2241
+ result
2242
+ });
2243
+ await writeIntegrationSetupFiles({
2244
+ root,
2245
+ definition,
2246
+ force: options.force,
2247
+ dryRun: options.dryRun,
2248
+ result
2249
+ });
2250
+ await writeIntegrationRegistry({
2251
+ path: registryFile,
2252
+ integrationFile,
2253
+ definition,
2254
+ key,
2255
+ dryRun: options.dryRun,
2256
+ result
2257
+ });
2258
+ if (!options.skipPackageJson) await updatePackageJson({
2259
+ root,
2260
+ definition,
2261
+ dryRun: options.dryRun,
2262
+ result
2263
+ });
2264
+ if (!options.skipConfig) await updateFarmConfig({
2265
+ root,
2266
+ registryFile,
2267
+ dryRun: options.dryRun,
2268
+ result
2269
+ });
2270
+ if (options.ui) await installUIFeature({
2271
+ root,
2272
+ definition,
2273
+ key,
2274
+ dryRun: options.dryRun,
2275
+ force: options.force,
2276
+ skipPackageJson: options.skipPackageJson,
2277
+ result
2278
+ });
2279
+ return result;
2280
+ }
2281
+ async function addAIRouteIntegration(input) {
2282
+ const routeFile = path.resolve(input.root, input.routeFile || path.join("src", "app", "api", "chat", "route.ts"));
2283
+ const result = {
2284
+ provider: "ai",
2285
+ key: input.definition.defaultKey,
2286
+ mode: "route",
2287
+ integrationFile: routeFile,
2288
+ registryFile: "",
2289
+ routeFile,
2290
+ routePath: "/api/chat",
2291
+ created: [],
2292
+ updated: [],
2293
+ skipped: [],
2294
+ env: [...input.definition.env],
2295
+ notes: [...input.definition.notes || []]
2296
+ };
2297
+ await writeIntegrationComponent({
2298
+ path: routeFile,
2299
+ definition: input.definition,
2300
+ force: input.force,
2301
+ dryRun: input.dryRun,
2302
+ result
2303
+ });
2304
+ if (!input.skipPackageJson) await updatePackageJson({
2305
+ root: input.root,
2306
+ definition: input.definition,
2307
+ dryRun: input.dryRun,
2308
+ result
2309
+ });
2310
+ if (input.ui) await installUIFeature({
2311
+ root: input.root,
2312
+ definition: input.definition,
2313
+ key: input.definition.defaultKey,
2314
+ dryRun: input.dryRun,
2315
+ force: input.force,
2316
+ skipPackageJson: input.skipPackageJson,
2317
+ result
2318
+ });
2319
+ return result;
2320
+ }
2321
+ function resolveProvider(input) {
2322
+ const normalized = input.trim().toLowerCase();
2323
+ const match = PROVIDERS.find((provider) => provider.provider === normalized || provider.aliases.includes(normalized));
2324
+ if (!match) {
2325
+ const supported = PROVIDERS.map((provider) => provider.provider).join(", ");
2326
+ throw new Error(`Unknown integration "${input}". Supported integrations: ${supported}.`);
2327
+ }
2328
+ return match;
2329
+ }
2330
+ function assertValidIntegrationKey(key) {
2331
+ if (!/^[A-Za-z_$][\w$]*$/.test(key)) throw new Error(`Integration key "${key}" must be a valid JavaScript object property name.`);
2332
+ }
2333
+ async function writeIntegrationComponent(input) {
2334
+ const exists = existsSync(input.path);
2335
+ if (exists && !input.force) {
2336
+ input.result.skipped.push(input.path);
2337
+ return;
2338
+ }
2339
+ if (!input.dryRun) {
2340
+ await mkdir(path.dirname(input.path), { recursive: true });
2341
+ await writeFile(input.path, input.definition.template(), "utf8");
2342
+ }
2343
+ if (exists) input.result.updated.push(input.path);
2344
+ else input.result.created.push(input.path);
2345
+ }
2346
+ async function writeIntegrationRegistry(input) {
2347
+ const importPath = toImportPath(path.relative(path.dirname(input.path), input.integrationFile));
2348
+ const importLine = `import { ${input.definition.exportName} } from "${importPath}";`;
2349
+ const propertyLine = ` ${input.key}: ${input.definition.exportName},`;
2350
+ let nextSource;
2351
+ const exists = existsSync(input.path);
2352
+ if (exists) nextSource = ensureRegistryEntry(await readFile(input.path, "utf8"), {
2353
+ importLine,
2354
+ propertyLine,
2355
+ key: input.key,
2356
+ exportName: input.definition.exportName
2357
+ });
2358
+ else nextSource = `${importLine}
2359
+
2360
+ export const appIntegrations = {
2361
+ ${propertyLine}
2362
+ } as const;
2363
+
2364
+ export type AppIntegrations = typeof appIntegrations;
2365
+ `;
2366
+ if (!input.dryRun) {
2367
+ await mkdir(path.dirname(input.path), { recursive: true });
2368
+ await writeFile(input.path, nextSource, "utf8");
2369
+ }
2370
+ input.result[exists ? "updated" : "created"].push(input.path);
2371
+ }
2372
+ function ensureRegistryEntry(source, input) {
2373
+ if (new RegExp(`(^|\\n)\\s*${escapeRegExp(input.key)}\\s*:`, "m").test(source)) {
2374
+ if (source.includes(`${input.key}: ${input.exportName}`)) return source.includes(input.importLine) ? source : `${input.importLine}\n${source}`;
2375
+ throw new Error(`Integration key "${input.key}" already exists in the app integrations registry. Pass --key to use a different key.`);
2376
+ }
2377
+ const sourceWithImport = source.includes(input.importLine) ? source : `${input.importLine}\n${source}`;
2378
+ const appIntegrationsPattern = /export\s+const\s+appIntegrations\s*=\s*\{([\s\S]*?)\}\s*as\s+const;/m;
2379
+ const match = sourceWithImport.match(appIntegrationsPattern);
2380
+ if (!match) return `${sourceWithImport.trimEnd()}
2381
+
2382
+ export const appIntegrations = {
2383
+ ${input.propertyLine}
2384
+ } as const;
2385
+
2386
+ export type AppIntegrations = typeof appIntegrations;
2387
+ `;
2388
+ const body = match[1] || "";
2389
+ const nextBody = body.trim().length ? `${body.trimEnd()}\n${input.propertyLine}\n` : `\n${input.propertyLine}\n`;
2390
+ return sourceWithImport.replace(appIntegrationsPattern, () => {
2391
+ return `export const appIntegrations = {${nextBody}} as const;`;
2392
+ });
2393
+ }
2394
+ async function writeIntegrationSetupFiles(input) {
2395
+ for (const file of input.definition.setupFiles || []) {
2396
+ const absolutePath = path.join(input.root, file.path);
2397
+ const exists = existsSync(absolutePath);
2398
+ if (exists && !input.force) {
2399
+ if (file.merge === "lines") {
2400
+ const source = await readFile(absolutePath, "utf8");
2401
+ const additions = file.source().split(/\r?\n/).filter((line) => line && !source.split(/\r?\n/).includes(line));
2402
+ if (!additions.length) {
2403
+ input.result.skipped.push(absolutePath);
2404
+ continue;
2405
+ }
2406
+ if (!input.dryRun) await writeFile(absolutePath, `${source.trimEnd()}\n${additions.join("\n")}\n`, "utf8");
2407
+ input.result.updated.push(absolutePath);
2408
+ continue;
2409
+ }
2410
+ input.result.skipped.push(absolutePath);
2411
+ continue;
2412
+ }
2413
+ if (!input.dryRun) {
2414
+ await mkdir(path.dirname(absolutePath), { recursive: true });
2415
+ await writeFile(absolutePath, file.source(), "utf8");
2416
+ }
2417
+ input.result[exists ? "updated" : "created"].push(absolutePath);
2418
+ }
2419
+ }
2420
+ async function updatePackageJson(input) {
2421
+ const packageJsonPath = path.join(input.root, "package.json");
2422
+ if (!existsSync(packageJsonPath)) {
2423
+ input.result.skipped.push(packageJsonPath);
2424
+ return;
2425
+ }
2426
+ const source = await readFile(packageJsonPath, "utf8");
2427
+ const manifest = JSON.parse(source);
2428
+ const dependencies = missingDependencies(manifest, input.definition.dependencies);
2429
+ const devDependencies = missingDependencies(manifest, input.definition.devDependencies);
2430
+ manifest.dependencies = {
2431
+ ...manifest.dependencies,
2432
+ ...hasPackageDependency(manifest, "@farm.js/integrations") ? {} : { "@farm.js/integrations": getFarmIntegrationsVersion(manifest) },
2433
+ ...dependencies
2434
+ };
2435
+ if (Object.keys(devDependencies).length) manifest.devDependencies = {
2436
+ ...manifest.devDependencies,
2437
+ ...devDependencies
2438
+ };
2439
+ const nextSource = `${JSON.stringify(manifest, null, 2)}\n`;
2440
+ if (source === nextSource) {
2441
+ input.result.packageJson = packageJsonPath;
2442
+ input.result.skipped.push(packageJsonPath);
2443
+ return;
2444
+ }
2445
+ if (!input.dryRun) await writeFile(packageJsonPath, nextSource, "utf8");
2446
+ input.result.packageJson = packageJsonPath;
2447
+ input.result.updated.push(packageJsonPath);
2448
+ }
2449
+ function missingDependencies(manifest, dependencies) {
2450
+ return Object.fromEntries(Object.entries(dependencies || {}).filter(([name]) => !hasPackageDependency(manifest, name)));
2451
+ }
2452
+ async function updateFarmConfig(input) {
2453
+ const configFile = findFarmConfig(input.root);
2454
+ if (!configFile) {
2455
+ const newConfigFile = path.join(input.root, "farm.config.ts");
2456
+ const source = `import { defineConfig } from "@farm.js/core";
2457
+ import { appIntegrations } from "${toImportPath(path.relative(input.root, input.registryFile))}";
2458
+
2459
+ export default defineConfig({
2460
+ integrations: appIntegrations,
2461
+ });
2462
+ `;
2463
+ if (!input.dryRun) await writeFile(newConfigFile, source, "utf8");
2464
+ input.result.configFile = newConfigFile;
2465
+ input.result.created.push(newConfigFile);
2466
+ return;
2467
+ }
2468
+ input.result.configFile = configFile;
2469
+ const source = await readFile(configFile, "utf8");
2470
+ if (/\bintegrations\s*:/.test(source)) {
2471
+ input.result.skipped.push(configFile);
2472
+ input.result.notes.push(`farm.config already has an integrations field. Confirm it includes appIntegrations from ${path.relative(input.root, input.registryFile)}.`);
2473
+ return;
2474
+ }
2475
+ const importLine = `import { appIntegrations } from "${toImportPath(path.relative(path.dirname(configFile), input.registryFile))}";`;
2476
+ const sourceWithImport = source.includes(importLine) ? source : `${importLine}\n${source}`;
2477
+ const nextSource = insertIntegrationsConfig(sourceWithImport);
2478
+ if (nextSource === sourceWithImport) {
2479
+ input.result.skipped.push(configFile);
2480
+ input.result.notes.push(`Could not safely update ${path.relative(input.root, configFile)}. Add integrations: appIntegrations manually.`);
2481
+ return;
2482
+ }
2483
+ if (!input.dryRun) await writeFile(configFile, nextSource, "utf8");
2484
+ input.result.updated.push(configFile);
2485
+ }
2486
+ function insertIntegrationsConfig(source) {
2487
+ const defineConfigCall = /\bdefine(?:Farm)?Config\s*\(\s*\{/;
2488
+ if (defineConfigCall.test(source)) return source.replace(defineConfigCall, (match) => {
2489
+ return `${match}\n integrations: appIntegrations,`;
2490
+ });
2491
+ if (/export\s+default\s+\{/.test(source)) return source.replace(/export\s+default\s+\{/, (match) => {
2492
+ return `${match}\n integrations: appIntegrations,`;
2493
+ });
2494
+ return source;
2495
+ }
2496
+ function findFarmConfig(root) {
2497
+ for (const candidate of [
2498
+ "farm.config.ts",
2499
+ "farm.config.mts",
2500
+ "farm.config.js",
2501
+ "farm.config.mjs",
2502
+ "config.ts",
2503
+ "config.mts",
2504
+ "config.js",
2505
+ "config.mjs"
2506
+ ]) {
2507
+ const absolutePath = path.join(root, candidate);
2508
+ if (existsSync(absolutePath)) return absolutePath;
2509
+ }
2510
+ return null;
2511
+ }
2512
+ function hasPackageDependency(manifest, dependency) {
2513
+ return dependency in (manifest.dependencies || {}) || dependency in (manifest.devDependencies || {}) || dependency in (manifest.peerDependencies || {}) || dependency in (manifest.optionalDependencies || {});
2514
+ }
2515
+ function getFarmIntegrationsVersion(manifest) {
2516
+ return (manifest.dependencies?.["@farm.js/core"] ?? manifest.devDependencies?.["@farm.js/core"] ?? manifest.peerDependencies?.["@farm.js/core"] ?? manifest.optionalDependencies?.["@farm.js/core"])?.startsWith("workspace:") ? "workspace:*" : "latest";
2517
+ }
2518
+ function toImportPath(relativePath) {
2519
+ const normalized = relativePath.split(path.sep).join("/");
2520
+ return (normalized.startsWith(".") ? normalized : `./${normalized}`).replace(/\.tsx?$/, ".ts");
2521
+ }
2522
+ function escapeRegExp(input) {
2523
+ return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2524
+ }
2525
+ //#endregion
2526
+ export { listFarmIntegrationProviders as n, addFarmIntegration as t };
2527
+
2528
+ //# sourceMappingURL=add-integration-CdVfiPjG.mjs.map