-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
1875 lines (1711 loc) · 66.1 KB
/
index.ts
File metadata and controls
1875 lines (1711 loc) · 66.1 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 { QueryAST, SortNode, AggregationNode, isFilterAST } from '@objectstack/spec/data';
import {
BatchUpdateRequest,
BatchUpdateResponse,
UpdateManyRequest,
DeleteManyRequest,
BatchOptions,
MetadataCacheRequest,
MetadataCacheResponse,
StandardErrorCode,
ErrorCategory,
GetDiscoveryResponse,
GetMetaTypesResponse,
GetMetaItemsResponse,
LoginRequest,
SessionResponse,
GetPresignedUrlRequest,
PresignedUrlResponse,
CompleteUploadRequest,
FileUploadResponse,
InitiateChunkedUploadRequest,
InitiateChunkedUploadResponse,
UploadChunkResponse,
CompleteChunkedUploadRequest,
CompleteChunkedUploadResponse,
UploadProgress,
CheckPermissionRequest,
CheckPermissionResponse,
GetObjectPermissionsResponse,
GetEffectivePermissionsResponse,
RealtimeConnectRequest,
RealtimeConnectResponse,
RealtimeSubscribeRequest,
RealtimeSubscribeResponse,
SetPresenceRequest,
GetPresenceResponse,
GetWorkflowConfigResponse,
GetWorkflowStateResponse,
WorkflowTransitionRequest,
WorkflowTransitionResponse,
WorkflowApproveRequest,
WorkflowApproveResponse,
WorkflowRejectRequest,
WorkflowRejectResponse,
ListViewsResponse,
GetViewResponse,
CreateViewRequest,
CreateViewResponse,
UpdateViewRequest,
UpdateViewResponse,
DeleteViewResponse,
RegisterDeviceRequest,
RegisterDeviceResponse,
UnregisterDeviceResponse,
GetNotificationPreferencesResponse,
UpdateNotificationPreferencesRequest,
UpdateNotificationPreferencesResponse,
ListNotificationsResponse,
MarkNotificationsReadResponse,
MarkAllNotificationsReadResponse,
AiNlqRequest,
AiNlqResponse,
AiSuggestRequest,
AiSuggestResponse,
AiInsightsRequest,
AiInsightsResponse,
GetLocalesResponse,
GetTranslationsResponse,
GetFieldLabelsResponse,
RegisterRequest,
GetFeedResponse,
CreateFeedItemResponse,
UpdateFeedItemResponse,
DeleteFeedItemResponse,
AddReactionResponse,
RemoveReactionResponse,
PinFeedItemResponse,
UnpinFeedItemResponse,
StarFeedItemResponse,
UnstarFeedItemResponse,
SearchFeedResponse,
GetChangelogResponse,
SubscribeResponse,
UnsubscribeResponse,
WellKnownCapabilities,
ApiRoutes,
} from '@objectstack/spec/api';
import { Logger, createLogger } from '@objectstack/core';
import { RealtimeAPI } from './realtime-api';
/**
* Route types that the client can resolve.
* Covers all keys from `ApiRoutes` (the discovery schema) plus
* client-specific virtual routes (`views`, `permissions`).
*/
export type ApiRouteType = keyof ApiRoutes | 'views' | 'permissions';
export interface ClientConfig {
baseUrl: string;
token?: string;
/**
* Custom fetch implementation (e.g. node-fetch or for Next.js caching)
*/
fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
/**
* Logger instance for debugging
*/
logger?: Logger;
/**
* Enable debug logging
*/
debug?: boolean;
}
/**
* Discovery Result
* Re-export from @objectstack/spec/api for convenience
*/
export type DiscoveryResult = GetDiscoveryResponse;
/**
* @deprecated Use `data.query()` with standard QueryAST parameters instead.
* This interface uses legacy parameter names (filter/sort/top/skip) that
* require translation to QueryAST. Prefer QueryAST fields directly:
* - filter → where
* - select → fields
* - sort → orderBy
* - skip → offset
* - top → limit
*/
export interface QueryOptions {
select?: string[]; // Simplified Selection
/** @canonical Preferred filter parameter (singular). */
filter?: Record<string, any> | unknown[]; // Map or AST
/** @deprecated Use `filter` (singular). Kept for backward compatibility. */
filters?: Record<string, any> | unknown[]; // Map or AST
sort?: string | string[] | SortNode[]; // 'name' or ['-created_at'] or AST
top?: number;
skip?: number;
// Advanced features
aggregations?: AggregationNode[];
groupBy?: string[];
}
/**
* Canonical query options using Spec protocol field names.
* This is the recommended interface for `data.find()` queries.
*
* Canonical field mapping (QueryAST-aligned):
* - `where` — filter conditions (replaces legacy `filter`/`filters`)
* - `fields` — field selection (replaces legacy `select`)
* - `orderBy` — sort definition (replaces legacy `sort`)
* - `limit` — max records (replaces legacy `top`)
* - `offset` — skip records (replaces legacy `skip`)
* - `expand` — relation loading (replaces legacy `populate`)
*/
export interface QueryOptionsV2 {
/** Filter conditions (WHERE clause). Accepts MongoDB-style $op object or FilterCondition AST. */
where?: Record<string, any> | unknown[];
/** Fields to retrieve (SELECT clause). */
fields?: string[];
/** Sort definition (ORDER BY clause). */
orderBy?: string | string[] | SortNode[];
/** Maximum number of records to return (LIMIT). */
limit?: number;
/** Number of records to skip (OFFSET). */
offset?: number;
/** Relations to expand (JOIN / eager-load). */
expand?: Record<string, any> | string[];
/** Aggregation functions. */
aggregations?: AggregationNode[];
/** Group by fields. */
groupBy?: string[];
}
export interface PaginatedResult<T = any> {
/** Spec-compliant: array of matching records */
records: T[];
/** Total number of matching records (if requested) */
total?: number;
/** The object name */
object?: string;
/** Whether more records are available */
hasMore?: boolean;
}
/** Spec: GetDataResponseSchema */
export interface GetDataResult<T = any> {
object: string;
id: string;
record: T;
}
/** Spec: CreateDataResponseSchema */
export interface CreateDataResult<T = any> {
object: string;
id: string;
record: T;
}
/** Spec: UpdateDataResponseSchema */
export interface UpdateDataResult<T = any> {
object: string;
id: string;
record: T;
}
/** Spec: DeleteDataResponseSchema */
export interface DeleteDataResult {
object: string;
id: string;
deleted: boolean;
}
export interface StandardError {
code: StandardErrorCode;
message: string;
category: ErrorCategory;
httpStatus: number;
retryable: boolean;
details?: Record<string, any>;
}
export class ObjectStackClient {
private baseUrl: string;
private token?: string;
private fetchImpl: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
private discoveryInfo?: DiscoveryResult;
private logger: Logger;
private realtimeAPI: RealtimeAPI;
constructor(config: ClientConfig) {
this.baseUrl = config.baseUrl.replace(/\/$/, ''); // Remove trailing slash
this.token = config.token;
this.fetchImpl = config.fetch || globalThis.fetch.bind(globalThis);
// Initialize logger
this.logger = config.logger || createLogger({
level: config.debug ? 'debug' : 'info',
format: 'pretty'
});
// Initialize realtime API
this.realtimeAPI = new RealtimeAPI(this.baseUrl, this.token);
this.logger.debug('ObjectStack client created', { baseUrl: this.baseUrl });
}
/**
* Initialize the client by discovering server capabilities.
*/
async connect() {
this.logger.debug('Connecting to ObjectStack server', { baseUrl: this.baseUrl });
try {
let data: DiscoveryResult | undefined;
// 1. Try Standard Discovery (.well-known)
try {
let wellKnownUrl: string;
try {
// If baseUrl is absolute, get origin
const url = new URL(this.baseUrl);
wellKnownUrl = `${url.origin}/.well-known/objectstack`;
} catch {
// If baseUrl is relative, use absolute path from root
wellKnownUrl = '/.well-known/objectstack';
}
this.logger.debug('Probing .well-known discovery', { url: wellKnownUrl });
const res = await this.fetchImpl(wellKnownUrl);
if (res.ok) {
const body = await res.json();
data = body.data || body;
this.logger.debug('Discovered via .well-known');
}
} catch (e) {
this.logger.debug('Standard discovery probe failed', { error: (e as Error).message });
}
// 2. Fallback to Protocol-standard Discovery Path /api/v1/discovery
if (!data) {
const fallbackUrl = `${this.baseUrl}/api/v1/discovery`;
this.logger.debug('Falling back to standard discovery endpoint', { url: fallbackUrl });
const res = await this.fetchImpl(fallbackUrl);
if (!res.ok) {
throw new Error(`Failed to connect to ${fallbackUrl}: ${res.statusText}`);
}
const body = await res.json();
data = body.data || body;
}
if (!data) {
throw new Error('Connection failed: No discovery data returned');
}
this.discoveryInfo = data;
this.logger.info('Connected to ObjectStack server', {
version: data.version,
apiName: data.apiName,
services: data.services
});
return data as DiscoveryResult;
} catch (e) {
this.logger.error('Failed to connect to ObjectStack server', e as Error, { baseUrl: this.baseUrl });
throw e;
}
}
/**
* Well-known capability flags discovered from the server.
* Returns undefined if the client has not yet connected or the server
* did not include capabilities in its discovery response.
*
* The server may return capabilities in hierarchical format
* `{ key: { enabled: boolean } }` or flat boolean format `{ key: boolean }`.
* This getter normalizes both to flat `WellKnownCapabilities`.
*/
get capabilities(): WellKnownCapabilities | undefined {
const raw = this.discoveryInfo?.capabilities;
if (!raw) return undefined;
// Normalize: hierarchical { enabled: boolean } → flat boolean
const result: Record<string, boolean> = {};
for (const [key, value] of Object.entries(raw)) {
result[key] = typeof value === 'object' && value !== null ? !!(value as any).enabled : !!value;
}
return result as unknown as WellKnownCapabilities;
}
/**
* Metadata Operations
*/
meta = {
/**
* Get all available metadata types
* Returns types like 'object', 'plugin', 'view', etc.
*/
getTypes: async (): Promise<GetMetaTypesResponse> => {
const route = this.getRoute('metadata');
const res = await this.fetch(`${this.baseUrl}${route}`);
return this.unwrapResponse<GetMetaTypesResponse>(res);
},
/**
* Get all items of a specific metadata type
* @param type - Metadata type name (e.g., 'object', 'plugin')
* @param options - Optional filters (e.g., packageId to scope by package)
*/
getItems: async (type: string, options?: { packageId?: string }): Promise<GetMetaItemsResponse> => {
const route = this.getRoute('metadata');
const params = new URLSearchParams();
if (options?.packageId) params.set('package', options.packageId);
const qs = params.toString();
const url = `${this.baseUrl}${route}/${type}${qs ? `?${qs}` : ''}`;
const res = await this.fetch(url);
return this.unwrapResponse<GetMetaItemsResponse>(res);
},
/**
* Get a specific metadata item by type and name
* @param type - Metadata type (e.g., 'object', 'plugin')
* @param name - Item name (snake_case identifier)
* @param options - Optional filters (e.g., packageId to scope by package)
*/
getItem: async (type: string, name: string, options?: { packageId?: string }) => {
const route = this.getRoute('metadata');
const params = new URLSearchParams();
if (options?.packageId) params.set('package', options.packageId);
const qs = params.toString();
const url = `${this.baseUrl}${route}/${type}/${name}${qs ? `?${qs}` : ''}`;
const res = await this.fetch(url);
return this.unwrapResponse(res);
},
/**
* Save a metadata item
* @param type - Metadata type (e.g., 'object', 'plugin')
* @param name - Item name
* @param item - The metadata content to save
*/
saveItem: async (type: string, name: string, item: any) => {
const route = this.getRoute('metadata');
const res = await this.fetch(`${this.baseUrl}${route}/${type}/${name}`, {
method: 'PUT',
body: JSON.stringify(item)
});
return this.unwrapResponse(res);
},
/**
* Delete a metadata item
* @param type - Metadata type (e.g., 'object', 'plugin')
* @param name - Item name (snake_case identifier)
*/
deleteItem: async (type: string, name: string): Promise<{ type: string; name: string; deleted: boolean }> => {
const route = this.getRoute('metadata');
const res = await this.fetch(`${this.baseUrl}${route}/${encodeURIComponent(type)}/${encodeURIComponent(name)}`, {
method: 'DELETE',
});
return this.unwrapResponse(res);
},
/**
* Get object metadata with cache support
* Supports ETag-based conditional requests for efficient caching
*/
getCached: async (name: string, cacheOptions?: MetadataCacheRequest): Promise<MetadataCacheResponse> => {
const route = this.getRoute('metadata');
const headers: Record<string, string> = {};
if (cacheOptions?.ifNoneMatch) {
headers['If-None-Match'] = cacheOptions.ifNoneMatch;
}
if (cacheOptions?.ifModifiedSince) {
headers['If-Modified-Since'] = cacheOptions.ifModifiedSince;
}
const res = await this.fetch(`${this.baseUrl}${route}/object/${name}`, {
headers
});
// Check for 304 Not Modified
if (res.status === 304) {
return {
notModified: true,
etag: cacheOptions?.ifNoneMatch ? {
value: cacheOptions.ifNoneMatch.replace(/^W\/|"/g, ''),
weak: cacheOptions.ifNoneMatch.startsWith('W/')
} : undefined
};
}
const data = await res.json();
const etag = res.headers.get('ETag');
const lastModified = res.headers.get('Last-Modified');
return {
data,
etag: etag ? {
value: etag.replace(/^W\/|"/g, ''),
weak: etag.startsWith('W/')
} : undefined,
lastModified: lastModified || undefined,
notModified: false
};
},
getView: async (object: string, type: 'list' | 'form' = 'list') => {
const route = this.getRoute('ui');
const res = await this.fetch(`${this.baseUrl}${route}/view/${object}?type=${type}`);
return this.unwrapResponse(res);
}
};
/**
* Analytics Services
*/
analytics = {
query: async (payload: any) => {
const route = this.getRoute('analytics');
const res = await this.fetch(`${this.baseUrl}${route}/query`, {
method: 'POST',
body: JSON.stringify(payload)
});
return res.json();
},
meta: async (cube: string) => {
const route = this.getRoute('analytics');
const res = await this.fetch(`${this.baseUrl}${route}/meta/${cube}`);
return res.json();
},
explain: async (payload: any) => {
const route = this.getRoute('analytics');
const res = await this.fetch(`${this.baseUrl}${route}/explain`, {
method: 'POST',
body: JSON.stringify(payload)
});
return res.json();
}
};
/**
* Package Management Services
*
* Manages the lifecycle of installed packages.
* A package (ManifestSchema) is the unit of installation.
* An app (AppSchema) is a UI navigation definition within a package.
* A package may contain 0, 1, or many apps, or be a pure functionality plugin.
*
* Endpoints:
* - GET /packages → list installed packages
* - GET /packages/:id → get package details
* - POST /packages → install a package
* - DELETE /packages/:id → uninstall a package
* - PATCH /packages/:id/enable → enable a package
* - PATCH /packages/:id/disable → disable a package
*/
packages = {
/**
* List all installed packages with optional filters.
*/
list: async (filters?: { status?: string; type?: string; enabled?: boolean }) => {
const route = this.getRoute('packages');
const params = new URLSearchParams();
if (filters?.status) params.set('status', filters.status);
if (filters?.type) params.set('type', filters.type);
if (filters?.enabled !== undefined) params.set('enabled', String(filters.enabled));
const qs = params.toString();
const url = `${this.baseUrl}${route}${qs ? '?' + qs : ''}`;
const res = await this.fetch(url);
return this.unwrapResponse<{ packages: any[]; total: number }>(res);
},
/**
* Get a specific installed package by its ID (reverse domain identifier).
*/
get: async (id: string) => {
const route = this.getRoute('packages');
const res = await this.fetch(`${this.baseUrl}${route}/${encodeURIComponent(id)}`);
return this.unwrapResponse<{ package: any }>(res);
},
/**
* Install a new package from its manifest.
*/
install: async (manifest: any, options?: { settings?: Record<string, any>; enableOnInstall?: boolean }) => {
const route = this.getRoute('packages');
const res = await this.fetch(`${this.baseUrl}${route}`, {
method: 'POST',
body: JSON.stringify({
manifest,
settings: options?.settings,
enableOnInstall: options?.enableOnInstall,
}),
});
return this.unwrapResponse<{ package: any; message?: string }>(res);
},
/**
* Uninstall a package by its ID.
*/
uninstall: async (id: string) => {
const route = this.getRoute('packages');
const res = await this.fetch(`${this.baseUrl}${route}/${encodeURIComponent(id)}`, {
method: 'DELETE',
});
return this.unwrapResponse<{ id: string; success: boolean; message?: string }>(res);
},
/**
* Enable a disabled package.
*/
enable: async (id: string) => {
const route = this.getRoute('packages');
const res = await this.fetch(`${this.baseUrl}${route}/${encodeURIComponent(id)}/enable`, {
method: 'PATCH',
});
return this.unwrapResponse<{ package: any; message?: string }>(res);
},
/**
* Disable an installed package.
*/
disable: async (id: string) => {
const route = this.getRoute('packages');
const res = await this.fetch(`${this.baseUrl}${route}/${encodeURIComponent(id)}/disable`, {
method: 'PATCH',
});
return this.unwrapResponse<{ package: any; message?: string }>(res);
},
};
/**
* Authentication Services
*/
auth = {
/**
* Login with email and password
* Uses better-auth endpoint: POST /sign-in/email
*/
login: async (request: LoginRequest): Promise<SessionResponse> => {
const route = this.getRoute('auth');
const res = await this.fetch(`${this.baseUrl}${route}/sign-in/email`, {
method: 'POST',
body: JSON.stringify(request)
});
const data = await res.json();
// Auto-set token if present in response
if (data.data?.token) {
this.token = data.data.token;
}
return data;
},
/**
* Logout current user
* Uses better-auth endpoint: POST /sign-out
*/
logout: async () => {
const route = this.getRoute('auth');
await this.fetch(`${this.baseUrl}${route}/sign-out`, { method: 'POST' });
this.token = undefined;
},
/**
* Get current user session
* Uses better-auth endpoint: GET /get-session
*/
me: async (): Promise<SessionResponse> => {
const route = this.getRoute('auth');
const res = await this.fetch(`${this.baseUrl}${route}/get-session`);
return res.json();
},
/**
* Register a new user account
* Uses better-auth endpoint: POST /sign-up/email
*/
register: async (request: RegisterRequest): Promise<SessionResponse> => {
const route = this.getRoute('auth');
const res = await this.fetch(`${this.baseUrl}${route}/sign-up/email`, {
method: 'POST',
body: JSON.stringify(request)
});
const data = await res.json();
if (data.data?.token) {
this.token = data.data.token;
}
return data;
},
/**
* Refresh an authentication token
* Note: better-auth handles token refresh automatically via /get-session
* @param _refreshToken - Not used (better-auth handles refresh automatically)
*/
refreshToken: async (_refreshToken: string): Promise<SessionResponse> => {
const route = this.getRoute('auth');
// better-auth doesn't have a separate refresh endpoint
// Session refresh is handled automatically when calling /get-session
const res = await this.fetch(`${this.baseUrl}${route}/get-session`, {
method: 'GET'
});
const data = await res.json();
if (data.data?.token) {
this.token = data.data.token;
}
return data;
}
};
/**
* Storage Services
*/
storage = {
upload: async (file: any, scope: string = 'user'): Promise<FileUploadResponse> => {
// 1. Get Presigned URL
const presignedReq: GetPresignedUrlRequest = {
filename: file.name,
mimeType: file.type,
size: file.size,
scope
};
const route = this.getRoute('storage');
const presignedRes = await this.fetch(`${this.baseUrl}${route}/upload/presigned`, {
method: 'POST',
body: JSON.stringify(presignedReq)
});
const { data: presigned } = await presignedRes.json() as { data: PresignedUrlResponse['data'] };
// 2. Upload to Cloud directly (Bypass API Middleware to avoid Auth headers if using S3)
// Use fetchImpl directly
const uploadRes = await this.fetchImpl(presigned.uploadUrl, {
method: presigned.method,
headers: presigned.headers,
body: file
});
if (!uploadRes.ok) {
throw new Error(`Storage Upload Failed: ${uploadRes.statusText}`);
}
// 3. Complete Upload
const completeReq: CompleteUploadRequest = {
fileId: presigned.fileId
};
const completeRes = await this.fetch(`${this.baseUrl}${route}/upload/complete`, {
method: 'POST',
body: JSON.stringify(completeReq)
});
return completeRes.json();
},
getDownloadUrl: async (fileId: string): Promise<string> => {
const route = this.getRoute('storage');
const res = await this.fetch(`${this.baseUrl}${route}/files/${fileId}/url`);
const data = await res.json();
return data.url;
},
/**
* Get a presigned URL for direct-to-cloud upload
*/
getPresignedUrl: async (req: GetPresignedUrlRequest): Promise<PresignedUrlResponse> => {
const route = this.getRoute('storage');
const res = await this.fetch(`${this.baseUrl}${route}/upload/presigned`, {
method: 'POST',
body: JSON.stringify(req)
});
return res.json();
},
/**
* Initiate a chunked (multipart) upload session
*/
initChunkedUpload: async (req: InitiateChunkedUploadRequest): Promise<InitiateChunkedUploadResponse> => {
const route = this.getRoute('storage');
const res = await this.fetch(`${this.baseUrl}${route}/upload/chunked`, {
method: 'POST',
body: JSON.stringify(req)
});
return res.json();
},
/**
* Upload a single chunk/part of a multipart upload
*/
uploadPart: async (uploadId: string, chunkIndex: number, resumeToken: string, data: Blob | Buffer): Promise<UploadChunkResponse> => {
const route = this.getRoute('storage');
const res = await this.fetch(`${this.baseUrl}${route}/upload/chunked/${uploadId}/chunk/${chunkIndex}`, {
method: 'PUT',
headers: { 'x-resume-token': resumeToken },
body: data as any
});
return res.json();
},
/**
* Complete a chunked upload by assembling all parts
*/
completeChunkedUpload: async (req: CompleteChunkedUploadRequest): Promise<CompleteChunkedUploadResponse> => {
const route = this.getRoute('storage');
const res = await this.fetch(`${this.baseUrl}${route}/upload/chunked/${req.uploadId}/complete`, {
method: 'POST',
body: JSON.stringify(req)
});
return res.json();
},
/**
* Resume an interrupted chunked upload.
* Fetches current progress, then uploads remaining chunks and completes.
*/
resumeUpload: async (uploadId: string, file: Blob | ArrayBuffer, chunkSize: number, resumeToken: string): Promise<CompleteChunkedUploadResponse> => {
const route = this.getRoute('storage');
// 1. Get current progress
const progressRes = await this.fetch(`${this.baseUrl}${route}/upload/chunked/${uploadId}/progress`);
const progress = await progressRes.json() as UploadProgress;
const { totalChunks, uploadedChunks } = progress.data;
const parts: Array<{ chunkIndex: number; eTag: string }> = [];
// 2. Upload remaining chunks
const fileBuffer = file instanceof ArrayBuffer ? file : await file.arrayBuffer();
for (let i = uploadedChunks; i < totalChunks; i++) {
const start = i * chunkSize;
const end = Math.min(start + chunkSize, fileBuffer.byteLength);
const chunk = new Blob([fileBuffer.slice(start, end)]);
const chunkRes = await this.storage.uploadPart(uploadId, i, resumeToken, chunk);
parts.push({ chunkIndex: i, eTag: chunkRes.data.eTag });
}
// 3. Complete
return this.storage.completeChunkedUpload({ uploadId, parts });
},
};
/**
* Automation Services
*/
automation = {
/**
* Trigger a named automation flow (legacy endpoint)
*/
trigger: async (triggerName: string, payload: any) => {
const route = this.getRoute('automation');
const res = await this.fetch(`${this.baseUrl}${route}/trigger/${triggerName}`, {
method: 'POST',
body: JSON.stringify(payload)
});
return res.json();
},
/**
* List all registered automation flows
*/
list: async (): Promise<{ flows: string[]; total: number; hasMore: boolean }> => {
const route = this.getRoute('automation');
const res = await this.fetch(`${this.baseUrl}${route}`);
return this.unwrapResponse(res);
},
/**
* Get a flow definition by name
*/
get: async (name: string): Promise<any> => {
const route = this.getRoute('automation');
const res = await this.fetch(`${this.baseUrl}${route}/${name}`);
return this.unwrapResponse(res);
},
/**
* Create (register) a new flow
*/
create: async (name: string, definition: any): Promise<any> => {
const route = this.getRoute('automation');
const res = await this.fetch(`${this.baseUrl}${route}`, {
method: 'POST',
body: JSON.stringify({ name, ...definition }),
});
return this.unwrapResponse(res);
},
/**
* Update an existing flow
*/
update: async (name: string, definition: any): Promise<any> => {
const route = this.getRoute('automation');
const res = await this.fetch(`${this.baseUrl}${route}/${name}`, {
method: 'PUT',
body: JSON.stringify({ definition }),
});
return this.unwrapResponse(res);
},
/**
* Delete (unregister) a flow
*/
delete: async (name: string): Promise<{ name: string; deleted: boolean }> => {
const route = this.getRoute('automation');
const res = await this.fetch(`${this.baseUrl}${route}/${name}`, {
method: 'DELETE',
});
return this.unwrapResponse(res);
},
/**
* Enable or disable a flow
*/
toggle: async (name: string, enabled: boolean): Promise<{ name: string; enabled: boolean }> => {
const route = this.getRoute('automation');
const res = await this.fetch(`${this.baseUrl}${route}/${name}/toggle`, {
method: 'POST',
body: JSON.stringify({ enabled }),
});
return this.unwrapResponse(res);
},
/**
* Execution run history
*/
runs: {
/**
* List execution runs for a flow
*/
list: async (flowName: string, options?: { limit?: number; cursor?: string }): Promise<{ runs: any[]; hasMore: boolean }> => {
const route = this.getRoute('automation');
const params = new URLSearchParams();
if (options?.limit) params.set('limit', String(options.limit));
if (options?.cursor) params.set('cursor', options.cursor);
const qs = params.toString();
const res = await this.fetch(`${this.baseUrl}${route}/${flowName}/runs${qs ? `?${qs}` : ''}`);
return this.unwrapResponse(res);
},
/**
* Get a single execution run
*/
get: async (flowName: string, runId: string): Promise<any> => {
const route = this.getRoute('automation');
const res = await this.fetch(`${this.baseUrl}${route}/${flowName}/runs/${runId}`);
return this.unwrapResponse(res);
},
},
};
/**
* Event Subscription API
* Provides real-time event subscriptions for metadata and data changes
*/
get events() {
return this.realtimeAPI;
}
/**
* Permissions Services
*/
permissions = {
/**
* Check if current user has permission for an action on an object
*/
check: async (request: CheckPermissionRequest): Promise<CheckPermissionResponse> => {
const route = this.getRoute('permissions');
const params = new URLSearchParams({ object: request.object, action: request.action });
if (request.recordId !== undefined) params.set('recordId', request.recordId);
if (request.field !== undefined) params.set('field', request.field);
const res = await this.fetch(`${this.baseUrl}${route}/check?${params.toString()}`);
return this.unwrapResponse<CheckPermissionResponse>(res);
},
/**
* Get all permissions for a specific object
*/
getObjectPermissions: async (object: string): Promise<GetObjectPermissionsResponse> => {
const route = this.getRoute('permissions');
const res = await this.fetch(`${this.baseUrl}${route}/objects/${encodeURIComponent(object)}`);
return this.unwrapResponse<GetObjectPermissionsResponse>(res);
},
/**
* Get effective permissions for the current user
*/
getEffectivePermissions: async (): Promise<GetEffectivePermissionsResponse> => {
const route = this.getRoute('permissions');
const res = await this.fetch(`${this.baseUrl}${route}/effective`);
return this.unwrapResponse<GetEffectivePermissionsResponse>(res);
}
};
/**
* Realtime Services
*/
realtime = {
/**
* Establish a realtime connection
*/
connect: async (request?: RealtimeConnectRequest): Promise<RealtimeConnectResponse> => {
const route = this.getRoute('realtime');
const res = await this.fetch(`${this.baseUrl}${route}/connect`, {
method: 'POST',
body: JSON.stringify(request || {})
});
return this.unwrapResponse<RealtimeConnectResponse>(res);
},
/**
* Disconnect from realtime services
*/
disconnect: async (): Promise<void> => {
const route = this.getRoute('realtime');
await this.fetch(`${this.baseUrl}${route}/disconnect`, {
method: 'POST'
});
},
/**
* Subscribe to a channel
*/
subscribe: async (request: RealtimeSubscribeRequest): Promise<RealtimeSubscribeResponse> => {
const route = this.getRoute('realtime');
const res = await this.fetch(`${this.baseUrl}${route}/subscribe`, {
method: 'POST',
body: JSON.stringify(request)
});
return this.unwrapResponse<RealtimeSubscribeResponse>(res);
},
/**
* Unsubscribe from a channel
*/
unsubscribe: async (subscriptionId: string): Promise<void> => {
const route = this.getRoute('realtime');
await this.fetch(`${this.baseUrl}${route}/unsubscribe`, {
method: 'POST',
body: JSON.stringify({ subscriptionId })
});
},
/**
* Set presence state on a channel
*/
setPresence: async (channel: string, state: SetPresenceRequest['state']): Promise<void> => {
const route = this.getRoute('realtime');
await this.fetch(`${this.baseUrl}${route}/presence`, {
method: 'PUT',
body: JSON.stringify({ channel, state })
});
},
/**
* Get presence information for a channel
*/