@objectstack/objectql 4.0.3 → 4.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/engine.ts DELETED
@@ -1,1548 +0,0 @@
1
- // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
2
-
3
- import { QueryAST, HookContext, ServiceObject } from '@objectstack/spec/data';
4
- import {
5
- EngineQueryOptions,
6
- DataEngineInsertOptions,
7
- EngineUpdateOptions,
8
- EngineDeleteOptions,
9
- EngineAggregateOptions,
10
- EngineCountOptions
11
- } from '@objectstack/spec/data';
12
- import { ExecutionContext, ExecutionContextSchema } from '@objectstack/spec/kernel';
13
- import { DriverInterface, IDataEngine, Logger, createLogger } from '@objectstack/core';
14
- import { CoreServiceName } from '@objectstack/spec/system';
15
- import { IRealtimeService, RealtimeEventPayload } from '@objectstack/spec/contracts';
16
- import { pluralToSingular } from '@objectstack/spec/shared';
17
- import { SchemaRegistry } from './registry.js';
18
-
19
- export type HookHandler = (context: HookContext) => Promise<void> | void;
20
-
21
- /**
22
- * Per-object hook entry with priority support
23
- */
24
- export interface HookEntry {
25
- handler: HookHandler;
26
- object?: string | string[]; // undefined = global hook
27
- priority: number;
28
- packageId?: string;
29
- }
30
-
31
- /**
32
- * Operation Context for Middleware Chain
33
- */
34
- export interface OperationContext {
35
- object: string;
36
- operation: 'find' | 'findOne' | 'insert' | 'update' | 'delete' | 'count' | 'aggregate';
37
- ast?: QueryAST;
38
- data?: any;
39
- options?: any;
40
- context?: ExecutionContext;
41
- result?: any;
42
- }
43
-
44
- /**
45
- * Engine Middleware (Onion model)
46
- */
47
- export type EngineMiddleware = (
48
- ctx: OperationContext,
49
- next: () => Promise<void>
50
- ) => Promise<void>;
51
-
52
- /**
53
- * Host Context provided to plugins (Internal ObjectQL Plugin System)
54
- */
55
- export interface ObjectQLHostContext {
56
- ql: ObjectQL;
57
- logger: Logger;
58
- // Extensible map for host-specific globals (like HTTP Router, etc.)
59
- [key: string]: any;
60
- }
61
-
62
- /**
63
- * ObjectQL Engine
64
- *
65
- * Implements the IDataEngine interface for data persistence.
66
- * Acts as the reference implementation for:
67
- * - CoreServiceName.data (CRUD)
68
- * - CoreServiceName.metadata (Schema Registry)
69
- */
70
- export class ObjectQL implements IDataEngine {
71
- private drivers = new Map<string, DriverInterface>();
72
- private defaultDriver: string | null = null;
73
- private logger: Logger;
74
-
75
- // Per-object hooks with priority support
76
- private hooks: Map<string, HookEntry[]> = new Map([
77
- ['beforeFind', []], ['afterFind', []],
78
- ['beforeInsert', []], ['afterInsert', []],
79
- ['beforeUpdate', []], ['afterUpdate', []],
80
- ['beforeDelete', []], ['afterDelete', []],
81
- ]);
82
-
83
- // Middleware chain (onion model)
84
- private middlewares: Array<{
85
- fn: EngineMiddleware;
86
- object?: string;
87
- }> = [];
88
-
89
- // Action registry: key = "objectName:actionName"
90
- private actions = new Map<string, { handler: (ctx: any) => Promise<any> | any; package?: string }>();
91
-
92
- // Host provided context additions (e.g. Server router)
93
- private hostContext: Record<string, any> = {};
94
-
95
- // Realtime service for event publishing
96
- private realtimeService?: IRealtimeService;
97
-
98
- constructor(hostContext: Record<string, any> = {}) {
99
- this.hostContext = hostContext;
100
- // Use provided logger or create a new one
101
- this.logger = hostContext.logger || createLogger({ level: 'info', format: 'pretty' });
102
- this.logger.info('ObjectQL Engine Instance Created');
103
- }
104
-
105
- /**
106
- * Service Status Report
107
- * Used by Kernel to verify health and capabilities.
108
- */
109
- getStatus() {
110
- return {
111
- name: CoreServiceName.enum.data,
112
- status: 'running',
113
- version: '0.9.0',
114
- features: ['crud', 'query', 'aggregate', 'transactions', 'metadata']
115
- };
116
- }
117
-
118
- /**
119
- * Expose the SchemaRegistry for plugins to register metadata
120
- */
121
- get registry() {
122
- return SchemaRegistry;
123
- }
124
-
125
- /**
126
- * Load and Register a Plugin
127
- */
128
- async use(manifestPart: any, runtimePart?: any) {
129
- this.logger.debug('Loading plugin', {
130
- hasManifest: !!manifestPart,
131
- hasRuntime: !!runtimePart
132
- });
133
-
134
- // 1. Validate / Register Manifest
135
- if (manifestPart) {
136
- this.registerApp(manifestPart);
137
- }
138
-
139
- // 2. Execute Runtime
140
- if (runtimePart) {
141
- const pluginDef = (runtimePart as any).default || runtimePart;
142
- if (pluginDef.onEnable) {
143
- this.logger.debug('Executing plugin runtime onEnable');
144
-
145
- const context: ObjectQLHostContext = {
146
- ql: this,
147
- logger: this.logger,
148
- // Expose the driver registry helper explicitly if needed
149
- drivers: {
150
- register: (driver: DriverInterface) => this.registerDriver(driver)
151
- },
152
- ...this.hostContext
153
- };
154
-
155
- await pluginDef.onEnable(context);
156
- this.logger.debug('Plugin runtime onEnable completed');
157
- }
158
- }
159
- }
160
-
161
- /**
162
- * Register a hook
163
- * @param event The event name (e.g. 'beforeFind', 'afterInsert')
164
- * @param handler The handler function
165
- * @param options Optional: target object(s) and priority
166
- */
167
- registerHook(event: string, handler: HookHandler, options?: {
168
- object?: string | string[];
169
- priority?: number;
170
- packageId?: string;
171
- }) {
172
- if (!this.hooks.has(event)) {
173
- this.hooks.set(event, []);
174
- }
175
- const entries = this.hooks.get(event)!;
176
- entries.push({
177
- handler,
178
- object: options?.object,
179
- priority: options?.priority ?? 100,
180
- packageId: options?.packageId,
181
- });
182
- // Sort by priority (lower runs first)
183
- entries.sort((a, b) => a.priority - b.priority);
184
- this.logger.debug('Registered hook', { event, object: options?.object, priority: options?.priority ?? 100, totalHandlers: entries.length });
185
- }
186
-
187
- public async triggerHooks(event: string, context: HookContext) {
188
- const entries = this.hooks.get(event) || [];
189
-
190
- if (entries.length === 0) {
191
- this.logger.debug('No hooks registered for event', { event });
192
- return;
193
- }
194
-
195
- this.logger.debug('Triggering hooks', { event, count: entries.length });
196
-
197
- for (const entry of entries) {
198
- // Per-object matching
199
- if (entry.object) {
200
- const targets = Array.isArray(entry.object) ? entry.object : [entry.object];
201
- if (!targets.includes('*') && !targets.includes(context.object)) {
202
- continue; // Skip non-matching hooks
203
- }
204
- }
205
- await entry.handler(context);
206
- }
207
- }
208
-
209
- // ========================================
210
- // Action System
211
- // ========================================
212
-
213
- /**
214
- * Register a named action on an object.
215
- * Actions are custom business logic callable via `repo.execute(actionName, params)`.
216
- *
217
- * @param objectName Target object
218
- * @param actionName Unique action name within the object
219
- * @param handler Handler function
220
- * @param packageName Optional package owner (for cleanup)
221
- */
222
- registerAction(objectName: string, actionName: string, handler: (ctx: any) => Promise<any> | any, packageName?: string): void {
223
- const key = `${objectName}:${actionName}`;
224
- this.actions.set(key, { handler, package: packageName });
225
- this.logger.debug('Registered action', { objectName, actionName, package: packageName });
226
- }
227
-
228
- /**
229
- * Execute a named action on an object.
230
- */
231
- async executeAction(objectName: string, actionName: string, ctx: any): Promise<any> {
232
- const entry = this.actions.get(`${objectName}:${actionName}`);
233
- if (!entry) {
234
- throw new Error(`Action '${actionName}' on object '${objectName}' not found`);
235
- }
236
- return entry.handler(ctx);
237
- }
238
-
239
- /**
240
- * Remove all actions registered by a specific package.
241
- */
242
- removeActionsByPackage(packageName: string): void {
243
- for (const [key, entry] of this.actions.entries()) {
244
- if (entry.package === packageName) {
245
- this.actions.delete(key);
246
- }
247
- }
248
- }
249
-
250
- /**
251
- * Register a middleware function
252
- * Middlewares execute in onion model around every data operation.
253
- * @param fn The middleware function
254
- * @param options Optional: target object filter
255
- */
256
- registerMiddleware(fn: EngineMiddleware, options?: { object?: string }): void {
257
- this.middlewares.push({ fn, object: options?.object });
258
- this.logger.debug('Registered middleware', { object: options?.object, total: this.middlewares.length });
259
- }
260
-
261
- /**
262
- * Execute an operation through the middleware chain
263
- */
264
- private async executeWithMiddleware(ctx: OperationContext, executor: () => Promise<any>): Promise<any> {
265
- const applicable = this.middlewares.filter(m =>
266
- !m.object || m.object === '*' || m.object === ctx.object
267
- );
268
-
269
- let index = 0;
270
- const next = async (): Promise<void> => {
271
- if (index < applicable.length) {
272
- const mw = applicable[index++];
273
- await mw.fn(ctx, next);
274
- } else {
275
- ctx.result = await executor();
276
- }
277
- };
278
-
279
- await next();
280
- return ctx.result;
281
- }
282
-
283
- /**
284
- * Build a HookContext.session from ExecutionContext
285
- */
286
- private buildSession(execCtx?: ExecutionContext): HookContext['session'] {
287
- if (!execCtx) return undefined;
288
- return {
289
- userId: execCtx.userId,
290
- tenantId: execCtx.tenantId,
291
- roles: execCtx.roles,
292
- accessToken: execCtx.accessToken,
293
- };
294
- }
295
-
296
- /**
297
- * Register contribution (Manifest)
298
- *
299
- * Installs the manifest as a Package (the unit of installation),
300
- * then decomposes it into individual metadata items (objects, apps, actions, etc.)
301
- * and registers each into the SchemaRegistry.
302
- *
303
- * Key: Package ≠ App. The manifest is the package. The apps[] array inside
304
- * the manifest contains UI navigation definitions (AppSchema).
305
- */
306
- registerApp(manifest: any) {
307
- const id = manifest.id || manifest.name;
308
- const namespace = manifest.namespace as string | undefined;
309
- this.logger.debug('Registering package manifest', { id, namespace });
310
-
311
- // 1. Register the Package (manifest + lifecycle state)
312
- SchemaRegistry.installPackage(manifest);
313
- this.logger.debug('Installed Package', { id: manifest.id, name: manifest.name, namespace });
314
-
315
- // 2. Register owned objects
316
- if (manifest.objects) {
317
- if (Array.isArray(manifest.objects)) {
318
- this.logger.debug('Registering objects from manifest (Array)', { id, objectCount: manifest.objects.length });
319
- for (const objDef of manifest.objects) {
320
- const fqn = SchemaRegistry.registerObject(objDef, id, namespace, 'own');
321
- this.logger.debug('Registered Object', { fqn, from: id });
322
- }
323
- } else {
324
- this.logger.debug('Registering objects from manifest (Map)', { id, objectCount: Object.keys(manifest.objects).length });
325
- for (const [name, objDef] of Object.entries(manifest.objects)) {
326
- // Ensure name in definition matches key
327
- (objDef as any).name = name;
328
- const fqn = SchemaRegistry.registerObject(objDef as any, id, namespace, 'own');
329
- this.logger.debug('Registered Object', { fqn, from: id });
330
- }
331
- }
332
- }
333
-
334
- // 2b. Register object extensions (fields added to objects owned by other packages)
335
- if (Array.isArray(manifest.objectExtensions) && manifest.objectExtensions.length > 0) {
336
- this.logger.debug('Registering object extensions', { id, count: manifest.objectExtensions.length });
337
- for (const ext of manifest.objectExtensions) {
338
- const targetFqn = ext.extend;
339
- const priority = ext.priority ?? 200;
340
- // Create a partial object definition for the extension
341
- const extDef = {
342
- name: targetFqn, // Use the target FQN as name
343
- fields: ext.fields,
344
- label: ext.label,
345
- pluralLabel: ext.pluralLabel,
346
- description: ext.description,
347
- validations: ext.validations,
348
- indexes: ext.indexes,
349
- };
350
- // Register as extension (namespace is undefined since we're targeting by FQN)
351
- SchemaRegistry.registerObject(extDef as any, id, undefined, 'extend', priority);
352
- this.logger.debug('Registered Object Extension', { target: targetFqn, priority, from: id });
353
- }
354
- }
355
-
356
- // 3. Register apps (UI navigation definitions) as their own metadata type
357
- if (Array.isArray(manifest.apps) && manifest.apps.length > 0) {
358
- this.logger.debug('Registering apps from manifest', { id, count: manifest.apps.length });
359
- for (const app of manifest.apps) {
360
- const appName = app.name || app.id;
361
- if (appName) {
362
- SchemaRegistry.registerApp(app, id);
363
- this.logger.debug('Registered App', { app: appName, from: id });
364
- }
365
- }
366
- }
367
-
368
- // 4. If manifest itself looks like an App (has navigation), also register as app
369
- // This handles the case where the manifest IS the app definition (legacy/simple packages)
370
- if (manifest.name && manifest.navigation && !manifest.apps?.length) {
371
- SchemaRegistry.registerApp(manifest, id);
372
- this.logger.debug('Registered manifest-as-app', { app: manifest.name, from: id });
373
- }
374
-
375
- // 5. Register all other metadata types generically
376
- const metadataArrayKeys = [
377
- // UI Protocol
378
- 'actions', 'views', 'pages', 'dashboards', 'reports', 'themes',
379
- // Automation Protocol
380
- 'flows', 'workflows', 'approvals', 'webhooks',
381
- // Security Protocol
382
- 'roles', 'permissions', 'profiles', 'sharingRules', 'policies',
383
- // AI Protocol
384
- 'agents', 'ragPipelines',
385
- // API Protocol
386
- 'apis',
387
- // Data Extensions
388
- 'hooks', 'mappings', 'analyticsCubes',
389
- // Integration Protocol
390
- 'connectors',
391
- ];
392
- for (const key of metadataArrayKeys) {
393
- const items = (manifest as any)[key];
394
- if (Array.isArray(items) && items.length > 0) {
395
- this.logger.debug(`Registering ${key} from manifest`, { id, count: items.length });
396
- for (const item of items) {
397
- const itemName = item.name || item.id;
398
- if (itemName) {
399
- SchemaRegistry.registerItem(pluralToSingular(key), item, 'name' as any, id);
400
- }
401
- }
402
- }
403
- }
404
-
405
- // 6. Register seed data as metadata (keyed by target object name)
406
- const seedData = (manifest as any).data;
407
- if (Array.isArray(seedData) && seedData.length > 0) {
408
- this.logger.debug('Registering seed data datasets', { id, count: seedData.length });
409
- for (const dataset of seedData) {
410
- if (dataset.object) {
411
- SchemaRegistry.registerItem('data', dataset, 'object' as any, id);
412
- }
413
- }
414
- }
415
-
416
- // 6. Register contributions
417
- if (manifest.contributes?.kinds) {
418
- this.logger.debug('Registering kinds from manifest', { id, kindCount: manifest.contributes.kinds.length });
419
- for (const kind of manifest.contributes.kinds) {
420
- SchemaRegistry.registerKind(kind);
421
- this.logger.debug('Registered Kind', { kind: kind.name || kind.type, from: id });
422
- }
423
- }
424
-
425
- // 7. Recursively register nested plugins
426
- if (Array.isArray(manifest.plugins) && manifest.plugins.length > 0) {
427
- this.logger.debug('Processing nested plugins', { id, count: manifest.plugins.length });
428
- for (const plugin of manifest.plugins) {
429
- if (plugin && typeof plugin === 'object') {
430
- const pluginName = plugin.name || plugin.id || 'unnamed-plugin';
431
- this.logger.debug('Registering nested plugin', { pluginName, parentId: id });
432
- this.registerPlugin(plugin, id, namespace);
433
- }
434
- }
435
- }
436
- }
437
-
438
- /**
439
- * Register a nested plugin's metadata (objects, actions, views, etc.)
440
- *
441
- * Unlike registerApp(), this does NOT call SchemaRegistry.installPackage()
442
- * because plugins are not formal manifests — they are lightweight config
443
- * bundles with objects, actions, triggers, and navigation.
444
- *
445
- * @param plugin - The plugin config object
446
- * @param parentId - The parent package ID (for ownership tracking)
447
- * @param parentNamespace - The parent package's namespace (for FQN resolution)
448
- */
449
- private registerPlugin(plugin: any, parentId: string, parentNamespace?: string) {
450
- const pluginName = plugin.name || plugin.id || 'unnamed';
451
- const pluginNamespace = plugin.namespace || parentNamespace;
452
-
453
- // Use parentId as the owning package for namespace consistency.
454
- // The parent package already claimed the namespace — nested plugins
455
- // contribute objects UNDER the parent's ownership.
456
- const ownerId = parentId;
457
-
458
- // Register objects (supports both Array and Map formats)
459
- if (plugin.objects) {
460
- try {
461
- if (Array.isArray(plugin.objects)) {
462
- this.logger.debug('Registering plugin objects (Array)', { pluginName, count: plugin.objects.length });
463
- for (const objDef of plugin.objects) {
464
- const fqn = SchemaRegistry.registerObject(objDef, ownerId, pluginNamespace, 'own');
465
- this.logger.debug('Registered Object', { fqn, from: pluginName });
466
- }
467
- } else {
468
- const entries = Object.entries(plugin.objects);
469
- this.logger.debug('Registering plugin objects (Map)', { pluginName, count: entries.length });
470
- for (const [name, objDef] of entries) {
471
- (objDef as any).name = name;
472
- const fqn = SchemaRegistry.registerObject(objDef as any, ownerId, pluginNamespace, 'own');
473
- this.logger.debug('Registered Object', { fqn, from: pluginName });
474
- }
475
- }
476
- } catch (err: any) {
477
- this.logger.warn('Failed to register plugin objects', { pluginName, error: err.message });
478
- }
479
- }
480
-
481
- // Register plugin as app if it has navigation (for sidebar display)
482
- if (plugin.name && plugin.navigation) {
483
- try {
484
- SchemaRegistry.registerApp(plugin, ownerId);
485
- this.logger.debug('Registered plugin-as-app', { app: plugin.name, from: pluginName });
486
- } catch (err: any) {
487
- this.logger.warn('Failed to register plugin as app', { pluginName, error: err.message });
488
- }
489
- }
490
-
491
- // Register metadata arrays (actions, views, triggers, etc.)
492
- const metadataArrayKeys = [
493
- 'actions', 'views', 'pages', 'dashboards', 'reports', 'themes',
494
- 'flows', 'workflows', 'approvals', 'webhooks',
495
- 'roles', 'permissions', 'profiles', 'sharingRules', 'policies',
496
- 'agents', 'ragPipelines', 'apis',
497
- 'hooks', 'mappings', 'analyticsCubes', 'connectors',
498
- ];
499
- for (const key of metadataArrayKeys) {
500
- const items = (plugin as any)[key];
501
- if (Array.isArray(items) && items.length > 0) {
502
- for (const item of items) {
503
- const itemName = item.name || item.id;
504
- if (itemName) {
505
- SchemaRegistry.registerItem(pluralToSingular(key), item, 'name' as any, ownerId);
506
- }
507
- }
508
- }
509
- }
510
- }
511
-
512
- /**
513
- * Register a new storage driver
514
- */
515
- registerDriver(driver: DriverInterface, isDefault: boolean = false) {
516
- if (this.drivers.has(driver.name)) {
517
- this.logger.warn('Driver already registered, skipping', { driverName: driver.name });
518
- return;
519
- }
520
-
521
- this.drivers.set(driver.name, driver);
522
- this.logger.info('Registered driver', {
523
- driverName: driver.name,
524
- version: driver.version
525
- });
526
-
527
- if (isDefault || this.drivers.size === 1) {
528
- this.defaultDriver = driver.name;
529
- this.logger.info('Set default driver', { driverName: driver.name });
530
- }
531
- }
532
-
533
- /**
534
- * Set the realtime service for publishing data change events.
535
- * Should be called after kernel resolves the realtime service.
536
- *
537
- * @param service - An IRealtimeService instance for event publishing
538
- */
539
- setRealtimeService(service: IRealtimeService): void {
540
- this.realtimeService = service;
541
- this.logger.info('RealtimeService configured for data events');
542
- }
543
-
544
- /**
545
- * Helper to get object definition
546
- */
547
- getSchema(objectName: string): ServiceObject | undefined {
548
- return SchemaRegistry.getObject(objectName);
549
- }
550
-
551
- /**
552
- * Resolve an object name to its Fully Qualified Name (FQN).
553
- *
554
- * Short names like 'task' are resolved to FQN like 'todo__task'
555
- * via SchemaRegistry lookup. If no match is found, the name is
556
- * returned as-is (for ad-hoc / unregistered objects).
557
- *
558
- * This ensures that all driver operations use a consistent key
559
- * regardless of whether the caller uses the short name or FQN.
560
- */
561
- private resolveObjectName(name: string): string {
562
- const schema = SchemaRegistry.getObject(name);
563
- if (schema) {
564
- // Prefer the physical table name (e.g., 'sys_user') over the FQN
565
- // (e.g., 'sys__user'). ObjectSchema.create() auto-derives tableName
566
- // as {namespace}_{name} which matches the storage convention.
567
- return schema.tableName || schema.name;
568
- }
569
- return name; // Ad-hoc object, keep as-is
570
- }
571
-
572
- /**
573
- * Helper to get the target driver
574
- */
575
- private getDriver(objectName: string): DriverInterface {
576
- const object = SchemaRegistry.getObject(objectName);
577
-
578
- // 1. If object definition exists, check for explicit datasource
579
- if (object) {
580
- const datasourceName = object.datasource || 'default';
581
-
582
- // If configured for 'default', try to find the default driver
583
- if (datasourceName === 'default') {
584
- if (this.defaultDriver && this.drivers.has(this.defaultDriver)) {
585
- return this.drivers.get(this.defaultDriver)!;
586
- }
587
- } else {
588
- // Specific datasource requested
589
- if (this.drivers.has(datasourceName)) {
590
- return this.drivers.get(datasourceName)!;
591
- }
592
- throw new Error(`[ObjectQL] Datasource '${datasourceName}' configured for object '${objectName}' is not registered.`);
593
- }
594
- }
595
-
596
- // 2. Fallback for ad-hoc objects or missing definitions
597
- if (this.defaultDriver) {
598
- return this.drivers.get(this.defaultDriver)!;
599
- }
600
-
601
- throw new Error(`[ObjectQL] No driver available for object '${objectName}'`);
602
- }
603
-
604
- /**
605
- * Initialize the engine and all registered drivers
606
- */
607
- async init() {
608
- this.logger.info('Initializing ObjectQL engine', {
609
- driverCount: this.drivers.size,
610
- drivers: Array.from(this.drivers.keys())
611
- });
612
-
613
- const failedDrivers: string[] = [];
614
- for (const [name, driver] of this.drivers) {
615
- try {
616
- await driver.connect();
617
- this.logger.info('Driver connected successfully', { driverName: name });
618
- } catch (e) {
619
- failedDrivers.push(name);
620
- this.logger.error('Failed to connect driver', e as Error, { driverName: name });
621
- }
622
- }
623
-
624
- if (failedDrivers.length > 0) {
625
- this.logger.warn(
626
- `${failedDrivers.length} of ${this.drivers.size} driver(s) failed initial connect. ` +
627
- `Operations may recover via lazy reconnection or fail at query time.`,
628
- { failedDrivers }
629
- );
630
- }
631
-
632
- this.logger.info('ObjectQL engine initialization complete');
633
- }
634
-
635
- async destroy() {
636
- this.logger.info('Destroying ObjectQL engine', { driverCount: this.drivers.size });
637
-
638
- for (const [name, driver] of this.drivers.entries()) {
639
- try {
640
- await driver.disconnect();
641
- } catch (e) {
642
- this.logger.error('Error disconnecting driver', e as Error, { driverName: name });
643
- }
644
- }
645
-
646
- this.logger.info('ObjectQL engine destroyed');
647
- }
648
-
649
- // ============================================
650
- // Helper: Expand Related Records
651
- // ============================================
652
-
653
- /** Maximum depth for recursive expand to prevent infinite loops */
654
- private static readonly MAX_EXPAND_DEPTH = 3;
655
-
656
- /**
657
- * Post-process expand: resolve lookup/master_detail fields by batch-loading related records.
658
- *
659
- * This is a driver-agnostic implementation that uses secondary queries ($in batches)
660
- * to load related records, then injects them into the result set.
661
- *
662
- * @param objectName - The source object name
663
- * @param records - The records returned by the driver
664
- * @param expand - The expand map from QueryAST (field name → nested QueryAST)
665
- * @param depth - Current recursion depth (0-based)
666
- * @returns Records with expanded lookup fields (IDs replaced by full objects)
667
- */
668
- private async expandRelatedRecords(
669
- objectName: string,
670
- records: any[],
671
- expand: Record<string, QueryAST>,
672
- depth: number = 0,
673
- ): Promise<any[]> {
674
- if (!records || records.length === 0) return records;
675
- if (depth >= ObjectQL.MAX_EXPAND_DEPTH) return records;
676
-
677
- const objectSchema = SchemaRegistry.getObject(objectName);
678
- // If no schema registered, skip expand — return raw data
679
- if (!objectSchema || !objectSchema.fields) return records;
680
-
681
- for (const [fieldName, nestedAST] of Object.entries(expand)) {
682
- const fieldDef = objectSchema.fields[fieldName];
683
-
684
- // Skip if field not found or not a relationship type
685
- if (!fieldDef || !fieldDef.reference) continue;
686
- if (fieldDef.type !== 'lookup' && fieldDef.type !== 'master_detail') continue;
687
-
688
- const referenceObject = fieldDef.reference;
689
-
690
- // Collect all foreign key IDs from records (handle both single and multiple values)
691
- const allIds: any[] = [];
692
- for (const record of records) {
693
- const val = record[fieldName];
694
- if (val == null) continue;
695
- if (Array.isArray(val)) {
696
- allIds.push(...val.filter((id: any) => id != null));
697
- } else if (typeof val === 'object') {
698
- // Already expanded — skip
699
- continue;
700
- } else {
701
- allIds.push(val);
702
- }
703
- }
704
-
705
- // De-duplicate IDs
706
- const uniqueIds = [...new Set(allIds)];
707
- if (uniqueIds.length === 0) continue;
708
-
709
- // Batch-load related records using $in query
710
- try {
711
- const relatedQuery: QueryAST = {
712
- object: referenceObject,
713
- where: { id: { $in: uniqueIds } },
714
- ...(nestedAST.fields ? { fields: nestedAST.fields } : {}),
715
- ...(nestedAST.orderBy ? { orderBy: nestedAST.orderBy } : {}),
716
- };
717
-
718
- const driver = this.getDriver(referenceObject);
719
- const relatedRecords = await driver.find(referenceObject, relatedQuery) ?? [];
720
-
721
- // Build a lookup map: id → record
722
- const recordMap = new Map<string, any>();
723
- for (const rec of relatedRecords) {
724
- const id = rec.id;
725
- if (id != null) recordMap.set(String(id), rec);
726
- }
727
-
728
- // Recursively expand nested relations if present
729
- if (nestedAST.expand && Object.keys(nestedAST.expand).length > 0) {
730
- const expandedRelated = await this.expandRelatedRecords(
731
- referenceObject,
732
- relatedRecords,
733
- nestedAST.expand,
734
- depth + 1,
735
- );
736
- // Rebuild map with expanded records
737
- recordMap.clear();
738
- for (const rec of expandedRelated) {
739
- const id = rec.id;
740
- if (id != null) recordMap.set(String(id), rec);
741
- }
742
- }
743
-
744
- // Inject expanded records back into the original result set
745
- for (const record of records) {
746
- const val = record[fieldName];
747
- if (val == null) continue;
748
-
749
- if (Array.isArray(val)) {
750
- record[fieldName] = val.map((id: any) => recordMap.get(String(id)) ?? id);
751
- } else if (typeof val !== 'object') {
752
- record[fieldName] = recordMap.get(String(val)) ?? val;
753
- }
754
- // If val is already an object, leave it as-is
755
- }
756
- } catch (e) {
757
- // Graceful degradation: if expand fails, keep original IDs
758
- this.logger.warn('Failed to expand relationship field; retaining foreign key IDs', {
759
- object: objectName,
760
- field: fieldName,
761
- reference: referenceObject,
762
- error: (e as Error).message,
763
- });
764
- }
765
- }
766
-
767
- return records;
768
- }
769
-
770
- // ============================================
771
- // Data Access Methods (IDataEngine Interface)
772
- // ============================================
773
-
774
- async find(object: string, query?: EngineQueryOptions): Promise<any[]> {
775
- object = this.resolveObjectName(object);
776
- this.logger.debug('Find operation starting', { object, query });
777
- const driver = this.getDriver(object);
778
- const ast: QueryAST = { object, ...query };
779
- // Remove context from the AST — it's not a driver concern
780
- delete (ast as any).context;
781
- // Normalize OData `top` alias → standard `limit`
782
- if ((ast as any).top != null && ast.limit == null) {
783
- ast.limit = (ast as any).top;
784
- }
785
- delete (ast as any).top;
786
-
787
- const opCtx: OperationContext = {
788
- object,
789
- operation: 'find',
790
- ast,
791
- options: query,
792
- context: query?.context,
793
- };
794
-
795
- await this.executeWithMiddleware(opCtx, async () => {
796
- const hookContext: HookContext = {
797
- object,
798
- event: 'beforeFind',
799
- input: { ast: opCtx.ast, options: opCtx.options },
800
- session: this.buildSession(opCtx.context),
801
- transaction: opCtx.context?.transaction,
802
- ql: this
803
- };
804
- await this.triggerHooks('beforeFind', hookContext);
805
-
806
- try {
807
- let result = await driver.find(object, hookContext.input.ast as QueryAST, hookContext.input.options as any);
808
-
809
- // Post-process: expand related records if expand is requested
810
- if (ast.expand && Object.keys(ast.expand).length > 0 && Array.isArray(result)) {
811
- result = await this.expandRelatedRecords(object, result, ast.expand, 0);
812
- }
813
-
814
- hookContext.event = 'afterFind';
815
- hookContext.result = result;
816
- await this.triggerHooks('afterFind', hookContext);
817
-
818
- return hookContext.result;
819
- } catch (e) {
820
- this.logger.error('Find operation failed', e as Error, { object });
821
- throw e;
822
- }
823
- });
824
-
825
- return opCtx.result as any[];
826
- }
827
-
828
- async findOne(objectName: string, query?: EngineQueryOptions): Promise<any> {
829
- objectName = this.resolveObjectName(objectName);
830
- this.logger.debug('FindOne operation', { objectName });
831
- const driver = this.getDriver(objectName);
832
- const ast: QueryAST = { object: objectName, ...query, limit: 1 };
833
- // Remove context and top alias from the AST
834
- delete (ast as any).context;
835
- delete (ast as any).top;
836
-
837
- const opCtx: OperationContext = {
838
- object: objectName,
839
- operation: 'findOne',
840
- ast,
841
- options: query,
842
- context: query?.context,
843
- };
844
-
845
- await this.executeWithMiddleware(opCtx, async () => {
846
- let result = await driver.findOne(objectName, opCtx.ast as QueryAST);
847
-
848
- // Post-process: expand related records if expand is requested
849
- if (ast.expand && Object.keys(ast.expand).length > 0 && result != null) {
850
- const expanded = await this.expandRelatedRecords(objectName, [result], ast.expand, 0);
851
- result = expanded[0];
852
- }
853
-
854
- return result;
855
- });
856
-
857
- return opCtx.result;
858
- }
859
-
860
- async insert(object: string, data: any | any[], options?: DataEngineInsertOptions): Promise<any> {
861
- object = this.resolveObjectName(object);
862
- this.logger.debug('Insert operation starting', { object, isBatch: Array.isArray(data) });
863
- const driver = this.getDriver(object);
864
-
865
- const opCtx: OperationContext = {
866
- object,
867
- operation: 'insert',
868
- data,
869
- options,
870
- context: options?.context,
871
- };
872
-
873
- await this.executeWithMiddleware(opCtx, async () => {
874
- const hookContext: HookContext = {
875
- object,
876
- event: 'beforeInsert',
877
- input: { data: opCtx.data, options: opCtx.options },
878
- session: this.buildSession(opCtx.context),
879
- transaction: opCtx.context?.transaction,
880
- ql: this
881
- };
882
- await this.triggerHooks('beforeInsert', hookContext);
883
-
884
- try {
885
- let result;
886
- if (Array.isArray(hookContext.input.data)) {
887
- // Bulk Create
888
- if (driver.bulkCreate) {
889
- result = await driver.bulkCreate(object, hookContext.input.data as any[], hookContext.input.options as any);
890
- } else {
891
- // Fallback loop
892
- result = await Promise.all((hookContext.input.data as any[]).map((item: any) => driver.create(object, item, hookContext.input.options as any)));
893
- }
894
- } else {
895
- result = await driver.create(object, hookContext.input.data as Record<string, unknown>, hookContext.input.options as any);
896
- }
897
-
898
- hookContext.event = 'afterInsert';
899
- hookContext.result = result;
900
- await this.triggerHooks('afterInsert', hookContext);
901
-
902
- // Publish data.record.created event to realtime service
903
- if (this.realtimeService) {
904
- try {
905
- if (Array.isArray(result)) {
906
- // Bulk insert - publish event for each record
907
- for (const record of result) {
908
- const event: RealtimeEventPayload = {
909
- type: 'data.record.created',
910
- object,
911
- payload: {
912
- recordId: record.id,
913
- after: record,
914
- },
915
- timestamp: new Date().toISOString(),
916
- };
917
- await this.realtimeService.publish(event);
918
- }
919
- this.logger.debug(`Published ${result.length} data.record.created events`, { object });
920
- } else {
921
- const event: RealtimeEventPayload = {
922
- type: 'data.record.created',
923
- object,
924
- payload: {
925
- recordId: result.id,
926
- after: result,
927
- },
928
- timestamp: new Date().toISOString(),
929
- };
930
- await this.realtimeService.publish(event);
931
- this.logger.debug('Published data.record.created event', { object, recordId: result.id });
932
- }
933
- } catch (error) {
934
- this.logger.warn('Failed to publish data event', { object, error });
935
- }
936
- }
937
-
938
- return hookContext.result;
939
- } catch (e) {
940
- this.logger.error('Insert operation failed', e as Error, { object });
941
- throw e;
942
- }
943
- });
944
-
945
- return opCtx.result;
946
- }
947
-
948
- async update(object: string, data: any, options?: EngineUpdateOptions): Promise<any> {
949
- object = this.resolveObjectName(object);
950
- this.logger.debug('Update operation starting', { object });
951
- const driver = this.getDriver(object);
952
-
953
- // 1. Extract ID from data or where if it's a single update by ID
954
- let id = data.id;
955
- if (!id && options?.where && typeof options.where === 'object' && 'id' in options.where) {
956
- id = (options.where as Record<string, unknown>).id;
957
- }
958
-
959
- const opCtx: OperationContext = {
960
- object,
961
- operation: 'update',
962
- data,
963
- options,
964
- context: options?.context,
965
- };
966
-
967
- await this.executeWithMiddleware(opCtx, async () => {
968
- const hookContext: HookContext = {
969
- object,
970
- event: 'beforeUpdate',
971
- input: { id, data: opCtx.data, options: opCtx.options },
972
- session: this.buildSession(opCtx.context),
973
- transaction: opCtx.context?.transaction,
974
- ql: this
975
- };
976
- await this.triggerHooks('beforeUpdate', hookContext);
977
-
978
- try {
979
- let result;
980
- if (hookContext.input.id) {
981
- result = await driver.update(object, hookContext.input.id as string, hookContext.input.data as Record<string, unknown>, hookContext.input.options as any);
982
- } else if (options?.multi && driver.updateMany) {
983
- const ast: QueryAST = { object, where: options.where };
984
- result = await driver.updateMany(object, ast, hookContext.input.data as Record<string, unknown>, hookContext.input.options as any);
985
- } else {
986
- throw new Error('Update requires an ID or options.multi=true');
987
- }
988
-
989
- hookContext.event = 'afterUpdate';
990
- hookContext.result = result;
991
- await this.triggerHooks('afterUpdate', hookContext);
992
-
993
- // Publish data.record.updated event to realtime service
994
- if (this.realtimeService) {
995
- try {
996
- const resultId = (typeof result === 'object' && result && 'id' in result) ? (result as any).id : undefined;
997
- const recordId = String(hookContext.input.id || resultId || '');
998
- const event: RealtimeEventPayload = {
999
- type: 'data.record.updated',
1000
- object,
1001
- payload: {
1002
- recordId,
1003
- changes: hookContext.input.data,
1004
- after: result,
1005
- },
1006
- timestamp: new Date().toISOString(),
1007
- };
1008
- await this.realtimeService.publish(event);
1009
- this.logger.debug('Published data.record.updated event', { object, recordId });
1010
- } catch (error) {
1011
- this.logger.warn('Failed to publish data event', { object, error });
1012
- }
1013
- }
1014
-
1015
- return hookContext.result;
1016
- } catch (e) {
1017
- this.logger.error('Update operation failed', e as Error, { object });
1018
- throw e;
1019
- }
1020
- });
1021
-
1022
- return opCtx.result;
1023
- }
1024
-
1025
- async delete(object: string, options?: EngineDeleteOptions): Promise<any> {
1026
- object = this.resolveObjectName(object);
1027
- this.logger.debug('Delete operation starting', { object });
1028
- const driver = this.getDriver(object);
1029
-
1030
- // Extract ID logic similar to update
1031
- let id: any = undefined;
1032
- if (options?.where && typeof options.where === 'object' && 'id' in options.where) {
1033
- id = (options.where as Record<string, unknown>).id;
1034
- }
1035
-
1036
- const opCtx: OperationContext = {
1037
- object,
1038
- operation: 'delete',
1039
- options,
1040
- context: options?.context,
1041
- };
1042
-
1043
- await this.executeWithMiddleware(opCtx, async () => {
1044
- const hookContext: HookContext = {
1045
- object,
1046
- event: 'beforeDelete',
1047
- input: { id, options: opCtx.options },
1048
- session: this.buildSession(opCtx.context),
1049
- transaction: opCtx.context?.transaction,
1050
- ql: this
1051
- };
1052
- await this.triggerHooks('beforeDelete', hookContext);
1053
-
1054
- try {
1055
- let result;
1056
- if (hookContext.input.id) {
1057
- result = await driver.delete(object, hookContext.input.id as string, hookContext.input.options as any);
1058
- } else if (options?.multi && driver.deleteMany) {
1059
- const ast: QueryAST = { object, where: options.where };
1060
- result = await driver.deleteMany(object, ast, hookContext.input.options as any);
1061
- } else {
1062
- throw new Error('Delete requires an ID or options.multi=true');
1063
- }
1064
-
1065
- hookContext.event = 'afterDelete';
1066
- hookContext.result = result;
1067
- await this.triggerHooks('afterDelete', hookContext);
1068
-
1069
- // Publish data.record.deleted event to realtime service
1070
- if (this.realtimeService) {
1071
- try {
1072
- const resultId = (typeof result === 'object' && result && 'id' in result) ? (result as any).id : undefined;
1073
- const recordId = String(hookContext.input.id || resultId || '');
1074
- const event: RealtimeEventPayload = {
1075
- type: 'data.record.deleted',
1076
- object,
1077
- payload: {
1078
- recordId,
1079
- },
1080
- timestamp: new Date().toISOString(),
1081
- };
1082
- await this.realtimeService.publish(event);
1083
- this.logger.debug('Published data.record.deleted event', { object, recordId });
1084
- } catch (error) {
1085
- this.logger.warn('Failed to publish data event', { object, error });
1086
- }
1087
- }
1088
-
1089
- return hookContext.result;
1090
- } catch (e) {
1091
- this.logger.error('Delete operation failed', e as Error, { object });
1092
- throw e;
1093
- }
1094
- });
1095
-
1096
- return opCtx.result;
1097
- }
1098
-
1099
- async count(object: string, query?: EngineCountOptions): Promise<number> {
1100
- object = this.resolveObjectName(object);
1101
- const driver = this.getDriver(object);
1102
-
1103
- const opCtx: OperationContext = {
1104
- object,
1105
- operation: 'count',
1106
- options: query,
1107
- context: query?.context,
1108
- };
1109
-
1110
- await this.executeWithMiddleware(opCtx, async () => {
1111
- if (driver.count) {
1112
- const ast: QueryAST = { object, where: query?.where };
1113
- return driver.count(object, ast);
1114
- }
1115
- // Fallback to find().length
1116
- const res = await this.find(object, { where: query?.where, fields: ['id'] });
1117
- return res.length;
1118
- });
1119
-
1120
- return opCtx.result as number;
1121
- }
1122
-
1123
- async aggregate(object: string, query: EngineAggregateOptions): Promise<any[]> {
1124
- object = this.resolveObjectName(object);
1125
- const driver = this.getDriver(object);
1126
- this.logger.debug(`Aggregate on ${object} using ${driver.name}`, query);
1127
-
1128
- const opCtx: OperationContext = {
1129
- object,
1130
- operation: 'aggregate',
1131
- options: query,
1132
- context: query?.context,
1133
- };
1134
-
1135
- await this.executeWithMiddleware(opCtx, async () => {
1136
- const ast: QueryAST = {
1137
- object,
1138
- where: query.where,
1139
- groupBy: query.groupBy,
1140
- aggregations: query.aggregations,
1141
- };
1142
-
1143
- return driver.find(object, ast);
1144
- });
1145
-
1146
- return opCtx.result as any[];
1147
- }
1148
-
1149
- async execute(command: any, options?: Record<string, any>): Promise<any> {
1150
- // Direct pass-through implies we know which driver to use?
1151
- // Usually execute is tied to a specific object context OR we need a way to select driver.
1152
- // If command has 'object', we use that.
1153
- if (options?.object) {
1154
- const driver = this.getDriver(options.object);
1155
- if (driver.execute) {
1156
- return driver.execute(command, undefined, options);
1157
- }
1158
- }
1159
- throw new Error('Execute requires options.object to select driver');
1160
- }
1161
-
1162
- // ============================================
1163
- // Compatibility / Convenience API
1164
- // ============================================
1165
- // These methods provide a higher-level API matching the @objectql/core
1166
- // ObjectQL interface, enabling painless migration from the legacy layer.
1167
-
1168
- /**
1169
- * Register a single object definition.
1170
- *
1171
- * Proxies to SchemaRegistry.registerObject() with sensible defaults.
1172
- * Fields without a `name` property are auto-assigned from their key.
1173
- */
1174
- registerObject(
1175
- schema: ServiceObject,
1176
- packageId: string = '__runtime__',
1177
- namespace?: string
1178
- ): string {
1179
- // Auto-assign field names from keys
1180
- if (schema.fields) {
1181
- for (const [key, field] of Object.entries(schema.fields)) {
1182
- if (field && typeof field === 'object' && !('name' in field)) {
1183
- (field as any).name = key;
1184
- }
1185
- }
1186
- }
1187
- return SchemaRegistry.registerObject(schema, packageId, namespace);
1188
- }
1189
-
1190
- /**
1191
- * Unregister a single object by name.
1192
- */
1193
- unregisterObject(name: string, packageId?: string): void {
1194
- if (packageId) {
1195
- SchemaRegistry.unregisterObjectsByPackage(packageId);
1196
- } else {
1197
- // Remove from generic metadata as fallback
1198
- SchemaRegistry.unregisterItem('object', name);
1199
- }
1200
- }
1201
-
1202
- /**
1203
- * Get an object definition by name.
1204
- * Alias for getSchema() — matches @objectql/core API.
1205
- */
1206
- getObject(name: string): ServiceObject | undefined {
1207
- return this.getSchema(name);
1208
- }
1209
-
1210
- /**
1211
- * Get all registered object configs as a name→config map.
1212
- * Matches @objectql/core getConfigs() API.
1213
- */
1214
- getConfigs(): Record<string, ServiceObject> {
1215
- const result: Record<string, ServiceObject> = {};
1216
- const objects = SchemaRegistry.getAllObjects();
1217
- for (const obj of objects) {
1218
- if (obj.name) {
1219
- result[obj.name] = obj;
1220
- }
1221
- }
1222
- return result;
1223
- }
1224
-
1225
- /**
1226
- * Get a registered driver by datasource name.
1227
- *
1228
- * Unlike the private getDriver() (which resolves by object name),
1229
- * this method directly looks up a driver by its registered name.
1230
- */
1231
- getDriverByName(name: string): DriverInterface | undefined {
1232
- return this.drivers.get(name);
1233
- }
1234
-
1235
- /**
1236
- * Get the driver responsible for the given object.
1237
- *
1238
- * Resolves datasource binding from the object's schema definition,
1239
- * falling back to the default driver. This is a public version of
1240
- * the internal getDriver() used by CRUD operations.
1241
- *
1242
- * @param objectName - FQN or short name of the registered object.
1243
- * @returns The resolved DriverInterface, or undefined if no driver is available.
1244
- */
1245
- getDriverForObject(objectName: string): DriverInterface | undefined {
1246
- try {
1247
- return this.getDriver(objectName);
1248
- } catch {
1249
- return undefined;
1250
- }
1251
- }
1252
-
1253
- /**
1254
- * Get a registered driver by datasource name.
1255
- * Alias matching @objectql/core datasource() API.
1256
- *
1257
- * @throws Error if the datasource is not found
1258
- */
1259
- datasource(name: string): DriverInterface {
1260
- const driver = this.drivers.get(name);
1261
- if (!driver) {
1262
- throw new Error(`[ObjectQL] Datasource '${name}' not found`);
1263
- }
1264
- return driver;
1265
- }
1266
-
1267
- /**
1268
- * Register a hook handler.
1269
- * Convenience alias for registerHook() matching @objectql/core on() API.
1270
- *
1271
- * Usage:
1272
- * ql.on('beforeInsert', 'user', async (ctx) => { ... });
1273
- */
1274
- on(
1275
- event: string,
1276
- objectName: string,
1277
- handler: (ctx: HookContext) => Promise<void> | void,
1278
- packageId?: string
1279
- ): void {
1280
- this.registerHook(event, handler, { object: objectName, packageId });
1281
- }
1282
-
1283
- /**
1284
- * Remove all hooks, actions, and objects contributed by a package.
1285
- */
1286
- removePackage(packageId: string): void {
1287
- // Remove hooks
1288
- for (const [key, handlers] of this.hooks.entries()) {
1289
- const filtered = handlers.filter(h => h.packageId !== packageId);
1290
- if (filtered.length !== handlers.length) {
1291
- this.hooks.set(key, filtered);
1292
- }
1293
- }
1294
- // Remove actions
1295
- this.removeActionsByPackage(packageId);
1296
- // Remove objects
1297
- SchemaRegistry.unregisterObjectsByPackage(packageId, true);
1298
- }
1299
-
1300
- /**
1301
- * Gracefully shut down the engine, disconnecting all drivers.
1302
- * Alias for destroy() — matches @objectql/core close() API.
1303
- */
1304
- async close(): Promise<void> {
1305
- return this.destroy();
1306
- }
1307
-
1308
- /**
1309
- * Create a scoped execution context bound to this engine.
1310
- *
1311
- * Usage:
1312
- * const ctx = engine.createContext({ userId: '...', tenantId: '...' });
1313
- * const users = ctx.object('user');
1314
- * await users.find({ filter: { status: 'active' } });
1315
- */
1316
- createContext(ctx: Partial<ExecutionContext>): ScopedContext {
1317
- return new ScopedContext(
1318
- ExecutionContextSchema.parse(ctx),
1319
- this
1320
- );
1321
- }
1322
-
1323
- /**
1324
- * Static factory: create a fully configured ObjectQL instance.
1325
- *
1326
- * Matches @objectql/core's `new ObjectQL(config)` pattern but also
1327
- * registers drivers and objects, then calls init().
1328
- *
1329
- * Usage:
1330
- * const ql = await ObjectQL.create({
1331
- * datasources: { default: myDriver },
1332
- * objects: { user: { name: 'user', fields: { ... } } }
1333
- * });
1334
- */
1335
- static async create(config: {
1336
- datasources?: Record<string, DriverInterface>;
1337
- objects?: Record<string, ServiceObject>;
1338
- hooks?: Array<{ event: string; object: string; handler: (ctx: HookContext) => Promise<void> | void }>;
1339
- }): Promise<ObjectQL> {
1340
- const ql = new ObjectQL();
1341
-
1342
- // Register drivers
1343
- if (config.datasources) {
1344
- for (const [name, driver] of Object.entries(config.datasources)) {
1345
- // Set driver name if not already set
1346
- if (!driver.name) {
1347
- (driver as any).name = name;
1348
- }
1349
- ql.registerDriver(driver, name === 'default');
1350
- }
1351
- }
1352
-
1353
- // Register objects
1354
- if (config.objects) {
1355
- for (const [_key, schema] of Object.entries(config.objects)) {
1356
- ql.registerObject(schema);
1357
- }
1358
- }
1359
-
1360
- // Register hooks
1361
- if (config.hooks) {
1362
- for (const hook of config.hooks) {
1363
- ql.on(hook.event, hook.object, hook.handler);
1364
- }
1365
- }
1366
-
1367
- // Initialize (connect drivers)
1368
- await ql.init();
1369
-
1370
- return ql;
1371
- }
1372
- }
1373
-
1374
- /**
1375
- * Repository scoped to a single object, bound to an execution context.
1376
- *
1377
- * Provides both IDataEngine-style methods (find, insert, update, delete)
1378
- * and convenience aliases (create, updateById, deleteById) matching
1379
- * the @objectql/core ObjectRepository API.
1380
- */
1381
- export class ObjectRepository {
1382
- constructor(
1383
- private objectName: string,
1384
- private context: ExecutionContext,
1385
- private engine: IDataEngine & { executeAction?: (o: string, a: string, c: any) => Promise<any> }
1386
- ) {}
1387
-
1388
- async find(query: any = {}): Promise<any[]> {
1389
- return this.engine.find(this.objectName, {
1390
- ...query,
1391
- context: this.context,
1392
- });
1393
- }
1394
-
1395
- async findOne(query: any = {}): Promise<any> {
1396
- return this.engine.findOne(this.objectName, {
1397
- ...query,
1398
- context: this.context,
1399
- });
1400
- }
1401
-
1402
- async insert(data: any): Promise<any> {
1403
- return this.engine.insert(this.objectName, data, {
1404
- context: this.context,
1405
- });
1406
- }
1407
-
1408
- /** Alias for insert() — matches @objectql/core convention */
1409
- async create(data: any): Promise<any> {
1410
- return this.insert(data);
1411
- }
1412
-
1413
- async update(data: any, options: any = {}): Promise<any> {
1414
- return this.engine.update(this.objectName, data, {
1415
- ...options,
1416
- context: this.context,
1417
- });
1418
- }
1419
-
1420
- /** Update a single record by ID */
1421
- async updateById(id: string | number, data: any): Promise<any> {
1422
- return this.engine.update(this.objectName, { ...data, id: id }, {
1423
- where: { id: id },
1424
- context: this.context,
1425
- });
1426
- }
1427
-
1428
- async delete(options: any = {}): Promise<any> {
1429
- return this.engine.delete(this.objectName, {
1430
- ...options,
1431
- context: this.context,
1432
- });
1433
- }
1434
-
1435
- /** Delete a single record by ID */
1436
- async deleteById(id: string | number): Promise<any> {
1437
- return this.engine.delete(this.objectName, {
1438
- where: { id: id },
1439
- context: this.context,
1440
- });
1441
- }
1442
-
1443
- async count(query: any = {}): Promise<number> {
1444
- return this.engine.count(this.objectName, {
1445
- ...query,
1446
- context: this.context,
1447
- });
1448
- }
1449
-
1450
- /** Aggregate query */
1451
- async aggregate(query: any = {}): Promise<any[]> {
1452
- return this.engine.aggregate(this.objectName, {
1453
- ...query,
1454
- context: this.context,
1455
- });
1456
- }
1457
-
1458
- /** Execute a named action registered on this object */
1459
- async execute(actionName: string, params?: any): Promise<any> {
1460
- if (this.engine.executeAction) {
1461
- return this.engine.executeAction(this.objectName, actionName, {
1462
- ...params,
1463
- userId: this.context.userId,
1464
- tenantId: this.context.tenantId,
1465
- roles: this.context.roles,
1466
- });
1467
- }
1468
- throw new Error(`Actions not supported by engine`);
1469
- }
1470
- }
1471
-
1472
- /**
1473
- * Scoped execution context with object() accessor.
1474
- *
1475
- * Provides identity (userId, tenantId/spaceId, roles),
1476
- * repository access via object(), privilege escalation via sudo(),
1477
- * and transactional execution via transaction().
1478
- */
1479
- export class ScopedContext {
1480
- constructor(
1481
- private executionContext: ExecutionContext,
1482
- private engine: IDataEngine
1483
- ) {}
1484
-
1485
- /** Get a repository scoped to this context */
1486
- object(name: string): ObjectRepository {
1487
- return new ObjectRepository(name, this.executionContext, this.engine as any);
1488
- }
1489
-
1490
- /** Create an elevated (system) context */
1491
- sudo(): ScopedContext {
1492
- return new ScopedContext(
1493
- { ...this.executionContext, isSystem: true },
1494
- this.engine
1495
- );
1496
- }
1497
-
1498
- /**
1499
- * Execute a callback within a database transaction.
1500
- *
1501
- * The callback receives a new ScopedContext whose operations
1502
- * share the same transaction handle. If the callback throws,
1503
- * the transaction is rolled back; otherwise it is committed.
1504
- *
1505
- * Falls back to non-transactional execution if the driver
1506
- * does not support transactions.
1507
- */
1508
- async transaction(callback: (trxCtx: ScopedContext) => Promise<any>): Promise<any> {
1509
- const engine = this.engine as any;
1510
-
1511
- // Find the default driver for transaction support
1512
- const driver = engine.defaultDriver
1513
- ? engine.drivers?.get(engine.defaultDriver)
1514
- : undefined;
1515
-
1516
- if (!driver?.beginTransaction) {
1517
- // No transaction support — execute directly
1518
- return callback(this);
1519
- }
1520
-
1521
- const trx = await driver.beginTransaction();
1522
- const trxCtx = new ScopedContext(
1523
- { ...this.executionContext, transaction: trx },
1524
- this.engine
1525
- );
1526
-
1527
- try {
1528
- const result = await callback(trxCtx);
1529
- if (driver.commit) await driver.commit(trx);
1530
- else if (driver.commitTransaction) await driver.commitTransaction(trx);
1531
- return result;
1532
- } catch (error) {
1533
- if (driver.rollback) await driver.rollback(trx);
1534
- else if (driver.rollbackTransaction) await driver.rollbackTransaction(trx);
1535
- throw error;
1536
- }
1537
- }
1538
-
1539
- get userId() { return this.executionContext.userId; }
1540
- get tenantId() { return this.executionContext.tenantId; }
1541
- /** Alias for tenantId — matches ObjectQLContext.spaceId convention */
1542
- get spaceId() { return this.executionContext.tenantId; }
1543
- get roles() { return this.executionContext.roles; }
1544
- get isSystem() { return this.executionContext.isSystem; }
1545
-
1546
- /** Internal: expose the transaction handle for driver-level access */
1547
- get transactionHandle() { return this.executionContext.transaction; }
1548
- }