oneie 2.0.3 → 2.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CLAUDE.md +220 -29
  2. package/LICENSE.md +84 -0
  3. package/README.md +489 -931
  4. package/dist/copy-claude-config.d.ts.map +1 -1
  5. package/dist/copy-claude-config.js +3 -1
  6. package/dist/copy-claude-config.js.map +1 -1
  7. package/dist/sync-agents.d.ts.map +1 -1
  8. package/dist/sync-agents.js +3 -1
  9. package/dist/sync-agents.js.map +1 -1
  10. package/dist/sync-ontology.d.ts.map +1 -1
  11. package/dist/sync-ontology.js +9 -7
  12. package/dist/sync-ontology.js.map +1 -1
  13. package/folders.yaml +78 -17
  14. package/one/.obsidian/workspace.json +6 -6
  15. package/one/events/CASCADE-2-BACKEND-AGNOSTIC.md +412 -0
  16. package/one/events/FEATURE-2-4-COMPLETE.md +302 -0
  17. package/one/events/FEATURE_2_3_COMPLETE.md +575 -0
  18. package/one/events/GROUPS-MIGRATION.md +625 -0
  19. package/one/events/INSTALL-TESTS.md +293 -0
  20. package/one/events/INTEGRATION-ARCHITECTURE.md +561 -0
  21. package/one/events/INTEGRATION-CHECKLIST.md +1234 -0
  22. package/one/events/INTEGRATION-ORCHESTRATION.md +2623 -0
  23. package/one/events/INTEGRATION-SUMMARY.md +653 -0
  24. package/one/events/MIGRATION-REPORT.md +435 -0
  25. package/one/events/MIGRATION.md +69 -0
  26. package/one/events/README-archived.md +519 -0
  27. package/one/events/TEST-SUMMARY.md +393 -0
  28. package/one/events/TESTS-QUICK-REF.md +262 -0
  29. package/one/groups/groups.md +543 -0
  30. package/one/knowledge/CLOUDFLARE_ENV_SETUP.md +49 -0
  31. package/one/knowledge/architecture-any-backend.md +1366 -0
  32. package/one/knowledge/docs/flow.md +0 -0
  33. package/one/knowledge/ontology-documentation.md +18 -18
  34. package/one/knowledge/ontology.md +154 -143
  35. package/one/knowledge/ontology.md.backup +2822 -0
  36. package/one/knowledge/ontology.yaml +87 -87
  37. package/one/knowledge/provider-creation-guide.md +1064 -0
  38. package/one/knowledge/todo.md +251 -0
  39. package/one/license.md +84 -0
  40. package/one/things/CHECKLIST.md +356 -0
  41. package/one/things/ONE.md +510 -0
  42. package/one/things/{cli.md → cli/cli.md} +27 -4
  43. package/one/things/features/2-1-dataprovider-interface.md +2358 -0
  44. package/one/things/features/2-2-config-system.md +3075 -0
  45. package/one/things/features/2-3-effectts-services.md +1498 -0
  46. package/one/things/features/2-4-react-hooks.md +2120 -0
  47. package/one/things/features/2-5-auth-migration.md +2046 -0
  48. package/one/things/features/2-6-dashboard-migration.md +1985 -0
  49. package/one/things/features/2-7-alternative-providers.md +2505 -0
  50. package/one/things/features/2-7-implementation-report.md +680 -0
  51. package/one/things/features/2-cli.md +39 -39
  52. package/one/things/features/2-design.md +1738 -0
  53. package/one/things/features/2-tests.md +520 -0
  54. package/one/things/features/AUTH_HOOKS_IMPLEMENTATION.md +521 -0
  55. package/one/things/features/DECOUPLING.md +272 -0
  56. package/one/things/features/DEPLOYMENT.md +452 -0
  57. package/one/things/features/IMPLEMENTATION_SUMMARY.md +316 -0
  58. package/one/things/features/dataprovider-interface/1-tests.md +1522 -0
  59. package/one/things/features/improve.md +843 -0
  60. package/one/things/features/remove-convex-deps.md +45 -0
  61. package/one/things/features/top-features.md +79 -0
  62. package/one/things/ideas/2-backend-agnostic-frontend.md +384 -0
  63. package/one/things/plans/2-backend-agnostic-frontend.md +543 -0
  64. package/one/things/plans/3-groups.md +502 -0
  65. package/one/things/plans/backend-agnostic-frontend.md +323 -0
  66. package/one/things/plans/deploy-to-cloudflare.md +581 -0
  67. package/one/things/plans/organizations-to-groups.md +705 -0
  68. package/one/things/plans/release.md +432 -0
  69. package/one/things/products/ontology.md +1 -1
  70. package/one/things/system.md +600 -0
  71. package/one/things/tests/2-1-dataprovider-interface.md +1144 -0
  72. package/one/things/tests/2-1-test-analysis.md +496 -0
  73. package/one/things/vision/elegant-interface.md +214 -0
  74. package/package.json +1 -1
  75. package/one/organisation/organisation.md +0 -438
  76. package/one/repomix-output.md +0 -92634
  77. /package/one/{things → connections}/agentkit.md +0 -0
  78. /package/one/{things → connections}/copilotkit.md +0 -0
  79. /package/one/{organisation → groups}/one.md +0 -0
  80. /package/one/{organisation → groups}/revenue.md +0 -0
  81. /package/one/{organisation → groups}/strategy.md +0 -0
  82. /package/one/{organisation → groups}/vision.md +0 -0
  83. /package/one/things/{cli-code.md → cli/cli-code.md} +0 -0
  84. /package/one/things/{cli-compiler-code.md → cli/cli-compiler-code.md} +0 -0
@@ -0,0 +1,1064 @@
1
+ # Provider Creation Guide
2
+
3
+ **Version:** 1.0.0
4
+ **Status:** Production
5
+ **Audience:** Backend Engineers, Integration Specialists
6
+ **Prerequisites:** TypeScript, Effect.ts, REST APIs
7
+
8
+ ---
9
+
10
+ ## Overview
11
+
12
+ This guide teaches you how to create a custom DataProvider implementation for the ONE Platform, enabling integration with any backend system (databases, SaaS platforms, APIs, etc.).
13
+
14
+ **You will learn:**
15
+ - DataProvider interface structure
16
+ - 6-dimension ontology mapping
17
+ - ID conversion patterns
18
+ - Status/type mapping strategies
19
+ - Error handling with Effect.ts
20
+ - Hybrid storage approaches
21
+ - Testing strategies
22
+
23
+ ---
24
+
25
+ ## Prerequisites
26
+
27
+ ### Required Knowledge
28
+
29
+ 1. **TypeScript:** Strong typing, generics, advanced types
30
+ 2. **Effect.ts:** Effects, Layers, Error handling
31
+ 3. **REST APIs:** HTTP methods, authentication, pagination
32
+ 4. **ONE Ontology:** 6 dimensions (Organizations, People, Things, Connections, Events, Knowledge)
33
+
34
+ ### Required Tools
35
+
36
+ - Node.js 18+
37
+ - TypeScript 5.9+
38
+ - Effect.ts 3.0+
39
+ - Your target backend's SDK (if available)
40
+
41
+ ### Required Files
42
+
43
+ Read these before starting:
44
+ 1. `/frontend/src/providers/DataProvider.ts` - Interface definition
45
+ 2. `/frontend/src/providers/convex/ConvexProvider.ts` - Reference implementation
46
+ 3. `/one/knowledge/ontology.md` - 6-dimension ontology specification
47
+
48
+ ---
49
+
50
+ ## Step 1: Understand the DataProvider Interface
51
+
52
+ The DataProvider interface defines operations for all 6 dimensions:
53
+
54
+ ```typescript
55
+ export interface DataProvider {
56
+ // ===== THINGS (Dimension 3) =====
57
+ things: {
58
+ get: (id: string) => Effect.Effect<Thing, ThingNotFoundError>;
59
+ list: (options?: ListThingsOptions) => Effect.Effect<Thing[], QueryError>;
60
+ create: (input: CreateThingInput) => Effect.Effect<string, ThingCreateError>;
61
+ update: (id: string, input: UpdateThingInput) => Effect.Effect<void, ThingUpdateError>;
62
+ delete: (id: string) => Effect.Effect<void, ThingNotFoundError>;
63
+ };
64
+
65
+ // ===== CONNECTIONS (Dimension 4) =====
66
+ connections: {
67
+ get: (id: string) => Effect.Effect<Connection, ConnectionNotFoundError>;
68
+ list: (options?: ListConnectionsOptions) => Effect.Effect<Connection[], QueryError>;
69
+ create: (input: CreateConnectionInput) => Effect.Effect<string, ConnectionCreateError>;
70
+ delete: (id: string) => Effect.Effect<void, ConnectionNotFoundError>;
71
+ };
72
+
73
+ // ===== EVENTS (Dimension 5) =====
74
+ events: {
75
+ get: (id: string) => Effect.Effect<Event, DataProviderError>;
76
+ list: (options?: ListEventsOptions) => Effect.Effect<Event[], QueryError>;
77
+ create: (input: CreateEventInput) => Effect.Effect<string, EventCreateError>;
78
+ };
79
+
80
+ // ===== KNOWLEDGE (Dimension 6) =====
81
+ knowledge: {
82
+ get: (id: string) => Effect.Effect<Knowledge, KnowledgeNotFoundError>;
83
+ list: (options?: SearchKnowledgeOptions) => Effect.Effect<Knowledge[], QueryError>;
84
+ create: (input: CreateKnowledgeInput) => Effect.Effect<string, DataProviderError>;
85
+ link: (thingId: string, knowledgeId: string, role?: ThingKnowledge["role"]) => Effect.Effect<string, DataProviderError>;
86
+ search: (embedding: number[], options?: SearchKnowledgeOptions) => Effect.Effect<Knowledge[], QueryError>;
87
+ };
88
+ }
89
+ ```
90
+
91
+ **Key Insights:**
92
+
93
+ 1. All operations return `Effect.Effect<Result, Error>`
94
+ 2. All errors are typed (no generic `Error` throwing)
95
+ 3. IDs are strings (you control format)
96
+ 4. All operations are pure (no side effects outside Effect)
97
+
98
+ ---
99
+
100
+ ## Step 2: Plan Your Backend Mapping
101
+
102
+ Before writing code, plan how your backend maps to the 6 dimensions:
103
+
104
+ ### Mapping Template
105
+
106
+ Fill out this template for your backend:
107
+
108
+ ```typescript
109
+ // EXAMPLE: Airtable Provider Planning
110
+
111
+ // 1. ORGANIZATIONS (Dimension 1)
112
+ // How: Each Airtable Base = 1 organization
113
+ // Configuration: Store base ID in organization properties
114
+ // Isolation: Queries scoped to base ID
115
+
116
+ // 2. PEOPLE (Dimension 2)
117
+ // How: Airtable doesn't have native users - use separate Users table
118
+ // Roles: Map collaborator permissions → ONE roles
119
+ // Auth: Use API key per organization
120
+
121
+ // 3. THINGS (Dimension 3)
122
+ // How: Each Airtable Table = 1 thing type
123
+ // Properties: Map Airtable fields → properties JSON
124
+ // Status: Use Status field (Single Select)
125
+ // ID Format: airtable_<table-name>_<record-id>
126
+
127
+ // 4. CONNECTIONS (Dimension 4)
128
+ // How: Airtable Linked Records = connections
129
+ // Storage: Native (Airtable supports linked records)
130
+ // Metadata: Store in separate JSON field
131
+
132
+ // 5. EVENTS (Dimension 5)
133
+ // How: Airtable doesn't support events - use hybrid with Convex
134
+ // Storage: Delegate to Convex
135
+ // Pattern: Log events to Convex, store reference in Airtable
136
+
137
+ // 6. KNOWLEDGE (Dimension 6)
138
+ // How: Airtable doesn't support vectors - use hybrid with Convex
139
+ // Storage: Delegate to Convex
140
+ // Pattern: Store labels in Airtable, vectors in Convex
141
+ ```
142
+
143
+ ### Decision Matrix
144
+
145
+ For each dimension, decide:
146
+
147
+ | Dimension | Native Support? | Storage Strategy | Notes |
148
+ |-----------|-----------------|------------------|-------|
149
+ | Organizations | No | Config-based | Each config = 1 org |
150
+ | People | Partial | Custom table | Map roles |
151
+ | Things | Yes | Native storage | Full CRUD |
152
+ | Connections | Partial | Hybrid/Custom | Depends on backend |
153
+ | Events | No | Hybrid (Convex) | Most backends lack this |
154
+ | Knowledge | No | Hybrid (Convex) | Most backends lack vectors |
155
+
156
+ **Hybrid Pattern:** If your backend doesn't support a dimension natively, delegate to Convex:
157
+
158
+ ```typescript
159
+ events: {
160
+ create: (input) => Effect.fail(
161
+ new EventCreateError("Use Convex for event storage - this provider doesn't support events")
162
+ ),
163
+ list: () => Effect.succeed([]),
164
+ get: (id) => Effect.fail(new QueryError("Events not supported")),
165
+ }
166
+ ```
167
+
168
+ ---
169
+
170
+ ## Step 3: Design Your ID Format
171
+
172
+ ONE uses string IDs. Design a format that:
173
+ 1. Prevents collisions with other providers
174
+ 2. Allows round-trip conversion (ONE ID ↔ Backend ID)
175
+ 3. Includes type information (helpful for debugging)
176
+
177
+ ### ID Format Examples
178
+
179
+ ```typescript
180
+ // Pattern: <provider>_<type>_<backend-id>
181
+
182
+ // Notion
183
+ "notion_abc123def456789012345678" // UUID without hyphens + prefix
184
+
185
+ // WordPress
186
+ "wp_course_123" // post type + post ID
187
+
188
+ // Airtable
189
+ "airtable_courses_recABC123" // table name + record ID
190
+
191
+ // Supabase
192
+ "supabase_uuid_550e8400-e29b-41d4-a716-446655440000" // standard UUID
193
+
194
+ // Firebase
195
+ "firebase_users_kYGxgYvdl5cDMNuvLKN0" // collection + document ID
196
+ ```
197
+
198
+ ### ID Converter Functions
199
+
200
+ Always implement bidirectional conversion:
201
+
202
+ ```typescript
203
+ // ONE ID → Backend ID
204
+ const oneIdToBackendId = (oneId: string): string => {
205
+ const match = oneId.match(/^mybackend_([^_]+)_(.+)$/);
206
+ if (!match) throw new Error(`Invalid ONE ID: ${oneId}`);
207
+ const [_, type, backendId] = match;
208
+ return backendId;
209
+ };
210
+
211
+ // Backend ID → ONE ID
212
+ const backendIdToOneId = (type: string, backendId: string): string => {
213
+ return `mybackend_${type}_${backendId}`;
214
+ };
215
+
216
+ // Parse ONE ID (extract type and backend ID)
217
+ const parseOneId = (oneId: string): { type: string; backendId: string } => {
218
+ const match = oneId.match(/^mybackend_([^_]+)_(.+)$/);
219
+ if (!match) throw new Error(`Invalid ONE ID: ${oneId}`);
220
+ return { type: match[1], backendId: match[2] };
221
+ };
222
+ ```
223
+
224
+ ---
225
+
226
+ ## Step 4: Implement Status Mapping
227
+
228
+ ONE uses standard status values. Map them to your backend's status system:
229
+
230
+ ```typescript
231
+ // ONE Status Values
232
+ type ThingStatus = "draft" | "active" | "published" | "archived" | "inactive";
233
+
234
+ // Your Backend Mapping
235
+ const mapONEStatusToBackend = (status: ThingStatus): string => {
236
+ const mapping: Record<ThingStatus, string> = {
237
+ draft: "Draft", // Your backend's draft status
238
+ active: "Active", // Your backend's active status
239
+ published: "Published", // Your backend's published status
240
+ archived: "Archived", // Your backend's archived status
241
+ inactive: "Inactive", // Your backend's inactive status
242
+ };
243
+ return mapping[status];
244
+ };
245
+
246
+ const mapBackendStatusToONE = (backendStatus: string): ThingStatus => {
247
+ const mapping: Record<string, ThingStatus> = {
248
+ "Draft": "draft",
249
+ "In Progress": "active", // Map backend statuses to ONE statuses
250
+ "Published": "published",
251
+ "Deleted": "archived",
252
+ "Paused": "inactive",
253
+ };
254
+ return mapping[backendStatus] || "draft"; // Default to draft
255
+ };
256
+ ```
257
+
258
+ ---
259
+
260
+ ## Step 5: Implement Type Mapping
261
+
262
+ ONE has 66+ thing types. Map them to your backend's entity types:
263
+
264
+ ```typescript
265
+ // ONE Thing Types (subset)
266
+ type ThingType = "course" | "lesson" | "creator" | "blog_post" | "token" | ...;
267
+
268
+ // Your Backend Mapping
269
+ const mapONETypeToBackend = (type: ThingType): string => {
270
+ const mapping: Record<ThingType, string> = {
271
+ course: "courses", // Your backend's course entity
272
+ lesson: "lessons",
273
+ creator: "users",
274
+ blog_post: "articles",
275
+ token: "products",
276
+ // ... map all 66 types
277
+ };
278
+ return mapping[type] || "generic"; // Default fallback
279
+ };
280
+
281
+ const mapBackendTypeToONE = (backendType: string): ThingType => {
282
+ const mapping: Record<string, ThingType> = {
283
+ courses: "course",
284
+ lessons: "lesson",
285
+ users: "creator",
286
+ articles: "blog_post",
287
+ products: "token",
288
+ };
289
+ return mapping[backendType] || "unknown";
290
+ };
291
+ ```
292
+
293
+ ---
294
+
295
+ ## Step 6: Create Your Provider Class
296
+
297
+ ```typescript
298
+ // File: /frontend/src/providers/mybackend/MyBackendProvider.ts
299
+
300
+ import { Effect, Layer } from "effect";
301
+ import {
302
+ DataProvider,
303
+ DataProviderService,
304
+ ThingNotFoundError,
305
+ ThingCreateError,
306
+ // ... import all error types
307
+ type Thing,
308
+ type Connection,
309
+ // ... import all types
310
+ } from "../DataProvider";
311
+
312
+ // ============================================================================
313
+ // CONFIG
314
+ // ============================================================================
315
+
316
+ export interface MyBackendProviderConfig {
317
+ apiUrl: string;
318
+ apiKey: string;
319
+ organizationId: string;
320
+ // Add your backend-specific config
321
+ }
322
+
323
+ // ============================================================================
324
+ // PROVIDER IMPLEMENTATION
325
+ // ============================================================================
326
+
327
+ export const makeMyBackendProvider = (config: MyBackendProviderConfig): DataProvider => {
328
+ // Initialize your backend client
329
+ const client = new MyBackendClient(config.apiUrl, config.apiKey);
330
+
331
+ return {
332
+ // ===== THINGS =====
333
+ things: {
334
+ get: (id: string) =>
335
+ Effect.tryPromise({
336
+ try: async () => {
337
+ const { type, backendId } = parseOneId(id);
338
+ const backendEntity = await client.getEntity(type, backendId);
339
+ return mapBackendEntityToThing(backendEntity, type);
340
+ },
341
+ catch: (error) => new ThingNotFoundError(id, String(error)),
342
+ }),
343
+
344
+ list: (options?: ListThingsOptions) =>
345
+ Effect.tryPromise({
346
+ try: async () => {
347
+ if (!options?.type) {
348
+ throw new QueryError("Type required for listing");
349
+ }
350
+ const backendType = mapONETypeToBackend(options.type);
351
+ const entities = await client.listEntities(backendType, {
352
+ limit: options.limit,
353
+ offset: options.offset,
354
+ });
355
+ return entities.map(e => mapBackendEntityToThing(e, options.type!));
356
+ },
357
+ catch: (error) => new QueryError("Failed to list things", error),
358
+ }),
359
+
360
+ create: (input: CreateThingInput) =>
361
+ Effect.tryPromise({
362
+ try: async () => {
363
+ const backendType = mapONETypeToBackend(input.type);
364
+ const backendEntity = transformThingToBackendEntity(input);
365
+ const created = await client.createEntity(backendType, backendEntity);
366
+ return backendIdToOneId(input.type, created.id);
367
+ },
368
+ catch: (error) => new ThingCreateError(String(error), error),
369
+ }),
370
+
371
+ update: (id: string, input: UpdateThingInput) =>
372
+ Effect.tryPromise({
373
+ try: async () => {
374
+ const { type, backendId } = parseOneId(id);
375
+ const backendType = mapONETypeToBackend(type);
376
+ const updates = transformUpdatesToBackendFormat(input);
377
+ await client.updateEntity(backendType, backendId, updates);
378
+ },
379
+ catch: (error) => new ThingUpdateError(id, String(error), error),
380
+ }),
381
+
382
+ delete: (id: string) =>
383
+ Effect.tryPromise({
384
+ try: async () => {
385
+ const { type, backendId } = parseOneId(id);
386
+ const backendType = mapONETypeToBackend(type);
387
+ await client.deleteEntity(backendType, backendId);
388
+ },
389
+ catch: (error) => new ThingNotFoundError(id, String(error)),
390
+ }),
391
+ },
392
+
393
+ // ===== CONNECTIONS =====
394
+ connections: {
395
+ // Implement connection operations
396
+ // Use native backend relationships if available
397
+ // Otherwise use custom storage table
398
+ },
399
+
400
+ // ===== EVENTS =====
401
+ events: {
402
+ // Implement if backend supports event logging
403
+ // Otherwise delegate to Convex (hybrid approach)
404
+ },
405
+
406
+ // ===== KNOWLEDGE =====
407
+ knowledge: {
408
+ // Implement if backend supports vectors
409
+ // Otherwise delegate to Convex (hybrid approach)
410
+ },
411
+ };
412
+ };
413
+
414
+ // ============================================================================
415
+ // EFFECT LAYER
416
+ // ============================================================================
417
+
418
+ export const MyBackendProviderLive = (config: MyBackendProviderConfig) =>
419
+ Layer.succeed(DataProviderService, makeMyBackendProvider(config));
420
+
421
+ // ============================================================================
422
+ // FACTORY FUNCTION
423
+ // ============================================================================
424
+
425
+ export const myBackendProvider = (
426
+ apiUrl: string,
427
+ apiKey: string,
428
+ organizationId: string
429
+ ) => makeMyBackendProvider({ apiUrl, apiKey, organizationId });
430
+ ```
431
+
432
+ ---
433
+
434
+ ## Step 7: Implement Mappers
435
+
436
+ ### Backend Entity → ONE Thing
437
+
438
+ ```typescript
439
+ const mapBackendEntityToThing = (entity: BackendEntity, type: string): Thing => {
440
+ return {
441
+ _id: backendIdToOneId(type, entity.id),
442
+ type: type,
443
+ name: entity.name || entity.title || "Untitled",
444
+ organizationId: config.organizationId,
445
+ status: mapBackendStatusToONE(entity.status),
446
+ properties: {
447
+ // Store backend-specific fields
448
+ ...entity.customFields,
449
+ // Store original backend ID for reference
450
+ backendId: entity.id,
451
+ backendUrl: entity.url,
452
+ // Parse and merge any JSON properties
453
+ ...(entity.metadata ? JSON.parse(entity.metadata) : {}),
454
+ },
455
+ createdAt: new Date(entity.created_at).getTime(),
456
+ updatedAt: new Date(entity.updated_at).getTime(),
457
+ };
458
+ };
459
+ ```
460
+
461
+ ### ONE Thing → Backend Entity
462
+
463
+ ```typescript
464
+ const transformThingToBackendEntity = (input: CreateThingInput): BackendEntity => {
465
+ return {
466
+ name: input.name,
467
+ status: mapONEStatusToBackend(input.status || "draft"),
468
+ // Map common properties to backend fields
469
+ description: input.properties.content || input.properties.description,
470
+ price: input.properties.price,
471
+ duration: input.properties.duration,
472
+ // Store full properties as JSON for maximum flexibility
473
+ metadata: JSON.stringify(input.properties),
474
+ // Add organization tracking
475
+ organization_id: config.organizationId,
476
+ };
477
+ };
478
+ ```
479
+
480
+ ---
481
+
482
+ ## Step 8: Handle Properties Mapping
483
+
484
+ **Strategy 1: Full JSON Storage** (Recommended)
485
+
486
+ Store entire `properties` object as JSON in a single backend field:
487
+
488
+ ```typescript
489
+ // Backend entity structure
490
+ {
491
+ id: "123",
492
+ name: "Course Title",
493
+ status: "Published",
494
+ metadata: "{\"content\":\"...\",\"price\":99,\"duration\":3600}" // Full properties
495
+ }
496
+
497
+ // Advantages:
498
+ // - Maximum flexibility (no schema changes needed)
499
+ // - All properties preserved
500
+ // - Easy to implement
501
+
502
+ // Disadvantages:
503
+ // - Can't query/filter by individual properties
504
+ // - Large JSON blobs
505
+ ```
506
+
507
+ **Strategy 2: Mapped Fields** (Better UX)
508
+
509
+ Map common properties to native backend fields:
510
+
511
+ ```typescript
512
+ // Backend entity structure
513
+ {
514
+ id: "123",
515
+ name: "Course Title",
516
+ status: "Published",
517
+ description: "...", // Mapped from properties.content
518
+ price: 99, // Mapped from properties.price
519
+ duration: 3600, // Mapped from properties.duration
520
+ metadata: "{...}" // Remaining properties as JSON
521
+ }
522
+
523
+ // Advantages:
524
+ // - Can query/filter by common fields
525
+ // - Better backend UX
526
+ // - Smaller JSON blobs
527
+
528
+ // Disadvantages:
529
+ // - Requires field mapping logic
530
+ // - Backend schema must support common fields
531
+ ```
532
+
533
+ **Best Practice:** Use Strategy 2 (mapped fields) + full JSON fallback:
534
+
535
+ ```typescript
536
+ const transformPropertiesToBackend = (properties: Record<string, any>) => {
537
+ return {
538
+ // Map common fields
539
+ description: properties.content || properties.description,
540
+ price: properties.price,
541
+ duration: properties.duration,
542
+ difficulty: properties.difficulty,
543
+ // Store full properties as JSON
544
+ metadata: JSON.stringify(properties),
545
+ };
546
+ };
547
+
548
+ const extractPropertiesFromBackend = (entity: BackendEntity): Record<string, any> => {
549
+ // Start with JSON properties
550
+ const properties = entity.metadata ? JSON.parse(entity.metadata) : {};
551
+
552
+ // Override with mapped fields (these are source of truth)
553
+ if (entity.description) properties.content = entity.description;
554
+ if (entity.price !== undefined) properties.price = entity.price;
555
+ if (entity.duration !== undefined) properties.duration = entity.duration;
556
+ if (entity.difficulty) properties.difficulty = entity.difficulty;
557
+
558
+ return properties;
559
+ };
560
+ ```
561
+
562
+ ---
563
+
564
+ ## Step 9: Implement Error Handling
565
+
566
+ Use Effect.ts typed errors for all failure cases:
567
+
568
+ ```typescript
569
+ // Example: Get thing with detailed error handling
570
+
571
+ things: {
572
+ get: (id: string) =>
573
+ Effect.tryPromise({
574
+ try: async () => {
575
+ // Validate ID format
576
+ if (!id.startsWith("mybackend_")) {
577
+ throw new ThingNotFoundError(id, "Invalid ID format");
578
+ }
579
+
580
+ const { type, backendId } = parseOneId(id);
581
+
582
+ // Fetch from backend
583
+ let entity;
584
+ try {
585
+ entity = await client.getEntity(type, backendId);
586
+ } catch (error: any) {
587
+ if (error.status === 404) {
588
+ throw new ThingNotFoundError(id, "Entity not found in backend");
589
+ }
590
+ if (error.status === 401) {
591
+ throw new ThingNotFoundError(id, "Authentication failed");
592
+ }
593
+ throw error; // Re-throw other errors
594
+ }
595
+
596
+ // Validate entity
597
+ if (!entity) {
598
+ throw new ThingNotFoundError(id, "Entity is null");
599
+ }
600
+
601
+ // Transform to Thing
602
+ return mapBackendEntityToThing(entity, type);
603
+ },
604
+ catch: (error) => {
605
+ // Convert all errors to ThingNotFoundError
606
+ if (error instanceof ThingNotFoundError) return error;
607
+ return new ThingNotFoundError(id, String(error));
608
+ },
609
+ }),
610
+ }
611
+ ```
612
+
613
+ **Error Types to Use:**
614
+
615
+ - `ThingNotFoundError` - Entity doesn't exist
616
+ - `ThingCreateError` - Failed to create entity
617
+ - `ThingUpdateError` - Failed to update entity
618
+ - `ConnectionNotFoundError` - Relationship doesn't exist
619
+ - `ConnectionCreateError` - Failed to create relationship
620
+ - `EventCreateError` - Failed to log event
621
+ - `KnowledgeNotFoundError` - Knowledge doesn't exist
622
+ - `QueryError` - Generic query failure
623
+
624
+ ---
625
+
626
+ ## Step 10: Handle Hybrid Storage
627
+
628
+ If your backend doesn't support Events or Knowledge, use Convex:
629
+
630
+ ```typescript
631
+ // Hybrid Events Pattern
632
+
633
+ events: {
634
+ create: (input: CreateEventInput) =>
635
+ Effect.tryPromise({
636
+ try: async () => {
637
+ // Store event in Convex (not in your backend)
638
+ const convexUrl = config.convexUrl;
639
+ if (!convexUrl) {
640
+ throw new EventCreateError("Convex URL required for event storage");
641
+ }
642
+
643
+ const response = await fetch(`${convexUrl}/api/events`, {
644
+ method: "POST",
645
+ headers: { "Content-Type": "application/json" },
646
+ body: JSON.stringify({
647
+ ...input,
648
+ metadata: {
649
+ ...input.metadata,
650
+ provider: "mybackend",
651
+ originalId: input.targetId, // Link back to backend entity
652
+ },
653
+ }),
654
+ });
655
+
656
+ const result = await response.json();
657
+ return result.id;
658
+ },
659
+ catch: (error) => new EventCreateError(String(error), error),
660
+ }),
661
+
662
+ list: (options?: ListEventsOptions) =>
663
+ Effect.tryPromise({
664
+ try: async () => {
665
+ // Query events from Convex
666
+ const convexUrl = config.convexUrl;
667
+ if (!convexUrl) return [];
668
+
669
+ const params = new URLSearchParams({
670
+ provider: "mybackend",
671
+ targetId: options?.targetId || "",
672
+ });
673
+
674
+ const response = await fetch(`${convexUrl}/api/events?${params}`);
675
+ return response.json();
676
+ },
677
+ catch: (error) => new QueryError("Failed to list events", error),
678
+ }),
679
+
680
+ get: (id: string) =>
681
+ Effect.fail(
682
+ new QueryError("Use Convex for event retrieval")
683
+ ),
684
+ }
685
+ ```
686
+
687
+ ---
688
+
689
+ ## Step 11: Write Tests
690
+
691
+ ### Unit Tests
692
+
693
+ Test each operation in isolation:
694
+
695
+ ```typescript
696
+ // File: /frontend/src/providers/__tests__/MyBackendProvider.test.ts
697
+
698
+ import { describe, it, expect, beforeEach } from "vitest";
699
+ import { Effect } from "effect";
700
+ import { makeMyBackendProvider } from "../mybackend/MyBackendProvider";
701
+
702
+ describe("MyBackendProvider", () => {
703
+ let provider: DataProvider;
704
+
705
+ beforeEach(() => {
706
+ provider = makeMyBackendProvider({
707
+ apiUrl: "https://test.example.com",
708
+ apiKey: "test-key",
709
+ organizationId: "org_123",
710
+ });
711
+ });
712
+
713
+ describe("things.get", () => {
714
+ it("should get thing by ID", async () => {
715
+ const result = await Effect.runPromise(
716
+ provider.things.get("mybackend_course_123")
717
+ );
718
+
719
+ expect(result._id).toBe("mybackend_course_123");
720
+ expect(result.type).toBe("course");
721
+ expect(result.name).toBeTruthy();
722
+ });
723
+
724
+ it("should fail with ThingNotFoundError for invalid ID", async () => {
725
+ const result = Effect.runPromise(
726
+ provider.things.get("invalid_id")
727
+ );
728
+
729
+ await expect(result).rejects.toThrow("Invalid ID");
730
+ });
731
+ });
732
+
733
+ describe("things.list", () => {
734
+ it("should list things by type", async () => {
735
+ const result = await Effect.runPromise(
736
+ provider.things.list({ type: "course", limit: 10 })
737
+ );
738
+
739
+ expect(Array.isArray(result)).toBe(true);
740
+ expect(result.length).toBeLessThanOrEqual(10);
741
+ result.forEach(thing => {
742
+ expect(thing.type).toBe("course");
743
+ });
744
+ });
745
+ });
746
+
747
+ // ... more tests
748
+ });
749
+ ```
750
+
751
+ ### Integration Tests
752
+
753
+ Test with real backend (using test account):
754
+
755
+ ```typescript
756
+ // File: /frontend/tests/integration/mybackend-provider.test.ts
757
+
758
+ import { describe, it, expect } from "vitest";
759
+ import { Effect } from "effect";
760
+ import { makeMyBackendProvider } from "@/providers/mybackend/MyBackendProvider";
761
+
762
+ describe("MyBackendProvider Integration", () => {
763
+ const provider = makeMyBackendProvider({
764
+ apiUrl: process.env.TEST_BACKEND_URL!,
765
+ apiKey: process.env.TEST_BACKEND_API_KEY!,
766
+ organizationId: "test_org",
767
+ });
768
+
769
+ it("should create, get, update, and delete a thing", async () => {
770
+ // Create
771
+ const id = await Effect.runPromise(
772
+ provider.things.create({
773
+ type: "course",
774
+ name: "Test Course",
775
+ properties: { content: "Test content" },
776
+ status: "draft",
777
+ })
778
+ );
779
+
780
+ expect(id).toBeTruthy();
781
+
782
+ // Get
783
+ const thing = await Effect.runPromise(provider.things.get(id));
784
+ expect(thing.name).toBe("Test Course");
785
+
786
+ // Update
787
+ await Effect.runPromise(
788
+ provider.things.update(id, { name: "Updated Course" })
789
+ );
790
+
791
+ const updated = await Effect.runPromise(provider.things.get(id));
792
+ expect(updated.name).toBe("Updated Course");
793
+
794
+ // Delete
795
+ await Effect.runPromise(provider.things.delete(id));
796
+
797
+ // Verify deleted
798
+ const result = Effect.runPromise(provider.things.get(id));
799
+ await expect(result).rejects.toThrow();
800
+ });
801
+ });
802
+ ```
803
+
804
+ ---
805
+
806
+ ## Step 12: Document Your Provider
807
+
808
+ Create a setup guide for your provider:
809
+
810
+ ```markdown
811
+ # MyBackend Provider Setup Guide
812
+
813
+ ## Prerequisites
814
+
815
+ 1. MyBackend account with API access
816
+ 2. API key generated from MyBackend dashboard
817
+ 3. ONE Platform organization created
818
+
819
+ ## Installation
820
+
821
+ \`\`\`bash
822
+ npm install @mybackend/sdk
823
+ \`\`\`
824
+
825
+ ## Configuration
826
+
827
+ \`\`\`typescript
828
+ import { myBackendProvider } from "@/providers/mybackend/MyBackendProvider";
829
+
830
+ const provider = myBackendProvider(
831
+ "https://api.mybackend.com",
832
+ "your-api-key",
833
+ "your-org-id"
834
+ );
835
+ \`\`\`
836
+
837
+ ## Backend Setup
838
+
839
+ 1. Create required custom fields in MyBackend:
840
+ - `organization_id` (text field)
841
+ - `metadata` (JSON field)
842
+ - `status` (select field with values: Draft, Active, Published, Archived)
843
+
844
+ 2. Enable API access in MyBackend settings
845
+
846
+ 3. Configure webhooks (optional, for real-time updates)
847
+
848
+ ## Limitations
849
+
850
+ - Events: Stored in Convex (hybrid approach)
851
+ - Knowledge: Stored in Convex (no vector support)
852
+ - Rate Limits: 100 requests/minute
853
+
854
+ ## Testing
855
+
856
+ Run integration tests:
857
+ \`\`\`bash
858
+ TEST_BACKEND_URL=https://api.mybackend.com \
859
+ TEST_BACKEND_API_KEY=your-test-key \
860
+ npm test integration/mybackend-provider.test.ts
861
+ \`\`\`
862
+ ```
863
+
864
+ ---
865
+
866
+ ## Common Patterns
867
+
868
+ ### Pattern 1: Pagination
869
+
870
+ ```typescript
871
+ list: (options?: ListThingsOptions) =>
872
+ Effect.tryPromise({
873
+ try: async () => {
874
+ const limit = options?.limit || 10;
875
+ const offset = options?.offset || 0;
876
+
877
+ // Convert to backend pagination format
878
+ const page = Math.floor(offset / limit) + 1;
879
+
880
+ const response = await client.list({
881
+ page,
882
+ per_page: limit,
883
+ status: options?.status,
884
+ });
885
+
886
+ return response.items.map(item => mapToThing(item));
887
+ },
888
+ catch: (error) => new QueryError("Failed to list", error),
889
+ }),
890
+ ```
891
+
892
+ ### Pattern 2: Batching
893
+
894
+ ```typescript
895
+ const batchGet = (ids: string[]) =>
896
+ Effect.tryPromise({
897
+ try: async () => {
898
+ // Backend supports batch fetch
899
+ const backendIds = ids.map(id => parseOneId(id).backendId);
900
+ const entities = await client.batchGet(backendIds);
901
+ return entities.map((e, i) => mapToThing(e, parseOneId(ids[i]).type));
902
+ },
903
+ catch: (error) => new QueryError("Batch get failed", error),
904
+ });
905
+ ```
906
+
907
+ ### Pattern 3: Caching
908
+
909
+ ```typescript
910
+ const cache = new Map<string, { thing: Thing; expiry: number }>();
911
+
912
+ things: {
913
+ get: (id: string) =>
914
+ Effect.tryPromise({
915
+ try: async () => {
916
+ // Check cache
917
+ const cached = cache.get(id);
918
+ if (cached && cached.expiry > Date.now()) {
919
+ return cached.thing;
920
+ }
921
+
922
+ // Fetch from backend
923
+ const thing = await fetchFromBackend(id);
924
+
925
+ // Store in cache (5 minute TTL)
926
+ cache.set(id, {
927
+ thing,
928
+ expiry: Date.now() + 5 * 60 * 1000,
929
+ });
930
+
931
+ return thing;
932
+ },
933
+ catch: (error) => new ThingNotFoundError(id, String(error)),
934
+ }),
935
+ }
936
+ ```
937
+
938
+ ### Pattern 4: Rate Limiting
939
+
940
+ ```typescript
941
+ import { RateLimiter } from "limiter";
942
+
943
+ const limiter = new RateLimiter({
944
+ tokensPerInterval: 100,
945
+ interval: "minute",
946
+ });
947
+
948
+ const withRateLimit = async <T>(fn: () => Promise<T>): Promise<T> => {
949
+ await limiter.removeTokens(1);
950
+ return fn();
951
+ };
952
+
953
+ things: {
954
+ get: (id: string) =>
955
+ Effect.tryPromise({
956
+ try: () => withRateLimit(() => client.getEntity(id)),
957
+ catch: (error) => new ThingNotFoundError(id, String(error)),
958
+ }),
959
+ }
960
+ ```
961
+
962
+ ---
963
+
964
+ ## Troubleshooting
965
+
966
+ ### Issue: TypeScript errors in Effect types
967
+
968
+ **Solution:** Ensure Effect.ts version matches:
969
+
970
+ ```json
971
+ {
972
+ "dependencies": {
973
+ "effect": "^3.0.0"
974
+ }
975
+ }
976
+ ```
977
+
978
+ ### Issue: ID conversion fails
979
+
980
+ **Solution:** Add validation to ID converters:
981
+
982
+ ```typescript
983
+ const parseOneId = (oneId: string): { type: string; backendId: string } => {
984
+ const match = oneId.match(/^mybackend_([^_]+)_(.+)$/);
985
+ if (!match) {
986
+ console.error(`Invalid ONE ID format: ${oneId}`);
987
+ throw new Error(`Invalid ONE ID: ${oneId}`);
988
+ }
989
+ return { type: match[1], backendId: match[2] };
990
+ };
991
+ ```
992
+
993
+ ### Issue: Properties not mapping correctly
994
+
995
+ **Solution:** Log before/after mapping:
996
+
997
+ ```typescript
998
+ const mapToThing = (entity: BackendEntity): Thing => {
999
+ console.log("Backend entity:", entity);
1000
+ const thing = {
1001
+ _id: backendIdToOneId(entity.type, entity.id),
1002
+ // ... mapping logic
1003
+ };
1004
+ console.log("Mapped thing:", thing);
1005
+ return thing;
1006
+ };
1007
+ ```
1008
+
1009
+ ### Issue: Backend API rate limits exceeded
1010
+
1011
+ **Solution:** Implement request batching or caching:
1012
+
1013
+ ```typescript
1014
+ // Batch multiple gets into single request
1015
+ const batchCache: Map<string, Promise<Thing>> = new Map();
1016
+
1017
+ things: {
1018
+ get: (id: string) => {
1019
+ if (!batchCache.has(id)) {
1020
+ batchCache.set(id, fetchThing(id));
1021
+ setTimeout(() => batchCache.delete(id), 100); // Clear after 100ms
1022
+ }
1023
+ return batchCache.get(id)!;
1024
+ }
1025
+ }
1026
+ ```
1027
+
1028
+ ---
1029
+
1030
+ ## Checklist
1031
+
1032
+ Before releasing your provider, verify:
1033
+
1034
+ - [ ] All 4 dimensions implemented (or hybrid approach documented)
1035
+ - [ ] ID conversion works both ways (ONE ↔ Backend)
1036
+ - [ ] Status mapping covers all ONE statuses
1037
+ - [ ] Type mapping covers common thing types
1038
+ - [ ] Error handling uses typed Effect errors
1039
+ - [ ] Properties mapping preserves all data
1040
+ - [ ] Organization isolation enforced
1041
+ - [ ] Unit tests cover all operations (80%+ coverage)
1042
+ - [ ] Integration tests pass with real backend
1043
+ - [ ] Setup guide documented
1044
+ - [ ] Limitations clearly stated
1045
+ - [ ] Performance benchmarked
1046
+ - [ ] Rate limiting implemented (if needed)
1047
+
1048
+ ---
1049
+
1050
+ ## Next Steps
1051
+
1052
+ 1. **Share your provider:** Submit to ONE Platform provider registry
1053
+ 2. **Get feedback:** Test with real users
1054
+ 3. **Iterate:** Add features based on feedback
1055
+ 4. **Maintain:** Keep up with backend API changes
1056
+
1057
+ ---
1058
+
1059
+ **Need Help?**
1060
+ - Read existing providers: `/frontend/src/providers/convex/`, `/notion/`, `/wordpress/`
1061
+ - Review ontology: `/one/knowledge/ontology.md`
1062
+ - Ask questions: GitHub Discussions or Discord
1063
+
1064
+ **Happy Provider Building!** 🚀