-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.ts
More file actions
2239 lines (2052 loc) · 80.3 KB
/
Copy pathindex.ts
File metadata and controls
2239 lines (2052 loc) · 80.3 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
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { ObjectStackClient, type QueryOptions as ObjectStackQueryOptions } from '@objectstack/client';
import type { DataSource, QueryParams, QueryResult, FileUploadResult } from '@object-ui/types';
import { convertFiltersToAST } from '@object-ui/core';
import { MetadataCache } from './cache/MetadataCache';
import {
ObjectStackError,
MetadataNotFoundError,
BulkOperationError,
ConnectionError,
createErrorFromResponse,
} from './errors';
/**
* Map human-readable filter operator names produced by SDUI view configs
* (e.g. `lead.view.ts`) to the canonical operator symbols expected by the
* ObjectStack server's filter AST. Unknown operators fall through unchanged
* so existing AST-style entries keep working.
*/
const FILTER_OPERATOR_ALIASES: Record<string, string> = {
equals: '=',
eq: '=',
'==': '=',
not_equals: '!=',
notequals: '!=',
ne: '!=',
greater_than: '>',
greaterthan: '>',
gt: '>',
greater_than_or_equal: '>=',
greater_than_or_equals: '>=',
greaterthanorequal: '>=',
gte: '>=',
less_than: '<',
lessthan: '<',
lt: '<',
less_than_or_equal: '<=',
less_than_or_equals: '<=',
lessthanorequal: '<=',
lte: '<=',
in: 'in',
not_in: 'nin',
notin: 'nin',
nin: 'nin',
contains: 'contains',
not_contains: 'notcontains',
notcontains: 'notcontains',
starts_with: 'startswith',
startswith: 'startswith',
ends_with: 'endswith',
endswith: 'endswith',
between: 'between',
is_null: 'isnull',
isnull: 'isnull',
is_not_null: 'isnotnull',
isnotnull: 'isnotnull',
};
function normalizeFilterOperator(op: unknown): string | null {
if (typeof op !== 'string') return null;
const lower = op.toLowerCase();
return FILTER_OPERATOR_ALIASES[lower] ?? FILTER_OPERATOR_ALIASES[op] ?? op;
}
function objectFilterEntryToAST(entry: any): [string, string, any] | null {
if (!entry || typeof entry !== 'object') return null;
const field = entry.field ?? entry.name;
const rawOp = entry.operator ?? entry.op ?? '=';
const op = normalizeFilterOperator(rawOp);
if (!field || !op) return null;
return [String(field), op, entry.value];
}
/**
* Translate any of the filter shapes accepted by ObjectUI into the AST format
* understood by the ObjectStack server's `parseFilterAST()`.
*
* Accepted inputs:
* - `[{ field, operator, value }, ...]` — ViewFilterRule[] from view configs
* - `[field, op, value]` — single AST tuple (passed through)
* - `['and'|'or', ...children]` — logical AST node (passed through)
* - `[[...], [...]]` — legacy nested AST (passed through)
* - `{ field: value }` / `{ field: { $op: value } }` — MongoDB-style object
*
* Returns `undefined` when the input is empty/unrecognized so callers can
* skip emitting `?filter=` entirely.
*/
function translateFilterToAST(filter: unknown): unknown | undefined {
if (filter === undefined || filter === null) return undefined;
if (Array.isArray(filter)) {
if (filter.length === 0) return undefined;
// Object form: [{ field, operator, value }, ...]
const first = filter[0];
const isObjectForm = filter.length > 0
&& typeof first === 'object'
&& first !== null
&& !Array.isArray(first)
&& (first as any).field !== undefined;
if (isObjectForm) {
const tuples = (filter as any[])
.map(entry => objectFilterEntryToAST(entry))
.filter((t): t is [string, string, any] => t !== null);
if (tuples.length === 0) return undefined;
if (tuples.length === 1) return tuples[0];
return ['and', ...tuples];
}
// Already AST — pass through.
return filter;
}
if (typeof filter === 'object') {
if (Object.keys(filter as Record<string, unknown>).length === 0) return undefined;
return filter;
}
return undefined;
}
// Module-level discovery cache. Multiple ObjectStackAdapter instances pointed
// at the same baseUrl (e.g. ConditionalAuthWrapper's throwaway adapter +
// AdapterProvider's main adapter) would otherwise each fire `/discovery`. By
// keying on baseUrl we collapse them to a single network round trip per origin.
const discoveryCache = new Map<string, Promise<unknown>>();
/**
* Fetch the server `discovery` document once per (baseUrl) and reuse the
* resulting Promise. Used by `ObjectStackAdapter.connect()` (and any caller
* that wants the discovery payload without spinning up a new client).
*/
export async function getSharedDiscovery(
baseUrl: string,
fetcher: () => Promise<unknown>,
): Promise<unknown> {
const key = baseUrl || '<default>';
const cached = discoveryCache.get(key);
if (cached) return cached;
const p = fetcher().catch((err) => {
// Allow retry on failure
discoveryCache.delete(key);
throw err;
});
discoveryCache.set(key, p);
return p;
}
/** Test/dev helper to drop the cache (e.g. on logout or origin change). */
export function clearSharedDiscoveryCache(): void {
discoveryCache.clear();
}
/**
* Detect "missing resource" errors regardless of where they originate.
*
* The ObjectStack client decorates thrown errors with `httpStatus` (and a
* machine-readable `code` such as `object_not_found`/`record_not_found`),
* while raw `fetch()` callers may surface `status` or `statusCode`. Treat
* any of these as a 404 so callers can degrade gracefully instead of
* tripping on the property-name mismatch.
*/
export function is404Error(error: unknown): boolean {
if (!error || typeof error !== 'object') return false;
const err = error as Record<string, unknown>;
if (err.httpStatus === 404 || err.status === 404 || err.statusCode === 404) {
return true;
}
const code = typeof err.code === 'string' ? err.code : '';
return code === 'object_not_found' || code === 'record_not_found';
}
/**
* Thrown by `update()` / `delete()` when the server returns
* `409 CONCURRENT_UPDATE` — i.e. the record was modified by someone else
* between when the caller last read it and when they attempted to write.
*
* The error carries the current server-side `updated_at` version and the
* full latest record so the UI can render an informed conflict-resolution
* dialog (typically "Reload latest" / "Overwrite anyway" / "Cancel").
*
* Mirrors the {@link ConcurrentUpdateError} thrown by
* `@objectstack/objectql`'s protocol; the wire shape is:
* ```json
* { "code": "CONCURRENT_UPDATE",
* "error": "<message>",
* "currentVersion": "<updated_at>",
* "currentRecord": { ...latest... } }
* ```
*/
export class ConcurrentUpdateError extends Error {
readonly code = 'CONCURRENT_UPDATE';
readonly httpStatus = 409;
readonly currentVersion: string | null;
readonly currentRecord: unknown;
constructor(opts: { currentVersion: string | null; currentRecord: unknown; message?: string }) {
super(opts.message ?? 'Record was modified by another user');
this.name = 'ConcurrentUpdateError';
this.currentVersion = opts.currentVersion;
this.currentRecord = opts.currentRecord;
}
}
/**
* Detect "concurrent update" errors raised by the platform. The wire
* shape is `409` + `code: 'CONCURRENT_UPDATE'`. The client surfaces
* extra details on `error.details` (full response body).
*/
export function isConcurrentUpdateError(error: unknown): error is ConcurrentUpdateError {
if (!error || typeof error !== 'object') return false;
const e = error as Record<string, unknown>;
return e.code === 'CONCURRENT_UPDATE' || e.name === 'ConcurrentUpdateError';
}
/**
* Convert any error thrown by the upstream client into a typed
* `ConcurrentUpdateError` when it represents a 409 CONCURRENT_UPDATE.
* Returns the original error untouched otherwise. Callers can simply
* `throw normaliseClientError(err)` from their catch blocks.
*/
export function normaliseClientError(error: unknown): unknown {
if (!error || typeof error !== 'object') return error;
const e = error as Record<string, unknown>;
if (e.code !== 'CONCURRENT_UPDATE' && e.httpStatus !== 409) return error;
if (e.code !== 'CONCURRENT_UPDATE') return error;
const details = (e.details ?? {}) as Record<string, unknown>;
return new ConcurrentUpdateError({
currentVersion: typeof details.currentVersion === 'string' ? details.currentVersion : null,
currentRecord: details.currentRecord ?? null,
message: typeof e.message === 'string' ? e.message : undefined,
});
}
/**
* Build a Logger compatible with @objectstack/client that demotes expected
* 404 noise to console.debug. The client logs every non-2xx response with
* `logger.error("HTTP request failed", undefined, { status, error })`, but
* 404s on optional collections (sys_presence, sys_activity, …) are part of
* normal degraded operation when those plugins aren't installed on the
* server — they should not surface as errors in the browser DevTools.
*
* Returned object is loosely typed because the spec's Logger interface lives
* in a transitive package; using `any` keeps us decoupled.
*/
function createQuietHttpLogger(): any {
const isExpected404 = (meta?: Record<string, any>): boolean => {
if (!meta || typeof meta !== 'object') return false;
if (meta.status === 404 || meta.statusCode === 404) return true;
const errBody = meta.error;
if (errBody && typeof errBody === 'object') {
const code = (errBody as Record<string, unknown>).code;
if (code === 'object_not_found' || code === 'record_not_found') return true;
}
return false;
};
const logger: any = {
debug: (message: string, meta?: Record<string, any>) =>
console.debug(message, meta ?? ''),
info: (message: string, meta?: Record<string, any>) =>
console.info(message, meta ?? ''),
warn: (message: string, meta?: Record<string, any>) =>
console.warn(message, meta ?? ''),
error: (message: string, error?: Error, meta?: Record<string, any>) => {
if (isExpected404(meta)) {
console.debug(`[ObjectStack] ${message} (suppressed expected 404)`, meta);
return;
}
console.error(message, error ?? '', meta ?? '');
},
fatal: (message: string, error?: Error, meta?: Record<string, any>) =>
console.error(message, error ?? '', meta ?? ''),
log: (message: string, ...args: any[]) => console.log(message, ...args),
child: () => logger,
withTrace: () => logger,
};
return logger;
}
/**
* Connection state for monitoring
*/
export type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'error';
/**
* Connection state change event
*/
export interface ConnectionStateEvent {
state: ConnectionState;
timestamp: number;
error?: Error;
}
/**
* Batch operation progress event
*/
export interface BatchProgressEvent {
operation: 'create' | 'update' | 'delete';
total: number;
completed: number;
failed: number;
percentage: number;
}
/**
* Event listener type for connection state changes
*/
export type ConnectionStateListener = (event: ConnectionStateEvent) => void;
/**
* Event listener type for batch operation progress
*/
export type BatchProgressListener = (event: BatchProgressEvent) => void;
// Re-export FileUploadResult from types for consumers
export type { FileUploadResult } from '@object-ui/types';
/**
* Deterministic JSON.stringify with sorted object keys, used to build cache
* keys for in-flight request coalescing. Produces identical output for
* `{ a: 1, b: 2 }` and `{ b: 2, a: 1 }` so callers that build params in
* different orders still hit the same key.
*/
function stableStringify(value: unknown): string {
if (value === null || typeof value !== 'object') return JSON.stringify(value);
if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
const obj = value as Record<string, unknown>;
const keys = Object.keys(obj).sort();
return `{${keys.map(k => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(',')}}`;
}
/**
* ObjectStack Data Source Adapter
*
* Bridges the ObjectStack Client SDK with the ObjectUI DataSource interface.
* This allows Object UI applications to seamlessly integrate with ObjectStack
* backends while maintaining the universal DataSource abstraction.
*
* @example
* ```typescript
* import { ObjectStackAdapter } from '@object-ui/data-objectstack';
*
* const dataSource = new ObjectStackAdapter({
* baseUrl: 'https://api.example.com',
* token: 'your-api-token',
* autoReconnect: true,
* maxReconnectAttempts: 5
* });
*
* // Monitor connection state
* dataSource.onConnectionStateChange((event) => {
* console.log('Connection state:', event.state);
* });
*
* const users = await dataSource.find('users', {
* $filter: { status: 'active' },
* $top: 10
* });
* ```
*/
export class ObjectStackAdapter<T = unknown> implements DataSource<T> {
private client: ObjectStackClient;
private connected: boolean = false;
private connectPromise: Promise<void> | null = null;
private metadataCache: MetadataCache;
private connectionState: ConnectionState = 'disconnected';
private connectionStateListeners: ConnectionStateListener[] = [];
private batchProgressListeners: BatchProgressListener[] = [];
private autoReconnect: boolean;
private maxReconnectAttempts: number;
private reconnectDelay: number;
private reconnectAttempts: number = 0;
private baseUrl: string;
private token?: string;
private fetchImpl: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
// In-flight find() requests keyed by resource + serialized params.
// Coalesces concurrent identical reads (e.g. React StrictMode double-mount,
// multiple sibling components requesting the same dataset on first paint)
// into a single network round trip.
private inflightFinds = new Map<string, Promise<QueryResult<T>>>();
// Resources that have responded 404 at least once (collection not installed
// on this backend). Subsequent find() calls short-circuit to an empty result
// so optional collections like sys_presence don't hammer the server with
// failing requests on every record open / panel render.
private missingResources = new Set<string>();
constructor(config: {
baseUrl: string;
token?: string;
fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
cache?: {
maxSize?: number;
ttl?: number;
};
autoReconnect?: boolean;
maxReconnectAttempts?: number;
reconnectDelay?: number;
}) {
// Inject a quiet logger that demotes expected 404s ("HTTP request failed"
// from probing optional collections like sys_presence/sys_activity) to
// debug() so they don't pollute the browser console. Other log levels are
// forwarded to the standard console.
this.client = new ObjectStackClient({ ...config, logger: createQuietHttpLogger() });
this.metadataCache = new MetadataCache(config.cache);
this.autoReconnect = config.autoReconnect ?? true;
this.maxReconnectAttempts = config.maxReconnectAttempts ?? 3;
this.reconnectDelay = config.reconnectDelay ?? 1000;
this.baseUrl = config.baseUrl;
this.token = config.token;
this.fetchImpl = config.fetch || globalThis.fetch.bind(globalThis);
}
/**
* Ensure the client is connected to the server.
* Call this before making requests or it will auto-connect on first request.
*/
async connect(): Promise<void> {
if (this.connected) return;
// Dedupe concurrent connect() calls — without this, every component
// that mounts on first paint can trigger an independent discovery
// request before the first one completes.
if (this.connectPromise) return this.connectPromise;
this.setConnectionState('connecting');
this.connectPromise = (async () => {
try {
// Use the module-level discovery cache so multiple adapter instances
// (or React StrictMode double-mounts) at the same baseUrl share a
// single network round trip. We inject the result into the client's
// private `discoveryInfo` field to avoid client.connect() re-fetching.
const baseUrl = this.baseUrl || '';
const discoveryUrl = baseUrl
? `${baseUrl.replace(/\/$/, '')}/api/v1/discovery`
: '/api/v1/discovery';
const data = await getSharedDiscovery(baseUrl, async () => {
const res = await this.fetchImpl(discoveryUrl, {
method: 'GET',
headers: this.token
? { Authorization: `Bearer ${this.token}` }
: undefined,
});
if (!res.ok) {
throw new Error(`discovery ${res.status} ${res.statusText}`);
}
const body = await res.json();
return body && typeof body.success === 'boolean' && 'data' in body
? body.data
: body;
});
// Prime the underlying client's cached discovery so capability/route
// helpers continue to work without a redundant fetch.
(this.client as unknown as { discoveryInfo?: unknown }).discoveryInfo = data;
this.connected = true;
this.reconnectAttempts = 0;
this.setConnectionState('connected');
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : 'Failed to connect to ObjectStack server';
const connectionError = new ConnectionError(
errorMessage,
undefined,
{ originalError: error }
);
this.setConnectionState('error', connectionError);
// Attempt auto-reconnect if enabled
if (this.autoReconnect && this.reconnectAttempts < this.maxReconnectAttempts) {
await this.attemptReconnect();
} else {
throw connectionError;
}
} finally {
this.connectPromise = null;
}
})();
return this.connectPromise;
}
/**
* Attempt to reconnect to the server with exponential backoff
*/
private async attemptReconnect(): Promise<void> {
this.reconnectAttempts++;
this.setConnectionState('reconnecting');
// Exponential backoff: delay * 2^(attempts-1)
const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
await new Promise(resolve => setTimeout(resolve, delay));
this.connected = false;
await this.connect();
}
/**
* Get the current connection state
*/
getConnectionState(): ConnectionState {
return this.connectionState;
}
/**
* Check if the adapter is currently connected
*/
isConnected(): boolean {
return this.connected && this.connectionState === 'connected';
}
/**
* Register a listener for connection state changes
*/
onConnectionStateChange(listener: ConnectionStateListener): () => void {
this.connectionStateListeners.push(listener);
// Return unsubscribe function
return () => {
const index = this.connectionStateListeners.indexOf(listener);
if (index > -1) {
this.connectionStateListeners.splice(index, 1);
}
};
}
/**
* Register a listener for batch operation progress
*/
onBatchProgress(listener: BatchProgressListener): () => void {
this.batchProgressListeners.push(listener);
// Return unsubscribe function
return () => {
const index = this.batchProgressListeners.indexOf(listener);
if (index > -1) {
this.batchProgressListeners.splice(index, 1);
}
};
}
/**
* Set connection state and notify listeners
*/
private setConnectionState(state: ConnectionState, error?: Error): void {
this.connectionState = state;
const event: ConnectionStateEvent = {
state,
timestamp: Date.now(),
error,
};
this.connectionStateListeners.forEach(listener => {
try {
listener(event);
} catch (err) {
console.error('Error in connection state listener:', err);
}
});
}
/**
* Emit batch progress event to listeners
*/
private emitBatchProgress(event: BatchProgressEvent): void {
this.batchProgressListeners.forEach(listener => {
try {
listener(event);
} catch (err) {
console.error('Error in batch progress listener:', err);
}
});
}
/**
* Find multiple records with query parameters.
* Converts OData-style params to ObjectStack query options.
*/
async find(resource: string, params?: QueryParams): Promise<QueryResult<T>> {
// Short-circuit when this resource has previously responded 404 — the
// collection isn't installed on this backend. Callers (AppHeader,
// RecordDetailView, …) treat empty data as "feature unavailable".
if (this.missingResources.has(resource)) {
return { data: [], total: 0 } as QueryResult<T>;
}
const key = `${resource}::${stableStringify(params)}`;
const existing = this.inflightFinds.get(key);
if (existing) return existing;
const promise = (async () => {
await this.connect();
// When $expand is requested, use a raw GET request to the REST API with
// `populate` as a URL query param. The server's REST plugin routes
// GET /data/:object to protocol.findData({ object, query: req.query }),
// which parses `populate` (comma-separated) into an array for lookup expansion.
// We use a raw request because the client SDK's data.find() QueryOptions
// interface does not include populate/expand fields.
if (params?.$expand && params.$expand.length > 0) {
const result = await this.rawFindWithPopulate(resource, params);
return this.normalizeQueryResult(result, params);
}
const queryOptions = this.convertQueryParams(params);
try {
const result: unknown = await this.client.data.find<T>(resource, queryOptions);
return this.normalizeQueryResult(result, params);
} catch (err) {
if (is404Error(err)) {
// Mark the resource so subsequent calls don't repeat the 404.
this.missingResources.add(resource);
return { data: [], total: 0 } as QueryResult<T>;
}
throw err;
}
})();
this.inflightFinds.set(key, promise);
// Use `.then(cleanup, cleanup)` instead of `.finally(cleanup)`. `.finally`
// returns a new chained promise that re-raises the rejection, and because
// we don't return that chain, Node/browsers see it as an unhandled
// rejection — flooding DevTools when callers handle the original `promise`
// via `.catch()` (e.g. AppHeader probing optional sys_presence/sys_activity).
const cleanup = () => {
// Only clear if the entry still points at this promise; a later call
// that started after settle may have already replaced it.
if (this.inflightFinds.get(key) === promise) {
this.inflightFinds.delete(key);
}
};
promise.then(cleanup, cleanup);
return promise;
}
/**
* Find a single record by ID.
*/
async findOne(resource: string, id: string | number, params?: QueryParams): Promise<T | null> {
await this.connect();
// When $expand is requested, use a raw GET request with a filter by id
// and populate. The installed server v3.0.10's getData() does not support
// expand/populate, so we route through findData which does.
if (params?.$expand && params.$expand.length > 0) {
try {
const findParams: QueryParams = {
...params,
$filter: { id: String(id) },
$top: 1,
};
const result = await this.rawFindWithPopulate(resource, findParams);
// Handle array responses (some servers return data as flat arrays)
if (Array.isArray(result)) {
return result[0] || null;
}
const resultObj = result as { records?: T[]; value?: T[] };
const records = resultObj.records || resultObj.value || [];
return records[0] || null;
} catch (error: unknown) {
if (is404Error(error)) {
return null;
}
// Fall through to direct GET without $expand — some servers don't
// support the filter+populate API, so gracefully degrade to a
// simple data.get() call below rather than failing with "Record not found".
}
}
try {
const result = await this.client.data.get<T>(resource, String(id));
return result.record;
} catch (error: unknown) {
// If record not found, return null instead of throwing
if (is404Error(error)) {
return null;
}
throw error;
}
}
/**
* Create a new record.
*/
async create(resource: string, data: Partial<T>): Promise<T> {
await this.connect();
const result = await this.client.data.create<T>(resource, data);
return result.record;
}
/**
* Update an existing record.
*
* Optional `opts.ifMatch` enables Optimistic Concurrency Control: the
* server compares the supplied token (typically the `updated_at` value
* the caller previously read) against the record's current version
* and throws a {@link ConcurrentUpdateError} on mismatch (HTTP 409).
*
* Requires `@objectstack/client@>=4.2.0`, which forwards `opts.ifMatch`
* as an `If-Match` HTTP header.
*/
async update(
resource: string,
id: string | number,
data: Partial<T>,
opts?: { ifMatch?: string },
): Promise<T> {
await this.connect();
try {
const result = await this.client.data.update<T>(
resource,
String(id),
data,
opts?.ifMatch ? { ifMatch: opts.ifMatch } : undefined,
);
return result.record;
} catch (err) {
throw normaliseClientError(err);
}
}
/**
* Delete a record.
*
* Optional `opts.ifMatch` enables Optimistic Concurrency Control —
* see {@link update} for details. On 409 the call rejects with
* a {@link ConcurrentUpdateError}.
*/
async delete(
resource: string,
id: string | number,
opts?: { ifMatch?: string },
): Promise<boolean> {
await this.connect();
try {
const result = await this.client.data.delete(
resource,
String(id),
opts?.ifMatch ? { ifMatch: opts.ifMatch } : undefined,
);
return result.deleted;
} catch (err) {
throw normaliseClientError(err);
}
}
/**
* Apply the same patch to many records in a single round-trip.
*
* Sends one `POST /api/v1/data/:object/updateMany` request whose body
* is `{ records: ids.map(id => ({id, data: patch})), options: { continueOnError: true }}`.
* The server iterates server-side (still N engine writes) but the
* client only pays for ONE HTTP/auth/RLS round-trip — the relevant
* perf win for inbox / list-toolbar "mark all read" / "archive
* selected" interactions where N can easily be in the hundreds.
*
* Falls back to a sequential per-id loop when the connected client
* does not expose `updateMany` (older clients / offline adapters).
* In that case `continueOnError` semantics are emulated locally so
* callers see the same return shape.
*/
async bulkUpdate(
resource: string,
ids: ReadonlyArray<string | number>,
patch: Partial<T>,
): Promise<number> {
await this.connect();
if (!ids || ids.length === 0) return 0;
const records = ids.map((id) => ({ id: String(id), data: patch as any }));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const updateMany = (this.client.data as any).updateMany;
if (typeof updateMany === 'function') {
try {
const res = await updateMany(resource, records, { continueOnError: true });
// The server returns BatchUpdateResponse { succeeded, failed, ... };
// fall back to ids.length on adapters that return a bare array.
if (res && typeof res === 'object' && typeof (res as any).succeeded === 'number') {
return (res as any).succeeded as number;
}
if (Array.isArray(res)) return (res as any[]).length;
return ids.length;
} catch (err) {
throw normaliseClientError(err);
}
}
// Fallback: sequential per-id updates, tolerating failures.
let succeeded = 0;
for (const id of ids) {
try {
await this.client.data.update<T>(resource, String(id), patch);
succeeded++;
} catch {
// continueOnError semantics — swallow per-row errors
}
}
return succeeded;
}
/**
* Single-call bulk delete. Mirrors the bulkUpdate contract: prefers
* the server's `deleteMany` primitive when the client supports it;
* otherwise emulates `continueOnError` by looping `delete` per id and
* swallowing per-row failures. Returns the count of rows reported
* deleted by the server (or successfully deleted in fallback mode).
*/
async bulkDelete(
resource: string,
ids: ReadonlyArray<string | number>,
): Promise<number> {
await this.connect();
if (!ids || ids.length === 0) return 0;
const strIds = ids.map((id) => String(id));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const deleteMany = (this.client.data as any).deleteMany;
if (typeof deleteMany === 'function') {
try {
const res = await deleteMany(resource, strIds, { continueOnError: true });
if (res && typeof res === 'object' && typeof (res as any).succeeded === 'number') {
return (res as any).succeeded as number;
}
if (Array.isArray(res)) return (res as any[]).length;
// deleteMany historically returns void on success — assume all hit.
return strIds.length;
} catch (err) {
throw normaliseClientError(err);
}
}
// Fallback: sequential per-id deletes, tolerating failures.
let succeeded = 0;
for (const id of strIds) {
try {
await this.client.data.delete(resource, id);
succeeded++;
} catch {
// continueOnError semantics — swallow per-row errors
}
}
return succeeded;
}
/**
* Bulk operations with optimized batch processing and error handling.
* Emits progress events for tracking operation status.
*
* @param resource - Resource name
* @param operation - Operation type (create, update, delete)
* @param data - Array of records to process
* @returns Promise resolving to array of results
*/
/**
* Cross-object transactional batch (ObjectStack #1604). Runs the operations
* in ONE server transaction — commit all or roll back all. A field value of
* `{ $ref: <earlier op index> }` resolves to that op's created id, so a child
* can reference its parent created earlier in the same batch (master-detail).
*/
async batchTransaction(
operations: Array<{ object: string; action?: 'create' | 'update' | 'delete'; data?: any; id?: string }>,
): Promise<{ results: any[] }> {
const url = `${this.baseUrl}/api/v1/batch`;
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...this.getAuthHeaders() },
body: JSON.stringify({ operations }),
});
if (!response.ok) {
const error = await response.json().catch(() => ({ message: response.statusText }));
throw new ObjectStackError(
error.error || error.message || `Batch failed with status ${response.status}`,
'BATCH_ERROR',
response.status,
);
}
return response.json();
}
async bulk(resource: string, operation: 'create' | 'update' | 'delete', data: Partial<T>[]): Promise<T[]> {
await this.connect();
if (!data || data.length === 0) {
return [];
}
const total = data.length;
let completed = 0;
let failed = 0;
const emitProgress = () => {
this.emitBatchProgress({
operation,
total,
completed,
failed,
percentage: total > 0 ? (completed + failed) / total * 100 : 0,
});
};
try {
switch (operation) {
case 'create': {
emitProgress();
const created = await this.client.data.createMany<T>(resource, data);
completed = created.length;
failed = total - completed;
emitProgress();
return created;
}
case 'delete': {
const ids = data.map(item => (item as Record<string, unknown>).id).filter(Boolean) as string[];
if (ids.length === 0) {
// Track which items are missing IDs
const errors = data.map((_, index) => ({
index,
error: `Missing ID for item at index ${index}`
}));
failed = data.length;
emitProgress();
throw new BulkOperationError('delete', 0, data.length, errors);
}
emitProgress();
await this.client.data.deleteMany(resource, ids);
completed = ids.length;
failed = total - completed;
emitProgress();
return [] as T[];
}
case 'update': {
// Check if client supports updateMany
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (typeof (this.client.data as any).updateMany === 'function') {
try {
emitProgress();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const updateMany = (this.client.data as any).updateMany;
const updated = await updateMany(resource, data) as T[];
completed = updated.length;
failed = total - completed;
emitProgress();
return updated;
} catch {
// If updateMany is not supported, fall back to individual updates
// Silently fallback without logging
}
}
// Fallback: Process updates individually with detailed error tracking and progress
const results: T[] = [];
const errors: Array<{ index: number; error: unknown }> = [];
for (let i = 0; i < data.length; i++) {
const item = data[i];
const id = (item as Record<string, unknown>).id;
if (!id) {
errors.push({ index: i, error: 'Missing ID' });
failed++;
emitProgress();
continue;
}
try {
const result = await this.client.data.update<T>(resource, String(id), item);
results.push(result.record);
completed++;
emitProgress();
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : String(error);
errors.push({ index: i, error: errorMessage });
failed++;
emitProgress();
}
}
// If there were any errors, throw BulkOperationError
if (errors.length > 0) {
throw new BulkOperationError(
'update',
results.length,
errors.length,
errors,
{ resource, totalRecords: data.length }
);
}
return results;