create-terreno-app 57.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2754 @@
1
+ import packageJson from "../package.json" with { type: "json" };
2
+ /** Pinned so `npx -y` does not resolve a moving `@latest` target in generated MCP configs. */
3
+ export const PLAYWRIGHT_MCP_PACKAGE_VERSION = "0.0.76";
4
+ /** Bun-safe Mongo stack — caret ranges resolve to mongoose 9.10 / mongodb 7.6 / bson 7.3 and crash Bun. */
5
+ export const MONGOOSE_VERSION = "9.7.4";
6
+ export const MONGODB_VERSION = "7.2.0";
7
+ export const BSON_VERSION = "7.2.0";
8
+ export const PACKAGE_VERSION = packageJson.version;
9
+ const TERRENO_DEP_VERSION = `^${PACKAGE_VERSION}`;
10
+ const generateCursorRules = (args) => {
11
+ const { appDisplayName } = args;
12
+ return `# ${appDisplayName}
13
+
14
+ A full-stack application built with the Terreno framework.
15
+
16
+ ## Project Structure
17
+
18
+ - **frontend/** - Expo/React Native frontend using @terreno/ui, @terreno/syncdb, and @terreno/rtk (SDK + Better Auth)
19
+ - **backend/** - Express/Mongoose backend using @terreno/api
20
+
21
+ ## Development
22
+
23
+ Uses [Bun](https://bun.sh/) as the package manager.
24
+
25
+ \`\`\`bash
26
+ # Backend
27
+ cd backend && bun run dev # Start backend on port 4000
28
+
29
+ # Frontend
30
+ cd frontend && bun run web # Start web frontend
31
+ cd frontend && bun run sdk # Regenerate SDK after backend changes
32
+ \`\`\`
33
+
34
+ ## Code Style
35
+
36
+ ### TypeScript/JavaScript
37
+ - Use ES module syntax and TypeScript for all code
38
+ - Prefer interfaces over types; avoid enums, use maps
39
+ - Prefer const arrow functions over \`function\` keyword
40
+ - Use descriptive variable names with auxiliary verbs (e.g., \`isLoading\`)
41
+ - Favor named exports
42
+ - Use the RORO pattern (Receive an Object, Return an Object)
43
+
44
+ ### Dates and Time
45
+ - Always use Luxon instead of Date or dayjs
46
+
47
+ ### Error Handling
48
+ - Check error conditions at start of functions and return early
49
+ - Limit nested if statements
50
+ - Use multiline syntax with curly braces for all conditionals
51
+
52
+ ### React Best Practices
53
+ - Use functional components with \`React.FC\` type
54
+ - Add explanatory comment above each \`useEffect\`
55
+ - Wrap callbacks in \`useCallback\`
56
+ - Use Redux Toolkit for state management
57
+
58
+ ### Backend Conventions
59
+ - Use \`modelRouter\` for CRUD endpoints
60
+ - Use \`APIError\` for error responses
61
+ - Use \`logger.info/warn/error/debug\` for logging
62
+ - Use \`Model.findExactlyOne\` or \`Model.findOneOrNone\` (not \`Model.findOne\`)
63
+
64
+ ### Frontend Conventions
65
+ - Use \`@terreno/syncdb/react\` hooks (\`useQuery\`, \`useMutate\`) for synced collection CRUD
66
+ - Use generated SDK hooks from \`@/store/openApiSdk\` for non-synced routes only
67
+ - Use @terreno/ui components (Box, Page, Button, TextField, etc.)
68
+ - Never modify \`openApiSdk.ts\` manually - regenerate with \`bun run sdk\`
69
+
70
+ ## AI Assistance
71
+
72
+ This project is configured to use the Terreno MCP server for AI-assisted development.
73
+ Use the MCP tools and prompts for:
74
+ - Generating new models and routes
75
+ - Creating screens and forms
76
+ - Following Terreno patterns and best practices
77
+ `;
78
+ };
79
+ const generateMcpSettings = (args) => {
80
+ const mcpUrl = args.mcpServerUrl || "https://mcp.terreno.flourish.health";
81
+ return JSON.stringify({
82
+ mcpServers: {
83
+ expo: {
84
+ type: "http",
85
+ url: "https://mcp.expo.dev/mcp",
86
+ },
87
+ playwright: {
88
+ args: ["-y", `@playwright/mcp@${PLAYWRIGHT_MCP_PACKAGE_VERSION}`],
89
+ command: "npx",
90
+ },
91
+ terreno: {
92
+ type: "http",
93
+ url: `${mcpUrl}/mcp`,
94
+ },
95
+ "terreno-local": {
96
+ args: ["terreno-mcp-local"],
97
+ command: "bunx",
98
+ },
99
+ },
100
+ }, null, 2);
101
+ };
102
+ const generateRootGitignore = () => {
103
+ return [
104
+ "# Dependencies",
105
+ "node_modules/",
106
+ "",
107
+ "# Local env (use .env.example as a template)",
108
+ "backend/.env",
109
+ "frontend/.env",
110
+ "",
111
+ "# Local Terreno dev logs (winston JSONL + optional browser fallback)",
112
+ ".terreno/",
113
+ "",
114
+ "# Build outputs",
115
+ "dist/",
116
+ "build/",
117
+ "",
118
+ "# OS",
119
+ ".DS_Store",
120
+ "",
121
+ ].join("\n");
122
+ };
123
+ const DEPLOYMENT_BASELINE_DOC = "https://github.com/FlourishHealth/terreno/blob/master/docs/explanation/deployment-baseline.md";
124
+ const DEPLOY_BACKEND_CLOUD_RUN_DOC = "https://github.com/FlourishHealth/terreno/blob/master/docs/how-to/deploy-backend-to-cloud-run.md";
125
+ const BUILD_FOR_WEB_DOC = "https://github.com/FlourishHealth/terreno/blob/master/docs/how-to/build-for-web.md";
126
+ const generateRootReadme = (args) => {
127
+ const { appDisplayName, appName } = args;
128
+ const dbName = appName.replace(/-/g, "_");
129
+ return `# ${appDisplayName}
130
+
131
+ Full-stack Terreno app generated by [\`create-terreno-app\`](https://www.npmjs.com/package/create-terreno-app).
132
+
133
+ ## Project structure
134
+
135
+ - **backend/** — Express/Mongoose API (\`@terreno/api\`, Better Auth, admin, sync)
136
+ - **frontend/** — Expo universal app (\`@terreno/ui\`, \`@terreno/syncdb\`, \`@terreno/rtk\`)
137
+
138
+ ## Local development
139
+
140
+ 1. **MongoDB replica set** (required for sync/realtime). For local dev, run a single-node replica set and point \`MONGO_URI\` at it. See the [deployment baseline](${DEPLOYMENT_BASELINE_DOC}).
141
+
142
+ 2. **Install dependencies**
143
+
144
+ \`\`\`bash
145
+ cd backend && bun install
146
+ cd ../frontend && bun install
147
+ \`\`\`
148
+
149
+ 3. **Configure env** — copy \`backend/.env.example\` and \`frontend/.env.example\` to \`.env\` (or use the generated, gitignored local defaults in \`backend/.env\` / \`frontend/.env\`).
150
+
151
+ 4. **Seed login users**
152
+
153
+ \`\`\`bash
154
+ cd backend && bun run seed
155
+ \`\`\`
156
+
157
+ Creates \`test@example.com\` and \`admin@example.com\` (password \`testpassword123\`).
158
+
159
+ 5. **Start the stack**
160
+
161
+ \`\`\`bash
162
+ # Terminal 1 — API (default port 4000)
163
+ cd backend && bun run dev
164
+
165
+ # Terminal 2 — web UI (port 8082)
166
+ cd frontend && bun run web
167
+ \`\`\`
168
+
169
+ After backend route changes, regenerate the OpenAPI SDK:
170
+
171
+ \`\`\`bash
172
+ cd frontend && bun run sdk
173
+ \`\`\`
174
+
175
+ ## Deploy
176
+
177
+ Read the [deployment baseline](${DEPLOYMENT_BASELINE_DOC}) first (MongoDB replica set, auth secrets, \`EXPO_PUBLIC_*\` at build time, \`/health\`, and more).
178
+
179
+ ### Backend (Docker / Cloud Run)
180
+
181
+ This repo includes a **consumer** \`Dockerfile\` at the project root. It builds only \`backend/\` — not the Terreno monorepo.
182
+
183
+ \`\`\`bash
184
+ docker build -t ${appName}-backend .
185
+ docker run --rm -p 8080:8080 \\
186
+ -e MONGO_URI='mongodb+srv://...' \\
187
+ -e BETTER_AUTH_SECRET='...' \\
188
+ -e BETTER_AUTH_URL='https://api.example.com' \\
189
+ ${appName}-backend
190
+ \`\`\`
191
+
192
+ Cloud Run and other platforms set \`PORT\`; the server listens on that port and exposes \`GET /health\`.
193
+
194
+ Step-by-step GCP deploy: [Deploy backend to Cloud Run](${DEPLOY_BACKEND_CLOUD_RUN_DOC}).
195
+
196
+ ### Frontend (static web)
197
+
198
+ Set \`EXPO_PUBLIC_API_URL\` **before** export — it is inlined into the bundle at build time:
199
+
200
+ \`\`\`bash
201
+ cd frontend
202
+ EXPO_PUBLIC_API_URL=https://api.example.com bun expo export --platform web
203
+ \`\`\`
204
+
205
+ Full walkthrough: [Build for web](${BUILD_FOR_WEB_DOC}).
206
+
207
+ ## Default local database name
208
+
209
+ \`MONGO_URI\` defaults to \`mongodb://127.0.0.1:27017/${dbName}?replicaSet=rs0\` in \`backend/.env\`.
210
+ `;
211
+ };
212
+ const generateRootDockerfile = () => {
213
+ return `# Consumer Terreno backend image — builds backend/ only (not the Terreno monorepo).
214
+ FROM oven/bun:1-slim AS builder
215
+ WORKDIR /app
216
+
217
+ COPY backend/package.json ./
218
+ RUN bun install
219
+
220
+ COPY backend/ ./
221
+
222
+ FROM oven/bun:1-slim
223
+ WORKDIR /app
224
+
225
+ RUN apt-get update \\
226
+ && apt-get install -y --no-install-recommends curl \\
227
+ && rm -rf /var/lib/apt/lists/* \\
228
+ && useradd -r -u 1001 appuser
229
+
230
+ COPY --from=builder /app/ ./
231
+
232
+ ENV NODE_ENV=production
233
+ ENV PORT=8080
234
+
235
+ EXPOSE 8080
236
+
237
+ HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=3 \\
238
+ CMD curl -fsS "http://127.0.0.1:\${PORT}/health" | grep -q '"healthy":true' || exit 1
239
+
240
+ RUN chown -R appuser:appuser /app
241
+ USER appuser
242
+
243
+ CMD ["bun", "run", "start"]
244
+ `;
245
+ };
246
+ const generateRootDockerignore = () => {
247
+ return [
248
+ ".git",
249
+ ".gitignore",
250
+ "**/node_modules",
251
+ "**/dist",
252
+ "backend/.env",
253
+ "frontend/.env",
254
+ "",
255
+ ].join("\n");
256
+ };
257
+ const generateClaudeMd = (args) => {
258
+ const { appDisplayName } = args;
259
+ return `# ${appDisplayName}
260
+
261
+ A full-stack application built with the Terreno framework.
262
+
263
+ ## Project Structure
264
+
265
+ - **frontend/** - Expo/React Native frontend
266
+ - **backend/** - Express/Mongoose backend
267
+
268
+ ## Development
269
+
270
+ \`\`\`bash
271
+ # Install dependencies
272
+ cd backend && bun install
273
+ cd frontend && bun install
274
+
275
+ # Start backend (port 4000)
276
+ cd backend && bun run dev
277
+
278
+ # Start frontend (port 8082)
279
+ cd frontend && bun run web
280
+
281
+ # Regenerate SDK after backend changes
282
+ cd frontend && bun run sdk
283
+ \`\`\`
284
+
285
+ ## Adding Features
286
+
287
+ 1. Create model in \`backend/src/models/\`
288
+ 2. Create route in \`backend/src/api/\`
289
+ 3. Register route in \`backend/src/server.ts\`
290
+ 4. Regenerate SDK: \`cd frontend && bun run sdk\`
291
+ 5. Create screens in \`frontend/app/\`
292
+
293
+ ## Code Style
294
+
295
+ - Use TypeScript with ES modules
296
+ - Use Luxon for dates
297
+ - Prefer const arrow functions
298
+ - Named exports preferred
299
+ - Use interfaces over types
300
+ `;
301
+ };
302
+ // Backend file generators
303
+ const generateBackendPackageJson = (args) => {
304
+ const { appName } = args;
305
+ return JSON.stringify({
306
+ dependencies: {
307
+ "@terreno/admin-backend": TERRENO_DEP_VERSION,
308
+ "@terreno/api": TERRENO_DEP_VERSION,
309
+ "@terreno/api-health": TERRENO_DEP_VERSION,
310
+ luxon: "^3.7.2",
311
+ mongodb: MONGODB_VERSION,
312
+ mongoose: MONGOOSE_VERSION,
313
+ "passport-local-mongoose": "^9.0.1",
314
+ },
315
+ devDependencies: {
316
+ "@biomejs/biome": "^2.3.6",
317
+ "@types/bun": "^1.4.0",
318
+ "@types/express": "^4.17.21",
319
+ "@types/luxon": "^3.7.1",
320
+ typescript: "~5.9.2",
321
+ },
322
+ name: `@${appName}/backend`,
323
+ overrides: {
324
+ bson: BSON_VERSION,
325
+ mongodb: MONGODB_VERSION,
326
+ },
327
+ private: true,
328
+ scripts: {
329
+ build: "bun build src/index.ts --outdir ./dist --target node",
330
+ compile: "tsc",
331
+ dev: "PORT=4000 bun run --watch src/index.ts",
332
+ format: "biome format --write .",
333
+ lint: "biome check .",
334
+ "lint:fix": "biome check --write .",
335
+ "lint:unsafefix": "biome check --write . --unsafe",
336
+ seed: "bun run src/scripts/seed.ts",
337
+ start: "bun run src/index.ts",
338
+ test: "bun test",
339
+ },
340
+ type: "module",
341
+ version: "1.0.0",
342
+ }, null, 2);
343
+ };
344
+ const generateBackendTsConfig = () => {
345
+ return JSON.stringify({
346
+ compilerOptions: {
347
+ allowSyntheticDefaultImports: true,
348
+ esModuleInterop: true,
349
+ lib: ["ESNext"],
350
+ module: "ESNext",
351
+ moduleResolution: "bundler",
352
+ noEmit: true,
353
+ outDir: "./dist",
354
+ resolveJsonModule: true,
355
+ skipLibCheck: true,
356
+ strict: true,
357
+ target: "ESNext",
358
+ types: ["bun-types"],
359
+ },
360
+ exclude: ["node_modules", "dist"],
361
+ include: ["src/**/*"],
362
+ }, null, 2);
363
+ };
364
+ const generateBackendBiomeJsonc = () => {
365
+ return `{
366
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
367
+ "assist": {
368
+ "actions": {
369
+ "source": {
370
+ "organizeImports": "on",
371
+ "useSortedAttributes": "on",
372
+ "useSortedKeys": "on"
373
+ }
374
+ },
375
+ "enabled": true
376
+ },
377
+ "files": {
378
+ "includes": [
379
+ "package.json",
380
+ "src/**/*.ts",
381
+ "src/**/*.tsx",
382
+ "!!**/node_modules",
383
+ "!!**/dist",
384
+ "!!**/build",
385
+ "!!**/coverage",
386
+ "!!**/.git"
387
+ ]
388
+ },
389
+ "formatter": {
390
+ "enabled": true,
391
+ "indentStyle": "space",
392
+ "indentWidth": 2,
393
+ "lineWidth": 100
394
+ },
395
+ "javascript": {
396
+ "formatter": {
397
+ "arrowParentheses": "always",
398
+ "bracketSpacing": false,
399
+ "jsxQuoteStyle": "double",
400
+ "quoteStyle": "double",
401
+ "semicolons": "always",
402
+ "trailingCommas": "es5"
403
+ },
404
+ // TODO: Remove once we don't need to import React from 'react' in our JSX files.
405
+ "jsxRuntime": "reactClassic"
406
+ },
407
+ "linter": {
408
+ "enabled": true,
409
+ "rules": {
410
+ "nursery": {
411
+ "noFloatingPromises": "error",
412
+ "noMisusedPromises": "error",
413
+ "useExhaustiveSwitchCases": "error"
414
+ },
415
+ "recommended": true,
416
+ "suspicious": {
417
+ "noConsole": {
418
+ "level": "error",
419
+ "options": {
420
+ "allow": ["assert", "debug", "error", "info", "warn"]
421
+ }
422
+ },
423
+ "noExplicitAny": "off",
424
+ "noImplicitAnyLet": "off"
425
+ }
426
+ }
427
+ },
428
+ "vcs": {
429
+ "clientKind": "git",
430
+ "defaultBranch": "master",
431
+ "enabled": true
432
+ }
433
+ }
434
+ `;
435
+ };
436
+ const generateBackendIndex = () => {
437
+ return `import "./server";
438
+ `;
439
+ };
440
+ const generateBackendAccess = () => {
441
+ return `import {
442
+ createAccess,
443
+ terrenoStatements,
444
+ type UserModel as TerrenoAuthUserModel,
445
+ } from "@terreno/api";
446
+ import mongoose from "mongoose";
447
+
448
+ import {User} from "./models/user";
449
+
450
+ export const access = createAccess({
451
+ connection: mongoose.connection,
452
+ organizations: true,
453
+ statements: terrenoStatements,
454
+ userModel: User as unknown as TerrenoAuthUserModel,
455
+ });
456
+ `;
457
+ };
458
+ const generateBackendServer = (args) => {
459
+ const { appDisplayName } = args;
460
+ return `import {AdminApp} from "@terreno/admin-backend";
461
+ import {HealthApp} from "@terreno/api-health";
462
+ import {
463
+ BetterAuthApp,
464
+ checkModelsStrict,
465
+ createBetterAuth,
466
+ getMongoClientFromMongoose,
467
+ logger,
468
+ Membership,
469
+ RealtimeApp,
470
+ SyncApp,
471
+ TerrenoApp,
472
+ type UserModel as TerrenoAuthUserModel,
473
+ } from "@terreno/api";
474
+ import type express from "express";
475
+ import mongoose from "mongoose";
476
+ import {access} from "./access";
477
+ import {userRouter} from "./api/users";
478
+ import {AppConfiguration} from "./models/appConfiguration";
479
+ import {organizationSettingsSchema} from "./models/organizationSettings";
480
+ import {User} from "./models/user";
481
+ import "./types/models/organizationSettingsTypes";
482
+ import {buildBetterAuthConfig, getWebOrigins} from "./utils/betterAuthConfig";
483
+ import {connectToMongoDB} from "./utils/database";
484
+
485
+ const isDeployed = process.env.NODE_ENV === "production";
486
+
487
+ export const start = async (skipListen = false): Promise<express.Application> => {
488
+ await connectToMongoDB();
489
+
490
+ logger.info(\`Starting ${appDisplayName} server on port \${process.env.PORT || 4000}\`);
491
+
492
+ if (!isDeployed) {
493
+ checkModelsStrict();
494
+ }
495
+
496
+ await access.roles.seedDefaults();
497
+
498
+ const betterAuthConfig = buildBetterAuthConfig();
499
+ const betterAuthInstance = betterAuthConfig
500
+ ? createBetterAuth({
501
+ config: betterAuthConfig,
502
+ mongoClient: getMongoClientFromMongoose(),
503
+ // noExplicitAny: User model type mismatch
504
+ // biome-ignore lint/suspicious/noExplicitAny: User model type mismatch
505
+ userModel: User as any,
506
+ })
507
+ : undefined;
508
+
509
+ const terraApp = new TerrenoApp({
510
+ accessControl: access,
511
+ corsOrigin: getWebOrigins(),
512
+ loggingOptions: {
513
+ disableConsoleColors: isDeployed,
514
+ level: "debug",
515
+ logRequests: !isDeployed,
516
+ },
517
+ organizations: {
518
+ settingsSchema: organizationSettingsSchema,
519
+ },
520
+ skipListen,
521
+ // noExplicitAny: User model type mismatch
522
+ // biome-ignore lint/suspicious/noExplicitAny: User model type mismatch
523
+ userModel: User as any,
524
+ }).configure(AppConfiguration);
525
+
526
+ if (betterAuthConfig) {
527
+ terraApp.register(
528
+ new BetterAuthApp({
529
+ config: betterAuthConfig,
530
+ userModel: User as unknown as TerrenoAuthUserModel,
531
+ })
532
+ );
533
+ }
534
+
535
+ return terraApp
536
+ .register(userRouter)
537
+ .register(
538
+ new HealthApp({
539
+ check: async () => {
540
+ const mongoConnected = mongoose.connection.readyState === 1;
541
+ return {
542
+ details: {
543
+ database: mongoConnected ? "connected" : "disconnected",
544
+ uptime: process.uptime(),
545
+ },
546
+ healthy: mongoConnected,
547
+ };
548
+ },
549
+ })
550
+ )
551
+ .register(
552
+ new AdminApp({
553
+ models: [
554
+ {
555
+ displayName: "Users",
556
+ listFields: ["email", "name", "admin", "created"],
557
+ // noExplicitAny: User model type mismatch
558
+ // biome-ignore lint/suspicious/noExplicitAny: User model type mismatch
559
+ model: User as any,
560
+ routePath: "/users",
561
+ },
562
+ ],
563
+ })
564
+ )
565
+ .register(
566
+ new SyncApp({
567
+ accessControl: access,
568
+ getUserScopes: async (user) => {
569
+ const memberships = await Membership.findActiveForUser(user.id);
570
+ return memberships.map((membership) => String(membership.organizationId));
571
+ },
572
+ })
573
+ )
574
+ .register(
575
+ new RealtimeApp({
576
+ betterAuth: betterAuthInstance
577
+ ? {
578
+ auth: betterAuthInstance,
579
+ // noExplicitAny: User model type mismatch
580
+ // biome-ignore lint/suspicious/noExplicitAny: User model type mismatch
581
+ userModel: User as any,
582
+ }
583
+ : undefined,
584
+ // noExplicitAny: User model type mismatch
585
+ // biome-ignore lint/suspicious/noExplicitAny: User model type mismatch
586
+ userModel: User as any,
587
+ })
588
+ )
589
+ .start();
590
+ };
591
+
592
+ start().catch((error) => {
593
+ logger.error(\`Fatal error starting server: \${error}\`);
594
+ });
595
+ `;
596
+ };
597
+ const generateBackendDatabase = (args) => {
598
+ const { appName } = args;
599
+ const dbName = appName.replace(/-/g, "_");
600
+ return `import {logger} from "@terreno/api";
601
+ import mongoose from "mongoose";
602
+
603
+ export const connectToMongoDB = async (): Promise<void> => {
604
+ if (mongoose.connection.readyState === 1) {
605
+ logger.info("Already connected to MongoDB");
606
+ return;
607
+ }
608
+
609
+ const mongoURI =
610
+ process.env.MONGO_URI || "mongodb://127.0.0.1:27017/${dbName}?replicaSet=rs0";
611
+
612
+ try {
613
+ await mongoose.connect(mongoURI);
614
+ logger.info("Connected to MongoDB");
615
+ } catch (error: unknown) {
616
+ logger.error(\`MongoDB connection error: \${error}\`);
617
+ throw error;
618
+ }
619
+
620
+ mongoose.connection.on("error", (error: unknown) => {
621
+ logger.error(\`MongoDB connection error: \${error}\`);
622
+ });
623
+
624
+ mongoose.connection.on("disconnected", () => {
625
+ logger.warn("MongoDB disconnected");
626
+ });
627
+ };
628
+ `;
629
+ };
630
+ const generateBackendSeed = (args) => {
631
+ const { appDisplayName } = args;
632
+ return `import {
633
+ APIError,
634
+ createBetterAuth,
635
+ getMongoClientFromMongoose,
636
+ logger,
637
+ Membership,
638
+ Organization,
639
+ runSeedCli,
640
+ seedBetterAuthUser,
641
+ type SeedStep,
642
+ type UserModel as TerrenoAuthUserModel,
643
+ } from "@terreno/api";
644
+ import mongoose from "mongoose";
645
+
646
+ import {access} from "../access";
647
+ import {User} from "../models/user";
648
+ import {buildBetterAuthConfig} from "../utils/betterAuthConfig";
649
+ import {connectToMongoDB} from "../utils/database";
650
+
651
+ const SEED_USERS = [
652
+ {
653
+ admin: false,
654
+ email: "test@example.com",
655
+ name: "Test User",
656
+ password: "testpassword123",
657
+ },
658
+ {
659
+ admin: true,
660
+ email: "admin@example.com",
661
+ name: "Admin User",
662
+ password: "testpassword123",
663
+ },
664
+ ];
665
+
666
+ const seedSteps: SeedStep[] = [
667
+ {
668
+ description: "Create login-ready development users and reconcile profile fields",
669
+ name: "users",
670
+ run: async (context) => {
671
+ if (context.dryRun) {
672
+ for (const user of SEED_USERS) {
673
+ const existing = await User.findByEmail(user.email);
674
+ context.changes.push({
675
+ change: existing ? "updated" : "created",
676
+ count: 1,
677
+ key: JSON.stringify({email: user.email}),
678
+ model: User.modelName,
679
+ });
680
+ }
681
+ return;
682
+ }
683
+
684
+ const config = buildBetterAuthConfig();
685
+ if (!config) {
686
+ throw new APIError({
687
+ status: 500,
688
+ title: "Seed users require Better Auth to be enabled",
689
+ });
690
+ }
691
+ const auth = createBetterAuth({
692
+ config,
693
+ mongoClient: getMongoClientFromMongoose(),
694
+ userModel: User as unknown as TerrenoAuthUserModel,
695
+ });
696
+ for (const definition of SEED_USERS) {
697
+ const user = await seedBetterAuthUser({
698
+ auth,
699
+ user: definition,
700
+ userModel: User as unknown as TerrenoAuthUserModel,
701
+ });
702
+ const appUser = user as unknown as {
703
+ admin: boolean;
704
+ save: () => Promise<unknown>;
705
+ };
706
+ appUser.admin = definition.admin;
707
+ const roles = (appUser as unknown as {roles?: string[]}).roles ?? [];
708
+ if (definition.admin && !roles.includes("operator")) {
709
+ (appUser as unknown as {roles: string[]}).roles = [...roles, "operator"];
710
+ }
711
+ await appUser.save();
712
+ }
713
+ },
714
+ },
715
+ {
716
+ description: "Create the default organization and attach the admin as org-admin",
717
+ name: "organization",
718
+ run: async (context) => {
719
+ await access.roles.seedDefaults();
720
+ const existing = await Organization.findOneOrNone({name: "${appDisplayName}"});
721
+ if (context.dryRun) {
722
+ context.changes.push({
723
+ change: existing ? "updated" : "created",
724
+ count: 1,
725
+ key: JSON.stringify({name: "${appDisplayName}"}),
726
+ model: Organization.modelName,
727
+ });
728
+ return;
729
+ }
730
+ const admin = await User.findByEmail("admin@example.com");
731
+ if (!admin) {
732
+ throw new APIError({
733
+ status: 500,
734
+ title: "Default organization requires admin@example.com",
735
+ });
736
+ }
737
+ const organization =
738
+ existing ??
739
+ (await Organization.create({
740
+ name: "${appDisplayName}",
741
+ ownerId: admin._id,
742
+ }));
743
+ const membership = await Membership.findOneOrNone({
744
+ organizationId: organization._id,
745
+ userId: admin._id,
746
+ });
747
+ if (!membership) {
748
+ await Membership.create({
749
+ organizationId: organization._id,
750
+ roleName: "org-admin",
751
+ userId: admin._id,
752
+ });
753
+ }
754
+ },
755
+ },
756
+ ];
757
+
758
+ const main = async (): Promise<void> => {
759
+ const cli = await runSeedCli({
760
+ allowProductionReset: () => process.env.ALLOW_SEED_RESET === "true",
761
+ connect: connectToMongoDB,
762
+ disconnect: async () => {
763
+ await mongoose.disconnect();
764
+ },
765
+ name: "bun run seed",
766
+ steps: seedSteps,
767
+ });
768
+ if (cli.help) {
769
+ logger.info(cli.help);
770
+ }
771
+ process.exit(cli.exitCode);
772
+ };
773
+
774
+ main().catch((error: unknown) => {
775
+ logger.error(\`Seed failed: \${error}\`);
776
+ process.exit(1);
777
+ });
778
+ `;
779
+ };
780
+ const generateBackendBetterAuthConfig = (args) => {
781
+ const { appName } = args;
782
+ return `import type {AuthProvider, BetterAuthConfig} from "@terreno/api";
783
+
784
+ const DEFAULT_BETTER_AUTH_URL = "http://localhost:4000";
785
+ const DEFAULT_WEB_ORIGINS = ["http://localhost:8082", "http://127.0.0.1:8082"];
786
+ const APP_SCHEMES = ["${appName}://", "exp://"];
787
+
788
+ export const getAuthProvider = (): AuthProvider => {
789
+ const provider = process.env.AUTH_PROVIDER as AuthProvider | undefined;
790
+ return provider ?? "better-auth";
791
+ };
792
+
793
+ export const getWebOrigins = (): string[] => {
794
+ const origins = new Set<string>(DEFAULT_WEB_ORIGINS);
795
+ const fromEnv = process.env.CORS_ORIGINS?.split(",")
796
+ .map((value) => value.trim())
797
+ .filter(Boolean);
798
+ for (const origin of fromEnv ?? []) {
799
+ origins.add(origin);
800
+ }
801
+ return [...origins];
802
+ };
803
+
804
+ export const buildBetterAuthConfig = (): BetterAuthConfig | undefined => {
805
+ if (getAuthProvider() !== "better-auth") {
806
+ return undefined;
807
+ }
808
+
809
+ const secret = process.env.BETTER_AUTH_SECRET;
810
+ if (!secret) {
811
+ throw new Error("BETTER_AUTH_SECRET is required when AUTH_PROVIDER=better-auth");
812
+ }
813
+
814
+ return {
815
+ baseURL: process.env.BETTER_AUTH_URL ?? DEFAULT_BETTER_AUTH_URL,
816
+ crossDomainCookies: process.env.CROSS_DOMAIN_AUTH_COOKIES === "true",
817
+ enabled: true,
818
+ secret,
819
+ trustedOrigins: [...APP_SCHEMES, ...getWebOrigins()],
820
+ };
821
+ };
822
+ `;
823
+ };
824
+ const generateBackendModelPlugins = () => {
825
+ return `import {
826
+ createdUpdatedPlugin,
827
+ findExactlyOne,
828
+ findOneOrNone,
829
+ isDeletedPlugin,
830
+ } from "@terreno/api";
831
+ import type mongoose from "mongoose";
832
+
833
+ // noExplicitAny: Leaving open for flexibility
834
+ // biome-ignore lint/suspicious/noExplicitAny: Leaving open for flexibility
835
+ export function addDefaultPlugins(schema: mongoose.Schema<any, any, any, any>): void {
836
+ schema.plugin(createdUpdatedPlugin);
837
+ schema.plugin(isDeletedPlugin);
838
+ schema.plugin(findOneOrNone);
839
+ schema.plugin(findExactlyOne);
840
+ }
841
+ `;
842
+ };
843
+ const generateBackendUserModel = () => {
844
+ return `import mongoose from "mongoose";
845
+ import passportLocalMongoose from "passport-local-mongoose";
846
+ import type {UserDocument, UserModel} from "../types";
847
+ import {addDefaultPlugins} from "./modelPlugins";
848
+
849
+ const userSchema = new mongoose.Schema<UserDocument, UserModel>(
850
+ {
851
+ admin: {
852
+ default: false,
853
+ description: "Whether the user has administrator access",
854
+ type: Boolean,
855
+ },
856
+ betterAuthId: {
857
+ description: "Identifier linking to the Better Auth session provider",
858
+ index: true,
859
+ sparse: true,
860
+ type: String,
861
+ },
862
+ email: {
863
+ description: "The user's email address, used for authentication",
864
+ lowercase: true,
865
+ required: true,
866
+ trim: true,
867
+ type: String,
868
+ unique: true,
869
+ },
870
+ name: {
871
+ description: "The user's display name",
872
+ required: true,
873
+ trim: true,
874
+ type: String,
875
+ },
876
+ },
877
+ {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
878
+ );
879
+
880
+ userSchema.plugin(passportLocalMongoose, {
881
+ usernameField: "email",
882
+ });
883
+
884
+ addDefaultPlugins(userSchema);
885
+
886
+ userSchema.method("getDisplayName", function (this: UserDocument): string {
887
+ return this.name;
888
+ });
889
+
890
+ export const User = mongoose.model<UserDocument, UserModel>("User", userSchema);
891
+
892
+ User.findByEmail = async function (email: string): Promise<UserDocument | null> {
893
+ return this.findOneOrNone({email: email.toLowerCase()});
894
+ };
895
+ `;
896
+ };
897
+ const generateBackendAppConfiguration = (args) => {
898
+ const { appDisplayName } = args;
899
+ return `import {configurationPlugin, createdUpdatedPlugin} from "@terreno/api";
900
+ import mongoose, {Schema} from "mongoose";
901
+
902
+ const generalSchema = new Schema(
903
+ {
904
+ appName: {
905
+ default: "${appDisplayName}",
906
+ description: "Display name of the application",
907
+ type: String,
908
+ },
909
+ maintenanceMode: {
910
+ default: false,
911
+ description: "When enabled, the app returns 503 for all non-admin requests",
912
+ type: Boolean,
913
+ },
914
+ },
915
+ {_id: false}
916
+ );
917
+
918
+ const debugSchema = new Schema(
919
+ {
920
+ websocketsDebug: {
921
+ default: false,
922
+ description: "Enable verbose WebSocket and realtime sync debug logging",
923
+ type: Boolean,
924
+ },
925
+ },
926
+ {_id: false}
927
+ );
928
+
929
+ export interface AppConfigDocument {
930
+ general: {
931
+ appName: string;
932
+ maintenanceMode: boolean;
933
+ };
934
+ debug: {
935
+ websocketsDebug: boolean;
936
+ };
937
+ }
938
+
939
+ const appConfigSchema = new Schema<AppConfigDocument>(
940
+ {
941
+ general: {
942
+ description: "General application settings",
943
+ type: generalSchema,
944
+ },
945
+ debug: {
946
+ description: "Debug and diagnostic settings",
947
+ type: debugSchema,
948
+ },
949
+ },
950
+ {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
951
+ );
952
+
953
+ appConfigSchema.plugin(configurationPlugin);
954
+ appConfigSchema.plugin(createdUpdatedPlugin);
955
+
956
+ export const AppConfiguration = mongoose.model<AppConfigDocument>(
957
+ "AppConfiguration",
958
+ appConfigSchema
959
+ );
960
+ `;
961
+ };
962
+ const generateBackendOrganizationSettings = () => {
963
+ return `import {createOrganizationSettingsSchema} from "@terreno/api";
964
+
965
+ export const organizationSettingsSchema = createOrganizationSettingsSchema({
966
+ timezone: {
967
+ description: "IANA timezone used for organization-local dates",
968
+ type: String,
969
+ },
970
+ });
971
+ `;
972
+ };
973
+ const generateBackendOrganizationSettingsTypes = () => {
974
+ return `export interface AppOrganizationSettings {
975
+ timezone?: string;
976
+ }
977
+
978
+ declare module "@terreno/api" {
979
+ interface OrganizationSettings extends AppOrganizationSettings {}
980
+ }
981
+ `;
982
+ };
983
+ const generateBackendModelsIndex = () => {
984
+ return `export * from "./appConfiguration";
985
+ export * from "./organizationSettings";
986
+ export * from "./user";
987
+ `;
988
+ };
989
+ const generateBackendUserRoutes = () => {
990
+ return `import {Permissions, modelRouter} from "@terreno/api";
991
+ import type {Model} from "mongoose";
992
+ import {User} from "../models/user";
993
+ import type {UserDocument} from "../types";
994
+
995
+ export const userRouter = modelRouter("/users", User as unknown as Model<UserDocument>, {
996
+ permissions: {
997
+ create: [Permissions.IsAdmin],
998
+ delete: [Permissions.IsAdmin],
999
+ list: [Permissions.IsAdmin],
1000
+ read: [Permissions.IsAdmin],
1001
+ update: [Permissions.IsAdmin],
1002
+ },
1003
+ queryFields: ["email", "name"],
1004
+ sort: "name",
1005
+ });
1006
+ `;
1007
+ };
1008
+ const generateBackendTypes = () => {
1009
+ return `export * from "./models";
1010
+ `;
1011
+ };
1012
+ const generateBackendTypesModels = () => {
1013
+ return `export * from "./organizationSettingsTypes";
1014
+ export * from "./userTypes";
1015
+ `;
1016
+ };
1017
+ const generateBackendUserTypes = () => {
1018
+ return `import type {APIErrorConstructor} from "@terreno/api";
1019
+ import type mongoose from "mongoose";
1020
+ import type {Document, Model} from "mongoose";
1021
+ import type {
1022
+ PassportLocalMongooseDocument,
1023
+ PassportLocalMongooseModel,
1024
+ } from "passport-local-mongoose";
1025
+
1026
+ type ModelQuery<T> = Partial<Record<keyof T, unknown>> & Record<string, unknown>;
1027
+
1028
+ export interface DefaultStatics<T> {
1029
+ findOneOrNone(
1030
+ query: ModelQuery<T>,
1031
+ errorArgs?: Partial<APIErrorConstructor>
1032
+ ): Promise<(Document & T) | null>;
1033
+
1034
+ findExactlyOne(
1035
+ query: ModelQuery<T>,
1036
+ errorArgs?: Partial<APIErrorConstructor>
1037
+ ): Promise<Document & T>;
1038
+ }
1039
+
1040
+ export interface DefaultPluginFields {
1041
+ created: Date;
1042
+ updated: Date;
1043
+ deleted: boolean;
1044
+ }
1045
+
1046
+ export type DefaultModel<T> = Model<T & DefaultPluginFields> & DefaultStatics<T>;
1047
+ export type DefaultDoc = mongoose.Document<mongoose.Types.ObjectId> & DefaultPluginFields;
1048
+
1049
+ export type UserMethods = {
1050
+ getDisplayName: (this: UserDocument) => string;
1051
+ };
1052
+
1053
+ export type UserStatics = DefaultStatics<UserDocument> & {
1054
+ findByEmail: (this: UserModel, email: string) => Promise<UserDocument | null>;
1055
+ };
1056
+
1057
+ export type UserModel = DefaultModel<UserDocument> &
1058
+ UserStatics &
1059
+ PassportLocalMongooseModel<UserDocument>;
1060
+
1061
+ export type UserSchema = mongoose.Schema<UserDocument, UserModel, UserMethods>;
1062
+
1063
+ export type UserDocument = DefaultDoc &
1064
+ UserMethods &
1065
+ PassportLocalMongooseDocument & {
1066
+ admin: boolean;
1067
+ betterAuthId?: string;
1068
+ email: string;
1069
+ name: string;
1070
+ };
1071
+ `;
1072
+ };
1073
+ // Frontend file generators
1074
+ const generateFrontendPackageJson = (args) => {
1075
+ const { appName } = args;
1076
+ return JSON.stringify({
1077
+ dependencies: {
1078
+ "@expo/vector-icons": "^15.1.1",
1079
+ "@react-native-async-storage/async-storage": "2.2.0",
1080
+ "@reduxjs/toolkit": "^2.11.1",
1081
+ "@sentry/react": "^10.29.0",
1082
+ "@terreno/admin-frontend": TERRENO_DEP_VERSION,
1083
+ "@terreno/rtk": TERRENO_DEP_VERSION,
1084
+ "@terreno/syncdb": TERRENO_DEP_VERSION,
1085
+ "@terreno/ui": TERRENO_DEP_VERSION,
1086
+ expo: "~57.0.14",
1087
+ "expo-constants": "~57.0.12",
1088
+ "expo-router": "~57.0.14",
1089
+ "expo-sqlite": "~57.0.1",
1090
+ lodash: "^4.18.1",
1091
+ luxon: "^3.7.2",
1092
+ react: "19.2.3",
1093
+ "react-dom": "19.2.3",
1094
+ "react-native": "0.86.2",
1095
+ "react-native-reanimated": "4.5.1",
1096
+ "react-redux": "^9.2.0",
1097
+ "redux-persist": "^6.0.0",
1098
+ },
1099
+ devDependencies: {
1100
+ "@biomejs/biome": "^2.3.6",
1101
+ "@playwright/test": "^1.58.2",
1102
+ "@rtk-query/codegen-openapi": "^2.2.0",
1103
+ "@types/bun": "^1.4.0",
1104
+ "@types/lodash": "^4.17.17",
1105
+ "@types/luxon": "^3.7.1",
1106
+ "@types/react": "~19.2.14",
1107
+ "ts-node": "^10.9.2",
1108
+ tsx: "^4.23.12",
1109
+ typescript: "~6.0.3",
1110
+ },
1111
+ main: "expo-router/entry",
1112
+ name: `@${appName}/frontend`,
1113
+ private: true,
1114
+ scripts: {
1115
+ android: "EXPO_UNSTABLE_MCP_SERVER=1 bun expo start --android --port 8082",
1116
+ compile: "tsc",
1117
+ ios: "EXPO_UNSTABLE_MCP_SERVER=1 bun expo start --ios --port 8082",
1118
+ lint: "bun biome check .",
1119
+ "lint:fix": "bun biome check --write .",
1120
+ "lint:unsafefix": "biome check --write . --unsafe",
1121
+ sdk: "bun scripts/generate-sdk.ts && bun biome check --write scripts/generate-sdk.ts",
1122
+ start: "EXPO_UNSTABLE_MCP_SERVER=1 bun expo start --port 8082",
1123
+ test: "bun test",
1124
+ web: "EXPO_UNSTABLE_MCP_SERVER=1 bun expo start --web --port 8082",
1125
+ },
1126
+ version: "1.0.0",
1127
+ }, null, 2);
1128
+ };
1129
+ const generateFrontendAppJson = (args) => {
1130
+ const { appDisplayName, appName } = args;
1131
+ return JSON.stringify({
1132
+ // No icon/splash/favicon keys: Expo falls back to its built-in defaults, so a freshly
1133
+ // generated app bundles without any binary assets. Add your own branding later and
1134
+ // point `icon`, `android.adaptiveIcon`, `splash`, and `web.favicon` at those files.
1135
+ expo: {
1136
+ experiments: {
1137
+ typedRoutes: true,
1138
+ },
1139
+ ios: {
1140
+ supportsTablet: true,
1141
+ },
1142
+ name: appDisplayName,
1143
+ orientation: "portrait",
1144
+ plugins: ["expo-router"],
1145
+ scheme: appName,
1146
+ slug: appName,
1147
+ userInterfaceStyle: "automatic",
1148
+ version: "1.0.0",
1149
+ web: {
1150
+ bundler: "metro",
1151
+ output: "static",
1152
+ },
1153
+ },
1154
+ }, null, 2);
1155
+ };
1156
+ const generateFrontendTsConfig = () => {
1157
+ // No `baseUrl`: it is deprecated as of TypeScript 6 and makes `tsc` abort with TS5101
1158
+ // before checking a single file. `paths` entries are relative to this tsconfig instead.
1159
+ return JSON.stringify({
1160
+ compilerOptions: {
1161
+ allowJs: true,
1162
+ allowSyntheticDefaultImports: true,
1163
+ esModuleInterop: true,
1164
+ ignoreDeprecations: "6.0",
1165
+ jsx: "react-jsx",
1166
+ lib: ["DOM", "ESNext"],
1167
+ module: "esnext",
1168
+ moduleResolution: "bundler",
1169
+ noEmit: true,
1170
+ paths: {
1171
+ "@/*": ["./*"],
1172
+ "@components/*": ["./components/*"],
1173
+ "@store": ["./store/index"],
1174
+ "@store/*": ["./store/*"],
1175
+ "@utils": ["./utils/index"],
1176
+ "@utils/*": ["./utils/*"],
1177
+ },
1178
+ resolveJsonModule: true,
1179
+ skipLibCheck: true,
1180
+ strict: true,
1181
+ target: "ESNext",
1182
+ types: ["bun-types", "react-native", "@types/react"],
1183
+ },
1184
+ extends: "expo/tsconfig.base",
1185
+ include: ["**/*.ts", "**/*.tsx", ".expo/types/**/*.ts", "expo-env.d.ts"],
1186
+ }, null, 2);
1187
+ };
1188
+ const generateFrontendMetroConfig = () => {
1189
+ return `const {getDefaultConfig} = require("expo/metro-config");
1190
+ const path = require("path");
1191
+
1192
+ const config = getDefaultConfig(__dirname);
1193
+
1194
+ const defaultResolveRequest = config.resolver.resolveRequest;
1195
+
1196
+ config.resolver.resolveRequest = (context, moduleName, platform) => {
1197
+ // @terreno/admin-frontend imports jspdf for its consent-PDF export. jspdf's CommonJS and
1198
+ // Node builds wrap an AMD-style \`require(["html2canvas"], cb)\` call that Metro's static
1199
+ // transform cannot parse, which fails the whole bundle — including Expo Router's static
1200
+ // web render, which resolves under a "node" condition and would otherwise pick
1201
+ // jspdf.node.min.js. Pin every jspdf request to the ESM browser build on web, and drop it
1202
+ // on native, where PDF export is unavailable and jspdf's browser/Node APIs are missing.
1203
+ if (moduleName === "jspdf" || moduleName.startsWith("jspdf/dist/jspdf.node")) {
1204
+ if (platform !== "web") {
1205
+ return {type: "empty"};
1206
+ }
1207
+ try {
1208
+ const jspdfDir = path.dirname(require.resolve("jspdf/package.json", {paths: [__dirname]}));
1209
+ return {
1210
+ filePath: path.join(jspdfDir, "dist", "jspdf.es.min.js"),
1211
+ type: "sourceFile",
1212
+ };
1213
+ } catch {
1214
+ // jspdf is not installed — let Metro report the failure itself.
1215
+ }
1216
+ }
1217
+
1218
+ return defaultResolveRequest
1219
+ ? defaultResolveRequest(context, moduleName, platform)
1220
+ : context.resolveRequest(context, moduleName, platform);
1221
+ };
1222
+
1223
+ module.exports = config;
1224
+ `;
1225
+ };
1226
+ const generateFrontendTsConfigCodegen = () => {
1227
+ return JSON.stringify({
1228
+ compilerOptions: {
1229
+ esModuleInterop: true,
1230
+ ignoreDeprecations: "6.0",
1231
+ module: "commonjs",
1232
+ moduleResolution: "node",
1233
+ resolveJsonModule: true,
1234
+ skipLibCheck: true,
1235
+ strict: true,
1236
+ target: "ES2020",
1237
+ },
1238
+ }, null, 2);
1239
+ };
1240
+ const generateFrontendBiomeJsonc = () => {
1241
+ return `{
1242
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
1243
+ "assist": {
1244
+ "actions": {
1245
+ "source": {
1246
+ "organizeImports": "on",
1247
+ "useSortedAttributes": "on",
1248
+ "useSortedKeys": "on"
1249
+ }
1250
+ },
1251
+ "enabled": true
1252
+ },
1253
+ "files": {
1254
+ "includes": [
1255
+ "package.json",
1256
+ "app/**/*.ts",
1257
+ "app/**/*.tsx",
1258
+ "components/**/*.ts",
1259
+ "components/**/*.tsx",
1260
+ "store/**/*.ts",
1261
+ "store/**/*.tsx",
1262
+ "utils/**/*.ts",
1263
+ "utils/**/*.tsx",
1264
+ "constants/**/*.ts",
1265
+ "scripts/**/*.ts",
1266
+ "!!**/node_modules",
1267
+ "!!**/dist",
1268
+ "!!**/build",
1269
+ "!!**/coverage",
1270
+ "!!**/.expo",
1271
+ "!!**/.next",
1272
+ "!!**/generated",
1273
+ "!!**/.git"
1274
+ ]
1275
+ },
1276
+ "formatter": {
1277
+ "enabled": true,
1278
+ "indentStyle": "space",
1279
+ "indentWidth": 2,
1280
+ "lineWidth": 100
1281
+ },
1282
+ "javascript": {
1283
+ "formatter": {
1284
+ "arrowParentheses": "always",
1285
+ "bracketSpacing": false,
1286
+ "jsxQuoteStyle": "double",
1287
+ "quoteStyle": "double",
1288
+ "semicolons": "always",
1289
+ "trailingCommas": "es5"
1290
+ },
1291
+ // TODO: Remove once we don't need to import React from 'react' in our JSX files.
1292
+ "jsxRuntime": "reactClassic"
1293
+ },
1294
+ "linter": {
1295
+ "enabled": true,
1296
+ "rules": {
1297
+ "nursery": {
1298
+ "noFloatingPromises": "error",
1299
+ "noMisusedPromises": "error",
1300
+ "useExhaustiveSwitchCases": "error"
1301
+ },
1302
+ "recommended": true,
1303
+ "suspicious": {
1304
+ "noConsole": {
1305
+ "level": "error",
1306
+ "options": {
1307
+ "allow": ["assert", "debug", "error", "info", "warn"]
1308
+ }
1309
+ },
1310
+ "noExplicitAny": "off",
1311
+ "noImplicitAnyLet": "off"
1312
+ }
1313
+ }
1314
+ },
1315
+ "vcs": {
1316
+ "clientKind": "git",
1317
+ "defaultBranch": "master",
1318
+ "enabled": true
1319
+ }
1320
+ }
1321
+ `;
1322
+ };
1323
+ const generateFrontendBetterAuthApi = () => {
1324
+ return `/**
1325
+ * RTK Query API base for Better Auth session cookies.
1326
+ *
1327
+ * Unlike \`@terreno/rtk\`'s JWT \`emptySplitApi\`, this base query reads the Better Auth
1328
+ * session token on every request and sends it as a Bearer header with credentials.
1329
+ */
1330
+ import {createApi, fetchBaseQuery} from "@reduxjs/toolkit/query/react";
1331
+ import {baseUrl, IsWeb, type VersionCheckResponse} from "@terreno/rtk";
1332
+ import Constants from "expo-constants";
1333
+ import {betterAuthClient} from "@/lib/betterAuth";
1334
+
1335
+ const readSessionToken = async (): Promise<string | null> => {
1336
+ try {
1337
+ const result = await betterAuthClient.getSession();
1338
+ const envelope = (result as {data?: {session?: {token?: string}}})?.data ?? result;
1339
+ const session = (envelope as {session?: {token?: string}})?.session;
1340
+ return session?.token ?? null;
1341
+ } catch {
1342
+ return null;
1343
+ }
1344
+ };
1345
+
1346
+ const betterAuthBaseQuery = fetchBaseQuery({
1347
+ baseUrl,
1348
+ credentials: "include",
1349
+ prepareHeaders: async (headers) => {
1350
+ const token = await readSessionToken();
1351
+ if (token) {
1352
+ headers.set("authorization", \`Bearer \${token}\`);
1353
+ }
1354
+ const version = Constants.expoConfig?.version;
1355
+ if (version) {
1356
+ headers.set("App-Version", version);
1357
+ }
1358
+ headers.set("App-Platform", IsWeb ? "web" : "mobile");
1359
+ return headers;
1360
+ },
1361
+ responseHandler: async (response) => {
1362
+ if (response.status === 204) {
1363
+ return null;
1364
+ }
1365
+ const result = await response.json();
1366
+ if (result && typeof result === "object" && "more" in result) {
1367
+ return result;
1368
+ }
1369
+ if (result?.data) {
1370
+ return result.data;
1371
+ }
1372
+ return result;
1373
+ },
1374
+ });
1375
+
1376
+ export const emptySplitApi = createApi({
1377
+ baseQuery: betterAuthBaseQuery,
1378
+ endpoints: (builder) => ({
1379
+ getVersionCheck: builder.query<VersionCheckResponse, {platform: string; version: number}>({
1380
+ query: ({platform, version}) => ({
1381
+ params: {platform, version},
1382
+ url: "/version-check",
1383
+ }),
1384
+ }),
1385
+ }),
1386
+ reducerPath: "terreno-rtk",
1387
+ });
1388
+
1389
+ export const {useGetVersionCheckQuery, useLazyGetVersionCheckQuery} = emptySplitApi;
1390
+ `;
1391
+ };
1392
+ const generateFrontendOpenApiConfig = () => {
1393
+ return `import type {ConfigFile} from "@rtk-query/codegen-openapi";
1394
+
1395
+ const config: ConfigFile = {
1396
+ apiFile: "./store/betterAuthApi.ts",
1397
+ apiImport: "emptySplitApi",
1398
+ argSuffix: "Args",
1399
+ exportName: "openapi",
1400
+ flattenArg: true,
1401
+ hooks: true,
1402
+ outputFile: "./store/openApiSdk.ts",
1403
+ responseSuffix: "Res",
1404
+ schemaFile: process.env.OPENAPI_URL ?? "http://localhost:4000/openapi.json",
1405
+ tag: true,
1406
+ };
1407
+
1408
+ export default config;
1409
+ `;
1410
+ };
1411
+ const generateFrontendGenerateSdk = () => {
1412
+ return `#!/usr/bin/env bun
1413
+
1414
+ import {execFile} from "node:child_process";
1415
+ import {existsSync, readFileSync, realpathSync, writeFileSync} from "node:fs";
1416
+ import {basename, dirname, extname, join, resolve, sep} from "node:path";
1417
+
1418
+ const cliPath = join(
1419
+ __dirname,
1420
+ "..",
1421
+ "node_modules",
1422
+ "@rtk-query",
1423
+ "codegen-openapi",
1424
+ "lib",
1425
+ "bin",
1426
+ "cli.mjs"
1427
+ );
1428
+ const configFile = process.argv[2] ?? "openapi-config.ts";
1429
+ const sdkFile = process.argv[3] ?? "store/openApiSdk.ts";
1430
+ const projectRoot = resolve(__dirname, "..");
1431
+ const configPath = resolve(projectRoot, configFile);
1432
+ const sdkPath = resolve(projectRoot, sdkFile);
1433
+ const tsConfigPath = join(__dirname, "..", "tsconfig.codegen.json");
1434
+ const canonicalProjectRoot = realpathSync(projectRoot);
1435
+
1436
+ const isProjectFile = (filePath: string): boolean => {
1437
+ if (!filePath.startsWith(\`\${projectRoot}\${sep}\`) || extname(filePath) !== ".ts") {
1438
+ return false;
1439
+ }
1440
+ try {
1441
+ const canonicalPath = existsSync(filePath)
1442
+ ? realpathSync(filePath)
1443
+ : resolve(realpathSync(dirname(filePath)), basename(filePath));
1444
+ return canonicalPath.startsWith(\`\${canonicalProjectRoot}\${sep}\`);
1445
+ } catch {
1446
+ return false;
1447
+ }
1448
+ };
1449
+
1450
+ if (!isProjectFile(configPath) || !isProjectFile(sdkPath)) {
1451
+ console.error("SDK config and output must be TypeScript files inside frontend/");
1452
+ process.exit(1);
1453
+ }
1454
+
1455
+ execFile(
1456
+ "tsx",
1457
+ [cliPath, configPath],
1458
+ {env: {...process.env, TS_NODE_PROJECT: tsConfigPath}},
1459
+ (error, _stdout, stderr) => {
1460
+ if (error) {
1461
+ console.error(\`Error: \${error.message}\`);
1462
+ process.exit(1);
1463
+ }
1464
+ if (stderr) {
1465
+ console.error(\`stderr: \${stderr}\`);
1466
+ }
1467
+
1468
+ if (existsSync(sdkPath)) {
1469
+ let content = readFileSync(sdkPath, "utf8");
1470
+ content = content.replace(/^export const \\{\\} = injectedRtkApi;\\n?/m, "");
1471
+ if (!content.startsWith("// biome-ignore-all lint/suspicious/noExplicitAny")) {
1472
+ content =
1473
+ "// biome-ignore-all lint/suspicious/noExplicitAny: types are generated from backend OpenAPI schemas\\n" +
1474
+ content;
1475
+ }
1476
+ writeFileSync(sdkPath, content, "utf8");
1477
+ }
1478
+
1479
+ execFile(
1480
+ "bunx",
1481
+ ["biome", "check", "--unsafe", "--write", sdkPath],
1482
+ {cwd: projectRoot},
1483
+ (formatError) => {
1484
+ if (formatError) {
1485
+ console.error(\`Formatting error: \${formatError.message}\`);
1486
+ process.exit(1);
1487
+ }
1488
+ }
1489
+ );
1490
+ }
1491
+ );
1492
+ `;
1493
+ };
1494
+ const generateFrontendRootLayout = (_args) => {
1495
+ return `import {DefaultTheme, ThemeProvider} from "expo-router/react-navigation";
1496
+ import {Stack} from "expo-router";
1497
+ import {useEffect} from "react";
1498
+ import "react-native-reanimated";
1499
+ import {baseUrl, selectBetterAuthIsLoading, selectBetterAuthUserId} from "@terreno/rtk";
1500
+ import {SyncDbProvider} from "@terreno/syncdb/react";
1501
+ import {Spinner, TerrenoProvider} from "@terreno/ui";
1502
+ import {Provider, useSelector} from "react-redux";
1503
+ import {PersistGate} from "redux-persist/integration/react";
1504
+ import store, {persistor, syncBetterAuthSession} from "@/store/index";
1505
+ import {setSyncDbReady, syncDb} from "@/store/syncdb";
1506
+
1507
+ export {ErrorBoundary} from "expo-router";
1508
+
1509
+ export const unstable_settings = {
1510
+ initialRouteName: "(tabs)",
1511
+ };
1512
+
1513
+ // TerrenoProvider loads the Nunito/Titillium Web families @terreno/ui renders with, so this
1514
+ // app ships no font assets of its own. Add \`useFonts\` here only for extra custom faces.
1515
+ export default function RootLayout(): React.ReactElement | null {
1516
+ return (
1517
+ <Provider store={store}>
1518
+ <PersistGate loading={null} persistor={persistor}>
1519
+ <TerrenoProvider openAPISpecUrl={\`\${baseUrl}/openapi.json\`}>
1520
+ <RootLayoutNav />
1521
+ </TerrenoProvider>
1522
+ </PersistGate>
1523
+ </Provider>
1524
+ );
1525
+ }
1526
+
1527
+ function RootLayoutNav(): React.ReactElement {
1528
+ const userId = useSelector(selectBetterAuthUserId) ?? undefined;
1529
+ const isAuthLoading = useSelector(selectBetterAuthIsLoading);
1530
+
1531
+ // Hydrate Better Auth session into Redux on startup.
1532
+ useEffect(() => {
1533
+ void syncBetterAuthSession(store.dispatch);
1534
+ }, []);
1535
+
1536
+ // Start syncdb after login; stop on logout.
1537
+ useEffect(() => {
1538
+ if (!userId) {
1539
+ setSyncDbReady(false);
1540
+ return;
1541
+ }
1542
+ let stopped = false;
1543
+ void syncDb
1544
+ .start()
1545
+ .then(() => {
1546
+ if (!stopped) {
1547
+ setSyncDbReady(true);
1548
+ }
1549
+ })
1550
+ .catch((startError: unknown) => {
1551
+ console.error("[syncdb] start failed", startError);
1552
+ setSyncDbReady(false);
1553
+ });
1554
+ return () => {
1555
+ stopped = true;
1556
+ setSyncDbReady(false);
1557
+ void syncDb.stop();
1558
+ };
1559
+ }, [userId]);
1560
+
1561
+ if (isAuthLoading) {
1562
+ return <Spinner />;
1563
+ }
1564
+
1565
+ return (
1566
+ <SyncDbProvider client={syncDb}>
1567
+ <ThemeProvider value={DefaultTheme}>
1568
+ {/* Stack.Protected is the supported way to gate routes on auth state. Rendering
1569
+ Stack.Screen children behind a raw conditional (or a fragment) crashes the
1570
+ navigator, because Stack reads its screen config off the child elements. */}
1571
+ <Stack>
1572
+ <Stack.Protected guard={!userId}>
1573
+ <Stack.Screen name="login" options={{headerShown: false}} />
1574
+ <Stack.Screen name="signup" options={{headerShown: false}} />
1575
+ </Stack.Protected>
1576
+ <Stack.Protected guard={Boolean(userId)}>
1577
+ <Stack.Screen name="(tabs)" options={{headerShown: false}} />
1578
+ </Stack.Protected>
1579
+ </Stack>
1580
+ </ThemeProvider>
1581
+ </SyncDbProvider>
1582
+ );
1583
+ }
1584
+ `;
1585
+ };
1586
+ const generateFrontendLogin = () => {
1587
+ return `import {baseUrl} from "@terreno/rtk";
1588
+ import {LoginScreen} from "@terreno/ui";
1589
+ import {useRouter} from "expo-router";
1590
+ import type React from "react";
1591
+ import {useCallback, useState} from "react";
1592
+ import {betterAuthClient} from "@/lib/betterAuth";
1593
+ import {syncBetterAuthSession, useAppDispatch} from "@/store/index";
1594
+
1595
+ const Login: React.FC = () => {
1596
+ const router = useRouter();
1597
+ const dispatch = useAppDispatch();
1598
+ const [errorMessage, setErrorMessage] = useState<string | undefined>(undefined);
1599
+ const [isSubmitting, setIsSubmitting] = useState(false);
1600
+
1601
+ const handleSubmit = useCallback(
1602
+ async (values: Record<string, string>): Promise<void> => {
1603
+ const {email, password} = values;
1604
+ setErrorMessage(undefined);
1605
+ setIsSubmitting(true);
1606
+ try {
1607
+ const result = await betterAuthClient.signIn.email({email, password});
1608
+ if (result.error) {
1609
+ setErrorMessage(result.error.message ?? "Sign in failed.");
1610
+ return;
1611
+ }
1612
+ await syncBetterAuthSession(dispatch);
1613
+ router.replace("/(tabs)");
1614
+ } catch (error: unknown) {
1615
+ console.error("[login] Sign in threw", {baseUrl, error});
1616
+ setErrorMessage("Sign in failed. Please try again.");
1617
+ } finally {
1618
+ setIsSubmitting(false);
1619
+ }
1620
+ },
1621
+ [dispatch, router]
1622
+ );
1623
+
1624
+ return (
1625
+ <LoginScreen
1626
+ error={errorMessage}
1627
+ fields={[
1628
+ {autoComplete: "off", label: "Email", name: "email", required: true, type: "email"},
1629
+ {label: "Password", name: "password", required: true, type: "password"},
1630
+ ]}
1631
+ loading={isSubmitting}
1632
+ onSignUpPress={() => router.push("/signup")}
1633
+ onSubmit={handleSubmit}
1634
+ title="Welcome"
1635
+ />
1636
+ );
1637
+ };
1638
+
1639
+ export default Login;
1640
+ `;
1641
+ };
1642
+ const generateFrontendSignup = () => {
1643
+ return `import {SignUpScreen, simplePasswordRequirements} from "@terreno/ui";
1644
+ import {useRouter} from "expo-router";
1645
+ import type React from "react";
1646
+ import {useCallback, useState} from "react";
1647
+ import {betterAuthClient} from "@/lib/betterAuth";
1648
+ import {syncBetterAuthSession, useAppDispatch} from "@/store/index";
1649
+
1650
+ const SignUp: React.FC = () => {
1651
+ const router = useRouter();
1652
+ const dispatch = useAppDispatch();
1653
+ const [errorMessage, setErrorMessage] = useState<string | undefined>(undefined);
1654
+ const [isSubmitting, setIsSubmitting] = useState(false);
1655
+
1656
+ const handleSubmit = useCallback(
1657
+ async (values: Record<string, string>): Promise<void> => {
1658
+ const {email, password, name} = values;
1659
+ setErrorMessage(undefined);
1660
+ setIsSubmitting(true);
1661
+ try {
1662
+ const result = await betterAuthClient.signUp.email({email, name, password});
1663
+ if (result.error) {
1664
+ setErrorMessage(result.error.message ?? "Sign up failed.");
1665
+ return;
1666
+ }
1667
+ await syncBetterAuthSession(dispatch);
1668
+ router.replace("/(tabs)");
1669
+ } catch {
1670
+ setErrorMessage("Sign up failed. Please try again.");
1671
+ } finally {
1672
+ setIsSubmitting(false);
1673
+ }
1674
+ },
1675
+ [dispatch, router]
1676
+ );
1677
+
1678
+ return (
1679
+ <SignUpScreen
1680
+ error={errorMessage}
1681
+ fields={[
1682
+ {label: "Name", name: "name", required: true, type: "text"},
1683
+ {autoComplete: "off", label: "Email", name: "email", required: true, type: "email"},
1684
+ {label: "Password", name: "password", required: true, type: "password"},
1685
+ ]}
1686
+ loading={isSubmitting}
1687
+ onLoginPress={() => router.back()}
1688
+ onSubmit={handleSubmit}
1689
+ passwordRequirements={simplePasswordRequirements}
1690
+ />
1691
+ );
1692
+ };
1693
+
1694
+ export default SignUp;
1695
+ `;
1696
+ };
1697
+ const generateFrontendTabsLayout = () => {
1698
+ return `import FontAwesome from "@expo/vector-icons/FontAwesome";
1699
+ import {useTheme} from "@terreno/ui";
1700
+ import {Tabs} from "expo-router";
1701
+ import type React from "react";
1702
+ import type {ColorValue} from "react-native";
1703
+
1704
+ const TabBarIcon: React.FC<{
1705
+ name: React.ComponentProps<typeof FontAwesome>["name"];
1706
+ color: ColorValue;
1707
+ }> = ({name, color}) => {
1708
+ return <FontAwesome color={color} name={name} size={24} style={{marginBottom: -3}} />;
1709
+ };
1710
+
1711
+ const TabLayout: React.FC = () => {
1712
+ const {theme} = useTheme();
1713
+
1714
+ return (
1715
+ <Tabs
1716
+ screenOptions={{
1717
+ headerShown: false,
1718
+ tabBarActiveTintColor: theme.surface.primary,
1719
+ }}
1720
+ >
1721
+ <Tabs.Screen
1722
+ name="index"
1723
+ options={{
1724
+ tabBarIcon: ({color}) => <TabBarIcon color={color} name="home" />,
1725
+ title: "Home",
1726
+ }}
1727
+ />
1728
+ <Tabs.Screen
1729
+ name="profile"
1730
+ options={{
1731
+ headerShown: false,
1732
+ tabBarIcon: ({color}) => <TabBarIcon color={color} name="user" />,
1733
+ title: "Profile",
1734
+ }}
1735
+ />
1736
+ <Tabs.Screen
1737
+ name="admin"
1738
+ options={{
1739
+ headerShown: false,
1740
+ tabBarIcon: ({color}) => <TabBarIcon color={color} name="cog" />,
1741
+ title: "Admin",
1742
+ }}
1743
+ />
1744
+ </Tabs>
1745
+ );
1746
+ };
1747
+
1748
+ export default TabLayout;
1749
+ `;
1750
+ };
1751
+ const generateFrontendTabsIndex = (args) => {
1752
+ const { appDisplayName } = args;
1753
+ return `import {Box, Heading, Page, Text} from "@terreno/ui";
1754
+ import type React from "react";
1755
+
1756
+ const HomeScreen: React.FC = () => {
1757
+ return (
1758
+ <Page navigation={undefined} title="Home">
1759
+ <Box padding={4} gap={4}>
1760
+ <Heading>Welcome to ${appDisplayName}</Heading>
1761
+ <Text>Your app is ready for development!</Text>
1762
+ <Text color="secondaryDark">
1763
+ Start by adding models to the backend and screens to the frontend.
1764
+ </Text>
1765
+ </Box>
1766
+ </Page>
1767
+ );
1768
+ };
1769
+
1770
+ export default HomeScreen;
1771
+ `;
1772
+ };
1773
+ const generateFrontendTabsProfile = () => {
1774
+ return `import {Box, Button, Card, Heading, Page, Spinner, TapToEdit, Text} from "@terreno/ui";
1775
+ import type React from "react";
1776
+ import {useCallback, useEffect, useState} from "react";
1777
+ import {signOut} from "@/lib/betterAuth";
1778
+ import {logout, syncBetterAuthSession, useAppDispatch} from "@/store/index";
1779
+ import {useGetMeQuery, usePatchMeMutation} from "@/store/sdk";
1780
+
1781
+ const ProfileScreen: React.FC = () => {
1782
+ const dispatch = useAppDispatch();
1783
+ const {data: profile, isLoading} = useGetMeQuery();
1784
+ const [updateProfile] = usePatchMeMutation();
1785
+ const [name, setName] = useState<string>("");
1786
+ const [email, setEmail] = useState<string>("");
1787
+ const [password, setPassword] = useState<string>("");
1788
+ const [saveError, setSaveError] = useState<string | null>(null);
1789
+
1790
+ const user = profile;
1791
+
1792
+ // Copy the server name into local state without resetting an in-progress email edit.
1793
+ useEffect(() => {
1794
+ if (!user) {
1795
+ return;
1796
+ }
1797
+ setName(user.name || "");
1798
+ }, [user?.name]);
1799
+
1800
+ // Copy the server email into local state without resetting an in-progress name edit.
1801
+ useEffect(() => {
1802
+ if (!user) {
1803
+ return;
1804
+ }
1805
+ setEmail(user.email || "");
1806
+ }, [user?.email]);
1807
+
1808
+ const handleLogout = useCallback(async (): Promise<void> => {
1809
+ await signOut();
1810
+ dispatch(logout());
1811
+ await syncBetterAuthSession(dispatch);
1812
+ }, [dispatch]);
1813
+
1814
+ const handleSaveName = useCallback(
1815
+ async (value: string): Promise<void> => {
1816
+ setSaveError(null);
1817
+ try {
1818
+ await updateProfile({name: value}).unwrap();
1819
+ } catch (err) {
1820
+ console.error("Error updating name:", err);
1821
+ setSaveError("Failed to update name");
1822
+ }
1823
+ },
1824
+ [updateProfile]
1825
+ );
1826
+
1827
+ const handleSaveEmail = useCallback(
1828
+ async (value: string): Promise<void> => {
1829
+ setSaveError(null);
1830
+ try {
1831
+ await updateProfile({email: value}).unwrap();
1832
+ } catch (err) {
1833
+ console.error("Error updating email:", err);
1834
+ setSaveError("Failed to update email");
1835
+ }
1836
+ },
1837
+ [updateProfile]
1838
+ );
1839
+
1840
+ const handleSavePassword = useCallback(
1841
+ async (value: string): Promise<void> => {
1842
+ if (!value) {
1843
+ return;
1844
+ }
1845
+ setSaveError(null);
1846
+ try {
1847
+ await updateProfile({password: value}).unwrap();
1848
+ setPassword("");
1849
+ } catch (err) {
1850
+ console.error("Error updating password:", err);
1851
+ setSaveError("Failed to update password");
1852
+ }
1853
+ },
1854
+ [updateProfile]
1855
+ );
1856
+
1857
+ if (isLoading) {
1858
+ return (
1859
+ <Page navigation={undefined} title="Profile">
1860
+ <Box alignItems="center" flex="grow" justifyContent="center" padding={4}>
1861
+ <Spinner />
1862
+ </Box>
1863
+ </Page>
1864
+ );
1865
+ }
1866
+
1867
+ return (
1868
+ <Page navigation={undefined} scroll title="Profile">
1869
+ <Box gap={4} padding={4}>
1870
+ <Heading>Profile</Heading>
1871
+ <Card>
1872
+ <Box gap={4}>
1873
+ <TapToEdit
1874
+ onSave={handleSaveName}
1875
+ setValue={setName}
1876
+ title="Name"
1877
+ type="text"
1878
+ value={name}
1879
+ />
1880
+ <TapToEdit
1881
+ onSave={handleSaveEmail}
1882
+ setValue={setEmail}
1883
+ title="Email"
1884
+ type="email"
1885
+ value={email}
1886
+ />
1887
+ <TapToEdit
1888
+ helperText="Leave blank to keep your current password"
1889
+ onSave={handleSavePassword}
1890
+ setValue={setPassword}
1891
+ title="New Password"
1892
+ type="password"
1893
+ value={password}
1894
+ />
1895
+ {saveError && <Text color="error">{saveError}</Text>}
1896
+ </Box>
1897
+ </Card>
1898
+ <Box marginTop={4}>
1899
+ <Button fullWidth onClick={handleLogout} text="Logout" variant="outline" />
1900
+ </Box>
1901
+ </Box>
1902
+ </Page>
1903
+ );
1904
+ };
1905
+
1906
+ export default ProfileScreen;
1907
+ `;
1908
+ };
1909
+ const generateFrontendAdminLayout = () => {
1910
+ return `import {Stack} from "expo-router";
1911
+ import type React from "react";
1912
+
1913
+ const AdminLayout: React.FC = () => {
1914
+ return <Stack screenOptions={{headerShown: false}} />;
1915
+ };
1916
+
1917
+ export default AdminLayout;
1918
+ `;
1919
+ };
1920
+ const generateFrontendAdminIndex = () => {
1921
+ return `import {AdminModelList} from "@terreno/admin-frontend";
1922
+ import type React from "react";
1923
+ import {adminTerrenoApi} from "@/store/sdk";
1924
+
1925
+ const AdminListScreen: React.FC = () => {
1926
+ return (
1927
+ <AdminModelList
1928
+ api={adminTerrenoApi}
1929
+ baseUrl="/admin"
1930
+ configurationPath="/admin/configuration"
1931
+ />
1932
+ );
1933
+ };
1934
+
1935
+ export default AdminListScreen;
1936
+ `;
1937
+ };
1938
+ const generateFrontendAdminConfiguration = () => {
1939
+ return `import {ConfigurationScreen} from "@terreno/admin-frontend";
1940
+ import type React from "react";
1941
+ import {adminTerrenoApi} from "@/store/sdk";
1942
+
1943
+ const ConfigurationPage: React.FC = () => {
1944
+ return <ConfigurationScreen api={adminTerrenoApi} />;
1945
+ };
1946
+
1947
+ export default ConfigurationPage;
1948
+ `;
1949
+ };
1950
+ const generateFrontendNotFound = () => {
1951
+ return `import {Box, Heading, Text} from "@terreno/ui";
1952
+ import {Link, Stack} from "expo-router";
1953
+ import type React from "react";
1954
+
1955
+ const NotFoundScreen: React.FC = () => {
1956
+ return (
1957
+ <>
1958
+ <Stack.Screen options={{title: "Oops!"}} />
1959
+ <Box alignItems="center" flex="grow" justifyContent="center" padding={4}>
1960
+ <Heading size="xl">This screen doesn't exist.</Heading>
1961
+ <Link href="/" style={{marginTop: 15, paddingVertical: 15}}>
1962
+ <Text color="link" size="md">
1963
+ Go to home screen!
1964
+ </Text>
1965
+ </Link>
1966
+ </Box>
1967
+ </>
1968
+ );
1969
+ };
1970
+
1971
+ export default NotFoundScreen;
1972
+ `;
1973
+ };
1974
+ const generateFrontendStoreIndex = () => {
1975
+ return `import AsyncStorage from "@react-native-async-storage/async-storage";
1976
+ import {combineReducers, configureStore, type Store} from "@reduxjs/toolkit";
1977
+ import {
1978
+ type BetterAuthClientInterface,
1979
+ generateBetterAuthSlice,
1980
+ registerTerrenoDevStore,
1981
+ } from "@terreno/rtk";
1982
+ import {DateTime} from "luxon";
1983
+ import {useDispatch} from "react-redux";
1984
+ import type {Storage} from "redux-persist";
1985
+ import {persistReducer, persistStore} from "redux-persist";
1986
+ import {betterAuthClient} from "@/lib/betterAuth";
1987
+
1988
+ import appState from "./appState";
1989
+ import {rtkQueryErrorMiddleware} from "./errors";
1990
+ import {terrenoApi} from "./sdk";
1991
+
1992
+ const betterAuth = generateBetterAuthSlice({
1993
+ authClient: betterAuthClient as unknown as BetterAuthClientInterface,
1994
+ });
1995
+
1996
+ export const logout = betterAuth.actions.logout;
1997
+ export const syncBetterAuthSession = betterAuth.syncSession;
1998
+
1999
+ const createSafeStorage = (): Storage => {
2000
+ return {
2001
+ getItem: async (key: string): Promise<string | null> => {
2002
+ if (typeof window !== "undefined") {
2003
+ return AsyncStorage.getItem(key);
2004
+ }
2005
+ return null;
2006
+ },
2007
+ removeItem: async (key: string): Promise<void> => {
2008
+ if (typeof window !== "undefined") {
2009
+ return AsyncStorage.removeItem(key);
2010
+ }
2011
+ },
2012
+ setItem: async (key: string, value: string): Promise<void> => {
2013
+ if (typeof window !== "undefined") {
2014
+ return AsyncStorage.setItem(key, value);
2015
+ }
2016
+ },
2017
+ };
2018
+ };
2019
+
2020
+ const persistConfig = {
2021
+ blacklist: ["terreno-rtk", "betterAuth"],
2022
+ key: "root",
2023
+ storage: createSafeStorage(),
2024
+ timeout: 0,
2025
+ version: 1,
2026
+ };
2027
+
2028
+ const rootReducer = combineReducers({
2029
+ appState,
2030
+ betterAuth: betterAuth.reducer,
2031
+ "terreno-rtk": terrenoApi.reducer,
2032
+ });
2033
+
2034
+ const persistedReducer = persistReducer(persistConfig, rootReducer);
2035
+
2036
+ const store = configureStore({
2037
+ devTools: process.env.NODE_ENV !== "production" && {
2038
+ name: \`App-\${
2039
+ typeof window !== "undefined"
2040
+ // biome-ignore lint/suspicious/noAssignInExpressions: Window name assignment
2041
+ ? window.name || ((window.name = \`Window-\${DateTime.now().toFormat("HH:mm:ss")}\`))
2042
+ : "Unknown"
2043
+ }\`,
2044
+ },
2045
+ middleware: (getDefaultMiddleware) => {
2046
+ return getDefaultMiddleware({
2047
+ immutableCheck: false,
2048
+ serializableCheck: false,
2049
+ thunk: true,
2050
+ }).concat([
2051
+ ...betterAuth.middleware,
2052
+ // noExplicitAny: RTK Query middleware typing
2053
+ // biome-ignore lint/suspicious/noExplicitAny: RTK Query middleware typing
2054
+ terrenoApi.middleware as any,
2055
+ rtkQueryErrorMiddleware,
2056
+ // noExplicitAny: Middleware array typing
2057
+ // biome-ignore lint/suspicious/noExplicitAny: Middleware array typing
2058
+ ]) as any;
2059
+ },
2060
+ reducer: persistedReducer,
2061
+ });
2062
+
2063
+ registerTerrenoDevStore(store as unknown as Store<Record<string, unknown>>);
2064
+
2065
+ export const persistor = persistStore(store);
2066
+
2067
+ export type RootState = ReturnType<typeof store.getState>;
2068
+ export type AppDispatch = typeof store.dispatch;
2069
+
2070
+ export const useAppDispatch: () => AppDispatch = useDispatch;
2071
+
2072
+ export default store;
2073
+ `;
2074
+ };
2075
+ const generateFrontendStoreAppState = () => {
2076
+ return `import {createSlice, type PayloadAction} from "@reduxjs/toolkit";
2077
+ import {type TypedUseSelectorHook, useSelector} from "react-redux";
2078
+ import type {RootState} from "./index";
2079
+
2080
+ export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
2081
+
2082
+ export type AppState = {
2083
+ darkMode: boolean;
2084
+ language: string;
2085
+ };
2086
+
2087
+ const initialState: AppState = {
2088
+ darkMode: false,
2089
+ language: "en",
2090
+ };
2091
+
2092
+ export const appStateSlice = createSlice({
2093
+ initialState,
2094
+ name: "appState",
2095
+ reducers: {
2096
+ resetAppState: () => initialState,
2097
+ setDarkMode: (state, action: PayloadAction<boolean>) => {
2098
+ state.darkMode = action.payload;
2099
+ },
2100
+ setLanguage: (state, action: PayloadAction<string>) => {
2101
+ state.language = action.payload;
2102
+ },
2103
+ },
2104
+ });
2105
+
2106
+ export const {setDarkMode, setLanguage, resetAppState} = appStateSlice.actions;
2107
+
2108
+ export const useSelectDarkMode = (): boolean => {
2109
+ return useAppSelector((state) => state.appState.darkMode);
2110
+ };
2111
+
2112
+ export const useSelectLanguage = (): string => {
2113
+ return useAppSelector((state) => state.appState.language);
2114
+ };
2115
+
2116
+ export default appStateSlice.reducer;
2117
+ `;
2118
+ };
2119
+ const generateFrontendStoreErrors = () => {
2120
+ return `import type {Middleware} from "@reduxjs/toolkit";
2121
+ import {useToast} from "@terreno/ui";
2122
+
2123
+ const ignoredErrors = [
2124
+ "Password or username is incorrect",
2125
+ "Token refresh failed with 401",
2126
+ "Failed to refresh token",
2127
+ ];
2128
+
2129
+ // noExplicitAny: Generic middleware
2130
+ // biome-ignore lint/suspicious/noExplicitAny: Generic middleware
2131
+ export const rtkQueryErrorMiddleware: Middleware = () => (next) => (action: any) => {
2132
+ if (action?.error && action?.payload) {
2133
+ const errorMessage =
2134
+ action.payload?.data?.title ??
2135
+ action.payload?.data?.message ??
2136
+ action.payload?.error ??
2137
+ JSON.stringify(action.payload);
2138
+
2139
+ let endpointInfo = "unknown endpoint";
2140
+ if (action.meta?.baseQueryMeta?.request?.method && action.meta?.baseQueryMeta?.request?.url) {
2141
+ endpointInfo = \`\${action.meta.baseQueryMeta.request.url} \${action.meta.baseQueryMeta.request.method}\`;
2142
+ } else if (action.meta?.arg?.endpointName) {
2143
+ endpointInfo = \`\${action.meta.arg.endpointName} rejected \${action.meta.arg.type || ""}\`;
2144
+ }
2145
+
2146
+ const message = \`\${endpointInfo.trim()}: \${errorMessage}\`;
2147
+ console.debug(message);
2148
+
2149
+ if (action.payload.status === 404 || action.payload.status === 401) {
2150
+ return next(action);
2151
+ }
2152
+
2153
+ const shouldIgnore = ignoredErrors.some((err) => errorMessage.includes(err));
2154
+ if (!shouldIgnore) {
2155
+ console.warn(message);
2156
+ }
2157
+ }
2158
+
2159
+ return next(action);
2160
+ };
2161
+
2162
+ export const useSentryAndToast = (): ((errorMessage: string) => void) => {
2163
+ const toast = useToast();
2164
+ return (error: string): void => {
2165
+ if (!error) {
2166
+ return;
2167
+ }
2168
+ toast.error(error);
2169
+ console.warn(\`Error: \${error}\`);
2170
+ };
2171
+ };
2172
+ `;
2173
+ };
2174
+ const generateFrontendStoreSdk = () => {
2175
+ return `import type {AdminScreenProps} from "@terreno/admin-frontend";
2176
+ import {generateTags} from "@terreno/rtk";
2177
+ import startCase from "lodash/startCase";
2178
+
2179
+ import {addTagTypes, openapi} from "./openApiSdk";
2180
+
2181
+ /** emptyApi unwraps the \`data\` envelope — profile fields are top-level on the response. */
2182
+ export interface ProfileResponse {
2183
+ _id: string;
2184
+ id: string;
2185
+ email: string;
2186
+ name: string;
2187
+ }
2188
+
2189
+ export interface UpdateProfileRequest {
2190
+ name?: string;
2191
+ email?: string;
2192
+ password?: string;
2193
+ }
2194
+
2195
+ export const terrenoApi = openapi
2196
+ .enhanceEndpoints({
2197
+ addTagTypes: ["profile"],
2198
+ })
2199
+ .injectEndpoints({
2200
+ endpoints: (builder) => ({
2201
+ getMe: builder.query<ProfileResponse, void>({
2202
+ providesTags: ["profile"],
2203
+ query: () => ({
2204
+ method: "GET",
2205
+ url: "/auth/me",
2206
+ }),
2207
+ }),
2208
+ patchMe: builder.mutation<ProfileResponse, UpdateProfileRequest>({
2209
+ invalidatesTags: ["profile"],
2210
+ query: (body) => ({
2211
+ body,
2212
+ method: "PATCH",
2213
+ url: "/auth/me",
2214
+ }),
2215
+ }),
2216
+ }),
2217
+ })
2218
+ .enhanceEndpoints({
2219
+ endpoints: {
2220
+ ...generateTags(openapi, [...addTagTypes]),
2221
+ },
2222
+ });
2223
+
2224
+ /** Type-erased API instance for @terreno/admin-frontend screens. */
2225
+ export const adminTerrenoApi = terrenoApi as unknown as AdminScreenProps["api"];
2226
+
2227
+ export const {
2228
+ useGetMeQuery,
2229
+ usePatchMeMutation,
2230
+ } = terrenoApi;
2231
+ export * from "./openApiSdk";
2232
+
2233
+ type OpenApiEndpoints = Record<string, unknown>;
2234
+
2235
+ export const getSdkHook = (
2236
+ modelName: string,
2237
+ type: "list" | "read" | "create" | "update" | "remove"
2238
+ ): Record<string, unknown> => {
2239
+ const modelPath = startCase(modelName).replace(/\\s/g, "");
2240
+ const endpoints = openapi.endpoints as OpenApiEndpoints;
2241
+ switch (type) {
2242
+ case "list":
2243
+ return endpoints[\`get\${modelPath}\`] as Record<string, unknown>;
2244
+ case "read":
2245
+ return endpoints[\`get\${modelPath}ById\`] as Record<string, unknown>;
2246
+ case "create":
2247
+ return endpoints[\`post\${modelPath}\`] as Record<string, unknown>;
2248
+ case "update":
2249
+ return endpoints[\`patch\${modelPath}ById\`] as Record<string, unknown>;
2250
+ case "remove":
2251
+ return endpoints[\`delete\${modelPath}ById\`] as Record<string, unknown>;
2252
+ default:
2253
+ throw new Error(\`Invalid SDK hook: \${modelName}/\${type}\`);
2254
+ }
2255
+ };
2256
+ `;
2257
+ };
2258
+ const generateFrontendStoreOpenApiSdk = () => {
2259
+ return `// THIS FILE IS AUTO-GENERATED. DO NOT EDIT.
2260
+ // Run "bun run sdk" to regenerate this file from the backend OpenAPI spec.
2261
+
2262
+ import {emptySplitApi as api} from "./betterAuthApi";
2263
+ export const addTagTypes = ["Users", "Auth", "profile"] as const;
2264
+ const injectedRtkApi = api
2265
+ .enhanceEndpoints({
2266
+ addTagTypes,
2267
+ })
2268
+ .injectEndpoints({
2269
+ endpoints: () => ({}),
2270
+ overrideExisting: false,
2271
+ });
2272
+ export {injectedRtkApi as openapi};
2273
+ `;
2274
+ };
2275
+ const generateFrontendTheme = () => {
2276
+ return `// Theme configuration for the app
2277
+ // Override these values to customize the app's appearance
2278
+ // Colors are based on @terreno/ui's default theme primitives
2279
+
2280
+ export const primitives = {
2281
+ // Primary colors (teal/cyan)
2282
+ primary000: "#EBFAFF",
2283
+ primary050: "#BCE9F7",
2284
+ primary100: "#90D8F0",
2285
+ primary200: "#73CAE8",
2286
+ primary300: "#40B8E0",
2287
+ primary400: "#0E9DCD",
2288
+ primary500: "#0086B3",
2289
+ primary600: "#0A7092",
2290
+ primary700: "#035D7E",
2291
+ primary800: "#004B64",
2292
+ primary900: "#013749",
2293
+
2294
+ // Secondary colors (dark teal)
2295
+ secondary000: "#F2F9FA",
2296
+ secondary050: "#D7E5EA",
2297
+ secondary100: "#B6CDD5",
2298
+ secondary200: "#9EB7BF",
2299
+ secondary300: "#87A1AA",
2300
+ secondary400: "#608997",
2301
+ secondary500: "#2B6072",
2302
+ secondary600: "#1C4E5F",
2303
+ secondary700: "#0F3D4D",
2304
+ secondary800: "#092E3A",
2305
+ secondary900: "#041E27",
2306
+
2307
+ // Accent colors (gold/yellow)
2308
+ accent000: "#FFFDF7",
2309
+ accent050: "#FCECC2",
2310
+ accent100: "#F9E0A1",
2311
+ accent200: "#F7D582",
2312
+ accent300: "#F2CB62",
2313
+ accent400: "#E5B132",
2314
+ accent500: "#D69C0E",
2315
+ accent600: "#B58201",
2316
+ accent700: "#956A00",
2317
+ accent800: "#543C00",
2318
+ accent900: "#332400",
2319
+
2320
+ // Neutral colors (grays)
2321
+ neutral000: "#FFFFFF",
2322
+ neutral050: "#F2F2F2",
2323
+ neutral100: "#E6E6E6",
2324
+ neutral200: "#D9D9D9",
2325
+ neutral300: "#CDCDCD",
2326
+ neutral400: "#B3B3B3",
2327
+ neutral500: "#9A9A9A",
2328
+ neutral600: "#686868",
2329
+ neutral700: "#4E4E4E",
2330
+ neutral800: "#353535",
2331
+ neutral900: "#1C1C1C",
2332
+
2333
+ // Status colors
2334
+ error000: "#FDD7D7",
2335
+ error100: "#D33232",
2336
+ error200: "#BD1111",
2337
+ success000: "#DCF2E2",
2338
+ success100: "#3EA45C",
2339
+ success200: "#1A7F36",
2340
+ warning000: "#FFE3C6",
2341
+ warning100: "#F36719",
2342
+ warning200: "#B14202",
2343
+ };
2344
+
2345
+ // Semantic color mappings - override these to change app appearance
2346
+ export const colors = {
2347
+ // Backgrounds
2348
+ background: primitives.neutral000,
2349
+ backgroundSecondary: primitives.neutral050,
2350
+
2351
+ // Text
2352
+ text: primitives.neutral900,
2353
+ textSecondary: primitives.neutral600,
2354
+ textInverted: primitives.neutral000,
2355
+
2356
+ // Primary action colors
2357
+ primary: primitives.primary400,
2358
+ primaryDark: primitives.primary600,
2359
+ primaryLight: primitives.primary100,
2360
+
2361
+ // Secondary colors
2362
+ secondary: primitives.secondary500,
2363
+ secondaryDark: primitives.secondary700,
2364
+ secondaryLight: primitives.secondary100,
2365
+
2366
+ // Accent colors
2367
+ accent: primitives.accent500,
2368
+ accentDark: primitives.accent700,
2369
+ accentLight: primitives.accent100,
2370
+
2371
+ // Status colors
2372
+ error: primitives.error100,
2373
+ errorLight: primitives.error000,
2374
+ success: primitives.success100,
2375
+ successLight: primitives.success000,
2376
+ warning: primitives.warning100,
2377
+ warningLight: primitives.warning000,
2378
+
2379
+ // UI elements
2380
+ border: primitives.neutral300,
2381
+ borderFocus: primitives.primary200,
2382
+ icon: primitives.neutral600,
2383
+ tint: primitives.primary400,
2384
+
2385
+ // Tab bar
2386
+ tabIconDefault: primitives.neutral600,
2387
+ tabIconSelected: primitives.primary400,
2388
+ };
2389
+
2390
+ export default colors;
2391
+ `;
2392
+ };
2393
+ const generateFrontendEnv = () => {
2394
+ return `EXPO_PUBLIC_API_URL=http://localhost:4000
2395
+ `;
2396
+ };
2397
+ const generateBackendEnvExample = (args) => {
2398
+ const { appName } = args;
2399
+ const dbName = appName.replace(/-/g, "_");
2400
+ return `# Copy to backend/.env and fill in production values (Secret Manager / platform secrets).
2401
+ # MongoDB must be a replica set for sync and realtime — see deployment baseline docs.
2402
+
2403
+ MONGO_URI=mongodb://127.0.0.1:27017/${dbName}?replicaSet=rs0
2404
+ AUTH_PROVIDER=better-auth
2405
+ BETTER_AUTH_SECRET=
2406
+ BETTER_AUTH_URL=https://api.example.com
2407
+ CORS_ORIGINS=https://app.example.com
2408
+ TOKEN_SECRET=
2409
+ TOKEN_ISSUER=
2410
+ REFRESH_TOKEN_SECRET=
2411
+ SESSION_SECRET=
2412
+ PORT=8080
2413
+ NODE_ENV=production
2414
+ `;
2415
+ };
2416
+ const generateFrontendEnvExample = () => {
2417
+ return `# Copy to frontend/.env for local dev, or export before web build.
2418
+ # EXPO_PUBLIC_* is inlined at export time — set before \`bun expo export --platform web\`.
2419
+
2420
+ EXPO_PUBLIC_API_URL=https://api.example.com
2421
+ `;
2422
+ };
2423
+ const generateBackendEnv = (args) => {
2424
+ const { appName } = args;
2425
+ const dbName = appName.replace(/-/g, "_");
2426
+ return `MONGO_URI=mongodb://127.0.0.1:27017/${dbName}?replicaSet=rs0
2427
+ AUTH_PROVIDER=better-auth
2428
+ BETTER_AUTH_SECRET=${appName}-better-auth-secret-dev-only-32chars
2429
+ BETTER_AUTH_URL=http://localhost:4000
2430
+ TOKEN_SECRET=dev-token-secret
2431
+ TOKEN_ISSUER=${appName}-dev
2432
+ REFRESH_TOKEN_SECRET=dev-refresh-secret
2433
+ SESSION_SECRET=dev-session-secret
2434
+ PORT=4000
2435
+ `;
2436
+ };
2437
+ const generateFrontendBetterAuthLib = (args) => {
2438
+ const { appName } = args;
2439
+ return `import {baseUrl, createBetterAuthClient} from "@terreno/rtk";
2440
+ import Constants from "expo-constants";
2441
+
2442
+ const getAppScheme = (): string => {
2443
+ const expoExtra = Constants.expoConfig?.extra;
2444
+ return expoExtra?.scheme ?? "${appName}";
2445
+ };
2446
+
2447
+ export const betterAuthClient = createBetterAuthClient({
2448
+ baseURL: baseUrl,
2449
+ scheme: getAppScheme(),
2450
+ storagePrefix: "${appName}",
2451
+ });
2452
+
2453
+ export const signOut = async (): Promise<void> => {
2454
+ await betterAuthClient.signOut();
2455
+ };
2456
+ `;
2457
+ };
2458
+ const generateFrontendSyncDb = (args) => {
2459
+ const { appName } = args;
2460
+ const dbName = appName.replace(/-/g, "-");
2461
+ return `import {baseUrl} from "@terreno/rtk";
2462
+ import {
2463
+ type BetterAuthClientLike,
2464
+ betterAuthAdapter,
2465
+ createSyncDb,
2466
+ type SyncDb,
2467
+ } from "@terreno/syncdb";
2468
+ import {betterAuthClient} from "@/lib/betterAuth";
2469
+
2470
+ export const SYNC_DB_NAME = "${dbName}";
2471
+
2472
+ /** Add synced collection names here as you register modelRouter sync scopes on the backend. */
2473
+ export const SYNC_COLLECTIONS: string[] = [];
2474
+
2475
+ /**
2476
+ * The Better Auth *react* client delivers session changes through a nanostore atom
2477
+ * (\`$store.atoms.session\`), but its \`useSession\` is a React hook without \`.subscribe\`.
2478
+ * betterAuthAdapter looks for \`useSession.subscribe\`; without it, it falls back to
2479
+ * polling \`getSession()\` every 5s (constant /api/auth/get-session traffic). Bridge the
2480
+ * atom to the shape the adapter expects so auth changes are event-driven instead.
2481
+ */
2482
+ type SessionAtomLike = {subscribe: (listener: (value: unknown) => void) => () => void};
2483
+ const sessionAtom = (
2484
+ betterAuthClient as unknown as {$store?: {atoms?: {session?: SessionAtomLike}}}
2485
+ ).$store?.atoms?.session;
2486
+
2487
+ const syncAuthClient: BetterAuthClientLike = {
2488
+ getSession: () => betterAuthClient.getSession(),
2489
+ ...(sessionAtom
2490
+ ? {useSession: {subscribe: (listener): (() => void) => sessionAtom.subscribe(listener)}}
2491
+ : {}),
2492
+ };
2493
+
2494
+ // pollIntervalMs is only used as a fallback if the session atom bridge above is
2495
+ // unavailable (e.g. a future Better Auth client shape change); keep it slow.
2496
+ const authProvider = betterAuthAdapter(syncAuthClient, {pollIntervalMs: 60_000});
2497
+
2498
+ export const syncDb: SyncDb = createSyncDb({
2499
+ authProvider,
2500
+ baseUrl,
2501
+ collections: SYNC_COLLECTIONS,
2502
+ name: SYNC_DB_NAME,
2503
+ });
2504
+
2505
+ let syncDbReady = false;
2506
+ const syncDbReadyListeners = new Set<() => void>();
2507
+
2508
+ export const setSyncDbReady = (ready: boolean): void => {
2509
+ if (syncDbReady === ready) {
2510
+ return;
2511
+ }
2512
+ syncDbReady = ready;
2513
+ for (const listener of syncDbReadyListeners) {
2514
+ listener();
2515
+ }
2516
+ };
2517
+
2518
+ export const subscribeSyncDbReady = (listener: () => void): (() => void) => {
2519
+ syncDbReadyListeners.add(listener);
2520
+ return () => {
2521
+ syncDbReadyListeners.delete(listener);
2522
+ };
2523
+ };
2524
+
2525
+ export const getSyncDbReadySnapshot = (): boolean => syncDbReady;
2526
+ `;
2527
+ };
2528
+ const generateFrontendUtilsIndex = () => {
2529
+ return `export const captureException = (error: unknown): void => {
2530
+ console.error("Captured exception:", error);
2531
+ };
2532
+
2533
+ export const captureMessage = (message: string): void => {
2534
+ console.warn("Captured message:", message);
2535
+ };
2536
+
2537
+ export const createSentryReduxEnhancer = (): unknown => {
2538
+ return undefined;
2539
+ };
2540
+ `;
2541
+ };
2542
+ const generateBackendCiWorkflow = (_args) => {
2543
+ return `name: Backend CI
2544
+
2545
+ on:
2546
+ push:
2547
+ paths:
2548
+ - "backend/**"
2549
+ - ".github/workflows/backend-ci.yml"
2550
+
2551
+ jobs:
2552
+ lint-and-test:
2553
+ name: Backend Lint, Build, and Test
2554
+ runs-on: ubuntu-latest
2555
+ strategy:
2556
+ matrix:
2557
+ mongodb-version: ["6.0"]
2558
+ steps:
2559
+ - uses: actions/checkout@v6
2560
+
2561
+ - name: Setup Bun
2562
+ uses: oven-sh/setup-bun@v2
2563
+ with:
2564
+ bun-version: latest
2565
+
2566
+ - name: Cache Bun dependencies
2567
+ id: cache
2568
+ uses: actions/cache@v5
2569
+ with:
2570
+ path: |
2571
+ ~/.bun/install/cache
2572
+ node_modules
2573
+ key: bun-\${{ runner.os }}-\${{ github.ref }}-\${{ hashFiles('bun.lock', 'package.json') }}
2574
+ restore-keys: |
2575
+ bun-\${{ runner.os }}-\${{ github.ref }}-
2576
+ bun-\${{ runner.os }}-
2577
+
2578
+ - name: Start MongoDB
2579
+ uses: supercharge/mongodb-github-action@1.12.1
2580
+ with:
2581
+ mongodb-version: \${{ matrix.mongodb-version }}
2582
+
2583
+ - name: Install dependencies
2584
+ run: bun install
2585
+ working-directory: backend
2586
+
2587
+ - name: Lint
2588
+ run: bun run lint
2589
+ working-directory: backend
2590
+
2591
+ - name: Build
2592
+ run: bun run compile
2593
+ working-directory: backend
2594
+
2595
+ - name: Test
2596
+ run: bun run test
2597
+ working-directory: backend
2598
+ env:
2599
+ CI: true
2600
+ `;
2601
+ };
2602
+ const generateFrontendCiWorkflow = (_args) => {
2603
+ return `name: Frontend CI
2604
+
2605
+ on:
2606
+ push:
2607
+ paths:
2608
+ - "frontend/**"
2609
+ - ".github/workflows/frontend-ci.yml"
2610
+
2611
+ jobs:
2612
+ lint-and-test:
2613
+ name: Frontend Lint, Build, and Test
2614
+ runs-on: ubuntu-latest
2615
+ steps:
2616
+ - uses: actions/checkout@v6
2617
+
2618
+ - name: Setup Bun
2619
+ uses: oven-sh/setup-bun@v2
2620
+ with:
2621
+ bun-version: latest
2622
+
2623
+ - name: Cache Bun dependencies
2624
+ id: cache
2625
+ uses: actions/cache@v5
2626
+ with:
2627
+ path: |
2628
+ ~/.bun/install/cache
2629
+ node_modules
2630
+ key: bun-\${{ runner.os }}-\${{ github.ref }}-\${{ hashFiles('bun.lock', 'package.json') }}
2631
+ restore-keys: |
2632
+ bun-\${{ runner.os }}-\${{ github.ref }}-
2633
+ bun-\${{ runner.os }}-
2634
+
2635
+ - name: Install dependencies
2636
+ run: bun install
2637
+ working-directory: frontend
2638
+
2639
+ - name: Lint
2640
+ run: bun run lint
2641
+ working-directory: frontend
2642
+
2643
+ - name: TypeScript compile
2644
+ run: bun run compile
2645
+ working-directory: frontend
2646
+
2647
+ - name: Test
2648
+ run: bun run test
2649
+ working-directory: frontend
2650
+ env:
2651
+ CI: true
2652
+ `;
2653
+ };
2654
+ export const getFenceLanguage = (filePath) => {
2655
+ if (filePath.endsWith(".json") || filePath.endsWith(".jsonc")) {
2656
+ return "json";
2657
+ }
2658
+ if (filePath.endsWith(".js")) {
2659
+ return "javascript";
2660
+ }
2661
+ if (filePath.endsWith(".yml") || filePath.endsWith(".yaml")) {
2662
+ return "yaml";
2663
+ }
2664
+ if (filePath.endsWith(".md")) {
2665
+ return "markdown";
2666
+ }
2667
+ return "typescript";
2668
+ };
2669
+ export const generateAllFiles = (args) => {
2670
+ const frontendDir = `frontend`;
2671
+ const backendDir = `backend`;
2672
+ return [
2673
+ // Root files
2674
+ { content: generateRootGitignore(), path: ".gitignore" },
2675
+ { content: generateRootReadme(args), path: "README.md" },
2676
+ { content: generateRootDockerignore(), path: ".dockerignore" },
2677
+ { content: generateRootDockerfile(), path: "Dockerfile" },
2678
+ { content: generateCursorRules(args), path: ".cursorrules" },
2679
+ { content: generateMcpSettings(args), path: ".cursor/mcp.json" },
2680
+ { content: generateClaudeMd(args), path: "CLAUDE.md" },
2681
+ // Backend files
2682
+ { content: generateBackendPackageJson(args), path: `${backendDir}/package.json` },
2683
+ { content: generateBackendTsConfig(), path: `${backendDir}/tsconfig.json` },
2684
+ { content: generateBackendBiomeJsonc(), path: `${backendDir}/biome.jsonc` },
2685
+ { content: generateBackendIndex(), path: `${backendDir}/src/index.ts` },
2686
+ { content: generateBackendAccess(), path: `${backendDir}/src/access.ts` },
2687
+ { content: generateBackendServer(args), path: `${backendDir}/src/server.ts` },
2688
+ { content: generateBackendDatabase(args), path: `${backendDir}/src/utils/database.ts` },
2689
+ { content: generateBackendSeed(args), path: `${backendDir}/src/scripts/seed.ts` },
2690
+ {
2691
+ content: generateBackendBetterAuthConfig(args),
2692
+ path: `${backendDir}/src/utils/betterAuthConfig.ts`,
2693
+ },
2694
+ { content: generateBackendEnv(args), path: `${backendDir}/.env` },
2695
+ { content: generateBackendEnvExample(args), path: `${backendDir}/.env.example` },
2696
+ { content: generateBackendModelPlugins(), path: `${backendDir}/src/models/modelPlugins.ts` },
2697
+ { content: generateBackendUserModel(), path: `${backendDir}/src/models/user.ts` },
2698
+ {
2699
+ content: generateBackendOrganizationSettings(),
2700
+ path: `${backendDir}/src/models/organizationSettings.ts`,
2701
+ },
2702
+ {
2703
+ content: generateBackendAppConfiguration(args),
2704
+ path: `${backendDir}/src/models/appConfiguration.ts`,
2705
+ },
2706
+ { content: generateBackendModelsIndex(), path: `${backendDir}/src/models/index.ts` },
2707
+ { content: generateBackendUserRoutes(), path: `${backendDir}/src/api/users.ts` },
2708
+ { content: generateBackendTypes(), path: `${backendDir}/src/types/index.ts` },
2709
+ { content: generateBackendTypesModels(), path: `${backendDir}/src/types/models/index.ts` },
2710
+ { content: generateBackendUserTypes(), path: `${backendDir}/src/types/models/userTypes.ts` },
2711
+ {
2712
+ content: generateBackendOrganizationSettingsTypes(),
2713
+ path: `${backendDir}/src/types/models/organizationSettingsTypes.ts`,
2714
+ },
2715
+ // Frontend files
2716
+ { content: generateFrontendPackageJson(args), path: `${frontendDir}/package.json` },
2717
+ { content: generateFrontendAppJson(args), path: `${frontendDir}/app.json` },
2718
+ { content: generateFrontendTsConfig(), path: `${frontendDir}/tsconfig.json` },
2719
+ { content: generateFrontendTsConfigCodegen(), path: `${frontendDir}/tsconfig.codegen.json` },
2720
+ { content: generateFrontendMetroConfig(), path: `${frontendDir}/metro.config.js` },
2721
+ { content: generateFrontendBiomeJsonc(), path: `${frontendDir}/biome.jsonc` },
2722
+ { content: generateFrontendOpenApiConfig(), path: `${frontendDir}/openapi-config.ts` },
2723
+ { content: generateFrontendGenerateSdk(), path: `${frontendDir}/scripts/generate-sdk.ts` },
2724
+ { content: generateFrontendRootLayout(args), path: `${frontendDir}/app/_layout.tsx` },
2725
+ { content: generateFrontendLogin(), path: `${frontendDir}/app/login.tsx` },
2726
+ { content: generateFrontendSignup(), path: `${frontendDir}/app/signup.tsx` },
2727
+ { content: generateFrontendNotFound(), path: `${frontendDir}/app/+not-found.tsx` },
2728
+ { content: generateFrontendTabsLayout(), path: `${frontendDir}/app/(tabs)/_layout.tsx` },
2729
+ { content: generateFrontendTabsIndex(args), path: `${frontendDir}/app/(tabs)/index.tsx` },
2730
+ { content: generateFrontendTabsProfile(), path: `${frontendDir}/app/(tabs)/profile.tsx` },
2731
+ { content: generateFrontendAdminLayout(), path: `${frontendDir}/app/(tabs)/admin/_layout.tsx` },
2732
+ { content: generateFrontendAdminIndex(), path: `${frontendDir}/app/(tabs)/admin/index.tsx` },
2733
+ {
2734
+ content: generateFrontendAdminConfiguration(),
2735
+ path: `${frontendDir}/app/(tabs)/admin/configuration.tsx`,
2736
+ },
2737
+ { content: generateFrontendStoreIndex(), path: `${frontendDir}/store/index.ts` },
2738
+ { content: generateFrontendStoreAppState(), path: `${frontendDir}/store/appState.ts` },
2739
+ { content: generateFrontendStoreErrors(), path: `${frontendDir}/store/errors.ts` },
2740
+ { content: generateFrontendStoreSdk(), path: `${frontendDir}/store/sdk.ts` },
2741
+ { content: generateFrontendBetterAuthApi(), path: `${frontendDir}/store/betterAuthApi.ts` },
2742
+ { content: generateFrontendStoreOpenApiSdk(), path: `${frontendDir}/store/openApiSdk.ts` },
2743
+ { content: generateFrontendBetterAuthLib(args), path: `${frontendDir}/lib/betterAuth.ts` },
2744
+ { content: generateFrontendSyncDb(args), path: `${frontendDir}/store/syncdb.ts` },
2745
+ { content: generateFrontendTheme(), path: `${frontendDir}/constants/theme.ts` },
2746
+ { content: generateFrontendUtilsIndex(), path: `${frontendDir}/utils/index.ts` },
2747
+ { content: generateFrontendEnv(), path: `${frontendDir}/.env` },
2748
+ { content: generateFrontendEnvExample(), path: `${frontendDir}/.env.example` },
2749
+ // GitHub Actions workflows
2750
+ { content: generateBackendCiWorkflow(args), path: ".github/workflows/backend-ci.yml" },
2751
+ { content: generateFrontendCiWorkflow(args), path: ".github/workflows/frontend-ci.yml" },
2752
+ ];
2753
+ };
2754
+ //# sourceMappingURL=generate.js.map