@farm.js/create-app 0.1.0-beta.4 → 0.1.0-beta.41

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.
Files changed (164) hide show
  1. package/README.md +41 -4
  2. package/bin/create-farm-app.js +8 -2
  3. package/dist/index.js +3244 -19
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.mjs +3239 -18
  6. package/dist/index.mjs.map +1 -1
  7. package/dist/utils.js +9 -6
  8. package/dist/utils.js.map +1 -1
  9. package/dist/utils.mjs +9 -6
  10. package/dist/utils.mjs.map +1 -1
  11. package/package.json +2 -2
  12. package/templates/_integrations/better-auth/preact/farm.config.ts +17 -0
  13. package/templates/_integrations/better-auth/preact/src/app/dashboard/page.tsx +73 -0
  14. package/templates/_integrations/better-auth/preact/src/app/layout.tsx +14 -0
  15. package/templates/_integrations/better-auth/preact/src/app/page.tsx +36 -0
  16. package/templates/_integrations/better-auth/preact/src/app/sign-in/page.tsx +10 -0
  17. package/templates/_integrations/better-auth/preact/src/app/sign-up/page.tsx +10 -0
  18. package/templates/_integrations/better-auth/preact/src/components/auth-form.tsx +92 -0
  19. package/templates/_integrations/better-auth/preact/src/components/auth-shell.tsx +16 -0
  20. package/templates/_integrations/better-auth/preact/src/lib/auth-client.ts +5 -0
  21. package/templates/_integrations/better-auth/solid/farm.config.ts +17 -0
  22. package/templates/_integrations/better-auth/solid/src/app/dashboard/page.tsx +67 -0
  23. package/templates/_integrations/better-auth/solid/src/app/layout.tsx +14 -0
  24. package/templates/_integrations/better-auth/solid/src/app/page.tsx +36 -0
  25. package/templates/_integrations/better-auth/solid/src/app/sign-in/page.tsx +10 -0
  26. package/templates/_integrations/better-auth/solid/src/app/sign-up/page.tsx +10 -0
  27. package/templates/_integrations/better-auth/solid/src/components/auth-form.tsx +91 -0
  28. package/templates/_integrations/better-auth/solid/src/components/auth-shell.tsx +16 -0
  29. package/templates/_integrations/better-auth/solid/src/lib/auth-client.ts +5 -0
  30. package/templates/_integrations/better-auth/svelte/farm.config.ts +17 -0
  31. package/templates/_integrations/better-auth/svelte/src/app/dashboard/page.svelte +62 -0
  32. package/templates/_integrations/better-auth/svelte/src/app/layout.svelte +20 -0
  33. package/templates/_integrations/better-auth/svelte/src/app/page.svelte +32 -0
  34. package/templates/_integrations/better-auth/svelte/src/app/sign-in/page.svelte +10 -0
  35. package/templates/_integrations/better-auth/svelte/src/app/sign-up/page.svelte +10 -0
  36. package/templates/_integrations/better-auth/svelte/src/components/auth-form.svelte +83 -0
  37. package/templates/_integrations/better-auth/svelte/src/components/auth-shell.svelte +16 -0
  38. package/templates/_integrations/better-auth/svelte/src/components/resource-links.svelte +47 -0
  39. package/templates/_integrations/better-auth/svelte/src/lib/auth-client.ts +5 -0
  40. package/templates/_integrations/better-auth/vue/farm.config.ts +17 -0
  41. package/templates/_integrations/better-auth/vue/src/app/dashboard/page.vue +62 -0
  42. package/templates/_integrations/better-auth/vue/src/app/layout.vue +20 -0
  43. package/templates/_integrations/better-auth/vue/src/app/page.vue +34 -0
  44. package/templates/_integrations/better-auth/vue/src/app/sign-in/page.vue +12 -0
  45. package/templates/_integrations/better-auth/vue/src/app/sign-up/page.vue +12 -0
  46. package/templates/_integrations/better-auth/vue/src/components/auth-form.vue +86 -0
  47. package/templates/_integrations/better-auth/vue/src/components/auth-shell.vue +15 -0
  48. package/templates/_integrations/better-auth/vue/src/components/resource-links.vue +43 -0
  49. package/templates/_integrations/better-auth/vue/src/lib/auth-client.ts +5 -0
  50. package/templates/_renderers/preact/farm.config.ts +12 -0
  51. package/templates/_renderers/preact/package.json +27 -0
  52. package/templates/_renderers/preact/src/app/api/greeting/route.ts +15 -0
  53. package/templates/_renderers/preact/src/app/layout.tsx +16 -0
  54. package/templates/_renderers/preact/src/app/page.tsx +66 -0
  55. package/templates/_renderers/preact/src/app/preact.css +26 -0
  56. package/templates/_renderers/preact/src/components/resource-links.tsx +71 -0
  57. package/templates/_renderers/preact/src/lib/api-client.ts +4 -0
  58. package/templates/_renderers/preact/src/lib/api.generated.ts +7 -0
  59. package/templates/_renderers/preact/tsconfig.json +25 -0
  60. package/templates/_renderers/solid/farm.config.ts +12 -0
  61. package/templates/_renderers/solid/package.json +26 -0
  62. package/templates/_renderers/solid/src/app/api/greeting/route.ts +15 -0
  63. package/templates/_renderers/solid/src/app/layout.tsx +15 -0
  64. package/templates/_renderers/solid/src/app/page.tsx +56 -0
  65. package/templates/_renderers/solid/src/app/solid.css +22 -0
  66. package/templates/_renderers/solid/src/components/resource-links.tsx +71 -0
  67. package/templates/_renderers/solid/src/lib/api-client.ts +4 -0
  68. package/templates/_renderers/solid/src/lib/api.generated.ts +7 -0
  69. package/templates/_renderers/solid/tsconfig.json +25 -0
  70. package/templates/_renderers/svelte/farm.config.ts +9 -0
  71. package/templates/_renderers/svelte/package.json +28 -0
  72. package/templates/_renderers/svelte/src/app/api/greeting/route.ts +15 -0
  73. package/templates/_renderers/svelte/src/app/layout.svelte +21 -0
  74. package/templates/_renderers/svelte/src/app/page.svelte +64 -0
  75. package/templates/_renderers/svelte/src/app/svelte.css +26 -0
  76. package/templates/_renderers/svelte/src/components/resource-links.svelte +31 -0
  77. package/templates/_renderers/svelte/src/lib/api-client.ts +4 -0
  78. package/templates/_renderers/svelte/src/lib/api.generated.ts +7 -0
  79. package/templates/_renderers/svelte/tsconfig.json +23 -0
  80. package/templates/_renderers/vue/farm.config.ts +12 -0
  81. package/templates/_renderers/vue/package.json +27 -0
  82. package/templates/_renderers/vue/src/app/api/greeting/route.ts +15 -0
  83. package/templates/_renderers/vue/src/app/layout.vue +21 -0
  84. package/templates/_renderers/vue/src/app/page.vue +69 -0
  85. package/templates/_renderers/vue/src/app/vue.css +26 -0
  86. package/templates/_renderers/vue/src/components/resource-links.vue +33 -0
  87. package/templates/_renderers/vue/src/env.d.ts +7 -0
  88. package/templates/_renderers/vue/src/lib/api-client.ts +4 -0
  89. package/templates/_renderers/vue/src/lib/api.generated.ts +7 -0
  90. package/templates/_renderers/vue/tsconfig.json +23 -0
  91. package/templates/auth/.env.example +6 -0
  92. package/templates/auth/README.md +95 -0
  93. package/templates/auth/farm.config.ts +14 -0
  94. package/templates/auth/gitignore +10 -0
  95. package/templates/auth/package.json +32 -0
  96. package/templates/auth/pnpm-workspace.yaml +13 -0
  97. package/templates/auth/src/app/dashboard/middleware.ts +13 -0
  98. package/templates/auth/src/app/dashboard/page.tsx +140 -0
  99. package/templates/auth/src/app/error.tsx +25 -0
  100. package/templates/auth/src/app/globals.css +1064 -0
  101. package/templates/auth/src/app/layout.tsx +11 -0
  102. package/templates/auth/src/app/loading.tsx +15 -0
  103. package/templates/auth/src/app/not-found.tsx +26 -0
  104. package/templates/auth/src/app/page.tsx +46 -0
  105. package/templates/auth/src/app/sign-in/page.tsx +16 -0
  106. package/templates/auth/src/app/sign-up/page.tsx +16 -0
  107. package/templates/auth/src/components/auth-form.tsx +120 -0
  108. package/templates/auth/src/components/auth-shell.tsx +21 -0
  109. package/templates/auth/src/components/resource-links.tsx +78 -0
  110. package/templates/auth/src/components/sign-out-button.tsx +45 -0
  111. package/templates/auth/src/components/site-header.tsx +46 -0
  112. package/templates/auth/tsconfig.json +20 -0
  113. package/templates/basic/farm.config.ts +3 -0
  114. package/templates/basic/gitignore +23 -0
  115. package/templates/basic/package.json +4 -2
  116. package/templates/basic/pnpm-workspace.yaml +8 -0
  117. package/templates/basic/public/favicon.svg +13 -0
  118. package/templates/basic/src/app/globals.css +241 -0
  119. package/templates/basic/src/app/layout.tsx +6 -5
  120. package/templates/basic/src/app/page.tsx +20 -61
  121. package/templates/basic/src/components/resource-links.tsx +78 -0
  122. package/templates/basic/tsconfig.json +4 -0
  123. package/templates/better-auth/.env.example +3 -0
  124. package/templates/better-auth/README.md +89 -0
  125. package/templates/better-auth/farm.config.ts +32 -0
  126. package/templates/better-auth/gitignore +10 -0
  127. package/templates/better-auth/package.json +34 -0
  128. package/templates/better-auth/pnpm-workspace.yaml +13 -0
  129. package/templates/better-auth/src/app/dashboard/middleware.ts +15 -0
  130. package/templates/better-auth/src/app/dashboard/page.tsx +188 -0
  131. package/templates/better-auth/src/app/error.tsx +25 -0
  132. package/templates/better-auth/src/app/globals.css +1064 -0
  133. package/templates/better-auth/src/app/layout.tsx +11 -0
  134. package/templates/better-auth/src/app/loading.tsx +15 -0
  135. package/templates/better-auth/src/app/not-found.tsx +26 -0
  136. package/templates/better-auth/src/app/page.tsx +50 -0
  137. package/templates/better-auth/src/app/sign-in/page.tsx +16 -0
  138. package/templates/better-auth/src/app/sign-up/page.tsx +16 -0
  139. package/templates/better-auth/src/components/auth-form.tsx +120 -0
  140. package/templates/better-auth/src/components/auth-shell.tsx +21 -0
  141. package/templates/better-auth/src/components/resource-links.tsx +78 -0
  142. package/templates/better-auth/src/components/sign-out-button.tsx +45 -0
  143. package/templates/better-auth/src/components/site-header.tsx +46 -0
  144. package/templates/better-auth/src/lib/auth-client.ts +5 -0
  145. package/templates/better-auth/src/lib/auth.ts +50 -0
  146. package/templates/better-auth/src/lib/session.ts +8 -0
  147. package/templates/better-auth/tsconfig.json +20 -0
  148. package/templates/react-compiler/README.md +62 -0
  149. package/templates/react-compiler/farm.config.ts +23 -0
  150. package/templates/react-compiler/gitignore +23 -0
  151. package/templates/react-compiler/package.json +31 -0
  152. package/templates/react-compiler/pnpm-workspace.yaml +8 -0
  153. package/templates/react-compiler/public/favicon.svg +5 -0
  154. package/templates/react-compiler/scripts/verify-experiment.mjs +113 -0
  155. package/templates/react-compiler/src/app/globals.css +470 -0
  156. package/templates/react-compiler/src/app/layout.tsx +22 -0
  157. package/templates/react-compiler/src/app/page.tsx +47 -0
  158. package/templates/react-compiler/src/components/compiler-comparison.tsx +93 -0
  159. package/templates/react-compiler/src/components/resource-links.tsx +78 -0
  160. package/templates/react-compiler/src/farm.d.ts +73 -0
  161. package/templates/react-compiler/src/lib/api.generated.ts +10 -0
  162. package/templates/react-compiler/tsconfig.json +24 -0
  163. package/templates/basic/src/app/about/page.tsx +0 -32
  164. package/templates/basic/src/farm-images.d.ts +0 -59
package/dist/index.js CHANGED
@@ -7,14 +7,2956 @@ let path = require("path");
7
7
  path = require_rolldown_runtime.__toESM(path);
8
8
  let fs_promises = require("fs/promises");
9
9
  fs_promises = require_rolldown_runtime.__toESM(fs_promises);
10
+ let node_child_process = require("node:child_process");
11
+ let node_fs = require("node:fs");
12
+ let node_fs_promises = require("node:fs/promises");
13
+ let node_path = require("node:path");
14
+ node_path = require_rolldown_runtime.__toESM(node_path);
15
+ let node_crypto = require("node:crypto");
16
+ let node_os = require("node:os");
17
+ node_os = require_rolldown_runtime.__toESM(node_os);
18
+ //#region ../farm-cli/src/ui-feature-registry.ts
19
+ async function installUIFeature(input) {
20
+ const feature = input.definition.ui;
21
+ if (!feature) {
22
+ input.result.notes.push(`No --ui feature pack is available for ${input.definition.provider} yet.`);
23
+ return;
24
+ }
25
+ input.result.ui = {
26
+ feature: feature.name,
27
+ components: [...feature.components],
28
+ files: []
29
+ };
30
+ input.result.notes.push(`Installed ${feature.description} with shadcn-style local source components.`, ...feature.notes || []);
31
+ await ensureComponentsJson({
32
+ root: input.root,
33
+ dryRun: input.dryRun,
34
+ result: input.result
35
+ });
36
+ await ensureShadcnGlobals({
37
+ root: input.root,
38
+ dryRun: input.dryRun,
39
+ result: input.result
40
+ });
41
+ await ensureTsconfigAlias({
42
+ root: input.root,
43
+ dryRun: input.dryRun,
44
+ result: input.result
45
+ });
46
+ if (!input.skipPackageJson) await updateUIPackageJson({
47
+ root: input.root,
48
+ dryRun: input.dryRun,
49
+ result: input.result
50
+ });
51
+ await writeGeneratedFile({
52
+ root: input.root,
53
+ relativePath: node_path.default.join("src", "lib", "utils.ts"),
54
+ source: shadcnUtilsTemplate(),
55
+ dryRun: input.dryRun,
56
+ force: input.force,
57
+ result: input.result
58
+ });
59
+ for (const component of feature.components) await writeGeneratedFile({
60
+ root: input.root,
61
+ relativePath: node_path.default.join("src", "components", "ui", `${component}.tsx`),
62
+ source: shadcnComponentTemplate(component),
63
+ dryRun: input.dryRun,
64
+ force: input.force,
65
+ result: input.result
66
+ });
67
+ if (feature.needsApiClient !== false) await writeGeneratedFile({
68
+ root: input.root,
69
+ relativePath: node_path.default.join("src", "lib", "api.ts"),
70
+ source: apiClientTemplate(),
71
+ dryRun: input.dryRun,
72
+ force: input.force,
73
+ result: input.result
74
+ });
75
+ for (const file of feature.files({
76
+ key: input.key,
77
+ provider: input.definition.provider
78
+ })) await writeGeneratedFile({
79
+ root: input.root,
80
+ relativePath: file.path,
81
+ source: file.source,
82
+ dryRun: input.dryRun,
83
+ force: input.force,
84
+ result: input.result
85
+ });
86
+ }
87
+ function stripeBillingUIFeature() {
88
+ return billingUIFeature({
89
+ provider: "stripe",
90
+ label: "Stripe"
91
+ });
92
+ }
93
+ function polarBillingUIFeature() {
94
+ return billingUIFeature({
95
+ provider: "polar",
96
+ label: "Polar"
97
+ });
98
+ }
99
+ function autumnBillingUIFeature() {
100
+ return billingUIFeature({
101
+ provider: "autumn",
102
+ label: "Autumn"
103
+ });
104
+ }
105
+ function aiChatUIFeature() {
106
+ return {
107
+ name: "ai-chat",
108
+ description: "AI chat UI",
109
+ components: [
110
+ "badge",
111
+ "button",
112
+ "card",
113
+ "input"
114
+ ],
115
+ needsApiClient: false,
116
+ notes: ["Open \"/integrations/ai\" to try the generated chat UI."],
117
+ files: () => [componentFile("ai-chat.tsx", aiChatTemplate()), integrationPageFile("ai", "AIChat", "ai-chat")]
118
+ };
119
+ }
120
+ function supabaseAuthUIFeature() {
121
+ return {
122
+ name: "supabase-auth",
123
+ description: "Supabase auth UI",
124
+ components: [
125
+ "badge",
126
+ "button",
127
+ "card",
128
+ "input",
129
+ "label"
130
+ ],
131
+ notes: ["Open \"/integrations/supabase\" to try the generated auth UI."],
132
+ files: (input) => [componentFile("supabase-auth-panel.tsx", supabaseAuthTemplate(input.key)), integrationPageFile("supabase", "SupabaseAuthPanel")]
133
+ };
134
+ }
135
+ function workosAuthUIFeature() {
136
+ return {
137
+ name: "workos-auth",
138
+ description: "WorkOS auth UI",
139
+ components: [
140
+ "badge",
141
+ "button",
142
+ "card"
143
+ ],
144
+ notes: ["Open \"/integrations/workos\" to try the generated auth UI."],
145
+ files: (input) => [componentFile("workos-auth-panel.tsx", hostedAuthTemplate({
146
+ key: input.key,
147
+ provider: "WorkOS",
148
+ componentName: "WorkOSAuthPanel",
149
+ statusCall: "session",
150
+ statusMethod: "get",
151
+ logoutCall: "logout",
152
+ logoutMethod: "post",
153
+ loginHref: "/login?returnTo=/dashboard",
154
+ signupHref: "/signup?returnTo=/dashboard",
155
+ statusLabel: "Session"
156
+ })), integrationPageFile("workos", "WorkOSAuthPanel", "workos-auth-panel")]
157
+ };
158
+ }
159
+ function auth0AuthUIFeature() {
160
+ return authRouteShellUIFeature({
161
+ provider: "auth0",
162
+ label: "Auth0",
163
+ componentName: "Auth0AuthPanel",
164
+ signInHref: "/auth/login?returnTo=/dashboard",
165
+ signUpHref: "/auth/signup?returnTo=/dashboard",
166
+ sessionHref: "/auth/profile"
167
+ });
168
+ }
169
+ function clerkAuthUIFeature() {
170
+ return authRouteShellUIFeature({
171
+ provider: "clerk",
172
+ label: "Clerk",
173
+ componentName: "ClerkAuthPanel",
174
+ signInHref: "/sign-in",
175
+ signUpHref: "/sign-up",
176
+ sessionHref: "/dashboard"
177
+ });
178
+ }
179
+ function betterAuthUIFeature() {
180
+ return {
181
+ name: "better-auth-auth",
182
+ description: "Better Auth email and password UI",
183
+ components: [
184
+ "badge",
185
+ "button",
186
+ "card",
187
+ "input",
188
+ "label"
189
+ ],
190
+ needsApiClient: false,
191
+ notes: ["Open \"/integrations/better-auth\" to try the generated auth UI."],
192
+ files: () => [
193
+ {
194
+ path: node_path.default.join("src", "lib", "auth-client.ts"),
195
+ source: betterAuthClientTemplate()
196
+ },
197
+ componentFile("better-auth-panel.tsx", betterAuthPanelTemplate()),
198
+ integrationPageFile("better-auth", "BetterAuthPanel")
199
+ ]
200
+ };
201
+ }
202
+ function authjsUIFeature() {
203
+ return authRouteShellUIFeature({
204
+ provider: "authjs",
205
+ label: "Auth.js",
206
+ componentName: "AuthJsPanel",
207
+ signInHref: "/api/auth/signin",
208
+ signUpHref: "/api/auth/signin",
209
+ sessionHref: "/api/auth/session"
210
+ });
211
+ }
212
+ function resendEmailUIFeature() {
213
+ return {
214
+ name: "resend-email",
215
+ description: "Resend email console UI",
216
+ components: [
217
+ "badge",
218
+ "button",
219
+ "card",
220
+ "input",
221
+ "label"
222
+ ],
223
+ notes: ["Open \"/integrations/resend\" to try the generated email UI."],
224
+ files: (input) => [componentFile("resend-email-console.tsx", resendEmailTemplate(input.key)), integrationPageFile("resend", "ResendEmailConsole")]
225
+ };
226
+ }
227
+ function jobsUIFeature(provider) {
228
+ const label = provider === "inngest" ? "Inngest" : "Trigger.dev";
229
+ return {
230
+ name: `${provider}-jobs`,
231
+ description: `${label} jobs console UI`,
232
+ components: [
233
+ "badge",
234
+ "button",
235
+ "card",
236
+ "input",
237
+ "label"
238
+ ],
239
+ notes: [`Open "/integrations/jobs-${provider}" to try the generated jobs UI.`],
240
+ files: (input) => [componentFile(`${provider}-jobs-console.tsx`, jobsConsoleTemplate(input.key, label, provider)), integrationPageFile(`jobs-${provider}`, `${pascalCase(provider)}JobsConsole`)]
241
+ };
242
+ }
243
+ function unkeyApiKeysUIFeature() {
244
+ return {
245
+ name: "unkey-api-keys",
246
+ description: "Unkey protected route UI",
247
+ components: ["badge", "card"],
248
+ needsApiClient: false,
249
+ notes: ["Open \"/integrations/unkey\" to test the generated protected API route."],
250
+ files: () => [
251
+ componentFile("unkey-api-keys-console.tsx", unkeyApiKeysTemplate()),
252
+ integrationPageFile("unkey", "UnkeyApiKeysConsole"),
253
+ {
254
+ path: node_path.default.join("src", "app", "api", "protected", "route.ts"),
255
+ source: unkeyProtectedRouteTemplate()
256
+ }
257
+ ]
258
+ };
259
+ }
260
+ function billingUIFeature(input) {
261
+ return {
262
+ name: `${input.provider}-billing`,
263
+ description: `${input.label} pricing and checkout UI`,
264
+ components: [
265
+ "badge",
266
+ "button",
267
+ "card"
268
+ ],
269
+ notes: [`Open "/integrations/${input.provider}" to try the generated ${input.label} billing UI.`],
270
+ files: (templateInput) => [componentFile(`${input.provider}-billing.tsx`, billingPricingTemplate({
271
+ key: templateInput.key,
272
+ provider: input.provider,
273
+ label: input.label,
274
+ componentName: `${pascalCase(input.provider)}Billing`
275
+ })), integrationPageFile(input.provider, `${pascalCase(input.provider)}Billing`)]
276
+ };
277
+ }
278
+ function authRouteShellUIFeature(input) {
279
+ return {
280
+ name: `${input.provider}-auth`,
281
+ description: `${input.label} auth UI`,
282
+ components: [
283
+ "badge",
284
+ "button",
285
+ "card"
286
+ ],
287
+ needsApiClient: false,
288
+ notes: [`Open "/integrations/${input.provider}" to try the generated auth UI.`],
289
+ files: () => [componentFile(`${input.provider}-auth-panel.tsx`, authRouteShellTemplate({
290
+ provider: input.label,
291
+ componentName: input.componentName,
292
+ signInHref: input.signInHref,
293
+ signUpHref: input.signUpHref,
294
+ sessionHref: input.sessionHref
295
+ })), integrationPageFile(input.provider, input.componentName, input.provider === "authjs" ? "authjs-auth-panel" : void 0)]
296
+ };
297
+ }
298
+ function componentFile(fileName, source) {
299
+ return {
300
+ path: node_path.default.join("src", "components", "farm", fileName),
301
+ source
302
+ };
303
+ }
304
+ function integrationPageFile(provider, componentName, sourceFileName = kebabCase(componentName)) {
305
+ return {
306
+ path: node_path.default.join("src", "app", "integrations", provider, "page.tsx"),
307
+ source: `import { ${componentName} } from "@/components/farm/${sourceFileName}";
308
+
309
+ export default function ${componentName}Page() {
310
+ return <${componentName} />;
311
+ }
312
+ `
313
+ };
314
+ }
315
+ async function writeGeneratedFile(input) {
316
+ const absolutePath = node_path.default.join(input.root, input.relativePath);
317
+ const exists = (0, node_fs.existsSync)(absolutePath);
318
+ const source = resolveGeneratedAliases(input.source, input.relativePath);
319
+ input.result.ui?.files.push(absolutePath);
320
+ if (exists && !input.force) {
321
+ pushResultPath(input.result.skipped, absolutePath);
322
+ return;
323
+ }
324
+ if (!input.dryRun) {
325
+ await (0, node_fs_promises.mkdir)(node_path.default.dirname(absolutePath), { recursive: true });
326
+ await (0, node_fs_promises.writeFile)(absolutePath, source, "utf8");
327
+ }
328
+ pushResultPath(exists ? input.result.updated : input.result.created, absolutePath);
329
+ }
330
+ function resolveGeneratedAliases(source, relativePath) {
331
+ const sourceDirectory = node_path.default.dirname(relativePath);
332
+ return source.replace(/(["'])@\/([^"']+)\1/g, (_match, quote, target) => {
333
+ const relativeTarget = node_path.default.relative(sourceDirectory, node_path.default.join("src", target)).split(node_path.default.sep).join("/");
334
+ return `${quote}${relativeTarget.startsWith(".") ? relativeTarget : `./${relativeTarget}`}${quote}`;
335
+ });
336
+ }
337
+ async function ensureComponentsJson(input) {
338
+ const componentsJsonPath = node_path.default.join(input.root, "components.json");
339
+ input.result.ui?.files.push(componentsJsonPath);
340
+ const defaults = createComponentsJson();
341
+ if (!(0, node_fs.existsSync)(componentsJsonPath)) {
342
+ if (!input.dryRun) await (0, node_fs_promises.writeFile)(componentsJsonPath, `${JSON.stringify(defaults, null, 2)}\n`, "utf8");
343
+ pushResultPath(input.result.created, componentsJsonPath);
344
+ return;
345
+ }
346
+ let current;
347
+ try {
348
+ current = JSON.parse(await (0, node_fs_promises.readFile)(componentsJsonPath, "utf8"));
349
+ } catch {
350
+ pushResultPath(input.result.skipped, componentsJsonPath);
351
+ input.result.notes.push("components.json could not be parsed. Keep shadcn aliases pointed at src/components and src/lib/utils.");
352
+ return;
353
+ }
354
+ const next = mergeComponentsJson(current, defaults);
355
+ if (JSON.stringify(current) === JSON.stringify(next)) {
356
+ pushResultPath(input.result.skipped, componentsJsonPath);
357
+ return;
358
+ }
359
+ if (!input.dryRun) await (0, node_fs_promises.writeFile)(componentsJsonPath, `${JSON.stringify(next, null, 2)}\n`, "utf8");
360
+ pushResultPath(input.result.updated, componentsJsonPath);
361
+ }
362
+ async function ensureShadcnGlobals(input) {
363
+ const globalsPath = node_path.default.join(input.root, "src", "app", "globals.css");
364
+ input.result.ui?.files.push(globalsPath);
365
+ if (!(0, node_fs.existsSync)(globalsPath)) {
366
+ const source = `@import "tailwindcss";
367
+
368
+ ${SHADCN_THEME_CSS}
369
+ `;
370
+ if (!input.dryRun) {
371
+ await (0, node_fs_promises.mkdir)(node_path.default.dirname(globalsPath), { recursive: true });
372
+ await (0, node_fs_promises.writeFile)(globalsPath, source, "utf8");
373
+ }
374
+ pushResultPath(input.result.created, globalsPath);
375
+ return;
376
+ }
377
+ const source = await (0, node_fs_promises.readFile)(globalsPath, "utf8");
378
+ const hasTailwindImport = source.includes("@import \"tailwindcss\"");
379
+ const hasTheme = source.includes("--color-background") || source.includes("--background:");
380
+ if (hasTailwindImport && hasTheme) {
381
+ pushResultPath(input.result.skipped, globalsPath);
382
+ return;
383
+ }
384
+ const nextSource = `${hasTailwindImport ? "" : "@import \"tailwindcss\";\n\n"}${source.trimEnd()}${hasTheme ? "\n" : `
385
+
386
+ ${SHADCN_THEME_CSS}
387
+ `}`;
388
+ if (!input.dryRun) await (0, node_fs_promises.writeFile)(globalsPath, nextSource, "utf8");
389
+ pushResultPath(input.result.updated, globalsPath);
390
+ }
391
+ async function ensureTsconfigAlias(input) {
392
+ const tsconfigPath = node_path.default.join(input.root, "tsconfig.json");
393
+ input.result.ui?.files.push(tsconfigPath);
394
+ const defaults = { compilerOptions: {
395
+ baseUrl: ".",
396
+ paths: { "@/*": ["./src/*"] }
397
+ } };
398
+ if (!(0, node_fs.existsSync)(tsconfigPath)) {
399
+ if (!input.dryRun) await (0, node_fs_promises.writeFile)(tsconfigPath, `${JSON.stringify(defaults, null, 2)}\n`, "utf8");
400
+ pushResultPath(input.result.created, tsconfigPath);
401
+ return;
402
+ }
403
+ let tsconfig;
404
+ try {
405
+ tsconfig = JSON.parse(await (0, node_fs_promises.readFile)(tsconfigPath, "utf8"));
406
+ } catch {
407
+ pushResultPath(input.result.skipped, tsconfigPath);
408
+ input.result.notes.push("tsconfig.json could not be parsed. Add paths: { \"@/*\": [\"./src/*\"] } manually.");
409
+ return;
410
+ }
411
+ const compilerOptions = readObject(tsconfig.compilerOptions);
412
+ const paths = readObject(compilerOptions.paths);
413
+ const nextCompilerOptions = {
414
+ ...compilerOptions,
415
+ baseUrl: typeof compilerOptions.baseUrl === "string" ? compilerOptions.baseUrl : ".",
416
+ paths: {
417
+ ...paths,
418
+ "@/*": ["./src/*"]
419
+ }
420
+ };
421
+ const nextTsconfig = {
422
+ ...tsconfig,
423
+ compilerOptions: nextCompilerOptions
424
+ };
425
+ if (JSON.stringify(tsconfig) === JSON.stringify(nextTsconfig)) {
426
+ pushResultPath(input.result.skipped, tsconfigPath);
427
+ return;
428
+ }
429
+ if (!input.dryRun) await (0, node_fs_promises.writeFile)(tsconfigPath, `${JSON.stringify(nextTsconfig, null, 2)}\n`, "utf8");
430
+ pushResultPath(input.result.updated, tsconfigPath);
431
+ }
432
+ async function updateUIPackageJson(input) {
433
+ const packageJsonPath = node_path.default.join(input.root, "package.json");
434
+ input.result.ui?.files.push(packageJsonPath);
435
+ if (!(0, node_fs.existsSync)(packageJsonPath)) {
436
+ pushResultPath(input.result.skipped, packageJsonPath);
437
+ return;
438
+ }
439
+ const source = await (0, node_fs_promises.readFile)(packageJsonPath, "utf8");
440
+ const manifest = JSON.parse(source);
441
+ let changed = false;
442
+ for (const [dependency, version] of Object.entries(UI_DEPENDENCIES)) {
443
+ if (hasPackageDependency$1(manifest, dependency)) continue;
444
+ manifest.dependencies = {
445
+ ...manifest.dependencies,
446
+ [dependency]: version
447
+ };
448
+ changed = true;
449
+ }
450
+ if (!changed) {
451
+ pushResultPath(input.result.skipped, packageJsonPath);
452
+ return;
453
+ }
454
+ if (!input.dryRun) await (0, node_fs_promises.writeFile)(packageJsonPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
455
+ input.result.packageJson = packageJsonPath;
456
+ pushResultPath(input.result.updated, packageJsonPath);
457
+ }
458
+ const UI_DEPENDENCIES = {
459
+ "class-variance-authority": "^0.7.1",
460
+ clsx: "^2.1.1",
461
+ "tailwind-merge": "^3.3.1",
462
+ tailwindcss: "^4.1.18"
463
+ };
464
+ const SHADCN_THEME_CSS = `@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *));
465
+
466
+ @theme inline {
467
+ --color-background: var(--background);
468
+ --color-foreground: var(--foreground);
469
+ --color-card: var(--card);
470
+ --color-card-foreground: var(--card-foreground);
471
+ --color-popover: var(--popover);
472
+ --color-popover-foreground: var(--popover-foreground);
473
+ --color-primary: var(--primary);
474
+ --color-primary-foreground: var(--primary-foreground);
475
+ --color-secondary: var(--secondary);
476
+ --color-secondary-foreground: var(--secondary-foreground);
477
+ --color-muted: var(--muted);
478
+ --color-muted-foreground: var(--muted-foreground);
479
+ --color-accent: var(--accent);
480
+ --color-accent-foreground: var(--accent-foreground);
481
+ --color-destructive: var(--destructive);
482
+ --color-border: var(--border);
483
+ --color-input: var(--input);
484
+ --color-ring: var(--ring);
485
+ --radius-sm: calc(var(--radius) - 4px);
486
+ --radius-md: calc(var(--radius) - 2px);
487
+ --radius-lg: var(--radius);
488
+ }
489
+
490
+ :root,
491
+ [data-theme="light"] {
492
+ --radius: 0.5rem;
493
+ --background: oklch(1 0 0);
494
+ --foreground: oklch(0.145 0 0);
495
+ --card: oklch(1 0 0);
496
+ --card-foreground: oklch(0.145 0 0);
497
+ --popover: oklch(1 0 0);
498
+ --popover-foreground: oklch(0.145 0 0);
499
+ --primary: oklch(0.205 0 0);
500
+ --primary-foreground: oklch(0.985 0 0);
501
+ --secondary: oklch(0.97 0 0);
502
+ --secondary-foreground: oklch(0.205 0 0);
503
+ --muted: oklch(0.97 0 0);
504
+ --muted-foreground: oklch(0.556 0 0);
505
+ --accent: oklch(0.97 0 0);
506
+ --accent-foreground: oklch(0.205 0 0);
507
+ --destructive: oklch(0.577 0.245 27.325);
508
+ --border: oklch(0.922 0 0);
509
+ --input: oklch(0.922 0 0);
510
+ --ring: oklch(0.708 0 0);
511
+ }
512
+
513
+ [data-theme="dark"] {
514
+ --background: oklch(0.145 0 0);
515
+ --foreground: oklch(0.985 0 0);
516
+ --card: oklch(0.205 0 0);
517
+ --card-foreground: oklch(0.985 0 0);
518
+ --popover: oklch(0.205 0 0);
519
+ --popover-foreground: oklch(0.985 0 0);
520
+ --primary: oklch(0.922 0 0);
521
+ --primary-foreground: oklch(0.205 0 0);
522
+ --secondary: oklch(0.269 0 0);
523
+ --secondary-foreground: oklch(0.985 0 0);
524
+ --muted: oklch(0.269 0 0);
525
+ --muted-foreground: oklch(0.708 0 0);
526
+ --accent: oklch(0.269 0 0);
527
+ --accent-foreground: oklch(0.985 0 0);
528
+ --destructive: oklch(0.704 0.191 22.216);
529
+ --border: oklch(1 0 0 / 10%);
530
+ --input: oklch(1 0 0 / 15%);
531
+ --ring: oklch(0.556 0 0);
532
+ }
533
+
534
+ @layer base {
535
+ * {
536
+ @apply border-border outline-ring/50;
537
+ }
538
+
539
+ body {
540
+ @apply bg-background text-foreground;
541
+ }
542
+ }`;
543
+ function createComponentsJson() {
544
+ return {
545
+ $schema: "https://ui.shadcn.com/schema.json",
546
+ style: "new-york",
547
+ rsc: true,
548
+ tsx: true,
549
+ tailwind: {
550
+ config: "",
551
+ css: "src/app/globals.css",
552
+ baseColor: "zinc",
553
+ cssVariables: true
554
+ },
555
+ aliases: {
556
+ components: "@/components",
557
+ utils: "@/lib/utils",
558
+ ui: "@/components/ui",
559
+ lib: "@/lib",
560
+ hooks: "@/hooks"
561
+ },
562
+ registries: { farm: { url: "https://farmjs.dev/r/{name}.json" } }
563
+ };
564
+ }
565
+ function mergeComponentsJson(current, defaults) {
566
+ const aliases = readObject(current.aliases);
567
+ const tailwind = readObject(current.tailwind);
568
+ const registries = readObject(current.registries);
569
+ return {
570
+ ...current,
571
+ $schema: typeof current.$schema === "string" ? current.$schema : defaults.$schema,
572
+ style: typeof current.style === "string" ? current.style : defaults.style,
573
+ rsc: typeof current.rsc === "boolean" ? current.rsc : defaults.rsc,
574
+ tsx: typeof current.tsx === "boolean" ? current.tsx : defaults.tsx,
575
+ tailwind: {
576
+ ...defaults.tailwind,
577
+ ...tailwind
578
+ },
579
+ aliases: {
580
+ ...defaults.aliases,
581
+ ...aliases
582
+ },
583
+ registries: {
584
+ ...registries,
585
+ farm: readObject(registries.farm).url ? registries.farm : defaults.registries.farm
586
+ }
587
+ };
588
+ }
589
+ function shadcnUtilsTemplate() {
590
+ return `import { clsx, type ClassValue } from "clsx";
591
+ import { twMerge } from "tailwind-merge";
592
+
593
+ export function cn(...inputs: ClassValue[]) {
594
+ return twMerge(clsx(inputs));
595
+ }
596
+ `;
597
+ }
598
+ function apiClientTemplate() {
599
+ return `import { createIntegrations } from "@farm.js/core/client";
600
+ import type { AppIntegrations } from "./integrations";
601
+
602
+ export const { api, apiClient } = createIntegrations<AppIntegrations>();
603
+ `;
604
+ }
605
+ function shadcnComponentTemplate(component) {
606
+ switch (component) {
607
+ case "badge": return `import * as React from "react";
608
+ import { cva, type VariantProps } from "class-variance-authority";
609
+ import { cn } from "@/lib/utils";
610
+
611
+ const badgeVariants = cva(
612
+ "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",
613
+ {
614
+ variants: {
615
+ variant: {
616
+ default: "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
617
+ secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
618
+ outline: "text-foreground",
619
+ },
620
+ },
621
+ defaultVariants: {
622
+ variant: "default",
623
+ },
624
+ },
625
+ );
626
+
627
+ export interface BadgeProps
628
+ extends React.HTMLAttributes<HTMLDivElement>,
629
+ VariantProps<typeof badgeVariants> {}
630
+
631
+ export function Badge({ className, variant, ...props }: BadgeProps) {
632
+ return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
633
+ }
634
+
635
+ export { badgeVariants };
636
+ `;
637
+ case "button": return `import * as React from "react";
638
+ import { cva, type VariantProps } from "class-variance-authority";
639
+ import { cn } from "@/lib/utils";
640
+
641
+ const buttonVariants = cva(
642
+ "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",
643
+ {
644
+ variants: {
645
+ variant: {
646
+ default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
647
+ secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
648
+ outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
649
+ ghost: "hover:bg-accent hover:text-accent-foreground",
650
+ },
651
+ size: {
652
+ default: "h-9 px-4 py-2",
653
+ sm: "h-8 rounded-md px-3 text-xs",
654
+ lg: "h-10 rounded-md px-8",
655
+ },
656
+ },
657
+ defaultVariants: {
658
+ variant: "default",
659
+ size: "default",
660
+ },
661
+ },
662
+ );
663
+
664
+ export interface ButtonProps
665
+ extends React.ButtonHTMLAttributes<HTMLButtonElement>,
666
+ VariantProps<typeof buttonVariants> {}
667
+
668
+ export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
669
+ ({ className, variant, size, ...props }, ref) => {
670
+ return (
671
+ <button
672
+ className={cn(buttonVariants({ variant, size, className }))}
673
+ ref={ref}
674
+ {...props}
675
+ />
676
+ );
677
+ },
678
+ );
679
+ Button.displayName = "Button";
680
+
681
+ export { buttonVariants };
682
+ `;
683
+ case "card": return `import * as React from "react";
684
+ import { cn } from "@/lib/utils";
685
+
686
+ export const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
687
+ ({ className, ...props }, ref) => (
688
+ <div
689
+ ref={ref}
690
+ className={cn("rounded-lg border bg-card text-card-foreground shadow-sm", className)}
691
+ {...props}
692
+ />
693
+ ),
694
+ );
695
+ Card.displayName = "Card";
696
+
697
+ export const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
698
+ ({ className, ...props }, ref) => (
699
+ <div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
700
+ ),
701
+ );
702
+ CardHeader.displayName = "CardHeader";
703
+
704
+ export const CardTitle = React.forwardRef<HTMLHeadingElement, React.HTMLAttributes<HTMLHeadingElement>>(
705
+ ({ className, ...props }, ref) => (
706
+ <h3 ref={ref} className={cn("text-2xl font-semibold leading-none tracking-normal", className)} {...props} />
707
+ ),
708
+ );
709
+ CardTitle.displayName = "CardTitle";
710
+
711
+ export const CardDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
712
+ ({ className, ...props }, ref) => (
713
+ <p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
714
+ ),
715
+ );
716
+ CardDescription.displayName = "CardDescription";
717
+
718
+ export const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
719
+ ({ className, ...props }, ref) => (
720
+ <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
721
+ ),
722
+ );
723
+ CardContent.displayName = "CardContent";
724
+
725
+ export const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
726
+ ({ className, ...props }, ref) => (
727
+ <div ref={ref} className={cn("flex items-center p-6 pt-0", className)} {...props} />
728
+ ),
729
+ );
730
+ CardFooter.displayName = "CardFooter";
731
+ `;
732
+ case "input": return `import * as React from "react";
733
+ import { cn } from "@/lib/utils";
734
+
735
+ export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}
736
+
737
+ export const Input = React.forwardRef<HTMLInputElement, InputProps>(
738
+ ({ className, type, ...props }, ref) => (
739
+ <input
740
+ type={type}
741
+ className={cn(
742
+ "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",
743
+ className,
744
+ )}
745
+ ref={ref}
746
+ {...props}
747
+ />
748
+ ),
749
+ );
750
+ Input.displayName = "Input";
751
+ `;
752
+ case "label": return `import * as React from "react";
753
+ import { cn } from "@/lib/utils";
754
+
755
+ export const Label = React.forwardRef<HTMLLabelElement, React.LabelHTMLAttributes<HTMLLabelElement>>(
756
+ ({ className, ...props }, ref) => (
757
+ <label
758
+ ref={ref}
759
+ className={cn("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70", className)}
760
+ {...props}
761
+ />
762
+ ),
763
+ );
764
+ Label.displayName = "Label";
765
+ `;
766
+ }
767
+ }
768
+ function billingPricingTemplate(input) {
769
+ return `"use client";
770
+
771
+ import * as React from "react";
772
+ import { Badge } from "@/components/ui/badge";
773
+ import { Button } from "@/components/ui/button";
774
+ import {
775
+ Card,
776
+ CardContent,
777
+ CardDescription,
778
+ CardFooter,
779
+ CardHeader,
780
+ CardTitle,
781
+ } from "@/components/ui/card";
782
+ import { apiClient } from "@/lib/api";
783
+
784
+ type BillingProduct = NonNullable<Awaited<ReturnType<typeof apiClient.${input.key}.products>>["data"]>[number];
785
+
786
+ export function ${input.componentName}() {
787
+ const [products, setProducts] = React.useState<BillingProduct[]>([]);
788
+ const [loading, setLoading] = React.useState(true);
789
+ const [checkingOut, setCheckingOut] = React.useState<string | null>(null);
790
+ const [error, setError] = React.useState<string | null>(null);
791
+
792
+ React.useEffect(() => {
793
+ let active = true;
794
+
795
+ async function loadProducts() {
796
+ setLoading(true);
797
+ setError(null);
798
+
799
+ try {
800
+ const response = await apiClient.${input.key}.products();
801
+ if (response.error) {
802
+ throw new Error(readErrorMessage(response.error, "${input.label} request failed."));
803
+ }
804
+
805
+ if (active) {
806
+ setProducts(Array.from(response.data ?? []));
807
+ }
808
+ } catch (cause) {
809
+ if (active) {
810
+ setError(cause instanceof Error ? cause.message : "Could not load ${input.label} products.");
811
+ }
812
+ } finally {
813
+ if (active) {
814
+ setLoading(false);
815
+ }
816
+ }
817
+ }
818
+
819
+ void loadProducts();
820
+
821
+ return () => {
822
+ active = false;
823
+ };
824
+ }, []);
825
+
826
+ async function startCheckout(product: BillingProduct) {
827
+ const productId = String(readProductField(product, "id") ?? "");
828
+ if (!productId) {
829
+ setError("This Stripe product is missing an id.");
830
+ return;
831
+ }
832
+
833
+ setCheckingOut(productId);
834
+ setError(null);
835
+
836
+ try {
837
+ const response = await apiClient.${input.key}.checkout({
838
+ body: {
839
+ productId,
840
+ successPath: "/billing/success",
841
+ cancelPath: "/integrations/${input.provider}",
842
+ },
843
+ });
844
+ if (response.error) {
845
+ throw new Error(readErrorMessage(response.error, "${input.label} checkout failed."));
846
+ }
847
+
848
+ const redirectTo = response.data?.redirectTo;
849
+ if (!redirectTo) {
850
+ throw new Error("${input.label} checkout did not return a redirect URL.");
851
+ }
852
+
853
+ window.location.assign(redirectTo);
854
+ } catch (cause) {
855
+ setError(cause instanceof Error ? cause.message : "Could not start ${input.label} checkout.");
856
+ setCheckingOut(null);
857
+ }
858
+ }
859
+
860
+ return (
861
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
862
+ <section className="mx-auto flex w-full max-w-5xl flex-col gap-8">
863
+ <div className="max-w-2xl space-y-3">
864
+ <Badge variant="secondary">${input.label}</Badge>
865
+ <h1 className="text-3xl font-semibold tracking-normal">${input.label} billing</h1>
866
+ <p className="text-sm leading-6 text-muted-foreground">
867
+ Plans, checkout, and customer billing actions in one place.
868
+ </p>
869
+ </div>
870
+
871
+ {error ? (
872
+ <div className="rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
873
+ {error}
874
+ </div>
875
+ ) : null}
876
+
877
+ {loading ? (
878
+ <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
879
+ {Array.from({ length: 3 }).map((_, index) => (
880
+ <Card key={index} className="min-h-[220px] animate-pulse" />
881
+ ))}
882
+ </div>
883
+ ) : products.length ? (
884
+ <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
885
+ {products.map((product) => {
886
+ const productId = String(readProductField(product, "id") ?? "");
887
+ const fallbackName = productId || "Product";
888
+ const name = String(readProductField(product, "name") ?? fallbackName);
889
+ const description =
890
+ readProductField(product, "description") ?? "Connected to your Stripe catalog.";
891
+
892
+ return (
893
+ <Card key={productId || name} className="flex min-h-[260px] flex-col">
894
+ <CardHeader>
895
+ <CardTitle className="text-xl">{name}</CardTitle>
896
+ <CardDescription>{String(description)}</CardDescription>
897
+ </CardHeader>
898
+ <CardContent className="flex-1">
899
+ <div className="text-3xl font-semibold">{formatProductPrice(product)}</div>
900
+ </CardContent>
901
+ <CardFooter>
902
+ <Button
903
+ className="w-full"
904
+ disabled={!productId || checkingOut === productId}
905
+ onClick={() => void startCheckout(product)}
906
+ >
907
+ {checkingOut === productId ? "Starting checkout..." : "Checkout"}
908
+ </Button>
909
+ </CardFooter>
910
+ </Card>
911
+ );
912
+ })}
913
+ </div>
914
+ ) : (
915
+ <Card>
916
+ <CardHeader>
917
+ <CardTitle>No products yet</CardTitle>
918
+ <CardDescription>
919
+ Add products to the generated ${input.label} integration template or provider dashboard.
920
+ </CardDescription>
921
+ </CardHeader>
922
+ </Card>
923
+ )}
924
+ </section>
925
+ </main>
926
+ );
927
+ }
928
+
929
+ function readProductField(product: BillingProduct, field: string) {
930
+ return (product as Record<string, unknown>)[field];
931
+ }
932
+
933
+ function formatProductPrice(product: BillingProduct) {
934
+ const amount = readProductField(product, "amount") ?? readProductField(product, "unitAmount");
935
+ const currency = String(readProductField(product, "currency") ?? "USD").toUpperCase();
936
+ const interval = readProductField(product, "interval");
937
+
938
+ if (typeof amount === "number" && Number.isFinite(amount)) {
939
+ const formatted = new Intl.NumberFormat("en", {
940
+ style: "currency",
941
+ currency,
942
+ }).format(amount / 100);
943
+
944
+ return interval ? \`\${formatted}/\${String(interval)}\` : formatted;
945
+ }
946
+
947
+ return "Custom";
948
+ }
949
+
950
+ function readErrorMessage(error: unknown, fallback: string) {
951
+ if (error && typeof error === "object" && "message" in error) {
952
+ return String((error as { message?: unknown }).message);
953
+ }
954
+
955
+ return fallback;
956
+ }
957
+ `;
958
+ }
959
+ function aiChatTemplate() {
960
+ return `"use client";
961
+
962
+ import * as React from "react";
963
+ import { Badge } from "@/components/ui/badge";
964
+ import { Button } from "@/components/ui/button";
965
+ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
966
+ import { Input } from "@/components/ui/input";
967
+
968
+ type ChatMessage = {
969
+ role: "user" | "assistant";
970
+ content: string;
971
+ };
972
+
973
+ export function AIChat() {
974
+ const [messages, setMessages] = React.useState<ChatMessage[]>([]);
975
+ const [input, setInput] = React.useState("");
976
+ const [pending, setPending] = React.useState(false);
977
+ const [error, setError] = React.useState<string | null>(null);
978
+
979
+ async function sendMessage(event: React.FormEvent<HTMLFormElement>) {
980
+ event.preventDefault();
981
+ const nextInput = input.trim();
982
+ if (!nextInput) {
983
+ return;
984
+ }
985
+
986
+ const nextMessages: ChatMessage[] = [...messages, { role: "user", content: nextInput }];
987
+ setMessages(nextMessages);
988
+ setInput("");
989
+ setPending(true);
990
+ setError(null);
991
+
992
+ try {
993
+ const response = await fetch("/api/chat", {
994
+ method: "POST",
995
+ headers: {
996
+ "content-type": "application/json",
997
+ },
998
+ body: JSON.stringify({
999
+ messages: nextMessages.map((message) => ({
1000
+ role: message.role,
1001
+ parts: [{ type: "text", text: message.content }],
1002
+ })),
1003
+ }),
1004
+ });
1005
+
1006
+ const text = await response.text();
1007
+ if (!response.ok) {
1008
+ throw new Error(text || "AI request failed.");
1009
+ }
1010
+
1011
+ setMessages([...nextMessages, { role: "assistant", content: text || "Done." }]);
1012
+ } catch (cause) {
1013
+ setError(cause instanceof Error ? cause.message : "AI request failed.");
1014
+ } finally {
1015
+ setPending(false);
1016
+ }
1017
+ }
1018
+
1019
+ return (
1020
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1021
+ <section className="mx-auto flex w-full max-w-3xl flex-col gap-6">
1022
+ <div className="space-y-3">
1023
+ <Badge variant="secondary">AI</Badge>
1024
+ <h1 className="text-3xl font-semibold tracking-normal">Chat</h1>
1025
+ </div>
1026
+
1027
+ <Card>
1028
+ <CardHeader>
1029
+ <CardTitle className="text-xl">Conversation</CardTitle>
1030
+ </CardHeader>
1031
+ <CardContent className="space-y-4">
1032
+ <div className="min-h-[320px] space-y-3 rounded-md border bg-muted/30 p-4">
1033
+ {messages.length ? (
1034
+ messages.map((message, index) => (
1035
+ <div
1036
+ key={index}
1037
+ 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"}
1038
+ >
1039
+ {message.content}
1040
+ </div>
1041
+ ))
1042
+ ) : (
1043
+ <p className="text-sm text-muted-foreground">Start a conversation.</p>
1044
+ )}
1045
+ </div>
1046
+
1047
+ {error ? <p className="text-sm text-destructive">{error}</p> : null}
1048
+
1049
+ <form className="flex gap-2" onSubmit={sendMessage}>
1050
+ <Input
1051
+ value={input}
1052
+ onChange={(event) => setInput(event.target.value)}
1053
+ placeholder="Ask something..."
1054
+ />
1055
+ <Button disabled={pending} type="submit">
1056
+ {pending ? "Sending..." : "Send"}
1057
+ </Button>
1058
+ </form>
1059
+ </CardContent>
1060
+ </Card>
1061
+ </section>
1062
+ </main>
1063
+ );
1064
+ }
1065
+ `;
1066
+ }
1067
+ function supabaseAuthTemplate(key) {
1068
+ return `"use client";
1069
+
1070
+ import * as React from "react";
1071
+ import { Badge } from "@/components/ui/badge";
1072
+ import { Button } from "@/components/ui/button";
1073
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1074
+ import { Input } from "@/components/ui/input";
1075
+ import { Label } from "@/components/ui/label";
1076
+ import { apiClient } from "@/lib/api";
1077
+
1078
+ export function SupabaseAuthPanel() {
1079
+ const [email, setEmail] = React.useState("");
1080
+ const [password, setPassword] = React.useState("");
1081
+ const [mode, setMode] = React.useState<"login" | "signup">("login");
1082
+ const [pending, setPending] = React.useState(false);
1083
+ const [status, setStatus] = React.useState<string | null>(null);
1084
+
1085
+ async function submit(event: React.FormEvent<HTMLFormElement>) {
1086
+ event.preventDefault();
1087
+ setPending(true);
1088
+ setStatus(null);
1089
+
1090
+ const response =
1091
+ mode === "login"
1092
+ ? await apiClient.${key}.login.post({ body: { email, password, returnTo: "/dashboard" } })
1093
+ : await apiClient.${key}.signup.post({ body: { email, password, returnTo: "/dashboard" } });
1094
+
1095
+ if (response.error) {
1096
+ setStatus(response.error.message);
1097
+ setPending(false);
1098
+ return;
1099
+ }
1100
+
1101
+ if (response.data?.redirectTo) {
1102
+ window.location.assign(response.data.redirectTo);
1103
+ return;
1104
+ }
1105
+
1106
+ setStatus(response.data?.message ?? "Check your email to continue.");
1107
+ setPending(false);
1108
+ }
1109
+
1110
+ async function loadSession() {
1111
+ const response = await apiClient.${key}.session.get();
1112
+ setStatus(response.error ? response.error.message : response.data?.authenticated ? "Authenticated" : "No active session");
1113
+ }
1114
+
1115
+ async function logout() {
1116
+ const response = await fetch("/auth/logout", {
1117
+ method: "POST",
1118
+ headers: { "content-type": "application/json" },
1119
+ body: JSON.stringify({ returnTo: "/" }),
1120
+ });
1121
+ const data = (await response.json()) as { redirectTo?: string; error?: string };
1122
+ if (data.redirectTo) {
1123
+ window.location.assign(data.redirectTo);
1124
+ return;
1125
+ }
1126
+ setStatus(data.error ?? "Signed out");
1127
+ }
1128
+
1129
+ return (
1130
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1131
+ <section className="mx-auto flex w-full max-w-xl flex-col gap-6">
1132
+ <div className="space-y-3">
1133
+ <Badge variant="secondary">Supabase</Badge>
1134
+ <h1 className="text-3xl font-semibold tracking-normal">Auth</h1>
1135
+ </div>
1136
+
1137
+ <Card>
1138
+ <CardHeader>
1139
+ <CardTitle className="text-xl">{mode === "login" ? "Sign in" : "Create account"}</CardTitle>
1140
+ <CardDescription>Email and password access for this app.</CardDescription>
1141
+ </CardHeader>
1142
+ <CardContent>
1143
+ <form className="space-y-4" onSubmit={submit}>
1144
+ <div className="space-y-2">
1145
+ <Label htmlFor="email">Email</Label>
1146
+ <Input id="email" value={email} onChange={(event) => setEmail(event.target.value)} type="email" />
1147
+ </div>
1148
+ <div className="space-y-2">
1149
+ <Label htmlFor="password">Password</Label>
1150
+ <Input id="password" value={password} onChange={(event) => setPassword(event.target.value)} type="password" />
1151
+ </div>
1152
+ {status ? <p className="text-sm text-muted-foreground">{status}</p> : null}
1153
+ <div className="flex flex-wrap gap-2">
1154
+ <Button disabled={pending} type="submit">{pending ? "Working..." : mode === "login" ? "Sign in" : "Sign up"}</Button>
1155
+ <Button type="button" variant="outline" onClick={() => setMode(mode === "login" ? "signup" : "login")}>
1156
+ {mode === "login" ? "Use sign up" : "Use sign in"}
1157
+ </Button>
1158
+ <Button type="button" variant="ghost" onClick={() => void loadSession()}>Session</Button>
1159
+ <Button type="button" variant="ghost" onClick={() => void logout()}>Logout</Button>
1160
+ </div>
1161
+ </form>
1162
+ </CardContent>
1163
+ </Card>
1164
+ </section>
1165
+ </main>
1166
+ );
1167
+ }
1168
+ `;
1169
+ }
1170
+ function hostedAuthTemplate(input) {
1171
+ return `"use client";
1172
+
1173
+ import * as React from "react";
1174
+ import { Badge } from "@/components/ui/badge";
1175
+ import { Button } from "@/components/ui/button";
1176
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1177
+ import { apiClient } from "@/lib/api";
1178
+
1179
+ export function ${input.componentName}() {
1180
+ const [status, setStatus] = React.useState<string>("Idle");
1181
+ const [pending, setPending] = React.useState(false);
1182
+
1183
+ async function refreshStatus() {
1184
+ setPending(true);
1185
+ const response = await apiClient.${input.key}.${input.statusCall}.${input.statusMethod}();
1186
+ if (response.error) {
1187
+ setStatus(response.error.message);
1188
+ } else {
1189
+ setStatus(response.data?.authenticated ? "Authenticated" : "No active session");
1190
+ }
1191
+ setPending(false);
1192
+ }
1193
+
1194
+ async function logout() {
1195
+ setPending(true);
1196
+ const response = await apiClient.${input.key}.${input.logoutCall}.${input.logoutMethod}();
1197
+ if (response.data?.redirectTo) {
1198
+ window.location.assign(response.data.redirectTo);
1199
+ return;
1200
+ }
1201
+ setStatus(response.error?.message ?? "Signed out");
1202
+ setPending(false);
1203
+ }
1204
+
1205
+ return (
1206
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1207
+ <section className="mx-auto flex w-full max-w-3xl flex-col gap-6">
1208
+ <div className="space-y-3">
1209
+ <Badge variant="secondary">${input.provider}</Badge>
1210
+ <h1 className="text-3xl font-semibold tracking-normal">Auth</h1>
1211
+ </div>
1212
+
1213
+ <Card>
1214
+ <CardHeader>
1215
+ <CardTitle className="text-xl">${input.provider} session</CardTitle>
1216
+ <CardDescription>Hosted auth, account session, and sign-out controls.</CardDescription>
1217
+ </CardHeader>
1218
+ <CardContent className="space-y-4">
1219
+ <p className="rounded-md border bg-muted/30 px-3 py-2 text-sm">{status}</p>
1220
+ <div className="flex flex-wrap gap-2">
1221
+ <Button type="button" onClick={() => window.location.assign("${input.loginHref}")}>Sign in</Button>
1222
+ <Button type="button" variant="outline" onClick={() => window.location.assign("${input.signupHref}")}>Sign up</Button>
1223
+ <Button type="button" variant="ghost" disabled={pending} onClick={() => void refreshStatus()}>Refresh</Button>
1224
+ <Button type="button" variant="ghost" disabled={pending} onClick={() => void logout()}>Logout</Button>
1225
+ </div>
1226
+ </CardContent>
1227
+ </Card>
1228
+ </section>
1229
+ </main>
1230
+ );
1231
+ }
1232
+ `;
1233
+ }
1234
+ function authRouteShellTemplate(input) {
1235
+ return `"use client";
1236
+
1237
+ import { Badge } from "@/components/ui/badge";
1238
+ import { Button } from "@/components/ui/button";
1239
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1240
+
1241
+ export function ${input.componentName}() {
1242
+ return (
1243
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1244
+ <section className="mx-auto flex w-full max-w-3xl flex-col gap-6">
1245
+ <div className="space-y-3">
1246
+ <Badge variant="secondary">${input.provider}</Badge>
1247
+ <h1 className="text-3xl font-semibold tracking-normal">Auth</h1>
1248
+ </div>
1249
+
1250
+ <Card>
1251
+ <CardHeader>
1252
+ <CardTitle className="text-xl">${input.provider} routes</CardTitle>
1253
+ <CardDescription>Account entry points and session route.</CardDescription>
1254
+ </CardHeader>
1255
+ <CardContent className="flex flex-wrap gap-2">
1256
+ <Button type="button" onClick={() => window.location.assign("${input.signInHref}")}>Sign in</Button>
1257
+ <Button type="button" variant="outline" onClick={() => window.location.assign("${input.signUpHref}")}>Sign up</Button>
1258
+ <Button type="button" variant="ghost" onClick={() => window.location.assign("${input.sessionHref}")}>Session</Button>
1259
+ </CardContent>
1260
+ </Card>
1261
+ </section>
1262
+ </main>
1263
+ );
1264
+ }
1265
+ `;
1266
+ }
1267
+ function betterAuthClientTemplate() {
1268
+ return `import { createAuthClient } from "better-auth/react";
1269
+
1270
+ export const authClient = createAuthClient({
1271
+ baseURL: "",
1272
+ });
1273
+ `;
1274
+ }
1275
+ function betterAuthPanelTemplate() {
1276
+ return `"use client";
1277
+
1278
+ import * as React from "react";
1279
+ import { Badge } from "@/components/ui/badge";
1280
+ import { Button } from "@/components/ui/button";
1281
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1282
+ import { Input } from "@/components/ui/input";
1283
+ import { Label } from "@/components/ui/label";
1284
+ import { authClient } from "@/lib/auth-client";
1285
+
1286
+ type Mode = "sign-in" | "sign-up";
1287
+
1288
+ export function BetterAuthPanel() {
1289
+ const [mode, setMode] = React.useState<Mode>("sign-in");
1290
+ const [pending, setPending] = React.useState(false);
1291
+ const [message, setMessage] = React.useState("Ready");
1292
+ const [sessionEmail, setSessionEmail] = React.useState<string | null>(null);
1293
+
1294
+ async function submit(event: React.FormEvent<HTMLFormElement>) {
1295
+ event.preventDefault();
1296
+ setPending(true);
1297
+ setMessage(mode === "sign-in" ? "Signing in…" : "Creating account…");
1298
+
1299
+ const form = new FormData(event.currentTarget);
1300
+ const email = String(form.get("email") || "");
1301
+ const password = String(form.get("password") || "");
1302
+ const name = String(form.get("name") || "");
1303
+ try {
1304
+ const response =
1305
+ mode === "sign-in"
1306
+ ? await authClient.signIn.email({ email, password })
1307
+ : await authClient.signUp.email({ email, password, name });
1308
+
1309
+ if (response.error) {
1310
+ setMessage(response.error.message || "Authentication failed.");
1311
+ return;
1312
+ }
1313
+
1314
+ setSessionEmail(email);
1315
+ setMessage(mode === "sign-in" ? "Signed in." : "Account created.");
1316
+ } catch (cause) {
1317
+ setMessage(cause instanceof Error ? cause.message : "Could not reach the auth server.");
1318
+ } finally {
1319
+ setPending(false);
1320
+ }
1321
+ }
1322
+
1323
+ async function refreshSession() {
1324
+ setPending(true);
1325
+ try {
1326
+ const response = await authClient.getSession();
1327
+ setSessionEmail(response.data?.user.email || null);
1328
+ setMessage(response.error?.message || (response.data ? "Session active." : "No active session."));
1329
+ } catch (cause) {
1330
+ setMessage(cause instanceof Error ? cause.message : "Could not read the session.");
1331
+ } finally {
1332
+ setPending(false);
1333
+ }
1334
+ }
1335
+
1336
+ async function signOut() {
1337
+ setPending(true);
1338
+ try {
1339
+ const response = await authClient.signOut();
1340
+ if (response.error) {
1341
+ setMessage(response.error.message || "Could not sign out.");
1342
+ return;
1343
+ }
1344
+ setSessionEmail(null);
1345
+ setMessage("Signed out.");
1346
+ } catch (cause) {
1347
+ setMessage(cause instanceof Error ? cause.message : "Could not reach the auth server.");
1348
+ } finally {
1349
+ setPending(false);
1350
+ }
1351
+ }
1352
+
1353
+ return (
1354
+ <main className="min-h-screen bg-background px-5 py-12 text-foreground sm:px-8">
1355
+ <section className="mx-auto grid w-full max-w-5xl gap-8 lg:grid-cols-[1fr_420px] lg:items-start">
1356
+ <div className="space-y-5 py-4">
1357
+ <Badge variant="secondary">Better Auth × Farm.js</Badge>
1358
+ <div className="space-y-3">
1359
+ <h1 className="max-w-xl text-4xl font-semibold tracking-tight sm:text-5xl">
1360
+ Authentication that starts ready.
1361
+ </h1>
1362
+ <p className="max-w-xl text-base leading-7 text-muted-foreground">
1363
+ Test account creation, email sign-in, session reads, and sign-out through Farm’s
1364
+ generated Better Auth integration.
1365
+ </p>
1366
+ </div>
1367
+ <div aria-live="polite" className="border-l-2 border-primary pl-4 text-sm">
1368
+ <p className="font-medium">{message}</p>
1369
+ <p className="mt-1 text-muted-foreground">
1370
+ {sessionEmail ? \`Signed in as \${sessionEmail}\` : "No authenticated user"}
1371
+ </p>
1372
+ </div>
1373
+ </div>
1374
+
1375
+ <Card>
1376
+ <CardHeader>
1377
+ <CardTitle>{mode === "sign-in" ? "Welcome back" : "Create an account"}</CardTitle>
1378
+ <CardDescription>
1379
+ {mode === "sign-in"
1380
+ ? "Enter your credentials to start a secure session."
1381
+ : "Use an email and password to create your local account."}
1382
+ </CardDescription>
1383
+ </CardHeader>
1384
+ <CardContent>
1385
+ <form className="space-y-4" onSubmit={submit}>
1386
+ {mode === "sign-up" ? (
1387
+ <div className="space-y-2">
1388
+ <Label htmlFor="name">Name</Label>
1389
+ <Input autoComplete="name" id="name" name="name" required />
1390
+ </div>
1391
+ ) : null}
1392
+ <div className="space-y-2">
1393
+ <Label htmlFor="email">Email</Label>
1394
+ <Input autoComplete="email" id="email" name="email" required type="email" />
1395
+ </div>
1396
+ <div className="space-y-2">
1397
+ <Label htmlFor="password">Password</Label>
1398
+ <Input
1399
+ autoComplete={mode === "sign-in" ? "current-password" : "new-password"}
1400
+ id="password"
1401
+ minLength={8}
1402
+ name="password"
1403
+ required
1404
+ type="password"
1405
+ />
1406
+ </div>
1407
+ <Button className="w-full" disabled={pending} type="submit">
1408
+ {pending ? "Working…" : mode === "sign-in" ? "Sign in" : "Create account"}
1409
+ </Button>
1410
+ </form>
1411
+
1412
+ <div className="mt-4 grid gap-2 sm:grid-cols-2">
1413
+ <Button
1414
+ disabled={pending}
1415
+ type="button"
1416
+ variant="outline"
1417
+ onClick={() => {
1418
+ setMode(mode === "sign-in" ? "sign-up" : "sign-in");
1419
+ setMessage("Ready");
1420
+ }}
1421
+ >
1422
+ {mode === "sign-in" ? "Create account" : "Use sign in"}
1423
+ </Button>
1424
+ <Button disabled={pending} type="button" variant="outline" onClick={() => void refreshSession()}>
1425
+ Check session
1426
+ </Button>
1427
+ </div>
1428
+ <Button
1429
+ className="mt-2 w-full"
1430
+ disabled={pending || !sessionEmail}
1431
+ type="button"
1432
+ variant="ghost"
1433
+ onClick={() => void signOut()}
1434
+ >
1435
+ Sign out
1436
+ </Button>
1437
+ </CardContent>
1438
+ </Card>
1439
+ </section>
1440
+ </main>
1441
+ );
1442
+ }
1443
+ `;
1444
+ }
1445
+ function resendEmailTemplate(key) {
1446
+ return `"use client";
1447
+
1448
+ import * as React from "react";
1449
+ import { Badge } from "@/components/ui/badge";
1450
+ import { Button } from "@/components/ui/button";
1451
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1452
+ import { Input } from "@/components/ui/input";
1453
+ import { Label } from "@/components/ui/label";
1454
+ import { apiClient } from "@/lib/api";
1455
+
1456
+ export function ResendEmailConsole() {
1457
+ const [to, setTo] = React.useState("");
1458
+ const [name, setName] = React.useState("Ada");
1459
+ const templateId = "welcome" as const;
1460
+ const [status, setStatus] = React.useState("Idle");
1461
+ const [previewHtml, setPreviewHtml] = React.useState("");
1462
+
1463
+ async function loadTemplates() {
1464
+ const response = await apiClient.${key}.templates();
1465
+ const templates = Array.isArray(response.data)
1466
+ ? (response.data as Array<{ id: string }>)
1467
+ : [];
1468
+ setStatus(response.error ? response.error.message : "Templates: " + templates.map((item) => item.id).join(", "));
1469
+ }
1470
+
1471
+ async function preview() {
1472
+ const response = await apiClient.${key}.preview({
1473
+ body: {
1474
+ templateId,
1475
+ data: { name },
1476
+ },
1477
+ });
1478
+ if (response.error) {
1479
+ setStatus(response.error.message);
1480
+ return;
1481
+ }
1482
+ setPreviewHtml(response.data?.html ?? "");
1483
+ setStatus(response.data?.subject ?? "Preview loaded");
1484
+ }
1485
+
1486
+ async function send() {
1487
+ const response = await apiClient.${key}.send({
1488
+ body: {
1489
+ templateId,
1490
+ to,
1491
+ data: { name },
1492
+ },
1493
+ });
1494
+ setStatus(response.error ? response.error.message : "Sent " + (response.data?.id ?? "email"));
1495
+ }
1496
+
1497
+ return (
1498
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1499
+ <section className="mx-auto flex w-full max-w-3xl flex-col gap-6">
1500
+ <div className="space-y-3">
1501
+ <Badge variant="secondary">Resend</Badge>
1502
+ <h1 className="text-3xl font-semibold tracking-normal">Email console</h1>
1503
+ </div>
1504
+ <Card>
1505
+ <CardHeader>
1506
+ <CardTitle className="text-xl">Send template</CardTitle>
1507
+ <CardDescription>Template previews and delivery controls.</CardDescription>
1508
+ </CardHeader>
1509
+ <CardContent className="space-y-4">
1510
+ <div className="grid gap-4 sm:grid-cols-2">
1511
+ <div className="space-y-2">
1512
+ <Label htmlFor="to">To</Label>
1513
+ <Input id="to" value={to} onChange={(event) => setTo(event.target.value)} />
1514
+ </div>
1515
+ <div className="space-y-2">
1516
+ <Label htmlFor="name">Name</Label>
1517
+ <Input id="name" value={name} onChange={(event) => setName(event.target.value)} />
1518
+ </div>
1519
+ </div>
1520
+ <p className="rounded-md border bg-muted/30 px-3 py-2 text-sm">{status}</p>
1521
+ {previewHtml ? <div className="max-h-64 overflow-auto rounded-md border p-3 text-sm" dangerouslySetInnerHTML={{ __html: previewHtml }} /> : null}
1522
+ <div className="flex flex-wrap gap-2">
1523
+ <Button type="button" variant="outline" onClick={() => void loadTemplates()}>Templates</Button>
1524
+ <Button type="button" variant="outline" onClick={() => void preview()}>Preview</Button>
1525
+ <Button type="button" onClick={() => void send()}>Send</Button>
1526
+ </div>
1527
+ </CardContent>
1528
+ </Card>
1529
+ </section>
1530
+ </main>
1531
+ );
1532
+ }
1533
+ `;
1534
+ }
1535
+ function jobsConsoleTemplate(key, label, provider) {
1536
+ return `"use client";
1537
+
1538
+ import * as React from "react";
1539
+ import { Badge } from "@/components/ui/badge";
1540
+ import { Button } from "@/components/ui/button";
1541
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1542
+ import { Input } from "@/components/ui/input";
1543
+ import { Label } from "@/components/ui/label";
1544
+ import { apiClient } from "@/lib/api";
1545
+
1546
+ type JobTask = {
1547
+ key: string;
1548
+ description?: string | null;
1549
+ };
1550
+
1551
+ export function ${`${pascalCase(provider)}JobsConsole`}() {
1552
+ const [tasks, setTasks] = React.useState<JobTask[]>([]);
1553
+ const [taskKey, setTaskKey] = React.useState("");
1554
+ const [runId, setRunId] = React.useState("");
1555
+ const [status, setStatus] = React.useState("Idle");
1556
+
1557
+ async function loadTasks() {
1558
+ const response = await apiClient.${key}.tasks.list();
1559
+ if (response.error) {
1560
+ setStatus(response.error.message);
1561
+ return;
1562
+ }
1563
+ const nextTasks = Array.from(response.data ?? []);
1564
+ setTasks(nextTasks);
1565
+ setTaskKey(nextTasks[0]?.key ?? "");
1566
+ setStatus(nextTasks.length ? "Tasks loaded" : "No tasks registered yet");
1567
+ }
1568
+
1569
+ async function triggerTask() {
1570
+ const task = (apiClient.${key} as Record<string, any>)[taskKey];
1571
+ if (!task?.trigger) {
1572
+ setStatus("Select a task first.");
1573
+ return;
1574
+ }
1575
+ const response = await task.trigger({ body: { input: {} } });
1576
+ setStatus(response.error ? response.error.message : "Triggered " + (response.data?.runId ?? response.data?.id ?? taskKey));
1577
+ }
1578
+
1579
+ async function checkStatus() {
1580
+ const task = (apiClient.${key} as Record<string, any>)[taskKey];
1581
+ if (!task?.status || !runId) {
1582
+ setStatus("Enter a task and run id.");
1583
+ return;
1584
+ }
1585
+ const response = await task.status({ query: { runId } });
1586
+ setStatus(response.error ? response.error.message : JSON.stringify(response.data));
1587
+ }
1588
+
1589
+ return (
1590
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1591
+ <section className="mx-auto flex w-full max-w-4xl flex-col gap-6">
1592
+ <div className="space-y-3">
1593
+ <Badge variant="secondary">${label}</Badge>
1594
+ <h1 className="text-3xl font-semibold tracking-normal">Jobs console</h1>
1595
+ </div>
1596
+ <Card>
1597
+ <CardHeader>
1598
+ <CardTitle className="text-xl">Tasks</CardTitle>
1599
+ <CardDescription>Task runs and status checks.</CardDescription>
1600
+ </CardHeader>
1601
+ <CardContent className="space-y-4">
1602
+ <div className="grid gap-4 sm:grid-cols-2">
1603
+ <div className="space-y-2">
1604
+ <Label htmlFor="taskKey">Task key</Label>
1605
+ <Input id="taskKey" value={taskKey} onChange={(event) => setTaskKey(event.target.value)} />
1606
+ </div>
1607
+ <div className="space-y-2">
1608
+ <Label htmlFor="runId">Run id</Label>
1609
+ <Input id="runId" value={runId} onChange={(event) => setRunId(event.target.value)} />
1610
+ </div>
1611
+ </div>
1612
+ <p className="rounded-md border bg-muted/30 px-3 py-2 text-sm">{status}</p>
1613
+ <div className="flex flex-wrap gap-2">
1614
+ <Button type="button" variant="outline" onClick={() => void loadTasks()}>Load tasks</Button>
1615
+ <Button type="button" onClick={() => void triggerTask()}>Trigger</Button>
1616
+ <Button type="button" variant="ghost" onClick={() => void checkStatus()}>Status</Button>
1617
+ </div>
1618
+ {tasks.length ? (
1619
+ <div className="grid gap-2">
1620
+ {tasks.map((task) => (
1621
+ <button key={task.key} className="rounded-md border px-3 py-2 text-left text-sm" onClick={() => setTaskKey(task.key)} type="button">
1622
+ {task.key}
1623
+ </button>
1624
+ ))}
1625
+ </div>
1626
+ ) : null}
1627
+ </CardContent>
1628
+ </Card>
1629
+ </section>
1630
+ </main>
1631
+ );
1632
+ }
1633
+ `;
1634
+ }
1635
+ function unkeyApiKeysTemplate() {
1636
+ return `import { Badge } from "@/components/ui/badge";
1637
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1638
+
1639
+ export function UnkeyApiKeysConsole() {
1640
+ return (
1641
+ <main className="min-h-screen bg-background px-6 py-12 text-foreground">
1642
+ <section className="mx-auto flex w-full max-w-3xl flex-col gap-6">
1643
+ <div className="space-y-3">
1644
+ <Badge variant="secondary">Unkey</Badge>
1645
+ <h1 className="text-3xl font-semibold tracking-normal">API keys</h1>
1646
+ </div>
1647
+ <Card>
1648
+ <CardHeader>
1649
+ <CardTitle className="text-xl">Protected API</CardTitle>
1650
+ <CardDescription>Requests are verified by Unkey before the route runs.</CardDescription>
1651
+ </CardHeader>
1652
+ <CardContent className="space-y-3">
1653
+ <code className="block overflow-x-auto rounded-md border bg-muted/30 p-3 text-xs">
1654
+ curl http://localhost:3000/api/protected -H &quot;Authorization: Bearer YOUR_KEY&quot;
1655
+ </code>
1656
+ <p className="text-sm text-muted-foreground">
1657
+ Create and rotate keys from trusted server code or the Unkey dashboard.
1658
+ </p>
1659
+ </CardContent>
1660
+ </Card>
1661
+ </section>
1662
+ </main>
1663
+ );
1664
+ }
1665
+ `;
1666
+ }
1667
+ function unkeyProtectedRouteTemplate() {
1668
+ return `export function GET() {
1669
+ return Response.json({
1670
+ ok: true,
1671
+ message: "Valid Unkey API key.",
1672
+ });
1673
+ }
1674
+ `;
1675
+ }
1676
+ function pascalCase(input) {
1677
+ return input.split(/[^A-Za-z0-9]+/g).filter(Boolean).map((part) => `${part.charAt(0).toUpperCase()}${part.slice(1)}`).join("");
1678
+ }
1679
+ function kebabCase(input) {
1680
+ return input.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[^A-Za-z0-9]+/g, "-").replace(/^-+|-+$/g, "").toLowerCase();
1681
+ }
1682
+ function hasPackageDependency$1(manifest, dependency) {
1683
+ return dependency in (manifest.dependencies || {}) || dependency in (manifest.devDependencies || {}) || dependency in (manifest.peerDependencies || {}) || dependency in (manifest.optionalDependencies || {});
1684
+ }
1685
+ function readObject(value) {
1686
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1687
+ }
1688
+ function pushResultPath(list, filePath) {
1689
+ if (!list.includes(filePath)) list.push(filePath);
1690
+ }
1691
+ //#endregion
1692
+ //#region ../farm-cli/src/add-integration.ts
1693
+ const PROVIDERS = [
1694
+ {
1695
+ provider: "ai",
1696
+ aliases: [
1697
+ "ai-sdk",
1698
+ "vercel-ai",
1699
+ "vercel-ai-sdk",
1700
+ "chat"
1701
+ ],
1702
+ defaultKey: "chat",
1703
+ packageName: "@farm.js/ai",
1704
+ fileName: "chat",
1705
+ exportName: "POST",
1706
+ description: "Vercel AI SDK chat route",
1707
+ env: ["AI_GATEWAY_API_KEY"],
1708
+ notes: [
1709
+ "Use @ai-sdk/react useChat with api: \"/api/chat\" on the client.",
1710
+ "Replace model with any AI SDK provider model or Vercel AI Gateway model id.",
1711
+ "No farm.config integration wiring is required for this route."
1712
+ ],
1713
+ ui: aiChatUIFeature(),
1714
+ template: () => `import { aiChatRoute } from "@farm.js/ai";
1715
+
1716
+ export const POST = aiChatRoute({
1717
+ model: "openai/gpt-4o-mini",
1718
+ system: "You are a helpful assistant.",
1719
+ });
1720
+ `
1721
+ },
1722
+ {
1723
+ provider: "stripe",
1724
+ aliases: [
1725
+ "billing-stripe",
1726
+ "payments",
1727
+ "stripe-billing"
1728
+ ],
1729
+ defaultKey: "billing",
1730
+ packageName: "@farm.js/stripe",
1731
+ fileName: "stripe",
1732
+ exportName: "stripeIntegration",
1733
+ description: "Stripe billing and checkout routes",
1734
+ env: ["STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET"],
1735
+ template: () => `import type { FarmIntegrationLogEvent } from "@farm.js/core";
1736
+ import { stripe } from "@farm.js/stripe";
1737
+
1738
+ export const stripeIntegration = stripe({
1739
+ secretKey: process.env.STRIPE_SECRET_KEY,
1740
+ webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
1741
+ products: [],
1742
+ log(event: FarmIntegrationLogEvent) {
1743
+ console.log("[stripe]", event.phase, event.route?.path || "none");
1744
+ },
1745
+ });
1746
+ `,
1747
+ ui: stripeBillingUIFeature()
1748
+ },
1749
+ {
1750
+ provider: "supabase",
1751
+ aliases: ["auth-supabase", "supabase-auth"],
1752
+ defaultKey: "auth",
1753
+ packageName: "@farm.js/supabase",
1754
+ fileName: "supabase",
1755
+ exportName: "supabaseIntegration",
1756
+ description: "Supabase auth routes and middleware",
1757
+ env: [
1758
+ "SUPABASE_URL",
1759
+ "SUPABASE_ANON_KEY",
1760
+ "APP_BASE_URL"
1761
+ ],
1762
+ ui: supabaseAuthUIFeature(),
1763
+ template: () => `import { supabase } from "@farm.js/supabase";
1764
+
1765
+ export const supabaseIntegration = supabase({
1766
+ callbackUrl: \`\${process.env.APP_BASE_URL || "http://localhost:3000"}/auth/callback\`,
1767
+ protectedRoutes: ["/dashboard(.*)"],
1768
+ pages: {
1769
+ signIn: "/sign-in",
1770
+ signUp: "/sign-up",
1771
+ },
1772
+ log(event) {
1773
+ console.log("[supabase]", event.phase, event.route?.path || "none");
1774
+ },
1775
+ });
1776
+ `
1777
+ },
1778
+ {
1779
+ provider: "workos",
1780
+ aliases: ["auth-workos", "workos-auth"],
1781
+ defaultKey: "auth",
1782
+ packageName: "@farm.js/workos",
1783
+ fileName: "workos",
1784
+ exportName: "workosIntegration",
1785
+ description: "WorkOS auth routes and protected route middleware",
1786
+ env: [
1787
+ "WORKOS_CLIENT_ID",
1788
+ "WORKOS_API_KEY",
1789
+ "WORKOS_COOKIE_PASSWORD"
1790
+ ],
1791
+ ui: workosAuthUIFeature(),
1792
+ template: () => `import { workos } from "@farm.js/workos";
1793
+
1794
+ export const workosIntegration = workos({
1795
+ protectedRoutes: ["/dashboard(.*)"],
1796
+ log(event) {
1797
+ console.log("[workos]", event.phase, event.route?.path || "none");
1798
+ },
1799
+ });
1800
+ `
1801
+ },
1802
+ {
1803
+ provider: "auth0",
1804
+ aliases: ["auth-auth0", "auth0-auth"],
1805
+ defaultKey: "auth",
1806
+ packageName: "@farm.js/auth0",
1807
+ fileName: "auth0",
1808
+ exportName: "auth0Integration",
1809
+ description: "Auth0 login, callback, logout, and profile routes",
1810
+ env: [
1811
+ "AUTH0_DOMAIN",
1812
+ "AUTH0_CLIENT_ID",
1813
+ "AUTH0_CLIENT_SECRET",
1814
+ "AUTH0_SECRET"
1815
+ ],
1816
+ ui: auth0AuthUIFeature(),
1817
+ template: () => `import { auth0 } from "@farm.js/auth0";
1818
+
1819
+ export const auth0Integration = auth0({
1820
+ callbackUrl: \`\${process.env.APP_BASE_URL || "http://localhost:3000"}/auth/callback\`,
1821
+ protectedRoutes: ["/dashboard(.*)"],
1822
+ log(event) {
1823
+ console.log("[auth0]", event.phase, event.route?.path || "none");
1824
+ },
1825
+ });
1826
+ `
1827
+ },
1828
+ {
1829
+ provider: "clerk",
1830
+ aliases: ["auth-clerk", "clerk-auth"],
1831
+ defaultKey: "auth",
1832
+ packageName: "@farm.js/clerk",
1833
+ fileName: "clerk",
1834
+ exportName: "clerkIntegration",
1835
+ description: "Clerk auth provider and protected route middleware",
1836
+ env: ["NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY", "CLERK_SECRET_KEY"],
1837
+ dependencies: { "@clerk/react": "^6.1.0" },
1838
+ ui: clerkAuthUIFeature(),
1839
+ template: () => `import { clerk } from "@farm.js/clerk";
1840
+
1841
+ export const clerkIntegration = clerk({
1842
+ signInUrl: "/sign-in",
1843
+ signUpUrl: "/sign-up",
1844
+ protectedRoutes: ["/dashboard(.*)"],
1845
+ log(event) {
1846
+ console.log("[clerk]", event.phase, event.route?.path || "none");
1847
+ },
1848
+ });
1849
+ `
1850
+ },
1851
+ {
1852
+ provider: "resend",
1853
+ aliases: ["email", "resend-email"],
1854
+ defaultKey: "email",
1855
+ packageName: "@farm.js/email",
1856
+ fileName: "resend",
1857
+ exportName: "resendIntegration",
1858
+ description: "Resend email send, preview, schedule, and webhook routes",
1859
+ env: [
1860
+ "RESEND_API_KEY",
1861
+ "RESEND_FROM_EMAIL",
1862
+ "RESEND_WEBHOOK_SECRET"
1863
+ ],
1864
+ ui: resendEmailUIFeature(),
1865
+ template: () => `import { createElement } from "react";
1866
+ import { resend, template } from "@farm.js/email";
1867
+
1868
+ function WelcomeEmail(props: { name: string }) {
1869
+ return createElement("div", null, \`Welcome \${props.name}\`);
1870
+ }
1871
+
1872
+ WelcomeEmail.PreviewProps = {
1873
+ name: "Ada",
1874
+ };
1875
+
1876
+ export const emailTemplates = {
1877
+ welcome: template(WelcomeEmail, {
1878
+ subject: ({ name }) => \`Welcome, \${name}\`,
1879
+ previewText: () => "Welcome to the app",
1880
+ }),
1881
+ } as const;
1882
+
1883
+ export const resendIntegration = resend({
1884
+ apiKey: process.env.RESEND_API_KEY,
1885
+ defaults: {
1886
+ from: process.env.RESEND_FROM_EMAIL,
1887
+ replyTo: process.env.RESEND_REPLY_TO_EMAIL ?? process.env.RESEND_FROM_EMAIL,
1888
+ },
1889
+ templates: emailTemplates,
1890
+ webhooks: process.env.RESEND_WEBHOOK_SECRET
1891
+ ? {
1892
+ secret: process.env.RESEND_WEBHOOK_SECRET,
1893
+ }
1894
+ : undefined,
1895
+ log(event) {
1896
+ console.log("[resend]", event.phase, event.route?.path || "none");
1897
+ },
1898
+ });
1899
+ `
1900
+ },
1901
+ {
1902
+ provider: "jobs-inngest",
1903
+ aliases: ["inngest", "jobs"],
1904
+ defaultKey: "jobs",
1905
+ packageName: "@farm.js/jobs",
1906
+ fileName: "jobs-inngest",
1907
+ exportName: "jobsIntegration",
1908
+ description: "Jobs integration backed by Inngest",
1909
+ env: [
1910
+ "INNGEST_APP_ID",
1911
+ "INNGEST_EVENT_KEY",
1912
+ "INNGEST_SIGNING_KEY"
1913
+ ],
1914
+ notes: ["Add tasks to jobTasks before using the generated jobs API."],
1915
+ ui: jobsUIFeature("inngest"),
1916
+ template: () => `import { defineTasks, inngest, jobs } from "@farm.js/jobs";
1917
+
1918
+ export const jobTasks = defineTasks({});
1919
+
1920
+ export const jobsIntegration = jobs({
1921
+ runtime: inngest({
1922
+ appId: process.env.INNGEST_APP_ID,
1923
+ eventKey: process.env.INNGEST_EVENT_KEY,
1924
+ signingKey: process.env.INNGEST_SIGNING_KEY,
1925
+ }),
1926
+ tasks: jobTasks,
1927
+ log(event) {
1928
+ console.log("[jobs:inngest]", event.phase, event.route?.path || "none");
1929
+ },
1930
+ });
1931
+ `
1932
+ },
1933
+ {
1934
+ provider: "jobs-trigger",
1935
+ aliases: [
1936
+ "trigger",
1937
+ "trigger-dev",
1938
+ "jobs-triggerdev"
1939
+ ],
1940
+ defaultKey: "jobs",
1941
+ packageName: "@farm.js/jobs",
1942
+ fileName: "jobs-trigger",
1943
+ exportName: "jobsIntegration",
1944
+ description: "Jobs integration backed by Trigger.dev",
1945
+ env: [
1946
+ "TRIGGER_PROJECT_REF",
1947
+ "TRIGGER_SECRET_KEY",
1948
+ "TRIGGER_WEBHOOK_SECRET"
1949
+ ],
1950
+ notes: ["Add tasks to jobTasks before using the generated jobs API."],
1951
+ ui: jobsUIFeature("trigger"),
1952
+ template: () => `import { defineTasks, jobs, trigger } from "@farm.js/jobs";
1953
+
1954
+ export const jobTasks = defineTasks({});
1955
+
1956
+ export const jobsIntegration = jobs({
1957
+ runtime: trigger({
1958
+ projectRef: process.env.TRIGGER_PROJECT_REF,
1959
+ apiKey: process.env.TRIGGER_SECRET_KEY,
1960
+ webhookSecret: process.env.TRIGGER_WEBHOOK_SECRET,
1961
+ }),
1962
+ tasks: jobTasks,
1963
+ log(event) {
1964
+ console.log("[jobs:trigger]", event.phase, event.route?.path || "none");
1965
+ },
1966
+ });
1967
+ `
1968
+ },
1969
+ {
1970
+ provider: "polar",
1971
+ aliases: ["polar-billing", "billing-polar"],
1972
+ defaultKey: "billing",
1973
+ packageName: "@farm.js/polar",
1974
+ fileName: "polar",
1975
+ exportName: "polarIntegration",
1976
+ description: "Polar billing and checkout routes",
1977
+ env: [
1978
+ "POLAR_ACCESS_TOKEN",
1979
+ "POLAR_WEBHOOK_SECRET",
1980
+ "APP_BASE_URL"
1981
+ ],
1982
+ notes: ["Replace resolveBillingOwner with your app user or organization lookup."],
1983
+ ui: polarBillingUIFeature(),
1984
+ template: () => `import type { FarmIntegrationHandlerContext } from "@farm.js/core";
1985
+ import { polar } from "@farm.js/polar";
1986
+
1987
+ function resolveBillingOwner(_context: FarmIntegrationHandlerContext): never {
1988
+ throw new Error("Configure Polar billing owner resolution for your app.");
1989
+ }
1990
+
1991
+ export const polarIntegration = polar({
1992
+ accessToken: process.env.POLAR_ACCESS_TOKEN,
1993
+ server: (process.env.POLAR_SERVER as "sandbox" | "production" | undefined) ?? "sandbox",
1994
+ appBaseUrl: process.env.APP_BASE_URL,
1995
+ webhooks: process.env.POLAR_WEBHOOK_SECRET
1996
+ ? {
1997
+ secret: process.env.POLAR_WEBHOOK_SECRET,
1998
+ }
1999
+ : undefined,
2000
+ billing: {
2001
+ resolveOwner: resolveBillingOwner,
2002
+ plans: {},
2003
+ products: {},
2004
+ },
2005
+ log(event) {
2006
+ console.log("[polar]", event.phase, event.route?.path || "none");
2007
+ },
2008
+ });
2009
+ `
2010
+ },
2011
+ {
2012
+ provider: "autumn",
2013
+ aliases: ["autumn-billing", "billing-autumn"],
2014
+ defaultKey: "billing",
2015
+ packageName: "@farm.js/autumn",
2016
+ fileName: "autumn",
2017
+ exportName: "autumnIntegration",
2018
+ description: "Autumn billing and checkout routes",
2019
+ env: [
2020
+ "AUTUMN_SECRET_KEY",
2021
+ "AUTUMN_WEBHOOK_SECRET",
2022
+ "APP_BASE_URL"
2023
+ ],
2024
+ notes: ["Replace resolveBillingOwner with your app user or organization lookup."],
2025
+ ui: autumnBillingUIFeature(),
2026
+ template: () => `import type { FarmIntegrationHandlerContext } from "@farm.js/core";
2027
+ import { autumn } from "@farm.js/autumn";
2028
+
2029
+ function resolveBillingOwner(_context: FarmIntegrationHandlerContext): never {
2030
+ throw new Error("Configure Autumn billing owner resolution for your app.");
2031
+ }
2032
+
2033
+ export const autumnIntegration = autumn({
2034
+ secretKey: process.env.AUTUMN_SECRET_KEY,
2035
+ appBaseUrl: process.env.APP_BASE_URL,
2036
+ webhooks: process.env.AUTUMN_WEBHOOK_SECRET
2037
+ ? {
2038
+ secret: process.env.AUTUMN_WEBHOOK_SECRET,
2039
+ }
2040
+ : undefined,
2041
+ billing: {
2042
+ resolveOwner: resolveBillingOwner,
2043
+ plans: {},
2044
+ products: {},
2045
+ },
2046
+ log(event) {
2047
+ console.log("[autumn]", event.phase, event.route?.path || "none");
2048
+ },
2049
+ });
2050
+ `
2051
+ },
2052
+ {
2053
+ provider: "better-auth",
2054
+ aliases: ["betterauth", "auth-better-auth"],
2055
+ defaultKey: "auth",
2056
+ packageName: "@farm.js/better-auth",
2057
+ fileName: "better-auth",
2058
+ exportName: "betterAuthIntegration",
2059
+ description: "Better Auth route adapter",
2060
+ env: [
2061
+ "BETTER_AUTH_SECRET",
2062
+ "BETTER_AUTH_URL",
2063
+ "BETTER_AUTH_DATABASE_PATH"
2064
+ ],
2065
+ dependencies: {
2066
+ "better-auth": "^1.5.5",
2067
+ "better-sqlite3": "^12.6.2"
2068
+ },
2069
+ devDependencies: { "@types/better-sqlite3": "^7.6.13" },
2070
+ 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."],
2071
+ setupFiles: [
2072
+ {
2073
+ path: "src/lib/auth.ts",
2074
+ source: () => `import Database from "better-sqlite3";
2075
+ import { betterAuth as createBetterAuth } from "better-auth";
2076
+ import { getMigrations } from "better-auth/db/migration";
2077
+
2078
+ const baseURL = process.env.BETTER_AUTH_URL || "http://localhost:3000";
2079
+ export const auth = createBetterAuth({
2080
+ database: new Database(process.env.BETTER_AUTH_DATABASE_PATH || "better-auth.sqlite"),
2081
+ secret: process.env.BETTER_AUTH_SECRET,
2082
+ baseURL,
2083
+ trustedOrigins: [baseURL],
2084
+ emailAndPassword: {
2085
+ enabled: true,
2086
+ },
2087
+ });
2088
+
2089
+ const migrations = await getMigrations(auth.options);
2090
+ await migrations.runMigrations();
2091
+ `
2092
+ },
2093
+ {
2094
+ path: ".env.example",
2095
+ merge: "lines",
2096
+ source: () => `BETTER_AUTH_SECRET=replace-with-at-least-32-random-characters
2097
+ BETTER_AUTH_URL=http://localhost:3000
2098
+ BETTER_AUTH_DATABASE_PATH=better-auth.sqlite
2099
+ `
2100
+ },
2101
+ {
2102
+ path: ".gitignore",
2103
+ merge: "lines",
2104
+ source: () => `better-auth.sqlite
2105
+ better-auth.sqlite-shm
2106
+ better-auth.sqlite-wal
2107
+ `
2108
+ }
2109
+ ],
2110
+ ui: betterAuthUIFeature(),
2111
+ template: () => `import { betterAuth } from "@farm.js/better-auth";
2112
+ import { auth } from "../auth.ts";
2113
+
2114
+ export const betterAuthIntegration = betterAuth({
2115
+ instance: auth,
2116
+ log(event) {
2117
+ console.log("[better-auth]", event.phase, event.route?.path || "none");
2118
+ },
2119
+ });
2120
+ `
2121
+ },
2122
+ {
2123
+ provider: "authjs",
2124
+ aliases: [
2125
+ "auth-js",
2126
+ "nextauth",
2127
+ "next-auth"
2128
+ ],
2129
+ defaultKey: "auth",
2130
+ packageName: "@farm.js/authjs",
2131
+ fileName: "authjs",
2132
+ exportName: "authjsIntegration",
2133
+ description: "Auth.js route adapter",
2134
+ env: [
2135
+ "AUTH_SECRET",
2136
+ "AUTH_GITHUB_ID",
2137
+ "AUTH_GITHUB_SECRET"
2138
+ ],
2139
+ dependencies: { "@auth/core": "0.34.3" },
2140
+ setupFiles: [{
2141
+ path: "src/lib/auth.ts",
2142
+ source: () => `import { Auth } from "@auth/core";
2143
+ import GitHub from "@auth/core/providers/github";
2144
+
2145
+ const config = {
2146
+ providers: [
2147
+ GitHub({
2148
+ clientId: process.env.AUTH_GITHUB_ID!,
2149
+ clientSecret: process.env.AUTH_GITHUB_SECRET!,
2150
+ }),
2151
+ ],
2152
+ secret: process.env.AUTH_SECRET,
2153
+ trustHost: true,
2154
+ };
2155
+
2156
+ const handler = (request: Request) => Auth(request, config);
2157
+
2158
+ export const auth = {
2159
+ handlers: {
2160
+ GET: handler,
2161
+ POST: handler,
2162
+ },
2163
+ };
2164
+ `
2165
+ }],
2166
+ notes: ["The generated Auth.js instance uses GitHub OAuth through @auth/core; add or replace providers in src/lib/auth.ts."],
2167
+ ui: authjsUIFeature(),
2168
+ template: () => `import { authjs } from "@farm.js/authjs";
2169
+ import { auth } from "../auth.ts";
2170
+
2171
+ export const authjsIntegration = authjs({
2172
+ instance: auth,
2173
+ log(event) {
2174
+ console.log("[authjs]", event.phase, event.route?.path || "none");
2175
+ },
2176
+ });
2177
+ `
2178
+ },
2179
+ {
2180
+ provider: "unkey",
2181
+ aliases: [
2182
+ "api-keys",
2183
+ "apikeys",
2184
+ "keys",
2185
+ "unkey-api-keys"
2186
+ ],
2187
+ defaultKey: "apiKeys",
2188
+ packageName: "@farm.js/unkey",
2189
+ fileName: "unkey",
2190
+ exportName: "unkeyIntegration",
2191
+ description: "Unkey API key creation, verification, and route protection",
2192
+ env: [
2193
+ "UNKEY_ROOT_KEY",
2194
+ "UNKEY_API_ID",
2195
+ "UNKEY_BASE_URL"
2196
+ ],
2197
+ ui: unkeyApiKeysUIFeature(),
2198
+ template: () => `import { unkey } from "@farm.js/unkey";
2199
+
2200
+ export const unkeyIntegration = unkey({
2201
+ rootKey: process.env.UNKEY_ROOT_KEY,
2202
+ apiId: process.env.UNKEY_API_ID,
2203
+ baseUrl: process.env.UNKEY_BASE_URL,
2204
+ protectedRoutes: ["/api/protected(.*)"],
2205
+ log(event) {
2206
+ console.log("[unkey]", event.phase, event.route?.path || "none");
2207
+ },
2208
+ });
2209
+ `
2210
+ }
2211
+ ];
2212
+ async function addFarmIntegration(options) {
2213
+ const root = node_path.default.resolve(options.root || process.cwd());
2214
+ const definition = resolveProvider(options.provider);
2215
+ if (definition.provider === "ai") return addAIRouteIntegration({
2216
+ root,
2217
+ definition,
2218
+ routeFile: options.routeFile,
2219
+ ui: options.ui,
2220
+ skipPackageJson: options.skipPackageJson,
2221
+ dryRun: options.dryRun,
2222
+ force: options.force
2223
+ });
2224
+ const key = options.key || definition.defaultKey;
2225
+ assertValidIntegrationKey(key);
2226
+ const registryFile = node_path.default.resolve(root, options.integrationsFile || node_path.default.join("src", "lib", "integrations.ts"));
2227
+ const integrationFile = node_path.default.join(node_path.default.dirname(registryFile), "integrations", `${definition.fileName}.ts`);
2228
+ const result = {
2229
+ provider: definition.provider,
2230
+ key,
2231
+ mode: "integration",
2232
+ integrationFile,
2233
+ registryFile,
2234
+ created: [],
2235
+ updated: [],
2236
+ skipped: [],
2237
+ env: [...definition.env],
2238
+ notes: [...definition.notes || []]
2239
+ };
2240
+ await writeIntegrationComponent({
2241
+ path: integrationFile,
2242
+ definition,
2243
+ force: options.force,
2244
+ dryRun: options.dryRun,
2245
+ result
2246
+ });
2247
+ await writeIntegrationSetupFiles({
2248
+ root,
2249
+ definition,
2250
+ force: options.force,
2251
+ dryRun: options.dryRun,
2252
+ result
2253
+ });
2254
+ await writeIntegrationRegistry({
2255
+ path: registryFile,
2256
+ integrationFile,
2257
+ definition,
2258
+ key,
2259
+ dryRun: options.dryRun,
2260
+ result
2261
+ });
2262
+ if (!options.skipPackageJson) await updatePackageJson$1({
2263
+ root,
2264
+ definition,
2265
+ dryRun: options.dryRun,
2266
+ result
2267
+ });
2268
+ if (!options.skipConfig) await updateFarmConfig({
2269
+ root,
2270
+ registryFile,
2271
+ dryRun: options.dryRun,
2272
+ result
2273
+ });
2274
+ if (options.ui) await installUIFeature({
2275
+ root,
2276
+ definition,
2277
+ key,
2278
+ dryRun: options.dryRun,
2279
+ force: options.force,
2280
+ skipPackageJson: options.skipPackageJson,
2281
+ result
2282
+ });
2283
+ return result;
2284
+ }
2285
+ async function addAIRouteIntegration(input) {
2286
+ const routeFile = node_path.default.resolve(input.root, input.routeFile || node_path.default.join("src", "app", "api", "chat", "route.ts"));
2287
+ const result = {
2288
+ provider: "ai",
2289
+ key: input.definition.defaultKey,
2290
+ mode: "route",
2291
+ integrationFile: routeFile,
2292
+ registryFile: "",
2293
+ routeFile,
2294
+ routePath: "/api/chat",
2295
+ created: [],
2296
+ updated: [],
2297
+ skipped: [],
2298
+ env: [...input.definition.env],
2299
+ notes: [...input.definition.notes || []]
2300
+ };
2301
+ await writeIntegrationComponent({
2302
+ path: routeFile,
2303
+ definition: input.definition,
2304
+ force: input.force,
2305
+ dryRun: input.dryRun,
2306
+ result
2307
+ });
2308
+ if (!input.skipPackageJson) await updatePackageJson$1({
2309
+ root: input.root,
2310
+ definition: input.definition,
2311
+ dryRun: input.dryRun,
2312
+ result
2313
+ });
2314
+ if (input.ui) await installUIFeature({
2315
+ root: input.root,
2316
+ definition: input.definition,
2317
+ key: input.definition.defaultKey,
2318
+ dryRun: input.dryRun,
2319
+ force: input.force,
2320
+ skipPackageJson: input.skipPackageJson,
2321
+ result
2322
+ });
2323
+ return result;
2324
+ }
2325
+ function resolveProvider(input) {
2326
+ const normalized = input.trim().toLowerCase();
2327
+ const match = PROVIDERS.find((provider) => provider.provider === normalized || provider.aliases.includes(normalized));
2328
+ if (!match) {
2329
+ const supported = PROVIDERS.map((provider) => provider.provider).join(", ");
2330
+ throw new Error(`Unknown integration "${input}". Supported integrations: ${supported}.`);
2331
+ }
2332
+ return match;
2333
+ }
2334
+ function assertValidIntegrationKey(key) {
2335
+ if (!/^[A-Za-z_$][\w$]*$/.test(key)) throw new Error(`Integration key "${key}" must be a valid JavaScript object property name.`);
2336
+ }
2337
+ async function writeIntegrationComponent(input) {
2338
+ const exists = (0, node_fs.existsSync)(input.path);
2339
+ if (exists && !input.force) {
2340
+ input.result.skipped.push(input.path);
2341
+ return;
2342
+ }
2343
+ if (!input.dryRun) {
2344
+ await (0, node_fs_promises.mkdir)(node_path.default.dirname(input.path), { recursive: true });
2345
+ await (0, node_fs_promises.writeFile)(input.path, input.definition.template(), "utf8");
2346
+ }
2347
+ if (exists) input.result.updated.push(input.path);
2348
+ else input.result.created.push(input.path);
2349
+ }
2350
+ async function writeIntegrationRegistry(input) {
2351
+ const importPath = toImportPath(node_path.default.relative(node_path.default.dirname(input.path), input.integrationFile));
2352
+ const importLine = `import { ${input.definition.exportName} } from "${importPath}";`;
2353
+ const propertyLine = ` ${input.key}: ${input.definition.exportName},`;
2354
+ let nextSource;
2355
+ const exists = (0, node_fs.existsSync)(input.path);
2356
+ if (exists) nextSource = ensureRegistryEntry(await (0, node_fs_promises.readFile)(input.path, "utf8"), {
2357
+ importLine,
2358
+ propertyLine,
2359
+ key: input.key,
2360
+ exportName: input.definition.exportName
2361
+ });
2362
+ else nextSource = `${importLine}
2363
+
2364
+ export const appIntegrations = {
2365
+ ${propertyLine}
2366
+ } as const;
2367
+
2368
+ export type AppIntegrations = typeof appIntegrations;
2369
+ `;
2370
+ if (!input.dryRun) {
2371
+ await (0, node_fs_promises.mkdir)(node_path.default.dirname(input.path), { recursive: true });
2372
+ await (0, node_fs_promises.writeFile)(input.path, nextSource, "utf8");
2373
+ }
2374
+ input.result[exists ? "updated" : "created"].push(input.path);
2375
+ }
2376
+ function ensureRegistryEntry(source, input) {
2377
+ if (new RegExp(`(^|\\n)\\s*${escapeRegExp(input.key)}\\s*:`, "m").test(source)) {
2378
+ if (source.includes(`${input.key}: ${input.exportName}`)) return source.includes(input.importLine) ? source : `${input.importLine}\n${source}`;
2379
+ throw new Error(`Integration key "${input.key}" already exists in the app integrations registry. Pass --key to use a different key.`);
2380
+ }
2381
+ const sourceWithImport = source.includes(input.importLine) ? source : `${input.importLine}\n${source}`;
2382
+ const appIntegrationsPattern = /export\s+const\s+appIntegrations\s*=\s*\{([\s\S]*?)\}\s*as\s+const;/m;
2383
+ const match = sourceWithImport.match(appIntegrationsPattern);
2384
+ if (!match) return `${sourceWithImport.trimEnd()}
2385
+
2386
+ export const appIntegrations = {
2387
+ ${input.propertyLine}
2388
+ } as const;
2389
+
2390
+ export type AppIntegrations = typeof appIntegrations;
2391
+ `;
2392
+ const body = match[1] || "";
2393
+ const nextBody = body.trim().length ? `${body.trimEnd()}\n${input.propertyLine}\n` : `\n${input.propertyLine}\n`;
2394
+ return sourceWithImport.replace(appIntegrationsPattern, () => {
2395
+ return `export const appIntegrations = {${nextBody}} as const;`;
2396
+ });
2397
+ }
2398
+ async function writeIntegrationSetupFiles(input) {
2399
+ for (const file of input.definition.setupFiles || []) {
2400
+ const absolutePath = node_path.default.join(input.root, file.path);
2401
+ const exists = (0, node_fs.existsSync)(absolutePath);
2402
+ if (exists && !input.force) {
2403
+ if (file.merge === "lines") {
2404
+ const source = await (0, node_fs_promises.readFile)(absolutePath, "utf8");
2405
+ const additions = file.source().split(/\r?\n/).filter((line) => line && !source.split(/\r?\n/).includes(line));
2406
+ if (!additions.length) {
2407
+ input.result.skipped.push(absolutePath);
2408
+ continue;
2409
+ }
2410
+ if (!input.dryRun) await (0, node_fs_promises.writeFile)(absolutePath, `${source.trimEnd()}\n${additions.join("\n")}\n`, "utf8");
2411
+ input.result.updated.push(absolutePath);
2412
+ continue;
2413
+ }
2414
+ input.result.skipped.push(absolutePath);
2415
+ continue;
2416
+ }
2417
+ if (!input.dryRun) {
2418
+ await (0, node_fs_promises.mkdir)(node_path.default.dirname(absolutePath), { recursive: true });
2419
+ await (0, node_fs_promises.writeFile)(absolutePath, file.source(), "utf8");
2420
+ }
2421
+ input.result[exists ? "updated" : "created"].push(absolutePath);
2422
+ }
2423
+ }
2424
+ async function updatePackageJson$1(input) {
2425
+ const packageJsonPath = node_path.default.join(input.root, "package.json");
2426
+ if (!(0, node_fs.existsSync)(packageJsonPath)) {
2427
+ input.result.skipped.push(packageJsonPath);
2428
+ return;
2429
+ }
2430
+ const source = await (0, node_fs_promises.readFile)(packageJsonPath, "utf8");
2431
+ const manifest = JSON.parse(source);
2432
+ const dependencies = missingDependencies(manifest, input.definition.dependencies);
2433
+ const devDependencies = missingDependencies(manifest, input.definition.devDependencies);
2434
+ manifest.dependencies = {
2435
+ ...manifest.dependencies,
2436
+ ...hasPackageDependency(manifest, input.definition.packageName) ? {} : { [input.definition.packageName]: getFarmIntegrationVersion(manifest) },
2437
+ ...dependencies
2438
+ };
2439
+ if (Object.keys(devDependencies).length) manifest.devDependencies = {
2440
+ ...manifest.devDependencies,
2441
+ ...devDependencies
2442
+ };
2443
+ const nextSource = `${JSON.stringify(manifest, null, 2)}\n`;
2444
+ if (source === nextSource) {
2445
+ input.result.packageJson = packageJsonPath;
2446
+ input.result.skipped.push(packageJsonPath);
2447
+ return;
2448
+ }
2449
+ if (!input.dryRun) await (0, node_fs_promises.writeFile)(packageJsonPath, nextSource, "utf8");
2450
+ input.result.packageJson = packageJsonPath;
2451
+ input.result.updated.push(packageJsonPath);
2452
+ }
2453
+ function missingDependencies(manifest, dependencies) {
2454
+ return Object.fromEntries(Object.entries(dependencies || {}).filter(([name]) => !hasPackageDependency(manifest, name)));
2455
+ }
2456
+ async function updateFarmConfig(input) {
2457
+ const configFile = findFarmConfig(input.root);
2458
+ if (!configFile) {
2459
+ const newConfigFile = node_path.default.join(input.root, "farm.config.ts");
2460
+ const source = `import { defineConfig } from "@farm.js/core";
2461
+ import { appIntegrations } from "${toImportPath(node_path.default.relative(input.root, input.registryFile))}";
2462
+
2463
+ export default defineConfig({
2464
+ integrations: appIntegrations,
2465
+ });
2466
+ `;
2467
+ if (!input.dryRun) await (0, node_fs_promises.writeFile)(newConfigFile, source, "utf8");
2468
+ input.result.configFile = newConfigFile;
2469
+ input.result.created.push(newConfigFile);
2470
+ return;
2471
+ }
2472
+ input.result.configFile = configFile;
2473
+ const source = await (0, node_fs_promises.readFile)(configFile, "utf8");
2474
+ if (/\bintegrations\s*:/.test(source)) {
2475
+ input.result.skipped.push(configFile);
2476
+ input.result.notes.push(`farm.config already has an integrations field. Confirm it includes appIntegrations from ${node_path.default.relative(input.root, input.registryFile)}.`);
2477
+ return;
2478
+ }
2479
+ const importLine = `import { appIntegrations } from "${toImportPath(node_path.default.relative(node_path.default.dirname(configFile), input.registryFile))}";`;
2480
+ const sourceWithImport = source.includes(importLine) ? source : `${importLine}\n${source}`;
2481
+ const nextSource = insertIntegrationsConfig(sourceWithImport);
2482
+ if (nextSource === sourceWithImport) {
2483
+ input.result.skipped.push(configFile);
2484
+ input.result.notes.push(`Could not safely update ${node_path.default.relative(input.root, configFile)}. Add integrations: appIntegrations manually.`);
2485
+ return;
2486
+ }
2487
+ if (!input.dryRun) await (0, node_fs_promises.writeFile)(configFile, nextSource, "utf8");
2488
+ input.result.updated.push(configFile);
2489
+ }
2490
+ function insertIntegrationsConfig(source) {
2491
+ const defineConfigCall = /\bdefine(?:Farm)?Config\s*\(\s*\{/;
2492
+ if (defineConfigCall.test(source)) return source.replace(defineConfigCall, (match) => {
2493
+ return `${match}\n integrations: appIntegrations,`;
2494
+ });
2495
+ if (/export\s+default\s+\{/.test(source)) return source.replace(/export\s+default\s+\{/, (match) => {
2496
+ return `${match}\n integrations: appIntegrations,`;
2497
+ });
2498
+ return source;
2499
+ }
2500
+ function findFarmConfig(root) {
2501
+ for (const candidate of [
2502
+ "farm.config.ts",
2503
+ "farm.config.mts",
2504
+ "farm.config.js",
2505
+ "farm.config.mjs",
2506
+ "config.ts",
2507
+ "config.mts",
2508
+ "config.js",
2509
+ "config.mjs"
2510
+ ]) {
2511
+ const absolutePath = node_path.default.join(root, candidate);
2512
+ if ((0, node_fs.existsSync)(absolutePath)) return absolutePath;
2513
+ }
2514
+ return null;
2515
+ }
2516
+ function hasPackageDependency(manifest, dependency) {
2517
+ return dependency in (manifest.dependencies || {}) || dependency in (manifest.devDependencies || {}) || dependency in (manifest.peerDependencies || {}) || dependency in (manifest.optionalDependencies || {});
2518
+ }
2519
+ function getFarmIntegrationVersion(manifest) {
2520
+ const farmCoreVersion = manifest.dependencies?.["@farm.js/core"] ?? manifest.devDependencies?.["@farm.js/core"] ?? manifest.peerDependencies?.["@farm.js/core"] ?? manifest.optionalDependencies?.["@farm.js/core"];
2521
+ if (!farmCoreVersion) return "latest";
2522
+ return farmCoreVersion.startsWith("workspace:") ? "workspace:*" : farmCoreVersion;
2523
+ }
2524
+ function toImportPath(relativePath) {
2525
+ const normalized = relativePath.split(node_path.default.sep).join("/");
2526
+ return (normalized.startsWith(".") ? normalized : `./${normalized}`).replace(/\.tsx?$/, ".ts");
2527
+ }
2528
+ function escapeRegExp(input) {
2529
+ return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2530
+ }
2531
+ //#endregion
2532
+ //#region ../farm-cli/src/telemetry.ts
2533
+ const TELEMETRY_SCHEMA_VERSION = 1;
2534
+ const DEFAULT_TELEMETRY_ENDPOINT = "https://farmjs.dev/api/telemetry/v1/events";
2535
+ const TELEMETRY_NOTICE_URL = "https://farmjs.dev/docs/telemetry";
2536
+ const REQUEST_TIMEOUT_MS = 750;
2537
+ const FARM_TEMPLATES = [
2538
+ "basic",
2539
+ "react-compiler",
2540
+ "auth",
2541
+ "better-auth",
2542
+ "ai",
2543
+ "auth0",
2544
+ "authjs",
2545
+ "autumn",
2546
+ "clerk",
2547
+ "jobs-inngest",
2548
+ "jobs-trigger",
2549
+ "polar",
2550
+ "resend",
2551
+ "stripe",
2552
+ "supabase",
2553
+ "unkey",
2554
+ "workos"
2555
+ ];
2556
+ const RENDERERS = [
2557
+ "react",
2558
+ "preact",
2559
+ "solid",
2560
+ "vue",
2561
+ "svelte"
2562
+ ];
2563
+ const PACKAGE_MANAGERS = [
2564
+ "npm",
2565
+ "pnpm",
2566
+ "yarn",
2567
+ "bun"
2568
+ ];
2569
+ function defaultConfig() {
2570
+ return {
2571
+ version: TELEMETRY_SCHEMA_VERSION,
2572
+ enabled: true,
2573
+ noticeShown: false
2574
+ };
2575
+ }
2576
+ function configDirectory() {
2577
+ if (process.env.FARM_TELEMETRY_CONFIG_DIR) return node_path.default.resolve(process.env.FARM_TELEMETRY_CONFIG_DIR);
2578
+ if (process.platform === "win32") return node_path.default.join(process.env.APPDATA || node_path.default.join(node_os.default.homedir(), "AppData", "Roaming"), "farmjs");
2579
+ if (process.platform === "darwin") return node_path.default.join(node_os.default.homedir(), "Library", "Application Support", "farmjs");
2580
+ return node_path.default.join(process.env.XDG_CONFIG_HOME || node_path.default.join(node_os.default.homedir(), ".config"), "farmjs");
2581
+ }
2582
+ function getFarmTelemetryConfigFile() {
2583
+ return node_path.default.join(configDirectory(), "telemetry.json");
2584
+ }
2585
+ async function readConfig() {
2586
+ try {
2587
+ const parsed = JSON.parse(await (0, node_fs_promises.readFile)(getFarmTelemetryConfigFile(), "utf8"));
2588
+ if (parsed.version !== TELEMETRY_SCHEMA_VERSION) return {
2589
+ config: defaultConfig(),
2590
+ stored: false
2591
+ };
2592
+ return {
2593
+ config: {
2594
+ version: TELEMETRY_SCHEMA_VERSION,
2595
+ enabled: parsed.enabled === true,
2596
+ noticeShown: parsed.noticeShown === true,
2597
+ anonymousId: isUuid(parsed.anonymousId) ? parsed.anonymousId : void 0
2598
+ },
2599
+ stored: true
2600
+ };
2601
+ } catch {
2602
+ return {
2603
+ config: defaultConfig(),
2604
+ stored: false
2605
+ };
2606
+ }
2607
+ }
2608
+ async function writeConfig(config) {
2609
+ const file = getFarmTelemetryConfigFile();
2610
+ const directory = node_path.default.dirname(file);
2611
+ const temporaryFile = `${file}.${process.pid}.${(0, node_crypto.randomUUID)()}.tmp`;
2612
+ try {
2613
+ await (0, node_fs_promises.mkdir)(directory, {
2614
+ recursive: true,
2615
+ mode: 448
2616
+ });
2617
+ await (0, node_fs_promises.writeFile)(temporaryFile, `${JSON.stringify(config, null, 2)}\n`, { mode: 384 });
2618
+ await (0, node_fs_promises.rename)(temporaryFile, file);
2619
+ await (0, node_fs_promises.chmod)(file, 384).catch(() => void 0);
2620
+ } catch {
2621
+ await (0, node_fs_promises.unlink)(temporaryFile).catch(() => void 0);
2622
+ }
2623
+ }
2624
+ function isUuid(value) {
2625
+ return typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
2626
+ }
2627
+ function isTrue(value) {
2628
+ return value !== void 0 && [
2629
+ "1",
2630
+ "true",
2631
+ "yes",
2632
+ "on"
2633
+ ].includes(value.toLowerCase());
2634
+ }
2635
+ function isFalse(value) {
2636
+ return value !== void 0 && [
2637
+ "0",
2638
+ "false",
2639
+ "no",
2640
+ "off"
2641
+ ].includes(value.toLowerCase());
2642
+ }
2643
+ function environmentDecision() {
2644
+ if (process.env.DO_NOT_TRACK !== void 0 && !isFalse(process.env.DO_NOT_TRACK)) return {
2645
+ enabled: false,
2646
+ reason: "DO_NOT_TRACK is set"
2647
+ };
2648
+ if (isTrue(process.env.FARM_TELEMETRY_DISABLED)) return {
2649
+ enabled: false,
2650
+ reason: "FARM_TELEMETRY_DISABLED is set"
2651
+ };
2652
+ if (isTrue(process.env.FARM_TELEMETRY)) return { enabled: true };
2653
+ if (isFalse(process.env.FARM_TELEMETRY)) return {
2654
+ enabled: false,
2655
+ reason: "FARM_TELEMETRY disables collection"
2656
+ };
2657
+ return {};
2658
+ }
2659
+ function isContinuousIntegration() {
2660
+ return isTrue(process.env.CI) || isTrue(process.env.GITHUB_ACTIONS) || isTrue(process.env.BUILDKITE) || isTrue(process.env.CIRCLECI);
2661
+ }
2662
+ function isInteractive() {
2663
+ return process.stdin.isTTY === true && process.stdout.isTTY === true;
2664
+ }
2665
+ function getEndpoint() {
2666
+ const candidate = process.env.FARM_TELEMETRY_ENDPOINT || DEFAULT_TELEMETRY_ENDPOINT;
2667
+ try {
2668
+ const url = new URL(candidate);
2669
+ const isLocal = [
2670
+ "localhost",
2671
+ "127.0.0.1",
2672
+ "::1"
2673
+ ].includes(url.hostname);
2674
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && isLocal)) return DEFAULT_TELEMETRY_ENDPOINT;
2675
+ return url.toString();
2676
+ } catch {
2677
+ return DEFAULT_TELEMETRY_ENDPOINT;
2678
+ }
2679
+ }
2680
+ async function resolveState() {
2681
+ const { config, stored } = await readConfig();
2682
+ const environment = environmentDecision();
2683
+ const enabled = environment.enabled ?? config.enabled;
2684
+ const source = environment.enabled !== void 0 ? "environment" : stored ? "configuration" : "default";
2685
+ if (!enabled) return {
2686
+ config,
2687
+ enabled,
2688
+ active: false,
2689
+ source,
2690
+ reason: environment.reason
2691
+ };
2692
+ if (environment.enabled === true) return {
2693
+ config,
2694
+ enabled,
2695
+ active: true,
2696
+ source
2697
+ };
2698
+ if (process.env.NODE_ENV === "test") return {
2699
+ config,
2700
+ enabled,
2701
+ active: false,
2702
+ source,
2703
+ reason: "test environments are skipped"
2704
+ };
2705
+ if (isContinuousIntegration()) return {
2706
+ config,
2707
+ enabled,
2708
+ active: false,
2709
+ source,
2710
+ reason: "CI environments are skipped"
2711
+ };
2712
+ if (!isInteractive()) return {
2713
+ config,
2714
+ enabled,
2715
+ active: false,
2716
+ source,
2717
+ reason: "non-interactive commands are skipped"
2718
+ };
2719
+ return {
2720
+ config,
2721
+ enabled,
2722
+ active: true,
2723
+ source
2724
+ };
2725
+ }
2726
+ async function showFarmTelemetryNotice() {
2727
+ if (!isInteractive() || isContinuousIntegration() || process.env.NODE_ENV === "test") return;
2728
+ if (environmentDecision().enabled !== void 0) return;
2729
+ const { config } = await readConfig();
2730
+ if (config.noticeShown) return;
2731
+ process.stderr.write(`Farm.js collects anonymous CLI telemetry by default. Run "farm telemetry disable" to opt out.\nLearn more: ${TELEMETRY_NOTICE_URL}\n`);
2732
+ await writeConfig({
2733
+ ...config,
2734
+ noticeShown: true
2735
+ });
2736
+ }
2737
+ async function trackFarmProjectCreated(input) {
2738
+ const template = allowlisted(input.template, FARM_TEMPLATES);
2739
+ const renderer = allowlisted(input.renderer, RENDERERS);
2740
+ const packageManager = allowlisted(input.packageManager, PACKAGE_MANAGERS);
2741
+ await track({
2742
+ eventType: "project_created",
2743
+ source: "create-app",
2744
+ packageName: "@farm.js/create-app",
2745
+ packageVersion: sanitizeVersion(input.packageVersion),
2746
+ ...template ? { template } : {},
2747
+ ...renderer ? { renderer } : {},
2748
+ ...packageManager ? { packageManager } : {},
2749
+ ...typeof input.typescript === "boolean" ? { typescript: input.typescript } : {},
2750
+ ...typeof input.installedDependencies === "boolean" ? { installedDependencies: input.installedDependencies } : {}
2751
+ });
2752
+ }
2753
+ async function track(event) {
2754
+ try {
2755
+ const state = await resolveState();
2756
+ if (!state.active) return;
2757
+ const anonymousId = state.config.anonymousId || (0, node_crypto.randomUUID)();
2758
+ if (!state.config.anonymousId) await writeConfig({
2759
+ ...state.config,
2760
+ anonymousId
2761
+ });
2762
+ await send({
2763
+ schemaVersion: TELEMETRY_SCHEMA_VERSION,
2764
+ eventId: (0, node_crypto.randomUUID)(),
2765
+ anonymousId,
2766
+ nodeMajor: Number.parseInt(process.versions.node.split(".")[0] || "0", 10),
2767
+ platform: normalizePlatform(process.platform),
2768
+ architecture: normalizeArchitecture(process.arch),
2769
+ ...event
2770
+ });
2771
+ } catch {}
2772
+ }
2773
+ async function send(payload) {
2774
+ const controller = new AbortController();
2775
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
2776
+ timeout.unref?.();
2777
+ try {
2778
+ await fetch(getEndpoint(), {
2779
+ method: "POST",
2780
+ headers: { "content-type": "application/json" },
2781
+ body: JSON.stringify(payload),
2782
+ signal: controller.signal,
2783
+ keepalive: true
2784
+ });
2785
+ } catch {} finally {
2786
+ clearTimeout(timeout);
2787
+ }
2788
+ }
2789
+ function sanitizeVersion(value) {
2790
+ return /^[0-9A-Za-z.+_-]{1,64}$/.test(value) ? value : "unknown";
2791
+ }
2792
+ function allowlisted(value, values) {
2793
+ return value && values.includes(value) ? value : void 0;
2794
+ }
2795
+ function normalizePlatform(value) {
2796
+ if (value === "darwin" || value === "linux") return value;
2797
+ if (value === "win32") return "windows";
2798
+ return "other";
2799
+ }
2800
+ function normalizeArchitecture(value) {
2801
+ return value === "arm64" || value === "x64" ? value : "other";
2802
+ }
2803
+ //#endregion
10
2804
  //#region src/index.ts
2805
+ const templateDetails = {
2806
+ basic: {
2807
+ title: "Basic starter",
2808
+ description: "A minimal Farm.js app with built-in Tailwind support",
2809
+ instructions: ["Tailwind is enabled by default. You only need postcss config for custom plugins."]
2810
+ },
2811
+ "react-compiler": {
2812
+ title: "React Compiler starter (experimental)",
2813
+ description: "React AOT compiler with a focused live comparison",
2814
+ instructions: ["The React AOT compiler is experimental; unsupported components safely stay on React.", "Run pnpm experiment after installing Playwright Chromium to verify the compiled update path."]
2815
+ },
2816
+ auth: {
2817
+ title: "Auth starter",
2818
+ description: "Farm.js-native auth with local SQLite, secure sessions, and protected routes",
2819
+ instructions: ["FARMJS Auth uses local SQLite automatically; no auth environment variables are needed locally.", "For production, set FARM_AUTH_URL, FARM_AUTH_SECRET, and DATABASE_URL, then run the auth:migrate script."]
2820
+ },
2821
+ "better-auth": {
2822
+ title: "Better Auth starter",
2823
+ description: "Better Auth with Postgres, secure sessions, and protected routes",
2824
+ instructions: ["Before starting, copy .env.example to .env.local and set DATABASE_URL and BETTER_AUTH_SECRET.", "Better Auth migrations run automatically when the auth instance starts."]
2825
+ },
2826
+ ai: integrationTemplate({
2827
+ title: "AI starter",
2828
+ description: "AI SDK chat route with a ready-to-use chat interface",
2829
+ provider: "ai",
2830
+ label: "AI",
2831
+ route: "/integrations/ai",
2832
+ docsPath: "/docs/integrations"
2833
+ }),
2834
+ auth0: integrationTemplate({
2835
+ title: "Auth0 starter",
2836
+ description: "Auth0 login, sessions, protected routes, and account controls",
2837
+ provider: "auth0",
2838
+ label: "Auth0",
2839
+ route: "/integrations/auth0",
2840
+ docsPath: "/docs/integrations/auth/auth0"
2841
+ }),
2842
+ authjs: integrationTemplate({
2843
+ title: "Auth.js starter",
2844
+ description: "Auth.js with GitHub OAuth and Farm-owned route mounting",
2845
+ provider: "authjs",
2846
+ label: "Auth.js",
2847
+ route: "/integrations/authjs",
2848
+ docsPath: "/docs/integrations/auth/authjs"
2849
+ }),
2850
+ autumn: integrationTemplate({
2851
+ title: "Autumn starter",
2852
+ description: "Autumn products, checkout, billing state, and customer portal",
2853
+ provider: "autumn",
2854
+ label: "Autumn",
2855
+ route: "/integrations/autumn",
2856
+ docsPath: "/docs/integrations/autumn"
2857
+ }),
2858
+ clerk: integrationTemplate({
2859
+ title: "Clerk starter",
2860
+ description: "Clerk authentication, account entry points, and protected routes",
2861
+ provider: "clerk",
2862
+ label: "Clerk",
2863
+ route: "/integrations/clerk",
2864
+ docsPath: "/docs/integrations/auth/clerk"
2865
+ }),
2866
+ "jobs-inngest": integrationTemplate({
2867
+ title: "Inngest starter",
2868
+ description: "Typed background jobs backed by Inngest",
2869
+ provider: "jobs-inngest",
2870
+ label: "Inngest",
2871
+ route: "/integrations/jobs-inngest",
2872
+ docsPath: "/docs/integrations/inngest"
2873
+ }),
2874
+ "jobs-trigger": integrationTemplate({
2875
+ title: "Trigger.dev starter",
2876
+ description: "Typed background jobs backed by Trigger.dev",
2877
+ provider: "jobs-trigger",
2878
+ label: "Trigger.dev",
2879
+ route: "/integrations/jobs-trigger",
2880
+ docsPath: "/docs/integrations/trigger"
2881
+ }),
2882
+ polar: integrationTemplate({
2883
+ title: "Polar starter",
2884
+ description: "Polar products, checkout, billing state, and customer portal",
2885
+ provider: "polar",
2886
+ label: "Polar",
2887
+ route: "/integrations/polar",
2888
+ docsPath: "/docs/integrations/polar"
2889
+ }),
2890
+ resend: integrationTemplate({
2891
+ title: "Resend starter",
2892
+ description: "Resend templates, delivery, scheduling, and webhooks",
2893
+ provider: "resend",
2894
+ label: "Resend",
2895
+ route: "/integrations/resend",
2896
+ docsPath: "/docs/integrations/email"
2897
+ }),
2898
+ stripe: integrationTemplate({
2899
+ title: "Stripe starter",
2900
+ description: "Stripe products, checkout, billing portal, and webhooks",
2901
+ provider: "stripe",
2902
+ label: "Stripe",
2903
+ route: "/integrations/stripe",
2904
+ docsPath: "/docs/integrations/stripe"
2905
+ }),
2906
+ supabase: integrationTemplate({
2907
+ title: "Supabase starter",
2908
+ description: "Supabase authentication, sessions, OAuth, and protected routes",
2909
+ provider: "supabase",
2910
+ label: "Supabase",
2911
+ route: "/integrations/supabase",
2912
+ docsPath: "/docs/integrations/auth/supabase"
2913
+ }),
2914
+ unkey: integrationTemplate({
2915
+ title: "Unkey starter",
2916
+ description: "Unkey API key creation, verification, and route protection",
2917
+ provider: "unkey",
2918
+ label: "Unkey",
2919
+ route: "/integrations/unkey",
2920
+ docsPath: "/docs/integrations/unkey"
2921
+ }),
2922
+ workos: integrationTemplate({
2923
+ title: "WorkOS starter",
2924
+ description: "WorkOS AuthKit, organization sessions, and protected routes",
2925
+ provider: "workos",
2926
+ label: "WorkOS",
2927
+ route: "/integrations/workos",
2928
+ docsPath: "/docs/integrations/auth/workos"
2929
+ })
2930
+ };
2931
+ function integrationTemplate(input) {
2932
+ return {
2933
+ title: input.title,
2934
+ description: input.description,
2935
+ instructions: [],
2936
+ integration: {
2937
+ provider: input.provider,
2938
+ label: input.label,
2939
+ route: input.route,
2940
+ docsPath: input.docsPath
2941
+ }
2942
+ };
2943
+ }
11
2944
  async function createApp(projectName, options = {}) {
12
2945
  require_utils.showBanner();
2946
+ await showFarmTelemetryNotice();
13
2947
  const templates = await getAvailableTemplates();
14
2948
  if (templates.length === 0) {
15
2949
  require_utils.logger.error("No templates are available in this package.");
16
2950
  process.exit(1);
17
2951
  }
2952
+ if (options.listTemplates) {
2953
+ require_utils.logger.info("Available templates");
2954
+ for (const template of templates) {
2955
+ const details = templateDetails[template];
2956
+ require_utils.logger.info(` ${template.padEnd(14)} ${details?.description ?? ""}`.trimEnd());
2957
+ }
2958
+ return;
2959
+ }
18
2960
  if (!projectName) {
19
2961
  const response = await (0, prompts.default)({
20
2962
  type: "text",
@@ -41,11 +2983,14 @@ async function createApp(projectName, options = {}) {
41
2983
  type: "select",
42
2984
  name: "template",
43
2985
  message: "Which template would you like to use?",
44
- choices: templates.map((name) => ({
45
- title: prettifyTemplateName(name),
46
- value: name,
47
- description: name === "basic" ? "A simple Farm.js app with built-in Tailwind support" : void 0
48
- })),
2986
+ choices: templates.map((name) => {
2987
+ const details = templateDetails[name];
2988
+ return {
2989
+ title: details?.title ?? prettifyTemplateName(name),
2990
+ value: name,
2991
+ description: details?.description
2992
+ };
2993
+ }),
49
2994
  initial: 0
50
2995
  });
51
2996
  if (!response.template) {
@@ -57,6 +3002,56 @@ async function createApp(projectName, options = {}) {
57
3002
  require_utils.logger.error(`Unknown template "${template}". Available: ${templates.map((t) => `"${t}"`).join(", ")}`);
58
3003
  process.exit(1);
59
3004
  }
3005
+ let renderer = options.renderer?.toLowerCase();
3006
+ if (renderer && renderer !== "react" && renderer !== "preact" && renderer !== "solid" && renderer !== "vue" && renderer !== "svelte") {
3007
+ require_utils.logger.error(`Unknown renderer "${options.renderer}". Available: "react", "preact", "solid", "vue", "svelte".`);
3008
+ process.exit(1);
3009
+ }
3010
+ if (!renderer && !options.template && (template === "basic" || template === "better-auth")) {
3011
+ const response = await (0, prompts.default)({
3012
+ type: "select",
3013
+ name: "renderer",
3014
+ message: "Which rendering library would you like to use?",
3015
+ choices: [
3016
+ {
3017
+ title: "React",
3018
+ value: "react",
3019
+ description: "The default FARMJS renderer"
3020
+ },
3021
+ {
3022
+ title: "Preact",
3023
+ value: "preact",
3024
+ description: "Small React-compatible runtime with SSR and hydration"
3025
+ },
3026
+ {
3027
+ title: "Solid",
3028
+ value: "solid",
3029
+ description: "Fine-grained reactivity with Solid"
3030
+ },
3031
+ {
3032
+ title: "Vue",
3033
+ value: "vue",
3034
+ description: "Vue SFCs with server rendering and hydration"
3035
+ },
3036
+ {
3037
+ title: "Svelte",
3038
+ value: "svelte",
3039
+ description: "Svelte components with server rendering and hydration"
3040
+ }
3041
+ ],
3042
+ initial: 0
3043
+ });
3044
+ if (!response.renderer) {
3045
+ require_utils.logger.error("Operation cancelled.");
3046
+ process.exit(1);
3047
+ }
3048
+ renderer = response.renderer;
3049
+ }
3050
+ renderer ||= "react";
3051
+ if (renderer !== "react" && template !== "basic" && !await hasRendererIntegrationTemplate(template, renderer)) {
3052
+ require_utils.logger.error(`The "${template}" starter currently targets React. Use --template basic or --template better-auth with --renderer ${renderer}.`);
3053
+ process.exit(1);
3054
+ }
60
3055
  let useTypeScript = options.typescript;
61
3056
  if (useTypeScript === void 0) {
62
3057
  const response = await (0, prompts.default)({
@@ -72,6 +3067,7 @@ async function createApp(projectName, options = {}) {
72
3067
  useTypeScript = response.typescript;
73
3068
  }
74
3069
  const projectPath = path.default.resolve(process.cwd(), projectName);
3070
+ const packageManager = detectPackageManager();
75
3071
  if (await directoryHasFiles(projectPath)) {
76
3072
  if (!(await (0, prompts.default)({
77
3073
  type: "confirm",
@@ -83,39 +3079,225 @@ async function createApp(projectName, options = {}) {
83
3079
  process.exit(1);
84
3080
  }
85
3081
  }
86
- require_utils.logger.info(`Creating Farm.js app in ${projectPath}`);
3082
+ require_utils.logger.info(`Creating FARMJS app in ${projectPath}`);
87
3083
  await fs_promises.default.mkdir(projectPath, { recursive: true });
88
- await copyTemplate(template, projectPath, useTypeScript);
89
- await updatePackageJson(projectPath, projectName);
3084
+ const integrationResult = await copyTemplate(template, projectPath, useTypeScript, renderer);
3085
+ await updatePackageJson(projectPath, projectName, packageManager);
90
3086
  require_utils.logger.success(`🚜 Created ${projectName}`);
3087
+ if (!options.skipInstall) {
3088
+ require_utils.logger.info(`Installing dependencies with ${packageManager.name}...`);
3089
+ await installDependencies(projectPath, packageManager);
3090
+ require_utils.logger.success("Dependencies installed");
3091
+ }
91
3092
  require_utils.logger.info("");
92
3093
  require_utils.logger.info("Next steps");
93
3094
  require_utils.logger.info(` cd ${projectName}`);
94
- require_utils.logger.info(" pnpm install");
95
- require_utils.logger.info(" pnpm dev");
3095
+ if (options.skipInstall) require_utils.logger.info(` ${packageManager.name} install`);
3096
+ require_utils.logger.info(` ${getDevCommand(packageManager.name)}`);
96
3097
  require_utils.logger.info("");
97
- require_utils.logger.info("Tailwind is enabled by default. You only need postcss config for custom plugins.");
3098
+ for (const instruction of templateDetails[template]?.instructions ?? []) require_utils.logger.info(instruction);
3099
+ if (integrationResult) {
3100
+ const details = templateDetails[template].integration;
3101
+ require_utils.logger.info(`Open ${details.route} for the ${details.label} starter.`);
3102
+ if (integrationResult.env.length) require_utils.logger.info("Copy .env.example to .env.local and add your provider credentials.");
3103
+ for (const note of integrationResult.notes) require_utils.logger.info(note);
3104
+ }
3105
+ await trackFarmProjectCreated({
3106
+ packageVersion: options.telemetryPackageVersion ?? "unknown",
3107
+ template,
3108
+ renderer,
3109
+ packageManager: packageManager.name,
3110
+ typescript: useTypeScript,
3111
+ installedDependencies: !options.skipInstall
3112
+ });
98
3113
  }
99
- async function copyTemplate(template, projectPath, useTypeScript) {
100
- await copyDir(path.default.join(__dirname, "..", "templates", template), projectPath);
3114
+ async function copyTemplate(template, projectPath, useTypeScript, renderer) {
3115
+ const details = templateDetails[template];
3116
+ await copyDir(path.default.join(__dirname, "..", "templates", details?.integration ? "basic" : template), projectPath);
3117
+ const basePackageJson = await readPackageJson(projectPath);
101
3118
  if (useTypeScript) {
102
3119
  const tsTemplatePath = path.default.join(__dirname, "..", "templates", "_typescript");
103
3120
  if (await dirExists(tsTemplatePath)) await copyDir(tsTemplatePath, projectPath);
104
3121
  }
3122
+ if (renderer !== "react") {
3123
+ await applyRendererTemplate(projectPath, renderer, basePackageJson);
3124
+ const integrationRendererPath = getRendererIntegrationTemplatePath(template, renderer);
3125
+ if (await dirExists(integrationRendererPath)) {
3126
+ await removeRendererIntegrationConflicts(projectPath);
3127
+ await copyDir(integrationRendererPath, projectPath);
3128
+ }
3129
+ }
3130
+ if (!details?.integration) return;
3131
+ const result = await addFarmIntegration({
3132
+ root: projectPath,
3133
+ provider: details.integration.provider,
3134
+ ui: true
3135
+ });
3136
+ await writeEnvironmentExample(projectPath, result.env);
3137
+ await writeIntegrationHomePage(projectPath, details.integration, result.env.length > 0);
3138
+ await writeIntegrationReadme(projectPath, details.integration, result.env);
3139
+ return result;
3140
+ }
3141
+ async function applyRendererTemplate(projectPath, renderer, basePackageJson) {
3142
+ const rendererTemplatePath = path.default.join(__dirname, "..", "templates", "_renderers", renderer);
3143
+ if (renderer === "vue" || renderer === "svelte") await Promise.all([
3144
+ fs_promises.default.rm(path.default.join(projectPath, "src", "app", "page.tsx"), { force: true }),
3145
+ fs_promises.default.rm(path.default.join(projectPath, "src", "app", "layout.tsx"), { force: true }),
3146
+ fs_promises.default.rm(path.default.join(projectPath, "src", "components", "resource-links.tsx"), { force: true })
3147
+ ]);
3148
+ await copyDir(rendererTemplatePath, projectPath);
3149
+ await writePackageJson(projectPath, mergeRendererPackageJson(basePackageJson, await readPackageJson(projectPath)));
3150
+ }
3151
+ function mergeRendererPackageJson(base, renderer) {
3152
+ const dependencies = {
3153
+ ...base.dependencies,
3154
+ ...renderer.dependencies
3155
+ };
3156
+ const devDependencies = {
3157
+ ...base.devDependencies,
3158
+ ...renderer.devDependencies
3159
+ };
3160
+ for (const name of ["react", "react-dom"]) delete dependencies[name];
3161
+ for (const name of ["@types/react", "@types/react-dom"]) delete devDependencies[name];
3162
+ return {
3163
+ ...base,
3164
+ ...renderer.type ? { type: renderer.type } : {},
3165
+ scripts: {
3166
+ ...base.scripts,
3167
+ ...renderer.scripts
3168
+ },
3169
+ dependencies,
3170
+ devDependencies
3171
+ };
3172
+ }
3173
+ async function readPackageJson(projectPath) {
3174
+ return JSON.parse(await fs_promises.default.readFile(path.default.join(projectPath, "package.json"), "utf8"));
3175
+ }
3176
+ async function writePackageJson(projectPath, packageJson) {
3177
+ await fs_promises.default.writeFile(path.default.join(projectPath, "package.json"), `${JSON.stringify(packageJson, null, 2)}\n`, "utf8");
3178
+ }
3179
+ function getRendererIntegrationTemplatePath(template, renderer) {
3180
+ return path.default.join(__dirname, "..", "templates", "_integrations", template, renderer);
3181
+ }
3182
+ async function hasRendererIntegrationTemplate(template, renderer) {
3183
+ return dirExists(getRendererIntegrationTemplatePath(template, renderer));
3184
+ }
3185
+ async function removeRendererIntegrationConflicts(projectPath) {
3186
+ const appFiles = [
3187
+ "page.tsx",
3188
+ "layout.tsx",
3189
+ "loading.tsx",
3190
+ "error.tsx",
3191
+ "not-found.tsx",
3192
+ "sign-in/page.tsx",
3193
+ "sign-up/page.tsx",
3194
+ "dashboard/page.tsx",
3195
+ "preact.css",
3196
+ "solid.css",
3197
+ "vue.css",
3198
+ "svelte.css",
3199
+ "api/greeting/route.ts"
3200
+ ];
3201
+ const componentFiles = [
3202
+ "auth-form.tsx",
3203
+ "auth-shell.tsx",
3204
+ "sign-out-button.tsx",
3205
+ "site-header.tsx"
3206
+ ];
3207
+ await Promise.all([
3208
+ ...appFiles.map((file) => fs_promises.default.rm(path.default.join(projectPath, "src", "app", file), { force: true })),
3209
+ ...componentFiles.map((file) => fs_promises.default.rm(path.default.join(projectPath, "src", "components", file), { force: true })),
3210
+ fs_promises.default.rm(path.default.join(projectPath, "src", "lib", "api-client.ts"), { force: true }),
3211
+ fs_promises.default.rm(path.default.join(projectPath, "src", "lib", "api.generated.ts"), { force: true })
3212
+ ]);
3213
+ }
3214
+ async function writeEnvironmentExample(projectPath, keys) {
3215
+ if (keys.length === 0) return;
3216
+ const envPath = path.default.join(projectPath, ".env.example");
3217
+ let current = "";
3218
+ try {
3219
+ current = await fs_promises.default.readFile(envPath, "utf8");
3220
+ } catch {}
3221
+ const existingKeys = new Set(current.split(/\r?\n/).map((line) => line.match(/^([A-Z][A-Z0-9_]*)=/)?.[1]).filter((key) => Boolean(key)));
3222
+ const additions = keys.filter((key) => !existingKeys.has(key)).map((key) => `${key}=${environmentExampleValue(key)}`);
3223
+ if (additions.length > 0) await fs_promises.default.writeFile(envPath, `${current.trimEnd()}${current.trim() ? "\n" : ""}${additions.join("\n")}\n`, "utf8");
3224
+ }
3225
+ function environmentExampleValue(key) {
3226
+ if (key === "APP_BASE_URL") return "http://localhost:3000";
3227
+ if (key === "AUTH_SECRET") return "replace-with-at-least-32-random-characters";
3228
+ if (key === "UNKEY_BASE_URL") return "https://api.unkey.com";
3229
+ return "";
3230
+ }
3231
+ async function writeIntegrationHomePage(projectPath, integration, hasEnvironment) {
3232
+ const commandRows = [...hasEnvironment ? ["cp .env.example .env.local"] : [], "pnpm dev"].map((command, index) => ` <div className="command-row">
3233
+ <span>${String(index + 1).padStart(2, "0")}</span>
3234
+ <code>${command}</code>
3235
+ </div>`).join("\n");
3236
+ const source = `import { ResourceLinks } from "../components/resource-links";
3237
+
3238
+ export default function HomePage() {
3239
+ return (
3240
+ <main className="landing-main">
3241
+ <section className="hero-section">
3242
+ <div className="hero-copy">
3243
+ <div className="eyebrow-row">
3244
+ <span>00</span>
3245
+ <span>FARMJS / ${integration.label} starter</span>
3246
+ </div>
3247
+
3248
+ <h1>
3249
+ Start at <code>${integration.route}</code>.
3250
+ </h1>
3251
+
3252
+ <div className="command-list" aria-label="Getting started commands">
3253
+ ${commandRows}
3254
+ </div>
3255
+
3256
+ <ResourceLinks
3257
+ className="resource-links"
3258
+ primary={{ href: "${integration.route}", label: "Get started" }}
3259
+ />
3260
+ </div>
3261
+ </section>
3262
+ </main>
3263
+ );
3264
+ }
3265
+ `;
3266
+ await fs_promises.default.writeFile(path.default.join(projectPath, "src", "app", "page.tsx"), source, "utf8");
3267
+ }
3268
+ async function writeIntegrationReadme(projectPath, integration, env) {
3269
+ const environmentSetup = env.length ? `cp .env.example .env.local\n# Add values for: ${env.join(", ")}\n` : "";
3270
+ const wiring = integration.provider === "ai" ? "The AI route lives in `src/app/api/chat/route.ts` and its local UI lives under `src/components/farm`." : "The provider wiring lives in `src/lib/integrations` and is registered from `farm.config.ts`.";
3271
+ const source = `# FARMJS ${integration.label} Starter
3272
+
3273
+ ## Getting started
3274
+
3275
+ \`\`\`bash
3276
+ pnpm install
3277
+ ${environmentSetup}pnpm dev
3278
+ \`\`\`
3279
+
3280
+ Open [${integration.route}](http://localhost:3000${integration.route}) for the integration UI.
3281
+
3282
+ ${wiring}
3283
+ See the [${integration.label} integration guide](https://farm.js.dev${integration.docsPath}) for provider setup and production guidance.
3284
+ `;
3285
+ await fs_promises.default.writeFile(path.default.join(projectPath, "README.md"), source, "utf8");
105
3286
  }
106
3287
  async function copyDir(src, dest) {
107
3288
  await fs_promises.default.mkdir(dest, { recursive: true });
108
3289
  const entries = await fs_promises.default.readdir(src, { withFileTypes: true });
109
3290
  for (const entry of entries) {
110
3291
  const srcPath = path.default.join(src, entry.name);
111
- const destPath = path.default.join(dest, entry.name);
3292
+ const destinationName = entry.name === "gitignore" ? ".gitignore" : entry.name;
3293
+ const destPath = path.default.join(dest, destinationName);
112
3294
  if (entry.isDirectory()) await copyDir(srcPath, destPath);
113
3295
  else await fs_promises.default.copyFile(srcPath, destPath);
114
3296
  }
115
3297
  }
116
- async function dirExists(path$2) {
3298
+ async function dirExists(path$5) {
117
3299
  try {
118
- return (await fs_promises.default.stat(path$2)).isDirectory();
3300
+ return (await fs_promises.default.stat(path$5)).isDirectory();
119
3301
  } catch {
120
3302
  return false;
121
3303
  }
@@ -144,20 +3326,63 @@ function prettifyTemplateName(name) {
144
3326
  }
145
3327
  async function getAvailableTemplates() {
146
3328
  const templatesRoot = path.default.join(__dirname, "..", "templates");
147
- return (await fs_promises.default.readdir(templatesRoot, { withFileTypes: true })).filter((entry) => entry.isDirectory() && !entry.name.startsWith("_")).map((entry) => entry.name).sort();
3329
+ const entries = await fs_promises.default.readdir(templatesRoot, { withFileTypes: true });
3330
+ const templateOrder = Object.keys(templateDetails);
3331
+ const directoryTemplates = entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith("_")).map((entry) => entry.name);
3332
+ const generatedTemplates = Object.entries(templateDetails).filter(([, details]) => Boolean(details.integration)).map(([name]) => name);
3333
+ return [.../* @__PURE__ */ new Set([...directoryTemplates, ...generatedTemplates])].sort((left, right) => {
3334
+ const leftIndex = templateOrder.indexOf(left);
3335
+ const rightIndex = templateOrder.indexOf(right);
3336
+ return (leftIndex === -1 ? Number.MAX_SAFE_INTEGER : leftIndex) - (rightIndex === -1 ? Number.MAX_SAFE_INTEGER : rightIndex) || left.localeCompare(right);
3337
+ });
148
3338
  }
149
- async function updatePackageJson(projectPath, projectName) {
3339
+ async function updatePackageJson(projectPath, projectName, packageManager) {
150
3340
  const packageJsonPath = path.default.join(projectPath, "package.json");
151
3341
  try {
152
3342
  const content = await fs_promises.default.readFile(packageJsonPath, "utf-8");
153
3343
  const packageJson = JSON.parse(content);
154
3344
  packageJson.name = projectName;
3345
+ if (packageManager.version) packageJson.packageManager = `${packageManager.name}@${packageManager.version}`;
155
3346
  await fs_promises.default.writeFile(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}\n`);
156
- } catch (error) {
3347
+ } catch {
157
3348
  require_utils.logger.warn("Could not update package.json");
158
3349
  }
159
3350
  }
3351
+ function detectPackageManager(userAgent = process.env.npm_config_user_agent) {
3352
+ const match = userAgent?.match(/^(npm|pnpm|yarn|bun)\/([^\s]+)/);
3353
+ if (!match) return { name: "pnpm" };
3354
+ const [, name, version] = match;
3355
+ return {
3356
+ name,
3357
+ version: version === "?" ? void 0 : version
3358
+ };
3359
+ }
3360
+ function installDependencies(projectPath, packageManager) {
3361
+ return new Promise((resolve, reject) => {
3362
+ const command = process.platform === "win32" ? `${packageManager.name}.cmd` : packageManager.name;
3363
+ const child = (0, node_child_process.spawn)(command, ["install"], {
3364
+ cwd: projectPath,
3365
+ env: process.env,
3366
+ stdio: "inherit"
3367
+ });
3368
+ child.on("error", reject);
3369
+ child.on("close", (code, signal) => {
3370
+ if (code === 0) {
3371
+ resolve();
3372
+ return;
3373
+ }
3374
+ const reason = signal ? `signal ${signal}` : `exit code ${code ?? "unknown"}`;
3375
+ reject(/* @__PURE__ */ new Error(`${packageManager.name} install failed with ${reason}.`));
3376
+ });
3377
+ });
3378
+ }
3379
+ function getDevCommand(packageManager) {
3380
+ if (packageManager === "npm" || packageManager === "bun") return `${packageManager} run dev`;
3381
+ return `${packageManager} dev`;
3382
+ }
160
3383
  //#endregion
161
3384
  exports.createApp = createApp;
3385
+ exports.detectPackageManager = detectPackageManager;
3386
+ exports.installDependencies = installDependencies;
162
3387
 
163
3388
  //# sourceMappingURL=index.js.map