@terreno/admin-backend 58.0.0-beta.1 → 58.0.0-beta.2

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.
package/CHANGELOG.md CHANGED
@@ -20,6 +20,52 @@ Upgrade notes for consumer action live in [`mcp-server/src/docs/upgrades/`](mcp-
20
20
 
21
21
  Unreleased changes live in [`changelog/unreleased/`](changelog/unreleased/). Add one Markdown file per feature (see that directory's README) instead of editing this section.
22
22
 
23
+ ## [58.0.0-beta.2] - 2026-11-03
24
+
25
+ Upgrade note: [`mcp-server/src/docs/upgrades/58.0.0-beta.2.md`](mcp-server/src/docs/upgrades/58.0.0-beta.2.md).
26
+
27
+ ### Breaking
28
+
29
+ - Terreno 58 targets Expo SDK 58 (`~58.0.14`), React Native `0.88.0`, and React `19.3.0`. `@terreno/ui` peers `react-native` `0.88.0`. Native catalog moves with the SDK: `react-native-gesture-handler` `~3.3.0`, `react-native-reanimated` `4.7.1` + `react-native-worklets` `0.13.0`, `react-native-screens` `~4.30.0`, `react-native-webview` `14.0.1`, `@sentry/react-native` `~8.28.0`, `@shopify/flash-list` `2.3.2`, `@shopify/react-native-skia` `2.14.0`. Rebuild dev clients and store binaries.
30
+ - Expo Router 58: set `export const unstable_settings = {initialRouteName}` on the layout instead of passing `initialRouteName` to `<Slot>` / navigators. `SidebarNavigation` ignores the prop.
31
+ - Expo Router 58 static rendering: a custom `app/+html.tsx` must render `headNodes` and `bodyNodes` from `useServerDocumentContext()` (`expo-router/html`), or exported pages ship without their JavaScript. `example-frontend` is updated.
32
+ - React Native 0.88 generated types: type refs as `ViewInstance`, `TextInstance`, `ScrollViewInstance`, and `TextInputInstance` (`Box.scrollRef`, `TextField.inputRef`, `Text` `ref`).
33
+ - `create-terreno-app` scaffolds Expo `~58.0.14`, React Native `0.88.0`, and React `19.3.0`.
34
+ - The Terreno 58 native module baseline lands in `example-frontend` and `demo`: `@stripe/stripe-react-native` 0.81.0, `react-native-purchases` and `react-native-purchases-ui` 10.12.2, `expo-device`, `expo-crypto`, `expo-local-authentication`, `expo-system-ui`, and `expo-build-properties` (Android Kotlin 2.2.21 and `compileSdkVersion` 37 pins). Rebuild every dev client and store binary. `react-native-otp-verify` is left out because it does not support the New Architecture. The demo has a hidden **Native Modules** page that shows each module's version and whether the running binary links it. See the 58.0.0 upgrade note.
35
+ - `TerrenoApp` turns HTTP rate limiting on by default. Omitting `rateLimit` now mounts the limiter with the memory store (auth 20 / 15 min, api 600 / 15 min). Pass `rateLimit: false` to turn it off. On Cloud Run pass `rateLimit: {trustProxy: 1}` so unauthenticated traffic keys by client IP. See the 58.0.0 upgrade note.
36
+ - `@terreno/admin-frontend` no longer takes an RTK `api`. The `api` prop is removed from every admin component (`AdminProvider`, `AdminShellLayout`, `AdminHome`, `AdminModelList`, `AdminModelTable`, `AdminModelForm`, `AdminScreenRouter`, `ConfigurationScreen`, `DocumentStorageBrowser`, `ConsentHistory`, comms, jobs, org, consent, and announcement screens, and widget props), and admin hooks drop their `api` argument (`useAdminConfig(apiBase)`, `useAdminScripts(apiBase)`, `useAdminRoles(apiBase)`, `useConfigurationApi({basePath})`, `useDocumentStorageApi(basePath)`, `useConsentHistory(baseUrl)`, `useOrganizationsApi(basePath)`, `useCommsDashboardApi()`, `useJobsDashboardApi()`, and the `useAiObservability*Api()` hooks).
37
+ - `useAdminApi(api, routePath, modelName)` is removed. Use `useAdminModelApi(routePath, modelName)`, which keeps the same hook names and calls the same `/admin/{routePath}` URLs through the admin fetch client. `AdminApi`, `EndpointBuilder`, and admin `injectEndpoints` are gone; `@reduxjs/toolkit` and `react-redux` are no longer peers of admin-frontend.
38
+ - `AdminProvider` is now the required auth binding for every admin request, including ObjectId and API-only model CRUD. Cookie SPAs pass `credentials="same-origin"`; embedded apps pass `apiOrigin` and `getAuthHeaders`. Product screens that reuse admin components wrap them in `AdminProvider`. See the 58.0.0 upgrade guide.
39
+ - Removed the legacy RTK realtime path. Use `sync` on `modelRouter` with `@terreno/syncdb` for live collection updates. `RealtimeApp`, `SyncApp`, socket auth, `sync:delta`, and admin `admin:model.changed` events are unchanged. See the 58.0.0 upgrade note.
40
+ - `@terreno/api`: `modelRouter` no longer accepts `realtime` (now a TypeScript error), and the change stream no longer emits the `sync` websocket event. Removed `RealtimeConfig`, `RealtimeEvent`, `DocumentSubscription`, `QuerySubscription`, `registerRealtime`, `getRealtimeRegistry`, `findRegistryEntryByCollection`, `findRegistryEntryByRoutePath`, `updateRealtimeRegistryOptions`, `clearRealtimeRegistry`, `RealtimeRegistryEntry`, the query-subscription store (`addQuerySubscription`, `removeQuerySubscription`, `removeAllSocketQueries`, `getQuerySubscriptionsForCollection`, `computeQueryId`, `clearQueryStore`), and `MAX_MODEL_SUBSCRIPTIONS` / `MAX_DOCUMENT_SUBSCRIPTIONS` / `MAX_QUERY_SUBSCRIPTIONS`. Sockets no longer handle `subscribe:model`, `subscribe:document`, or `subscribe:query`.
41
+ - `@terreno/rtk`: removed `realtimeList`, `realtimeDocument`, `setRealtimeSocket`, `getRealtimeSocket`, `useSyncConnection`, and the `RealtimeEvent` type. The rest of `@terreno/rtk` (including `useSocketConnection` and `useRealtimeDebug`) is removed in the same release; see `remove-rtk.md`.
42
+ - Removed `@terreno/rtk` and every Redux dependency (`@reduxjs/toolkit`, `react-redux`, `redux-persist`, `@rtk-query/codegen-openapi`). `@terreno/rtk` is not published for 58. `@terreno/syncdb` is the only frontend data, request, and session layer. Follow `docs/how-to/migrate-rtk-to-syncdb.md`, which maps every removed export to its replacement, and the 58.0.0 upgrade note.
43
+ - `@terreno/syncdb` adds `@terreno/syncdb/api` (`createApiClient`, `ApiError`), request hooks in `@terreno/syncdb/react` (`ApiClientProvider`, `useApiQuery`, `useLazyApiQuery`, `useApiMutation`, `useSocketEvent`), `@terreno/syncdb/config` (`baseUrl`, `baseWebsocketsUrl`, `appHeaders`), `@terreno/syncdb/auth` (`createBetterAuthClient`, `SessionProvider`, `useSession`, `jwtAuthAdapter`, `useJwtAuth`, token-expiry helpers), `@terreno/syncdb/flags` (`useFeatureFlags`, `useTerrenoFeatureFlags` on the sync socket), `@terreno/syncdb/app` (`useUpgradeCheck`, `hasPermission`, `canOpenAdminPage`, `installDevConsoleLogger`, `useMCPTools`), and `@terreno/syncdb/buildNumber`.
44
+ - `terreno-syncdb-codegen --api-out` generates typed hooks for every non-synced OpenAPI operation (same names as the RTK codegen), replacing `@rtk-query/codegen-openapi`. `bun run sdk` writes `store/apiSdk.ts`.
45
+ - `@terreno/ui` `ConsentNavigator`, `AnnouncementNavigator`, `useConsentForms`, `useSubmitConsent`, `useAnnouncements`, and `useAcknowledgeAnnouncement` take a request `client` instead of an RTK `api`.
46
+ - `GptHistory` (`gpt/histories`) is a synced collection and keeps its ObjectId `_id` (no migration). `McpServiceToken` (`mcp/service-tokens`, read-only) is a synced collection with String ids; run `mcpServiceTokenStringIdsMigration` (`@terreno/api`) before deploying 58 frontends.
47
+ - `create-terreno-app`, the `terreno_bootstrap` prompt, and the `terreno_generate_screen` tool scaffold apps without Redux or `@terreno/rtk`. The terreno-mcp-local `get_rtk_state` tool, the MCP resource `terreno://docs/rtk`, and `terreno state --slice rtk` are removed; use `get_syncdb_state` and `terreno state`.
48
+
49
+ ### Added
50
+
51
+ - `DataTable` columns size themselves when `width` is omitted. Each auto column starts at the wider of its header and its content (sampled from at most 50 rows, measured with a canvas on web and estimated on native), clamped to 80–360px, and auto columns grow to fill the table's container. Columns that set `width` keep it. `DataTableColumn.width` is now optional.
52
+ - `@terreno/syncdb` `createSyncDb({idFormats})` mints 24-hex ObjectIds for a collection set to `"objectId"`, so a model that keeps Mongoose's default ObjectId `_id` can sync without migrating its ids. `mutate()` throws on an explicit non-hex id for such a collection. `generateObjectId` and the `SyncIdFormat` type are exported.
53
+ - Sync `validation` nacks carry an optional `reason`: `invalid_id` when an ObjectId-keyed collection gets a non-hex id (rejected before the mutation is claimed), and `id_collision` when a create names an `_id` another document holds. A collision never touches the existing document and its message never names the holder. The ledger records the reason (`SyncMutation.nackReason`) so a redelivery replays it.
54
+ - `GET /sync/entities` leaves out non-hex ids for an ObjectId-keyed model instead of answering 400, so a rejected create queued for repair cannot fail the rest of the repair batch.
55
+
56
+ ### Changed
57
+
58
+ - The repository's agent rules now generate with rulesync 17 (up from 9). The root rule `.rulesync/rules/00-root.md` now generates `AGENTS.md`, which Devin and other AGENTS.md readers load, in place of `.devin/rules/00-root.md`. Never edit `AGENTS.md` by hand: edit the root rule and run `bun run rules`. The examples that existed only in the old hand-edited `AGENTS.md` (syncdb and RTK SDK usage) moved into the root rule, so `CLAUDE.md`, the Cursor root rule, and Copilot instructions get them too. Links in the root rule now resolve from the repository root. Generated Copilot hooks use the portable `command` field. Generated Copilot subagents no longer list `agent/runSubagent` as their only tool, so they get every default tool. Generated skills carry their `license`, `disable-model-invocation`, and Devin `triggers` frontmatter.
59
+ - `@terreno/syncdb/auth` `SessionProvider`: `logout()` no longer clears the session before the server answers. The session stays in the state until `authClient.signOut()` finishes (`signOutTimeoutMs`, default 10 seconds), and then it is cleared. Meanwhile the new `isSigningOut` state (`useSession().isSigningOut`) is true; `isLoading` is left alone, so a navigator gated on it keeps its screen. Before, a login screen that opened at once could find the still-live session and sign the user straight back in. A sign-out that fails or times out checks the session first. A session that is still live, or a cookie or native session the server cannot be asked about, stays signed in, and `error` is set to `SIGN_OUT_FAILED_MESSAGE` ("Couldn't sign out. Check your connection and try again."). A web bearer client, which drops its token before the request leaves, ends signed out. The global `auth/logout` action (a refused session) now ends signed out even when the sign-out request fails. With `apisToReset` (57.17.0), `logout()` purges the cache when the session clears, not when it is dispatched: a purge at dispatch refetched every mounted screen mid-sign-out, and a refetch that could not reach the server answered 401 and signed the user out even though the sign-out failed. A failed sign-out keeps both the session and the cache. The global `auth/logout` action still purges at once (only the first of several in flight) and again when the session clears. A sign-in for another user that lands while a sign-out is in flight is kept; a sign-out that started signed out asks `getSession` first, so a restore of the session it revoked is cleared. Show `selectBetterAuthIsSigningOut` on the sign-out control and `selectBetterAuthError` after a failed sign-out.
60
+
61
+ ### Removed
62
+
63
+ - `@terreno/ui` no longer exports the `Filter` and `FilterProps` aliases deprecated in 57.7.0. Import `DropdownPanel` and `DropdownPanelProps` instead. `FilterSelectMenu`, `FilterBoolean`, `FilterAccordion`, and `FilterChangesBadge` keep their names.
64
+
65
+ ### Fixed
66
+
67
+ - `@terreno/syncdb`: logging out while `syncDb.start()` is still running no longer loses local writes or logs errors. `start()` now resolves the web encryption key from `GET /sync/key` before it loads the store, so the flush in `stop()` never needs the network after the session has ended. A `stop()` or `signOut()` call now cancels a `start()` that is running or queued ahead of it, so the transport never connects without a session. A failed key fetch is now retried on the next save instead of failing every save for the rest of the session.
68
+
23
69
  ## [58.0.0-beta.1] - 2026-11-02
24
70
 
25
71
  Upgrade note: [`mcp-server/src/docs/upgrades/58.0.0-beta.1.md`](mcp-server/src/docs/upgrades/58.0.0-beta.1.md).
package/package.json CHANGED
@@ -5,8 +5,8 @@
5
5
  },
6
6
  "dependencies": {
7
7
  "@google-cloud/storage": "^7.15.0",
8
- "@terreno/api": "58.0.0-beta.1",
9
- "@terreno/jobs": "58.0.0-beta.1",
8
+ "@terreno/api": "58.0.0-beta.2",
9
+ "@terreno/jobs": "58.0.0-beta.2",
10
10
  "express": "^5.2.1",
11
11
  "luxon": "^3.7.2",
12
12
  "multer": "2.2.0"
@@ -14,7 +14,7 @@
14
14
  "description": "Admin panel backend plugin for @terreno/api — part of Terreno, the batteries-included TypeScript framework for universal apps.",
15
15
  "devDependencies": {
16
16
  "@biomejs/biome": "^2.3.6",
17
- "@terreno/test": "58.0.0-beta.1",
17
+ "@terreno/test": "58.0.0-beta.2",
18
18
  "@types/bun": "^1.4.0",
19
19
  "@types/express": "^5.0.6",
20
20
  "@types/luxon": "^3.7.1",
@@ -24,6 +24,13 @@
24
24
  "supertest": "^7.2.2",
25
25
  "typescript": "~6.0.3"
26
26
  },
27
+ "files": [
28
+ "LICENSE",
29
+ "CHANGELOG.md",
30
+ "dist/**/*",
31
+ "src/**/*",
32
+ ".ai/**/*"
33
+ ],
27
34
  "homepage": "https://github.com/TerrenoLabs/terreno#readme",
28
35
  "keywords": [
29
36
  "admin",
@@ -58,5 +65,5 @@
58
65
  "typecheck": "tsc -p tsconfig.typecheck.json"
59
66
  },
60
67
  "types": "dist/index.d.ts",
61
- "version": "58.0.0-beta.1"
68
+ "version": "58.0.0-beta.2"
62
69
  }
@@ -1,223 +0,0 @@
1
- # Terreno
2
-
3
- Terreno is Django/Rails for TypeScript — with universal app support.
4
-
5
- Terreno is Django/Rails for TypeScript — a batteries-included, full-stack
6
- framework where the undifferentiated 80% of an app is already written. On the
7
- backend you get Mongoose models, auto-generated REST APIs, permissions, an admin
8
- panel, authentication, and an AI service. On the frontend you get one universal
9
- app — a single React Native codebase that ships to iOS, Android, and web. It is
10
- built to be driven by AI coding agents from the first prompt to a production
11
- deploy.
12
-
13
- - Batteries included — auth, CRUD APIs, admin, permissions, AI, realtime,
14
- feature flags, and consent are already built, so your code is business logic.
15
- - Universal by default — one React Native codebase ships to iOS, Android, and
16
- web. Not a web framework with a mobile bolt-on.
17
- - AI-native — agents are a first-class client of the framework, not an
18
- afterthought.
19
-
20
- ## Packages
21
-
22
- - **api/** - REST API framework built on Express/Mongoose (`@terreno/api`)
23
- - **ui/** - React Native UI component library (`@terreno/ui`)
24
- - **rtk/** - Redux Toolkit Query utilities for API backends (`@terreno/rtk`)
25
- - **admin-backend/** - Admin panel backend plugin for @terreno/api (`@terreno/admin-backend`)
26
- - **admin-frontend/** - Admin panel frontend screens for @terreno/api backends (`@terreno/admin-frontend`)
27
- - **demo/** - Demo app for showcasing and testing UI components
28
- - **example-frontend/** - Example Expo app demonstrating full stack usage
29
- - **example-backend/** - Example Express backend using @terreno/api
30
-
31
- ## Development
32
-
33
- Uses [Bun](https://bun.sh/) as the package manager.
34
-
35
- ```bash
36
- bun install # Install dependencies
37
- bun run compile # Compile all packages
38
- bun run lint # Lint all packages
39
- bun run lint:fix # Fix lint issues
40
- bun run test # Run tests in api and ui
41
- ```
42
-
43
- ### Package-specific commands
44
-
45
- ```bash
46
- bun run api:test # Test API package
47
- bun run ui:test # Test UI package
48
- bun run demo:start # Start demo app
49
- bun run frontend:web # Start frontend example
50
- bun run backend:dev # Start backend example
51
- bun run admin-backend:compile # Compile admin backend
52
- bun run admin-frontend:compile # Compile admin frontend
53
- ```
54
-
55
- ## How the Packages Work Together
56
-
57
- The three core packages form a complete full-stack framework:
58
-
59
- ```
60
- BACKEND
61
- @terreno/api
62
- - Mongoose models with modelRouter -> CRUD endpoints
63
- - Built-in auth (JWT + Passport)
64
- - Automatic OpenAPI spec generation
65
- |
66
- /openapi.json
67
- |
68
- RTK Query SDK Codegen
69
- |
70
- FRONTEND
71
- @terreno/rtk
72
- - Generated hooks from OpenAPI spec
73
- - Auth slice with JWT token management
74
- - Automatic token refresh
75
- +
76
- @terreno/ui
77
- - React Native components (Box, Button, TextField, etc.)
78
- - TerrenoProvider for theming
79
- ```
80
-
81
- ### Integration Flow
82
-
83
- 1. **Backend (api)**: Define Mongoose models, use `modelRouter` to create CRUD endpoints with permissions
84
- 2. **OpenAPI Generation**: `setupServer` automatically generates `/openapi.json`
85
- 3. **SDK Codegen**: Frontend runs `bun run sdk` to generate RTK Query hooks from OpenAPI spec
86
- 4. **Frontend (rtk + ui)**: Use generated hooks with UI components for type-safe API calls
87
-
88
- ## Example Apps (Keep These Updated!)
89
-
90
- The `example-frontend/` and `example-backend/` directories serve as both documentation and integration tests. When adding features to api, ui, or rtk:
91
-
92
- 1. **Add examples** demonstrating new features
93
- 2. **Update SDK** after backend changes: `cd example-frontend && bun run sdk`
94
- 3. **Verify integration** by running both examples together
95
-
96
- ### Running the Full Stack
97
-
98
- ```bash
99
- # Terminal 1: Start backend
100
- bun run backend:dev
101
-
102
- # Terminal 2: Start frontend
103
- bun run frontend:web
104
- ```
105
-
106
- ## Code Style
107
-
108
- ### TypeScript/JavaScript
109
- - Use ES module syntax and TypeScript for all code
110
- - Prefer interfaces over types; avoid enums, use maps
111
- - Prefer const arrow functions over `function` keyword
112
- - Use descriptive variable names with auxiliary verbs (e.g., `isLoading`)
113
- - Use camelCase directories (e.g., `components/authWizard`)
114
- - Favor named exports
115
- - Use the RORO pattern (Receive an Object, Return an Object)
116
-
117
- ### Dates and Time
118
- - Always use Luxon instead of Date or dayjs
119
-
120
- ### Error Handling
121
- - Check error conditions at start of functions and return early
122
- - Limit nested if statements
123
- - Use multiline syntax with curly braces for all conditionals
124
-
125
- ### Testing
126
- - Use bun test with expect for testing
127
-
128
- ### Logging
129
- - Frontend: Use `console.info`, `console.debug`, `console.warn`, or `console.error` for permanent logs
130
- - Backend: Use `logger.info/warn/error/debug` for permanent logs
131
- - Use `console.log` only for debugging (to be removed)
132
-
133
- ### Development Practices
134
- - Don't apologize for errors: fix them
135
- - Prioritize modularity, DRY, performance, and security
136
- - Focus on readability over performance
137
- - Write complete, functional code without TODOs when possible
138
- - Comments should describe purpose, not effect
139
-
140
- ## Package Reference
141
-
142
- ### @terreno/api
143
-
144
- REST API framework providing:
145
-
146
- - **modelRouter**: Auto-generates CRUD endpoints for Mongoose models
147
- - **Permissions**: `IsAuthenticated`, `IsOwner`, `IsAdmin`, `IsAuthenticatedOrReadOnly`
148
- - **Query Filters**: `OwnerQueryFilter` for filtering list queries by owner
149
- - **setupServer**: Express server setup with auth, OpenAPI, and middleware
150
- - **APIError**: Standardized error handling
151
- - **logger**: Winston-based logging
152
-
153
- Key imports:
154
- ```typescript
155
- import {
156
- modelRouter,
157
- setupServer,
158
- Permissions,
159
- OwnerQueryFilter,
160
- APIError,
161
- logger,
162
- asyncHandler,
163
- authenticateMiddleware,
164
- } from "@terreno/api";
165
- ```
166
-
167
- ### @terreno/ui
168
-
169
- React Native UI component library (a large component library):
170
-
171
- - **Layout**: Box, Page, ListDetailLayout, SplitPage, Card
172
- - **Forms**: TextField, SelectField, DateTimeField, CheckBox
173
- - **Display**: Text, Heading, Badge, DataTable
174
- - **Actions**: Button, IconButton, Link
175
- - **Feedback**: Spinner, Modal, Toast
176
- - **Theming**: TerrenoProvider, useTheme
177
-
178
- Key imports:
179
- ```typescript
180
- import {
181
- Box,
182
- Button,
183
- Card,
184
- Page,
185
- Text,
186
- TextField,
187
- TerrenoProvider,
188
- } from "@terreno/ui";
189
- ```
190
-
191
- ### @terreno/rtk
192
-
193
- Redux Toolkit Query integration:
194
-
195
- - **generateAuthSlice**: Creates auth reducer and middleware with JWT handling
196
- - **emptyApi**: Base RTK Query API for code generation
197
- - **Platform utilities**: Secure token storage (expo-secure-store for native, AsyncStorage for web)
198
-
199
- Key imports:
200
- ```typescript
201
- import {generateAuthSlice} from "@terreno/rtk";
202
- ```
203
-
204
- ## CI/CD Workflows
205
-
206
- ### Required Secret Validation
207
-
208
- 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.
209
-
210
- ```yaml
211
- - name: Validate required secrets
212
- run: |
213
- missing=()
214
- if [ -z "$VAR_NAME" ]; then missing+=("VAR_NAME"); fi
215
- if [ ${#missing[@]} -ne 0 ]; then
216
- echo "::error::Missing required secrets: ${missing[*]}"
217
- exit 1
218
- fi
219
- ```
220
-
221
- ## Dependency Management
222
-
223
- Uses [Bun Catalogs](https://bun.sh/docs/install/catalogs) - shared versions defined in root `package.json` under `catalog`. Reference with `catalog:` in workspace packages.
@@ -1,357 +0,0 @@
1
- ---
2
- description: Terreno monorepo root guidelines
3
- globs: **/*
4
- ---
5
-
6
- # Terreno
7
-
8
- Terreno is Django/Rails for TypeScript — with universal app support.
9
-
10
- Terreno is Django/Rails for TypeScript — a batteries-included, full-stack
11
- framework where the undifferentiated 80% of an app is already written. On the
12
- backend you get Mongoose models, auto-generated REST APIs, permissions, an admin
13
- panel, authentication, and an AI service. On the frontend you get one universal
14
- app — a single React Native codebase that ships to iOS, Android, and web. It is
15
- built to be driven by AI coding agents from the first prompt to a production
16
- deploy.
17
-
18
- - Batteries included — auth, CRUD APIs, admin, permissions, AI, realtime,
19
- feature flags, and consent are already built, so your code is business logic.
20
- - Universal by default — one React Native codebase ships to iOS, Android, and
21
- web. Not a web framework with a mobile bolt-on.
22
- - AI-native — agents are a first-class client of the framework, not an
23
- afterthought.
24
-
25
- ## Packages
26
-
27
- - **api/** - REST API framework built on Express/Mongoose (`@terreno/api`)
28
- - **ui/** - React Native UI component library (`@terreno/ui`)
29
- - **rtk/** - Redux Toolkit Query utilities for API backends (`@terreno/rtk`)
30
- - **admin-backend/** - Admin panel backend plugin for @terreno/api (`@terreno/admin-backend`)
31
- - **admin-frontend/** - Admin panel frontend screens for @terreno/api backends (`@terreno/admin-frontend`)
32
- - **mcp-server/** - MCP server for AI assistant integration (`@terreno/mcp-server`)
33
- - **demo/** - Demo app for showcasing and testing UI components
34
- - **example-frontend/** - Example Expo app demonstrating full stack usage
35
- - **example-backend/** - Example Express backend using @terreno/api
36
-
37
- ## Development
38
-
39
- Uses [Bun](https://bun.sh/) as the package manager.
40
-
41
- ```bash
42
- bun install # Install dependencies
43
- bun run compile # Compile all packages
44
- bun run lint # Lint all packages
45
- bun run lint:fix # Fix lint issues
46
- bun run test # Run tests in api and ui
47
- ```
48
-
49
- ### Package-specific commands
50
-
51
- ```bash
52
- bun run api:test # Test API package
53
- bun run ui:test # Test UI package
54
- bun run demo:start # Start demo app
55
- bun run frontend:web # Start frontend example
56
- bun run backend:dev # Start backend example
57
- bun run mcp:build # Build MCP server
58
- bun run mcp:start # Start MCP server
59
- bun run admin-backend:compile # Compile admin backend
60
- bun run admin-frontend:compile # Compile admin frontend
61
- ```
62
-
63
- ## How the Packages Work Together
64
-
65
- The three core packages form a complete full-stack framework:
66
-
67
- ```
68
- BACKEND
69
- @terreno/api
70
- - Mongoose models with modelRouter -> CRUD endpoints
71
- - Built-in auth (JWT + Passport)
72
- - Automatic OpenAPI spec generation
73
- |
74
- /openapi.json
75
- |
76
- RTK Query SDK Codegen
77
- |
78
- FRONTEND
79
- @terreno/rtk
80
- - Generated hooks from OpenAPI spec
81
- - Auth slice with JWT token management
82
- - Automatic token refresh
83
- +
84
- @terreno/ui
85
- - React Native components (Box, Button, TextField, etc.)
86
- - TerrenoProvider for theming
87
- ```
88
-
89
- ### Integration Flow
90
-
91
- 1. **Backend (api)**: Define Mongoose models, use `modelRouter` to create CRUD endpoints with permissions
92
- 2. **OpenAPI Generation**: `setupServer` automatically generates `/openapi.json`
93
- 3. **SDK Codegen**: Frontend runs `bun run sdk` to generate RTK Query hooks from OpenAPI spec
94
- 4. **Frontend (rtk + ui)**: Use generated hooks with UI components for type-safe API calls
95
-
96
- ## Example Apps (Keep These Updated!)
97
-
98
- The `example-frontend/` and `example-backend/` directories serve as both documentation and integration tests. When adding features to api, ui, or rtk:
99
-
100
- 1. **Add examples** demonstrating new features
101
- 2. **Update SDK** after backend changes: `cd example-frontend && bun run sdk`
102
- 3. **Verify integration** by running both examples together
103
-
104
- ### Running the Full Stack
105
-
106
- ```bash
107
- # Terminal 1: Start backend
108
- bun run backend:dev
109
-
110
- # Terminal 2: Start frontend
111
- bun run frontend:web
112
- ```
113
-
114
- ## Code Style
115
-
116
- ### TypeScript/JavaScript
117
- - Use ES module syntax and TypeScript for all code
118
- - Prefer interfaces over types; avoid enums, use maps
119
- - Prefer const arrow functions over `function` keyword
120
- - Use descriptive variable names with auxiliary verbs (e.g., `isLoading`)
121
- - Use camelCase directories (e.g., `components/authWizard`)
122
- - Favor named exports
123
- - Use the RORO pattern (Receive an Object, Return an Object)
124
-
125
- ### Dates and Time
126
- - Always use Luxon instead of Date or dayjs
127
-
128
- ### Error Handling
129
- - Check error conditions at start of functions and return early
130
- - Limit nested if statements
131
- - Use multiline syntax with curly braces for all conditionals
132
-
133
- ### Testing
134
- - Use bun test with expect for testing
135
-
136
- ### Logging
137
- - Frontend: Use `console.info`, `console.debug`, `console.warn`, or `console.error` for permanent logs
138
- - Backend: Use `logger.info/warn/error/debug` for permanent logs
139
- - Use `console.log` only for debugging (to be removed)
140
-
141
- ### Development Practices
142
- - Don't apologize for errors: fix them
143
- - Prioritize modularity, DRY, performance, and security
144
- - Focus on readability over performance
145
- - Write complete, functional code without TODOs when possible
146
- - Comments should describe purpose, not effect
147
-
148
- ## Package Reference
149
-
150
- ### @terreno/api
151
-
152
- REST API framework providing:
153
-
154
- - **modelRouter**: Auto-generates CRUD endpoints for Mongoose models
155
- - **Permissions**: `IsAuthenticated`, `IsOwner`, `IsAdmin`, `IsAuthenticatedOrReadOnly`
156
- - **Query Filters**: `OwnerQueryFilter` for filtering list queries by owner
157
- - **setupServer**: Express server setup with auth, OpenAPI, and middleware
158
- - **APIError**: Standardized error handling
159
- - **logger**: Winston-based logging
160
-
161
- Key imports:
162
- ```typescript
163
- import {
164
- modelRouter,
165
- setupServer,
166
- Permissions,
167
- OwnerQueryFilter,
168
- APIError,
169
- logger,
170
- asyncHandler,
171
- authenticateMiddleware,
172
- } from "@terreno/api";
173
- ```
174
-
175
- #### modelRouter Usage
176
-
177
- ```typescript
178
- import {modelRouter, modelRouterOptions, Permissions} from "@terreno/api";
179
-
180
- const router = modelRouter(YourModel, {
181
- permissions: {
182
- list: [Permissions.IsAuthenticated],
183
- create: [Permissions.IsAuthenticated],
184
- read: [Permissions.IsOwner],
185
- update: [Permissions.IsOwner],
186
- delete: [], // Disabled
187
- },
188
- sort: "-created",
189
- queryFields: ["_id", "type", "name"],
190
- });
191
- ```
192
-
193
- #### Custom Routes
194
-
195
- For non-CRUD endpoints, use the OpenAPI builder:
196
-
197
- ```typescript
198
- import {asyncHandler, authenticateMiddleware, createOpenApiBuilder} from "@terreno/api";
199
-
200
- router.get("/yourRoute/:id", [
201
- authenticateMiddleware(),
202
- createOpenApiBuilder(options)
203
- .withTags(["yourTag"])
204
- .withSummary("Brief summary")
205
- .withPathParameter("id", {type: "string"})
206
- .withResponse(200, {data: {type: "object"}})
207
- .build(),
208
- ], asyncHandler(async (req, res) => {
209
- return res.json({data: result});
210
- }));
211
- ```
212
-
213
- #### API Conventions
214
-
215
- - Throw `APIError` with appropriate status codes: `throw new APIError({status: 400, title: "Message"})`
216
- - Do not use `Model.findOne` - use `Model.findExactlyOne` or `Model.findOneOrThrow`
217
- - Define statics/methods by direct assignment: `schema.methods = {bar() {}}`
218
- - All model types live in `src/modelInterfaces.ts`
219
- - In routes: `req.user` is `UserDocument | undefined`
220
- - In @terreno/api callbacks: cast with `const user = u as unknown as UserDocument`
221
-
222
- ### @terreno/ui
223
-
224
- React Native UI component library (a large component library):
225
-
226
- - **Layout**: Box, Page, ListDetailLayout, SplitPage, Card
227
- - **Forms**: TextField, SelectField, DateTimeField, CheckBox
228
- - **Display**: Text, Heading, Badge, DataTable
229
- - **Actions**: Button, IconButton, Link
230
- - **Feedback**: Spinner, Modal, Toast
231
- - **Theming**: TerrenoProvider, useTheme
232
-
233
- Key imports:
234
- ```typescript
235
- import {
236
- Box,
237
- Button,
238
- Card,
239
- Page,
240
- Text,
241
- TextField,
242
- TerrenoProvider,
243
- } from "@terreno/ui";
244
- ```
245
-
246
- #### UI Component Examples
247
-
248
- Layout with Box:
249
- ```typescript
250
- <Box direction="row" padding={4} gap={2} alignItems="center">
251
- <Text>Content</Text>
252
- <Button text="Action" />
253
- </Box>
254
- ```
255
-
256
- Buttons:
257
- ```typescript
258
- <Button
259
- text="Submit"
260
- variant="primary" // 'primary' | 'secondary' | 'outline' | 'ghost'
261
- onClick={handleSubmit}
262
- loading={isLoading}
263
- iconName="check"
264
- />
265
- ```
266
-
267
- Forms:
268
- ```typescript
269
- <TextField
270
- label="Email"
271
- value={email}
272
- onChangeText={setEmail}
273
- error={emailError}
274
- helperText="Enter a valid email"
275
- />
276
- ```
277
-
278
- Modals:
279
- ```typescript
280
- <Modal
281
- title="Confirm Action"
282
- visible={isVisible}
283
- primaryButtonText="Confirm"
284
- secondaryButtonText="Cancel"
285
- onDismiss={() => setIsVisible(false)}
286
- onPrimaryAction={handleConfirm}
287
- >
288
- <Text>Are you sure?</Text>
289
- </Modal>
290
- ```
291
-
292
- #### UI Common Pitfalls
293
-
294
- - Don't use inline styles when theme values are available
295
- - Don't use raw `View`/`Text` when `Box`/@terreno/ui `Text` are available
296
- - Don't forget loading and error states
297
- - Don't use `style` prop when equivalent props exist (`padding`, `margin`)
298
- - Never modify `openApiSdk.ts` manually
299
-
300
- ### @terreno/rtk
301
-
302
- Redux Toolkit Query integration:
303
-
304
- - **generateAuthSlice**: Creates auth reducer and middleware with JWT handling
305
- - **emptyApi**: Base RTK Query API for code generation
306
- - **Platform utilities**: Secure token storage (expo-secure-store for native, AsyncStorage for web)
307
-
308
- Key imports:
309
- ```typescript
310
- import {generateAuthSlice} from "@terreno/rtk";
311
- ```
312
-
313
- Always use generated SDK hooks - never use `axios` or `request` directly:
314
-
315
- ```typescript
316
- // Correct
317
- import {useGetYourRouteQuery} from "@/store/openApiSdk";
318
- const {data, isLoading, error} = useGetYourRouteQuery({id: "value"});
319
-
320
- // Wrong - don't use axios directly
321
- // const result = await axios.get("/api/yourRoute/value");
322
- ```
323
-
324
- ## React Best Practices (Frontend Packages)
325
-
326
- - Use functional components with `React.FC` type
327
- - Import hooks directly: `import {useEffect, useMemo} from 'react'`
328
- - Always provide return types for functions
329
- - Add explanatory comment above each `useEffect`
330
- - Wrap callbacks in `useCallback`
331
- - Prefer const arrow functions
332
- - Use inline styles over `StyleSheet.create`
333
- - Use Luxon for date operations
334
- - Place static content and interfaces at beginning of file
335
- - Minimize `use client`, `useEffect`, and `setState`
336
- - Always support React-Native Web
337
-
338
- ## CI/CD Workflows
339
-
340
- ### Required Secret Validation
341
-
342
- 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.
343
-
344
- ```yaml
345
- - name: Validate required secrets
346
- run: |
347
- missing=()
348
- if [ -z "$VAR_NAME" ]; then missing+=("VAR_NAME"); fi
349
- if [ ${#missing[@]} -ne 0 ]; then
350
- echo "::error::Missing required secrets: ${missing[*]}"
351
- exit 1
352
- fi
353
- ```
354
-
355
- ## Dependency Management
356
-
357
- Uses [Bun Catalogs](https://bun.sh/docs/install/catalogs) - shared versions defined in root `package.json` under `catalog`. Reference with `catalog:` in workspace packages.