@farm.js/create-app 0.1.0-beta.7 → 0.1.0-beta.71

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