@object-ui/core 3.3.0 → 3.3.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.
Files changed (101) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +20 -1
  3. package/dist/actions/ActionRunner.d.ts +9 -0
  4. package/dist/actions/ActionRunner.js +41 -4
  5. package/dist/adapters/ValueDataSource.js +3 -1
  6. package/dist/registry/Registry.d.ts +47 -0
  7. package/dist/registry/Registry.js +92 -0
  8. package/dist/utils/filter-converter.js +25 -5
  9. package/package.json +32 -8
  10. package/.turbo/turbo-build.log +0 -4
  11. package/src/__benchmarks__/core.bench.ts +0 -64
  12. package/src/__tests__/protocols/DndProtocol.test.ts +0 -186
  13. package/src/__tests__/protocols/KeyboardProtocol.test.ts +0 -177
  14. package/src/__tests__/protocols/NotificationProtocol.test.ts +0 -142
  15. package/src/__tests__/protocols/ResponsiveProtocol.test.ts +0 -176
  16. package/src/__tests__/protocols/SharingProtocol.test.ts +0 -188
  17. package/src/actions/ActionEngine.ts +0 -268
  18. package/src/actions/ActionRunner.ts +0 -717
  19. package/src/actions/TransactionManager.ts +0 -521
  20. package/src/actions/UndoManager.ts +0 -215
  21. package/src/actions/__tests__/ActionEngine.test.ts +0 -206
  22. package/src/actions/__tests__/ActionRunner.params.test.ts +0 -134
  23. package/src/actions/__tests__/ActionRunner.test.ts +0 -711
  24. package/src/actions/__tests__/TransactionManager.test.ts +0 -447
  25. package/src/actions/__tests__/UndoManager.test.ts +0 -320
  26. package/src/actions/index.ts +0 -12
  27. package/src/adapters/ApiDataSource.ts +0 -376
  28. package/src/adapters/README.md +0 -180
  29. package/src/adapters/ValueDataSource.ts +0 -459
  30. package/src/adapters/__tests__/ApiDataSource.test.ts +0 -418
  31. package/src/adapters/__tests__/ValueDataSource.test.ts +0 -571
  32. package/src/adapters/__tests__/resolveDataSource.test.ts +0 -144
  33. package/src/adapters/index.ts +0 -15
  34. package/src/adapters/resolveDataSource.ts +0 -79
  35. package/src/builder/__tests__/schema-builder.test.ts +0 -235
  36. package/src/builder/schema-builder.ts +0 -584
  37. package/src/data-scope/DataScopeManager.ts +0 -269
  38. package/src/data-scope/ViewDataProvider.ts +0 -282
  39. package/src/data-scope/__tests__/DataScopeManager.test.ts +0 -211
  40. package/src/data-scope/__tests__/ViewDataProvider.test.ts +0 -270
  41. package/src/data-scope/index.ts +0 -24
  42. package/src/errors/__tests__/errors.test.ts +0 -292
  43. package/src/errors/index.ts +0 -269
  44. package/src/evaluator/ExpressionCache.ts +0 -206
  45. package/src/evaluator/ExpressionContext.ts +0 -118
  46. package/src/evaluator/ExpressionEvaluator.ts +0 -315
  47. package/src/evaluator/FormulaFunctions.ts +0 -398
  48. package/src/evaluator/SafeExpressionParser.ts +0 -893
  49. package/src/evaluator/__tests__/ExpressionCache.test.ts +0 -135
  50. package/src/evaluator/__tests__/ExpressionContext.test.ts +0 -110
  51. package/src/evaluator/__tests__/ExpressionEvaluator.test.ts +0 -558
  52. package/src/evaluator/__tests__/FormulaFunctions.test.ts +0 -447
  53. package/src/evaluator/index.ts +0 -13
  54. package/src/index.ts +0 -38
  55. package/src/protocols/DndProtocol.ts +0 -168
  56. package/src/protocols/KeyboardProtocol.ts +0 -181
  57. package/src/protocols/NotificationProtocol.ts +0 -150
  58. package/src/protocols/ResponsiveProtocol.ts +0 -210
  59. package/src/protocols/SharingProtocol.ts +0 -185
  60. package/src/protocols/index.ts +0 -13
  61. package/src/query/__tests__/query-ast.test.ts +0 -211
  62. package/src/query/__tests__/window-functions.test.ts +0 -275
  63. package/src/query/index.ts +0 -7
  64. package/src/query/query-ast.ts +0 -341
  65. package/src/registry/PluginScopeImpl.ts +0 -259
  66. package/src/registry/PluginSystem.ts +0 -206
  67. package/src/registry/Registry.ts +0 -219
  68. package/src/registry/WidgetRegistry.ts +0 -316
  69. package/src/registry/__tests__/PluginSystem.test.ts +0 -309
  70. package/src/registry/__tests__/Registry.test.ts +0 -293
  71. package/src/registry/__tests__/WidgetRegistry.test.ts +0 -321
  72. package/src/registry/__tests__/plugin-scope-integration.test.ts +0 -283
  73. package/src/theme/ThemeEngine.ts +0 -530
  74. package/src/theme/__tests__/ThemeEngine.test.ts +0 -668
  75. package/src/theme/index.ts +0 -24
  76. package/src/types/index.ts +0 -21
  77. package/src/utils/__tests__/debug-collector.test.ts +0 -102
  78. package/src/utils/__tests__/debug.test.ts +0 -134
  79. package/src/utils/__tests__/expand-fields.test.ts +0 -120
  80. package/src/utils/__tests__/extract-records.test.ts +0 -50
  81. package/src/utils/__tests__/filter-converter.test.ts +0 -118
  82. package/src/utils/__tests__/merge-views-into-objects.test.ts +0 -110
  83. package/src/utils/__tests__/normalize-quick-filter.test.ts +0 -123
  84. package/src/utils/debug-collector.ts +0 -100
  85. package/src/utils/debug.ts +0 -148
  86. package/src/utils/expand-fields.ts +0 -76
  87. package/src/utils/extract-records.ts +0 -33
  88. package/src/utils/filter-converter.ts +0 -133
  89. package/src/utils/merge-views-into-objects.ts +0 -36
  90. package/src/utils/normalize-quick-filter.ts +0 -78
  91. package/src/validation/__tests__/object-validation-engine.test.ts +0 -567
  92. package/src/validation/__tests__/schema-validator.test.ts +0 -118
  93. package/src/validation/__tests__/validation-engine.test.ts +0 -102
  94. package/src/validation/index.ts +0 -10
  95. package/src/validation/schema-validator.ts +0 -344
  96. package/src/validation/validation-engine.ts +0 -528
  97. package/src/validation/validators/index.ts +0 -25
  98. package/src/validation/validators/object-validation-engine.ts +0 -722
  99. package/tsconfig.json +0 -15
  100. package/tsconfig.tsbuildinfo +0 -1
  101. package/vitest.config.ts +0 -2
@@ -1,180 +0,0 @@
1
- # Data Source Adapters
2
-
3
- This directory contains data source adapters that bridge various backend protocols with the ObjectUI DataSource interface.
4
-
5
- ## ObjectStack Adapter
6
-
7
- The `ObjectStackAdapter` provides seamless integration with ObjectStack Protocol servers.
8
-
9
- ### Features
10
-
11
- - ✅ Full CRUD operations (find, findOne, create, update, delete)
12
- - ✅ Bulk operations (createMany, updateMany, deleteMany)
13
- - ✅ Auto-discovery of server capabilities
14
- - ✅ Query parameter translation (OData-style → ObjectStack)
15
- - ✅ Proper error handling
16
- - ✅ TypeScript types
17
-
18
- ### Usage
19
-
20
- ```typescript
21
- import { createObjectStackAdapter } from '@object-ui/core';
22
-
23
- // Create the adapter
24
- const dataSource = createObjectStackAdapter({
25
- baseUrl: 'https://api.example.com',
26
- token: 'your-auth-token', // Optional
27
- });
28
-
29
- // Use it with ObjectUI components
30
- const schema = {
31
- type: 'data-table',
32
- dataSource,
33
- resource: 'users',
34
- columns: [
35
- { header: 'Name', accessorKey: 'name' },
36
- { header: 'Email', accessorKey: 'email' },
37
- ]
38
- };
39
- ```
40
-
41
- ### Advanced Usage
42
-
43
- ```typescript
44
- import { ObjectStackAdapter } from '@object-ui/core';
45
-
46
- const adapter = new ObjectStackAdapter({
47
- baseUrl: 'https://api.example.com',
48
- token: process.env.API_TOKEN,
49
- fetch: customFetch // Optional: use custom fetch (e.g., Next.js fetch)
50
- });
51
-
52
- // Manually connect (optional, auto-connects on first request)
53
- await adapter.connect();
54
-
55
- // Query with filters (MongoDB-like operators)
56
- const result = await adapter.find('tasks', {
57
- $filter: {
58
- status: 'active',
59
- priority: { $gte: 2 }
60
- },
61
- $orderby: { createdAt: 'desc' },
62
- $top: 20,
63
- $skip: 0
64
- });
65
-
66
- // Access the underlying client for advanced operations
67
- const client = adapter.getClient();
68
- const metadata = await client.meta.getObject('task');
69
- ```
70
-
71
- ### Filter Conversion
72
-
73
- The adapter automatically converts MongoDB-like filter operators to **ObjectStack FilterNode AST format**. This ensures compatibility with the latest ObjectStack Protocol (v0.1.2+).
74
-
75
- #### Supported Filter Operators
76
-
77
- | MongoDB Operator | ObjectStack Operator | Example |
78
- |------------------|---------------------|---------|
79
- | `$eq` or simple value | `=` | `{ status: 'active' }` → `['status', '=', 'active']` |
80
- | `$ne` | `!=` | `{ status: { $ne: 'archived' } }` → `['status', '!=', 'archived']` |
81
- | `$gt` | `>` | `{ age: { $gt: 18 } }` → `['age', '>', 18]` |
82
- | `$gte` | `>=` | `{ age: { $gte: 18 } }` → `['age', '>=', 18]` |
83
- | `$lt` | `<` | `{ age: { $lt: 65 } }` → `['age', '<', 65]` |
84
- | `$lte` | `<=` | `{ age: { $lte: 65 } }` → `['age', '<=', 65]` |
85
- | `$in` | `in` | `{ status: { $in: ['active', 'pending'] } }` → `['status', 'in', ['active', 'pending']]` |
86
- | `$nin` / `$notin` | `notin` | `{ status: { $nin: ['archived'] } }` → `['status', 'notin', ['archived']]` |
87
- | `$contains` / `$regex` | `contains` | `{ name: { $contains: 'John' } }` → `['name', 'contains', 'John']` |
88
- | `$startswith` | `startswith` | `{ email: { $startswith: 'admin' } }` → `['email', 'startswith', 'admin']` |
89
- | `$between` | `between` | `{ age: { $between: [18, 65] } }` → `['age', 'between', [18, 65]]` |
90
-
91
- #### Complex Filter Examples
92
-
93
- **Multiple conditions** are combined with `'and'`:
94
-
95
- ```typescript
96
- // Input
97
- $filter: {
98
- age: { $gte: 18, $lte: 65 },
99
- status: 'active'
100
- }
101
-
102
- // Converted to AST
103
- ['and',
104
- ['age', '>=', 18],
105
- ['age', '<=', 65],
106
- ['status', '=', 'active']
107
- ]
108
- ```
109
-
110
- ### Query Parameter Mapping
111
-
112
- The adapter automatically converts ObjectUI query parameters (OData-style) to ObjectStack protocol:
113
-
114
- | ObjectUI ($) | ObjectStack | Description |
115
- |--------------|-------------|-------------|
116
- | `$select` | `select` | Field selection |
117
- | `$filter` | `filters` (AST) | Filter conditions (converted to FilterNode AST) |
118
- | `$orderby` | `sort` | Sort order |
119
- | `$skip` | `skip` | Pagination offset |
120
- | `$top` | `top` | Limit records |
121
-
122
- ### Example with Sorting
123
-
124
- ```typescript
125
- // OData-style
126
- await dataSource.find('users', {
127
- $orderby: {
128
- createdAt: 'desc',
129
- name: 'asc'
130
- }
131
- });
132
-
133
- // Converted to ObjectStack: ['-createdAt', 'name']
134
- ```
135
-
136
- ## Creating Custom Adapters
137
-
138
- To create a custom adapter, implement the `DataSource<T>` interface:
139
-
140
- ```typescript
141
- import type { DataSource, QueryParams, QueryResult } from '@object-ui/types';
142
-
143
- export class MyCustomAdapter<T = any> implements DataSource<T> {
144
- async find(resource: string, params?: QueryParams): Promise<QueryResult<T>> {
145
- // Your implementation
146
- }
147
-
148
- async findOne(resource: string, id: string | number): Promise<T | null> {
149
- // Your implementation
150
- }
151
-
152
- async create(resource: string, data: Partial<T>): Promise<T> {
153
- // Your implementation
154
- }
155
-
156
- async update(resource: string, id: string | number, data: Partial<T>): Promise<T> {
157
- // Your implementation
158
- }
159
-
160
- async delete(resource: string, id: string | number): Promise<boolean> {
161
- // Your implementation
162
- }
163
-
164
- // Optional: bulk operations
165
- async bulk?(resource: string, operation: string, data: Partial<T>[]): Promise<T[]> {
166
- // Your implementation
167
- }
168
- }
169
- ```
170
-
171
- ## Available Adapters
172
-
173
- - **ObjectStackAdapter** - For ObjectStack Protocol servers
174
- - More adapters coming soon (REST, GraphQL, Supabase, Firebase, etc.)
175
-
176
- ## Related Packages
177
-
178
- - `@objectstack/client` - ObjectStack Client SDK
179
- - `@objectstack/spec` - ObjectStack Protocol Specification
180
- - `@object-ui/types` - ObjectUI Type Definitions
@@ -1,459 +0,0 @@
1
- /**
2
- * ObjectUI — ValueDataSource
3
- * Copyright (c) 2024-present ObjectStack Inc.
4
- *
5
- * This source code is licensed under the MIT license found in the
6
- * LICENSE file in the root directory of this source tree.
7
- *
8
- * A DataSource adapter for the `provider: 'value'` ViewData mode.
9
- * Operates entirely on an in-memory array — no network requests.
10
- */
11
-
12
- import type {
13
- DataSource,
14
- MutationEvent,
15
- QueryParams,
16
- QueryResult,
17
- AggregateParams,
18
- AggregateResult,
19
- } from '@object-ui/types';
20
-
21
- // ---------------------------------------------------------------------------
22
- // Configuration
23
- // ---------------------------------------------------------------------------
24
-
25
- export interface ValueDataSourceConfig<T = any> {
26
- /** The static data array */
27
- items: T[];
28
- /** Optional ID field name for findOne/update/delete (defaults to 'id' then '_id') */
29
- idField?: string;
30
- }
31
-
32
- // ---------------------------------------------------------------------------
33
- // Helpers
34
- // ---------------------------------------------------------------------------
35
-
36
- /** Resolve the ID of a record given possible field names */
37
- function getRecordId(record: any, idField?: string): string | number | undefined {
38
- if (idField) return record[idField];
39
- return record.id ?? record._id;
40
- }
41
-
42
- /**
43
- * Evaluate an AST-format filter node against a record.
44
- * Supports conditions like ['field', 'op', value] and logical
45
- * combinations like ['and', ...conditions] or ['or', ...conditions].
46
- */
47
- function matchesASTFilter(record: any, filterNode: any[]): boolean {
48
- if (!filterNode || filterNode.length === 0) return true;
49
-
50
- const head = filterNode[0];
51
-
52
- // Logical operators: ['and', ...conditions] or ['or', ...conditions]
53
- if (head === 'and') {
54
- return filterNode.slice(1).every((sub: any) => matchesASTFilter(record, sub));
55
- }
56
- if (head === 'or') {
57
- return filterNode.slice(1).some((sub: any) => matchesASTFilter(record, sub));
58
- }
59
-
60
- // Condition node: [field, operator, value]
61
- if (filterNode.length === 3 && typeof head === 'string') {
62
- const [field, operator, target] = filterNode;
63
- const value = record[field];
64
-
65
- switch (operator) {
66
- case '=':
67
- return value === target;
68
- case '!=':
69
- return value !== target;
70
- case '>':
71
- return value > target;
72
- case '>=':
73
- return value >= target;
74
- case '<':
75
- return value < target;
76
- case '<=':
77
- return value <= target;
78
- case 'in':
79
- return Array.isArray(target) && target.includes(value);
80
- case 'not in':
81
- case 'notin': // alias used by convertFiltersToAST
82
- return Array.isArray(target) && !target.includes(value);
83
- case 'contains': {
84
- const lv = typeof value === 'string' ? value.toLowerCase() : '';
85
- return typeof value === 'string' && lv.includes(String(target).toLowerCase());
86
- }
87
- case 'notcontains': {
88
- const lv = typeof value === 'string' ? value.toLowerCase() : '';
89
- return typeof value === 'string' && !lv.includes(String(target).toLowerCase());
90
- }
91
- case 'startswith': {
92
- const lv = typeof value === 'string' ? value.toLowerCase() : '';
93
- return typeof value === 'string' && lv.startsWith(String(target).toLowerCase());
94
- }
95
- case 'between':
96
- return Array.isArray(target) && target.length === 2 && value >= target[0] && value <= target[1];
97
- default:
98
- return true;
99
- }
100
- }
101
-
102
- return true;
103
- }
104
-
105
- /**
106
- * Simple in-memory filter evaluation.
107
- * Supports flat key-value equality and basic operators ($gt, $gte, $lt, $lte, $ne, $in).
108
- */
109
- function matchesFilter(record: any, filter: Record<string, any>): boolean {
110
- for (const [key, condition] of Object.entries(filter)) {
111
- const value = record[key];
112
-
113
- if (condition && typeof condition === 'object' && !Array.isArray(condition)) {
114
- // Operator-based filter
115
- for (const [op, target] of Object.entries(condition)) {
116
- switch (op) {
117
- case '$gt':
118
- if (!(value > (target as any))) return false;
119
- break;
120
- case '$gte':
121
- if (!(value >= (target as any))) return false;
122
- break;
123
- case '$lt':
124
- if (!(value < (target as any))) return false;
125
- break;
126
- case '$lte':
127
- if (!(value <= (target as any))) return false;
128
- break;
129
- case '$ne':
130
- if (value === target) return false;
131
- break;
132
- case '$in':
133
- if (!Array.isArray(target) || !target.includes(value)) return false;
134
- break;
135
- case '$contains':
136
- if (typeof value !== 'string' || !value.toLowerCase().includes(String(target).toLowerCase())) return false;
137
- break;
138
- default:
139
- break;
140
- }
141
- }
142
- } else {
143
- // Simple equality
144
- if (value !== condition) return false;
145
- }
146
- }
147
- return true;
148
- }
149
-
150
- /** Apply sort ordering to an array (returns a new sorted array) */
151
- function applySort<T>(
152
- data: T[],
153
- orderby?: QueryParams['$orderby'],
154
- ): T[] {
155
- if (!orderby) return data;
156
-
157
- // Normalize to array of { field, order }
158
- let sorts: Array<{ field: string; order: 'asc' | 'desc' }> = [];
159
-
160
- if (Array.isArray(orderby)) {
161
- sorts = orderby.map((item) => {
162
- if (typeof item === 'string') {
163
- if (item.startsWith('-')) {
164
- return { field: item.slice(1), order: 'desc' as const };
165
- }
166
- return { field: item, order: 'asc' as const };
167
- }
168
- return { field: item.field, order: (item.order ?? 'asc') as 'asc' | 'desc' };
169
- });
170
- } else if (typeof orderby === 'object') {
171
- sorts = Object.entries(orderby).map(([field, order]) => ({
172
- field,
173
- order: order as 'asc' | 'desc',
174
- }));
175
- }
176
-
177
- if (sorts.length === 0) return data;
178
-
179
- return [...data].sort((a: any, b: any) => {
180
- for (const { field, order } of sorts) {
181
- const av = a[field];
182
- const bv = b[field];
183
- if (av === bv) continue;
184
- if (av == null) return order === 'asc' ? -1 : 1;
185
- if (bv == null) return order === 'asc' ? 1 : -1;
186
- const cmp = av < bv ? -1 : 1;
187
- return order === 'asc' ? cmp : -cmp;
188
- }
189
- return 0;
190
- });
191
- }
192
-
193
- /** Pick specific fields from a record */
194
- function selectFields<T>(record: T, fields?: string[]): T {
195
- if (!fields || fields.length === 0) return record;
196
- const out: any = {};
197
- for (const f of fields) {
198
- if (f in (record as any)) {
199
- out[f] = (record as any)[f];
200
- }
201
- }
202
- return out as T;
203
- }
204
-
205
- // ---------------------------------------------------------------------------
206
- // ValueDataSource
207
- // ---------------------------------------------------------------------------
208
-
209
- /**
210
- * ValueDataSource — an in-memory DataSource backed by a static array.
211
- *
212
- * Used when `ViewData.provider === 'value'`. All operations are synchronous
213
- * (but wrapped in Promises to satisfy the DataSource interface). Supports
214
- * basic filter, sort, pagination, and CRUD operations.
215
- *
216
- * @example
217
- * ```ts
218
- * const ds = new ValueDataSource({
219
- * items: [
220
- * { id: '1', name: 'Alice', age: 30 },
221
- * { id: '2', name: 'Bob', age: 25 },
222
- * ],
223
- * });
224
- *
225
- * const result = await ds.find('users', { $filter: { age: { $gt: 26 } } });
226
- * // result.data === [{ id: '1', name: 'Alice', age: 30 }]
227
- * ```
228
- */
229
- export class ValueDataSource<T = any> implements DataSource<T> {
230
- private items: T[];
231
- private idField: string | undefined;
232
- private mutationListeners = new Set<(event: MutationEvent<T>) => void>();
233
-
234
- constructor(config: ValueDataSourceConfig<T>) {
235
- // Deep clone to prevent external mutation
236
- this.items = JSON.parse(JSON.stringify(config.items));
237
- this.idField = config.idField;
238
- }
239
-
240
- /** Notify all mutation subscribers */
241
- private emitMutation(event: MutationEvent<T>): void {
242
- for (const listener of this.mutationListeners) {
243
- try { listener(event); } catch (err) { console.warn('ValueDataSource: mutation listener error', err); }
244
- }
245
- }
246
-
247
- // -----------------------------------------------------------------------
248
- // DataSource interface
249
- // -----------------------------------------------------------------------
250
-
251
- async find(_resource: string, params?: QueryParams): Promise<QueryResult<T>> {
252
- let result = [...this.items];
253
-
254
- // Filter — support both MongoDB-style objects and AST-format arrays
255
- if (params?.$filter) {
256
- if (Array.isArray(params.$filter) && params.$filter.length > 0) {
257
- result = result.filter((r) => matchesASTFilter(r, params.$filter as any[]));
258
- } else if (!Array.isArray(params.$filter) && Object.keys(params.$filter).length > 0) {
259
- result = result.filter((r) => matchesFilter(r, params.$filter!));
260
- }
261
- }
262
-
263
- // Search (simple text search across all string fields)
264
- if (params?.$search) {
265
- const q = params.$search.toLowerCase();
266
- result = result.filter((r) =>
267
- Object.values(r as any).some(
268
- (v) => typeof v === 'string' && v.toLowerCase().includes(q),
269
- ),
270
- );
271
- }
272
-
273
- const totalCount = result.length;
274
-
275
- // Sort
276
- result = applySort(result, params?.$orderby);
277
-
278
- // Pagination
279
- const skip = params?.$skip ?? 0;
280
- const top = params?.$top;
281
- if (skip > 0) result = result.slice(skip);
282
- if (top !== undefined) result = result.slice(0, top);
283
-
284
- // Select
285
- if (params?.$select?.length) {
286
- result = result.map((r) => selectFields(r, params.$select));
287
- }
288
-
289
- return {
290
- data: result,
291
- total: totalCount,
292
- hasMore: skip + (top ?? result.length) < totalCount,
293
- };
294
- }
295
-
296
- async findOne(
297
- _resource: string,
298
- id: string | number,
299
- params?: QueryParams,
300
- ): Promise<T | null> {
301
- const record = this.items.find(
302
- (r) => String(getRecordId(r, this.idField)) === String(id),
303
- );
304
- if (!record) return null;
305
-
306
- if (params?.$select?.length) {
307
- return selectFields(record, params.$select);
308
- }
309
- return { ...record };
310
- }
311
-
312
- async create(_resource: string, data: Partial<T>): Promise<T> {
313
- const record = { ...data } as T;
314
- // Auto-generate an ID if missing
315
- if (!getRecordId(record, this.idField)) {
316
- const field = this.idField ?? 'id';
317
- (record as any)[field] = `auto_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
318
- }
319
- this.items.push(record);
320
- this.emitMutation({ type: 'create', resource: _resource, record: { ...record } });
321
- return { ...record };
322
- }
323
-
324
- async update(
325
- _resource: string,
326
- id: string | number,
327
- data: Partial<T>,
328
- ): Promise<T> {
329
- const index = this.items.findIndex(
330
- (r) => String(getRecordId(r, this.idField)) === String(id),
331
- );
332
- if (index === -1) {
333
- throw new Error(`ValueDataSource: Record with id "${id}" not found`);
334
- }
335
- this.items[index] = { ...this.items[index], ...data };
336
- this.emitMutation({ type: 'update', resource: _resource, id, record: { ...this.items[index] } });
337
- return { ...this.items[index] };
338
- }
339
-
340
- async delete(_resource: string, id: string | number): Promise<boolean> {
341
- const index = this.items.findIndex(
342
- (r) => String(getRecordId(r, this.idField)) === String(id),
343
- );
344
- if (index === -1) return false;
345
- this.items.splice(index, 1);
346
- this.emitMutation({ type: 'delete', resource: _resource, id });
347
- return true;
348
- }
349
-
350
- async bulk(
351
- _resource: string,
352
- operation: 'create' | 'update' | 'delete',
353
- data: Partial<T>[],
354
- ): Promise<T[]> {
355
- const results: T[] = [];
356
- for (const item of data) {
357
- switch (operation) {
358
- case 'create':
359
- results.push(await this.create(_resource, item));
360
- break;
361
- case 'update': {
362
- const id = getRecordId(item, this.idField);
363
- if (id !== undefined) {
364
- results.push(await this.update(_resource, id, item));
365
- }
366
- break;
367
- }
368
- case 'delete': {
369
- const id = getRecordId(item, this.idField);
370
- if (id !== undefined) {
371
- await this.delete(_resource, id);
372
- }
373
- break;
374
- }
375
- }
376
- }
377
- return results;
378
- }
379
-
380
- async getObjectSchema(_objectName: string): Promise<any> {
381
- // Infer a minimal schema from the first item
382
- if (this.items.length === 0) return { name: _objectName, fields: {} };
383
-
384
- const sample = this.items[0];
385
- const fields: Record<string, any> = {};
386
- for (const [key, value] of Object.entries(sample as any)) {
387
- fields[key] = { type: typeof value };
388
- }
389
- return { name: _objectName, fields };
390
- }
391
-
392
- async getView(_objectName: string, _viewId: string): Promise<any | null> {
393
- return null;
394
- }
395
-
396
- async getApp(_appId: string): Promise<any | null> {
397
- return null;
398
- }
399
-
400
- async aggregate(_resource: string, params: AggregateParams): Promise<AggregateResult[]> {
401
- const { field, function: aggFn, groupBy } = params;
402
- const groups: Record<string, any[]> = {};
403
-
404
- for (const record of this.items as any[]) {
405
- const key = String(record[groupBy] ?? 'Unknown');
406
- if (!groups[key]) groups[key] = [];
407
- groups[key].push(record);
408
- }
409
-
410
- return Object.entries(groups).map(([key, group]) => {
411
- const values = group.map(r => Number(r[field]) || 0);
412
- let result: number;
413
-
414
- switch (aggFn) {
415
- case 'count':
416
- result = group.length;
417
- break;
418
- case 'avg':
419
- result = values.length > 0 ? values.reduce((a, b) => a + b, 0) / values.length : 0;
420
- break;
421
- case 'min':
422
- result = values.length > 0 ? Math.min(...values) : 0;
423
- break;
424
- case 'max':
425
- result = values.length > 0 ? Math.max(...values) : 0;
426
- break;
427
- case 'sum':
428
- default:
429
- result = values.reduce((a, b) => a + b, 0);
430
- break;
431
- }
432
-
433
- return { [groupBy]: key, [field]: result };
434
- });
435
- }
436
-
437
- // -----------------------------------------------------------------------
438
- // Mutation subscription (P2 — Event Bus)
439
- // -----------------------------------------------------------------------
440
-
441
- onMutation(callback: (event: MutationEvent<T>) => void): () => void {
442
- this.mutationListeners.add(callback);
443
- return () => { this.mutationListeners.delete(callback); };
444
- }
445
-
446
- // -----------------------------------------------------------------------
447
- // Extra utilities
448
- // -----------------------------------------------------------------------
449
-
450
- /** Get the current number of items */
451
- get count(): number {
452
- return this.items.length;
453
- }
454
-
455
- /** Get a snapshot of all items (cloned) */
456
- getAll(): T[] {
457
- return JSON.parse(JSON.stringify(this.items));
458
- }
459
- }