-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathengine.ts
More file actions
3407 lines (3129 loc) · 141 KB
/
Copy pathengine.ts
File metadata and controls
3407 lines (3129 loc) · 141 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { AsyncLocalStorage } from 'node:async_hooks';
import { QueryAST, HookContext, ServiceObject } from '@objectstack/spec/data';
import {
EngineQueryOptions,
DataEngineInsertOptions,
EngineUpdateOptions,
EngineDeleteOptions,
EngineAggregateOptions,
EngineCountOptions
} from '@objectstack/spec/data';
import { parseAutonumberFormat, renderAutonumber, missingFieldValues } from '@objectstack/spec/data';
import { ExecutionContext, ExecutionContextSchema } from '@objectstack/spec/kernel';
import { IDataDriver, IDataEngine, Logger, createLogger } from '@objectstack/core';
import { CoreServiceName, StorageNameMapping } from '@objectstack/spec/system';
import { IRealtimeService, RealtimeEventPayload } from '@objectstack/spec/contracts';
import type { ICryptoProvider, CryptoHandle } from '@objectstack/spec/contracts';
import {
collectSecretFields,
makeSecretRef,
parseSecretRef,
isSecretRef,
SECRET_MASK,
} from './secret-fields.js';
import { pluralToSingular, ExternalWriteForbiddenError } from '@objectstack/spec/shared';
import { SchemaRegistry, computeFQN } from './registry.js';
import { expandSearchToFilter } from './search-filter.js';
import { ExpressionEngine } from '@objectstack/formula';
import type { Expression } from '@objectstack/spec';
import { isAggregatedViewContainer, expandViewContainer } from '@objectstack/spec';
import { bindHooksToEngine } from './hook-binder.js';
import { validateRecord, normalizeMultiValueFields, coerceBooleanFields } from './validation/record-validator.js';
import { evaluateValidationRules, needsPriorRecord, stripReadonlyWhenFields } from './validation/rule-validator.js';
import { applyInMemoryAggregation } from './in-memory-aggregation.js';
interface FormulaPlanEntry { name: string; expression: Expression; }
function planFormulaProjection(
schema: any,
requestedFields: string[] | undefined
): { plan: FormulaPlanEntry[]; projected?: string[] } {
if (!schema?.fields) return { plan: [] };
const allFieldNames = Object.keys(schema.fields);
// When no explicit projection, evaluate every formula field on the schema —
// matches REST default of "return everything". Explicit projection still
// honours the caller's selection.
const targets = (Array.isArray(requestedFields) && requestedFields.length > 0)
? requestedFields
: allFieldNames;
const plan: FormulaPlanEntry[] = [];
const projected = new Set<string>();
for (const f of targets) {
const def = (schema.fields as any)[f];
if (def?.type === 'formula' && def.expression) {
// Normalize string-shorthand → Expression envelope (M9 transition).
const expr: Expression = typeof def.expression === 'string'
? { dialect: 'cel', source: def.expression }
: def.expression;
plan.push({ name: f, expression: expr });
// Pre-compile to surface syntax errors at planning stage rather than
// per-row eval. Dependency discovery (which fields the formula reads)
// is no longer used — CEL uses dynamic projection via `record.<field>`.
ExpressionEngine.compile(expr);
} else if (Array.isArray(requestedFields) && requestedFields.length > 0) {
projected.add(f);
}
}
if (plan.length === 0) return { plan: [] };
// For formulas: project all schema fields so CEL `record.<field>` lookups
// see complete data. Static dependency analysis on AST is M9.7 work.
if (Array.isArray(requestedFields) && requestedFields.length > 0) {
if (!projected.has('id')) projected.add('id');
for (const fname of allFieldNames) {
// Skip formula fields themselves — they are virtual and not
// projectable by the underlying driver. Without this guard the
// SQL driver emits `SELECT response_rate ...` which fails as
// "no such column" and the driver returns [] (silently).
const fdef = (schema.fields as any)[fname];
if (fdef?.type === 'formula') continue;
projected.add(fname);
}
return { plan, projected: Array.from(projected) };
}
// Implicit/full projection — leave projected undefined so the driver
// returns its default columns (typically *).
return { plan };
}
/**
* Evaluate read-time formula virtual fields against the raw rows.
*
* The eval context mirrors `applyFieldDefaults` so formula and default
* expressions see the same shape: a `now` pinned ONCE per operation (every row
* and every formula field in one `find()` observes the same instant —
* determinism, and no per-eval `new Date()` drift), plus `os.user` / `os.org`
* resolved from the execution context (so a computed field can reference the
* caller, e.g. `os.user.id`). Previously this passed only `{ record }`, so
* `now()`/`today()` ran against live wall-clock and user/org were unreachable.
*
* (ADR-0053 Phase 2 will additionally thread `timezone` here once
* `ExecutionContext.timezone` exists — see #1980; this change is independent
* of timezone.)
*/
function applyFormulaPlan(
plan: FormulaPlanEntry[],
records: any[],
execCtx?: ExecutionContext,
nowSnapshot?: Date,
): void {
if (!plan.length) return;
const now = nowSnapshot ?? new Date();
const timezone = execCtx?.timezone;
const user = execCtx?.userId ? { id: String(execCtx.userId), positions: execCtx?.positions ?? [] } : undefined;
const org = execCtx?.tenantId ? { id: String(execCtx.tenantId) } : undefined;
for (const rec of records) {
if (rec == null) continue;
for (const fp of plan) {
const r = ExpressionEngine.evaluate(fp.expression, { now, timezone, user, org, record: rec });
rec[fp.name] = r.ok ? r.value : null;
}
}
}
export type HookHandler = (context: HookContext) => Promise<void> | void;
/**
* Per-object hook entry with priority support
*/
export interface HookEntry {
handler: HookHandler;
object?: string | string[]; // undefined = global hook
priority: number;
packageId?: string;
/**
* Original metadata-form `Hook` definition this entry was bound from
* (when registered via `bindHooksToEngine`). Pure code-paths that call
* `engine.registerHook` directly leave this undefined.
*/
meta?: any;
/** Hook `name` from metadata; used for diagnostics & deduplication. */
hookName?: string;
}
/** Function registry entry — see `registerFunction`. */
interface FunctionEntry {
handler: HookHandler;
packageId?: string;
}
/**
* Operation Context for Middleware Chain
*/
export interface OperationContext {
object: string;
operation: 'find' | 'findOne' | 'insert' | 'update' | 'delete' | 'count' | 'aggregate';
ast?: QueryAST;
data?: any;
options?: any;
context?: ExecutionContext;
result?: any;
}
/**
* Trailing options for the READ methods (find / findOne / count / aggregate).
*
* Historically the read methods took their execution context INSIDE the query
* (`query.context`), while the WRITE methods (insert / update) took it in a
* trailing `options.context`. That split was a footgun: the same `{ context }`
* object is correct as the 3rd arg to `insert` but was SILENTLY DROPPED as the
* 3rd arg to `find` — a class of bugs where an intended `isSystem` bypass just
* vanished (e.g. control-plane reads coming back empty once org-scoping hooks
* were added). We now ALSO accept `context` via this trailing options arg on the
* read methods, so "execution context goes in the trailing options argument" is
* one rule across reads and writes. `query.context` remains supported; when both
* are given, `options.context` wins (it is the explicit channel).
*/
export interface EngineReadOptions {
context?: ExecutionContext;
}
/** Merge read-path execution context from the query and the trailing options. */
function mergeReadContext(
fromQuery?: ExecutionContext,
fromOptions?: ExecutionContext,
): ExecutionContext | undefined {
if (fromOptions == null) return fromQuery;
if (fromQuery == null) return fromOptions;
return { ...fromQuery, ...fromOptions };
}
/**
* Engine Middleware (Onion model)
*/
export type EngineMiddleware = (
ctx: OperationContext,
next: () => Promise<void>
) => Promise<void>;
/**
* Host Context provided to plugins (Internal ObjectQL Plugin System)
*/
export interface ObjectQLHostContext {
ql: ObjectQL;
logger: Logger;
// Extensible map for host-specific globals (like HTTP Router, etc.)
[key: string]: any;
}
/**
* Derive the registry key for a metadata item.
*
* Most metadata items expose a top-level `name` (or `id`). The `View`
* container defined by `@objectstack/spec/ui` is special: it aggregates
* `list / form / listViews / formViews` for a single object and is
* keyed implicitly by its target object name (see `data.object`).
*
* Per spec, `ViewSchema` does NOT have a top-level `name` field
* (view.zod.ts), so we resolve it from the inner data source. This
* matches the server-side metadata API contract (`/api/v1/meta/views/:object`).
*/
function resolveMetadataItemName(key: string, item: any): string | undefined {
if (!item) return undefined;
if (item.name) return item.name;
if (item.id) return item.id;
if (key === 'views') {
// Independent ViewItems ("Object has-many View") carry a top-level `name`
// (handled above) and bind to their object via `object`. The aggregated
// container has no top-level name/object, so fall back to its inner data
// source — matching the loader's expansion key.
return (
item?.object ||
item?.list?.data?.object ||
item?.form?.data?.object ||
undefined
);
}
return undefined;
}
/**
* ObjectQL Engine
*
* Implements the IDataEngine interface for data persistence.
* Acts as the reference implementation for:
* - CoreServiceName.data (CRUD)
* - CoreServiceName.metadata (Schema Registry)
*/
/** A roll-up `summary` field on a parent object that aggregates a child. */
interface SummaryDescriptor {
parentObject: string;
summaryField: string;
/** FK field on the child pointing back to the parent. */
fkField: string;
fn: 'count' | 'sum' | 'min' | 'max' | 'avg';
/** Child field aggregated (unused for count). */
sourceField: string;
}
export class ObjectQL implements IDataEngine {
/**
* Ambient transaction store (ADR-0034). While a `transaction()` callback
* runs, the active transaction handle lives here so that EVERY data
* operation — including internal reads done during a write (reference
* checks, hooks, expand) — automatically binds to the same connection
* instead of asking the pool for another one and deadlocking on the
* single-connection SQLite pool.
*/
private readonly txStore = new AsyncLocalStorage<{ transaction: unknown }>();
private drivers = new Map<string, IDataDriver>();
private defaultDriver: string | null = null;
private logger: Logger;
// Datasource mapping rules (imported from defineStack)
private datasourceMapping: Array<{
namespace?: string;
package?: string;
objectPattern?: string;
default?: boolean;
datasource: string;
priority?: number;
}> = [];
// Package manifests registry (for defaultDatasource lookup)
private manifests = new Map<string, any>();
// Datasource definitions by name (ADR-0015): carries schemaMode +
// external.allowWrites so the write gate (Gate 3) can enforce federation
// ownership. Populated from manifests in registerApp and via
// registerDatasourceDef. Absent entry ⇒ treated as managed (default DB).
private datasourceDefs = new Map<string, { schemaMode?: string; external?: { allowWrites?: boolean } }>();
// Per-object hooks with priority support
private hooks: Map<string, HookEntry[]> = new Map([
['beforeFind', []], ['afterFind', []],
['beforeInsert', []], ['afterInsert', []],
['beforeUpdate', []], ['afterUpdate', []],
['beforeDelete', []], ['afterDelete', []],
]);
// Middleware chain (onion model)
private middlewares: Array<{
fn: EngineMiddleware;
object?: string;
}> = [];
// Action registry: key = "objectName:actionName"
private actions = new Map<string, { handler: (ctx: any) => Promise<any> | any; package?: string }>();
// Function registry: name → handler. Used by `bindHooksToEngine` to
// resolve string-named hook handlers (the JSON-safe form). Populated by
// `defineStack({ functions })` via `AppPlugin`, or directly via
// `engine.registerFunction(...)`.
private functions = new Map<string, FunctionEntry>();
// Host provided context additions (e.g. Server router)
private hostContext: Record<string, any> = {};
// Realtime service for event publishing
private realtimeService?: IRealtimeService;
// Crypto provider backing `secret`-typed fields. Optional: when absent,
// writing an object that declares a secret field fails closed (never
// persists cleartext). Injected by the host via setCryptoProvider().
private cryptoProvider?: ICryptoProvider;
// Per-engine SchemaRegistry instance.
//
// Historically SchemaRegistry was a process-wide singleton of static state,
// which broke multi-environment servers: a project kernel would inherit every
// object registered by the control plane (e.g. sys_metadata), and
// getDriver()'s owner lookup would route CRUD to the wrong database. Each
// engine now owns its registry so kernels are fully isolated.
private _registry: SchemaRegistry = new SchemaRegistry();
constructor(hostContext: Record<string, any> = {}) {
this.hostContext = hostContext;
// Use provided logger or create a new one
this.logger = hostContext.logger || createLogger({ level: 'info', format: 'pretty' });
// Pick up production hardening switches from env so deployers can
// enforce strict-body without code changes:
// OBJECTQL_STRICT_HOOKS=1 → unresolved hooks throw at bind time
// OBJECTQL_WARN_LEGACY_HANDLER=1 → log a deprecation per legacy bind
if (process?.env?.OBJECTQL_STRICT_HOOKS === '1') {
(this as any)._strictHookBinding = true;
}
if (process?.env?.OBJECTQL_WARN_LEGACY_HANDLER === '1') {
(this as any)._warnLegacyHandler = true;
}
this.logger.info('ObjectQL Engine Instance Created');
}
/**
* Service Status Report
* Used by Kernel to verify health and capabilities.
*/
getStatus() {
return {
name: CoreServiceName.enum.data,
status: 'running',
version: '0.9.0',
features: ['crud', 'query', 'aggregate', 'transactions', 'metadata']
};
}
/**
* Expose the SchemaRegistry for plugins to register metadata.
*
* Returns the per-engine instance, NOT the class. Each ObjectQL engine
* owns its registry so multi-environment kernels remain isolated.
*/
get registry(): SchemaRegistry {
return this._registry;
}
/**
* Load and Register a Plugin
*/
async use(manifestPart: any, runtimePart?: any) {
this.logger.debug('Loading plugin', {
hasManifest: !!manifestPart,
hasRuntime: !!runtimePart
});
// 1. Validate / Register Manifest
if (manifestPart) {
this.registerApp(manifestPart);
}
// 2. Execute Runtime
if (runtimePart) {
const pluginDef = (runtimePart as any).default || runtimePart;
if (pluginDef.onEnable) {
this.logger.debug('Executing plugin runtime onEnable');
const context: ObjectQLHostContext = {
ql: this,
logger: this.logger,
// Expose the driver registry helper explicitly if needed
drivers: {
register: (driver: IDataDriver) => this.registerDriver(driver)
},
...this.hostContext
};
await pluginDef.onEnable(context);
this.logger.debug('Plugin runtime onEnable completed');
}
}
}
/**
* Register a hook
* @param event The event name (e.g. 'beforeFind', 'afterInsert')
* @param handler The handler function
* @param options Optional: target object(s) and priority
*/
registerHook(event: string, handler: HookHandler, options?: {
object?: string | string[];
priority?: number;
packageId?: string;
/** Original metadata Hook definition (set by `bindHooksToEngine`). */
meta?: any;
/** Stable name from metadata (set by `bindHooksToEngine`). */
hookName?: string;
}) {
if (!this.hooks.has(event)) {
this.hooks.set(event, []);
}
const entries = this.hooks.get(event)!;
entries.push({
handler,
object: options?.object,
priority: options?.priority ?? 100,
packageId: options?.packageId,
meta: options?.meta,
hookName: options?.hookName,
});
// Sort by priority (lower runs first)
entries.sort((a, b) => a.priority - b.priority);
this.logger.debug('Registered hook', { event, object: options?.object, priority: options?.priority ?? 100, totalHandlers: entries.length });
}
/**
* Remove all hooks registered under a given `packageId`. Used by
* `bindHooksToEngine` to make re-binding (hot reload, app reinstall)
* idempotent, and by app uninstall flows.
*/
unregisterHooksByPackage(packageId: string): number {
if (!packageId) return 0;
let removed = 0;
for (const [event, entries] of this.hooks.entries()) {
const before = entries.length;
const kept = entries.filter((e) => e.packageId !== packageId);
if (kept.length !== before) {
this.hooks.set(event, kept);
removed += before - kept.length;
}
}
if (removed > 0) {
this.logger.debug('Unregistered hooks by package', { packageId, removed });
}
return removed;
}
/**
* Register a named function handler that can later be referenced by
* string from a `Hook.handler` field. This is the JSON-safe form of
* handler binding — declarative metadata persisted to disk or shipped
* over the wire only carries the name.
*/
registerFunction(name: string, handler: HookHandler, packageId?: string): void {
if (!name || typeof handler !== 'function') return;
this.functions.set(name, { handler, packageId });
this.logger.debug('Registered function', { name, packageId });
}
/** Look up a registered function by name. */
resolveFunction(name: string): HookHandler | undefined {
return this.functions.get(name)?.handler;
}
/** Remove all functions registered under a given `packageId`. */
unregisterFunctionsByPackage(packageId: string): number {
if (!packageId) return 0;
let removed = 0;
for (const [name, entry] of this.functions.entries()) {
if (entry.packageId === packageId) {
this.functions.delete(name);
removed += 1;
}
}
if (removed > 0) {
this.logger.debug('Unregistered functions by package', { packageId, removed });
}
return removed;
}
/**
* Bind a list of declarative `Hook` metadata definitions to this engine.
*
* Convenience proxy to the canonical `bindHooksToEngine` so callers do
* not need a separate import. Use `import { bindHooksToEngine } from
* '@objectstack/objectql'` directly when you want the result object.
*/
bindHooks(hooks: any[] | undefined, opts?: {
packageId?: string;
functions?: Record<string, HookHandler>;
bodyRunner?: any;
strict?: boolean;
warnLegacyHandler?: boolean;
metrics?: any;
}): void {
const merged = { ...(opts ?? {}), logger: this.logger } as any;
if (!merged.bodyRunner && (this as any)._defaultBodyRunner) {
merged.bodyRunner = (this as any)._defaultBodyRunner;
}
if (merged.strict === undefined && (this as any)._strictHookBinding) {
merged.strict = true;
}
if (merged.warnLegacyHandler === undefined && (this as any)._warnLegacyHandler) {
merged.warnLegacyHandler = true;
}
if (!merged.metrics && (this as any)._hookMetricsRecorder) {
merged.metrics = (this as any)._hookMetricsRecorder;
}
bindHooksToEngine(this, hooks, merged);
}
/**
* Install a default body-runner used when `bindHooks` is called without
* an explicit one. The runtime layer sets this once on each per-project
* engine so every binding path (template seed, metadata sync, AppPlugin)
* can execute hook `body.source` consistently.
*/
setDefaultBodyRunner(runner: any): void {
(this as any)._defaultBodyRunner = runner;
}
/**
* Install a default ACTION body-runner factory: `(actionDef) => handler |
* undefined`. The runtime layer sets this once per engine (same boot point
* as {@link setDefaultBodyRunner}) so runtime-authored `action` metadata —
* which registers through paths that have no sandbox access of their own,
* notably ObjectQLPlugin's metadata-service re-sync — can turn a declarative
* `body` into an executable `registerAction` handler. The factory returns
* `undefined` for actions it cannot run (no `body`, invalid shape), which
* callers must treat as "skip", not an error.
*/
setDefaultActionRunner(runner: (actionDef: any) => ((ctx: any) => Promise<unknown>) | undefined): void {
(this as any)._defaultActionRunner = runner;
}
/**
* Toggle strict hook-binding mode for this engine. When enabled, every
* subsequent `bindHooks` call rejects on the first unresolved hook
* instead of silently warning. Production runtimes should enable this.
*/
setStrictHookBinding(strict: boolean): void {
(this as any)._strictHookBinding = strict;
}
/** Toggle deprecation warnings for hooks still using legacy `handler` ref. */
setWarnLegacyHandler(warn: boolean): void {
(this as any)._warnLegacyHandler = warn;
}
/**
* Install a metrics recorder used by every subsequent `bindHooks` call.
* The recorder's methods are invoked per-execution to count outcomes
* (success / error / timeout / capability_rejected), skips, and retries.
* Defaults to no-op so the engine pays zero cost when nobody is observing.
*/
setHookMetricsRecorder(recorder: any): void {
(this as any)._hookMetricsRecorder = recorder;
}
/** Read the engine's installed metrics recorder, if any. */
getHookMetricsRecorder(): any {
return (this as any)._hookMetricsRecorder;
}
public async triggerHooks(event: string, context: HookContext) {
const entries = this.hooks.get(event) || [];
if (entries.length === 0) {
this.logger.debug('No hooks registered for event', { event });
return;
}
this.logger.debug('Triggering hooks', { event, count: entries.length });
// `session.skipAutomations` (set from ExecutionContext.skipAutomations —
// import with "run automations & triggers" unchecked, import undo)
// suppresses hooks bound FROM METADATA (`bindHooksToEngine` stamps
// `entry.meta`). Hooks registered in code by plugins — audit, capability
// gates, sharing projection — have no `meta` and always run: the opt-out
// must never bypass security or audit (#2922).
const skipAutomations =
(context.session as { skipAutomations?: boolean } | undefined)?.skipAutomations === true;
for (const entry of entries) {
// Per-object matching
if (entry.object) {
const targets = Array.isArray(entry.object) ? entry.object : [entry.object];
if (!targets.includes('*') && !targets.includes(context.object)) {
continue; // Skip non-matching hooks
}
}
if (skipAutomations && entry.meta) {
this.logger.debug('Skipping metadata-bound hook (skipAutomations)', { event, hook: entry.hookName });
continue;
}
await entry.handler(context);
}
}
// ========================================
// Action System
// ========================================
/**
* Register a named action on an object.
* Actions are custom business logic callable via `repo.execute(actionName, params)`.
*
* @param objectName Target object
* @param actionName Unique action name within the object
* @param handler Handler function
* @param packageName Optional package owner (for cleanup)
*/
registerAction(objectName: string, actionName: string, handler: (ctx: any) => Promise<any> | any, packageName?: string): void {
const key = `${objectName}:${actionName}`;
this.actions.set(key, { handler, package: packageName });
this.logger.debug('Registered action', { objectName, actionName, package: packageName });
}
/**
* Execute a named action on an object.
*/
async executeAction(objectName: string, actionName: string, ctx: any): Promise<any> {
const entry = this.actions.get(`${objectName}:${actionName}`);
if (!entry) {
throw new Error(`Action '${actionName}' on object '${objectName}' not found`);
}
return entry.handler(ctx);
}
/**
* Remove all actions registered by a specific package.
*/
removeActionsByPackage(packageName: string): void {
for (const [key, entry] of this.actions.entries()) {
if (entry.package === packageName) {
this.actions.delete(key);
}
}
}
/**
* Register a middleware function
* Middlewares execute in onion model around every data operation.
* @param fn The middleware function
* @param options Optional: target object filter
*/
registerMiddleware(fn: EngineMiddleware, options?: { object?: string }): void {
this.middlewares.push({ fn, object: options?.object });
this.logger.debug('Registered middleware', { object: options?.object, total: this.middlewares.length });
}
/**
* Execute an operation through the middleware chain
*/
private async executeWithMiddleware(ctx: OperationContext, executor: () => Promise<any>): Promise<any> {
const applicable = this.middlewares.filter(m =>
!m.object || m.object === '*' || m.object === ctx.object
);
let index = 0;
const next = async (): Promise<void> => {
if (index < applicable.length) {
const mw = applicable[index++];
await mw.fn(ctx, next);
} else {
ctx.result = await executor();
}
};
await next();
return ctx.result;
}
/**
* Build a HookContext.session from ExecutionContext
*/
private buildSession(execCtx?: ExecutionContext): HookContext['session'] {
if (!execCtx) return undefined;
return {
userId: execCtx.userId,
tenantId: execCtx.tenantId,
positions: execCtx.positions,
accessToken: execCtx.accessToken,
// Propagate system-elevated flag so hooks can distinguish engine
// self-writes (e.g. approval status mirror) from genuine user writes.
...((execCtx as any).isSystem ? { isSystem: true } : {}),
// Propagate the automation-suppression flag so the record-change trigger
// can skip flow dispatch for seed/bulk writes (ADR: seed loads end-state
// data, not user events). `skipAutomations` implies `skipTriggers` —
// suppressing metadata hooks while still dispatching flows would leave
// the "run automations & triggers" opt-out half-working (#2922).
...((execCtx as any).skipTriggers || (execCtx as any).skipAutomations ? { skipTriggers: true } : {}),
// Propagate the full automation opt-out so `triggerHooks` can skip
// metadata-bound hooks (import with "run automations" unchecked, undo).
...((execCtx as any).skipAutomations ? { skipAutomations: true } : {}),
} as HookContext['session'];
}
/**
* Build the acting-user object (ADR-0068 EvalUser shape) surfaced to
* validation-time predicates as `current_user` — notably per-option
* `visibleWhen` authorization gating (objectui#2284). Returns undefined for
* system / unauthenticated writes, where membership predicates then fail-open.
*/
private buildEvalUser(
execCtx?: ExecutionContext,
): { id: string; positions: string[]; organizationId: string | null } | undefined {
if (!execCtx || execCtx.userId == null) return undefined;
return {
id: String(execCtx.userId),
positions: execCtx.positions ?? [],
organizationId: execCtx.tenantId != null ? String(execCtx.tenantId) : null,
};
}
/**
* Build the DriverOptions blob passed to every IDataDriver call.
*
* Always carries `tenantId` from the active ExecutionContext so the
* driver can enforce per-tenant isolation (SQL driver auto-scopes reads
* and auto-injects the tenant column on writes). Existing user-supplied
* shapes (transactions, AST extras) are preserved by spreading them
* first.
*
* System / isSystem callers may still cross tenants by clearing
* `tenantId` themselves on the resulting object; this helper does not
* mask the system path.
*/
private buildDriverOptions(execCtx?: ExecutionContext, base?: any): any {
// The open transaction may arrive explicitly via the context, or ambiently
// via txStore when an internal query runs during a transactional write
// (ADR-0034). Explicit wins; ambient is the safety net.
const tx = execCtx?.transaction !== undefined
? execCtx.transaction
: this.txStore.getStore()?.transaction;
const hasTx = tx !== undefined;
const hasTenant = execCtx?.tenantId !== undefined;
const hasTz = execCtx?.timezone !== undefined;
const isSystem = execCtx?.isSystem === true;
if (!hasTx && !hasTenant && !isSystem && !hasTz) return base;
const opts: any = base && typeof base === 'object' ? { ...base } : {};
if (hasTx && opts.transaction === undefined) {
opts.transaction = tx;
}
if (hasTenant && opts.tenantId === undefined) {
opts.tenantId = execCtx!.tenantId;
}
if (hasTz && opts.timezone === undefined) {
// Thread the business timezone so date-dependent driver generation
// (autonumber `{YYYYMMDD}` tokens) resolves the calendar day correctly.
opts.timezone = execCtx!.timezone;
}
if (isSystem && opts.bypassTenantAudit === undefined) {
// System-elevated writes (boot-time seeds, internal mirrors, scheduled
// hooks) are unscoped by design — silence the audit warn for them but
// still flag genuine user-path bugs.
opts.bypassTenantAudit = true;
}
return opts;
}
/**
* Build a HookContext.api: a ScopedContext that hooks can use to
* read/write other objects within the same execution context.
* Falls back to a system-elevated empty context when no execCtx
* is supplied (e.g. system-triggered hooks).
*/
private buildHookApi(execCtx?: ExecutionContext): ScopedContext {
const safeCtx: ExecutionContext = execCtx ?? ({ isSystem: true } as any);
return new ScopedContext(safeCtx, this as unknown as IDataEngine);
}
/**
* Apply field defaults to an incoming insert payload. Defaults that are
* Expression envelopes (e.g. `{ dialect: 'cel', source: 'today()' }`,
* `{ dialect: 'cel', source: 'os.user.id' }`) are evaluated via
* `ExpressionEngine` against the calling user/org/now snapshot. Static
* defaults are applied verbatim. Records that already supplied a value for a
* field are left untouched.
*
* "Supplied a value" means the field is present with a non-null value. Both an
* OMITTED field (`undefined`) and an EXPLICIT `null` are treated as "not
* supplied" and get the default. This runs on the INSERT path only, where a
* `null` from a form (an unpicked control serializes to `null`, not omission)
* unambiguously means "no value"; the UPDATE path never calls this, so a
* deliberate "set to null" on update is preserved (#2706). Empty string `''`
* is a real, user-entered value and is left as-is.
*
* Implements ROADMAP §M9.9b — `defaultValue` accepts Expression so authors
* can replace "write a hook to default to today/current-user" with a
* declarative `defaultValue: cel\`today()\``.
*/
private applyFieldDefaults(
object: string,
record: Record<string, unknown>,
execCtx?: ExecutionContext,
nowSnapshot?: Date,
): Record<string, unknown> {
const schema = this.getSchema(object);
const fieldsRaw = (schema as any)?.fields;
if (!fieldsRaw || typeof fieldsRaw !== 'object') return record;
// `fields` may be a Record<string, Field> (canonical) or an array (legacy).
const fieldEntries: Array<{ name: string; defaultValue?: unknown }> = Array.isArray(fieldsRaw)
? fieldsRaw
: Object.entries(fieldsRaw).map(([name, def]) => ({ name, ...(def as object) }));
const out = { ...record };
const now = nowSnapshot ?? new Date();
for (const f of fieldEntries) {
// Apply the default when the field is either OMITTED (`undefined`) or an
// EXPLICIT `null` — both mean "no value supplied" on insert (#2706). A
// real value (including `''`) is respected. Insert-only path, so an
// intentional "set to null" on update is never touched here.
if (out[f.name] != null) continue;
if (f.defaultValue == null) continue;
const dv = f.defaultValue;
if (typeof dv === 'object' && dv !== null && (dv as any).dialect && typeof (dv as any).source === 'string') {
const result = ExpressionEngine.evaluate(dv as any, {
now,
timezone: execCtx?.timezone,
user: execCtx?.userId ? { id: String(execCtx.userId), positions: execCtx?.positions ?? [] } : undefined,
org: execCtx?.tenantId ? { id: String(execCtx.tenantId) } : undefined,
record: out,
extra: { object },
});
if (result.ok) {
out[f.name] = result.value as unknown;
} else {
this.logger.warn('Failed to evaluate default expression', {
object, field: f.name, error: result.error,
});
}
} else if (dv === 'current_user') {
// `current_user` token → the acting user's id at insert time. Declarative
// counterpart to writing a beforeInsert hook; mirrors the 'NOW()' string
// convention and is resolved app-side per request (driver-agnostic), so
// `Field.user({ defaultValue: 'current_user' })` auto-fills the actor.
// When there is no authenticated user (system/anonymous), leave it unset
// and let required-validation decide — never stamp a bogus owner.
if (execCtx?.userId != null) out[f.name] = String(execCtx.userId);
} else {
out[f.name] = dv;
}
}
return out;
}
/**
* Generate values for empty `autonumber` fields on insert — ONLY for drivers
* that do not generate them natively (memory, mongodb). For SQL-backed objects
* the driver owns a persistent, atomic `_objectstack_sequences` table and
* advertises `supports.autonumber === true`; the engine then defers entirely
* and never pre-fills (so the persistent sequence is the single source of
* truth — see #1603). Required-validation exempts `autonumber` either way, so
* a `required` record number is never rejected for "missing" — the runtime
* owns the value, not the client.
*
* In the fallback path the next value is `max(existing) + 1`, seeded once per
* `object.field.<scope>` from the store then incremented in memory (monotonic
* within the process, resilient to deletions). The shared `autonumberFormat`
* renderer is honored end-to-end, so date tokens (`AD{YYYYMMDD}{0000}`), field
* interpolation (`{island_zone}{000}`) and per-scope reset behave identically
* to the SQL driver's persistent sequence (#1603). NOTE: this in-memory seeding
* is single-instance.
*/
private async applyAutonumbers(
object: string,
record: Record<string, unknown>,
execCtx?: ExecutionContext,
driverOwnsAutonumber?: boolean,
): Promise<void> {
if (driverOwnsAutonumber) return; // driver generates persistently in create()
const fields = (this.getSchema(object) as any)?.fields;
if (!fields || typeof fields !== 'object' || Array.isArray(fields)) return;
const now = new Date();
const timezone = execCtx?.timezone;
for (const [name, def] of Object.entries(fields)) {
if ((def as any)?.type !== 'autonumber') continue;
const current = record[name];
if (current != null && current !== '') continue; // respect explicit value
// Honor either the spec-canonical `autonumberFormat` or the shorthand
// `format` (both appear in metadata; the driver reads both too) — #1603.
const fmt = (def as any).autonumberFormat ?? (def as any).format;
const tokens = parseAutonumberFormat(typeof fmt === 'string' ? fmt : '');
// Refuse to generate when an interpolated `{field}` is empty — it would
// render to an empty prefix and merge this record into the wrong counter
// scope. Mirror the SQL driver so both paths fail identically (#1603).
const missing = missingFieldValues(tokens, record);
if (missing.length > 0) {
throw new Error(
`Cannot generate autonumber "${object}.${name}" (format "${fmt}"): ` +
`referenced field(s) [${missing.join(', ')}] are empty on the record. ` +
`Fields interpolated into an autonumber format must be set before the record is created.`,
);
}
// The counter scope is the rendered prefix (date/field tokens before the
// sequence slot); it is independent of the counter value, so a throwaway
// render with seq 0 yields the scope and the literal prefix to seed from.
const probe = renderAutonumber({ tokens, seq: 0, record, now, timezone });
const counterKey = `${object}.${name}.${probe.scope}`;
let next = this.autonumberCounters.get(counterKey);
if (next == null) next = await this.seedAutonumber(object, name, probe.prefix, execCtx);
next += 1;
this.autonumberCounters.set(counterKey, next);
record[name] = renderAutonumber({ tokens, seq: next, record, now, timezone }).value;
}
}
/**
* Seed the autonumber counter from the current max in store, scoped to
* `prefix`. With a non-empty prefix (date/field formats) only rows in the
* same scope count, and the counter is the digit-run immediately after the
* prefix; with an empty prefix (legacy fixed-prefix formats) the last digit
* run of the whole value is used, preserving the original behaviour.
*/
private async seedAutonumber(
object: string,
field: string,
prefix: string,
execCtx?: ExecutionContext,
): Promise<number> {
try {
const rows = await this.find(object, {
select: ['id', field],
limit: 5000,
context: execCtx,
} as any);
let max = 0;
for (const r of rows || []) {
const v = r?.[field];
if (v == null) continue;
const s = String(v);
if (prefix && !s.startsWith(prefix)) continue;
const tail = prefix ? s.slice(prefix.length) : s;
// With a prefix the counter is the digit run right after it; without one
// (legacy fixed-prefix formats) it is the LAST digit run. Both use the
// linear /\d+/g — a backtracking lookahead here is a polynomial-ReDoS
// sink on stored values full of zeros (CodeQL js/polynomial-redos).
let digits: string | undefined;
if (prefix) {
const head = tail.match(/^\d+/);
digits = head ? head[0] : undefined;
} else {
const runs = tail.match(/\d+/g);
digits = runs ? runs[runs.length - 1] : undefined;
}
if (digits) max = Math.max(max, parseInt(digits, 10) || 0);
}
return max;
} catch {
return 0;
}
}
/**
* Register contribution (Manifest)
*
* Installs the manifest as a Package (the unit of installation),
* then decomposes it into individual metadata items (objects, apps, actions, etc.)
* and registers each into the SchemaRegistry.
*
* Key: Package ≠ App. The manifest is the package. The apps[] array inside
* the manifest contains UI navigation definitions (AppSchema).
*/
registerApp(manifest: any) {
const id = manifest.id || manifest.name;
const namespace = manifest.namespace as string | undefined;
this.invalidateSummaryIndex(); // new objects may add/change summary fields
this.logger.debug('Registering package manifest', { id, namespace });
console.warn(`[ObjectQL:registerApp] id=${id} flows=${Array.isArray(manifest.flows) ? manifest.flows.length : typeof manifest.flows} keys=${Object.keys(manifest).join(',')}`);
// Store manifest for defaultDatasource lookup
if (id) {
this.manifests.set(id, manifest);
}
// Index datasource definitions (ADR-0015) so the write gate can read
// schemaMode + external.allowWrites. Manifests may carry `datasources`
// as an array or a name-keyed map.
if (manifest.datasources) {
const dsList = Array.isArray(manifest.datasources)
? manifest.datasources