-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLLM.txt
More file actions
882 lines (709 loc) · 24.7 KB
/
LLM.txt
File metadata and controls
882 lines (709 loc) · 24.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
# Technical Guide for LLMs
This is the technical guide for a Module Federation monorepo demonstrating every-plugin architecture, runtime-loaded configuration, and NEAR Protocol integration. The canonical runtime package is `everything-dev`; `bos` is its CLI alias.
For contribution guidelines, see [CONTRIBUTING.md](./CONTRIBUTING.md).
## Architecture Overview
This is a **Module Federation monorepo** with runtime-loaded configuration:
```
┌─────────────────────────────────────────────────────────┐
│ Host (Server) │
│ - Hono.js + oRPC router │
│ - Runtime config loader (bos.config.json) │
│ - Module Federation host │
│ - every-plugin runtime │
└─────────────────────────────────────────────────────────┘
↓ ↓
┌───────────────────────┐ ┌───────────────────────┐
│ UI Remote │ │ API Plugin │
│ - React 19 │ │ - every-plugin │
│ - TanStack Router │ │ - oRPC contract │
│ - Module Federation │ │ - Effect services │
└───────────────────────┘ └───────────────────────┘
```
**Key Characteristics:**
- ✅ Runtime-loaded configuration (no rebuild for URL changes)
- ✅ Independent deployment of UI, API, and Host
- ✅ Type-safe RPC with oRPC
- ✅ NEAR Protocol authentication via Better-Auth
- ✅ CDN-ready with Module Federation
## Configuration System: bos.config.json
The **entire system** is configured via `bos.config.json` - a runtime-loaded JSON file:
```json
{
"account": "example.near",
"app": {
"host": {
"title": "App Title",
"development": "http://localhost:3000",
"production": "https://example.com"
},
"ui": {
"name": "ui",
"development": "http://localhost:3002",
"production": "https://cdn.example.com/ui/remoteEntry.js"
},
"api": {
"name": "api",
"development": "http://localhost:3014",
"production": "https://cdn.example.com/api/remoteEntry.js",
"variables": {},
"secrets": ["API_DATABASE_URL", "API_DATABASE_AUTH_TOKEN"]
}
}
}
```
**Why this approach?**
- Environment switching via `NODE_ENV` (no rebuild needed)
- CDN URLs can be updated without code changes
- Secrets use template injection (`{{VAR_NAME}}`)
- Single source of truth for all configurations
**Implementation:** See `host/src/config.ts` for the loader.
## Module Federation Setup
### UI Remote (ui/)
**Technology:** Rsbuild + `@module-federation/rsbuild-plugin`
The UI is a **React 19 application** built with:
- TanStack Router (file-based routing)
- TanStack Query (data fetching)
- Tailwind CSS v4 (styling)
- shadcn/ui (component library)
**Exposed Modules:**
```typescript
exposes: {
'./App': './src/bootstrap.tsx', // Main application
'./Router': './src/router.tsx', // TanStack Router instance
'./components': './src/components/index.ts', // Reusable components
'./providers': './src/providers/index.tsx', // Context providers
}
```
**Shared Dependencies (singleton):**
- `react`, `react-dom`
- `@tanstack/react-query`, `@tanstack/react-router`
- `@hot-labs/near-connect`, `near-kit`
**Build Config:** `ui/rsbuild.config.ts`
- Uses `pluginModuleFederation` for federation
- Uses `withZephyr` for automatic CDN deployment
- Auto-updates `bos.config.json` on deployment
**How Host Loads UI:**
```typescript
// host/src/main.tsx
const config = await loadBosConfig(); // Reads bos.config.json
createInstance({
name: 'host',
remotes: [{
name: config.ui.name, // "ui"
entry: `${config.ui.url}/remoteEntry.js` // From config!
}]
});
const RemoteApp = await loadRemote(`${config.ui.name}/App`);
```
**Key Point:** No hardcoded URLs. Everything derived from `bos.config.json`.
### API Plugin (api/)
**Technology:** Rspack + `every-plugin`
The API is an **every-plugin** that exposes an oRPC router. It can compose across other plugins in-process via `createPlugin.withPlugins<PluginsClient>()`. See [every-plugin template guide](https://github.com/near-everything/every-plugin/blob/main/plugins/_template/LLM.txt) for plugin development patterns.
**Structure:**
```
api/
├── src/
│ ├── contract.ts # oRPC route definitions
│ ├── index.ts # createPlugin.withPlugins() implementation
│ ├── plugins-client.gen.ts # Generated PluginsClient type (auto-generated, gitignored)
│ ├── schema.ts # Zod schemas for validation
│ ├── services/ # Business logic (Effect-based)
│ └── db/ # Database schema (Drizzle)
└── plugin.dev.ts # Dev server config
```
**Plugin Definition:**
```typescript
// api/src/index.ts
import type { PluginsClient } from "./plugins-client.gen";
export default createPlugin.withPlugins<PluginsClient>()({
variables: z.object({
demoMessage: z.string().optional(),
}),
secrets: z.object({
API_DATABASE_URL: z.string(),
API_DATABASE_AUTH_TOKEN: z.string()
}),
contract, // oRPC contract from contract.ts
initialize: (config, plugins) => Effect.gen(function* () {
// Create services with config
const db = createDb(config.secrets.API_DATABASE_URL);
const service = new MyService(db);
return { service, plugins, demoMessage: config.variables.demoMessage ?? "not configured" };
}),
createRouter: (services, builder) => ({
// Direct routes
ping: builder.ping.handler(async () => ({ status: "ok", timestamp: new Date().toISOString() })),
// Composed route — calls registry plugin in-process
pluginDemo: builder.pluginDemo.handler(async () => {
const status = await services.plugins.registry().getRegistryStatus();
return { apiVariable: services.demoMessage, registryStatus: status, availablePlugins: Object.keys(services.plugins) };
}),
})
});
```
**How Host Loads API (two-phase):**
```typescript
// Phase 1: Load all non-API plugins
const pluginResults = await Promise.all(
pluginEntries.map(entry => runtime.usePlugin(entry.runtimeId, { variables, secrets }))
);
// Build pluginsClient map from Phase 1 results
const pluginsClient = {};
for (const result of pluginResults) {
pluginsClient[result.key] = result.createClient; // Factory, not instance
}
// Phase 2: Load API plugin with injected pluginsClient
const apiPlugin = await runtime.usePlugin(apiEntry.runtimeId, {
variables: apiEntry.config.variables,
secrets: collectSecrets(apiEntry),
}, pluginsClient);
```
**Key Point:** The host is generic — no plugin-specific code. `pluginsClient` is a map of `createClient` factories typed by the generated `PluginsClient` type. The API calls `services.plugins.registry()` to execute plugin routers in-process.
## UI Styling Guidelines
### Semantic Tailwind Classes
This project uses **Tailwind CSS v4** with semantic color classes defined via CSS variables. Always use semantic classes instead of hardcoded colors.
**Available Semantic Colors:**
```typescript
// Backgrounds and surfaces
bg-background // Main background
bg-card // Card backgrounds
bg-popover // Popover/dropdown backgrounds
bg-primary // Primary action color
bg-secondary // Secondary elements
bg-muted // Muted/disabled states
bg-accent // Accent highlights
bg-destructive // Destructive actions (delete, errors)
// Text colors (use corresponding -foreground variants)
text-foreground // Main text on background
text-card-foreground // Text on card
text-primary-foreground // Text on primary
text-secondary-foreground // Text on secondary
text-muted-foreground // Muted/helper text
text-accent-foreground // Text on accent
text-destructive-foreground // Text on destructive
// Borders and inputs
border-border // Border color
border-input // Input border color
ring-ring // Focus ring color
```
**Custom Brand Colors:**
```css
/* Available as CSS variables */
--near-green: #00ec97;
--near-green-hover: #00d66f;
--near-green-light: #d4fced;
--near-blue: #3d7fff;
--near-purple: #635bff;
```
**Example Usage:**
```tsx
// ✅ Good: Semantic classes
<button className="bg-primary text-primary-foreground hover:bg-primary/90">
Submit
</button>
<div className="bg-card text-card-foreground border border-border rounded-lg">
<h2 className="text-foreground">Title</h2>
<p className="text-muted-foreground">Description</p>
</div>
// ❌ Bad: Hardcoded colors
<button className="bg-blue-600 text-white">
Submit
</button>
```
**Key Benefits:**
- Automatic dark mode support (colors switch via `.dark` class)
- Consistent design system
- Uses oklch color space for better color perception
- Theme customization via CSS variables
**Border Radius:**
```typescript
rounded-sm // calc(var(--radius) - 4px)
rounded-md // calc(var(--radius) - 2px)
rounded-lg // var(--radius)
rounded-xl // calc(var(--radius) + 4px)
```
## NEAR Protocol Integration
### Authentication: Better-Auth + better-near-auth
The project uses **Better-Auth** with multiple authentication methods:
1. **better-near-auth** plugin for NEAR Protocol authentication (SIWN - Sign In With NEAR)
2. **Email/Password** with verification
3. **Anonymous** authentication for guest users
**Host Setup (host/src/services/auth.ts):**
```typescript
import { betterAuth } from "better-auth";
import { admin, anonymous } from "better-auth/plugins";
import { siwn } from "better-near-auth";
export const auth = betterAuth({
database: drizzleAdapter(db, { provider: "sqlite", schema }),
plugins: [
siwn({ recipient: "your-account.near" }),
admin({ defaultRole: "user", adminRoles: ["admin"] }),
anonymous({
emailDomainName: "your-account.near",
onLinkAccount: async ({ anonymousUser, newUser }) => {
// Migrate anonymous user data to new user
}
}),
],
emailAndPassword: {
enabled: true,
requireEmailVerification: true,
sendResetPassword: async ({ user, url }) => {
void sendEmail({ to: user.email, subject: "Reset your password", text: `Click: ${url}` });
},
},
emailVerification: {
sendVerificationEmail: async ({ user, url }) => {
void sendEmail({ to: user.email, subject: "Verify your email", text: `Click: ${url}` });
},
sendOnSignUp: true,
sendOnSignIn: true,
autoSignInAfterVerification: true,
},
account: {
accountLinking: {
enabled: true,
trustedProviders: ["siwn", "email-password"],
allowDifferentEmails: true,
},
},
});
```
**Client Setup (ui/src/lib/auth-client.ts):**
```typescript
import { adminClient, anonymousClient } from "better-auth/client/plugins";
import { createAuthClient } from "better-auth/react";
import { siwnClient } from "better-near-auth/client";
export const authClient = createAuthClient({
plugins: [
siwnClient({ recipient: "your-account.near", networkId: "mainnet" }),
adminClient(),
anonymousClient(),
],
});
```
### Authentication Features
#### 1. NEAR Sign In (SIWN)
Single-step authentication with automatic wallet capability detection:
```typescript
await authClient.signIn.near({
onSuccess: () => navigate({ to: "/" }),
onError: (error) => {
if (error.code === "UNAUTHORIZED_NONCE_REPLAY") {
toast.error("Sign-in already used");
}
},
});
```
#### 2. Email/Password with Verification
```typescript
// Sign up with email
await authClient.signUp.email({
email: "user@example.com",
password: "password123",
name: "User Name",
});
// Email automatically verified via sendOnSignUp: true
// Users can also request manual verification:
await authClient.sendVerificationEmail({ email: "user@example.com" });
```
#### 3. Anonymous Authentication
```typescript
// Create anonymous user
const { data: user } = await authClient.signIn.anonymous();
// Link anonymous account to real account later
await authClient.signIn.email({ email: "user@example.com", password: "password123" });
// onLinkAccount callback automatically migrates data
```
#### 4. Password Reset
```typescript
await authClient.forgetPassword({
email: "user@example.com",
redirectTo: "/reset-password",
});
```
### NEAR Client: near-kit
**near-kit** provides a unified interface for NEAR Protocol operations. Full documentation: https://kit.near.tools/llms-full.txt
**How it's exposed:**
Via **better-near-auth**, you get access to a near-kit client through `getNearClient()`:
```typescript
// After authentication
const { data: session } = authClient.useSession();
if (session?.user?.walletAddress) {
const nearClient = await getNearClient({
network: 'mainnet',
accountId: session.user.walletAddress
});
// Now use near-kit methods
const balance = await nearClient.getBalance(session.user.walletAddress);
// Call contracts
await nearClient.callContract({
contractId: 'registry.everything.near',
method: '__fastdata_kv',
args: { 'apps/my.near/site/bos.config.json': { ... } }
});
}
```
See [better-near-auth LLM.txt](https://github.com/elliotBraem/better-near-auth/blob/main/LLM.txt) for complete authentication patterns.
**Key near-kit features:**
- ✅ Unified API for mainnet/testnet
- ✅ Account management (create, import, export)
- ✅ Contract calls (view, change methods)
- ✅ Transaction signing
- ✅ Balance queries
- ✅ Storage deposit management
- ✅ Meta-transaction support (via relayer)
## Database Schema
**Host Database** (Better-Auth):
- `host/src/db/schema/auth.ts` - User accounts, sessions, verification tokens
**API Database**:
- `api/src/db/schema.ts` - Application-specific data
Both use **Drizzle ORM** with **SQLite** (libsql).
**Migrations:**
```bash
# Host migrations
bun --filter host db:push
# API migrations
bun --filter api db:push
```
## Development Workflow
### Local Development
**Start all services:**
```bash
bun dev
# Starts:
# - API: http://localhost:3014
# - UI: http://localhost:3002
# - Host: http://localhost:3000
```
**Individual services:**
```bash
bun dev:api # API only (port 3014)
bun dev:ui # UI only (port 3002)
bun dev:host # Host only (port 3000)
```
**Environment switching:**
```bash
# Use local remotes (default)
bun dev:host
# Use production remotes
NODE_ENV=production bun dev:host
```
The host reads `NODE_ENV` and loads URLs from `bos.config.json`:
- `development` → `http://localhost:3002`, `http://localhost:3014`
- `production` → CDN URLs
### Development Commands with bos CLI
The `bos` CLI provides the primary development workflow:
**Typical Development:**
```bash
bos dev --host remote # Remote host, local UI + API
```
This is the standard workflow because:
- The host is already deployed and running remotely
- You only need to work on UI and/or API locally
- Hot reload works for local packages
- Production-like environment
**Isolating Work:**
```bash
bos dev --api remote # Work on UI only (API is remote)
bos dev --ui remote # Work on API only (UI is remote)
bos dev # Full local (rarely needed, initial setup only)
```
**Production Preview:**
```bash
bos start --no-interactive # Run with all production modules
```
### How Host, UI, and API Relate
```
Development Mode (bos dev --host remote):
┌─────────────────────────────────────────┐
│ Host (Remote) │
│ - Running on production/staging URL │
│ - Loads UI from localhost:3002 │
│ - Loads API from localhost:3014 │
└─────────────────────────────────────────┘
↓ ↓
┌──────────────┐ ┌──────────────┐
│ UI (Local) │ │ API (Local) │
│ :3002 │ │ :3014 │
└──────────────┘ └──────────────┘
```
**Key Points:**
1. **Host** orchestrates everything - serves the HTML, loads the UI runtime, merges API routes
2. **UI** owns routes/components; runtime factories live in `everything-dev/ui/client` and `/server`
3. **API** is an every-plugin - host loads plugin and merges its router
4. During dev with `--host remote`, host URLs come from `bos.config.json` production URLs
5. Local UI/API URLs are injected at runtime
### Debugging Development Issues
**Process Logs:**
```bash
# Check running processes
bos ps
# View logs
ls .bos/logs/ # Available log files
cat .bos/logs/api.log # API process logs
cat .bos/logs/ui.log # UI process logs
```
**API Not Responding:**
1. Check `bos ps` - is API process running?
2. Check `.bos/logs/api.log` - any startup errors?
3. Check `bos status` - are remotes healthy?
4. Verify `bos.config.json` - are URLs correct?
5. Test directly: `curl http://localhost:3014/health`
**UI Not Loading:**
1. Check `bos ps` - is UI process running?
2. Check browser console for Module Federation errors
3. Check `bos.config.json` - is `app.ui.development` URL correct?
4. Clear browser cache and hard reload
5. Verify the UI build output is accessible at the URL
**Type Errors After API Changes:**
1. Ensure `api/src/contract.ts` is updated
2. Run `bun typecheck` in both ui/ and api/
3. Check that UI imports match contract exports
4. Restart dev server if needed
**Module Federation Errors:**
- Clear browser cache (Ctrl+Shift+R / Cmd+Shift+R)
- Verify shared dependency versions match in all package.json files
- Check browser console for specific MF error messages
- Ensure `bos.config.json` URLs are accessible from browser
### Deployment
**Deploy UI:**
```bash
cd ui
bun build
# 1. Builds to dist/
# 2. Uploads to CDN via zephyr-rsbuild-plugin
# 3. Auto-updates bos.config.json with production URL
```
**Deploy API:**
```bash
cd api
bun build
# 1. Builds to dist/
# 2. Uploads to CDN via zephyr-rspack-plugin
# 3. Auto-updates bos.config.json with production URL
```
**Deploy Host:**
```bash
cd host
bun build
# 1. Builds server bundle to dist/
# 2. Deploy to hosting provider (Vercel, Railway, etc.)
# 3. Ensure bos.config.json is accessible at runtime
```
**Key Point:** UI and API are **independently deployable** without rebuilding the host!
## Changesets & Release Workflow
We use [Changesets](https://github.com/changesets/changesets) for versioning and releases.
### When to Add a Changeset
**Add a changeset for:**
- New features
- Bug fixes
- Deprecations
- Breaking changes
**Skip changeset for:**
- Documentation-only changes
- Internal refactors
- Test-only changes
- CI/CD changes
### Creating Changesets
```bash
# Interactive - select packages and write description
bun run changeset
# This creates a .changeset/*.md file describing the change
```
### Changeset File Format
```markdown
---
"api": minor
"ui": patch
---
Added new endpoint for user profiles
```
### Release Process
The release workflow (`.github/workflows/release.yml`) runs automatically on merge to main:
1. **Version PR Creation:**
- Changesets action creates/updates a "Version Packages" PR
- This PR bumps versions and updates CHANGELOG.md files
2. **On Merge of Version PR:**
- Publishes GitHub releases for `api` and `ui` packages
- Runs `bun run deploy` to build and deploy to Zephyr Cloud
- Commits updated `bos.config.json` with new production URLs
**Local Release Commands (rarely needed):**
```bash
bun run version # Bump versions based on changesets
bun run release # Create releases (CI handles this)
```
## Type Safety
### oRPC Contract
The API contract provides **end-to-end type safety**:
```typescript
// api/src/contract.ts
export const contract = oc.router({
getData: oc.route({ method: 'GET', path: '/data' })
.input(z.object({
id: z.string()
}))
.output(z.object({
data: DataSchema
}))
});
// ui/src/integrations/api/
// TypeScript knows the exact input/output types!
const { data } = await client.getData({ id: '123' });
// data is typed!
```
### Module Federation Types
Shared dependencies ensure singleton React/TanStack instances:
```typescript
// Both ui and host use the same React instance
import { useState } from 'react'; // Singleton
// Type imports work across remote boundaries
import type { Data } from 'ui/types';
```
## Testing
**Unit Tests:**
```bash
bun test # All workspaces
bun test:api # API only
bun test:ui # UI only
```
**Integration Tests:**
See `api/tests/` for plugin testing patterns.
**Running Tests:**
```bash
# All tests
bun test
# API integration tests only
bun run test:integration
# API unit tests only
bun run test:api
# With coverage
bun run --cwd api coverage
```
## Linting
This project uses [Biome](https://biomejs.dev/) for linting and formatting:
```bash
# Check linting
bun lint
# Fix auto-fixable issues
bun lint:fix
# Format code
bun format
# Check formatting without writing
bun format:check
```
**Configuration:** `biome.json` at project root
**Ignored Files:**
- `**/node_modules/**`
- `**/dist/**`
- `**/*.gen.ts` (generated files like routeTree.gen.ts)
- `**/coverage/**`
## Common Patterns
### Adding a New API Endpoint
1. **Define in contract** (`api/src/contract.ts`):
```typescript
export const contract = oc.router({
myNewEndpoint: oc.route({ method: 'POST', path: '/my-endpoint' })
.input(MyInputSchema)
.output(MyOutputSchema)
.errors(CommonPluginErrors)
});
```
2. **Create service** (`api/src/services/my-service.ts`):
```typescript
export class MyService {
doSomething(input: MyInput) {
return Effect.tryPromise({
try: async () => {
// Implementation
return result;
},
catch: (error: unknown) => new Error(`Failed: ${error}`)
});
}
}
```
3. **Add handler** (`api/src/index.ts`):
```typescript
createRouter: (context, builder) => ({
myNewEndpoint: builder.myNewEndpoint.handler(async ({ input }) => {
return await Effect.runPromise(
context.myService.doSomething(input)
);
})
})
```
4. **Use in UI** (`ui/src/integrations/api/`):
```typescript
export const useMyEndpoint = () => {
return useMutation({
mutationFn: (input: MyInput) =>
client.myNewEndpoint(input)
});
};
```
### Adding a New UI Page
1. **Create route file** (`ui/src/routes/my-page.tsx`):
```tsx
import { createFileRoute } from '@tanstack/react-router';
export const Route = createFileRoute('/my-page')({
component: MyPage
});
function MyPage() {
return (
<div className="bg-background text-foreground">
<h1 className="text-2xl font-bold">My Page</h1>
<p className="text-muted-foreground">Description</p>
</div>
);
}
```
2. **TanStack Router auto-generates** route tree on save.
3. **Navigate**: `<Link to="/my-page">Go</Link>`
### Configuring a New Environment
1. **Add to bos.config.json**:
```json
{
"app": {
"host": {
"staging": "https://staging.example.com"
},
"ui": {
"staging": "https://cdn.example.com/ui-staging/remoteEntry.js"
}
}
}
```
2. **Update config types** (`host/src/config.ts`):
```typescript
type Environment = 'development' | 'production' | 'staging';
```
3. **Use**: `NODE_ENV=staging bun dev:host`
## Related Documentation
- **AGENTS.md**: [./AGENTS.md](./AGENTS.md) - Quick operational guide for agents
- **CONTRIBUTING.md**: [./CONTRIBUTING.md](./CONTRIBUTING.md) - Contribution guidelines
- **every-plugin Guide**: https://github.com/near-everything/every-plugin/blob/main/plugins/_template/LLM.txt
- **near-kit Full Documentation**: https://kit.near.tools/llms-full.txt
- **better-near-auth Guide**: https://github.com/elliotBraem/better-near-auth/blob/main/LLM.txt
## Troubleshooting
**Module Federation Issues:**
- Clear browser cache
- Check `bos.config.json` URLs are accessible
- Verify shared dependencies versions match in `package.json`
**Type Errors:**
- Run `bun typecheck` in each workspace
- Ensure oRPC contract is up-to-date
- Check Module Federation type exports
**Build Errors:**
- Check all dependencies are installed: `bun install`
- Clear dist folders: `rm -rf */dist`
- Rebuild: `bun build`
**Runtime Config Not Loading:**
- Ensure `bos.config.json` is in host root
- Check file is accessible at runtime (not in .gitignore)
- Verify NODE_ENV matches a key in config
**Lint Errors:**
- Run `bun lint:fix` to auto-fix issues
- Check `biome.json` for configuration
- Exclude generated files if needed
For more help, see [CONTRIBUTING.md](./CONTRIBUTING.md) or open an issue.