@terreno/admin-backend 0.3.2 → 0.5.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,208 @@
1
+ # Terreno
2
+
3
+ A monorepo containing shared packages for building full-stack applications with React Native and Express/Mongoose.
4
+
5
+ ## Packages
6
+
7
+ - **api/** - REST API framework built on Express/Mongoose (`@terreno/api`)
8
+ - **ui/** - React Native UI component library (`@terreno/ui`)
9
+ - **rtk/** - Redux Toolkit Query utilities for API backends (`@terreno/rtk`)
10
+ - **admin-backend/** - Admin panel backend plugin for @terreno/api (`@terreno/admin-backend`)
11
+ - **admin-frontend/** - Admin panel frontend screens for @terreno/api backends (`@terreno/admin-frontend`)
12
+ - **demo/** - Demo app for showcasing and testing UI components
13
+ - **example-frontend/** - Example Expo app demonstrating full stack usage
14
+ - **example-backend/** - Example Express backend using @terreno/api
15
+
16
+ ## Development
17
+
18
+ Uses [Bun](https://bun.sh/) as the package manager.
19
+
20
+ ```bash
21
+ bun install # Install dependencies
22
+ bun run compile # Compile all packages
23
+ bun run lint # Lint all packages
24
+ bun run lint:fix # Fix lint issues
25
+ bun run test # Run tests in api and ui
26
+ ```
27
+
28
+ ### Package-specific commands
29
+
30
+ ```bash
31
+ bun run api:test # Test API package
32
+ bun run ui:test # Test UI package
33
+ bun run demo:start # Start demo app
34
+ bun run frontend:web # Start frontend example
35
+ bun run backend:dev # Start backend example
36
+ bun run admin-backend:compile # Compile admin backend
37
+ bun run admin-frontend:compile # Compile admin frontend
38
+ ```
39
+
40
+ ## How the Packages Work Together
41
+
42
+ The three core packages form a complete full-stack framework:
43
+
44
+ ```
45
+ BACKEND
46
+ @terreno/api
47
+ - Mongoose models with modelRouter -> CRUD endpoints
48
+ - Built-in auth (JWT + Passport)
49
+ - Automatic OpenAPI spec generation
50
+ |
51
+ /openapi.json
52
+ |
53
+ RTK Query SDK Codegen
54
+ |
55
+ FRONTEND
56
+ @terreno/rtk
57
+ - Generated hooks from OpenAPI spec
58
+ - Auth slice with JWT token management
59
+ - Automatic token refresh
60
+ +
61
+ @terreno/ui
62
+ - React Native components (Box, Button, TextField, etc.)
63
+ - TerrenoProvider for theming
64
+ ```
65
+
66
+ ### Integration Flow
67
+
68
+ 1. **Backend (api)**: Define Mongoose models, use `modelRouter` to create CRUD endpoints with permissions
69
+ 2. **OpenAPI Generation**: `setupServer` automatically generates `/openapi.json`
70
+ 3. **SDK Codegen**: Frontend runs `bun run sdk` to generate RTK Query hooks from OpenAPI spec
71
+ 4. **Frontend (rtk + ui)**: Use generated hooks with UI components for type-safe API calls
72
+
73
+ ## Example Apps (Keep These Updated!)
74
+
75
+ The `example-frontend/` and `example-backend/` directories serve as both documentation and integration tests. When adding features to api, ui, or rtk:
76
+
77
+ 1. **Add examples** demonstrating new features
78
+ 2. **Update SDK** after backend changes: `cd example-frontend && bun run sdk`
79
+ 3. **Verify integration** by running both examples together
80
+
81
+ ### Running the Full Stack
82
+
83
+ ```bash
84
+ # Terminal 1: Start backend
85
+ bun run backend:dev
86
+
87
+ # Terminal 2: Start frontend
88
+ bun run frontend:web
89
+ ```
90
+
91
+ ## Code Style
92
+
93
+ ### TypeScript/JavaScript
94
+ - Use ES module syntax and TypeScript for all code
95
+ - Prefer interfaces over types; avoid enums, use maps
96
+ - Prefer const arrow functions over `function` keyword
97
+ - Use descriptive variable names with auxiliary verbs (e.g., `isLoading`)
98
+ - Use camelCase directories (e.g., `components/authWizard`)
99
+ - Favor named exports
100
+ - Use the RORO pattern (Receive an Object, Return an Object)
101
+
102
+ ### Dates and Time
103
+ - Always use Luxon instead of Date or dayjs
104
+
105
+ ### Error Handling
106
+ - Check error conditions at start of functions and return early
107
+ - Limit nested if statements
108
+ - Use multiline syntax with curly braces for all conditionals
109
+
110
+ ### Testing
111
+ - Use bun test with expect for testing
112
+
113
+ ### Logging
114
+ - Frontend: Use `console.info`, `console.debug`, `console.warn`, or `console.error` for permanent logs
115
+ - Backend: Use `logger.info/warn/error/debug` for permanent logs
116
+ - Use `console.log` only for debugging (to be removed)
117
+
118
+ ### Development Practices
119
+ - Don't apologize for errors: fix them
120
+ - Prioritize modularity, DRY, performance, and security
121
+ - Focus on readability over performance
122
+ - Write complete, functional code without TODOs when possible
123
+ - Comments should describe purpose, not effect
124
+
125
+ ## Package Reference
126
+
127
+ ### @terreno/api
128
+
129
+ REST API framework providing:
130
+
131
+ - **modelRouter**: Auto-generates CRUD endpoints for Mongoose models
132
+ - **Permissions**: `IsAuthenticated`, `IsOwner`, `IsAdmin`, `IsAuthenticatedOrReadOnly`
133
+ - **Query Filters**: `OwnerQueryFilter` for filtering list queries by owner
134
+ - **setupServer**: Express server setup with auth, OpenAPI, and middleware
135
+ - **APIError**: Standardized error handling
136
+ - **logger**: Winston-based logging
137
+
138
+ Key imports:
139
+ ```typescript
140
+ import {
141
+ modelRouter,
142
+ setupServer,
143
+ Permissions,
144
+ OwnerQueryFilter,
145
+ APIError,
146
+ logger,
147
+ asyncHandler,
148
+ authenticateMiddleware,
149
+ } from "@terreno/api";
150
+ ```
151
+
152
+ ### @terreno/ui
153
+
154
+ React Native component library with 88+ components:
155
+
156
+ - **Layout**: Box, Page, SplitPage, Card
157
+ - **Forms**: TextField, SelectField, DateTimeField, CheckBox
158
+ - **Display**: Text, Heading, Badge, DataTable
159
+ - **Actions**: Button, IconButton, Link
160
+ - **Feedback**: Spinner, Modal, Toast
161
+ - **Theming**: TerrenoProvider, useTheme
162
+
163
+ Key imports:
164
+ ```typescript
165
+ import {
166
+ Box,
167
+ Button,
168
+ Card,
169
+ Page,
170
+ Text,
171
+ TextField,
172
+ TerrenoProvider,
173
+ } from "@terreno/ui";
174
+ ```
175
+
176
+ ### @terreno/rtk
177
+
178
+ Redux Toolkit Query integration:
179
+
180
+ - **generateAuthSlice**: Creates auth reducer and middleware with JWT handling
181
+ - **emptyApi**: Base RTK Query API for code generation
182
+ - **Platform utilities**: Secure token storage (expo-secure-store for native, AsyncStorage for web)
183
+
184
+ Key imports:
185
+ ```typescript
186
+ import {generateAuthSlice} from "@terreno/rtk";
187
+ ```
188
+
189
+ ## CI/CD Workflows
190
+
191
+ ### Required Secret Validation
192
+
193
+ GitHub Actions workflows that use secrets or environment variables must validate all required variables are set before using them. Add a validation step early in the job that fails fast with a clear error message listing any missing variables.
194
+
195
+ ```yaml
196
+ - name: Validate required secrets
197
+ run: |
198
+ missing=()
199
+ if [ -z "$VAR_NAME" ]; then missing+=("VAR_NAME"); fi
200
+ if [ ${#missing[@]} -ne 0 ]; then
201
+ echo "::error::Missing required secrets: ${missing[*]}"
202
+ exit 1
203
+ fi
204
+ ```
205
+
206
+ ## Dependency Management
207
+
208
+ Uses [Bun Catalogs](https://bun.sh/docs/install/catalogs) - shared versions defined in root `package.json` under `catalog`. Reference with `catalog:` in workspace packages.
@@ -0,0 +1,342 @@
1
+ ---
2
+ description: Terreno monorepo root guidelines
3
+ globs: **/*
4
+ ---
5
+
6
+ # Terreno
7
+
8
+ A monorepo containing shared packages for building full-stack applications with React Native and Express/Mongoose.
9
+
10
+ ## Packages
11
+
12
+ - **api/** - REST API framework built on Express/Mongoose (`@terreno/api`)
13
+ - **ui/** - React Native UI component library (`@terreno/ui`)
14
+ - **rtk/** - Redux Toolkit Query utilities for API backends (`@terreno/rtk`)
15
+ - **admin-backend/** - Admin panel backend plugin for @terreno/api (`@terreno/admin-backend`)
16
+ - **admin-frontend/** - Admin panel frontend screens for @terreno/api backends (`@terreno/admin-frontend`)
17
+ - **mcp-server/** - MCP server for AI assistant integration (`@terreno/mcp-server`)
18
+ - **demo/** - Demo app for showcasing and testing UI components
19
+ - **example-frontend/** - Example Expo app demonstrating full stack usage
20
+ - **example-backend/** - Example Express backend using @terreno/api
21
+
22
+ ## Development
23
+
24
+ Uses [Bun](https://bun.sh/) as the package manager.
25
+
26
+ ```bash
27
+ bun install # Install dependencies
28
+ bun run compile # Compile all packages
29
+ bun run lint # Lint all packages
30
+ bun run lint:fix # Fix lint issues
31
+ bun run test # Run tests in api and ui
32
+ ```
33
+
34
+ ### Package-specific commands
35
+
36
+ ```bash
37
+ bun run api:test # Test API package
38
+ bun run ui:test # Test UI package
39
+ bun run demo:start # Start demo app
40
+ bun run frontend:web # Start frontend example
41
+ bun run backend:dev # Start backend example
42
+ bun run mcp:build # Build MCP server
43
+ bun run mcp:start # Start MCP server
44
+ bun run admin-backend:compile # Compile admin backend
45
+ bun run admin-frontend:compile # Compile admin frontend
46
+ ```
47
+
48
+ ## How the Packages Work Together
49
+
50
+ The three core packages form a complete full-stack framework:
51
+
52
+ ```
53
+ BACKEND
54
+ @terreno/api
55
+ - Mongoose models with modelRouter -> CRUD endpoints
56
+ - Built-in auth (JWT + Passport)
57
+ - Automatic OpenAPI spec generation
58
+ |
59
+ /openapi.json
60
+ |
61
+ RTK Query SDK Codegen
62
+ |
63
+ FRONTEND
64
+ @terreno/rtk
65
+ - Generated hooks from OpenAPI spec
66
+ - Auth slice with JWT token management
67
+ - Automatic token refresh
68
+ +
69
+ @terreno/ui
70
+ - React Native components (Box, Button, TextField, etc.)
71
+ - TerrenoProvider for theming
72
+ ```
73
+
74
+ ### Integration Flow
75
+
76
+ 1. **Backend (api)**: Define Mongoose models, use `modelRouter` to create CRUD endpoints with permissions
77
+ 2. **OpenAPI Generation**: `setupServer` automatically generates `/openapi.json`
78
+ 3. **SDK Codegen**: Frontend runs `bun run sdk` to generate RTK Query hooks from OpenAPI spec
79
+ 4. **Frontend (rtk + ui)**: Use generated hooks with UI components for type-safe API calls
80
+
81
+ ## Example Apps (Keep These Updated!)
82
+
83
+ The `example-frontend/` and `example-backend/` directories serve as both documentation and integration tests. When adding features to api, ui, or rtk:
84
+
85
+ 1. **Add examples** demonstrating new features
86
+ 2. **Update SDK** after backend changes: `cd example-frontend && bun run sdk`
87
+ 3. **Verify integration** by running both examples together
88
+
89
+ ### Running the Full Stack
90
+
91
+ ```bash
92
+ # Terminal 1: Start backend
93
+ bun run backend:dev
94
+
95
+ # Terminal 2: Start frontend
96
+ bun run frontend:web
97
+ ```
98
+
99
+ ## Code Style
100
+
101
+ ### TypeScript/JavaScript
102
+ - Use ES module syntax and TypeScript for all code
103
+ - Prefer interfaces over types; avoid enums, use maps
104
+ - Prefer const arrow functions over `function` keyword
105
+ - Use descriptive variable names with auxiliary verbs (e.g., `isLoading`)
106
+ - Use camelCase directories (e.g., `components/authWizard`)
107
+ - Favor named exports
108
+ - Use the RORO pattern (Receive an Object, Return an Object)
109
+
110
+ ### Dates and Time
111
+ - Always use Luxon instead of Date or dayjs
112
+
113
+ ### Error Handling
114
+ - Check error conditions at start of functions and return early
115
+ - Limit nested if statements
116
+ - Use multiline syntax with curly braces for all conditionals
117
+
118
+ ### Testing
119
+ - Use bun test with expect for testing
120
+
121
+ ### Logging
122
+ - Frontend: Use `console.info`, `console.debug`, `console.warn`, or `console.error` for permanent logs
123
+ - Backend: Use `logger.info/warn/error/debug` for permanent logs
124
+ - Use `console.log` only for debugging (to be removed)
125
+
126
+ ### Development Practices
127
+ - Don't apologize for errors: fix them
128
+ - Prioritize modularity, DRY, performance, and security
129
+ - Focus on readability over performance
130
+ - Write complete, functional code without TODOs when possible
131
+ - Comments should describe purpose, not effect
132
+
133
+ ## Package Reference
134
+
135
+ ### @terreno/api
136
+
137
+ REST API framework providing:
138
+
139
+ - **modelRouter**: Auto-generates CRUD endpoints for Mongoose models
140
+ - **Permissions**: `IsAuthenticated`, `IsOwner`, `IsAdmin`, `IsAuthenticatedOrReadOnly`
141
+ - **Query Filters**: `OwnerQueryFilter` for filtering list queries by owner
142
+ - **setupServer**: Express server setup with auth, OpenAPI, and middleware
143
+ - **APIError**: Standardized error handling
144
+ - **logger**: Winston-based logging
145
+
146
+ Key imports:
147
+ ```typescript
148
+ import {
149
+ modelRouter,
150
+ setupServer,
151
+ Permissions,
152
+ OwnerQueryFilter,
153
+ APIError,
154
+ logger,
155
+ asyncHandler,
156
+ authenticateMiddleware,
157
+ } from "@terreno/api";
158
+ ```
159
+
160
+ #### modelRouter Usage
161
+
162
+ ```typescript
163
+ import {modelRouter, modelRouterOptions, Permissions} from "@terreno/api";
164
+
165
+ const router = modelRouter(YourModel, {
166
+ permissions: {
167
+ list: [Permissions.IsAuthenticated],
168
+ create: [Permissions.IsAuthenticated],
169
+ read: [Permissions.IsOwner],
170
+ update: [Permissions.IsOwner],
171
+ delete: [], // Disabled
172
+ },
173
+ sort: "-created",
174
+ queryFields: ["_id", "type", "name"],
175
+ });
176
+ ```
177
+
178
+ #### Custom Routes
179
+
180
+ For non-CRUD endpoints, use the OpenAPI builder:
181
+
182
+ ```typescript
183
+ import {asyncHandler, authenticateMiddleware, createOpenApiBuilder} from "@terreno/api";
184
+
185
+ router.get("/yourRoute/:id", [
186
+ authenticateMiddleware(),
187
+ createOpenApiBuilder(options)
188
+ .withTags(["yourTag"])
189
+ .withSummary("Brief summary")
190
+ .withPathParameter("id", {type: "string"})
191
+ .withResponse(200, {data: {type: "object"}})
192
+ .build(),
193
+ ], asyncHandler(async (req, res) => {
194
+ return res.json({data: result});
195
+ }));
196
+ ```
197
+
198
+ #### API Conventions
199
+
200
+ - Throw `APIError` with appropriate status codes: `throw new APIError({status: 400, title: "Message"})`
201
+ - Do not use `Model.findOne` - use `Model.findExactlyOne` or `Model.findOneOrThrow`
202
+ - Define statics/methods by direct assignment: `schema.methods = {bar() {}}`
203
+ - All model types live in `src/modelInterfaces.ts`
204
+ - In routes: `req.user` is `UserDocument | undefined`
205
+ - In @terreno/api callbacks: cast with `const user = u as unknown as UserDocument`
206
+
207
+ ### @terreno/ui
208
+
209
+ React Native component library with 88+ components:
210
+
211
+ - **Layout**: Box, Page, SplitPage, Card
212
+ - **Forms**: TextField, SelectField, DateTimeField, CheckBox
213
+ - **Display**: Text, Heading, Badge, DataTable
214
+ - **Actions**: Button, IconButton, Link
215
+ - **Feedback**: Spinner, Modal, Toast
216
+ - **Theming**: TerrenoProvider, useTheme
217
+
218
+ Key imports:
219
+ ```typescript
220
+ import {
221
+ Box,
222
+ Button,
223
+ Card,
224
+ Page,
225
+ Text,
226
+ TextField,
227
+ TerrenoProvider,
228
+ } from "@terreno/ui";
229
+ ```
230
+
231
+ #### UI Component Examples
232
+
233
+ Layout with Box:
234
+ ```typescript
235
+ <Box direction="row" padding={4} gap={2} alignItems="center">
236
+ <Text>Content</Text>
237
+ <Button text="Action" />
238
+ </Box>
239
+ ```
240
+
241
+ Buttons:
242
+ ```typescript
243
+ <Button
244
+ text="Submit"
245
+ variant="primary" // 'primary' | 'secondary' | 'outline' | 'ghost'
246
+ onClick={handleSubmit}
247
+ loading={isLoading}
248
+ iconName="check"
249
+ />
250
+ ```
251
+
252
+ Forms:
253
+ ```typescript
254
+ <TextField
255
+ label="Email"
256
+ value={email}
257
+ onChangeText={setEmail}
258
+ error={emailError}
259
+ helperText="Enter a valid email"
260
+ />
261
+ ```
262
+
263
+ Modals:
264
+ ```typescript
265
+ <Modal
266
+ title="Confirm Action"
267
+ visible={isVisible}
268
+ primaryButtonText="Confirm"
269
+ secondaryButtonText="Cancel"
270
+ onDismiss={() => setIsVisible(false)}
271
+ onPrimaryAction={handleConfirm}
272
+ >
273
+ <Text>Are you sure?</Text>
274
+ </Modal>
275
+ ```
276
+
277
+ #### UI Common Pitfalls
278
+
279
+ - Don't use inline styles when theme values are available
280
+ - Don't use raw `View`/`Text` when `Box`/@terreno/ui `Text` are available
281
+ - Don't forget loading and error states
282
+ - Don't use `style` prop when equivalent props exist (`padding`, `margin`)
283
+ - Never modify `openApiSdk.ts` manually
284
+
285
+ ### @terreno/rtk
286
+
287
+ Redux Toolkit Query integration:
288
+
289
+ - **generateAuthSlice**: Creates auth reducer and middleware with JWT handling
290
+ - **emptyApi**: Base RTK Query API for code generation
291
+ - **Platform utilities**: Secure token storage (expo-secure-store for native, AsyncStorage for web)
292
+
293
+ Key imports:
294
+ ```typescript
295
+ import {generateAuthSlice} from "@terreno/rtk";
296
+ ```
297
+
298
+ Always use generated SDK hooks - never use `axios` or `request` directly:
299
+
300
+ ```typescript
301
+ // Correct
302
+ import {useGetYourRouteQuery} from "@/store/openApiSdk";
303
+ const {data, isLoading, error} = useGetYourRouteQuery({id: "value"});
304
+
305
+ // Wrong - don't use axios directly
306
+ // const result = await axios.get("/api/yourRoute/value");
307
+ ```
308
+
309
+ ## React Best Practices (Frontend Packages)
310
+
311
+ - Use functional components with `React.FC` type
312
+ - Import hooks directly: `import {useEffect, useMemo} from 'react'`
313
+ - Always provide return types for functions
314
+ - Add explanatory comment above each `useEffect`
315
+ - Wrap callbacks in `useCallback`
316
+ - Prefer const arrow functions
317
+ - Use inline styles over `StyleSheet.create`
318
+ - Use Luxon for date operations
319
+ - Place static content and interfaces at beginning of file
320
+ - Minimize `use client`, `useEffect`, and `setState`
321
+ - Always support React-Native Web
322
+
323
+ ## CI/CD Workflows
324
+
325
+ ### Required Secret Validation
326
+
327
+ GitHub Actions workflows that use secrets or environment variables must validate all required variables are set before using them. Add a validation step early in the job that fails fast with a clear error message listing any missing variables.
328
+
329
+ ```yaml
330
+ - name: Validate required secrets
331
+ run: |
332
+ missing=()
333
+ if [ -z "$VAR_NAME" ]; then missing+=("VAR_NAME"); fi
334
+ if [ ${#missing[@]} -ne 0 ]; then
335
+ echo "::error::Missing required secrets: ${missing[*]}"
336
+ exit 1
337
+ fi
338
+ ```
339
+
340
+ ## Dependency Management
341
+
342
+ Uses [Bun Catalogs](https://bun.sh/docs/install/catalogs) - shared versions defined in root `package.json` under `catalog`. Reference with `catalog:` in workspace packages.